Функции регулярных выражений POSIX

Смотрите также

Для регулярных выражений с Perl-совместимым синтаксисом смотрите функции PCRE. Простое сравнение с шаблоном подстановок командной оболочки обеспечивается функцией fnmatch().

Содержание

  • ereg_replace — Осуществляет замену по регулярному выражению
  • ereg — Совпадение с регулярным выражением
  • eregi_replace — Осуществляет замену по регулярному выражению без учета регистра
  • eregi — Совпадение с регулярным выражением без учёта регистра
  • split — Разбиение строки на массив по регулярному выражению
  • spliti — Разбивает строку в массив с помощью регулярного выражения без учета регистра
  • sql_regcase — Создает регулярное выражение для регистронезависимого сравнения

User Contributed Notes

Edward Z. Yang 01-Apr-2007 10:16
The fact that 'regex' functions are not binary safe have some very important security implications for people who are using ereg to validate their input data.

Suppose I have an expression:

<?php
$pattern = '^[[:alnum:]]*$';
?>

This should match any number of alphanumeric characters, right? Well, if the string you're matching is not binary, sure. However, say we have a null-byte tossed in the string:

<?php
$string = chr(0) . "<script>alert('xss')</script>";
echo ereg($pattern, $string);
?>

Will return true. Note that it is trivially easy to inject null bytes into PHP parameters:

index.php?content=%00ASCII

Scary. So unless you really know what you're doing, just use the PCRE preg_* functions.
nate[-at-]theklaibers[-dot-]com 07-Feb-2006 12:19
I am using a regex with the same thought process in mind as the earlier phone number. However, I have also implemented it to allow the '1' so a number like.

1 222 222 2222 would still be valid as well (along with all of the other combinations.

In my regex, I pull out the matches - not the exact string. So if someone were to forget a bracket, it wouldnt matter to the actual output as it is stripped from that match.

So, if you put in 222) 233 3454, the matches would only pull out 1=>222, 2=>233, 3=>3454

This has been very helpful in tweaking my regex.

Thanks,
Nate
ajd at cloudiness dot com 23-Aug-2005 09:05
A minor tweak to trucex' phone validator, because some people use a dot separator between the area code, exchange and four-digit block.
Posted here for your copy-and-paste convenience.

$regex = '^[(]?[2-9]{1}[0-9]{2}[) -.]{0,2}' . '[0-9]{3}[- .]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$';
nothing at nothing dot com 29-Jul-2005 03:35
His regular expression is correct, the ^ is to check for the beginning of the string. It is just looking for delimiter characters, try putting slashes around it.
"/<regex>/"
stringer at stringerstudios dot com 28-Jul-2005 05:07
Hey trucex. Cool phone number function but your $regex produces the following error. Warning: No ending delimiter '^' found

Instead of:
$regex = '^[(]?[2-9]{1}[0-9]{2}[) -]{0,2}' . '[0-9]{3}[- ]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$';

It think should be:
$regex = '^[(]?[2-9]{1}[0-9]{2}[) -]{0,2}' . '[0-9]{3}[- ]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$^';
trucex[at] gmail 27-Jul-2005 11:00
I was having a ton of issues with other people's phone number validation expressions, so I made my own. It works with most US phone numbers, including those with extentions. Format matches any of the following formats:

5551234567
555 1234567
555 123 4567
555 123-4567
555-1234567
555-123-4567
555123-4567
(555)1234567
(555)123 4567
(555)123-4567
(555) 1234567
(555) 123-4567
(555) 123 4567

And any of the following extentions can be added with or without a space between them and the number:
x123
x.123
x. 123
x 123
ext.123
ext. 123
ext 123
ext123

Extentions support between 1 and 5 digits.

Here is the expression:

$regex = '^[(]?[2-9]{1}[0-9]{2}[) -]{0,2}' . '[0-9]{3}[- ]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$';

Enjoy!
annie 08-Sep-2004 05:17
Another nice tutorial about regular expressions: http://www.mkssoftware.com/docs/man5/regexp.5.asp
tgt at tip dot nl 08-Sep-2004 02:17
Tip !
Metacharacters in regular expresions are usefull and easy to use.

The following is a set of special values that denote certain common ranges. They have the advantage that also take in account the 'locale' i.e. any variant of the local language/coding system.

[:digit:]      Only the digits 0 to 9
[:alnum:]      Any alphanumeric character 0 to 9 OR A to Z or a to z.
[:alpha:]       Any alpha character A to Z or a to z.
[:blank:]       Space and TAB characters only.
[:xdigit:]     .
[:punct:]       Punctuation symbols . , " ' ? ! ; :
[:print:]      Any printable character.
[:space:]      Any space characters.
[:graph:]       .
[:upper:]       Any alpha character A to Z.
[:lower:]       Any alpha character a to z.
[:cntrl:]        .
mina86 at tlen dot pl 19-Oct-2003 10:14
I tested how fast POSIX and Perl regular expresions are, and here are the results:

           | POSIX Extended  | Perl-Compatible |   POSIX - Perl
-----------+-----------------+-----------------+-----------------
     match |    0.1296420097 |    0.1006720066 |  0.0289700031
   match i |    0.1204010248 |    0.1101620197 |  0.0102390051
   replace |    0.1896649599 |    0.1298999786 |  0.0597649813
 replace i |   10.6998120546 |    0.1453789473 | 10.5544331074

So, as you can see, preg_* functions are faster then ereg* functions. You can find source code of my test script here: http://mina86.home.staszic.waw.pl/temp/regexp-speed-test.txt
Robin 15-Jan-2003 10:53
Ever wondered how to exclude "[" and "]"?
Here it goes: "[^][]". Extra characters to exclude can beadded right in the middle like this: "[^]fobar[]".
moc DOT liamtoh AT ssengnorw 18-Oct-2002 09:28
In a PCRE \s matches whitespace, but not inside a character class:

preg_match ('/\s/', ' ') // match
preg_match ('/[\s]/', ' ') // no match

Within a character class [:space:] is treated as a single character that matches any single whitespace character:

$pattern = '/[[:space:]]/';
$subject = "space tab\tnewline\n";
preg_match_all($pattern, $subject, $out) // == 3

To match a hyphen from within a character class, it must either be first or last; otherwise, it will act as a range operator.

Example: To match a blank string or a string containing only uppercase letters, underscores, spaces, and hyphens:

preg_match('/^[A-Z_ -]*$/', $subject)

To match any whitespace, not just spaces:

preg_match('/^[A-Z_[:space:]-]*$/', $subject)
paper 08-Sep-2002 11:57
I have also experienced the same problem as bps7j@yahoo.com had been experiencing, except I did not recognize the problem until after many hours of debugging.

"\s" does not seem to represent spaces, however "[[:space:]]" does.

Another problem I was having was matching dashes/hyphens '-'. You must escape them "\-" and place them at the end of a bracket expression.

Example: To match a blank string or a string containing only uppercase letters, underscores, spaces, and hyphens:

^([A-Z_\-]|[[:space:]])*$

Hope this saves someone some time from debugging like I was. :)
bps7j at yahoo dot com 21-Aug-2002 07:40
Something that really got me: I'm used to using Perl's regexps, and so I used \s to check for a whitespace character in a password on a website. My PHP book (Wrox Press, Professional PHP Programming) agreed with me that this is exactly the same as [ \r\n\t\f\v], but it's NOT. In fact, what it did was keep anyone from joining the site if they put an 's' in their password! So beware, check for subtle differences between what you're used to and PHP.

[[:space:]] works fine, by the way.

I'm going to use the pcre functions from now on... I like Perl :o)
david at NOgreenhammerSPAM dot com 09-Mar-2002 10:40
Sadly, the Posix regexp evaluator (PHP 4.1.2) does not seem to support multi-character coallating sequences, even though such sequences are included in the man-page documentation.

Specifically, the man-page discusses the expression "[[.ch.]]*c" which matches the first five characters of "chchcc".  Running this expression in ereg_replace generates the error "Warning: REG_ECOLLATE".  (Running an equivalent expression with only one character between the periods does work, however.)

Multi-character coallating sequences are not supported!

This is really, really too bad, because it would have provided a simple way to exlude words from the target.

I'm going to go learn PCRE, now.  :-(
regex at dan42 dot cjb dot net 07-Mar-2002 10:33
Follow-up to my previous post:
Some simple optimization allowed me to realize that excluding a word at the beginning of a string has a degree of complexity O(n) rather than O(n^2). I only had to follow the logic:

if str[0] != badword[0] then OK
else
  if str[1] != badword[1] then OK
  else
    if str[2] != badword[2] then OK
    else ...

So excluding the word 'abc' at the beginning of a string is much more simple than I had made it out to be:
  ^([^a]|a[^b]|ab[^c])
spiceee at potentialvalleys dot com 06-Mar-2002 10:26
sorry to be picky here but saying ^ is beginning of a line or $ is end of line is rather misleading, if you're working on a daily basis with regexes.

it might be that it is most of the time correct BUT in some occasions you'd be better off to think of ^ as "start of string" and $ as "end of string".

there are ways to make your regex engine forget about your system's notion of a newline, it's what is commonly refered to as multiline regexes...
luciano_at_braziliantranslation.net 03-Mar-2002 12:15
mholdgate wrote a very nice quick reference guide in the next page (http://www.php.net/manual/en/function.ereg.php), but I felt it could be improved a little:
________________

^        Start of line
$        End of line
n?        Zero or only one single occurrence of character 'n'
n*        Zero or more occurrences of character 'n'
n+        At least one or more occurrences of character 'n'
n{2}        Exactly two occurrences of 'n'
n{2,}        At least 2 or more occurrences of 'n'
n{2,4}        From 2 to 4 occurrences of 'n'
.        Any single character
()        Parenthesis to group expressions
(.*)        Zero or more occurrences of any single character, ie, anything!
(n|a)        Either 'n' or 'a'
[1-6]        Any single digit in the range between 1 and 6
[c-h]        Any single lower case letter in the range between c and h
[D-M]        Any single upper case letter in the range between D and M
[^a-z]        Any single character EXCEPT any lower case letter between a and z.

        Pitfall: the ^ symbol only acts as an EXCEPT rule if it is the
        very first character inside a range, and it denies the
        entire range including the ^ symbol itself if it appears again
        later in the range. Also remember that if it is the first
        character in the entire expression, it means "start of line".
        In any other place, it is always treated as a regular ^ symbol.
        In other words, you cannot deny a word with ^undesired_word
        or a group with ^(undesired_phrase).
        Read more detailed regex documentation to find out what is
        necessary to achieve this.

[_4^a-zA-Z]    Any single character which can be the underscore or the
        number 4 or the ^ symbol or any letter, lower or upper case

?, +, * and the {} count parameters can be appended not only to a single character, but also to a group() or a range[].

therefore,
^.{2}[a-z]{1,2}_?[0-9]*([1-6]|[a-f])[^1-9]{2}a+$
would mean:

^.{2}         = A line beginning with any two characters,
[a-z]{1,2}     = followed by either 1 or 2 lower case letters,
_?         = followed by an optional underscore,
[0-9]*         = followed by zero or more digits,
([1-6]|[a-f])     = followed by either a digit between 1 and 6 OR a
        lower case letter between a and f,
[^1-9]{2}     = followed by any two characters except digits
        between 1 and 9 (0 is possible),
a+$         = followed by at least one or more
        occurrences of 'a' at the end of a line.
regex at dan42 dot cjb dot net 20-Feb-2002 09:12
It's easy to exclude characters but excluding words with a regular expression is a bit more tricky. For parentheses there is no equivalent to the ^ for brackets. The only way I've found to exclude a string is to proceed by inverse logic: accept all the words that do NOT correspond to the string. So if you want to accept all strings except those _begining_ with "abc", you'd have to accept any string that matches one of the following:
  ^(ab[^c])
  ^(a[^b]c)
  ^(a[^b][^c])
  ^([^a]bc)
  ^([^a]b[^c])
  ^([^a][^b]c)
  ^([^a][^b][^c])

which, put together, gives the regex
  ^(ab[^c]|a[^b]c|a[^b][^c]|[^a]bc|[^a]b[^c]|[^a][^b]c|[^a][^b][^c])

Note that this won't work to detect the word "abc" anywhere in a string. You need to have some way of anchoring the inverse word match
like: ^(a[^b]|[^a]b|[^a][^b])   ;"ab" not at begining of line
  or: (a[^b]|[^a]b|[^a][^b])&   ;"ab" not at end of line
  or: 123(a[^b]|[^a]b|[^a][^b]) ;"ab" not after "123"

I don't know why "(abc){0,0}" is an invalid synthax. It would've made all this much simpler.

Slightly off-topic, here's a regex date validator (format yyyy-mm-dd, remove all spaces and linefeeds):
  ^(19|20)([0-9]{2}-((0[13-9]|1[0-2])-(0[1-9]|[12][0-9]|30)|
  (0[13578]|1[02])-31|02-(0[1-9]|1[0-9]|2[0-8]))|([2468]0|
  [02468][48]|[13579][26])-02-29)$
02-Feb-2002 07:02
if you are looking for the abbreviations like tab, carriage return, regex-class definitions

you should look here:
http://elvin.dstc.edu.au/doc/regex.html

some excerpts:

    \a    control characters bell
    \b    backspace
    \f    form feed
    \n    line feed
    \r    carriage return
    \t    horizontal tab
    \v    vertical tab

class example
    \cLu    all uppercase letters
Примеры
ereg_replace
Регулярные выражения POSIX


Осуществляет замену по регулярному выражению

Функции регулярных выражений POSIX
ereg
Функции регулярных выражений POSIX
PHP Manual

ereg_replace

(PHP 4, PHP 5)

ereg_replace — Осуществляет замену по регулярному выражению

Описание

string ereg_replace ( string $pattern , string $replacement , string $string )

Эта функция сканирует строку string для поиска совпадений с pattern, затем заменяет совпавший текст на replacement.

Внимание

С версии PHP 5.3.0 эта функция считается УСТАРЕВШЕЙ. Крайне не рекомендуется полагаться на эту возможность.

Список параметров

pattern

Расширенное регулярное выражение POSIX.

replacement

Если pattern содержит подстроки в скобках, replacement может содержать подстроки вида \digit, которые будут заменены текстом, совпавшим с digit-подстрокой в скобках; \0 воспроизведет все содержимое строки. Может использоваться до 9 подстрок. Круглые скобки могут быть вложенными, в этом случае они подсчитываются по открывающим скобкам.

string

Исходная cтрока.

Возвращаемые значения

Возвращается измененная строка. Если в строке string совпадений не найдено, она возвратится без изменений.

Примеры

Например, следующий фрагмент кода печатает "This was a test" три раза:

Пример #1 Пример использования ereg_replace()

<?php

$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\\1was", $string);
echo ereg_replace("(( )is)", "\\2was", $string);

?>

Единственное, что следует принять к сведению - если вы используете целочисленное значение как параметр replacement, вы можете не получить ожидаемого результата. Это происходит из-за того, что функция ereg_replace() будет интерпретировать число как порядковое значение символа. Например:

Пример #2 Пример использования ereg_replace()

<?php
/* Это будет работать не так, как ожидалось. */
$num = 4;
$string = "В этой строке четыре слова.";
$string = ereg_replace('четыре', $num, $string);
echo $string;   /* Вывод: 'В этой строке   слова.' */

/* Это будет работать. */
$num = '4';
$string = "В этой строке четыре слова.";
$string = ereg_replace('четыре', $num, $string);
echo $string;   /* Вывод: 'В этой строке 4 слова.' */
?>

Пример #3 Замена URL-адресов на ссылки

<?php
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     '<a href="\\0">\\0</a>', $text);
?>

Примечания

Замечание:

С версии PHP 5.3.0, расширение regex помечено устаревшим и заменено расширением PCRE. Вызов этой функции приведет к ошибке уровня E_DEPRECATED. Смотрите список отличий для помощи при конвертировании в PCRE.

Подсказка

Функция preg_replace(), которая использует Perl-совместимый синтаксис регулярного выражения, часто является более быстрой альтернативой функции ereg_replace().

Смотрите также

  • ereg() - Совпадение с регулярным выражением
  • eregi() - Совпадение с регулярным выражением без учёта регистра
  • eregi_replace() - Осуществляет замену по регулярному выражению без учета регистра
  • str_replace() - Заменяет все вхождения строки поиска на строку замены
  • preg_replace() - Выполняет поиск и замену по регулярному выражению

User Contributed Notes

lvt 17-Oct-2010 07:11
Be careful, don't replace all ereg_replace() with str_replace() as many people will likely to recommend if there is regular expression stuffs, or your script will stop running !!!

Example : replace the (.) at the end of the text with (...)

<?php

$text = "This is a simple text.";

print( ereg_replace( "\.$", "...", $text ) );

?>

Test with str_replace() you will find it's not working.
Joe 25-Jun-2010 11:24
Since ereg_replace is now deprecated, many users will be coming to this page, in an attempt to troubleshoot and fix broken scripts after a PHP upgrade.

ereg_replace is essentially a search and replace function and it follows a pattern like this:

<?php

$input = ereg_replace("find this", "replace it with", $output);

?>

You start out by defining the input variable ($input), then the = ereg_replace portion tells php to do a search and replace action on the value of $input, then once the value has been modified with your 'find this' and 'replace with' section, the resulting value is defined as a variable $output which you can then use in other parts of your script or page.

Lets take a real world example.

There is a e-comm site - http://www.example.com - that has millions of item records.  Each item has a name, that is defined as a variable called $title.  Each $title value has spaces, i.e. "Range Cookers" or "Bosch Dishwashers", but we want to convert these into a page url that does not contain spaces, but uses the plus character '+' instead of a space (you can use hyphens '-' or other characters).

If using the deprecated ereg_replace function, it might look something like this:

<?php

$title=ereg_replace(" ", "+", $itemurl);

?>

But to avoid those deprecated errors, we change the function name to preg_replace and add a set of delimiters, in this case the 2 forward slashes / / where the contents inside that are matched as the 'find this' portion.

<?php

$title=preg_replace("/ /", "+", $itemurl);

?>

It is not absolutely necessary to use / / as the delimiters, if you are modifying directory names which may naturally contain forward slashes, it could cause it to break because the slashes in the url or directory would be interpreted as the delimiter, so you could use other obscure characters i.e.  ("# #", "+", $itemurl);  instead.  This would give an output like:

http://www.example.com/-Range+Cooker

http://www.example.com/-Bosch+Dishwasher

This would strip out the spaces from the value of $title and give you a variable called $itemurl where all the spaces were replaced with the plus character, so you could potentially use it as a url like above.

So to summarize:  ereg_replace is a deprecated search and replace action where preg_replace can be used instead, and it follows a pattern as described earlier where it takes the input data, finds a match based on what you are looking for, replaces it with something else you define, and then gives you an output data variable that you can use in your script or page.  Hopefully by understanding the process, the php code functions wont seem like voodoo and you could troubleshoot and fix many of the deprecated errors yourself.
Anonymous 06-Mar-2009 07:17
<?php
// highlights the recognized patterns (a good tool for experiments)

$output = ereg_replace("your regexp here", "<font color=red>\\0</font>", $input)
print $output;
?>
Real PHP Geek 01-Feb-2009 03:55
This function makes links unclickable, read the comments:

<?php
function strip_urls($text, $repPat)
{
    if(!$repPat){
        $repPat = "text [url]";
    }
    $aimpstr = 'PHP_STRIP_URLS_FUNCTION_BY_REAL-PHP-GEEK';
    //change $aimpstr to anything you want.
    $impstr = md5($aimpstr);
    $text = str_replace('</a>', '</a>' . $impstr, $text);
    $text = explode($impstr, $text);
    $n = 0;
    $texta = array();
    $repPat = str_ireplace(array('text', 'url'), array('\\4', '\\2'), $repPat);
    foreach ($text as $text) {
        $texta[$n] = ereg_replace("<a(.*)href=\"(.*)\"(.*)>(.*)</a>", $repPat, $text);
        $n++;
    }
    $textb = implode("</a>", $texta);
    return $textb;
}

//EXAMPLES:
$string_of_text = '<a href="http://www.php.net/">PHP</a> rocks. <a href="http://www.apache.org/">Apache</a> also!';
echo strip_urls($string_of_text, "text");
echo strip_urls($string_of_text, "url");
echo strip_urls($string_of_text, "text [url]");
echo strip_urls($string_of_text, NULL);
?>
computer_guru 06-Aug-2008 04:39
Here is the code I use to make links clickable. The code only works on xxxx:// (i.e. ftp://, http://, etc...). It does not work on www. because that is how I want it. The reason my code has an if condition is that it ignores html links and only modifies non-html urls. (see below)

<?php
function make_clickable($text)
{

    if (ereg("[\"|'][[:alpha:]]+://",$text) == false)
    {
        $text = ereg_replace('([[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/])', '<a target=\"_new\" href="\\1">\\1</a>', $text);
    }
    return($text);
}
?>

My function ignores code like this:

<a href="http://php.net"> php.net </a>

But it would make this one click able:

http://php.net
jammin320 03-Jul-2008 12:52
Just a quick addition to the last post -

modifying the regular expression for the www clause to include a newline at the begining will allow it to catch URLs that are the first in a line but not the first in a string. The previous version would only catch them if a space preceded the value...

    // match www.something
    $text = ereg_replace("(^| |\n)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
http://www.bbgames.co.nr 04-May-2008 07:57
In response to a post above, his coding was a bit wrong.  The correct coding should be :

<?php
function hyperlink($text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);

    // return $text
    return $text;
}
?>

You can use this function like this:
<?php
$line = "Check the links: www.yahoo.com http://www.php.net";
hyperlink($line);
// Now, all text that looks like a link becomes a link
?>
tugla 29-Feb-2008 09:29
If you're not relying on regular expressions, str_replace() can be far faster.
Renjith 20-Jan-2008 10:02
Code:

<?php

$s = "Coding PHP is fun.";

$pattern = "(.*)PHP(.*)";
$replacement = " They say \\1other languages\\2";

print ereg_replace($pattern, $replacement, $s);

?>

Output:
They say Coding other languages is fun.
Explanation:

"PHP" is replaced with "other languages", and the sentence is changed a little, using \1 and \2 to access the parts within parentheses.
http://php-regex.blogspot.com/
bjwarshaw2 at yahoo dot com 29-Sep-2007 06:27
It's worth mentioning for ultimate clarity that you're safest using double quotes when matching a pattern, since without them, metacharacters will be interpreted as a backslash plus another character.

Granted, this is part of the language syntax for the string type, but it might not be quite so obvious when dealing with patterns in this function, which is taking the pattern as a parameter.

So if you find that '[\n]' is taking the 'n' out of your string and leaving the new lines alone, switch to doubles before changing anything else.
jarfil at jarfil dot net 26-Aug-2007 02:42
For simple patterns like "[a-z]", preg_replace is up to 6 times faster than ereg_replace.
mephissto at gmail dot com 30-May-2007 06:40
Your right but you just need to replace by :

<?php
function hyperlink(&$text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| |.)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
?>
hoffaboffa (at) hotmail dott com 15-May-2007 06:03
cristiklein's hyperlink function is nice but works incorrect with a www-string like this

\r\nwww.google.se

then it does not become a hyperlink
bmcswee at gmail dot com dot invalid 06-Apr-2007 09:33
Function to strip an HTML tag out of a string. I use this in part for parsing XML documents.

<?php

function stripTags($tag, $string) {
        // Regular expressions only work with strings if the regexp has been pre-concocted
    $regExp = "<" . "$tag" . "[^>]*>";

    $string = str_replace("</$tag>", "", $string);
    $string = ereg_replace($regExp, "", $string);

    return $string;
}

?>
Joachim Kruyswijk 25-May-2006 12:59
Use mb_ereg_replace() instead of ereg_replace() when working with multi-byte strings!
chrish at shield dot on dot ca 12-Feb-2006 05:43
I was having problems with Microsoft Outlook viewing forms within email.  I was only able to see the first word of the text box after I used the following code.

If I entered words into the text box and used the enter key to give me a CRLF I could see in the returned data the %0D%0A string, so I assumed if I just used the ereg-replace as below it would just replace the %0D%0A with a single space...

function remove_extra_linebreaks($string) {
   $new_string=ereg_replace("%0D%0A", " ", $string);
  return $new_string;
}

But the form as displayed by Outlook only showed the text upto the first replaced string, then it was blank!
I could view the source of the email and it would show all of the text I expected.

The following will show the correct data in the form

function remove_extra_linebreaks($string) {
   $new_string=ereg_replace("%0D%0A", '+', $string);
  return $new_string;
}
Chris 20-Jan-2006 11:43
I've updated the function a little that was posted below.  I use it to make database field names readable when making a header row.  I needed it to quit putting a space in "GPA" and to put a space in between numbers and letters.

<?php
/**
*  Converts "fieldcontainingGPAInMyDatabaseFrom2005"
*  To       "Field Containing GPA In My Database From 2005"
*/
function innerCapsToReadableText($text) {
    $text = ereg_replace("([A-Z]) ", "\\1",ucwords(strtolower(ereg_replace("[A-Z]"," \\0",$text))));
    return ereg_replace("([A-Za-z])([0-9])", "\\1 \\2", $text);
}
?>
codergeek42 at users dot sourceforge.net 21-Dec-2005 09:15
In response to "php dot net at lenix dot de," a cleaner (easier to read) method would be to type-cast the integer as a string by quoting it. For example:

<?php
$foo = 42;
echo ereg_replace ( "bar", "$foo" , "foobar" ); /* Would output "foo42". */
?>
benlanc at ster dot me dot uk 22-Aug-2005 03:49
Quite how I managed to get my previous post so wrong, I don't know. Correction follows:
<?php
/* function to turn InterCaps style strings (i.e. CSS Properties in Javascript) to human readable ones */
function deInterCaps($var){
   return ucfirst(strtolower(ereg_replace("[A-Z]"," \\0",$var)));
}

$interCapsString = "aLoadOfNonsenseToDemonstrateTheFunction";

echo deInterCaps($interCapsString);

// output: A load of nonsense to demonstrate the function
?>
php dot net at lenix dot de 07-Jul-2005 03:26
One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that.

If you're ever having trouble with this one there's an easy workarround:

instead of
<?php
$foo = 23;
echo ereg_replace ( "bar", $foo , "foobar" );
?>

just do

<?php
$foo = 23;
echo ereg_replace ( "bar", "" . $foo , "foobar" );
?>

to replace "bar" inside "foobar" with the string "23".
zaczek at gmail dot com 05-Jul-2005 04:09
If you want the function to process query strings, such as:

http://www.php.net/index.php?id=10%32&wp=test

modify the function as follows:

function hyperlink(&$text)
{
   // match protocol://address/path/
   $text = ereg_replace("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\">\\0</a>", $text);

   // match www.something
   $text = ereg_replace("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
cristiklein at yahoo dot com 09-Apr-2005 02:50
Sometimes, you would like to match both styles of URL links that are common in chat windows:

http://www.yahoo.com
www.yahoo.com

You can do this by using the following code:

<?php
function hyperlink(&$text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
?>

You can use this function like this:
<?php
$line = "Check the links: www.yahoo.com http://www.php.net";
hyperlink($line);
// Now, all text that looks like a link becomes a link
?>
bgoodman at osogrande dot com 02-Mar-2005 02:25
When you are dealing with databases you can end up with quite a few \" to deal with.  To ereg_replace all these with something else it requires you to \ the \ and \ the " so you end up with:

$var1 = '\"';
$var2 = ereg_replace('\\\"','1234',$var1);

print $var2;  //this should print 1234
eerie at gmx dot net 27-Feb-2005 11:44
<?php $path = ereg_replace("\\", "/", $path); ?>
as posted from mmtach at yahoo dot com causes an error because you have to escape the backslash twice, once for the quotation marks and a second time due the posix syntax.
<?php $path = ereg_replace("\\\\", "/", $path); ?>
or
<?php $path = ereg_replace('\\', "/", $path); ?>
should both work as expected. since you don't have to escape the backslash in brackets (posix syntax) his alternative works also.
Функции регулярных выражений POSIX
ereg
Функции регулярных выражений POSIX


Совпадение с регулярным выражением

ereg_replace
eregi_replace
Функции регулярных выражений POSIX
PHP Manual

ereg

(PHP 4, PHP 5)

ereg — Совпадение с регулярным выражением

Описание

int ereg ( string $pattern , string $string [, array &$regs ] )

Ищет в строке string совпадения с регулярным выражением, заданным в pattern регистрозависимым образом.

Внимание

С версии PHP 5.3.0 эта функция считается УСТАРЕВШЕЙ. Крайне не рекомендуется полагаться на эту возможность.

Список параметров

pattern

Регулярное выражение, чувствительное к регистру.

string

Входная строка.

regs

Если совпадения найдены для подстрок в скобках из pattern, и функция вызывается с третьим аргументом regs, совпадения будут сохранены в элементах массива regs.

$regs[1] будет содержать подстроку, которая начинается с первой левой круглой скобки; $regs[2] будет содержать подстроку, начинающуюся со второй, и т.д. $regs[0] будет содержать полную копию совпавшей строки.

Возвращаемые значения

Возвращает длину совпавшей строки, если совпадение c pattern найдено в string, или FALSE, если совпадений не было или возникла ошибка.

Если необязательный параметр regs не передан, или длина совпавшей строки равна 0, функция возвращает 1.

Список изменений

Версия | Описание
4.1.0 | Вплоть до (и включая) PHP 4.1.0 $regs будет заполняться точно десятью элементами, хотя реально может совпасть больше или меньше десяти подстрок в скобках. Это не влияет на способность ereg() совпадать с большим количеством подстрок. Если совпадения не найдены, $regs не будет изменен функцией ereg().

Примеры

Пример #1 Пример использования ereg()

Следующий фрагмент кода принимает дату в формате ISO (YYYY-MM-DD) и печатает её в формате DD.MM.YYYY:

<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
    echo "$regs[3].$regs[2].$regs[1]";
} else {
    echo "Недопустимый формат даты: $date";
}
?>

Примечания

Замечание:

С версии PHP 5.3.0, расширение regex помечено устаревшим и заменено расширением PCRE. Вызов этой функции приведет к ошибке уровня E_DEPRECATED. Смотрите список отличий для помощи при конвертировании в PCRE.

Замечание:

Функция preg_match(), которая использует Perl-совместимый синтаксис регулярного выражения, часто является более быстрой альтернативой функции ereg().

Смотрите также

  • eregi() - Совпадение с регулярным выражением без учёта регистра
  • ereg_replace() - Осуществляет замену по регулярному выражению
  • eregi_replace() - Осуществляет замену по регулярному выражению без учета регистра
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • strpos() - Возвращает позицию первого вхождения подстроки
  • strstr() - Находит первое вхождение подстроки
  • quotemeta() - Экранирует специальные символы

User Contributed Notes

lists at cmsws dot com 09-Nov-2009 11:19
My rendition of a function that validates email addresses.

<?php
function validate_EmailAddress($email) {
  return
    is_string($email) &&
    !empty($email) &&
    eregi("^[a-z0-9_-]+[a-z0-9_.-]*@[a-z0-9_-]+[a-z0-9_.-]*\.[a-z]{2,5}$", $email);
}

?>
datai at mail dot ru 16-May-2009 03:47
email validation, based on previous script:

<?php
function validateMail($mail) {
  if($mail !== "") {
    if(ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $mail)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}
?>
Remember, from "if(ereg..." to "$mail)) {" it's ONE line. Dont brake it. =)
Thanks to Parsaj.
parsaj at gmail dot com 22-Apr-2009 03:33
Here a little clear and easy script
that I wrote to validate an E-Mail Input.

I tried to understand ereg,
but the describtion on php.net did not help me,
so I made some research and finally (think)
that Im sure how to use ereg.

The following function works for me well and allows
an E-Mail to contain the following characters:
"A-Z, a-z, 0-9, . , - , _ "

<?php
function validateMail($mail) {
    if($mail !== "") {
        if(!ereg("^[A-Za-z0-9\.|-|_]*
          [@]{1}[A-Za-z0-9\.|-|_]*[.]{1}[a-z]{2,5}$", $mail)) {
        echo "wrong Input for E-Mail";
        $mail ="";
        return $mail;
         }
        else {
        return $mail;
        }
    }
}
?>

to make it clear:
^ means begin here (startpoint of ereg)
$ means end here (endpoint of ereg)
* stand for endless characters (I want A-Z, a-z, 0-9 and the other characters to apear from 0 to endless
optional you can write {1,5} for
min 1 times a character or max 5 times a
characters instead of *
{1,2} means min 1 time a character and max 2 times a character (optional you can write * intead of {1,2}
{1} stand for max 1 time a character
\ means from here special characters (like .-_$ and so on)
| means OR
Anonymous 16-Jan-2009 12:20
Recognizing E-mail Addresses

worth noting: a valid e-mail may contain a + character.

for example:
if you send e-mail to myemail+something@gmail.com, gmail reroutes it to the account myemail@gmail.com. This is a useful feature, and it is very frustrating when websites that take your e-mail don't allow you to do this.
hreisin at gmail dot com 21-Nov-2008 01:50
Hi,
for those looking for email adress PHP validation,
isemail is a javascrit function that checks the following conditions for the email string:

   • only one @ sign permitted
   • domain extension separator (.) must come after the @ symbol
   • must be at least 2 characters (letters) after the domain extension separator (.)
   • rejects all illegal characters including spaces.
   • Allows only numbers, letters, the underscore (_) and the dash (-) character as valid input
     (excluding the mandatory "@" and "." symbols).
   • Minimum of 6 characters

The following pattern satisfy all-in-one for the ereg function:
$pattern = "^([A-Za-z0-9\.|-|_]{1,60})([@])";
$pattern .="([A-Za-z0-9\.|-|_]{1,60})(\.)([A-Za-z]{2,3})$";

ereg($pattern,$email)
pascalaschwandenPLEASENOSPAM at gmail dot com 18-Jul-2008 06:16
Here is a series of useful regular expressions.

<?php
function isValid($type,$var) {
 $valid = false;
 switch ($type) {
  case "IP":
   if (ereg('^([0-9]{1,3}\.){3}[0-9]{1,3}$',$var)) {
    $valid = true;
   }
   break;
  case “URL”:
   if (ereg("^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu)$",$var)) {
    $valid = true;
   }
   break;
  case “SSN”:
   if (ereg("^[0-9]{3}[- ][0-9]{2}[- ][0-9]{4}|[0-9]{9}$",$var)) {
    $valid = true;
   }
   break;
  case “CC”:
   if (ereg("^([0-9]{4}[- ]){3}[0-9]{4}|[0-9]{16}$",$var)) {
    $valid = true;
   }
   break;
  case “ISBN”:
   if (ereg("^[0-9]{9}[[0-9]|X|x]$",$var)) {
    $valid = true;
   }
   break;
  case “Date”:
   if (ereg("^([0-9][0-2]|[0-9])\/([0-2][0-9]|3[01]|[0-9])\/[0-9]{4}|([0-9][0-2]|[0-9])-([0-2][0-9]|3[01]|[0-9])-[0-9]{4}$",$var)) {
    $valid = true;
   }
   break;
  case “Zip”:
   if (ereg("^[0-9]{5}(-[0-9]{4})?$",$var)) {
    $valid = true;
   }
   break;
  case "Phone":
   if (ereg("^((\([0-9]{3}\) ?)|([0-9]{3}-))?[0-9]{3}-[0-9]{4}$",$var)) {
    $valid = true;
   }
   break;
  case “HexColor”:
   if (ereg('^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$',$var)) {
    $valid = true;
   }
   break;
  case “User”:
   if (ereg("^[a-zA-Z0-9_]{3,16}$",$var)) {
    $valid = true;
   }
   break;
 }
 return $valid;
}

#Example:
$phone = "789-1234";
if (isValid("Phone",$phone)) {
 echo "Valid Phone Number";
} else {
 echo "Invalid Phone Number";
}
?>
Jeff K. 18-Jul-2008 01:16
In reply to Francis,

Your regular expression:
$pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";

I actually used this to validate a phone number. The one discrepancy I found is with patterns such as 503-555-1212, 503-5551212, [503]5551212, and every other pattern that does not have single whitespace or a dash as a delimiter, ereg() will return false when given your expression.

Based on your pattern, I came up with a more general and concise version making use of the dot meta-character:
$pattern = "^.?[0-9]{3}.?.?[0-9]{3}.?[0-9]{4}$";

When passed to ereg(), it will return "true" so long as there is 10 digits, regardless of the delimiter chosen by the user.

[503] 5551212 //true
5035551212 //true
503+555 1212//true

$pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";
Jeremy M at unitydc dot co dot uk 23-May-2008 05:11
UK postcode validation.

We've used the expression put forward by tomas and jaik,
but we found that it fails on Coventry (CV) postcodes.

Here is an alternative that works for these postcodes and
also adds support for the Overseas Territories like Tristan da Cunha.

<?php

function IsPostcode($postcode) {
    $postcode = strtoupper($postcode);
    if(ereg("((GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)"
."|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)"
."|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]"
."|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))"
."|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})", $postcode)) {
        return $postcode;
    } else {
        return FALSE;
    }
}

?>
John Thur 02-Apr-2008 11:29
<?php
function fractionstr2decimal($fs){
        if (is_numeric($fs)){
                return $fs;
        } elseif (ereg ("([0-9]{1,6}[ ])?([0-9]{1,6})\/([0-9]{0,6}[1-9][0-9]{0,6})", $fs, $regs)) {
        /* ({1-6 digits}space  optional) {1-6 digits}/(1-13 digits with at least one digit not 0 )*/
                return ($regs[1]+$regs[2]/$regs[3]);
        } else {
                return (NULL); /* Invalid Fraction */
        }
}

echo fractionstr2decimal("1024 5/132")."<br>";   /* 1024.0378787879  */
echo fractionstr2decimal("23")."<br>";           /* 23 */

$i=fractionstr2decimal("1 2/3");
echo "<br>$i";                                  /* 1.66666666666667 */
if ($i and $i<=1 ) echo "<1<br>";               /*  */
$i=fractionstr2decimal("2/3");
echo "<br>$i";                                  /*  0.66666666666667 */
if ($i and $i<=1 ) echo "<1<br>";               /*  <1 */
$i=fractionstr2decimal("2/0");
echo "<br>$i";
if ($i and $i<=1 ) echo "<1<br>";
?>
Francis 29-Mar-2008 12:35
I noticed that /s which is used to check for spaces doesn't work with ereg.  Not sure why. Here's an example of a US phone validation function that works for me.  I couldn't find a working example anywhere, so here it is.

<?

function invalid_phone($phone_no){
  $pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";
  $phone_no = trim($phone_no);
  if (!ereg($pattern, $phone_no)) return 1;
  return 0;
} // invalid_phone

// example of use

$phone = "(503) 555-1212";  // ok
$phone = "(503) 555 - 1212"; // ok
$phone = "503-555-1212"; // ok
$phone = "503 - 555 - 1212"; // ok
$phone = 5035551212; // ok

if (invalid_phone($phone) > 0) echo "Make sure the phone number you have entered matches the standard format: (503) 555-1212";
?>
E. Stuart Hicks 27-Feb-2008 11:23
It's important to note for certain regular expression that your $regs[] array will only contain as many values as you have sets of parenthesis in your regexp. (plus 1, of course)  For example, the regexp below was designed to locate tags enclosed in <> characters inside a string:

<?php ereg("^([^<]*)(<[^>]+>[^<]*)*$", $str, $tags) ?>

This will *not* create an arbitrarily long array in $tags for the number of tags that it finds.  Given the string "This <has> a <couple> of <tags> in it", you'll see:

0 : This <has> a <couple> of <tags> in it
1 : This
2 : <tags> in it

Since the same parenthesized section of the regexp is matching all tags found, it overwrites the same section of the array.  If you try increasing the number of parenthesis, it just creates duplicates of the same result.
Will 01-Feb-2008 07:47
There is undocumented behaviour for this command!

You cannot check for strings of 1-256 characters or longer.

For example, this will evaluate to true:

ereg("^[a-zA-Z0-9' ]{1,255}$","ghfhg");

But this will give the error:
PHP Warning:  ereg(): REG_BADBR

ereg("^[a-zA-Z0-9' ]{1,256}$","ghfhg");

PHP version (on Windows XP):

PHP 5.2.5 (cli) (built: Nov  8 2007 23:18:51)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
savage 28-Jan-2008 08:38
This is a fix for days over 31 and shorter version
^(([1]{1}[0-2]{1}|[0]{0,1}[1-9]{1})[\-]{1}([0-2]{0,1}\d{1|
[3]{1,1}[0-1]{1})[\-]{1}[1-2]{1}\d{3}|([0-2]{0,1}\d{1}|
[3]{1,1}[0-1]{1})[\-]{1}([1]{1}[0-2]{1}|[0]{0,1}[1-9]{1})
[\-]{1}[1-2]{1}\d{3}|[1-2]{1}\d{3}[\-]{1}([1]{1}[0-2]{1}|
[0]{0,1}[1-9]{1})[\-]{1}([0-2]{0,1}\d{1}|[3]{1,1}[0-1]{1}))$
savage at gmail dot com 27-Jan-2008 08:48
This is a date regexp that I made to allow different combinations of month, day, and year. it's rather long but it works.

(^([0-3]{0,1})([1-9]{1,1})([\-]{1,1})(([1]{1,1})([0-2]{1,1})|
([0]{0,1})([1-9]{1,1}))([\-]{1,1})([1-2]{1,1})(\d{3})$)|
(^(([1]{1,1})([0-2]{1,1})|([0]{0,1})([1-9]{1,1}))([\-]{1,1})
([0-3]{0,1})([1-9]{1,1})([\-]{1,1})([1-2]{1,1})(\d{3})$)|
(^([1-2]{1,1})(\d{3})([\-]{1,1})(([1]{1,1})([0-2]{1,1})|
([0]{0,1})([1-9]{1,1}))([\-]{1,1})([0-3]{0,1})([1-9]{1,1})$)

yyyy-mm-dd, mm-dd-yyyy, dd-mm-yyyy
2007-02-05
12-25-2007
25-02-2007
2-5-2007
25-2-2007
2007-9-23
09-06-2007
09-23-2007
The above will check valid

Anything not in one of the combinations of dd,mm,yyyy formats above will fail.

these will also fail
2007-32-12
13-22-2007
0-1-2007
1-0-2007

Any sugestions on making it smaller and more efficients would be appreciated.
notbald at gmail spam away com 11-Jul-2007 01:26
Save yourself some headache and time, don't use the \d (digits) \w (alphanumeric) and \s (whitespace) short forms. Not only do they make the code less readable, they don't seem to work with ereg.

Use [0-9], [A-Za-z0-9], [ \n\r\t] instead.

Since the regex example in this article is a bit on the complex side, I'll throw in a simpler regex example:

Say you want to validate valid variable names:

<?php
$regex_valid_variable_name = '^[A-Za-z_][A-Za-z0-9_]*$';

// ^ in this context means that the regex is anchored
// to the beginning of the string.
//
// A single [xxx] means that a single letter must mach
// the criteria within
//
// The [xxx]* means that [xxx] can mach from zero to
// unlimited times.
//
// The $ is another anchor, except it is for the end of
// the sting.

// Valid names: "_", "hello1", "a_variable"
// Invalid names: "4number", "five-to", "one two", " space "

//Test it out:
$regx = $regx_valid_variable_name;
$valid = array ( '_', 'hello1', 'a_variable' );
$invalid = array ( '4number', 'five-to', 'one two', ' space ');
foreach($valid as $v)
    echo 'Valid '.(ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n";

foreach($invalid as $v)
    echo 'Invalid '.(!ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n";
?>
jaik at fluidcreativity dot co dot uk 31-Aug-2006 08:41
Here is a fixed version of the UK postcode check function by tomas at phusis dot co dot uk. There was a bug on line 2 of the reg expression where a closing square-bracket was doubled-up ("]]" which should've been "]").

<?php
function IsPostcode($postcode) {
  $postcode = strtoupper(str_replace(chr(32),'',$postcode));
  if(ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
   return $postcode;
  else
   return FALSE;
}
?>
theppg_001 at hotmail dot com 19-Aug-2006 07:00
Ok well someone else posted this but if didn't work so I made my own.
I used this to check file names that are to be created on a server.
File names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), and dot(.) will be accepted.
File names beginning with anything but a-Z or 0-9 will be rejected.
File names  containing anything other than above mentioned will also be rejected.

Here it is.
<?php
$result = ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$" , $filename);
?>
tomas at phusis dot co dot uk 06-Jun-2006 08:41
I could not find a definitive and 100% working function that validates the UK postcodes, so was forced to write one myself.
The authoritative source of information is

http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm

which I amended with the new postcode for Tristan da Cunha.

Here is the ugly beast (don't wanna see regexp's ever again):

<?php
function IsPostcode($postcode) {
  $postcode = strtoupper(str_replace(chr(32),'',$postcode));
  if(ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y]][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
    return $postcode;
  else
    return FALSE;
}
?>
'morgan'.'galpin'.chr(64).'gmail'.'.com' 11-May-2006 01:16
Try this version instead of the one previously posted.

<?php
  /**
    Returns an array containing each of the sub-strings from text that
    are between openingMarker and closingMarker. The text from
    openingMarker and closingMarker are not included in the result.
    This function does not support nesting of markers.
  */
  function returnSubstrings($text, $openingMarker, $closingMarker) {
    $openingMarkerLength = strlen($openingMarker);
    $closingMarkerLength = strlen($closingMarker);

    $result = array();
    $position = 0;
    while (($position = strpos($text, $openingMarker, $position)) !== false) {
      $position += $openingMarkerLength;
      if (($closingMarkerPosition = strpos($text, $closingMarker, $position)) !== false) {
        $result[] = substr($text, $position, $closingMarkerPosition - $position);
        $position = $closingMarkerPosition + $closingMarkerLength;
      }
    }
    return $result;
  }

  // Example:
  $exampleText = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";
  $result = returnSubstrings($exampleText, "<b>", "</b>");
  var_export($result);

  // Prints:
  // array (
  //   0 => 'bonjour',
  //   1 => 'comment',
  // )
?>
info at orgied dot com 21-Mar-2006 06:54
Here's a function i've created to return an array of each substring searched in a string.

<?
function Return_Substrings($text, $sopener, $scloser)
                {
                $result = array();

                $noresult = substr_count($text, $sopener);
                $ncresult = substr_count($text, $scloser);

                if ($noresult < $ncresult)
                        $nresult = $noresult;
                else
                        $nresult = $ncresult;

                unset($noresult);
                unset($ncresult);

                for ($i=0;$i<$nresult;$i++)
                        {
                        $pos = strpos($text, $sopener) + strlen($sopener);

                        $text = substr($text, $pos, strlen($text));

                        $pos = strpos($text, $scloser);

                        $result[] = substr($text, 0, $pos);

                        $text = substr($text, $pos + strlen($scloser), strlen($text));
                        }

                return $result;
                }
?>

Example :

<?
    $string = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";

    $result = Return_Substrings($string, "<b>", "</b>");
?>
psonice (aat) gmail.com 14-Mar-2006 01:39
I wanted a more strict check for UK postcodes, and decided to do it by stripping all whitespace then using ereg:

<?php
$pcode=str_replace(" ","",$in_post_code);
if (!ereg('^[a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]{0,1}[0-9]{1}[a-zA-Z]{2}$', $pcode))
{
    return false;
}
?>

Probably could be improved, as I've just started, but it matches everything listed on the post office spec.
ar_cat at shaw dot ca 14-Dec-2005 03:13
I had problem using is_numeric() to verify if user inputs is a number (including optional floating sign and decimals).  Instead I found this expression from http://www.regular-expressions.info/floatingpoint.html and modified it for a bit.

^[+-]?[0-9]*\.?[0-9]+$

/*
3.55      true
-3.55     true
+3.55    true
2456.90  true
34skd    false
23.      false
2dt6      false
*/

Note: mine doesn't have the exponent part; for matching number with exponents, visit the site above :)
net_navard at yahoo dot com 15-Nov-2005 07:35
Hello

I think this is not clear:

"the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched. "

Beacause By "substring," it means the string contained within the parenthesis.

But in that statement it isn't so clearly

With regards

Amir Hossein Estakhrian
Jason Smart knarlin at yahoo dot com dot au 16-Oct-2005 01:13
A common mistake seems to be trying to escape characters within a bracket
expression. Unlike the preg functions, backslash is always taken literally
within a bracket expression using the ereg functions. See
http://php.planetmirror.com/manual/en/function.eregi.php#57824
for more details.

Some of the posts here can be re-written to be much simpler.

16-Feb-2005 10:02
attempts to allow square brackets in a string with
^[a-zA-Z0-9 [.[.] [.].] ]{1,}$
Although this appears to work a less confusing means is
^[]a-zA-Z0-9[]{1,}$
The ] has to be the first character (after a possible ^) but the [ can be
anywhere as long as it is not in the middle of a range of course.

09-Apr-2005 11:52
Says that ereg("hi[:space:]*bob", $string)
doesnt work in php 4 and to use preg_match() instead.

The above quoted use is incorrect it should be
<?php ereg("hi[[:space:]]*bob", $string); ?>

I tested this with the following in php 4.3.3 and it works fine
<?php
//The hex codes are space, tab, line feed, vertical tab, form feed, carriage return
 $whitespace = "\x20\x09\x0a\x0b\x0C\x0d";
 $teststring = "hi".$whitespace."bob";
 $result = ereg ("hi[[:space:]]*bob", $teststring, $arr);
echo ('Matches '.$result.' characters');
//Prints Matches 11 characters
?>

23-May-2005 08:22
Says that ereg("^[' A-Za-Z]+$", $cardName); will not work.

The fault with the above is the range a-Z the capital Z comes before small a
and so this will fail. The following works fine
<?php
$cardname = "John 'Doe'";
$result = ereg("^[' A-Za-z]+$", $cardname, $arr);
echo ('Matches '.$result.' characters');
//Prints Matches 10 characters
?>

09-Sep-2005 11:01
Tries to escape with \ in a bracket expression
You cannot with ereg functions (preg you can) so
ereg("^([-a-zA-Z0-9_\.\!@#\$&\*\+\=\|])*$" , $var)
should be
<?php ereg("^([-a-zA-Z0-9_.!@#$&*+=|])*$", $var); ?>
Joel Weierman 22-Jun-2005 12:56
While this is relatively simple example, I was unable find a clean method of doing this anywhere else, so I thought I would post it here.

As part of a file upload package, I wanted to prevent the uploading of double byte character filenames and other special ASCII characters that may not work well on a Windows and/or Linux system. Here is the statement I ended up using which seems to have done the trick.

ereg("[^a-zA-Z0-9._-]", $file_name)
php at REMOVEMEkennel17 dot co dot uk 26-Apr-2005 07:00
After a lot of hard work I managed to create the following regular expression, which matches any HTML tag pair (i.e. opening and closing tag), as specified by tagname:

^(.*)(<[ \n\r\t]*tagname(>|[^>]*>))(.*)(<[ \n\r\t]*/[ \n\r\t]*tagname(>|[^>]*>))(.*)$

The expression is deliberately very forgiving of bad HTML - I wanted to match anything that could be reasonably accepted by a forgiving browser, rather than make it standards compliant. Whitespace is allowed between the tagname and the opening and closing tag symbols, and also between the / and the tagname for the closing tag.

For my own use, I have wrapped it in a function call, which you may find useful.  Here it is with a few notes. I hope somebody finds it useful.

- Mark Clements

<?php

function ereg_MatchedHTMLTags($tagname) {
    return "^(.*)(<[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)(<[ \\n\\r\\t]*/[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)$";
}

// Use with eregi to ensure case-insensitive match.
//        e.g. to split an HTML page based on body tag:
//             eregi(ereg_MatchedHTMLTags('body'), $Source, $Matches)

// The following values will be held in $Matches
//(marked values are unintended byproducts of the expression)
//           *[0] - the entire string ($Source).
//            [1] - everything before the opening tag
//            [2] - the opening tag, including all contents (i.e. everything between < and >)
//           *[3] - the opening tag from end of the tag name,
//                      e.g. '<body bgcolor="#000000">' gives ' bgcolor="#000000">'
//            [4] - the tag contents (everything between the opening and closing tag)
//            [5] - the complete closing tag.
//           *[6] - the closing tag from the end of the tag name
//                      e.g. '</body invalid text>' gives ' invalid text>'
//            [7] - everything after the closing tag.

?>
ereg_replace
eregi_replace
Функции регулярных выражений POSIX


Осуществляет замену по регулярному выражению без учета регистра

ereg
eregi
Функции регулярных выражений POSIX
PHP Manual

eregi_replace

(PHP 4, PHP 5)

eregi_replace — Осуществляет замену по регулярному выражению без учета регистра

Описание

string eregi_replace ( string $pattern , string $replacement , string $string )

Эта функция идентична функции ereg_replace() за исключением того, что игнорирует регистр при сравнении алфавитных символов.

Внимание

С версии PHP 5.3.0 эта функция считается УСТАРЕВШЕЙ. Крайне не рекомендуется полагаться на эту возможность.

Список параметров

pattern

Расширенное регулярное выражение POSIX.

replacement

Если pattern содержит подстроки в скобках, replacement может содержать подстроки вида \digit, которые будут заменены текстом, совпавшим с digit-подстрокой в скобках; \0 воспроизведет все содержимое строки. Может использоваться до 9 подстрок. Круглые скобки могут быть вложенными, в этом случае они подсчитываются по открывающим скобкам.

string

Исходная строка.

Возвращаемые значения

Возвращается измененная строка. Если в строке string совпадений не найдено, она возвратится без изменений.

Примеры

Пример #1 Выделение результатов поиска

<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>

Примечания

Замечание:

С версии PHP 5.3.0, расширение regex помечено устаревшим и заменено расширением PCRE. Вызов этой функции приведет к ошибке уровня E_DEPRECATED. Смотрите список отличий для помощи при конвертировании в PCRE.

Смотрите также

  • ereg() - Совпадение с регулярным выражением
  • eregi() - Совпадение с регулярным выражением без учёта регистра
  • ereg_replace() - Осуществляет замену по регулярному выражению
  • preg_replace() - Выполняет поиск и замену по регулярному выражению

User Contributed Notes

dave at bevhost dot com 06-Jan-2012 12:22
The easiest function to replace this with is mb_eregi_replace(),
which is the mutibyte version that works on unicode characters such as chinese letters in your strings.
jgriggs777 at yahoo dot com 06-Jun-2008 07:26
My apologies.  I'm a PHP newbie and the count function didn't work right if you have more than one "keyword".  I searched and spent a long time to get this to work right, so wanted to share it.

This is very easy to use by doing the following.

$text - is the text to search
$words - are the words to highlight (search text)
$the_place - is so that you can tell your users what "area" was searched.

<?php

function highlight_this($text, $words, $the_place) {
    $words = trim($words);
    $the_count = 0;
    $wordsArray = explode(' ', $words);
        foreach($wordsArray as $word) {
         if(strlen(trim($word)) != 0)

         //exclude these words from being replaced
         $exclude_list = array("word1", "word2", "word3");
        // Check if it's excluded
        if ( in_array( strtolower($word), $exclude_list ) ) {

        } else {
            $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);
            $the_count = $count + $the_count;
            }

    }
    //added to show how many keywords were found
    echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $the_count . "</strong> matches within the " . $the_place. ".</div><br>";

    return $text;
}

//example of how to use
$text_to_highlight = highlight_this($text_to_highlight, $search_text, "Place you searched");

?>
jgriggs777 at yahoo dot com 05-Jun-2008 12:56
I modified the script from the note below this one so that you could show how many matches were found.  I know this should probably be posted in the str_ireplace() area, so I will post it there afterwards.

$text - is the text to search
$words - are the words to highlight (search text)
$the_place - is so that you can tell your users what "area" was searched.

<?php
function highlight_this($text, $words, $the_place) {
    $words = trim($words);
    $wordsArray = explode(' ', $words);
    foreach($wordsArray as $word) {
        if(strlen(trim($word)) != 0)
            $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);
    }
    //added to show how many keywords were found
    echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $count . "</strong> matches within the " . $the_place. ".</div><br>";

    //end script modification
    return $text;
}
?>
a dot dotreppe at gmail dot com 20-May-2008 03:49
Hi everyone.
I saw a lot of highlighting functions, but no one was simple... maybe I missed a part of discussion ?

Anyway, I think this function is the easiest:

<?php
function highlight($text, $words) {
    $words = trim($words);
    $wordsArray = explode(' ', $words);
    foreach($wordsArray as $word) {
        if(strlen(trim($word)) != 0)
            $text = eregi_replace($word, '<span class="highlight">\\0</span>', $text);
    }
    return $text;
}
?>
dan at dotgospel dot com 22-Feb-2008 07:30
/*******************************************************
Function highlights the text. You can replace the html tags with whatever you like. $x is the string, $var is the string to be highlighted. We explode the string to highlight more than one word.
*/

function highlight($x,$var) {
    $var = explode(" ",$var);

   for($j=0; $j< count($var); $j++){
        $xtemp = "";
        $i=0;
        while($i<strlen($x)){
            if((($i + strlen($var[$j])) <= strlen($x)) && (strcasecmp($var[$j], substr($x, $i, strlen($var[$j]))) == 0)) {
                    $xtemp .= "<b>" . substr($x, $i , strlen($var[$j])) . "</b>";
                    $i += strlen($var[$j]);
            }
            else {
                $xtemp .= $x{$i};
                $i++;
            }
        }
        $x = $xtemp;
    }
    return $x;
}
mp3spl at o2 dot pl 23-Dec-2007 04:40
Nice way to highlight that what someone search.

For example is some one search for "Wire Mobile 6"

It will highlight every word separated even if found "Wire Xp and some mobile stuff"

© and ® are importiant, because without special signs, string in second turn will convert also <span class="searchtext">
which will be already in text.

<?

$searchcolor = explode(' ',$search);
$ilosc = count($searchcolor);
$ilosc2 = "0";
while ($ilosc2 != $ilosc ) {
$name = eregi_replace ($searchcolor[$ilosc2],'©'.$searchcolor[$ilosc2].'®',$name);
$ilosc2++;
        }
$name = str_replace('©','<span class="searchtext">',$name);
$name = str_replace('®','</span>',$name);

echo $name;

?>
augusto at fagioli dot biz 21-Dec-2007 12:50
related to the private at sfiac dot net function,
please note that you  can add a dot in the

$c=ereg_replace".
   "("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);

having it to find email address like user.name@test.com

this is my example
$c=ereg_replace".
   "("[-a-z0-9.!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);
webmaster at hhgroups dot com 28-Nov-2007 01:24
Your remove links functions are incorrect if there are a php var in the URL, we have to add '?' character inside our pattern, I have three this function working correctly with php vars:

function transformUrl($str){
    $str=utf8_decode(urldecode($str));
    $str=eregi_replace("(^| |>)(www([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"http://\\2\">Look link</a>", $str);
    $str=eregi_replace("(^| |>)(http://www([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"\\2\">Look link</a>", $str);
    $str=eregi_replace("(^| |>)(http://([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"\\2\">Look link</a>", $str);
    return utf8_encode($str);
}
ash at atomic-network dot co dot uk 31-Aug-2007 02:46
@bluedragonx at gmail dot com
true but then use of the case insensitive version,
will correct this.

<?php

$_POST['email'] = str_ireplace("@", "[at]", $_POST['email']);

?>
php[at]drixe[dot]net 24-Jun-2007 12:49
Melissa,
This one is a better setup for your marvelous code.
It handles Melissa Magic and also Magic Melissa

function underline($subject, $word)
        {
        $mywords = explode(" ",$word);
        for ($j=0;$j<count($mywords);$j++)
            {
            $regex_chars = '\.+?(){}[]^$';
            for ($i=0; $i<strlen($regex_chars); $i++)
                {
                $char = substr($regex_chars, $i, 1);
                $mywords[$j] = str_replace($char, '\\'.$char, $mywords[$j]);
                }
            $mywords[$j] = '(.*)('.$mywords[$j].')(.*)';
            $subject =  eregi_replace($mywords[$j], '\1<span style="background:#ACA;padding:0;margin:0;">\2</span>\3', $subject);
            }
        return $subject;
        }
spiritualmind at gmail dot com 11-Jun-2007 08:19
eregi_replace seems not to deal with UTF8 chars !
I needed to utf8_decode / encode my string to parse it in eregi_replace :

<?php
  $input = "string_from_utf8_form" ;
  $output = utf8_encode(eregi_replace("(pattern)", "replacement", utf8_decode($input)) ;

 echo $output ;
?>

I think UTF8 is not totally supported by PHP.
Vladimir Luchaninov 22-Oct-2006 07:38
If you have plain text e-mails and links but need to make them real links

<?
function replaceLinks($text) {
    // convert support@pogoda.in into
    // <a href="mailto:support@pogoda.in">
    // support@pogoda.in</a>
    $text = ereg_replace('[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*',
        '<a href="mailto:\\0">\\0</a>',$text);

    // convert http://www.pogoda.in/new_york/eng/ into
    // <a href="http://pogoda.in/new_york/eng/">
    // pogoda.in/new_york/eng/</a>
    $text = ereg_replace('[a-zA-Z]+://(([.]?[a-zA-Z0-9_/-])*)',
        '<a href="\\0">\\1</a>',$text);

    // convert www.pogoda.in/new_york/eng/ into
    // <a href="http://www.pogoda.in/new_york/eng/">
    // www.pogoda.in/new_york/eng/</a>
    $text = ereg_replace('(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)',
        ' <a href="http://\\2">\\2</a>',$text);

    return $text;
}
?>
private at sfiac dot net 08-Sep-2006 08:44
# I was looking to remove all email address and links from post
# for a non-commercial posting website (like forum or classifieds)

# The function

<?PHP
function verify_email_and_link_in_post($c){
 # modify email addess and link with this:
 $l="LINKS ARE PROHIBITED ON THIS WEBSITE";
 $e="EMAIL ADDRESS ARE PROHIBITER ON THIS WEBSITE";
 # check for email address
 $c=ereg_replace".
   "("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);
 # replace all sign @ with the letters at
 $c=ereg_replace".
   "("@", " at ",$c);
 # check for link HTML input
 $c=eregi_replace".
   "('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>].*>([^<]*)</a>)',".
   "$l,$c);
 # check for anythink like http:// or ftp://
 $c=ereg_replace".
   "("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*",".
   "$l,$c);
 # check for anyhting starting with www.
 $c=ereg_replace".
   "("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)",".
   "$l,$c);
 # finaly check for anything like a-z.a-z
 $c=ereg_replace".
   "("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+[.]+[-a-z0-9]",".
   "$l,$c);
 return $c;
}
?>
# hope this help someone ;-)
carlos at braziland dot com 15-May-2006 05:11
@bluedragonx at gmail dot com: Now you're calling two functions instead of one. I'm trully curious if that would still be faster.

My original post was just to highlight the need to escape characters that could be used to abuse a contact form. Something everyone should do, especially if doing it for a customer.

But bluedragonx, thanks for your input.
melissa at melissagirl dot com 14-Apr-2006 09:28
Here's a nice case-insensitive highlight function that ignores any regular expression characters and highlights a word and leaves it in whatever case it was before:

<?
function highlight($word, $subject) {
    $regex_chars = '\.+?(){}[]^$';
    for ($i=0; $i<strlen($regex_chars); $i++) {
        $char = substr($regex_chars, $i, 1);
        $word = str_replace($char, '\\'.$char, $word);
    }
    $word = '(.*)('.$word.')(.*)';
    return eregi_replace($word, '\1<span class="highlight">\2</span>\3', $subject);
}
?>
02-Nov-2005 03:06
@bluedragonx: You're right. And i got the order of the params wrong as well, must've been sleepy when i wrote that note. For what it's worth:

<? $_POST['email'] = str_replace("[at]", "@", strtolower($_POST['email'])); ?>

Not similar to Carlos' code though, since it'll convert all characters to lowercase.
bluedragonx at gmail dot com 16-Oct-2005 04:42
Actually that wouldn't work because str_replace is case sensitive.  So any instances of [AT] [aT] or [At] would be ignored.
php dot net at nr78 dot net 08-Aug-2005 05:36
@carlos at braziland dot com: Hate to be a wisecrack, but i believe the following code might be slightly faster with the same result:

<?php

$_POST['email'] = str_replace("@", "[at]", $_POST['email']);

?>
carlos at braziland dot com 31-Jul-2005 12:54
So here is my answer to those who are trying to submit headers through my simple contact form:

$any_form_field = eregi_replace("@","[at]",$_POST['just_one_field']); //how can anyone send emails to other email addresses without the @ symbol :)

My suggestion is to do a foreach loop in the $_POST array and remove the @ symbol from all fields (unless you want one of the fields to have the @ symbol, in which case it should be very careful and question if the symbol is necessary).

Not the best solution, but it's simple and it works.
joltmans at amersel dot com 01-Mar-2005 11:06
PHP's Regex engine differs from several others in its treatment of parsing spaces.

In many Regex languages '\s' denotes a space.
PHP does not recognize '\s', just type a space ' ' instead.

This simple example illustrates the problem:
<?php
    $string = "A sentence with   spaces";
    if (eregi("with\s*spaces", $string))
    {
        // Will never print
        echo "PHP understood \s";
    }
    else
    {
        // Will always print
        echo "PHP doesn't understand \s";
    }
?>

This example does work:
<?php
    $string = "A sentence with   spaces";
    if (eregi("with *spaces", $string))
    {
        // Will print
        echo "PHP understood ' '";
    }
?>
27-Jan-2005 08:15
never mind my last post for the eregi_replace not replacing.

I just used str_replace instead and it works fine.  I must have had something wrong with my search string.  POSIX, Perl.. hmm.. yeah probably something there.

Mettedraq / Gene
Ausvald 19-Jun-2004 04:21
Zach Johnson missed up. ereg* funcs use posix regex, not the rfc one
furiousgreencloud at yahoo dot com 17-Jun-2004 08:47
To simply convert wild input into a sensable sting, say for a filename I use:

function cleanString($wild) {
    return ereg_replace("[^[:alnum:]+]","",$wild);
}

echo cleanString("@#$&*$@#H~e'{}l{}l<o\{}"); // outputs: Hello
e dot boeters at planet dot nl 03-Jun-2004 04:46
This is a 'faster' way to highlight search results:

$content = str_replace($query, "<span class=\"highlight\">" . $query . "</span>", $content);
julien at ratatouille dot com dot fr 24-Nov-2003 06:28
This function replace < and > symbols between <code> and </code> tags by html code for lower than (&lt;) and greather than (&gt;) elements.

function retourne_format_code($texte)
{
    $tablo=split("<code>",$texte);
    $texte="";
    $texte.=$tablo[0];
    foreach($tablo as $cle=>$valeur)
    {
        if(eregi("</code>",$valeur))
        {
            $tablo1=split("</code>",$valeur);
            $tablo1[0]=eregi_replace("<","&lt;",$tablo1[0]);
            $tablo1[0]=eregi_replace(">","&gt;",$tablo1[0]);
            foreach($tablo1 as $cle1=>$valeur1)
            {
                if($cle1==0)
                    $valeur1="<code>".$valeur1."</code>";
                $texte.=$valeur1;
            }
        }
    }
    return $texte;
}
martin_goldmann at gmx dot net 18-Nov-2003 12:43
After reading the last message I wrote that de-spamizer:

function despamMailURI($myStrMail='')
{
    ?>javascript:void(location.href='mailto:'+<?=eregi_replace( "^([_\.0-9a-z-]+)@([0-9a-z][0-9a-z-]+)\.([a-z]{2,6})$", "'\\1'+'@'+'\\2'+'.'+'\\3'",$myStrMail)?>)<?
}

Usage example:
<a href="<?=despamMailURI("user@foo.bar")?>">Mail me</a>
iparanoid at gmx dot de 23-Aug-2003 09:03
To obtain the an email addresse in the scheme user at host dot use following function

function antispam_mail($mail) {
    return eregi_replace( "^([_\.0-9a-z-]+)@([0-9a-z][0-9a-z-]+)\.([a-z]{2,6})$", '\\1 at \\2 dot \\3',$mail );
};

Combined with a wee JavaScript (document.location='mailto:'+user+'@'+host+'.'+tld) this provides a very powerfull anti-spam mechanism while providing full mailto: link functionality.
chpins-php at romu92 dot freesurf dot fr 02-Jun-2003 04:15
/*new function for href2text : */

function AHREF2text($string) {
 return eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>].*>([^<]*)</a>)','[\\3] (link: \\2)', $string);
}

// by Ch'Pins
buddy at directpay dot cz 14-May-2003 10:22
i had to solve problem conserning DB2 timestamp format. here is how to parse ANSI timestamp format to DB2 timestamp format:

$mydate = Date("Y-m-d H:i:s");

$var = eregi_replace
("([0-9]{4}-[0-9]{2}-[0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})"
,"\\1-\\2.\\3.\\4",$mydate);

echo "ANSI: $mydate, DB2 format: $var";

happy codding
buddy
eder at xce dot de 03-May-2003 07:23
/*As php at silisoftware dot com's example works only if there is not more than one link in $string, I rewrote his expression to function with strings containing multiple links: */

function AHREF2text($string) {
  return eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','[\\3] (link: \\2)', $string);
}
Rainmaker526 at hotmail.com 09-Mar-2003 07:02
I have found that some characters cannot be used by eregi_replace (or ereg_replace). When you get the REG_BADRPT error, try backslashing any special chars in your pattern string

ex.
$str = eregi_replace("*", "", $somevar)

gives the REG_BADRPT error. Change it to
$str = eregi_replace("\*", "", $somevar)

to make it work
php at silisoftware dot com 18-Feb-2003 11:08
Transform HTML links into plain-text "links" with the URL visible

function AHREF2text($string) {
    return eregi_replace('<A .*HREF=("|\')?([^ "\']*)("|\')?.*>([^<]*)</A>', '[\\4] (link: \\2)', $string);
}

$HTMLstring = 'A link to <a href="http://www.php.net">PHP.net</A>';
echo AHREF2text($HTMLstring);
// prints:  A link to [PHP.net] (link: http://www.php.net)
simon_a99 at yahoo dot co dot uk 27-Aug-2002 12:07
To find a string regardless of case, you might want to use the matched string in the replacement string without changing its case.

For example, you're searching for $search = "letter" and the text being searched is $text = "post lEtTeR".  I want to change the format of the matched string.

Do this:
eregi_replace($search, "<b>\\0</b>", $text);

$text has now been changed to "post <b>lEtTeR</b>".  \\0 is the entire text matched (lEtTer in this case).
ereg
eregi
Функции регулярных выражений POSIX


РЎРѕРІРїР°РґРµРЅРёРµ СЃ СЂРµРіСѓР»СЏСЂРЅС‹Рј РІС‹СЂР°Р¶РµРЅРёРµРј Р±РµР· СѓС‡С‘С‚Р° СЂРµРіРёСЃС‚СЂР°

eregi_replace
split
Р¤СѓРЅРєС†РёРё СЂРµРіСѓР»СЏСЂРЅС‹С… РІС‹СЂР°Р¶РµРЅРёР№ POSIX
PHP Manual

eregi

(PHP 4, PHP 5)

eregi — РЎРѕРІРїР°РґРµРЅРёРµ СЃ СЂРµРіСѓР»СЏСЂРЅС‹Рј РІС‹СЂР°Р¶РµРЅРёРµРј Р±РµР· СѓС‡С‘С‚Р° СЂРµРіРёСЃС‚СЂР°

РћРїРёСЃР°РЅРёРµ

int eregi ( string $pattern , string $string [, array &$regs ] )

РС‚Р° С„СѓРЅРєС†РёСЏ РёРґРµРЅС‚РёС‡РЅР° С„СѓРЅРєС†РёРё ereg() Р·Р° РёСЃРєР»СЋС‡РµРЅРёРµРј С‚РѕРіРѕ, С‡С‚Рѕ РёРіРЅРѕСЂРёСЂСѓРµС‚ СЂРµРіРёСЃС‚СЂ РїСЂРё СЃСЂР°РІРЅРµРЅРёРё Р°Р»С„Р°РІРёС‚РЅС‹С… СЃРёРјРІРѕР»РѕРІ.

Р’РЅРёРјР°РЅРёРµ

РЎ РІРµСЂСЃРёРё PHP 5.3.0 СЌС‚Р° С„СѓРЅРєС†РёСЏ СЃС‡РёС‚Р°РµС‚СЃСЏ РЈРЎРўРђР Р•Р’РЁР•Р™. РљСЂР°Р№РЅРµ РЅРµ СЂРµРєРѕРјРµРЅРґСѓРµС‚СЃСЏ РїРѕР»Р°РіР°С‚СЊСЃСЏ РЅР° СЌС‚Сѓ РІРѕР·РјРѕР¶РЅРѕСЃС‚СЊ.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

pattern

Р РµРіРёСЃС‚СЂРѕРЅРµР·Р°РІРёСЃРёРјРѕРµ СЂРµРіСѓР»СЏСЂРЅРѕРµ РІС‹СЂР°Р¶РµРЅРёРµ.

string

Р’С…РѕРґРЅР°СЏ СЃС‚СЂРѕРєР°.

regs

Р•СЃР»Рё СЃРѕРІРїР°РґРµРЅРёСЏ РЅР°Р№РґРµРЅС‹ РґР»СЏ РїРѕРґСЃС‚СЂРѕРє РІ СЃРєРѕР±РєР°С… РёР· pattern, Рё С„СѓРЅРєС†РёСЏ РІС‹Р·С‹РІР°РµС‚СЃСЏ СЃ С‚СЂРµС‚СЊРёРј Р°СЂРіСѓРјРµРЅС‚РѕРј regs, СЃРѕРІРїР°РґРµРЅРёСЏ Р±СѓРґСѓС‚ СЃРѕС…СЂР°РЅРµРЅС‹ РІ СЌР»РµРјРµРЅС‚Р°С… РјР°СЃСЃРёРІР° regs.

$regs[1] Р±СѓРґРµС‚ СЃРѕРґРµСЂР¶Р°С‚СЊ РїРѕРґСЃС‚СЂРѕРєСѓ, РєРѕС‚РѕСЂР°СЏ РЅР°С‡РёРЅР°РµС‚СЃСЏ СЃ РїРµСЂРІРѕР№ Р»РµРІРѕР№ РєСЂСѓРіР»РѕР№ СЃРєРѕР±РєРё; $regs[2] Р±СѓРґРµС‚ СЃРѕРґРµСЂР¶Р°С‚СЊ РїРѕРґСЃС‚СЂРѕРєСѓ, РЅР°С‡РёРЅР°СЋС‰СѓСЋСЃСЏ СЃРѕ РІС‚РѕСЂРѕР№, Рё С‚.Рґ. $regs[0] Р±СѓРґРµС‚ СЃРѕРґРµСЂР¶Р°С‚СЊ РїРѕР»РЅСѓСЋ РєРѕРїРёСЋ СЃРѕРІРїР°РІС€РµР№ СЃС‚СЂРѕРєРё.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ РґР»РёРЅСѓ СЃРѕРІРїР°РІС€РµР№ СЃС‚СЂРѕРєРё, РµСЃР»Рё СЃРѕРІРїР°РґРµРЅРёСЏ СЃ pattern РЅР°Р№РґРµРЅС‹ РІ string, РёР»Рё FALSE, РµСЃР»Рё СЃРѕРІРїР°РґРµРЅРёР№ РЅРµ РЅР°Р№РґРµРЅРѕ РёР»Рё РІРѕР·РЅРёРєР»Р° РѕС€РёР±РєР°.

Р•СЃР»Рё РґРѕРїРѕР»РЅРёС‚РµР»СЊРЅС‹Р№ РїР°СЂР°РјРµС‚СЂ regs РЅРµ РїРµСЂРµРґР°РЅ, РёР»Рё РґР»РёРЅР° СЃРѕРІРїР°РІС€РµР№ СЃС‚СЂРѕРєРё СЂР°РІРЅР° 0, С„СѓРЅРєС†РёСЏ РІРѕР·РІСЂР°С‰Р°РµС‚ 1.

РџСЂРёРјРµСЂС‹

РџСЂРёРјРµСЂ #1 РџСЂРёРјРµСЂ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёСЏ eregi()

<?php
$string = 'XYZ';
if (eregi('z', $string)) {
    echo "'$string' СЃРѕРґРµСЂР¶РёС‚ 'z' РёР»Рё 'Z'!";
}
?>

РџСЂРёРјРµС‡Р°РЅРёСЏ

Р—Р°РјРµС‡Р°РЅРёРµ:

РЎ РІРµСЂСЃРёРё PHP 5.3.0, СЂР°СЃС€РёСЂРµРЅРёРµ regex РїРѕРјРµС‡РµРЅРѕ СѓСЃС‚Р°СЂРµРІС€РёРј Рё Р·Р°РјРµРЅРµРЅРѕ СЂР°СЃС€РёСЂРµРЅРёРµРј PCRE. Р’С‹Р·РѕРІ СЌС‚РѕР№ С„СѓРЅРєС†РёРё РїСЂРёРІРµРґРµС‚ Рє РѕС€РёР±РєРµ СѓСЂРѕРІРЅСЏ E_DEPRECATED. РЎРјРѕС‚СЂРёС‚Рµ СЃРїРёСЃРѕРє РѕС‚Р»РёС‡РёР№ РґР»СЏ РїРѕРјРѕС‰Рё РїСЂРё РєРѕРЅРІРµСЂС‚РёСЂРѕРІР°РЅРёРё РІ PCRE.

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • ereg() - РЎРѕРІРїР°РґРµРЅРёРµ СЃ СЂРµРіСѓР»СЏСЂРЅС‹Рј РІС‹СЂР°Р¶РµРЅРёРµРј
  • ereg_replace() - РћСЃСѓС‰РµСЃС‚РІР»СЏРµС‚ Р·Р°РјРµРЅСѓ РїРѕ СЂРµРіСѓР»СЏСЂРЅРѕРјСѓ РІС‹СЂР°Р¶РµРЅРёСЋ
  • eregi_replace() - РћСЃСѓС‰РµСЃС‚РІР»СЏРµС‚ Р·Р°РјРµРЅСѓ РїРѕ СЂРµРіСѓР»СЏСЂРЅРѕРјСѓ РІС‹СЂР°Р¶РµРЅРёСЋ Р±РµР· СѓС‡РµС‚Р° СЂРµРіРёСЃС‚СЂР°
  • preg_match() - Р’С‹РїРѕР»РЅСЏРµС‚ РїСЂРѕРІРµСЂРєСѓ РЅР° СЃРѕРѕС‚РІРµС‚СЃС‚РІРёРµ СЂРµРіСѓР»СЏСЂРЅРѕРјСѓ РІС‹СЂР°Р¶РµРЅРёСЋ
  • stripos() - Р’РѕР·РІСЂР°С‰Р°РµС‚ РїРѕР·РёС†РёСЋ РїРµСЂРІРѕРіРѕ РІС…РѕР¶РґРµРЅРёСЏ РїРѕРґСЃС‚СЂРѕРєРё Р±РµР· СѓС‡РµС‚Р° СЂРµРіРёСЃС‚СЂР°
  • stristr() - Р РµРіРёСЃС‚СЂРѕ-РЅРµР·Р°РІРёСЃРёРјС‹Р№ РІР°СЂРёР°РЅС‚ С„СѓРЅРєС†РёРё strstr

User Contributed Notes

Pallieter 11-Feb-2011 12:09
Too many email regexps get it wrong and limit the ability of people to use many valid email addresses. Plus there is active/serious discussion on many websites about what actually is a valid email address. So filter_var($email, FILTER_VALIDATE_EMAIL) should be used (although not perfect yet) or a very complete function like http://code.google.com/p/isemail/ for the simple reason that they are maintained to conform to the latest state of affairs.
info at o08 dot com 14-Apr-2010 09:12
because eregi is not recommended after php 5, you can replaced it with stristr if just for simple search.

For editors with regular express function:
eregi\(([^,]*),([^)]*)\)
stristr(\2,\1)
julia_kean25 at yahoo dot com 10-Feb-2009 02:15
I use this in my app_config.php file to sanitize each request:

<?php
// app_config.php

    /**
    *    SANITIZE REQUEST
    */

    function sanitize_request($methods, $array)
    {
        // methods: trim ; addslashes ; stripslashes ; etc...
        // array : $_GET ; $_POST ; etc...

        foreach ($methods as $function) {
            $array = array_map($function, $array);
        }
        return $array;
    }

    if ( ! get_magic_quotes_gpc() )
    {
        $methods = array('trim', 'addslashes');
        $_GET = sanitize_request($methods, $_GET);
        $_POST = sanitize_request($methods, $_POST);
        $_COOKIE = sanitize_request($methods, $_COOKIE);
        $_REQUEST = sanitize_request($methods, $_REQUEST);
    }
?>

it currently only trims and adds slashes to the request but it would be nice to have the possibility to add the striptags function too.
jrgpmaster at gmail dot com 13-Sep-2008 01:04
Here is a simple way of checking if the visitor if your page is a search engine or a normal person. It does this by checking if the user agent returned by $_SERVER['HTTP_USER_AGENT'] contains one of the keywords search engine's user agents usually contain.

<?php

    //check if user is a bot of some sort
function is_bot()
{
    $bots = array('google','yahoo','msn');
    //takes the list above and returns (google)|(yahoo)|(msn)
    $regex = '('.implode($bots, ')|(').')';
    /*uses the generated regex above to see if those keywords are contained in the user agent variable*/
    return eregi($regex, $_SERVER['HTTP_USER_AGENT']);
}

?>
sumit270 at gmail dot com 12-Jun-2008 09:45
Prevent XXS attack

<?php
// Prevent any possible XSS attacks via $_GET.
foreach ($_GET as $check_url) {
    if ((eregi("<[^>]*script*\"?[^>]*>", $check_url)) || (eregi("<[^>]*object*\"?[^>]*>", $check_url)) ||
        (eregi("<[^>]*iframe*\"?[^>]*>", $check_url)) || (eregi("<[^>]*applet*\"?[^>]*>", $check_url)) ||
        (eregi("<[^>]*meta*\"?[^>]*>", $check_url)) || (eregi("<[^>]*style*\"?[^>]*>", $check_url)) ||
        (eregi("<[^>]*form*\"?[^>]*>", $check_url)) || (eregi("\([^>]*\"?[^)]*\)", $check_url)) ||
        (eregi("\"", $check_url))) {
    die ();
    }
}
unset($check_url);
?>
Jeff Morris 30-May-2008 11:06
Email Address RegEx -- The Final Frontier?

Inspired by bobocop's stalwart effort. Cheers for that matey!

Contrary to most folks' expectation, a quoted @ character is permitted in the
local part of an email address. So strictly speaking bobocop's test result for
'@exam@exam.com' is ...inconclusive?

The RFC prohibits control characters in the address. So it's no coincidence
that most header-related exploits try to inject control characters into the
fields sent to the server. If we're validating client-side, we need to ensure
user input is restricted to the printable code set. And in the spirit of not
trusting anything inbound, we need to filter again server-side. It's handy
to have the same regex working at both ends.

My variant of bobocop's regex is listed below. Note the mask for the local
part matches any printable character *excluding the dot*. The dot is reserved
as a label separator. Bobocop's regex enforces that role while ensuring the
local part does not start or end with a dot.

Outside of the 7-bit ASCII and dot rules, the RFC says 'anything goes' in the
local part. Them's the breaks folks.

All we need to realise is that our endeavours are limited, and the nearest
we'll get to validating an email address is finding an MX record in DNS.
Whatever, don't go probing mail servers with test emails, you might get more
than you bargained for. That's sp@mmer territory, that is.
If you want to positively vet a mail server, consider running a check against
sbl-xbl.spamhaus.org. Search for the checkdnsrr function page on this site and
read the comments for good info.

Anyhoo, here's the modded regex builder:

//the variables
$local            = '[\x20-\x2D\x2F-\x7E]';
$alnum            = 'a-z0-9';
$domain            = "([$alnum]([-$alnum]*[$alnum]+)?)";

//the array
$arr            = array();
$arr['start']    = '^';
$arr['local']    = "$local+(\.$local+)*";
$arr['at']        = '@';
$arr['domain']    = "($domain{1,63}\.)+";
$arr['tld']        = "[$alnum]{2,6}";
$arr['end']        = '$';

//the regex
$regex            = implode('',$arr);

/**

$regex evaluates to:

^[\x20-\x2D\x2F-\x7E]+(\.[\x20-\x2D\x2F-\x7E]+)*@
(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$

(regex split into 2 lines due to line length limits)

Add virgules front and back for the javascript equivalent.

I'm running this in an AJAX app right now and it does what it says on the tin.

If you're uncomfortable with the character length limits on domain and tld
names, change them to taste.

**/
ted devito 02-May-2008 04:29
RE: validate a url
--------------------
based on "ian at hyperborea dot co dot uk" below...
original date: 10-Nov-2004 03:15

I added a test for http(s?) and ftp as well as a trailing slash on urls that don't specify a page.

now it allows...
http://test.com/
https://www.test.com

$domain = "(http(s?):\/\/|ftp:\/\/)*([[:alpha:]][-[:alnum:]]*[[:alnum:]])
    (\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])+";
$dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]])*";
$trailingslash  = "(\/?)";
$page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?";
$getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+)
    (&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+))*)?";
$pattern = "^".$domain.$dir.$trailingslash.$page.$getstring."$";
mbfreight atthe gmail place 03-Jan-2008 02:53
keran at kiwi-interactive dot com wrote (5ish years ago) 07-Mar-2003 08:21

$feedback = "Error: $email isn't a valid mail address!";
return $feedback;
-- and --
$feedback = "Error: $domain isn't a valid domain!";
return $feedback;

I've been crushed with patching up XSS and anytime you get user input, it's best to just not show it back to them if possible. The auditor loves throwing these at me: >"><script>alert(123)</script><"  in the url, in forms, everywhere. Some looking around and you can find and build an amazing testing string.

I have found that using htmlentities($user_input) isn't enough, either. There are a few tricks that can help like
        // from http://us3.php.net/manual/en/function.strip-tags.php
    while($input != strip_tags($input)) {
            $input = strip_tags($input);
        }

In my case, I'm starting off by testing for <[tag]> as well as keyword() and then do some preg_replace ing.
shwetank dot sharma86 at gmail dot com 07-Dec-2007 05:13
we define some notficatio for making the Expression for eregi(exp, string)

so first of all syntax
   [ ]  this brakit  used to define chracters
   eg  [a-z], [0-9]
  { } this brakit used ti define range
  eg  {1,3}
if you wanna to make a expresion which take which take maximum
three digit no
        "^[0-9]{1,3}$"

and if make exp for only three digit no than

       "^[0-9]{3}$"

ok if any problem mail me
c00lways at gmail dot com 10-Mar-2007 06:10
hodsfords:

i love your expression,
and i've came out with a solutions which does not need to set the number of times {1,3} for the domain.
it can accept unlimited number of times, but @ least 1 time .com / .xxx

$exp = "^[a-z0-9]+[a-z0-9\?\.\+-_]*" .
@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]+$";
m at tthew dot org dot uk 07-Nov-2006 02:47
This example checks for a valid IP address or CIDR notation address range. (Thanks Walo for just the start I needed.)

The reg exp is too long to post in the code. It is:
^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(/[0-9]{1,2}){0,1}$
(substitute for EXPR)

<?php

function checkValidIp($cidr) {

    // Checks for a valid IP address or optionally a cidr notation range
    // e.g. 1.2.3.4 or 1.2.3.0/24

   if(!eregi("EXPR", $cidr)) {
       $return = FALSE;
   } else {
       $return = TRUE;
   }

    if ( $return == TRUE ) {

        $parts = explode("/", $cidr);
        $ip = $parts[0];
        $netmask = $parts[1];
        $octets = explode(".", $ip);

        foreach ( $octets AS $octet ) {
            if ( $octet > 255 ) {
                $return = FALSE;
            }
        }

        if ( ( $netmask != "" ) && ( $netmask > 32 ) ) {
            $return = FALSE;
        }

    }

    return $return;

}

?>
benjohnson{-at-}maine{-dot-}rr{-dot-}com 11-Sep-2006 02:33
It's probably worth noting that eregi() (and most likely, the related variations) appears to have a 255-character limit with respect to the length of the input it will attempt to parse.

If you try to do something like

if (!eregi("^[a-zA-Z0-9]{0,256}$", $text)) { ...

eregi() will return FALSE, irrespective of whether or not the input matches the pattern.
markus dot sipila at no dot spam dot iki dot fi dot invalid 02-Aug-2006 02:29
One more comment about email validation and usability of validators.

The fact that RFC 2822 allows broader set of characters in email addresses than typically used makes things quite challenging usability wise.

A very common usability problem with email validators is that they do not accept all valid addresses (such as foo{bar}.baz!@example.com. Almost as  common problem is that the validator only checks that the syntax is valid and passes addresses like foo#@example.com without any warning. Even though foo#@example.com is syntactically valid it might just as well be a typo of foo@example.com.

I resolved this usability challenge by doing the validation in two phases. In the first phase the address is validated so that it can't include exotic characters like { or |. Most addresses pass this validation.

If they don't, they are validated with the other validator that allows all RFC-compliant addresses. In this case the validator shows a message that the address is syntactically valid but it recommends to double check it for typos.

An example without regexps:
<?php
if (eregi($normal, $email)) {
  echo("The address $email is valid and looks normal.");
}

else if (eregi($validButRare, $email)) {
  echo("The address $email looks a bit strange but it is syntactically valid. You might want to check it for typos.");
}

else {
  echo("The address $email is not valid.");
}
?>

The full article with the regexps and demo can be found at http://www.iki.fi/markus.sipila/pub/emailvalidator.php
tim at rocketry dot org 29-Apr-2006 09:32
The easiest way I've found to validate a properly formed email address is this:

if(!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $_POST['EmailAddress'])) {
     echo "<p>Not a valid email address</p>\n";
}

It basically just wants to see some alphanumeric characters + an @ sign + a . + 2 to 4 alpha characters. So far it has done what I need for quite a while now.. Hope that helps someone. :)

Tim
info at stenschke dot com 03-Feb-2006 04:39
i needed a function to find hyperlinks containing a url as text of the hyperlink, exceeding a given maximum length.
here my function to finds too long hyperlinks and insert <br />s where needed into the linktext:

    function breakTooLongLinks($text,$maxLen) {
        //find hyperlinks that contain too many chars & insert <br>s where neccessary
        $pattern= '[>]www[.].*/*(.doc|.pdf|.htm|.html|.shtml|.php|.asp)(</a>|</A>)';
        $match= eregi($pattern, $text, $regs);
        if ($match) {
            foreach ($regs as $link) {
                if (strlen($link)>$maxLen) {
                    $linkParts= explode('/',$link);
                    $linkRepl= array(); $replI=0; $curLinkPart='';
                    foreach($linkParts as $linkPart) {
                        $curLinkPart.= $linkPart.'/';
                        if (strlen($curLinkPart)>$maxLen) {
                            $linkRepl[]= $curLinkPart;
                            $curLinkPart='';
                        }
                    }
                    $linkRepl= implode('<br />',$linkRepl);
                    $text= str_replace($link, $linkRepl, $text);
                }
            }
        }
        return $text;
    }
opedroso at swoptimizer dot com 07-Jan-2006 05:13
I you are trying to match accented characters (e.g. you want to match "Cafй Olй"), you can use the following regex:

"[a-zа-ь ]+"

This takes advantage of the fact that in the iso-8859-1 "Latin 1", the "а" is the first accented char and the "ь", the last one.

By the way, the regex above will match this string as a single match:

"aeiou аимтщ бйнуъ вкофы гх с длпць з"

Beware that your local code page may include a few more char codes in the range "[а-ь]", so it may match more than you expect.
Jason Smart knarlin at yahoo dot com dot au 14-Oct-2005 10:28
There seems to be a lot of confusion about escaping special characters within a bracket expression enclosed in []

The reference is the regex man page at http://www.tin.org/bin/man.cgi?section=7&topic=regex , Linked from the "Regular Expression Functions (POSIX Extended)" page in the PHP manual at http://php.planetmirror.com/manual/en/ref.regex.php

The simple rule is there should be no backslash `\' in a bracket expression unless you are matching it literally.
ALL special characters (the few exceptions are listed below), lose their special significance in a bracket expression.
This includes .[$()|*+?{\ all of which have special meaning outside of a bracket expression, inside they will match LITERALLY!

The backslash character can never escape anything in a bracket expression including itself! It is always interpreted literally.

Here are the exceptions

^ at the start of the bracket expression will match on all but the set of characters within the bracket expression

- (hyphen) Indicates range, so [a-z] will match a single character in the range a-z (case insensitive for eregi).
  To match a literal `-' it must be at the start or end of the bracket expression or the end of a range, or enclosed in [. .] to be the start of a range.
  Examples:
  [0-9-]
  [-0-9]
  Both the above will match a single character from the set comprising the digits and hyphen `-'

  [!--] is the same as [!"#$%&'()*+,-]
  i.e. it matches a single character from the range of characters from `!' to hyphen `-'

  [[.-.]-9] is the same as [-./0123456789] or [./0123456789-]
  and will match a single digit from the range of characters from hyphen `-' to digit 9

] The closing bracket indicates the end of a bracket expression but not if it immediately follows the opening bracket `[' or `[^' in that case the closing bracket is matched literally.
  Examples:
  [][0-9] is the same as []0-9[]
  and matches a single character from the set of digits and a literal closing bracket `]' and opening bracket `]'

  [^][0-9] is the same as [^]0-9[]
  and matches a single character from the group of all characters except the set of digits and literal `]' or `['

Look at the regex man page for more on the above and the following special cases

[.characters.]
  A collating element
[=characters=]
  An equivalence class
[:alnum:]
  A character class

That's it for special cases! ALL other characters match literally within a bracket expression and can never be escaped with `\'

Here is a list of some of the postings here that have mistakenly tried to use special characters within a bracket expression.
28-Jan-2002 12:56, 09-Feb-2002 06:28, 24-Sep-2002 01:21, 08-Mar-2003 02:21, 11-Apr-2003 03:22 (uses `|' as if it was `or' it is not, it is a literal `|'), 27-Jun-2003 04:03, 06-Sep-2003 07:17, 20-Apr-2004 04:55, 24-Nov-2004 09:12, 25-Nov-2004 02:11, 06-Jan-2005 08:54, 24-Feb-2005 06:05

It seems people are copying each others mistakes so this needs to be cleared up. Most of the mistakes attempt to escape special characters within a bracket expression with backslash. That never works! A simple fix is to simply remove any backslashes within the bracket expression that are not meant to be matched literally.

The attempt to use | as 'or' within a bracketed expression should be put in parentheses instead.

I used a simple script attached to a form to test these results. Here's the script.
<?php
  if(isset($_POST['pattern']) && isset($_POST['teststring'])) {
    $pattern = stripslashes($_POST['pattern']);
    $teststring = stripslashes($_POST['teststring']);
    $match = ereg($pattern, $teststring, $regs);
    if(!$match) $match = 0;
    echo('<p>The regular expression is: '.$pattern.'</p>');
    echo('<p>The string for testing is: '.$teststring.'</p>');
    echo('<p>The number of matching characters is: '.$match.'</p>');
  }
?>
Just use a form with input fields named "pattern" and "teststring"

Hope this helps and clears up some misconceptions
Jason Smart
Monash University Student
manuel at cvam dot com dot ar 27-Jul-2005 03:47
Please note that event though email pattern submitted by bobocop at bobocop dot cz below is RFC compliant, actual domain names are not!

They do start with numbers (as in 1800flowers.com, etc), so the second line, domain, should be:
<?php
$domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
?>
(everything else just like bobocop's comment from 02-May-2005 11:09)
somebody at somewhere dot com 09-May-2005 09:35
Say you want to validate a random sized string (at least one character though), and make sure it DOESN't contains anything BUT these characters: [:space:]a-zA-Z0-9_.-

function valid_name($name)
{

   // return FALSE if it contains characters which
   // which ARNT on the specified list
   if(ereg('[^[:space:]a-zA-Z0-9_.-]{1,}', $name))
   {
      return false;
   }
   else
   {
      return true;
   }

}
bobocop at bobocop dot cz 02-May-2005 08:09
<?php
// Completely update for match RFC 2822 and RFC 1035
// http://www.faqs.org/rfcs/rfc2822.html
// http://www.faqs.org/rfcs/rfc1035.html

// Example results:

$email[] = 'foo@example.com';                      // matched
$email[] = 'foo.bar@example.co.uk';                // matched
$email[] = 'foo_bar@example.com';                  // matched
$email[] = '_foo_bar@example.com';                 // matched
$email[] = 'foo@example.example';                  // matched
$email[] = '%#a+f.*&654_-._@ee.xx';                // matched
$email[] = 'foo@abc-123.xx';                       // matched
$email[] = 'a@a.a.a.a.aa';                         // matched
$email[] = 'a@a9.aa';                              // matched
$email[] = 'a!b#c$d%e^f&g*h\'i+j-k{l|m}n_/@op.qr'; //matched

$email[] = '';                                     //separator

$email[] = 'foo@-example.com';                     // not matched
$email[] = 'foo@example-.com';                     // not matched
$email[] = '%#af.*&@a%#b.xx';                      // not matched
$email[] = 'a@a.99.00.a.aa';                       // not matched
$email[] = '_-._@-.--';                            // not matched
$email[] = 'any..thing@bla.bla';                   // not matched
$email[] = '@.';                                   // not matched
$email[] = '@.com';                                // not matched
$email[] = '@exam@exam.com';                       // not matched
$email[] = ' @ .com';                              // not matched
$email[] = '.bar@example.com';                     // not matched
$email[] = 'foo.@example.com';                     // not matched
$email[] = 'foo@example.x';                        // not matched

$atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]';    // allowed characters for part before "at" character
$domain = '([a-z]([-a-z0-9]*[a-z0-9]+)?)'; // allowed characters for part after "at" character

$regex = '^' . $atom . '+' .         // One or more atom characters.
'(\.' . $atom . '+)*'.               // Followed by zero or more dot separated sets of one or more atom characters.
'@'.                                 // Followed by an "at" character.
'(' . $domain . '{1,63}\.)+'.        // Followed by one or max 63 domain characters (dot separated).
$domain . '{2,63}'.                  // Must be followed by one set consisting a period of two
'$';                                 // or max 63 domain characters.

foreach ($email as $example) {
    if (strlen($example) == 0):
        echo '&nbsp;<br>';
    else:
      if (eregi($regex, $example)):
       echo $example . ' matched<br>';
      else:
       echo '<strong>'. $example . ' not matched</strong><br>';
      endif;
    endif;
}
?>
Sergio Santana: ssantana at tlaloc dot imta dot mx 01-Mar-2005 04:32
Sometimes we require checking the syntax of
floating point numbers. Here is a php-code that
performs this task.

// To call this program:
//   php floats.php
//--------------------------
// Example of the use of regular expressions for checking
// the syntax of floating point numbers.
<?php
// This opens standard in ready for interactive input..
$STDIN = fopen("php://stdin","r");

for(;;) { // FOREVER-LOOP
  echo "Float>";
  $s = trim(fgets($STDIN,256));
  if ($s) {
    $le =
      eregi(
       "-?(([0-9]+e-?[0-9]+)|((([0-9]+\.[0-9]*)|(\.[0-9]+))" .
       "(e-?[0-9]+)?))",
         $s, $regs);
    if ($le==strlen($s))
      echo "Yes it's float\n";
    else if ($le > 0)
      echo "$le chars of the string correspond to a float\n";
    else
      echo "No, it isn't float\n";
  }
  else
    break;
}

fclose($STDIN);

?>
krum at estnet dot bg 23-Feb-2005 12:05
I was searching for a fast way to check all fields of a form, so I can
include the $_POST information directly to the sql query. So I wrote
another script in my class in order to check the submitted data. So here it
is:
<?
function check_post () {
 foreach ($_POST as $key => $val) {
  $$key = $val;
 }
 $data = Array();
 $data["^[a-z0-9!@#$%^&*]"] = Array ("first_name", "last_name",
 "nick", "pass", "description", "user", "message", "event", "name", "title",
 "text");
 $data['^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'
.'@'.'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'
.'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'] = Array("mail");
 $data["^[0-9]{1,4}"] = Array("day", "month", "owner", "type", "forum_id", "topic_id");
 foreach ($data as $key => $val) {
  foreach ($val as $k => $c) {
   if ( isset($$c) ) {
    if ( !eregi($key, $$c) ) {
     echo "You have used an not allowed character in " .$$c. " field\n";
     exit;
    }
   }
  }
 }
}
?>
I hope it will help someone ^_^
sven.heinicke.org 03-Feb-2005 11:49
The  gethostbyname($regs[2]) == $regs[2] is a bad idea.  Some domain names have a MX record but not an IP number.  The first example I found is jhu.edu domain:

sven@chef:~$ host jhu.edu
jhu.edu A record currently not present
sven@chef:~$ host -t mx jhu.edu
jhu.edu                 MX      10 smtp.johnshopkins.edu
selman17@yahoo com 24-Nov-2004 08:11
<?php

$iletisim="selman17@yahoo.com http://www.yahoo.com selman@yahoo.com";

$ilet=explode(" ",$iletisim);
$iletisim="";
for($i=0;$i<sizeof($ilet);$i++){

if(eregi("^.[a-zA-Z0-9_.\.-]+@[a-z0-9_]+\\.[a-z]+",$ilet[$i])){
$ilet[$i]= str_replace("$ilet[$i]","<a href='mailto:$ilet[$i]'>$ilet[$i]</a><br>",$ilet[$i]);
}
if(eregi("http://.[a-zA-Z0-9_.\.-]",$ilet[$i])){
$ilet[$i]= str_replace("$ilet[$i]","<a href='$ilet[$i]' target='_blank'>$ilet[$i]</a><br>",$ilet[$i]);
}
$iletisim .=$ilet[$i];
}
/* this will out put
<a href="mailto:selman17@yahoo.com">selman17@yahoo.com</a><br>
<a href="http://www.yahoo.com" target="_blank">http://www.yahoo.com</a><br>
<a href="mailto:selman@yahoo.com">selman17@yahoo.com</a>
*/
?>
cristian81 AT katamail DOT com 24-Nov-2004 03:12
The same "checkipaddress" function posted by "lueck at gerwan dot de", with the add of an optional jolly char suport. Returns TRUE or FALSE

Results:

check_ip_address('125.32.15.0') is TRUE
check_ip_address('125.32.15.*') is FALSE
check_ip_address('125.32.15.*', '*') is TRUE
check_ip_address('*.*.*.*', '*') is TRUE
check_ip_address('125.-.15.2', '-') is TRUE

<?php
function check_ip_address($checkip, $jolly_char='') {
    if ($jolly_char=='.')        // dot ins't allowed as jolly char
        $jolly_char = '';

    if ($jolly_char!='') {
        $checkip = str_replace($jolly_char, '*', $checkip);        // replace the jolly char with an asterisc
        $my_reg_expr = "^[0-9\*]{1,3}\.[0-9\*]{1,3}\.[0-9\*]{1,3}\.[0-9\*]{1,3}$";
        $jolly_char = '*';
    }
    else
        $my_reg_expr = "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$";

    if (eregi($my_reg_expr, $checkip)) {
        for ($i = 1; $i <= 3; $i++) {
            if (!(substr($checkip, 0, strpos($checkip, ".")) >= "0" && substr($checkip, 0, strpos($checkip, ".")) <= "255")) {
                if ($jolly_char!='') {            // if exists, check for the jolly char
                    if (substr($checkip, 0, strpos($checkip, "."))!=$jolly_char)
                        return false;
                }
                else
                    return false;
            }

            $checkip = substr($checkip, strpos($checkip, ".") + 1);
        }

        if (!($checkip >= "0" && $checkip <= "255")) {        // class D
            if ($jolly_char!='') {            // if exists, check for the jolly char
                if ($checkip!=$jolly_char)
                    return false;
            }
            else
                return false;
        }
    }
    else
        return false;

    return true;
}
?>
ian at hyperborea dot co dot uk 10-Nov-2004 03:15
I was looking for something to validate a URL, and as usual turned to 'php.net' as it provides an invaluable source of information. I couldn't find exactly what I wanted so came up with something of my own which I hope will be of use to others.

<?php
function validateURL($URL) {
    $domain = "([[:alpha:]][-[:alnum:]]*[[:alnum:]])
(\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])+";
    $dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]])*";
    $page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?";
    $getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+)
(&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+))*)?";
    $pattern = "^".$domain.$dir.$page.$getstring."$";
    return eregi($pattern, $URL);
}
?>
Be sure to enter each pattern on a single line.

The function accepts a URL and validates the domain, directory path, page and any GET parameters. You can see I have split the patterns for validating each section for easier reading and maintaining.

Domain Name:
This can be made of of many parts each seperated by a '.' (dot). each part must start with an alpha char. followed by any alphanumeric chars., or '-'. With the exception of the first part each part must end in an alpha char..

e.g. www.google.co.uk and www9.g-88gle.co.uk are valid, but 9ww.google.3o.uk and www.google4.co.uk3 are not.

Directory Path:
Each directory must start with a '/' followed by an alpha char., then any alpha numeric char., or '-', and ending in an alphanumeric char.

e.g. /path1/to-page is valid, but /path1-/2-page is not.

Page:
This is like the directory path but it must end with a '.' (dot) followed by 3-5 alpha chars.

e.g. /phpinfo.php and /page.shtml are valid, but /phpinfo.php4 and /pageshtml are not.

Get String:
This follows the page and begins with a '?'. This is then followed by key/value pairs each seperated by an '&'.

e.g. ?key1=value1&key2=value2

Each key, or value must start and end with an alpahnumeric char. I have allowed for a '%' to be specified for URL encoded chars., and also '_' (underscore) is allowed.

Well thats it hope it is of some use. It is NOT perfect, for instance in the 'getstring' I would like to ensure that encoded characters (i.e. %20) consist of a % symbol followed by two characters with values '0-9A-F' but couldn't get anything I tried to work.
I would welcome any suggestions or improvements, there are bound to be some.

Note: The patterns are based on an earlier post by 'fusillo at NOSPAM dot netgang dot it' for matching domain names. Thanks to him.
gabriel at gabrielharrison co uk 01-Nov-2004 04:19
There is a bug in the regex that means it doesn't work with a domain suffex that has two parts eg: .co.uk
I'm not good enough with regexs to sort this - sorry.

There can also be a problem if the domain doesn't have a domain entry without the www. subdomain. To solve this modify the code with:

elseif( gethostbyname($regs[2]) == $regs[2] ||
gethostbyname('www' . $regs[2]) == 'www' . $regs[2])
chadkeffer at mail dot com 01-Jul-2004 04:42
There's seems to be some confusion on just what is allowed in an email address and thus how to build your regular expression.  RFC 2822 replaced RFC 822 over 3 years ago, so make sure you're referencing the correct RFC.  Also, don't assume all servers comply with the RFC.
gullevek at gullevek dot org 23-Jun-2004 01:58
for the comment from 'joseph dot ragsdale at xconduit dot com'

The regex has one bug thought. It elminates <user>@jp.t.ne.jp addresses which are completly valid as it needs at least 2 chars in the domain part.

This regex fixes it:

^[_a-z0-9-]+(\.[_a-z0-9-]+)*
@[a-z0-9-]+(\.[a-z0-9-]{1,})*\.([a-z]{2,}){1}$

[but the regex in one line]
kidproto at hotmail dot com 19-Apr-2004 11:55
"^[a-zA-Z0-9_\-]+(:?\.svg|\.wmf|\.zip|\.tar\.gz|\.tgz)$"

That is the proper file check for a well formatted beginning and ending filename for those select files. The one in this list is incorrect for at least php 4.3.0 which is what I'm using.

The (:?) makes sure that the parentheses aren't used for storing the matched regex.
fusillo at NOSPAM dot netgang dot it 03-Jan-2004 02:24
This is a simple function that uses eregi() function to validate a domain name (according to the RFC 1034).

function check_host($host) {
if (
   eregi("^[[:alpha:]]+([-[:digit:][:alpha:]]*
          [[:digit:][:alpha:]])*(\.[[:alpha:]]+
          ([-[:digit:][:alpha:]]*[[:digit:][:alpha:]])*)
          *$",$host)
  ) {
       return 1;
    } else return 0;
};

NOTE: This expression must be written on a single line to work
I had to brake it on separate lines to post on the site.

Returns 1 if $host is an RFC compliant domain name else returns 0.

This function is part of the code of blackboxed linux distribution coming on your screen late genuary.

-fusillo-
alexm(_A_T_)factory7.com 11-Dec-2003 12:30
A little interesting and hopefully on topic point I found while browsing the internet at: http://www.clemburg.com/x1713.html#AEN1717

According to RFC 822 (see http://www.rfc-editor.org/), email addresses
are case-sensitive in the part before the "@" sign, except for the
special address "POSTMASTER", which is not case-sensitive. The part
after the "@" sign is a host name, and is not case-sensitive.

Note that many organizations will implement an aliasing facility that
recognizes alternative forms for an email address (e.g., providing
"John.Doe@my.organization.com", "john.doe@my.organization.com",
"doe@my.organization.com", "Doe@my.organization.com" etc.). However,
this is not required by the standard as specified in RFC 822.

so you may want to keep that in mind....
i.e. breakup the username/alias (ereg) and domain (eregi) parts of the email
joseph dot ragsdale at xconduit dot com 06-Nov-2003 02:31
I'm posting this as a - hopefully - helpful example to those who are learning regular expressions. Apologies to the documentation team and moderators for posting yet another email address validation example, but it's hard to argue against it as most everyone will see regular expressions as being a solution to this problem.

<?php
// Example results:

$email[] = 'foo@example.com';       // matched
$email[] = 'foo.bar@example.co.uk'; // matched
$email[] = 'foo_bar@example.com';   // matched
$email[] = '_foo_bar@example.com';  // matched
$email[] = 'foo@example.example';   // matched
$email[] = '_-._@-.--';             // matched

$email[] = '@.';               // not matched
$email[] = '@.com';            // not matched
$email[] = ' @ .com';          // not matched
$email[] = '.bar@example.com'; // not matched
$email[] = 'foo.@example.com'; // not matched
$email[] = 'foo@example.x.y';  // not matched

$regex =
  '^'.
  '[_a-z0-9-]+'.        /* One or more underscore, alphanumeric,
                           or hyphen charactures. */
  '(\.[_a-z0-9-]+)*'.   /* Followed by zero or more sets consisting
                           of a period and one or more underscore,
                           alphanumeric, or hyphen charactures. */
  '@'.                  /* Followed by an "at" characture. */
  '[a-z0-9-]+'.         /* Followed by one or more alphanumeric
                           or hyphen charactures. */
  '(\.[a-z0-9-]{2,})+'. /* Followed by one or more sets consisting
                           of a period and two or more alphanumeric
                           or hyphen charactures. */
  '$';

foreach ($email as $example) {
  if (eregi($regex, $example)) {
    echo $example . ' matched<br>';
  } else {
    echo $example . ' not matched<br>';
  }
}
?>
banerian at u dot washington dot edu 16-Sep-2003 06:55
It should be noted that in the function validateEmail, the final verification relies on the mail server responding to the test $email with a reply code of 250.   Nowadays, many/most/all servers will reply 250/Ok for any  user@thier.domain regardless of whether or not the userid actually exists.  mail servers tend to accept the mail (if it passes other checks), and if the user really does not exist, it just "bounces" the mail back to sender.  thus the validateEmail function can give false positives...an unfortunate victim of having to deal with spam.
Hodfords 06-Sep-2003 02:17
Most of the Ereg functions for emails that I have seen do not
work for emails like :-

joe@something.co..uk

And emails such as
joe@something.co.uk+1234

This eregi which we put together, I think works, it should be just one line, but php.net did not let us submit, because it said that even after using wordwrap() the line was too long :-

$ereg_string =
"^[\'+\\./0-9A-Z^_\`a-z{|}~\-]+@
[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){1,3}$";

Adjust the number "3" right at the end to whatever number
you want.

A long domain name such as "@finance.uk.yahoo.co.uk" which
has 5 parts will require the number to be higher.
tomi at vacilando dot net 26-Jun-2003 11:03
Keran's solution is a good one but I found it does not work for a small number of domains -- because of a bug in gethostbyname() that causes some valid domains not to resolve properly. The workaround is to test such domains with "www." added to the beginning. This script does all that and works perfectly for me. Enjoy!

// Function to validate emails.
function validate_email($email_raw)
    {
    // replace any ' ' and \n in the email
    $email_nr = eregi_replace("\n", "", $email_raw);
    $email = eregi_replace(" +", "", $email_nr);
    $email = strtolower( $email );
    // do the eregi to look for bad characters
    if( !eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*". "@([a-z0-9]+([\.-][a-z0-9]+))*$",$email) ){
      // okay not a good email
      $feedback = 'Error: "' . $email . '" is not a valid e-mail address!';
      return $feedback;
      } else {
      // okay now check the domain
      // split the email at the @ and check what's left
      $item = explode("@", $email);
      $domain = $item["1"];
      if ( ( gethostbyname($domain) == $domain ) )
        {
          if ( gethostbyname("www." . $domain) == "www." . $domain )
             {
               $feedback = 'Error: "' . $domain . '" is most probably not a valid domain!';
               return $feedback;
             }
        // ?
           $feedback = "valid";
           return $feedback;
        } else {
        $feedback = "valid";
        return $feedback;
        }
      }
    }
steve at brainwashstudios dot com 10-Apr-2003 10:22
why not match some filenames?

if (!ereg("^[a-ZA-Z0-9]+[/.gif|/.jpg|/.png]$",$match){
 echo "Invalid Filename";
}else{
 if (file_exists($match)){
  echo "blah";
 }
}

I suppose that would work off the top of my head but I have yet to test it, so you may want to check it first.
keran at kiwi-interactive dot com 07-Mar-2003 08:21
I couldn't get any of the email validation items above to actually work (maybe I'm thick) :)

So I adapted a couple and came up with this, and it seems to work

// function to validate email
function validate_email($email_raw) {

    // replace any ' ' and \n in the email
    $email_nr = eregi_replace("\n", "", $email_raw);
    $email = eregi_replace(" +", "", $email_nr);

    // do the ergei to look for bad characters
  if( !eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*".
"@([a-z0-9]+([\.-][a-z0-9]+))*$",$email) ){
    // okay not a good email
    $feedback = "Error: $email isn't a valid mail address!";
    return $feedback;
    } else {
        // okay now check the domain
        // split the email at the @ and check what's left
        $item = explode("@", $email);
        $domain = $item["1"];
        if( gethostbyname($domain) == $domain) {
            $feedback = "Error: $domain isn't a valid domain!";
            return $feedback;
        } else {
            $feedback = "valid";
            return $feedback;
        }
    }

}
slavo at polovnictvo-mn dot sk 19-Feb-2003 05:30
This is what I found (by Jon S. Stevens jon@clearink.com with
Copyright 1998 Jon S. Stevens, Clear Ink)

function validateEmail ($email){
   global $SERVER_NAME;
   $return = array(false,  "" );
   list ($user, $domain) = split( "@", $email, 2);
   $arr = explode( ".", $domain);
   $count = count ($arr);
   $tld = $arr[$count - 2] .  "." . $arr[$count - 1];
   if(checkdnsrr($tld,  "MX")) {
      if(getmxrr($tld, $mxhosts, $weight)) {
         for($i = 0; $i < count($mxhosts); $i++){
               $fp = fsockopen($mxhosts[$i], 25);
            if ($fp){
               $s = 0;
               $c = 0;
               $out =  "";
               set_socket_blocking($fp, false);
               do {
                  $out = fgets($fp, 2500);
                  if(ereg( "^220", $out)){
                           $s = 0;
                     $out =  "";
                     $c++;
                  }
                  else if(($c > 0) && ($out ==  "")){
                     break;
                  }
                  else {
                     $s++;
                  }
                  if($s == 9999) {
                     break;
                  }
               } while($out ==  "");
               set_socket_blocking($fp, true);
               fputs($fp,  "HELO $SERVER_NAME\n");
               $output = fgets ($fp, 2000);
               fputs($fp,  "MAIL FROM: <info@" . $tld .  ">\n" );
               $output = fgets($fp, 2000);
               fputs($fp,  "RCPT TO: <$email>\n");
               $output = fgets($fp, 2000);
               if(ereg(  "^250", $output )) {
                  $return[0] = true;
               }
               else {
                  $return[0] = false;
                  $return[1] = $output;
               }
               fputs ($fp,  "QUIT\n");
               fclose($fp);
               if($return[0] == true){
                  break;
               }
            }
         }
      }
   }
   return $return;
}

----
hope it helps you...
webmaster at textedit dot co dot uk 19-Jan-2003 11:03
I notice a lot of queries involving regular expressions and is_float() regarding currency validation.

If you have a version of php that uses the std C ctype.h functions then it will ALWAYS work with the following code.

function check_price($price)
{
$data=split('[.]',$price);

    if ( count($data) != 2 )
        return "false";

    if ( ctype_digit($data[0]) && ctype_digit($data[1]) && $data[0][0] != '0')
        return "true";
    else
          return "false";
}

Peter Lorimer

http:www.textedit.co.uk
webmaster@textedit.co.uk
X-Istence.com 17-Jan-2003 06:48
To check email, i use the following code:

if (!eregi ("^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}$", $email) {
echo "Invalid Email Adress";
}
else {
echo "Valid Email Adress";
}
respectthepinguin at yahoo dot com 03-Jan-2003 11:30
validating an email can be pretty tough... however this....
^([[:alnum]]|_|\.|-)+@([[:alnum]]|\.|-)+(\.)([a-z]{2,4})$
makes this task much easier. (:)
BKDotCom at hotmail dot com 30-Sep-2002 11:56
in regards to using gethostbyname() to validate email addresses:
Large flaw:
Doesn't work if the host has a NS & MX record, but no A record.
mark dot edwards dot no dot spam at rayconNOSPAM dot com dot au 23-Sep-2002 08:21
The apostrophe is an allowable character in the username of an email address.

The regex I use for this is:
^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$

Escaping the apostrophe unfortunately allows users to put a backslash in their username and the regex will not complain.

Better I feel to allow some errors through than to deny legitimate addresses.
henrik jensen<hj at this_netwerk dot dk> 27-Jul-2002 10:05
Looking for at regex to check if a file is an image file, this seems to work?

Note: it does not check for illegeal filesystem names - it only looks at the filename extension.

if (eregi ("(.)+\\.(jp(e){0,1}g$|gif$|png$)",$filename)){
    // This is an imagefile
}

[ remove this_ from emailaddress ]
trosho at vip dot bg 09-Jun-2002 04:47
Please note that eregi() is case sensitive if you use cyrillic chars
re at lloc dot de 06-Mar-2002 07:36
An additional note to one of these
expressions above: I use

"^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]
+([.-][a-z0-9]+)*)+\\.[a-z]{2,4}$"
tuxx at tuxx-home dot at 27-Feb-2002 03:11
A small note to one of these expressions above:
Inside a character class ([...]) one does not need to escape the fullstop, therefore

[-\\._]

would become

[-._]
steve at fish2find dot co dot uk 26-Feb-2002 07:40
hope this helps with some validation problems, simple text validation:
            //$firstname = "somename"; // valid
    or  //$firstname = "somenam3"; // not valid

            //lets validate a field entry & trim off any white spaces
            $firstname = trim($firstname);

        //set lenght of the field to a max 12 characters
            $len = "0,12";
            $field = $firstname;

            //call function
            if (is_valid($field, $len)){

            //if field entry valid then set
            $valid_firstname = $field;
            //set record to yes
            $valid_record = "TRUE";
                  echo "$field is a valid name";
            }
            else{
            //set record to null
            $valid_record = "FALSE";
                  echo " $field is not a valid name";
            }
            //process to see if valid record
            if ($valid_record == "FALSE"){
                  echo " & is not a valid record";
            }
            else{ //assume record is valid
                  echo " & is a valid record";
            }

            //validate field entry function

            function is_valid($field, $len) {
            if(eregi("^[[:alpha:]]{{$len}}$", $field)) return                TRUE;
            else return FALSE;
            }
ruben dot no dot spam at artek dot no dot spam dot es 08-Feb-2002 12:28
Well, this can be improved a little. According to the previous, these email addresses would be correct:
  user@domain.e
  user@domain.123
  user@domain-ltd

I suggest this regexp:

if( !eregi( "^" .
            "[a-z0-9]+([_\\.-][a-z0-9]+)*" .    //user
            "@" .
            "([a-z0-9]+([\.-][a-z0-9]+)*)+" .   //domain
            "\\.[a-z]{2,}" .                    //sld, tld
            "$", $email, $regs)
   )
...
mmc at nospam dot dk 27-Jan-2002 06:56
I'm not sure about "\." being the same as "." above.

Anyway, the mentioned regex would not recognize .museum-names, and generally isn't future safe.
Also, it doesn't verify that usernames and hostnames cannot start with "-._".

I would recommend a more general (=future safe) expression and then instead check the hostname. An example:

if( !eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*"
    ."@([a-z0-9]+([\.-][a-z0-9]+))*$",
    $mail, $regs) )
{
    echo "Error: '$mail' isn't a valid mail address!\n";
}
elseif( gethostbyname($regs[2]) == $regs[2] )
{
    echo "Error: Can't find the host '$regs[2]'!<br>\n";
}

Note: I had to split the regex for it to fit this note.
Also note: The reason I'm using gethostbyname() and not getmxrr() or such is that getmxrr() doesn't work on Win2000/XP.
eregi_replace
split
Р¤СѓРЅРєС†РёРё СЂРµРіСѓР»СЏСЂРЅС‹С… РІС‹СЂР°Р¶РµРЅРёР№ POSIX


Разбиение строки на массив по регулярному выражению

eregi
spliti
Функции регулярных выражений POSIX
PHP Manual

split

(PHP 4, PHP 5)

split — Разбиение строки на массив по регулярному выражению

Описание

array split ( string $pattern , string $string [, int $limit = -1 ] )

Разбивает строку string на массив по регулярному выражению.

Внимание

С версии PHP 5.3.0 эта функция считается УСТАРЕВШЕЙ. Крайне не рекомендуется полагаться на эту возможность.

Список параметров

pattern

Регулярное выражение, чувствительное к регистру.

Если необходимо разбить строку по символам, являющимся специальными для регулярных выражений, их следует экранировать. Если вам кажется, что split() (или любая другая функция, работающая с регулярными выражениями) ведет себя неожиданно, пожалуйста, прочтите файл regex.7, расположенный в поддиректории regex/ дистрибутива PHP. Он сохранен в формате manpage, поэтому для удобства чтения используйте команду man /usr/local/src/regex/regex.7.

string

Входная строка.

limit

Если указан параметр limit, возвращаемый массив будет содержать максимум limit элементов, причем последний элемент будет включать всю оставшуюся часть строки string.

Возвращаемые значения

Возвращает массив строк, каждая из которых является строкой, образованной разбиением строки string чувствительным к регистру регулярным выражением pattern.

Если pattern встречается n раз, результирующий массив будет содержать n+1 элементов. Например, если pattern в строке отсутствует, будет возвращен массив, содержащий 1 элемент. Само собой, это также верно в случае, когда string является пустой строкой. В случае ошибки split() возвращает FALSE.

Примеры

Пример #1 Пример использования split()

Получаем первые четыре поля строки из /etc/passwd:

<?php
list($user, $pass, $uid, $gid, $extra) =
    split(":", $passwd_line, 5);
?>

Пример #2 Пример использования split()

Распознаем дату, отформатированную с использованием слешей, точек или дефисов:

<?php
// Разделителями могут быть слеши, точки или дефисы
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Месяц: $month; День: $day; Год: $year<br />\n";
?>

Примечания

Замечание:

С версии PHP 5.3.0, расширение regex помечено устаревшим и заменено расширением PCRE. Вызов этой функции приведет к ошибке уровня E_DEPRECATED. Смотрите список отличий для помощи при конвертировании в PCRE.

Подсказка

preg_split(), использующая Perl-совместимый синтаксис регулярных выражений, чаще всего работает быстрее split(). В случае, когда нет необходимости использовать регулярные выражения, эффективнее использовать explode(), которая не использует дополнительные ресурсы для разбора регулярного выражения.

Подсказка

Пользователям, которым необходимо эмулировать поведение @chars = split('', $str) из Perl, следует обратиться к примерам для preg_split() или str_split().

Смотрите также

  • preg_split() - Разбивает строку по регулярному выражению
  • spliti() - Разбивает строку в массив с помощью регулярного выражения без учета регистра
  • str_split() - Преобразует строку в массив
  • explode() - Разбивает строку с помощью разделителя
  • implode() - Объединяет элементы массива в строку
  • chunk_split() - Разбивает строку на фрагменты
  • wordwrap() - Переносит строку по указанному количеству символов

User Contributed Notes

dave at bevhost dot com 06-Jan-2012 12:19
The easiest function to replace this with is mb_split(),
which is the mutibyte version that works on unicode characters such as chinese letters in your strings.
Bob 24-Apr-2009 06:58
I was interested in the performance of various tokenizing algorithms, in particular splitting a string by a list of tokens. I've compared 3 methods, including a custom function based on strtok().
My aim was to split a MySQL type definition into its various parts, i.e. split "int(10) unsigned zerofill" to Array( 1 => "int", 2 => "10", 3 => " unsigned zerofill" )
This is the code I ran:
<?php
function getmicrotime()

{

    list($usec, $sec) = explode(" ",microtime());

    return ((float)$usec + (float)$sec);

}

function toksplit($string, $tokens)
{
    $val = array();
    $v = strtok($string, $tokens);
    do $val[] = $v;
    while($v = strtok($tokens));
    return $val;
}

echo "<pre>";

$string = "int(10) unsigned zerofill";
$ntrials = 100000;

for($i = 0, $t = getmicrotime(); $i < $ntrials; ++$i) $toksplit_result = toksplit($string, '()');
$time = getmicrotime()-$t;
$avg = $time/$ntrials;
echo "toksplit(): $avg\n";
print_r($toksplit_result);

for($i = 0, $t = getmicrotime(); $i < $ntrials; ++$i) $split_result = split('[()]', $string);
$time = getmicrotime()-$t;
$avg = $time/$ntrials;
echo "split(): $avg\n";
print_r($split_result);

for($i = 0, $t = getmicrotime(); $i < $ntrials; ++$i) $preg_split_result = preg_split('/[()]/', $string);
$time = getmicrotime()-$t;
$avg = $time/$ntrials;
echo "preg_split(): $avg\n";
print_r($preg_split_result);

echo "</pre>";
?>
These were the results:
toksplit(): 1.94901299477E-5
Array
(
    [0] => int
    [1] => 100
    [2] =>  unsigned zerofill
)
split(): 1.50095391273E-5
Array
(
    [0] => int
    [1] => 100
    [2] =>  unsigned zerofill
)
preg_split(): 1.82743000984E-5
Array
(
    [0] => int
    [1] => 100
    [2] =>  unsigned zerofill
)

Interestingly, split() was the fastest.
I also modified my test to also strip whitespace from each token, changing the patterns to "\s*[()]\s*" and adding a trim() call to the toksplit() function. The results went from fastest to slowest: preg_split(), split(), toksplit().
I would infer from this that split() is the fastest if you want to simply split by a list of delimiters. However, if you want to split by a more complicated pattern, preg_split() is the best.
strtok() is clearly slower.
NOTE: if you want to split by a single delimiter (not a list or pattern), use explode().
charles at etherscapes dot com 18-Mar-2009 09:33
This function just makes sure there are 10 digits in a string, no matter what other characters there are. I'm using it for validating any phone number in the world and requiring an area code. It's far from perfect, but since I don't know which country the phone number is for, it's good enough for my purposes:

<?php
function validPhone($str) {
    $digits = split("[0-9]",$str);
    return count($digits)>10;
}
?>
Greg Levine 04-Dec-2008 01:45
I kept running into the same issue Chris Tyler experienced with lewis [ at t] hcoms [d dot t] co [d dot t] uk's function before realizing that Chris had come up with a solution. However, that solution was just a little off it seems, unless your CSV only contains one line.

If you simply add another --length; in the place you suggested, then the function will always trim the last two characters on the line. Since the newline character is the last character on the line and the redundant quote (or other enclosure) is the second to last character, this works for the final segment. But when parsing segments that do not include a newline character, you end up trimming the redundant enclosure and the last character before the enclosure.

For example,

"he","she","him","her"\r\n

becomes

[0] => h
[1] => sh
[2] => hi
[3] => her

Since the segment could end with the enclosure (i.e., ") or the enclosure followed by the newline (i.e., "\r\n), you have make sure you are only adding another --length; when the latter is the case. Replacing the code block that you suggested with the following will do the trick.

# Is the last thing a newline?
if( $char == $newline )
{
    # Well then get rid of it
    --$length;
}

# Is the last thing a quote?
if( $trim_quote )
{
    # Well then get rid of it
    --$length;
}

I've tested this only for the purposes of the script I'm working on at this time. So, there could be other bugs I haven't come across, but this seems like the easiest way to eliminate the redundant enclosure.
sue_hok at hotmail dot com 11-Sep-2008 11:26
This function basically is to split the string from right with limit
<?php

function split_right($pattern,$input,$len=0)
    {
if($len==0)
    return split($pattern,$input);

            $tempInput = split($pattern,$input);
            $tempInput = array_reverse($tempInput);
            $tempArray = array();
            $ArrayIndex=0;
            $indexCount=0;
            foreach($tempInput as $values)
            {
                if($indexCount<$len)
                {
                    $tempArray[$ArrayIndex]=$values;
                    if($indexCount<$len-1)
                        $ArrayIndex++;
                }
                else
                {
                        $tempArray[$ArrayIndex]=$values.$pattern.$tempArray[$ArrayIndex];

                }

                $indexCount++;

            }
            return array_reverse($tempArray);
    }

//For Example:
$string = "Hello World Split";
print_r(split(" ",$string,2));
print_r(split_right(" ",$string,2));

/*OutPut
Array
(
    [0] => Hello
    [1] => World Split
)

Array
(
    [0] => Hello World
    [1] => Split
)
*/

?>
anthonyhoivik at gmail dot com 15-Aug-2008 08:45
Convert a full name ( in one text input ) to a first, middle, last.

$fullname = $_POST['fullname'];
  list($first, $middle, $last) = split(' ', $fullname);
  if ( !$last ) {
    $last = $middle;
    unset($middle);
  }
pascalaschwandenNOSPAM at gmail dot com 13-Jul-2008 12:12
The following code will mimick the explode functionality: explode( " ", $s );  The difference, of course, is that the split method takes a regular expression instead of a string.

$s = "Split this sentence by spaces";
$words = split("[ ]+", $s);
print_r($words);

Output:
Array
(
    [0] => Split
    [1] => this
    [2] => sentence
    [3] => by
    [4] => spaces
)
http://www.codesplunk.com/nr/questions/php12.html
Chris Tyler 09-Apr-2008 03:25
Thank you Dave for your code below.  Here is one change I made to avoid a redundant quote at the end of some lines (at least when I used excel:

Added another --length;  into the if statement below:

                // Is the last thing a quote?
                if ($trim_quote){
                    // Well then get rid of it
                    --$length;
        // ADD TO FIX extra quote
    --$length;
                }
lewis [ at t] hcoms [d dot t] co [d dot t] uk 25-Mar-2008 03:32
Those of you trying to use split for CSV, it won't always work as expected. Instead, try using a simple stack method:

<?php

    /**
     * Create a 2D array from a CSV string
     *
     * @param mixed $data 2D array
     * @param string $delimiter Field delimiter
     * @param string $enclosure Field enclosure
     * @param string $newline Line seperator
     * @return
     */
    function parse($data, $delimiter = ',', $enclosure = '"', $newline = "\n"){
        $pos = $last_pos = -1;
        $end = strlen($data);
        $row = 0;
        $quote_open = false;
        $trim_quote = false;

        $return = array();

        // Create a continuous loop
        for ($i = -1;; ++$i){
            ++$pos;
            // Get the positions
            $comma_pos = strpos($data, $delimiter, $pos);
            $quote_pos = strpos($data, $enclosure, $pos);
            $newline_pos = strpos($data, $newline, $pos);

            // Which one comes first?
            $pos = min(($comma_pos === false) ? $end : $comma_pos, ($quote_pos === false) ? $end : $quote_pos, ($newline_pos === false) ? $end : $newline_pos);

            // Cache it
            $char = (isset($data[$pos])) ? $data[$pos] : null;
            $done = ($pos == $end);

            // It it a special character?
            if ($done || $char == $delimiter || $char == $newline){

                // Ignore it as we're still in a quote
                if ($quote_open && !$done){
                    continue;
                }

                $length = $pos - ++$last_pos;

                // Is the last thing a quote?
                if ($trim_quote){
                    // Well then get rid of it
                    --$length;
                }

                // Get all the contents of this column
                $return[$row][] = ($length > 0) ? str_replace($enclosure . $enclosure, $enclosure, substr($data, $last_pos, $length)) : '';

                // And we're done
                if ($done){
                    break;
                }

                // Save the last position
                $last_pos = $pos;

                // Next row?
                if ($char == $newline){
                    ++$row;
                }

                $trim_quote = false;
            }
            // Our quote?
            else if ($char == $enclosure){

                // Toggle it
                if ($quote_open == false){
                    // It's an opening quote
                    $quote_open = true;
                    $trim_quote = false;

                    // Trim this opening quote?
                    if ($last_pos + 1 == $pos){
                        ++$last_pos;
                    }

                }
                else {
                    // It's a closing quote
                    $quote_open = false;

                    // Trim the last quote?
                    $trim_quote = true;
                }

            }

        }

        return $return;
    }

?>

This *should* work for any valid CSV string, regardless of what it contains inside its quotes (using RFC 4180). It should also be faster than most of the others I've seen. It's very simple in concept, and thoroughly commented.
Dave Walter 29-Feb-2008 03:39
In response to  the getCSVValues() function posted by justin at cam dot org, my testing indicates that it has a problem with a CSV string like this:

1,2,"3,""4,5"",6",7

This parses as:

array(6) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(4) "3,"4"
  [3]=>
  string(1) "5"
  [4]=>
  string(0) ""
  [5]=>
  string(1) "7"
}

instead of:

array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(9) "3,"4,5",6"
  [3]=>
  string(1) "7"
}

To fix this, I changed the second substr_count to look for an odd number of quotes, as opposed to any quotes at all:

<?php
function getCSVValues($string, $separator=",")
{
    $elements = explode($separator, $string);
    for ($i = 0; $i < count($elements); $i++) {
        $nquotes = substr_count($elements[$i], '"');
        if ($nquotes %2 == 1) {
            for ($j = $i+1; $j < count($elements); $j++) {
                if (substr_count($elements[$j], '"') %2 == 1) { // Look for an odd-number of quotes
                    // Put the quoted string's pieces back together again
                    array_splice($elements, $i, $j-$i+1,
                        implode($separator, array_slice($elements, $i, $j-$i+1)));
                    break;
                }
            }
        }
        if ($nquotes > 0) {
            // Remove first and last quotes, then merge pairs of quotes
            $qstr =& $elements[$i];
            $qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1);
            $qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1);
            $qstr = str_replace('""', '"', $qstr);
        }
    }
    return $elements;
}
?>
Nate Sweet 31-May-2007 01:39
This function takes a string like this...

this=cool that="super cool" thing='ridiculous cool'

And gives you an associative array of names and values.

function parseNameValues ($text) {
    $values = array();
    if (preg_match_all('/([^=\s]+)=("(?P<value1>[^"]+)"|' . '\'(?P<value2>[^\']+)\'|(?P<value3>.+?)\b)/', $text, $matches, PREG_SET_ORDER))
        foreach ($matches as $match)
            $values[trim($match[1])] = trim(@$match['value1'] . @$match['value2'] . @$match['value3']);
    return $values;
}

(regex broken into two strings so it won't be too long for this webpage)
Mike 18-May-2007 10:40
// Split a string into words on boundaries of one or more spaces, tabs or new-lines
$s = "Please cut   \t me \n in pieces";
$words = split("[\n\r\t ]+", $s);
print_r($words);

// Output:
Array
(
    [0] => Please
    [1] => cut
    [2] => me
    [3] => in
    [4] => pieces
)
Jort 14-Mar-2007 12:53
If you are looking for EITHER open square brackets OR close square brackets, then '[[]]' won't work (reasonably expected), but neither will '[\[\]]', nor with any number of escapes. HOWEVER, if your pattern is '[][]' it will work.
justin at cam dot org 15-Feb-2007 10:21
The previous solution assumes that a quoted string always starts a new element (true in real CSV files, but not in my application). The following routine does not make any such assumptions. It also deals with pairs of quotes and does not use any regular expressions.

<?php
function getCSVValues($string, $separator=",")
{
    $elements = explode($separator, $string);
    for ($i = 0; $i < count($elements); $i++) {
        $nquotes = substr_count($elements[$i], '"');
        if ($nquotes %2 == 1) {
            for ($j = $i+1; $j < count($elements); $j++) {
                if (substr_count($elements[$j], '"') > 0) {
                    // Put the quoted string's pieces back together again
                    array_splice($elements, $i, $j-$i+1,
                        implode($separator, array_slice($elements, $i, $j-$i+1)));
                    break;
                }
            }
        }
        if ($nquotes > 0) {
            // Remove first and last quotes, then merge pairs of quotes
            $qstr =& $elements[$i];
            $qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1);
            $qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1);
            $qstr = str_replace('""', '"', $qstr);
        }
    }
    return $elements;
}
?>
Theodule 24-Jan-2007 08:41
A little modification from dan jones.
_New_: I had a parameter to specify separator (default ",").
_Fix _: double-quotes who appear in a spreadsheet exported to CSV, they get escaped by doubling them. So I remplace them by ' caracter
<?php
function getCSVValues($string,$separator=",")
{
    $string = str_replace('""', "'", $string);
    // split the string at double quotes "
    $bits = explode('"',$string);
    $elements = array();
    for ( $i=0; $i < count($bits) ; $i++ ) {
        /*
        odd numbered elements would have been
        enclosed by double quotes
        even numbered elements would not have been
        */
        if (($i%2) == 1) {
            /* if the element number is odd add the
            whole string  to the output array */
            $elements[] = $bits[$i];
        } else
        {
            /* otherwise split the unquoted stuff at commas
            and add the elements to the array */
            $rest = $bits[$i];
            $rest = preg_replace("/^".$separator."/","",$rest);
            $rest = preg_replace("/".$separator."$/","",$rest);
            $elements = array_merge($elements,explode($separator,$rest));
        }
    }
    return $elements;
}
?>
dan dot jones at lunarfish dot co dot uk 17-Aug-2006 05:24
Here's a function to split a string into csv values where they are optionally enclosed by " to allow values with commas in.

I think it works. Let me know if I'm wrong.

Cheers. Dan

function getCSVValues($string) {
   // split the string at double quotes "
   $bits = split('"',$string);
   $elements = array();
   for ($i=0;$i<count($bits);$i++) {
      /*
          odd numbered elements would have been
          enclosed by double quotes
          even numbered elements would not have been
      */
      if (($i%2) == 1) {
         /* if the element number is odd add the
             whole string  to the output array */
         $elements[] = $bits[$i];
      } else {
         /* otherwise split the unquoted stuff at commas
             and add the elements to the array */
         $rest = $bits[$i];
         $rest = preg_replace("/^,/","",$rest);
         $rest = preg_replace("/,$/","",$rest);
         $elements = array_merge($elements,split(',',$rest));
      }
   }
   return $elements;
}
destes at ix dot netcom dot com 14-Feb-2006 12:15
Some corrections to robin-at-teddyb's CSV splitting function.  Recall that the point of this is to properly implement a split() function that handles data exported to CSV, where data containing commas gets quote-delimited.

* Problem 1: As jh-at-junetz pointed out, the +1 in robin's nonquoted splitting command mistakenly adds an extra element to the resulting array.
* Problem 2: If consecutive fields are quote-delimited, the remaining "separator" between them only contains one delimiter and no actual fields - so an extra element gets added to the parsed array.
* Problem 3: When double-quotes appear in a spreadsheet exported to CSV, they get escaped by doubling them, i.e. a data field reading "this is a test of a "special" case" gets written to CSV as, "this is a test of a ""special"" case".  These quotes are also interpreted as top-level delimiters and (mistakenly) add extra array elements to the output.

I have hacked a conversion of "" to a single quote ( ' ), but a truly clever preg_split for the top-level splitter (instead of the explode) might preserve the original doubled "s without bugging up the top-level parsing.  i.e., a smarter man than I could solve the problem rather than avoiding it by replacing the bad data.

(current) Solution:

<?php

function quotesplit( $splitter=',', $s, $restore_quotes=0 ) {
    // hack because i'm a bad programmer - replace doubled "s with a '
    $s = str_replace('""', "'", $s);

    //First step is to split it up into the bits that are surrounded by quotes
    //and the bits that aren't. Adding the delimiter to the ends simplifies
    //the logic further down
    $getstrings = explode('"', $splitter.$s.$splitter);

    //$instring toggles so we know if we are in a quoted string or not
    $delimlen = strlen($splitter);
    $instring = 0;

    while (list($arg, $val) = each($getstrings)) {
        if ($instring==1) {
            if( $restore_quotes ) {
                //Add the whole string, untouched to the previous value in the array
                $result[count($result)-1] = $result[count($result)-1].'"'.$val.'"';
            } else {
                //Add the whole string, untouched to the array
                $result[] = $val;
            }
            $instring = 0;
        } else {
            // check that we have data between multiple $splitter delimiters
                        if ((strlen($val)-$delimlen) >= 1) {

                //Break up the string according to the delimiter character
                //Each string has extraneous delimiters around it (inc the ones we added
                //above), so they need to be stripped off
                $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen ) );

                while(list($iarg, $ival) = each($temparray)) {
                    $result[] = trim($ival);
                }
            }
            // else, the next element needing parsing is a quoted string and the comma
            // here is just a single separator and contains no data, so skip it

            $instring = 1;
        }
    }

    return $result;
}

?>
RE: gcerretini at technica dot net /UTF8 08-Feb-2006 04:26
Original problem:
=================

I've try using split function.

<?php
$ferro="2&#65533;12";
$valore=split("[&#65533;]",$ferro);
echo $ferro."<br>";
echo "p1-".$valore[0]."<br>";
echo "p2-".$valore[1]."<br>";
echo "p3-".$valore[2]."<br>";
$ferro="2d12";
$valore=split("[d]",$ferro);
echo $ferro."<br>";
echo "p1-".$valore[0]."<br>";
echo "p2-".$valore[1]."<br>";
echo "p3-".$valore[2]."<br>";
?>

This return:
============

2&#65533;12
p1-2
p2-
p3-12
2d12
p1-2
p2-12
p3-

I use charset UTF-8. When I use char &#65533; the split function ad an empty string between "2" and "12"... Why?

Explanation:
============

UTF-8 charset codes some characters (like the "&#65533;" character) into two bytes. In fact the regular expresion "[&#65533;]" contains 4 bytes (4 non-unicode characters). To demonstrate the real situation I wrote following example:

$ferro="2de12";
$valore=split("[de]",$ferro);
echo $ferro."<br>";
echo "p1-".$valore[0]."<br>";
echo "p2-".$valore[1]."<br>";
echo "p3-".$valore[2]."<br>";

This returns:
=============

2d12
p1-2
p2-
p3-12
04-Dec-2005 05:57
Be advised

$arr = split("x", "x" );
print_r($arr);

will output:

Array
(
    [0] =>
    [1] =>
)

That is it will catch 2 empty strings on each side of the delimiter.
franz at fholzinger dot com 04-Nov-2005 04:34
The example from ramkumar rajendran did not work.
$line = split("/\n", $input_several_lines_long);
I do not know why this does not work for me.

The following has worked for me to get a maximum of 2 array parts separated by the first new line (independant if saved under UNIX or WINDOWS):
$line = preg_split('/[\n\r]+/',$input_several_lines_long,2);
Also empty lines are not considered here.
passtschu AT freenet DOT de 24-Sep-2005 12:09
divide a string with a template. the "template dividers" are the keys for the output array.

<?PHP
function string2array ($string, $template){
  #search defined dividers
  preg_match_all ("|%(.+)%|U", $template, $template_matches);
  #replace dividers with "real dividers"
  $template = preg_replace ("|%(.+)%|U", "(.+)", $template);
  #search matches
  preg_match ("|" . $template . "|", $string, $string_matches);
  #[template_match] => $string_match
  foreach ($template_matches[1] as $key => $value){
     $output[$value] = $string_matches[($key + 1)];
  }
  return $output;
}

$string1 = 'www.something.com 66.196.91.121 - - [01/Sep/2005:04:20:39 +0200] "GET /robots.txt HTTP/1.0" 200 49 "-"';
$string2= '%Domain% %IP% - %User% \[%Date%:%Time% %TimeZone%\] "%Method% %Request% %Protocol%" %ServerCode% %Bytes% "%Referer%"';

print_r (string2array ($string1, $string2));

/*
Array

(
  [ServerAddress] => www.something.com
  [IP] => 66.196.91.121
  [User] => -
  [Date] => 01/Sep/2005
  [Time] => 04:20:39
  [TimeZone] => +0200
  [Method] => GET
  [Request] => /robots.txt
  [Protocol] => HTTP/1.0
  [ServerCode] => 200
  [Bytes] => 49
  [Referer] => -
)
*/
?>
robin at teddyb dot org 29-Jun-2005 09:01
Actually, this version is better than the last I submitted.  The goal here is to be able to engage in *multiple* delimeter removal passes; for all but the last pass, set the third value to "1", and everything should go well.

    function quotesplit( $splitter=',', $s, $restore_quotes=0 )
    {
        //First step is to split it up into the bits that are surrounded by quotes
        //and the bits that aren't. Adding the delimiter to the ends simplifies
        //the logic further down

        $getstrings = explode('"', $splitter.$s.$splitter);

        //$instring toggles so we know if we are in a quoted string or not
        $delimlen = strlen($splitter);
        $instring = 0;

        while (list($arg, $val) = each($getstrings))
        {
            if ($instring==1)
            {
                if( $restore_quotes )
                {
                    //Add the whole string, untouched to the previous value in the array
                    $result[count($result)-1] = $result[count($result)-1].'"'.$val.'"';
                } else {
                    //Add the whole string, untouched to the array
                    $result[] = $val;
                }
                $instring = 0;
            }
            else
            {
                //Break up the string according to the delimiter character
                //Each string has extraneous delimiters around it (inc the ones we added
                //above), so they need to be stripped off
                $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen+1 ) );

                while(list($iarg, $ival) = each($temparray))
                {
                    $result[] = trim($ival);
                }
                $instring = 1;
            }
        }

        return $result;
    }
robin at teddyb dot org 29-Jun-2005 08:50
wchris's quotesplit assumes that anything that is quoted must also be a complete delimiter-seperated entry by itself.  This version does not.  It also uses split's argument order.

    function quotesplit( $splitter=',', $s )
    {
        //First step is to split it up into the bits that are surrounded by quotes
        //and the bits that aren't. Adding the delimiter to the ends simplifies
        //the logic further down

        $getstrings = explode('"', $splitter.$s.$splitter);

        //$instring toggles so we know if we are in a quoted string or not
        $delimlen = strlen($splitter);
        $instring = 0;

        while (list($arg, $val) = each($getstrings))
        {
            if ($instring==1)
            {
                //Add the whole string, untouched to the previous value in the array
                $result[count($result)-1] = $result[count($result)-1].$val;
                $instring = 0;
            }
            else
            {
                //Break up the string according to the delimiter character
                //Each string has extraneous delimiters around it (inc the ones we added
                //above), so they need to be stripped off
                $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen+1 ) );

                while(list($iarg, $ival) = each($temparray))
                {
                    $result[] = trim($ival);
                }
                $instring = 1;
            }
        }

        return $result;
    }
wchris 18-Feb-2005 03:53
moritz's quotesplit didn't work for me. It seemed to split on a comma even though it was between a pair of quotes. However, this did work:

function quotesplit($s, $splitter=',')
{
//First step is to split it up into the bits that are surrounded by quotes and the bits that aren't. Adding the delimiter to the ends simplifies the logic further down

    $getstrings = split('\"', $splitter.$s.$splitter);

//$instring toggles so we know if we are in a quoted string or not
    $delimlen = strlen($splitter);
    $instring = 0;

    while (list($arg, $val) = each($getstrings))
    {
        if ($instring==1)
        {
//Add the whole string, untouched to the result array.
            $result[] = $val;
            $instring = 0;
        }
        else
        {
//Break up the string according to the delimiter character
//Each string has extraneous delimiters around it (inc the ones we added above), so they need to be stripped off
            $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen ) );

            while(list($iarg, $ival) = each($temparray))
            {
                $result[] = trim($ival);
            }
            $instring = 1;
        }
    }
    return $result;
}
ramkumar rajendran 17-Jan-2005 10:09
A correction to a earlier note
If you want to use split to check on line feeds (\n), the following won't work:

$line = split("\n", $input_several_lines_long);

You really have to do this instead, notice the second slash:
$line = split("/\n", $input_several_lines_long);

Took me a little while to figure to do
claes at dot2me.com 03-Nov-2004 04:10
Though this is obvious, the manual is a bit incorrect when claiming that the return will always be 1+number of time the split pattern occures.  If the split pattern is the first part of the string, the return will still be 1.  E.g.

$a = split("zz," "zzxsj.com");
count($a);

=> 1.

The return of this can not in anyway be seperated from the return where the split pattern is not found.
moritz 09-Apr-2004 11:54
Often you want to split CSV-Like data, so this is the function for this :)

It splits data formatted like:

1,2,3
-> [1,2,3]

1 , 3, 4
-> [1,3,4]

one; two;three
-> ['one','two','three']

"this is a string", "this is a string with , and ;", 'this is a string with quotes like " these', "this is a string with escaped quotes \" and \'.", 3
-> ['this is a string','this is a string with , and ;','this is a string with quotes like " these','this is a string with escaped quotes " and '.',3]

function quotesplit($s)
{
    $r = Array();
    $p = 0;
    $l = strlen($s);
    while ($p < $l) {
        while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
        if ($s[$p] == '"') {
            $p++;
            $q = $p;
            while (($p < $l) && ($s[$p] != '"')) {
                if ($s[$p] == '\\') { $p+=2; continue; }
                $p++;
            }
            $r[] = stripslashes(substr($s, $q, $p-$q));
            $p++;
            while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
            $p++;
        } else if ($s[$p] == "'") {
            $p++;
            $q = $p;
            while (($p < $l) && ($s[$p] != "'")) {
                if ($s[$p] == '\\') { $p+=2; continue; }
                $p++;
            }
            $r[] = stripslashes(substr($s, $q, $p-$q));
            $p++;
            while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
            $p++;
        } else {
            $q = $p;
            while (($p < $l) && (strpos(",;",$s[$p]) === false)) {
                $p++;
            }
            $r[] = stripslashes(trim(substr($s, $q, $p-$q)));
            while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
            $p++;
        }
    }
    return $r;
}
alphibia at alphibia dot com 31-Mar-2004 06:19
I'd like to correct myself, I found that after testing my last solution it will create 5 lines no matter what... So I added this to make sure that it only displays 5 if there are five newlines. :-)

<?php
    $MaxNewLines = 5;

    $BRCount = substr_count($Message, '<br />');
    if ($BRCount<$MaxNewLines)
    $MaxNewLines=$BRCount;
    else if($BRCount == 0)
    $MaxNewLines=1;

    $Message = str_replace(chr(13), "<br />", $Message);
    $MessageArray = split("<br />", $Message, $MaxNewLines);
    $Message = ""; $u=0;
    do    {
    $Message.=$MessageArray[$u].'<br />';
    $u++;
    } while($u<($MaxNewLines-1));
    $Message.=str_replace("<br />"," ",$MessageArray[$u]);
    ?>

-Tim
http://www.alphibia.com
nomail at please dot now 21-Nov-2003 09:33
If you want to use split to check on line feeds (\n), the following won't work:

$line = split("\n", $input_several_lines_long);

You really have to do this instead, notice the second slash:
$line = split("\\n", $input_several_lines_long);

Took me a little while to figure out.
krahn at niehs dot nih dot gov 24-Oct-2003 12:14
> strange things happen with split
> this didn't work
> $vontag $vonmonat were empty strings
...
> list ($vontag , $vonmonat) = split ('.' , $fromdate); // << bad

Split is acting exactly as it should; it splits on regular expressions.
A period is a regular expression pattern for a single character.
So, an actual period must be escaped with a backslash:  '\.'
A period within brackets is not an any-character pattern, because it does
not make sense in that context.

Beware that regular expressions can be confusing becuase there
are a few different varieties of patterns.
dalu at uni dot de 08-Oct-2003 12:26
php4.3.0

strange things happen with split

this didn't work
$vontag $vonmonat were empty strings

<?php
function ckdate($fromdate="01.01", $todate="31.12")
{
    $nowyear = date("Y");
    list ($vontag , $vonmonat) = split ('.' , $fromdate); // << bad
    $vondatum = "$nowyear-$vonmonat-$vontag";
    list ($bistag , $bismonat) = split ('.' , $todate); // << bad
    $bisdatum = "$nowyear-$bismonat-$bistag";
    $von = strtotime($vondatum);
    $bis = strtotime($bisdatum);
    $now = time();
    if (($now <= $bis) and ($now >= $von))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
?>

however this one worked perfectly

<?php
function ckdate($fromdate="01.01", $todate="31.12")
{
    $nowyear = date("Y");
    list ($vontag , $vonmonat) = split ('[.]' , $fromdate); // << good
    $vondatum = "$nowyear-$vonmonat-$vontag";
    list ($bistag , $bismonat) = split ('[.]' , $todate); // << good
    $bisdatum = "$nowyear-$bismonat-$bistag";
    $von = strtotime($vondatum);
    $bis = strtotime($bisdatum);
    $now = time();
    if (($now <= $bis) and ($now >= $von))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
?>

btw this fn checks if $now if between $fromdate and $todate
use it if you like
jeffrey at jhu dot edu 10-Jan-2003 01:51
In answer to gwyne at gmx dot net, dec 1, 2002:

For split(), when using a backslash as the delimiter, you have to *double escape* the backslash.

example:
==================================
<pre>
<?
$line = 'stuff\\\thing\doodad\\';
$linearray = split('\\\\', $line); //<--NOTE USE OF FOUR(4)backslashes
print join(":", $linearray);
?>
</pre>

==================================
output is:

<pre>
stuff::thing:doodad:
</pre>
paha at paha dot hu 21-Jul-2002 06:51
It's evident but not mentioned in the documentation that using asterisks is more restricted than in a normal regular expression.

for exaple you cannot say:

split(";*",$string);

because what if there's no ";" separator?(which is covered by this regular expression)

so you have to use at least

split(";+",$quotatxt);

in this situation.
fotw at gmx dot net 17-Jun-2002 12:50
Ups! It seems that neither explode nor split REALY takes a STRING but only a single character as a string for splitting the string.
 I found this problem in one of my codes when trying to split a string using ";\n" as breaking string. The result, only ";" was thaken... the rest of the string was ignored.
 Same when I tried to substitute "\n" by any other thing. :(
not at anythingspecial dot com 16-Jun-2002 06:48
If you need to do a split on a period make sure you escape the period out..

$ext_arr = split("\.","something.jpg");
... because
$ext_arr = split(".","something.jpg"); won't work properly.
kang at elpmis dot com 12-Jun-2002 11:30
This is a good way to display a comma delimited file with two columns.  The first column is the URL's description, the second is the actual URL.

<ul>
<?php
  $fname="relatedlinks.csv";
  $fp=fopen($fname,"r") or die("Error found.");
  $line = fgets( $fp, 1024 );
  while(!feof($fp))
  {
    list($desc,$url,$dummy) = split( ",", $line, 3 );
    print "<li>";
    print "<a href='$url'>$desc</a>";
    print "</li>\n";
    $line = fgets( $fp, 1024 );
  }
  fclose($fp);
?>
</ul>
jchart at sdccu dot net 31-May-2002 12:56
[Ed. note: Close. The pipe *is* an operator in PHP, but
the reason this fails is because it's also an operator
in the regex syntax. The distinction here is important
since a PHP operator inside a string is just a character.]

The reason your code:

$line = "12|3|Fred";
list ($msgid, $msgref, $msgtopic)=split('|', $line);

didn't work is because the "|" symbol is an operator in PHP. If you want to use the pipe symbol as a delimiter you must excape it with a back slash, "\|". You code should look like this:

$line = "12|3|Fred";
list ($msgid, $msgref, $msgtopic)=split('\|', $line);
mcgarry at tig dot com dot au 17-May-2002 03:27
split() doesn't like NUL characters within the string, it treats the first one it meets as the end of the string, so if you have data you want to split that can contain a NUL character you'll need to convert it into something else first, eg:

$line=str_replace(chr(0),'',$line);
eregi
spliti
Функции регулярных выражений POSIX


Разбивает строку в массив с помощью регулярного выражения без учета регистра

split
sql_regcase
Функции регулярных выражений POSIX
PHP Manual

spliti

(PHP 4 >= 4.0.1, PHP 5)

spliti — Разбивает строку в массив с помощью регулярного выражения без учета регистра

Описание

array spliti ( string $pattern , string $string [, int $limit = -1 ] )

Разбивает строку string в массив с помощью регулярного выражения.

Эта функция идентична функции split() за исключением того, что она игнорирует регистр символов при сравнении.

Внимание

С версии PHP 5.3.0 эта функция считается УСТАРЕВШЕЙ. Крайне не рекомендуется полагаться на эту возможность.

Список параметров

pattern

Регистронезависимое регулярное выражение.

Если вы хотите разделить строку по символам, которые являются специальными символами регулярного выражения, вам сначала нужно заэкранировать эти символы. Если вы думаете, что функция spliti() (или другая функция для работы с регулярными выражениями) делает что-то странное, пожалуйста, прочитайте файл regex.7, который находится в папке regex/ дитсрибутива PHP. Этот файл находится в формате manpage, поэтому вы можете прочитать его коммандой man /usr/local/src/regex/regex.7.

string

Строка для разделения.

limit

Если установлен limit, возвращаемый массив будет содержать максимум limit элементов, в котором последний элемент содержит всю строку string.

Возвращаемые значения

Возвращает массив строк, каждая из которых является подстрокой строки string, образованный с помощью регистронезависимого разделения регулярным выражением pattern.

Если встречаются n вхождений pattern, возвращаемый массив будет содержать n+1 элементов. К примеру, если вхождений pattern не будет найдено, то будет возвращен массив только с одним элементом. Естественно, это также справедливо, если string пустая. Если в процессе возникает ошибка, spliti() возвращает FALSE.

Примеры

Разделение строки, используя 'a' как разделитель:

Пример #1 Пример spliti()

<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>

Результат выполнения данного примера:

Array
(
  [0] =>
  [1] => BBB
  [2] => CCC
  [3] => DDD
  [4] => EEEaGGGA
)

Примечания

Замечание:

С версии PHP 5.3.0, расширение regex помечено устаревшим и заменено расширением PCRE. Вызов этой функции приведет к ошибке уровня E_DEPRECATED. Смотрите список отличий для помощи при конвертировании в PCRE.

Смотрите также

  • preg_split() - Разбивает строку по регулярному выражению
  • split() - Разбиение строки на массив по регулярному выражению
  • explode() - Разбивает строку с помощью разделителя
  • implode() - Объединяет элементы массива в строку

User Contributed Notes

jeffmixpute 25-Jan-2011 02:41
This example shows the use of spliti.
Here it splits the path of the server as it can be used further.

<?php

require_once 'Beispiel.php';
$seq = new Sequence();

$path = $_SERVER["PATH_INFO"];

echo "PATH: ".$path."<br/>";
echo "Request mode: ".$_SERVER["REQUEST_METHOD"]."<br/>";

$daten = spliti ("/", $path);

echo "get-daten[1] ".$daten[1]."<br/>";

if($_SERVER["REQUEST_METHOD"]== "POST"){
  echo "POST".$daten[1];
  $seq->setzeSequence($daten[1], $_POST["xml"]);
}
elseif($_SERVER["REQUEST_METHOD"] == "DELETE"){
  echo "DELETE".$daten[1];
  $seq->loescheSequence($daten[1]);
}
elseif($_SERVER["REQUEST_METHOD"] == "GET"){

$antwort = $seq->holeSequence($daten[1]);
  echo "antwort[0]: ".$antwort[0]."<br/>";
  foreach($antwort as $mes){
   echo "mes ".$mes."<br/>";
   }
}

?>
16-Apr-2004 11:22
When using special characters such as the tab placeholder "\t" in the split function, be careful not to escape the slash by adding a slah in front of it. To signify a tab, new line or carriage return use only one slash in front of the character. For example:

$cartes= "one\ttwo\tthree";

$tab_cartes = split("\t",$cartes );

$items = count($tab_cartes);
for ($x = 0; $x < $items; $x++)
   { echo $tab_cartes[$x] . "\n"; }
vbelon at hotmail dot com 27-Jan-2004 06:51
To split $cartes which contains data and tabulations:
Doesnt work :
$tab_cartes = split("\\t",$cartes );

But \t = char(9), so, works well:
$tab_cartes = split(Chr(9),$cartes);

Idem for :
\n = char(10)
\r = char(13)

Found in http://www.asp-magazine.com/fr/asp/blitz/blitz4.asp
split
sql_regcase
Функции регулярных выражений POSIX


Создает регулярное выражение для регистронезависимого сравнения

spliti
ssdeep
Функции регулярных выражений POSIX
PHP Manual

sql_regcase

(PHP 4, PHP 5)

sql_regcase — Создает регулярное выражение для регистронезависимого сравнения

Описание

string sql_regcase ( string $string )

Создает регулярное выражение для регистронезависимого сравнения.

Внимание

С версии PHP 5.3.0 эта функция считается УСТАРЕВШЕЙ. Крайне не рекомендуется полагаться на эту возможность.

Список параметров

string

Входная строка.

Возвращаемые значения

Создает допустимое регулярное выражение, которое будет совпадать с string, игнорируя регистр символов. Это выражение является string, в которой каждый буквенный символ заменен на символьный класс (выражение в квадратных скобках); каждый такой символьный класс содержит символы в нижнем и верхнем регистре. Другие символы остаются без изменений.

Примеры

Пример #1 Пример функции sql_regcase()

<?php
echo sql_regcase("Foo - bar.");
?>

Результат выполнения данного примера:

[Ff][Oo][Oo] - [Bb][Aa][Rr].

Это может быть использовано для получения регистронезависимых шаблонов поиска на системах, которые поддерживают только регистрозависимые регулярные выражения.

Примечания

Замечание:

С версии PHP 5.3.0, расширение regex помечено устаревшим и заменено расширением PCRE. Вызов этой функции приведет к ошибке уровня E_DEPRECATED. Смотрите список отличий для помощи при конвертировании в PCRE.

User Contributed Notes

irker at irker dot net 28-Sep-2008 02:14
&lt;?php
function mb_sql_regcase($string,$encoding=\\\'auto\\\'){
  $max=mb_strlen($item,$encoding);
  for ($i = 0; $i &lt; $max; $i++) {
    $char=mb_substr($item,$i,1,$encoding);
    $up=mb_strtoupper ($char,$encoding);
    $low=mb_strtolower($char,$encoding);
    $ret.=($up!=$low)?\\\'[\\\'.$up.$low.\\\']\\\' : $char;
  }
  return $ret;
}
?&gt;
edge at gts dot smtn dot stavropol dot ru 25-Jun-2003 06:56
if you set right locale:

setlocale(LC_CTYPE,"ru_RU.KOI8-R");

print sql_regcase("Цffnung");

will output:
"[Цц][Ff][Ff][Nn][Uu][Nn][Gg]"
spliti
ssdeep
Функции регулярных выражений POSIX


ssdeep Fuzzy Hashing

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • ssdeep Функции
    • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
    • ssdeep_fuzzy_hash — Create a fuzzy hash from a string

User Contributed Notes

There are no user contributed notes for this page.
sql_regcase
Введение
Обработка текста


Введение

ssdeep is a utility for creating and comparing fuzzy hashes or » context-triggered piecewise hashing.

Fuzzy hashing can match signatures which have "...sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length". (» ssdeep project page)

This extension provides functions for creating and comparing fuzzy hashes.

User Contributed Notes

There are no user contributed notes for this page.
ssdeep
Установка и настройка
ssdeep


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
ssdeep


Требования

This extension requires the » ssdeep library.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Это расширение » PECL не поставляется вместе с PHP.

Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pecl.php.net/package/ssdeep.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
ssdeep Функции
ssdeep


ssdeep Функции

Содержание

  • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
  • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
  • ssdeep_fuzzy_hash — Create a fuzzy hash from a string

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
ssdeep_fuzzy_compare
ssdeep


Calculates the match score between two fuzzy hash signatures

ssdeep Функции
ssdeep_fuzzy_hash_filename
ssdeep Функции
PHP Manual

ssdeep_fuzzy_compare

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures

Описание

int ssdeep_fuzzy_compare ( string $signature1 , string $signature2 )

Calculates the match score between signature1 and signature2 using » context-triggered piecewise hashing, and returns the match score.

Список параметров

signature1

The first fuzzy hash signature string.

signature2

The second fuzzy hash signature string.

Возвращаемые значения

Returns an integer from 0 to 100 on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.
ssdeep Функции
ssdeep_fuzzy_hash_filename
ssdeep Функции


Create a fuzzy hash from a file

ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
ssdeep Функции
PHP Manual

ssdeep_fuzzy_hash_filename

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file

Описание

string ssdeep_fuzzy_hash_filename ( string $file_name )

ssdeep_fuzzy_hash_filename() calculates the hash of the file specified by file_name using » context-triggered piecewise hashing, and returns that hash.

Список параметров

file_name

The filename of the file to hash.

Возвращаемые значения

Returns a string on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.
ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
ssdeep Функции


Create a fuzzy hash from a string

ssdeep_fuzzy_hash_filename
Строки
ssdeep Функции
PHP Manual

ssdeep_fuzzy_hash

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash — Create a fuzzy hash from a string

Описание

string ssdeep_fuzzy_hash ( string $to_hash )

ssdeep_fuzzy_hash() calculates the hash of to_hash using » context-triggered piecewise hashing, and returns that hash.

Список параметров

to_hash

The input string.

Возвращаемые значения

Returns a string on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.
ssdeep_fuzzy_hash_filename
Строки
ssdeep Функции


Строки

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Обработка строк
    • addcslashes — Экранирует cтроку слэшами в стиле языка C
    • addslashes — Экранирует строку с помощью слэшей
    • bin2hex — Преобразует бинарные данные в шестнадцатиричное представление
    • chop — Псевдоним rtrim
    • chr — Возвращает символ по его коду
    • chunk_split — Разбивает строку на фрагменты
    • convert_cyr_string — Преобразует строку из одной кириллической кодировки в другую
    • convert_uudecode — Декодирует строку из формата uuencode в обычный вид
    • convert_uuencode — Кодирует строку в формат uuencode
    • count_chars — Возвращает информацию о символах, входящих в строку
    • crc32 — Вычисляет полином CRC32 для строки
    • crypt — Необратимое хэширование строки
    • echo — Выводит одну или более строк
    • explode — Разбивает строку с помощью разделителя
    • fprintf — Записывает отформатированную строку в поток
    • get_html_translation_table — Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities
    • hebrev — Преобразует текст на иврите из логической кодировки в визуальную
    • hebrevc — Преобразует текст на иврите из логической кодировки в визуальную с преобразованием перевода строки
    • hex2bin — Преобразует шестнадцатеричные данные в двоичные
    • html_entity_decode — Преобразует все HTML-сущности в соответствующие символы
    • htmlentities — Преобразует все возможные символы в соответствующие HTML-сущности
    • htmlspecialchars_decode — Преобразует специальные HTML-сущности обратно в соответствующие символы
    • htmlspecialchars — Преобразует специальные символы в HTML-сущности
    • implode — Объединяет элементы массива в строку
    • join — Псевдоним implode
    • lcfirst — Преобразует первый символ строки в нижний регистр
    • levenshtein — Вычисляет расстояние Левенштейна между двумя строками
    • localeconv — Возвращает информацию о числовых форматах
    • ltrim — Удаляет пробелы (или другие символы) из начала строки
    • md5_file — Возвращает MD5-хэш файла
    • md5 — Возвращает MD5-хэш строки
    • metaphone — Возвращает ключ metaphone для строки
    • money_format — Форматирует число как денежную величину
    • nl_langinfo — Возвращает информацию о языке и локали
    • nl2br — Вставляет HTML-код разрыва строки перед каждым переводом строки
    • number_format — Форматирует число с разделением групп
    • ord — Возвращает ASCII-код символа
    • parse_str — Разбирает строку в переменные
    • print — Выводит строку
    • printf — Выводит отформатированную строку
    • quoted_printable_decode — Преобразует строку, закодированную методом quoted-printable в 8-битовую строку
    • quoted_printable_encode — Кодирует 8-битную строку в с помощью метода quoted-printable
    • quotemeta — Экранирует специальные символы
    • rtrim — Удаляет пробелы (или другие символы) из конца строки
    • setlocale — Устанавливает настройки локали
    • sha1_file — Возвращает SHA1-хэш файла
    • sha1 — Возвращает SHA1-хэш строки
    • similar_text — Вычисляет степень похожести двух строк
    • soundex — Возвращает ключ soundex для строки
    • sprintf — Возвращает отформатированную строку
    • sscanf — Разбирает строку в соответствии с заданным форматом
    • str_getcsv — Выполняет разбор CSV-строки в массив
    • str_ireplace — Регистро-независимый вариант функции str_replace
    • str_pad — Дополняет строку другой строкой до заданной длины
    • str_repeat — Возвращает повторяющуюся строку
    • str_replace — Заменяет все вхождения строки поиска на строку замены
    • str_rot13 — Выполняет преобразование ROT13 над строкой
    • str_shuffle — Переставляет символы в строке случайным образом
    • str_split — Преобразует строку в массив
    • str_word_count — Возвращает информацию о словах, входящих в строку
    • strcasecmp — Бинарно-безопасное сравнение строк без учета регистра
    • strchr — Псевдоним strstr
    • strcmp — Бинарно-безопасное сравнение строк
    • strcoll — Сравнение строк с учетом текущей локали
    • strcspn — Возвращает длину участка в начале строки, не соответствующего маске
    • strip_tags — Удаляет HTML и PHP-теги из строки
    • stripcslashes — Удаляет экранирование символов, произведенное функцией addcslashes
    • stripos — Возвращает позицию первого вхождения подстроки без учета регистра
    • stripslashes — Удаляет экранирование символов
    • stristr — Регистро-независимый вариант функции strstr
    • strlen — Возвращает длину строки
    • strnatcasecmp — Сравнение строк без учета регистра с использованием алгоритма "natural order"
    • strnatcmp — Сравнение строк с использованием алгоритма "natural order"
    • strncasecmp — Бинарно-безопасное сравнение первых n символов строк без учета регистра
    • strncmp — Бинарно-безопасное сравнение первых n символов строк
    • strpbrk — Ищет в строке любой символ из заданного набора
    • strpos — Возвращает позицию первого вхождения подстроки
    • strrchr — Находит последнее вхождение символа в строке
    • strrev — Переворачивает строку задом наперед
    • strripos — Возвращает позицию последнего вхождения подстроки без учета регистра
    • strrpos — Возвращает позицию последнего вхождения подстроки в строке
    • strspn — Возвращает длину участка в начале строки, полностью соответствующего маске
    • strstr — Находит первое вхождение подстроки
    • strtok — Разбивает строку на токены
    • strtolower — Преобразует строку в нижний регистр
    • strtoupper — Преобразует строку в верхний регистр
    • strtr — Преобразует заданные символы или заменяет подстроки
    • substr_compare — Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
    • substr_count — Возвращает число вхождений подстроки
    • substr_replace — Заменяет часть строки
    • substr — Возвращает подстроку
    • trim — Удаляет пробелы (или другие символы) из начала и конца строки
    • ucfirst — Преобразует первый символ строки в верхний регистр
    • ucwords — Преобразует в верхний регистр первый символ каждого слова в строке
    • vfprintf — Записывает отформатированную строку в поток
    • vprintf — Выводит отформатированную строку
    • vsprintf — Возвращает отформатированную строку
    • wordwrap — Переносит строку по указанному количеству символов

User Contributed Notes

There are no user contributed notes for this page.
ssdeep_fuzzy_hash
Введение
Обработка текста


Введение

Эти функции предназначены для выполнения различных манипуляций со строками. Более специализированные функции см. в разделах, посвященных регулярным выражениям и обработке URL.

Для получения общей информации о работе со строками, особенно об использовании одиночных, двойных кавычек и экранировании символов, смотрите главу Строки в разделе Типы .

User Contributed Notes

chris at bjelleklang dot org 27-Oct-2010 05:00
Please note that these String functions does not handle multibyte encodings such as UTF-8. Use the functions found in Multibyte String for these encodings.
Строки
Установка и настройка
Строки


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Строки


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

CRYPT_SALT_LENGTH integer
CRYPT_STD_DES integer
CRYPT_EXT_DES integer
CRYPT_MD5 integer
CRYPT_BLOWFISH integer
HTML_SPECIALCHARS (integer)
HTML_ENTITIES (integer)
ENT_COMPAT (integer)
ENT_QUOTES (integer)
ENT_NOQUOTES (integer)
ENT_IGNORE (integer)
ENT_SUBSTITUTE (integer)
ENT_DISALLOWED (integer)
ENT_HTML401 (integer)
ENT_XML1 (integer)
ENT_XHTML (integer)
ENT_HTML5 (integer)
CHAR_MAX (integer)
LC_CTYPE (integer)
LC_NUMERIC (integer)
LC_TIME (integer)
LC_COLLATE (integer)
LC_MONETARY (integer)
LC_ALL (integer)
LC_MESSAGES (integer)
STR_PAD_LEFT (integer)
STR_PAD_RIGHT (integer)
STR_PAD_BOTH (integer)

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Обработка строк
Строки


Обработка строк

Смотрите также

Для получения информации о более сложной обработке строк обратитесь к разделам о регулярных выражениях: POSIX-совместимых и Perl-совместимых.

Содержание

  • addcslashes — Экранирует cтроку слэшами в стиле языка C
  • addslashes — Экранирует строку с помощью слэшей
  • bin2hex — Преобразует бинарные данные в шестнадцатиричное представление
  • chop — Псевдоним rtrim
  • chr — Возвращает символ по его коду
  • chunk_split — Разбивает строку на фрагменты
  • convert_cyr_string — Преобразует строку из одной кириллической кодировки в другую
  • convert_uudecode — Декодирует строку из формата uuencode в обычный вид
  • convert_uuencode — Кодирует строку в формат uuencode
  • count_chars — Возвращает информацию о символах, входящих в строку
  • crc32 — Вычисляет полином CRC32 для строки
  • crypt — Необратимое хэширование строки
  • echo — Выводит одну или более строк
  • explode — Разбивает строку с помощью разделителя
  • fprintf — Записывает отформатированную строку в поток
  • get_html_translation_table — Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities
  • hebrev — Преобразует текст на иврите из логической кодировки в визуальную
  • hebrevc — Преобразует текст на иврите из логической кодировки в визуальную с преобразованием перевода строки
  • hex2bin — Преобразует шестнадцатеричные данные в двоичные
  • html_entity_decode — Преобразует все HTML-сущности в соответствующие символы
  • htmlentities — Преобразует все возможные символы в соответствующие HTML-сущности
  • htmlspecialchars_decode — Преобразует специальные HTML-сущности обратно в соответствующие символы
  • htmlspecialchars — Преобразует специальные символы в HTML-сущности
  • implode — Объединяет элементы массива в строку
  • join — Псевдоним implode
  • lcfirst — Преобразует первый символ строки в нижний регистр
  • levenshtein — Вычисляет расстояние Левенштейна между двумя строками
  • localeconv — Возвращает информацию о числовых форматах
  • ltrim — Удаляет пробелы (или другие символы) из начала строки
  • md5_file — Возвращает MD5-хэш файла
  • md5 — Возвращает MD5-хэш строки
  • metaphone — Возвращает ключ metaphone для строки
  • money_format — Форматирует число как денежную величину
  • nl_langinfo — Возвращает информацию о языке и локали
  • nl2br — Вставляет HTML-код разрыва строки перед каждым переводом строки
  • number_format — Форматирует число с разделением групп
  • ord — Возвращает ASCII-код символа
  • parse_str — Разбирает строку в переменные
  • print — Выводит строку
  • printf — Выводит отформатированную строку
  • quoted_printable_decode — Преобразует строку, закодированную методом quoted-printable в 8-битовую строку
  • quoted_printable_encode — Кодирует 8-битную строку в с помощью метода quoted-printable
  • quotemeta — Экранирует специальные символы
  • rtrim — Удаляет пробелы (или другие символы) из конца строки
  • setlocale — Устанавливает настройки локали
  • sha1_file — Возвращает SHA1-хэш файла
  • sha1 — Возвращает SHA1-хэш строки
  • similar_text — Вычисляет степень похожести двух строк
  • soundex — Возвращает ключ soundex для строки
  • sprintf — Возвращает отформатированную строку
  • sscanf — Разбирает строку в соответствии с заданным форматом
  • str_getcsv — Выполняет разбор CSV-строки в массив
  • str_ireplace — Регистро-независимый вариант функции str_replace
  • str_pad — Дополняет строку другой строкой до заданной длины
  • str_repeat — Возвращает повторяющуюся строку
  • str_replace — Заменяет все вхождения строки поиска на строку замены
  • str_rot13 — Выполняет преобразование ROT13 над строкой
  • str_shuffle — Переставляет символы в строке случайным образом
  • str_split — Преобразует строку в массив
  • str_word_count — Возвращает информацию о словах, входящих в строку
  • strcasecmp — Бинарно-безопасное сравнение строк без учета регистра
  • strchr — Псевдоним strstr
  • strcmp — Бинарно-безопасное сравнение строк
  • strcoll — Сравнение строк с учетом текущей локали
  • strcspn — Возвращает длину участка в начале строки, не соответствующего маске
  • strip_tags — Удаляет HTML и PHP-теги из строки
  • stripcslashes — Удаляет экранирование символов, произведенное функцией addcslashes
  • stripos — Возвращает позицию первого вхождения подстроки без учета регистра
  • stripslashes — Удаляет экранирование символов
  • stristr — Регистро-независимый вариант функции strstr
  • strlen — Возвращает длину строки
  • strnatcasecmp — Сравнение строк без учета регистра с использованием алгоритма "natural order"
  • strnatcmp — Сравнение строк с использованием алгоритма "natural order"
  • strncasecmp — Бинарно-безопасное сравнение первых n символов строк без учета регистра
  • strncmp — Бинарно-безопасное сравнение первых n символов строк
  • strpbrk — Ищет в строке любой символ из заданного набора
  • strpos — Возвращает позицию первого вхождения подстроки
  • strrchr — Находит последнее вхождение символа в строке
  • strrev — Переворачивает строку задом наперед
  • strripos — Возвращает позицию последнего вхождения подстроки без учета регистра
  • strrpos — Возвращает позицию последнего вхождения подстроки в строке
  • strspn — Возвращает длину участка в начале строки, полностью соответствующего маске
  • strstr — Находит первое вхождение подстроки
  • strtok — Разбивает строку на токены
  • strtolower — Преобразует строку в нижний регистр
  • strtoupper — Преобразует строку в верхний регистр
  • strtr — Преобразует заданные символы или заменяет подстроки
  • substr_compare — Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
  • substr_count — Возвращает число вхождений подстроки
  • substr_replace — Заменяет часть строки
  • substr — Возвращает подстроку
  • trim — Удаляет пробелы (или другие символы) из начала и конца строки
  • ucfirst — Преобразует первый символ строки в верхний регистр
  • ucwords — Преобразует в верхний регистр первый символ каждого слова в строке
  • vfprintf — Записывает отформатированную строку в поток
  • vprintf — Выводит отформатированную строку
  • vsprintf — Возвращает отформатированную строку
  • wordwrap — Переносит строку по указанному количеству символов

User Contributed Notes

Tomek Rychtyk 08-Feb-2012 09:58
Get the intersection of two strings using array_intersect

<?php

function string_intersect($string1, $string2)
{
    $array1 = $array2 = array();

    for($i = 0, $j = 0, $s1_len = strlen($string1), $s2_len = strlen($string2);($i < $s1_len) || ($j < $s2_len); $i++, $j++) {
        if($i < $s1_len) {
            $array1[] = $string1[$i];
        }
        if($j < $s2_len) {
            $array2[] = $string2[$j];
        }
    }

    return implode('', array_intersect($array1, $array2));
}

?>

For more advanced comparison you can use array_uintersect as well.
Peter -the pete- de Pijd 14-Oct-2009 05:01
get the intersection of two strings; may not have optimal performance

<?php
function mb_string_intersect($string1, $string2, $minChars = 5)
{
    assert('$minChars > 1');

    $string1 = trim($string1);
    $string2 = trim($string2);

    $length1 = mb_strlen($string1);
    $length2 = mb_strlen($string2);

    if ($length1 > $length2) {
        // swap variables, shortest first

        $string3 = $string1;
        $string1 = $string2;
        $string2 = $string3;

        $length3 = $length1;
        $length1 = $length2;
        $length2 = $length3;

        unset($string3, $length3);
    }

    if ($length2 > 255) {
        return null; // to much calculation required
    }

    for ($l = $length1; $l >= $minChars; --$l) { // length
        for ($i = 0, $ix = $length1 - $l; $i <= $ix; ++$i) { // index
            $substring1 = mb_substr($string1, $i, $l);
            $found = mb_strpos($string2, $substring1);
            if ($found !== false) {
                return trim(mb_substr($string2, $found, mb_strlen($substring1)));
            }
        }
    }

    return null;
}
echo mb_string_intersect("hello spencer", "hey spencer how are you?"); // output "spencer"
?>
Stephen Dewey 19-Nov-2008 05:33
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.

Works in PHP >= 5.

(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)

<?php

// Returns all of $haystack up to (but excluding) the $n_occurrence occurrence of $needle. Therefore:
//        If there are < $n_occurrence occurrences of $needle in $haystack, the entire string will be returned.
//        If there are >= $n_occurrence occurrences of $needle in $haystack, the returned string will end before the $n_occurrence'th needle.
// This function only makes sense for $n_occurrence >= 1
function nsubstr($needle, $haystack, $n_occurrence)
{
    // After exploding by $needle, every entry in $arr except (possibly) part of the last entry should have its content returned.
    $arr = explode($needle,$haystack,$n_occurrence);
    // Examine last entry in $arr. If it contains $needle, cut out all text except for the text before $needle.
    $last = count($arr) - 1;
    $pos_in_last = strpos($arr[$last],$needle);

    if ($pos_in_last !== false)
        $arr[$last] = substr($arr[$last],0,$pos_in_last);

    return implode($needle,$arr);
}

$string = 'd24jkdslgjldk2424jgklsjg24jskgldjk24';

print 'S:  ' . $string . '<br>';
print '1: ' . nsubstr('24',$string,1) . '<br>';
print '2: ' . nsubstr('24',$string,2) . '<br>';
print '3: ' . nsubstr('24',$string,3) . '<br>';
print '4: ' . nsubstr('24',$string,4) . '<br>';
print '5: ' . nsubstr('24',$string,5) . '<br>';
print '6: ' . nsubstr('24',$string,6) . '<br>';
print '7: ' . nsubstr('24',$string,7) . '<br>';

/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/

?>

Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using <br>, and then you can use this function to only return text up to the N'th <br>.

You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().

See example:

<?php

$text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.';

$wrapped_text = wordwrap($text,100,'<br>',true);

$three_lines = nsubstr('<br>',$wrapped_text,3);

print '<br><br>' . $three_lines;

$four_lines = nsubstr('<br>',$wrapped_text,4);

print '<br><br>' . $four_lines;

/*
prints:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida

*/

?>
kriskra at gmail dot com 04-Aug-2008 04:10
In reference to Moe... best random string function
<?php
function random_string($l = 10){
    $c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";
    for(;$l > 0;$l--) $s .= $c{rand(0,strlen($c))};
    return str_shuffle($s);
}
?>
Salomon 28-Mar-2008 02:43
If you want to indent a block of text with $level tabs, you can use

function str_indent($level, $text) {
    return str_repeat("\t", $level).str_replace("\n", "\n".str_repeat("\t", $level), $text);
}
Verdauga 19-Mar-2008 06:06
Just a note in regards to bloopletech a few posts down:

The word "and" should not be used when converting numbers to text.  "And" (at least in US English) should only be used to indicate the decimal place.

Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
geek dot de at gmail dot com 07-Jan-2008 03:18
This took me quite some time to figure out and it is so obvious. So, I hope it helps someone out there like it would have helped me if I would have found it on this page:

I wanted to read a binary file and write it out with some modified bytes with their hex values. The easiest way I could come up with was the following:

read the file line by line, e.g. 400 bytes and then chuck it into an array with e.g.

<?php
$handle = @fopen("/path/to/file.bin", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer[] = fgets($handle, 400);
    }
    fclose($handle);
    $buffer[0][0] = chr(hexdec("FF")); // set the first byte to 0xFF
}
// write out the file from the array ...
?>

One could write a function for that, so that One can write a string of bytes. Don't have time for this now but you should get the idea.
m 26-Jul-2007 05:10
Regarding the code for the function beginsWith($str, $sub), I found that it has problems when only one character is present after the string searched for. I found that this works better instead:

<?php
function beginsWith($str, $sub) {
    return (strncmp($str, $sub, strlen($sub)) == 0);
}
?>
Moe 10-Jul-2007 06:44
In responce to mike here is a better random string function

<?php
    function random_string($max = 20){
        $chars = "abcdefghijklmnopqrstuvwxwz0123456789_";
        for($i = 0; $i < $max; $i++){
            $rand_key = mt_rand(0, strlen($chars));
            $string  .= substr($chars, $rand_key, 1);
        }
        return str_shuffle($string);
    }
?>
mike &#34;eyes&#34; moe 17-Jun-2007 05:59
Here is a truly random string generator it uses the most common string functions it will work on anywhere.

<?php
    function random_string($max = 20){
        $chars = explode(" ", "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9");
        for($i = 0; $i < $max; $i++){
            $rnd = array_rand($chars);
            $rtn .= base64_encode(md5($chars[$rnd]));
        }
        return substr(str_shuffle(strtolower($rtn)), 0, $max);
    }
?>
bloopletech at gmail dot com 22-May-2007 06:05
[Editor's Note: Remember that number names are locale-specific. Thus in the US 1,000,000,000 is called a billion, while in other countries this might be different (ie. miljard in Dutch). This function provides support only for the US locale]

If you want to convert a number, (int or float) to full spoken text, then you can use my num2text converter, at http://bloople.net/num2text

Examples:
40000 => forty thousand
1,796,706 => one million, seven hundred and ninety-six thousand, seven hundred and six.

If works for positive an negative integers/floats/doubles. The code is only a page long, and you don't have to install any modules or anything.

I hope this comes in handy for somebody!
benjamin at webbutvecklarna dot se 25-Mar-2007 04:23
An update to admin at fivestarbuy dot com's StrParse. Since php5.2.x the occurance of an object in the vardata will cause a "Catchable fatal error". Previously it has failed silently, so I added nullification of present objects.
I also updated comments to be more specific, I hope that's ok with you, admin at fivestarbuy dot com:

<?php
function StrParse($str,$vardata) {

# Variables present in $str is replaced by values of variables in $vardata
# typical use:
# $vardata = get_defined_vars();
# $str = some template code with variables present.
# uncomment the echo line to debug.

$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
   $myvar=$getvarkeys[$x];
   if(is_object($vardata[$myvar])) $vardata[$myvar] = null;
   #echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
   $ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;
}
?>
beggining pro 02-Aug-2006 11:00
Well for you egold users out ther I wrote this to just return the balance ONLY
If anyone knows a better way to write this lemme know as im a novice

    function _GetBalance($from, $frompass) {
   $defined_vars = get_defined_vars();

   $_url = 'https://www.e-gold.com/acct/balance.asp';

        $_url_p = "AccountID=" . $from . "&PassPhrase=" . $frompass ."";
           $ch = curl_init();

   curl_setopt($ch, CURLOPT_POST,1);
   curl_setopt($ch, CURLOPT_POSTFIELDS,$_url_p);
   curl_setopt($ch, CURLOPT_URL,$_url);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
   curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
   $content = curl_exec ($ch);

   curl_close ($ch);
$content=strtolower($content);
$content=strstr($content,"</select></font></th></form></tr>");
$content=strip_tags($content);
$content=strrev($content);
$content=strstr($content,"eseht :eton");
$content=str_replace("eseht :eton","",$content);
$content=ltrim($content);
$content=rtrim($content);
$content=substr($content,0,11);
$content=strrev($content);
$content=ltrim($content);

   return $content;

    }
admin at rotarymulundeast dot org 30-Jul-2006 03:16
Here's an easier way to find nth...

function nth($numbex){
  if ($numbex%10 == 1 && $numbex%100 != 11) $sth='st';
  elseif ($numbex%10 == 2 && $numbex%100 != 12) $sth='nd';
  elseif ($numbex%10 == 3 && $numbex%100 != 13) $sth='rd';
  else $sth = 'th';
  return $sth;
}

there is is no need to check if the user has entered a non-integer as we may be using this function for expressing variables as well eg. ith value of x , nth root of z ,etc...
heavyraptor 27-Jul-2006 08:17
I think that
administrador(ensaimada)sphoera(punt)com's function is
too complicated. It's easier with regular expressions.
So I made this function, it isn't really the same,
it's even better because it returns an array with all the
matches found
If there are no matches, false is returned.

<?php
// bool/array str_between( string str, string
start_str, string end_str )
function str_between($str,$start,$end) {
  if (preg_match_all('/' . preg_quote($start) . '(.*?)' . preg_quote($end) . '/',$str,$matches)) {
   return $matches[1];
  }
  // no matches
  return false;
}
?>

Enjoy
da (dot) blayde (a t) gmail (dot) com 19-Jul-2006 10:52
Sometimes when converting integers to strings, it looks better to have the number spelled out. I wrote this function that converts integers from -999 to 999 into spelled out strings:

function int2str($int=0){
 $doOnes=true;
 $neg=$int<0?true:false;
 $int=abs(round($int));
 $str='';
 switch(strlen($int)){
  case 1:$int='0'.$int;
  case 2:$int='0'.$int;
  case 3:$int.='';break;
  default:return $int;
 }
 switch($int{0}){
  case 1:$str.='one-hundred-';break;
  case 2:$str.='two-hundred-';break;
  case 3:$str.='three-hundred-';break;
  case 4:$str.='four-hundred-';break;
  case 5:$str.='five-hundred-';break;
  case 6:$str.='six-hundred-';break;
  case 7:$str.='seven-hundred-';break;
  case 8:$str.='eight-hundred-';break;
  case 9:$str.='nine-hundred-';break;
 }
 switch($int{1}){
  case 1:
   switch($int{2}){
    case 0:$str.='ten-';break;
    case 1:$str.='eleven-';break;
    case 2:$str.='twelve-';break;
    case 3:$str.='thirteen-';break;
    case 4:$str.='fourteen-';break;
    case 5:$str.='fifteen-';break;
    case 6:$str.='sixteen-';break;
    case 7:$str.='seventeen-';break;
    case 8:$str.='eighteen-';break;
    case 9:$str.='nineteen-';break;
   }
   $doOnes=false;
  break;
  case 2:$str.='twenty-';break;
  case 3:$str.='thirty-';break;
  case 4:$str.='forty-';break;
  case 5:$str.='fifty-';break;
  case 6:$str.='sixty-';break;
  case 7:$str.='seventy-';break;
  case 8:$str.='eighty-';break;
  case 9:$str.='ninety-';break;
 }
 if($doOnes){
  switch($int{2}){
   case 1:$str.='one-';break;
   case 2:$str.='two-';break;
   case 3:$str.='three-';break;
   case 4:$str.='four-';break;
   case 5:$str.='five-';break;
   case 6:$str.='six-';break;
   case 7:$str.='seven-';break;
   case 8:$str.='eight-';break;
   case 9:$str.='nine-';break;
 }}
 $str=substr($str,0,-1);
 if($neg){
  $str='negative '.$str;
 }
 if($int=='000'){
  $str='zero';
 }
 return $str;
}

Hope this helps someone,
-Blayde
mickycole at hotmail dot com 19-Jul-2006 12:01
In responce to James Baker's sencence case function.
Great function however i would make one slight variation being that it doesn't take into account the fact that a capital is required after a new paragraph so i modified it to check for /r and /n as follows:
<?PHP
/*/ Author : James Baker /*/
function sentenceCase($s){
   $str = strtolower($s);
   $cap = true;

   for($x = 0; $x < strlen($str); $x++){
       $letter = substr($str, $x, 1);
       if($letter == "." || $letter == "!" || $letter == "?" || $letter == "\n" || $letter == "\r"){
           $cap = true;
       }elseif($letter != " " && $cap == true){
           $letter = strtoupper($letter);
           $cap = false;
       }

       $ret .= $letter;
   }

   return $ret;
}
?>
administrador(ensaimada)sphoera(punt)com 02-Mar-2006 06:10
I've prepared this simple function to obtain a string delimited between tags (not only XML tags!). Anybody needs something like this?.

<?php

function get_string_between($string, $start, $end){
    $string = " ".$string;
     $ini = strpos($string,$start);
     if ($ini == 0) return "";
     $ini += strlen($start);
     $len = strpos($string,$end,$ini) - $ini;
     return substr($string,$ini,$len);
}

$string = "this [custom] function is useless!!";
echo get_string_between($string,"[","]");
// must return "custom";
?>
more functions at http://www.sphoera.com
SteveRusin 24-Feb-2006 11:00
The functions below:

function beginsWith( $str, $sub )
function endsWith( $str, $sub )

Are correct, but flawed.  You'd need to use the === operator instead:

function beginsWith( $str, $sub ) {
   return ( substr( $str, 0, strlen( $sub ) ) === $sub );
}
function endsWith( $str, $sub ) {
   return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}

Otherwise, endsWith would return "foobar.0" ends with ".0" as well as "0" or "00" or any amount of zeros because numerically .0 does equal 0.
navarr at gmail dot com 20-Dec-2005 06:24
stripos for PHP4.x

<?php
  function stripos($haystack,$needle) {
    return strpos(strtoupper($haystack),strtoupper($needle));
  }
?>
dkflbk at nm dot ru 11-Dec-2005 08:58
I needed str2bin() function for one of my project, so if some one else is want to use it, have fun :)

<?php
/**
 *    Returns an ASCII string containing
 *    the binary representation of the input data .
**/
function str2bin($str, $mode=0) {
    $out = false;
    for($a=0; $a < strlen($str); $a++) {
        $dec = ord(substr($str,$a,1));
        $bin = '';
        for($i=7; $i>=0; $i--) {
            if ( $dec >= pow(2, $i) ) {
                $bin .= "1";
                $dec -= pow(2, $i);
            } else {
                $bin .= "0";
            }
        }
        /* Default-mode */
        if ( $mode == 0 ) $out .= $bin;
        /* Human-mode (easy to read) */
        if ( $mode == 1 ) $out .= $bin . " ";
        /* Array-mode (easy to use) */
        if ( $mode == 2 ) $out[$a] = $bin;
    }
    return $out;
}
?>
admin at fivestarbuy dot com 21-Oct-2005 09:18
This example lets you parse an unparsed strings variables. Warning: This could cause security leaks if you allow users to pass $variables through this engine. I recommend only using this for your Content Management System.

<?
$mytime=time();
$mydog="My Dog Ate My PHP!";

# Your Parsing String:
$s1 = 'Hyphen Variable Preserving: $mytime, and $mydog';
echo "Before: <br><br>$s1<br><br>";

# Remember, wherever you define this, it will not be defined GLOBAL into the function
# which is why we define it here. Defining it global could lead to security issues.
$vardata=get_defined_vars();

# Parse the string
$s1 = StrParse($s1,$vardata);

echo "After: <br><br>$s1";

function StrParse($str,$vardata) {
# Takes a string, or piece of data, that contains PHP Variables

 # For example, unparsed variables like:  Test using time: $mytime
 # This example shows $mytime, and not the actual variable value.
 # The end result shows the actual variable value of $mytime.

 # This is useful for building a content management system,
 # and directing your variables into your content data,
 # where content is stored in a file or database, unparsed.
 # Of course this could slow down page loads, but it's a good way
 # to parse data from current variables into your loaded new data
 # making it compatible.

# Then the variables are replaced with the actual variable..
$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
    $myvar=$getvarkeys[$x];
    #echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
    $ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;

}

?>
17-Oct-2005 03:27
to: james dot d dot baker at gmail dot com

PHP has a builtin function  for doing what your function does,

http://php.net/ucfirst
http://php.net/ucwords
14-Oct-2005 08:24
Updated; used to test for input as an array, should have been a string, added some validation of the input while I was at it.  Enjoy.

<?php
/*----------        Directory Tree to Array        ----------//
  Takes base directory, returns an associative array
       containing each directory name as an associative key
       and each file as an indexed entry in the appropriate
       directory.
  If no path is provided, it uses the current directory
  If $style == 1, it will return a sorted, non-associative
       array

  By Peter Dolan
  www.peterd.net
  Updated 2005-10-12

  Use it as much as you like for whatever
  For my own entertainment, please let me know if you do
//-----------------------------------------------------------*/
function dirTreeToArray( $path = "./", $style="0" ) {
     if ( !is_string($path) or !($style==0 or $style==1) ) die("Improper arguments in function dirTreeToArray(string \$path, \$style = {0, 1})");
     else {
        $path = trim($path);
        $path = str_replace("\\", "/", $path);
        if( '/' == $path{strlen($path)-1} || '\'' == $path{strlen($path)-1} ) $path = substr($path, 0, strlen($path)-1);
     }
     $tree = array();
     $arrayPointer = & $tree;
   if ( $handle = opendir($path) ) {
       while ( $fileName = readdir($handle) ) {
             if ( $fileName != "." and $fileName != ".." ) {
                       $newPath = "$path/$fileName";        // Used for testing directory or file property
                 if ( is_dir($newPath) ) {
                   $dummyPointer = & $arrayPointer;        // Save the current pointer
                     if ( $style == 0 ) $arrayPointer = & $arrayPointer[$fileName];    // Drop the pointer into a subdirectory
                     elseif ( $style == 1 ) $arrayPointer = & $arrayPointer[];        // Drop the pointer into a subdirectory
                     $arrayPointer = dirTreeToArray($newPath, $style);            // Process the new subdirectory
                   if ( $style == 1 ) sort($arrayPointer);    // Sort it if we're in a non-associative mode
                     $arrayPointer = & $dummyPointer;        // Bring the pointer back up a level
               }
                 elseif ( is_file($newPath) ) $arrayPointer[] = $fileName;    // Enter the files
           }
       }
               return $tree;
   }
   else die("Failed to open directory $path in function dirTreeToArray(string \$path, \$style = {0, 1})");
}
?>
tim_meredith at s4s dot org 13-Oct-2005 01:32
--Convert MSWord Quotes--
Use this before any conversion to HTML entities or characters to clean up a form entry cut and pasted from MSWord.

function fixword($scratch)
{
    $start=chr(226).chr(128);
    $word=array();$fixword=array();
    $word[]=$start.chr(152);$fixword[]="'";
    $word[]=$start.chr(153);$fixword[]="'";
    $word[]=$start.chr(156);$fixword[]="\"";
    $word[]=$start.chr(157);$fixword[]="\"";
    return str_replace($word, $fixword, $scratch);
}
webmaster at cafe-clope dot net 13-Aug-2005 04:40
A comprehensive concatenation function, that works with array and strings

<?php
function str_cat() {
  $args = func_get_args() ;

  // Asserts that every array given as argument is $dim-size.
  // Keys in arrays are stripped off.
  // If no array is found, $dim stays unset.
  foreach($args as $key => $arg) {
    if(is_array($arg)) {
      if(!isset($dim))
        $dim = count($arg) ;
      elseif($dim != count($arg))
        return FALSE ;
      $args[$key] = array_values($arg) ;
    }
  }

  // Concatenation
  if(isset($dim)) {
    $result = array() ;
    for($i=0;$i<$dim;$i++) {
      $result[$i] = '' ;
      foreach($args as $arg)
        $result[$i] .= ( is_array($arg) ? $arg[$i] : $arg ) ;
    }
    return $result ;
  } else {
    return implode($args) ;
  }
}
?>

A simple example :

<?php
str_cat(array(1,2,3), '-', array('foo' => 'foo', 'bar' => 'bar', 'noop' => 'noop')) ;
?>

will return :
Array (
  [0] => 1-foo
  [1] => 2-bar
  [2] => 3-noop
)

More usefull :

<?php
$myget = $_GET ; // retrieving previous $_GET values
$myget['foo'] = 'b a r' ; // changing one value
$myget = str_cat(array_keys($myget), '=', array_map('rawurlencode', array_values($myget))) ;
$querystring = implode(ini_get('arg_separator.output'), $myget)) ;
?>

will return a valid querystring with some values changed.

Note that <?php str_cat('foo', '&', 'bar') ; ?> will return 'foo&bar', while <?php str_cat(array('foo'), '&', 'bar') ; ?> will return array(0 => foo&bar)
t0russ at gmail dot com 14-Jun-2005 10:38
to kristin at greenaple dot on dot ca:
thanx for sharing.
your function in recursive form proved to be slightly faster and it returns false (as it should) when the character is not found instead of number 0:
<?php
function strnposr($haystack, $needle, $occurance, $pos = 0) {
    return ($occurance<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurance-1,strpos($haystack, $needle, $pos) + 1);
}
?>
rh at richardhoward dot net 05-Jun-2005 11:41
<?php
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.

Any string can (usually) be thought of as being in one of these 'modes':

pure = what the user actually typed / what you want to see on the page /
       what is actually stored in the DB
gpc  = incoming GET, POST or COOKIE data
sql  = escaped for passing safely to RDBMS via SQL (also, data from DB
       queries and file reads if you have magic_quotes_runtime on--which
       is rare)
html = safe for html display (htmlentities applied)

Always knowing what mode your string is in--using these methods to
convert between modes--will prevent SQL injection and cross-site scripting.

This class refers to its own namespace (so it can work in PHP 4--there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.

Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST['username']);
*/

//This sets SQL escaping to use slashes; for Sybase(/MSSQL)-style escaping
// ( ' --> '' ), set to true.
define('STR_SYBASE', false);

class Str {
    function gpc2sql($gpc, $maxLength = false)
    {
        return Str::pure2sql(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2html($gpc, $maxLength = false)
    {
        return Str::pure2html(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2pure($gpc)
    {
        if (ini_get('magic_quotes_sybase'))
            $pure = str_replace("''", "'", $gpc);
        else $pure = get_magic_quotes_gpc() ? stripslashes($gpc) : $gpc;
        return $pure;
    }
    function html2pure($html)
    {
        return html_entity_decode($html);
    }
    function html2sql($html, $maxLength = false)
    {
        return Str::pure2sql(Str::html2pure($html), $maxLength);
    }
    function pure2html($pure, $maxLength = false)
    {
        return $maxLength ? htmlentities(substr($pure, 0, $maxLength))
                          : htmlentities($pure);
    }
    function pure2sql($pure, $maxLength = false)
    {
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return (STR_SYBASE)
               ? str_replace("'", "''", $pure)
               : addslashes($pure);
    }
    function sql2html($sql, $maxLength = false)
    {
        $pure = Str::sql2pure($sql);
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return Str::pure2html($pure);
    }
    function sql2pure($sql)
    {
        return (STR_SYBASE)
               ? str_replace("''", "'", $sql)
               : stripslashes($sql);
    }
}
?>
james dot d dot baker at gmail dot com 27-May-2005 10:45
<?php
/*
Written By James Baker, May 27th 2005

sentenceCase($string);
    $string: The string to convert to sentence case.

Converts a string into proper sentence case (First letter of each sentance capital, all the others smaller)

Example Usage:
echo sentenceCase("HELLO WORLD!!! THIS IS A CAPITALISED SENTENCE. this isn't.");

Returns:
Hello world!!! This is a capitalised sentence. This isn't.
*/

function sentenceCase($s){
    $str = strtolower($s);
    $cap = true;

    for($x = 0; $x < strlen($str); $x++){
        $letter = substr($str, $x, 1);
        if($letter == "." || $letter == "!" || $letter == "?"){
            $cap = true;
        }elseif($letter != " " && $cap == true){
            $letter = strtoupper($letter);
            $cap = false;
        }

        $ret .= $letter;
    }

    return $ret;
}
?>
php at moechofe dot com 26-Apr-2005 06:34
<?php
  /*
  * str_match
  *
  * return a string with only cacacteres defined in a expression return false if the expression is not valid
  *
  * @param $str string the string
  * @param $match the expression based on the class definition off a PCRE regular expression.
  *   the '[', ']', '\' and '^' at class start need to be escaped.
  *   like : -a-z0-9_@.
  */
  function str_match( $str, $match )
  {
    $return = '';
    if( eregi( '(.*)', $match, $class ) )
    {
      $match = '['.$regs[1].']';
      for( $i=0; $i<strlen($str); $i++ )
      if( ereg( '['.$class[1].']', $str[$i] ) )
      $return .= $str{$i};
      return $return;
    }
    else return false;
  }

  /*
  * example
  * accept only alphanum caracteres from the GET/POST parameters 'a'
  */

  if( ! empty($_REQUEST['a']) )
    $_REQUEST['a'] = str_match( $_REQUEST['a'], 'a-zA-Z0-9' );
  else
    $_REQUEST['a'] = 'default';
?>
Pommef 19-Mar-2005 01:15
Example: Give me everything up to the fourth occurance of '/'.

<?php

   $haystack = "/home/username/www/index.php";
   $needle = "/";

   function strnpos($haystack, $needle, $occurance, $pos = 0) {

        $res = implode($needle,$haystack);

        $res = array_slice($res, $pos,  $occurance);

        return explode ($needle,$res);
    }
?>
kristin at greenapple dot on dot ca 02-Jan-2005 08:32
I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.

strnpos() - Find the nth position of needle in haystack.

<?php

    function strnpos($haystack, $needle, $occurance, $pos = 0) {

        for ($i = 1; $i <= $occurance; $i++) {
            $pos = strpos($haystack, $needle, $pos) + 1;
        }
        return $pos - 1;

    }

?>

Example: Give me everything up to the fourth occurance of '/'.

<?php

    $haystack = "/home/username/www/index.php";
    $needle = "/";

    $root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4));

    echo $root_dir;

?>

Returns: /home/username/www

Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!
20-Dec-2004 08:31
In response to hackajar <matt> yahoo <trot> com,

No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11's "Strings" article under the "String access and modification by character" heading.
andy a t onesandzeros d o t biz 09-Nov-2004 02:54
I use these little doo-dads quite a bit. I just thought I'd share them and maybe save someone a little time. No biggy. :)

// returns true if $str begins with $sub
function beginsWith( $str, $sub ) {
    return ( substr( $str, 0, strlen( $sub ) ) == $sub );
}

// return tru if $str ends with $sub
function endsWith( $str, $sub ) {
    return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
}

// trims off x chars from the front of a string
// or the matching string in $off is trimmed off
function trimOffFront( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, $off );
    else
        return substr( $str, strlen( $off ) );
}

// trims off x chars from the end of a string
// or the matching string in $off is trimmed off
function trimOffEnd( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, 0, strlen( $str ) - $off );
    else
        return substr( $str, 0, strlen( $str ) - strlen( $off ) );
}
[tab!] 27-Oct-2004 12:29
//
// string strtrmvistl(  string str, [int maxlen = 64],
//                      [bool right_justify = false],
//                      [string delimter = "<br>\n"])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to 'spread' a string over two lines.
//

function strtrmvistl($str, $maxlen = 64, $right_justify = false, $delimter = "<br>\n") {
    if(($len = strlen($str = chop($str))) > ($maxlen = max($maxlen, 12))) {
        $newstr = substr($str, 0, $maxlen - 3);

        if($len > ($maxlen - 3)) {
            $endlen = min(($len - strlen($newstr)), $maxlen - 3);
            $newstr .= "..." . $delimter;

            if($right_justify)
                $newstr .= str_pad('', $maxlen - $endlen - 3, ' ');

            $newstr .= "..." . substr($str, $len - $endlen);
        }

        return($newstr);
    }

    return($str);
}
terry dot greenlaw at logicalshift dot com 11-Aug-2004 10:52
Here's a simpler "simplest" way to toggle through a set of 1..n colors for web backgrounds:

<?php
$colours = array('#000000', '#808080', '#A0A0A0', '#FFFFFF');

// Get a colour
$color = next($colors) or $color = reset($colors);
?>

The code doesn't need to know anything about the number of elements being cycled through. That way you won't have to tracking down all the code when changing the number of colors or the color values.
Предопределенные константы
addcslashes
Строки


Экранирует cтроку слэшами в стиле языка C

Обработка строк
addslashes
Обработка строк
PHP Manual

addcslashes

(PHP 4, PHP 5)

addcslashes — Экранирует cтроку слэшами в стиле языка C

Описание

string addcslashes ( string $str , string $charlist )

Возвращает строку, экранированную обратными слэшами перед символами, указанными в параметре charlist.

Список параметров

str

Экранируемая строка.

charlist

Список экранируемых символов. Если charlist содержит символы \n, \r и т.п., они будут преобразованы в стиле C, тогда как другие нецифробуквенные символы с ASCII-кодами ниже 32 и выше 126 будут преобразованы в восьмеричное представление.

Следует быть внимательным при указании диапазона символов в аргументе charlist. Проверяйте, какие символы входят в этот диапазон.

<?php
echo addcslashes('foo[ ]', 'A..z');
// выводит:  \f\o\o\[ \]
// Будут экранированы заглавные и строчные английские буквы
// ... а также [\]^_`
?>
Также, если ASCII-код первого символа диапазона больше, чем последнего, диапазон не будет создан. Вместо этого будут экранироваться только первый символ, последний символ и точка. Для определения ASCII-кода символов используйте функцию ord().
<?php
echo addcslashes("zoo['.']", 'z..A');
// выводит:  \zoo['\.']
?>

Будьте внимательны при экранировании символв 0, a, b, f, n, r, t и v. Они будут преобразованы в \0, \a, \b, \f, \n, \r, \t и \v. В C все они являются предопределенными escape-последовательностями, в то время как в PHP это только \0 (NULL), \r (возврат каретки), \n (перевод строки), \f (разрыв страницы), \v (вертикальная табуляция) и \t (табуляция).

Возвращаемые значения

Возвращает экранированную строку.

Список изменений

Версия | Описание
5.2.5 | Добавлены экранирующие последовательности \v и \f.

Примеры

charlist, например, "\0..\37", что проэкранирует все символы с ASCII-кодами от 0 до 31.

Пример #1 addcslashes() example

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

Смотрите также

  • stripcslashes() - Удаляет экранирование символов, произведенное функцией addcslashes
  • stripslashes() - Удаляет экранирование символов
  • addslashes() - Экранирует строку с помощью слэшей
  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • quotemeta() - Экранирует специальные символы

User Contributed Notes

kongaspar at gmail dot com 27-Jul-2009 05:33
Perhaps the following is a more efficient JavaScript escape function:

<?php
function jsEscape($str) {
    return addcslashes($str,"\\\'\"&\n\r<>");
}
?>
stein at visibone dot com 12-Nov-2007 03:16
addcslashes() treats NUL as a string terminator:

   assert("any"  === addcslashes("any\0body", "-"));

unless you order it backslashified:

   assert("any\\000body" === addcslashes("any\0body", "\0"));

(Uncertain whether this should be declared a bug or simply that addcslashes() is not binary-safe, whatever that means.)
Johannes 26-Oct-2007 05:34
Be carefull with adding the \ to the list of encoded characters. When you add it at the last position it encodes all encoding slashes. I got a lot of \\\ by this mistake.

So always encode \ at first.
phpcoder at cyberpimp dot pimpdomain dot com 20-Jan-2005 12:35
Forgot to add something:
The only time you would likely use addcslashes() without specifying the backslash (\) character in charlist is when you are VALIDATING (not encoding!) a data string.

(Validation ensures that all control characters and other unsafe characters are correctly encoded / escaped, but does not alter any pre-existing escape sequences.)

You can validate a data string multiple times without fear of "double encoding".  A single decoding pass will return the original data, regardless of how many times it was validated.)
phpcoder at cyberpimp dot pimpdomain dot com 19-Jan-2005 11:02
If you are using addcslashes() to encode text which is to later be decoded back to it's original form, you MUST specify the backslash (\) character in charlist!

Example:

<?php
  $originaltext = 'This text does NOT contain \\n a new-line!';
  $encoded = addcslashes($originaltext, '\\');
  $decoded = stripcslashes($encoded);
  //$decoded now contains a copy of $originaltext with perfect integrity
  echo $decoded; //Display the sentence with it's literal \n intact
?>

If the '\\' was not specified in addcslashes(), any literal \n (or other C-style special character) sequences in $originaltext would pass through un-encoded, but then be decoded into control characters by stripcslashes() and the data would lose it's integrity through the encode-decode transaction.
ruben at intesys dot it 31-May-2004 09:51
jsAddSlashes for XHTML documents:

<?php
header("Content-type: text/xml");

print <<<EOF
<?xml version="1.0"?>
<html>
<head>
<script type="text/javascript">

EOF;

function jsAddSlashes($str) {
    $pattern = array(
        "/\\\\/"  , "/\n/"    , "/\r/"    , "/\"/"    ,
        "/\'/"    , "/&/"     , "/</"     , "/>/"
    );
    $replace = array(
        "\\\\\\\\", "\\n"     , "\\r"     , "\\\""    ,
        "\\'"     , "\\x26"   , "\\x3C"   , "\\x3E"
    );
    return preg_replace($pattern, $replace, $str);
}

$message = jsAddSlashes("\"<Hello>\",\r\n'&World'\\!");

print <<<EOF
alert("$message");
</script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

EOF;
?>
21-Sep-2003 11:44
<?php
function jsaddslashes($s)
{
 $o="";
 $l=strlen($s);
 for($i=0;$i<$l;$i++)
 {
  $c=$s[$i];
  switch($c)
  {
   case '<': $o.='\\x3C'; break;
   case '>': $o.='\\x3E'; break;
   case '\'': $o.='\\\''; break;
   case '\\': $o.='\\\\'; break;
   case '"':  $o.='\\"'; break;
   case "\n": $o.='\\n'; break;
   case "\r": $o.='\\r'; break;
   default:
   $o.=$c;
  }
 }
 return $o;
}

?>
<script language="javascript">
document.write("<? echo jsaddslashes('<h1 style="color:red">hello</h1>'); ?>");
</script>

output :

<script language="javascript">
document.write("\x3Ch1 style=\"color:red\"\x3Ehello\x3C/h1\x3E");
</script>
natNOSPAM at noworrie dot NO_SPAM dot com 17-May-2002 04:22
I have found the following to be much more appropriate code example:

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\@\177..\377");
?>

This will protect original, innocent backslashes from stripcslashes.
Обработка строк
addslashes
Обработка строк


Экранирует строку с помощью слэшей

addcslashes
bin2hex
Обработка строк
PHP Manual

addslashes

(PHP 4, PHP 5)

addslashes — Экранирует строку с помощью слэшей

Описание

string addslashes ( string $str )

Возвращает строку, в которой перед каждым спецсимволом добавлен обратный слэш, например, для последующего использования этой строки в запросе к базе данных и т.п. Экранируются одиночная кавычка ('), двойная кавычка ("), обратный слэш (\) и NUL (байт NULL).

Функция addslashes() часто применяется при записи в базу данных. Предположим, если нужно внести в базу данных имя O'reilly, то эту строку необходимо проэкранировать. Настоятельно рекомендуется использовать функцию экранирования, специфичную для используемой вами базы данных (например, mysqli_real_escape_string() для MySQL или pg_escape_string() для PostgreSQL), но если используемая вами база данных не имеет собственной функции экранирования и для экранирования специальных символов используется символ \, то для этой цели можно воспользоваться данной функцией. Заметьте, что сам символ \ в базу данных записан не будет, он используется только для корректной передачи данных в базу. Если директива конфигурации magic_quotes_sybase имеет значение on, то символ одинарной кавычки ' будет экранироваться добавлением еще одной кавычки ' вместо обратного слэша.

Директива конфигурации magic_quotes_gpc по умолчанию имела значение on в версиях до PHP 5.4, при этом функция addslashes() автоматически применялась ко всем данным GET, POST, и COOKIE. Не используйте addslashes() для данных, обработанных magic_quotes_gpc, чтобы избежать двойного экранирования. Для проверки состояния этой директивы используется get_magic_quotes_gpc().

Список параметров

str

Экранируемая строка.

Возвращаемые значения

Возвращает экранируемую строку.

Примеры

Пример #1 Пример использования addslashes()

<?php
$str = "Ваше имя O'reilly?";

// выводит: Ваше имя O\'reilly?
echo addslashes($str);
?>

Смотрите также

  • stripcslashes() - Удаляет экранирование символов, произведенное функцией addcslashes
  • stripslashes() - Удаляет экранирование символов
  • addcslashes() - Экранирует cтроку слэшами в стиле языка C
  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • quotemeta() - Экранирует специальные символы
  • get_magic_quotes_gpc() - Получение текущего значения настройки конфигурации magic_quotes_gpc

User Contributed Notes

Lars 03-Apr-2012 08:51
Even for simple json string backslash encodings, do not use this function. Some tests may work fine, but in json the single quote (') must not be escaped.
qeremy [atta] gmail [dotta] com 24-Feb-2012 03:11
Actually I prefer to escape the SQL queries completely (then no more challenge for data security);

<?php
function escape_query($str) {
    return strtr($str, array(
        "\0" => "",
        "'"  => "&#39;",
        "\"" => "&#34;",
        "\\" => "&#92;",
        // more secure
        "<"  => "&lt;",
        ">"  => "&gt;",
    ));
}
?>

// &#39;&#34;&#92;
echo escape_query("'\"\\\0");

// &lt;script&gt;alert(1)&lt;/script&gt;
echo escape_query("<\0script>alert(1)<\0/script>");

// See more: www.asciitable.com
boyaqb at gmail dot com 14-Aug-2011 03:34
so you can use replace single quote and double quote with HTML Entities

for example

<?php
/**
 * replcae quotes to HTML entities by names or numbers
 *
 * @param (string) escaped string value
 * @param (string) default ='number' will be return to number entities you can use ='name' to return name entities
 * Note : don't use ='name' coz (&apos;) (does not work in IE)
 */
function quote2entities($string,$entities_type='number')
{
    $search                     = array("\"","'");
    $replace_by_entities_name   = array("&quot;","&apos;");
    $replace_by_entities_number = array("&#34;","&#39;");
    $do = null;
    if ($entities_type == 'number')
    {
        $do = str_replace($search,$replace_by_entities_number,$string);
    }
    else if ($entities_type == 'name')
    {
        $do = str_replace($search,$replace_by_entities_name,$string);
    }
    else
    {
        $do = addslashes($string);
    }
    return $do;
}

echo quote2entities("I love 'PHP' for ever");
// will return I love 'PHP' for ever in browsere
// but in view code and database will be  I love &#34;PHP&#34; for ever in source
?>
cliprz at gmail dot com 26-Mar-2011 11:08
<?php

/**
 * @desc add slashes if use MySQL and check if function addslashes is exits else
 * return to escape string in MySQL .
 * same way its return to stripslashes function
 * @param string $type any string u want to insert in MySQL and display from MySQL
 * @param string $type must be add to add slashes and strip to strip slashes
 * @author Yousef Ismaeil - cliprz@gmail.com
 */
function PHP_slashes($string,$type='add')
{
    if ($type == 'add')
    {
        if (get_magic_quotes_gpc())
        {
            return $string;
        }
        else
        {
            if (function_exists('addslashes'))
            {
                return addslashes($string);
            }
            else
            {
                return mysql_real_escape_string($string);
            }
        }
    }
    else if ($type == 'strip')
    {
        return stripslashes($string);
    }
    else
    {
        die('error in PHP_slashes (mixed,add | strip)');
    }
}

?>
svenr at selfhtml dot org 01-Feb-2011 08:45
To output a PHP variable to Javascript, use json_encode().

<?php

$var = "He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo "alert(".json_encode($var).");\n";

?>

Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;
roysimke at microsoftsfirstmailprovider dot com 18-Jun-2010 01:35
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.

keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.
Simon Barrett 04-May-2010 01:46
Heres a hassle free function to use to check your query string and before its handed to the db.  It will add/remove slashes according to the get_magic_quotes_gpc state

<?php
    function mysql_prep($value)
    {
        if(get_magic_quotes_gpc()){
            $value = stripslashes($value);
        } else {
            $value = addslashes($value);
        }
        return $value;
    }
?>
adam at NOSPAM dot awgtek dot com 18-Oct-2009 08:16
When checking whether to addslashes, use get_magic_quotes_runtime(). Using get_magic_quotes_gpc() may not be accurate.
DarkHunterj 25-Aug-2009 05:11
Based on:
Danijel Pticar
05-Aug-2009 05:22
I recommend this extended version, to replace addslashes altogether(works for both strings and arrays):
<?php
function addslashesextended(&$arr_r)
{
    if(is_array($arr_r))
    {
        foreach ($arr_r as &$val)
            is_array($val) ? addslashesextended($val):$val=addslashes($val);
        unset($val);
    }
    else
        $arr_r=addslashes($arr_r);
}
?>
Danijel Pticar 05-Aug-2009 10:22
Hi,
I use this recursive function for POST. It handles multidimensional arrays.

<?php
function as_array(&$arr_r)
{
 foreach ($arr_r as &$val) is_array($val) ? as_array($val):$val=addslashes($val);
 unset($val);
}

as_array($_POST);
?>
leocullen at fastmail dot fm 06-Feb-2009 01:06
this is my version of an addslashes function, useful for processing $_POST array:

<?php
function add_slashes ($an_array) {
  foreach ($an_array as $key => $value) {
    $new_array[$key] = addslashes($an_array[$key]);
  }
}
?>

then call it:

<?php add_slashes($_POST); ?>
stuart at horuskol dot co dot uk 11-Dec-2008 02:44
Be careful on whether you use double or single quotes when creating the string to be escaped:

$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';

echo $test;
echo "\r\n\r\n";
echo addslashes($test);

$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";

echo $test;
echo "\r\n\r\n";
echo addslashes($test);
Taslim Sohel (sohel62 at yahoo dot com) 07-Dec-2008 10:09
About Raymond and Aditya's post

Following code can help you to add slashes with posted array.
I just added a recursive function with Aditya's code.

<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    if(is_array($input_arr)){
        $_POST[$key] = addslashes_array($input_arr);
    }else{
        $_POST[$key] = addslashes($input_arr);
    }

}

// Recursive Function to add slashes with posted array.
function addslashes_array($input_arr){
    if(is_array($input_arr)){
        $tmp = array();
        foreach ($input_arr as $key1 => $val){
            $tmp[$key1] = addslashes_array($val);
        }
        return $tmp;
    }else{
        return addslashes($input_arr);
    }
}

?>
Raymond Hofman 24-Jun-2008 12:14
In addition to the post made by Aditya P Bhatt below. This code works fine for posting a single string but does not work for posting arrays.
Aditya P Bhatt (adityabhai at gmail dot com) 27-Mar-2008 09:59
Automagically add slashes to $_POST variables. It helps to prevent some sql injection attacks. Also works with $_GET variables.

FILE NAME: input_cl.php
<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    $_POST[$key] = addslashes($input_arr);
}
?>

Just put this at the top of your script that gets the variables. Here is an example.

Usage Example
<?php
include("input_cl.php");
// all $_POST variables have slashes added to them
$f_name = $_POST["f_name"];
$l_name = $_POST["l_name"];
$phone_num = $_POST["phone_num"];
$address1 = $_POST["address1"];
$address2 = $_POST["address2"];
$city = $_POST["city"];
$State = $_POST["State"];
$zip = $_POST["zip"];

//sql insert code goes here.
?>
Edwin at NOSPAM dot example dot com 22-Jan-2008 07:11
In the note below of Adrian C (3-3-2007) checkaddslashes will not behave well with strings starting with a single quote (because of the non-typed comparison) or with strings having a mix of escaped and non-escaped single quotes.

Although addslashes also escapes double quotes, this function worked for single quotes fine.

<?php
function checkaddslashes($str){
    $str2 = str_replace("\'", "*****", $str);
    if(strpos($str2,"'")!== false)
        return str_replace('*****', "\'", addslashes($str2));
    else
        return $str;
}
?>
Nate from RuggFamily.com 24-May-2007 07:19
If you want to add slashes to special symbols that would interfere with a regular expression (i.e., . \ + * ? [ ^ ] $ ( ) { } = ! < > | :), you should use the preg_quote() function.
yoder2 at purdue dot edu 27-Apr-2007 12:23
to quote boris-pieper AT t-online DOT de, 15-Jan-2005 06:07,

Note: You should use mysql_real_escape_string() (http://php.net/mysql_real_escape_string) if possible (PHP => 4.3.0) instead of mysql_escape_string().

You may also want to us it instead of addslashes.
sam dot fullman at verizon 20-Mar-2007 02:37
There are other functions "kind of" like this one but this should help adding slashes to a form post which also contains arrays (and you can't access runtime quotes), or you need to add slashes to an array which is already stripped:

<?php
    function addslashes_array($a){
        if(is_array($a)){
            foreach($a as $n=>$v){
                $b[$n]=addslashes_array($v);
            }
            return $b;
        }else{
            return addslashes($a);
        }
    }
?>

note this does not add slashes to the keys - you could easily modify to do this..
Adrian C 02-Mar-2007 06:06
What happends when you add addslashes(addslashes($str))? This is not a good thing and it may be fixed:

function checkaddslashes($str){
    if(strpos(str_replace("\'",""," $str"),"'")!=false)
        return addslashes($str);
    else
        return $str;
}

checkaddslashes("aa'bb");  => aa\'bb
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'");  => \'

Hope this will help you
pulstar at ig dot com dot br 11-Sep-2006 07:50
May it is better use the function mysql_real_escape_string instead of addslashes when inserting data into a MySQL database. Check it at:

http://www.php.net/manual/en/function.mysql-real-escape-string.php
joechrz at gmail dot com 19-Aug-2006 05:36
Here's an example of a function that prevents double-quoting, I'm surprised noone has put something like this up yet... (also works on arrays)

<?php
function escape_quotes($receive) {
    if (!is_array($receive))
        $thearray = array($receive);
    else
        $thearray = $receive;

    foreach (array_keys($thearray) as $string) {
        $thearray[$string] = addslashes($thearray[$string]);
        $thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
    }

    if (!is_array($receive))
        return $thearray[0];
    else
        return $thearray;
}
?>
Picky 24-May-2006 12:55
This function is deprecated in PHP 4.0, according to this article:

http://www.newsforge.com/article.pl?sid=06/05/23/2141246

Also, it is worth mentioning that PostgreSQL will soon start to block queries involving escaped single quotes using \ as the escape character, for some cases, which depends on the string's encoding.  The standard way to escape quotes in SQL (not all SQL databases, mind you) is by changing single quotes into two single quotes (e.g, ' ' ' becomes ' '' ' for queries).

You should look into other ways for escaping strings, such as "mysql_real_escape_string" (see the comment below), and other such database specific escape functions.
luciano at vittoretti dot com dot br 31-Oct-2005 03:18
Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);
    }

    return $str;
}

function stripslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = stripslashes_mssql($value);
        }
    } else {
        $str = str_replace("''", "'", $str);
    }

    return $str;
}
thisisroot at gmail dot com 26-Sep-2005 09:30
In response to Krasimir Slavov and Luiz Miguel Axcar:

There are several encoding schemes for inserting binary data into places it doesn't typically belong, such as databases and e-mail bodies. Check out the base64_encode() and convert_uuencode() functions for the details.
Krasimir Slavov kkslavov at yahoo dot com 16-Sep-2005 11:51
If you have problems with adding images or other binady data with addslashes() for php 4.3 >= use:

<?php
$search = array("\x00", "\x0a", "\x0d", "\x1a", "\x09");
$replace = array('\0', '\n', '\r', '\Z' , '\t');

$chrData .= str_replace($search, $replace, $Data );
?>

and put in your SQL field='$chrData' ! please remark quotes
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br) 01-Sep-2005 06:16
Hello,

If you are getting trouble to SGDB write/read HTML data, try to use this:

<?php

//from html_entity_decode() manual page
function unhtmlentities ($string) {
   $trans_tbl =get_html_translation_table (HTML_ENTITIES );
   $trans_tbl =array_flip ($trans_tbl );
   return strtr ($string ,$trans_tbl );
}

//read from db
$content = stripslashes (htmlspecialchars ($field['content']));

//write to db
$content = unhtmlentities (addslashes (trim ($_POST['content'])));

//make sure result of function get_magic_quotes_gpc () == 0, you can get strange slashes in your content adding slashes twice

//better to do this using addslashes
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;

?>
unsafed 30-Apr-2005 08:23
addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.
gv 06-Nov-2004 05:23
Regarding the previous note using addslashes/stripslahes with regular expressions and databases it looks as if the purpose of these functions gets mixed.

addslahes encodes data to be sent to a database or something similar. Here you need addslashes because you send commands to the database as command strings that contain data and thus you have to escape characters that are special in the command language like SQL.

Therefore the use of addslahses on a regex does properly store the regex in the database.

stripslashes does the opposite: it decodes an addslashes encoded string. However, retrieving data from a database works differently: it does not go through some string interpretation because you actually retrieve your binary data in your variables. In other words: the data stored in your variable is the unmodified binary data that your database returned. You do not run stripslahes on data returned from a database. That way, the regexs are retrieved correctly, too.

This is different from other data exchange like urlencoded strings that you exchange with your browser. Here the data channel uses the same encodings in both directions: therefore you have to encode data to be sent and you have to decode data received.
percy at rotteveel dot ca 19-Oct-2004 08:08
Be very careful when using addslashes and stripslashes in combination with regular expression that will be stored in a MySQL database. Especially when the regular expression contain escape characters!

To store a regular expression with escape characters in a MySQL database you use addslashes. For example:

$l_reg_exp = addslashes( �[\x00-\x1F]� );

After this the variable $l_reg_exp will contain: [\\x00-\\x1F].

When you store this regular expression in a MySQL database, the regular expression in the database becomes [\x00-\x1F].

When you retrieve the regular expression from the MySQL database and apply the PHP function stripslashes(), the single backslashes will be gone!

The regular expression will become [x00-x1F] and your regular expression might not work!
mark at hagers dot demon dot nl 27-Sep-2004 03:34
I was stumped for a long time by the fact that even when using addslashes and stripslashes explicitly on the field values double quotes (") still didn't seem to show up in strings read from a database. Until I looked at the source, and realised that the field value is just truncated at the first occurrence of a double quote. the remainder of the string is there (in the source), but is ignored when the form is displayed and submitted.

This can easily be solved by replacing double quotes with "&quot;" when building the form. like this:
$fld_value =  str_replace ( "\"", "&quot;", $src_string ) ;
The reverse replacement after the form submission is not necessary.
hazy underscore fakie at ringwraith dot org 12-Jul-2003 11:23
Note that when using addslashes() on a string that includes cyrillic characters, addslashes() totally mixes up the string, rendering it unusable.
phil at internetprojectmanagers dot com 09-Apr-2003 06:46
re: problem with mcrypt, addslashes and mysql

Here is my solution to the problem of characters from mcrypt creating issues with mysql calls (due to characters which aren't cleaned up by addslashes).

Solution: simply convert your encryption string to hex, then back to binary when you are ready to decrypt.

<?php
// ie.
$encrypted = addslashes($string);
$encrypted = bin2hex($encrypted);

// ... then:
$decrypted = hex2bin($encrypted);
$decrypted = stripslashes($decrypted);

// where hex2bin() is:
function hex2bin($hexdata) {
  $bindata="";

  for ($i=0;$i<strlen($hexdata);$i+=2) {
    $bindata.=chr(hexdec(substr($hexdata,$i,2)));
  }

  return $bindata;
}
?>

One word of caution: this will increase the length of your initial data string, so you will need to increase the field length for your mysql database.

Cheers, Phil
PS. I knew that I'd eventually be able to give something back to the site!
phil at internetprojectmanagers dot com 09-Apr-2003 04:47
re: encryption, addslashes and mysql

Note that mcrypt encryption may add in an apostrophe from the ascii table which cannot be protected by addslashes. It may not even be on your keyboard.

Because encryption strings are random, you may not discover it unless you test (or stumble?) on the correct sequence which inserts an apostrophe in the encrypted string.

This means that testing is even more important where encryption is concerned. If I create a solution I'll post it here.

Phil
steve at teamITS dot com 18-Jan-2003 05:53
For thelogrus, my testing shows the opposite--that a slashed string is stored correctly by MySQL.  Consider

insert into test (field1) values ('test\'test')

...which is stored as "test'test".  If you were posting "Sir'Weaser" from a form to your script and have magic_quotes_gpc on, then the string is slashed already so if you run addslashes() again you will be entering "Sir\\'Weaser" into MySQL.  In that case "Sir\'Weaser" would be the correct output.

In summary, addslashes() is not necessary if magic_quotes_gpc is on.
mike at gyrate dot org 13-Jan-2003 02:05
[Editor's note: See also the php.ini configuration magic_quotes_sybase at the URL http://www.php.net/manual/en/ref.sybase.php]

please note that addslashes will NOT work with mssql, since mssql does not use the backslash character as an escape mechanism.  just double your quotes instead.  or use this:

<?php
function mssql_addslashes($data) {
    $data = str_replace("'", "''", $data);
    return $data;
}
?>
hoskerr at nukote dot com 12-Nov-2002 03:16
Beware of using addslashes() on input to the serialize() function.   serialize() stores strings with their length; the length must match the stored string or unserialize() will fail.

Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized.

In other words, do this...

<?php
$string="O'Reilly";
$ser=serialize($string);    # safe -- won't count the slash
$result=addslashes($ser);
?>

...and not this...

<?php
$string="O'Reilly";
$add=addslashes($string);   # RISKY!  -- will count the slash
$result=serialize($add);
?>

In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize().

[Note to the maintainers: You may, at your option, want to link this note to serialize() as well as to addslashes().  I'll refrain from doing such cross-posting myself...]
php at slamb dot org 30-Oct-2002 10:48
spamdunk at home dot com, your way is dangerous on PostgreSQL (and presumably MySQL). You're quite correct that ANSI SQL specifies using ' to escape, but those databases also support \ for escaping (in violation of the standard, I think). Which means that if they pass in a string that includes a "\'", you expand it to "\'''" (an escaped quote followed by a non-escaped quote. WRONG! Attackers can execute arbitrary SQL to drop your tables, make themselves administrators, whatever they want.)

The best way to be safe and correct is to:

- don't use magic quotes; this approach is bad. For starters, that's making the assumption that you will be using your input in a database query, which is arbitrary. (Why not escape all "<"s with "&lt;"s instead? Cross-site scripting attacks are quite common as well.) It's better to set up a way that does whatever escaping is correct for you when you use it, as below:

- when inserting into the database, use prepared statements with placeholders. For example, when using PEAR DB:

<?php
    $stmt = $dbh->prepare('update mb_users set password = ? where username = ?');
    $dbh->execute($stmt, array('12345', 'bob'));
?>

Notice that there are no quotes around the ?s. It handles that for you automatically. It's guaranteed to be safe for your database. (Just ' on oracle, \ and ' on PostgreSQL, but you don't even have to think about it.)

Plus, if the database supports prepared statements (the soon-to-be-released PostgreSQL 7.3, Oracle, etc), several executes on the same prepare can be faster, since it can reuse the same query plan. If it doesn't (MySQL, etc), this way falls back to quoting code that's specifically written for your database, avoiding the problem I mentioned above.

(Pardon my syntax if it's off. I'm not really a PHP programmer; this is something I know from similar things in Java, Perl, PL/SQL, Python, Visual Basic, etc.)
guy_AT_datalink_DOT_net_DOT_au 30-Mar-2002 01:58
If you're trying to escape quotes in a javascript event as such:

<img src="foo.gif" OnMouseOver="alert('<? print $myString ?>')">

It helps to perform this first:

$myString = str_replace("'", "\'", $myString);
$myString = str_replace('"', "'+String.fromCharCode(34)+'", $myString);
hybrid at n0spam dot pearlmagik dot com 08-May-2001 10:46
Remember to slash underscores (_) and percent signs (%), too, if you're going use the LIKE operator on the variable or you'll get some unexpected results.
php at NO_SPAMj-w3 dot com 02-Apr-2001 03:18
As mentioned, magic_quotes_gpc automatically adds slashes to POST and GET data and these slashes don't go in the database.  BUT, be careful of this. If you have a form with an error check, make sure you strip the slashes if your form remembers the OK fields, so the user doesn't view these automagically added slashes.
addcslashes
bin2hex
Обработка строк


РџСЂРµРѕР±СЂР°Р·СѓРµС‚ Р±РёРЅР°СЂРЅС‹Рµ РґР°РЅРЅС‹Рµ РІ С€РµСЃС‚РЅР°РґС†Р°С‚РёСЂРёС‡РЅРѕРµ РїСЂРµРґСЃС‚Р°РІР»РµРЅРёРµ

addslashes
chop
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє
PHP Manual

bin2hex

(PHP 4, PHP 5)

bin2hex — РџСЂРµРѕР±СЂР°Р·СѓРµС‚ Р±РёРЅР°СЂРЅС‹Рµ РґР°РЅРЅС‹Рµ РІ С€РµСЃС‚РЅР°РґС†Р°С‚РёСЂРёС‡РЅРѕРµ РїСЂРµРґСЃС‚Р°РІР»РµРЅРёРµ

РћРїРёСЃР°РЅРёРµ

string bin2hex ( string $str )

Р’РѕР·РІСЂР°С‰Р°РµС‚ ASCII-СЃС‚СЂРѕРєСѓ, СЃРѕРґРµСЂР¶Р°С‰СѓСЋ С€РµСЃС‚РЅР°РґС†Р°С‚РёСЂРёС‡РЅРѕРµ РїСЂРµРґСЃС‚Р°РІР»РµРЅРёРµ Р°СЂРіСѓРјРµРЅС‚Р° str. РџСЂРµРѕР±СЂР°Р·РѕРІР°РЅРёРµ РїСЂРѕРёР·РІРѕРґРёС‚СЃСЏ РїРѕР±Р°Р№С‚РЅРѕ, РЅР°С‡РёРЅР°СЏ СЃ РІРµСЂС…РЅРµРіРѕ РїРѕР»СѓР±Р°Р№С‚Р°.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

str

РЎС‚СЂРѕРєР°.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ С€РµСЃС‚РЅР°РґС†Р°С‚РёСЂРёС‡РЅРѕРµ РїСЂРµРґСЃС‚Р°РІР»РµРЅРёРµ СѓРєР°Р·Р°РЅРЅРѕР№ СЃС‚СЂРѕРєРё.

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • hex2bin() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ С€РµСЃС‚РЅР°РґС†Р°С‚РµСЂРёС‡РЅС‹Рµ РґР°РЅРЅС‹Рµ РІ РґРІРѕРёС‡РЅС‹Рµ
  • pack() - РЈРїР°РєРѕРІС‹РІР°РµС‚ РґР°РЅРЅС‹Рµ РІ Р±РёРЅР°СЂРЅСѓСЋ СЃС‚СЂРѕРєСѓ

User Contributed Notes

subdivizion at gmail dot com 18-Sep-2009 05:19
Here's a function to check if a string contains any 7-bit GSM characters.

It might come useful for people working on SMS platforms.

<?php

function check_gsm($str)
{
    $arr = array(
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05","0x06","0x07","0x08","0x09",
"0x0A","0x0B","0x0C","0x0D","0x0E","0x0F","0x10","0x11","0x12","0x13",
"0x14","0x15","0x16","0x17","0x18","0x19","0x1A","0x1B","0x1B0A",
"0x1B14","0x1B28","0x1B29","0x1B2F","0x1B3C","0x1B3D","0x1B3E",
"0x1B40","0x1B65","0x1C","0x1D","0x1E","0x1F","0x20","0x21","0x22",
"0x23","0x24","0x25","0x26","0x27","0x28","0x29","0x2A","0x2B","0x2C",
"0x2D","0x2E","0x2F","0x30","0x31","0x32","0x33","0x34","0x35","0x36",
"0x37","0x38","0x39","0x3A","0x3B","0x3C","0x3D","0x3E","0x3F","0x40",
"0x41","0x42","0x43","0x44","0x45","0x46","0x47","0x48","0x49","0x4A",
"0x4B","0x4C","0x4D","0x4E","0x4F","0x50","0x51","0x52","0x53","0x54",
"0x55","0x56","0x57","0x58","0x59","0x5A","0x5B","0x5C","0x5D","0x5E",
"0x5F","0x60","0x61","0x62","0x63","0x64","0x65","0x66","0x67","0x68",
"0x69","0x6A","0x6B","0x6C","0x6D","0x6E","0x6F","0x70","0x71","0x72",
"0x73","0x74","0x75","0x76","0x77","0x78","0x79","0x7A","0x7B","0x7C",
"0x7D","0x7E","0x7F");

    $strl = strlen($str);
    for ($i = 0;$i < $strl; $i++)
    {
        $char = '0x' . bin2hex(substr($str,$i,1));
        $pos = in_array($char,$arr);
        if ($pos == 1)
        {
            $j++;
        }
    }

    if ($j < $strl)
    {
        return false;
    }
    else
    {
        return true;
    }
}
?>
me at juanmaria dot com 03-Sep-2009 06:05
Regarding the fabled hex2bin, the easiest way I've found to "replace" it is the following call to function pack():

<?php
$bin_str = pack("H*" , $hex_str);
?>
gimpstraw at gmail dot com 20-Apr-2009 11:01
I want clear this up for everyone using functions like the one below this...

<?php
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= dechex(ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// Look what happens when ord($str{$i}) is 0...15
// you get a single digit hexadecimal value 0...F

// bin2hex($str) could return something like 4a3,
// decimals(74, 3), whatever the binary value is of those.

function hex2bin($str) {
    $bin = "";
    $i = 0;
    do {
        $bin .= chr(hexdec($str{$i}.$str{($i + 1)}));
        $i += 2;
    } while ($i < strlen($str));
    return $bin;
}

// hex2bin("4a3") just broke. Now what?

// Using sprintf() to get it right.
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= sprintf("%02x", ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// now using whatever the binary value of decimals(74, 3)
// and this bin2hex() you get a hexadecimal value you can
// then run the hex2bin function on. 4a03 instead of 4a3.
?>
nodarinodo 18-Dec-2008 01:35
<?php
if(!function_exists('bin2hex'))
{
function bin2hex($str)
    {
        $strl = strlen($str);
        $fin = '';
        for($i =0; $i < $strl; $i++)
        {
            $fin .= dechex(ord($str[$i]));
        }
        return $fin;
    }
}
?>
chaos79 03-Oct-2008 08:30
Because the way back (hex2bin) doesn't exist on php, i've written another little function without using commands like pack:

<?php
// Convert a hex-string to binary-string (the way back from bin2hex)

function hex2bin($h)
  {
  if (!is_string($h)) return null;
  $r='';
  for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
  return $r;
  }

echo bin2hex('Hello'); // result: 48656c6c6f
echo hex2bin('48656c6c6f'); // result: Hello
?>
admin at purespider dot de 15-Aug-2008 05:08
The most simple way to do binary (10101010 or so) to hex is
<?PHP echo dechex(bindec(10101010)); ?>
kissifrot at gmail dot com 26-Nov-2007 02:37
hex2bin can be useful to insert data into BLOB binary fields.

for example if you want to insert the content of a file :

<?php
$filename = '/foo/bar';
$bin_content = fread(fopen($filename,"r"),filesize($filename));

// use the usual mysql_connect() function

$insert_query = "INSERT INTO mytable (blob_field) VALUES ('".bin2hex($bin_content)."')";
mysql_query($insert_query);

?>
tehjosh at gamingg dot net 11-Aug-2007 11:35
This function is for converting binary data into a hexadecimal string representation.  This function is not for converting strings representing binary digits into hexadecimal.  If you want that functionality, you can simply do this:

<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>

This would output "f9".  Just remember that there is a very big difference between binary data and a string representation of binary.
ratfactor at gmail dot com 23-Nov-2006 12:13
I also wished to have the ability to translate a string containing a binary number ('1101') to a string containing a hexadecimal number ('d').  Here is my function:

function strbin2hex($bin){
  $last = strlen($bin)-1;
  for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
  return dechex($x);
}

Example:
strbin2hex('1101');   // returns 'd'

I also added some optional features to my function (zero padding and upper case hex letters):

function strbin2hex($bin, $pad=false, $upper=false){
  $last = strlen($bin)-1;
  for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
  $x = dechex($x);
  if($pad){ while(strlen($x) < intval(strlen($bin))/4){ $x = "0$x"; } }
  if($upper){ $x = strtoupper($x); }
  return $x;
}

Examples:
strbin2hex('11110101', true, true);   // returns 'F5'
strbin2hex('00001011', true, true);   // returns '0B'
nilzie at gmail dot com 14-Jul-2006 06:12
Since PHP only has a way to convert a real binary string into hex, couldn't I find a function that can convert binary information written in ascii (like 0110). This function will convert that

<?
function asciibin2hex($str) {

$str = str_replace(" ", "", $str); //delete some probably spaces

//Binary to HEX list

$binary['0000'] = "0";
$binary['0001'] = "1";
$binary['0010'] = "2";
$binary['0011'] = "3";
$binary['0100'] = "4";
$binary['0101'] = "5";
$binary['0110'] = "6";
$binary['0111'] = "7";
$binary['1000'] = "8";
$binary['1001'] = "9";
$binary['1010'] = "a";
$binary['1011'] = "b";
$binary['1100'] = "c";
$binary['1101'] = "d";
$binary['1110'] = "e";
$binary['1111'] = "f";

//make sets of 4
for( ; ; ) {
$calc = strlen($str) / 4;
if(is_numeric($calc)&&(intval($calc)==floatval($calc))) {
    break;
    }
    else {
        $str .= 0;
        }
 }

//translate binary to hex
for($i = 0 ; $i < strlen($str) ; $i = $i + 4) {
        $set = substr($str, $i, 4);
        $inhex .= $binary[$set];
}

return $inhex;

}
//Examples:
echo asciibin2hex("101101011100"); //prints: b5c
echo asciibin2hex("1011 1000 1111 1100") //prints: b8fc
echo asciibin2hex("1000 1011 1101 001") //prints: 8bd2
?>

I hope I didn't make it too hard for myself writing this all, but hГ©, it works :)
mike at go dot online dot pt 14-Mar-2006 04:03
Unicode/multibyte capable 'bin2hex' function, inspired by v0rbiz at yahoo dot com >> http://www.php.net/manual/en/function.ord.php#42778

function unibin2hex($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = bin2hex(substr($k, 0, 1));
    $k2 = bin2hex(substr($k, 1, 1));
    return $k2.$k1;
}

Note: UCS-2LE = UCS-2 little endian; UCS-2 = UTF-16
lihong dot wei at mwbiz dot de 18-May-2005 05:15
Convert special characters(inclusiv line break) in a string into hexadecimal characters
function spec2hex($str) {
   $result = '';
   for($i = 0; $i < strlen($str); $i++) {
           if(ord(substr($str, $i, 1)) > 127 || ord(substr($str, $i, 1)) == 10){
               $result .= '&#x'.bin2hex(substr($str, $i, 1)).';';
           }
           else{
               $result .= substr($str, $i, 1);
           }
   }
   return $result;
}
php_guru дt bestof dдsh inter dцt net 03-Feb-2005 12:15
The function hexentities($str) of the previous post is equivalent to

<?= substr( chunk_split( bin2hex( " $str" ), 2, ";&#x" ), 3,-3) ?>

Also, I think that the <address> tag should be used for the whole paragraph (usually at document foot) and not as shortcut for <span class=email> or so (although it is an %inline; element), see e.g. http://www.w3.org/TR/html4/struct/global.html#h-7.5.6
manithu at fahr-zur-hoelle dot org 09-Jan-2005 01:30
This function returns the string $str in htmlentity hex format (&#xnumber;).
It is useful to prevent spam bots indexing your email adress.

<?php

function hexentities($str) {
    $return = '';
    for($i = 0; $i < strlen($str); $i++) {
        $return .= '&#x'.bin2hex(substr($str, $i, 1)).';';
    }
    return $return;
}

?>

example:
<?php echo 'email: <address>'.hexentities('foo@bar').'</address>'; ?>
will return:

email: <address>&#x66;&#x6f;&#x6f;&#x40;&#x62;&#x61;&#x72;</address>

the browser will show foo@bar.
j_lozinskit at yahoo dot co dot uk 24-Nov-2004 05:11
A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following:

<?php
$field=bin2hex($field);
$field=chunk_split($field,2,"\\x");
$field= "\\x" . substr($field,0,-2);
?>

this will convert your field (binary or not) into hex and then convert the hex into a string which may be placed in a php file:

FFFFFFFF -> \xFF\xFF\xFF\xFF
t0rus at dr dot com 22-Nov-2004 08:18
modified version of Thoth's hexbin and binhex to convert
any size numbers
(original doesn't take more than integer - 32bit)
<?
function hexbin($hex){
    $bin='';
    for($i=0;$i<strlen($hex);$i++)
        $bin.=str_pad(decbin(hexdec($hex{$i})),4,'0',STR_PAD_LEFT);
       return $bin;
}

function binhex($bin){
    $hex='';
    for($i=strlen($bin)-4;$i>=0;$i-=4)
        $hex.=dechex(bindec(substr($bin,$i,4)));
   return strrev($hex);
}
?>
brams006 at umn dot edu 19-Aug-2004 03:05
Here's a modified version of an earlier post (asc2bin and bin2asc) to convert an incoming ascii string to hex and out again.  For example, this is really useful if you want to insert data into a mySQL database which contains both escaped and non-escaped characters.  For example, if you want to store code snibbets in a mySQL text field:

printf("here's some \"text\".");

If you INSERT this into mySQL, it probably won't come out in friendly executable format, and you can't escape all double-quotes, nor can you strip out all the slashes.  One solution is to just convert the string to hex, store it in hex, then convert back to ascii before using it in some way:

function asc2hex ($temp) {
   $len = strlen($temp);
   for ($i=0; $i<$len; $i++) $data.=sprintf("%02x",ord(substr($temp,$i,1)));
   return $data;
}

function hex2asc($temp) {
   $len = strlen($temp);
   for ($i=0;$i<$len;$i+=2) $data.=chr(hexdec(substr($temp,$i,2)));
   return $data;
}
aidan at php dot net 30-Apr-2004 08:48
hexdump() is a function for "dumping" packets or binary output from servers. See the below link for more information.

http://aidanlister.com/repos/v/function.hexdump.php
mhspam at mail dot sce dot cz 23-Apr-2004 07:14
My version of quoted-printable mail subject converting function (maybe not as effective, but preserving characters which don't need conversion).
Martin
<?php
// Transfer mail subject into Quoted Printable encoding
function mail_quote_subj($str, $charset){
    $out = '';
    for($i = 0; $i < strlen($str); $i++){
        $out .= (ord($str[$i]) > 127) ? "=" . bin2hex($str[$i]) : $str[$i];
    }
    return "=?$charset?Q?".$out."?=";
};
?>
AntonioAlcorn at yahoo dot coma 19-Apr-2004 11:34
In response to Patrik:
A simpler way to print a number in binary is to use base_convert().
<? echo base_convert($bin, 10, 2); ?>
If you need it to print all 32 bits (as your function does) you can just pad it out:
<? echo str_pad(base_convert($bin, 10, 2), 32, '0', STR_PAD_LEFT); ?>
The conversion is from base 10 because when $bin is passed to base_convert(), it is converted to a string, and the default representation is in decimal.
Hope this helps.
Patrik 01-Feb-2004 09:14
I needed a little function that will print the binary as a string, here it comes.

<?php
function bin2string($bin) {
    $res = "";
    for($p=31; $p >= 0; $p--) {
      $res .= ($bin & (1 << $p)) ? "1" : "0";
    }
    return $res;
}
?>
mkr at binarywerks dot dk 29-Oct-2003 05:34
Ok, this is a better version than my previous poor example.

Running this in shell creates a progress indicator. Very useful if used when parsing large log files for instance.

#!/usr/bin/php4 -q
<?
// Displays a progress indicator
function progress($line)
{
        global $last_len;

        $del_char = pack("H" . 2, "7F");
        $line_len = strlen($line);
        $del_chars=(isset($last_len)) ? $last_len : $line_len;

        $last_len = $line_len;
        return str_repeat($del_char, ($del_chars)).$line;
}

// demo code:
for($i=0;$i<100;$i++)
{
        sleep(1);
        echo progress("i is now: $i out of 100");
}
?>
Thoth 24-Oct-2003 05:24
I thought it'll give me an "F" if i give it a "1111"...

Here's something to convert a binary-string into a hex-string and other direction too:

<?php
function hexbin($hex) {
    $bin = decbin(hexdec($hex));
    return $bin;
}

function binhex($bin) {
    $hex = dechex(bindec($bin));
    return $hex;
}
?>

simple, isn't it?
Francisco (ffaria at mutua dot com dot br) 21-Jul-2003 04:33
function to search a character in a normal string change this for a hexadecimal and take the especifical char code in hexa and replace this char and return the string

<?php
function hex_replace($pCaracter,$sCaracter,$conteudo) {

    $pHex = bin2hex($pCaracter);
    $sHex = bin2hex($sCaracter);

    $tam = strlen($conteudo);

    for($i = 0; $i <= $tam; $i++) {
        $cont = bin2hex(substr($conteudo,$i,1));

        if ($cont == $pHex) {
           $cont = $sHex;
           $hex .= $cont;
        }
    }

    for ($i=0;$i<strlen($hex);$i+=2)
          $bin .= chr(hexdec(substr($hex,$i,2)));
    return $bin;
}
?>

by from a litle brazilian. :-P
andreas.schmeiler 05-Feb-2003 06:01
<?php
function hex2bin($hexdata) {

   for ($i=0;$i<strlen($hexdata);$i+=2) {
      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
   }

   return $bindata;
}
?>
admin at tsunaquack dot com 16-Jan-2003 01:04
Some gave a function to convert a hex code back into a simple text (human readable ASCII :P)

Some else gave a function that makes use of bin2hex to convert URLs into something like %12%34%56

Here is a function to go from the form %12%34%56 back into ASCII

Note that this function can easily be changed in order to transform any hex code into ASCII

<?
function _hex2text($str) {
    $str = explode('%', $str);
    array_shift($str);
    $nmlstr = '';
    foreach($str as $hexstr) {
      $nmlstr .= chr(base_convert($hexstr, 16, 10));
    }
    return $nmlstr;
}
?>

'hope this helps :)
Regards
-Tsuna
matthew dot eastman at hotpop dot com 08-Oct-2002 10:00
This function undoes it (converts back into ASCII).

<?php
function hex2asc($myin) {
for ($i=0; $i<strlen($myin)/2; $i++) {
$myout.=chr(base_convert(substr($myin,$i*2,2),16,10));
}
return $myout;
}
?>
matt at zevi dot net 21-Aug-2002 02:27
Hopefully this helps someone...

It just displays an html representation of hex data, much like a hex viewer would.

Matt

<?php
function hexview($data){
  $bytePosition = $columnCount = $lineCount = 0;
  $columns = 8;
  $dataLength = strlen($data);
  $return = array();
  $return[] = '<table border="1" cellspacing="0" cellpadding="2">';
  for($n = 0; $n < $dataLength; $n++){
    $lines[$lineCount][$columnCount++] = substr($data, $n, 1);
    if($columnCount == $columns){
      $lineCount++;
      $columnCount = 0;
    }
  }
  foreach($lines as $line){
    $return[] = '<tr><td align="right">'.$bytePosition.': </td>';
    for($n = 0; $n < $columns; $n++){
      $return[] = '<td>'.strtoupper(bin2hex($line[$n])).'</td>';
    }
    $return[] = '<td> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </td>';
    for($n = 0; $n < $columns; $n++){
      $return[] = '<td>'.(htmlentities($line[$n]) ? htmlentities($line[$n]) : '&nbsp;').'</td>';
    }
    $return[] = '</tr>';
    $bytePosition = $bytePosition + $columns;
  }
  $return[] = '</table>';
  return implode('', $return);
}
?>
php at (what spam?) at vaejas dot com 04-Aug-2002 05:01
I have found the above quoted-printable encoding function to be
extremely useful, and thank maxg for making a great function that is not already included in PHP.
(Pity it's hidden all the way over here when it could be found more easily in quoted_printable_decode() )

However, there is one missing character in the code that needs to be included:

Right after the ?Q? there needs to be an extra equal sign in order for the very first character to be translated by the e-mail software.

$string = "=?$charset?Q?=" . $encoded . "?=";
is correct.

I don't yet have enough experience to speak for other caveats or improvements, but your mileage may vary depending on the e-mail server.

- Luke
maxg at hot dot ee 14-Dec-2001 11:47
I wrote the function that is useful for sending emails for example in cyrillic encoding (wondows-1251, koi8-r and so on).
It converts every symbol in the string into hexadecimal presentation with "=" symbol as delimiter.

For example, the string "Регистрационный код для" will look like that:
=d0=e5=e3=e8=f1=f2=f0=e0=f6=e8=ee=ed=ed=fb=e9=20=ea=ee=e4=20=e4=eb=ff

I use it for encoding email subject, but it could be modified for anything else.

<?php
function hex4email ($string,$charset)
{
    $string=bin2hex ($string);
    $encoded = chunk_split($string, 2, '=');
    $encoded=preg_replace ("/=$/","",$encoded);
    $string="=?$charset?Q?".$encoded."?=";

return $string;
}
?>
tightcode at hotmail dot com 25-Aug-2001 08:05
I was just browsing the above and with a little modification,
came up with the following which I believe to be more flexible:

<?php
function bin2hex($data) {
    $corrected = ereg_replace("[^0-9a-fA-F]","",$data);
    return pack("H".strlen($corrected),$corrected);
}
?>

This will make sure that whatever you pass, even if it is padded
at the extremeties or between pairs, should return the desired data.
pedram at redhive dot com 31-Jan-2001 05:21
In an attempt to dodge spam bots I've seen people (including myself) hex encode their email addresses in "mailto" tags. This is the small chunk of code I wrote to automate the process:

<?php
function hex_encode ($email_address)    {
        $encoded = bin2hex("$email_address");
        $encoded = chunk_split($encoded, 2, '%');
        $encoded = '%' . substr($encoded, 0, strlen($encoded) - 1);
        return $encoded;
}
?>

so for example:
<a href="mailto:&lt;?=hex_encode("pedram@redhive.com")?>">email me</a>

would produce the following address:
%70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d

-pedram
addslashes
chop
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє


Псевдоним rtrim

bin2hex
chr
Обработка строк
PHP Manual

chop

(PHP 4, PHP 5)

chop — Псевдоним rtrim()

Описание

Эта функция является псевдонимом: rtrim().

Примечания

Замечание:

Действие chop() отличается от одноименной функции chop() языка Perl, удаляющей последний символ строки.

User Contributed Notes

tomas at matfyz dot cz 24-May-2010 05:47
This function corresponds more or less to the PERL chomp() function.
rahuls8730 at gmail dot com 17-May-2009 11:03
Definition and Usage

The chop() function will remove a white space or other predefined character from the right end of a string.

This function is an alias of the rtrim() function.
Syntax
chop(string,charlist)

Parameter     Description
string     Required. Specifies the string to check
charlist     Optional. Specifies which characters to remove from the string.
The following characters are allowed and is set to be removed if the charlist parameter is empty:

    * "\0" - ASCII 0, NULL
    * "\t" - ASCII 9, a tab
    * "\n" - ASCII 10, a new line
    * "\x0B" - ASCII 11, a vertical tab.
    * "\r" - ASCII 13, a carriage return
    * " " - ASCII 32, an ordinary white space
anon at mailinator dot com 11-May-2007 01:06
Another possible one would be to use this:

<?php
function chup(){

$ar=Array();

foreach(func_get_args() as $b) {

push($ar,$b[strlen($b)-1]);

&$b[strlen($b)-1]='';

  }

return $ar;

 }
?>

If you wanted to perl-chop a va list of strings and return the removed chars. Obviously you can easily mod it for va list arrays of strings and the like.
bin2hex
chr
Обработка строк


Возвращает символ по его коду

chop
chunk_split
Обработка строк
PHP Manual

chr

(PHP 4, PHP 5)

chr — Возвращает символ по его коду

Описание

string chr ( int $ascii )

Возвращает строку из одного символа, код которого задан аргументом ascii.

Эта функция дополняет функцию ord().

Список параметров

ascii

ASCII-код.

Возвращаемые значения

Возвращает символ по его коду.

Примеры

Пример #1 Пример использования chr()

<?php
$str = "Эта строка заканчивается на escape: ";
$str .= chr(27); /* добавляет символ escape в конец $str */

/* Но обычно лучше использовать такую конструкцию */

$str = sprintf("The string ends in escape: %c", 27);
?>

Смотрите также

  • Описание формата %c функции sprintf()
  • ord()
  • » Таблица ASCII-кодов

User Contributed Notes

gjarrige at six-axe dot fr 01-Mar-2012 09:47
to remove the ASCII control characters (except "line feed" and "tab") :

$tab_chr = array() ;
for($control = 0; $control < 32; $control++) {
    if ($control != 9 && $control != 10) {
        $tab_chr[]= chr($control) ;
    }
}
$tab_chr[]= chr(127) ;
$string = str_replace($tab_chr, '', $string);
stanislav at nechutny dot net 01-Oct-2011 06:26
There is simple function for converting number to chars. If you want make table like excel where colums are indetified by chars A,B,C...AA,AB.. you can easyli iterate on integer and call this function.
<?php
function numtochars($num,$start=65,$end=90)
{
    $sig = ($num < 0);
    $num = abs($num);
    $str = "";
    $cache = ($end-$start);
    while($num != 0)
    {
        $str = chr(($num%$cache)+$start-1).$str;
        $num = ($num-($num%$cache))/$cache;
    }
    if($sig)
    {
        $str = "-".$str;
    }
    return $str;
}
?>
robin leffmann 24-Sep-2011 08:46
While the documentation appears to imply ASCII character operation only, chr() can actually be used to convert arbitrary byte values into binary content:

<?php

while( @$i++ < 32 )
    $a = chr( mt_rand(0, 255) );

file_put_contents( 'filename', $a );

?>
mailderemi at gmail dot com 04-Feb-2011 08:17
Here is a sample of encoding and decoding using "chr" and "ord".
<?php
    function Encode($txtData,$Level){
        for ($j = 0;$j<$Level;$j++){
            $tmpStr = '';
            for ($i = 0;$i<strlen($txtData);$i++)
                $tmpStr .= ord(substr(strtoupper($txtData), $i, 1));
            $txtData = $tmpStr;
        }
        return (strlen($Level)).$Level.$txtData;
    }

    function Decode($txtData){
        $intLevel = substr($txtData, 1, substr($txtData, 0, 1));
        $startStr = substr($txtData, substr($txtData, 0, 1)+1, strlen($txtData));
        for ($j = 0;$j<$intLevel;$j++){
            for ($i = 0;$i<strlen($startStr);$i+=2)
                $tmpStr .= chr(intval(substr($startStr, $i, 2)));
            $startStr = $tmpStr;

            $tmpStr = "";
        }
        return $startStr;
    }

echo Encode('123',4).'<br>';
echo Decode(Encode('123',5));
?>
Icar 11-Mar-2010 08:31
Here is code for generation Russian alphabet:
<?php
for ($i=176;$i<=207;++$i) {
    echo $i.'='.iconv('ISO-8859-5', 'UTF-8', chr($i)).'<br>';
}
?>
This simple code generates all Russian capital letters, but without 'Ё'.
Emprivo.com 01-Sep-2009 07:36
Replaces special characters with non-special equivalents

<?php
function normalize_special_characters( $str )
{
    # Quotes cleanup
    $str = ereg_replace( chr(ord("`")), "'", $str );        # `
    $str = ereg_replace( chr(ord("´")), "'", $str );        # ´
    $str = ereg_replace( chr(ord("„")), ",", $str );        # „
    $str = ereg_replace( chr(ord("`")), "'", $str );        # `
    $str = ereg_replace( chr(ord("´")), "'", $str );        # ´
    $str = ereg_replace( chr(ord("“")), "\"", $str );        # “
    $str = ereg_replace( chr(ord("”")), "\"", $str );        # ”
    $str = ereg_replace( chr(ord("´")), "'", $str );        # ´

    $unwanted_array = array(    'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                                'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
                                'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
                                'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
                                'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
    $str = strtr( $str, $unwanted_array );

    # Bullets, dashes, and trademarks
    $str = ereg_replace( chr(149), "&#8226;", $str );    # bullet •
    $str = ereg_replace( chr(150), "&ndash;", $str );    # en dash
    $str = ereg_replace( chr(151), "&mdash;", $str );    # em dash
    $str = ereg_replace( chr(153), "&#8482;", $str );    # trademark
    $str = ereg_replace( chr(169), "&copy;", $str );    # copyright mark
    $str = ereg_replace( chr(174), "&reg;", $str );        # registration mark

    return $str;
}
?>
sinfocol at sinfocol dot org 30-Jun-2009 02:38
The function chr() also accepts negative numbers as an ascii code, so chr(-number) is equal to chr((number%256)+256).
And for ascii code higher than 255 is chr(number%256)

We can test with a little script
<?php
    for($i=-300; $i<300; $i++){
        echo "Ascii $i\t" . ord(chr($i)) . "\n";
    }
?>
glen at glencooper dot com 10-Mar-2009 11:27
Thank you joeldegan for your termcolored function.  I write a lot of command-line scripts using PHP and like to colorize them.  I was having a problem with the termcolored function where the next character echo'ed after calling termcolored() was being dropped.  Turns out you don't need the extra chr(27) at the end of each term color code.

Here's my modified version of your function, renamed to echocolor.

<?php
function echocolor($text,$color="normal",$back=0)
{
  $colors = array('light_red'  => "[1;31m", 'light_green' => "[1;32m", 'yellow'     => "[1;33m",
                  'light_blue' => "[1;34m", 'magenta'     => "[1;35m", 'light_cyan' => "[1;36m",
                  'white'      => "[1;37m", 'normal'      => "[0m",    'black'      => "[0;30m",
                  'red'        => "[0;31m", 'green'       => "[0;32m", 'brown'      => "[0;33m",
                  'blue'       => "[0;34m", 'cyan'        => "[0;36m", 'bold'       => "[1m",
                  'underscore' => "[4m",    'reverse'     => "[7m" );
  $out = $colors["$color"];
  $ech = chr(27)."$out"."$text".chr(27)."[0m";
  if($back)
  {
    return $ech;
  }
  else
  {
    echo $ech;
  }
}
?>
voromax 31-Jan-2009 07:39
Another quick and short function to get unicode char by its code.

<?php
/**
 * Return unicode char by its code
 *
 * @param int $u
 * @return char
 */
function unichr($u) {
    return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
?>
jacob at loggy punt nl 31-Dec-2008 05:46
This function creates a ascii table, and replaces all the ascii characters in the mail.
---
Deze functie maakt een ascii tabel, en zet alles juist om.

<?php
 function makeASCII($a){
  $find[] = "=\r\n";
  $replace[] = "";

  for($i=0; $i < 256; $i++){
    $find[] = "=".dechex($i)."";
    $replace[] = chr($i);
  }
  $a = str_replace($find,$replace,$a);
  return $a;
 }
?>
scott at quinlan dot co dot nz 20-Oct-2008 09:51
Secure password generator with a variable maximum amount of symbols.

<?php

function passwdGen($minLength = 8, $maxLength = 12, $maxSymbols = 2)
{
    $symbolCount = 0;

    srand((double)microtime() * 1000003);

    for ($i = 0; $i < rand($minLength, $maxLength); $i++)
    {
        do
        {
            $char = rand(33, 126);

            $symbolCount += $isSymbol = (!in_array($char, range(48, 57)) && !in_array($char, range(65, 90)) && !in_array($char, range(97, 122)));

            if ($symbolCount <= $maxSymbols || !$isSymbol)
            {
                break;
            }
        }
        while (true);

        $passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, $char);
    }

    return $passwd;
}

?>
Josh B. 12-Aug-2008 02:06
In addition to replacing Microsoft Windows smart quotes, as sgaston demonstrated on 2006-02-13, I replace all other Microsoft Windows characters using suggestions[1] published by character code specialist[2] Jukka Korpela.

<?php
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
$str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
$str = str_replace(chr(147), '"', $str);    // left double quote
$str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '-', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
$str = str_replace(chr(152), '~', $str);    // tilde accent
$str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
$str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
?>

[1] On the use of some MS Windows characters in HTML
http://www.cs.tut.fi/~jkorpela/www/windows-chars.html

[2] Unicode Explained by Jukka Korpela
http://www.amazon.com/dp/059610121X/
markem at airmail dot net 09-Jul-2008 03:34
First, the linefeed versus carriage return confusion:

When typewriters were first invented they were manually moved.  You could do a couple of things with them.  You could type on it (which would move the carriage one space to the left as you typed each character), you could hit the backspace key (which would move the carriage one space to the right), press the line feed button (which would cause the carriage to roll up one line), and return (which would move the carriage all the way to the right again).  When electric typewriters came in to being these functions were made into their electronic counterparts. When terminals appeared they were given the same functions just as word processors, text editors, and everything else that deals with the typed word handles them.

When computers first came out though, the dopey people who invented them wanted to distinguish themselves.  One of the ways they did that was to only use some of the commands.  Which is why the Macintosh originally only used the carriage return command and why Linux/Unix only used the line feed command.  This is why there is "\r" (carriage return), "\l" (Line Feed), and "\n" (OS appropriate).  One of the few things that IBM got right was that it should really be <Carriage Return><Line Feed> and not just one or the other.

So like the reason our roads are a certain width is because that was the width of two horses pulling a Roman chariot, the reason we use these terms is because of the humble non-electronic typewriter and how it worked.

Second - I believe that PHP actually generates ANSI characters and not ASCII characters.  Although there were different extended character sets for the ASCII characters (ie: 128-255), the one depicted on the http://www.asciitable.com/ website clearly shows the IBM standardized ASCII extended table.  (ie: If you ran a BASIC program on your computer you would see the set shown on the above website.)  If, however, you print out the characters via the CHR() function in PHP it prints out the ANSI character set.  (ASCII and ANSI are the same for 0-127.)  Although you can get the characters to print (via Unicode) through the CHR() function - this is still simply showing it is using ANSI and not ASCII.  (Because Unicode is an extension of the ANSI character set and not the ASCII character set.)

If this is so (and my tests show it is) - should the documentation be changed to reflect this?  :-?
darkodemon at gmail dot com 27-Apr-2007 04:33
chr() with unicode support

<?php

function uchr ($codes) {
    if (is_scalar($codes)) $codes= func_get_args();
    $str= '';
    foreach ($codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
    return $str;
}

echo uchr(23383); echo '<br/>';
echo uchr(23383,215,23383); echo '<br/>';
echo uchr(array(23383,215,23383,215,23383)); echo '<br/>';

?>
mwgamera at gmail dot com 22-Aug-2006 08:20
Unicode version of chr() using mbstring
<?php
  function unichr($u) {
    return mb_convert_encoding(pack("N",$u), mb_internal_encoding(), 'UCS-4BE');
  }
?>
It returns a string in internal encoding (possibly more than one byte).
JasonLauDotBiz 16-Feb-2006 07:34
I didn't see it here, so here's simple random string generation using char.

<?php
for($i=0; $i<7; $i++){
    $random_string .= chr(rand(0,25)+65);
}
echo $random_string;
?>
sgaston at mercy corps dot ()rg 13-Feb-2006 02:52
I found this function useful as a way to detect and to replace Microsoft Smart Quotes when desplaying info on a webpage.

The following lines seem to do the trick:

<?php
$text = "string containing Microsoft Smart Quotes...";
$chrs = array (chr(150), chr(147), chr(148), chr(146));
$repl = array ("-", "\"", "\"", "'");
$text = str_replace($chrs, $repl, $text);
?>
plugwash at p10link dot net 14-Jan-2006 12:41
bear in mind that php doesn't really care about character sets. php strings are just arbitary byte sequences thier meaning (especailly when you go beyond code 127) depends entirely on whats interpreting the data (in the case of a browser the charset specified in the http headers).
admin at icstrategy dot midgetforhire dot com 08-Jan-2006 10:51
I made a password generator with this function...

<?php
$passlength = 8;
$pass = "";
$i = 0;
while($i <= $passlength)
    {
    $pass .= chr(rand(33,126));
    $i++;
    }
echo $pass;
?>

Ofcourse you can change passlength.

Example of an 8-char password:
AFJ\)t'u}

I realise it isn't compatible for all sites, but most will accept :)
grey - greywyvern - com 19-Aug-2005 07:55
I spent hours looking for a function which would take a numeric HTML entity value and output the appropriate UTF-8 bytes.  I found this at another site and only had to modify it slightly; so I don't take credit for this.

<?php function unichr($dec) {
  if ($dec < 128) {
    $utf = chr($dec);
  } else if ($dec < 2048) {
    $utf = chr(192 + (($dec - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  } else {
    $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
    $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  }
  return $utf;
} ?>

So for example:

<?php

  $str = "Chinese: &#20013;&#25991;";
  $str = preg_replace("/&#(\d{2,5});/e", "unichr($1);", $str);

?>
24-May-2005 07:15
If you want to increment your letter, which is stored as a string, you have to convert it back to an integer first.

<?php
    $letter=strtolower($_GET['letter']);    //You wanted this originally, but not decided you want the previous letter
    $letter=ord($letter);            //Convert to an integer
    $letter=chr($letter-1);            //Convert back to a string, but the previous letter (naturally won't work with A or a)
?>
sarabas at itstudio dot pl 17-Feb-2005 04:26
The following function helped me to generate ascii-only usernames from firstname/lastname containing iso-8859-2 characters. The convertion array was based on contents of 'man iso-8859-2'.

Example: iso2ascii("b&#322;a&#380;ej.&#378;d&#378;b&#322;o") returns "blazej.zdzblo"

<?php
function iso2ascii($str) {
 $arr=array(
  chr(161)=>'A', chr(163)=>'L', chr(165)=>'L', chr(166)=>'S', chr(169)=>'S',
  chr(170)=>'S', chr(171)=>'T', chr(172)=>'Z', chr(174)=>'Z', chr(175)=>'Z',
  chr(177)=>'a', chr(179)=>'l', chr(181)=>'l', chr(182)=>'s', chr(185)=>'s',
  chr(186)=>'s', chr(187)=>'t', chr(188)=>'z', chr(190)=>'z', chr(191)=>'z',
  chr(192)=>'R', chr(193)=>'A', chr(194)=>'A', chr(195)=>'A', chr(196)=>'A',
  chr(197)=>'L', chr(198)=>'C', chr(199)=>'C', chr(200)=>'C', chr(201)=>'E',
  chr(202)=>'E', chr(203)=>'E', chr(204)=>'E', chr(205)=>'I', chr(206)=>'I',
  chr(207)=>'D', chr(208)=>'D', chr(209)=>'N', chr(210)=>'N', chr(211)=>'O',
  chr(212)=>'O', chr(213)=>'O', chr(214)=>'O', chr(216)=>'R', chr(217)=>'U',
  chr(218)=>'U', chr(219)=>'U', chr(220)=>'U', chr(221)=>'Y', chr(222)=>'T',
  chr(223)=>'s', chr(224)=>'r', chr(225)=>'a', chr(226)=>'a', chr(227)=>'a',
  chr(228)=>'a', chr(229)=>'l', chr(230)=>'c', chr(231)=>'c', chr(232)=>'c',
  chr(233)=>'e', chr(234)=>'e', chr(235)=>'e', chr(236)=>'e', chr(237)=>'i',
  chr(238)=>'i', chr(239)=>'d', chr(240)=>'d', chr(241)=>'n', chr(242)=>'n',
  chr(243)=>'o', chr(244)=>'o', chr(245)=>'o', chr(246)=>'o', chr(248)=>'r',
  chr(249)=>'u', chr(250)=>'u', chr(251)=>'u', chr(252)=>'u', chr(253)=>'y',
  chr(254)=>'t'
 );
 return strtr($str,$arr);
}
?>
tenyou at gmail dot com 14-Jul-2004 11:05
When having to deal with parsing an IIS4 or IIS5 metabase dump I wrote a simple function for converting those MS hexidecimal values into their ascii counter parts. Hopefully someone will find use for it.

<?php
function hex_decode($string)  {
        for ($i=0; $i < strlen($string); $i)  {
        $decoded .= chr(hexdec(substr($string,$i,2)));
        $i = (float)($i)+2;
        }
return $decoded;
}
?>
jmartin at prescientsoftware dot com 13-Apr-2004 02:42
Here is a function that will convert column numbers in to a letters for use in a spreadsheet.  It is limited up to 'ZZ' but can easliy by modifed.

<?php
 function col2chr($a){
        if($a<27){
            return strtoupper(chr($a+96));
        }else{
            while($a > 26){
                $b++;
                $a = $a-26;
            }
            $b = strtoupper(chr($b+96));
            $a = strtoupper(chr($a+96));
            return $b.$a;
        }
    }
?>
perrodin at laposte dot net 11-Apr-2004 04:20
Note that if the number is higher than 256, it will return the number mod 256.
For example :
chr(321)=A because A=65(256)
jgray at triangle dash solutions dot com 25-Jul-2003 10:20
Lowercase alphabet:
<?php for($a=97;$a<(97+26);$a++){ echo chr($a); } ?>
infoserv at chollian dot net 24-Jun-2003 08:16
Cutting Korean(2Byte)-String

<?php
function cutStr($str,$len){
    if(strlen($str) > $len){
        $str = substr($str,0,$len - 2);
        if(strlen(substr(strrchr($str," "),1)) % 2)
            $str = substr($str,0,strlen($str) - 1);
        $str .= "..";
    }
    return $str;
}
?>
jcokos 26-Mar-2003 06:12
A quick function that I use to make strings "XML" compliant, changing every special character into their #$... equivalent.

htmlentities doesn't get all of the chars above 127, so the second part of this (which I stole from one of the comments above) finishes the process, returning a nice, xml happy string.

<?php
    function strictify ( $string ) {

        $fixed = htmlentities( $string, ENT_QUOTES );

        $trans_array = array();
        for ($i=127; $i<255; $i++) {
           $trans_array[chr($i)] = "&#" . $i . ";";
        }

        $really_fixed = strtr($fixed, $trans_array);

        return $really_fixed;

    }
?>

HTH
Kristin 06-Mar-2003 08:19
Note that chr(10) is a 'line feed' and chr(13) is a 'carriage return' and they are not the same thing! I found this out while attempting to parse text from forms and text files for inclusion as HTML by replacing all the carriage returns with <BR>'s only to find after many head-scratchings that I should have been looking for line feeds. If anyone can shed some light on what the difference is, please do.

If you're planning on saving text from a form into a database for later display, you'll need to apply the following function so that it gets saved with the proper HTML tags.

<?php
$text = str_replace ( chr(10), "<BR>", $text );
?>

When you want to plug it back into that form for editing you need to convert it back.

<?php
$text = str_replace ( "<BR>", chr(10), $text)
?>

Hope this saves somebody some trouble. :)
joeldegan AT yahoo.com 14-Dec-2002 02:53
Want terminal colors in command line php scripts?

This should take care of that.
<?

$_colors = array(
        'LIGHT_RED'      => "[1;31m",
        'LIGHT_GREEN'     => "[1;32m",
        'YELLOW'     => "[1;33m",
        'LIGHT_BLUE'     => "[1;34m",
        'MAGENTA'     => "[1;35m",
        'LIGHT_CYAN'     => "[1;36m",
        'WHITE'     => "[1;37m",
        'NORMAL'     => "[0m",
        'BLACK'     => "[0;30m",
        'RED'         => "[0;31m",
        'GREEN'     => "[0;32m",
        'BROWN'     => "[0;33m",
        'BLUE'         => "[0;34m",
        'CYAN'         => "[0;36m",
        'BOLD'         => "[1m",
        'UNDERSCORE'     => "[4m",
        'REVERSE'     => "[7m",

);

function termcolored($text, $color="NORMAL", $back=1){
    global $_colors;
    $out = $_colors["$color"];
    if($out == ""){ $out = "[0m"; }
    if($back){
        return chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }else{
        echo chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }//fi
}// end function

echo termcolored("test\n", "BLUE");
?>
gschafer at robandger dot com 08-Nov-2002 04:17
Here's a small function I wrote up to generate random passwords using the chr() function.

<?php
function randPass($len)
{
 $pw = ''; //intialize to be blank
 for($i=0;$i<$len;$i++)
 {
   switch(rand(1,3))
   {
     case 1: $pw.=chr(rand(48,57));  break; //0-9
     case 2: $pw.=chr(rand(65,90));  break; //A-Z
     case 3: $pw.=chr(rand(97,122)); break; //a-z
   }
 }
 return $pw;
}
?>

Example:

<?php
 $password = randPass(10); //assigns 10-character password
?>

I found this useful in my early coding days... I'm sure someone else will too :D
28-Jun-2002 08:05
This bit of code will convert all those lovely tilde,umlaut etc. etc. characters into safe character codes:

<?php
    $trans_array = array();
    for ($i=127; $i<255; $i++) {
        $trans_array[chr($i)] = "&#" . $i . ";";
    }
    $outtext = strtr($intext, $trans_array);
?>
webmaster at project-enigma dot net 13-Apr-2002 12:51
\n == &#13;
Usefull if u want to display multi-line-alt-strings
e.g. <img src="/gifs/php_logo.gif" alt="Here u can see the&#13;PHPLogo&#13;3rd line">
happyevil(at)1218.org 26-Mar-2001 07:31
Here is a function that's help me find what chr(number) outputs what character quicker than typing out 256 echo tags.

<?php
 function listChr(){
  for ($i = 0; $i < 256; ++$i) {
  static $genNum;
  $genNum++;
  echo "chr($genNum) will output '";
  echo (chr($genNum));
  echo "'< br>\n";
  }
}
listChr();
?>

Another helpful chr is #9, being a tab.  Quite using when making error logs.

 $tab = (chr(9));
 echo "<pre>error{$tab}date{$tab}time</pre>";

 -- HappyEvil
ddawsonNOSPAM at execpc dot com 09-May-2000 04:59
[Editor's note:

%c is defined as: "Print the character belonging to the ascii code given"

chr() just gives a string, so you need to use %s, even if the string consists of only one character. This is consistent with other languages.
--Jeroen@php.net]

Learn from my mistake:
Do not expect this to work!

<?php
$c_question = chr(63);
$v_out = sprintf("<%cphp\n", $c_question);
//... more stuff being sprintf'd into v_out here ...
$v_out = sprintf("%s%c>\n", $v_out, $c_question);
$v_fp = fopen("foofile", "w");
if ($v_fp)
{
     fwrite($v_fp, $v_out, strlen($v_out));
     fclose($v_fp);
}
?>

When I did this, foofile contained <NUL NUL NUL NUL NUL>.
I spun my wheels quite awhile looking at fputs, fwrite to verify I was calling those functions correctly.
My mistake was using $c_question = chr(63) instead of
$c_question = 63 (correct).  Then everything worked fine.
chop
chunk_split
Обработка строк


Разбивает строку на фрагменты

chr
convert_cyr_string
Обработка строк
PHP Manual

chunk_split

(PHP 4, PHP 5)

chunk_split — Разбивает строку на фрагменты

Описание

string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] )

Функция используется для разбиения строки на фрагменты, например, для приведения результата функции base64_encode() в соответствие с требованиями RFC 2045. Она вставляет строку end после каждых chunklen символов.

Список параметров

body

Разбиваемая строка.

chunklen

Длина фрагмента.

end

Последовательность символов, используемая в качестве конца строки.

Возвращаемые значения

Возвращает преобразованную строку.

Примеры

Пример #1 Пример использования chunk_split()

<?php
// форматирование данных в соответствии с RFC 2045
$new_string = chunk_split(base64_encode($data));
?>

Смотрите также

  • str_split() - Преобразует строку в массив
  • explode() - Разбивает строку с помощью разделителя
  • split() - Разбиение строки на массив по регулярному выражению
  • wordwrap() - Переносит строку по указанному количеству символов
  • » RFC 2045

User Contributed Notes

qeremy [atta] gmail [dotta] com 28-Feb-2012 03:35
An alternative for unicode strings;

<?php
function chunk_split_unicode($str, $l = 76, $e = "\r\n") {
    $tmp = array_chunk(
        preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $l);
    $str = "";
    foreach ($tmp as $t) {
        $str .= join("", $t) . $e;
    }
    return $str;
}

$str = "Yarım kilo çay, yarım kilo şeker";
echo chunk_split($str, 4) ."\n";
echo chunk_split_unicode($str, 4);
?>

Yar�
�m k
ilo
çay
, ya
rım
 kil
o ş
eker

Yarı
m ki
lo ç
ay,
yarı
m ki
lo ş
eker
belal dot nabeh at gmail dot com 10-Aug-2010 08:02
If you are using UTF-8 charset you will face a problem with Arabic language
to solve this problem i used this function

<?php
function chunk_split_($text,$length,$string_end)
{
    $text = iconv("UTF-8","windows-1256",$text);
    $text = str_split($text);
    foreach($text as $val)
    {
        if($a !== $val)
        {
            $a = $val;
            $x = 0;
        }else{
            $a = $val;
            $x++;
        }
        if($x > $length)
        {
            $new_text .= $val.$string_end;
            $x = 0;
        }else
        {
             $new_text .= $val;
        }

    }
    $new_text = iconv("windows-1256","UTF-8",$new_text);
    return $new_text;
}
?>
Peter from dezzignz.com 05-Apr-2010 06:07
Oops. Here is a correction for the post below.

<?php

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
    }
    return $array;
}

function mb_chunk_split($str, $len, $glue) {
    if (empty($str)) return false;
    $array = mbStringToArray ($str);
    $n = -1;
    $new = '';
    foreach ($array as $char) {
        $n++;
        if ($n < $len) $new .= $char;
        elseif ($n == $len) {
            $new .= $glue . $char;
            $n = 0;
        }
    }
    return $new;
}

// DEMO:
$str = '一二一二一二一二一二';
echo mb_chunk_split($str, 2, '*<br />');

// produces this output:
一二*
一二*
一二*
一二*
一二

?>
Peter from dezzignz.com 05-Apr-2010 04:30
chunk_split() is not multibyte safe. If you ever run into needing the function that is multibyte safe, here you go:

<?php

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
    }
    return $array;
}

function mb_chunk_split($str, $len, $glue) {
    if (empty($str)) return false;
    $array = mbStringToArray ($str);
    $n = 0;
    $new = '';
    foreach ($array as $char) {
        if ($n < $len) $new .= $char;
        elseif ($n == $len) {
            $new .= $glue . $char;
            $n = 0;
        }
        $n++;
    }
    return $new;
}

?>
dampee at earthlink dot net 20-Nov-2009 09:10
I've found this quite useful for simulating various kinds of shuffles with cards.  It is humorous but can imitate multiple deck cuts and other (imperfectly) random events.

<?php
function truffle_shuffle($body, $chunklen = 76, $end = "\r\n")
{
     $chunk = chunk_split($body, $chunklen, "-=blender=-");
     $truffle = explode("-=blender=-",$chunk);
     $shuffle = shuffle($truffle);
     $huknc = implode($end,$shuffle);
     return $huknc;
}
?>
tim at weird spots in my crotch dot com 08-May-2008 02:29
@Royce

I think this is better, since you can still use the ampersand in your text:

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    elseif($c == " ")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
neos at blizzz dot ru 03-May-2008 11:38
"version" of chunk_split for cyrillic characters in UTF-8

public function UTFChunk($Text,$Len = 10,$End = "\r\n")
{
    if(mb_detect_encoding($Text) == "UTF-8")
    {
        return mb_convert_encoding(
                chunk_split(
                    mb_convert_encoding($Text, "KOI8-R","UTF-8"), $Len,$End
                ),
                "UTF-8", "KOI8-R"
            );
    } else
    {
        return chunk_split($Text,$Len,$End);
    }
}

this is example for russian language
Royce 16-Apr-2008 12:31
Here's a version of Chunk Split I wrote that will not split html entities. Useful if you need to inject something in html (in my case, <wbr/> tags to allow for long text wrapping).

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
lehongviet at gmail dot com 29-Jun-2007 03:23
This function works well to cut long para for preview without cutting word. Good for Unicode such as &#7789;

function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
    $xlenint = strpos($xstr," ",$xlenint);
   return substr($xstr,0,$xlenint).$xlaststr;
}
mark [at] d0gz [dot] net 10-Apr-2007 10:12
When using ssmtp for simple command line mailing:

$mail_to = "destination@emailbox.com";
$msg = "this would be an actual base64_encoded gzip msg";
$date = date(r);
$mail  = "X-FROM: root@sender.org \n";
$mail .= "X-TO: ".$mail_to. " \n";
$mail .= "To: ".$mail_to. " \n";
$mail .= "Date: $date \n";
$mail .= "From: root@sender.org \n";
$mail .= "Subject: lifecheck \n";
$mail .= $msg." \n";
exec("echo '$mail' | /usr/sbin/ssmtp ".$mail_to);

be sure to invoke chunk_split() on your message body - ssmtp becomes unhappy with long lines and will subsequently trash  your message.
06-Mar-2007 02:45
in response to "hansvane at yahoo dot com dot ar"

you can do that ALOT easier:

<?php
function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
   return substr($xstr,0,$xlenint).$xlaststr;
}
?>
hansvane at yahoo dot com dot ar 21-Jan-2007 10:06
This function is very simple and many other functions make this on PHP 5 and even some ones in 4 the good think about this one is that work on php 3.0.6 and 4

function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
    $texttoshow = chunk_split($xstr,$xlenint,"\r\n");
    $texttoshow  = split("\r\n",$texttoshow);
    $texttoshow = $texttoshow[0].$xlaststr;
    return $texttoshow;
}

// For use

echo split_hjms_chars("This is your text",6,"...");

// Will return

This i...

It is useful to cut long text on preview lists and if the server it's old.

Hope it helps some one. Hans Svane
chris AT w3style.co DOT uk 14-Aug-2006 12:32
I'm not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP.

In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string.  But in PHP 5.0.4 this does not happen.  This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this.
xamine at gmail dot com 04-Jun-2006 11:06
In reply to "adrian at zhp dot inet dot pl" digit grouping function:
<?php
    $number = strrev(chunk_split (strrev($number), 3,' '));
    //If $number is '1234567', result is '1 234 567'.
?>

There is a much more simple way of doing this, by using the built-in number_format() function.

<?php
   $number = number_format($number,2,"."," ");

   //This will round $number to 2 decimals, use the dot (".")
   //as decimal point, and the space (" ") as thousand sepparator.

?>
kevin @t hyguard,com 03-Oct-2005 07:08
Not quite completely obvious, but...

you can un_chunk_split() by:

$long_str = str_replace( "\r\n", "", $chunked_str );
harish at thespitbox dot net 30-Jul-2005 05:45
another way to group thousands in a number, which is much simpler, is built into PHP :)

www.php.net/number_format
adrian at zhp dot inet dot pl 08-Jul-2005 02:28
If you need to output number formated with thousand's separator, just use it:

$number = strrev(chunk_split (strrev($number), 3,' '));

If $number is '1234567', result is '1 234 567'.
Kevin 25-Jun-2005 04:10
To phpkid:

This is a much simpler solution.

<?php
function longWordWrap($string) {
    $string = str_replace("\n", "\n ", $string); // add a space after newline characters, so that 2 words only seperated by \n are not considered as 1 word
    $words = explode(" ", $string); // now split by space
    foreach ($words as $word) {
        $outstring .= chunk_split($word, 12, " ") . " ";
    }
    return $outstring;
}
?>
Chris 15-Jun-2005 02:18
@phpkid:

You can avoid such long complex code and just use some CSS stuff.

Just add style="table-layout:fixed" in your <td > tag and your problem will be solved.

ciao
phpkid 28-May-2005 10:47
Well I have been having issues with a shoutbox I am coding it would keep expanding the <TD> if there were large words in it but I fixed it with this:

function PadString($String){
    $Exploded = explode(" ", $String);
    $Max_Parts = count($Exploded);

    $CurArray = 0;
    $OutString = '';
    while($CurArray<=$Max_Parts)
    {
        $Peice_Size = strlen($Exploded[$CurArray]);
        if($Peice_Size>15)
        {
            $OutString .= chunk_split($Exploded[$CurArray], 12, " ");
            $CurArray++;
        } else {
            $OutString .= " ".$Exploded[$CurArray];
            $CurArray++;
        }
    }

    return $OutString;
}
mv@NOSPAM 24-Jan-2004 07:39
the best way to solve the problem with the last string added by chunk_split() is:

<?php
$string = '1234';
substr(chunk_split($string, 2, ':'), 0, -1);
// will return 12:34
?>
Danilo 10-Dec-2003 02:51
>> chunk_split will also add the break _after_ the last occurence.

this should be not the problem

substr(chunk_split('FF99FF', 2, ':'),0,8);
will return FF:99:FF
sbarnum at pointsystems dot com 20-Apr-2001 07:46
[Editor's note: You can always use wordwrap('FF99FF', 2, ':', 2); to avoid this]

chunk_split will also add the break _after_ the last occurence.  So, attempting to split a color into base components,
chunk_split('FF99FF', 2, ':');
will return FF:99:FF:
chr
convert_cyr_string
Обработка строк


РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РёР· РѕРґРЅРѕР№ РєРёСЂРёР»Р»РёС‡РµСЃРєРѕР№ РєРѕРґРёСЂРѕРІРєРё РІ РґСЂСѓРіСѓСЋ

chunk_split
convert_uudecode
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє
PHP Manual

convert_cyr_string

(PHP 4, PHP 5)

convert_cyr_string — РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РёР· РѕРґРЅРѕР№ РєРёСЂРёР»Р»РёС‡РµСЃРєРѕР№ РєРѕРґРёСЂРѕРІРєРё РІ РґСЂСѓРіСѓСЋ

РћРїРёСЃР°РЅРёРµ

string convert_cyr_string ( string $str , string $from , string $to )

РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РёР· РѕРґРЅРѕР№ РєРёСЂРёР»Р»РёС‡РµСЃРєРѕР№ РєРѕРґРёСЂРѕРІРєРё РІ РґСЂСѓРіСѓСЋ.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

str

РљРѕРЅРІРµСЂС‚РёСЂСѓРµРјР°СЏ СЃС‚СЂРѕРєР°.

from

РСЃС…РѕРґРЅР°СЏ РєРёСЂРёР»Р»РёС‡РµСЃРєР°СЏ РєРѕРґРёСЂРѕРІРєР°, РѕРґРёРЅ СЃРёРјРІРѕР».

to

Р¦РµР»РµРІР°СЏ РєРёСЂРёР»Р»РёС‡РµСЃРєР°СЏ РєРѕРґРёСЂРѕРІРєР°, РѕРґРёРЅ СЃРёРјРІРѕР».

РџРѕРґРґРµСЂР¶РёРІР°СЋС‚СЃСЏ СЃР»РµРґСѓСЋС‰РёРµ СЃРёРјРІРѕР»С‹:

  • k - koi8-r
  • w - windows-1251
  • i - iso8859-5
  • a - x-cp866
  • d - x-cp866
  • m - x-mac-cyrillic

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ РїСЂРµРѕР±СЂР°Р·РѕРІР°РЅРЅСѓСЋ СЃС‚СЂРѕРєСѓ.

РџСЂРёРјРµС‡Р°РЅРёСЏ

Р—Р°РјРµС‡Р°РЅРёРµ: РС‚Р° С„СѓРЅРєС†РёСЏ Р±РµР·РѕРїР°СЃРЅР° РґР»СЏ РѕР±СЂР°Р±РѕС‚РєРё РґР°РЅРЅС‹С… РІ РґРІРѕРёС‡РЅРѕР№ С„РѕСЂРјРµ.

User Contributed Notes

strrev(&#34;moc dot liamg at voglod dot yilisav&#34;); 20-Feb-2009 12:02
Unfortunately input data must be a string only. But it is may be changed! ;)

To convert multi-dimensional array I use this recursive function:

<?php
function convert_cyr_array($array,$from,$to){
    foreach($array as $key=>$value){
        if(is_array($value)) {
            $result[$key] = convert_cyr_array($value,$from,$to);
            continue;
        }
        $result[$key] = convert_cyr_string($value,$from,$to);
    }
    return $result;
}
?>

An example:

<?php
$array[0] = "СЃР’РњРџР›Рџ";
$array[1] = "Р·РўРҐР«Р‘";
$array[2] = array("РїР—РҐРўР•Р“","СЂРџРќР™Р”РџРў");
$array[3] = array(
                     array("Р±Р Р•РњРЁРЈР™Рћ","РЅР‘РћР”Р‘РўР™Рћ"),
                     array("Р±Р’РўР™Р›РџРЈ","СЂР•РўРЈР™Р›")
                );

$result = convert_cyr_array($array,"k","w");
/* Returns:

Array
(
  [0] => РЇР±Р»РѕРєРѕ
  [1] => Р“СЂСѓС€Р°
  [2] => Array
    (
      [0] => РћРіСѓСЂРµС†
      [1] => РџРѕРјРёРґРѕСЂ
    )
  [3] => Array
    (
      [0] => Array
        (
          [0] => РђРїРµР»СЊСЃРёРЅ
          [1] => РњР°РЅРґР°СЂРёРЅ
        )
      [1] => Array
        (
          [0] => РђР±СЂРёРєРѕСЃ
          [1] => РџРµСЂСЃРёРє
        )
    )
)*/
?>
svet007 at gmail dot com 01-Dec-2008 11:47
The win2utf function below is nice but it needs some cleanup: it uses "if ($c==184)..." condition three times and "if ($c==168)..." twice which makes no sense.
web at uit dot kiev dot ua 13-May-2008 06:51
convert text back from utf8 to windows 1251 (russian and ukrainian letters)

function Utf8ToWin($fcontents) {
    $out = $c1 = '';
    $byte2 = false;
    for ($c = 0;$c < strlen($fcontents);$c++) {
        $i = ord($fcontents[$c]);
        if ($i <= 127) {
            $out .= $fcontents[$c];
        }
        if ($byte2) {
            $new_c2 = ($c1 & 3) * 64 + ($i & 63);
            $new_c1 = ($c1 >> 2) & 5;
            $new_i = $new_c1 * 256 + $new_c2;
            if ($new_i == 1025) {
                $out_i = 168;
            } else {
                if ($new_i == 1105) {
                    $out_i = 184;
                } else {
                    $out_i = $new_i - 848;
                }
            }
            // UKRAINIAN fix
            switch ($out_i){
                case 262: $out_i=179;break;// С–
                case 182: $out_i=178;break;// Р†
                case 260: $out_i=186;break;// С”
                case 180: $out_i=170;break;// Р„
                case 263: $out_i=191;break;// С—
                case 183: $out_i=175;break;// Р‡
                case 321: $out_i=180;break;// Т‘
                case 320: $out_i=165;break;// Тђ
            }
            $out .= chr($out_i);

            $byte2 = false;
        }
        if ( ( $i >> 5) == 6) {
            $c1 = $i;
            $byte2 = true;
        }
    }
    return $out;
}
web at uit dot kiev dot ua 24-Apr-2008 07:42
real convert windows-1251 to utf-8 (ukrainian, russian)

function win2utf($s)    {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
            if ($c==168) { $t.=chr(208).chr(129);  continue; };
            if ($c==184) { $t.=chr(209).chr(145); continue; }; #С‘
            if ($c==168) { $t.=chr(208).chr(129); continue; }; #РЃ
            if ($c==179) { $t.=chr(209).chr(150); continue; }; #С–
            if ($c==178) { $t.=chr(208).chr(134); continue; }; #Р†
            if ($c==191) { $t.=chr(209).chr(151); continue; }; #С—
            if ($c==175) { $t.=chr(208).chr(135); continue; }; #С—
            if ($c==186) { $t.=chr(209).chr(148); continue; }; #С”
            if ($c==170) { $t.=chr(208).chr(132); continue; }; #Р„
            if ($c==180) { $t.=chr(210).chr(145); continue; }; #Т‘
            if ($c==165) { $t.=chr(210).chr(144); continue; }; #Тђ
            if ($c==184) { $t.=chr(209).chr(145); continue; }; #Тђ
   }
   return $t;
}
apoc at ukr dot net 17-Sep-2007 10:43
:) what about NUMBER!!!???

    function Utf8Win($str,$type="w")
    {
        static $conv='';
        if (!is_array($conv))
        {
            $conv = array();
            for($x=128;$x<=143;$x++)
            {
                $conv['u'][]=chr(209).chr($x);
                $conv['w'][]=chr($x+112);
            }
            for($x=144;$x<=191;$x++)
            {
                $conv['u'][]=chr(208).chr($x);
                $conv['w'][]=chr($x+48);
            }
            $conv['u'][]=chr(208).chr(129); // РЃ
            $conv['w'][]=chr(168);
            $conv['u'][]=chr(209).chr(145); // С‘
            $conv['w'][]=chr(184);
            $conv['u'][]=chr(208).chr(135); // Р‡
            $conv['w'][]=chr(175);
            $conv['u'][]=chr(209).chr(151); // С—
            $conv['w'][]=chr(191);
            $conv['u'][]=chr(208).chr(134); // Р†
            $conv['w'][]=chr(178);
            $conv['u'][]=chr(209).chr(150); // С–
            $conv['w'][]=chr(179);
            $conv['u'][]=chr(210).chr(144); // Тђ
            $conv['w'][]=chr(165);
            $conv['u'][]=chr(210).chr(145); // Т‘
            $conv['w'][]=chr(180);
            $conv['u'][]=chr(208).chr(132); // Р„
            $conv['w'][]=chr(170);
            $conv['u'][]=chr(209).chr(148); // С”
            $conv['w'][]=chr(186);
            $conv['u'][]=chr(226).chr(132).chr(150); // в„–
            $conv['w'][]=chr(185);
        }
        if ($type == 'w') { return str_replace($conv['u'],$conv['w'],$str); }
        elseif ($type == 'u') { return str_replace($conv['w'], $conv['u'],$str); }
        else { return $str; }
    }
Vasyl Skotona 14-Sep-2007 09:28
A better function to convert cp1251 string to utf8.
Works with russian and ukrainian text.

function unicod($str) {
    $conv=array();
    for($x=128;$x<=143;$x++) $conv[$x+112]=chr(209).chr($x);
    for($x=144;$x<=191;$x++) $conv[$x+48]=chr(208).chr($x);
    $conv[184]=chr(209).chr(145); #С‘
    $conv[168]=chr(208).chr(129); #РЃ
    $conv[179]=chr(209).chr(150); #С–
    $conv[178]=chr(208).chr(134); #Р†
    $conv[191]=chr(209).chr(151); #С—
    $conv[175]=chr(208).chr(135); #С—
    $conv[186]=chr(209).chr(148); #С”
    $conv[170]=chr(208).chr(132); #Р„
    $conv[180]=chr(210).chr(145); #Т‘
    $conv[165]=chr(210).chr(144); #Тђ
    $conv[184]=chr(209).chr(145); #Тђ
    $ar=str_split($str);
    foreach($ar as $b) if(isset($conv[ord($b)])) $nstr.=$conv[ord($b)]; else $nstr.=$b;
    return $nstr;
}
Sote Korveziroski 24-May-2006 02:53
I have made mistake remove this test line:
         echo "<p>".ord($xchr)."</p>\n";
code should be like this:

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
Sote Korveziroski 24-May-2006 10:24
Only this code works OK for me, for translating win-1251 to utf-8 for macedonian letters!

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         echo "<p>".ord($xchr)."</p>\n";
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
zehyaat] yandex dotru 23-Mar-2006 12:15
Sorry for my previous post. NOT array_reverce, array_flip is actual function. Correct function:

function Encode($str,$type=u)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_flip($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}

Sorry for my English ;)
zehya [at] yandex dotru 23-Mar-2006 11:58
cathody at mail dot ru(27-Jul-2005 06:41)
You function doesn't work on my PC..
It's work:
function Encode2($str,$type)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_reverse($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}
sidor <sidor at sidor dot nnov dot ru> 09-Mar-2006 09:23
Sorry for my English

100% worked function for convertion string to utf-8. In this implementation support main cyrilic encodings (cp1251, koi8-r, cp866, mac) For supporting another codepages - just add needed codepage in $recode array (codes in UCS-4. Add just second part of codetable). Second argument for this function for cyrilic codepages - like in convert_cyr_string function ('k','w','a','d','m')
Writed in accordance with rfc2279

Created by Andrey A Sidorenko aka sidor

http://sidor.nnov.ru/str2utf.txt
Timuretis 06-Nov-2005 06:56
// Modificated by tapin13
// Corrected by Timuretis
// Convert win-1251 to utf-8

 function unicode_russian($str) {
     $encode = "";
//    1025 = "&#1025;";
//    1105 = "&#1105;";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 168) {
//             $xchr = "&#1025";
               $xchr = "&#1025;"; //!!!!!!!!!!!!!!!!!!!!!!!
         }
         if(ord($xchr) == 184) {
//             $xchr = "&#1105";
               $xchr = "&#1105;"; //!!!!!!!!!!!!!!!!!!!!!!
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
tapin13 at atilian dot co dot il 18-Oct-2005 02:20
// Modificated by tapin13
// Convert win-1251 to utf-8

 function unicode_russian($str) {
     $encode = "";
//     1025 = "&#1025;";
//     1105 = "&#1105;";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 168) {
             $xchr = "&#1025";
         }
         if(ord($xchr) == 184) {
             $xchr = "&#1105";
         }
         $encode=$encode . $xchr;
    }
     return $encode;
}
webmaster at chassidus dot ru 29-Aug-2005 10:51
//I've also built the same way for hebrew to utf converting

function heb2utf($s) {

    for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=224 )    {$t.=chr(215).chr($c-80); continue; }

   }
    return $t;
}

//Simple unicoder and decoder for hebrew and russian:

function unicode_hebrew($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>223) {
            $xchr=ord($xchr)+1264;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function unicode_russian($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>191) {
            $xchr=ord($xchr)+848;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function decode_unicoded_hebrew($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1456 and $code<=1514) { //hebrew
                   $code=$code-1264;
                $xchr=chr($code);
               } else { //other unicode
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else //not unicode
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}

function decode_unicoded_russian($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1040 and $code<=1103) {
                   $code=$code-848;
                $xchr=chr($code);
               } else {
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}
cathody at mail dot ru 27-Jul-2005 06:41
Praising other people for their efforts to write a convenient UTF8 to Win-1251 functions may I mention that, since str_replace allows arrays as parameters, the function may be rewritten in a slightly efficient way (moreover, the array generated may be stored for performance improvement):

<?php

 function Encode ( $str, $type )
{
 // $type:
// 'w' - encodes from UTF to win
 // 'u' - encodes from win to UTF

    static $conv='';
    if (!is_array ( $conv ))
    {
        $conv=array ();
        for ( $x=128; $x <=143; $x++ )
        {
          $conv['utf'][]=chr(209).chr($x);
          $conv['win'][]=chr($x+112);
        }

        for ( $x=144; $x <=191; $x++ )
        {
               $conv['utf'][]=chr(208).chr($x);
               $conv['win'][]=chr($x+48);
        }

        $conv['utf'][]=chr(208).chr(129);
        $conv['win'][]=chr(168);
        $conv['utf'][]=chr(209).chr(145);
        $conv['win'][]=chr(184);
     }
     if ( $type=='w' )
          return str_replace ( $conv['utf'], $conv['win'], $str );
     elseif ( $type=='u' )
          return str_replace ( $conv['win'], $conv['utf'], $str );
     else
        return $str;
  }
?>
artyomch at coolfold dot com 26-Apr-2005 01:38
I needed a code for taking UTF8 encoded string from DB and printing it in Win1251 encoded HTML. The problem was that I had to print not just english & cyrillic characters, but all characters stored in UTF encoded string (in my case the DB contained english, russian & hebrew characters).
After reading carefully the UTF8 manual, I've written the following code, that converts all non-win1251 characters into html entities (&#XXXX;).

function utf8_2_win1251 ($str_src)
{
    $str_dst = "";
    $i      = 0;
    while ($i<strlen($str_src))
    {
        $code_dst  = 0;
        $code_src1 = ord($str_src[$i]);
        $i++;

        if ($code_src1<=127)
        {
            $str_dst .= chr($code_src1);
            continue;
        }
        else
        if (($code_src1 & 0xE0) == 0xC0)
        {
            $code_src2 = ord($str_src[$i++]);
            if (($code_src2 & 0xC0) != 0x80)
                continue;

            $code_dst = ( ($code_src1 & 0x1F) << 6) + ($code_src2 & 0x3F);
        }
        else
        if (($code_src1 & 0xF0) == 0xE0)
        {
            $code_src2 = ord($str_src[$i++]);
            if (($code_src2 & 0xC0) != 0x80)
                continue;

            $code_src3 = ord($str_src[$i++]);
            if (($code_src3 & 0xC0) != 0x80)
                continue;

            $code_dst = ( ($code_src1 & 0x1F) << 12) + ( ($code_src2 & 0x3F) << 6) + ($code_src3 & 0x3F);
        }
        else
        if (($code_src1 & 0xF8) == 0xF0)
        {
            $code_src2 = ord($str_src[$i++]);
            if (($code_src2 & 0xC0) != 0x80)
                continue;

            $code_src3 = ord($str_src[$i++]);
            if (($code_src3 & 0xC0) != 0x80)
                continue;

            $code_src4 = ord($str_src[$i++]);
            if (($code_src4 & 0xC0) != 0x80)
                continue;

            $code_dst = ( ($code_src1 & 0x1F) << 18) + ( ($code_src2 & 0x3F) << 12) + ( ($code_src3 & 0x3F) << 6) + ($code_src4 & 0x3F);
        }
        else
        {
            continue;
        }

        if ($code_dst)
        {
            if ($code_dst==0x401)
            {
                $str_dst .= "Ё";
            }
            else
            if ($code_dst==0x451)
            {
                $str_dst .= "ё";
            }
            else
            if ( ($code_dst>=0x410) && ($code_dst<=0x44F) )
            {
                $str_dst .= chr ($code_dst-848);
            }
            else
                $str_dst .= "&#{$code_dst};";
        }
    }
    return $str_dst;
}
felix[at]tvpro.net.ru 13-Feb-2005 12:57
Check this code -- exelent to convert win-1251 to UTF-8
just one fix!!!
       if ($c==184) { $t.=chr(209).chr(145); continue; };

Anything more it is not necessary.
It is grateful to threed [at] koralsoft.com
28-Jul-2003 03:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
   if ($c==168) { $t.=chr(208).chr(129);  continue; };
   }
   return $t;
}
?>
webmaster [ at ] platinumgeneration dot com 11-Jan-2005 06:36
Here's a WORKING function to convert from UTF-8 to Windows-1251, if your hosting provider does not support iconv
<?php
for ($c=0;$c<strlen($s);$c++){
    $i=ord($s[$c]);
    if ($i<=127) $out.=$s[$c];
        if ($byte2){
            $new_c2=($c1&3)*64+($i&63);
            $new_c1=($c1>>2)&5;
            $new_i=$new_c1*256+$new_c2;
        if ($new_i==1025){
            $out_i=168;
        } else {
            if ($new_i==1105){
                $out_i=184;
            } else {
                $out_i=$new_i-848;
            }
        }
        $out.=chr($out_i);
        $byte2=false;
        }
    if (($i>>5)==6) {
        $c1=$i;
        $byte2=true;
    }
}
return $out;
}
?>
standov at cgu dot kiev dot ua 08-Dec-2004 01:05
He is improved function to decode win1251->UTF8
<?php
        function win2utf($s){
            $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
            for($i=0; $i<strlen($s); $i++)    {
                $c=ord($s[$i]);
                if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
                elseif ($c>239) $t.=$c209.chr($c-112);
                elseif ($c==184) $t.=$c209.$c209;
                elseif ($c==168)    $t.=$c208.$c129;
                else $t.=$s[$i];
            }
            return $t;
        }
?>
aeon 27-Dec-2003 08:20
threed's function works great, but the replacement for the letter small io (&#1105;) needs to be changed from
<?php
if ($c==184) { $t.=chr(209).chr(209); continue; };
?>

to
<?php
if ($c==184) { $t.=chr(209).chr(145); continue; };
?>

so, the final working result should look like this:
<?php
function win3utf($s) {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
       if ($c==168) { $t.=chr(208).chr(129); continue; };
   }
   return $t;
}
?>
almi at univ dot kiev dot ua 06-Dec-2003 03:43
to convert cyrillic string to UTF-8 you can use icovn() function. It does work!

<?php
echo iconv ('CP1251','UTF-8','some cyr string');
?>

But you should copile your php '--with-iconv=[DIR]'
threed [at] koralsoft.com 28-Jul-2003 04:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
    for($i=0, $m=strlen($s); $i<$m; $i++)    {
        $c=ord($s[$i]);
        if ($c<=127) {$t.=chr($c); continue; }
        if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
        if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
        if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
        if ($c==184) { $t.=chr(209).chr(209); continue; };
    if ($c==168) { $t.=chr(208).chr(129);  continue; };
    }
    return $t;
}
?>
checat at chat dot ru 12-May-2003 04:59
See also more general
http://www.php.net/manual/ref.iconv.php iconv functions (standart in last glibc) and
http://www.php.net/manual/ref.recode.php Recode functions
german at artexpert dot ee 03-May-2003 05:13
previous bit of code (grmaxim's win_to_utf8 function) didn't work for me, so I wrote my own func to convert from win1251 to utf8:

<?php
function win2utf($s) {
    for($i=0,$m=strlen($s);$i<$m;$i++) {
        $c=ord($s[$i]);
        if ($c>127) // convert only special chars
            if     ($c==184)    $t.=chr(209).chr(209); // small io
            elseif ($c==168)    $t.=chr(208).chr(129); // capital io
            else              $t.=($c>239?chr(209):chr(208)).chr($c-48);
        else $t.=$s[$i];
    }
    return $t;
}
?>

Hope this helps
grmaxim at givc dot ru 17-Apr-2003 08:21
I hope it to you we shall help

<?php
function win_to_utf8($str){
$str = convert_cyr_string($str, 'w','i'); // w - windows-1251   to  i - iso8859-5
$str = utf8_encode ($str); //  iso8859-5   to  utf8
return $str;
}

function utf8_to_win($str){
$str = utf8_decode ($str); //  utf8 to iso8859-5
$str = convert_cyr_string($str, 'i','w'); // w - windows-1251   to  i - iso8859-5
return $str;
}
?>

If there are questions - shall help. Good luck friends!!!
pavel_bashkatov at elkogroup dot com 17-Apr-2003 05:20
To: mihailsbo at lycos dot ru
Transliteration could be done easier:

<?
function transliterate($cyrstr)
    {
        $ru = array('A', 'a',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?');

        $en = array('A', 'a',
                    'B', 'b',
                    'V', 'v',
                    'G', 'g',
                    'D', 'd',
                    'E', 'e',
                    'E', 'e',
                    'Zh', 'zh',
                    'Z', 'z',
                    'I', 'i',
                    'J', 'j',
                    'K', 'k',
                    'L', 'l',
                    'M', 'm',
                    'N', 'n',
                    'O', 'o',
                    'P', 'p',
                    'R', 'r',
                    'S', 's',
                    'T', 't',
                    'U', 'u',
                    'F', 'f',
                    'H', 'h',
                    'C', 'c',
                    'Ch', 'ch',
                    'Sh', 'sh',
                    'Sch', 'sch',
                    '\'', '\'',
                    'Y', 'y',
                    '\'', '\'',
                    'E', 'e',
                    'Ju', 'ju',
                    'Ja', 'ja');

        return str_replace($ru, $en, $cyrstr);
    }
?>
mihailsbo at lycos dot ru 03-Mar-2003 03:15
<?php
// Here is a function that may be useful if you wish
// to convert cyrillic text (windows-1251) to english
// letters (e.g. for sending to a cell phone)

function transliterate( $text )
{
  $cyrlet = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'.
            'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';

  $englet = 'ABVGD   ZIJKLMNOPRSTUFHC   `Y`E  '.
            'abvgd   zijklmnoprstufhc   `y`e  ';

  $result = '';
  for ( $i=0; $i<strlen($text); $i++ ) {
    $c1 = $text[ $i ];
    $p1 = strpos( $cyrlet, $c1 );
    if ( $p1 === FALSE ) { $result .= $c1; continue; }

    $ct = $englet[ $p1 ];
    if ( $ct != ' ' ) { $result .= $ct; continue; }
    switch ( $c1 )
    {
      case 'Е':
        $ct = 'Je';
        break;

      case 'е':
        $ct = 'e';
        break;

      case 'Ё':
        $ct = 'Jo';
        break;

      case 'ё':
        $ct = 'jo';
        break;

      case 'Ж':
        $ct = 'Zh';
        break;

      case 'ж':
        $ct = 'zh';
        break;

      case 'Ч':
        $ct = 'Ch';
        break;

      case 'ч':
        $ct = 'ch';
        break;

      case 'Ш':
        $ct = 'Sh';
        break;

      case 'ш':
        $ct = 'sh';
        break;

      case 'Щ':
        $ct = 'Sch';
        break;

      case 'щ':
        $ct = 'sch';
        break;

      case 'Ю':
        $ct = 'Ju';
        break;

      case 'ю':
        $ct = 'ju';
        break;

      case 'Я':
        $ct = 'Ja';
        break;

      case 'я':
        $ct = 'ja';
        break;

      default:
        $ct = '?';
    }
    $result .= $ct;
  }
  return $result;
}
?>

// P.S. Thanks to PHP developers for rich and convenient
// programming language!
mitya at alesh dot ru 25-Sep-2002 02:21
there is a little script that convert  utf to cp1251

<?php
function u8($win,$h,$t) {
  global $w8;
  $w8[chr($h).chr($t)] = $win;
}

$c1 = chr(208);
$c2 = chr(209);

u8("й",208,185); u8("ц",209,134); u8("у",209,131);
u8("к",208,186); u8("е",208,181); u8("н",208,189);
u8("г",208,179); u8("ш",209,136); u8("щ",209,137);
u8("з",208,183); u8("х",209,133); u8("ъ",209,138);
u8("ф",209,132); u8("ы",209,139); u8("в",208,178);
u8("а",208,176); u8("п",208,191); u8("р",209,128);
u8("о",208,190); u8("л",208,187); u8("д",208,180);
u8("ж",208,182); u8("э",209,141); u8("я",209,143);
u8("ч",209,135); u8("с",209,129); u8("м",208,188);
u8("и",208,184); u8("т",209,130); u8("ь",209,140);
u8("б",208,177); u8("ю",209,142); u8("Й",208,153);
u8("Ц",208,166); u8("У",208,163); u8("К",208,154);
u8("Е",208,149); u8("Н",208,157); u8("Г",208,147);
u8("Ш",208,168); u8("Щ",208,169); u8("З",208,151);
u8("Х",208,165); u8("Ъ",208,170); u8("Ф",208,164);
u8("Ы",208,171); u8("В",208,146); u8("А",208,144);
u8("П",208,159); u8("Р",208,160); u8("О",208,158);
u8("Л",208,155); u8("Д",208,148); u8("Ж",208,150);
u8("Э",208,173); u8("Я",208,175); u8("Ч",208,167);
u8("С",208,161); u8("М",208,156); u8("И",208,152);
u8("Т",208,162); u8("Ь",208,172); u8("Б",208,145);
u8("Ю",208,174); u8("ё",209,145); u8("Ё",208,129);

function utf2win ($text) {
  global $c1,$c2,$w8;
  $u = false;
  $temp = "";
  for($i=0,$len=strlen($text); $i<$len; $i++) {
    $c = substr($text,$i,1);
    if ($u) {
      $c = $w8[$lc.$c];
      $temp .= isset($c)?$c:"?";
      $u = false;
    }
    else if ($c==$c1 || $c==$c2) {
      $u = true;
      $lc = $c;
    }
    else
      $temp .= $c;
  }
  return $temp;
}

$text = file("utf8.txt");
foreach($text as $line)
  echo "<br>".utf2win($line);

?>

how it works you can see on http://www.alesh.ru/lj
But there is another function iconv() (http://php.net/iconv) but not all hosters support iconv
mokvas at freemail dot org dot mk 30-Jul-2001 09:45
Not all of cyrilic characters are supported by this function. Cyrilic chars from Macedonian Alphabet like Sh, kj, dz' ,nj are not supported.
chunk_split
convert_uudecode
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє


Декодирует строку из формата uuencode в обычный вид

convert_cyr_string
convert_uuencode
Обработка строк
PHP Manual

convert_uudecode

(PHP 5)

convert_uudecode — Декодирует строку из формата uuencode в обычный вид

Описание

string convert_uudecode ( string $data )

convert_uudecode() декодирует строку из формата uuencode в обычный вид.

Список параметров

data

Данные в формате uuencode.

Возвращаемые значения

Возвращает декодированные данные в виде строки.

Примеры

Пример #1 Пример использования convert_uudecode()

<?php
/* Догадаетесь, что выведет этот код? :) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

Смотрите также

  • convert_uuencode() - Кодирует строку в формат uuencode

User Contributed Notes

Vipindas K.S 09-May-2008 08:58
Code snippet for retrieving Encoded passwords stored in mysql database .
Consider a file named "test.php" consisting of an input form as given below:
<html>
<body>
<form action="test.php"  method="post">
<input type="text" name="fname" id="fname"  />
<input type="password" name="password" id="password"  />
<input type="submit" name="submit" value="submit" />
</form>

<?
/*
below php code takes input field values , encode the password and then store the values in a database .
Create a table named test with fields id,name,password where id is auto incremented..
*/

if(isset($_post['submit']))
{
$fname=$_POST['fname'];
$pass=$_POST['password'];
$encoded_pass=convert_uuencode($pass);
$con=mysql_connect("your hostname","your username","your password"); //connecting to the database
$db=mysql_select_db("your_database_name",$con);
$sql="INSERT INTO test (id,name,password) VALUES('','$fname', '$encoded_pass' )";
$result=mysql_query($sql)or die("unable to insert");

/****encoding and storing ends here******/

/* Code snippet for retrieving the last inserted entry from the database and decoding starts here */

$id2=mysql_insert_id(); // id of the last entry
$sql2="select password from test where id='$id2' ";
$result2=mysql_query($sql2);
$row=mysql_fetch_array($result2);
$decoded_pass=convert_uudecode($row[0]); //decoding takes place here
echo "decoded password: ".$decoded_pass;

}

?>
</body>
</html>
aidan at php dot net 29-May-2005 08:51
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
convert_cyr_string
convert_uuencode
Обработка строк


Кодирует строку в формат uuencode

convert_uudecode
count_chars
Обработка строк
PHP Manual

convert_uuencode

(PHP 5)

convert_uuencode — Кодирует строку в формат uuencode

Описание

string convert_uuencode ( string $data )

convert_uuencode() кодирует строку с помощью алгоритма uuencode.

Кодирование uuencode переводит строки (включая бинарные символы) в последовательности печатных (7-битных) ASCII-символов, что позволяет безопасно обмениваться данными через сеть. Закодированные данные примерно на 35% больше оригинала.

Список параметров

data

Кодируемые данные.

Возвращаемые значения

Возвращает закодированные данные в формате uuencode.

Примеры

Пример #1 Пример использования convert_uuencode()

<?php
$some_string = "test\ntext text\r\n";

echo convert_uuencode($some_string);
?>

Смотрите также

  • convert_uudecode() - Декодирует строку из формата uuencode в обычный вид
  • base64_encode() - Kодирует данные алгоритмом MIME base64

User Contributed Notes

abc518 at gmail dot com 26-Sep-2008 01:06
Using uuencode for passwords isn't any more secure than plain text (maybe slightly: non-developers or too lazy to figure out what you used). mcrypt or even md5 is much more secure.
zash at zash dot se 30-May-2008 12:30
note that using base64 or uuencode to store data in a database is pretty useless. if you properly escape your data and use a binary field (BLOB etc) there is no problem.
allali at labri dot fr 02-Apr-2008 12:06
if you want to use convert_uuencode with command uudecode you must insert a line "begin %s %s\n" at the beginning and "end\n" at the end:

<?php

echo "begin 644 hello.txt\n";
echo convert_uuencode("hello");
echo "end\n";

?>

the first arg. after begin is the mode (destination file rights), the second is the destination file name.

Then you can do a wget followed by a uudecode.

JA.
root at mantoru dot de 10-Nov-2007 09:29
@Craig's note: base64_encode() is better suited for that. In fact, it produces smaller output and operates slightly faster. I did a little benchmark -- here are my findings:

File: JPG, 631614 bytes

== Base64 ==
execution time: 0.0039639472961426 secs
output length: 842152

== UUencode ==
execution time: 0.004105806350708 secs
output length: 870226
tmaschler at NOSPAM dot ditf-denkendorf dot de 20-Sep-2006 01:46
Note to the tip of Craig at frostycoolslug dot com:

If you are using fulltext functionality on columns with uuencoded texts, collations will not work. You might prefer to pass the text escaped to the database engine.
nmmm at nmmm dot nu 12-Apr-2006 08:17
uuencode is recognisable as email attachment in Ms Outlook, but in Outlook Express (at least in older versions) - is not.

This is shell script, but it may give you an idea how you can send attachments using uuencode:

cat file.bin | uuencode file.bin | mail someone@domain.com -s "file.bin"

uuencode mail attachments from other point of wiev are deprecated. However I use such technic for years now and it work well.
aidan at php dot net 29-May-2005 08:51
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
Craig at frostycoolslug dot com 08-Aug-2004 07:15
This function can be useful if you wish to store files in a MySQL database, it will save any problems with obscure binary data breaking the queries.

just remember to convery-uudecode before you try to use the data again.

(A common example of something that uses this system, would be email attachments)
convert_uudecode
count_chars
Обработка строк


Возвращает информацию о символах, входящих в строку

convert_uuencode
crc32
Обработка строк
PHP Manual

count_chars

(PHP 4, PHP 5)

count_chars — Возвращает информацию о символах, входящих в строку

Описание

mixed count_chars ( string $string [, int $mode = 0 ] )

Подсчитывает количество вхождений каждого из символов с ASII-кодами в диапазоне (0..255) в строке string и возвращает эту информацию в различных форматах.

Список параметров

string

Исследуемая строка.

mode

Смотрите возвращаемые значения.

Возвращаемые значения

В зависимости от параметра mode count_chars() возвращает одно из следующих значений:

  • 0 - массив, индексами которого являются ASCII-коды, а значениями - число вхождений соответствующего символа.
  • 1 - то же, что и для 0, но информация о символах с нулевым числом вхождений не включается в массив.
  • 2 - то же, что и для 0, но в массив включается информация только о символах с нулевым числом вхождений.
  • 3 - строка, содержащая все уникальные символы в исследуемой строке.
  • 4 - строка, состоящая из символов, которые не входят в исходую строку.

Примеры

Пример #1 Пример использования count_chars()

<?php
$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i => $val) {
   echo "\"" , chr($i) , "\" встречается в строке $val раз(а).\n";
}
?>

Результат выполнения данного примера:

" " встречается в строке 4 раз(а).
"." встречается в строке 1 раз(а).
"F" встречается в строке 1 раз(а).
"T" встречается в строке 2 раз(а).
"a" встречается в строке 1 раз(а).
"d" встречается в строке 1 раз(а).
"e" встречается в строке 1 раз(а).
"n" встречается в строке 2 раз(а).
"o" встречается в строке 2 раз(а).
"s" встречается в строке 1 раз(а).
"w" встречается в строке 1 раз(а).

Смотрите также

  • strpos() - Возвращает позицию первого вхождения подстроки
  • substr_count() - Возвращает число вхождений подстроки

User Contributed Notes

marcus33cz 01-Feb-2012 11:43
If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode "1" of the original function.

<?php
/**
 * Counts character occurences in a multibyte string
 * @param string $input UTF-8 data
 * @return array associative array of characters.
 */
function mb_count_chars($input) {
    $l = mb_strlen($input, 'UTF-8');
    $unique = array();
    for($i = 0; $i < $l; $i++) {
        $char = mb_substr($input, $i, 1, 'UTF-8');
        if(!array_key_exists($char, $unique))
            $unique[$char] = 0;
        $unique[$char]++;
    }
    return $unique;
}

$input = "Let's try some Greek letters: αααααΕεΙιΜμΨψ, Russian: ЙЙЫЫЩН, Czech: ěščřžýáíé";
print_r( mb_count_chars($input) );
//returns: Array ( [L] => 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [α] => 5 [Ε] => 1 [ε] => 1 [Ι] => 1 [ι] => 1 [Μ] => 1 [μ] => 1 [Ψ] => 1 [ψ] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [Й] => 2 [Ы] => 2 [Щ] => 1 [Н] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [ě] => 1 [š] => 1 [č] => 1 [ř] => 1 [ž] => 1 [ý] => 1 [á] => 1 [í] => 1 [é] => 1 )
?>
phpC2007 04-Dec-2007 07:42
Here's a function to count number of strings in a string. It can be used as a simple utf8-enabled count_chars (but limited to a single mode)...

<?php
function utf8_count_strings($stringChar)
{
    $num = -1;
    $lenStringChar = strlen($stringChar);

    for ($lastPosition = 0;
        $lastPosition !== false;
        $lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
    {
        $num++;
    }

    return $num;
}
?>
pzb at novell dot com 28-Jul-2007 06:29
This function is great for input validation.  I frequently need to check that all characters in a string are 7-bit ASCII (and not null).  This is the fastest function I have found yet:

<?php
function is7bit($string) {
    // empty strings are 7-bit clean
    if (!strlen($string)) {
        return true;
    }
    // count_chars returns the characters in ascending octet order
    $str = count_chars($str, 3);
    // Check for null character
    if (!ord($str[0])) {
        return false;
    }
    // Check for 8-bit character
    if (ord($str[strlen($str)-1]) & 128) {
        return false;
    }
    return true;
}
?>
Patrick Palka 10-Apr-2007 08:46
A faster unique character-checking function:

<?php
function chr_unique($string) {
  return strlen(count_chars($string, 3));
}
?>
apinpratap at gmail dot com 29-Mar-2007 10:54
this code can find each characters count

<?php
$enter = 0;
$data = strtolower ($inputString);
foreach (count_chars ($data, 1) as $i => $val)
    {
        if ($enter == 1)
        {
            $enter = 0;
            continue;
        }
        if (chr ($i) == "\n")
        {
            echo "There are $val instance(s) of \" Enter \" in the string.\n";
            $enter = 1;
        }
        else
        {
            echo "There are $val instance(s) of \"" , chr ($i) , "\" in the string.\n";
        }
    }
?>
Eric Pecoraro 27-May-2005 07:31
<?php

// Require (n) unique characters in a string
// Modification of a function below which ads some flexibility in how many unique characters are required in a given string.

$pass = '123456' ; // true
$pass = '111222' ; // false

req_unique($pass,3);

function req_unique($string,$unique=3) {
    if ( count(count_chars($string,1)) < $unique) {
        echo 'false';
    }else{
        echo 'true';
    }
}

?>
Alex Gemmell 14-Feb-2005 10:03
Use: Great for checking for unique characters in a password.

I wanted to check that my website users, when registering a user account, chose a "valid" (not-so-easily-guessed) password.

One of the many checks was that the password must have 6 unique characters.  I was tying myself in knots with all kinds of recursive array calling when I was offered this wonderful one line solution:

function check_password($password) {

   #Have 6 unique characters
   if (count(count_chars($password, 1)) < 6) return false;

   #
   # other checks returning false as necessary
   #
   #

   return true;
}

I cannot claim this wonderful line for myself - a Mr Lynch suggested this to me.  Thanks!
seb at synchrocide dot net 16-May-2004 03:08
After much trial and error trying to create a function that finds the number of unique characters in a string I same across count_chars() - my 20+ lines of useless code were wiped for this:

<?
function unichar($string) {
$two= strtolower(str_replace(' ', '', $string));
$res = count(count_chars($two, 1));
return $res;
}

/* examples :: */

echo unichar("bob"); // 2
echo unichar("Invisibility"); //8
echo unichar("The quick brown fox slyly jumped over the lazy dog"); //26

?>

I have no idea where this could be used, but it's quite fun
mlong at mlong dot org 29-Jan-2002 04:27
// Usefulness of the two functions

<?php
 $string="aaabbc";

 // You just want to count the letter a
 $acount=substr_count($string,"a");

 // You want to count both letter a and letter b
 $counts=count_chars($string,0);
 $acount=$counts[ord("a")];
 $bcount=$counts[ord("b")];
?>
maotin at hongkong dot com 31-Jan-2001 05:04
Here are some more experiments on this relatively new and extremely handy function.

<?php
$string = 'I have never seen ANYTHING like that before! My number is "4670-9394".';

foreach(count_chars($string, 1) as $chr => $hit)
echo 'The character '.chr(34).chr($chr).chr(34).' has appeared in this string '.$hit.' times.<BR>';

#The result looks like
#The character " " has appeared in this string 11 times.

echo count_chars($string,3);
#The output is '!"-.034679AGHIMNTYabefhiklmnorstuvy'

echo strlen($string).' is not the same as '.strlen(count_chars($string, 3));

#This shows that '70 is not the same as 36'
?>

As we can see above:

1)If you cares only about what is in the string, use count_chars($string, 1) and it will return an (associative?) array of what shows up only.

2) Either I misunderstood what the manul actually said, or it does not work the way it described: count_chars($strting, 3) actually returned a string of what characters are in the string, not a string of their byte-values (which is great because a string of numbers would be much harder to handle);

3)This is a short version of password checking: get the original string's length, then compare with the length of the string returned by count_chars($string,3).

<?php
$length_of_string = strlen($string);
$num_of_chars = strlen(count_chars($string, 3));

$diff = ($length_of_string - $num_of_chars);

if ($diff)
echo 'At least one character has been used more than once.';
else
echo 'All character have been used only once.;
?>

Note that since $num_of_chars gives no information about the actual number of occurance, we cannot go any further by the same rationale and say when $diff =2 then 2 characters showed up twice; it might be 1 character showd up 3 times, we have no way to tell (a good tolerance level setter, though).  You have to get the array and check the values if you want to have more control.

4) Final trick: now we have a primitive way to count the number of words in a string! (or do we have a fuction for that already?)
convert_uuencode
crc32
Обработка строк


Вычисляет полином CRC32 для строки

count_chars
crypt
Обработка строк
PHP Manual

crc32

(PHP 4 >= 4.0.1, PHP 5)

crc32 — Вычисляет полином CRC32 для строки

Описание

int crc32 ( string $str )

Функция вычисляет циклический избыточный код 32-битных полиномов (CRC32) для строки str. Это обычно используется для контроля целостности передаваемых данных.

В PHP целые числа имеют знак, поэтому многие контрольные суммы могут оказаться отрицательными. Для получения строкового представления CRC32 без знака используйте формат "%u" в функциях sprintf() или printf().

Список параметров

str

Данные.

Возвращаемые значения

Возвращает контрольную сумму crc32 строки str в виде целого числа.

Примеры

Пример #1 Вывод контрольной суммы CRC32

Этот пример иллюстрирует вывод вычисленной контрольной суммы с помощью функции printf():

<?php
$checksum = crc32("Быстрый коричневый лис перепрыгнул через ленивую собаку.");
printf("%u\n", $checksum);
?>

Смотрите также

  • md5() - Возвращает MD5-хэш строки
  • sha1() - Возвращает SHA1-хэш строки

User Contributed Notes

alban dot lopez+php [ at ] gmail dot com 26-Nov-2011 06:02
I made this code to verify Transmition with Vantage Pro2 ( weather station ) based on CRC16-CCITT standard.

<?php
// CRC16-CCITT validator
$crc_table = array(
    0x0,  0x1021,  0x2042,  0x3063,  0x4084,  0x50a5,  0x60c6,  0x70e7,
        0x8108,  0x9129,  0xa14a,  0xb16b,  0xc18c,  0xd1ad,  0xe1ce,  0xf1ef,
        0x1231,  0x210,  0x3273,  0x2252,  0x52b5,  0x4294,  0x72f7,  0x62d6,
        0x9339,  0x8318,  0xb37b,  0xa35a,  0xd3bd,  0xc39c,  0xf3ff,  0xe3de,
        0x2462,  0x3443,  0x420,  0x1401,  0x64e6,  0x74c7,  0x44a4,  0x5485,
        0xa56a,  0xb54b,  0x8528,  0x9509,  0xe5ee,  0xf5cf,  0xc5ac,  0xd58d,
        0x3653,  0x2672,  0x1611,  0x630,  0x76d7,  0x66f6,  0x5695,  0x46b4,
        0xb75b,  0xa77a,  0x9719,  0x8738,  0xf7df,  0xe7fe,  0xd79d,  0xc7bc,
        0x48c4,  0x58e5,  0x6886,  0x78a7,  0x840,  0x1861,  0x2802,  0x3823,
        0xc9cc,  0xd9ed,  0xe98e,  0xf9af,  0x8948,  0x9969,  0xa90a,  0xb92b,
        0x5af5,  0x4ad4,  0x7ab7,  0x6a96,  0x1a71,  0xa50,  0x3a33,  0x2a12,
        0xdbfd,  0xcbdc,  0xfbbf,  0xeb9e,  0x9b79,  0x8b58,  0xbb3b,  0xab1a,
        0x6ca6,  0x7c87,  0x4ce4,  0x5cc5,  0x2c22,  0x3c03,  0xc60,  0x1c41,
        0xedae,  0xfd8f,  0xcdec,  0xddcd,  0xad2a,  0xbd0b,  0x8d68,  0x9d49,
        0x7e97,  0x6eb6,  0x5ed5,  0x4ef4,  0x3e13,  0x2e32,  0x1e51,  0xe70,
        0xff9f,  0xefbe,  0xdfdd,  0xcffc,  0xbf1b,  0xaf3a,  0x9f59,  0x8f78,
        0x9188,  0x81a9,  0xb1ca,  0xa1eb,  0xd10c,  0xc12d,  0xf14e,  0xe16f,
        0x1080,  0xa1,  0x30c2,  0x20e3,  0x5004,  0x4025,  0x7046,  0x6067,
        0x83b9,  0x9398,  0xa3fb,  0xb3da,  0xc33d,  0xd31c,  0xe37f,  0xf35e,
        0x2b1,  0x1290,  0x22f3,  0x32d2,  0x4235,  0x5214,  0x6277,  0x7256,
        0xb5ea,  0xa5cb,  0x95a8,  0x8589,  0xf56e,  0xe54f,  0xd52c,  0xc50d,
        0x34e2,  0x24c3,  0x14a0,  0x481,  0x7466,  0x6447,  0x5424,  0x4405,
        0xa7db,  0xb7fa,  0x8799,  0x97b8,  0xe75f,  0xf77e,  0xc71d,  0xd73c,
        0x26d3,  0x36f2,  0x691,  0x16b0,  0x6657,  0x7676,  0x4615,  0x5634,
        0xd94c,  0xc96d,  0xf90e,  0xe92f,  0x99c8,  0x89e9,  0xb98a,  0xa9ab,
        0x5844,  0x4865,  0x7806,  0x6827,  0x18c0,  0x8e1,  0x3882,  0x28a3,
        0xcb7d,  0xdb5c,  0xeb3f,  0xfb1e,  0x8bf9,  0x9bd8,  0xabbb,  0xbb9a,
        0x4a75,  0x5a54,  0x6a37,  0x7a16,  0xaf1,  0x1ad0,  0x2ab3,  0x3a92,
        0xfd2e,  0xed0f,  0xdd6c,  0xcd4d,  0xbdaa,  0xad8b,  0x9de8,  0x8dc9,
        0x7c26,  0x6c07,  0x5c64,  0x4c45,  0x3ca2,  0x2c83,  0x1ce0,  0xcc1,
        0xef1f,  0xff3e,  0xcf5d,  0xdf7c,  0xaf9b,  0xbfba,  0x8fd9,  0x9ff8,
        0x6e17,  0x7e36,  0x4e55,  0x5e74,  0x2e93,  0x3eb2,  0xed1,  0x1ef0);

    $test = chr(0xC6).chr(0xCE).chr(0xA2).chr(0x03); // CRC16-CCITT = 0xE2B4
    genCRC ($test);

function genCRC (&$ptr)
{
    $crc = 0x0000;
    $crc_table = $GLOBALS['crc_table'];
    for ($i = 0; $i < strlen($ptr); $i++)
        $crc =  $crc_table[(($crc>>8) ^ ord($ptr[$i]))] ^ (($crc<<8) & 0x00FFFF);
    return $crc;
}
?>
arris at zsolttech dot com 19-Oct-2011 05:17
not found anywhere crc64 based on http://bioinfadmin.cs.ucl.ac.uk/downloads/crc64/crc64.c .

(use gmp module)

<?php

/* OLDCRC */
define('POLY64REV', "d800000000000000");
define('INITIALCRC', "0000000000000000");
define('TABLELEN', 256);
/* NEWCRC */
// define('POLY64REV', "95AC9329AC4BC9B5");
// define('INITIALCRC', "FFFFFFFFFFFFFFFF");

if(function_exists('gmp_init')){
        class CRC64{

                private static $CRCTable = array();

                public static function encode($seq){

                        $crc = gmp_init(INITIALCRC, 16);
                        $init = FALSE;
                        $poly64rev = gmp_init(POLY64REV, 16);

                        if (!$init)
                        {
                                $init = TRUE;
                                for ($i = 0; $i < TABLELEN; $i++)
                                {
                                        $part = gmp_init($i, 10);
                                        for ($j = 0; $j < 8; $j++)
                                        {
                                                if (gmp_strval(gmp_and($part, "0x1")) != "0"){
                                                        // if (gmp_testbit($part, 1)){ /* PHP 5 >= 5.3.0, untested */
                                                        $part = gmp_xor(gmp_div_q($part, "2"), $poly64rev);
                                                } else {
                                                        $part = gmp_div_q($part, "2");
                                                }
                                        }
                                        self::$CRCTable[$i] = $part;
                                }
                        }

                        for($k = 0; $k < strlen($seq); $k++){
                                $tmp_gmp_val = gmp_init(ord($seq[$k]), 10);
                                $tableindex = gmp_xor(gmp_and($crc, "0xff"), $tmp_gmp_val);
                                $crc = gmp_div_q($crc, "256");
                                $crc = gmp_xor($crc, self::$CRCTable[gmp_strval($tableindex, 10)]);
                        }

                        $res = gmp_strval($crc, 16);

                        return $res;
                }
        }
} else {
        die("Please install php-gmp package!!!");
}
?>
sukitsupaluk at hotmail dot com 08-Sep-2011 03:04
small sample convert crc32 to character map

<?php

function khash($data) {
    static $map="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hash=crc32($data)+0x100000000;
    $str = "";
    do {
        $str = $map[31+ ($hash % 31)] . $str;
        $hash /= 31;
    } while($hash >= 1);
    return $str;
}
$test= array(null,TRUE,FALSE,0,"0",1,"1","2","3","ab","abc","abcd","abcde","abcdefoo");
$out = array();
foreach($test as $s)
{
    $out[]=khash($s).": ". $s;
}
var_dump($out);

/*
output:
array
  0 => string 'zVvOYTv: ' (length=9)
  1 => string 'xKDKKL8: 1' (length=10)
  2 => string 'zVvOYTv: ' (length=9)
  3 => string 'zOKCQxh: 0' (length=10)
  4 => string 'zOKCQxh: 0' (length=10)
  5 => string 'xKDKKL8: 1' (length=10)
  6 => string 'xKDKKL8: 1' (length=10)
  7 => string 'AFSzIAO: 2' (length=10)
  8 => string 'BXGSvQJ: 3' (length=10)
  9 => string 'xZWOQSu: ab' (length=11)
  10 => string 'AVAwHOR: abc' (length=12)
  11 => string 'zKASNE1: abcd' (length=13)
  12 => string 'xLCTOV7: abcde' (length=14)
  13 => string 'zQLzKMt: abcdefoo' (length=17)

*/

?>
chernyshevsky at hotmail dot com 22-Sep-2010 03:54
The crc32_combine() function provided by petteri at qred dot fi has a bug that causes an infinite loop, a shift operation on a 32-bit signed int might never reach zero. Replacing the function gf2_matrix_times() with the following seems to fix it:

<?php
function gf2_matrix_times($mat, $vec)
{
    $sum=0;
    $i=0;

    while ($vec) {
        if ($vec & 1) {
            $sum ^= $mat[$i];
        }
        $vec = ($vec >> 1) & 0x7FFFFFFF;
        $i++;
    }
    return $sum;
}
?>

Otherwise, it's probably the best solution if you can't use hash_file(). Using a 1meg read buffer, the function only takes twice as long to process a 300meg files than hash_file() in my test.
gabri dot ns at gmail dot com 15-Sep-2010 10:05
if you are looking for a fast function to hash a file, take a look at
http://www.php.net/manual/en/function.hash-file.php
this is crc32 file checker based on a CRC32 guide
it have performance at ~ 625 KB/s on my 2.2GHz Turion
far slower than hash_file('crc32b','filename.ext')
<?php
function crc32_file ($filename)
{
   $f = @fopen($filename,'rb');
   if (!$f) return false;

   static $CRC32Table, $Reflect8Table;
   if (!isset($CRC32Table))
   {
      $Polynomial = 0x04c11db7;
      $topBit = 1 << 31;

      for($i = 0; $i < 256; $i++)
      {
         $remainder = $i << 24;
         for ($j = 0; $j < 8; $j++)
         {
            if ($remainder & $topBit)
               $remainder = ($remainder << 1) ^ $Polynomial;
            else $remainder = $remainder << 1;
         }

         $CRC32Table[$i] = $remainder;

         if (isset($Reflect8Table[$i])) continue;
         $str = str_pad(decbin($i), 8, '0', STR_PAD_LEFT);
         $num = bindec(strrev($str));
         $Reflect8Table[$i] = $num;
         $Reflect8Table[$num] = $i;
      }
   }

   $remainder = 0xffffffff;
   while ($data = fread($f,1024))
   {
      $len = strlen($data);
      for ($i = 0; $i < $len; $i++)
      {
         $byte = $Reflect8Table[ord($data[$i])];
         $index = (($remainder >> 24) & 0xff) ^ $byte;
         $crc = $CRC32Table[$index];
         $remainder = ($remainder << 8) ^ $crc;
      }
   }

   $str = decbin($remainder);
   $str = str_pad($str, 32, '0', STR_PAD_LEFT);
   $remainder = bindec(strrev($str));
   return $remainder ^ 0xffffffff;
}
?>

<?php
$a = microtime();
echo dechex(crc32_file('filename.ext'))."\n";
$b = microtime();
echo array_sum(explode(' ',$b)) - array_sum(explode(' ',$a))."\n";
?>
Output:
ec7369fe
2.384134054184 (or similiar)
carlos at dimension-e dot net 26-Aug-2010 07:36
This crc32 issue on 64 bits servers may not be a bug, but for sure it wracks many applications when the server migrates to a linux 64 bit machine.

For example, many database fields are set to accept signed 32 bits integers. This odd behavior makes those fields to be filled with the 2147483647 value, which es the higest possible number to be saved in this type of field.

It seems the PHP team regards this as a operative system issue, rather than a language issue, but the result is just the same: You just can not rely on this for data comparison between machines.
jian at theorchard dot com 17-Feb-2010 10:13
This function returns an unsigned integer from a 64-bit Linux platform.  It does return the signed integer from other 32-bit platforms even a 64-bit Windows one.

The reason is because the two constants PHP_INT_SIZE and PHP_INT_MAX have different values on the 64-bit Linux platform.

I've created a work-around function to handle this situation.

<?php
function get_signed_int($in) {
    $int_max = pow(2, 31)-1;
    if ($in > $int_max){
        $out = $in - $int_max * 2 - 2;
    }
    else {
        $out = $in;
    }
    return $out;
}
?>

Hope this helps.
berna (at) gensis (dot) com (dot) br 29-Sep-2009 08:16
For those who want a more familiar return value for the function:

<?php
function strcrc32($text) {
  $crc = crc32($text);
  if ($crc & 0x80000000) {
    $crc ^= 0xffffffff;
    $crc += 1;
    $crc = -$crc;
  }
  return $crc;
}
?>

And to show the result in Hex string:

<?php
function int32_to_hex($value) {
  $value &= 0xffffffff;
  return str_pad(strtoupper(dechex($value)), 8, "0", STR_PAD_LEFT);
}
?>
Anonymous 16-Jul-2009 01:26
<?php
  echo crc32('example')+4294967296;
?>

gives you the same result as the CRC32() function in MySQL (>=4.1)

"SELECT CRC32('example')"

vice versa

"SELECT CRC32('example')-4294967296"

in MySQL gives you the same result as:

<?php
  echo  crc32('example');
?>
angelo (at) mandato (period) com 18-Jan-2008 06:54
From my tests noted below, md5_file() function is the best function for performing file verification. This will remain the case until a native crc32_file() function is added to PHP.

file_crc() function that Bulk at bulksplace dot com posted is the most efficient solution on Windows for small and medium size files.  It is most likely because file_get_contents() uses memory mapping techniques.  Unfortunately on Linux (Fedora), the results were slightly better for md5_file().

sha1_file() on large files is slower than md5_file().  The time it takes for the __crc32_file() function found below is linear to the size of the file.  I would avoid using __crc32_file().  The file_crc() function will fail when using the file_get_contents() if the file is larger than the PHP.ini memory_limit setting.  Windows does not seem to use the memory_limit for file_get_contents(), but I did run into an error 'FATAL: emalloc(): Unable to allocate x bytes' when testing iso files.

I ran the following tests on both WindowsXP and Fedora 4 machines.

<?php
   // File verification tests by Angelo Mandato (angelo [at] mandato {period} com)

   // __crc32_file() is very slow, you can uncomment to test for yourself.
   //require_once('crc32_file.php');
   // Copy and paste the contents of the crc32_file() code found on
   // the php.net crc32 PHP manual page in a new file and save
   // as crc32_file.php in the same directory as this script.

   // Get microseconds
   function GetMicrotime()
   {
       list($usec, $sec) = explode(" ", microtime());
       return ((float)$usec + (float)$sec);
   }

   // file_crc() - function to test
   function file_crc($file)
   {
       $file_string = file_get_contents($file);
       $crc = crc32($file_string);
       return sprintf("%u", $crc);
   }

   $Methods = array('sha1_file()', 'md5_file()', 'file_crc()');
   if( function_exists('__crc32_file') )
       $Methods[] = '__crc32_file()';
   $directory = '/path/to/directory/'; // Don't forget trailing backslash.
   $files = scandir($directory);

   for( $method_index = 0; $method_index < count($Methods); $method_index++ )
   {
       $start_time = GetMicrotime();
       while( list($index,$file) = each($files) )
       {
           if( $file != '.' && $file != '..' && is_file($directory.$file) )
           {
               switch( $method_index )
               {
                   case 0: { // sha1_file()
                       $value = sha1_file($directory.$file);
                   }; break;
                   case 1: { // md5_file()
                       $value = md5_file($directory.$file);
                   }; break;
                   case 2: { // file_crc()
                       $value = file_crc($directory.$file);
                   }; break;
                   case 3: { // __crc32_file()
                       $value = __crc32_file($directory.$file);
                   }; break;
               }
           }
           else // It is not part of our test results, lets remove it from the array
           {
               unset($files[$index]);
           }
       }
       $end_time = GetMicrotime();
       echo sprintf("%s took %.03f seconds to calculate %d files.\n", $Methods[$method_index], $end_time-$start_time, count($files) );
       reset($files); // Reset pointer in array
   }
   echo "file verification tests completed.\n";
?>

It would be nice if a crc32_file() function was added to PHP natively.

I am not sure why anyone removed this post from this thread, but this is very useful information. and I believe it should remain.  If you're the moderator and deleted this before, please contact me and explain why it was removed. This is not a question, a report of a bug nor a feature request.  This is factual information that is useful to all.
dave at jufer dot info 03-Dec-2007 02:15
This function returns the same int value on a 64 bit mc. like the crc32() function on a 32 bit mc.

<?php
function crcKw($num){
    $crc = crc32($num);
    if($crc & 0x80000000){
        $crc ^= 0xffffffff;
        $crc += 1;
        $crc = -$crc;
    }
    return $crc;
}
?>
Ren 03-Oct-2007 11:53
Dealing with 32 bit unsigned values overflowing 32 bit php signed values can be done by adding 0x10000000 to any unexpected negative result, rather than using sprintf.

$i = crc32('1');
printf("%u\n", $i);
if (0 > $i)
{
    // Implicitly casts i as float, and corrects this sign.
    $i += 0x100000000;
}
var_dump($i);

Outputs:

2212294583
float(2212294583)
petteri at qred dot fi 28-Jun-2007 11:03
If you have php version<5.1.2 you might use this.
It's a little bit faster than __crc32_file() :)

Ps. crc32_combine() is ported directly from zlib.

<?php
function crc32_file($filename)
{
    $fp=fopen($filename, "rb");
    $old_crc=false;

    if ($fp != false) {
        $buffer = '';

        while (!feof($fp)) {
            $buffer=fread($fp, 10485760);
            $len=strlen($buffer);
            $t=crc32($buffer);

            if ($old_crc) {
                $crc32=crc32_combine($old_crc, $t, $len);
                $old_crc=$crc32;
            } else {
                $crc32=$old_crc=$t;
            }
        }
        fclose($fp);
    } else {
        print "Cannot open file\n";
    }

    return $crc32;
}

function crc32_combine($crc1, $crc2, $len2)
{
    $odd[0]=0xedb88320;
    $row=1;

    for($n=1;$n<32;$n++) {
        $odd[$n]=$row;
        $row<<=1;
    }

    gf2_matrix_square($even,$odd);
    gf2_matrix_square($odd,$even);

    do {
        /* apply zeros operator for this bit of len2 */
        gf2_matrix_square($even, $odd);

        if ($len2 & 1)
            $crc1=gf2_matrix_times($even, $crc1);

        $len2>>=1;

        /* if no more bits set, then done */
        if ($len2==0)
            break;

        /* another iteration of the loop with odd and even swapped */
        gf2_matrix_square($odd, $even);
        if ($len2 & 1)
            $crc1=gf2_matrix_times($odd, $crc1);
        $len2>>= 1;

    } while ($len2 != 0);

    $crc1 ^= $crc2;
    return $crc1;
}

function gf2_matrix_square(&$square, &$mat)
{
    for ($n=0;$n<32;$n++) {
        $square[$n]=gf2_matrix_times($mat, $mat[$n]);
    }
}

function gf2_matrix_times($mat, $vec)
{
    $sum=0;
    $i=0;
    while ($vec) {
        if ($vec & 1) {
            $sum ^= $mat[$i];
        }
        $vec>>= 1;
        $i++;
    }
    return $sum;
}
?>
slimshady451 20-Jun-2007 02:14
I see a lot of function for crc32_file, but for php version >= 5.1.2 don't forget you can use this :

<?php
function crc32_file($filename)
{
    return hash_file ('CRC32', $filename , FALSE );
}
?>

Using crc32(file_get_contents($filename)) will use too many memory on big file so don't use it.
mail at tristansmis dot nl 30-May-2007 01:36
I used the abs value of this function on a 32-bit system. When porting the code to a 64-bit system I’ve found that the value is different. The following code has the same outcome on both systems.
<?php

   $crc = abs(crc32($string));
   if( $crc & 0x80000000){
      $crc ^= 0xffffffff;
      $crc += 1;
   }

   /* Old solution
    * $crc = abs(crc32($string))
    */

?>
roberto at spadim dot com dot br 07-Apr-2006 09:52
MODBUS RTU, CRC16,
input-> modbus rtu string
output -> 2bytes string, in correct modbus order

<?php
function crc16($string,$length=0){

    $auchCRCHi=array(    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40);
    $auchCRCLo=array(    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4,
                0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
                0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD,
                0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
                0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7,
                0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
                0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE,
                0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
                0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2,
                0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
                0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB,
                0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
                0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91,
                0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
                0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88,
                0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
                0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80,
                0x40);
    $length        =($length<=0?strlen($string):$length);
    $uchCRCHi    =0xFF;
    $uchCRCLo    =0xFF;
    $uIndex        =0;
    for ($i=0;$i<$length;$i++){
        $uIndex        =$uchCRCLo ^ ord(substr($string,$i,1));
        $uchCRCLo    =$uchCRCHi ^ $auchCRCHi[$uIndex];
        $uchCRCHi    =$auchCRCLo[$uIndex] ;
    }
    return(chr($uchCRCLo).chr($uchCRCHi));
}
?>
Bulk at bulksplace dot com 27-Aug-2005 05:46
A faster way I've found to return CRC values of larger files, is instead of using the file()/implode() method used below, is to us file_get_contents() (PHP 4 >= 4.3.0) which uses memory mapping techniques if supported by your OS to enhance performance. Here's my example function:

<?php
// $file is the path to the file you want to check.
function file_crc($file)
{
    $file_string = file_get_contents($file);

    $crc = crc32($file_string);

    return sprintf("%u", $crc);
}

$file_to_crc = /home/path/to/file.jpg;

echo file_crc($file_to_crc); // Outputs CRC value for given file.
?>

I've found in testing this method is MUCH faster for larger binary files.
waldomonster at netjukebox dot demon dot nl 23-Apr-2004 08:48
<?php
$data = 'dot';
echo dechex(crc32($data));
?>

Returns 59278a3
Witch is missing a leading zero.

<?php
$data = 'dot';
echo str_pad(dechex(crc32($data)), 8, '0', STR_PAD_LEFT);
?>

Returns the correct string: 059278a3
arachnid at notdot dot net 13-Apr-2004 08:44
Note that the CRC32 algorithm should NOT be used for cryptographic purposes, or in situations where a hostile/untrusted user is involved, as it is far too easy to generate a hash collision for CRC32 (two different binary strings that have the same CRC32 hash). Instead consider SHA-1 or MD5.
same 01-Feb-2004 05:27
bit by bit crc32 computation

<?php

function bitbybit_crc32($str,$first_call=false){

    //reflection in 32 bits of crc32 polynomial 0x04C11DB7
    $poly_reflected=0xEDB88320;

    //=0xFFFFFFFF; //keep track of register value after each call
    static $reg=0xFFFFFFFF;

    //initialize register on first call
    if($first_call) $reg=0xFFFFFFFF;

    $n=strlen($str);
    $zeros=$n<4 ? $n : 4;

    //xor first $zeros=min(4,strlen($str)) bytes into the register
    for($i=0;$i<$zeros;$i++)
        $reg^=ord($str{$i})<<$i*8;

    //now for the rest of the string
    for($i=4;$i<$n;$i++){
        $next_char=ord($str{$i});
        for($j=0;$j<8;$j++)
            $reg=(($reg>>1&0x7FFFFFFF)|($next_char>>$j&1)<<0x1F)
                ^($reg&1)*$poly_reflected;
    }

    //put in enough zeros at the end
    for($i=0;$i<$zeros*8;$i++)
        $reg=($reg>>1&0x7FFFFFFF)^($reg&1)*$poly_reflected;

    //xor the register with 0xFFFFFFFF
    return ~$reg;
}

$str="123456789"; //whatever
$blocksize=4; //whatever

for($i=0;$i<strlen($str);$i+=$blocksize) $crc=bitbybit_crc32(substr($str,$i,$blocksize),!$i);

?>
xethmir at yournextclient dot com 16-Jul-2003 07:12
This is a really simple way of displaying the crc-32 hexadecimal code/checksum for a file... (absolute paths are more reliable)

<?php
$file = "http://example.com/bar.jpg";

// Read the file into an array
$data = file($file);

// Join the array into a string
$data = implode('', $data);

// Calculate the crc
$crc = crc32($data);

//convert from decimal to hexadecimal
$crchex=DecHex($crc*1);

//echo the result
echo "$crchex";
?>
quix at free dot fr 05-May-2003 01:19
I needed the crc32 of a file that was pretty large, so I didn't want to read it into memory.
So I made this:

<?php
    $GLOBALS['__crc32_table']=array();        // Lookup table array
    __crc32_init_table();

    function __crc32_init_table() {            // Builds lookup table array
        // This is the official polynomial used by
        // CRC-32 in PKZip, WinZip and Ethernet.
        $polynomial = 0x04c11db7;

        // 256 values representing ASCII character codes.
        for($i=0;$i <= 0xFF;++$i) {
            $GLOBALS['__crc32_table'][$i]=(__crc32_reflect($i,8) << 24);
            for($j=0;$j < 8;++$j) {
                $GLOBALS['__crc32_table'][$i]=(($GLOBALS['__crc32_table'][$i] << 1) ^
                    (($GLOBALS['__crc32_table'][$i] & (1 << 31))?$polynomial:0));
            }
            $GLOBALS['__crc32_table'][$i] = __crc32_reflect($GLOBALS['__crc32_table'][$i], 32);
        }
    }

    function __crc32_reflect($ref, $ch) {        // Reflects CRC bits in the lookup table
        $value=0;

        // Swap bit 0 for bit 7, bit 1 for bit 6, etc.
        for($i=1;$i<($ch+1);++$i) {
            if($ref & 1) $value |= (1 << ($ch-$i));
            $ref = (($ref >> 1) & 0x7fffffff);
        }
        return $value;
    }

    function __crc32_string($text) {        // Creates a CRC from a text string
        // Once the lookup table has been filled in by the two functions above,
        // this function creates all CRCs using only the lookup table.

        // You need unsigned variables because negative values
        // introduce high bits where zero bits are required.
        // PHP doesn't have unsigned integers:
        // I've solved this problem by doing a '&' after a '>>'.

        // Start out with all bits set high.
        $crc=0xffffffff;
        $len=strlen($text);

        // Perform the algorithm on each character in the string,
        // using the lookup table values.
        for($i=0;$i < $len;++$i) {
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($text{$i})];
        }

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }

    function __crc32_file($name) {            // Creates a CRC from a file
        // Info: look at __crc32_string

        // Start out with all bits set high.
        $crc=0xffffffff;

        if(($fp=fopen($name,'rb'))===false) return false;

        // Perform the algorithm on each character in file
        for(;;) {
            $i=@fread($fp,1);
            if(strlen($i)==0) break;
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($i)];
        }

        @fclose($fp);

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }
?>
spectrumizer at cycos dot net 29-Dec-2002 03:30
Here is a tested and working CRC16-Algorithm:

<?php
function crc16($string) {
  $crc = 0xFFFF;
  for ($x = 0; $x < strlen ($string); $x++) {
    $crc = $crc ^ ord($string[$x]);
    for ($y = 0; $y < 8; $y++) {
      if (($crc & 0x0001) == 0x0001) {
        $crc = (($crc >> 1) ^ 0xA001);
      } else { $crc = $crc >> 1; }
    }
  }
  return $crc;
}
?>

Regards,
Mario
count_chars
crypt
Обработка строк


Необратимое хэширование строки

crc32
echo
Обработка строк
PHP Manual

crypt

(PHP 4, PHP 5)

crypt — Необратимое хэширование строки

Описание

string crypt ( string $str [, string $salt ] )

crypt() возвращает хэшированную строку, полученную с помощью стандартного алгоритма UNIX, основанного на DES, или другого алгоритма, имеющегося в системе.

Некоторые операционные системы поддерживают несколько алгоритмов хэширования. Иногда стандартный алгоритм, основанный на DES, заменяется алгоритмом на основе MD5. Вид хэширования определяется переданным аргументом salt (соль). До версии PHP 5.3, PHP определял доступные алгоритмы шифрования во время инсталляции, базируясь на системной функции crypt(). Если соль не указана, будет автоматически сгенерирована стандартная случайная двухсимвольная (DES) либо двенадцатисимвольная (MD5) соль, в зависимости от доступности алгоритма MD5 в crypt(). Предопределенная константа CRYPT_SALT_LENGTH позволяет определить максимально доступную длину соли в соответствии с используемыми алгоритмами.

Стандартная функция crypt() на основе DES копирует возвращает соль в качестве первых двух символов возвращаемой строки. Кроме того, она использует только первые восемь символов строки str, поэтому более длинные строки, начинающиеся с тех же восьми символов, сгенерируют один и тот же результат (при использовании одинаковой соли).

На системах, где функция crypt() поддерживает несколько алгоритмов хэширования, следующие константы устанавливаются в 0 или 1 в зависимости от доступности соответствующего алгоритма:

  • CRYPT_STD_DES - Стандартное DES-шифрование с двухсимвольной солью из алфавита "./0-9A-Za-z""./0-9A-Za-z". Использование других символов в соли повлечет за собой отказ работы crypt().
  • CRYPT_EXT_DES - Расширенное DES-шифрование. "Соль" является девятисимвольной строкой, состоящей из символа подчеркивания, за которым следуют 4 байта счетчика итерации и 4 байта соли. Эти данные будут закодированы в виде печатаемых символов, 6 бит на символ, с меньшим значащим символом указанным первым. Значения от 0 до 63 кодируются как "./0-9A-Za-z". Использование других символов в соли повлечет за собой отказ работы crypt().
  • CRYPT_MD5 - MD5-шифрование с 12-символьной солью, начинающейся с $1$
  • CRYPT_BLOWFISH - Blowfish-шифрование со следующей солью: "$2a$", весовой параметр из двух цифр, "$" и 22 цифры из алфавита "./0-9A-Za-z". Использование других символов в соли повлечет за собой возвращение пустой строки. Весовой параметр из двух цифр является двоичным логарифмом счетчика итераций низлежащего хэширующего алгоритма, основанного на Blowfish, и должен быть в диапазоне 04-31, значения вне данного диапазона вызовут отказ crypt().
  • CRYPT_SHA256 - хэш SHA-256 с шестнадцатисимвольной солью, начинающейся с $5$. Если строка с солью начинается с 'rounds=<N>$', число N будет использовано для обозначения количества раундов хэширования, по аналогии с весовым параметром в Blowfish. По умолчанию используемое количество раундов равно 5000, минимально доступно 1000 и максимально 999,999,999. Любой значение вне этого диапазона будет усечено до ближайшего лимита.
  • CRYPT_SHA512 - хэш SHA-512 с шестнадцатисимвольной солью, начинающейся с $6$. Если строка с солью начинается с 'rounds=<N>$', число N будет использовано для обозначения количества раундов хэширования, по аналогии с весовым параметром в Blowfish. По умолчанию используемое количество раундов равно 5000, минимально доступно 1000 и максимально 999,999,999. Любой значение вне этого диапазона будет усечено до ближайшего лимита.

Замечание:

Начиная с версии PHP 5.3.0, PHP использует свою собственную реализацию, которая будет использована при отсутствии в системе какого-либо алгоритма.

Список параметров

str

Хэшируемая строка.

salt

Необязательный параметр с солью, на которой будет основано хэширование. Если не указан, поведение определяется по наличию реализованных алгоритмов в системе и может привести к неожиданным результатам.

Возвращаемые значения

Возвращает хэшированную строку или строку короче 13 символов, гарантированно отличающуюся от соли в случае ошибки.

Список изменений

Версия | Описание
5.3.2 | Добавлено хэширование алгоритмами SHA-256 и SHA-512, основанное на » реализации Ulrich Drepper.
5.3.2 | Исправлено поведение Blowfish при некорректных раундах: теперь возвращается "ошибочная" строка ("*0" или "*1") вместо отката к использованию DES.
5.3.0 | PHP теперь использует собственную реализацию MD5, стандартного DES, расширенного DES и Blowfish алгоритмов, которые будут использованы в случае отсутствия их поддержки в системе.

Примеры

Пример #1 Пример использования crypt()

<?php
$password = crypt('mypassword'); // соль будет сгенерирована автоматически

/* Для проверки пароля в качестве параметра salt следует передавать результат работы
   crypt() целиком во избежание проблем при использовании различных
   алгоритмов (как уже было отмечено выше, стандартный DES-алгоритм
   использует 2-символьную соль, а MD5 - 12-символьную. */
if (crypt($user_input, $password) == $password) {
   echo "Пароль верен!";
}
?>

Пример #2 Использование crypt() и htpasswd

<?php
// пароль
$password = 'mypassword';

// получение хэша, соль генерируется автоматически
$hash = crypt($password);
?>

Пример #3 Использование crypt() с различными видами хэшей

<?php
if (CRYPT_STD_DES == 1) {
    echo 'Стандартный DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}

if (CRYPT_EXT_DES == 1) {
    echo 'Расширенный DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}

if (CRYPT_MD5 == 1) {
    echo 'MD5:             ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}

if (CRYPT_BLOWFISH == 1) {
    echo 'Blowfish:        ' . crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA256 == 1) {
    echo 'SHA-256:         ' . crypt('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA512 == 1) {
    echo 'SHA-512:         ' . crypt('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n";
}
?>

Результатом выполнения данного примера будет что-то подобное:

Стандартный DES: rl.3StKT.4T8M
Расширенный DES: _J9..rasmBYk8r9AiWNc
MD5:             $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:        $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256:         $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512:         $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

Примечания

Замечание: Функция расшифровки отсутствует, так как crypt() использует необратимый алгоритм хэширования.

Смотрите также

  • md5() - Возвращает MD5-хэш строки
  • Расширение Mcrypt
  • Страница руководства Unix по вашей функции crypt

User Contributed Notes

Matteo 18-May-2012 10:39
Password hashing should be done only with crypt and NEVER with SHA* and MD5 or hash(). The fundamental reason is that crypt is designed to be SLOW which is a VERY good thing for password hashing.

It also automatically generate a salt every time which makes pre-computed tables to "decrypt" passwords useless (the generated salt is stored in the returned string for convenience).
chris at ocportal dot com 29-Mar-2012 09:49
If you need to support older versions of PHP be aware that constants such as CRYPT_BLOWFISH may not actually be defined. So rather than following Example #3, you need a defined('CRYPT_...') call there before checking the constant's value.
Anonymous 19-Feb-2012 09:21
This function is not binary safe. Any binary string containing a NULL byte (chr(0)) will not produce a valid hash.
harry at simans dot net 27-Sep-2011 04:34
I made a nice little wrapper function for crypt():

<?php
function hasher($info, $encdata = false)
{
  $strength = "08";
  //if encrypted data is passed, check it against input ($info)
  if ($encdata) {
    if (substr($encdata, 0, 60) == crypt($info, "$2a$".$strength."$".substr($encdata, 60))) {
      return true;
    }
    else {
      return false;
    }
  }
  else {
  //make a salt and hash it with input, and add salt to end
  $salt = "";
  for ($i = 0; $i < 22; $i++) {
    $salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1);
  }
  //return 82 char string (60 char hash & 22 char salt)
return crypt($info, "$2a$".$strength."$".$salt).$salt;
}
}
?>

This wrapper will accept a string as input and hash it, and output the hash result of the string and salt together, plus the salt added on the end. You can then store that output in a db, and pass it on to the function as the 2nd parameter when you go to verify it, along with the user input or whatever as the first.

Examples:

<?php
$hash = hasher($userinput);
if ($hash == hasher($userinput, $hash) {//authed}
?>

Neat huh?
kaminski at istori dot com 05-Feb-2011 03:43
Here is an expression to generate pseudorandom salt for the CRYPT_BLOWFISH hash type:

<?php $salt = substr(str_replace('+', '.', base64_encode(pack('N4', mt_rand(), mt_rand(), mt_rand(), mt_rand()))), 0, 22); ?>

It is intended for use on systems where mt_getrandmax() == 2147483647.

The salt created will be 128 bits in length, padded to 132 bits and then expressed in 22 base64 characters.  (CRYPT_BLOWFISH only uses 128 bits for the salt, even though there are 132 bits in 22 base64 characters.  If you examine the CRYPT_BLOWFISH input and output, you can see that it ignores the last four bits on input, and sets them to zero on output.)

Note that the high-order bits of the four 32-bit dwords returned by mt_rand() will always be zero (since mt_getrandmax == 2^31), so only 124 of the 128 bits will be pseudorandom.  I found that acceptable for my application.
php at nospam dot nowhere dot com 26-Aug-2009 07:21
The makesalt() function code below when used to create an MD5 salt, produces a salt with characters not typically in a salt used by operating system crypt functions.  Some of these characters may have unintended side effects depending on how they are used - including the following: @ ` ~ \ | {}.

I am using the following to create MD5-Crypt hashes, (yes, I am assuming CRYPT_MD5 support is present).

<?php
function md5crypt($password){
    // create a salt that ensures crypt creates an md5 hash
    $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                    .'abcdefghijklmnopqrstuvwxyz0123456789+/';
    $salt='$1$';
    for($i=0; $i<9; $i++){
        $salt.=$base64_alphabet[rand(0,63)];
    }
    // return the crypt md5 password
    return crypt($password,$salt.'$');
}
?>
Jou 06-Apr-2007 01:52
I found out that you can use php:s crypt function to change  the user/root password in Linux distributions (at least in Slackware).

You just have to change the encrypted password for the user in the /etc/shadow file with the output from crypt("newpassword");
mikey_nich (at) hotmáil . com 04-Mar-2007 07:47
Are you using Apache2 on f.i. WinXP and want to create .htpasswd files via php? Then you need to use the APR1-MD5 encryption method. Here is a function for that:

<?php

function crypt_apr1_md5($plainpasswd) {
    $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
    $len = strlen($plainpasswd);
    $text = $plainpasswd.'$apr1$'.$salt;
    $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
    for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
    for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
    $bin = pack("H32", md5($text));
    for($i = 0; $i < 1000; $i++) {
        $new = ($i & 1) ? $plainpasswd : $bin;
        if ($i % 3) $new .= $salt;
        if ($i % 7) $new .= $plainpasswd;
        $new .= ($i & 1) ? $bin : $plainpasswd;
        $bin = pack("H32", md5($new));
    }
    for ($i = 0; $i < 5; $i++) {
        $k = $i + 6;
        $j = $i + 12;
        if ($j == 16) $j = 5;
        $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
    }
    $tmp = chr(0).chr(0).$bin[11].$tmp;
    $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    return "$"."apr1"."$".$salt."$".$tmp;
}

?>
picolobo at pilab dot dyndns dot org 21-Sep-2006 01:49
I had problems with ENCRYPT MySQL function when i tried to compare with the encrypted password (with ENCRYPT).

Another solution i read from "UNIX Advanced programming" where i found about the UNIX system call "crypt()":

Password="tB" //The two first letters of encrypted password

SELECT password from users where Password=ENCRYPT('".$_POST['password']."',Password)

mysql> select password from users where password=encrypt('pasword','tB');
+---------------+
| password      |
+---------------+
| tBY8OVuabSiTU |
+---------------+
1 row in set (0.01 sec)

Bye.

> topace at lightbox dot org
> 22-Sep-2005 06:34
>
> To authenticate against a stored crypt in MySQL, simply use:
>
> SELECT ................
>           AND Password=ENCRYPT('".$_POST['password']."',Password)
solar at openwall dot com 23-Dec-2005 11:20
With different password hashing methods supported on different systems and with the need to generate salts with your own PHP code in order to use the more advanced / more secure methods, it takes special knowledge to use crypt() optimally, producing strong password hashes.  Other message digest / hashing functions supported by PHP, such as md5() and sha1(), are really no good for password hashing if used naively, resulting in hashes which may be brute-forced at rates much higher than those possible for hashes produced by crypt().

I have implemented a PHP password hashing framework (in PHP, tested with all of PHP 3, 4, and 5) which hides the complexity from your PHP applications (no need for you to worry about salts, etc.), yet does things in almost the best way possible given the constraints of the available functions.  The homepage for the framework is:

http://www.openwall.com/phpass/

I have placed this code in the public domain, so there are no copyrights or licensing restrictions to worry about.

P.S. I have 10 years of experience in password (in)security and I've developed several other password security tools and libraries.  So most people can feel confident they're getting this done better by using my framework than they could have done it on their own.
hotdog (at) gmx (dot) net 16-Nov-2005 07:34
WRONG:

$mypassword = "toto";
$smd5_pass = "{SMD5}......." // in openldap

if (preg_match ("/{SMD5}/i", $smd5_pass))
 {
  $encrypted = substr($md5_pass, 6);
  $hash = base64_decode($encrypted);
  $salt = substr($hash,16);
  $mhashed =  mhash(MHASH_MD5, $mypassword . $salt) ;
  $without_salt = explode($salt,$hash_hex);
   if ($without_salt[0] == $mhashed) {
    echo "Password verified <br>";
    } else {
    echo "Password Not verified<br>";
    }
 }

$without_salt = explode($salt,$hash_hex); should be $without_salt = explode($salt,$hash);

RIGHT:

$mypassword = "toto";
$smd5_pass = "{SMD5}......." // in openldap

if (preg_match ("/{SMD5}/i", $smd5_pass))
 {
  $encrypted = substr($md5_pass, 6);
  $hash = base64_decode($encrypted);
  $salt = substr($hash,16);
  $mhashed =  mhash(MHASH_MD5, $mypassword . $salt) ;
  $without_salt = explode($salt,$hash);
   if ($without_salt[0] == $mhashed) {
    echo "Password verified <br>";
    } else {
    echo "Password Not verified<br>";
    }
 }
Vlad Alexa Mancini mancin at nextcode dot org 15-May-2005 01:57
cleaner version of shadow() and with more ascii chars

<?php

function shadow ($input){
         for ($n = 0; $n < 9; $n++){
              $s .= chr(rand(64,126));
         }
         $seed =  "$1$".$s."$";
         $return = crypt($input,$seed);
    return $return;
}

>
thorhajo at gmail dot com 02-Sep-2004 03:34
Here's a little function I wrote to generate MD5 password hashes in the format they're found in /etc/shadow:

function shadow($password)
{
  $hash = '';
  for($i=0;$i<8;$i++)
  {
    $j = mt_rand(0,53);
    if($j<26)$hash .= chr(rand(65,90));
    else if($j<52)$hash .= chr(rand(97,122));
    else if($j<53)$hash .= '.';
    else $hash .= '/';
  }
  return crypt($password,'$1$'.$hash.'$');
}

I've written this so that each character in the a-zA-Z./ set has a 1/54 of a chance of being selected (26 + 26 + 2 = 54), thus being statistically even.
aidan at php dot net 05-Jul-2004 07:52
Text_Password allows one to create pronounceable and unpronounceable passwords.

http://pear.php.net/package/text_password
crc32
echo
Обработка строк


Выводит одну или более строк

crypt
explode
Обработка строк
PHP Manual

echo

(PHP 4, PHP 5)

echo — Выводит одну или более строк

Описание

void echo ( string $arg1 [, string $... ] )

Выводит все аргументы.

На самом деле echo - это не функция, а конструкция языка, поэтому заключать аргументы в скобки необязательно. echo (в отличии от других языковых конструкций) не ведет себя как функция, поэтому не всегда может быть использована в контексте функции. Вдобавок, если вы хотите передать более одного аргумента в echo, эти аргументы нельзя заключать в скобки.

echo имеет также краткую форму, представляющую собой знак равенства, следующий непосредственно за открывающим тэгом. Этот сокращенный синтаксис допустим только когда включена директива конфигурации short_open_tag.

I have <?=$foo?> foo.

Список параметров

arg1

The parameter to output.

...

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Примеры использования echo

<?php
echo "Привет мир!";

echo "Это займет
несколько строк. Переводы строки тоже
выводятся";

echo "Это займет\nнесколько строк. Переводы строки тоже\nвыводятся";

echo "Экранирование символов делается \"Так\".";

// с echo можно использовать переменные ...
$foo = "foobar";
$bar = "barbaz";

echo "foo - это $foo"; // foo - это foobar

// ... и массивы
$baz = array("value" => "foo");

echo "это {$baz['value']} !"; // это foo !

// При использовании одиночных кавычек выводится имя переменной, а не значение
echo 'foo - это $foo'; // foo - это $foo

// Если вы не используете другие символы, можно вывести просто значения переменных
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// Некоторые предпочитают передачу нескольких аргументов вместо конкатенации
echo 'Эта ', 'строка ', 'была ', 'создана ', 'несколькими параметрами.', chr(10);
echo 'Эта ' . 'строка ' . 'была ' . 'создана ' . 'с помощью конкатенации.' . "\n";

echo <<<END
Здесь используется синтаксис "here document" для вывода
нескольких строк с подстановкой переменных $variable.
Заметьте, что закрывающий идентификатор должен
располагаться в отдельной строке. никаких пробелов!
END;

// Следующая строка неверна, так как echo не является функцией
($some_var) ? echo 'true' : echo 'false';

// Но это можно записать по другому
($some_var) ? print 'true' : print 'false'; // print также является конструкцией языка,
                                            // но ведет себя как функция, поэтому она
                                            // может быть использована в этом контексте.
echo $some_var ? 'true': 'false'; // echo вынесен за пределы выражения
?>

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Смотрите также

  • print() - Выводит строку
  • printf() - Выводит отформатированную строку
  • flush() - Сброс буфера вывода
  • Heredoc синтаксис

User Contributed Notes

ximlabz at gmail dot com 05-Nov-2011 10:16
A remedy to the problems caused by different management of returns between different platforms you can use the predefined constant PHP_EOF as the second parameter:

<?php
$foo = "foo";
$bar = "bar";

echo "Foo is $foo", PHP_EOL;
echo "Bar is $bar";

// is the same as using:

echo "Foo is $foo\n";
echo "Bar is $bar";

// but here only for UNIX-like platforms
?>
fire at dls dot net 29-Jul-2011 11:01
Pay attention to this part of the documentation:
echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function

I was trying to make certain that I was detecting errors and was trying code like this:

@alwaysFails() or echo('Surprise! It failed again');

This error was generated:
[29-Jul-2011 12:56:19] PHP Parse error:  syntax error, unexpected T_ECHO in /Applications/MAMP/test.php on line 12

Changing to die(), print() or a function I defined worked fine. Beware of this limitation of echo.
gbarros at yahoo-inc dot com 26-Jan-2010 02:10
just banged my head on this missing bits on the manual.
When using the <<< method, the array keys does not require any kind of quotes.

<?php
foreach ( $data as $i ){
echo <<< END
 <tr>
  <td>$i[date]</td>
  <td>$i[name]</td>
 </tr>
END;
}
?>

Let's hope you don't have any <?php echo $klingonships['th\'bl][ath']?> kind of array :)
Jakob Thomsen 23-Nov-2008 06:23
A way to color your echo output is to use shell_exec and the echo command (this only works on Linux/bash) in the following way:

<?php
echo shell_exec('echo "\e[0;31m Red color \e[0;32mGreen color \e[0m No color "');
?>

See http://wiki.archlinux.org/index.php/Color_Bash_Prompt for more colors and other options.
sandaimespaceman at gmail dot com 31-Aug-2008 11:25
Outputting \n won't generate a line break in the browser, <br /> is required for line break. Also,
<?php
echo "first line";
echo "second line";
?>
will like
first linesecond line
because you didn't insert spaces/line breaks.
the echo function can also be written like
<?php
echo ('text here')
?>
nikolaas dot mennega at links dot com dot au 31-Oct-2007 11:04
hemanman at gmail dot com, the problem is that func() doesn't actually return a value (string or otherwise), so the result of echoing func() is null.

With the comma version, each argument is evaluated and echoed in turn: first the literal string (simple), then func(). Evaluating a function call obviously calls the function (and in this case executes its own internal echo), and the result (null) is then echoed accordingly. So we end up with "outside func() within func()" as we would expect.

Thus:

<?php
echo "outside func ()\n", func ();
?>

effectively becomes:

<?php
echo "outside func ()\n";
//func ()
{
echo "within func ()\n";
}
echo '';
?>

The dot version is different: there's only one argument here, and it has to be fully evaluated before it can be echoed as requested. So we start at the beginning again: a literal string, no problem, then a concatenator, then a function call. Obviously the function call has to be evaluated before the result can be concatenated with the literal string, and THAT has to happen BEFORE we can complete the echo command. But evaluating func() produces its own call to echo, which promptly gets executed.

Thus:

<?php
echo "outside func ()\n" . func ();
?>

effectively becomes:

<?php
//func ()
{
echo "within func ()\n";
}
echo "outside func ()\n" . '';
?>
Jason Carlson - SiteSanity 16-May-2005 10:28
In response to Ryan's post with his echobig() function, using str_split wastes memory resources for what you are doing.

If all you want to do is echo smaller chunks of a large string, I found the following code to perform better and it will work in PHP versions 3+

<?php
function echobig($string, $bufferSize = 8192)
{
  // suggest doing a test for Integer & positive bufferSize
  for ($chars=strlen($string)-1,$start=0;$start <= $chars;$start += $bufferSize) {
    echo substr($string,$start,$buffer_size);
  }
}
?>
ryan at wonko dot com 27-Feb-2005 12:56
Due to the way TCP/IP packets are buffered, using echo to send large strings to the client may cause a severe performance hit. Sometimes it can add as much as an entire second to the processing time of the script. This even happens when output buffering is used.

If you need to echo a large string, break it into smaller chunks first and then echo each chunk. The following function will do the trick in PHP5:

<?php
function echobig($string, $bufferSize = 8192)
{
    $splitString = str_split($string, $bufferSize);

    foreach($splitString as $chunk)
        echo $chunk;
}
?>
zombie)at(localm)dot(org) 25-Jan-2003 11:26
[Ed. Note: During normal execution, the buffer (where echo's arguments go) is not flushed (sent) after each write to the buffer. To do that you'd need to use the flush() function, and even that may not cause the data to be sent, depending on your web server.]

Echo is an i/o process and i/o processes are typically time consuming. For the longest time i have been outputting content by echoing as i get the data to output. Therefore i might have hundreds of echoes in my document. Recently, i have switched to concatenating all my string output together and then just doing one echo at the end. This organizes the code more, and i do believe cuts down on a bit of time. Likewise, i benchmark all my pages and echo seems to influence this as well. At the top of the page i get the micro time, and at the end i figure out how long the page took to process. With the old method of "echo as you go" the processing time seemed to be dependent on the user's net connection as well as the servers processing speed. This was probably due to how echo works and the sending of packets of info back and forth to the user. One an one script i was getting .0004 secs on a cable modem, and a friend of mine in on dialup was getting .2 secs. Finally, to test that echo is slow; I built strings of XML and XSLT and used the PHP sablotron functions to do a transformation and return a new string. I then echoed the string. Before the echo, the process time was around .025 seconds and .4 after the echo. So if you are big into getting the actual processing time of your scripts, don't include echoes since they seem to be user dependent. Note that this is just my experience and it could be a fluke.
crypt
explode
Обработка строк


Разбивает строку с помощью разделителя

echo
fprintf
Обработка строк
PHP Manual

explode

(PHP 4, PHP 5)

explode — Разбивает строку с помощью разделителя

Описание

array explode ( string $delimiter , string $string [, int $limit ] )

Возвращает массив строк, полученных разбиением строки string с использованием delimiter в качестве разделителя.

Список параметров

delimiter

Разделитель.

string

Входная строка.

limit

Если аргумент limit является положительным, возвращаемый массив будет содержать максимум limit элементов, при этом последний элемент будет содержать остаток строки string.

Если параметр limit отрицателен, то будут возвращены все компоненты кроме последних -limit.

Если limit равен нулю, то он расценивается как 1.

По историческим причинам, функции implode() можно передавать аргументы в любом порядке, но для explode() это недопустимо. Убедитесь в том, что delimiter указан перед аргументом string.

Возвращаемые значения

Возвращает массив (array) строк (string), созданный делением параметра string по границам, указанным параметром delimiter.

Если delimiter является пустой строкой (""), explode() возвращает FALSE. Если delimiter не содержится в string, и используется отрицательный limit, то будет возвращен пустой массив (array), иначе будет возвращен массив, содержащий string.

Список изменений

Версия | Описание
5.1.0 | Добавлена поддержка отрицательных значений limit
4.0.1 | Добавлен параметр limit

Примеры

Пример #1 Пример использования explode()

<?php
// Пример 1
$pizza  = "кусок1 кусок2 кусок3 кусок4 кусок5 кусок6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // кусок1
echo $pieces[1]; // кусок2

// Пример 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

Пример #2 Примеры с использованием параметра limit

<?php
$str = 'один|два|три|четыре';

// положительный лимит
print_r(explode('|', $str, 2));

// отрицательный лимит (начиная с PHP 5.1)
print_r(explode('|', $str, -1));
?>

Результат выполнения данного примера:

Array
(
    [0] => один
    [1] => два|три|четыре
)
Array
(
    [0] => один
    [1] => два
    [2] => три
)

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • preg_split() - Разбивает строку по регулярному выражению
  • str_split() - Преобразует строку в массив
  • mb_split() - Разделение строк в многобайтных кодировках, используя регулярное выражение
  • str_word_count() - Возвращает информацию о словах, входящих в строку
  • strtok() - Разбивает строку на токены
  • implode() - Объединяет элементы массива в строку

User Contributed Notes

Mobin Hosseini 14-Mar-2012 10:25
Hello,
I just wanted to note some behaviours of the explode function, well i am submitting a bunch of urls, one each line and i am using the "\n" (it should be within double quotes) as the delimiter and i am iterating to check for dupe values and always the last value stays unchecked unless i am appending a new line "\n" to the $_POST.

Let me demonstrate what i mean(sorry if there is any syntax error i am just writing this on-the-fly):

if(isset($_POST['files']) && !empty($_POST['files'])){

        $regex = "((http|ftp)+\:\/\/(www.)?(.*)/(.*)(\.)?(.*)?)";
        $ls = $_POST['files'];
        $posts = explode("\n", $ls);

        //remove duplicates
        $count = count($posts);
        for($i=0;$i<$count;$i++){
            if($posts[$i]=="") continue;
            for($j=$i+1;$j<$count;$j++){
                if($posts[$j]=="") continue;
                if((string)$posts[$i] == (string)$posts[$j]){
                    $posts[$j] = "";
                }
            }
        }
        $i=0;
        $files = array();
        foreach($posts as $f ){
            if(preg_match($regex,$f,$matches)){
                $files[] = $f;
                 $i++;
            }
            if($i>=10){
                break;
            }
        }

        echo "<pre>";
        print_r($files);
        echo "</pre>";

}

submit some urls in this format :
http://www.google.com/admin.db
http://www.google.com/admin.db[dont hit the "enter" key here]

i didn't have much time to look at it in deep so i just appended using javascript the new line :
document.getElementById('files').value += "\n";

This way the last dupe value will get deleted too otherwise it wont!
ali balouch 11-Mar-2012 06:59
exploding string.......
<?php
    //(,'')
            $array2 = array();
            $string2 = "this is a car";
            $whitspace = " ";
            $increment=0;
            $length = strlen($string2);
                for($i=1;$i<$length;$i++){
                    $char = substr($string2,$i,1);
                        if($whitspace == $char){
                            $increment++;
                            }
                        elseif($whitspace==""){
                            $array2[$increment].= $char;
                            $increment++;
                            }else{
                            $array2[$increment].= $char;
                            }
            }
        var_dump($array2);
    ?>
qeremy [atta] gmail [dotta] com 23-Feb-2012 11:17
If you don't want any empty array element, just use simply "preg_split" instead this function (or struggle with an extra function, i.e. "trim");

<?php
$uri = "/user/123/";

$tmp = explode("/", $uri);
print_r($tmp);

$tmp = explode("/", trim($uri, "/"));
print_r($tmp);

$tmp = preg_split("~/~", $uri, -1, PREG_SPLIT_NO_EMPTY);
print_r($tmp);
?>

Array
(
    [0] =>
    [1] => user
    [2] => 123
    [3] =>
)
Array
(
    [0] => user
    [1] => 123
)
Array
(
    [0] => user
    [1] => 123
)
eye_syah88 at yahoo dot com 30-May-2011 12:32
a simple one line method to explode & trim whitespaces from the exploded elements

array_map('trim',explode(",",$str));

example:

$str="one  ,two  ,       three  ,  four    ";
print_r(array_map('trim',explode(",",$str)));

Output:

Array ( [0] => one [1] => two [2] => three [3] => four )
Rijk van Wel 17-May-2011 08:05
Here's another one of those functions that allow you to work with an escaped delimiter. It works by internally url-encoding the escaped delimiters before calling explode(). So if your delimiter is a %, you should use another encoding function ;)

<?php
function explode_escaped( $delimiter, $string ) {
    $string = str_replace( '\\' . $delimiter, urlencode( $delimiter ), $string );
    return array_map( 'urldecode', explode( $delimiter, $string ) );
}
?>
bernard.schenk [at] bordet.be 17-May-2011 02:53
Nifty multiple explode function:

<?php
function multipleExplode($delimiters = array(), $string = ''){

    $mainDelim=$delimiters[count($delimiters)-1]; // dernier

    array_pop($delimiters);

    foreach($delimiters as $delimiter){

        $string= str_replace($delimiter, $mainDelim, $string);

    }

    $result= explode($mainDelim, $string);
    return $result;

}
?>
alexander at textalk dot se 12-Apr-2011 12:27
If the string begins or ends with the delimiter:

<?php

$path = '/one/two/three/';
$folderNames = explode('/', $path);
print_r($folderNames);

?>

Will give:

Array
(
    [0] =>
    [1] => one
    [2] => two
    [3] => three
    [4] =>
)
lm at ms dot net 23-Mar-2011 03:58
while explode() and implode() are counterparts, note that it does NOT work for an empty delimiter!

solution: use str_split($str) instead of explode('', $str)

example:
<?php
$str1 = 'abc';
var_dump($str1);

$str2 = implode(',' , explode(',' , $str1)); // OK (explode with non-empty delimiter)
var_dump($str2);

$str3 = implode('' , str_split($str1));      // OK (str_split)
var_dump($str3);

$str4 = implode('' , explode('' , $str1));   // ERROR! (explode with empty delimiter)
var_dump($str4);
?>

returns:
string 'abc' (length=3)
string 'abc' (length=3)
string 'abc' (length=3)
Warning: explode() [function.explode]: Empty delimiter.
Warning: implode() [function.implode]: Bad arguments.
null
Kamba Jeno 19-Mar-2011 05:47
if u cannot use the original function explode, or your version is less than 4.0.1 you can use this example  whith optional limit argument.

<?php
function exploding($separator,$string,$limit=NULL){
$returnarray = array();
$increment = 0;
$length = strlen($string);
$limit_negative=($limit < 0);

    for($i = 0; $i < $length;$i++){
        $current = substr($string,$i,1);
         //main explode function
            if($separator == $current){
            $increment++;
            }
            elseif($separator == ""){
            @$returnarray[$increment].=$current;
            $increment++;
            }
            else{
            @$returnarray[$increment].=$current;
            }
        //if limit is positive
        if(isset($limit) && $limit == $increment){
        break;
        }

    }
    //if limit is negative
    if($limit_negative){
        for($i = 0; $i > $limit;$i--){
           array_pop($returnarray);
           }

    }
return $returnarray;
}

//Test
$something = "Kamba.jeno.attila";

$result = exploding(".",$something)
/*returns
array(3) {
[0]=> string(5) "Kamba"
[1]=> string(4) "Jeno"
[2]=> string(6) "Attila" }
*/

$result2 = exploding(".",$something,1)
/*returns
array(1) {
[0]=> string(5) "Kamba" }
*/

$result3 = exploding(".",$something,-1)
/*returns
array(2) {
[0]=> string(5) "Kamba"
[1]=> string(4) "Jeno" }
*/
?>
Aram Kocharyan 27-Feb-2011 07:04
Here is a function to explode a comma separated string and trim the elements of any whitespace that may come before or after the comma, and will also trim whitespace from the front and end of the string, as well as allow you to specify a delimiter yourself.

<?php

/* Performs explode() on a string with the given delimiter and trims all whitespace for the elements */
function explode_trim($str, $delimiter = ',') {
    if ( is_string($delimiter) ) {
        $str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str));
        return explode($delimiter, $str);
    }
    return $str;
}

// Test
$str = '    mouse ,cat , dog  ,  human    ';
$array = explode_trim($str);
print_r($array);

?>

This will output:
(
    [0] => mouse
    [1] => cat
    [2] => dog
    [3] => human
)
jehoshua02 at gmail dot com 22-Feb-2011 11:37
If you are looking for a simpler multi-explode that returns a flat array, use a regular expression to standardize all delimiters before exploding.

<?php

// function to explode on multiple delimiters
function multi_explode($pattern, $string, $standardDelimiter = ':')
{
    // replace delimiters with standard delimiter, also removing redundant delimiters
    $string = preg_replace(array($pattern, "/{$standardDelimiter}+/s"), $standardDelimiter, $string);

    // return the results of explode
    return explode($standardDelimiter, $string);
}

// test

    // set up variables
    $string = "zero  one | two :three/ four\ five:: six|| seven eight nine\n ten \televen twelve thirteen fourteen fifteen";
    $pattern = '/[:\|\\\\\/\s]/';  // colon (:), pipe (escaped '\|'), slashes (escaped '\\\\' and '\/'), white space (\s)

    // call function
    $result = multi_explode($pattern, $string);

    // display results
    var_dump($result);

?>

Output:

array
  0 => string 'zero' (length=4)
  1 => string 'one' (length=3)
  2 => string 'two' (length=3)
  3 => string 'three' (length=5)
  4 => string 'four' (length=4)
  5 => string 'five' (length=4)
  6 => string 'six' (length=3)
  7 => string 'seven' (length=5)
  8 => string 'eight' (length=5)
  9 => string 'nine' (length=4)
  10 => string 'ten' (length=3)
  11 => string 'eleven' (length=6)
  12 => string 'twelve' (length=6)
  13 => string 'thirteen' (length=8)
  14 => string 'fourteen' (length=8)
  15 => string 'fifteen' (length=7)

See:
http://www.php.net/manual/en/book.pcre.php
dhz 30-Dec-2010 09:21
A one-liner to extract a portion of a string, starting from the END of the string....
<?php
$extracted_string = implode('.', array_slice(explode('.', $original_string), -2));
?>
jamestrowbridge at gmail dot com 19-Dec-2010 12:50
FYI, use double quotes for the separator parameter:

<?php
$string = "Hello\nHello\nHello";
$arr = explode('\n',$string);//Using single quotes
print_r($arr);
/*
Returns:
Array
(
    [0] => Hello
Hello
Hello
)
*/
?>
Is different than:
<?php
$string = "Hello\nHello\nHello";
$arr = explode("\n",$string);//Using double quotes
print_r($arr);
/*
Returns:
Array
(
    [0] => Hello
    [1] => Hello
    [2] => Hello
)
*/
?>
xananax at yelostudio dot com 10-Nov-2010 06:18
I needed a way to explode an array, just like one would explode a string, and could not find anything on the net.
Maybe this can be made more efficient, but it fits my purpose. Contributions and comments welcome.
<?php
    /**
     * Allows to explode an array into multiple arrays on a set delimiter.
     * Delimiter Can be set either by key, or by value, or by both (in which case,
     * both key and value must be strictly equal to values provided).
     * Note that numeric indexes don't work since the original array is reduced
     * at each loop (thus making numerical indexes useless).
     * @param array $array the array to explode
     * @param mixed $key the key to check
     * @param mixed $value the value to check
     * @param int $limit You can limit the number of parts with this. If set to 0, limit is infinite
     * @param boolean $removeDelimiter if set to TRUE, removes the delimiter key from the returned arrays
     * @return array|boolean an array of as many parts as needed, or FALSE on error.
     */
    function array_explode(array $array, $key=NULL, $value=NULL, $limit=0, $removeDelimiter=TRUE){
        if($key===NULL && $value===NULL){return FALSE;}
        $parts = array();
        $delimiter = NULL;
        $partsN = 0;
        while($v = current($array)){
            $k = key($array);
            if(
                (($key!==NULL && $value!==NULL) && ($k===$key && $v===$value)) ||
                ($key!==NULL && $value===NULL && $k===$key) ||
                ($value!==NULL && $key===NULL && $v===$value)
            ){
                $delimiter = TRUE;
                if($removeDelimiter){array_shift($array);}
                $partsN++;
                if($partsN===$limit){$parts[$partsN] = $array;return $parts;}
            }
            $parts[$partsN][] = array_shift($array);
        }
        if($delimiter){
            return $parts;
        }
        return FALSE;
    }
?>
mvpetrovich 09-Sep-2010 05:35
In using explode, with the list command, you will get errors if the number of variables is larger than the produced array by explode.

For example:

<?php
$str = 'aa|bb|cc';
list($one, $two, $three, $four) = explode('|', $str);
?>

To solve these cases, where you would like to assign empty strings to the extra variables (and eliminate errors), append a delimiter string to the string as follows.

<?php
$str = 'aa|bb|cc';
list($one, $two, $three, $four) = explode('|', $str . '|||');
?>

This way, the list variables will always be assigned.
tiago dot dias at flow-me dot com 09-Sep-2010 03:40
Beaware splitting empty strings.

<?php
$str = "";
$res = explode(",", $str);
print_r($res);
?>

If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value.

Array
(
    [0] =>
)

To solve this, just use array_filter() without callback. Quoting manual page "If the callback function is not supplied, array_filter() will remove all the entries of input that are equal to FALSE.".

<?php
$str = "";
$res = array_filter(explode(",", $str));
print_r($res);
?>

Array
(
)
Cody G. 08-Aug-2010 06:41
I'm sure you guys get just a bit frustrated at times when you need a fraction of a very simple string and you use "explode()", but then you have to define a whole extra variable. (That is because you need to store a function-returned array in a variable before you can extract a value).

If you're extracting the last half, or third, of a string, there's an easy inline workaround. Check this:

<?php
 $mystr = "separated-text";
 print(str_replace("-","",strstr("-",$mystr)));
 //Returns "text"
?>

If the separator (dash) can be left in, you don't even need the "str_replace()" function.

Lets try this with 3 fractions:

<?php
 $mystr = "separated-text-again";
 //Comment submission wouldn't let me
 // combine this into one statement.
 // That's okay, it's more readable.
 $split1 = str_replace("-","",strstr("-",$mystr));
 print(str_replace("-","",strstr("-",$split1)));
 //Returns "again"
?>

Anything more than 3 fractions gets really confusing, in that case you should use "explode()".

Hope this helps!
~Cody G.
m0gr14 at gmail dot com 31-Jul-2010 07:02
Here's a function for "multi" exploding a string.

<?php
//the function
//Param 1 has to be an Array
//Param 2 has to be a String
function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
             $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}

// Example of use
$string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
$delimiters = Array(",",":","|","-");

$res = multiexplode($delimiters,$string);
echo '<pre>';
print_r($res);
echo '</pre>';

//returns
/*
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                        )

                    [1] => Array
                        (
                            [0] => 4
                            [1] => 5
                        )

                    [2] => Array
                        (
                            [0] => 6
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 7
                            [1] => 8
                            [2] => 9
                            [3] => 0
                        )

                    [1] => Array
                        (
                            [0] => 1
                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 2
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 3
                            [1] => 4
                        )

                    [1] => Array
                        (
                            [0] => 5
                        )

                )

        )

)
*/
?>
info at noextratime dot com 04-Jul-2010 01:09
Here is a function for "double" exploding a string, like in the case of a flattened multi-dimensional array.
<?php

function doubleExplode ($del1, $del2, $array){
    $array1 = explode("$del1", $array);
foreach($array1 as $key=>$value){
$array2 = explode("$del2", $value);
foreach($array2 as $key2=>$value2){
$array3[] = $value2;
}
}
    $afinal = array();
for ( $i = 0; $i <= count($array3); $i += 2) {
    if($array3[$i]!=""){
    $afinal[trim($array3[$i])] = trim($array3[$i+1]);
    }
}
return $afinal;
}
$proddetails = 'Size=Large, Color=Black';
$test = doubleExplode(',', '=', $proddetails);
print_r($test);
?>

/*
Array
(
    [Size] => Large
    [Color] => Black
)
*/
jessebusman at gmail dot com 27-May-2010 12:45
Sometimes you need to explode a string by different delimiters. In that case you can use this function:

<?php
print_r(explodeX(Array(".","!"," ","?",";"),"This.sentence?contains wrong;characters"));
// Returns:
// Array("This","sentence","contains","wrong","characters")

function explodeX($delimiters,$string)
{
    $return_array = Array($string); // The array to return
    $d_count = 0;
    while (isset($delimiters[$d_count])) // Loop to loop through all delimiters
    {
        $new_return_array = Array();
        foreach($return_array as $el_to_split) // Explode all returned elements by the next delimiter
        {
            $put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);
            foreach($put_in_new_return_array as $substr) // Put all the exploded elements in array to return
            {
                $new_return_array[] = $substr;
            }
        }
        $return_array = $new_return_array; // Replace the previous return array by the next version
        $d_count++;
    }
    return $return_array; // Return the exploded elements
}
?>
Onur Nizam onur dot nizam at yahoo dot com 16-May-2010 12:27
The regular expression parameters such as \n or \t can be used as well as other strings as the delimeter which can be used to parse any given text files or downloaded web pages to read line by line.

An example may be considered as, name surname and phone numbers are written into a text file line by line and columns are seperated by tabs, can be exploded and read easily through the return and tab characters. After storing them in the array they can be manipulated or displayed in any other formats.

<?php
// Explode text file and store each row of the file into the array elements
function explodeRows($data) {
  $rowsArr = explode("\n", $data);
  return $rowsArr;
}

// Explode the columns according to tabs
function explodeTabs($singleLine) {
  $tabsArr = explode("\t", $singleLine);
  return $tabsArr;
}

// Open the text file and get the content
$filename = "phonebook.txt";
$handle   = fopen($filename, 'r');
$data     = fread($handle, filesize($filename));
$rowsArr  = explodeRows($data);

// Display content which is exploded by regular expression parameters \n and \t
for($i=0;$i<count($rowsArr);$i++) {
  $lineDetails = explodeTabs($rowsArr[$i]);
    echo "<br>Name : " . $lineDetails[0];
    echo "<br>Surname : " . $lineDetails[1];
    echo "<br>Tel Number : " . $lineDetails[2];
    echo "<br><br>";
}

/*
phonebook.txt text file can be something like this;
name1    sname1    +905429998877
name2    sname2    +905429998876
name3    sname3    +905429998875

The output will be as follows;
Name : name1
Surname : sname1
Tel Number : +905429998877

Name : name2
Surname : sname2
Tel Number : +905429998876

Name : name3
Surname : sname3
Tel Number : +905429998875
*/

?>
drieick at hotmail dot com 21-Apr-2010 08:34
When explode is given an empty $string, it'll return an array with a single empty element.

<?php

# returns Array([0] => );
print_r(explode(',', ''));

?>

This is not a bug, but it can be pretty tricky (especially with callbacks that expect a certain type of array). So, be sure to check your arrays. It's not a bug, because there's nothing to split.
locoluis at gmail dot com 08-Apr-2010 09:02
That with all stateful encodings that use bytes between 0x00 and 0x7f for something other than, say, encoding ASCII characters. Including GBK, BIG5, Shift-JIS etc.

explode and other such PHP functions work on bytes, not characters.

What you do is to convert the string to UTF-8 using iconv(), then explode, then go back to GBK.
gxd305 at gmail dot com 16-Nov-2009 05:47
when the encoding of $string  is 'GBK' and $delimiter is '|' , the return value may be wrong.
for example:

<?php
$result = explode("|", "滕华弢|海青");
var_dump($result);
?>

and the result will be:
array (
  0 => '滕华,
  1 => '',
  2 => '海青',
)

bcz "弢" 's GBK is '0x8f7c'. and "|" 's ASCII is '0x7c'.

So, all GBK-encoding characters include '7c' will lead to the error result.
nick dot brown at free dot fr 14-Oct-2009 03:47
My application was running out of memory (my hosting company limits PHP to 32MB).  I have a string containing between 100 and 20000 triplets, separated by a space, with each triplet consisting of three double-precision numbers, separated by commas.  Total size of the biggest string, with 20000 triplets, is about 1MB.

The application needs to split the string into triplets, then split the triplet into numbers.  In C, this would take up about 480K (20000 times 3 x 8 bytes) for the final array.  The intermediate array of strings shouldn't be much bigger than the long string itself (1MB).  And I expect some overhead from PHP, say 300% to allow for indexes etc.

Well, PHP5 manages to run out of memory *at the first stage* (exploding the string on the space character).  I'm expecting to get an array of 20000 strings, but it needs more than 32MB to store it.  Amazing.

The workaround was easy and had the bonus of producing faster code (I compared it on a 10000 triplet string).  Since in any case I had to split up the numeric triplets afterwards, I decided to use preg_match_all() on the original string.  Despite the fact that the resulting "matches" array contains more data per element than the result of explode() - because it stores the matched triplet, plus its component numbers - it takes up far less memory.

Moral: be careful when using explode() on big strings, as it can also explode your memory usage.
Jrg Wagner 12-Oct-2009 02:28
Here is a very concise example for a quote aware explode - substrings in quotes (or another definable enclosure char) are not exploded.
An additional parameter allows to determine whether the enclosure chars should be preserved within the resulting array elements. Please note that as of PHP 5.3 the str_getcsv function offers a built-in way to do this!

<?php
function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
  $resArr = array();
  $n = 0;
  $expEncArr = explode($enclose, $str);
  foreach($expEncArr as $EncItem){
    if($n++%2){
      array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
    }else{
      $expDelArr = explode($delim, $EncItem);
      array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
      $resArr = array_merge($resArr, $expDelArr);
    }
  }
  return $resArr;
}
?>
Anonymous 28-Sep-2009 03:20
Note to the previous example: we can do the whole string->array conversion using explode() exclusively.

<?php
    // converts pure string into a trimmed keyed array
    function string_2_array( $string, $delimiter = ',', $kv = '=>')
    {
        if ($element = explode( $delimiter, $string ))
        {
            // create parts
            foreach ( $element as $key_value )
            {
                // key -> value pair or single value
                $atom = explode( $kv, $key_value );

                if( trim($atom[1]) )
                {
                  $key_arr[trim($atom[0])] = trim($atom[1]);
                }
                else
                {
                    $key_arr[] = trim($atom[0]);
                }
            }
        }
        else
        {
            $key_arr = false;
        }

        return $key_arr;
    }
?>
Anonymous 02-Sep-2009 07:18
<?php
// converts pure string into a trimmed keyed array
function string2KeyedArray($string, $delimiter = ',', $kv = '=>') {
  if ($a = explode($delimiter, $string)) { // create parts
    foreach ($a as $s) { // each part
      if ($s) {
        if ($pos = strpos($s, $kv)) { // key/value delimiter
          $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
        } else { // key delimiter not found
          $ka[] = trim($s);
        }
      }
    }
    return $ka;
  }
} // string2KeyedArray

$string = 'a=>1, b=>23   , $a, c=> 45% , true,d => ab c ';
print_r(string2KeyedArray($string));
?>

Array
(
  [a] => 1
  [b] => 23
  [0] => $a
  [c] => 45%
  [1] => true
  [d] => ab c
)
Anonymous 10-Aug-2009 10:55
If you are exploding string literals in your code that have a dollar sign ($) in it, be sure to use single-quotes instead of double-quotes, since php will not spare any chance to interpret the variable-friendly characters after the dollar signs as variables, leading to unintended consequences, the most typical being missing characters.

<?php
$doubleAr = explode(" ", "The $quick brown fox");
$singleAr = explode(" ", 'The $quick brown fox');
echo $doubleAr[1]; // prints "";
echo $singleAr[1]; // prints "$quick";
?>
vzverev at nm dot ru 24-Jul-2009 07:33
If you are going to use foreach after explode(), call reset() before foreach:
<?php
$arr = explode("\n", 'test \n test2 \n test3');
reset($arr);
foreach($arr as $line)
{ /* do something */ ; }
?>
marcus at synchromedia dot co dot uk 15-Jun-2009 06:50
Just in case the comment about empty strings is not clear:

<?php
$a = array();
var_dump($a);
$s = implode("\n", $a);
var_dump($s);
$b = explode("\n", $s);
var_dump($b);
$b = preg_split('/\n/', $s,-1,PREG_SPLIT_NO_EMPTY);
var_dump($b);
?>

Results in:

array(0) {
}
string(0) ""
array(1) {
  [0]=>
  string(0) ""
}
array(0) {
}

i.e. exploding an empty string results in an array with one element. You can use preg_split to skip the empty item, but that may not be quite what you need should your array have empty elements intentionally.
SR 21-Apr-2009 07:50
Keep in mind that explode() can return empty elements if the delimiter is immediately repeated twice (or more), as shown by the following example:

<?php
$foo = 'uno dos  tres'; // two spaces between "dos" and "tres"
print_r(explode(' ', $foo));
?>

Array
(
    [0] => uno
    [1] => dos
    [2] =>
    [3] => tres
)

Needless to say this is definitely not intuitive and must be handled carefully.
Michael 19-Apr-2009 02:29
Here's a simple script which uses explode() to check to see if an IP address is in an array (can be used as a ban-check, without needing to resort to database storage and queries).

<?php

 function denied($one) {

  $denied = array(

   0 => '^255.255.255.255',
   1 => '^255.250',
   2 => '^255.255.250'

  );

  for ($i = 0 ; $i < sizeof($denied) ; $i++) {

   if (sizeof(explode($denied[$i], '^' . $one . '$')) == 2) {
    return true;
   }

  }

  return false;

 }

 if (denied($_SERVER['REMOTE_ADDR'])) {
  header('Location: denied.php');
 }

?>
Navi 31-Mar-2009 04:03
<?php
function my_explode($delim, $str, $lim = 1)
{
    if ($lim > -2) return explode($delim, $str, abs($lim));

    $lim = -$lim;
    $out = explode($delim, $str);
    if ($lim >= count($out)) return $out;

    $out = array_chunk($out, count($out) - $lim + 1);

    return array_merge(array(implode($delim, $out[0])), $out[1]);
}
?>
This function can assume `limit' parameter less than 0, for example:
<?php
print_r(my_explode('.', 'file.some.ext.jpg', -2));
?>
prints
Array
(
    [0] => file.some.ext
    [1] => jpg
)
adrian at bilsoftware dot com 23-Feb-2009 02:40
<?php
function explode_escaped($delimiter, $string){
        $exploded = explode($delimiter, $string);
        $fixed = array();
        for($k = 0, $l = count($exploded); $k < $l; ++$k){
            if($exploded[$k][strlen($exploded[$k]) - 1] == '\\') {
                if($k + 1 >= $l) {
                    $fixed[] = trim($exploded[$k]);
                    break;
                }
                $exploded[$k][strlen($exploded[$k]) - 1] = $delimiter;
                $exploded[$k] .= $exploded[$k + 1];
                array_splice($exploded, $k + 1, 1);
                --$l;
                --$k;
            } else $fixed[] = trim($exploded[$k]);
        }
        return $fixed;
    }
?>

Here's a function which explodes string with delimiter, but if delimiter is "escaped" by backslash, function won't split in that point. Example:

<?php

$result = explode_escaped(',', 'string, piece, group\, item\, item2, next\,asd');
print_r($result);
?>
Will give:
Array
(
    [0] => string
    [1] => piece
    [2] => group, item, item2
    [3] => next,asd
)
Elad Elrom 04-Dec-2008 09:02
<?php
// Remove words if more than max allowed character are insert or add a string in case less than min are displayed
// Example: LimitText("The red dog ran out of thefence",15,20,"<br>");

function LimitText($Text,$Min,$Max,$MinAddChar) {
   if (strlen($Text) < $Min) {
       $Limit = $Min-strlen($Text);
       $Text .= $MinAddChar;
   }
   elseif (strlen($Text) >= $Max) {
       $words = explode(" ", $Text);
       $check=1;
       while (strlen($Text) >= $Max) {
           $c=count($words)-$check;
           $Text=substr($Text,0,(strlen($words[$c])+1)*(-1));
           $check++;
       }
   }

   return $Text;
}
?>
Nobody 16-Nov-2008 05:38
A really better and shorter way to get extension is via:

<?php $extension = end(explode('.', $filename)); ?>

this will print the last part after the last dot :)
shaun 29-Aug-2008 12:24
For anyone trying to get an array of key => value pairs from a query string, use parse_str.  (Better alternative than the explode_assoc function listed way down the page unless you need different separators.)
pinkgothic at gmail dot com 15-Oct-2007 02:26
coroa at cosmo-genics dot com mentioned using preg_split() instead of explode() when you have multiple delimiters in your text and don't want your result array cluttered with empty elements. While that certainly works, it means you need to know your way around regular expressions... and, as it turns out, it is slower than its alternative. Specifically, you can cut execution time roughly in half if you use array_filter(explode(...)) instead.

Benchmarks (using 'too many spaces'):
Looped 100000 times:
preg_split: 1.61789011955 seconds
filter-explode: 0.916578054428 seconds

Looped 10000 times:
preg_split: 0.162719011307 seconds
filter-explode: 0.0918920040131 seconds

(The relation is, evidently, pretty linear.)

Note: Adding array_values() to the filter-explode combination, to avoid having those oft-feared 'holes' in your array, doesn't remove the benefit, either. (For scale - the '9' becomes a '11' in the benchmarks above.)

Also note: I haven't tested anything other than the example with spaces - since djogo_curl at yahoo's note seems to imply that explode() might get slow with longer delimiters, I expect this would be the case here, too.

I hope this helps someone. :)
seventoes at gmail dot com 09-Dec-2006 07:49
Note that explode, split, and functions like it, can accept more than a single character for the delimiter.

<?php
$string = "Something--next--something else--next--one more";

print_r(explode('--next--',$string));
?>
djogo_curl at yahoo 01-Dec-2004 04:50
Being a beginner in php but not so in Perl, I was used to split() instead of explode(). But as split() works with regexps it turned out to be much slower than explode(), when working with single characters.
coroa at cosmo-genics dot com 16-Nov-2003 08:01
To split a string containing multiple seperators between elements rather use preg_split than explode:

preg_split ("/\s+/", "Here  are    to    many  spaces in   between");

which gives you
array ("Here", "are", "to", "many", "spaces", "in", "between");
echo
fprintf
Обработка строк


Записывает отформатированную строку в поток

explode
get_html_translation_table
Обработка строк
PHP Manual

fprintf

(PHP 5)

fprintf — Записывает отформатированную строку в поток

Описание

int fprintf ( resource $handle , string $format [, mixed $args [, mixed $... ]] )

Записывает строку, созданную с использованием строки формата format, в поток, дескриптор которого передается в параметре handle.

Список параметров

handle

Указатель (resource) на файл, обычно создаваемый с помощью функции fopen().

format

Описание параметра format смотрите в описании функции sprintf().

args

...

Возвращаемые значения

Возвращает длину записанной строки.

Примеры

Пример #1 fprintf(): заполнение нулями

<?php
if (!($fp = fopen('date.txt', 'w'))) {
    return;
}

fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// запишет форматированную ISO дату в файл date.txt
?>

Пример #2 fprintf(): форматирование денежных величин

<?php
if (!($fp = fopen('currency.txt', 'w'))) {
    return;
}

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money выведет "123.1";
$len = fprintf($fp, '%01.2f', $money);
// строка "123.10" записана в файл currency.txt

echo "записано $len байт в файл currency.txt";
// используйте возвращаемое из fprintf значение для определения количества записанных байт
?>

Смотрите также

  • printf() - Выводит отформатированную строку
  • sprintf() - Возвращает отформатированную строку
  • sscanf() - Разбирает строку в соответствии с заданным форматом
  • fscanf() - Обрабатывает данные из файла в соответствии с форматом
  • vsprintf() - Возвращает отформатированную строку
  • number_format() - Форматирует число с разделением групп

User Contributed Notes

jgbreezer at hotmail dot com 07-Sep-2006 07:14
Another alternative using sprintf and fwrite() for pre-v5 php's:

fwrite( resource, sprintf(format [, mixed args [, mixed ...]] ))

Barring slight logical differences in meaning of returned value and (maybe??) how it handles magic_quotes_runtime config option, see fwrite() help.
aidan at php dot net 30-May-2004 10:35
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
explode
get_html_translation_table
Обработка строк


Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities

fprintf
hebrev
Обработка строк
PHP Manual

get_html_translation_table

(PHP 4, PHP 5)

get_html_translation_table — Возвращает таблицу преобразований, используемую функциями htmlspecialchars() и htmlentities()

Описание

array get_html_translation_table ([ int $table = HTML_SPECIALCHARS [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = 'UTF-8' ]]] )

get_html_translation_table() возвращает таблицу
преобразований, используемую функциями htmlspecialchars()
и htmlentities().

Замечание:

Специальные символы могут быть закодированы разными способами. Например, " может быть закодирован как &quot;, &#34; или &#x22. get_html_translation_table() возвращает только формы, используемые функциями htmlspecialchars() и htmlentities().

Список параметров

table

Указывает, какую таблицу использовать для преобразований. Либо HTML_ENTITIES, либо HTML_SPECIALCHARS.

flags

Битовая маска, состоящая из одного или нескольких перечисленных ниже флагов, которые указывают какие кавычки будет содержать таблица, а также для какого документа таблица предназначена. Значение по умолчанию ENT_COMPAT | ENT_HTML401.

Доступные константы в параметре flags
Имя константы | Описание
ENT_COMPAT | Таблица будет содержать сущности для двойных кавычек, но не будет для одинарных.
ENT_QUOTES | Таблица будет содержать сущности как для двойных кавычек, так и для одинарных.
ENT_NOQUOTES | Таблица не будет содержать сущности ни для двойных кавычек, ни для одинарных.
ENT_HTML401 | Таблица для HTML 4.01.
ENT_XML1 | Таблица для XML 1.
ENT_XHTML | Таблица для XHTML.
ENT_HTML5 | Таблица для HTML 5.

encoding

Используемая кодировка. Если не указана, то значением по умолчанию для этого аргумента является ISO-8859-1 в версиях PHP до 5.4.0 и UTF-8, начиная с версии 5.4.0 и далее.

Поддерживаются следующие кодировки:

Поддерживаемые кодировки
Кодировка | Псевдонимы | Описание
ISO-8859-1 | ISO8859-1 | Западно-европейская Latin-1.
ISO-8859-5 | ISO8859-5 | Редкоиспользуемая кириллическая кодировка (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Западно-европейская Latin-9. Добавляет знак евро, французские и финские буквы к кодировке Latin-1(ISO-8859-1).
UTF-8 | 8-битная Unicode, совместимая с ASCII.
cp866 | ibm866, 866 | Кириллическая кодировка, применяемая в DOS.
cp1251 | Windows-1251, win-1251, 1251 | Кириллическая кодировка, применяемая в Windows.
cp1252 | Windows-1252, 1252 | Западно-европейская кодировка, применяемая в Windows.
KOI8-R | koi8-ru, koi8r | Русская кодировка.
BIG5 | 950 | Традиционный китайский, применяется в основном на Тайване.
GB2312 | 936 | Упрощенный китайский, стандартная национальная кодировка.
BIG5-HKSCS | Расширенная Big5, применяемая в Гонг-Конге.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Японская кодировка.
EUC-JP | EUCJP, eucJP-win | Японская кодировка.
MacRoman | Кодировка, используемая в Mac OS.
'' Пустая строка активирует режим определения кодировки из файла скрипта (Zend multibyte), default_charset и текущей локали (см. nl_langinfo() и setlocale()), в указанном порядке. Не рекомендуется к использованию.

Замечание: Остальные кодировки не поддерживаются, вместо них будет применена кодировка по умолчанию и сгенерировано предупреждение.

Возвращаемые значения

Возвращает таблицу преобразований в виде массива с оригинальными символами в качестве ключей и сущностями в качестве значений.

Список изменений

Версия | Описание
5.4.0 | Значение по умолчанию для параметра encoding было изменено на UTF-8.
5.4.0 | Были добавлены константы ENT_HTML401, ENT_XML1, ENT_XHTML и ENT_HTML5.
5.3.4 | Добавлен параметр encoding.

Примеры

Пример #1 Пример таблицы преобразований

<?php
var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5));
?>

Результатом выполнения данного примера будет что-то подобное:

array(1510) {
  ["    "]=>
  string(5) "&Tab;"
  ["
"]=>
  string(9) "&NewLine;"
  ["!"]=>
  string(6) "&excl;"
  ["""]=>
  string(6) "&quot;"
  ["#"]=>
  string(5) "&num;"
  ["$"]=>
  string(8) "&dollar;"
  ["%"]=>
  string(8) "&percnt;"
  ["&"]=>
  string(5) "&amp;"
  ["'"]=>
  string(6) "&apos;"
  // ...
}

Смотрите также

  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • htmlentities() - Преобразует все возможные символы в соответствующие HTML-сущности
  • html_entity_decode() - Преобразует все HTML-сущности в соответствующие символы

User Contributed Notes

michael dot genesis at gmail dot com 12-Dec-2011 03:01
The fact that MS-word and some other sources use CP-1252, and that it is so close to Latin1 ('ISO-8859-1') causes a lot of confusion. What confused me the most was finding that mySQL uses CP-1252 by default.

You may run into trouble if you find yourself tempted to do something like this:
<?php
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
?>

Don't do it. DON'T DO IT!

You can use:
<?php
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'WINDOWS-1252');
?>

or just convert directly:
<?php
    $output = htmlentities($input, ENT_NOQUOTES, 'WINDOWS-1252');
?>

But your web page is probably encoded UTF-8, and you probably don't really want CP-1252 text flying around, so fix the character encoding first:
<?php
    $output = mb_convert_encoding($input, 'UTF-8', 'WINDOWS-1252');
    $ouput = htmlentities($output);
?>
kevin at cwsmailbox dot xom 15-Sep-2010 09:55
Be careful using get_html_translation_table() in a loop, as it's very slow.
subweb007 at hotmail dot com 09-Apr-2009 01:29
This function will convert get_html_translation_table from a ISO-8859-1 string to UTF-8 string.

<?php
function translation_table_to_utf8($arTranslationtable)
{
    //loop through the array and convert everything both keys and values
    foreach($arTranslationtable as $charkey => $char)
    {
        $charkey = utf8_encode($charkey);
        $arUTFchars[$charkey]= utf8_encode($char);
    }
     return $arUTFchars;
}

//get the translation table
$arSpecialchar     = get_html_translation_table(HTML_ENTITIES);

//call the function to convert to utf-8
$arUTFchars = translation_table_to_utf8($arSpecialchar);
print_r($arUTFchars);
?>
Kenneth Kin Lum 23-Sep-2008 05:54
to display the mapping on a webpage no matter what the server encoding is, this can be used

  echo "<pre>\n";
  echo htmlentities(print_r((get_html_translation_table(HTML_SPECIALCHARS)), true));
  echo htmlentities(print_r((get_html_translation_table(HTML_ENTITIES)), true));

since get_html_translation_table() actually gives the special chars in iso-8859-1 (Latin-1) encoding, so to see the tables correctly using

  print_r(get_html_translation_table(HTML_ENTITIES));

your server needs to give a HTTP header as iso-8859-1, unless you use header() or manually set the browser's encoding setting to iso-8859-1.  And you need to view the source of the page to see the mapping.  (except English version of IE 7 outputs the page source as iso-8859-1 anyway).
robertn972 at gmail dot com 22-Jul-2008 08:18
I found this useful in converting latin characters

<?php
function convertLatin1ToHtml($str) {
$allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
$specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
$noTags = array_diff($allEntities, $specialEntities);
$str = strtr($str, $noTags);
return $str;
}
?>
adolfoabegg at gmail dot com 03-Jul-2008 12:47
"rafael at phpit dot com dot br" your solution only works for the ISO-8859-1 encoding, I mean, it works but only for that encoding and that's because get_html_translation_table won't let you specify the charset... it uses the default one, that is ISO-8859-1

The solution from "olito24 at gmx dot de" does work for UTF-8, I just modified it a bit specifying the UTF-8 charset, also the $str parameter wasn't being used at all, I just renamed it to $string

Note:
Change ENT_NOQUOTES to ENT_QUOTES to convert both double and single quotes

These are the functions to encode html but tags using UTF-8 and ISO-8859-1

<?php

class Html
{

/*by olito24 at gmx dot de*/
    function htmlButTags($string) {

        $pattern = '<([a-zA-Z0-9\. "\'_\/-=;\(\)?&#%]+)>';
        preg_match_all ('/' . $pattern . '/', $string, $tagMatches, PREG_SET_ORDER);
        $textMatches = preg_split ('/' . $pattern . '/', $string);

        foreach ($textMatches as $key => $value) {
            $textMatches [$key] = htmlentities ($value, ENT_NOQUOTES, 'UTF-8');
        }

        for ($i = 0; $i < count ($textMatches); $i ++) {
            $textMatches [$i] = $textMatches [$i] . $tagMatches [$i] [0];
        }

        return implode ($textMatches);

    }

/*by "rafael at phpit dot com dot br" */
    function htmlButTags_iso($str){
        // Take all the html entities
        $caracteres = get_html_translation_table(HTML_ENTITIES,ENT_NOQUOTES);
        // Find out the "tags" entities
        $remover = get_html_translation_table(HTML_SPECIALCHARS,ENT_NOQUOTES);
        // Spit out the tags entities from the original table
        $caracteres = array_diff($caracteres, $remover);
        // Translate the string....
        $str = strtr($str, $caracteres);
        // And that's it!
        return $str;
    }

}

?>
Liam Morland 16-Jun-2008 08:57
Here is a simple way to convert named character entities to numeric character entities:

<?php
function numeric_entities($string){
    $mapping = array();
    foreach (get_html_translation_table(HTML_ENTITIES, ENT_QUOTES) as $char => $entity){
        $mapping[$entity] = '&#' . ord($char) . ';';
    }
    return str_replace(array_keys($mapping), $mapping, $string);
}
?>
iain (duh) workingsoftware.com.au 07-Sep-2007 02:06
I wrote a quick little function for converting something like '&middot;' into '&#183;':

$to_convert = '&middot;';
$table = get_html_translation_table(HTML_ENTITIES);
$equiv = '&#'.ord(array_search($to_convert,$table)).';';
Maurizio Siliani at trident dot it 20-Jul-2007 08:43
If you have troubles (like me) getting data from ISO-8859-1 encoded forms where user copy and paste from word, this routine could be useful.
It adds to the standard get_html_translation_table the codes of the characters usually M$ Word replacs into typed text.
Otherwise those characters would never be displayed correctly in html output.

function get_html_translation_table_CP1252() {
    $trans = get_html_translation_table(HTML_ENTITIES);
    $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
    $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
    $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
    $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
    $trans[chr(134)] = '&dagger;';    // Dagger
    $trans[chr(135)] = '&Dagger;';    // Double Dagger
    $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
    $trans[chr(137)] = '&permil;';    // Per Mille Sign
    $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
    $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
    $trans[chr(140)] = '&OElig;    ';    // Latin Capital Ligature OE
    $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
    $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
    $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
    $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
    $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
    $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
    $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
    $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
    ksort($trans);
    return $trans;
}
yes at king22 dot com 10-Apr-2007 08:33
Searching for a fast replacement of the MS WORD special characters which are not covered by get_html_translation_table() , I think the following function might help someone

<?php
function clean_up($str){
$str = stripslashes($str);
$str = strtr($str, get_html_translation_table(HTML_ENTITIES));
$str = str_replace( array("\x82", "\x84", "\x85", "\x91", "\x92", "\x93", "\x94", "\x95", "\x96",  "\x97"), array("&#8218;", "&#8222;", "&#8230;", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8226;", "&#8211;", "&#8212;"),$str);
return $str;
}
?>

It replaces all types of quotes (single and double), horizontal ellipsis (...), bullet, en dash and em dash.
chris 21-Feb-2007 05:49
A lot of quite common characters (or at least not rare, like oelig, euro or minus) are missing from the table unfortunately.
Here are some, if you want to make your translation table more complete and your xml data less error-prone. Not sure why some characters have 2 codes, just use one. Here goes: '&apos;'=>'&#39;', '&minus;'=>'&#45;', '&circ;'=>'&#94;', '&tilde;'=>'&#126;', '&Scaron;'=>'&#138;', '&lsaquo;'=>'&#139;', '&OElig;'=>'&#140;', '&lsquo;'=>'&#145;', '&rsquo;'=>'&#146;', '&ldquo;'=>'&#147;', '&rdquo;'=>'&#148;', '&bull;'=>'&#149;', '&ndash;'=>'&#150;', '&mdash;'=>'&#151;', '&tilde;'=>'&#152;', '&trade;'=>'&#153;', '&scaron;'=>'&#154;', '&rsaquo;'=>'&#155;', '&oelig;'=>'&#156;', '&Yuml;'=>'&#159;', '&yuml;'=>'&#255;', '&OElig;'=>'&#338;', '&oelig;'=>'&#339;', '&Scaron;'=>'&#352;', '&scaron;'=>'&#353;', '&Yuml;'=>'&#376;', '&fnof;'=>'&#402;', '&circ;'=>'&#710;', '&tilde;'=>'&#732;', '&Alpha;'=>'&#913;', '&Beta;'=>'&#914;', '&Gamma;'=>'&#915;', '&Delta;'=>'&#916;', '&Epsilon;'=>'&#917;', '&Zeta;'=>'&#918;', '&Eta;'=>'&#919;', '&Theta;'=>'&#920;', '&Iota;'=>'&#921;', '&Kappa;'=>'&#922;', '&Lambda;'=>'&#923;', '&Mu;'=>'&#924;', '&Nu;'=>'&#925;', '&Xi;'=>'&#926;', '&Omicron;'=>'&#927;', '&Pi;'=>'&#928;', '&Rho;'=>'&#929;', '&Sigma;'=>'&#931;', '&Tau;'=>'&#932;', '&Upsilon;'=>'&#933;', '&Phi;'=>'&#934;', '&Chi;'=>'&#935;', '&Psi;'=>'&#936;', '&Omega;'=>'&#937;', '&alpha;'=>'&#945;', '&beta;'=>'&#946;', '&gamma;'=>'&#947;', '&delta;'=>'&#948;', '&epsilon;'=>'&#949;', '&zeta;'=>'&#950;', '&eta;'=>'&#951;', '&theta;'=>'&#952;', '&iota;'=>'&#953;', '&kappa;'=>'&#954;', '&lambda;'=>'&#955;', '&mu;'=>'&#956;', '&nu;'=>'&#957;', '&xi;'=>'&#958;', '&omicron;'=>'&#959;', '&pi;'=>'&#960;', '&rho;'=>'&#961;', '&sigmaf;'=>'&#962;', '&sigma;'=>'&#963;', '&tau;'=>'&#964;', '&upsilon;'=>'&#965;', '&phi;'=>'&#966;', '&chi;'=>'&#967;', '&psi;'=>'&#968;', '&omega;'=>'&#969;', '&thetasym;'=>'&#977;', '&upsih;'=>'&#978;', '&piv;'=>'&#982;', '&ensp;'=>'&#8194;', '&emsp;'=>'&#8195;', '&thinsp;'=>'&#8201;', '&zwnj;'=>'&#8204;', '&zwj;'=>'&#8205;', '&lrm;'=>'&#8206;', '&rlm;'=>'&#8207;', '&ndash;'=>'&#8211;', '&mdash;'=>'&#8212;', '&lsquo;'=>'&#8216;', '&rsquo;'=>'&#8217;', '&sbquo;'=>'&#8218;', '&ldquo;'=>'&#8220;', '&rdquo;'=>'&#8221;', '&bdquo;'=>'&#8222;', '&dagger;'=>'&#8224;', '&Dagger;'=>'&#8225;', '&bull;'=>'&#8226;', '&hellip;'=>'&#8230;', '&permil;'=>'&#8240;', '&prime;'=>'&#8242;', '&Prime;'=>'&#8243;', '&lsaquo;'=>'&#8249;', '&rsaquo;'=>'&#8250;', '&oline;'=>'&#8254;', '&frasl;'=>'&#8260;', '&euro;'=>'&#8364;'
chris 21-Feb-2007 05:49
and a few more :
'&image;'=>'&#8465;', '&weierp;'=>'&#8472;', '&real;'=>'&#8476;', '&trade;'=>'&#8482;', '&alefsym;'=>'&#8501;', '&larr;'=>'&#8592;', '&uarr;'=>'&#8593;', '&rarr;'=>'&#8594;', '&darr;'=>'&#8595;', '&harr;'=>'&#8596;', '&crarr;'=>'&#8629;', '&lArr;'=>'&#8656;', '&uArr;'=>'&#8657;', '&rArr;'=>'&#8658;', '&dArr;'=>'&#8659;', '&hArr;'=>'&#8660;', '&forall;'=>'&#8704;', '&part;'=>'&#8706;', '&exist;'=>'&#8707;', '&empty;'=>'&#8709;', '&nabla;'=>'&#8711;', '&isin;'=>'&#8712;', '&notin;'=>'&#8713;', '&ni;'=>'&#8715;', '&prod;'=>'&#8719;', '&sum;'=>'&#8721;', '&minus;'=>'&#8722;', '&lowast;'=>'&#8727;', '&radic;'=>'&#8730;', '&prop;'=>'&#8733;', '&infin;'=>'&#8734;', '&ang;'=>'&#8736;', '&and;'=>'&#8743;', '&or;'=>'&#8744;', '&cap;'=>'&#8745;', '&cup;'=>'&#8746;', '&int;'=>'&#8747;', '&there4;'=>'&#8756;', '&sim;'=>'&#8764;', '&cong;'=>'&#8773;', '&asymp;'=>'&#8776;', '&ne;'=>'&#8800;', '&equiv;'=>'&#8801;', '&le;'=>'&#8804;', '&ge;'=>'&#8805;', '&sub;'=>'&#8834;', '&sup;'=>'&#8835;', '&nsub;'=>'&#8836;', '&sube;'=>'&#8838;', '&supe;'=>'&#8839;', '&oplus;'=>'&#8853;', '&otimes;'=>'&#8855;', '&perp;'=>'&#8869;', '&sdot;'=>'&#8901;', '&lceil;'=>'&#8968;', '&rceil;'=>'&#8969;', '&lfloor;'=>'&#8970;', '&rfloor;'=>'&#8971;', '&lang;'=>'&#9001;', '&rang;'=>'&#9002;', '&loz;'=>'&#9674;', '&spades;'=>'&#9824;', '&clubs;'=>'&#9827;', '&hearts;'=>'&#9829;', '&diams;'=>'&#9830;'
Jérôme Jaglale 31-Dec-2006 11:43
htmlentities includes htmlspecialchars, so here's how to convert an UTF-8 string :
htmlentities($string, ENT_QUOTES, 'UTF-8');
zohar at zohararad dot com 04-Dec-2006 06:31
Another way of converting HTML entities into numeric entities to please XML parsers is using two arrays as conversion tables in a preg_replace function. The conversion table mechanism is based on Ryan's examples above.

<?php
function xmlEntities($s){
//build first an assoc. array with the entities we want to match
$table1 = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);

//now build another assoc. array with the entities we want to replace (numeric entities)
foreach ($table1 as $k=>$v){
  $table1[$k] = "/$v/";
  $c = htmlentities($k,ENT_QUOTES,"UTF-8");
  $table2[$c] = "&#".ord($k).";";
}

//now perform a replacement using preg_replace
//each matched value in array 1 will be replaced with the corresponding value in array 2
$s = preg_replace($table1,$table2,$s);
return $s;
}
?>
trukin at gmail dot com 29-Oct-2006 11:25
There have been issues when hispanic websites or other websites dont use the corrent collision in mysql.

Some problems result that the accents (éä ... ) result in weird characters when a backup is done and restored later on. Or when database is changed to another one.

To fix this try something like this
function accents($text){
    foreach(get_html_translation_table(HTML_ENTITIES) as $a=>$b){
        $text = str_replace($a,$b,$text);
    }
    return $text;
}

and use as accents("Hello ....... WITH ACCENTS") and it will return the escaped string.
edwardzyang at thewritingpot dot com 23-Jul-2006 07:04
Quite disappointingly, get_html_translation_table() only gives the characters for ISO-8859-1, making it quite useless for UTF-8 or anything else like that (as a previous commenter noticed).
rbotzer at yahoo dot com 19-Jul-2005 02:10
The existance of html entities such as &quot; inside an xml node causes most xml parsers to throw an error.  The following function cleans an input string by converting html entities to valid unicode entities.

<?php

function htmlentities2unicodeentities ($input) {
  $htmlEntities = array_values (get_html_translation_table (HTML_ENTITIES, ENT_QUOTES));
  $entitiesDecoded = array_keys   (get_html_translation_table (HTML_ENTITIES, ENT_QUOTES));
  $num = count ($entitiesDecoded);
  for ($u = 0; $u < $num; $u++) {
    $utf8Entities[$u] = '&#'.ord($entitiesDecoded[$u]).';';
  }
  return str_replace ($htmlEntities, $utf8Entities, $input);
}
?>

So, an input of
Copyrights &copy; make &quot;me&quot; grin &reg;

outputs
Copyrights &#169; make &#34;me&#34; grin &#174;
Patrick nospam at nospam mesopia dot com 29-May-2005 07:00
Not sure what's going on here but I've run into a problem that others might face as well...

<?php

$translations = array_flip(get_html_translation_table(HTML_ENTITIES,ENT_QUOTES));

?>

returns the single quote ' as being equal to &#39; while

<?php

$translatedString = htmlentities($string,ENT_QUOTES);

?>
returns it as being equal to &#039;

I've had to do a specific string replacement for the time being... Not sure if it's an issue with the function or the array manipulation.

-Pat
Alex Minkoff 18-May-2005 04:30
If you want to display special HTML entities in a web browser, you can use the following code:

<?
$entities = get_html_translation_table(HTML_ENTITIES);
foreach ($entities as $entity) {
    $new_entities[$entity] = htmlspecialchars($entity);
}
echo "<pre>";
print_r($new_entities);
echo "</pre>";
?>

If you don't, the key name of each element will appear to be the same as the element content itself, making it look mighty stupid. ;)
ryan at ryancannon dot com 26-Jan-2005 02:05
In XML, you can't assume that the doctype will include the same character entity definitions as HTML. XML authors may require character references instead. The following two functions use get_html_translation_table() to encode data in numeric references. The second, optional argument can be used to substitute a different translation table.

function xmlcharacters($string, $trans='') {
    $trans=(is_array($trans))? $trans:get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
    foreach ($trans as $k=>$v)
        $trans[$k]= "&#".ord($k).";";
    return strtr($string, $trans);
}
function xml_character_decode($string, $trans='') {
    $trans=(is_array($trans))? $trans:get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
    foreach ($trans as $k=>$v)
        $trans[$k]= "&#".ord($k).";";
    $trans=array_flip($trans);
    return strtr($string, $trans);
}
pinkpanther at swissonline dot ch 28-Jul-2003 02:29
In case you want a 'htmlentities' function which prevents 'double' encoding of the ampersands of already present entities (&gt; => &amp;gt;), use this:

<?php
function htmlentities2($myHTML) {
   $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
   $translation_table[chr(38)] = '&';
   return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , strtr($myHTML, $translation_table));
}
?>
kevin_bro at hostedstuff dot com 03-Jan-2003 06:06
Alans version didn't seem to work right. If you're having the same problem consider using this slightly modified version instead:

function unhtmlentities ($string)  {
   $trans_tbl = get_html_translation_table (HTML_ENTITIES);
   $trans_tbl = array_flip ($trans_tbl);
   $ret = strtr ($string, $trans_tbl);
   return preg_replace('/&#(\d+);/me',
      "chr('\\1')",$ret);
}
kumar at chicagomodular.com 28-Oct-2002 05:51
without heavy scientific analysis, this seems to work as a quick fix to making text originating from a Microsoft Word document display as HTML:

<?php
function DoHTMLEntities ($string)
    {
        $trans_tbl = get_html_translation_table (HTML_ENTITIES);

        // MS Word strangeness..
        // smart single/ double quotes:
        $trans_tbl[chr(145)] = '\'';
        $trans_tbl[chr(146)] = '\'';
        $trans_tbl[chr(147)] = '&quot;';
        $trans_tbl[chr(148)] = '&quot;';

                // Acute 'e'
        $trans_tbl[chr(142)] = '&eacute;';

        return strtr ($string, $trans_tbl);
    }
?>
alan at akbkhome dot com 03-Jun-2002 10:00
If you want to decode all those &#123; symbols as well....

function unhtmlentities ($string)  {
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    $ret = strtr ($string, $trans_tbl);
    return  preg_replace('/\&\#([0-9]+)\;/me',
        "chr('\\1')",$ret);
}
dirk at hartmann dot net 19-Jun-2001 01:41
get_html_translation_table
It works only with the first 256 Codepositions.
For Higher Positions, for Example &#1092;
(a kyrillic Letter) it shows the same.
fprintf
hebrev
Обработка строк


Преобразует текст на иврите из логической кодировки в визуальную

get_html_translation_table
hebrevc
Обработка строк
PHP Manual

hebrev

(PHP 4, PHP 5)

hebrev — Преобразует текст на иврите из логической кодировки в визуальную

Описание

string hebrev ( string $hebrew_text [, int $max_chars_per_line = 0 ] )

Преобразует текст на иврите из логической кодировки в визуальную.

Эта функция пытается избежать разрывов слов.

Список параметров

hebrew_text

Входная строка на иврите.

max_chars_per_line

Этот необязательный параметр указывает максимально возвращаемое число символов на строку.

Возвращаемые значения

Возвращает строку в визуальной кодировке.

Смотрите также

  • hebrevc() - Преобразует текст на иврите из логической кодировки в визуальную с преобразованием перевода строки

User Contributed Notes

ti-tim-timmy 04-Apr-2009 03:25
udioron - exactly right. That reversed the string.
Thank you.
udioron at geeee mmmaaaaiiillll dotcom 01-Jan-2009 05:14
This might work for unicode strings:

<?php
$s = iconv("ISO-8859-8", "UTF-8", hebrev(iconv("UTF-8", "ISO-8859-8", $s)));
?>

Udi
socket at quotez dot org 29-Apr-2008 12:58
hebrev/hebrevc does not support unicode strings.

when using the GD lib and imagettftext() with hebrew text you must reverse the chars before sending it to the function.

so there is a need for hebrev/c with unicode support.
nis at superlativ dot dk 04-Dec-2006 12:34
In response to the user talking of "characters in the range of ASCII 224-251". These codes are not defined in ASCII. You are probably talking about one of the extensions to ASCII, probably ISO-8859-8
tinko 14-Dec-2004 03:46
From my experience in using hebrev text in HTML, I prefer using

<html dir="rtl" lang="he">

over mentioned PHP functions. It works perfectly with IE 6 ... needs some tweaking in Mozilla though.

I found this site http://tlt.its.psu.edu/suggestions/international/web/tips/align.html useful.
socket at linuxloony dot net 03-Apr-2004 06:17
The hebrev function changes the string order to RTL.
Use fribidi_log2vis insted if you need LTR text direction
$text = fribidi_log2vis($text,FRIBIDI_LTR, FRIBIDI_CHARSET_CP1255)
php2eran at tromer dot org 01-Jun-2001 04:35
As of PHP 4.05 there's a problem in the handling of the characters '{}[]<>' compared to MSIE. Note that normal parenthesis '()' are OK.

For further information see http://www.php.net/bugs.php?id=11244 .
zak at php dot net 09-Jan-2001 03:39
hebrev() changes the flow of any Hebrew characters in a string from right-to-left to left-to-right.

It only affects characters within the range of ASCII 224-251 (except for punctuation).
get_html_translation_table
hebrevc
Обработка строк


Преобразует текст на иврите из логической кодировки в визуальную с преобразованием перевода строки

hebrev
hex2bin
Обработка строк
PHP Manual

hebrevc

(PHP 4, PHP 5)

hebrevc — Преобразует текст на иврите из логической кодировки в визуальную с преобразованием перевода строки

Описание

string hebrevc ( string $hebrew_text [, int $max_chars_per_line = 0 ] )

Эта функция похожа на hebrev() с тем отличием, что что она преобразует символы перевода строки (\n) в "<br>\n".

Эта функция пытается избежать разрывов слов.

Список параметров

hebrew_text

Входная строка на иврите.

max_chars_per_line

Этот необязательный параметр указывает максимально возвращаемое число символов на строку.

Возвращаемые значения

Возвращает строку в визуальной кодировке.

Смотрите также

  • hebrev() - Преобразует текст на иврите из логической кодировки в визуальную

User Contributed Notes

Oded 03-Jul-2009 03:57
If you want to use hebrevc with english,
just use strrev.
yfurman at yahoo dot com 10-Dec-2001 04:41
Beware of English use!
I was working on a little project, and used hebrevc to reverse Hebrew in a loop. The hebrevc function got a variable as an argument. Sometimes the variable was pure English and sometimes it was hebrew.
Suddenly I found out that the English too was cut with BR tags, which made it look funny - the last line was the first.

If you're going to use that function in mixed text, don't forget to check the language before using the function.

Yael
hebrev
hex2bin
Обработка строк


Преобразует шестнадцатеричные данные в двоичные

hebrevc
html_entity_decode
Обработка строк
PHP Manual

hex2bin

(PHP >= 5.4.0)

hex2bin — Преобразует шестнадцатеричные данные в двоичные

Описание

string hex2bin ( string $data )

Декодирует строку данных из шестнадцатеричного представления

Предостережение

Эта функция НЕ конвертирует шестнадцатиричные числа в двоичные. Если нужно именно это, используйте функцию base_convert().

Список параметров

data

Шестнадцатеричное представление данных.

Возвращаемые значения

Возвращает двоичное представление данных, или FALSE в случае возникновения ошибки.

Ошибки

Если во входной шестнадцатиричной строке окажется нечетное число байт, будет выдано предупреждение E_WARNING.

Список изменений

Версия | Описание
PHP 5.4.1 | Если строка имеет нечетную длину, выбрасывается предупреждение. ВPHP 5.4.0 такая строка принималась, а последний байт просто обрезался.

Примеры

Пример #1 Пример использования hex2bin()

<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

Результатом выполнения данного примера будет что-то подобное:

string(16) "пример hex данных"

Смотрите также

  • bin2hex() - Преобразует бинарные данные в шестнадцатиричное представление
  • unpack() - Распаковывает данные из бинарной строки

User Contributed Notes

Anonymous 23-Feb-2012 02:28
The function pack("H*" , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.

For example:

<?php echo ord(pack("H*", 'F')); ?>

will return 240 not 15. Use pack("H*", '0F'); instead.
Anonymous 31-Aug-2011 01:32
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);
hebrevc
html_entity_decode
Обработка строк


Преобразует все HTML-сущности в соответствующие символы

hex2bin
htmlentities
Обработка строк
PHP Manual

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5)

html_entity_decode — Преобразует все HTML-сущности в соответствующие символы

Описание

string html_entity_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = 'UTF-8' ]] )

html_entity_decode() является противоположностью функции htmlentities(). Она преобразует все HTML-сущности в строке string в соответствующие символы.

Список параметров

string

Входная строка.

flags

Битовая маска, состоящая из одного или более флагов, которые указывают как обращаться с кавычками и какой тип документа использовать. По умолчанию маска принимает значение ENT_COMPAT | ENT_HTML401.

Константы flags
Имя константы | Описание
ENT_COMPAT | Преобразуются двойные кавычки, одиночные остаются без изменений.
ENT_QUOTES | Преобразуются и двойные, и одиночные кавычки.
ENT_NOQUOTES | И двойные, и одиночные кавычки остаются без изменений.
ENT_HTML401 | Обрабатывать код как HTML 4.01.
ENT_XML1 | Обрабатывать код как XML 1.
ENT_XHTML | Обрабатывать код как XHTML.
ENT_HTML5 | Обрабатывать код как HTML 5.

encoding

Кодировка для использования. Если не указана, то значением по умолчанию для этого аргумента является ISO-8859-1 в версиях PHP до 5.4.0 и UTF-8 начиная с PHP 5.4.0 и далее.

Поддерживаются следующие кодировки:

Поддерживаемые кодировки
Кодировка | Псевдонимы | Описание
ISO-8859-1 | ISO8859-1 | Западно-европейская Latin-1.
ISO-8859-5 | ISO8859-5 | Редкоиспользуемая кириллическая кодировка (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Западно-европейская Latin-9. Добавляет знак евро, французские и финские буквы к кодировке Latin-1(ISO-8859-1).
UTF-8 | 8-битная Unicode, совместимая с ASCII.
cp866 | ibm866, 866 | Кириллическая кодировка, применяемая в DOS.
cp1251 | Windows-1251, win-1251, 1251 | Кириллическая кодировка, применяемая в Windows.
cp1252 | Windows-1252, 1252 | Западно-европейская кодировка, применяемая в Windows.
KOI8-R | koi8-ru, koi8r | Русская кодировка.
BIG5 | 950 | Традиционный китайский, применяется в основном на Тайване.
GB2312 | 936 | Упрощенный китайский, стандартная национальная кодировка.
BIG5-HKSCS | Расширенная Big5, применяемая в Гонг-Конге.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Японская кодировка.
EUC-JP | EUCJP, eucJP-win | Японская кодировка.
MacRoman | Кодировка, используемая в Mac OS.
'' Пустая строка активирует режим определения кодировки из файла скрипта (Zend multibyte), default_charset и текущей локали (см. nl_langinfo() и setlocale()), в указанном порядке. Не рекомендуется к использованию.

Замечание: Остальные кодировки не поддерживаются, вместо них будет применена кодировка по умолчанию и сгенерировано предупреждение.

Возвращаемые значения

Возвращает раскодированную строку.

Список изменений

Версия | Описание
5.4.0 | Кодировка по умолчанию сменилась с ISO-8859-1 на UTF-8.
5.4.0 | Были добавлены константы ENT_HTML401, ENT_XML1, ENT_XHTML и ENT_HTML5.
5.0.0 | Добавлена поддержка многобайтных кодировок.

Примеры

Пример #1 Декодирование HTML-сущностей

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now
?>

Примечания

Замечание:

Может показаться странным, что результатом вызова trim(html_entity_decode('&nbsp;')); не является пустая строка. Причина том, что '&nbsp;' преобразуется не в символ с ASCII-кодом 32 (который удаляется функцией trim()),а в символ с ASCII-кодом 160 (0xa0) в принимаемой по умолчанию кодировке ISO-8859-1.

Смотрите также

  • htmlentities() - Преобразует все возможные символы в соответствующие HTML-сущности
  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • get_html_translation_table() - Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities
  • urldecode() - Декодирование URL-кодированной строки

User Contributed Notes

Victor 14-Dec-2011 06:22
We were having very peculiar behavior regarding foreign characters such as e-acute.

However, it was only showing up as a problem when extracting those characters out of our mysql database and when being displayed through a proxy server of ours that handles dns issues.

As other users have made a note of, the default character setting wasn't what they were expecting it to be when they left theirs blank.

When we changed our default_charset to "UTF-8", our problems and needs for using functions like these were no longer necessary in handling foreign characters such as e-acute. Good enough for us!
Martin 26-Jun-2011 04:37
If you need something that converts &#[0-9]+ entities to UTF-8, this is simple and works:

<?php
/* Entity crap. /
$input = "Fovi&#269;";

$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);

/* Plain UTF-8. */
echo $output;
?>
John_Schlick at hotmail dot com 16-Feb-2011 02:39
BE AWARE:  The documentation around the default charset might be wrong.

The changelog says:
5.3.3     Default charset changed from ISO-8859-1 to UTF-8.

Despite the fact that we are running 5.3.3-7 when we do

html_entity_decode("&nbsp;", ENT_QUOTES);
we get "\xa0" the ISO-8859-1 version of a non breaking space.

When we change this to:
html_entity_decode("&nbsp;", ENT_QUOTES, 'UTF-8');
we properly get "\xc2\xa0"

Implying that 'UTF-8' is NOT the default for our installation of php.
neurotic dot neu at gmail dot com 10-Aug-2010 12:25
This is a safe rawurldecode with utf8 detection:

<?php
function utf8_rawurldecode($raw_url_encoded){
    $enc = rawurldecode($raw_url_encoded);
    if(utf8_encode(utf8_decode($enc))==$enc){;
        return rawurldecode($raw_url_encoded);
    }else{
        return utf8_encode(rawurldecode($raw_url_encoded));
    }
}
?>
Free at Key dot no 01-Jul-2010 05:51
Handy function to convert remaining HTML-entities into human readable chars (for entities which do not exist in target charset):

<?php
function cleanString($in,$offset=null)
{
    $out = trim($in);
    if (!empty($out))
    {
        $entity_start = strpos($out,'&',$offset);
        if ($entity_start === false)
        {
            // ideal
            return $out;
        }
        else
        {
            $entity_end = strpos($out,';',$entity_start);
            if ($entity_end === false)
            {
                 return $out;
            }
            // zu lang um eine entity zu sein
            else if ($entity_end > $entity_start+7)
            {
                 // und weiter gehts
                 $out = cleanString($out,$entity_start+1);
            }
            // gottcha!
            else
            {
                 $clean = substr($out,0,$entity_start);
                 $subst = substr($out,$entity_start+1,1);
                 // &scaron; => "s" / &#353; => "_"
                 $clean .= ($subst != "#") ? $subst : "_";
                 $clean .= substr($out,$entity_end+1);
                 // und weiter gehts
                 $out = cleanString($clean,$entity_start+1);
            }
        }
    }
    return $out;
}
?>
Matt Robinson 06-Sep-2009 02:11
I wrote in a previous comment that html_entity_decode() only handled about 100 characters. That's not quite true; it only handles entities that exist in the output character set (the third argument). If you want to get ALL HTML entities, make sure you use ENT_QUOTES and set the third argument to 'UTF-8'.

If you don't want a UTF-8 string, you'll need to convert it afterward with something like utf8_decode(), iconv(), or mb_convert_encoding().

If you're producing XML, which doesn't recognise most HTML entities:

When producing a UTF-8 document (the default), then htmlspecialchars(html_entity_decode($string, ENT_QUOTES, 'UTF-8'), ENT_NOQUOTES, 'UTF-8') (because you only need to escape < and > and & unless you're printing inside the XML tags themselves).

Otherwise, either convert all the named entities to numeric ones, or declare the named entities in the document's DTD. The full list of 252 entities can be found in the HTML 4.01 Spec, or you can cut and paste the function from my site (http://inanimatt.com/php-convert-entities.php).
marion at figmentthinking dot com 10-Mar-2009 05:11
I just ran into the:
Bug #27626 html_entity_decode bug - cannot yet handle MBCS in html_entity_decode()!

The simple solution if you're still running PHP 4 is to wrap the html_entity_decode() function with the utf8_decode() function.

<?php
$string = '&nbsp;';
$utf8_encode = utf8_encode(html_entity_decode($string));
?>

By default html_entity_decode() returns the ISO-8859-1 character set, and by default utf8_decode()...

http://us.php.net/manual/en/function.utf8-decode.php
"Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1"
jl dot garcia at gmail dot com 04-Mar-2009 03:33
I created this function to filter all the text that goes in or comes out of the database.

<?php
function filter_string($string, $nohtml='', $save='') {
    if(!empty($nohtml)) {
        $string = trim($string);
        if(!empty($save)) $string = htmlentities(trim($string), ENT_QUOTES, 'ISO-8859-15');
        else $string = html_entity_decode($string, ENT_QUOTES, 'ISO-8859-15');
    }
    if(!empty($save)) $string = mysql_real_escape_string($string);
    else $string = stripslashes($string);
    return($string);
}
?>
Anonymous 30-Jul-2008 10:01
You may want to specify the character set if you see unexpected behavior.  Here is an example.

# cat test.php
<?php
$str = '&#33;';
$quotes = html_entity_decode($str, ENT_QUOTES);
$noquotes = html_entity_decode($str, ENT_NOQUOTES);
$noquotesutf8 = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
echo "quotes='$quotes', noquotes='$noquotes', noquotesutf8='$noquotesutf8'\n";
?>

# php test.php
quotes='!', noquotes='&#33;', noquotesutf8='!'
kae at verens dot com 09-May-2008 06:11
the references to 'chr()' in the example unhtmlentities() function should be changed to unichr, using the example unichr() function described in the 'chr' reference (http://php.net/chr).

the reason for this is characters such as &#x20AC; which do not break down into an ASCII number (that's the Euro, by the way).
me at richardsnazell dot com 21-Jan-2008 04:19
I had a problem getting the 'TM' trademark symbol to display correctly in an email subject line. Using html_entity_decode() with different charsets didn't work, but directly replacing the entity with it's ASCII equivalent did:

$subject = str_replace('&trade;', chr(153), $subject);
jojo 03-Nov-2006 08:27
The decipherment does the character encoded by the escape function of JavaScript.
When the multi byte is used on the page, it is effective.

javascript escape('aaああaa') ..... 'aa%u3042%u3042aa'
php  jsEscape_decode('aa%u3042%u3042aa')..'aaああaa'

<?php
function jsEscape_decode($jsEscaped,$outCharCode='SJIS'){
    $arrMojis = explode("%u",$jsEscaped);
    for ($i = 1;$i < count($arrMojis);$i++){
        $c = substr($arrMojis[$i],0,4);
        $cc = mb_convert_encoding(pack('H*',$c),$outCharCode,'UTF-16');
        $arrMojis[$i] = substr_replace($arrMojis[$i],$cc,0,4);
    }
    return implode('',$arrMojis);
}
?>
romekt at CUTTHISgmail dot com 01-Sep-2006 02:15
here's a simple workaround for the UTF-8 support problem

<?php
$var=iconv("UTF-8","ISO-8859-1",$var);
$var=html_entity_decode($var, ENT_QUOTES, 'ISO-8859-1');
$var=iconv("ISO-8859-1","UTF-8",$var);
?>
grvg (at) free (dot) fr 29-Jul-2006 09:44
Here is the ultimate functions to convert HTML entities to UTF-8 :
The main function is htmlentities2utf8
Others are helper functions

<?php
function chr_utf8($code)
    {
        if ($code < 0) return false;
        elseif ($code < 128) return chr($code);
        elseif ($code < 160) // Remove Windows Illegals Cars
        {
            if ($code==128) $code=8364;
            elseif ($code==129) $code=160; // not affected
            elseif ($code==130) $code=8218;
            elseif ($code==131) $code=402;
            elseif ($code==132) $code=8222;
            elseif ($code==133) $code=8230;
            elseif ($code==134) $code=8224;
            elseif ($code==135) $code=8225;
            elseif ($code==136) $code=710;
            elseif ($code==137) $code=8240;
            elseif ($code==138) $code=352;
            elseif ($code==139) $code=8249;
            elseif ($code==140) $code=338;
            elseif ($code==141) $code=160; // not affected
            elseif ($code==142) $code=381;
            elseif ($code==143) $code=160; // not affected
            elseif ($code==144) $code=160; // not affected
            elseif ($code==145) $code=8216;
            elseif ($code==146) $code=8217;
            elseif ($code==147) $code=8220;
            elseif ($code==148) $code=8221;
            elseif ($code==149) $code=8226;
            elseif ($code==150) $code=8211;
            elseif ($code==151) $code=8212;
            elseif ($code==152) $code=732;
            elseif ($code==153) $code=8482;
            elseif ($code==154) $code=353;
            elseif ($code==155) $code=8250;
            elseif ($code==156) $code=339;
            elseif ($code==157) $code=160; // not affected
            elseif ($code==158) $code=382;
            elseif ($code==159) $code=376;
        }
        if ($code < 2048) return chr(192 | ($code >> 6)) . chr(128 | ($code & 63));
        elseif ($code < 65536) return chr(224 | ($code >> 12)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
        else return chr(240 | ($code >> 18)) . chr(128 | (($code >> 12) & 63)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
    }

    // Callback for preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $str);
    function html_entity_replace($matches)
    {
        if ($matches[2])
        {
            return chr_utf8(hexdec($matches[3]));
        } elseif ($matches[1])
        {
            return chr_utf8($matches[3]);
        }
        switch ($matches[3])
        {
            case "nbsp": return chr_utf8(160);
            case "iexcl": return chr_utf8(161);
            case "cent": return chr_utf8(162);
            case "pound": return chr_utf8(163);
            case "curren": return chr_utf8(164);
            case "yen": return chr_utf8(165);
            //... etc with all named HTML entities
        }
        return false;
    }

    function htmlentities2utf8 ($string) // because of the html_entity_decode() bug with UTF-8
    {
        $string = preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $string);
        return $string;
    }
?>
loufoque 08-Oct-2005 01:15
If you want to decode NCRs to utf-8 use this function instead of chr().

<?php
function utf8_chr($code)
{
    if($code<128) return chr($code);
    else if($code<2048) return chr(($code>>6)+192).chr(($code&63)+128);
    else if($code<65536) return chr(($code>>12)+224).chr((($code>>6)&63)+128).chr(($code&63)+128);
    else if($code<2097152) return chr($code>>18+240).chr((($code>>12)&63)+128)
                                  .chr(($code>>6)&63+128).chr($code&63+128));
}
?>
florianborn (at) yahoo (dot) de 20-Jul-2005 03:43
Note that

<?php

 echo urlencode(html_entity_decode("&nbsp;"));

?>

will output "%A0" instead of "+".
gaui at gaui dot is 04-Jul-2005 05:15
[If you are missing the html_entity_decode() function in your version of PHP, you may wish to try this code snippet.]

<?php
if( !function_exists( 'html_entity_decode' ) )
{
    function html_entity_decode( $given_html, $quote_style = ENT_QUOTES ) {
        $trans_table = array_flip(get_html_translation_table( HTML_SPECIALCHARS, $quote_style ));
        $trans_table['&#39;'] = "'";
        return ( strtr( $given_html, $trans_table ) );
       }
}
?>
marius (at) hot (dot) ee 08-Apr-2005 06:40
To convert html entities into unicode characters, use the following:

<?php
        $trans_tbl = get_html_translation_table(HTML_ENTITIES);
        foreach($trans_tbl as $k => $v)
        {
            $ttr[$v] = utf8_encode($k);
        }

        $text = strtr($text, $ttr);
?>
php dot net at c dash ovidiu dot tk 18-Mar-2005 12:37
Quick & dirty code that translates numeric entities to UTF-8.

<?php

    function replace_num_entity($ord)
    {
        $ord = $ord[1];
        if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match))
        {
            $ord = hexdec($match[1]);
        }
        else
        {
            $ord = intval($ord);
        }

        $no_bytes = 0;
        $byte = array();

        if ($ord < 128)
        {
            return chr($ord);
        }
        elseif ($ord < 2048)
        {
            $no_bytes = 2;
        }
        elseif ($ord < 65536)
        {
            $no_bytes = 3;
        }
        elseif ($ord < 1114112)
        {
            $no_bytes = 4;
        }
        else
        {
            return;
        }

        switch($no_bytes)
        {
            case 2:
            {
                $prefix = array(31, 192);
                break;
            }
            case 3:
            {
                $prefix = array(15, 224);
                break;
            }
            case 4:
            {
                $prefix = array(7, 240);
            }
        }

        for ($i = 0; $i < $no_bytes; $i++)
        {
            $byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;
        }

        $byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];

        $ret = '';
        for ($i = 0; $i < $no_bytes; $i++)
        {
            $ret .= chr($byte[$i]);
        }

        return $ret;
    }

    $test = 'This is a &#269;&#x5d0; test&#39;';

    echo $test . "<br />\n";
    echo preg_replace_callback('/&#([0-9a-fx]+);/mi', 'replace_num_entity', $test);

?>
Silvan 28-Jan-2005 07:33
Passing NULL or FALSE as a string will generate a '500 Internal Server Error' (or break the script when inside a function).

So always test your string first before passing it to html_entity_decode().
daniel at brightbyte dot de 13-Nov-2004 06:12
This function seems to have to have two limitations (at least in PHP 4.3.8):

a) it does not work with multibyte character codings, such as UTF-8
b) it does not decode numeric entity references

a) can be solved by using iconv to convert to ISO-8859-1, then decoding the entities, than convert to UTF-8 again. But that's quite ugly and detroys all characters not present in Latin-1.

b) can be solved rather nicely using the following code:

<?php
function decode_entities($text) {
    $text= html_entity_decode($text,ENT_QUOTES,"ISO-8859-1"); #NOTE: UTF-8 does not work!
    $text= preg_replace('/&#(\d+);/me',"chr(\\1)",$text); #decimal notation
    $text= preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)",$text);  #hex notation
    return $text;
}
?>

HTH
aidan at php dot net 14-Sep-2004 12:57
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
hex2bin
htmlentities
Обработка строк


Преобразует все возможные символы в соответствующие HTML-сущности

html_entity_decode
htmlspecialchars_decode
Обработка строк
PHP Manual

htmlentities

(PHP 4, PHP 5)

htmlentities — Преобразует все возможные символы в соответствующие HTML-сущности

Описание

string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = 'UTF-8' [, bool $double_encode = true ]]] )

Эта функция идентична htmlspecialchars() за исключением того, что htmlentities() преобразует все символы в соответствющие HTML-сущности (для тех символов, для которых HTML сущности существуют).

Если же вы хотите раскодировать строку (наоборот), используйте html_entity_decode().

Список параметров

string

Входная строка.

flags

Битовая маска из нижеуказанных флагов, определяющих режим обработки кавычек, некорректных кодовых последовательностей и используемый тип документа. По умолчанию используется ENT_COMPAT | ENT_HTML401.

Доступные значения параметра flags
Название константы | Описание
ENT_COMPAT | Преобразует двойные кавычки, одинарные кавычки не изменяются.
ENT_QUOTES | Преобразует как двойные, так и одинарные кавычки.
ENT_NOQUOTES | Оставляет без изменения как двойные, так и одинарные кавычки.
ENT_IGNORE | Молча отбрасывает некорректные кодовые последовательности вместо возврата пустой строки. Использование этого флага не рекомендуется, так как это » может внести уязвимости в ваш код.
ENT_SUBSTITUTE | Заменяет некорреткные кодовые последовательности символом замены Юникода U+FFFD в случае использования UTF-8 и &#FFFD; при использовании другой кодировки, вместо возврата пустой строки.
ENT_DISALLOWED | Заменяет неверные коды символов для заданного типа документа символом замены юникода U+FFFD (UTF-8) или &#FFFD; (при использовании другой кодировки) вместо того, чтобы оставлять все как есть. Это может быть полезно, например, для того, чтобы убедиться в формальной правильности XML-документов со встроенным внешним контентом.
ENT_HTML401 | Обработка кода в соответствии с HTML 4.01.
ENT_XML1 | Обработка кода в соответствии с XML 1.
ENT_XHTML | Обработка кода в соответствии с XHTML.
ENT_HTML5 | Обработка кода в соответствии с HTML 5.

encoding

Подобно htmlspecialchars(), функция htmlentities() принимает необязательный третий аргумент encoding, который задает кодировку, используемую при преобразовании. Если он не указан, то по умолчанию используется кодировка ISO-8859-1 в версиях PHP до 5.4.0 и UTF-8 - начиная с 5.4.0 и далее. Несмотря на то, что этот аргумент формально является необязательным, настоятельно рекомендуется указать правильное значение в вашем коде.

Поддерживаются следующие кодировки:

Поддерживаемые кодировки
Кодировка | Псевдонимы | Описание
ISO-8859-1 | ISO8859-1 | Западно-европейская Latin-1.
ISO-8859-5 | ISO8859-5 | Редкоиспользуемая кириллическая кодировка (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Западно-европейская Latin-9. Добавляет знак евро, французские и финские буквы к кодировке Latin-1(ISO-8859-1).
UTF-8 | 8-битная Unicode, совместимая с ASCII.
cp866 | ibm866, 866 | Кириллическая кодировка, применяемая в DOS.
cp1251 | Windows-1251, win-1251, 1251 | Кириллическая кодировка, применяемая в Windows.
cp1252 | Windows-1252, 1252 | Западно-европейская кодировка, применяемая в Windows.
KOI8-R | koi8-ru, koi8r | Русская кодировка.
BIG5 | 950 | Традиционный китайский, применяется в основном на Тайване.
GB2312 | 936 | Упрощенный китайский, стандартная национальная кодировка.
BIG5-HKSCS | Расширенная Big5, применяемая в Гонг-Конге.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Японская кодировка.
EUC-JP | EUCJP, eucJP-win | Японская кодировка.
MacRoman | Кодировка, используемая в Mac OS.
'' Пустая строка активирует режим определения кодировки из файла скрипта (Zend multibyte), default_charset и текущей локали (см. nl_langinfo() и setlocale()), в указанном порядке. Не рекомендуется к использованию.

Замечание: Остальные кодировки не поддерживаются, вместо них будет применена кодировка по умолчанию и сгенерировано предупреждение.

double_encode

При выключении параметра double_encode PHP не будет преобразовывать существующие html-сущности. По умолчанию преобразуется все без ограничений.

Возвращаемые значения

Возвращает преобразованную строку.

При наличии во входном параметре string недопустимой последовательности символов в заданной кодировке encoding будет возвращена пустая строка, если не установлены флаги ENT_IGNORE или ENT_SUBSTITUTE.

Список изменений

Версия | Описание
5.4.0 | Значение по умолчанию для параметра encoding было изменено на UTF-8.
5.4.0 | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML и ENT_HTML5.
5.3.0 | Добавлена константа ENT_IGNORE.
5.2.3 | Добавлен параметр double_encode.
4.1.0 | Добавлен параметр encoding.
4.0.3 | Добавлен параметр flags.

Примеры

Пример #1 Пример использования htmlentities()

<?php
$str = "A 'quote' is <b>bold</b>";

// выводит: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// выводит: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

Пример #2 Использование ENT_IGNORE

<?php
$str = "\x8F!!!";

// Выводит пустую строку
echo htmlentities($str, ENT_QUOTES, "UTF-8");

// Выводит "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>

Смотрите также

  • html_entity_decode() - Преобразует все HTML-сущности в соответствующие символы
  • get_html_translation_table() - Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities
  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • nl2br() - Вставляет HTML-код разрыва строки перед каждым переводом строки
  • urlencode() - URL-кодирование строки

User Contributed Notes

ustimenko dot alexander at gmail dot com 09-Apr-2012 02:15
For those Spanish (and not only) folks, that want their national letters back after htmlentities :)

<?php
protected function _decodeAccented($encodedValue, $options = array()) {
    $options += array(
        'quote'     => ENT_NOQUOTES,
        'encoding'  => 'UTF-8',
    );
    return preg_replace_callback(
        '/&\w(acute|uml|tilde);/',
        create_function(
            '$m',
            'return html_entity_decode($m[0], ' . $options['quote'] . ', "' .
            $options['encoding'] . '");'
        ),
        $encodedValue
    );
}
?>
n at erui dot eu 20-Mar-2012 12:46
html entities does not encode all unicode characters. It encodes what it can [all of latin1], and the others slip through. &#1033; is the nasty I use. I have searched for a function which encodes everything, but in the end I wrote this. This is as simple as I can get it. Consult an ansii table to custom include/omit chars you want/don't. I'm sure it's not that fast.

// Unicode-proof htmlentities.
// Returns 'normal' chars as chars and weirdos as numeric html entites.
function superentities( $str ){
    // get rid of existing entities else double-escape
    $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');
    $ar = preg_split('/(?<!^)(?!$)/u', $str );  // return array of every multi-byte character
    foreach ($ar as $c){
        $o = ord($c);
        if ( (strlen($c) > 1) || /* multi-byte [unicode] */
            ($o <32 || $o > 126) || /* <- control / latin weirdos -> */
            ($o >33 && $o < 40) ||/* quotes + ambersand */
            ($o >59 && $o < 63) /* html */
        ) {
            // convert to numeric entity
            $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
        }
        $str2 .= $c;
    }
    return $str2;
}
wd at NOSPAMwd dot it 19-Dec-2011 02:20
Hi there,

after several and several tests, I figured out that dot:

- htmlentities() function remove characters like "à","è",etc when you specify a flag and a charset

- htmlentities() function DOES NOT remove characters like those above when you DO NOT specify anything

So, let's assume that..

<?php

$str = "Hèèèllooo";

$res_1 = htmlentities($str, ENT_QUOTES, "UTF-8");
$res_2 = htmlentities($str);

echo var_dump($res_1); // Result: string '' (length=0)
echo var_dump($res_2); // string 'H&egrave;&egrave;&egrave;llooo' (length=30)

?>

I used this for a textarea content for comments. Anyway, note that using the "$res_2" form the function will leave unconverted single/double quotes. At this point you should use str_replace() function to perform the characters but be careful because..

<?php

$str = "'Hèèèllooo'";

$res_2 = str_replace("'","&#039;",$str);
$res_2 = htmlentities($str);
echo var_dump($res_2); // string '&amp;#039;H&egrave;&egrave;&egrave;llooo&amp;#039;'

$res_3 = htmlentities($str);
$res_3 = str_replace("'","&#039;",$res_3);
echo var_dump($res_3); // string '&#039;H&egrave;&egrave;&egrave;llooo&#039;' --> Nice
?>

Hope it will helps you.

Regards,
W.D.
steve at mcdragonsoftware dot com 16-Nov-2011 08:59
I'm glad 5.4 has xml support, but many of us are working with older installations, some of us still have to use PHP4. If you're like me you've been frustrated with trying to use htmlentites/htmlspecial chars with xml output. I was hoping to find an option to force numeric encoding, lacking that, I have written my own xmlencode function, which I now offer:

usage:

$string xmlencode( $string )

it will use htmlspecialchars for the valid xml entities amp, quote, lt, gt, (apos) and return the numeric entity for all other non alpha-numeric characters.

-------------------------------------------

<?php
if( !function_exists( 'xmlentities' ) ) {
    function xmlentities( $string ) {
        $not_in_list = "A-Z0-9a-z\s_-";
        return preg_replace_callback( "/[^{$not_in_list}]/" , 'get_xml_entity_at_index_0' , $string );
    }
    function get_xml_entity_at_index_0( $CHAR ) {
        if( !is_string( $CHAR[0] ) || ( strlen( $CHAR[0] ) > 1 ) ) {
            die( "function: 'get_xml_entity_at_index_0' requires data type: 'char' (single character). '{$CHAR[0]}' does not match this type." );
        }
        switch( $CHAR[0] ) {
            case "'":    case '"':    case '&':    case '<':    case '>':
                return htmlspecialchars( $CHAR[0], ENT_QUOTES );    break;
            default:
                return numeric_entity_4_char($CHAR[0]);                break;
        }
    }
    function numeric_entity_4_char( $char ) {
        return "&#".str_pad(ord($char), 3, '0', STR_PAD_LEFT).";";
    }
}
?>
Waygood 06-Jun-2011 02:09
When putting values inside comment tags <!-- --> you should replace -- with &#45;&#45; too, as this would end your tag and show the rest of the comment.
robin at robinwinslow dot co dot uk 15-Apr-2011 08:14
htmlentities seems to have changed at some point between version 5.1.6 and 5.3.3, such that it now returns an empty string for anything containing a pound sign:

$ php -v
PHP 5.1.6 (cli) (built: May 22 2008 09:08:44)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
&pound;hello
$

$ php -v
PHP 5.3.3 (cli) (built: Aug 19 2010 12:07:49)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
$

(Returns an empty string the second time)

Just a heads up.
markus at senoner dot com 15-Apr-2011 07:27
Pay attention, that htmlentities() does not recognise all Unicode-Symbols.  For example the bullet "•" (&bull; or &#8226;) will not be converted to a html-entity.
admin at wapforum dot rs 24-Feb-2011 01:11
A useful little function to convert the symbols in the different inputs.
<?php
function ConvertSimbols($var, $ConvertQuotes = 0) {
if ($ConvertQuotes > 0) {
$var = htmlentities($var, ENT_NOQUOTES, 'UTF-8');
$var = str_replace('\"', '', $var);
$var = str_replace("\'", '', $var);
} else {
$var = htmlentities($var, ENT_QUOTES, 'UTF-8');
}
return $var;
}
?>

Usage with quotes for example message:

$message = ConvertSimbols($message);

Usage without quotes for example link:

$link = ConvertSimbols($link, 1);
kindrosker at gmail dot com 10-Feb-2011 05:31
All Codes list

array('À'=>'&Agrave;', 'à'=>'&agrave;', 'Á'=>'&Aacute;', 'á'=>'&aacute;', 'Â'=>'&Acirc;', 'â'=>'&acirc;', 'Ã'=>'&Atilde;', 'ã'=>'&atilde;', 'Ä'=>'&Auml;', 'ä'=>'&auml;', 'Å'=>'&Aring;', 'å'=>'&aring;', 'Æ'=>'&AElig;', 'æ'=>'&aelig;', 'Ç'=>'&Ccedil;', 'ç'=>'&ccedil;', 'Ð'=>'&ETH;', 'ð'=>'&eth;', 'È'=>'&Egrave;', 'è'=>'&egrave;', 'É'=>'&Eacute;', 'é'=>'&eacute;', 'Ê'=>'&Ecirc;', 'ê'=>'&ecirc;', 'Ë'=>'&Euml;', 'ë'=>'&euml;', 'Ì'=>'&Igrave;', 'ì'=>'&igrave;', 'Í'=>'&Iacute;', 'í'=>'&iacute;', 'Î'=>'&Icirc;', 'î'=>'&icirc;', 'Ï'=>'&Iuml;', 'ï'=>'&iuml;', 'Ñ'=>'&Ntilde;', 'ñ'=>'&ntilde;', 'Ò'=>'&Ograve;', 'ò'=>'&ograve;', 'Ó'=>'&Oacute;', 'ó'=>'&oacute;', 'Ô'=>'&Ocirc;', 'ô'=>'&ocirc;', 'Õ'=>'&Otilde;', 'õ'=>'&otilde;', 'Ö'=>'&Ouml;', 'ö'=>'&ouml;', 'Ø'=>'&Oslash;', 'ø'=>'&oslash;', 'Œ'=>'&OElig;', 'œ'=>'&oelig;', 'ß'=>'&szlig;', 'Þ'=>'&THORN;', 'þ'=>'&thorn;', 'Ù'=>'&Ugrave;', 'ù'=>'&ugrave;', 'Ú'=>'&Uacute;', 'ú'=>'&uacute;', 'Û'=>'&Ucirc;', 'û'=>'&ucirc;', 'Ü'=>'&Uuml;', 'ü'=>'&uuml;', 'Ý'=>'&Yacute;', 'ý'=>'&yacute;', 'Ÿ'=>'&Yuml;', 'ÿ'=>'&yuml;');
galert420 at gmail dot com 05-Nov-2010 10:24
Croatian entites

<?php
$ent = array(
    'Ć'=>'&#262;',
    'ć'=>'&#263;',
    'Č'=>'&#268;',
    'č'=>'&#269;',
    'Đ'=>'&#272',
    'đ'=>'&#273',
    'Š'=>'&#352',
    'š'=>'&#353',
    'Ž'=>'&#381',
    'ž'=>'&#382'
);

echo strtr('ĆćČčĐđŠšŽž', $ent);
?>
php dot net at softmoon-webware dot com 12-Oct-2010 02:32
<?php
$HTML_ENTS=array("quot", "amp", "apos", "lt", "gt", "nbsp", "iexcl", "cent",
"pound","curren", "yen", "brvbar", "sect", "uml", "copy", "ordf", "laquo",
"not", "shy", "reg", "macr", "deg", "plusmn", "sup2", "sup3", "acute",
"micro", "para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14",
"frac12", "frac34", "iquest", "Agrave", "Aacute", "Acirc", "Atilde", "Auml",
"Aring", "AElig", "Ccedil", "Egrave", "Eacute", "Ecirc", "Euml", "Igrave",
"Iacute", "Icirc", "Iuml", "ETH", "Ntilde", "Ograve", "Oacute", "Ocirc",
"Otilde", "Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml",
"Yacute", "THORN", "szlig", "agrave", "aacute", "acirc", "atilde", "auml",
"aring", "aelig", "ccedil", "egrave", "eacute", "ecirc", "euml", "igrave",
"iacute", "icirc", "iuml", "eth", "ntilde", "ograve", "oacute", "ocirc",
"otilde", "ouml", "divide", "oslash", "ugrave", "uacute", "ucirc", "uuml",
"yacute", "thorn", "yuml", "OElig", "oelig", "Scaron", "scaron", "Yuml",
"fnof", "circ", "tilde", "Alpha", "Beta", "Gamma", "Delta", "Epsilon",
"Zeta", "Eta", "Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi",
"Omicron", "Pi", "Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi",
"Omega", "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta",
"theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi",
"rho", "sigmaf", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega",
"thetasym", "upsih", "piv", "ensp", "emsp", "thinsp", "zwnj", "zwj", "lrm",
"rlm", "ndash", "mdash", "lsquo", "rsquo", "sbquo", "ldquo", "rdquo",
"bdquo", "dagger", "Dagger", "bull", "hellip", "permil", "prime", "Prime",
"lsaquo", "rsaquo", "oline", "frasl", "euro", "image", "weierp", "real",
"trade", "alefsym", "larr", "uarr", "rarr", "darr", "harr", "crarr", "lArr",
"uArr", "rArr", "dArr", "hArr", "forall", "part", "exist", "empty", "nabla",
"isin", "notin", "ni", "prod", "sum", "minus", "lowast", "radic", "prop",
"infin", "ang", "and", "or", "cap", "cup", "int", "there4", "sim", "cong",
"asymp", "ne", "equiv", "le", "ge", "sub", "sup", "nsub", "sube", "supe",
"oplus", "otimes", "perp", "sdot", "lceil", "rceil", "lfloor",
"rfloor", "lang", "rang", "loz", "spades", "clubs", "hearts", "diams");

// The selection of tags below is optimized for use with a webmaster's database,
// --NOT-- to process user POSTs from the World Wide Web
//  for inclusion on a public page.

//  NOT included:
//   form,  input,  select,  option,  label,  optgroup,  textarea,  area,  map,
//   html,  head,  style,  link,  meta,  base,  body,  isindex,
//   frame,  frameset,  noframes
//  (include those above at your wish,  remove those below at your wish)
$HTML_TAGS=array("a", "abbr", "acronym", "address", "applet", "b", "basefont",
"bdo", "big", "blockquote", "br", "button", "caption", "center", "cite",
"code", "col", "colgroup", "dd", "del", "dfn", "dir", "div", "dl", "dt", "em",
"embed", "fieldset", "font", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i",
"iframe", "img", "ins", "kbd", "legend", "li", "menu", "noembed", "noscript",
"object", "ol", "p", "param", "pre", "q", "s", "samp", "script", "small",
"span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot",
"th", "thead", "title", "tr", "tt", "u", "ul", "var");

$Xchars = array(
 128 => '&#8364;',
 130 => '&#8218;',
 131 => '&#402;',
 132 => '&#8222;',
 133 => '&#8230;',
 134 => '&#8224;',
 135 => '&#8225;',
 136 => '&#710;',
 137 => '&#8240;',
 138 => '&#352;',
 139 => '&#8249;',
 140 => '&#338;',
 142 => '&#381;',
 145 => '&#8216;',
 146 => '&#8217;',
 147 => '&#8220;',
 148 => '&#8221;',
 149 => '&#8226;',
 150 => '&#8211;',
 151 => '&#8212;',
 152 => '&#732;',
 153 => '&#8482;',
 154 => '&#353;',
 155 => '&#8250;',
 156 => '&#339;',
 158 => '&#382;',
 159 => '&#376;');
?>
drallen at cs dot uwaterloo dot ca 29-Sep-2010 04:11
A pointer to http://www.php.net/manual/en/function.mb-convert-encoding.php if your intention is to translate *all* characters in a charset to their corresponding HTML entities, not just named characters. Non-named characters will be replaced with HTML numeric encoding. eg:

$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
h_guillaume at hotmail dot com 17-Sep-2010 01:14
I use this function to encode all the xml entities and also all the &something; that are not defined in xml like &trade;
You can also decode what you encode with my decode function.
My function works a little like the htmlentities.
You can also add other string to the array if you want to exclude them from the encoding.

<?php
function xml_entity_decode($text, $charset = 'Windows-1252'){
    // Double decode, so if the value was &amp;trade; it will become Trademark
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    return $text;
}

function xml_entities($text, $charset = 'Windows-1252'){
     // Debug and Test
    // $text = "test &amp; &trade; &amp;trade; abc &reg; &amp;reg; &#45;";

    // First we encode html characters that are also invalid in xml
    $text = htmlentities($text, ENT_COMPAT, $charset, false);

    // XML character entity array from Wiki
    // Note: &apos; is useless in UTF-8 or in UTF-16
    $arr_xml_special_char = array("&quot;","&amp;","&apos;","&lt;","&gt;");

    // Building the regex string to exclude all strings with xml special char
    $arr_xml_special_char_regex = "(?";
    foreach($arr_xml_special_char as $key => $value){
        $arr_xml_special_char_regex .= "(?!$value)";
    }
    $arr_xml_special_char_regex .= ")";

    // Scan the array for &something_not_xml; syntax
    $pattern = "/$arr_xml_special_char_regex&([a-zA-Z0-9]+;)/";

    // Replace the &something_not_xml; with &amp;something_not_xml;
    $replacement = '&amp;${1}';
    return preg_replace($pattern, $replacement, $text);
}
?>
Sijmen Ruwhof 13-Sep-2010 12:18
An important note below about using this function to secure your application against Cross Site Scripting (XSS) vulnerabilities.

When printing user input in an attribute of an HTML tag, the default configuration of htmlEntities() doesn't protect you against XSS, when using single quotes to define the border of the tag's attribute-value. XSS is then possible by injecting a single quote:

<?php
$_GET['a'] = "#000' onload='alert(document.cookie)";
?>

XSS possible (insecure):

<?php
$href = htmlEntities($_GET['a']);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000' onload='alert(document.cookie)'>
?>

Use the 'ENT_QUOTES' quote style option, to ensure no XSS is possible and your application is secure:

<?php
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000&#039; onload=&#039;alert(document.cookie)'>
?>

The 'ENT_QUOTES' option doesn't protect you against javascript evaluation in certain tag's attributes, like the 'href' attribute of the 'a' tag. When clicked on the link below, the given JavaScript will get executed:

<?php
$_GET['a'] = 'javascript:alert(document.cookie)';
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<a href='$href'>link</a>"; # results in: <a href='javascript:alert(document.cookie)'>link</a>
?>
Wired 13-May-2010 05:22
I needed a simple little function to take a string and convert extended ascii characters into html entities. I couldn't find a function for this so I whipped one up.

<?php
/* Convert Extended ASCII Characters to HTML Entities */
function ascii2entities($string){
    for($i=128;$i<=255;$i++){
        $entity = htmlentities(chr($i), ENT_QUOTES, 'cp1252');
        $temp = substr($entity, 0, 1);
        $temp .= substr($entity, -1, 1);
        if ($temp != '&;'){
            $string = str_replace(chr($i), '', $string);
        }
        else{
            $string = str_replace(chr($i), $entity, $string);
        }
    }
    return $string;
}

echo ascii2entities("•");
?>
phil at lavin dot me dot uk 08-Apr-2010 08:34
The following will make a string completely safe for XML:

<?php
function philsXMLClean($strin) {
        $strout = null;

        for ($i = 0; $i < strlen($strin); $i++) {
                $ord = ord($strin[$i]);

                if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
                        $strout .= "&amp;#{$ord};";
                }
                else {
                        switch ($strin[$i]) {
                                case '<':
                                        $strout .= '&lt;';
                                        break;
                                case '>':
                                        $strout .= '&gt;';
                                        break;
                                case '&':
                                        $strout .= '&amp;';
                                        break;
                                case '"':
                                        $strout .= '&quot;';
                                        break;
                                default:
                                        $strout .= $strin[$i];
                        }
                }
        }

        return $strout;
}
?>
silverbeat -eat- gmx -hot- at 09-Mar-2010 12:42
When using UTF-8 as a charset, htmlentities will only convert 1-byte and 2-byte characters. Use this function if you also want to convert 3-byte and 4-byte characters:

<?php

// converts a UTF8-string into HTML entities
//  - $utf8:        the UTF8-string to convert
//  - $encodeTags:  booloean. TRUE will convert "<" to "&lt;"
//  - return:       returns the converted HTML-string
function utf8tohtml($utf8, $encodeTags) {
    $result = '';
    for ($i = 0; $i < strlen($utf8); $i++) {
        $char = $utf8[$i];
        $ascii = ord($char);
        if ($ascii < 128) {
            // one-byte character
            $result .= ($encodeTags) ? htmlentities($char) : $char;
        } else if ($ascii < 192) {
            // non-utf8 character or not a start byte
        } else if ($ascii < 224) {
            // two-byte character
            $result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
            $i++;
        } else if ($ascii < 240) {
            // three-byte character
            $ascii1 = ord($utf8[$i+1]);
            $ascii2 = ord($utf8[$i+2]);
            $unicode = (15 & $ascii) * 4096 +
                       (63 & $ascii1) * 64 +
                       (63 & $ascii2);
            $result .= "&#$unicode;";
            $i += 2;
        } else if ($ascii < 248) {
            // four-byte character
            $ascii1 = ord($utf8[$i+1]);
            $ascii2 = ord($utf8[$i+2]);
            $ascii3 = ord($utf8[$i+3]);
            $unicode = (15 & $ascii) * 262144 +
                       (63 & $ascii1) * 4096 +
                       (63 & $ascii2) * 64 +
                       (63 & $ascii3);
            $result .= "&#$unicode;";
            $i += 3;
        }
    }
    return $result;
}

echo utf8tohtml($anyUTF8string, TRUE);

?>

regards, silverbeat
sirarthur at sirarthur dot info 05-Oct-2009 01:05
When happens that you want to encode special characters but not the HTML tags using this function you've two options:

a) Build your own function and go replace by character; eg.

<?php
  for($i = 0; $i < strlen($string); $i++){
     switch(substr($string,$i,1)){
        //..... A VERY HUGE switch here with all characters to encode.
    }
 }
?>

b) use this function and simple restore the html tags afterwards. Which gives you a 6 line function as follow:

<?php
  function keephtml($string){
          $res = htmlentities($string);
          $res = str_replace("&lt;","<",$res);
          $res = str_replace("&gt;",">",$res);
          $res = str_replace("&quot;",'"',$res);
          $res = str_replace("&amp;",'&',$res);
          return $res;
}
?>
montana 08-Jul-2009 09:54
under what circumstances would someone want a ntilde [ñ] to be converted into "Ã±" as htmlentities does?
the correct method of translation should return the accurate NCR for the multibyte unicode sequence
which in this case is &#241;

<?php

    //simple task: convert everything from utf-8 into an NCR[numeric character reference]
    class unicode_replace_entities {
        public function UTF8entities($content="") {
            $contents = $this->unicode_string_to_array($content);
            $swap = "";
            $iCount = count($contents);
            for ($o=0;$o<$iCount;$o++) {
                $contents[$o] = $this->unicode_entity_replace($contents[$o]);
                $swap .= $contents[$o];
            }
            return mb_convert_encoding($swap,"UTF-8"); //not really necessary, but why not.
        }

        public function unicode_string_to_array( $string ) { //adjwilli
            $strlen = mb_strlen($string);
            while ($strlen) {
                $array[] = mb_substr( $string, 0, 1, "UTF-8" );
                $string = mb_substr( $string, 1, $strlen, "UTF-8" );
                $strlen = mb_strlen( $string );
            }
            return $array;
        }

        public function unicode_entity_replace($c) { //m. perez
            $h = ord($c{0});
            if ($h <= 0x7F) {
                return $c;
            } else if ($h < 0xC2) {
                return $c;
            }

            if ($h <= 0xDF) {
                $h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            } else if ($h <= 0xEF) {
                $h = ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            } else if ($h <= 0xF4) {
                $h = ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            }
        }
    }//

    //utf-8 environment
    $content = "<strong>baño baño baño</strong>日本語 = nihongo da ze.<br />";

    $oUnicodeReplace = new unicode_replace_entities();
    $content = $oUnicodeReplace->UTF8entities($content);
    echo "<br />Result:<br />";
    echo $content;
    $source = htmlentities($content);
    echo "<br />htmlentities of resulting data:<br />";
    echo $source;

    echo "<br /><br />Note: Entities get replaced with 'literals' in textarea FF3<br /><br />";
    echo "<textarea style='width:300px;height:150px;'>";
    echo $content;
    echo "</textarea>";

    echo "<br /><br />For editing NCR's rather than 'literals' in a textarea<br /><br />";
    echo "<textarea style='width:300px;height:150px;'>";
    echo preg_replace("/(&#)+/","&amp;#",$content);
    echo "</textarea>";

?>
brianhamner at yahoo dot com 08-Jul-2009 09:26
If you want something simple that actually works, try this. Strips MS word and other entities and returns a clear data string:

<?php
//call this function

function DoHTMLEntities ($string) {
    $trans_tbl[chr(145)] = '&#8216;';
    $trans_tbl[chr(146)] = '&#8217;';
    $trans_tbl[chr(147)] = '&#8220;';
    $trans_tbl[chr(148)] = '&#8221;';
    $trans_tbl[chr(142)] = '&eacute;';
    $trans_tbl[chr(150)] = '&#8211;';
    $trans_tbl[chr(151)] = '&#8212;';
    return strtr ($string, $trans_tbl);
}

//insert your string variable here

        $foo = str_replace("\r\n\r\n","",htmlentities($your_string));
        $foo2 = str_replace("\r\n"," ",$foo);
        $foo3 = str_replace(" & ","&amp;",$foo2);
        echo DoHTMLEntities ($foo3);
?>
alonso05 at gmail dot com 30-Jun-2009 09:22
Hello, I found a great function when you need a way to encode content from the database as numeric entity references, as that’s a safe way to use high characters and special characters in an xml document, like in an RSS feed.

<?php
function xml_character_encode($string, $trans='') {
  $trans = (is_array($trans)) ? $trans : get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
  foreach ($trans as $k=>$v)
    $trans[$k]= "&#".ord($k).";";

  return strtr($string, $trans);
}
?>
mzvarik at gmail dot com 14-May-2009 05:03
CZECH entities:

<?php
$ent = array(
    'ě' => '&#283;',
    'Ě' => '&#282;',
    'š' => '&#353;',
    'Š' => '&#352;',
    'č' => '&#269;',
    'Č' => '&#268;',
    'ř' => '&#345;',
    'Ř' => '&#344;',
    'ž' => '&#382;',
    'Ž' => '&#381;',
    'ý' => '&#253;',
    'Ý' => '&#221;',
    'á' => '&#225;',
    'Á' => '&#193;',
    'í' => '&#237;',
    'Í' => '&#205;',
    'é' => '&#233;',
    'É' => '&#201;',
    'ú' => '&#250;',
    'ů' => '&#367;',
    'Ů' => '&#366;',
    'ď' => '&#271;',
    'Ď' => '&#270;',
    'ť' => '&#357;',
    'Ť' => '&#356;',
    'ň' => '&#328;',
    'Ň' => '&#327;'
);

echo strtr('ěščřžýáíéúůďťňĚŠČŘŽÝÁÍÉÚŮĎŤŇ', $ent);
?>
busbyjon at gmail dot com 07-Apr-2009 01:49
I took one of the previous functions above - (which only encodes the string once - which is great) and added the ability to encode & -> &amp;

See below.

Its a shame we cant do this straight with htmlentities (with double encode set to false)

<?php
function htmlButTags($str) {
        // Take all the html entities
        $caracteres = get_html_translation_table(HTML_ENTITIES);
        // Find out the "tags" entities
        $remover = get_html_translation_table(HTML_SPECIALCHARS);
        // Spit out the tags entities from the original table
        $caracteres = array_diff($caracteres, $remover);
        // Translate the string....
        $str = strtr($str, $caracteres);
        // And that's it!
        // oo now amps
        $str = preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , $str);

        return $str;
    }
?>
gunter [dot] sammet [at] gmail [dot] com 13-Jan-2009 10:48
Had a heck of a time to get my rss entities right. using htmlentities didn't work and using html_entity_decode didn't work either. Ended up writing a custom function to encode and decode. It might still need some work but I thought to share it because I couldn't find anything on the net. Always open for suggestions to improve it! Here it is:

<?php
  $entity_custom_from = false;
  $entity_custom_to = false;
  function html_entity_decode_encode_rss($data) {
    global $entity_custom_from, $entity_custom_to;
    if(!is_array($entity_custom_from) || !is_array($entity_custom_to)){
      $array_position = 0;
      foreach (get_html_translation_table(HTML_ENTITIES) as $key => $value) {
        //print("<br />key: $key, value: $value <br />\n");
        switch ($value) {
          // These ones we can skip
          case '&nbsp;':
            break;
          case '&gt;':
          case '&lt;':
          case '&quot;':
          case '&apos;':
          case '&amp;':
            $entity_custom_from[$array_position] = $key;
            $entity_custom_to[$array_position] = $value;
            $array_position++;
            break;
          default:
            $entity_custom_from[$array_position] = $value;
            $entity_custom_to[$array_position] = $key;
            $array_position++;
        }
      }
    }
    return str_replace($entity_custom_from, $entity_custom_to, $data);
  }
?>
Tom Walter 16-Oct-2008 07:14
Note that as of 5.2.5 it appears that if the input string contains a character that is not valid for the output encoding you've specified, then this function returns null.

You might expect it to just strip the invalid char, but it doesn't.

You can strip the chars yourself like so:

iconv('utf-8','utf-8',$str);

You can combine that with htmlentities also:

$str = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str, ENT_QUOTES, 'UTF-8');

Should give you a string with htmlentities encoded to utf-8, and any unsupported chars stripped.
Kenneth Kin Lum 22-Sep-2008 04:47
use htmlspecialchars() if you are passing in a usual ASCII string.  It is faster than htmlentities().

For example, if you are just doing

htmlentities('<div style="background: #fff"></div>');

then you can just use htmlspecialchars().  htmlentities() will look for all possible ways to convert string into html entities, such as &copy; or &eacute; (which is e with an acute accent on top).

Note that ASCII is just 7 bit, which is 0x00 to 0x7F.  htmlspecialchars() will handle characters inside this range already.  htmlentities() is for the 8-bit Latin-1 (ISO-8859-1) to handle European characters, or for UTF-8 when the 3rd argument is "UTF-8" to handle UTF-8 characters, or other types of encodings using different values for the 3rd argument passed into htmlentities().
snevi at im dot com dot ve 21-Jul-2008 06:10
correction to my previous post and improvement of the function: (the post was changed by the html parser and the characters displays as they should not)

<?php
    function XMLEntities($string)
    {
        $string = preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '_privateXMLEntities("$0")', $string);
        return $string;
    }

    function _privateXMLEntities($num)
    {
    $chars = array(
        128 => '&#8364;',
        130 => '&#8218;',
        131 => '&#402;',
        132 => '&#8222;',
        133 => '&#8230;',
        134 => '&#8224;',
        135 => '&#8225;',
        136 => '&#710;',
        137 => '&#8240;',
        138 => '&#352;',
        139 => '&#8249;',
        140 => '&#338;',
        142 => '&#381;',
        145 => '&#8216;',
        146 => '&#8217;',
        147 => '&#8220;',
        148 => '&#8221;',
        149 => '&#8226;',
        150 => '&#8211;',
        151 => '&#8212;',
        152 => '&#732;',
        153 => '&#8482;',
        154 => '&#353;',
        155 => '&#8250;',
        156 => '&#339;',
        158 => '&#382;',
        159 => '&#376;');
        $num = ord($num);
        return (($num > 127 && $num < 160) ? $chars[$num] : "&#".$num.";" );
    }
?>

in the previous post, to correct the HEX values that are not rendered, the program use a for each cicle, but that introduces a mayor complexity in execution time, so, we use the ability to call functions in the preg_replace second parameter, and ceate another funcion that evaluates the ord of the character given, and if it is between 127 and 160 it returns the modified HEX value to be understood by the browser and not brake the XML
(this work with dynamic XML generated form php with dynamic data from any source)

p.d: the '&'(&) should appear in this post as a single ampersand character and not as the html entity
keenskelly at gmail dot com 09-Jul-2008 10:00
Correction to my previous post: the set of ENTITY declarations must be inside a <!DOCTYPE element; also &nbsp; is NOT pre-defined in XML and must be left in the entity list. I also extended the list with the windows 1252 character set using a sample function borrowed from php.net user comments and extended with euro entity which we need for our app. Here is the final code that is in our production app:

<?php

// Generate a list of entity declarations from the HTML_ENTITIES set that PHP knows about to dump into the document
function htmlentities_entities() {
        $output = "<!DOCTYPE html [\n";
        foreach (get_html_translation_table_CP1252(HTML_ENTITIES) as $value) {
                $name = substr($value, 1, strlen($value) - 2);
                switch ($name) {
                        // These ones we can skip because they're built into XML
                        case 'gt':
                        case 'lt':
                        case 'quot':
                        case 'apos':
                        case 'amp': break;
                        default: $output .= "<!ENTITY {$name} \"&{$name};\">\n";
                }
        }
        $output .= "]>\n";
        return($output);
}

// ref: http://php.net/manual/en/function.get-html-translation-table.php#76564
function get_html_translation_table_CP1252($type) {
        $trans = get_html_translation_table($type);
        $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
        $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
        $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
        $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
        $trans[chr(134)] = '&dagger;';    // Dagger
        $trans[chr(135)] = '&Dagger;';    // Double Dagger
        $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
        $trans[chr(137)] = '&permil;';    // Per Mille Sign
        $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
        $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
        $trans[chr(140)] = '&OElig;';    // Latin Capital Ligature OE
        $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
        $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
        $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
        $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
        $trans[chr(149)] = '&bull;';    // Bullet
        $trans[chr(150)] = '&ndash;';    // En Dash
        $trans[chr(151)] = '&mdash;';    // Em Dash
        $trans[chr(152)] = '&tilde;';    // Small Tilde
        $trans[chr(153)] = '&trade;';    // Trade Mark Sign
        $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
        $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
        $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
        $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
        $trans['euro'] = '&euro;';    // euro currency symbol
        ksort($trans);
        return $trans;
}

?>

[EDIT BY danbrown AT php DOT net: The user's original note contained the following text:

"So here's something fun: if you create an XML document in PHP and use htmlentities() to encode text data, then later want to read and parse the same document with PHP's xml_parse(), unless you include entity declarations into the generated document, the parser will stop on the unknown entities.

To account for this, I created a small function to take the translation table and turn it into XML <!ENTITY> definitions. I insert this output into the XML document immediately after the <?xml?> line and the parse errors magically vanish"
]
mat at matinfo dot ch 21-Apr-2008 11:34
Hi,

below a method to convert UTF-8 Latin-1 characters to HTML-Entity,
I'm created this to translate string with HTML element on it and i just wont to convert entities.

<?php
function convertLatin1ToHtml($str) {
    $html_entities = array (
        "&" =>  "&amp;",     #ampersand
        "á" =>  "&aacute;",     #latin small letter a
        "Â" =>  "&Acirc;",     #latin capital letter A
        "â" =>  "&acirc;",     #latin small letter a
        "Æ" =>  "&AElig;",     #latin capital letter AE
        "æ" =>  "&aelig;",     #latin small letter ae
        "À" =>  "&Agrave;",     #latin capital letter A
        "à" =>  "&agrave;",     #latin small letter a
        "Å" =>  "&Aring;",     #latin capital letter A
        "å" =>  "&aring;",     #latin small letter a
        "Ã" =>  "&Atilde;",     #latin capital letter A
        "ã" =>  "&atilde;",     #latin small letter a
        "Ä" =>  "&Auml;",     #latin capital letter A
        "ä" =>  "&auml;",     #latin small letter a
        "Ç" =>  "&Ccedil;",     #latin capital letter C
        "ç" =>  "&ccedil;",     #latin small letter c
        "É" =>  "&Eacute;",     #latin capital letter E
        "é" =>  "&eacute;",     #latin small letter e
        "Ê" =>  "&Ecirc;",     #latin capital letter E
        "ê" =>  "&ecirc;",     #latin small letter e
        "È" =>  "&Egrave;",     #latin capital letter E
/*... sorry cutting because limitation of php.net ...
... but the principle is it ;) ... */
        "û" =>  "&ucirc;",     #latin small letter u
        "Ù" =>  "&Ugrave;",     #latin capital letter U
        "ù" =>  "&ugrave;",     #latin small letter u
        "Ü" =>  "&Uuml;",     #latin capital letter U
        "ü" =>  "&uuml;",     #latin small letter u
        "Ý" =>  "&Yacute;",     #latin capital letter Y
        "ý" =>  "&yacute;",     #latin small letter y
        "ÿ" =>  "&yuml;",     #latin small letter y
        "Ÿ" =>  "&Yuml;",     #latin capital letter Y
    );

    foreach ($html_entities as $key => $value) {
        $str = str_replace($key, $value, $str);
    }
    return $str;
}
?>
za at byza dot it 15-Apr-2008 09:15
Trouble when using files with different charset?

htmlentities and html_entity_decode can be used to translate between charset!

Sample function:

<?php
function utf2latin($text) {
   $text=htmlentities($text,ENT_COMPAT,'UTF-8');
   return html_entity_decode($text,ENT_COMPAT,'ISO-8859-1');
}
?>
TKVLPUAIBSDB at spammotel dot com 14-Nov-2007 04:11
Yet another "help paste from MS Word" function. Characters from ISO-8859-1 charset are left in peace, while entities are built for non-standard characters from Windows CP1252.

<?php
function win1252toIso( $string ) {
    // These chars seem to be not contained
    // in php's CP1252 translation table
    static $extensions = array(
        142 => "&Zcaron;",
        158 => "&zcaron;"
    );
    // Go through string and decide char by char:
    // "leave as is or build entity?"
    $newStr = "";
    for( $i=0; $i < strlen( $string ); $i++ ) {
        $ord = ord( $string[$i] );
        if ( in_array( $ord, array_keys( $extensions ) ) ) {
            // build entity using extra translation table
            $newStr .= $extensions[$ord];
        }
        else {
            // build entity using php's translation table
            // or leave as is
            $newStr .= ( $ord > 127 && $ord < 160 ) ?
                htmlentities( $string[$i], ENT_NOQUOTES, "CP1252" )
                : $string[$i];
        }
    }
    return $newStr;
}
?>
marktpitman at gmail dot com 15-Oct-2007 07:21
I just thought I would add that if you're using the default charset, htmlentities will not correctly return the trademark ( ™ ) sign.

Instead it will return something like this: â�¢

If you need the trademark symbol, use:

<?php htmlentities( $html, ENT_QUOTES, "UTF-8" ); ?>
D. Gasser 24-Apr-2007 10:40
When using UTF-8 as charset, you'll have to set UTF-8 in braces, otherwise the varaible is not recognized.
q (dot) rendeiro (at) gmail (dot) com 07-Mar-2007 04:41
I've seen lots of functions to convert all the entities, but I needed to do a fulltext search in a db field that had named entities instead of numeric entities (edited by tinymce), so I searched the tinymce source and found a string with the value->entity mapping. So, i wrote the following function to encode the user's query with named entities.

The string I used is different of the original, because i didn't want to convert ' or ". The string is too long, so I had to cut it. To get the original check TinyMCE source and search for nbsp or other entity ;)

<?php

$entities_unmatched = explode(',', '160,nbsp,161,iexcl,162,cent, [...] ');
$even = 1;
foreach($entities_unmatched as $c) {
    if($even) {
        $ord = $c;
    } else {
        $entities_table[$ord] = $c;
    }
    $even = 1 - $even;
}

function encode_named_entities($str) {
    global $entities_table;

    $encoded_str = '';
    for($i = 0; $i < strlen($str); $i++) {
        $ent = @$entities_table[ord($str{$i})];
        if($ent) {
            $encoded_str .= "&$ent;";
        } else {
            $encoded_str .= $str{$i};
        }
    }
    return $encoded_str;
}

?>
realcj at g mail dt com 06-Nov-2006 10:41
If you are building a loadvars page for Flash and have problems with special chars such as " & ", " ' " etc, you should escape them for flash:

Try trace(escape("&")); in flash' actionscript to see the escape code for &;

% = %25
& = %26
' = %27

<?php
function flashentities($string){
return str_replace(array("&","'"),array("%26","%27"),$string);
}
?>

Those are the two that concerned me. YMMV.
eric.wallet at yahoo.fr 26-Sep-2006 04:57
First method convert characters to decimal values.
Second will reverse the problem !!!

<?php
function htmlnumericentities($str){
  return preg_replace('/[^!-%\x27-;=?-~ ]/e', '"&#".ord("$0").chr(59)', $str);
}

function numericentitieshtml($str){
  return utf8_encode(preg_replace('/&#(\d+);/e', 'chr(str_replace(";","",str_replace("&#","","$0")))', $str));
}

echo (htmlnumericentities ("Ceci est un test : & é $ à ç <"));
echo ("<br/>\n");
echo (numericentitieshtml (htmlnumericentities ("Ceci est un test : & é $ à ç <")));
?>

Output is :
Ceci est un test : &#38; &#233; $ &#224; &#231; &#60;<br/>
Ceci est un test : & é $ à ç <
daviscabral[arroba]gmail[ponto]com 28-Jul-2006 12:52
unhtmlentities for all entities:

<?php

function unhtmlentities ($string) {
   $trans_tbl1 = get_html_translation_table (HTML_ENTITIES);
   foreach ( $trans_tbl1 as $ascii => $htmlentitie ) {
        $trans_tbl2[$ascii] = '&#'.ord($ascii).';';
   }
   $trans_tbl1 = array_flip ($trans_tbl1);
   $trans_tbl2 = array_flip ($trans_tbl2);
   return strtr (strtr ($string, $trans_tbl1), $trans_tbl2);
}

?>
info at pirandot dot de 22-Jul-2006 07:14
The data returned by a text input field is ready to be used in a data base query when enclosed in single quotes, e.g.
<?php
   mysql_query ("SELECT * FROM Article WHERE id = '$data'");
?>
But you will get problems when writing back this data into the input field's value,
<?php
   echo "<input name='data' type='text' value='$data'>";
?>
because hmtl codes would be interpreted and escape sequences would cause strange output.

The following function may help:
<?php
function deescape ($s, $charset='UTF-8')
{
   //  don't interpret html codes and don't convert quotes
   $s  =  htmlentities ($s, ENT_NOQUOTES, $charset);

   //  delete the inserted backslashes except those for protecting single quotes
   $s  =  preg_replace ("/\\\\([^'])/e", '"&#" . ord("$1") . ";"', $s);

   //  delete the backslashes inserted for protecting single quotes
   $s  =  str_replace ("\\'", "&#" . ord ("'") . ";", $s);

   return  $s;
}
?>
Try some input like:  a'b"c\d\'e\"f\\g&x#27;h  to test ...
anonymous 26-Apr-2006 12:38
This function will encode anything that is non Standard ASCII (that is, that is above #127 in the ascii table)

<?php
// allhtmlentities : mainly based on "chars_encode()"  by Tim Burgan <timburgan@gmail.com> [http://www.php.net/htmlentities]
function allhtmlentities($string) {
    if ( strlen($string) == 0 )
        return $string;
    $result = '';
    $string = htmlentities($string, HTML_ENTITIES);
    $string = preg_split("//", $string, -1, PREG_SPLIT_NO_EMPTY);
    $ord = 0;
    for ( $i = 0; $i < count($string); $i++ ) {
        $ord = ord($string[$i]);
        if ( $ord > 127 ) {
            $string[$i] = '&#' . $ord . ';';
        }
    }
    return implode('',$string);
}
?>
edo at edwaa dot com 17-Nov-2005 08:48
A version of the xml entities function below. This one replaces the "prime" character (′) with which I had difficulties.

<?php
// XML Entity Mandatory Escape Characters
function xmlentities($string) {
   return str_replace ( array ( '&', '"', "'", '<', '>', '�' ), array ( '&amp;' , '&quot;', '&apos;' , '&lt;' , '&gt;', '&apos;' ), $string );
}
?>
info at bleed dot ws 14-Oct-2005 10:42
here the centralized version of htmlentities() for multibyte.

<?php
function mb_htmlentities($string)
{
    $string = htmlentities($string, ENT_COMPAT, mb_internal_encoding());
    return $string;
}

?>
fanfatal at fanfatal dot pl 28-Aug-2005 02:28
I wrote usefull function which is support iso-8859-2 encoding with htmlentities function ;]

<?php
/*
 *    Function htmlentities which support iso-8859-2
 *
 *    @param string
 *    @return string
 *    @author FanFataL
 */
function htmlentities_iso88592($string='') {
    $pl_iso = array('&ecirc;', '&oacute;', '&plusmn;', '&para;', '&sup3;', '&iquest;', '&frac14;', '&aelig;', '&ntilde;', '&Ecirc;', '&Oacute;', '&iexcl;', '&brvbar;', '&pound;', '&not;', '&macr;', '&AElig;', '&Ntilde;');
    $entitles = get_html_translation_table(HTML_ENTITIES);
    $entitles = array_diff($entitles, $pl_iso);
    return strtr($string, $entitles);
}
?>

Greatings ;-)
...
send at mail dot 2aj dot net 14-Jul-2005 10:03
If you are programming XML documents and are using the htmlentities function, then performing a  str_replace on ' into &apos; to set mandatory escape characters you can use this simple function instead.

This function, xmlentities, is basically the XML parsing equivalent of htmlentities, with fewer options than its HTML counterpart:

<?php
// XML Entity Mandatory Escape Characters
function xmlentities ( $string )
{
    return str_replace ( array ( '&', '"', "'", '<', '>' ), array ( '&amp;' , '&quot;', '&apos;' , '&lt;' , '&gt;' ), $string );
}
?>

Example:

<?php
function xmlentities($string)
{
    return str_replace ( array ( '&', '"', "'", '<', '>' ), array ( '&amp;' , '&quot;', '&apos;' , '&lt;' , '&gt;' ), $string );
}

echo xmlentities("If you don't use these mandatory escape characters <tags> between </tags>, XML will \"eXtensively\" & \"implicitly\" give you errors.");
?>

Produces...
If you don&apos;t use these mandatory escape characters &lt;tags&gt; between &lt;/tags&gt;, XML will &quot;eXtensively&quot; &amp; &quot;implicitly&quot; give you errors.
marques at displague dot com 24-Jan-2005 10:01
htmlEncodeText (below) needs a small tweak, the dash needs to be made literal to get picked up in cases like '<a href="blah-blah.php">'.  I have been using this function to parse my postgresql database calls since I have alot of unicode data and I don't want HTML data to be neutered (via htmlentities()).

<?php
function htmlEncodeText ($string)
{
  $pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]@]+)>';
  preg_match_all ('/' . $pattern . '/', $string, $tagMatches, PREG_SET_ORDER);
  $textMatches = preg_split ('/' . $pattern . '/', $string);

  foreach ($textMatches as $key => $value) {
   $textMatches [$key] = htmlentities ($value);
  }

  for ($i = 0; $i < count ($textMatches); $i ++) {
   $textMatches [$i] = $textMatches [$i] . $tagMatches [$i] [0];
  }

  return implode ($textMatches);
}
?>

--Editor note: Combined some corrections to the regex pattern, thanks to fabian dot lange at web dot de, hammertscrew at veryweb dot com, webmaster AT scholesmafia DOT co DOT uk, thomas AT cosifan DOT de and marques at displague dot com---
Miguel (miguel at sigmanet dot com dot br) 20-Oct-2004 08:43
This is a simple script that I'm using to encode and decode values from a form. Save it with the name that you wish.

<?php

/*  When you call anyone of the two functions, set the $_str
     variable to the string that you want to encode or decode */

/* This function encodes the string.
    You can safetly use this function to save its result in a
    database. It eliminates any space in the beginning ou end
    of the string, HTML and PHP tags, and encode any special
    char to the usual HTML entities (&[...];), eliminating the
    possibility of bugs in inserting data on a table */
function encodeText($_str) {
  $_str = strip_tags($_str);
  $_str = trim($_str);
  $_str = htmlentities($_str);
  $_str = str_replace("\r\n", "#BR#", $_str);
  return($_str);
}

/* This function decodes the string.
    If you are showing the string in the body of a page, you
    can set the $_form variable to "false", and the function will
    use the "BR" tag to the new lines. But, if you need to show
    the string in a textarea, text or other input types of a form
    set the $_form variable to "true", then the function will use
    the "\r\n" to the new lines */
function decodeText($_str, $_form) {
  $trans_tbl = get_html_translation_table (HTML_ENTITIES);
  $trans_tbl = array_flip ($trans_tbl);
  $_str      = strtr($_str, $trans_tbl);
  if ($_form) {
    $_nl = "\r\n";
  } else {
    $_nl = "<br>";
  }
  $_str      = str_replace("#BR#", "$_nl", $_str);
  return($_str);
}

?>
m227 at poczta dot onet dot pl 26-May-2004 03:00
<?php
// tested with PHP 4.3.4, Apache 1.29
// function works like original htmlentities
// but preserves Polish characters encoded in CP-1250
// (Windows code page) from false conversion

// m227@poczta.onet.pl, 2004

function htmlentities1250($str)
{
    // four chars does not need any conversion
    // s` (9c), z` (9f), Z` (8f), S` (8c)
    $trans = array(
        "&sup3;"  => "\xb3", //  "l-"
        "&sup1;"  => "\xb9", //  "a,"
        "&ecirc;" => "\xea", //  "e,"
        "&aelig;" => "\xe6", //  "c`"
        "&ntilde;"=> "\xf1", //  "n`"
        "&iquest;"=> "\xbf", //  "z."
        "&yen;"   => "\xa5", //  "A,"
        "&AElig;" => "\xc6", //  "C`"
        "&macr;"  => "\xaf", //  "Z."
        "&Ecirc;" => "\xca", //  "E,"
        "&oacute;"=> "\xf3", //  "o`"
        "&Oacute;"=> "\xd3", //  "O`"
        "&pound;" => "\xa3", //  "L-"
        "&Ntilde;"=> "\xd1"  //  "N`"
    );
    return strtr(htmlentities($str), $trans);
}
?>
mail at britlinks dot com 19-May-2004 09:27
similar to cedric at shift-zone dot be's function, this 'cleans up' text from MS Word, and other non-alphanumeric characters to their valid [X]HTML counterparts

<?php
// strips slashes, and converts special characters to HTML equivalents for string defined in $var
function htmlfriendly($var,$nl2br = false){
    $chars = array(
        128 => '&#8364;',
        130 => '&#8218;',
        131 => '&#402;',
        132 => '&#8222;',
        133 => '&#8230;',
        134 => '&#8224;',
        135 => '&#8225;',
        136 => '&#710;',
        137 => '&#8240;',
        138 => '&#352;',
        139 => '&#8249;',
        140 => '&#338;',
        142 => '&#381;',
        145 => '&#8216;',
        146 => '&#8217;',
        147 => '&#8220;',
        148 => '&#8221;',
        149 => '&#8226;',
        150 => '&#8211;',
        151 => '&#8212;',
        152 => '&#732;',
        153 => '&#8482;',
        154 => '&#353;',
        155 => '&#8250;',
        156 => '&#339;',
        158 => '&#382;',
        159 => '&#376;');
    $var = str_replace(array_map('chr', array_keys($chars)), $chars, htmlentities(stripslashes($var)));
    if($nl2br){
        return nl2br($var);
    } else {
        return $var;
    }
}
?>
cedric at shift-zone dot be 04-May-2004 06:02
This is a conversion function for special chars.
Very usefull to convert a word document into valid html
(the html provided is successfully parsed by sablotron 0.97 using iso-8859-1 charset) :

<?php
function convertDoc2HTML($txt){
        $len = strlen($txt);
        $res = "";
        for($i = 0; $i < $len; ++$i) {
            $ord = ord($txt{$i});
            // check only non-standard chars
            if($ord >= 126){
                $res .= "&#".$ord.";";
            }
            else {
                // escape ", ' and \ chars
                switch($ord){
                    case 34 :
                        $res .= "\\\"";
                        break;
                    case 39 :
                        $res .= "\'";
                        break;
                    case 92 :
                        $res .= "\\\\";
                        break;
                    default : // the rest does not have to be modified
                        $res .= $txt{$i};
                }
            }
        }
        return $res;
}
?>
jake_mcmahon at hotmail dot com 29-Apr-2004 02:29
This fuction is particularly useful against XSS (cross-site-scripting-). XSS makes use of holes in code, whether it be in Javascript or PHP. XSS often, if not always, uses HTML entities to do its evil deeds, so this function in co-operation with your scripts (particularly search or submitting scripts) is a very useful tool in combatting "H4X0rz".
Guillaume Beaulieu 11-Apr-2004 02:10
Here's a simple script to transform filename with accented character in it into much more usable unaccented character for a restrictive filesystem.

<?php
$string = htmlentities($stringToModify);
/* Take the first letter of the entity (if you got filename with ([<>] in it the result will probably remain lookable*/
$string =  preg_replace("/\&(.)[^;]*;/", "\\1", $string);
/* Change the whitespace into _*/
$string = preg_replace("/[ ]/", "_", $string);
/* Dance ! */
print $string;
?>
Funky Ants 03-Apr-2004 11:55
I had a problem working with partially html encoded data, with a selection of unescaped ampersands, hex coded, and characters in "&amp;", style.
Which ive finally overcome by decoding all of the data, adn then reincoding it all.

I found a combination of a couple of peoples work useful.

<?php
function get_htmlspecialchars( $given, $quote_style = ENT_QUOTES ){
    return htmlentities( unhtmlentities(  $given ) , $quote_style  );
}

function unhtmlentities( $string ){
    $trans_tbl = get_html_translation_table ( HTML_ENTITIES );
    $trans_tbl = array_flip( $trans_tbl );
    $ret = strtr( $string, $trans_tbl );
    return preg_replace( '/&#(\d+);/me' , "chr('\\1')" , $ret );
}
?>
wwb at 3dwargamer dot net 31-Mar-2004 04:49
htmlentites is a very handy function, but it fails to fix one thing which I deal with alot: word 'smart' quotes and emdashes.

The below function replaces the funky double quotes with &quot;, funky single quotes with standard single quotes and fixes emdashes.

<?php
    function CleanupSmartQuotes($text)
    {
        $badwordchars=array(
                            chr(145),
                            chr(146),
                            chr(147),
                            chr(148),
                            chr(151)
                            );
        $fixedwordchars=array(
                            "'",
                            "'",
                            '&quot;',
                            '&quot;',
                            '&mdash;'
                            );
        return str_replace($badwordchars,$fixedwordchars,$text);
    }
?>
Julien CROUZET 27-Nov-2003 12:01
If you are looking for a htmlentities inverse :

<?php
$table        = array_flip(get_html_translation_table(HTML_ENTITIES));
$plaintext    = strtr($html, $table);
?>

Here is a full example to extract plaintext from a SIMPLE html page (not table, etc...)

<?php
$file_content     = file_get_contents($htmlfile);
$file_content     = strip_tags($file_content, '<br>');
$file_content     = preg_replace('/<br( )?(\/)?>/i', "\n", $file_content);
$file_content     = wordwrap($file_content);
$table            = array_flip(get_html_translation_table(HTML_ENTITIES));
$file_content     = strtr($file_content, $table);
?>
dmurphy at telegeography dot com 19-Sep-2003 11:14
<?php
// htmlentities() does not support Mac Roman, so this is a workaround. It requires the below table.
// This function runs on a Mac OSX machine, where text is stored in the Mac Roman character set inside a Mac OSX MySQL table.
function custom_htmlentities ($string, $table) {
    // Loop throught the array, replacing each ocurrance
    for ($n = 0; $n < count($table); $n++) {
        $table_line = each($table);
        // use the chr function to get the one character string for each ascii decimal code
        $find_char = chr($table_line[key]);
        $replace_string = $table_line[value];
        $string = str_replace($find_char, $replace_string, $string);
    }
    return $string;
}
?>
defrostdj at defrostdj dot com 25-Jul-2003 12:10
Here you have a character map function ;)

<?php
function htmldecode($encoded, $char = 'HTML_SPECIALCHARS') {
    foreach($encoded as $key => $value){
        echo $value .' --> ';
        if ($char == 'HTML_SPECIALCHARS') {
            echo htmlspecialchars($value);
        } else {
            echo htmlentities($value);
        }
        echo '&gtbr&lt';
    }
}
echo 'ENTITIES<&gtbr&lt><&gtbr&lt>';
$entities = get_html_translation_table (HTML_ENTITIES);
htmldecode($entities, 'HTML_ENTITIES');
echo '<&gtbr&lt>SPECIAL CHARACTERS<&gtbr&lt><&gtbr&lt>';
$specialchars = get_html_translation_table (HTML_SPECIALCHARS);
htmldecode($specialchars, 'HTML_SPECIALCHARS');

?>

So next time you're developing you'll always have a charmap ready to use.
Anthony Aragues 24-Jun-2003 04:24
I found in a previous not the function for encoding the input... which worked great, but it also encoded the &nbsp and <br> that was being automatically added in my POST, so I created and Output function to go with it that worked for me:

<?php
function VerbatimInput($String)
    {
    $Output = mysql_escape_string(htmlentities(addslashes($String)));
    return $Output;
    }

function VerbatimOutput($Input)
    {
    $Output = str_replace("&lt;br /&gt;", "<br>", "$Input");
        $Output = str_replace("&amp;nbsp;", "&nbsp", "$Output");
    return $Output;
    }
?>
rob at neorosa dot com 28-Feb-2003 08:12
This function will encode everything, either using ascii values or special entities:

<?php
function encode_everything($string){
    $encoded = "";
    for ($n=0;$n<strlen($string);$n++){
        $check = htmlentities($string[$n],ENT_QUOTES);
       $string[$n] == $check ? $encoded .= "&#".ord($string[$n]).";" : $encoded .= $check;
    }
    return $encoded;
}
?>

so you can use:

<?php $emailAddress = encode_everything($emailAddress); ?>

to protect an email address - although I imagine it's not a great deal of protection.
Bassie (: 05-Jan-2003 04:07
Note that you'll have use htmlentities() before any other function who'll edit text like nl2br().

If you use nl2br() first, the htmlentities() function will change < br > to &lt;br&gt;.
html_entity_decode
htmlspecialchars_decode
Обработка строк


Преобразует специальные HTML-сущности обратно в соответствующие символы

htmlentities
htmlspecialchars
Обработка строк
PHP Manual

htmlspecialchars_decode

(PHP 5 >= 5.1.0)

htmlspecialchars_decode — Преобразует специальные HTML-сущности обратно в соответствующие символы

Описание

string htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ] )

Эта функция является антиподом htmlspecialchars(). Она преобразует специальные HTML-сущности обратно в соответствующие символы.

Конвертируемые сущности : &amp;, &quot; (когда ENT_NOQUOTES не установлена), &#039; (когда ENT_QUOTES установлена), &lt; и &gt;.

Список параметров

string

Строка, которую надо преобразовать.

flags

Битовая маска из одного или нескольких следующих флагов, которые указывают как обрабатывать кавычки и какие типы документов использовать. Значением по умолчанию является ENT_COMPAT | ENT_HTML401.

Доступные константы, используемые в качестве параметра flags
Имя константы | Описание
ENT_COMPAT | Преобразует двойные кавычки и пропускает одинарные.
ENT_QUOTES | Преобразует и двойные, и одинарные кавычки.
ENT_NOQUOTES | Не преобразует ни двойные, ни одинарные кавычки.
ENT_HTML401 | Обрабатывать код как HTML 4.01.
ENT_XML1 | Обрабатывать код как XML 1.
ENT_XHTML | Обрабатывать код как XHTML.
ENT_HTML5 | Обрабатывать код как HTML 5.

Возвращаемые значения

Возвращает преобразованную строку.

Список изменений

Версия | Описание
5.4.0 | Добавлены константы ENT_HTML401, ENT_XML1, ENT_XHTML и ENT_HTML5.

Примеры

Пример #1 Пример использования функции htmlspecialchars_decode()

<?php
$str = "<p>this -&gt; &quot;</p>\n";

echo htmlspecialchars_decode($str);

// обратите внимание, что в данном случае кавычки не будут преобразованы
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>

Результат выполнения данного примера:

<p>this -> "</p>
<p>this -> &quot;</p>

Смотрите также

  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • html_entity_decode() - Преобразует все HTML-сущности в соответствующие символы
  • get_html_translation_table() - Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities

User Contributed Notes

selimx at live dot com 20-Apr-2011 02:35
this function

<?php
function htmlkarakter($string)
{
   $string = str_replace(array("&lt;", "&gt;", '&amp;', '&#039;', '&quot;','&lt;', '&gt;'), array("<", ">",'&','\'','"','<','>'), htmlspecialchars_decode($string, ENT_NOQUOTES));

       return $string;

}
?>

Before
<description>&lt;div class=&quot;google-ad1&quot;&gt;
  &lt;script type=&#039;text/javascript&#039;&gt;
    GA_googleFillSlot(&quot;EW_News_300x250&quot;);
  &lt;/script&gt;

&lt;/div&gt;

after using the function

<div class="google-ad1">
  <script type='text/javascript'>
    GA_googleFillSlot("EW_News_300x250");
  </script>
pinkgothic at gmail dot com 10-Jun-2010 09:24
Keep in mind that you should never trust user input - particularly for "mixed-bag" input containing a combination of plain text and markup or scripting code.

Why?

Well, consider someone sending '&amp;<script>alert('XSS');</script>' to your PHP script:

<?php
$var = "&amp;<script>alert('XSS');</script>";
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var;
?>

Since '&amp;' decodes into '&', (htmlspecialchars_decode($var) == $var) will be -false-, thus returning $var without that it's escaped. In consequence, the script-tags are untouched, and you've just opened yourself to XSS.

There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case 'I've already encoded this', you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure.
benharold at mac dot com 26-Jan-2009 04:48
or of course:

<?php

$var = "Blue & yellow make green.";

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // outputs Blue &amp; yellow make green.

// you can do it a bunch of times, it still won't screw you!

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // still outputs Blue &amp; yellow make green.

?>

Put it in a function. Add it to the method of some abstract data class.
benharold at mac dot com 26-Jan-2009 01:30
If you use `htmlspecialchars()` to change things like the ampersand (&) into it's HTML equivalent (&amp;), you might run into a situation where you mistakenly pass the same string to the function twice, resulting in things appearing on your website like, as I call it, the ampersanded amp; "&amp;". Clearly nobody want's "&amp;" on his or her web page where there is supposed to be just an ampersand. Here's a quick and easy trick to make sure this doesn't happen:

<?php

$var = "This is a string that could be passed to htmlspecialchars multiple times.";

if (htmlspecialchars_decode($var) == $var) {
    $var = htmlspecialchars($var);
}

echo $var;

?>

Now, if your dealing with text that is a mixed bag (has HTML entities and non-HTML entities) you're on your own.
thomas at xci[ignore_this]teit dot commm 28-Mar-2008 03:03
The example for "htmlspecialchars_decode()" below sadly does not work for all PHP4 versions.

Quote from the PHP manual:
"get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities()."

But it does NOT! At least not for PHP version 4.4.2.
This was already reported in a bug report (http://bugs.php.net/bug.php?id=25927), but it was marked as BOGUS.

Proof:
  Code:
--------------------
<?php
    var_dump(get_html_translation_table(HTML_SPECIALCHARS,ENT_QUOTES));
    var_dump(htmlspecialchars('\'',ENT_QUOTES));
?>
--------------------

  Output:
--------------------
array
  '"' => '&quot;'
  ''' => '&#39;'
  '<' => '&lt;'
  '>' => '&gt;'
  '&' => '&amp;'

'&#039;'
--------------------

This comment now is not to report this bug again (though I really believe it is one), but to complete the example and warn people of this pitfall.

To make sure your htmlspecialchars_decode fake for PHP4 works, you should do something like this:

<?php
    function htmlspecialchars_decode($string,$style=ENT_COMPAT)
    {
        $translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS,$style));
        if($style === ENT_QUOTES){ $translation['&#039;'] = '\''; }
        return strtr($string,$translation);
    }
?>

Br, Thomas
Wout 28-Jul-2007 09:06
The following replacement for PHP 4 is a little more complete, as the quote_style is taken into account as well:

if (!function_exists("htmlspecialchars_decode")) {
    function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT) {
        return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
    }
}
17-Aug-2006 05:49
This should be the best way to do it.
(Reposted because the other one seems a bit slower and because those who used the code under called it htmlspecialchars_decode_php4)

<?php

if ( !function_exists('htmlspecialchars_decode') )
{
    function htmlspecialchars_decode($text)
    {
        return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
    }
}

?>
TheSin 09-May-2006 02:51
Here is how you can get this function in php < 5.1, just make sure this function is before you try and call the function.

if (!function_exists('htmlspecialchars_decode')) {
        function htmlspecialchars_decode($str, $options="") {
                $trans = get_html_translation_table(HTML_SPECIALCHARS, $options);

                $decode = ARRAY();
                foreach ($trans AS $char=>$entity) {
                        $decode[$entity] = $char;
                }

                $str = strtr($str, $decode);

                return $str;
        }
}
se at designlinks dot net 14-Dec-2005 08:43
The code supplied by or-k at or-k dot com (14-Sep-2005 09:15) is better served using html_entity_decode() for PHP>=4.3.0.
geoffers@gmail (14-Jul-2005 01:38) offers the best htmlspecialchars_decode() for php4 users.
or-k at or-k dot com 14-Sep-2005 02:15
that works also with &auml; and &quot; and so on.
get_html_translation_table(HTML_ENTITIES) => offers more characters than HTML_SPECIALCHARS

function htmlspecialchars_decode_PHP4($uSTR)
{
 return strtr($uSTR, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
}
geoffers@gmail 14-Jul-2005 06:38
[Update of previous note, having noticed I forgot to put in quote style]

PHP4 Compatible function:

<?php

function htmlspecialchars_decode_php4 ($str, $quote_style = ENT_COMPAT) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}

?>
geoffers at gmail dot com 14-Jul-2005 06:30
For PHP4 Compatibility:

<?php

function htmlspecialchars_decode_php4 ($str) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
}

?>
htmlentities
htmlspecialchars
Обработка строк


Преобразует специальные символы в HTML-сущности

htmlspecialchars_decode
implode
Обработка строк
PHP Manual

htmlspecialchars

(PHP 4, PHP 5)

htmlspecialchars — Преобразует специальные символы в HTML-сущности

Описание

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = 'UTF-8' [, bool $double_encode = true ]]] )

В HTML некоторые символы имеют специальное значение и для сохранения своего значения должны быть преобразованы в HTML-сущности. Эта функция возвращает строку, над которой проведены эти преобразования. Если вам нужно преобразовать все возможные сущности, используйте htmlentities().

Вызова функции htmlspecialchars() достаточно, если кодировка поддерживает все символы во входной строке (такая как UTF-8, но также ISO-8859-1 при входной только ISO-8859-1). Необходимость в вызове функции htmlentities() появляется только тогда, когда выходная кодировка не поддерживает все символы из входной строки.

Эта функция полезна при отображении данных, введенных пользователем, которые могут содержать нежелательные HTML тэги, например в форуме или гостевой книге.

Производятся следующие преобразования:

  • '&' (амперсанд) преобразуется в '&amp;'
  • '"' (двойная кавычка) преобразуется в '&quot;' в режиме ENT_NOQUOTES is not set.
  • "'" (одиночная кавычка) преобразуется в '&#039;' только в режиме ENT_QUOTES.
  • '<' (знак "меньше чем") преобразуется в '&lt;'
  • '>' (знак "больше чем") преобразуется в '&gt;'

Список параметров

string

Конвертируемая строка (string).

flags

Битовая маска из нижеуказанных флагов, определяющих режим обработки кавычек, некорректных кодовых последовательностей и используемый тип документа. По умолчанию используется ENT_COMPAT | ENT_HTML401.

Доступные значения параметра flags
Название константы | Описание
ENT_COMPAT | Преобразует двойные кавычки, одинарные кавычки не изменяются.
ENT_QUOTES | Преобразует как двойные, так и одинарные кавычки.
ENT_NOQUOTES | Оставляет без изменения как двойные, так и одинарные кавычки.
ENT_IGNORE | Без всяких уведомительных сообщений отбрасывает некорректные кодовые последовательности вместо возврата пустой строки. Использование этого флага не рекомендуется, так как это может привести к » негативным последствиям, связанным с безопасностью.
ENT_SUBSTITUTE | Заменяет некорреткные кодовые последовательности символом замены Юникода U+FFFD в случае использования UTF-8 и &#FFFD; при использовании другой кодировки, вместо возврата пустой строки.
ENT_DISALLOWED | Заменяет неверные коды символов для заданного типа документа символом замены юникода U+FFFD (UTF-8) или &#FFFD; (при использовании другой кодировки) вместо того, чтобы оставлять все как есть. Это может быть полезно, например, для того, чтобы убедиться в формальной правильности XML-документов со встроенным внешним контентом.
ENT_HTML401 | Обработка кода в соответствии с HTML 4.01.
ENT_XML1 | Обработка кода в соответствии с XML 1.
ENT_XHTML | Обработка кода в соответствии с XHTML.
ENT_HTML5 | Обработка кода в соответствии с HTML 5.

encoding

Определяет кодировку, используемую для преобразования. Если не указано, то кодировкой по умолчанию является ISO-8859-1 для PHP до версии 5.4.0, и UTF-8 начиная с версии 5.4.0.

Для целей этой функции кодировки ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252 и KOI8-R являются практически эквивалентными, предполагая то, что сама строка string содержит корректные символы в указанной кодировке, то символы, изменяемые htmlspecialchars(), останутся на тех же местах во всех этих кодировках.

Поддерживаются следующие кодировки:

Поддерживаемые кодировки
Кодировка | Псевдонимы | Описание
ISO-8859-1 | ISO8859-1 | Западно-европейская Latin-1.
ISO-8859-5 | ISO8859-5 | Редкоиспользуемая кириллическая кодировка (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Западно-европейская Latin-9. Добавляет знак евро, французские и финские буквы к кодировке Latin-1(ISO-8859-1).
UTF-8 | 8-битная Unicode, совместимая с ASCII.
cp866 | ibm866, 866 | Кириллическая кодировка, применяемая в DOS.
cp1251 | Windows-1251, win-1251, 1251 | Кириллическая кодировка, применяемая в Windows.
cp1252 | Windows-1252, 1252 | Западно-европейская кодировка, применяемая в Windows.
KOI8-R | koi8-ru, koi8r | Русская кодировка.
BIG5 | 950 | Традиционный китайский, применяется в основном на Тайване.
GB2312 | 936 | Упрощенный китайский, стандартная национальная кодировка.
BIG5-HKSCS | Расширенная Big5, применяемая в Гонг-Конге.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Японская кодировка.
EUC-JP | EUCJP, eucJP-win | Японская кодировка.
MacRoman | Кодировка, используемая в Mac OS.
'' Пустая строка активирует режим определения кодировки из файла скрипта (Zend multibyte), default_charset и текущей локали (см. nl_langinfo() и setlocale()), в указанном порядке. Не рекомендуется к использованию.

Замечание: Остальные кодировки не поддерживаются, вместо них будет применена кодировка по умолчанию и сгенерировано предупреждение.

double_encode

Если параметр double_encode выключен, то PHP не будет преобразовывать существующие html-сущности. По умолчанию преобразуется все без ограничений.

Возвращаемые значения

Преобразованная строка (string).

Если входная строка string содержит неверную последовательность символов в указанной кодировке encoding, то будет возвращаться пустая строка в случае, если флаги ENT_IGNORE или ENT_SUBSTITUTE не установлены.

Список изменений

Версия | Описание
5.4.0 | Значение по умолчанию для параметра encoding было изменено на UTF-8.
5.4.0 | Добавлены константы ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML и ENT_HTML5.
5.3.0 | Добавлена константа ENT_IGNORE.
5.2.3 | Добавлен параметр double_encode.
4.1.0 | Добавлен параметр charset.

Примеры

Пример #1 Пример использования htmlspecialchars()

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Примечания

Замечание:

Обратите внимание, что функция не производит других преобразований кроме описанных выше. Для преобразования всех HTML сущностей используйте htmlentities().

Смотрите также

  • get_html_translation_table() - Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities
  • htmlspecialchars_decode() - Преобразует специальные HTML-сущности обратно в соответствующие символы
  • strip_tags() - Удаляет HTML и PHP-теги из строки
  • htmlentities() - Преобразует все возможные символы в соответствующие HTML-сущности
  • nl2br() - Вставляет HTML-код разрыва строки перед каждым переводом строки

User Contributed Notes

steve at mcdragonsoftware dot com 17-Oct-2011 09:13
I am working with xml and zip functions to create an xlsx document from a template. Just as I thought I had it finished it stopped working. After a bit of hunting I discovered my zip file began with php notices about undefined constant. I have no idea why my installation can't remember what ENT_XML1 is, it used to know it (or so I thought)

To save anyone else this headache I recommend adding the code at the top of your scripts to verify that these constants are registered. Something like:

defined( "ENT_XML1") or define( "ENT_XML1",        16    );

for each constant you use. Again, I don't know why this problem suddenly came up, but better safe than "Excel cannot open the file....... format... extension... corrupted... blah blah blah".

cheers :)

here's a list of the constant values (since they are not on this page) as taken from html.h for php5

#define ENT_HTML_QUOTE_NONE            0
#define ENT_HTML_QUOTE_SINGLE           1
#define ENT_HTML_QUOTE_DOUBLE                2
#define ENT_HTML_IGNORE_ERRORS        4
#define ENT_HTML_SUBSTITUTE_ERRORS     8
#define ENT_HTML_DOC_TYPE_MASK        (16|32)
#define ENT_HTML_DOC_HTML401           0
#define ENT_HTML_DOC_XML1            16
#define ENT_HTML_DOC_XHTML            32
#define ENT_HTML_DOC_HTML5            (16|32)
/* reserve bit 6 */
#define ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS    128

#define ENT_COMPAT        ENT_HTML_QUOTE_DOUBLE
#define ENT_QUOTES        (ENT_HTML_QUOTE_DOUBLE | ENT_HTML_QUOTE_SINGLE)
#define ENT_NOQUOTES    ENT_HTML_QUOTE_NONE
#define ENT_IGNORE        ENT_HTML_IGNORE_ERRORS
#define ENT_SUBSTITUTE    ENT_HTML_SUBSTITUTE_ERRORS
#define ENT_HTML401        0
#define ENT_XML1        16
#define ENT_XHTML        32
#define ENT_HTML5        (16|32)
#define ENT_DISALLOWED    128
ivan at lutrov dot com 15-Jun-2011 01:30
Be careful, the "charset" argument IS case sensitive. This is counter-intuitive and serves no practical purpose because the HTML spec actually has the opposite.
info at 8th dot at 12-May-2011 11:28
English:
I'd found THE Final Solution!
it finds and replaces all unknown letters!
(like Ä, Ö, Ü, ß, and much much more)

it turn em in a HTML AND XML compatible format

parameter: $text: a String with unsuported letters in it
return: a String where all unsupported(XML und HTML) letters are changed into the Unicode value (for example &#196;)

Deutsch/German:
Ich hab die perfekte Lösung gefunden!
Es findet und tauscht alle unbekannten Buchstaben!
(wie Ä, Ö, Ü, ß, und viel viel mehr)

es tauscht sie in ein HTML und XML kompatibles Format

parameter: $text: ein String mit nichtunterstüzten Buchstaben
return: ein String wo alle von XML und HTML ununterstützten Buchstaben ins Unicode-Format getauscht sind (z.B. &#196;)

FUNCTION:

<?php
function umlaute($text){
    $returnvalue="";
    for($i=0;$i<strlen($text);$i++){
        $teil=hexdec(rawurlencode(substr($text, $i, 1)));
        if($teil<32||$teil>1114111){
            $returnvalue.=substr($text, $i, 1);
        }else{
            $returnvalue.="&#".$teil.";";
        }
    }
    return $returnvalue;
}
?>
pinkgothic at gmail dot com 11-Mar-2011 05:00
Please note that this function results in an E_WARNING when display_errors is off and an invalid multibyte string is passed to it (e.g. with 'utf-8' as the encoding parameter and broken utf-8 characters somewhere in the string).

This is ESPECIALLY IMPORTANT if you have an EXCEPTION-THROWING ERROR HANDLER, since even though you can't reproduce it in a development mode where display_errors is on, you MUST wrap your function call in a try-catch, or your application will crash.

[ The reason PHP makes this distinction is because this is a core function and many production servers are misconfigured to have display_errors on (to prevent such things as path disclosure from error messages from accidentally cropping up). See: http://bugs.php.net/bug.php?id=47494 ]
Thomasvdbulk at gmail dot com 28-Dec-2010 10:05
i searched for a while for a script, that could see the difference between an html tag and just < and > placed in the text,
the reason is that i recieve text from a database,
wich is inserted by an html form, and contains text and html tags,
the text can contain < and >, so does the tags,
with htmlspecialchars you can validate your text to XHTML,
but you'll also change the tags, like <b> to &lt;b&gt;,
so i needed a script that could see the difference between those two...
but i couldn't find one so i made my own one,
i havent fully tested it, but the parts i tested worked perfect!
just for people that were searching for something like this,
it may looks big, could be done easier, but it works for me, so im happy.

<?php
function fixtags($text){
$text = htmlspecialchars($text);
$text = preg_replace("/=/", "=\"\"", $text);
$text = preg_replace("/&quot;/", "&quot;\"", $text);
$tags = "/&lt;(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=\"\"/", "=", $text);
return $text;
}
?>

an example:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br />
<a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

will echo:
this is smaller &lt; than this<br />
this is greater &gt; than this<br />
this is the same = as this<br />
<a href="http://www.example.com/example.php?test=test">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...

I hope its helpfull!!
Anonymous 01-Aug-2010 01:48
This may seem obvious, but if you want to output arbitrary (i.e. user-input) data as an attribute inside an HTML tag (such as the INPUT tags on a FORM), be aware of whether you are using ENT_QUOTES or ENT_COMPAT.  If you're using ENT_COMPAT, the attribute must be wrapped in double-quotes, as single-quotes will not be encoded and the user will be able to inject arbitrary HTML attributes (including javascript behavior) inside the tag, even though they will not be able to inject arbitrary HTML tags.

Also, if you want to allow users to input HTML attributes without them being double-encoded on display, there are two ways to accomplish this:

1 - Run their input through htmlentities_decode() followed by htmlspecialchars().

2 - Call htmlspecialchars() with $double_encode=false.

There is one functional difference between these two methods:  If you want to perform any search-replace on a user's input (such as word censoring in a message-board application), the second method will allow users to circumvent it by HTML-encoding their input, whereas the first will not.
nachitox2000 [at] hotmail [dot] com 01-Jul-2010 05:57
I had problems with spanish special characters. So i think in using htmlspecialchars but my strings also contain HTML.
So I used this :) Hope it help

<?php
function htmlspanishchars($str)
{
    return str_replace(array("&lt;", "&gt;"), array("<", ">"), htmlspecialchars($str, ENT_NOQUOTES, "UTF-8"));
}
?>
nessthehero at gmail dot com 19-May-2010 11:53
Here's a simple function I wrote for parsing form data.

It checks if it's an array and it is recursive (it calls itself).

It also decodes things that have already been encoded so it doesn't change &amp; to &amp;amp;

[In this version,] I found it easier to use a regular expression to check and see if any previously encoded data exists, then decode it repeatedly until there is none left, then re-encode it.

<?php
function formspecialchars($var)
    {
        $pattern = '/&(#)?[a-zA-Z0-9]{0,};/';

        if (is_array($var)) {    // If variable is an array
            $out = array();      // Set output as an array
            foreach ($var as $key => $v) {
                $out[$key] = formspecialchars($v);         // Run formspecialchars on every element of the array and return the result. Also maintains the keys.
            }
        } else {
            $out = $var;
            while (preg_match($pattern,$out) > 0) {
                $out = htmlspecialchars_decode($out,ENT_QUOTES);
            }
            $out = htmlspecialchars(stripslashes(trim($out)), ENT_QUOTES,'UTF-8',true);     // Trim the variable, strip all slashes, and encode it

        }

        return $out;
    }
?>
alif 11-Feb-2010 09:17
I had XML files with both '&amp;' , '&copyright;' and '&' characters. So, basically, I wrote this preg_replace, which replaces all '&' thats not an  entity to '&amp;'.

So '&amp;' doesnot get converted to '&ampamp;', only '&' gets converted to '&amp;'. Also, '&copyright;' , '&#160;' remains unaffected. Its basic, feel free to modify it.

preg_replace('/&(?![A-Za-z0-9#]{1,7};)/','&amp;',$theString);
timgvdh at gmail dot com 15-Dec-2009 08:54
Here's something that replicates the appearance of <pre> but still allows for word wrap:

<?php
function special_formatting($input) {
    $output = htmlspecialchars($input, ENT_QUOTES);
    $output = str_replace(array('  ', "\n"), array('&nbsp;&nbsp;', '<br>'), $output);
    return str_replace('&nbsp; ', '&nbsp;&nbsp;', $output);
}
?>
Anonymous 18-Sep-2009 10:16
This may seem obvious, but it caused me some frustration. If you try and use htmlspecialchars with the $charset argument set and the string you run it on is not actually the same charset you specify, you get any empty string returned without any notice/warning/error.

<?php

$ok_utf8 = "A valid UTF-8 string";
$bad_utf8 = "An invalid UTF-8 string";

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(0) ""

var_dump(htmlspecialchars($ok_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(20) "A valid UTF-8 string"

?>

So make sure your charsets are consistent

<?php

$bad_utf8 = "An invalid UTF-8 string";

// make sure it's really UTF-8
$bad_utf8 = mb_convert_encoding($bad_utf8, 'UTF-8', mb_detect_encoding($bad_utf8));

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(23) "An invalid UTF-8 string"

?>

I had this problem because a Mac user was submitting posts copy/pasted from a program and it contained weird chars in it.
Anonymous 16-Sep-2009 09:43
Just a few notes on how one can use htmlspecialchars() and htmlentities() to filter user input on forms for later display and/or database storage...

1. Use htmlspecialchars() to filter text input values for html input tags.  i.e.,

echo '<input name=userdata type=text value="'.htmlspecialchars($data).'" />';

2. Use htmlentities() to filter the same data values for most other kinds of html tags, i.e.,

echo '<p>'.htmlentities($data).'</p>';

3. Use your database escape string function to filter the data for database updates & insertions, for instance, using postgresql,

pg_query($connection,"UPDATE datatable SET datavalue='".pg_escape_string($data)."'");

This strategy seems to work well and consistently, without restricting anything the user might like to type and display, while still providing a good deal of protection against a wide variety of html and database escape sequence injections, which might otherwise be introduced through deliberate and/or accidental input of such character sequences by users submitting their input data via html forms.
chuck at N0SPAM1command dot com 12-Aug-2009 07:06
NOTE:
I made an error in my last post.

The last 3 lines should have read
<?php

...

$text = get_page($url);
--------^^^^^^^^
$new = htmlspecialchars($text, ENT_QUOTES); // here is the magic :)

    echo '<pre>' .$new. '</pre>';

?>

OOPS!
chuck at N0SPAM1command dot com 12-Aug-2009 05:57
Need to dump the source of page retrieved via <a href="http://us3.php.net/curl">CURL</a>?
I found it's easily done with htmlspecialchars()

eg;

<?php

function get_page($url)
{
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'some bot');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, '-');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
...
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_NOBODY, 0);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  $html = curl_exec($curl);
  curl_close($curl);

  return $html;
}

$text = get_page($url);
$new = htmlspecialchars($text, ENT_QUOTES); // here is the magic :)

    echo '<pre>' .$new. '</pre>';

?>

HTH
hm2k at php.net 22-Jun-2009 10:02
<?php
/**
 * A recursive version of htmlspecialchars() for arrays and strings.
 *
 */

function htmlspecialchars_deep($mixed, $quote_style = ENT_QUOTES, $charset = 'UTF-8')
{
    if (is_array($mixed)) {
        foreach($mixed as $key => $value) {
            $mixed[$key] = htmlspecialchars_deep($value, $quote_style, $charset);
        }
    } elseif (is_string($mixed)) {
        $mixed = htmlspecialchars(htmlspecialchars_decode($mixed, $quote_style), $quote_style, $charset);
    }
    return $mixed;
}
?>
hello at haroonahmad dot co dot uk 23-Mar-2009 01:56
a common confusion among beginner is that what is the difference between htmlentities() and htmlspecialchars() really, because the manual examples are converting angular brackets for both.

well, htmlentities() will ALSO look for other language characters in the string e.g German, French or Italian etc. So if you think your attacker can use some foreign language characters for a XSS attack in URL etc then use htmlentities() instead of htmlspecialchars().

I hope it helps,

Haroon Ahmad
Kenneth Kin Lum 08-Oct-2008 06:45
if your goal is just to protect your page from Cross Site Scripting (XSS) attack, or just to show HTML tags on a web page (showing <body> on the page, for example), then using htmlspecialchars() is good enough and better than using htmlentities().  A minor point is htmlspecialchars() is faster than htmlentities().  A more important point is, when we use  htmlspecialchars($s) in our code, it is automatically compatible with UTF-8 string.  Otherwise, if we use htmlentities($s), and there happens to be foreign characters in the string $s in UTF-8 encoding, then htmlentities() is going to mess it up, as it modifies the byte 0x80 to 0xFF in the string to entities like &eacute;.  (unless you specifically provide a second argument and a third argument to htmlentities(), with the third argument being "UTF-8").

The reason htmlspecialchars($s) already works with UTF-8 string is that, it changes bytes that are in the range 0x00 to 0x7F to &lt; etc, while leaving bytes in the range 0x80 to 0xFF unchanged.  We may wonder whether htmlspecialchars() may accidentally change any byte in a 2 to 4 byte UTF-8 character to &lt; etc.  The answer is, it won't.  When a UTF-8 character is 2 to 4 bytes long, all the bytes in this character is in the 0x80 to 0xFF range. None can be in the 0x00 to 0x7F range.  When a UTF-8 character is 1 byte long, it is just the same as ASCII, which is 7 bit, from 0x00 to 0x7F.  As a result, when a UTF-8 character is 1 byte long, htmlspecialchars($s) will do its job, and when the UTF-8 character is 2 to 4 bytes long, htmlspecialchars($s) will just pass those bytes unchanged.  So htmlspecialchars($s) will do the same job no matter whether $s is in ASCII, ISO-8859-1 (Latin-1), or UTF-8.
brendel at krumedia dot de 15-May-2008 10:28
I know some people posted similar functions but may be you are looking for this version:

function jschars($str)
{
    $str = mb_ereg_replace("\\\\", "\\\\", $str);
    $str = mb_ereg_replace("\"", "\\\"", $str);
    $str = mb_ereg_replace("'", "\\'", $str);
    $str = mb_ereg_replace("\r\n", "\\n", $str);
    $str = mb_ereg_replace("\r", "\\n", $str);
    $str = mb_ereg_replace("\n", "\\n", $str);
    $str = mb_ereg_replace("\t", "\\t", $str);
    $str = mb_ereg_replace("<", "\\x3C", $str); // for inclusion in HTML
    $str = mb_ereg_replace(">", "\\x3E", $str);
    return $str;
}

if you use smarty your code may look like:

<a onclick="alert('{$text|jschars|htmlchars}');return false;">Test</a>

(Yes, we have the shortcur htmlchars instead of htmlspecialchars, so we are able to tell the encoding e.g. UTF-8 or ISO-8859-1 to htmlspecialchars)
php dot net at orakio dot net 10-Apr-2008 11:26
I was recently exploring some code when I saw this being used to make data safe for "SQL".

This function should not be used to make data SQL safe (although to prevent phishing it is perfectly good).

Here is an example of how NOT to use this function:

<?php
$username = htmlspecialchars(trim("$_POST[username]"));

$uniqueuser = $realm_db->query("SELECT `login` FROM `accounts` WHERE `login` = '$username'");
?>

(Only other check on $_POST['username'] is to make sure it isn't empty which it is after trim on a white space only name)

The problem here is that it is left to default which allows single quote marks which are used in the sql query. Turning on magic quotes might fix it but you should not rely on magic quotes, in fact you should never use it and fix the code instead. There are also problems with \ not being escaped. Even if magic quotes were used there would be the problem of allowing usernames longer than the limit and having some really weird usernames given they are to be used outside of html, this just provide a front end for registering to another system using mysql. Of course using it on the output wouldn;t cause that problem.

Another way to make something of a fix would be to use ENT_QUOTE or do:

<?php
$uniqueuser = $realm_db->query('SELECT `login` FROM `accounts` WHERE `login` = "'.$username.'";');
?>

Eitherway none of these solutions are good practice and are not entirely unflawed. This function should simply never be used in such a fashion.

I hope this will prevent newbies using this function incorrectly (as they apparently do).
treyh 09-Apr-2008 11:41
Here is a function that wraps htmlspecialchars and makes it work for xml.

function xmlspecialchars($text) {
   return str_replace('&#039;', '&apos;', htmlspecialchars($text, ENT_QUOTES));
}
crestfresh at gmail dot com 18-Feb-2008 07:02
Re ish1301's jsspecialchars() function: use json_encode() instead.
ish1301 at gmail doooot com 20-Nov-2007 02:56
used this function for making a variable javascript compatible

<?php
function jsspecialchars( $string = '') {
    $string = preg_replace("/\r*\n/","\\n",$string);
    $string = preg_replace("/\//","\\\/",$string);
    $string = preg_replace("/\"/","\\\"",$string);
    $string = preg_replace("/'/"," ",$string);
    return $string;
}
?>
hope this may help those embedding php in javascripts
drew at august-harper dot com 22-Aug-2007 09:21
:// Escapes strings to be included in javascript
:function jsspecialchars($s) {
:    return preg_replace('/([^ :!#$%@()*+,-.\x30-\x5b\x5d-\x7e])/e',
:        "'\\x'.(ord('\\1')<16? '0': '').dechex(ord('\\1'))",$s);
:}

This function DOES NOT produce correct output in PHP5. Any strings containing a ” will be improperly escaped to \x5c, when it should be \x22.

I am not very good with regular expressions, so this is my solution to the problem.
//this is a workaround for jsspecialchars!
function ord2($s) {
if (strlen($s) == 2) {
return ord(substr($s,1,1));
} else {
return ord($s);
}
}
function JS_SpecialChars($s) {
return preg_replace(’/([^ !#$%@()*+,.\x30\x5b\x5d-\x7e])/e’,
”’\\x’.(ord2(’\\1’)&lt;16? ‘0’: ’’).dechex(ord2(’\\1’))”,$s);
}

I am sure that there is a better solution, but I can’t figure one out. This approach will probably also fix any other characters that end up being improperly escaped.
solar-energy 16-Jun-2007 03:21
also see function "urlencode()", useful for passing text with ampersand and other special chars through url

(i.e. the text is encoded as if sent from form using GET method)

e.g.

<?php
echo "<a href='foo.php?text=".urlencode("foo?&bar!")."'>link</a>";
?>

produces

<a href='foo.php?text=foo%3F%26bar%21'>link</a>

and if the link is followed, the $_GET["text"] in foo.php will contain "foo?&bar!"
galvao at galvao dot eti dot br 19-May-2007 06:19
There's a tiny error on alex-0 at hotmail dot co dot uk example:

The line:

$new = htmlspecialchars($_POST[message], ENT_QUOTES);

Should be written as:

$new = htmlspecialchars($_POST['message'], ENT_QUOTES);

Regards,
terminatorul at gmail dot com 27-Apr-2007 10:04
To html-encode Unicode characters that may not be part of your document character set (given in the META tag of your page), and so can not be output directly into your document source, you need to use mb_encode_numericentity(). Pay attention to it's conversion map argument.
frank at codedor dot be 16-Jan-2007 01:25
If you seem to have a problem with rendering dynamic RSS files from a database - try using htmlspecialchars() or htmlentities() on the text you are rendering.

Since XML and RSS is very strict about what is allowed inside nodes, you need to make sure everything is "A-OK" according to XML standards ...

Especially if the database you're pulling data from is fi. Latin-Swedish encoding, which seems to be the standard setting for MySQL databases.
alex-0 at hotmail dot co dot uk 23-Dec-2006 01:09
You can also use variables.
This is handy when working with forms to clear out an malicious html

<?php
$new = htmlspecialchars($_POST[message], ENT_QUOTES);
echo $new;
?>
richard at mf2fm dot com 03-Mar-2006 01:06
I had a script which detected swearing and wanted to make sure that words such as 'f &uuml; c k' didn't slip through the system.

After using htmlentities(), the following line converts most extended alphabet characters back to the standard alphabet so you can spot such problems..

$text=eregi_replace("&([a-z])[a-z0-9]{3,};", "\\\\1", $text);

This changes, for example, '&uuml;' into 'u' and '&szlig' into 's'.  Sadly it also converts '&pound;' and '&para;' into 'p' so it's not perfect but does solve a lot of the problems
mikiwoz at yahoo dot co dot uk 06-Oct-2005 02:40
I am not sure, maybe I'm missing something, but I have found something interesting:
I've been working on a project, where I had to use htmlspecialchars (for opbvious reasons). I olso needed to de-code the encoded string. What I have done was almost a copy and paste from php.net:
$trans=get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES);
$trans=array_flip($trans);
$string=strtr($encoded, $trans);
(it looked a bit different in my code, but the idea is clear)
I couldn't get the apostrophe sign de-coded, and I needed it for the <A> tags. After an hour or so of debuging, I decided do print_r($trans). What I got was:
...
[&#39;] => '
...
BUT the apostrophe was encoded to $#039; -> note the zero.
I don't suppose it's a bug, but it definetely IS a potential pitfall, watch out for this one.
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br) 01-Sep-2005 06:16
Hello,

If you are getting trouble to SGDB write/read HTML data, try to use this:

<?php

//from html_entity_decode() manual page
function unhtmlentities ($string) {
   $trans_tbl =get_html_translation_table (HTML_ENTITIES );
   $trans_tbl =array_flip ($trans_tbl );
   return strtr ($string ,$trans_tbl );
}

//read from db
$content = stripslashes (htmlspecialchars ($field['content']));

//write to db
$content = unhtmlentities (addslashes (trim ($_POST['content'])));

//make sure result of function get_magic_quotes_gpc () == 0, you can get strange slashes in your content adding slashes twice

//better to do this using addslashes
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;

?>
jspalletta at gmail dot com 12-Jul-2005 05:37
I have found that this regular expression is sufficient for making sure that existing character entities show after htmlspecialchars() replaces _all_ occurrences of & with the &amp; entity.

<?php
// Note: hsc is an abbreviation of htmlspecialchars
function hscFixed($str)
{
    return preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($str));
}
?>

The only flaw I can think of is if you have text of the vein; "&[word];", that is not meant to be a character but rather uses the ampersand and semicolon in their traditional grammatical denotations.  However I think this is highly unlikely to occur (among other reasons, the fact that anyone with enough grammatical inclination to use them as such probably won't leave out the space between the ampersand and the word).
25-Jun-2005 08:44
You can't use htmlspecialchars to create RSS feeds, since it expands ampersands.You need to use something like this:
$content = preg_replace(array('/</', '/>/', '/"/'), array('&lt;', '&gt;', '&quot;'), $content);
palrich at gmail dot com 16-May-2005 01:29
To Alexander Nofftz and urbanheroes:
It's not an IE problem.  There is no &apos; in HTML.  So it's only a problem if someone else does render this as an apostraphe on an HTML page.
paul dot l at aon dot at 09-May-2005 09:50
function reverse_htmlentities($mixed)
{
    $htmltable = get_html_translation_table(HTML_ENTITIES);
    foreach($htmltable as $key => $value)
    {
        $mixed = ereg_replace(addslashes($value),$key,$mixed);
    }
    return $mixed;
}

this is my version of a reversed htmlentities function
thisiswherejunkgoes at gmail dot com 05-May-2005 10:06
If there're any n00bs out there looking for a way to ensure that no html/special chars are getting sent to their databases/put through forms/etc., this has been doing the trick for me (though being at least slightly n00bish, if this won't always work perhaps someone will ammend :-)

function checkforchars ($foo) {

  if ($foo === htmlspecialchars($foo)) {
        return "Valid entry.";
  } else {
        return "Invalid entry.";
  }

}
urbanheroes {at} gmail {dot} com 30-Apr-2005 11:32
In response to the note made by Alexander Nofftz on October 2004, &#39; is used instead of &apos; because IE unfortunately seems to have trouble with the latter.
gt at realvertex.com 28-Apr-2005 09:55
Here is the recursive version that works for both arrays and strings. Doesn't look as elegant as the other recursive versions, because of the input checks.

function HTML_ESC($_input = null, $_esc_keys = false)
{
    if ((null != $_input) && (is_array($_input)))
    {
        foreach($_input as $key => $value)
        {
            if($_esc_keys)
            {
                $_return[htmlspecialchars($key)] = HTML_ESC($value,$_esc_keys);
            }
            else
            {
                $_return[$key] = HTML_ESC($value);
            }
        }
        return $_return;
    }
    elseif(null != $_input)
    {
        return htmlspecialchars($_input);
    }
    else
    {
        return null;
    }
}
took 23-Apr-2005 09:14
The Algo from donwilson at gmail dot com to reverse the action of htmlspecialchars(), edited for germany:

function unhtmlspecialchars( $string )
{
  $string = str_replace ( '&amp;', '&', $string );
  $string = str_replace ( '&#039;', '\'', $string );
  $string = str_replace ( '&quot;', '"', $string );
  $string = str_replace ( '&lt;', '<', $string );
  $string = str_replace ( '&gt;', '>', $string );
  $string = str_replace ( '&uuml;', '�', $string );
  $string = str_replace ( '&Uuml;', '�', $string );
  $string = str_replace ( '&auml;', '�', $string );
  $string = str_replace ( '&Auml;', '�', $string );
  $string = str_replace ( '&ouml;', '�', $string );
  $string = str_replace ( '&Ouml;', '�', $string );
  return $string;
}
11-Mar-2005 04:22
function htmlspecialchars_array($arr = array()) {
   $rs =  array();
   while(list($key,$val) = each($arr)) {
       if(is_array($val)) {
           $rs[$key] = htmlspecialchars_array($val);
       }
       else {
           $rs[$key] = htmlspecialchars($val, ENT_QUOTES);
       }
   }
   return $rs;
}
beer UNDRSCR nomaed AT hotmail DOT com 01-Feb-2005 02:46
After inspecting the non-native encoding problem, I noticed that for example, if the encoding is cyrillic, and I write Latin characters that are not part of the encoding (� for example - ae-ligature), the browser will send the real entity, such as &aelig; for this case.
Therefore, the only way I see to display multilingual text that is encoded with entities is by:
<?php
    echo str_replace('&amp;', '&', htmlspecialchars($txt));
?>

The regex for numeric entities will skip the Latin-1 textual entities.
zolinak at zoli dot szathmari dot hu 14-Dec-2004 04:46
A sample function, if anybody want to turn html entities (and special characters) back to simple. (eg: "&egrave;", "<" etc)

function html2specialchars($str){
    $trans_table = array_flip(get_html_translation_table(HTML_ENTITIES));
    return strtr($str, $trans_table);
}
beer UNDRSCR nomaed AT hotmail DOT com 21-Oct-2004 01:03
Quite often, on HTML pages that are not encoded as UTF-8, and people write in not native encoding, some browser (for sure IExplorer) will send the different charset characters using HTML Entities, such as &#1073; for small russian 'b'.
htmlspecialchars() will convert this character to the entity, since it changes all & to &amp;
What I usually do, is either turn &amp; back to & so the correct characters will appear in the output, or I use some regex to replace all entities of characters back to their original entity:
<?php
    // treat this as pseudo-code, it hasn't been tested...
    $result = preg_replace('/&amp;#(x[a-f0-9]+|[0-9]+);/i', '&#$1;', $source);
?>
Alexander Nofftz 20-Oct-2004 04:41
Why &#39;? The HTML and XML DTDs proposed &apos; for this.
See http://www.w3.org/TR/html/dtds.html#a_dtd_Special_characters

So better use this:

$text = htmlspecialchars($text, ENT_QUOTES);
$text = preg_replace('/&#0*39;/', '&apos;', $text);
mlvanbie at gmail dot com 06-Oct-2004 04:45
The code in the previous note has a bug.  If the original text was `&gt;' then htmlspecialchars will turn it into `&amp;gt;' and the suggested code will turn that into `>'.  The &amp; translation must be last.
donwilson at gmail dot com 25-Sep-2004 09:58
To reverse the action of htmlspecialchars(), use this code:

<?php
    unhtmlspecialchars( $string )
    {
        $string = str_replace ( '&amp;', '&', $string );
        $string = str_replace ( '&#039;', '\'', $string );
        $string = str_replace ( '&quot;', '\"', $string );
        $string = str_replace ( '&lt;', '<', $string );
        $string = str_replace ( '&gt;', '>', $string );

        return $string;
    }
?>
thelatesundayshow.com @ nathan (flip it) 02-Sep-2004 11:51
heres a version of the recursive escape function that takes the array byref rather than byval so saves some resources in case of big arrays

function recurse_array_HTML_safe(&$arr) {
    foreach ($arr as $key => $val)
        if (is_array($val))
            recurse_array_HTML_safe($arr[$key]);
        else
            $arr[$key] = htmlspecialchars($val, ENT_QUOTES);
}
moc.xnoitadnuof@310symerej 21-Apr-2004 04:04
Here are some usefull functions.
They will apply || decode, htmlspecialchars || htmlentities recursivly to arrays() || to regular $variables. They also protect agains "double encoding".

<?PHP
function htmlspecialchars_or( $mixed, $quote_style = ENT_QUOTES ){
    return is_array($mixed) ? array_map('htmlspecialchars_or',$mixed, array_fill(0,count($mixed),$quote_style)) : htmlspecialchars(htmlspecialchars_decode($mixed, $quote_style ),$quote_style);
}

function htmlspecialchars_decode( $mixed, $quote_style = ENT_QUOTES ) {
    if(is_array($mixed)){
      return array_map('htmlspecialchars_decode',$mixed, array_fill(0,count($mixed),$quote_style));
  }
  $trans_table = get_html_translation_table( HTML_SPECIALCHARS, $quote_style );
    if( $trans_table["'"] != '&#039;' ) { # some versions of PHP match single quotes to &#39;
        $trans_table["'"] = '&#039;';
    }
    return (strtr($mixed, array_flip($trans_table)));
}

function htmlentities_or($mixed, $quote_style = ENT_QUOTES){
    return is_array($mixed) ? array_map('htmlentities_or',$mixed, array_fill(0,count($mixed),$quote_style)) : htmlentities(htmlentities_decode($mixed, $quote_style ),$quote_style);
}

function htmlentities_decode( $mixed, $quote_style = ENT_QUOTES ) {
  if(is_array($mixed)){
      return array_map('htmlentities_decode',$mixed, array_fill(0,count($mixed),$quote_style));
  }
    $trans_table = get_html_translation_table(HTML_ENTITIES, $quote_style );
    if( $trans_table["'"] != '&#039;' ) { # some versions of PHP match single quotes to &#39;
        $trans_table["'"] = '&#039;';
    }
    return (strtr($mixed, array_flip($trans_table)));
}
?>

These functions are an addition to an earlier post. I would like to give the person some credit but I do not know who it was.

<?  ;llnu=u!eJq dHd?>
Dave Duchene 19-Feb-2004 05:58
Here is a handy function that will escape the contents of a variable, recursing into arrays.

<?php
function escaporize($thing) {
  if (is_array($thing)) {
    $escaped = array();

    foreach ($thing as $key => $value) {
      $escaped[$key] = escaporize($value);
    }

    return $escaped;
  }

  // else
  return htmlspecialchars($thing);
}
?>
mike-php at emerge2 dot com 20-Nov-2003 02:13
Here's a handy function that guards against 'double' encoding:

# Given a string, this function first strips out all html special characters, then
# encodes the string, safely returning an encoded string without double-encoding.
function get_htmlspecialchars( $given, $quote_style = ENT_QUOTES ){
   return htmlspecialchars( html_entity_decode( $given, $quote_style ), $quote_style );
}

# Needed for older versions of PHP that do not have this function built-in.
function html_entity_decode( $given_html, $quote_style = ENT_QUOTES ) {
   $trans_table = get_html_translation_table( HTML_SPECIALCHARS, $quote_style );
   if( $trans_table["'"] != '&#039;' ) { # some versions of PHP match single quotes to &#39;
      $trans_table["'"] = '&#039;';
   }
   return ( strtr( $given_html, array_flip( $trans_table ) ) );
}

Note: I set the default to ENT_QUOTES, as this makes more sense to me than the PHP function's default of ENT_COMPAT.
nospam at somewhere dot com 15-Jun-2003 10:28
most simple function for decoding html-encoded strings:

function htmldecode($encoded) {
    return strtr($encoded,array_flip(get_html_translation_table(HTML_ENTITIES)));
}
dystopia589 at yahoo dot com 13-Mar-2003 07:58
Sorry, part of that code was unnecessary. Here's a more readable version:

function SpecialChars($Security)
{
if (is_array($Security))
{
while(list($key, $val) = each($Security))
{
$Security[$key] = SpecialChars($val);
}
}
else
{
$Security = htmlspecialchars(stripslashes($Security), ENT_QUOTES);
}
return $Security;
}
webmaster at NOSPAM dot onlinegs dot com 28-Jan-2003 10:51
for those of you using V 4.3.0+ you can use html_entity_decode() to decode a string encoded with htmlspecialschars(), this should be faster and easier then using a str_replace or ereg.
_____ at luukku dot com 14-Sep-2002 02:21
People, don't use ereg_replace for the most simple string replacing operations (replacing constant string with another).
Use str_replace.
akira dot yoshi at shrine dot de 15-May-2002 09:15
If you need to htmlspecialchars a jis string, here's a function that does:

function htmlspecialchars_jis($text) {
    $ret="";
    if ($text=="") return "";
    $esc=chr(27);
    $text=$esc."$B".$esc."$B".$text;
    $text=str_replace($esc."(B", $esc."$B", $text);
    $trans=explode($esc."$B", $text);
    $enc=0;
    while (list (, $val) = each ($trans))  {
        if ($enc==0) {
            $val.="";
            if ($val!="") $ret.=htmlspecialchars($val);
            $enc=1;
        } else {
            $val.="";
            if ($val!="") $ret.=$esc."$B".$val.$esc."(B";
            $enc=0;
        };
    }
    return $ret;
};

BTW: I'm very(!) sure that JIS is iso-2022-jp, not iso-2002-jp
juadielon_NOSPAM at hotmail dot com 30-Apr-2002 09:09
I was trying to retrieve information from a database to display it into the browser. However it did not work as I was expecting.  For instance double quotes (��) and single quotes (��) were conflicting in HTML in an INPUT selector.

The first approach to solve this was to use htmlspecialchars to convert special characters to HTML entities to display the input box with its value.

$encode=htmlspecialchars($str, ENT_QUOTES);

However, the result was having HTML entities with a \ (backslash) preceding it (escape characters).  For instance ampersand (&) becomes \&amp; displaying \& and double quotes becomes \&quot; displaying \�

So the final solution was to replace first any \ (backslash) and then ask htmlspecialchars to make the conversion.

[Editor's Note: This is the wrong way to do this. The proper way is to use

$encoded = htmlspecialchars(stripslashes($str), ENT_QUOTES);
]

$encoded=htmlspecialchars(str_replace('\\', '', $str), ENT_QUOTES);

Try this example to see it your self.

<form action="<?php echo $PHP_SELF; ?>">
<input type="text" name="str" size="20" value="">
<input type="submit" value="Submit">
<br>
<?php
  if (!empty($str)) {
    $encoded=htmlspecialchars(str_replace('\\', '', $str), ENT_QUOTES);
    echo "<br><p>Result: <b>".$encoded."</b>. It should be the same you just typed</p>";
    echo "<p>But source code is transformed to:<b><xmp>".$encoded."</xmp></b></p>";
    // I know, I know <xmp> is deprecated in HTML 4 but was easy to use this time to display result.
  }
?>
</form>

Hope this will helps someone.
akira at kurogane dot net 01-Apr-2002 09:42
Beware of parsing JIS (aka 'iso-2002-jp') text through this function, as this function does not appear to have a sense for multibyte characters and may corrupt some characters. Eg. the japanese comma (the two ascii characters !" as viewed by an ascii client) gets transferred into !&quot; , which transforms the comma into a 'maru' mark and the following characters into garbage.
Conceivably this could affect other multibyte charsets.
joseph at nextique dot com 20-Feb-2002 01:21
Here is a handy function to htmlalize an array (or scalar) before you hand it off to xml.

function htmlspecialchars_array($arr = array()) {
    $rs =  array();
    while(list($key,$val) = each($arr)) {
        if(is_array($val)) {
            $rs[$key] = htmlspecialchars_array($val);
        }
        else {
            $rs[$key] = htmlspecialchars($val, ENT_QUOTES);
        }
    }
    return $rs;
}
14-Jul-2001 11:18
If your sending data from one form to another, the data in the textareas and text inputs may need to have htmlspecialchars("form data", ENT_QUOTES) applied, assuming you will ever have quotes or less-than signs or any of those special characters.  Using htmlspecialchars will make the text show up properly in the second form.  The changes are automatically undone whenever the form data is submitted. It does seem a little strange, but it works and my headache is now starting to go away.

AZ
ryan at ryano dot net 29-Jun-2001 03:06
Actually, if you're using >= 4.0.5, this should theoretically be quicker (less overhead anyway):

$text = str_replace(array("&gt;", "&lt;", "&quot;", "&amp;"), array(">", "<", "\"", "&"), $text);
thorax at inforocket dot com 08-Dec-1999 05:26
to convert a document back from this,
do string replacements in this order:

>   >
<   <
" "
&  &

Doing the last phase first will
reveal erroneous results.. For example:

'<'  => specialchars() => '&lt;' '&lt;' => convert ampersands => '<' => convert everything else => '<'
htmlspecialchars_decode
implode
Обработка строк


Объединяет элементы массива в строку

htmlspecialchars
join
Обработка строк
PHP Manual

implode

(PHP 4, PHP 5)

implode — Объединяет элементы массива в строку

Описание

string implode ( string $glue , array $pieces )
string implode ( array $pieces )

Объединяет элементы массива с помощью строки glue.

Замечание:

По историческим причинам, функции implode() можно передавать аргументы в любом порядке, однако для унификации с функцией explode() следует использовать документированный порядок аргументов.

Список параметров

glue

По умолчанию равен пустой строке. Это не является предпочтительным вариантом использования implode(), т.к. glue в таком случае будет вторым параметром, а это значит, что используется нежелательный прототип.

pieces

Массив объединяемых строк.

Возвращаемые значения

Возвращает строку, содержащую строкое представление всех элементов массива в указанном порядке, со строкой glue между каждым элементом.

Список изменений

Версия | Описание
4.3.0 | Параметр glue стал необязательным

Примеры

Пример #1 Пример использования implode()

<?php

$array = array('имя', 'почта', 'телефон');
$comma_separated = implode(",", $array);

echo $comma_separated; // имя,почта,телефон

// Пустая строка при использовании пустого массива:
var_dump(implode('hello', array())); // string(0) ""

?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • explode() - Разбивает строку с помощью разделителя
  • preg_split() - Разбивает строку по регулярному выражению

User Contributed Notes

michael dot janapin at gmail dot com 24-May-2012 11:13
I think some suggestions mentioned here in imploding an associative array for SQL operations might need some tweaking.

implode("', '", $array) leaves the first element with a missing open quote and the last element with a missing close quote.

i.e.,

$some_array = array(1,2,3);

$neat_list = implode('", "', $some_array);

echo $neatlist;

// RESULTS TO:
// 1", "2", "3

I think the glue is inserted just between the elements, thus the first open quote and the last open quote are missing.
lightningspirit at gmail dot com 08-Oct-2011 10:02
Here is a function to implode and array including the key and value pair.

<?php
/**
 * Implode an array with the key and value pair giving
 * a glue, a separator between pairs and the array
 * to implode.
 * @param string $glue The glue between key and value
 * @param string $separator Separator between pairs
 * @param array $array The array to implode
 * @return string The imploded array
 */
function array_implode( $glue, $separator, $array ) {
    if ( ! is_array( $array ) ) return $array;
    $string = array();
    foreach ( $array as $key => $val ) {
        if ( is_array( $val ) )
            $val = implode( ',', $val );
        $string[] = "{$key}{$glue}{$val}";

    }
    return implode( $separator, $string );

}
?>

You can, for example, encode an array to be sent as an URL query using this:
<?php
$query = url_encode( array_implode( '=', '&', $array ) );
?>

Or if you want to output an HTML element attributes:
<?php
echo '<input '.array_implode( '="', '" ', $array ).' />';
?>

Hope it can help someone!
jim at terrys dot net 07-Oct-2011 05:38
for dealing with tables:

<?php
$values = array('firstname'=>'firstname_value','lastname'=>'lastname_value');

sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'table_name', implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values)));

//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")

?>
gu_ludo at yahoo dot com dot br 19-Aug-2011 04:32
Hello there.
First, forgive me for my English if I write anything wrong. I'm brazilian.

I've made a recursive implode for multidimensional arrays. The $glue may be either an array or a string. If array, each element will be used as glue for each level of $pieces. If count($glue) is less than number of levels of $pieces, the last glue will be used for the remainder levels.

<?php

function implode_r($glue, $pieces){
        $return = "";

        if(!is_array($glue)){
            $glue = array($glue);
        }

        $thisLevelGlue = array_shift($glue);

        if(!count($glue)) $glue = array($thisLevelGlue);

        if(!is_array($pieces)){
            return (string) $pieces;
        }

        foreach($pieces as $sub){
            $return .= implode_r($glue, $sub) . $thisLevelGlue;
        }

        if(count($pieces)) $return = substr($return, 0, strlen($return) -strlen($thisLevelGlue));

        return $return;
    }

//Example
$arr = array(
    array(
        'SecondLevelFirstElement',
        'SecondLevelSecondElement'
    ),
    'FirstLevelFirstElement',
    'FirstLevelSecondElement'
);

echo implode_r(array("-|-", "_"));

?>

The output string will be:
"SecondLevelFirstElement_SecondLevelSecondElement-|-FirstLevelFirstElement-|-FirstLevelSecondElement"
alexey dot klimko at gmail dot com 23-Jun-2011 05:04
If you want to implode an array of booleans, you will get a strange result:
<?php
var_dump(implode('',array(true, true, false, false, true)));
?>

Output:
string(3) "111"

TRUE became "1", FALSE became nothing.
tl at magus dot dk 06-May-2011 10:42
It is also possible to implode an associative array using the following code (if you do not like (mis-)using http functions):

<?php

$assoc_array = array("Key1" => "Value1", "Key2" => "Value2");

$new_array = array_map(create_function('$key, $value', 'return $key.":".$value." # ";'), array_keys($assoc_array), array_values($assoc_array));

print implode($new_array);

?>

Which will output:

Key1:Value1 # Key2:Value2 #
sean at seancolombo dot com 11-Feb-2011 03:19
I've seen some code below for imploding an associative array.

Please note that http_build_query() will take care of that for you:
http://php.net/http_build_query

Happy coding!
stefan at efectos dot nl 09-Nov-2010 01:38
Small function when you just want to implode on the keys of an array. Especially helpful when you for instance create an array for database inserting in which the keys point to table row names.

Uses same function argument names as this documentation states for implode.

<?php
function implode_key($glue = "", $pieces = array()) {
    $arrK = array_keys($pieces);
    return implode($glue, $arrK);
}
?>
jords at NOSPAMshadowservices dot biz 02-Sep-2010 09:09
You don't need to do anything funny with implode() to get a php array into javascript - just use json_encode().
rustem 26-Apr-2010 07:17
If you need to output an array of strings inclosed in quotes (to convert it from php to JavaScript for instance), you can use this simple method:

var js_array = new Array("<?php echo implode('","',$php_array)?>");
kromped at yahoo dot com 08-Feb-2010 04:29
Recursive Implode

<?php

function r_implode( $glue, $pieces )
{
  foreach( $pieces as $r_pieces )
  {
    if( is_array( $r_pieces ) )
    {
      $retVal[] = r_implode( $glue, $r_pieces );
    }
    else
    {
      $retVal[] = $r_pieces;
    }
  }
  return implode( $glue, $retVal );
}

$test_arr = array( 0, 1, array( 'a', 'b' ), array( array( 'x', 'y'), 'z' ) );
echo r_implode( ',', $test_arr ) . "\n";
$test_arr = array( 0 );
echo r_implode( ',', $test_arr ) . "\n";
?>
mwwaygoo AT hotmail DOT com 18-Nov-2009 07:54
I was a little worried about the multi-dimensional array implodes listed here, as they are using 'for' loops, which is bad programming practice as arrays are not always nice and neat.

I hope this helps

<?php
function multi_implode($glue, $pieces)
{
    $string='';

    if(is_array($pieces))
    {
        reset($pieces);
        while(list($key,$value)=each($pieces))
        {
            $string.=$glue.multi_implode($glue, $value);
        }
    }
    else
    {
        return $pieces;
    }

    return trim($string, $glue);
}

?>
ravenswd at gmail dot com 07-Aug-2009 04:21
As "john" pointed out on 2004 Apr 26, implode does not always work in a way that could be considered intuitive.

You may need to sort your elements with ksort, or write a longer routine to fill in any "gaps". See this example:

<?php
$a = array(1=>'one', 7=>'seven', 5=>'five');

$b = implode (',', $a);

ksort ($a);

$c = implode (',', $a);

$highest = max(array_keys($a));
for ($i = 0; $i <= $highest; ++$i):
  if (! isset($a[$i])):
    $a[$i] = '';
  endif;
endfor;
ksort ($a);

$d = implode (',', $a);

print "\$b = '$b'<br>\n";
print "\$c = '$c'<br>\n";
print "\$d = '$d'<br>\n";

/*
output:
$b = 'one,seven,five'
$c = 'one,five,seven'
$d = ',one,,,,five,,seven'
*/
?>

Or, as a function:

<?php
function ensure (&$a, $filler = '') {

  // given: array $a with numerical keys
  // return: $a with keys sorted numerically and any gaps filled-in

   $highest = max(array_keys($a));
   for ($i = 0; $i <= $highest; ++$i):
     if (! isset($a[$i])):
       $a[$i] = $filler;
     endif;
   endfor;
   ksort ($a);

} // end function ensure

// usage:
// ensure($foo);
// ensure($bar, 0);
?>
adam82s at gmail dot com 04-Aug-2009 05:39
Found it very useful when inserting sql/mysql rows,

<?php
$values = array('firstname'=>'firstname_value','lastname'=>'lastname_value');

sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'table_name', implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values)));

//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")

?>
Very useful when dealing with tables with many columns.
houston_roadrunner at yahoo dot com 07-Apr-2009 11:50
it should be noted that an array with one or no elements works fine. for example:

<?php
    $a1 = array("1","2","3");
    $a2 = array("a");
    $a3 = array();

    echo "a1 is: '".implode("','",$a1)."'<br>";
    echo "a2 is: '".implode("','",$a2)."'<br>";
    echo "a3 is: '".implode("','",$a3)."'<br>";
?>

will produce:
===========
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
vega at terzapersona dot com 13-Mar-2009 01:26
I have improved crashinside's function for db use

function mt_implode($char,$array,$fix='',$addslashes=false)
{
    $lem = array_keys($array);
    $char = htmlentities($char);
    for($i=0;$i<sizeof($lem);$i++) {
      if($addslashes){
        $str .= $fix.(($i == sizeof($lem)-1) ? addslashes($array[$lem[$i]]).$fix : addslashes($array[$lem[$i]]).$fix.$char);
      }else{
        $str .= $fix.(($i == sizeof($lem)-1) ? $array[$lem[$i]].$fix : $array[$lem[$i]].$fix.$char);
      }
    }
    return $str;
}

$array = array("apple", "orange", "tree", "Sant' Anna");
echo mt_implode(', ', $array,'"',true);

// "apple", "orange", "tree", "Sant\' Anna"
crashinside 06-Jan-2009 02:57
I've implemented the function implode (it's easy):
<?php
function mt_implode($char,$array)
{
    $lem = array_keys($array);
    $char = htmlentities($char);
    for($i=0;$i<sizeof($lem);$i++) {
        $str .= ($i == sizeof($lem)-1) ? $array[$lem[$i]] : $array[$lem[$i]].$char;
    }
    return $str;
}
?>

Have fun
crazytonyi at example dot com 28-Dec-2008 11:04
For anyone looking for a good method to wrap each element before imploding it, I use this method:

<?php
function wrap_each(&$item)
{
    $item = "'$item'";
}

array_walk($array, 'wrap_each');
$array_csv = implode(",", $array);
?>
pr at technoparkcorp dot com 06-Nov-2008 12:48
This function is much more elegant and fast. It converts array to the list with 'and' at the end:

<?php
function ImplodeToEnglish ($array) {
    // sanity check
    if (!$array || !count ($array))
        return '';

    // get last element
    $last = array_pop ($array);

    // if it was the only element - return it
    if (!count ($array))
        return $last;

    return implode (', ', $array).' and '.$last;
}
?>
php at emanaton dot com 09-Oct-2008 08:27
I was fiddling around on a project and created an associative array implosion function that incorporates several of the ideas from this page, but which also adds a whack of nifty options. Unfortunately, the documentation for it made the post to long to display on this page, so I've provided the example on my site. Enjoy!

http://emanaton.com/code/php/implode_assoc
Kerberos 12-Sep-2008 05:09
Here's my version of the english implode function, it's quite crafty so I thought I'd share it...

<?php
    #
    # Transforms an array to an english list:
    # This, This and This
    #
    function array_to_english ( $list, $glueword='and' ) {

        $string = false;

        foreach ( array_reverse ( $list ) as $index=>$value ) {
            $string = "$value$glue$string";
            if ( $index == 0 ) $glue = " $glueword ";
            if ( $index == 1 ) $glue = ', ';
        }

        return $string;
    }
?>
compton 16-Aug-2008 08:51
superstuntguy below would save himself and his server a lot of time just by using $_SERVER['QUERY_STRING'] (see http://uk.php.net/manual/en/reserved.variables.server.php), as in:

<?php
echo '<form action=', $_SERVER['PHP_SELF'], '?', $_SERVER['QUERY_STRING'], ' method=post>';
?>

Note: using commas instead of full-stops (periods) between strings for echo is marginally more efficient as echo can then simply pop the substrings off the stack avoiding the tincy-wincy extra overhead of string concatenation.
mjong at magnafacta dot nl 30-Jul-2008 04:30
Many of the functions below can be simplified using this short function:

<?php
function array_implode($arrays, &$target = array()) {
    foreach ($arrays as $item) {
        if (is_array($item)) {
            array_implode($item, $target);
        } else {
            $target[] = $item;
        }
    }
    return $target;
}

$a = array('a', 'b', array('c', 'd', array('e'), 'f'), 'g', array('h'));

echo join(' - ', array_implode($a));
?>

The outputs:

<?php

a - b - c - d - e - f - g - h

?>
superstuntguy at gmail dot com 25-Jul-2008 05:38
I found this pretty useful so I wouldn't have to hardcode things:
<?php
function implode_get() {
    $first = true;
    $output = '';
    foreach($_GET as $key => $value) {
        if ($first) {
            $output = '?'.$key.'='.$value;
            $first = false;
        } else {
            $output .= '&'.$key.'='.$value;
        }
    }
    return $output;
}

echo '<form action='.$_SERVER['PHP_SELF'].implode_get()' method=post>';
?>
theuedimaster at gmail dot com 23-Jul-2008 06:36
This is a recursive implode function that can be used on multi-dimensional arrays. The explode function has also obeen included.

<?php
                //  Can implode an array of any dimension
        //  Uses a few basic rules for implosion:
        //        1. Replace all instances of delimeters in strings by '/' followed by delimeter
        //        2. 2 Delimeters in between keys
        //        3. 3 Delimeters in between key and value
        //        4. 4 Delimeters in between key-value pairs
        function implodeMDA($array, $delimeter, $keyssofar = '') {
            $output = '';
            foreach($array as $key => $value) {
                if (!is_array($value)) {
                    $value = str_replace($delimeter, '/'.$delimeter, $value);
                    $key = str_replace($delimeter, '/'.$delimeter, $key);
                    if ($keyssofar != '') $key = $key.$delimeter.$delimeter;
                    $pair = $key.$keyssofar.$delimeter.$delimeter.$delimeter.$value;
                    if ($output != '') $output .= $delimeter.$delimeter.$delimeter.$delimeter;
                    $output .= $pair;
                }
                else {
                    if ($output != '') $output .= $delimeter.$delimeter.$delimeter.$delimeter;
                    if ($keyssofar != '') $key = $key.$delimeter.$delimeter;
                    $output .= $this->implodeMDA($value, $delimeter, $key.$keyssofar);
                }
            }
            return $output;
        }

        //  Can explode a string created by corresponding implodeMDA function
        //  Uses a few basic rules for explosion:
        //        1. Instances of delimeters in strings have been replaced by '/' followed by delimeter
        //        2. 2 Delimeters in between keys
        //        3. 3 Delimeters in between key and value
        //        4. 4 Delimeters in between key-value pairs
        function explodeMDA($string, $delimeter) {
            $output = array();
            $pair_delimeter = $delimeter.$delimeter.$delimeter.$delimeter;
            $pairs = explode($pair_delimeter, $string);
            foreach ($pairs as $pair) {
                $keyvalue_delimeter = $delimeter.$delimeter.$delimeter;
                $keyvalue = explode($keyvalue_delimeter, $pair);
                $key_delimeter = $delimeter.$delimeter;
                $keys = explode($key_delimeter, $keyvalue[0]);
                $value = str_replace('/'.$delimeter, $delimeter, $keyvalue[1]);
                $keys[0] = str_replace('/'.$delimeter, $delimeter, $keys[0]);
                $pairarray = array($keys[0] => $value);
                for ($counter = 1; $counter < count($keys); $counter++) {
                    $pairarray = array($keys[$counter] => $pairarray);
                }
                $output = array_merge_recursive($output, $pairarray);
            }
            return $output;
        }
?>
webmaster at tubo-world dot de 15-Jul-2008 07:47
Refering to the previous post, here an optimized version:

<?php

function implode_wrapped($before, $after, $glue, $array){
    $output = '';
    foreach($array as $item){
        $output .= $before . $item . $after . $glue;
    }
    return substr($output, 0, -strlen($glue));
}

?>
mr dot bloar at gmail dot com 27-May-2008 07:12
A usefull version of implode() when you need to surround values, for example when you are working with nodes (HTML, XML)

<?php
function myImplode($before, $after, $glue, $array){
    $nbItem = count($array);
    $i = 1;
    foreach($array as $item){
        if($i < $nbItem){
            $output .= "$before$item$after$glue";
        }else $output .= "$before$item$after";
        $i++;
    }
    return $output;
}

$an_array = array('value1','value2');
print myImplode("<a href=\"#\">","</a>"," > ", $an_array);
?>

output : <a href="#">value1</a> > <a href="#">value2</a>
wesleys at opperschaap dot net 01-Apr-2008 04:36
I'm new to PHP, coming from Perl and I already had a problem once when I wanted to join some strings. In perl you can use join to join a list (which can be an array and/or a list of strings and/or hashes), where PHP does this only with arrays. That annoyed me.
I could not find any code which did this, so I created my own join, based on Perl's join function. It is called p_join().

<?php

/* is_assoc_array and is_sequential_array are STOLEN from:
 * http://nl3.php.net/manual/en/function.is-array.php#73505 */
function is_assoc_array($var) {
        return (array_merge($var) !== $var || !is_numeric(implode(array_keys($var))));
}

function is_sequential_array($var) {
        return (array_merge($var) === $var && is_numeric(implode(array_keys($var))));
}

function _p_join_assoc($sep, $hash) {
        $result = "";
        foreach ($hash as $k => $v) {
                $result .= $sep . $k .  $sep . $v ;
        }
        return $result;
}

function _p_join_array($sep, $array) {
        # Turn off notices and return to the old loglevel once we're done.
        # This is because we stringify an array in some cases..
        $old_error_reporting = error_reporting(E_ALL ^ E_NOTICE);
        $result = join($sep, $array);
        error_reporting($old_error_reporting);
        return $result;
}

function p_join() {

        $args = func_get_args();

        if (count($args) > 1) {
                $result     = "";
                $sep = array_shift($args);

                foreach ($args as $val) {
                        if (is_array($val)) {
                                if (is_assoc_array($val)) {
                                        $result .= _p_join_assoc($sep, $val);
                                } else {
                                        $result .= $sep  . _p_join_array($sep, $val);
                                }
                                continue;
                        }
                        $result .= $sep . $val;
                }
                # $result will always start with a $sep, so remove it..
                return substr_replace($result, "" ,0, strlen($sep));
        }

        trigger_error(sprintf("%s requires at least 2 parameters",
          __FUNCTION__), E_USER_WARNING);
        return null;
}

/* And some example code */

print p_join(",", "string", array("Key" => "Value", "Key 2" => "Value 2"),
  array("Hello", array("in", "hello", "world"), "array"), "string 2") . "\n";

/* Watch out, prints de indices when it you supply a mixed array */
print p_join(",", array(1,2,"Green" => "Apple" , array(1,2))) . "\n";

print "Warning.. ";
print p_join(",");
?>
ngkongs at gmail dot com 19-Mar-2008 10:39
implode() can't be used for simplexml's array but foreach() does the thing, make new implode function with foreach() will resolve this problem. use strval() to reset SimpleXMLElement object to a simple string variable.

<?php
function implode2($glue="", $var){
    if ($var){
        foreach ($var as $value){
            $array[]=strval($value);
        }
        return implode($glue, $array);
    }
    else return false;
}
?>
Anonymous 18-Feb-2008 03:41
So I looked through all the problem solutions  posted here, and combined them into one nice recursive function.

<?php

function implode_md( $glue, $array, $key = NULL, $list = NULL )
{
    if( !is_array( $array ) )
        return $array;
    if( !sizeof( $array ) )
        return "";
    if( !is_null( $key ) )
    {
        if( strpos( $key, "." ) )
        {
            $keys = array_reverse( explode( ".", $key ) );
            $currentKey = array_pop( $keys );
            if( sizeof( $keys ) ) $keys = implode( ".", $keys );
            else $keys = implode( "", $keys );
        }
        else
        {
            $currentKey = $key;
            $keys = NULL;
        }
        if( array_key_exists( $currentKey, $array ) )
            return implode_md( $glue, $array[$currentKey], $keys, $list );
        else
            return "";
    }
    if( !empty( $list ) )
    {
        $last = array_pop( $array );
        if( count( $array ) )
            return implode_md( $glue, $array, $key ) . " $list $last";
        else
            return $last;
    }
    $ret = array();
    for( $i = 0; $i < sizeof( $array ); $i++ )
        if( is_array( $array[$i] ) ) $ret[] = implode_md( $glue, $array[$i], $key, $list );
        else $ret[] = $array[$i];
    return implode( $glue, $ret );
}

?>
jimbob 12-Jan-2008 08:00
My take on a simple english list function - it's similar to what's already here, but calls count less

function x_implode_eng_list($array, $glue=', ', $final=' and '){
    //takes an array and outputs an English style list
    //perform the count once
    $count = count($array);
    //make sure it's an array and has content
    if((!is_array($array)) || ($count == 0)) {
        return '';
    } else {
        //pop off the end regardless of length
        $end = array_pop($array);
        //if there's more than one, implode the remainder using glue and append $end
        if($count>1){
            return implode($glue, $array) . $final . $end;
        } else {
            //only one value, return the popped end element
            return $end;
        }
    }
}
$names[] = 'bob';
$names[] = 'john';
$names[] = 'lucy';
echo x_implode_eng_list($names); //will output bob, john and lucy

echo x_implode_eng_list($names, ', ', ' or '); //will output bob, john or lucy
datacompboy at call2ru dot com 09-Nov-2007 11:50
suppose we have array $content with total size of 10Mb of text.

then,
  $content = join($content);
will run about 23 sec (on my machine -- athlon xp 2600+, 1.5 Gb ram)

and
  file_put_contents("tempfile", $content);
  $content = file_get_contents("tempfile");
will run for 0.12 sec (same machine).

so, think carefully about speed.
1413 at blargh dot com 10-Oct-2007 03:42
Below is the function for making an English-style list from an array, seems to be simpler than some of the other examples I've seen.

<?php
function ImplodeProper($arr, $lastConnector = 'and')
{
  if( !is_array($arr) or count($arr) == 0) return '';
  $last = array_pop($arr);
  if(count($arr))
    return implode(', ',$arr).", $lastConnector $last";
  else
    return $last;
}
?>

Examples:
<?
   print ImplodeProper(array()).'<br>';
   print ImplodeProper(array('foo')).'<br>';
   print ImplodeProper(array('foo','bar')).'<br>';
   print ImplodeProper(array('for','bar','bleh')).'<br>';
?>

Yields:

foo
foo, and bar
for, bar, and bleh
sinatosk at gmail dot com 07-Oct-2007 05:42
This code implodes same as the PHP built in except it allows you to do multi dimension arrays ( similar to a function below but works dynamic :p.

<?php

function implode_md($glue, $array, $array_path='')
{
    if ( !empty($array_path) )
    {
        $array_path = explode('.', $array_path);

        if ( ( $array_path_sizeof = sizeof($array_path) ) < 1 )
        {
            return implode($glue, $array);
        }
    }
    else
    {
        return implode($glue, $array);
    }

    $str = '';

    $array_sizeof = sizeof($array) - 1;

    for ( $i = 0; $i < $array_sizeof; $i++ )
    {
        $value = $array[ $i ];

        for ( $j = 0; $j < $array_path_sizeof; $j++ )
        {
            $value =& $value[ $array_path[ $j ] ];
        }

        $str .= $value . $glue;
    }

    $value = $array[ $array_sizeof ];

    for ( $j = 0; $j < $array_path_sizeof; $j++ )
    {
        $value =& $value[ $array_path[ $j ] ];
    }

    $str .= $value;

    return $str;
}

?>

And heres an example on how to use this

<?php

$arr = array();
$arr[]['data']['id'] = 'a';
$arr[]['data']['id'] = 'b';
$arr[]['data']['id'] = 'c';
$arr[]['data']['id'] = 'd';
$arr[]['data']['id'] = 'e';
$arr[]['data']['id'] = 'f';
$arr[]['data']['id'] = 'g';

echo implode_md(',', $arr, 'data.id');

?>

The output of this code should be

'a,b,c,d,e,f,g'

When you want to work with more dimensions... say for example you have an array that is like this

<?php

$arr=array();
$arr[0]['game']['pc']['fps']['idsoftware'] = 'Quake';
$arr[1]['game']['pc']['fps']['idsoftware'] = 'Quake II';
$arr[2]['game']['pc']['fps']['idsoftware'] = 'Quake III Arena';

?>

on the third parameter... as a string you simply type in

<?php

echo implode_md(', ', $arr, 'game.pc.fps.idsoftware');

?>

and the output should be

'Quake, Quake II, Quake III Arena'

Enjoy ;)
thomas at tgohome dot com 09-Jul-2007 01:05
This is my quick function to create a list, English style, but will accept any glue, so you could use 'or', or even 'or though, it could be', etcetera. It should also support PHP 4, although I haven't tested it; it doesn't use the PHP 5 negative substr() trick.

<?php

/**
 * Quick script to join items in an array, English
 * style; using the "one, two and three" style.
 *
 * Copyright 2007 Thomas O. Feel free to redistribute
 * so long as this copyright remains.
 */

function implode_ea($glue_punct, $glue_word, $array) {
    // Implode the entire array
    $result = implode($glue_punct, $array);

    // Check the length of the array
    if(count($array) > 1) {
        // Calculate the amount needed to trim
        $trimamount = strlen($array[count($array) - 1]) + strlen($glue_punct);

        // Trim the imploded string
        $result = substr($result, 0, strlen($result) - $trimamount); // PHP 4 compatible
        $result = "$result $glue_word " . $array[count($array) - 1];

        // Return the result
        return $result;
    } else {
        // In this case, the array cannot be splitted by a
        // word or punctuation, because it is too small.
        return $result;
    }
}

echo implode_ea(", ", "and", array("one", "two", "three"));
?>

(implode_ea stands for 'Implode, English And style')

Hope this helps,
Tom
peter dot goodman at gmail dot com 04-Jul-2007 10:36
I came up with this nifty function to implode an Iterator or class that implements IteratorAggregate:

function implode_iterator($sep = '', $it) {
    $a = array();

    if(!$it instanceof Traversable) {
        throw new UnexpectedValueException('$it must implement Traversable.');
    }

    if($it instanceof IteratorAggregate) {
        $a = iterator_to_array($it, FALSE);
    } else if($it instanceof Iterator) {
        foreach($it as $val) {
            $a[] = $val;
        }
    }

    return implode($sep, $a);
}
Dennis Day 02-Jul-2007 02:39
I have resolved an issue in SquirrelMail.  The problem seemed to be with the implode command.  Apparently you do not want to use this function with a large array as SquirellMail attempted to do.  This only was an issue with some of the email attachments larger that 2MB.

In /src/move_messages.php, replace the line line that says

$body = implode('', $body_a);

With :

// Dennis Day's custom code
                $body = "";
                foreach($body_a as $body_a_key=>$body_a_value){
                                $body .= $body_a_value;
                }
// End Dennis Day's custom code

// Original Bad Code
//              $body = implode('', $body_a);
TheMadBomberWhatBombsAtMidnight 14-Jun-2007 08:46
in response to Brian, building a POST/GET string from an assoc array is easily done with the builtin http_build_query...as the example from its doc page shows:

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
?>

of course, the builtin function also urlencodes the string it returns, which Brian's function did not.
darwinkid at gmail dot com 20-Mar-2007 12:09
this is a little function i made to implode an array based on key. its main purpose is to implode elements within
a multi-dimensional array. its slightly different than some of the other examples because it makes use of some
PHP SPL features. if your not using PHP5, this definitely won't work for you.

let me know what you think!

<?php
function implode_by_key($glue, $keyname, $pieces)
{

    // create a new recursive iterator to get array items
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($pieces));

    $arr = array();

    foreach($it AS $element) {

        if ($it->key() == $keyname) {

            $arr[] = $it->current();

        }

    }

    return implode($glue, $arr);

}

// here is an example

$array = array(
            array('somekey' => 'somevalue'),
            array(
                array('key2' => 'anoter value'),
                array('key2' => 'another sub value'),
                array(
                    array('key3' => 'asdlkfs jdafajdshf aoufiahsdlkfjsadf'),
                    array(
                        array('key4' => 'this is key 4 - 1'),
                        array('key4' => 'this is key 4 - 2'),
                        array('key4' => 'this is key 4 - 3'),
                        array(
                            array('key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
                            array('key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
                        )
                    )
                )

            )
        );

echo implode_by_key('<br/>', 'key4', $array);
?>

This outputs:

this is key 4 - 1
this is key 4 - 2
this is key 4 - 3
Hayley 19-Mar-2007 02:52
And adding one more case to drewish at katherinehouse dot com's code to deal with the two-element case "a and b":

<?php
case 2:
    return reset($array).' and '.end($array);
?>

Of course, then one can start considering Oxford rules again, and maybe testing that the argument really is an array....

<?php
function english_list($array, $useOxfordComma=false)
{
    if(!is_array($array))
        return '';
    switch(count($array))
    {
    case 0:
        return '';
    case 1:
        // This may not be a normal numerically-indexed array.
        return reset($array);
    case 2:
        return reset($array).' and '.end($array);
    default:
        $last = array_pop($array);
        return implode(', ', $array).($useOxfordComma?',':'').' and '.$last;
    }
}
?>
ahigerd at stratitec dot com 04-Jan-2007 06:43
Note that PHP uses copy-on-write so passing parameters (even array parameters) by reference gains you no performance benefit, and in fact in some cases can HURT performance.

For example:

php > $array = array('a','s','d','f');
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byref($array); echo microtime(true)-$start;
2.40807890892
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byval($array); echo microtime(true)-$start;
1.40822386742
bishop 23-Nov-2006 06:33
The english_list() implementation of davidpk212 at gmail dot com, Andy Morris, and tshort at cisco dot com does not handle the case of a two-element array with Oxford comma.  Example:

<?php
english_list(array ('a', 'b'), true) // == 'a, and b'
// should be 'a and b'
?>

Here's another implementation that addresses this issue, uses pass-by-reference without modifying the array, and illustrates yet another approach to solving the problem:

<?php
function english_list(&$array, $useOxfordComma = false) {
    $count = (is_array($array) ? count($array) : 0);
    if (3 <= $count) {
        $last = end($array);
        $list = prev($array) . ($useOxfordComma ? ', and ' : ' and ') . $last;
        while ($v = prev($array)) {
            $list = $v . ', ' . $list;
        }
    } else if (2 == $count) {
        $last = end($array);
        $list = prev($array) . ' and ' . $last;
    } else if (1 == $count) {
        $list = end($array);
    } else {
        return '';
    }

    reset($array);
    return $list;
}
?>

Run times for this version are comparable to the run times for heir earlier posted versions.
richard at happymango dot me dot uk 23-Nov-2006 04:43
This is a simple function that is the same as implode except it allows you to specify two glue parameters instead of one so an imploded array would output "this, this, this and this" rather than "this, this, this, this, this".

This is useful if you want to implode arrays into a string to echo as part of a sentence.

It uses the second glue between the last two items and the first glue between all others. It will use the second glue if there are only two items to implode so it would output "this and this".

<?php

function implode2($glue1, $glue2, $array)
{
    return ((sizeof($array) > 2)? implode($glue1, array_slice($array, 0, -2)).$glue1 : "").implode($glue2, array_slice($array, -2));
}

//example below

$array = array("Monday", "Tuesday");
echo "1: ".implode2(', ', ' and ', $array)."<br />";

$array = array("Mon", "Tue", "Wed", "Thu", "Fri");
echo "2: ".implode2(', ', ' &amp; ', $array)."<br />";

$array = array( 1, 2, 3, 4, 10);
echo "3: ".implode2(' + ', ' = ', $array)."<br />";

?>

This outputs

1: Monday and Tuesday
2: Mon, Tue, Wed, Thu & Fri
3: 1 + 2 + 3 + 4 = 10
Demonisch 05-Oct-2006 02:11
Very simple function for imploding a certain column in a 2D array. Useful if you have fetched records from a database in an associative array and want to store all the values in a certain column as a string, for use with JavaScript or passing values from page to page.

$sep = the separator, such as " ", "," or "&amp;"
$array = the 2D associative array
$key = the column key, such as "id"

Feel free to add error protection

function implodeArray2D ($sep, $array, $key)
{

    $num = count($array);
    $str = "";

    for ($i = 0; $i < $num; $i++)
    {

        if ($i)
        {
            $str .= $sep;
        }

        $str .= $array[$i][$key];

    }

    return $str;

}
triptripon at gmail dot com 05-Sep-2006 02:18
Here's my 2 matching (implode|explode)_with_key functions.
Notice, the inglue, outglue cannot appear within the keys\values.

function implode_with_key($assoc, $inglue = '>', $outglue = ',')
    {
        $return = '';
        foreach ($assoc as $tk => $tv)
        {
            $return .= $outglue . $tk . $inglue . $tv;
        }
        return substr($return,strlen($outglue));
    }

    function explode_with_key($str, $inglue = ">", $outglue = ',')
    {
        $hash = array();
        foreach (explode($outglue, $str) as $pair)
        {
            $k2v = explode($inglue, $pair);
            $hash[$k2v[0]] = $k2v[1];
        }
        return $hash;
    }

-- Tomer Levinboim
worldwideweb dot C-Kling dot de 12-Aug-2006 12:15
A Script for imploding a multideimensional Array. You give an array of separators in the first argument, and a (multidimensional) array in the second. The script will return the imploded array.

<?php
function multimplode($spacer,$array)
    {
    if (!is_array($array))
        {
        return($array);
        }
    if (empty($spacer))
        {
        return(multimplode(array(""),$array));
        }
    else
        {
        $trenn=array_shift($spacer);
        while (list($key,$val) = each($array))
            {
            if (is_array($val))
                {
                $array[$key]=multimplode($spacer,$val);
                }
            }
        $array=implode($trenn,$array);
        return($array);
        }
    }
?>
adnan at barakatdesigns dot net 23-May-2006 09:17
An easier way of achieving the same result as implode_with_keys() - and quicker execution time:

<?
/* NOTE: $glue is not used if $is_query is true */
function implode_with_keys($array, $glue, $is_query = false) {
    if($is_query == true) {
        return str_replace(array('[', ']', '&'), array('%5B', '%5D', '&amp;'), http_build_query($array));

    } else {
        return urldecode(str_replace("&", $glue, http_build_query($array)));

    }

}

echo implode_with_keys(array('a[1]' => 'some text', 'a[2]' => 'even more text'), false, true);
/* Will output 'a%5B1%5D=some+text&amp;a%5B2%5D=even+more+text' */
/* This won't break html validation */

echo implode_with_keys(array('a[1]' => 'foo bar', 'b' => 'more text'), '|');
/* Will output 'a[1]=foo bar|b=more text' */
?>
dabduster at gmail dot com 03-Jan-2006 08:39
an implementation of adrian at foeder dot de implode_with_keys function for input and update sql statement.

function implode_param($glue, $array, $valwrap='', $mode = 0)
   {
    /*
    if mode = 0 output is key and values
    if mode = 1 output only keys
    if mode = 2 output only values
    */

    switch ($mode){
        case 1:
               foreach($array AS $key => $value) {
                   $ret[] = $valwrap.$key.$valwrap;
               }
        break;

        case 2:
               foreach($array AS $key => $value) {
                   $ret[] = $valwrap.$value.$valwrap;
               }
        break;

        default:
        case 0:
               foreach($array AS $key => $value) {
                   $ret[] = $key."=".$valwrap.$value.$valwrap;
               }
        break;

    }

    return implode($glue, $ret);
}
adrian at foeder dot de 31-Oct-2005 04:53
...and a mysql-update-statement-compatible implementation of implode_with_keys:

<?php
function implode_with_keys($glue, $array, $valwrap='')
    {
        foreach($array AS $key => $value) {
            $ret[] = $key."=".$valwrap.$value.$valwrap;
        }
        return implode($glue, $ret);
    }
?>

so implode_with_keys(", ", $array, "'") will output:

key1='value1', key2='value2'

and so on. Useful for UPDATE table SET key1='value1', key2='value2'
Peter Hopfgartner 27-Sep-2005 07:26
Correctly initializing all variables, this would become:

function implode_with_key($assoc, $inglue = '=', $outglue = '&'){
    $return = '';
    foreach ($assoc as $tk => $tv) {
        $return = ($return != '' ? $return . $outglue : '') .
            $tk . $inglue . $tv;
    }
    return $return;
}

Note, the return value is also well defined if $assoc is empty.

Regards
php at josh dot jeppsons dot org 09-Sep-2005 09:22
Another variation on implode_with_key:

<?php
  function implode_with_key($assoc, $inglue = '=', $outglue = '&')
    foreach ($assoc as $tk => $tv) {
      $return = (isset($return) ? $return . $outglue : '') . $tk . $inglue . $tv;
    }
    return $return;
  }
?>
pr10n at spymac dot com 29-Aug-2005 09:46
A little tweak on info at urbits dot com's suggestion just incase someone changes their value of $outglue:

<?php
function implode_with_key($assoc, $inglue = '=', $outglue = '&')
{
   $return = null;
   foreach ($assoc as $tk => $tv) $return .= $outglue.$tk.$inglue.$tv;
   return substr($return,strlen($outglue));
}
?>
info at urbits dot com 19-Aug-2005 06:06
I liked memandeemail's (27-Apr-2005) neat code for imploding an associative array. I have done a mod so that, by default, it returns a url query string.

<?php
function implode_with_key($assoc, $inglue = '=', $outglue = '&')
{
   $return = null;
   foreach ($assoc as $tk => $tv) $return .= $outglue.$tk.$inglue.$tv;
   return substr($return,1);
}
?>

Example:
<?php
$assoc_array = array("a" => "foo", "b" => "bar", "c" => "foobar");
echo (implode_with_key($assoc_array);
?>

ouput: a=foo&b=bar&c=foobar

usage: After altering the $HTTP_GET_VARS values, I pass $HTTP_GET_VARS to the function to easily build variation urls for links and header redirects.

note: This function doesn't encode the url string or check for empty variables.
cristianDOTzuddas [AT] gmailDOTcom 07-Jul-2005 12:22
...and another variation of "implode_assoc" function. Just added the boolean parameter $urlencoded; if TRUE returns the array value in URL encod format. If the parameter is not given it behaves like the original function.

<?
function implode_assoc($inner_glue, $outer_glue, $array, $skip_empty=false, $urlencoded=false) {
    $output = array();
    foreach($array as $key=>$item) {
        if (!$skip_empty || isset($item)) {
            if ($urlencoded)
                $output[] = $key.$inner_glue.urlencode($item);
            else
                $output[] = $key.$inner_glue.$item;
        }
    }

    return implode($outer_glue, $output);
}
?>
sam dot bledsoe at nosp at nn dot gmail dot com 31-May-2005 08:57
The function below recursively outputs an array in a format condusive to parsing it in php or another scripting language.  It does NOT output the name of the original array, for that see note 1.  It handles all the cases I could think of elegantly.  Comments and criticisms are welcome.

For an array constructed with:

$arr = array("foo" => array('bar' => array(0 => "value 0", 1 => "value 1")), "foo two" => array(0 => array("bar" => "value2")));

The line below:

echo implode_parseable("=", ";<br>$", $arr, "$", ";");

Will produce:

$foo["bar"][0]="value 0";
$foo["bar"][1]="value 1";
$foo_two[0]["bar"]="value2";

NOTES:
1)  If the leading identifier on a line is a number, the output will most likely be unusable since variable names cannot begin with numbers.  You can get around this by doing something like:
$arr = array('arr' => $arr);
This will output the array as it actually is (because the key is the same name as the array) instead of just its fields.
2)  Since spaces are not allowed in variable names, they are replaced in lines' leading identifiers by the $space_replace_char parameter, '_' by default.

Hopefully someone will find this useful, if so drop me a line.  Credit and thanks go out to the people who posted their code on this manual page, especially davidpk212 at gmail dot com and phpWalter at torres dot ws.

function implode_parseable($inner_glue = "=", $outer_glue = "\n", $array = null, $prefix = "", $suffix = "", $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0){
  return $prefix . implode_parseable_r($inner_glue, $outer_glue, $array, $space_replace_char, $skip_empty, $current_loc, $recursion_level) . $suffix;
}

function implode_parseable_r($inner_glue = "=", $outer_glue = "\n", $array = null, $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0)
{
  if(is_array($array)){
    $output = array();
    foreach( $array as $key => $item ){
      if ( is_array ($item) ){

        //don't quote numeric indicies
        if(is_string($key))
          $quoted_key = "\"" . $key . "\"";
        else
          $quoted_key = $key;

        // This is value is an array, go and do it again!
        $level = $recursion_level + 1;
        if($recursion_level == 0){
          // can't have spaces in a variable name!
          $current_loc .= str_replace(' ', $space_replace_char, $key);
          $output[] = implode_parseable_r ($inner_glue, $outer_glue, $item,  '_', $skip_empty, $current_loc, $level);
          //start the position tracker over after every run from level 0
          $current_loc = '';
        }else{
          $current_loc .= "[" . $quoted_key . "]";
          $output[] = implode_parseable_r ($inner_glue, $outer_glue, $item,  '_', $skip_empty, $current_loc, $level);
          //remove the last index from the position tracker string after using it
          $current_loc = ereg_replace('\[[^]]*\]$', '', $current_loc);
        }

      }
      else{
        //  don't quote or []ify the base variable name,
        //  but do for all else as appropriate
        if($recursion_level != 0){
            if(is_string($key))
              $key = "\"" . $key . "\"";
            $key = "[" . $key . "]";
        }
//        echo "<br>";
//        var_dump($item);
//        echo "<br>";

        $skip_this = false;
        if($skip_empty && (!isset($item) || $item == NULL || $item == '')) $skip_this = true;

        //quote the item (which is the value of the array index) if it is a string
        if(is_string($item)) $item = "\"" . $item . "\"";

        if(!$skip_this) $output[] = $current_loc . $key . $inner_glue . $item;
      }
    }
    return implode($outer_glue, $output);
  }else{
    return $array;
  }
}
Kl�ba 31-May-2005 05:42
in case of value $item==0 but is set is necessary use function isset()

function implode_assoc($inner_glue,$outer_glue,$array,$skip_empty=false){
 $output=array();
 foreach($array as $key=>$item)
  if(!$skip_empty || isset($item)){$output[]=$key.$inner_glue.$item;}
 return implode($outer_glue,$output);
}
killroy at g m a i l dot c o m 16-May-2005 01:29
Here is another variation on Chris' function. I added a $skip_empty parameter. if it's set to TRUE the result string will not contain keys whose values are empty. Great for building query_strings. If the parameter is not given it behaves like the original function:

$a='1';
$b='';
$c='3';

INPUT: implode_assoc('=','&',array('a'=>$a,'b'=>$b,'c'=>$c),true);
OUTPUT: a=1&c=3

INPUT: implode_assoc('=','&',array('a'=>$a,'b'=>$b,'c'=>$c));
OUTPUT: a=1&b=&c=3

function implode_assoc($inner_glue,$outer_glue,$array,$skip_empty=false){
 $output=array();
 foreach($array as $key=>$item)
  if(!$skip_empty || $item){$output[]=$key.$inner_glue.$item;}
 return implode($outer_glue,$output);
}
tshort at cisco dot com 29-Apr-2005 07:20
Correction: I meant "passed by value", not "pass by reference". My mistake. Passing by reference would speed up any of these functions by avoiding the copy necessary for "by value.

Other solutions have problems with non-arrays as well. But it demonstrates that there are many ways to solve this problem. Adding checks for non-arrays and short arrays makes the solution less elegant, but safer. Other solutions should have included similar protections.

function english_list($array, $oxfordComma=0)
{
  if (!is_array($array)) return $array;
  if (count($array) <= 1) return join(", ", $array);
  $last = array_pop($array);
  return join(", ", $array) . ($oxfordComma ? "," : "") . " and " . $last;
}
Andy Morris 28-Apr-2005 05:27
It's always dangerous to give sweeping statements like "this will always work!". Your solution is much more elegant than mine, but perhaps it's a little too elegant for its own good! Try giving it an array with zero or one elements in it for example. You could say that folks shouldn't call it in that case, but you know folks... they like pushing the boundaries. :-)

Perhaps you meant to say that the array can be altered inside the function because it is passed "by value" rather than "by reference", or is that just a mixture of terminology from my C++ upbringing? Passing by reference would imply that you could alter the array inside the function and have that alter its value outside. Passing by value implies that any changes inside the function affect the local function copy only. In PHP, the latter is clearly the case, unless a variable is explicitly declared as global.

OK, that's my 2c.
tshort at cisco dot com 28-Apr-2005 01:54
/*
  english_list()
This one works with anything, since the array is passed by reference, modifying it in the function via pop has no effect on the array outside the function. But it can't be done on one line, because the array_pop() must occur before the join().
*/

function english_list($array, $oxfordComma=0)
{
  $last = array_pop($array);
  return join(", ", $array) . ($oxfordComma ? "," : "") . " and " . $last;
}
Andy Morris 28-Apr-2005 10:19
Similar to a previous note, but this works for any length array, plus also works for arrays with key strings instead of integer keys! I know it's not strictly an implode() example, but it concerns what you might be considering using implode() to help you to do achieve...

<?php
// Return array as a comma separated list; final two elements separated
// by 'and' with an optional "Oxford" comma preceding the 'and'.
function english_list($array, $oxfordComma=0)
{
  $optionalComma = ( $oxfordComma ) ? "," : "";
  $str = "";
  $size = count( $array );
  $i = 0;
  foreach ( $array as $item ) {
    $str .= $item;
    $i++;
    if ( $i < $size - 1) $str .= ", ";
    elseif ( $i == $size - 1) $str .= $optionalComma." and ";
  }
  return $str;
}

// test the comma separated list function
echo english_list( array(), 1 )."<br>";
echo english_list( array("foo"), 1 )."<br>";
echo english_list( array("foo", "bar"), 0 )."<br>";
echo english_list( array("a" => "foo", "b" => "bar", "c" => "foobar"), 1 )."<br>";
echo english_list( array("foo", "bar", "foobar", "barfoo"), 0 )."<br>";
?>
memandeemail at gmail dot com 27-Apr-2005 06:06
/**
     * Like implode but with keys
     *
     * @param string[optional] $glue
     * @param array $pieces
     * @param string[optional] $hifen
     * @return string
     */
    function implode_with_key($glue = null, $pieces, $hifen = ',') {
        $return = null;
        foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
        return substr($return,1);
    }
davidpk212 at gmail dot com 14-Apr-2005 08:36
I made this function to create an english-readable list from an array.

<?php
function english_list($array, $oxfordcomma=1) {
  $count = count($array)-1;
  $last = $array[$count];
  unset($array[$count]);
  $str = join(", ", $array);
  if ($oxfordcomma) {
    $str .= ",";
  }
  $str .= " and $last";

  return $str;
}
?>

The optional parameter "oxfordcomma" indicates whether or not to use the Oxford comma (a comma before the "and").

Example:

<?php
print english_list(array("foo", "bar", "foobar", "barfoo"));
?>
Would produce:

foo, bar, foobar, and barfoo
01-Apr-2005 06:07
Here is another varriation on the below code. This is useful if you are trying to store data as a string to be returned to an array later.  It allows unlimited nested arrays to be both stored and extracted, but does not print out as pretty.

function implode_assoc_r2($inner_glue = "=", $outer_glue = "\n", $recusion_level = 0, $array = null)
{
   $output = array();

   foreach( $array as $key => $item )
       if ( is_array ($item) )
       {
           // This is value is an array, go and do it again!
           $level = $recusion_level + 1;
           $output[] = $key . $inner_glue . $recusion_level . $inner_glue . implode_assoc_r ($inner_glue, $outer_glue, $level, $item, $keepOuterKey);
       }
       else
           $output[] = $key . $inner_glue . $recusion_level . $inner_glue . $item;

   return implode($outer_glue . $recusion_level . $outer_glue, $output);
}

function explode_assoc_r2($inner_glue = "=", $outer_glue = "\n", $recusion_level = 0, $string = null)
{
       $output=array();
       $array=explode($outer_glue.$recusion_level.$outer_glue, $string);

       foreach ($array as $value)
       {
               $row=explode($inner_glue.$recusion_level.$inner_glue,$value);
               $output[$row[0]]=$row[1];
               $level = $recusion_level + 1;
               if(strpos($output[$row[0]],$inner_glue.$level.$inner_glue))
                       $output[$row[0]] = explode_with_keys_a($inner_glue,$outer_glue,$level,$output[$row[0]]);
       }

       return $output;
}
php.net {at} nr78 {dot} net 30-Mar-2005 06:50
Also quite handy in INSERT statements:

<?php

   // array containing data
   $array = array(
      "name" => "John",
      "surname" => "Doe",
      "email" => "j.doe@intelligence.gov"
   );

   // build query...
   $sql  = "INSERT INTO table";

   // implode keys of $array...
   $sql .= " (`".implode("`, `", array_keys($array))."`)";

   // implode values of $array...
   $sql .= " VALUES ('".implode("', '", $array)."') ";

   // execute query...
   $result = mysql_query($sql) or die(mysql_error());

?>
stefan 03-Mar-2005 09:47
Even handier if you use the following:

<?php
$id_nums = array(1,6,12,18,24);

$id_nums = implode(", ", $id_nums);

$sqlquery = "Select name,email,phone from usertable where user_id IN ($id_nums)";

// $sqlquery becomes "Select name,email,phone from usertable where user_id IN (1,6,12,18,24)"
?>
Geoff Eby 03-Mar-2005 08:29
A handy use of implode in a MySQL query

<?php
$id_nums = array(1,6,12,18,24);

$id_nums = implode(" OR user_id=", $id_nums);

$sqlquery = "Select name,email,phone from usertable where user_id=$id_nums";

// $sqlquery becomes "Select name,email,phone from usertable where user_id=1 OR user_id=6 OR user_id=12 OR user_id=18 OR user_id=24"
?>
phpWalter at torres dot ws 14-Sep-2004 11:45
Chris Ross (17-Aug-2004 11:18) gave us a great function 'implode_assoc'.

But it didn't handle multi-level array.

I know, a few others here added this "feature", but...

I've modified Chirs' function to be recursive.

Hope it helps someone.

/**
  * Method to recursivly implode a multi-dimensional array
  * Orginal: Chris Ross - 17-Aug-2004
  * Modified: Walter Torres - 09-14-2004
  **/
function implode_assoc_r($inner_glue = "=", $outer_glue = "\n", $array = null, $keepOuterKey = false)
{
    $output = array();

    foreach( $array as $key => $item )
        if ( is_array ($item) )
        {
            if ( $keepOuterKey )
                $output[] = $key;

            // This is value is an array, go and do it again!
            $output[] = implode_assoc_r ($inner_glue, $outer_glue, $item, $keepOuterKey);
        }
        else
            $output[] = $key . $inner_glue . $item;

    return implode($outer_glue, $output);
}
Chris Ross 17-Aug-2004 11:18
I took static's implode_with_keys, and converted into something I considered a little more programatically useful.  I would argue that this sort of functionality should maybe be added to PHP.

<?php
/* This isn't really DB function, but it's general...  This will */
/* act like the PHP implode() function, but for assoc. arrays... */
function implode_assoc($inner_glue, $outer_glue, $array) {
        $output = array();
        foreach( $array as $key => $item )
                $output[] = $key . $inner_glue . $item;

        return implode($outer_glue, $output);
}
?>

  It's the same as static's, really, but allows you to join the keys to the values with any arbitrary string, rather than hard-coding a '='.
john 26-Apr-2004 02:15
hi,
to prevent implode from putting the zero at the end, I use ksort().

example:

$val[1]="one";
$val[2]="two";
$val[0]="zero";
ksort($val);
echo implode(":",$val);
//will return "zero:one:two"
chris at hitcatcher dot com 28-Oct-2003 01:50
I found it neccesary to create a function that joins the contents of a single dimension from a 2-d array. Here's the code in case anyone else should need to do the same:

<?php
function join_2d($glue, $pieces, $dimension = 0){
    //joins the values of a single dimension in a 2-d array
    $rtn = array();
    foreach($piece as $key => $value){
        if(isset($value[$dimension])){
            $rtn[] = $value[$dimension];
        }
    }
    return join($glue, $rtn);
}
?>

The dimension argument can be a positive integer or a named index. Here is an example:

<?php
$testarray = array(array(1 => 'a', 'three' => 1),
                          array(1 => 'b', 'three' => 2),
                          array(1 => 'c', 'three' => 3),
                          array(1 => 'd', 'three' => 4),
                          array(1 => 'e', 'three' => 5));

print "<pre>"; print_r($testarray); print "</pre>";
print join_2d(", ", $testarray, 1) . "<br>";
print join_2d(", ", $testarray, 'three') . "<br>";
?>
dan at danposluns dot com 23-Aug-2003 11:04
*** MULTI-DIMENSIONAL ARRAY IMPLODE ***

First of all, it should be noted that the function in the previous note is not technically correct, as it glues the outside of the first piece. This is the problem faced by any function that wants to construct a set out of an array without the overhead of handling the boundary indexes. It also doesn't preserve the dimensional architecture.

Use this function when you want to call implode() on a multi-dimensional array and want the resulting string to preserve the architecture of the different dimensions. For example:

array ( 5, array (2, 4, 6), array (3, 6, 9, array (12)))

would be reduced to:

[ 5, [ 2, 4, 6 ], [ 3, 6, 9, [ 12 ] ] ]

Note that this does not preserve key values. If you need those, you are probably better off using serialize() and then replacing the tokens with your own symbols using the string functions.

Anyway, here is the code:

function mdImpode($x, $y)
{
    $a = (is_array($x)) ? '[ ' . array_reduce($x, 'mdImplode') . ' ]' : $x;
    $b = (is_array($y)) ? '[ ' . array_reduce($y, 'mdImplode') . ' ]' : $y;
    return $a . ', ' . $b;
}

Then to call it, use:

$result = '[ ' . array_reduce($pieces, 'mdImplode') . ' ]';

Note that you have to make manual changes if you want different glue or set symbols. There may be a more elegant solution, but this should be a good compromise between efficiency and simplicity (the manual says that array_reduce is iterative, so this should be pretty speedy).
gregrahkin 19-Jun-2003 10:10
This function will implode a multi-dimension array

function implode_r ($glue, $pieces){
 $out = "";
 foreach ($pieces as $piece)
  if (is_array ($piece)) $out .= implode_r ($glue, $piece); // recurse
  else                   $out .= $glue.$piece;

 return $out;
 }
james at globalmegacorp dot org 30-May-2003 07:13
As a followup to the implode_with_keys function posted by 'static', here's a corresponding explode_with_keys function I wrote:

function explode_with_keys($seperator, $string)
{
        $output=array();
        $array=explode($seperator, $string);
        foreach ($array as $value) {
                $row=explode("=",$value);
                $output[$row[0]]=$row[1];
        }
        return $output;
}
ulderico at maber dot com dot br 07-Oct-2002 10:39
'Implode' does not implodes recursively... It might quite useful implode recursively when you get a many Arrays values with keys that replaces themselves as:

http://server/file.php?arg[1]=123&arg[2]=312&arg[3]=543&arg[2]=abc

If you build this URL progressively it would a great a idea that the newest value indeed took the place of any older ones, thus:

http://server/file.php?arg[1]=123&arg[3]=543&arg[2]=abc

would be a better option;

If one uses $_SERVER['REQUEST_URI'], this sanitation would not happen, the URL string would be greater and greater everytime.

With implode_r (see below) it becomes easier to build a "sanitised" URL, the one that less likely will overflow the browser.

$URL = $_SERVER['PHP_SELF'];
$tmp = implode_r("&", $_REQUEST); /* So as to allow to get ANY VALUE (G/P) from the Browser... */
$URL .= "?".$tmp;

/* implode_r */
function implode_r($glue, $array, $array_name = NULL){
while(list($key,$value) = @each($array))
if(is_array($value))
                        $return[] = implode_r($glue, $value, (string) $key);
                else
                        if($array_name != NULL)
                                $return[] = $array_name."[".(string) $key."]=".$value;
                        else
                                $return[] = $key."=".$value;

        return(implode($glue, $return));
}
sorry I couldn't format the code.
Cedric at isoca dot com 11-Jul-2002 10:39
Implode with an unset array will made a warning and fail, but is ok with an empty array.
So if you don't trust the content of the array, allways initialize it before :
  $param = array();
  [...]
  echo implode('&', $param);
static 14-May-2002 12:43
The one thing missing with this function is a way to add the keys. So I wrote this little function:

function implode_with_keys($glue, $array) {
        $output = array();
        foreach( $array as $key => $item )
                $output[] = $key . "=" . $item;

        return implode($glue, $output);
}
php at woodenpickle dot com 14-Mar-2002 10:55
Hey, I found a good use for implode() today. It came from a need to have a <select name=state multiple> box on the page that a person could select multiple states from and send those to a >SELECT * FROM customers WHERE state='$state'; query. But they need to be able to send just one state also. Well, I changes the html select box to say <select name=state[] multiple>. This turns $state into an array as you may know. I then, later on in the script, did this:

$count = count( $state );
if( $count > 1 ) {
     $states = implode( "'.'", $state );
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date <=$to AND state IN ('$states')" );
}

//This takes care of multiple states, but if the user sent only one state, I catch it here:

foreach( $state as $value );
if( $value )
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date<=$to AND state='$value'" );
else //This one will catch the ALL states option if they choose that.
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date<=$to" );

Anyway, I thought I'd post this up here in case it might help someone. Or maybe someone could figure out a better way and enlighten us all.. Have fun.. Bob
htmlspecialchars
join
Обработка строк


Псевдоним implode

implode
lcfirst
Обработка строк
PHP Manual

join

(PHP 4, PHP 5)

join — Псевдоним implode()

Описание

Эта функция является псевдонимом: implode().

User Contributed Notes

John 28-May-2012 10:42
An example of table join.

<?php
$conn = mysql_connect("localhost", "username", "password");
mysql_select_db("database name", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "select * from consumer, application where consumer.consumernum = application.consumernum and applicationnum = $variable";
$rs = mysql_query($sql, $conn)
or die ('Issue arose with query' . mysql_error());
?>
datacompboy at call2ru dot com 21-Feb-2009 09:43
Very useful function i have using: joinr (join-recursive).
It allows you easy join of multi-level arrays.
For example, if you have
  $intervals = array(array(5, 9), array(11, 15), array(22, 24))
and want to have comma-separated list of dash-separated intervals, just do
  print joinr(array(",","-"), $intervals);

Here is function code:
<?php
    function joinr($join, $value, $lvl=0)
    {
        if (!is_array($join)) return joinr(array($join), $value, $lvl);
        $res = array();
        if (is_array($value)&&sizeof($value)&&is_array(current($value))) { // Is value are array of sub-arrays?
            foreach($value as $val)
                $res[] = joinr($join, $val, $lvl+1);
        }
        elseif(is_array($value)) {
            $res = $value;
        }
        else $res[] = $value;
        return join(isset($join[$lvl])?$join[$lvl]:"", $res);
    }
?>
manbss at yahoo dot co dot in 09-May-2007 09:38
<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = join(",", $array);

echo $comma_separated; // lastname,email,phone

?>
implode
lcfirst
Обработка строк


Преобразует первый символ строки в нижний регистр

join
levenshtein
Обработка строк
PHP Manual

lcfirst

(PHP 5 >= 5.3.0)

lcfirst — Преобразует первый символ строки в нижний регистр

Описание

string lcfirst ( string $str )

Возвращает строку str, первый символ которой был преобразован в нижний регистр, если этот символ является буквой.

Принадлежность того или иного символа к буквенным определяется с учетом текущей локали. Это означает, что, например, в используемой по умолчанию локали "C", символ ä не будет преобразован.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает результирующую строку.

Примеры

Пример #1 Пример использования lcfirst()

<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo);             // helloWorld

$bar = 'HELLO WORLD!';
$bar = lcfirst($bar);             // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>

Смотрите также

  • ucfirst() - Преобразует первый символ строки в верхний регистр
  • strtolower() - Преобразует строку в нижний регистр
  • strtoupper() - Преобразует строку в верхний регистр
  • ucwords() - Преобразует в верхний регистр первый символ каждого слова в строке

User Contributed Notes

phpnet at katylavallee dot com 02-Apr-2009 08:50
Easiest work-around I've found for <5.3:
<?php

$string = "CamelCase"
$string{0} = strtolower($string{0})
echo $string; // outputs camelCase

?>
ahlers_wim at hotmail dot com 22-Nov-2008 09:48
As of PHP release 6 direct reference modification is not permitted any more.
Reference modification is the process of manipulating characters within a string by means of the instruction such as:
$str[0] in the code line: $str[0] = strtolower($str[0]);

For this reason I have recoded the lcfirst function (on function_exists('lcfirst') === false) as follows:

<?php
if ( false === function_exists('lcfirst') ):
    function lcfirst( $str )
    { return (string)(strtolower(substr($str,0,1)).substr($str,1));}
endif;
?>

Remarks:
Also notice that I have used the more modern scope delimeters (if:-endif;) and I have also removed the unnecessary intermediate result. That is, the manipulation is returned directly.
alex aulbach 06-Oct-2008 09:20
In some cases maybe more useful?

 $lower = strtolower( substr($upper,0,1) ) . substr($upper,1);
harmor 05-May-2008 03:43
A slight modification from Northie's post here ( http://us2.php.net/manual/en/function.ucfirst.php#68443), where lcfirst may not exist in your PHP build:

<?php

if(false === function_exists('lcfirst'))
{
    /**
     * Make a string's first character lowercase
     *
     * @param string $str
     * @return string the resulting string.
     */
    function lcfirst( $str ) {
        $str[0] = strtolower($str[0]);
        return (string)$str;
    }
}

/* Tests */
echo var_dump(lcFirst(NULL)).'<br />';    /* string(0) ""  */
echo var_dump(lcFirst(''))  .'<br />';    /* string(0) ""  */
echo var_dump(lcFirst('S')) .'<br />';    /* string(1) "S" */
echo var_dump(lcFirst('É')) .'<br />';    /* string(0) "�" */
echo var_dump(lcFirst('Hello World!!!')); /* string(14) "hello World!!!"  */
join
levenshtein
Обработка строк


Вычисляет расстояние Левенштейна между двумя строками

lcfirst
localeconv
Обработка строк
PHP Manual

levenshtein

(PHP 4 >= 4.0.1, PHP 5)

levenshtein — Вычисляет расстояние Левенштейна между двумя строками

Описание

int levenshtein ( string $str1 , string $str2 )
int levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del )

Расстояние Левенштейна - это минимальное количество вставок, замен и удалений символов, необходимое для преобразования str1 в str2. Сложность алгоритма равна O(m*n), где n и m - длины строк str1 и str2 (неплохо по сравнению с similar_text(), имеющей сложность O(max(n,m)**3), но все же довольно много).

В простейшей форме функция принимает в качестве аргументов две строки и возвращает минимальное количество вставок, замен и удалений символов, необходимое для преобразования str1 в str2.

Второй вариант принимает три дополнительных аргумента, задающих стоимость операций вставки, замены и удаления. Этот вариант универсальнее первого, но не так эффективен.

Список параметров

str1

Одна из строк, для которых вычисляется расстояние Левенштейна.

str2

Одна из строк, для которых вычисляется расстояние Левенштейна.

cost_ins

Определяет стоимость вставки.

cost_rep

Определяет стоимость замены.

cost_del

Определяет стоимость удаления.

Возвращаемые значения

Эта функция возвращает расстояние Левенштейна между двумя строками, или -1, если хотя бы одна из строк длиннее 255 символов.

Примеры

Пример #1 Пример использования levenshtein()

<?php
// введенное слово с опечаткой
$input = 'carrrot';

// массив сверяемых слов
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// кратчайшее расстояние пока еще не найдено
$shortest = -1;

// проходим по словам для нахождения самого близкого варианта
foreach ($words as $word) {

    // вычисляем расстояние между входным словом и текущим
    $lev = levenshtein($input, $word);

    // проверяем полное совпадение
    if ($lev == 0) {

        // это ближайшее слово (точное совпадение)
        $closest = $word;
        $shortest = 0;

        // выходим из цикла - мы нашли точное совпадение
        break;
    }

    // если это расстояние меньше следующего наименьшего расстояния
    // ИЛИ если следующее самое короткое слово еще не было найдено
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Вы ввели: $input\n";
if ($shortest == 0) {
    echo "Найдено точное совпадение: $closest\n";
} else {
    echo "Вы не имели в виду: $closest?\n";
}

?>

Результат выполнения данного примера:

Вы ввели: carrrot
Вы не имели в виду: carrot?

Смотрите также

  • soundex() - Возвращает ключ soundex для строки
  • similar_text() - Вычисляет степень похожести двух строк
  • metaphone() - Возвращает ключ metaphone для строки

User Contributed Notes

engineglue at gmail dot com 08-Jan-2012 08:05
I really like [the manual's] example for the use of the levenshtein function to match against an array. I ran into the need to specify the sensitivity of the result. There are circumstances when you want it to return false if the match is way out of line. I wouldn't want "marry had a little lamb" to match with "saw viii" simply because it was the best match in the array. Hence the need for sensitivity:

<?php
    function wordMatch($words, $input, $sensitivity){
        $shortest = -1;
        foreach ($words as $word) {
            $lev = levenshtein($input, $word);
            if ($lev == 0) {
                $closest = $word;
                $shortest = 0;
                break;
            }
            if ($lev <= $shortest || $shortest < 0) {
                $closest  = $word;
                $shortest = $lev;
            }
        }
        if($shortest <= $sensitivity){
            return $closest;
        } else {
            return 0;
        }
    }

    $word = 'PINEEEEAPPLE';

    $words  = array('apple','pineapple','banana','orange',
                    'radish','carrot','pea','bean','potato');

    echo wordMatch($words, strtolower($word), 2);
?>
Chaim Chaikin 02-Nov-2011 11:40
As regards to Example #1 above, would it not be more efficient to first use a simple php == comparison to check if the strings are equal even before testing the word with levenshtein().

Something like this:

<?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // check for an exact match
    if ($input == $word) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?>
andrejs at gmail 24-Nov-2010 06:38
A ported version of the memory efficient implementation by Sten Hjelmqvist at http://www.codeproject.com/KB/recipes/Levenshtein.aspx - works 1.5x faster than previous versions posted here (44s vs 63s on 2.5KB strings). If you don't care about UTF, you can substitute mb_substr for array-like access and get even faster (24s on the same test set).

I also added trimming of common beginning and end so you can save up to 99% more time — in case of small edits inside large texts.

<?php

function levenshteinDistance2($str1, $str2)
{
    $len1 = mb_strlen($str1);
    $len2 = mb_strlen($str2);

    // strip common prefix
    $i = 0;
    do {
        if(mb_substr($str1, $i, 1) != mb_substr($str2, $i, 1))
            break;
        $i++;
        $len1--;
        $len2--;
    } while($len1 > 0 && $len2 > 0);
    if($i > 0) {
        $str1 = mb_substr($str1, $i);
        $str2 = mb_substr($str2, $i);
    }

    // strip common suffix
    $i = 0;
    do {
        if(mb_substr($str1, $len1-1, 1) != mb_substr($str2, $len2-1, 1))
            break;
        $i++;
        $len1--;
        $len2--;
    } while($len1 > 0 && $len2 > 0);
    if($i > 0) {
        $str1 = mb_substr($str1, 0, $len1);
        $str2 = mb_substr($str2, 0, $len2);
    }

    if ($len1 == 0)
        return $len2;
    if ($len2 == 0)
        return $len1;

    $v0 = range(0, $len1);
    $v1 = array();

    for ($i = 1; $i <= $len2; $i++) {
        $v1[0] = $i;
        $str2j = mb_substr($str2, $i - 1, 1);

        for ($j = 1; $j <= $len1; $j++) {
            $cost = (mb_substr($str1, $j - 1, 1) == $str2j) ? 0 : 1;

            $m_min = $v0[$j] + 1;
            $b = $v1[$j - 1] + 1;
            $c = $v0[$j - 1] + $cost;

            if ($b < $m_min)
                $m_min = $b;
            if ($c < $m_min)
                $m_min = $c;

            $v1[$j] = $m_min;
        }

        $vTmp = $v0;
        $v0 = $v1;
        $v1 = $vTmp;
    }

    return $v0[$len1];
}

?>
paulroweatinamedotcom 22-Nov-2008 08:57
Once again, some testing (with thanks to Tiago) showed me that there was still an error in the code.  It wasn't coming up with the right distance when a deletion was involved.  This is because there was an error in the way that the distance array was instantiated.  (Also, my thanks to the editor for making this easier on everyone involved.)

<?php
/*
* This function starts out with several checks in an attempt to save time.
*   1.  The shorter string is always used as the "right-hand" string (as the size of the array is based on its length).
*   2.  If the left string is empty, the length of the right is returned.
*   3.  If the right string is empty, the length of the left is returned.
*   4.  If the strings are equal, a zero-distance is returned.
*   5.  If the left string is contained within the right string, the difference in length is returned.
*   6.  If the right string is contained within the left string, the difference in length is returned.
* If none of the above conditions were met, the Levenshtein algorithm is used.
*/
  function LevenshteinDistance($s1, $s2)
  {
    $nLeftLength = strlen($s1);
    $nRightLength = strlen($s2);
    if ($nLeftLength >= $nRightLength)
    {
      $sLeft = $s1;
      $sRight = $s2;
    } else {
      $sLeft = $s2;
      $sRight = $s1;
      $nLeftLength += $nRightLength;  //  arithmetic swap of two values
      $nRightLength = $nLeftLength - $nRightLength;
      $nLeftLength -= $nRightLength;
    }
    if ($nLeftLength == 0)
      return $nRightLength;
    else if ($nRightLength == 0)
      return $nLeftLength;
    else if ($sLeft === $sRight)
      return 0;
    else if (($nLeftLength < $nRightLength) && (strpos($sRight, $sLeft) !== FALSE))
      return $nRightLength - $nLeftLength;
    else if (($nRightLength < $nLeftLength) && (strpos($sLeft, $sRight) !== FALSE))
      return $nLeftLength - $nRightLength;
    else {
      $nsDistance = range(0, $nRightLength);
      for ($nLeftPos = 1; $nLeftPos <= $nLeftLength; ++$nLeftPos)
      {
        $cLeft = $sLeft[$nLeftPos - 1];
        $nDiagonal = $nLeftPos - 1;
        $nsDistance[0] = $nLeftPos;
        for ($nRightPos = 1; $nRightPos <= $nRightLength; ++$nRightPos)
        {
          $cRight = $sRight[$nRightPos - 1];
          $nCost = ($cRight == $cLeft) ? 0 : 1;
          $nNewDiagonal = $nsDistance[$nRightPos];
          $nsDistance[$nRightPos] =
            min($nsDistance[$nRightPos] + 1,
                $nsDistance[$nRightPos - 1] + 1,
                $nDiagonal + $nCost);
          $nDiagonal = $nNewDiagonal;
        }
      }
      return $nsDistance[$nRightLength];
    }
  }
?>
paulrowe at iname dot com 27-Aug-2008 05:58
[EDITOR'S NOTE: original post and 2 corrections combined into 1 -- mgf]

Here is an implementation of the Levenshtein Distance calculation that only uses a one-dimensional array and doesn't have a limit to the string length. This implementation was inspired by maze generation algorithms that also use only one-dimensional arrays.

I have tested this function with two 532-character strings and it completed in 0.6-0.8 seconds.

<?php
/*
* This function starts out with several checks in an attempt to save time.
*   1.  The shorter string is always used as the "right-hand" string (as the size of the array is based on its length).
*   2.  If the left string is empty, the length of the right is returned.
*   3.  If the right string is empty, the length of the left is returned.
*   4.  If the strings are equal, a zero-distance is returned.
*   5.  If the left string is contained within the right string, the difference in length is returned.
*   6.  If the right string is contained within the left string, the difference in length is returned.
* If none of the above conditions were met, the Levenshtein algorithm is used.
*/
function LevenshteinDistance($s1, $s2)
{
  $sLeft = (strlen($s1) > strlen($s2)) ? $s1 : $s2;
  $sRight = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
  $nLeftLength = strlen($sLeft);
  $nRightLength = strlen($sRight);
  if ($nLeftLength == 0)
    return $nRightLength;
  else if ($nRightLength == 0)
    return $nLeftLength;
  else if ($sLeft === $sRight)
    return 0;
  else if (($nLeftLength < $nRightLength) && (strpos($sRight, $sLeft) !== FALSE))
    return $nRightLength - $nLeftLength;
  else if (($nRightLength < $nLeftLength) && (strpos($sLeft, $sRight) !== FALSE))
    return $nLeftLength - $nRightLength;
  else {
    $nsDistance = range(1, $nRightLength + 1);
    for ($nLeftPos = 1; $nLeftPos <= $nLeftLength; ++$nLeftPos)
    {
      $cLeft = $sLeft[$nLeftPos - 1];
      $nDiagonal = $nLeftPos - 1;
      $nsDistance[0] = $nLeftPos;
      for ($nRightPos = 1; $nRightPos <= $nRightLength; ++$nRightPos)
      {
        $cRight = $sRight[$nRightPos - 1];
        $nCost = ($cRight == $cLeft) ? 0 : 1;
        $nNewDiagonal = $nsDistance[$nRightPos];
        $nsDistance[$nRightPos] =
          min($nsDistance[$nRightPos] + 1,
              $nsDistance[$nRightPos - 1] + 1,
              $nDiagonal + $nCost);
        $nDiagonal = $nNewDiagonal;
      }
    }
    return $nsDistance[$nRightLength];
  }
}
?>
luka8088 at gmail dot com 28-May-2008 01:03
Simple levenshtein function without string length limit ...

<?php

function levenshtein2($str1, $str2, $cost_ins = null, $cost_rep = null, $cost_del = null) {
    $d = array_fill(0, strlen($str1) + 1, array_fill(0, strlen($str2) + 1, 0));
    $ret = 0;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        $d[$i][0] = $i;
    for ($j = 1; $j < strlen($str2) + 1; $j++)
        $d[0][$j] = $j;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        for ($j = 1; $j < strlen($str2) + 1; $j++) {
            $c = 1;
            if ($str1{$i - 1} == $str2{$j - 1})
                $c = 0;
            $d[$i][$j] = min($d[$i - 1][$j] + 1, $d[$i][$j - 1] + 1, $d[$i - 1][$j - 1] + $c);
            $ret = $d[$i][$j];
        }

    return $ret;
}

?>
atx dot antrax at gmail dot com 17-Apr-2008 02:42
I have made a function that removes the length-limit of levenshtein function and ajust the result with similar_text:

<?php
function _similar($str1, $str2) {
    $strlen1=strlen($str1);
    $strlen2=strlen($str2);
    $max=max($strlen1, $strlen2);

    $splitSize=250;
    if($max>$splitSize)
    {
        $lev=0;
        for($cont=0;$cont<$max;$cont+=$splitSize)
        {
            if($strlen1<=$cont || $strlen2<=$cont)
            {
                $lev=$lev/($max/min($strlen1,$strlen2));
                break;
            }
            $lev+=levenshtein(substr($str1,$cont,$splitSize), substr($str2,$cont,$splitSize));
        }
    }
    else
    $lev=levenshtein($str1, $str2);

    $porcentage= -100*$lev/$max+100;
    if($porcentage>75)//Ajustar con similar_text
    similar_text($str1,$str2,$porcentage);

    return $porcentage;
}
?>
dale3h 12-Feb-2008 08:52
Using PHP's example along with Patrick's comparison percentage function, I have come up with a function that returns the closest word from an array, and assigns the percentage to a referenced variable:

<?php
  function closest_word($input, $words, &$percent = null) {
    $shortest = -1;
    foreach ($words as $word) {
      $lev = levenshtein($input, $word);

      if ($lev == 0) {
        $closest = $word;
        $shortest = 0;
        break;
      }

      if ($lev <= $shortest || $shortest < 0) {
        $closest  = $word;
        $shortest = $lev;
      }
    }

    $percent = 1 - levenshtein($input, $closest) / max(strlen($input), strlen($closest));

    return $closest;
  }
?>

Usage:
<?php
  $input = 'carrrot';
  $words = array('apple','pineapple','banana','orange',
                 'radish','carrot','pea','bean','potato');

  $percent = null;
  $found = closest_word($input, $words, $percent);

  printf('Closest word to "%s": %s (%s%% match)', $input, $found, round($percent * 100, 2));
?>

I found that lowercasing the array prior to comparing yields a better comparison when the case is not of importance, for example: comparing a user-inputted category to a list of existing categories.

I also found that when the percentage was above 75%, it was usually the match that I was looking for.
Patrick Palka 08-Apr-2007 02:47
To find the comparison percentage of levenshtein, use this function:

<?php
function _levenshtein($str1, $str2) {
    return 1-levenshtein($str1, $str2)/max(strlen($str1), strlen($str2));
}

echo _levenshtein('dogs', 'cats'); //.25

This function (along with levenshtein) is obsolete though: similar_text is 20% faster that the two.
?>
Paul 02-Mar-2007 10:47
@ ivo_gelov at gmx dot net

Your implementation of Myers' algorithm is not entirely correct. The algorithm finds the end of a match, but you still need to find the start of a match. The easiest way to find the start of a match is to execute the algorithm again on the reversed string, starting at the j'th character. You can't just assume the start of the match is at j - m because you don't know whether the match is longer, shorter, or of equal length.

Just my 2 cents.
ivo_gelov at gmx dot net 30-Oct-2006 07:03
Here is a small function to implement a fuzzy search.
If someone is wondering about the mathematics inside, this information can be found in "A fast bit-vector algorithm for approximate string matching based on dynamic programming" by Gene Myers, May 27 1998

<?php
// This can search for PATTERN into HAYSTACK with MIST mistaken symbols in PATTERN
// OK_MATCH is a function ($Position, $Score)
// Position is zero-based index in HAYSTACK, where PATTERN is found,
// and Score is the number of mistaken symbols
function FuzzyLook($pattern,$haystack,$mist,$ok_match)
{
    $m = strlen($pattern);
    $n = strlen($haystack);
    if($n==0 OR $m==0) return;
    // Precompute Peq[Z]
  for($i=0; $i<32; $i++) $Bit[$i] = (1 << $i);
    for($i=0; $i<$m; $i++) $Peq[ ord(substr($pattern,$i,1)) ] |= $Bit[$i];

    $Pv = 0xFFFFFFFF;
    $Mv = 0;
    $Score = $m;

    for($j=0; $j<$n; $j++)
    {
        $Eq = $Peq[ ord(substr($haystack,$j,1))];
        $Xv = $Eq | $Mv;
        $Xh = ((($Eq & $Pv) + $Pv) ^ $Pv) | $Eq;
        $Ph = $Mv | ~ ($Xh | $Pv);
        $Mh = $Pv & $Xh;
        if($Ph & (1 << ($m-1))) $Score += 1;
        elseif($Mh & (1 << ($m-1))) $Score -= 1;
        $Ph <<= 1;
        $Pv = ($Mh << 1) | ~ ($Xv | $Ph);
        $Mv = $Ph & $Xv;
        if($Score <= $mist && $j>=$m-1) $ok_match($j-$m+1,$Score);
    }
}

?>
carey at NOSPAM dot internode dot net dot au 28-Oct-2006 07:06
I have found that levenshtein is actually case-sensitive (in PHP 4.4.2 at least).

<?php
$distance=levenshtein('hello','ELLO');
echo "$distance";
?>

Outputs: "5", instead of "1". If you are implementing a fuzzy search feature that makes use of levenshtein, you will probably need to find a way to work around this.
dinesh AT dinsoft DOT net 17-Mar-2006 03:18
Here is a string resynch function:

<?php
// Trouve les operations a effectuer pour modifier $b en $a en exploitant leurs similitudes (Finds the operations required to change $b to $a)
// Identique a la fonction Resynch Compare de Hex Workshop
//
// Parametres:
//      $a Premiere chaine (cible, target)
//      $b Seconde chaine (source)
//      $l Nombre d'octets devant correspondre pour etre consides comme un bloc similaire (number of matching bytes required)
//      $s Distance maximale dans laquelle les blocs similaires sont cherches (search window)
//
// Retourne:
//      Array
//              Array
//                      [0] Operation: + Add , - Del , / Replace, = Match
//                      [1] Source offset
//                      [2] Source count
//                      [3] Target offset
//                      [4] Target count
//
function str_resynch($a,$b,$l=32,$s=2048) {
        $r=array();
        for($i=0,$c=strlen($a),$cc=strlen($b),$ii=0,$z=$s-1,$z2=($z<<1)+1; $i<$c; $i++) {
                $d=$i-$z;
                $d=($d<$ii)?substr($b,$ii,$z2-$ii+$d):substr($b,$d,$z2);

                $p=strpos($d,$a{$i});
                $n=0;
                while ($p!==FALSE) {
                        $m=1;
                        $bi=$i;
                        $bp=$p;
                        $p+=$ii;
                        while ((++$i<$c) && (++$p<$cc)) {
                                if ($a{$i}!=$b{$p}) break;
                                $m++;
                        }
                        if ($m<$l) {
                                $i=$bi;
                                $n=$bp+1;
                                $p=@strpos($d,$a{$i},$n);
                        }
                        else {
                                $i--;
                                $r[]=array($bi,$bp+$ii,$m); // offset a, offset b, Count
                                $ii=$p;
                                break;
                        }
                }
        }

        if (!count($r)) return ($cc)?array('/',0,$c,0,$cc):array(array('+',0,$c,0,0));

        $o=array();
        $bi=0;
        $bp=0;
        for($i=0,$m=count($r);$i<$m;$i++) {
                if ($r[$i][0]!=$bi) {
                        if ($r[$i][1]!=$bp) {
                                // Replace
                                $o[]=array('/',$bi,$r[$i][0]-$bi,$bp,$r[$i][1]-$bp);
                                $bi=$r[$i][0];
                                $bp=$r[$i][1];
                        }
                        else {
                                // Insertion
                                $o[]=array('+',$bi,$r[$i][0]-$bi,$bp,0);
                                $bi=$r[$i][0];
                        }
                }
                elseif ($r[$i][1]!=$bp) {
                        // Delete
                        $o[]=array('-',$bi,0,$bp,$r[$i][1]-$bp);
                        $bp=$r[$i][1];
                }

                // Match
                $o[]=array('=',$r[$i][0],$r[$i][2],$r[$i][1],$r[$i][2]);
                $bi+=$r[$i][2];
                $bp+=$r[$i][2];
        }

        if ($c!=$bi) {
                if ($cc!=$bp) $o[]=array('/',$bi,$c-$bi,$bp,$cc-$bp);
                else $o[]=array('+',$bi,$c-$bi,$bp,0);
        }
        elseif ($cc!=$bp) $o[]=array('-',$bi,0,$bp,$cc-$bp);

        return $o;
}
?>
june05 at tilo-hauke dot de 06-Jun-2005 12:44
//levenshtein for arrays
function array_levenshtein($array1,$array2)
         {   $aliases= array_flip(array_values(array_unique(array_merge($array1,$array2))));
             if(count($aliases)>255) return -1;
             $stringA=''; $stringB='';
             foreach($array1 as $entry) $stringA.=chr($aliases[$entry]);
             foreach($array2 as $entry) $stringB.=chr($aliases[$entry]);
             return levenshtein($stringA,$stringB);
         }

// e.g. use array_levenshtein to detect special expressions in unser-inputs

echo array_levenshtein(split(" ", "my name is xxx"), split(" ","my name is levenshtein"));

//output: 1
justin at visunet dot ie 05-Apr-2005 07:46
<?php

    /*********************************************************************
    * The below func, btlfsa, (better than levenstien for spelling apps)
    * produces better results when comparing words like haert against
    * haart and heart.
    *
    * For example here is the output of levenshtein compared to btlfsa
    * when comparing 'haert' to 'herat, haart, heart, harte'
    *
    * btlfsa('haert','herat'); output is.. 3
    * btlfsa('haert','haart'); output is.. 3
    * btlfsa('haert','harte'); output is.. 3
    * btlfsa('haert','heart'); output is.. 2
    *
    * levenshtein('haert','herat'); output is.. 2
    * levenshtein('haert','haart'); output is.. 1
    * levenshtein('haert','harte'); output is.. 2
    * levenshtein('haert','heart'); output is.. 2
    *
    * In other words, if you used levenshtein, 'haart' would be the
    * closest match to 'haert'. Where as, btlfsa sees that it should be
    * 'heart'
    */

    function btlfsa($word1,$word2)
    {
        $score = 0;

        // For each char that is different add 2 to the score
        // as this is a BIG difference

        $remainder  = preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word1)."]/i",'',$word2);
        $remainder .= preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word2)."]/i",'',$word1);
        $score      = strlen($remainder)*2;

        // Take the difference in string length and add it to the score
        $w1_len  = strlen($word1);
        $w2_len  = strlen($word2);
        $score  += $w1_len > $w2_len ? $w1_len - $w2_len : $w2_len - $w1_len;

        // Calculate how many letters are in different locations
        // And add it to the score i.e.
        //
        // h e a r t
        // 1 2 3 4 5
        //
        // h a e r t     a e        = 2
        // 1 2 3 4 5   1 2 3 4 5
        //

        $w1 = $w1_len > $w2_len ? $word1 : $word2;
        $w2 = $w1_len > $w2_len ? $word2 : $word1;

        for($i=0; $i < strlen($w1); $i++)
        {
            if ( !isset($w2[$i]) || $w1[$i] != $w2[$i] )
            {
                $score++;
            }
        }

        return $score;
    }

    // *************************************************************
    // Here is a full code example showing the difference

    $misspelled = 'haert';

    // Imagine that these are sample suggestions thrown back by soundex or metaphone..
    $suggestions = array('herat', 'haart', 'heart', 'harte');

    // Firstly order an array based on levenshtein
    $levenshtein_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $levenshtein_ordered[$suggestion] = levenshtein($misspelled,$suggestion);
    }
    asort($levenshtein_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by levenshtein...</b><ul><pre>";
    print_r($levenshtein_ordered);
    print "</pre></ul>";

    // Secondly order an array based on btlfsa
    $btlfsa_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $btlfsa_ordered[$suggestion] = btlfsa($misspelled,$suggestion);
    }
    asort($btlfsa_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by btlfsa...</b><ul><pre>";
    print_r($btlfsa_ordered);
    print "</pre></ul>";

?>
mcreuzer at r-world dot com 07-Mar-2005 09:01
I am using the Levenshtein distance to SORT my search results.

I have a search page for peoples names. I do a SOUNDEX() search on the name in mysql. MySQL SOUNDEX() will perform the "fuzzy" search for me.

I then calculate the Levenshtein distance between the search term and the actual name found by the SOUNDEX() search. This will give me a score on how close my results are to the search string.

I can the sort my results for display listing the closest results first.

<?php
// PHP CODE INCLUDING DB LOOKUPS HERE
    usort($searchresults, "finallevenshteinsortfunction");

function finallevenshteinsortfunction($a, $b)
{
    if(($a['levenshtein'] > $b['levenshtein']) || ( $a['levenshtein'] == $b['levenshtein'] && strnatcasecmp( $a['Last_Name'], $b['Last_Name']) >= 1) ){ return $a['levenshtein'];} // Ok... The levenstein is greater OR with the same levenshtein, the last name is alphanumerically first
    elseif($a['levenshtein'] == $b['levenshtein']){ return '0';} // The levenstein matches
    elseif($a['levenshtein'] < $b['levenshtein']){ return -$a['levenshtein'];}
    else{die("<!-- a horrable death -->");}
}
?>
silas at silaspalmer dot com 28-Feb-2004 02:52
Some code for a basic fuzzy search.

<?php

$needle = "Youser Nein stitched tymes hand";
$haystack = "
    Did you know that a stitch in time can save nine. Isn't that amazing! I think so
    The user-supplied function has to return the loser, from the sand. Describe the cost for this particular operation.
    Eweser may decide to use only some of the supplied nans. And pay attention. This isn't hard...
    ";

// explode into words
$hwords = preg_split("/[\s\W]+/", $haystack);
$nwords = preg_split("/[\s\W]+/", $needle);

echo "You searched for $needle<br>";
echo "I found...<br>";

foreach ($hwords as $hkey => $hayword) {
    $hmp = metaphone ($hayword);

    foreach ($nwords as $nkey => $needword) {

    // First or last letters of needle and haystack have to match (case insensitive)
    $nfirst = strtolower(substr($needword, 0, 1));
    $nlast = strtolower(substr($needword, -1));
    $hfirst = strtolower(substr($hayword, 0, 1));
    $hlast = strtolower(substr($hayword, -1));

    if (($hfirst == $nfirst) or ($hlast == $nlast)) {

        $nmp = metaphone ($needword);
        $distance = levenshtein ($hmp, $nmp);
        // $distance = levenshtein ($hayword, $needword);
        $n_len = strlen($nmp);
        $per = round(($distance/$n_len)*1000);

        if ($per < 335) {
                // Highlight word in haystack
                $haystack = str_replace($hayword, "<b>$hayword</b>", $haystack);
                $haystack = str_replace("<b><b>", "<b>", $haystack);
                $haystack = str_replace("</b></b>", "</b>", $haystack);

                }
            }
        }
    }

// echo the new haystack
echo $haystack;

// Returns ...
//
// You searched for Youser Nein stitched tymes hand
// I found...
// Did you know that a <b>stitch</b> in <b>time</b> can
// save <b>nine</b>. Isn't that amazing! I think so. The
// <b>user</b>-supplied function has to return the
// <b>loser</b>, from the sand. Describe the cost for this
// particular operation. Eweser may decide to use only some
// of the supplied nans. <b>And</b> pay attention. This
// isn't <b>hard</b>...

?>
gzink at zinkconsulting dot com 03-Dec-2003 03:03
Try combining this with metaphone() for a truly amazing fuzzy search function. Play with it a bit, the results can be plain scary (users thinking the computer is almost telepathic) when implemented properly. I wish spell checkers worked as well as the code I've written.

I would release my complete code if reasonable, but it's not, due to copyright issues. I just hope that somebody can learn from this little tip!
genialbrainmachine at dot IHATESPAM dot tiscali dot it 26-Oct-2003 11:55
I wrote this function to have an "intelligent" comparison between data to be written in a DB
and already existent data. Not ony calculating distances but also balancing distances for
each field.
<?php
/*
This function calculate a balanced percentage distance between an array of strings
"$record" and a compared array "$compared", balanced through an array of
weights "$weight". The three arrays must have the same indices.
For an unbalanced distance, set all weights to 1.
The used formula is:
percentage distance = sum(field_levenshtein_distance * field_weight) / sum(record_field_length * field_weight) * 100
*/
function search_similar($record, $weights, $compared, $precision=2) {
         $field_names = array_keys($record);
         # "Weighted length" of $record and "weighted distance".
         foreach ($field_names as $field_key) {
                 $record_weight += strlen($record[$field_key]) * $weights[$field_key];
                 $weighted_distance += levenshtein($record[$field_key],$compared[$field_key]) * $weights[$field_key];
                 }
         # Building the result..
         if ($record_weight) {
             return round(($weighted_distance / $record_weight * 100),$precision);
            } elseif ((strlen(implode("",$record)) == 0) && (strlen(implode("",$compared)) == 0)) { // empty records
            return round(0,$precision);
            } elseif (array_sum($weights) == 0) { // all weights == 0
            return round(0,$precision);
            } else {
            return false;
            }
         /*
         Be very careful distinguising 0 result and false result.
         The function results 0 ('0.00' if $precision is 2 and so on) if:
         - $record and $compared are equals (even if $record and $compared are empty);
         - all weights are 0 (the meaning could be "no care about any field").
         Conversely, the function results false if $record is empty, but the weights
         are not all 0 and $compared is not empty. That cause a "division by 0" error.
         I wrote this kind of check:

         if ($rel_dist = search_similar(...)) {
             print $rel_dist;
            } elseif ($rel_dist == "0.00") { // supposing that $precision is 2
            print $rel_dist;
            } else {
            print "infinite";
            }

         */
         }
?>
jlsalinas at gmx dot net 25-Oct-2003 07:28
Regarding the post by fgilles on April 26th 2001, I suggest not to use levenshtein() function to test for over-uppercasing unless you've got plenty of time to waste in your host. ;) Anyhow, I think it's a useful feature, as I get really annoyed when reading whole messages in uppercase.

PHP's levenshtein() function can only handle up to 255 characters, which is not realistic for user input (only the first paragraph oh this post has 285 characters). If you choose to use a custom function able to handle more than 255 characters, efficiency is an important issue.

I use this function, specific for this case, but much faster:

function ucase_percent ($str) {
    $str2 = strtolower ($str);

    $l = strlen ($str);
    $ucase = 0;

    for ($i = 0; $i < $l; $i++) {
        if ($str{$i} != $str2{$i}) {
            $ucase++;
        }
    }

    return $ucase / $l * 100.0;
}

I think 10% is enough for written English (maybe other languages like German, which use more capital letters, need more). With some sentencies in uppercase (everybody has the right to shout occasionally), 20% would be enough; so I use a threshold of 30%. When exceeded, I lowercase the whole message.

Hope you find it useful and it helps keeping the web free of ill-mannered people.
inerte is my hotmail.com username 11-Jul-2003 10:22
I am using this function to avoid duplicate information on my client's database.

After retrieving a series of rows and assigning the results to an array values, I loop it with foreach comparing its levenshtein() with the user supplied string.

It helps to avoid people re-registering "John Smith", "Jon Smith" or "Jon Smit".

Of course, I can't block the operation if the user really wants to, but a suggestion is displayed along the lines of: "There's a similar client with this name.", followed by the list of the similar strings.
asseg at ukl dot uni-feiburg dot de 09-May-2003 06:05
for the unserious guys how might do dna sequence analysis
with php. Here's the function that can handle long strings.
to get an output of the matrix uncomment the
printf-section. handle with care iteration are approximately
2x2^strlen ;)

------------------------------------------------------------
function levdis($s,$t){
    $n=strlen($s);
    $m=strlen($t);
    $matrix=array(range(0,$n+1),range(0,$m+1));
    $ret=0;
    if ($n==0){
        return $m;
    }
    elseif ($m==0){
        return $n;
    }
    for ($i=0;$i<=$n;$i++) {
        $matrix[$i][0]=$i;
    }
    for  ($j=0;$j<=$m;$j++) {
        $matrix[0][$j]=$j;
    }
    for ($i=1;$i<=$n;$i++) {
        for  ($j=1;$j<=$m;$j++) {
            if ($s[$i-1]==$t[$j-1]) {
                $cost=0;
            }else{
                $cost=1;
            }
           $matrix[$i][$j]=min($matrix[$i-1][$j]+1,
                                       $matrix[$i][$j-1]+1,
                                       $matrix[$i-1][$j-1]+$cost);

        }
    }
/* for ($j=0;$j<=$m;$j++) {
        for ($i=0;$i<=$n;$i++) {
            printf("  %02d",$matrix[$i][$j]);
        }
        echo "\n";
    }*/
    return $matrix[$n][$m];
}
                                                                                ----------------------------------------------
bisqwit at iki dot fi 12-Aug-2002 07:43
At the time of this manual note the user defined thing
in levenshtein() is not implemented yet. I wanted something
like that, so I wrote my own function. Note that this
doesn't return levenshtein() difference, but instead
an array of operations to transform a string to another.

Please note that the difference finding part (resync)
may be extremely slow on long strings.

<?php

/* matchlen(): returns the length of matching
 * substrings at beginning of $a and $b
 */
function matchlen(&$a, &$b)
{
  $c=0;
  $alen = strlen($a);
  $blen = strlen($b);
  $d = min($alen, $blen);
  while($a[$c] == $b[$c] && $c < $d)
    $c++;
  return $c;
}

/* Returns a table describing
 * the differences of $a and $b */
function calcdiffer($a, $b)
{
  $alen = strlen($a);
  $blen = strlen($b);
  $aptr = 0;
  $bptr = 0;

  $ops = array();

  while($aptr < $alen && $bptr < $blen)
  {
    $matchlen = matchlen(substr($a, $aptr), substr($b, $bptr));
    if($matchlen)
    {
      $ops[] = array('=', substr($a, $aptr, $matchlen));
      $aptr += $matchlen;
      $bptr += $matchlen;
      continue;
    }
    /* Difference found */

    $bestlen=0;
    $bestpos=array(0,0);
    for($atmp = $aptr; $atmp < $alen; $atmp++)
    {
      for($btmp = $bptr; $btmp < $blen; $btmp++)
      {
        $matchlen = matchlen(substr($a, $atmp), substr($b, $btmp));
        if($matchlen>$bestlen)
        {
          $bestlen=$matchlen;
          $bestpos=array($atmp,$btmp);
        }
        if($matchlen >= $blen-$btmp)break;
      }
    }
    if(!$bestlen)break;

    $adifflen = $bestpos[0] - $aptr;
    $bdifflen = $bestpos[1] - $bptr;

    if($adifflen)
    {
      $ops[] = array('-', substr($a, $aptr, $adifflen));
      $aptr += $adifflen;
    }
    if($bdifflen)
    {
      $ops[] = array('+', substr($b, $bptr, $bdifflen));
      $bptr += $bdifflen;
    }
    $ops[] = array('=', substr($a, $aptr, $bestlen));
    $aptr += $bestlen;
    $bptr += $bestlen;
  }
  if($aptr < $alen)
  {
    /* b has too much stuff */
    $ops[] = array('-', substr($a, $aptr));
  }
  if($bptr < $blen)
  {
    /* a has too little stuff */
    $ops[] = array('+', substr($b, $bptr));
  }
  return $ops;
}

Example:

$tab = calcdiffer('T�m� on jonkinlainen testi',
                  'T�m� ei ole mink��nlainen testi.');
$ops = array('='=>'Ok', '-'=>'Remove', '+'=>'Add');
foreach($tab as $k)
  echo $ops[$k[0]], " '", $k[1], "'\n";

Example output:

Ok 'T�m� '
Remove 'on jonki'
Add 'ei ole mink��'
Ok 'nlainen testi'
Add '.'
11-Apr-2002 06:57
For spell checking applications, delay could be tolerable if you assume the typist got the first two or three chars of each word right.  Then you'd only need to calc distances for a small segment of the dictionary.  This is a compromise but one I think a lot of spell checkers make.
For an example of site search using this function look at the PHP manual search button on this page.  It appears to be doing this for the PHP function list.
fgilles at free dot fr 26-Apr-2001 01:32
Exempla of use for a forum: users can't post messages too much uppercased

<?php
if ((strlen($subject)>10) and ( ( levenshtein ($subject, strtolower ($subject) / strlen ($subject) ) > .3 ) ){
    $subject = strtolower($subject);
}
?>
hholzgra at php dot net 11-Aug-2000 01:20
well, think of it as a sort of typo counter

by the way we might introduce a feature similar to something that the jikes compiler for java does using this function:

every time you try to access an undefined funtion you will get a suggestion of a function that's named
similar to what you requested

e.g.:

Undefined function 'rest()'!
Where you looking for 'reset()' instead?
dschultz at protonic dot com 10-Aug-2000 09:01
It's also useful if you want to make some sort of registration page and you want to make sure that people who register don't pick usernames that are very similar to their passwords.
Mathijs Brands &lt;mathijs at ilse dot nl&gt; 06-Aug-2000 05:54
This could come in handy if you were to implement a simple searchengine in PHP. It would allow for simple fuzzy searching.
ad1n at dc dot uba dot ar 04-Aug-2000 05:01
One application of this is when you want to look for a similar match instead of an exact one. You can sort the results of checking the distances of a word to a dictionary and sort them to see which were the more similar ones. Of course it will be a quite resourse consuming task anyway.
lcfirst
localeconv
Обработка строк


Возвращает информацию о числовых форматах

levenshtein
ltrim
Обработка строк
PHP Manual

localeconv

(PHP 4 >= 4.0.5, PHP 5)

localeconv — Возвращает информацию о числовых форматах

Описание

array localeconv ( void )

Возвращает ассоциативный массив с информацией о числовых и денежных форматах в текущей локали.

Возвращаемые значения

localeconv() возвращает данные, основанные на текущей локали, установленной функцией setlocale(). Возвращаемый массив содержит следующие элементы:

Элемент | Описание
decimal_point | Символ десятичной точки
thousands_sep | Разделитель групп
grouping | Массив, содержащий количества цифр в группах для числовых данных
int_curr_symbol | Международное обозначение валюты (например, RUB)
currency_symbol | Национальное обозначение валюты (например, руб)
mon_decimal_point | Символ десятичной точки в денежном формате
mon_thousands_sep | Разделитель групп в денежном формате
mon_grouping | Массив, содержащий количества цифр в группах для денежных данных
positive_sign | Знак для положительных чисел
negative_sign | Знак для отрицательных чисел
int_frac_digits | Число разрядов после точки (международное)
frac_digits | Число разрядов после точки (национальное)
p_cs_precedes | TRUE, если currency_symbol записывается перед положительным значением, иначе FALSE
p_sep_by_space | TRUE, если currency_symbol отделяется от положительного значения пробелом, иначе FALSE
n_cs_precedes | TRUE, если currency_symbol записывается перед отрицательным значением, иначе FALSE
n_sep_by_space | TRUE, если currency_symbol отделяется от отрицательного значения пробелом, иначе FALSE
p_sign_posn Для положительных чисел:
  • 0 - Число и обозначение валюты заключаются в скобки
  • 1 - Знак записывается перед числом и обозначением валюты
  • 2 - Знак записывается после числа и обозначения валюты
  • 3 - Знак записывается перед обозначением валюты
  • 4 - Знак записывается после обозначения валюты
n_sign_posn Для отрицательных чисел:
  • 0 - Число и обозначение валюты заключаются в скобки
  • 1 - Знак записывается перед числом и обозначением валюты
  • 2 - Знак записывается после числа и обозначения валюты
  • 3 - Знак записывается перед обозначением валюты
  • 4 - Знак записывается после обозначения валюты

p_sign_posn и n_sign_posn содержат строку с опциями форматирования. Каждое число представляет собой одно из вышеперечисленных условий.

Элементы группировки содержат массивы, которые описывают способ группировки цифр. Например, поле группировки денежных величин в локали nl_NL (в режиме UTF-8 со знаком евро) содержит массив из двух элементов со значениями 3 и 3. Больший индекс массива соответствует группировке цифр, расположенных левее. Если элемент массива равен CHAR_MAX, последующие цифры не группируются. Если элемент массива равен 0, используется значение предыдущего элемента.

Примеры

Пример #1 Пример использования localeconv()

<?php
if (false !== setlocale(LC_ALL, 'ru_RU.UTF-8')) {
    $locale_info = localeconv();
    print_r($locale_info);
}
?>

Результат выполнения данного примера:

Array
(
    [decimal_point] => ,
    [thousands_sep] =>
    [int_curr_symbol] => RUB
    [currency_symbol] => руб
    [mon_decimal_point] => .
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] => -
    [int_frac_digits] => 2
    [frac_digits] => 2
    [p_cs_precedes] => 0
    [p_sep_by_space] => 1
    [n_cs_precedes] => 0
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 1
    [grouping] => Array
        (
            [0] => 3
            [1] => 3
        )

    [mon_grouping] => Array
        (
            [0] => 3
            [1] => 3
        )

)

Смотрите также

  • setlocale() - Устанавливает настройки локали

User Contributed Notes

PixEye dot DELETE at bigfoot dot com 24-Nov-2007 01:15
A function to get the right money & number formats:
<?php
function displayLocales($number, $isMoney, $lg='en_US.utf8') {
    $ret = setLocale(LC_ALL, $lg);
    setLocale(LC_TIME, 'Europe/Paris');
    if ($ret===FALSE) {
        echo "Language '$lg' is not supported by this system.\n";
        return;
    }
    $LocaleConfig = localeConv();
    forEach($LocaleConfig as $key => $val) $$key = $val;

    // Sign specifications:
    if ($number>0) {
        $sign = $positive_sign;
        $sign_posn = $p_sign_posn;
        $sep_by_space = $p_sep_by_space;
        $cs_precedes = $p_cs_precedes;
    } else {
        $sign = $negative_sign;
        $sign_posn = $n_sign_posn;
        $sep_by_space = $n_sep_by_space;
        $cs_precedes = $n_cs_precedes;
    }

    // Number format:
    $n = number_format(abs($number), $frac_digits,
        $decimal_point, $thousands_sep);
    $n = str_replace(' ', '&nbsp;', $n);
    switch($sign_posn) {
        case 0: $n = "($n)"; break;
        case 1: $n = "$sign$n"; break;
        case 2: $n = "$n$sign"; break;
        case 3: $n = "$sign$n"; break;
        case 4: $n = "$n$sign"; break;
        default: $n = "$n [error sign_posn=$sign_posn&nbsp;!]";
    }

    // Currency format:
    $m = number_format(abs($number), $frac_digits,
        $mon_decimal_point, $mon_thousands_sep);
    if ($sep_by_space) $space = ' '; else $space = '';
    if ($cs_precedes) $m = "$currency_symbol$space$m";
    else $m = "$m$space$currency_symbol";
    $m = str_replace(' ', '&nbsp;', $m);
    switch($sign_posn) {
        case 0: $m = "($m)"; break;
        case 1: $m = "$sign$m"; break;
        case 2: $m = "$m$sign"; break;
        case 3: $m = "$sign$m"; break;
        case 4: $m = "$m$sign"; break;
        default: $m = "$m [error sign_posn=$sign_posn&nbsp;!]";
    }
    if ($isMoney) return $m; else return $n;
}

$number = -12345.12345;
echo '<div>'.displayLocales($number, FALSE)."</div>\n";
echo '<div>'.displayLocales($number, TRUE)."</div>\n";
?>
verdy_p at wanadoo dot fr 22-Jul-2001 07:13
The C99 standard modified slightly the definition of the international currency symbol, which is now 4 characters long instead of 3 in previous definitions. The fourth character will most often be an ASCII space, but its effective value is the locale-specific spacing character used for numeric grouping (i.e. the one refered by [sep_by_space] and [grouping])...
levenshtein
ltrim
Обработка строк


Удаляет пробелы (или другие символы) из начала строки

localeconv
md5_file
Обработка строк
PHP Manual

ltrim

(PHP 4, PHP 5)

ltrim — Удаляет пробелы (или другие символы) из начала строки

Описание

string ltrim ( string $str [, string $charlist ] )

Удаляет пробелы (или другие символы) из начала строки.

Список параметров

str

Входная строка.

charlist

С помощью параметра charlist можно также указать удаляемые символы. Просто перечислите все символы, которые вы хотите удалить. Можно указать конструкцию .. для обозначения диапазона символов.

Возвращаемые значения

Эта функция возвращает строку str с удаленными из начала строки пробелами. Если второй параметр не передан, ltrim() удаляет следующие символы:

  • " " (ASCII 32 (0x20)), обычный пробел.
  • "\t" (ASCII 9 (0x09)), символ табуляции.
  • "\n" (ASCII 10 (0x0A)), символ перевода строки.
  • "\r" (ASCII 13 (0x0D)), символ возврата каретки.
  • "\0" (ASCII 0 (0x00)), NUL-байт.
  • "\x0B" (ASCII 11 (0x0B)), вертикальная табуляция.

Список изменений

Версия | Описание
4.1.0 | Добавлен параметр charlist.

Примеры

Пример #1 Пример использования ltrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = ltrim($text);
var_dump($trimmed);

$trimmed = ltrim($text, " \t.");
var_dump($trimmed);

$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);

// удаляем управляющие ASCII-символы с начала $binary
// (от 0 до 31 включительно)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);

?>

Результат выполнения данного примера:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "These are a few words :) ...  "
string(30) "These are a few words :) ...  "
string(7) "o World"
string(15) "Example string
"

Смотрите также

  • trim() - Удаляет пробелы (или другие символы) из начала и конца строки
  • rtrim() - Удаляет пробелы (или другие символы) из конца строки

User Contributed Notes

dzek dot remove_this at dzek dot eu 25-Jul-2011 01:27
Guys, if += 0 is producing wrong values sometimes, and preg_replace is cpu consuming, then just stick to the main function described on that page, and use:
<?php
$value = ltrim($value, '0');
?>
should be the fastest and most reliable.
I think all those comments can be misleading for begginers checking this page - it's sort of using magic tricks to reinvent the wheel.
Mike 08-Jan-2011 12:03
Keep in mind the amount of resources preg_replace() uses.
I would suggest a simple if statement if you need to parse through large amounts of data.
<?php
function remove_leading_zeros_from_number($number_string) {
  $limit = 9000.1
  $temp = $number
  (float) $temp;
  if ($number < $limit) {
    $number += 0;
  } else {
    preg_replace('~^[0]*([1-9][0-9]*)$~','$1',$number_string)
  }
}
?>

Code is untested, but probably sound.
tanmar.de 06-May-2010 10:36
The neat trick from Mr. Sherwood has only one ugly side-effect: If the "number" contained in the string is considerably large, you will end up with an int (or float) value that has nothing to do with the original number ...

You may use preg_replace instead:

$number_string = preg_replace('~^[0]*([1-9][0-9]*)$~','$1',$number_string);

This kills any leading zeros safely without changing any other data.

Hope this helps.
Usamah M dot Ali (usamah1228 at gmail dot com) 04-Feb-2008 02:42
For those who use right-to-left languages such as Arabic, Hebrew, etc., it's worth mentioning that ltrim() (which stands for left trim) & rtrim() (which stands for right trim) DO NOT work contextually. The nomenclature is rather semantically incorrect. So in an RTL script, ltrim() will trim text from the right direction (i.e. beginning of RTL strings), and rtrim() will trim text from the left direction (i.e. end of RTL strings).
John Sherwood 06-Aug-2006 12:13
To remove leading/trailing zeroes (example: "0123.4560"), doing a += 0 is easier than trim tricks.
localeconv
md5_file
Обработка строк


Возвращает MD5-хэш файла

ltrim
md5
Обработка строк
PHP Manual

md5_file

(PHP 4 >= 4.2.0, PHP 5)

md5_file — Возвращает MD5-хэш файла

Описание

string md5_file ( string $filename [, bool $raw_output = false ] )

Вычисляет MD5-хэш файла, имя которого задано аргументом filename, используя » алгоритм MD5 RSA Data Security, Inc. и возвращает этот хэш. Хэш представляет собой 32-значное шестнадцатеричное число.

Список параметров

filename

Имя файла

raw_output

Если имеет значение TRUE, то возвращается бинарная строка из 16 символов.

Возвращаемые значения

Возвращает строку в случае успеха, иначе FALSE.

Список изменений

Версия | Описание
5.1.0 | Функция изменена для работы с потоковым API. Это означает, что ее можно использовать с обертками, например, так: md5_file('http://example.com/..')
5.0.0 | Добавлен параметр raw_output

Примеры

Пример #1 Пример использования md5_file()

<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';

echo 'MD5-хэш файла ' . $file . ': ' . md5_file($file);
?>

Смотрите также

  • md5() - Возвращает MD5-хэш строки
  • sha1_file() - Возвращает SHA1-хэш файла
  • crc32() - Вычисляет полином CRC32 для строки

User Contributed Notes

lukasamd at gmail dot com 14-Feb-2012 10:35
It's faster to use md5sum than openssl md5:

<?php
$begin = microtime(true);

$file_path = '../backup_file1.tar.gz';
$result = explode("  ", exec("md5sum $file_path"));
echo "Hash = ".$result[0]."<br />";

# Here 7 other big files (20-300 MB)

$end = microtime(true) - $begin;
echo "Time = $end";
# Time = 4.4475841522217

#Method with openssl
# Time = 12.1463856900543
?>

About 3x faster
Chris 08-Nov-2009 07:24
If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files.  There's no reason to read two whole files and do all the math if the second byte of each file is different.  If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files.  This can be much faster:

<?php
define('READ_LEN', 4096);

if(files_identical('file1.txt', 'file2.txt'))
    echo 'files identical';
else
    echo 'files not identical';

//   pass two file names
//   returns TRUE if files are the same, FALSE otherwise
function files_identical($fn1, $fn2) {
    if(filetype($fn1) !== filetype($fn2))
        return FALSE;

    if(filesize($fn1) !== filesize($fn2))
        return FALSE;

    if(!$fp1 = fopen($fn1, 'rb'))
        return FALSE;

    if(!$fp2 = fopen($fn2, 'rb')) {
        fclose($fp1);
        return FALSE;
    }

    $same = TRUE;
    while (!feof($fp1) and !feof($fp2))
        if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
            $same = FALSE;
            break;
        }

    if(feof($fp1) !== feof($fp2))
        $same = FALSE;

    fclose($fp1);
    fclose($fp2);

    return $same;
}
?>
Sebastian Zavadschi (php.box.md) 22-Sep-2008 01:55
I need to parse a big file after it was changed (a shared XLS file). I've fond a good idea to check once a minute the checksum of the file, in order to track if it was changed or not. Here is my code, hope will help some one. Any improvements are welcome!

<?php
$file_xls = "test.xls";
$file_md5 = "test.xls.md5"; // Must exists and must be writable for PHP
$md5_new_file = trim(md5_file($file_xls));
$md5_old_file = trim(file_get_contents($file_md5));

if($md5_new_file <> $md5_old_file)
    {
    echo "file is out of date, updating now...";
    rename($file_md5, $file_md5.".bak");
    $fp = fopen($file_md5, 'w');
    fwrite($fp, $md5_new_file);
    fclose($fp);
/*
Here we do some job...
In my case - dealing with "Spreadsheet Excel Reader"
*/
    unlink($file_md5.".bak");
    }
// "Not for crontab" - Remove the following section if you are intending to run it in crontab
else
    {
    echo "file is up to date, nothing to do...";
    }
// End "Not for crontab";
?>
smartin 12-Mar-2008 04:58
In response to using exec instead for performance (Nov 13 2007 post), It looks like the performance depends on the size of the file.  See the results below using the same script from the original post.  The first hash is with md5_file and the second is with openssl md5.

With a 1MB file:
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.005006
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.01498

With a 2MB file:

Hash = 4387904830a4245a8ab767e5937d722c; time = 0.010393
Hash = 4387904830a4245a8ab767e5937d722c; time = 0.016691

With a 10MB file:

Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.241907
Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.037597

Performance seems to change proportionally with the file size.  Judging from the previous post's default file name (.mov) he/she was probably dealing with a large file.  These are just quick tests and far from a perfect benchmark, but you might want to test your own files before assuming that the openssl solution is faster (ie, if working with small text files vs. movies, etc)
toby at globaloptima dot co dot uk 18-Nov-2007 12:15
I'm wondering about the MD5_DIR function posted by potsed, what happens if the file listing is returned in a different order?

From what I can tell you get different MD5's based on the order, a minor addition sorts this:

    ...
    asort($filemd5s); //sort the md5s before concat
    return md5(implode('', $filemd5s));
}
glau dot stuff at N0_SPAM dot ridiculousprods dot com 13-Nov-2007 05:54
It's much faster to call an 'exec' command to openssl md5 than to use md5_file.

<?php

$file_path = '/path/to/large/video_file.mov';

$begin = microtime(true);

$hash = md5_file($file_path);

$end = microtime(true) - $begin;

echo "Hash = $hash; time = $end<br>";
# Hash = eac425a6f5b90f69e74710b015228640; time = 2.5333859920502

$begin = microtime(true);

$result = split('=',exec("openssl md5 $file_path"));

$end = microtime(true) - $begin;

echo "Hash = ".$result[1]."; time = $end";
#Hash = eac425a6f5b90f69e74710b015228640; time = 0.79528999328613

?>

I consistently see about a 3x improvement in speed.
potsed [at] gmail [dot] com 27-May-2007 04:12
Heres a function to give an md5 for an entire directory..

function MD5_DIR($dir)
{
    if (!is_dir($dir))
    {
        return false;
    }

    $filemd5s = array();
    $d = dir($dir);

    while (false !== ($entry = $d->read()))
    {
        if ($entry != '.' && $entry != '..')
        {
             if (is_dir($dir.'/'.$entry))
             {
                 $filemd5s[] = MD5_DIR($dir.'/'.$entry);
             }
             else
             {
                 $filemd5s[] = md5_file($dir.'/'.$entry);
             }
         }
    }
    $d->close();
    return md5(implode('', $filemd5s));
}
bubba at revbubba dot com 29-Mar-2005 04:56
a working example of the usage of this function, to confirm a specific file has not been modified (replace all instances of "myfile.xxx" with your filename):

<?php
$chkfilename = "myfile.xxx";
$chkmd5return = md5_file($chkfilename);
if ($chkmd5return != "myfile.xxx's md5 value") {
     echo "You have replaced myfile.xxx with an unknown version of the file, please replace the original file.";
} else {
     (your code to be executed, now that it has confirmed your myfile.xxx has been unmodified)
}
?>

To find out the file's md5 value, create a new .php doc, and put this code in it:

<?php
$chkfilename = "myfile.xxx";
$chkmd5return = md5_file($chkfilename);
echo $chkmd5return;
?>

Then upload the new .php doc to your webserver and navigate to it.  Be sure to delete the new .php doc once you have plugged in the value it spits out, into the "myfile.xxx's md5 value" in the first example above.

I just thought this example might be helpful to someone somewhere...  if you php.net people feel it needs editing or deletion, I leave it to your discretion.  ;)
richard at interlink dot com dot au 16-Nov-2004 12:57
For those of you with PHP 4 that want to output the "raw" 128 bit hash, all you need to do is send it to pack to convert the hex string into the raw output.

ie:
$filename="checkthisfile.bin";
$rawhash=pack("H*",md5_file($filename));
ltrim
md5
Обработка строк


Возвращает MD5-хэш строки

md5_file
metaphone
Обработка строк
PHP Manual

md5

(PHP 4, PHP 5)

md5 — Возвращает MD5-хэш строки

Описание

string md5 ( string $str [, bool $raw_output = false ] )

Вычисляет MD5-хэш строки str используя » алгоритм MD5 RSA Data Security, Inc. и возвращает этот хэш.

Список параметров

str

Строка.

raw_output

Если необязательный аргумент raw_output имеет значение TRUE, то возвращается бинарная строка из 16 символов.

Возвращаемые значения

Возвращает хэш в виде 32-символьного шестнадцатеричного числа.

Список изменений

Версия | Описание
5.0.0 | Добавлен параметр raw_output.

Примеры

Пример #1 Пример использования md5()

<?php
$str = 'яблоко';

if (md5($str) === '1afa148eb41f2e7103f21410bf48346c') {
    echo "Вам зеленое или красное яблоко?";
}
?>

Примечания

Замечание: Безопасное хэширование паролей

В связи с быстрой природой хэширующего алгоритма не рекомендуется использовать эту функцию для обеспечения безопасности паролей. Подробнее об этом можно прочитать здесь.

Смотрите также

  • md5_file() - Возвращает MD5-хэш файла
  • sha1_file() - Возвращает SHA1-хэш файла
  • crc32() - Вычисляет полином CRC32 для строки
  • sha1() - Возвращает SHA1-хэш строки
  • hash() - Генерирует хеш-код (дайджест сообщения)

User Contributed Notes

anthonymccuen at yahoo dot com 24-Nov-2011 02:49
If your going to hash a password or some other content, you can try the code below.

<?php
function hash_pass($password) {
$appKey = sha1($password);

$appId = 555;
$otherApp = '6cf6e971f7c125615a1ee20510c1c70f';     // simple md5

$appSaltKey = crypt($password);

$getStrLen = strlen($appKey);
$getIdLen = strlen($appId);
$randzStrInt = rand($appId, 999);

    if ($appId === 555) {
        $go = strlen($appKey);
        $other = strlen(crypt(md5(rand($appId, $appId))));
        $execute = rand($other, $appId) . "-" . rand($go, $appId) . "-" . rand(strlen(crypt($otherApp)), $appId);
        echo $execute . " today is <b>" . $date . "</b>";
    }
?>
David Foley (dev at davidfoley dot org) 15-Sep-2011 06:54
If you are using Dojo toolkit's "dojox.encoding.digests.MD5()" to generate an MD5 hash on the client side, you may run in to difficulty. Dojo returns a base 64 encoded MD5 hash, and as a result is not the same as PHPs. This is an issue when trying to verify a hash.

To get the Dojo style hash from PHP use the following:

<?php

/**
 * Function to generate base 64 encoded hash
 * in the the style of dojox.encoding.digests.MD5()
 *
 * @param string $data Data to be hased
 * @return string base64 encoded MD5 hash
 */
function md5_base64($data) {
    return base64_encode(pack('H*',md5($data)));
}

?>
Anonymous 03-May-2011 10:28
This is not encryption..... it's only a sort of DIGEST
John 17-Nov-2009 03:08
If you want to hash a large amount of data you can use the hash_init/hash_update/hash_final functions.

This allows you to hash chunks/parts/incremental or whatever you like to call it.
Serge 20-May-2008 03:19
To convert an MD5 to 22 chars that contains only letters and numeric

<?php
define('HEX_CHARS',    '0123456789abcdef');
define('BASE62_CHARS', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

/*********************************************/
function ConvertFromArbitraryBase($Str, $Chars)
/*********************************************/
{
    /*
        Converts from an arbitrary-base string to a decimal string
    */

    if (ereg('^[' . $Chars . ']+$', $Str))
    {
        $Result = '0';

        for ($i=0; $i<strlen($Str); $i++)
        {
            if ($i != 0) $Result = bcmul($Result, strlen($Chars));
            $Result = bcadd($Result, strpos($Chars, $Str[$i]));
        }

        return $Result;
    }

    return false;
}

/*******************************************/
function ConvertToArbitraryBase($Str, $Chars)
/*******************************************/
{
    /*
        Converts from a decimal string to an arbitrary-base string
    */

    if (ereg('^[0-9]+$', $Str))
    {
        $Result = '';

        do
        {
            $Result .= $Chars[bcmod($Str, strlen($Chars))];
            $Str = bcdiv($Str, strlen($Chars));
        }
        while (bccomp($Str, '0') != 0);

        return strrev($Result);
    }

    return false;
}

/**********************/
function CustomMD5($Str)
/**********************/
{
    return ConvertToArbitraryBase(ConvertFromArbitraryBase(md5($Str), HEX_CHARS), BASE62_CHARS);
}
?>
KB 11-Mar-2008 06:02
This is probably well known, but I had a hard time finding a reference to it.

While md5 on a null string returns null, md5 on an EMPTY string does not return null or an empty string.  Rather it returns "d41d8cd98f00b204e9800998ecf8427e"
admin at gadelkareem dot com 14-Jan-2008 08:16
MySQL MD() will not give you the same hash if character set is different.
ex :
<?php
#suppose table_name CHARSET=UTF8
#$md5 = md5('Städte'); # will give you a different hash than MySQL MD5()
#instead use
$md5 = md5(utf8_encode('Städte'));
$r = mysql_query("SELECT *, MD5(`word`) FROM `table_name` WHERE MD5(`word`) LIKE '{$md5}'");
if($r)
    while( $row= mysql_fetch_assoc($r) )
        print_r($row);

?>
dionyziz at deviantart dot com 11-Aug-2007 12:24
Sometimes it's useful to get the actual, binary, md5 digest.
You can use this function for it:

<?php

function md5bin( $target ) {
    $md5 = md5( $target );
    $ret = '';

    for ( $i = 0; $i < 32; $i += 2 ) {
        $ret .= chr( hexdec( $md5{ $i + 1 } ) + hexdec( $md5{ $i } ) * 16 );
    }

    return $ret;
}

?>
sebastian dot haller at freesurf dot ch 07-Apr-2007 12:06
It has been found, that hash('md5', 'string'); is faster than md5($string):

http://www.php.net/manual/en/function.hash.php
marzetti dot marco at NOSPAM dot gmail dot com 16-May-2006 03:12
The complement of raw2hex

<?php

function hex2raw( $str ){
  $chunks = str_split($str, 2);
  for( $i = 0; $i < sizeof($chunks); $i++ ) {
        $op .= chr( hexdec( $chunks[$i] ) );
    }
    return $op;
}

?>
rick.gaither 20-Dec-2005 09:14
This is a nifty function to help in securing your web-forms.

If no argument is passed the function will return an encrypted hex code representing the second it was called. If the same hex code is passed to the function it will return the number of seconds that have elapsed. The php script can then check the time between accessing the web-page and submitting the POST. This thwarts script ran web-form submissions. The program can verify a suitable period has elapsed for expected manual entries. The time check can be from 1 second to about 17 hours.

The function requires the latest PEAR Blowfish Encryption module.

This would go in the form:
<?php  print "<input type='hidden' value='" . FormTimer() . "' name='FormCode'>";  ?>

This would go in the main php (post) script:
<?php
$seconds = FormTimer($_POST['FormCode']);
if (($seconds < 10) || ($seconds > 1900)) { die "Your entry time took less than 10 seconds or more than 30 minutes"; }
?>

Function...
<?php
function FormTimer($CodeID="") {

    require ('Blowfish.php');
    require ('Blowfish/DefaultKey.php');

    $key = "Secret^Word";
    $bf = new Crypt_Blowfish($key);
     $current = substr(sprintf("%d", (time()+1)),-8);

    if (!$CodeID) { return bin2hex($bf->encrypt($current)); }

    $len = strlen($CodeID); $cValue = -1;
    for ($i=0;$i<$len;$i+=2) $Crypt.=chr(hexdec(substr($CodeID,$i,2)));

    if ($Crypt) {
        $time_called = $bf->decrypt($Crypt);
        if ($time_called) { $cValue = (intval($current) - intval($time_called)); }
    }
    return $cValue;
}
?>
terry _at_ scribendi_com 28-Apr-2005 07:39
Do not use the hex strings returned by md5() as a key for MCrypt 256-bit encryption.  Hex characters only represent four bits each, so when you take 32 hex characters, you are only really using a 128-bit key, not a 256-bit one.

Using an alphanumeric key generator [A-Za-z0-9] will also only provide a 192-bit key in 32 characters.

Two different MD5s concatenated in raw binary form, or mcrypt_create_iv(32,MCRYPT_DEV_RANDOM) will give you a true 256-bit key string.
John S. 03-Dec-2004 11:42
If you want to replicate CPAN Digest::MD5's function md5_base64 in PHP, use this code:

<?php

function md5_base64 ( $data )
{
    return preg_replace('/=+$/','',base64_encode(pack('H*',md5($data))));
}

?>
Shane Allen 14-Apr-2003 08:53
From the documentation on Digest::MD5:
md5($data,...)
This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form.

md5_hex($data,...)
Same as md5(), but will return the digest in hexadecimal form.

PHP's function returns the digest in hexadecimal form, so my guess is that you're using md5() instead of md5_hex(). I have verified that md5_hex() generates the same string as PHP's md5() function.

(original comment snipped in various places)
>Hexidecimal hashes generated with Perl's Digest::MD5 module WILL
>NOT equal hashes generated with php's md5() function if the input
>text contains any non-alphanumeric characters.
>
>$phphash = md5('pa$$');
>echo "php original hash from text: $phphash";
>echo "md5 hash from perl: " . $myrow['password'];
>
>outputs:
>
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd
md5_file
metaphone
Обработка строк


Возвращает ключ metaphone для строки

md5
money_format
Обработка строк
PHP Manual

metaphone

(PHP 4, PHP 5)

metaphone — Возвращает ключ metaphone для строки

Описание

string metaphone ( string $str [, int $phonemes = 0 ] )

Возвращает ключ metaphone для строки str.

Подобно функции soundex(), metaphone возвращает одинаковое значение для слов, имеющих сходное произношение. Эта функция более точна, чем soundex(), так как учитывает основные правила произношения английского языка. Длина возвращаемой строки не фиксирована.

Функция metaphone была написана Lawrence Philips <lphilips at verity dot com> и описана в книге ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

Список параметров

str

Входная строка.

phonemes

Этот параметр выставляет ограничение в phonemes символов на длину возвращаемого ключа metaphone. Значение по умолчанию 0 означает отсутствие ограничений.

Возвращаемые значения

Возвращает ключ metaphone в виде строки, или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Простой пример использования metaphone()

<?php
var_dump(metaphone('programming'));
var_dump(metaphone('programmer'));
?>

Результатом выполнения данного примера будет что-то подобное:

string(7) "PRKRMNK"
string(6) "PRKRMR"

Пример #2 Использование параметра phonemes

<?php
var_dump(metaphone('programming', 5));
var_dump(metaphone('programmer', 5));
?>

Результатом выполнения данного примера будет что-то подобное:

string(5) "PRKRM"
string(5) "PRKRM"

User Contributed Notes

Vipindas K.S 09-May-2008 09:49
metaphone
=======================
The metaphone() function can be used for spelling applications.This function returns the metaphone key of the string on success, or FALSE on failure.Its main use is when you are searching a genealogy database. check to see if a metaphone search is offered. It is also useful in making/searching family tree.
Given below is a simple code that calculates and compares two strings to find whether its metaphone codes are equivalent.

html code
==========
<html>
<body>
<form action="test.php" name="test" method="get">
Name1:<input type="text" name="name1" /><br />
Name2:<input type="text" name="name2" /><br />
<input type="submit" name="submit" value="compare" />
</form>

<!--php code begins here -->

<?php
if(isset($_GET['submit']))
{
$str1 = $_GET['name1'];
$str2 = $_GET['name2'];
$meta_one=metaphone($str1);
$meta_two=metaphone($str2);
echo "metaphone code for ".$str1." is ". $meta_one;
echo "<br />";
echo "metaphone code for ".$str2." is ". $meta_two."<br>";
if($meta_one==$meta_two)
{
echo "metaphone codes are matching";
}
else
{
echo "metaphone codes are not matching";
}
}
?>

</body>
</html>

Metaphone  algorithm was developed by Lawrence Philips.

Lawrence Philips' RULES follow:

 The 16 consonant sounds:
                                             |--- ZERO represents "th"
                                             |
      B  X  S  K  J  T  F  H  L  M  N  P  R  0  W  Y

 Exceptions:

   Beginning of word: "ae-", "gn", "kn-", "pn-", "wr-"  ----> drop first letter
                      "Aebersold", "Gnagy", "Knuth", "Pniewski", "Wright"

   Beginning of word: "x"                                ----> change to "s"
                                      as in "Deng Xiaopeng"

   Beginning of word: "wh-"                              ----> change to "w"
                                      as in "Whalen"

 Transformations:

   B ----> B      unless at the end of word after "m", as in "dumb", "McComb"

   C ----> X      (sh) if "-cia-" or "-ch-"
           S      if "-ci-", "-ce-", or "-cy-"
                  SILENT if "-sci-", "-sce-", or "-scy-"
           K      otherwise, including in "-sch-"

   D ----> J      if in "-dge-", "-dgy-", or "-dgi-"
           T      otherwise

   F ----> F

   G ---->        SILENT if in "-gh-" and not at end or before a vowel
                            in "-gn" or "-gned"
                            in "-dge-" etc., as in above rule
           J      if before "i", or "e", or "y" if not double "gg"
           K      otherwise

   H ---->        SILENT if after vowel and no vowel follows
                         or after "-ch-", "-sh-", "-ph-", "-th-", "-gh-"
           H      otherwise

   J ----> J

   K ---->        SILENT if after "c"
           K      otherwise

   L ----> L

   M ----> M

   N ----> N

   P ----> F      if before "h"
           P      otherwise

   Q ----> K

   R ----> R

   S ----> X      (sh) if before "h" or in "-sio-" or "-sia-"
           S      otherwise

   T ----> X      (sh) if "-tia-" or "-tio-"
           0      (th) if before "h"
                  silent if in "-tch-"
           T      otherwise

   V ----> F

   W ---->        SILENT if not followed by a vowel
           W      if followed by a vowel

   X ----> KS

   Y ---->        SILENT if not followed by a vowel
           Y      if followed by a vowel

   Z ----> S
php at casadebender dot com 27-Mar-2008 10:24
A double metaphone pecl module is available: http://pecl.php.net/package/doublemetaphone
mail at spam-off dot iaindooley dot com 16-Jan-2004 12:37
you can use the metaphone function quite effectively with phrases by taking the levenshtein distances between two metaphone codes, and then taking this as a percentage of the length of the original metaphone code. thus you can define a percentage error, (say 20%) and accept only matches that are closer than that. i've found this works quite effectively in a function i am using on my website where an album name that the user entered is verified against existing album names that may be similar. this is also an excellent way of people being able to vaguely remember a phrase and get several suggestions out of the database. so you could type "i stiched nine times" with an error percentage of, say, 50 and still get 'a stitch in time saves nine' back as a match.
server: zinkconsulting.com user: galen@ 26-Nov-2003 02:18
A small warning about the double metaphone function/class implemented in php: it's slow. Very slow.

On my Mac OS X box it takes roughly 4 seconds to calculate the double_metaphone of a given string 1,000 times and set a variable to that value. Given the exact same code, the built in metaphone function takes a mere 0.03 seconds. That's a huge difference. For reference, soundex takes about 0.015 seconds.

I had dreams of ranking my person database search results with double_metaphone, but with searches yielding a few thousand results sometimes, this isn't terribly reasonable. I'm back to basic metaphone functions.

I'd suggest anyone considering the use of the double_metaphone functionality weigh the slight improvement in results with the fact it's 100 times slower than the php function metaphone. I believe this difference is probably due mostly to implementation and optimization (php code vs. optimized internal php function).

Anybody up for writing a double_metaphone function for php? Maybe php 5?
md5
money_format
Обработка строк


Форматирует число как денежную величину

metaphone
nl_langinfo
Обработка строк
PHP Manual

money_format

(PHP 4 >= 4.3.0, PHP 5)

money_format — Форматирует число как денежную величину

Описание

string money_format ( string $format , float $number )

money_format() форматирует число number как денежную величину. Эта функция вызывает функцию strfmon() языка C, но позволяет преобразовать только одно число за один вызов.

Список параметров

format

Описание формата состоит из:

  • символа %

  • необязательных флагов

  • необязательной ширины поля

  • необязательной точности до запятой

  • необязательной точности после запятой

  • обязательного описателя преобразования

Флаги

Могут быть использованы следующие флаги:

=f

Символ =, за которым следует еще один символ f, задает символ заполнения. По умолчанию пробел.

^

Отключает группировку символов (определяемую текущей локалью).

+ или (

Задает способ форматирования положительных и отрицательных значений. При использовании + будут использоваться аналоги символов + и - из текущей локали. Если указана (, отрицательные числа будут заключены в скобки. По умолчанию +.

!

Подавляет вывод символа валюты.

-

Если этот флаг задан, поля будут выравнены влево (с отбивкой вправо), вместо используемого по умолчанию выравнивания вправо (с отбивкой влево).

Ширина поля

w

Строка из десятичных цифр, задающая минимальную ширину поля. Поле будет выравнено вправо, если не указан флаг -. Значение по умолчанию - 0 (ноль).

Точность до запятой

#n

Максимальное количество цифр (n), которое ожидается до запятой. Это обычно используется при выводе значений одно под другим, чтобы десятичные точки располагались в одной колонке, при этом используется символ заполнения, если число цифр меньше n. Если число цифр больше n, этот параметр игнорируется.

Если группировка не была отключена флагом ^, разделители групп будут вставлены перед добавлением символов заполнения. Разделители групп не вставляются между символами заполнения, даже если заполнитель - цифра.

Для обеспечения выравнивания, все символы, выводимые до или после числа, такие как сивол валюты или знак, будут дополнены пробелами до одинаковой ширины.

Точность после запятой

.p

Точка, за которой следует число знаков (p), выводимых после запятой. Если значение p равно нулю, десятичная точка и цифры после нее не будут выводиться. Если этот параметр отсутствует, число знаков после запятой определяется текущей локалью. Перед форматированием число округляется до указанного количества знаков.

Описатель преобразования

i

Используется международный денежный формат из текущей локали (например, для американской локали: USD 1,234.56).

n

Используется национальный денежный формат из текущей локали (например, для локали de_DE: EU1.234,56).

%

Вставляет символ %.

number

Форматируемое число.

Возвращаемые значения

Возвращает отформатированную строку. Символы перед и после описания формата возвращаются без изменений. Если number не является числом, то будет возвращен NULL и вызвана ошибка уровня E_WARNING.

Примечания

Замечание:

Функция money_format() определена только если в системе присутствует функция strfmon. Например, в Windows она отсутствует, поэтому money_format() не определена в Windows.

Замечание:

На работу этой функции влияет установка категории LC_MONETARY текущей локали. Перед использованием этой функции установите нужную локаль с помощью setlocale().

Примеры

Пример #1 Пример использования money_format()

Проиллюстрируем применение этой функции для различных локалей и разных описаний формата.

<?php

$number = 1234.56;

// международный формат в локали en_US
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

// Итальянский национальный формат с 2 знаками после запятой
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56

// Использование отрицательных чисел
$number = -1234.5672;

// национальный формат США, с использованием скобок для
// отрицательных чисел и 10 знаков до запятой
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($        1,234.57)

// подобно предыдущему, но с добавлением 2 знаков после запятой
// и '*' в качестве символа заполнения
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)

// Выравнивание влево, ширина 14 знаков, 8 знаков до запятой,
// 2 знака после запятой, без разбиения на группы
// с использованием  международного формата в локали de_DE.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// Eu 1234,56****

// А теперь добавим текст перед и после описанием формата
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'Итоговая сумма: %i (после 10%% скидки)';
echo money_format($fmt, 1234.56) . "\n";
// Итоговая сумма:  GBP 1,234.56 (после 10% скидки)

?>

Смотрите также

  • setlocale() - Устанавливает настройки локали
  • sscanf() - Разбирает строку в соответствии с заданным форматом
  • sprintf() - Возвращает отформатированную строку
  • printf() - Выводит отформатированную строку
  • number_format() - Форматирует число с разделением групп

User Contributed Notes

phpdeveloperbalaji at gmail dot com 28-Sep-2011 01:04
Hi,

For South Asian Currencies, this function could be a handy one.

It will handle negative as well as float(Paise).

<?php
function my_money_format($number)
{
    if(strstr($number,"-"))
    {
        $number = str_replace("-","",$number);
        $negative = "-";
    }

    $split_number = @explode(".",$number);

    $rupee = $split_number[0];
    $paise = @$split_number[1];

    if(@strlen($rupee)>3)
    {
        $hundreds = substr($rupee,strlen($rupee)-3);
        $thousands_in_reverse = strrev(substr($rupee,0,strlen($rupee)-3));
        for($i=0; $i<(strlen($thousands_in_reverse)); $i=$i+2)
        {
            $thousands .= $thousands_in_reverse[$i].$thousands_in_reverse[$i+1].",";
        }
        $thousands = strrev(trim($thousands,","));
        $formatted_rupee = $thousands.",".$hundreds;

    }
    else
    {
        $formatted_rupee = $rupee;
    }

    if((int)$paise>0)
    {
        $formatted_paise = ".".substr($paise,0,2);
    }

    return $negative.$formatted_rupee.$formatted_paise;

}
?>

Thanks,
andrey.dobrozhanskiy [-a-t-] gmail com 07-Jul-2010 09:43
This function divides integer value by commas. F.e.

<?php
echo formatMoney(1050); # 1,050
echo formatMoney(1321435.4, true); # 1,321,435.40
echo formatMoney(10059240.42941, true); # 10,059,240.43
echo formatMoney(13245); # 13,245

function formatMoney($number, $fractional=false) {
    if ($fractional) {
        $number = sprintf('%.2f', $number);
    }
    while (true) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}
?>
Rafael M. Salvioni 19-Feb-2009 12:20
This is a some function posted before, however various bugs were corrected.

Thank you to Stuart Roe by reporting the bug on printing signals.

<?php
/*
That it is an implementation of the function money_format for the
platforms that do not it bear.

The function accepts to same string of format accepts for the
original function of the PHP.

(Sorry. my writing in English is very bad)

The function is tested using PHP 5.1.4 in Windows XP
and Apache WebServer.
*/
function money_format($format, $number)
{
    $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
              '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
    if (setlocale(LC_MONETARY, 0) == 'C') {
        setlocale(LC_MONETARY, '');
    }
    $locale = localeconv();
    preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
    foreach ($matches as $fmatch) {
        $value = floatval($number);
        $flags = array(
            'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
                           $match[1] : ' ',
            'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
            'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
                           $match[0] : '+',
            'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
            'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
        );
        $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
        $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
        $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
        $conversion = $fmatch[5];

        $positive = true;
        if ($value < 0) {
            $positive = false;
            $value  *= -1;
        }
        $letter = $positive ? 'p' : 'n';

        $prefix = $suffix = $cprefix = $csuffix = $signal = '';

        $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
        switch (true) {
            case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
                $prefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
                $suffix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
                $cprefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
                $csuffix = $signal;
                break;
            case $flags['usesignal'] == '(':
            case $locale["{$letter}_sign_posn"] == 0:
                $prefix = '(';
                $suffix = ')';
                break;
        }
        if (!$flags['nosimbol']) {
            $currency = $cprefix .
                        ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
                        $csuffix;
        } else {
            $currency = '';
        }
        $space  = $locale["{$letter}_sep_by_space"] ? ' ' : '';

        $value = number_format($value, $right, $locale['mon_decimal_point'],
                 $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
        $value = @explode($locale['mon_decimal_point'], $value);

        $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
        if ($left > 0 && $left > $n) {
            $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
        }
        $value = implode($locale['mon_decimal_point'], $value);
        if ($locale["{$letter}_cs_precedes"]) {
            $value = $prefix . $currency . $space . $value . $suffix;
        } else {
            $value = $prefix . $value . $space . $currency . $suffix;
        }
        if ($width > 0) {
            $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
                     STR_PAD_RIGHT : STR_PAD_LEFT);
        }

        $format = str_replace($fmatch[0], $value, $format);
    }
    return $format;
}

?>
jeremy 30-Sep-2008 10:41
If money_format doesn't seem to be working properly, make sure you are defining a valid locale.  For example, on Debian, 'en_US' is not a valid locale - you need 'en_US.UTF-8' or 'en_US.ISO-8559-1'.

This was frustrating me for a while.  Debian has a list of valid locales at /usr/share/i18n/SUPPORTED; find yours there if it's not working properly.
swapnet 22-Jul-2008 08:24
Consider formatting currency for some South Asian countries that use ##,##,###.## money format.
The following code generates something like Rs. 4,54,234.00 and so on.

<?php
function convertcash($num, $currency){
    if(strlen($num)>3){
            $lastthree = substr($num, strlen($num)-3, strlen($num));
            $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
            $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.

            $expunit = str_split($restunits, 2);
            for($i=0; $i<sizeof($expunit); $i++){
                $explrestunits .= (int)$expunit[$i].","; // creates each of the 2's group and adds a comma to the end
            }

            $thecash = $explrestunits.$lastthree;
    } else {
           $thecash = $convertnum;
    }

    return $currency.$thecash.".00"; // writes the final format where $currency is the currency symbol.
}
?>

now call the function as  convertcash($row['price'], 'Rs '); // that's the price from the database I called using an Indian Rupees prefix where the price has to be a plain number format, say something like 454234.
scot from ezyauctionz.co.nz 06-Oct-2007 03:10
This is a handy little bit of code I just wrote, as I was not able to find anything else suitable for my situation.
This will handle monetary values that are passed to the script by a user, to reformat any comma use so that it is not broken when it passes through an input validation system that checks for a float.

It is not foolproof, but will handle the common input as most users would input it, such as 1,234,567 (outputs 1234567) or 1,234.00 (outputs 1234.00), even handles 12,34 (outputs 12.34), I expect it would work with negative numbers, but have not tested it, as it is not used for that in my situation.

This worked when other options such as money_format() were not suitable or possible.

<?php
///////////////
// BEGIN CODE convert all price amounts into well formatted values
function converttonum($convertnum,$fieldinput){
        $bits = explode(",",$convertnum); // split input value up to allow checking

        $first = strlen($bits[0]); // gets part before first comma (thousands/millions)
        $last = strlen($bits[1]); // gets part after first comma (thousands (or decimals if incorrectly used by user)

        if ($last <3){ // checks for comma being used as decimal place
            $convertnum = str_replace(",",".",$convertnum);
        }
        else{ // assume comma is a thousands seperator, so remove it
            $convertnum = str_replace(",","",$convertnum);
        }

        $_POST[$fieldinput] = $convertnum; // redefine the vlaue of the variable, to be the new corrected one
}

@converttonum($_POST[inputone],"inputone");
@converttonum($_POST[inputtwo],"inputtwo");
@converttonum($_POST[inputthree],"inputthree");
// END CODE
//////////////

?>

This is suitable for the English usage, it may need tweaking to work with other types.
richard dot selby at uk dot clara dot net 17-Feb-2006 07:02
Double check that money_format() is defined on any version of PHP you plan your code to run on.  You might be surprised.

For example, it worked on my Linux box where I code, but not on  servers running  BSD 4.11 variants. (This is presumably because strfmon  is not defined - see note at the top of teis page). It's not just a windows/unix issue.
metaphone
nl_langinfo
Обработка строк


Возвращает информацию о языке и локали

money_format
nl2br
Обработка строк
PHP Manual

nl_langinfo

(PHP 4 >= 4.1.0, PHP 5)

nl_langinfo — Возвращает информацию о языке и локали

Описание

string nl_langinfo ( int $item )

nl_langinfo() используется для доступа к отдельным элементам различных категорий текущей локали. В отличии от localeconv(), возвращающей все элементы, nl_langinfo() позволяет выбрать отдельный элемент.

Список параметров

item

item может быть целым числом или соответствующей константой. Ниже приведены возможные константы для item и их описания. Для некоторых локалей отдельные константы могут быть неопределены.

Константы nl_langinfo
Константа | Описание
Константы в категории LC_TIME
ABDAY_(1-7) | Сокращенное название n-го дня недели.
DAY_(1-7) | Полное название n-го дня недели (DAY_1 соответствует воскресенью).
ABMON_(1-12) | Сокращенное название n-го месяца.
MON_(1-12) | Полное название n-го месяца.
AM_STR | Обозначение "до полудня".
PM_STR | Обозначение "после полудня".
D_T_FMT | Строка, которую можно использовать в качестве формата с функцией strftime() для вывода даты и времени.
D_FMT | Строка, которую можно использовать в качестве формата с функцией strftime() для вывода даты.
T_FMT | Строка, которую можно использовать в качестве формата с функцией strftime() для вывода времени.
T_FMT_AMPM | Строка, которую можно использовать в качестве формата с функцией strftime() для вывода времени в 12-часовом формате.
ERA | Эра
ERA_YEAR | Год в формате с эрой
ERA_D_T_FMT | Дата и время в формате с эрой (строка, которую можно использовать в качестве формата с функцией strftime()).
ERA_D_FMT | Дата в формате с эрой (строка, которую можно использовать в качестве формата с функцией strftime()).
ERA_T_FMT | Время в формате с эрой (строка, которую можно использовать в качестве формата с функцией strftime()).
Константы в категории LC_MONETARY
INT_CURR_SYMBOL | Международное обозначение валюты.
CURRENCY_SYMBOL | Национальное обозначение валюты.
CRNCYSTR | Аналог CURRENCY_SYMBOL.
MON_DECIMAL_POINT | Символ десятичной точки.
MON_THOUSANDS_SEP | Разделитель тысяч (групп из 3 цифр).
MON_GROUPING | Аналогичен элементу "grouping".
POSITIVE_SIGN | Знак для положительных чисел.
NEGATIVE_SIGN | Знак для отрицательных чисел.
INT_FRAC_DIGITS | Количество знаков после запятой (международный формат).
FRAC_DIGITS | Количество знаков после запятой (национальный формат).
P_CS_PRECEDES | Возвращает 1, если CURRENCY_SYMBOL записывется перед положительным значением.
P_SEP_BY_SPACE | Возвращает 1, если CURRENCY_SYMBOL отделяется от положительного значения пробелом.
N_CS_PRECEDES | Возвращает 1, если CURRENCY_SYMBOL записывется перед отрицательным значением.
N_SEP_BY_SPACE | Возвращает 1, если CURRENCY_SYMBOL отделяется от отрицательного значения пробелом.
P_SIGN_POSN
  • Возвращает 0, если число и обозначение валюты CURRENCY_SYMBOL заключаются в скобки
  • Возвращает 1, если знак записывается перед числом и обозначением валюты CURRENCY_SYMBOL
  • Возвращает 2, если знак записывается после числа и обозначения валюты CURRENCY_SYMBOL
  • Возвращает 3, если знак записывается перед обозначением валюты CURRENCY_SYMBOL
  • Возвращает 4, если знак записывается после обозначения валюты CURRENCY_SYMBOL
N_SIGN_POSN
Константы в категории LC_NUMERIC
DECIMAL_POINT | Символ десятичной точки.
RADIXCHAR | Аналогично DECIMAL_POINT.
THOUSANDS_SEP | Разделитель тысяч (групп из 3 цифр).
THOUSEP | Аналогично THOUSANDS_SEP.
GROUPING
Константы в категории LC_MESSAGES
YESEXPR | Регулярное выражение, при совпадении с которым строка рассматривается как положительный ответ ("yes").
NOEXPR | Регулярное выражение, при совпадении с которым строка рассматривается как отрицательный ответ ("no").
YESSTR | Слово "да" ("yes").
NOSTR | Слово "нет" ("no").
Константы в категории LC_CTYPE
CODESET | Возвращает строку с именем текущей кодировки.

Возвращаемые значения

Возвращает элемент в виде строки, или FALSE если item передан неправильно.

Примечания

Замечание: Для Windows-платформ эта функция не реализована.

Смотрите также

  • setlocale() - Устанавливает настройки локали
  • localeconv() - Возвращает информацию о числовых форматах

User Contributed Notes

avatar_at_hot_ee 11-Mar-2006 07:58
The value MON_(1-12) has special behavior in Russian locale: it returns declinated month names, that can be used as part of a date string, but not on their own.

For instance instead of "Январь" (the proper nominative form) it returns "Января" (form declinated for use in dates).

There seems to be no way to get the nominative form of the month name - one has to use translations instead.
zerof at terra dot com dot br 22-Apr-2005 10:34
<?php

$vlr19900 = nl_langinfo (CODESET);
$vlr19901 = nl_langinfo (D_T_FMT);
$vlr19902 = nl_langinfo (D_FMT);
$vlr19903 = nl_langinfo (T_FMT);
$vlr19904 = nl_langinfo (DAY_1);
$vlr19905 = nl_langinfo (ABDAY_1);
$vlr19906 = nl_langinfo (MON_1);
$vlr19907 = nl_langinfo (ABMON_1);
$vlr19908 = nl_langinfo (RADIXCHAR);
$vlr19909 = nl_langinfo (THOUSEP);
$vlr19910 = nl_langinfo (YESEXPR);
$vlr19911 = nl_langinfo (NOEXPR);
$vlr19912 = nl_langinfo (CRNCYSTR);

echo "encoding codeset => " . $vlr19900;
echo "<br /><br />date/time string para strftime => " . $vlr19901;
echo "<br /><br />date string for strftime => " . $vlr19902;
echo "<br /><br />time string for strftime => " . $vlr19903;
echo "<br /><br />long form day name => " . $vlr19904;
echo "<br /><br />short form day name => " . $vlr19905;
echo "<br /><br />long form month name => " . $vlr19906;
echo "<br /><br />short form month name => " . $vlr19907;
echo "<br /><br />decimals separator => " . $vlr19908;
echo "<br /><br />thousands separator => " . $vlr19909;
echo "<br /><br />REGEXP for 'Yes' => " . $vlr19910;
echo "<br /><br />REGEXP for 'No' => " . $vlr19911;
echo "<br /><br />local currency simbol => " . $vlr19912;

?>
money_format
nl2br
Обработка строк


Вставляет HTML-код разрыва строки перед каждым переводом строки

nl_langinfo
number_format
Обработка строк
PHP Manual

nl2br

(PHP 4, PHP 5)

nl2br — Вставляет HTML-код разрыва строки перед каждым переводом строки

Описание

string nl2br ( string $string [, bool $is_xhtml = true ] )

Возвращает строку string, в которой перед каждым переводом строки (\r\n, \n\r, \n и \r) вставлен '<br />' или '<br>'.

Список параметров

string

Входная строка.

is_xhtml

Использовать совместимые с XHTML переводы строк или нет.

Возвращаемые значения

Возвращает измененную строку.

Примеры

Пример #1 Пример использования nl2br()

<?php
echo nl2br("foo - это вам не\n bar");
?>

Результат выполнения данного примера:

foo - это вам не<br />
 bar

Пример #2 Генерирование корректной HTML-верстки с помощью параметра is_xhtml

<?php
echo nl2br("Привет!\r\nЭтой мой HTML-документ", false);
?>

Результат выполнения данного примера:

Привет!<br>
Этой мой HTML-документ

Пример #3 Различные разделители строк

<?php
$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);
?>

Результат выполнения данного примера:

This<br />
is<br />
a<br />
string<br />

Список изменений

Версия | Описание
5.3.0 | Добавлен необязательный параметр is_xhtml.
4.0.5 | nl2br() теперь совместима с XHTML. Все старые версии возвращали string, в которой перед переводами строк были вставлены '<br>' вместо '<br />'.

Смотрите также

  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • htmlentities() - Преобразует все возможные символы в соответствующие HTML-сущности
  • wordwrap() - Переносит строку по указанному количеству символов
  • str_replace() - Заменяет все вхождения строки поиска на строку замены

User Contributed Notes

j dot mons54 at gmail dot com 29-May-2012 09:45
for bbcode :

<?php
$message =  nl2br(preg_replace('#(\\]{1})(\\s?)\\n#Usi', ']', stripslashes($message)));
?>
php at djurredeboer dot nl 29-Jul-2011 07:28
If you use nl2br over a html table you get a lot of new lines above this table. you can fix it by using this function
<?php
$input = nl2br("
    this is a test<br/>

    Aadasd
    asda
    asd
    asd
    <table>
    <td></td>
    <td></td>
    <td></td>
    </table>");
$output = preg_replace_callback('%<table(.*?)>(.*?)</table>%si', 'delTableBr',$input);

function delTableBr($groups) {
    return '<table'.$groups[1].'>'.preg_replace('/<br[^>]*?>/si', '',$groups[2]).'</table>';
}

?>
Now it will return
<br />
    this is a test<br/><br />
    <br />
    Aadasd<br />
    asda<br />
    asd<br />
    asd<br />
    <table>
    <td></td>
    <td></td>
    <td></td>
    </table>
matthewkastor at live dot com 17-Apr-2011 08:49
I was converting text to simple HTML, and converting HTML to plain text. I needed an easy function to convert line breaks, no matter if they were characters or tags, into whatever line break I required at the time. This function worked pretty well. It detects double line breaks and preserves them, as long as the line breaks are in the same format i.e. \r\n \r\n or <br> <br>. It will not preserve a double line break such as <br>\n, instead, it treats this as a single line break for obvious reasons.

The following are recognized as single line breaks, and are replaced using this function:
    \r, \n, \r\n, <BR>, <br>, <br/>, <br />, and any combination of a single tag with any quantity of \r, \n, \r\n following it.

convert_line_breaks.php
<?php
/**
 * Converts newlines and break tags to an
 * arbitrary string selected by the user,
 * defaults to PHP_EOL.
 *
 * In the case where a break tag is followed by
 * any amount of whitespace, including \r and \n,
 * the tag and the whitespace will be converted
 * to a single instance of the line break argument.
 *
 * @author Matthew Kastor
 * @param string $string
 *   string in which newlines and break tags will be replaced
 * @param string $line_break
 *   replacement string for newlines and break tags
 * @return string
 *   Returns the original string with newlines and break tags
 *   converted
 */
function convert_line_breaks($string, $line_break=PHP_EOL) {
    $patterns = array(
                        "/(<br>|<br \/>|<br\/>)\s*/i",
                        "/(\r\n|\r|\n)/"
    );
    $replacements = array(
                            PHP_EOL,
                            $line_break
    );
    $string = preg_replace($patterns, $replacements, $string);
    return $string;
}
?>
mail at fort-hub dot com 18-Feb-2011 03:54
I noticed that I am using an earlier version of PHP which does not recognise the $xhtml parameter in nl2br(), therefore I am stuck with xhtml line breaks, which I do not want. Thus I made the following simple function:

<?php

    function NlToBr($inString)
    {
        return preg_replace("%\n%", "<br>", $inString);
    }

?>
dejan dot marjanovic at gmail dot com 26-Sep-2010 10:53
Hi, I wrote this function to prevent double lines when doing nl2br with pre tag in HTML. Hope it helps someone.

<?php
function my_nl2br($string){
    $string = str_replace("\n", "<br />", $string);
    if(preg_match_all('/\<pre\>(.*?)\<\/pre\>/', $string, $match)){
        foreach($match as $a){
            foreach($a as $b){
            $string = str_replace('<pre>'.$b.'</pre>', "<pre>".str_replace("<br />", "", $b)."</pre>", $string);
            }
        }
    }
return $string;
}
?>

Source: http://webarto.com/59/php-nl2br-pre
Joshua Anderson 11-Jun-2010 09:40
This function will change new lines (line breaks) to <br/> and it allows you to limit the amount of brs allowed at any point in time.

This function was made to avoid people spaming a textarea with hundreds of line breaks or empty lines.

<?php
function nl2br_limit($string, $num){

$dirty = preg_replace('/\r/', '', $string);
$clean = preg_replace('/\n{4,}/', str_repeat('<br/>', $num), preg_replace('/\r/', '', $dirty));

return nl2br($clean);
}

echo nl2br_limit($string,'4');
?>

// Heres how it works //

nl2br_limit($string, $num)
// $string is the entered text you want to strip lines out of, it could be ($_POST['myinput'])
// $num is the amount of consecutive <br/>'s that are allowed any at a time.

The user is allowed to enter as many line breaks as $num allows
Jose Canciani 18-May-2010 08:57
Recursive solution to avoid replacing newlines inside <pre> tags:

<?php
    function findOpenPre($line) {
        $start = strpos($line,'<pre');
        if ($start === false) {
            return nl2br($line);
        } else {
            return nl2br(substr($line,0,$start-1)).findClosePre(substr($line,$start));
        }
    }

    function findClosePre($line) {
        $start = strpos($line,'</pre>');
        if ($start === false) {
            return $line.'</pre>'; # should never come here
        } else {
            return substr($line,0,$start+6).findOpenPre(substr($line,$start+7));
        }
    }

    echo findOpenPre('hello '.chr(10).'<pre> world'.chr(10).'</pre>');
?>

will return "hello <br><pre> world\n</pre>"
instead of "hello <br><pre> world<br></pre>"

Jose.
gx 03-May-2010 09:02
*Strictly* reverts PHP's nl2br() effects (whether it was used in XHTML mode or not):

<?php
function nl2br_revert($string) {
    return preg_replace('`<br(?: /)?>([\\n\\r])`', '$1', $string);
}
?>

Indeed, in a string which was just nl2br'd:
- a BR added by PHP is directly followed by a \n or a \r character, and vice versa
- a PHP-added BR is either "<br />" or "<br>" (no need to match "<br/>", "<br   />", "<BR>"...)
Thus this function only removes PHP-added BRs (which "strictly reverts" meant).

The following would be even more logical, as nl2br() doesn't use both BR forms at once:
<?php
function nl2br_revert_bis($string) {
    $br = preg_match('`<br>[\\n\\r]`',$string) ? '<br>' : '<br />';
    return preg_replace('`'.$br.'([\\n\\r])`', '$1', $string);
}
?>

If you don't want to use regular expressions, here are "plain" alternatives:
<?php
function nl2br_revert_noregex($string) {
    // watch for order in arrays
    // (the first 2 elements are for the case nl2br() was used in old HTML mode)
    return str_replace(
        array("<br>\n",   "<br>\r",   "<br />\n", "<br />\r"),
        array("<br />\n", "<br />\r",       "\n",       "\r"),
        $string
    );
}

function nl2br_revert_bis_noregex($string) {
    $br = (strpos($string,"<br>\n")!==false || strpos($string,"<br>\r")!==false) ? '<br>' : '<br />';
    return str_replace(
        array($br."\n", $br."\r"),
        array(    "\n",     "\r"),
        $string
    );
}
?>
james bandit.co dot nz 29-Apr-2010 11:13
convert multiple new lines to p tags with an optional class assigned to the p tags

<?php
    function nl2p($string, $class='') {
        $class_attr = ($class!='') ? ' class="'.$class.'"' : '';
        return
            '<p'.$class_attr.'>'
            .preg_replace('#(<br\s*?/?>\s*?){2,}#', '</p>'."\n".'<p'.$class_attr.'>', nl2br($string, true))
            .'</p>';
    }
?>
SebastianJu 30-Nov-2009 01:49
Another br2nl-Function. This works with text for textareas too... Other solutions here would result in \n in the textbox and no wrap.

<?php
function br2nl($string){
  $return=eregi_replace('<br[[:space:]]*/?'.
    '[[:space:]]*>',chr(13).chr(10),$string);
  return $return;
}
?>

Grüße!
Sebastian
leaf at leafo dot net 26-Jun-2009 01:02
for the <pre> tag problem, the reason why nl2br does that is because it converts all \n to <br />\n
(see the extra \n there)

an easy hack is to use strtr to replace all \n with just <br />

eg.
<?php
function mynl2br($text) {
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />'));
}
?>

very simple and very fast. the only disadvantage is that anyone reading your nl2br'd html will see it all on one line.
eric dot NOSPAM dot dillenseger at gmail dot com 10-Apr-2009 02:34
An addition to sean' function:
Please read http://www.php.net/manual/en/function.strpos.php and the warning about return values of strpos().

<?php
// (... snip ...)
    if(!strpos($string, "<pre>"))  // triggered if <pre> is at the beginning of the string
// (... snip ...)
        if(strpos($line, "<pre>")) // this time, not triggered if <pre> is at the beginning of the line
// (... snip ...)
?>

Avoid shortcuts and compare boolean results strictly with '==='.

BTW, <pre> elements aren't allowed inside <p> elements (xhtml strict) so one would avoid putting a <br /> element at the end of a <pre> element.

<?php
// do nl2br except when in a pre tag
function nl2brPre($string)
{
    // First, check for <pre> tag
    if(strpos($string, "<pre>") === false)
    {
        return nl2br($string);
    }

    // If there is a <pre>, we have to split by line
    // and manually replace the linebreaks with <br />
    $strArr=explode("\n", $string);
    $output="";
    $preFound=3;

    // Loop over each line
    foreach($strArr as $line)
    {    // See if the line has a <pre>. If it does, set $preFound to true
        if(strpos($line, "<pre>") === true)
        {
            $preFound=1;
        }
        elseif(strpos($line, "</pre>"))
        {
            $preFound=2;
        }

        // If we are in a pre tag, just give a \n, else a <br />
        switch($preFound) {
            case 1: // found a <pre> tag, close the <p> element
                $output .= "</p>\n" . $line . "\n";
                break;
            case 2: // found the closing </pre> tag, append a newline and open a new <p> element
                $output .= $line . "\n<p>";
                $preFound = 3; // switch to normal behaviour
                break;
            case 3: // simply append a <br /> element
                $output .= $line . "<br />";
                break;
        }
    }

    return $output;
}
?>
sean at boyercentral dot net 03-Mar-2009 07:22
Ever had a problem with using nl2br() for something like a blog post which contains anything inside of a <pre> tag? It will give you double spaces. Ugly for posting code examples. Here's my solution.

If it doesn't detect a <pre> tag inside of the $string you pass in, it uses regular ol' nl2br(). Otherwise, it explodes the string by \n, and only adds <br /> to lines that are NOT inside the <pre> tag!

This function completely avoids using RegEx and stacks. Simple, and fairly fast.

<?php
// do nl2br except when in a pre tag
function nl2brPre($string)
{
    // First, check for <pre> tag
    if(!strpos($string, "<pre>"))
    {
        return nl2br($string);
    }

    // If there is a <pre>, we have to split by line
    // and manually replace the linebreaks with <br />
    $strArr=explode("\n", $string);
    $output="";
    $preFound=false;

    // Loop over each line
    foreach($strArr as $line)
    {    // See if the line has a <pre>. If it does, set $preFound to true
        if(strpos($line, "<pre>"))
        {
            $preFound=true;
        }
        elseif(strpos($line, "</pre>"))
        {
            $preFound=false;
        }

        // If we are in a pre tag, just give a \n, else a <br />
        if($preFound)
        {
            $output .= $line . "\n";
        }
        else
        {
            $output .= $line . "<br />";
        }
    }

    return $output;
}
?>

Hope this comes in handy!
N/A 29-Oct-2008 07:41
Here's a more simple one:

<?php
/**
 * Convert BR tags to nl
 *
 * @param string The string to convert
 * @return string The converted string
 */
function br2nl($string)
{
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
?>

Enjoy
rphsm at hotmail dot com 30-Apr-2008 01:56
function to replace all \n\n\n\n\n\n \r\r\r\r only one <br />

<?php
function Only1br($string)
{
    return preg_replace("/(\r\n)+|(\n|\r)+/", "<br />", $string);
}

$string = "this is \n\n\n a String with many \n\n\r\r returns!";

$string = Only1br($string);

//returns: this is <br /> a String with many <br /> returns!";
?>
blacknine313 at gmail dot com 01-Apr-2008 06:34
After a recent post at the forums on Dev Shed, I noticed that it isn't mentioned, so I will mention it.

nl2br returns pure HTML, so it should be after PHP anti-HTML functions ( such as strip_tags and htmlspecialchars ).
nacho dot exr at gmail dot com 31-Oct-2007 08:56
Simple function that converts more than one <br>,<br/>,<br />... to a <p></p>. Maybe it's useful for someone =)

<?php
function br2p($string)
{
  return preg_replace('#<p>[\n\r\s]*?</p>#m', '', '<p>'.preg_replace('#(<br\s*?/?>){2,}#m', '</p><p>', $string).'</p>');
}
?>

Useful used with nl2br:
<?php
br2p(nl2br(...));
?>
hyponiq at gmail dot com 25-Aug-2007 11:03
On the contrary, <b>mark at dreamjunky.comno-spam</b>, this function is rightfully named.  Allow me to explain.  Although it does re-add the line break, it does so in an attempt to stay standards-compliant with the W3C recommendations for code format.

According to said recommendations, a new line character must follow a line break tag.  In this situation, the new line is not removed, but a break tag is added for proper browser display where a paragraph isn't necessary or wanted.
moester at g-mail 25-Feb-2007 01:45
<?php
function nls2p($str)
{
  return str_replace('<p></p>', '', '<p>'
        . preg_replace('#([\r\n]\s*?[\r\n]){2,}#', '</p>$0<p>', $str)
        . '</p>');
}
?>

Turns two or more consecutive newlines (separated by possible white space) into a <p>...</p>.

Pass result to regular nl2br() to add <br/> to remaining nl's, eg,

<?php
echo nl2br(nls2p("Paragraph1\n\nParagraph2\n line1\n line2\n"));
?>

result:

<p>Paragraph1</p>
<p>Paragraph2<br/>
line1<br/>
line2<br/></p>
ngkongs at gmail dot com 23-Feb-2007 04:12
to replace all linebreaks to <br />
the best solution (IMO) is:

<?php
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
?>

because each OS have different ASCII chars for linebreak:
windows = \r\n
unix = \n
mac = \r

works perfect for me
fili at fili dot nl 11-Feb-2007 11:07
<?php
function p2nl ($str) {
    return preg_replace(array("/<p[^>]*>/iU","/<\/p[^>]*>/iU"),
                        array("","\n"),
                        $str);
}

$string = "0<p>1</p><p>2</p>3";
var_dump(p2nl($string));

/*
Output:

    string(6) "01
    2
    3"
*/
?>
Moore (at) Hs-Furtwangen (dot) De 18-Aug-2006 11:13
Here a litle function that might come handy one time:
It gives back a String and adds a <BR> (you can change it to <br />) to every line end. And it adds $num blanks to the front of the next line.

<?php
 function nl2brnl($text, $num)
  {
   return preg_replace("/\\r\\n|\\n|\\r/", sprintf("% -".(5+$num)."s","<BR>\\n"), $text);
  }

$a = " one\\n two\\r\\n three";

$b = nl2brnl($a, 2);

var_dump($b);

/* output will be:
string(30) " one<BR>
   two<BR>
   three"
*/

echo "  <P>\\n  ";
echo $b

/* output will be:
  <P>
   one<BR>
   two<BR>
   three
*/
?>

Is helpfull for avouding code_soup.
godfrank DOMAIN-IS msn TLD-IS com 17-May-2006 09:12
I have modified my function found in the previous post.

It now uses preg_replace() which should technically be faster than ereg_replace(). You can also specify what you want to replace "\r\n" with. If you use the function with only one parameter, it will use '<br />' by default.

<?php
function nl2brStrict($text, $replacement = '<br />')
{
    return preg_replace("((\r\n)+)", trim($replacement), $text);
}
?>
chayden at chayden dot com 10-Mar-2006 03:07
Using buzoganylaszlo at yahoo dot com simple nl2p function, I've written a more HTML compliant function to deal with line breaks ...

<?php

/* FORMATS LINE BREAKS WITH PROPER HTML TAGS */
function format_html($content)
 {
  $content = "<p>" . str_replace("\r\n", "<br/>", $content) . "";
  $content = "" . str_replace("<br/><br/>", "</p><p>", $content) . "";
  return "" . str_replace("<br/><li>", "<li>", $content) . "";
 }

?>

Here is an example of its use ...

<?php

/* CONTENT TO BE PROCCESSED */
$content = "This is a\r\nline break.\r\n\r\nAnd this is a new paragraph.";

/* USE OF format_html FUNCTION */
/* NOTE: If you want 100% proper HTML tags, you'll need to add a closing paragraph tag (</p>) as shown below. */
echo format_html("$content</p>");

?>

The above will print ...

<p>This is a
<br/>line break.

<p>And this is a paragraph.</p>
Anders Norrbring 09-Mar-2006 01:49
Seems like I was a bit too quick and left out the vital part, and I also missed to escape the slashes in the post...

<?php
function br2nl($text)
{
    return  preg_replace('/<br\\\\s*?\\/??>/i', "\\n", $text);
}
?>
Anders Norrbring 09-Mar-2006 01:28
Seeing all these suggestions on a br2nl function, I can also see that neither would work with a sloppy written html line break.. Users can't be trusted to write good code, we know that, and mixing case isn't too uncommon.

I think this little snippet would do most tricks, both XHTML style and HTML, even mixed case like <Br> <bR /> and even <br            > or <br     />.

<?php
function br2nl($text)
{
    return  preg_replace('/<br\\s*?\/??>/i', '', $text);
}
?>
tom dot crawford at emailsystems dot com 11-Jan-2006 02:32
Note to foltscane at yahoo dot com

Wouldn't it be easier to do this:

$encoded_string = nl2br( htmlentities( $string_to_encode ) );
buzoganylaszlo at yahoo dot com 05-Jan-2006 04:51
There is a simple nl2p function:

<?php
function nl2p($text) {
  return "<p>" . str_replace("\n", "</p><p>", $text) . "</p>";
}
?>
foltscane at yahoo dot com 03-Jan-2006 08:47
I was interested in changing \n to <BR> but then still having htmlentities enforced inbetween these added <BR>s. So I wrote this simple textentities which will do just that.

function textentities($s)
{
    while($sp = strpos($s,"\n"))
    {
        echo htmlentities(substr($s,0,$sp))."<BR>";
        $s = substr($s,$sp+1,strlen($s));
    }
    echo htmlentities($s);
}
btm at anfo dot pl 20-Dec-2005 03:22
Comment on emailfire at gmail dot com nl2brr. It should be:
<? return str_replace(array("\r\n", "\n", "\r"), "<br>", $text); ?>
You've forgotten the backslashes.
jonasnicklas at hotmail dot com 19-Dec-2005 02:04
Re: emailfire

The function emailfire posted is missing some backslashes, a better alternative to it is:

<?php

$foo = "This\nis a\r\ntest\rmessage";

function nl2brr($text)
{
    return preg_replace("/\r\n|\n|\r/", "<br>", $text);
}

echo nl2brr($foo);

# Output: This<br>is a<br>test<br>message

?>

I put both functions in a for-loop and surprisingly preg_replace is a lot faster, I assume this is because str_replace will search the string several times. If you know what kind of breaks (Windows/Unix) you are expecting it is obviously better to use str_replace.

A note: Internet Explorer does not have any XHTML support, even browsers that DO have XHTML support (such as Firefox or Opera) will not parse pages as XHTML unless told so via a Header (for example through php's header function, like <?php header(Content-type: application/xhtml+xml); ?>), the tag <br /> is invalid in HTML 4. Since all browsers show it correctly anyway (though according to the specification they shouldn't), you could simply not care...
silya at rfvnu dot lg dot ua 04-Dec-2005 08:02
Trouble was with file function when long tags where broken by \r\n and function strip_tags worked not correctly with every element of array. This step prepare string from file for using function file and then strip_tags. (For example, html file generated by M$ Word)

<?php
$str = file_get_contents($filename);
$str = str_replace("\r\n", "\n", $str);
$opentag = 0;
$nl = 0;
for($i = 0; $i < strlen($str); $i++)
{
   if($opentag == 1 && $str[$i] == "\n")
   {
      $str[$i] = '  ';
      continue;
   }

   if($str[$i] == '<')
      $opentag = 1;
   elseif($str[$i] == '>')
      $opentag = 0;
   else ;

}
?>
thunberg at gmail dot com 13-Sep-2005 11:15
I wrote this because I wanted users to be able to do basic layout formatting by hitting enter in a textbox but still wanted to allow HTML elements (tables, lists, etc). The problem was in order for the output to be correct with nl2br the HTML had to be "scrunched" up so newlines wouldn't be converted; the following function solved my problem so I figured I'd share.

<?php

function nl2br_skip_html($string)
{
    // remove any carriage returns (mysql)
    $string = str_replace("\r", '', $string);

    // replace any newlines that aren't preceded by a > with a <br />
    $string = preg_replace('/(?<!>)\n/', "<br />\n", $string);

    return $string;
}

?>
webmaster at cafe-clope dot net 13-Aug-2005 03:50
based on previous notes, a generalist function that works with any <tag>...</tag>, and its ^-1. (use it with "li", for example) :

<?php
function nl2any($string, $tag = 'p', $feed = '') {
  // making tags
  $start_tag = "<$tag" . ($feed ? ' '.$feed : '') . '>' ;
  $end_tag = "</$tag>" ;

  // exploding string to lines
  $lines = preg_split('`[\n\r]+`', trim($string)) ;

  // making new string
  $string = '' ;
  foreach($lines as $line)
    $string .= "$start_tag$line$end_tag\n" ;

  return $string ;
}

function any2nl($string, $tag = 'p') {
  //exploding
  preg_match_all("`<".$tag."[^>]*>(.*)</".$tag.">`Ui", $string, $results) ;
  // reimploding without tags
  return implode("\n", array_filter($results[1])) ;
}
?>

I just had a problem when trying "`<$tag[^>]*>(.*)</$tag>`Ui" regexp string, I can't figure out why.
x against capital x at x everywhere x 11-Aug-2005 05:47
Regarding last post by admin at ninthcircuit, I think:

"rather than get into nasty regular expressions" === "I don't understand regular expressions"

No offense, but please be aware that kristen's solution is much more robust.  The ninthcircuit solution will miss cases when there are differences in case (e.g., BR instead of br) and when there is more than one space between the r and the / (e.g., <br    />).

We all like robust code, don't we?
admin at ninthcircuit dot info 06-Jun-2005 02:00
As stated in the manual above, PHP's nl2br() feature only puts a "<br />" tag before each newline ("\n"). So -- if you intend to code a br2nl() function for yourselves, all you have to do is remove every occurence of "<br />" or "<br>".

Rather than get into nasty regular expressions to accomplish this, just use what PHP has built in already --  str_replace():

<?php
    /* br2nl for use with HTML forms, etc. */
    function br2nl($text)
    {
        /* Remove XHTML linebreak tags. */
        $text = str_replace("<br />","",$text);
        /* Remove HTML 4.01 linebreak tags. */
        $text = str_replace("<br>","",$text);
        /* Return the result. */
        return $text;
    }
?>

The final result from this function being called is whatever was entered before XHTML/HTML linebreaks were added.

All newlines are preserved by default, as per PHP ln2br() specification. Since the code above preserves newlines also, you can expect your data to reappear in the same way it was entered.

Hope this helps.
kristen at paristemi dot com 16-May-2005 01:12
A note to add to the br2nl. Since nl2br doesn't remove the line breaks when adding in the <br /> tags, it is necessary to strip those off before you convert all of the tags, otherwise you will get double spacing. Here is the modified function:

function br2nl($str) {
    $str = preg_replace("/(\r\n|\n|\r)/", "", $str);
    return preg_replace("=<br */?>=i", "\n", $str);
}
sebastian at no spam flashhilfe.de 10-May-2005 08:16
// Convert only <br> <br /> and <br     /> to newline

function br2nl($str) {
   return preg_replace('=<br */?>=i', "\n", $str);
}

The Script at the bottom whit '!<br.*>!iU' match tags like <break> or something.
jochem at vuilnisbak dot com 02-Apr-2005 08:43
For people trying br2nl, but getting stuck at double newlines (or at least more then needed), try this:

<?php
function br2nl($coffee) {
    $coffee = str_replace("\r\n", "\n", $coffee); // make from windows-returns, *nix-returns
    $coffee = str_replace("<br />\n", "\n", $coffee); // to retrieve it
    return $coffee;
}
?>

The first thing \r\n is replacing linebreaks made on Windows systems. I believe *nix systems only place \n (not sure about it).

Have fun.

Jochem
webKami [at] akdomains.com 01-Apr-2005 04:54
here is the CSS friendly version, called nl2li_css()

Inputs a param css_class (default ="none") and pass it as class of All <li> List Items.

<?
function nl2li_css($str,$css_class = "none",$ordered = 0, $type = "1") {

//check if its ordered or unordered list, set tag accordingly
if ($ordered)
{
    $tag="ol";
    //specify the type
    $tag_type="type=$type";
}
else
{
    $tag="ul";
    //set $type as NULL
    $tag_type=NULL;
}

// add ul / ol tag
// add tag type
// add first list item starting tag - use css class
// add last list item ending tag
$str = "<$tag $tag_type><li class=\"$css_class\">" . $str ."</li></$tag>";

//replace /n with adding two tags
// add previous list item ending tag
// add next list item starting tag - use css class
$str = str_replace("\n","</li><br />\n<li class=\"$css_class\">",$str);

//spit back the modified string
return $str;
}
?>

Suggestions welcome again :)
webkami [at] gmail dout com 30-Mar-2005 07:42
A handy function to convert new line \n seprated text into ordered or unordered list. I am calling it nl2li, suggestions welcome. Second optional parameter sets the list as ordered (1) or unordered (0 = default). Third parameter can be used to specify type of ordered list, valid inputs are "1" = default ,"a","A","i","I".

function nl2li($str,$ordered = 0, $type = "1") {

//check if its ordered or unordered list, set tag accordingly
if ($ordered)
{
    $tag="ol";
    //specify the type
    $tag_type="type=$type";
}
else
{
    $tag="ul";
    //set $type as NULL
    $tag_type=NULL;
}

// add ul / ol tag
// add tag type
// add first list item starting tag
// add last list item ending tag
$str = "<$tag $tag_type><li>" . $str ."</li></$tag>";

//replace /n with adding two tags
// add previous list item ending tag
// add next list item starting tag
$str = str_replace("\n","</li><br />\n<li>",$str);

//spit back the modified string
return $str;
}
mike at openconcept dot ca 10-Mar-2005 10:02
There are other nl2p examples above, but think this one will provide nicer html.  Also threw in a very related br2p function for all of those folks who want to strip away the <br /> tags which give their designers the blues.

   /**
    * replacement for php's nl2br tag that produces more designer friendly html
    *
    * Modified from: http://www.php-editors.com/contest/1/51-read.html
    *
    * @param string $text
    * @param string $cssClass
    * @return string
    */
    function nl2p($text, $cssClass=''){

      // Return if there are no line breaks.
      if (!strstr($text, "\n")) {
         return $text;
      }

      // Add Optional css class
      if (!empty($cssClass)) {
         $cssClass = ' class="' . $cssClass . '" ';
      }

      // put all text into <p> tags
      $text = '<p' . $cssClass . '>' . $text . '</p>';

      // replace all newline characters with paragraph
      // ending and starting tags
      $text = str_replace("\n", "</p>\n<p" . $cssClass . '>', $text);

      // remove empty paragraph tags & any cariage return characters
      $text = str_replace(array('<p' . $cssClass . '></p>', '<p></p>', "\r"), '', $text);

      return $text;

   } // end nl2p

  /**
    * expanding on the nl2p tag above to convert user contributed
    * <br />'s to <p>'s so it displays more nicely.
    *
    * @param string $text
    * @param string $cssClass
    * @return string
    */
    function br2p($text, $cssClass=''){

      if (!eregi('<br', $text)) {
         return $text;
      }

      if (!empty($cssClass)) {
         $cssClass = ' class="' . $cssClass . '" ';
      }

      // put all text into <p> tags
      $text = '<p' . $cssClass . '>' . $text . '</p>';

      // replace all break tags with paragraph
      // ending and starting tags
      $text = str_replace(array('<br>', '<br />', '<BR>', '<BR />'), "</p>\n<p" . $cssClass . '>', $text);

      // remove empty paragraph tags
      $text = str_replace(array('<p' . $cssClass . '></p>', '<p></p>', "<p>\n</p>"), '', $text);

      return $text;
}

This is all code from Back-End CMS (http://www.back-end.org), a template based gpl php/mysql cms.

Mike
freedman AT freeformit . com 03-Mar-2005 04:45
here's a modified version that allows the addition of style tags to the <p> marker

function nl2p($str,$addtag='') {
    return str_replace('<p'.$addtag.'></p>', '', '<p'.$addtag.'>' . preg_replace('#\n|\r#', '</p>$0<p'.$addtag.'>', $str) . '</p>');
}

$x = "abc\ndef"
echo nl2p($x);  // outputs <p>abc</p>\n<p>def</p>

echo nl2p($x,' style="text-align:justify"');
// outputs <p style="text-align:justify">abc</p>\n<p style="text-align:justify">def</p>
asentis at gmail dot com 23-Feb-2005 05:06
If you want to respect W3C, you can use this function :

<?php
function nl2p($str)
{
  return str_replace('<p></p>', '', '<p>' . preg_replace('#\n|\r#', '</p>$0<p>', $str) . '</p>');
}
?>

Cya :)
CGameProgrammer at gmail dot com 30-Jan-2005 05:28
It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved.

If you don't want newlines, do:

<?php
$Result = str_replace( "\n", '<br />', $Text );
?>
17-Jan-2005 12:04
string nl2br_indent ( string string [, mixed indent] )

This function adds break tags before newlines as nl2br and also indents the text.
If indent is not specified, string will not be indented.

<?php

function nl2br_indent($string, $indent = 0)
{
    //remove carriage returns
    $string = str_replace("\r", '', $string);

    //convert indent to whitespaces if it is a integer.
    if (is_int($indent)) {
        //set indent to length of the string
        $indent = str_repeat(' ', (int)$indent);
    }

    //replace newlines with "<br />\n$indent"
    $string = str_replace("\n", "<br />\n".$indent, $string);
    //add  the indent to the first line too
    $string = $indent.$string;

    return $string;
}

?>

This is for example useful to indent text in html tags:

<?php

$str = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc
scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.'

echo '<html>'."\n";
echo '  <p>'."\n";
echo nl2br_indent($str, 4)."\n";
echo '  </p>'."\n";
echo '</html>'."\n";

?>

will return:

<html>
  <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.<br />
    In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc<br />
    scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.
  </p>
</html>

- $str is indented by 4 spaces.
spertica at tiscalinet dot it 14-Jan-2005 01:23
An easy way to get HTML formatted with <br> from a ASCII text file with CR & LF:

<?php
      $string_text=file_get_contents("/path_to/file.txt"); // load text file in var
      $new_text=nl2br($string_text); // convert CR & LF in <br> in newvar
      echo $new_text; // print out HTML formatted text
      unset($string_text, $new_text); // clear all vars to unload memory
 ?>
php at keithtyler dot com 05-Nov-2004 10:58
Take extreme care with nl2br(). It is a simple replacement function -- apparently equivalent to preg_replace("\n","<br \>\n").

It should not be used on input from HTML textareas, unless all HTML tags are stripped from the input first. nl2br() does not do anything special to newlines that occur within HTML elements (such as the <a> anchor tag).

Some browsers will submit textarea data with newlines inserted at the points where the user's input wrapped to the next line. This can cause anchor links to break and other erratic appearance of HTML:

<a <br \>href=http://us2.php.net/manual/en/function.nl2br.php>PHP nl2br()</a>

or worse:

<a href="http://www.site.com/user/page with <br />spaces.html">URL with spaces</a>

A lot of people use nl2br() to allow their users to insert explicit line and paragraph breaks via newlines, and their applications will exhibit this problem when used with such browsers.
php at sharpdreams dot com 05-Apr-2004 09:52
Better br2nl function (allows for non-valid XHTML tags). I find it useful for parsing 3rd party websites to convert their screwy BR formats to \n.

<?php
function br2nl( $data ) {
    return preg_replace( '!<br.*>!iU', "\n", $data );
}
?>
greywyvern - greywyvern - com 05-Feb-2004 01:11
Just a couple adjustments to the function below.

<?php

function nl2br_pre($string, $wrap = 40) {
  $string = nl2br($string);

  preg_match_all("/<pre[^>]*?>(.|\n)*?<\/pre>/", $string, $pre1);

  for ($x = 0; $x < count($pre1[0]); $x++) {
    $pre2[$x] = preg_replace("/\s*<br[^>]*?>\s*/", "", $pre1[0][$x]);
    $pre2[$x] = preg_replace("/([^\n]{".$wrap."})(?!<\/pre>)(?!\n)/", "$1\n", $pre2[$x]);
    $pre1[0][$x] = "/".preg_quote($pre1[0][$x], "/")."/";
  }

  return preg_replace($pre1[0], $pre2, $string);
}

?>

You might ask, why not just use:
<?php $string = str_replace("\n", "<br />", $string); ?>

... and prevent double spacing that way by actually *replacing* the \n with <br />, whereas nl2br() *inserts* a <br />.

Well, the answer is, doing it that way makes all the HTML output appear on a single line!  Ugly, to say the least.  The function above will keep your HTML source output formatted the same way you input it. :)
matt at mullenweg dot com 15-Oct-2002 08:23
I put together a little function to convert multiple line breaks into XHTML paragraph tags. It also changes newlines within the psuedo-paragraphs to <br />. This should be well suited to CMS where (in my case) you don't want the client to deal with *any* HTML but you still want proper paragraphs for your pages.

USAGE: You can write your text just like I have here, using the enter key as the only formatting tool. This can probably be made more efficient and I'll keep an updated (and unmangled) version of it at
http://www.photomatt.net/scripts/autop
nl_langinfo
number_format
Обработка строк


Форматирует число с разделением групп

nl2br
ord
Обработка строк
PHP Manual

number_format

(PHP 4, PHP 5)

number_format — Форматирует число с разделением групп

Описание

string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

Функция принимает один, два или четыре аргумента (не три):

Если передан только один аргумент, number будет отформатирован без дробной части, но с запятой (",") между каждыми тремя цифрами.

Если переданы два аргумента, number будет отформатирован с decimals знаками после точки (".") и с запятой (",") между каждыми тремя цифрами.

Если переданы все четыре аргумента, number будет отформатирован с decimals знаками после точки и с разделителем между между каждыми тремя цифрами, при этом в качестве десятичной точки будет использован dec_point, а в качестве разделителя групп - thousands_sep.

Список параметров

number

Форматируемое число.

decimals

Устанавливает число знаков после запятой.

dec_point

Устанавливает разделитель дробной части.

thousands_sep

Устанавливает разделитель тысяч.

Возвращаемые значения

Возвращается отформатированное число number.

Список изменений

Версия | Описание
5.4.0 | Функция поддерживает многобайтную строку в качестве параметров dec_point и thousands_sep. В предыдущих версиях в качестве разделителя использовался только первый байт из каждого параметра.

Примеры

Пример #1 Пример использования number_format()

Во Франции обычно используются 2 знака после запятой (','), и пробел (' ') в качестве разделителя групп. Такое форматирование получается при использовании следующего кода:

<?php

$number = 1234.56;

// английский формат (по умолчанию)
$english_format_number = number_format($number);
// 1,235

// французский формат
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// английский формат без разделителей групп
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

Смотрите также

  • money_format() - Форматирует число как денежную величину
  • sprintf() - Возвращает отформатированную строку
  • printf() - Выводит отформатированную строку
  • sscanf() - Разбирает строку в соответствии с заданным форматом

User Contributed Notes

vgurudev at nikshepa dot com 04-May-2012 08:37
<?php

    function convertNumberToWordsForIndia($number){
        //A function to convert numbers into Indian readable words with Cores, Lakhs and Thousands.
        $words = array(
        '0'=> '' ,'1'=> 'one' ,'2'=> 'two' ,'3' => 'three','4' => 'four','5' => 'five',
        '6' => 'six','7' => 'seven','8' => 'eight','9' => 'nine','10' => 'ten',
        '11' => 'eleven','12' => 'twelve','13' => 'thirteen','14' => 'fouteen','15' => 'fifteen',
        '16' => 'sixteen','17' => 'seventeen','18' => 'eighteen','19' => 'nineteen','20' => 'twenty',
        '30' => 'thirty','40' => 'fourty','50' => 'fifty','60' => 'sixty','70' => 'seventy',
        '80' => 'eighty','90' => 'ninty');

        //First find the length of the number
        $number_length = strlen($number);
        //Initialize an empty array
        $number_array = array(0,0,0,0,0,0,0,0,0);
        $received_number_array = array();

        //Store all received numbers into an array
        for($i=0;$i<$number_length;$i++){    $received_number_array[$i] = substr($number,$i,1);    }

        //Populate the empty array with the numbers received - most critical operation
        for($i=9-$number_length,$j=0;$i<9;$i++,$j++){ $number_array[$i] = $received_number_array[$j]; }
        $number_to_words_string = "";
        //Finding out whether it is teen ? and then multiplying by 10, example 17 is seventeen, so if 1 is preceeded with 7 multiply 1 by 10 and add 7 to it.
        for($i=0,$j=1;$i<9;$i++,$j++){
            if($i==0 || $i==2 || $i==4 || $i==7){
                if($number_array[$i]=="1"){
                    $number_array[$j] = 10+$number_array[$j];
                    $number_array[$i] = 0;
                }
            }
        }

        $value = "";
        for($i=0;$i<9;$i++){
            if($i==0 || $i==2 || $i==4 || $i==7){    $value = $number_array[$i]*10; }
            else{ $value = $number_array[$i];    }
            if($value!=0){ $number_to_words_string.= $words["$value"]." "; }
            if($i==1 && $value!=0){    $number_to_words_string.= "Crores "; }
            if($i==3 && $value!=0){    $number_to_words_string.= "Lakhs ";    }
            if($i==5 && $value!=0){    $number_to_words_string.= "Thousand "; }
            if($i==6 && $value!=0){    $number_to_words_string.= "Hundred &amp; "; }
        }
        if($number_length>9){ $number_to_words_string = "Sorry This does not support more than 99 Crores"; }
        return ucwords(strtolower("Indian Rupees ".$number_to_words_string)." Only.");
    }

    echo convertNumberToWordsForIndia("987654321");

    //Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>
before_i_sleep at hotmail dot co dot uk 27-Apr-2012 02:26
As many people state the number_format function will round. Now if your like me and you don't want stuff to round (and the functions below do not work for you) you can try a little regex:

function convert_size_human($size){
    $unit=array('','KB','MB','GB','TB','PB');
    $byte_size = $size/pow(1024,($i=floor(log($size,1024))));

    if(is_really_int($byte_size)){
        return $byte_size.' '.$unit[$i];
    }else{
        preg_match('/^[0-9]+\.[0-9]{2}/', $byte_size, $matches);
        return $matches[0].' '.$unit[$i];
    }
}

The regex used when the number is not an int ensures that 3.99887 GB comes out as 3.99 GB instead of 4GB as it does from number_format or the functions below.
qwantastic 13-Feb-2012 07:04
I was looking for a way to format a number to a certain number of significant digits, instead of decimal points.

This is what I came up with:

<?php
function number_significant($x, $n) {
 $x_sci = sprintf("%.".$n."e", $x);
 $x_f = rtrim(sprintf("%f", $x_sci),"0");
 if ( $x_f[strlen($x_f)-1]=="." ) {
  $x_f .= "0";
 }
 return $x_f;
}
?>
liviu andrei (bls) 18-Nov-2011 08:10
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):

<?php
function fnumber_format($number, $decimals='', $sep1='', $sep2='') {

        if (($number * pow(10 , $decimals + 1) % 10 ) == 5)  //if next not significant digit is 5
            $number -= pow(10 , -($decimals+1));

        return number_format($number, $decimals, $sep1, $sep2);

}

$t=7.15;
echo $t . " | " . number_format($t, 1, '.', ',') .  " | " . fnumber_format($t, 1, '.', ',') . "\n\n";
//result is: 7.15 | 7.2 | 7.1

$t=7.3215;
echo $t . " | " . number_format($t, 3, '.', ',') .  " | " . fnumber_format($t, 3, '.', ',') . "\n\n";
//result is: 7.3215 | 7.322 | 7.321
} ?>

have fun!
t dot ulrich at airbus-pilots dot com 29-Aug-2011 05:48
leading zero´s are easier to do with some small if statement

<?php
$number = 123.3;

$number = explode(".",$number);

if(substr($number[1],1,1) == ""){
       $number[1] = $number[1] . "0";
}

$number = $number[0]. "." .$number[1];
?>

easy...
robmann at gmx dot li 05-May-2011 04:02
Here a function to filter exponential notation like 6e-06. Turn it to 0,000006 for comfortable reading. Supporting various number of decimals!

<?php
function easy_number_format($number, $dec_point, $thousands_sep)
{
    $number = rtrim(sprintf('%f', $number), "0");
    if (fmod($nummer, 1) != 0) {
        $array_int_dec = explode('.', $number);
    } else {
        $array_int_dec= array(strlen($nummer), 0);
    }
    (strlen($array_int_dec[1]) < 2) ? ($decimals = 2) : ($decimals = strlen($array_int_dec[1]));
    return number_format($number, $decimals, $dec_point, $thousands_sep);
}
?>

The maximum accuracy depends on sprintf('%f', $number). In this case 6 decimals. Expand it to 10 with '%.10f'.
info at swedishboy dot se 24-Jan-2011 03:12
There has been some suggestions around on how to keep trailing zeros. Best way is to use the example for currency provided by the php-crew in the sprintf function help section.

That is:
<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;

// echo $money will output "123.1";

$formatted = sprintf("%01.2f", $money); // << this does the trick!

// echo $formatted will output "123.10"

?>
WayneH 29-Nov-2010 02:24
When using number_format to create a string for output to a CSV file you will need to override the default thousands separator of "," with null ("") so that 1,000 becomes 1000 !!!
Ali Okan YKSEL 26-Oct-2010 02:47
function formats numbers of datetime type,

<?php
$_GET["zaman"]="1983-8-28 5:5:5";

function _parseDatetimeToList($datetimeStr) { //datetime format: Y-m-d H-i-s
    $datetimeArray=explode(" ", $datetimeStr);
    $dateArray=explode("-",$datetimeArray[0]);
    $year=str_pad($dateArray[0], 2, "0", STR_PAD_LEFT);
    $month=str_pad($dateArray[1], 2, "0", STR_PAD_LEFT);
    $day=str_pad($dateArray[2], 2, "0", STR_PAD_LEFT);
    $timeArray=explode(":",$datetimeArray[1]);
    $hour=str_pad($timeArray[0], 2, "0", STR_PAD_LEFT);
    $minute=str_pad($timeArray[1], 2, "0", STR_PAD_LEFT);
    $second=str_pad($timeArray[2], 2, "0", STR_PAD_LEFT);
    return array($year, $month, $day, $hour, $minute, $second);
}

list($year, $month, $day, $hour, $minute, $second) = _parseDatetimeToList($_GET["zaman"]);  // 1983-1-28 5:5:5
?>
Ricky *@* Mataka [com] 15-Oct-2010 11:10
Hey Guys, dont know if this is the best way but it worked for me as i faced a problem where I had to split any large number > then 10K into into to exact split amounts.. so i wrote this this to do the trick.. hope it helps some one out there!

<?php
function divide22($num)
{
  $valone = intval($num / 2);
  $valtwo = $valone;
  if (($num % 2) > 0) $valtwo++;
  return array($valone, $valtwo);
}
function split2vals($num,$split_amount)
{
  $store=array();
  $times = round(($num/$split_amount));
  $amount= $num/$times;
  for($i=0;$i<$times;$i++)
  {
     $store[]=round($amount);
  }
  foreach($store as $index=>$value)
  {
    if($value>$split_amount)
    {
       $get_splits=divide22($value);
       //unset the split
       unset($store[$index]);
       $store[]=$get_splits[0];
       $store[]=$get_splits[1];
    }
  }
  $sum=array_sum($store);

  if($sum > $num){
    $sub=$sum-$num;
      $end=end($store);
    array_pop($store);
    $store[]=$end-$sub;
  }
  if($sum < $num){
    $store[]=($num-$sum);
  }
  return $store;
}

//USAGE

$check_amount=50567.83;
echo 'Input Split = '.$check_amount.'<br><br>';
$store=split2vals($check_amount,10000);
print_r($store);
$sum=array_sum($store);
echo '<br><br>Should Be Exact ='. $sum;
exit();
?>
Anonymous 13-Oct-2010 02:52
Caution should be taken with large "string" values. This is due to the precision issues with converting a string to a float.

For example:

<?php
$org_num = "255173029255255255";
echo "<br>org: ".$org_num;
echo "<br>".number_format($org_num);
?>

returns:
org: 255173029255255255
255,173,029,255,255,264

Here is the function that can be used instead

<?php
function numberFormat($num)
{
     return preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$num);
}
?>
Cody G. 08-Aug-2010 02:06
Sometimes, I'm sure, you guys are looking for a way to do the exact opposite of this function: convert a comma-filled number back to normal decimal.
Here's a quick code that popped into my head today:

<?php
 $mynumstr = "100,000,000.75";
 $mynum = doubleval(str_replace(",","",$mynumstr));
?>

This is especially useful when validating user input. Some people like to include comma's with their numbers.
Some also like to include the dollar-sign when entering prices. Here's a modification:

<?php
 $mynumstr = '$100,000,000.25';
 $arr1 = array(',','$');
 $arr2 = array('','');
 $mynum = doubleval(str_replace($arr1,$arr2,$mynumstr));
 //The arrays had to be defined in a
 //  variable to shorten statement.
?>

Okay, that takes care of it, I use the PHP4 array compatibility update to remove several characters.
Don't forget to either use single-quotes or escape the dollar-sign!

~Cody G.
me dot nosp at m dot unreal4u dot com 08-Jul-2010 12:36
Maybe it is documented, but I just missed it. However, a comment is always useful.

An array will always be converted into 1, so, if you have:

<?php
$my_array = array(55);
echo number_format($my_array,0,',','.');
// 1
var_dump(number_format($my_array,2,',','.'));
// string(4) "1,00"
?>

Since it took me a while to figure it out, I hope this will save somebody's time.

Greetings !!
isedc at yahoo dot com 29-Mar-2010 12:38
Some programmers may have scripts that use the number_format function twice on a variable.  However, if a number is 4 or more digits, using the function twice with only the decimals parameter will lose part of the value that follows the thousands separator.

<?php
$var = number_format(2234,2);
$var = number_format($var,2);
echo $var;
# Expected Output: 2,234.00
# Actual Output: 2.00
?>

To fix, remove the thousands separator by setting the decimal point and thousands separator parameters like so:

<?php
$var = number_format(2234,2,'.','');
$var = number_format($var,2,'.','');
echo $var;
# Expected Output: 2234.00
# Actual Output: 2234.00
?>

If it's 3 digits or less, then it works normally with only the decimals parameter since there is no thousands separator.

<?php
$var = number_format(123,2);
$var = number_format($var,2);
echo $var;
# Expected Output: 123.00
# Actual Output: 123.00
?>
dipu dot ashok dot 17 at gmail dot com 28-Mar-2010 01:18
function to convert numbers to words
indian: thousand,lakh,crore
Note: function can only convert nos upto 99 crores

<?php
 $words = array('0'=> '' ,'1'=> 'one' ,'2'=> 'two' ,'3' => 'three','4' => 'four','5' => 'five','6' => 'six','7' => 'seven','8' => 'eight','9' => 'nine','10' => 'ten','11' => 'eleven','12' => 'twelve','13' => 'thirteen','14' => 'fouteen','15' => 'fifteen','16' => 'sixteen','17' => 'seventeen','18' => 'eighteen','19' => 'nineteen','20' => 'twenty','30' => 'thirty','40' => 'fourty','50' => 'fifty','60' => 'sixty','70' => 'seventy','80' => 'eighty','90' => 'ninty','100' => 'hundred &','1000' => 'thousand','100000' => 'lakh','10000000' => 'crore');
function no_to_words($no)
{    global $words;
    if($no == 0)
        return ' ';
    else {           $novalue='';$highno=$no;$remainno=0;$value=100;$value1=1000;
            while($no>=100)    {
                if(($value <= $no) &&($no  < $value1))    {
                $novalue=$words["$value"];
                $highno = (int)($no/$value);
                $remainno = $no % $value;
                break;
                }
                $value= $value1;
                $value1 = $value * 100;
            }
          if(array_key_exists("$highno",$words))
              return $words["$highno"]." ".$novalue." ".no_to_words($remainno);
          else {
             $unit=$highno%10;
             $ten =(int)($highno/10)*10;
             return $words["$ten"]." ".$words["$unit"]." ".$novalue." ".no_to_words($remainno);
           }
    }
}
echo no_to_words(999978987);

?>
binarte at gmail dot com 24-Dec-2009 09:10
number_format is deficient in the sense that it is currently unable to output numbers in japanese format (grouping algarisms in tens of thousands instead of thousands).
The alternative below will work just like number_format, but the added $group parameter allows to change how many algarisms per group the output will have.

<?php

function numberFormat  ($number  , $decimals = 2 , $dec_point = '.' , $sep = ',', $group=3   ){
    $num = sprintf("%0.{$decimals}f",$number);
    $num = explode('.',$num);
    while (strlen($num[0]) % $group) $num[0]= ' '.$num[0];
    $num[0] = str_split($num[0],$group);
    $num[0] = join($sep[0],$num[0]);
    $num[0] = trim($num[0]);
    $num = join($dec_point[0],$num);

    return $num;
}

echo numberformat(123456789,0,'.',' ',4); // 1 2345 6789

?>
Horvath, Sandor [HU] 05-Oct-2009 01:19
Because I had a lot of problems with number_format, here is a working, simple and small replacement:

<?php
function FormatNumber($number, $decimals = 0, $thousand_separator = '&nbsp;', $decimal_point = '.')
{
  $tmp1 = round((float) $number, $decimals);

  while (($tmp2 = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $tmp1)) != $tmp1)
    $tmp1 = $tmp2;

  return strtr($tmp1, array(' ' => $thousand_separator, '.' => $decimal_point));
}

echo FormatNumber(-913578.1415, 2, '.', ',') . "\n";
?>
Will Shaver 24-Aug-2009 11:42
Previous to version 4.3 an empty string as the first parameter would not cause an error. Now checking to make sure the string is empty before calling number_format is needed.
Peter de Pijd 17-Aug-2009 08:35
If you want to use nbsp as decimal/thousand delimiter with UTF-8 you have to replace the whitespace after using number_format:

<?php
$number = number_format(1000, 0, ".", " "); // normal space
echo str_replace(" ", utf8_encode("\xA0"), $number);
// or
echo str_replace(" ", html_entity_decode("&nbsp;", ENT_COMPAT, "UTF-8"), $number);
?>
therealsix 02-Jul-2009 08:40
I found you can add trailing zeroes simply by adding a float point value containing the number of decimal places you want to appear.

<?php
$number = 5.2;
$number += .0000;
echo $number;
?>

Outputs:
5.2000
info at daniel-marschall dot de 22-May-2009 12:54
In my function my_number_format() [shown below] there was a bug.

If a negative number which is smaller than 1 was entered (-0,...), then the result was wrongly positive because +0 is equal to -0 (the content of $tmp[0] which was interpretet as numeric value).

Here is the corrected version:

<?php

function my_number_format($number, $dec_point, $thousands_sep)
{
    $was_neg = $number < 0; // Because +0 == -0
    $number = abs($number);

    $tmp = explode('.', $number);
    $out = number_format($tmp[0], 0, $dec_point, $thousands_sep);
    if (isset($tmp[1])) $out .= $dec_point.$tmp[1];

    if ($was_neg) $out = "-$out";

    return $out;
}

?>

Thanks to Federico Cassinelli for the bug report.

[EDIT BY danbrown AT php DOT net: The original note follows.]

Let's say we got the number $inp = 1234.56

By using

<?php
return number_format($inp, 2, ',', '.');
?>

you can get the German format 1.234,56. (Comma as decimal separator and point as thousand separator)

But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits!

But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function.

But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456

So, I created following function, that doesn't change the amount of fractional digits:

<?php
function my_number_format($number, $dec_point, $thousands_sep)
{
  $tmp = explode('.', $number);
  $out = number_format($tmp[0], 0, $dec_point, $thousands_sep);
  if (isset($tmp[1])) $out .= $dec_point.$tmp[1];

  return $out;
}
?>
james at bandit dot co.nz 26-Mar-2009 09:03
Outputs a human readable number.

<?php
    #    Output easy-to-read numbers
    #    by james at bandit.co.nz
    function bd_nice_number($n) {
        // first strip any formatting;
        $n = (0+str_replace(",","",$n));

        // is this a number?
        if(!is_numeric($n)) return false;

        // now filter it;
        if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
        else if($n>1000000000) return round(($n/1000000000),1).' billion';
        else if($n>1000000) return round(($n/1000000),1).' million';
        else if($n>1000) return round(($n/1000),1).' thousand';

        return number_format($n);
    }
?>

Outputs:

247,704,360 -> 247.7 million
866,965,260,000 -> 867 billion
IMSoP 18-Mar-2009 02:36
I'm not sure if this is the right place anyway, but "ben at last dot fm"'s ordinal function can be simplified further by removing the redundant "floor" (the result of floor is still a float, it's the "%" that's converting to int) and outer switch.

Note that this version also returns the number with the suffix on the end, not just the suffix.

<?php
function ordinal($num)
{
    // Special case "teenth"
    if ( ($num / 10) % 10 != 1 )
    {
        // Handle 1st, 2nd, 3rd
        switch( $num % 10 )
        {
            case 1: return $num . 'st';
            case 2: return $num . 'nd';
            case 3: return $num . 'rd';
        }
    }
    // Everything else is "nth"
    return $num . 'th';
}
?>
ben at last dot fm 27-Feb-2009 04:22
Writing a function to get English ordinals for numbers is a problem every computer science student will face. Here's my solution - nice, short and simple:

<?php
    function st($i) {
        switch( floor($i/10) % 10 ) {
            default:
                switch( $i % 10 ) {
                    case 1: return 'st';
                    case 2: return 'nd';
                    case 3: return 'rd';
                }
            case 1:
        }
        return 'th';
    }
?>
Barbara 26-Jan-2009 11:04
I was looking for a SIMPLE way to format currency and account for negative values while not losing the calculation properties of my number.  Here's my function - it's not rocket science, but maybe can help someone along the way.

<?php
function wims_currency($number) {
   if ($number < 0) {
     $print_number = "($ " . str_replace('-', '', number_format ($number, 2, ".", ",")) . ")";
    } else {
     $print_number = "$ " .  number_format ($number, 2, ".", ",") ;
   }
   return $print_number;
}
?>
Sample use:

<?php
$pur_po_total =  ($pur_po_total + $pur_item_total);
$print_pur_po_total = wims_currency($pur_po_total);
?>

Returns (for example)    $ 44,561.00 or, if a negative ($ 407,250.00)

This way, I use my 1st variable for calculations and my 2nd variable for output.  I'm sure there are better ways to do it,  but this got me back on track.
thomas at weblizards dot de 23-Jan-2009 05:43
It's not explicitly documented; number_format also rounds:

<?php
$numbers = array(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009);
foreach ($numbers as $number)
    print $number."->".number_format($number, 2, '.', ',')."<br>";
?>

0.001->0.00
0.002->0.00
0.003->0.00
0.004->0.00
0.005->0.01
0.006->0.01
0.007->0.01
0.008->0.01
0.009->0.01
nospam at nospam dot com 02-Dec-2008 02:08
Simple function to show money as only dollars if no cents, but will show 2 decimals if cents exist.

The 'cents' flag can force to never or always show 2 decimals

<?php

// formats money to a whole number or with 2 decimals; includes a dollar sign in front
function formatMoney($number, $cents = 1) { // cents: 0=never, 1=if needed, 2=always
  if (is_numeric($number)) { // a number
    if (!$number) { // zero
      $money = ($cents == 2 ? '0.00' : '0'); // output zero
    } else { // value
      if (floor($number) == $number) { // whole number
        $money = number_format($number, ($cents == 2 ? 2 : 0)); // format
      } else { // cents
        $money = number_format(round($number, 2), ($cents == 0 ? 0 : 2)); // format
      } // integer or decimal
    } // value
    return '$'.$money;
  } // numeric
} // formatMoney

$a = array(1, 1234, 1.5, 1.234, 2.345, 2.001, 2.100, '1.000', '1.2345', '12345', 0, '0.00');

// show cents if needed ($cents=1)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 1));
1 = $1
1234 = $1,234
1.5 = $1.50
1.234 = $1.23
2.345 = $2.35
2.001 = $2.00
2.1 = $2.10
1.000 = $1
1.2345 = $1.23
12345 = $12,345
0 = $0
0.00 = $0

// never show cents ($cents=0)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 0));
1 = $1
1234 = $1,234
1.5 = $2
1.234 = $1
2.345 = $2
2.001 = $2
2.1 = $2
1.000 = $1
1.2345 = $1
12345 = $12,345
0 = $0
0.00 = $0

// always show cents ($cents=2)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 2));
1 = $1.00
1234 = $1,234.00
1.5 = $1.50
1.234 = $1.23
2.345 = $2.35
2.001 = $2.00
2.1 = $2.10
1.000 = $1.00
1.2345 = $1.23
12345 = $12,345.00
0 = $0.00
0.00 = $0.00

?>

Cheers :)

And remember to always contribute custom functions if they might be useful to the rest of us or future versions of the php language.
samuelpeixoto at gmail dot com 21-Nov-2008 05:05
Exemplo: Example:

<?php
$number = 1234567.896;
echo '1: '.number_format($number, 2, ',', '').'<br>';
echo '2: '.number_format($number, 2, '.', '').'<br>';
echo '3: '.number_format($number, 2, ',', '.').'<br>';
echo '4: '.number_format($number, 2, '.', ',').'<br>';
echo '5: '.number_format($number, 2, ',', ' ').'<br>';
echo '6: '.number_format($number, 2, ',', "'").'<br>';
echo '7: '.number_format($number, 2, '', '').'<br>';
?>

Resultado: Result:

 1: 1234567,90   -> Decimal separado por ,
 2: 1234567.90   -> Decimal separado por .
 3: 1.234.567,90 -> Moeda Brasil, Alemanha
 4: 1,234,567.90 -> Inglês, USA
 5: 1 234 567,90 -> França
 6: 1'234'567,90 -> Suíça
 7: 123456790    -> Sem decimal
with at held dot com 16-Sep-2008 11:17
Note:
The accuracy tends to drift if you're setting a large decimal value.

<?php
$number = 1234.560;
echo number_format($number, 2, '.', '');
echo number_format($number, 3, '.', '');
echo number_format($number, 4, '.', '');
echo number_format($number, 10, '.', '');
echo number_format($number, 20, '.', '');
echo number_format($number, 50, '.', '');
?>

echos this (for me at least).

1234.56
1234.560
1234.5600
1234.5600000000
1234.55999999999994543032
1234.55999999999994543031789362430572509765625000000000

SyCo
isapoetra at gmail dot com 15-Jun-2008 06:53
here is the code to convert number to Indonesian text, this code has limitation as is number_format function. sorry for this.
/*
* Created : Iwan Sapoetra - Jun 13, 2008
* Project : Web
* Package : cgaf
*
*/
function terbilang( $num ,$dec=4){
    $stext = array(
        "Nol",
        "Satu",
        "Dua",
        "Tiga",
        "Empat",
        "Lima",
        "Enam",
        "Tujuh",
        "Delapan",
        "Sembilan",
        "Sepuluh",
        "Sebelas"
    );
    $say  = array(
        "Ribu",
        "Juta",
        "Milyar",
        "Triliun",
        "Biliun", // remember limitation of float
        "--apaan---" ///setelah biliun namanya apa?
    );
    $w = "";

    if ($num <0 ) {
        $w  = "Minus ";
        //make positive
        $num *= -1;
    }

    $snum = number_format($num,$dec,",",".");
    die($snum);
    $strnum =  explode(".",substr($snum,0,strrpos($snum,",")));
    //parse decimalnya
    $koma = substr($snum,strrpos($snum,",")+1);

    $isone = substr($num,0,1)  ==1;
    if (count($strnum)==1) {
        $num = $strnum[0];
        switch (strlen($num)) {
            case 1:
            case 2:
                if (!isset($stext[$strnum[0]])){
                    if($num<19){
                        $w .=$stext[substr($num,1)]." Belas";
                    }else{
                        $w .= $stext[substr($num,0,1)]." Puluh ".
                            (intval(substr($num,1))==0 ? "" : $stext[substr($num,1)]);
                    }
                }else{
                    $w .= $stext[$strnum[0]];
                }
                break;
            case 3:
                $w .=  ($isone ? "Seratus" : terbilang(substr($num,0,1)) .
                    " Ratus").
                    " ".(intval(substr($num,1))==0 ? "" : terbilang(substr($num,1)));
                break;
            case 4:
                $w .=  ($isone ? "Seribu" : terbilang(substr($num,0,1)) .
                    " Ribu").
                    " ".(intval(substr($num,1))==0 ? "" : terbilang(substr($num,1)));
                break;
            default:
                break;
        }
    }else{
        $text = $say[count($strnum)-2];
        $w = ($isone && strlen($strnum[0])==1 && count($strnum) <=3? "Se".strtolower($text) : terbilang($strnum[0]).' '.$text);
        array_shift($strnum);
        $i =count($strnum)-2;
        foreach ($strnum as $k=>$v) {
            if (intval($v)) {
                $w.= ' '.terbilang($v).' '.($i >=0 ? $say[$i] : "");
            }
            $i--;
        }
    }
    $w = trim($w);
    if ($dec = intval($koma)) {
        $w .= " Koma ". terbilang($koma);
    }
    return trim($w);
}
//example
echo terbilang(999999999999)."\n";
/**
 * result : Sembilan Ratus Sembilan Puluh Sembilan Milyar Sembilan Ratus Sembilan Puluh Sembilan Juta Sembilan Ratus Sembilan Puluh Sembilan Ribu Sembilan Ratus Sembilan Puluh Sembilan
 */
echo terbilang(9999999999999999);
/**
 * todo : fix this bug pleasese
 * problem : number_format(9999999999999999) <--- 10.000.000.000.000.000,0000
 * Result : Sepuluh Biliun
 */
xkeeper at gmail dot com 09-Jun-2008 10:26
Technically, you can just use number_format() with "x" as the thousands seperator, then...

<?php
  str_replace("x", "character of choice", number_format(1234.56, ".", "x"));
?>

This will probably be many times more efficient.
team at glossword dot biz 26-May-2008 06:45
It's pity that the function supports one-byte characters only for "thousands separator".
For English it works well but for French and Russian it makes problem.
Developers should use character &#160; or chr(0xA0) as "thousands separator" to avoid the number of being moved to a new line in HTML-documents. But number_format() didn't understand that symbol.
To solve the problem, we wrote our own variant of number_format():

<?php
/* Replacement for number_format() */
function my_number_format($n, $decimals = 0, $dec_point = ',', $thousands_sep = '&#160;')
{
    $b = explode('.', $n);
    $rn = '';
    $l = strlen($b[0]);
    /* Reverse string */
    for ($i = $l; $i > 3; $i -= 3)
    {
        $rn = $thousands_sep . substr($b[0], $i - 3, 3) . $rn;
    }
    /* sprintf() used to correct 0.79 to 0.790 */
    /* str_replace() used to correct decimals */
    /* str_repeat() used to correct decimals */
    return substr($b[0], 0, $i) . $rn . ($decimals
            ? $dec_point.(isset($b[1])
                ? str_replace('0.', '', sprintf('%0.'.$decimals.'f', '0.'.$b[1]))
                : str_repeat(0, $decimals))
            : '');
}
/* Outputs 123&#160;456,790 */
print my_number_format(123456.78987, 3);
?>

It can be optimized more, but this variant works well also.
gabrielu at gmail dot com 08-May-2008 09:54
Using the number_format I'm having some unexpected results.  30% of 14.95 (14.95 * .3) = 4.485.  Now 4.485 rounded to two decimal places should give me 4.49.

Example:
<?php
echo number_format(14.95 * .3, 2, '.', '') . "\n";
echo number_format(4.485, 2, '.', '') . "\n";
?>

Unexpected Results:
4.48
4.49
eregon at msn dot com 30-Jan-2008 01:02
I have seen some scripts here for format a filesize, but i think this can be useful:

<?php
function format_filesize($number, $decimals = 3, $force_unit = false, $dec_char = ',', $thousands_char = ' ')
    {//string format_filesize(int(0,) $number, (bool(0), int(0,4)) $force_unit, int $decimals, char $dec_char, char $thousands_char)
    //format a filesize $number with unit (setted by $force_unit(see below for the number))
        $units = array('o', 'Ko', 'Mo', 'Go', 'To');
        if($force_unit === false)
            $unit = floor(log($number, 2) / 10);
        else
            $unit = $force_unit;
        if($unit == 0)
            $decimals = 0;
        return number_format($number / pow(1024, $unit), $decimals, $dec_char, $thousands_char).' '.$units[$unit];
    }
?>

ex:
format_filesize(2540367) => '2,423 Mo'
format_filesize(2540367, 2) => '2,42 Mo'
format_filesize(2540367, 1, 1) => '2 480,8 Ko' //0=>'o', 1=>'Ko', 2=>'Mo', 3=>'Go', 4=>'To' (see $units)
format_filesize(2540687367, 2, 1, ',', '.') => '2.481.140,01 Ko'

log($number, 2) / 10 = log($number, 1024) ;)
Fast & Easy, isn't it? :)
www.produkte24.com 08-Jan-2008 12:28
I have to verify price data from several formats, eg:
- 12.345,67 (German)
- 12,345.67 (English)
- 12 345,67 (French)
- 12'345,67 (Swiss)

Here is a quick function which helps me out of all this format mess, but please not the I only check for:
- positive values
- max 2 digits on the right side (.12)

function mk_price_to_float($price){
    $price = trim($price);
    if(preg_match("~^([0-9]+|(?:(?:[0-9]{1,3}([.,' ]))+[0-9]{3})+)(([.,])[0-9]{1,2})?$~", $price, $r)){
        if(!empty($r['2'])){
            $pre = preg_replace("~[".$r['2']."]~", "", $r['1']);
        }else{
            $pre = $r['1'];
        }
        if(!empty($r['4'])){
            $post = ".".preg_replace("~[".$r['4']."]~", "", $r['3']);
        }else{
            $post = false;
        }
        $form_price = $pre.$post;
        return $form_price;
    }
    return false;
}

This code is used at http://www.produkte24.com/ and http://www.who-sells-it.com/ and works like a charm.
uliciadrian01 at yahoo dot com 06-Oct-2007 02:34
A simple funtion to format american dollars.
<?
function formatMoney($money) {
    if($money<1) {
        $money='&cent;'.$money*100;
    }
    else {
        $dollars=intval($money);
        $cents=$money-$dollars;
        $cents=$cents*100;
        $money='$'.$dollars.' and &cent;'.$cents;
    }
    return $money;
}
echo formatmoney('52.342');
?>
This will output: "   $52 and ¢34.2  ".
eb1024 at gmail dot com 11-Aug-2007 10:38
To address the problems number_format has when dealing with big numbers I've created my own Number_Format method, it acts the same way as number_format and takes the same arguments but deals with numbers as strings solving the problems above referred.

(The other methods are available at http://www.alixaxel.com/wordpress/2007/05/19/php-math-library/)

function Number_Format($number, $decimal_precision = 0, $decimals_separator = '.', $thousands_separator = ',')
{
if ($this->Is_Negative($number))
{
    $negative = true;

    $number = str_replace('-', '', $number);
}

$number = explode('.', str_replace(' ', '', $number));

$number[0] = str_split(strrev($number[0]), 3);

$total_segments = count($number[0]);

for ($i = 0; $i < $total_segments; $i++)
{
    $number[0][$i] = strrev($number[0][$i]);
}

$number[0] = implode($thousands_separator, array_reverse($number[0]));

if ($negative === true)
{
    $number[0] = '-' . $number[0];
}

if (!empty($number[1]))
{
    $number[1] = $this->Round($number[1], $decimal_precision);
}

$number = implode($decimals_separator, $number);

return $number;
}

I hope this is useful for someone!
Jason Johnson 01-Aug-2007 12:39
Beware of this pitfall:
$value = number_format ($float_val, 2, ".");

This will silently return an empty string and not throw an error, at least with PHP 5.x.

This is the corrected code:
$value = number_format ($float_val, 2, ".", ",");
- or -
$value = number_format ($float_val, 2);

You must specifiy either the decimal point AND thousands separator else neither, otherwise you'll run into this issue.

I just spent over 30min debugging code with this problem!
user at example dot net 16-Jul-2007 07:52
The following function converts a string into Float or Integer while taking the given or locale number format into account.

<?php

    function strtonumber( $str, $dec_point=null, $thousands_sep=null )
    {
        if( is_null($dec_point) || is_null($thousands_sep) ) {
            $locale = localeconv();
            if( is_null($dec_point) ) {
                $dec_point = $locale['decimal_point'];
            }
            if( is_null($thousands_sep) ) {
                $thousands_sep = $locale['thousands_sep'];
            }
        }
        $number = (float) str_replace($dec_point, '.', str_replace($thousands_sep, '', $str));
        if( $number == (int) $number ) {
            return (int) $number;
        } else {
            return $number;
        }
    }

?>
alx at inbox dot lv 15-May-2007 02:14
enjoy the PHP!
<?php
function FormatPrice($price) {
    $price = preg_replace("/[^0-9\.]/", "", str_replace(',','.',$price));
    if (substr($price,-3,1)=='.') {
        $sents = '.'.substr($price,-2);
        $price = substr($price,0,strlen($price)-3);
    } elseif (substr($price,-2,1)=='.') {
        $sents = '.'.substr($price,-1);
        $price = substr($price,0,strlen($price)-2);
    } else {
        $sents = '.00';
    }
    $price = preg_replace("/[^0-9]/", "", $price);
    return number_format($price.$sents,2,'.','');
}
?>
Joeri 13-Feb-2007 07:18
Aj and astrolox, for perfect precision arithmetic, you can use the bcmath functions, which perform math on string representations of numbers, instead of on floats. Obviously this is an order of magnitude slower, but at least you don't lose any precision due to the complexities of IEEE-754.
ted at qtis dot co dot nz 07-Feb-2007 03:38
I use the following to get around the negative zero problem:

function currency_format($amount, $precision = 2, $use_commas = true, $show_currency_symbol = false, $parentheses_for_negative_amounts = false)
{
    /*
    **    An improvement to number_format.  Mainly to get rid of the annoying behaviour of negative zero amounts.
    */
    $amount = (float) $amount;
    // Get rid of negative zero
    $zero = round(0, $precision);
    if (round($amount, $precision) == $zero) {
        $amount = $zero;
    }

    if ($use_commas) {
        if ($parentheses_for_negative_amounts && ($amount < 0)) {
            $amount = '('.number_format(abs($amount), $precision).')';
        }
        else {
            $amount = number_format($amount, $precision);
        }
    }
    else {
        if ($parentheses_for_negative_amounts && ($amount < 0)) {
            $amount = '('.round(abs($amount), $precision).')';
        }
        else {
            $amount = round($amount, $precision);
        }
    }

    if ($show_currency_symbol) {
        $amount = '$'.$amount;  // Change this to use the organization's country's symbol in the future
    }
    return $amount;
}
zulisse at email dot it 06-Feb-2007 02:27
simpler function to convert a number in bytes, kilobytes....

<?php

function bytes($a) {
    $unim = array("B","KB","MB","GB","TB","PB");
    $c = 0;
    while ($a>=1024) {
        $c++;
        $a = $a/1024;
    }
    return number_format($a,($c ? 2 : 0),",",".")." ".$unim[$c];
}

?>

you may also add others units over PeraBytes when the hard disks will reach 1024 PB :)
lathem at gibsoncomputer dot net 22-Dec-2006 09:41
I've discovered that the commas which number_format() inserts as a thousands separators causes math functions to break.

Bit of a newbie thing, but it bit me in the ass.

eg--

<?
$foo = number_format(1234, 2);
?>

$foo is now equal to 1,234.00

<?
$bar = 23;
$result = $foo+$bar;
?>

One would think $result == 1,257.00.  However, because number_format added a comma to $foo, the expression will not evaluate correctly.

Instead, do things in this order:

<?
$foo=1234;
$bar=23;
$foobar=number_format($foo+$bar, 2);
?>

$foobar is now set to 1,257.00.

Another method, if you're fixing code you've already written and don't want to change a huge amount, is to remove the thousands separator, using the appropriate variable to number_format.

<?
$foo = number_format(1234, 2, '.', '');
$bar = number_format(23, 2, '.', '');
$foobar = number_format($foo+$bar, 2);
?>

$foobar will now be set to 1,257.00
webmaster at WWW.ELLESSEWEB.NET 24-Nov-2006 06:51
This is a simple and useful function to convert a byte number in a KB  or MB:

<?
function filesize_format ($bytes) {
  $bytes=(float)$bytes;
  if ($bytes<1024){
  $numero=number_format($bytes, 0, ',', '.')." Byte";
  return $numero;
  }
  if ($bytes<1048576){
      $numero=number_format($bytes/1024, 2, ',', '.')." KByte";
  return $numero;
  }
  if ($bytes>=1048576){
      $numero=number_format($bytes/1048576, 2, ',', '.')." MByte";
  return $numero;
  }
}
?>
giovanni dot cappellini at gmail dot com 26-Oct-2006 07:31
About the function of j-a-n at gmx dot de: it's useful, but the argument of the function is $number while the logic of the function requires it to be $in.
dwhitaker at dfwairport dot com 13-Sep-2006 07:56
You know sometimes we forget to add the basic cool stuff...

Found this over in the money_format section and felt some newbie is probably looking for it...

$val = "1000000";
echo number_format($val, 0, "", ","); // returns 1,000,000
26-Aug-2006 04:45
Unfortunately, this function is not multibyte-safe. If you want to use the typographically correct separator for thousands in Swiss German and UTF-8 (‘ - Unicode 2019), you'll only get the first byte - e.g. garbage -  since this function strips anything after the first byte, regardless of the charset used.
j-a-n at gmx dot de 10-Aug-2006 10:04
This function formats an decimal number to a String.
But it does'n use an fixed count of decimals but calculates the needed count of decimals.

<?
function formatNumber( $number, $decimals=2, $dec_point=".", $thousands_sep=",") {
    $nachkomma = abs($in - floor($in));
    $strnachkomma = number_format($nachkomma , $decimals, ".", "");

    for ($i = 1; $i <= $decimals; $i++) {
        if (substr($strnachkomma, ($i * -1), 1) != "0") {
            break;
        }
    }

    return number_format($in, ($decimals - $i +1), $dec_point, $thousands_sep);
}
?>
Example:

formatNumber( 100.00 );
--> 100
formatNumber( 100.50 );
--> 100.5
formatNumber( 100.1234 );
--> 100.12
formatNumber( 100.12, 4 );
--> 100.12
formatNumber( 100.12345, 4 );
--> 100.1234
04-Jun-2006 12:55
The modification to number_format below does what I actually want it to do, with currency, for example. I want it to show $1.40 and not $1.4 or $1.400 - except in the rare case where I have $1.435 for something, in which case I *don't* want it to round. The ugliness below serves my purpose.

function nof($number,$decimals) {
if (number_format($number,$decimals,'.',',') != $number) {
        return $number;
} else {
        return number_format($number,$decimals,'.',',');
        }
}
ck at vowel dot se 26-May-2006 03:11
Again, the function for returning file size in human readable format, but with a tweek for displaying one decimal when size is less than 10 units.

<?php
function human_readable( $size )
{
   $count = 0;
   $format = array("B","KB","MB","GB","TB","PB","EB","ZB","YB");
   while(($size/1024)>1 && $count<8)
   {
       $size=$size/1024;
       $count++;
   }
   if( $size < 10 ) $decimals = 1;
   else $decimals = 0;
   $return = number_format($size,$decimals,'.',' ')." ".$format[$count];
   return $return;
}
?>

Thanks to "php dot net at alan-smith dot no-ip dot com" and "service at dual-creators dot de".
rudie at jouwmoeder dot nl 22-May-2006 02:30
number_format is pretty fast. It's much slower than calculation though:
<?php

$start = microtime(true);

echo "<pre>";
for ($i=0;$i<100000;$i++)
{
    echo number_format(microtime(true)-$start,25)."\n";
}
echo "<hr />Parsetime: ".(microtime(true)-$start);

?>
This takes 1.03 seconds all the time. Without the -$start in the number_format cmd, it takes exactly as long (I ran it about 20 times).
The simple calculation inside number_format takes relatively no time. Defining the number before entering it into number_format also gives no change:
{
    $num = microtime(true)-$start;
    echo number_format($num,25)."\n";
}

Which concludes it takes about .01 sec to do a thousand number_format.
If you'd do the same routine without the number_format, it'd take .75 seconds -> number_format very fast!
gfinale at hotmail dot com 14-May-2006 10:58
Thanks to armstrong ~~at~~ rice ~~dot~~ edu for your number to words function.  There does seem to be one glitch I've discovered, at least on my system.  Hundreds work but hundreds of thousands and hundreds of millions do not.  e.g. 100,000 or 100,000,000 hangs.
chris_cember at cinmach dot com 15-Mar-2006 01:40
// the mktime shortcut is a little trickier than it would first appear, even with a mod...

function text_number($n) {
    $mod = $n % (($n > 20)?10:20);
    return $n . (($mod==0)?"th":date("S",mktime(0,0,0,1,$mod,2000)));
}

// or for those who don't appreciate shorthand:

function text_number($n) {
    if ($n > 20) {
        $mod_factor = 10;
    } else {
        $mod_factor = 20;
    }
    $mod = $n % $mod_factor;
    if ($mod == 0) {
        $txt = "th";
    } else {
        $txt = date("S",mktime(0,0,0,1,$mod,2000));
    }
    return $n . $txt;
}

/*
one issue comes up in numbers that mod to zero (which mktime will associate with the 31st of December, 1999).  another issue is between 23rd and 13rd, err I mean 13th.  If you use 20 (or even 30) all the time, however, you'll end up with 33th (or 43th).
*/
Steve Neill 03-Mar-2006 04:04
actually, you'd want to MOD the number to get it within a useful range first (1 .. 30).

Enjoy.
mikesabatino at gmail dot com 01-Mar-2006 07:34
<?php
# Function to represent a number like '2nd', '10th', '101st' etc
function text_number($n)
{
    # Array holding the teen numbers. If the last 2 numbers of $n are in this array, then we'll add 'th' to the end of $n
    $teen_array = array(11, 12, 13, 14, 15, 16, 17, 18, 19);

    # Array holding all the single digit numbers. If the last number of $n, or if $n itself, is a key in this array, then we'll add that key's value to the end of $n
    $single_array = array(1 => 'st', 2 => 'nd', 3 => 'rd', 4 => 'th', 5 => 'th', 6 => 'th', 7 => 'th', 8 => 'th', 9 => 'th', 0 => 'th');

    # Store the last 2 digits of $n in order to check if it's a teen number.
    $if_teen = substr($n, -2, 2);

    # Store the last digit of $n in order to check if it's a teen number. If $n is a single digit, $single will simply equal $n.
    $single = substr($n, -1, 1);

    # If $if_teen is in array $teen_array, store $n with 'th' concantenated onto the end of it into $new_n
    if ( in_array($if_teen, $teen_array) )
    {
        $new_n = $n . 'th';
    }
    # $n is not a teen, so concant the appropriate value of it's $single_array key onto the end of $n and save it into $new_n
    elseif ( $single_array[$single] )
    {
        $new_n = $n . $single_array[$single];
    }

    # Return new
    return $new_n;
}
?>
MarcM 20-Feb-2006 10:03
For Zero fill - just use the sprintf() function

$pr_id = 1;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 001
-----------------

$pr_id = 10;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 010
-----------------

You can change %03d to %04d, etc.
adnan 'at' barakatdesigns 'dot' net 30-Jan-2006 07:43
Just a note to the author of the "zerofill" function, you may find it easier using the str_pad function

<?php
$num = 4;
$zerofill = 3;

echo str_pad($num, $zerofill, "0", STR_PAD_LEFT);

/* Returns the same wanted result of '004' */
?>
versae arroba gmail punto com 24-Jan-2006 03:17
A modification for kolnedra's function

<?

function humanReadable($val, $miles = 0){
    if($val>=1000)
        $val = humanReadable($val / 1024, ++$miles);
    else {
        $unidad = array('','K','M','G','T','P','E','Z','Y',
        'X','W','V','U','TD','S','R',
        'Q','PP','O','N','MI','L');
        $val = round($val, 2).$unidad[$miles].'B';
    }
    return $val;
}

?>
20-Jan-2006 12:48
A function to return a number with needed zeros at the beginning. Called "zerofill"

<?php
// $num = 4; $zerofill= 3; returns "004"
function zerofill ($num,$zerofill) {
    while (strlen($num)<$zerofill) {
        $num = "0".$num;
    }
    return $num;
}
?>
YumYum 10-Jan-2006 10:19
Jarrat's example below has a problem.  If the number is negative, the sign is dropped.  It always returns positive numbers.  The problem seems to be in the float cast in:

return (float) $number[0].'.'.$decimal;

I have not had a problem in PHP5 with:

return $number[0].'.'.$decimal;
Sprille 21-Dec-2005 08:45
as response to mike at phpeeb dot com.

You can do aritmetic even on strings, you just need a little function to sort it out like this :

function str2no($number){
  $number = str_replace(".", "", $number);
  $number = str_replace(",", ".", $number);
  return $number;
}

function no2str($number){
  $number = number_format($number,2, ',', '.');
  return $number;
}

echo no2str(str2no("1.200,50")*3);

// we use 1200.50 as input "1.200,50" is the danish string for this number
//this will output 3601.50 with right formatting = 3.601,50 as string
//nice to know when dealing with money.
kolnedra at gmail dot com 10-Oct-2005 06:28
A way to let a number (in this case an ammount of money) be shown in dutch annotation:
<?
// geld(123) >>> 123
// geld(123456) >>> 1.234.567
function geld($nm) {
    for ($done=strlen($nm); $done > 3;$done -= 3) {
        $returnNum = ".".substr($nm,$done-3,3).$returnNum;
    }
    return substr($nm,0,$done).$returnNum;
}
?>
mikro_at_teppisti_dot_it 05-Oct-2005 04:04
This function formats numbers 'human readable' better (IMHO) than mircea way:

function humanReadable($val,$thousands=0){
   if($val>=1000)
     $val=humanReadable($val/1024,++$thousands);
   else{
     $unit=array('','K','M','T','P','E','Z','Y');
     $val=round($val,2).$unit[$thousands].'B';
   }
   return $val;
 }
Jeroen de Bruijn [NL] 01-Oct-2005 03:02
If you want to display a number ending with ,- (like 200,-) when there are no decimal characters and display the decimals when there are decimal characters i use:

function DisplayDouble($value)
  {
  list($whole, $decimals) = split ('[.,]', $value, 2);
  if (intval($decimals) > 0)
    return number_format($value,2,".",",");
  else
    return number_format($value,0,".",",") .",-";
  }
astrolox at lawyersonline dot co dot uk 01-Aug-2005 08:34
Users should be aware of the following behaviour.
I'm not sure if this is a PHP bug, libc bug, or if it's even a bug at all. So I thought I'd make a comment and allow everyone else to make up their own minds.

FreeBSD 4.3 PHP 4.3.3

<?php

// the comments show the output generated by this script

echo "input 8.525 output = ". number_format( 8.525, 2, '.', "") ."\n";
echo "input 8.525 output = ". number_format(8.525, 2, '.', "") ."\n";

// input 8.525 output = 8.53
// input 8.525 output = 8.53

$a = 483.00;
$b = 0.175;

$c = $a * $b;

echo "input \$c = $c type ". gettype($c) ." output = ". number_format( $c, 2, '.', "") ."\n";

// input $c = 84.525 type double output = 84.52

$d = 17.5;

$e = ( $a / 100 ) * $d;

echo "input \$e = $e type ". gettype($e) ." output = ". number_format( $e, 2, '.', "") ."\n";

// input $e = 84.525 type double output = 84.53

echo "input 63.745 output = ". number_format(63.745, 2, '.', "") ."\n";
echo "input 64.745 output = ". number_format(64.745, 2, '.', "") ."\n";
echo "input 65.745 output = ". number_format(65.745, 2, '.', "") ."\n";

// input 63.745 output = 63.74
// input 64.745 output = 64.75
// input 65.745 output = 65.75

?>
jarratt at si-works dot net 15-Jul-2005 03:06
With one of the payment providers they required a monitary input of 12345.67 always with a 2 decimal placing even if .00

if you have a number 12345.5 with only one decimal place i could find no sutable php function to guarentee two decimal palces and add a trailing zero if required,

This fucntion should assist

function format_number($str,$decimal_places='2',$decimal_padding="0"){
        /* firstly format number and shorten any extra decimal places */
        /* Note this will round off the number pre-format $str if you dont want this fucntionality */
        $str           =  number_format($str,$decimal_places,'.','');     // will return 12345.67
        $number       = explode('.',$str);
        $number[1]     = (isset($number[1]))?$number[1]:''; // to fix the PHP Notice error if str does not contain a decimal placing.
        $decimal     = str_pad($number[1],$decimal_places,$decimal_padding);
        return (float) $number[0].'.'.$decimal;
}

/* examples */

format_number('1234');       // -->   1234.00
format_number('1234.5');     //-->   1234.50
format_number('1234.567');  //-->   1234.57
marc dot vanwoerkom at fernuni-hagen dot de 14-Jul-2005 06:53
See also the documentation for localeconv, which will provide values for decimal point and thousands separator from the C standard library.

Of course localeconv features many more locale information, like indicating to put the negative sign behind the value for some locale settings which can't be used to customize present number_format.
venimus777 at yahoo dot com 08-Jun-2005 05:25
You could use the following regular expression to divide
a number into parts:

$1-number without fractal part
$2-fractal part
$3-first 2 digits of the fractal part
$4-rest of the fractal part

the regex removes any leading and trailing symbols and leading zeros. It doesnt validate the number, so 12 41 is considered to be correct input!

english notation:
/^.*?[0]*([\d\s]+)(([\.][\d]{0,2})([\d]*))?.*?$/

french notation:
/^.*?[0]*([\d\s]+)(([\,][\d]{0,2})([\d]*))?.*?$/

<?php
// truncate the fractal part up to 2 digits of an "english number":
$number = '01,234.50789';
$trunc = preg_replace(
    '/^.*?[0]*([\d\,]+)(([\.][\d]{0,2})([\d]*))?.*?$/',
    '$1$3',
    $number
);
echo $trunc;
?>

Outputs:
1,234.50

$number='e00012 41.100001e-4fasfd';
would output:
12 41.10
woodynadobhar at hotmail dot com 17-May-2005 09:04
What do you do if some of your numbers have decimal places, and some don't?  You can switch between functions, but if you're building it in a loop, that's not a good solution.  Instead, we have the same as below, with a slight change:

function number_format_unlimited_precision($number,$decimal = '.'){
    $broken_number = explode($decimal,$number);
    if($broken_number[1]==0){
        return number_format($broken_number[0]);
    }else{
        return number_format($broken_number[0]).$decimal.$broken_number[1];
    };
};
stm555 at hotmail dot com 27-Apr-2005 08:54
I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.

I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.

<?php
      function number_format_unlimited_precision($number,$decimal = '.')
      {
           $broken_number = explode($decimal,$number);
           return number_format($broken_number[0]).$decimal.$broken_number[1];
      }
?>
mike at phpeeb dot com 02-Apr-2005 01:13
Since number_format returns a string, you must perform all mathmatical functions on the number before applying number_format:

<?
$total = 100;
$total = number_format($total, 2);
$shipping = 20.00;
$grand_total = $total + $shipping;

echo number_format($grand_total, 2);

/* The above will return 21.00 because $total is now a string, and no longer an integer or float. Since a string will have a value of 1,  the addition of the two will return 21 and not 120. */

$total = 100;
$shipping = 20.00;
$grand_total = $total + $shipping;

echo number_format($grand_total, 2);

/* This works, and will return 120.00 as intended */

?>
php at mijav dot dk 31-Mar-2005 06:25
A bug was issued that -0,00 is invalid output from number_format(), but the bug was rejected since the number "-0.0000000000000000001E-999 is about -0". And the developer felt this was correct output.

Please beware of negative numbers close to zero, as they might produce this unusable (and in my opinion incorrect/off-description) output.
ChronoFish 23-Mar-2005 11:14
I was looking for an easy way to take a number (or string) and force into a specific format.  I came up with.  I apologize if this is redundant, but I could not find a simular function:

/***********************************
* string_format
***********************************/
function string_format($format, $string, $placeHolder = "#")
{
    $numMatches = preg_match_all("/($placeHolder+)/", $format, $matches);
    foreach ($matches[0] as $match)
    {
        $matchLen = strlen($match);
        $format = preg_replace("/$placeHolder+/", substr($string, 0, $matchLen), $format, 1);
        $string = substr($string, $matchLen);
    }
    return $format;
}

To Use:

print string_format("(###)###-####", "4015551212");
will print out:
(401)555-1212

Hope this helps someone,

CF
tonywebman at NOSPAM dot telusplanet dot net 23-Feb-2005 01:14
While trying to add variables whose values had been processed with number_format() I found an interesting gotcha. Perhaps this might help others.

Since number_format() returns a string, numbers returned that DO NOT have a comma in them will still be added but numbers that DO have a comma will not be added because PHP considers them a string and ignores them.

e.g. #1
$quant_mag = 1;
$cost_mag = 100;
$quant_ffr = 1
$cost_ffr = 100;

$ext_mag = number_format($quant_mag * $cost_mag,2);
$ext_ffr = number_format($quant_ffr * $cost_ffr,2);

$total_cost = $ext_mag + $ext_ffr;

// $total cost is: 200

e.g. #2
$quant_mag = 10;
$cost_mag = 100;
$quant_ffr = 1
$cost_ffr = 100;

$ext_mag = number_format($quant_mag * $cost_mag,2);
$ext_ffr = number_format($quant_ffr * $cost_ffr,2);

$total_cost = $ext_mag + $ext_ffr;
// $total cost is: 100 (not 1100 as you would expect) because $ext_mag is ignored because php interprets its value (1,000) as a string so it won't add it to $ext_ffr.
keyg at auralplanet dot com 22-Nov-2004 06:56
if you want &nbsp; as a separator and use windows charset this piece of code may help:

<?php
$number=number_format($number,2,'.',chr(0xA0));
?>
brandonprudent at yahoo dot com 10-Oct-2004 11:52
To convert numbers to thier textual representations, you can use an adapted version of the Number::Spell Perl module. The PHP conversion can be found here: http://pear.php.net/package/Numbers_Words
GeekPrices Dot Com 06-Oct-2004 05:57
this also works as well

$number = "29346.99"; //value
echo "$" .number_format($number, 2, '.', ',');

produces $29,346.99
Svein Tjonndal (sveint at yahoo dot com) 14-Sep-2004 07:18
If you use space as a separator, it will break on that space in HTML tables...

Furthermore, number_format doesn't like '&nbsp;' as a fourth parameter. I wrote the following function to display the numbers in an HTML table.

  function numberfix($number)
  {
    $number = number_format($number,0,","," ");
    return str_replace(" ", "&nbsp;", $number);
  }

For use in:
<table><tr><td><?php echo $number; ?></td></tr></table>
drew at zitnay dot com 17-Aug-2004 11:17
A more reliable and concise way of doing what S. Rahmel was trying to do below is as follows:

<?php
$field_inhalt = str_replace(array(".", ","), array("", "."), $field_inhalt);
?>

The str_replace() call will first replace all dots with blanks, and then replace all commas with dots.  That way, it doesn't break down when you try a number over one million (i.e. 1.010.453,21).

Drew
mircea at vtds dot co dot uk 02-Jun-2004 09:57
This function formats numbers 'human readable':

function byte_format($input, $dec=0)
{
  $prefix_arr = array(" B", "K", "M", "G", "T");
  $value = round($input, $dec);
  $i=0;
  while ($value>1024)
  {
     $value /= 1024;
     $i++;
  }
  $return_str = round($value, $dec).$prefix_arr[$i];
  return $return_str;
}
S. Rahmel 11-Mar-2004 02:47
if you converted a number to a German format with number_format() and want to save it in mySQL, you first have to change the number format back to an English format.

For example
10.453,21 >>>> 10453.21

Here is an example how to do this:

    $field_array=explode(".", $field_inhalt);
    $field_inhalt=$field_array[0].$field_array[1];
    $foeld_array=explode(",", $field_inhalt);
    $field_inhalt=$field_array[0].".".$feld_array[1];
    $field_inhalt=sprintf($field_inhalt, 2);

$field_inhalt is the variable of the actual number you want to change to the english format.
chandu at chandu dot org 07-Mar-2004 05:29
People here in India are more used to counting money in Lakhs & Crores .. so here is the code for formatting the commas with thousands for the first time and then with hundred multiples from there after.

Ex: 1234567  ->  12,34,567

<?php

function makecomma($input)
{
    // This function is written by some anonymous person - I got it from Google
    if(strlen($input)<=2)
    { return $input; }
    $length=substr($input,0,strlen($input)-2);
    $formatted_input = makecomma($length).",".substr($input,-2);
    return $formatted_input;
}

function formatInIndianStyle($num){
    // This is my function
    $pos = strpos((string)$num, ".");
    if ($pos === false) { $decimalpart="00";}
    else { $decimalpart= substr($num, $pos+1, 2); $num = substr($num,0,$pos); }

    if(strlen($num)>3 & strlen($num) <= 12){
                $last3digits = substr($num, -3 );
                $numexceptlastdigits = substr($num, 0, -3 );
                $formatted = makecomma($numexceptlastdigits);
                $stringtoreturn = $formatted.",".$last3digits.".".$decimalpart ;
    }elseif(strlen($num)<=3){
                $stringtoreturn = $num.".".$decimalpart ;
    }elseif(strlen($num)>12){
                $stringtoreturn = number_format($num, 2);
    }

    if(substr($stringtoreturn,0,2)=="-,"){$stringtoreturn = "-".substr($stringtoreturn,2 );}

    return $stringtoreturn;
}

$num = 1234567;
echo  formatInIndianStyle($num);

?>
armstrong ~~at~~ rice ~~dot~~ edu 23-Feb-2004 04:33
I submitted this question earlier, but I found the answer myself.  To convert a number to its word form (e.g. 34 to "thirty four")  try the function below.  It turned out to be a lot more complex than I thought!

I'm using it for printing dollar ammounts, so the cents get printed like 13/100

I converted most of it from this java code http://mindprod.com/inwords.html so credit goes to him for doing the hard part.

<?
/**
* convert long integer into American English words.
* e.g. -12345 -> "minus twelve thousand forty-five"
* Handles negative and positive integers
* on range -Long.MAX_VALUE .. Long.MAX_VALUE;
* It cannot handle Long.MIN_VALUE;
*/

function num2words( $num ){
    $ZERO = "zero";
    $MINUS = "minus";
    $lowName = array(
          /* zero is shown as "" since it is never used in combined forms */
          /* 0 .. 19 */
          "", "one", "two", "three", "four", "five",
          "six", "seven", "eight", "nine", "ten",
          "eleven", "twelve", "thirteen", "fourteen", "fifteen",
          "sixteen", "seventeen", "eighteen", "nineteen");

    $tys = array(
          /* 0, 10, 20, 30 ... 90 */
          "", "", "twenty", "thirty", "forty", "fifty",
          "sixty", "seventy", "eighty", "ninety");

    $groupName = array(
          /* We only need up to a quintillion, since a long is about 9 * 10 ^ 18 */
          /* American: unit, hundred, thousand, million, billion, trillion, quadrillion, quintillion */
          "", "hundred", "thousand", "million", "billion",
          "trillion", "quadrillion", "quintillion");

    $divisor = array(
          /* How many of this group is needed to form one of the succeeding group. */
          /* American: unit, hundred, thousand, million, billion, trillion, quadrillion, quintillion */
          100, 10, 1000, 1000, 1000, 1000, 1000, 1000) ;

    $num = str_replace(",","",$num);
    $num = number_format($num,2,'.','');
    $cents = substr($num,strlen($num)-2,strlen($num)-1);
    $num = (int)$num;

    $s = "";

    if ( $num == 0 ) $s = $ZERO;
    $negative = ($num < 0 );
    if ( $negative ) $num = -$num;

    // Work least significant digit to most, right to left.
    // until high order part is all 0s.
    for ( $i=0; $num>0; $i++ ) {
        $remdr = (int)($num % $divisor[$i]);
        $num = $num / $divisor[$i];
        // check for 1100 .. 1999, 2100..2999, ... 5200..5999
        // but not 1000..1099,  2000..2099, ...
        // Special case written as fifty-nine hundred.
        // e.g. thousands digit is 1..5 and hundreds digit is 1..9
        // Only when no further higher order.
        if ( $i == 1 /* doing hundreds */ && 1 <= $num && $num <= 5 ){
            if ( $remdr > 0 ){
                $remdr += $num * 10;
                $num = 0;
            } // end if
        } // end if
        if ( $remdr == 0 ){
            continue;
        }
        $t = "";
        if ( $remdr < 20 ){
            $t = $lowName[$remdr];
        }
        else if ( $remdr < 100 ){
            $units = (int)$remdr % 10;
            $tens = (int)$remdr / 10;
            $t = $tys [$tens];
            if ( $units != 0 ){
               $t .= "-" . $lowName[$units];
            }
        }else {
            $t = $inWords($remdr);
        }
        $s = $t . " " . $groupName[$i] . " "  . $s;
        $num = (int)$num;
    } // end for
    $s = trim($s);
    if ( $negative ){
        $s = $MINUS . " " . $s;
    }

    $s .= " and $cents/100";

    return $s;
} // end inWords

?>
cruzf_AT_fibertel.com.ar 07-Nov-2003 11:03
You could add padding zeros like this:

<?
$number="129";
$number=sprintf("%08d",$number);
?>
j dot bos at bytewriters dot nl 01-Jun-2003 12:45
If I'm not mistaking all these examples of adding leading zeros will not really work with floats. Sometimes though one needs it to have it working with floats as well.

With the function below use 2, 3 or 5 parameters. Don't ask me why 4 don't work, the number_format() function seems to have problems with that. At least my version of PHP has that "feature".

function leading_zero( $aNumber, $intPart, $floatPart=NULL, $dec_point=NULL, $thousands_sep=NULL) {        //Note: The $thousands_sep has no real function because it will be "disturbed" by plain leading zeros -> the main goal of the function
  $formattedNumber = $aNumber;
  if (!is_null($floatPart)) {    //without 3rd parameters the "float part" of the float shouldn't be touched
    $formattedNumber = number_format($formattedNumber, $floatPart, $dec_point, $thousands_sep);
    }
  //if ($intPart > floor(log10($formattedNumber)))
    $formattedNumber = str_repeat("0",($intPart + -1 - floor(log10($formattedNumber)))).$formattedNumber;
  return $formattedNumber;
  }

echo leading_zero(21.12345678, 4, 5);    // Output: 0021.12346
echo leading_zero(21.12345678, 4);    // Output: 0021.12345678
echo leading_zero(21.12345678, 3, 0); // Output: 021
echo leading_zero(21.12345678, 3, 5, ",", ""); // Output: 021,12346

addition: Just like the number_format I haven't found a way *not* to round a number while changing the decimal point and the thousands seperator.
sgj at dr dot com 17-May-2003 06:04
Just an observation:
The number_format rounds the value of the variable.

$val1 = 1.233;
$val2 = 1.235;
$val3 = 1.237;

echo number_format($val1,2,",","."); // returns: 1,23
echo number_format($val2,2,",","."); // returns: 1,24
echo number_format($val3,2,",","."); // returns: 1,24
Theo Diem 24-Mar-2003 01:45
formatting numbers may be more easy if u use number_format function.

I also wrote this :
function something($number)
{
    $locale = localeconv();
    return number_format($number,
       $locale['frac_digits'],
        $locale['decimal_point'],
        $locale['thousands_sep']);
}

hope this helps =)
[]'s
andrew at crucible dot co dot nz 04-Jan-2002 04:56
Remember that number_format returns a string, so you shouldn't run a number_format on a variable that's already a product of number_format (it will only take the first token of the string)...

eg. echo number_format("123,456.00", 2);
produces: 123.00
sctemplarknight at hotmail dot com 12-Dec-2001 01:27
number_format($number,$precision,".","") should be used when setting the value of form elements because if you read the number into a double upon submission, it will only store digits before the comma.
<p>
ie. <input type="text" value="<?php echo(number_format(2.5343,2,".","")">
nl2br
ord
Обработка строк


Возвращает ASCII-код символа

number_format
parse_str
Обработка строк
PHP Manual

ord

(PHP 4, PHP 5)

ord — Возвращает ASCII-код символа

Описание

int ord ( string $string )

Возвращает ASCII-код первого символа строки string.

Эта функция дополняет функцию chr().

Список параметров

string

Символ.

Возвращаемые значения

Возвращает ASCII-код в виде целого числа.

Примеры

Пример #1 Пример использования ord()

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "Первый символ \$str - перевод строки.\n";
}
?>

Смотрите также

  • chr() - Возвращает символ по его коду
  • » Таблица ASCII-кодов

User Contributed Notes

znaeff at mail dot ru 05-Oct-2011 09:36
I've found that variant with
unpack('N', mb_convert_encoding($c, 'UCS-4BE', 'UTF-8'));
is VERY-VERY slow.
Remember this when process strings longer than 1K.
Anonymous 05-Apr-2011 05:49
i need put utf8 hungarian "abc" into html id attribute, but id not contain non-ascii chars (like á, ő, ű), and not to begin a number.

<?php

function utfCharToNumber($char) {
    $i = 0;
    $number = '';
    while (isset($char{$i})) {
        $number.= ord($char{$i});
        ++$i;
        }
    return $number;
    }

// example use
foreach (array('a','A','b','B','c','C','e','é','É', 'ó','Ó','ö','Ö','ő','Ő','ú') as $d) {
    echo $d,': ',utfCharToNumber($d),"\n";
    }
?>

output:
a: 97
A: 65
b: 98
B: 66
c: 99
C: 67
e: 101
é: 195169
É: 195137
ó: 195179
Ó: 195147
ö: 195182
Ö: 195150
ő: 197145
Ő: 197144
ú: 195186

i generated the folowing ids:
"char-97", "char-65", "char-98" ...
manixrock(hat)gmail(doink)com 03-Jun-2010 08:14
For anyone having trouble trying to detect the encoding of a string because PHP provides no easy way to see the characters (and byte values) of a string, here's a function that returns the characters and byte values for the ASCII and UTF-8 encodings:

<?php
function hex_chars($data) {
    $mb_chars = '';
    $mb_hex = '';
    for ($i=0; $i<mb_strlen($data, 'UTF-8'); $i++) {
        $c = mb_substr($data, $i, 1, 'UTF-8');
        $mb_chars .= '{'. ($c). '}';

        $o = unpack('N', mb_convert_encoding($c, 'UCS-4BE', 'UTF-8'));
        $mb_hex .= '{'. hex_format($o[1]). '}';
    }
    $chars = '';
    $hex = '';
    for ($i=0; $i<strlen($data); $i++) {
        $c = substr($data, $i, 1);
        $chars .= '{'. ($c). '}';
        $hex .= '{'. hex_format(ord($c)). '}';
    }
    return array(
        'data' => $data,
        'chars' => $chars,
        'hex' => $hex,
        'mb_chars' => $mb_chars,
        'mb_hex' => $mb_hex,
    );
}
function hex_format($o) {
    $h = strtoupper(dechex($o));
    $len = strlen($h);
    if ($len % 2 == 1)
        $h = "0$h";
    return $h;
}
?>
regalia at umail dot ucsb dot edu 26-Jan-2009 03:54
Make sure that the parameter you are passing to the ord function is a string.

<?php
$num = 12345;

// Incorrect usage of square bracket notation
if(ord($num[0]) == 0)  {
    echo "Not a valid ASCII character";
}

// Using the substr method will account for any data type
if(ord(substr($num,0,1)) == 0) {
    echo "Not a valid ASCII character";
}

?>
darien at etelos dot com 19-Jan-2007 11:27
I found I wanted to sanitize a string for certain ASCII/ANSI characters, but to leave unicode alone. Since ord() breaks on processing unicode, I drew these two functions up to help with a saniziter which looked at ordinal values. (Finding "pack" and "unpack" was much better than my own powers-of-256 code.)

<?php

/*
    By Darien Hager, Jan 2007... Use however you wish, but please
    please give credit in source comments.

    Change "UTF-8" to whichever encoding you are expecting to use.
*/
function ords_to_unistr($ords, $encoding = 'UTF-8'){
    // Turns an array of ordinal values into a string of unicode characters
    $str = '';
    for($i = 0; $i < sizeof($ords); $i++){
        // Pack this number into a 4-byte string
        // (Or multiple one-byte strings, depending on context.)
        $v = $ords[$i];
        $str .= pack("N",$v);
    }
    $str = mb_convert_encoding($str,$encoding,"UCS-4BE");
    return($str);
}

function unistr_to_ords($str, $encoding = 'UTF-8'){
    // Turns a string of unicode characters into an array of ordinal values,
    // Even if some of those characters are multibyte.
    $str = mb_convert_encoding($str,"UCS-4BE",$encoding);
    $ords = array();

    // Visit each unicode character
    for($i = 0; $i < mb_strlen($str,"UCS-4BE"); $i++){
        // Now we have 4 bytes. Find their total
        // numeric value.
        $s2 = mb_substr($str,$i,1,"UCS-4BE");
        $val = unpack("N",$s2);
        $ords[] = $val[1];
    }
    return($ords);
}

?>
S.N.O.W.M.A.N.-X 28-Sep-2006 12:47
Well, i was thinking about a method to hash a string with md5 in a loose way, so md5("HELLO") isn't the same like md5("Hello"), even, i my case, it is about cd-titles i got submitted by users. So i made some function transforming my string to right what i want

Thisone is the "call" function returning the "loose hash".
It will get only the chars of a string, make them to uppercase and then hash with md5.

<?php
function loosehash($string){
    return md5(strtoupper(onlyChars($string)));
}
?>

Thisone is moving through a string like a chararray and check for the asciivalues, you can edit the values and condition to fit your needs

<?php
function onlyChars($string){
    $strlength = strlen($string);
    $retString = "";
    for($i = 0; $i < $strlength; $i++){
        if((ord($string[$i]) >= 48 && ord($string[$i]) <= 57) ||
        (ord($string[$i]) >= 65 && ord($string[$i]) <= 90) ||
        (ord($string[$i]) >= 97 && ord($string[$i]) <= 122)){
            $retString .= $string[$i];
        }
    }

    echo $retString;
}
?>
phil (at) pchowtos (dot) co (dot) uk 18-Jul-2006 10:51
You can use the following function to generate a random string between the lengths of $x and $y...

<?php
$x = 1;  //minimum length
$y = 10;  //maximum length

$len = rand($x,$y);  //get a random string length

for ($i = 0; $i < $len; $i++) {  //loop $len no. of times
   $whichChar = rand(1,3);  //choose if its a caps, lcase or num
   if ($whichChar == 1) { //it's a number
      $string .= chr(rand(48,57));  //randomly generate a num
   }
   elseif ($whichChar == 2) { //it's a small letter
      $string .= chr(rand(65,90));  //randomly generate an lcase
   }
   else { //it's a capital letter
      $string .= chr(rand(97,122));  //randomly generate a ucase
   }
}

echo $string;  //echo out the generated string
?>
erdem at a1tradenetwork dot com 16-May-2006 11:16
I have a new characters table. i want send it below that.

<?php
$color = "#f1f1f1";
echo "<center>";
echo "<h1>From 32 To 255 Characters Table</h1>";
echo "</center>";
echo "<table border=\"0\" style=\"font-family:verdana;font-size:11px;\"".
     " align=\"center\" width=\"800\"><tr style=\"font-weight:bold;\"  ".
     "bgcolor=\"#99cccc\">".
     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "</tr><tr>";
$ii = 0;
for ($i=32;$i<=255;$i++){
    $char = chr($i);
    $dec  = ord($char);
    if ($i == "32") {
        $char = "Space";
    }
    echo "<td style=\"background-color:$color;width:15px;\">".
         $dec."</td>\n<td style=\"background-color:$color;".
         "width:15px;text-align:left;\">".decoct($dec)."</td>\n".
         "<td style=\"background-color:$color;width:15px;".
         "text-align:left;\">".dechex($dec)."</td>\n ".
         "<td style=\"background-color:$color;width:15px;".
         "text-align:left;\"><b>".$char."</b></td>\n ";

    if (($ii % 6) == 5) {
    echo "</tr>\n<tr>\n";

    }

   if (($ii % 2) == 1) {
         $color = "#f1f1f1";
    }else {
         $color = "#ffffcc";
    }

    $ii++;
}
echo "</tr></table>";
?>
Matthew Flint 31-Oct-2005 02:59
I wrote the following function to clean illegal characters from input strings.

(Background: I have a php-based news website. People were writing articles in MS Word, then copy-and-pasting the text into the website. Word uses non-standard characters for opening and closing quotes and double-quotes, and for "..." - and this was resulting in articles on the website that failed XHTML validation)

<?php
function clean_string_input($input)
{
    $interim = strip_tags($input);

    if(get_magic_quotes_gpc())
    {
        $interim=stripslashes($interim);
    }

    // now check for pure ASCII input
    // special characters that might appear here:
    //   96: opening single quote (not strictly illegal, but substitute anyway)
    //   145: opening single quote
    //   146: closing single quote
    //   147: opening double quote
    //   148: closing double quote
    //   133: ellipsis (...)
    //   163: pound sign (this is safe, so no substitution required)
    // these can be substituted for safe equivalents
    $result = '';
    for ($i=0; $i<strlen($interim); $i++)
    {
        $char = $interim{$i};
        $asciivalue = ord($char);
        if ($asciivalue == 96)
        {
            $result .= '\\'';
        }
        else if (($asciivalue > 31 && $asciivalue < 127) ||
                 ($asciivalue == 163) || // pound sign
                 ($asciivalue == 10) || // lf
                 ($asciivalue == 13)) // cr
        {
            // it's already safe ASCII
            $result .= $char;
        }
        else if ($asciivalue == 145) // opening single quote
        {
            $result .= '\\'';
        }
        else if ($asciivalue == 146) // closing single quote
        {
            $result .= '\\'';
        }
        else if ($asciivalue == 147) // opening double quote
        {
            $result .= '"';
        }
        else if ($asciivalue == 148) // closing double quote
        {
            $result .= '"';
        }
        else if ($asciivalue == 133) // ellipsis
        {
            $result .= '...';
        }
    }

    return $result;
}
?>
28-Feb-2005 06:12
Function using ord() to strip out garbage characters and punctuation from a string. This is handy when trying to be smart about what an input is "trying" to be..
<?php

function cleanstr($string){
    $len = strlen($string);
    for($a=0; $a<$len; $a++){
        $p = ord($string[$a]);
        # chr(32) is space, it is preserved..
        (($p > 64 && $p < 123) || $p == 32) ? $ret .= $string[$a] : $ret .= "";
    }
    return $ret;
}

?>
jacobfri at skydebanen dot net 04-Jun-2004 05:10
Just to get things straight about which character table ord() and chr() uses.
The range 128-255 is _not_ equivalent with the widely used extended ASCII-table, like the one described in www.asciitable.com. The actual equivalent is the 128-255 range of Unicode.
That's a good thing, because then ord() and chr() is compatible with javascript, and any other language that uses Unicode.
But it's rather nice to know it, and the description of ord() is kind of misleading, when it only refers to www.asciitable.com.
v0rbiz at yahoo dot com 28-May-2004 04:15
I did not found a unicode/multibyte capable 'ord' function, so...

<?php
function uniord($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = ord(substr($k, 0, 1));
    $k2 = ord(substr($k, 1, 1));
    return $k2 * 256 + $k1;
}
?>
arjini at mac dot com 18-Mar-2004 11:49
If you're looking to provide bare bones protection to email addresses posted to the web try this:

<?php
$string = 'arjini@mac.com';
for($i=0;$i<strlen($string);++$i){
    $n = rand(0,1);
    if($n)
        $finished.='&#x'.sprintf("%X",ord($string{$i})).';';
    else
        $finished.='&#'.ord($string{$i}).';';
}
echo $finished;
?>

This randomly encodes a mix of hex and oridinary HTML entities for every character in the address. Note that a decoding mechanism for this could probably be written just as easily, so eventually the bots will be able to cut through this like butter, but for now, it seems like most harvesters are only looking for non-hex html entities.
number_format
parse_str
Обработка строк


Разбирает строку в переменные

ord
print
Обработка строк
PHP Manual

parse_str

(PHP 4, PHP 5)

parse_str — Разбирает строку в переменные

Описание

void parse_str ( string $str [, array &$arr ] )

Разбирает строку str, которая должна иметь формат строки запроса URL и присваивает значения переменным в текущем контексте.

Замечание:

Для получения текущей QUERY_STRING, можно использовать переменную $_SERVER['QUERY_STRING']. Кроме того, возможно вы захотите прочесть раздел о переменных вне PHP.

Замечание:

Опция magic_quotes_gpc влияет на вывод этой функции, так как parse_str() использует тот же механизм, что используется в PHP для заполнения $_GET, $_POST и других переменных.

Список параметров

str

Входная строка.

arr

Если указан второй параметр arr, то вместо присвоения переменных в текущем контексте они будут сохранены в этом параметре в качестве элементов массива.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

Версия | Описание
4.0.3 | Добавлен параметр arr

Примеры

Пример #1 Использование parse_str()

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

Смотрите также

  • parse_url() - Разбирает URL и возвращает его компоненты
  • pathinfo() - Возвращает информацию о пути к файлу
  • http_build_query() - Генерирует URL-кодированную строку запроса
  • get_magic_quotes_gpc() - Получение текущего значения настройки конфигурации magic_quotes_gpc
  • urldecode() - Декодирование URL-кодированной строки

User Contributed Notes

shagshag 14-May-2012 05:51
That's not says in the description but max_input_vars directive affects this function. If there are more input variables on the string than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
Benjamin Garcia 26-Apr-2012 09:18
function like parse_str, but doesn't convert spaces and dots to underscores in $_GET AND $_POST

/**
 * GET and POST input containing dots, etc.
 */
function getRealREQUEST() {
    $vars = array();

    $input    = $_SERVER['REDIRECT_QUERY_STRING'];
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs     as $pair) {
            $nv                = explode("=", $pair);

            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);

            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);

            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }

    $input    = file_get_contents("php://input");
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs as $pair) {
            $nv                = explode("=", $pair);

            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);

            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);

            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }

    return $vars;
}
eclipsehtd at hotmail dot com 02-Feb-2011 04:54
I wrote an array to string function that works recursively and works with an n-dimensional array turning it into a parsable string for parse_str.

<?php
function queryString($params, $name=null) {
$ret = "";
 foreach($params as $key=>$val) {
  if(is_array($val)) {
   if($name==null) $ret .= queryString($val, $key);
   else $ret .= queryString($val, $name."[$key]");
   } else {
   if($name!=null)
    $ret.=$name."[$key]"."=$val&";
   else $ret.= "$key=$val&";
  }
 }
 return $ret;
}
?>
Will Voelcker 12-Aug-2010 11:07
If you need a function that does something similar to parse_str, but doesn't convert spaces and dots to underscores, try something like the following:

<?php
function parseQueryString($str) {
    $op = array();
    $pairs = explode("&", $str);
    foreach ($pairs as $pair) {
        list($k, $v) = array_map("urldecode", explode("=", $pair));
        $op[$k] = $v;
    }
    return $op;
}
?>

It may need adapting to handle various edge cases.
sam dot fullman at verizon dot net 29-Jun-2010 01:28
If you're using .htaccess to spoof pages in any type of application, then $QUERY_STRING or $_SERVER['QUERY_STRING'] is going to be blank.  Instead, $_SERVER['REDIRECT_QUERY_STRING'] will hold the actual query string passed by user.  Use this function to parse this variable.
me at bubjavier dot com 04-Feb-2010 02:48
be careful using parse_str() without the [array &$arr] parameter, as this may override values of global and existing variables.

<?php
$var1 = 1;
parse_str('var1=one&var2=two');
// $var1 is now 'one'
?>

Also may lead to variable value injection when used with user input data:

<?php
$_POST['range'] = 'min=1&max=5&important_var=important_value_no_more';

$important_var = 'important_value';
parse_str($_POST['range']);
?>
julien at go-on-web dot com 22-Jun-2009 01:53
Hi,
I discovered that

<?php
$query = 'foo.bar=stuff';    // foo (dot) bar
parse_str( $query , $output);
print_r( $output );
?>

will output (underscore)

Array
(
    [foo_bar] => stuff
)

and not as expected (dot)

Array
(
    [foo.bar] => stuff
)

Query part of a requested URI is parsed the same. So never send parameters with a dot in their names

Hope it will save you time,
bye julien
zspencer at zacharyspencer dot com 13-Mar-2009 11:08
Also, an FYI but you cannot define arr when you call the function. I.E

<?php
$string="Tom=You&Zach=Me";
parse_str($string,$array);
print_r($array);
// Undefined variable $array on line 2!!!!
?>

However, if you define the array before hand, it works.

<?php
$string="Tom=You&Zach=Me";
$array=array();
parse_str($string,$array);
print_r($array);
/*
Array
(
  [Tom] => You
  [Zach] => Me
)
*/
?>
Mark Shust 23-Jul-2008 06:40
In addition to Maikel's posting, the following will iterate through previous arrays and automatically apply them to the current array.

The following code was implemented for YUI's Cookie/subCookie utility in which all form elements were stored as subcookies. This parses cookies and stores all cookie params (minus the parent value) into $_POST variables. if you would like to put elements into array's of the parent, just use the commented out line instead of the if statement.

<?php
// thise parses cookies and stores all fields as variables
foreach ($_COOKIE as $key => $value) {
    // parse_str overwrites previous array values so we must merge the previous ones with new array
    if (isset($_POST)) {
        $_POST_old = $_POST;
        parse_str($value, $_POST);
        $_POST = array_merge($_POST_old, $_POST);
    }
    // this puts all elements as children of parent array
    // comment out above if statement to use this instead
    //parse_str($key, $_POST[$value]);
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
tobsn at php dot net 01-Jul-2008 11:17
just a heads up with the example above:
?var[]=123 - the [] has to be urlencoded.
var names and var values - both have to be urlencoded!
helpmepro1 at gmail dot com 28-Apr-2008 09:09
<?
//by shimon doodkin

 $url_form=url_to_form($url);
 echo '<form action="'.$url_form['action'].'" method="get">';
 echo $url_form['hidden'];
 echo '<input name="otherfiled" type="text">';
 echo '<input type="submit">';
 echo '</form>';

 function url_to_form($url)
 {
  $url=split('\?',$url,2);
  $action=$url[0];
  $hidden="";
  if(isset($url[1]))
  {
   $pairs=split('&',$url[1]);
   foreach($pairs as $pair)
   {
    $pair=split('=',$pair,2);
    $name=$pair[0];
    if(isset($pair[1]))
     $value=$pair[1];
    else
     $value='';
    $name=$name;
    $value=htmlspecialchars($value);
    if($name!='')
     $hidden.='<hidden name="'.$name.'" value="'.$value.'">';
   }
  }
  return array('action'=>$action,'hidden'=>$hidden);
 }

?>
sean at getclicky dot com 21-Apr-2008 09:39
This function automatically urldecodes values (not mentioned in the docs).
Maikel 28-Mar-2008 08:44
Be careful when use the second parameter, this function cleans array var first. Look this:

<?php
$vars["foo"] = "foovalue";
$queryString = "bar=barvalue&stuff=stuffval";
parse_str($queryString, $vars);
echo "<pre>";
print_r($vars);
echo "</pre>";
?>

Result:

Array
(
    [bar] => barvalue
    [stuff] => stuffval
)

it is solved by:

<?php
$prevVars["foo"] = "foovalue";
$queryString = "bar=barvalue&stuff=stuffval";
$newVars = array();
parse_str($queryString, $newVars);

$vars = array_merge($prevVars, $newVars);
echo "<pre>";
print_r($vars);
echo "</pre>";
?>

Result:

Array
(
    [foo] => foovalue
    [bar] => barvalue
    [stuff] => stuffval
)
chris at mcfadyen dot ca 13-Nov-2007 04:02
I shouldn't've posted the original version, as it only worked with the most basic of query strings.

This function will parse an html-safe query-like url string for variables and php-like ordered and associative arrays.  It places them into the global scope as parse_str does and adds minimal slashes for database insertions without the triple-slash problems that magic quotes can produce (the reason I had to write it in the first place).  If you don't need the slashes, they're easy enough to remove.

<?php
function parse_query($str) {

    // Separate all name-value pairs
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {

        // Pull out the names and the values
        list($name, $value) = explode('=', $pair, 2);

        // Decode the variable name and look for arrays
        list($name, $index) = split('[][]', urldecode($name));

        // Arrays
        if(isset($index)) {

            // Declare or add to the global array defined by $name
            global $$name;
            if(!isset($$name)) $$name = array();

            // Associative array
            if($index != "") {
                ${$name}[$index] = addslashes(urldecode($value));

            // Ordered array
            } else {
                array_push($$name, addslashes(urldecode($value)));
            }

        // Variables
        } else {

            // Declare or overwrite the global variable defined by $name
            global $$name;
            $$name = addslashes(urldecode($value));
        }
    }
}
?>
chris at mcfadyen dot ca 31-Oct-2007 08:48
If you wish a version of parse_str sans magic quotes, the following will do the trick:

<?php
function parse_query($str) {
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {
        list($name, $value) = explode('=', $pair, 2);
        global $$name;
        $$name = $value;
    }
}
?>
miket3 at optonline dot net 30-Aug-2007 12:51
I saw some posts with people wondering
 why &'s are being
 sent to this function.  Well, basically
 because thats what comes
 from a QUERY_STRING. Anyway. The bug i found is
 that the first part of a query_string
 may not contain an &. Usually the
 first parameter comes directly after the ?.
So you
 might have to manually pre-pend an & to your
 query_string if one does not exist.

<?php
$base="www.yahoo.com/search.aspx?";
$parsedurl=parse_url($base."&".rawurldecode($_SERVER
['QUERY_STRING']), PHP_URL_QUERY);
parse_str($parsedurl,$myquery);
$qbn = "n=".urlencode($myquery['n']);
?>

oh my god! to get this to post is ridiculous.
kermodebear at kermodebear dot org 08-Aug-2007 11:09
An old post from several years ago mentions that variable names cannot have a dot. They also cannot have a space. Spaces are automatically replaced with an underscore.

The following:
parse_str("My Value=Something", $result);

Will result in:
$result['My_Value'] = 'Something'

Although I understand why it is done, I still feel that this is unintuitive behavior.
Evan K 30-Jul-2007 07:43
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields.  If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');

# the above produces:
$foo = array('foo' => '3');
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');

# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>

This can be confusing for anyone who's used to the CGI standard, so keep it in mind.  As an alternative, I use a "proper" querystring parser function:

<?php
function proper_parse_str($str) {
  # result array
  $arr = array();

  # split on outer delimiter
  $pairs = explode('&', $str);

  # loop through each pair
  foreach ($pairs as $i) {
    # split into name and value
    list($name,$value) = explode('=', $i, 2);

    # if name already exists
    if( isset($arr[$name]) ) {
      # stick multiple values into an array
      if( is_array($arr[$name]) ) {
        $arr[$name][] = $value;
      }
      else {
        $arr[$name] = array($arr[$name], $value);
      }
    }
    # otherwise, simply stick it in a scalar
    else {
      $arr[$name] = $value;
    }
  }

  # return result array
  return $arr;
}

$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
Vladimir Kornea 17-Jul-2007 09:04
parse_str() is confused by ampersands (&) being encoded as HTML entities (&amp;). This is relevant if you're extracting your query string from an HTML page (scraping). The solution is to run the string through html_entity_decode() before running it through parse_str().

(Editors: my original comment was a caution whose solution is obvious, but it has resulted in three replies ("so what?" "as intended" and "this is how to fix it"). Please remove the previous four posts dealing with this (69529, 70234, 72745, 74818) and leave just the above summary. This issue is too trivial to warrant the number of comments it has received.)
Vladimir Kornea 17-Jul-2007 08:46
parse_str() contained a bug (#39763) in PHP 5.2.0 that caused it to apply magic quotes twice. This bug was marked as fixed in the release notes of PHP 5.2.1, but there were apparently some issues with getting the fix through CVS on time, as our install of PHP 5.2.1 was still affected by it.
mike dot coley at inbox dot com 02-Jun-2007 12:25
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.

<?php

/* Converts an array of parameters into a query string to be appended to a URL.
 *
 * @return  string              : Query string to append to a URL.
 * @param   array    $array     : Array of parameters to append to the query string.
 * @param   string   $parent    : This should be left blank (it is used internally by the function).
 */
function append_params($array, $parent='')
{
    $params = array();
    foreach ($array as $k => $v)
    {
        if (is_array($v))
            $params[] = append_params($v, (empty($parent) ? urlencode($k) : $parent . '[' . urlencode($k) . ']'));
        else
            $params[] = (!empty($parent) ? $parent . '[' . urlencode($k) . ']' : urlencode($k)) . '=' . urlencode($v);
    }

    $sessid = session_id();
    if (!empty($parent) || empty($sessid))
        return implode('&', $params);

    // Append the session ID to the query string if we have to.
    $sessname = session_name();
    if (ini_get('session.use_cookies'))
    {
        if (!ini_get('session.use_only_cookies') && (!isset($_COOKIE[$sessname]) || ($_COOKIE[$sessname] != $sessid)))
            $params[] = $sessname . '=' . urlencode($sessid);
    }
    elseif (!ini_get('session.use_only_cookies'))
        $params[] = $sessname . '=' . urlencode($sessid);

    return implode('&', $params);
}

?>

Note that the function will also append the session ID to the query string if it needs to be.
Michal Zalewski 28-Apr-2007 11:27
Vladimir Kornea:
Try use html_entity_decode()

$str = 'first=value&amp;arr[]=foo+bar&amp;arr[]=baz';
parse_str(html_entity_decode($str), $output);
print_r($output);

Array
(
    [first] => value
    [arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )

)
php at voodoolabs dot net 07-Mar-2007 12:32
This is probably a better solution than below. The first line makes sure the file doesn't exist then the second line directs all requests to a script. No need to output a 200 header with this method either.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php      [L]
lenix.de 10-Feb-2007 04:20
if you would like to get a nice url scheme with php/apache and and want to handle all requests in a central php script there's a simple solution/hack:

create a .htaccess in your "basedir" where you've got your main script (in this example index.php) containing some lines like:

"ErrorDocument 404 /index.php"

inside index.php you can now do

<?php
    $virtual_path = substr(
        $_SERVER['REQUEST_URI'],
        strlen( dirname( $_SERVER['PHP_SELF'] ) ) + 1
    );
    if( ($pos = strpos( $virtual_path, '?' )) !== false ) {
        parse_str( substr( $virtual_path, $pos + 1 ), $_GET );
        $_REQUEST = array_merge( $_REQUEST, $_GET );
        $virtual_path = substr( $virtual_path, 0, $pos );
    }

    // some code checking for a valid location, etc...
    header( 'HTTP/1.1 200 OK' );
    header( 'Content-Type: text/plain' );

    echo $virtual_path."\n\n";
    print_r( $_REQUEST );
?>

// guido 'lenix' boehm
jgbreezer at gmail dot com 31-Jan-2007 04:52
Vladimir Kornea wrote on 8 Sep 2006:
"This function is confused by ampersands (&) being encoded as HTML entities (&amp;)"

Well, it would be - it's not supposed to be passed html entities, that's a different encoding scheme. This function does correctly decode url encoded params for you though (with the rawurlencode rather than urlencode, ie '+' is translated to a space).
Olivier Mengué 07-Oct-2006 02:02
Vladimir: the function is OK in how it deals with &amp;.
&amp; must only be used when outputing URLs in HTML/XML data.
You should ask yourself why you have &amp; in your URL when you give it to parse_str.
Vladimir Kornea 08-Sep-2006 02:15
This function is confused by ampersands (&) being encoded as HTML entities (&amp;).

$str = "first=value&amp;arr[]=foo+bar&amp;arr[]=baz";
parse_str($str, $output);
print_r($output);

Array
(
    [first] => value
    [amp;arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )
)
PEPE_RIVAS at repixel dot net 28-Aug-2006 06:21
CONVERT ANY FORMATTED STRING INTO VARIABLES

I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:

estado=1,txnid=5555444-8454445-4455554,monto=100.00

to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character... and i have  comma separated values... so i replace comma with &

<?php
$string = "estado=1,txnid=5555444-8454445-4455554,monto=100.00";
$string = str_replace(",","&",$string);
parse_str($string);
echo $monto; // outputs 100.00
?>
motin at demomusic dot nu 14-Apr-2006 06:13
When you have scripts run through the command-line (like locally via cron), you might want to be able to use _GET and _POST vars. Put this in top of your scheduled task files:

<?
    parse_str ($_SERVER['argv'][1], $GLOBALS['_GET']);
    parse_str ($_SERVER['argv'][2], $GLOBALS['_POST']);
?>

And call your script by:

/usr/local/bin/php /path/to/script.php "id=45&action=delete" "formsubmitted=true"

Cheers!
avi at amarcus dot com 03-Sep-2005 06:32
If you are trying to preserve a complex array, the function serialize might be better than http_build_query or other methods of making a query string.
ET 01-Sep-2005 03:14
In reply to what kerosuppi posted:

[quote]This does not work as expected.[/quote]
No, it works exactly as expected.

The call <?php parse_str($this->query_string);?>  "sets variables in the current scope" (just like said in the manual).

You are using this call in the constructor. Once the constructor is finished, the scope of this function has ended so it's logical that you can't access the variables anymore.

Your workaround though is a good one.

Hope this helps,
ET
Tore Bj�lseth 29-Jun-2005 05:59
As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.

This is a very useful combination if you want to re-use a search string url, but also slightly modify it:

Example:
<?
$url1 = "action=search&interest[]=sports&interest[]=music&sort=id";
$str = parse_str($url1, $output);

// Modifying criteria:
$output['sort'] = "interest";

$url2 = http_build_query($output);

echo "<br>url1: ".$url1;
echo "<br>url2: ".$url2;
?>

Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest

(Array indexes are automatically created.)
vargasangelo_1990 at hotmail dot com 19-Jun-2005 11:46
this can be another option for STR PARSING and use it as a $_GET variable.
<?php
$str= "op=downloads&id=1&details=1";
function parse_to_get($str=false){
    if($REQUEST_URI==$str): $ex = explode("/".$PHP_SELF."?", $str); $str = $ex[1]; endif;
    if($str):
        $a = explode("&", $str);
        foreach($a as $e){
            if($e):
                list($k,$v)=explode("=", $e);
                $_GET[$k]=$v;
            endif;
        }
    endif;
    extract($_GET);
}
parse_top_get("index.php?page=info&name=jonh&id=4245&app=server");

?>
:)

//Trukin
kerosuppi 29-May-2005 09:22
This does not work as expected.

<?php
class someclass
{
    var $query_string;
    function someclass($a_query_string)
    {
        $this->query_string = $a_query_string;
        parse_str($this->query_string);
    }
    function output()
    {
        echo $this->action;
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>

Use this instead.

<?php
class someclass
{
    var $arr;
    function someclass($a_query_string)
    {
        parse_str($a_query_string, $this->arr);
    }
    function output()
    {
        echo $this->arr['action'];
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>
mortoray at ecircle-ag dot com 25-May-2005 12:18
In Kent's solution you may wish to switch "urldecode" into "rawurldecode" if you'd like to get rid of the [annoying] plus '+' converted to space ' ' translation.
kent at nospam dot ioflux dot com 06-May-2005 08:13
You may want to parse the query string into an array.

<?php
/**
 * Similar to parse_str. Returns false if the query string or URL is empty. Because we're not parsing to
 * variables but to array key entries, this function will handle ?[]=1&[]=2 "correctly."
 *
 * @return array Similar to the $_GET formatting that PHP does automagically.
 * @param string $url A query string or URL
 * @param boolean $qmark Find and strip out everything before the question mark in the string
*/
function parse_query_string($url, $qmark=true)
{
    if ($qmark) {
        $pos = strpos($url, "?");
        if ($pos !== false) {
            $url = substr($url, $pos + 1);
        }
    }
    if (empty($url))
        return false;
    $tokens = explode("&", $url);
    $urlVars = array();
    foreach ($tokens as $token) {
        $value = string_pair($token, "=", "");
        if (preg_match('/^([^\[]*)(\[.*\])$/', $token, $matches)) {
            parse_query_string_array($urlVars, $matches[1], $matches[2], $value);
        } else {
            $urlVars[urldecode($token)] = urldecode($value);
        }
    }
    return $urlVars;
}

/**
 * Utility function for parse_query_string. Given a result array, a starting key, and a set of keys formatted like "[a][b][c]"
 * and the final value, updates the result array with the correct PHP array keys.
 *
 * @return void
 * @param array $result A result array to populate from the query string
 * @param string $k The starting key to populate in $result
 * @param string $arrayKeys The key list to parse in the form "[][a][what%20ever]"
 * @param string $value The value to place at the destination array key
*/
function parse_query_string_array(&$result, $k, $arrayKeys, $value)
{
    if (!preg_match_all('/\[([^\]]*)\]/', $arrayKeys, $matches))
        return $value;
    if (!isset($result[$k])) {
        $result[urldecode($k)] = array();
    }
    $temp =& $result[$k];
    $last = urldecode(array_pop($matches[1]));
    foreach ($matches[1] as $k) {
        $k = urldecode($k);
        if ($k === "") {
            $temp[] = array();
            $temp =& $temp[count($temp)-1];
        } else if (!isset($temp[$k])) {
            $temp[$k] = array();
            $temp =& $temp[$k];
        }
    }
    if ($last === "") {
        $temp[] = $value;
    } else {
        $temp[urldecode($last)] = $value;
    }
}

/**
* Breaks a string into a pair for a common parsing function.
*
* The string passed in is truncated to the left half of the string pair, if any, and the right half, if anything, is returned.
*
* An example of using this would be:
* <code>
* $path = "Account.Balance";
* $field = string_pair($path);
*
* $path is "Account"
* $field is "Balance"
*
* $path = "Account";
* $field = string_pair($path);
*
* $path is "Account"
* $field is false
* </code>
*
* @return string The "right" portion of the string is returned if the delimiter is found.
* @param string $a A string to break into a pair. The "left" portion of the string is returned here if the delimiter is found.
* @param string $delim The characters used to delimit a string pair
* @param mixed $default The value to return if the delimiter is not found in the string
* @desc
*/
function string_pair(&$a, $delim='.', $default=false)
{
    $n = strpos($a, $delim);
    if ($n === false)
        return $default;
    $result = substr($a, $n+strlen($delim));
    $a = substr($a, 0, $n);
    return $result;
}

?>
10-Mar-2005 04:26
yet another simpler way to do the reverse this function.
<?php
    /* BSD LINCENSE */
    function build_str($query_array) {
        $query_string = array();
        foreach ($query_array as $k => $v) {
            $query_string[] = $k.'='.$v;
        }
        return join('&', $query_string);
    }

    // example of use
    // set  a query string
    $test_query = "a=b&c=d";
    // parse a string
    parse_str($test_query, $query_array);
    //print it
    print_r($query_array);

    // test the build_str function
    if ( build_str($query_array) == $test_query ) {
        echo "It works";
    } else {
        echo "It doesn't work";
    }

?>
nospam at fiderallalla dot de 03-Feb-2005 02:29
Maybe you need an opposite which works with arrays:

<?php
function query_str ($params) {
    if ( !is_array($params) || count($params) == 0 ) return false;
    $fga = func_get_args();
    $akey = ( !isset($fga[1]) ) ? false : $fga[1];
    static $out = Array();

    foreach ( $params as $key=>$val ) {
        if ( is_array($val) ) {
            query_str($val,$key);
            continue;
        }

        $thekey = ( !$akey ) ? $key : $akey.'['.$key.']';
        $out[] = $thekey."=".$val;
    }

    return implode("&",$out);
}
?>
anatilmizun at gmail dot com 12-Oct-2004 04:10
I wrote a pair of functions using parse_str() that will write values in an array to a textfile and vice versa, read those values from the textfile back into the array. Quite useful if you need to store lots of data but don't have access to SQL.

Save the array by calling cfg_save($filename,$array) and load it back using $array=cfg_load($filename)

<?php
$newline="�";

function cfg_load($cfgfile){
    global $newline;
    $setting="";
    if(file_exists($cfgfile)){
        $setting=fopen($cfgfile, "r");
        $ookk="";
        while($ook=fgets($setting)){
            #strip comment
            $commt=strpos($ook,"##");
            if($commt!==false) $ook=substr($ook,0,$commt);
            #append
            if($ook!="") $ookk=$ookk."&".    str_replace($newline,"\n",str_replace("&","%26",trim($ook)));
        }
        fclose($setting);
        parse_str($ookk, $setting);
    }
    return $setting;
}

function cfg_save($cfgfile,$setting){
    global $intArray;
    $intArray="";
    for($i=0;$i<2000;$i++)
        $intArray[]=$i;
    if(is_array($setting)){
        $allkeys=array_keys($setting);
        foreach($allkeys as $aKey)
            cfg_recurse($setting[$aKey], $aKey, $outArray);
    }
    $cfgf=fopen($cfgfile,"w");
    foreach($outArray as $aLine)
        fputs($cfgf,stripslashes($aLine)."\r\n");
    fclose($cfgf);
}

function cfg_recurse($stuffIn, $keysofar, &$toAppend){
    global $intArray, $newline;
    if(is_array($stuffIn)){
        $allkeys=array_keys($stuffIn);
        if(array_slice($intArray,0,sizeof($allkeys))==$allkeys)
            $nokey=true;
        else
            $nokey=false;
        foreach($allkeys as $aKey){
            if(!$nokey) $toKey=$aKey;
            cfg_recurse($stuffIn[$aKey], $keysofar."[".$toKey."]", $toAppend);
        }
    }else
        $toAppend[]=$keysofar."=".str_replace("\n",$newline,$stuffIn);
}
?>

Note that these functions support nested arrays of unlimited levels ;)
Matt Curtis 08-Sep-2004 08:46
If the querystring contains duplicate keys in the key-value pairs, parse_str will only return the last instance of the value.  For example, in the following:

<?php
$mystr = "test1=blah&test2=bleh&test1=burp";
parse_str($mystr, $myarray);
echo $myarray['test1'];
?>
The value output will be 'burp'.

I wrote a function that takes a querystring and returns the the key-value pairs as a two-dimensional array so each duplicate key is available:

<?php
$str = "test1=blah&test2=bleh&test1=burp";
$valsarray = parse_str_ext($str);
echo $valsarray['test1'][0];
echo $valsarray['test1'][1];
echo $valsarray['test2'][0];

function parse_str_ext($toparse) {
    $returnarray = array();
    $keyvaluepairs = split("&", $toparse);
    foreach($keyvaluepairs as $pairval) {
        $splitpair = split("=", $pairval);
        if(!array_key_exists($splitpair[0], $returnarray)) $returnarray[$splitpair[0]] = array();

        $returnarray[$splitpair[0]][] = $splitpair[1];
    }
    return $returnarray;
}
?>

Output will be:
blah
burp
bleh
17-Jun-2004 05:23
Note that variables cannot contain a DOT (.) in PHP. So, DOT will be replaced by underscore.
e.g. variables like "variable.something" will be converted into "variable_something".
31-Mar-2004 10:58
The documentation does not appear to mention that parse_str also urldecodes each item in the resulting array.

There also appears to be a bug in earlier versions of PHP that causes these urldecoded strings to also be escaped.  (Certainly I was having problems with %22 being turned into /" on my server, but not on my development box, despite forcing magic quotes off).
dante at lorenso dot com 05-Jul-2003 10:11
You can perform the opposite of this function if you like with a function like I've built below:

    /**
     * Reverse of parse_str().  Converts array into
     * string with query format
     */
    function query_str ($params) {
        $str = '';
        foreach ($params as $key => $value) {
            $str .= (strlen($str) < 1) ? '' : '&';
            $str .= $key . '=' . rawurlencode($value);
        }
        return ($str);
    }

-- Dante
ord
print
Обработка строк


Выводит строку

parse_str
printf
Обработка строк
PHP Manual

print

(PHP 4, PHP 5)

print — Выводит строку

Описание

int print ( string $arg )

Выводит arg.

print не является "настоящей" функцией (это конструкция языка), поэтому заключать аргументы в скобки необязательно.

Список параметров

arg

Вводимые данные.

Возвращаемые значения

Возвращает 1, всегда.

Примеры

Пример #1 Примеры использования print

<?php
print("Привет мир!");

print "print() можно использовать и без скобок.";

print "Это займет
несколько строк. Переводы строки тоже
выводятся";

print "Это займет\nнесколько строк. Переводы строки тоже\nвыводятся";

print "Экранирование символов делается \"Так\".";

// с print можно использовать переменные ...
$foo = "foobar";
$bar = "barbaz";

print "foo - это $foo"; // foo - это foobar

// ... и массивы
$bar = array("value" => "foo");

print "это {$bar['value']} !"; // это foo !

// При использовании одиночных кавычек выводится имя переменной, а не значение
print 'foo - это $foo'; // foo - это $foo

// Если вы не используете другие символы, можно вывести просто значения переменных
print $foo;          // foobar

print <<<END
Здесь используется синтаксис "here document" для вывода
нескольких строк с подстановкой переменных $variable.
Заметьте, что закрывающий идентификатор должен
располагаться в отдельной строке, никаких пробелов!
END;
?>

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Смотрите также

  • echo() - Выводит одну или более строк
  • printf() - Выводит отформатированную строку
  • flush() - Сброс буфера вывода
  • Heredoc синтаксис

User Contributed Notes

aflavio at gmail dot com 12-Jan-2011 12:32
Check this statement:

echo 3 . print(2) . print(4) . 5 . 'c' . print(6) . print(7). 'b' .print(8) . 'a';

It's will always output starting from the right to the left.

Thus we have:

8a                              //1o print
7b18a                        //2o print
617b18a                    //3o print
8a7b16145c1             //4o print

8a7b16145c12131     //Final output

That's it.
sdaau 22-Dec-2009 02:28
Printing an empty string from PHP, as in

print "";

returns a single byte (content length=1) - the line-feed character '\n' (0a).

So if you truly want to return an empty string, you may want to use "flush()" instead - then headers without any Content-length will be returned.

Do note, however, that regardless of whether print or flush is used, accessing such a PHP output from AJAX (via .responseText) will always have a '\n' as a value for an "empty" string sent from PHP.
Chris Watson 01-Oct-2009 01:20
mvpetrovich of 2007 could just use single quotes as his string delimiters (see the example in the current documentation).
It's not ALWAYS appropriate, but generally it is best (the Zend Framework coding standards have a good take on this). It yields a number of interesting benefits:
1: Nobody will be tempted to write functions to replace backticks or other characters with double quotes. Such functions may cause a (negligible) loss of efficiency, and maybe other undesired effects.
2: You will be able to use double quotes without escaping. This is recommended (although not required) for HTML and XML attributes, as well as quoted text.
3: The script will hit the browser very slightly slightly faster since PHP doesn't have to scan through the string looking for variables, escaped characters, curly braces or other things.
4: Your code gets ten times easier to read. (as mvpetrovich pointed out)

If, in spite of these four excellent benefits, you really MUST still use double quotes to delimit boring old string constants (and seriously, why would you?), you could use the slightly less favourable single quotes as delimiters for most markup languages.
HTML served as HTML will even let you lay out unquoted attributes (yuck).

It should also be noted though that if you are just printing bare strings, you may as well shut off the php parser. The quickest way to send a string is to write it as plain text, OUTSIDE of the php tags. This will also make your code look excellent in a lot of syntax highlighters.

There are few disadvantages to doing this, if any. Output buffering still works. All your classes and objects and includes remain in place. Your script runs faster. World peace is obtained.
http://www.danielxmorris.com 28-Aug-2008 07:46
An update to the println function I wrote below, this is a more efficient, correct and returns a value (1, always; (print)).

<?php

    function println($string_message = '') {
        return isset($_SERVER['SERVER_PROTOCOL']) ? print "$string_message<br />" . PHP_EOL:
          print $string_message . PHP_EOL;
    }

?>
user at example dot net 25-Aug-2008 09:47
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
    if (print("foo") && print("bar")) {
        // "foo" and "bar" have been printed
    }
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
    if ((print "foo") && (print "bar")) {
        // "foo" and "bar" have been printed
    }
?>
user at example dot net 25-Aug-2008 09:45
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
    if (print("foo") && print("bar")) {
        // "foo" and "bar" had been printed
    }
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
    if ((print "foo") && (print "bar")) {
        // "foo" and "bar" had been printed
    }
?>
danielxmorris @ gmail dotcom 16-May-2008 04:08
I wrote a println function that determines whether a \n or a <br /> should be appended to the line depending on whether it's being executed in a shell or a browser window.  People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people.

<?php
function println ($string_message) {
    $_SERVER['SERVER_PROTOCOL'] ? print "$string_message<br />" : print "$string_message\n";
}
?>

Examples:

Running in a browser:

<?php println ("Hello, world!"); ?>
Output: Hello, world!<br />

Running in a shell:

<?php println ("Hello, world!"); ?>
Output: Hello, world!\n
jon 01-Jun-2007 07:19
the FAQTs article can be found archived at http://web.archive.org/web/20060601063513/http
://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

(url split to get past the line-length limitation)
mvpetrovich 29-Mar-2007 11:02
I grew quite tired of backslashes, and wrote these routines. It uses the back single quote as a substitute for double quotes within a statement.  It made my code much more readable.  It is a little easier than using a "here document."  I also found I make a few less typing errors.

<?php

function qq($text) {return str_replace('`','"',$text); }
function printq($text) { print qq($text); }
function printqn($text) { print qq($text)."\n"; }

//example - before

echo "<a href=\"#\" class=\"stdbutton\" style=\"float:left;\" onclick=\"myfunction(); return false;\">My Link</a>\n";

//becomes - with printqn function

printqn("<a href=`#` class=`stdbutton` style=`float:left;` onclick=`myfunction(); return false;`>My Link</a>");

?>
floppie at quadra-tec dot net 15-Nov-2006 09:09
At the top of your page, do something to this effect:
<?php
    $n = "\n";
    $t = "\t";
?>

Then, if you need your table cell four tabs in:

<?php echo($t . $t . $t . $t . '<td>whatever</td>' . $n); ?>

This means the parser only has to interpret four characters inside double quotes, then just stores them in variables.  With strings that small, concatenating six things together won't be slow at all.
vincent at bevort dot com 21-May-2006 12:36
Sometime there is no choice in using a single or double quote
ie when using special chars to format the output to make the HTML more readable you have to use the Double qoutes. Single quotes make PHP fotmat the '\n' as text
phpnet at i3x171um dot com 20-May-2006 07:41
I have written a script to benchmark the several methods of outputting data in PHP: via single quotes, double quotes, heredoc, and printf. The script constructs a paragraph of text with each method. It performs this construction 10,000 times, then records how long it took. In total, it prints 160,000 times and records 16 timings. Here are the raw results.

Outputted straight to browser--

Single quotes: 2,813 ms
...with concatenation: 1,179 ms
Double quotes: 5,180 ms
...with concatenation: 3,937 ms
heredoc: 7,300 ms
...with concatenation: 6,288 ms
printf: 9,527 ms
...with concatenation: 8,564 ms

Outputted to the output buffer--

Single quotes: 8 ms
...with concatenation: 38 ms
Double quotes: 8 ms
...with concatenation: 47 ms
heredoc: 17 ms
...with concatenation: 49 ms
printf: 54 ms
...with concatenation: 52 ms

A nice graph of the script's output can be found here:
http://i3x171um.com/output_benchmarks/ob.gif

So what should you choose to print your text? I found several things out writing this.

First, it should be noted that the print and echo keywords are interchangeable, performance-wise. The timings show that one is probably an alias for the other. So use whichever you feel most comfortable with.

Second, if you've ever wondered which was better, the definitive answer is single quotes. Single quotes are at least four times faster in any situation. Double quotes, while more convenient, do pose a debatably significant performance issue when outputting massive amounts of data.

Third, stay away from heredoc, and absolutely stay away from [s]printf. They're slow, and the alternatives are there.

The source of my script can be found here:
http://i3x171um.com/output_benchmarks/ob.txt

DO NOT RUN THE SCRIPT ON THE INTERNET! Run it instead from localhost. The script outputs ~45 megabytes of text in an html comment at the top of the page by default. Expect the benchmark to take ~45 seconds. If this is too long, you can change the amount of iterations to a lower number (the results scale accurately down to about 1,000 iterations).
g8z at yahoo dot com 13-Mar-2006 11:16
I wanted to print a file on a Windows 2003 server from PHP, and found the "print" function instead. Just in case some other users are trying to physically print to a printer, rather than print to the screen, here's a function to do it.

This function will print a single file of one of these types: pdf, doc, xls, rtf, or plain text. If you have the full .exe path, you can print other document types, too. The shell_exec function is not enabled in safe mode.

Courtesy of Darren's Script Archive: http://www.tufat.com

<?php

function print_file($filename)
{
    // path to your adobe executable
    $adobe_path='"C:/Program Files/Adobe/Acrobat 7.0/Reader/AcroRd32.exe"';

    $ext='';
    $ext=strrchr($filename,'.');
    $ext=substr($ext,1);
    $ext_xl=substr($ext,0,2);

    if ($ext=='pdf') {
        shell_exec ($adobe_path.' /t '.$filename);
    }
    else if ($ext=='doc'||$ext=='rtf'||$ext=='txt') {
        $word = new COM("Word.Application");
        $word->visible = true;
        $word->Documents->Open($filename);
        $word->ActiveDocument->PrintOut();
        $word->ActiveDocument->Close();
        $word->Quit();
    }
    else if ($ext_xl=='xl') {
        $excel = new COM("Excel.Application");
        $excel->visible = true;
        $excel->Workbooks->Open($filename);
        $excel->ActiveWorkBook->PrintOut();
        $excel->ActiveWorkBook->Close();
        $excel->Quit();
    }
}

// example of printing a PDF

print_file("C:/photo_gallery.pdf");

?>
jon at tap dot net 05-Dec-2005 01:48
I have a small utility run from the command line that processes a potentially huge list of files. As it can take hours to complete, I stuck a

print '.';

statement in the body of the main loop to prove that something was  happening.

For reasons unknown to me, the utiliity suddenly started buffering the output such that it printed nothing until completion, defeating the purpose of the running monitor. Adding flush() statements did nothing. The problem was solved by using

fputs(STDOUT, '.');

but I have no idea why.
james-web at and dot org 25-Jul-2005 03:47
Note that if you want to dump the value of a variable, you want to use print_r(), var_dump() or var_export().
ejallison at gmail dot com 16-Jul-2005 03:10
This is a simple function for printing debug comments that I didn't think of for a long time. Maybe it'll serve you good too.

<?php

function printd($str) {
  if ($debug) { echo $str; }
}

// ...

if ($valueCalculatedEarlierInTheScript == 3) {
  doSomethingWithNoOutput();
  printd("doSomethingWithNoOutput() has executed.");
}

?>

It's mostly just to make sure everything is running without having to go through everything and put in echo "Step #whatever has executed" whenever something mysterious isn't working.
gem at rellim dot com 05-Nov-2004 01:28
HERE Documents can reference arrays as long as you enclose
the vars in {}.

Like this:

<?php

$line = array( 'title' => "Hello", 'date' => 'Today');

echo <<<EOT
Title: {$line['title']}
Date: {$line['date']}
EOT;

?>

Run this and get
Title: Hello
Date: Today

More info here, scroll down to "heredoc syntax":
http://www.php.net/manual/en/language.types.string.php
rjl at xs4all dot nl 15-Jan-2004 04:08
To elaborate on above example adding an
array variable
$text = <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
User = {$_REQUEST['user']}
END;

'print $text;' Will output the string. Very handy for storing HTML.
Or adding {} around the array will allow you to use
above mentioned html blocks in conjuction with forms.

Rene =<>=
parse_str
printf
Обработка строк


Выводит отформатированную строку

print
quoted_printable_decode
Обработка строк
PHP Manual

printf

(PHP 4, PHP 5)

printf — Выводит отформатированную строку

Описание

int printf ( string $format [, mixed $args [, mixed $... ]] )

Выводит строку, отформатированную в соответствии с аргументом format.

Список параметров

format

Описание параметра format смотрите в описании функции sprintf().

args

...

Возвращаемые значения

Возвращает длину выведенной строки.

Смотрите также

  • print() - Выводит строку
  • sprintf() - Возвращает отформатированную строку
  • vprintf() - Выводит отформатированную строку
  • sscanf() - Разбирает строку в соответствии с заданным форматом
  • fscanf() - Обрабатывает данные из файла в соответствии с форматом
  • flush() - Сброс буфера вывода

User Contributed Notes

spiffytech at gmail dot com 15-Feb-2012 09:11
Be careful when relying on typecasting with printf(). For example,

    printf("%d", "17,999")

returns "17".
kalai_msc29 at rediffmail dot com 29-Mar-2007 11:04
//If you want to make many Hidden fields you can use the function
//You can pass the values as array value,This will help you, when you are going to post many hiddend fields:-
function MakeHidden($ArrValues)
    {
       global $dearvar;
       echo $dearvar;
       if(is_array($ArrValues)){
             foreach($ArrValues as $key=>$values)
              {
                 echo $MakeHTML = "<input type='hidden' name='$values' value='$values'>";
               }
      }

      else {
            echo $MakeHTML = "<input type='hidden' name='$ArrValues' value='$ArrValues'>";
         }
   return $MakeHTML;
}

//example:-

MakeHidden(array("value1","value2","value3"));

//OutPut :-

<input type="hidden" value="value1" name="value1"/>
<input type="hidden" value="value2" name="value2"/>
<input type="hidden" value="value3" name="value3"/>
php at iain dot nl 14-Mar-2006 07:24
for arrays, there is vprintf();

alternatively, if you have it all in one array (including the format), this will do the trick:

<?php

$goodevil = array ('There is a difference between %s and %s', 'good', 'evil');
echo vprintf(array_shift($goodevil),$goodevil);

?>

and without mangling your array, you might use call_user_func_array:

<?php

$goodevil = array ('There is a difference between %s and %s', 'good', 'evil');
echo call_user_func_array('sprintf',$goodevil);

?>
php at mole dot gnubb dot net 10-Apr-2005 06:15
[Editor's Note: Or just use vprintf...]

If you want to do something like <?php printf('There is a difference between %s and %s', array('good', 'evil')); ?> (this doesn't work)  instead of <?php printf('There is a difference between %s and %s', 'good', 'evil'); ?> you can use this function:

<?php
function printf_array($format, $arr)
{
    return call_user_func_array('printf', array_merge((array)$format, $arr));
}
?>

Use it the following way:
<?php
$goodevil = array('good', 'evil');
printf_array('There is a difference between %s and %s', $goodevil);
?>
and it will print:
There is a difference between good and evil
codeslinger at compsalot dot com 30-Jan-2005 08:24
Several people have commented about problems with aligning numbers.  I just wanted to add a bit of clarification.

According to the spec all True Type Fonts (especially porpotional spaced fonts) use a fixed width for numeric digits.  All digits have the same width which is equal to the width of "0".

Where things go haywire when trying to align numbers is that the space character does not have the same width as a digit when using a porportional spaced font.

Therefore if you want to line up a column of numbers, you can not use leading spaces to position them unless you use the same quantity of space characters for each row. e.g. your numbers have leading zeros etc.

The simplest solution is to switch to a monospaced font.  Alternativly you can use positioning tags.

Summary: Your numbers will always line up properly regardless of the font used, if you get the starting position to be consistant.
lordfarquaad at notredomaine dot net 03-Mar-2004 06:48
In response to chris dot breen at accurate dot com :

This will work, but i didn't try:
<?php
$format = 'The %2$s contains %1$d monkeys.
         That is a nice %2$s full of %1$d monkeys.';
printf($format, $num, $location);
?>

Your problem came from the fact that in the string "\$s", the $ is simply escaped by the \, but but you must not do that with single quoted strings. Try to echo your strings to test it, or just go to http://www.php.net/manual/en/language.types.string.php
php at soulcoffee dot com 24-May-2003 01:37
If you are experiencing weird difficulties with floating point numbers, namely ones that appear to be overflow errors, then it could be a compilation error. Try the following at a prompt:

python -c 'int(10.1); int(10000.3); int(1.2)'

If that overflows, then you'll need to do the following:

1) Fix your CFLAGS (probably change -march=pentium4 to -march=pentium3)
2) Recompile glibc
3) Recompile mod_php
4) Restart Apache
5) Check your script, it should be fine now

NOTE: This is _not_ a bug in PHP. It just appears that way because there is a problem in the underlying libraries.
brian at exclamationlabs dot com 02-Jan-2003 12:34
If you are printing data in a <pre>, courier font, or otherwise non-variable length font (like a terminal), you might have use for printf's justify feature.
<?php
$heading1 = "Label 1";
$heading2 = "Label 2";

$value1 = "31298";
$value2 = "98";

print "<pre>\n";
printf ("%'.-15.15s%'.6.6s\n", $heading1, $value1);
printf ("%'.-15.15s%'.6.6s\n", $heading2, $value2);
print "</pre>\n";
?>

Very handy for simple formatting..
eugenew at starhub dot net dot sg 20-Dec-2002 09:13
If anyone is looking for writing a quine using printf(),
this is my example:

<?php $f='<?php $f=%c%s%c; printf($f,39,$f,39); ?>'; printf($f,39,$f,39); ?>

This also helps those who are new to printf() see one way of using the 'mixed args' part, rather than just a single argument as in most examples I've seen.
dalu at uni SPAMHAM dot de 10-Dec-2002 10:43
copypasted from msdn

A format specification, which consists of optional and required fields, has the following form:

%[flags] [width] [.precision] [{h | l | I64 | L}]type

Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character (for example, %s). If a percent sign is followed by a character that has no meaning as a format field, the character is copied to stdout. For example, to print a percent-sign character, use %%.

The optional fields, which appear before the type character, control other aspects of the formatting, as follows:

type
Required character that determines whether the associated argument is interpreted as a character, a string, or a number (see the printf Type Field Characters table.
flags
Optional character or characters that control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes (see the Flag Characters table). More than one flag can appear in a format specification.
width
Optional number that specifies the minimum number of characters output (see printf Width Specification).
precision
Optional number that specifies the maximum number of characters printed for all or part of the output field, or the minimum number of digits printed for integer values (see the How Precision Values Affect Type table).
h | l | I64 | L
Optional prefixes to type-that specify the size of argument (see the Size Prefixes for printf and wprintf Format-Type Specifiers table).
sam[NOSPAM] at [NOSPAM]kingdomfaith dot com 28-Jun-2002 12:45
I don't know if this is useful to anyone, but here goes! Example for using the printf function to output an object.

class person
{
    var $name = "";
    function name($newname = NULL)
    {
        if(! is_null($newname))
        {
            $this->name=$newname;
        }
        return $this->name;
    }
    var $surname = "";
    function surname($newsurname = NULL)
    {
        if(! is_null($newsurname))
        {
            $this->surname=$newsurname;
        }
        return $this->surname;
    }
    var $age = "";
    function age($newage = NULL)
    {
        if(! is_null($newage))
        {
            $this->age=$newage;
        }
        return $this->age;
    }
}

$bob = new person;
$bob->name('Bob');
$bob->surname('Builder');
$bob->age('50');

printf("Hi %s, your surname is %s and you are %s years old", $bob->name, $bob->surname, $bob->age);

Outputs:

Hi Bob, your surname is Builder and you are 50 years old
maybird99 at yahoo dot com 26-Feb-2002 07:20
instead of writing a function to round off a float (let's call it 'x') accurately, it's much easier to add a small number to x and then truncate it...
For example: if you want to round off to the nearest integer, just add 0.5 to x and then truncate it. if x=12.6, then it would calculate 13.1, and truncate it to 13. If x=14.4, it would calculate 14.9 and truncate it to 14.
ezislis at mail dot ru 09-Feb-2002 07:25
be careful with integers, they cant hold large values.

printf("%d",10023123553.45634663);
will print out: 1433188961
and
printf("%.0f",10023123553.45634663);
will print out: 10023123553
deekayen at hotmail dot com 11-Oct-2001 05:54
You can use this function to format the decimal places in a number:

$num = 2.12;
printf("%.1f",$num);

prints:

2.1

see also: number_format()
shepard at ameth dot org 17-Sep-2001 07:37
Be sure that the output channel is available to write on before executing printf()!  Some functions in classes available from various sources (in my case, DB_Sql::query() in PHPLIB) assume that printing will work, even after the default output stream has been closed.

For me the issue was most notable in PHP4 session management when I was creating my own sess_write() handler.  Since I was unable to find any function that checks for the output stream that printf() uses, I just had to drop the crazy use of the printf(). (does some function already exist to check for the presence of an output stream?)
arunass at anm dot org 21-Aug-2000 07:38
There are times when you don't want a number like .0002 to be truncated to .00 - where you'd like to actually have at least some number of significant digits, not just the decimal places.
Here's a sample of how you might do that, although scientific notation might be better.  Why doesn't PHP support some of the other C style floating point formats?

<?php
//  string FloatFormat(float $Value, int $Precision)
//  - AGS 21/08/2000
//
//There is no range checking performed here so the
//  function will vaporize on out of range values.

function FloatFormat($Value, $Precision)
{
    $decimals = log10(abs($Value));

    $decimals = - (intval(min($decimals, 0)) - $Precision);

    $format = "%." . $decimals . "f";
    return sprintf($format, $Value);
}
?>
jeremiah at alcyon dot net 06-Jul-2000 10:15
Someone mentioned that the dropping of digits is pernicious; here's a small function you can throw in an include file or something to ensure some accurate precision.

<?php
//---------------------
// float precision (float, integer)
//
//                  - jlph 6.30.2000
//
// A function to limit the # of decimal places
// displayed in a float. Takes a float and an integer.
// The float will be taken to the decimal place
// specified by the integer and rounded up accordingly.
// Returns a float with the corners smoothed off.
//---------------------

function precision ($value, $place){
        $value = $value * pow(10, $place + 1);
        $value = floor($value);
        $value = (float) $value/10;
        (float) $modSquad = ($value - floor($value));
        $value = floor($value);
        if ($modSquad > .5){
                $value++;
        }
        return $value / (pow(10, $place));
}
?>
jarred at coltonsolutions dot com 23-Feb-2000 05:03
As far as I know, you should be able to simply include &nbsp; in the format string, so something like this:

printf("Value of I: &nbsp;&nbsp;%d\n", $i);

printf is the C/C++ style of doing formatted output, and as such the only special characters in the format string are '\' and '%', and characters immediately following these special cases may be affected.  (So "%c" mean a character, while "%%c" means print a percent sign followed by the letter c.)
dhosek at excite dot com 05-Dec-1999 02:27
Be careful:
printf ("(9.95 * 100) = %d \n", (9.95 * 100));

'994'

First %d converts a float to an int by truncation.

Second floats are notorious for tiny little rounding errors.
print
quoted_printable_decode
Обработка строк


Преобразует строку, закодированную методом quoted-printable в 8-битовую строку

printf
quoted_printable_encode
Обработка строк
PHP Manual

quoted_printable_decode

(PHP 4, PHP 5)

quoted_printable_decode — Преобразует строку, закодированную методом quoted-printable в 8-битовую строку

Описание

string quoted_printable_decode ( string $str )

Эта функция возращает 8-битную бинарную строку, соответствующую указанной строке в кодировке quoted-printable (в соответствии с разделом 6.7 » RFC2045, а не разделом 4.5.2 » RFC2821, т.е. дополнительные точки не будут вырезаны из начала строки).

Эта функция подобна функции imap_qprint(), но не требует для своей работы модуля IMAP.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает 8-битную бинарную строку.

Смотрите также

  • quoted_printable_encode() - Кодирует 8-битную строку в с помощью метода quoted-printable

User Contributed Notes

feedr 06-Mar-2009 02:39
Another (improved) version of quoted_printable_encode(). Please note the order of the array elements in str_replace().
I've just rewritten the previous function for better readability.

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
        $string = str_replace(array('%20', '%0D%0A', '%'), array(' ', "\r\n", '='), rawurlencode($string));
        $string = preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", $string);

        return $string;
  }
}
?>
andre at luyer dot nl 02-Nov-2008 12:36
A small update for Andrew's code below. This one leaves the original CRLF pairs intact (and allowing the preg_replace to work as intended):

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n",
      str_replace("%", "=", str_replace("%0D%0A", "\r\n",
        str_replace("%20"," ",rawurlencode($string)))));
  }
}
?>

Regards, André
Karora 19-Oct-2008 08:27
Taking a bunch of the earlier comments together, you can synthesize a nice short and reasonably efficient quoted_printable_encode function like this:

Note that I put this in my standard library file, so I wrap it in a !function_exists in order that if there is a pre-existing PHP one it will just work and this will evaluate to a noop.

<?php
if ( !function_exists("quoted_printable_encode") ) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7.  Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces aren't encoded as =20 though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string))));
  }
}
?>

Regards,
Andrew McMillan.
zg 27-Sep-2008 06:48
<?php

function quoted_printable_encode( $str, $chunkLen = 72 )
{
    $offset = 0;

    $str = strtr(rawurlencode($str), array('%' => '='));
    $len = strlen($str);
    $enc = '';

    while ( $offset < $len )
    {
        if ( $str{ $offset + $chunkLen - 1 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 1);
            $offset += $chunkLen - 1;
        }
        elseif ( $str{ $offset + $chunkLen - 2 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 2);
            $offset += $chunkLen - 2;
        }
        else
        {
            $line = substr($str, $offset, $chunkLen);
            $offset += $chunkLen;
        }

        if ( $offset + $chunkLen < $len )
            $enc .= $line ."=\n";
        else
            $enc .= $line;
    }

    return $enc;
}

?>
Christian Albrecht 24-Sep-2008 03:10
In Addition to david lionhead's function:

<?php
function quoted_printable_encode($txt) {
    /* Make sure there are no %20 or similar */
    $txt = rawurldecode($txt);
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9')) {
            $line.=$txt[$i];
            if (strlen($line)>=75) {
                $tmp.="$line=\n";
                $line="";
            }
        }
        else {
            /* Important to differentiate this case from the above */
            if (strlen($line)>=72) {
            $tmp.="$line=\n";
            $line="";
            }
            $line.="=".sprintf("%02X",ord($txt[$i]));
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
?>
lewiswright [ at t] gmail [d dot t] com 24-Sep-2008 11:16
In response to Bobo, using:

chunk_split($string, 76, "=\n");

Can result to broken encoding (in some rare cases). This is for a couple of reasons. Firstly, the chunk split could insert a newline between an encoding if it was on the end of a line. So it could turn an entity: =20 in to =2=\n0 - which breaks it. Secondly, the spec says that the line should be no longer than 76 in total, which includes the '=' used to indicate a soft newline.

Additionally, there's a couple of minor readability issues with it. Firstly, chunk_split leaves a trailing newline - which is unnecessary. Lastly, it does not consider newlines already in the text (which breaks readability) so it often wraps when not needed.

Here's a snippet which will fix all the issues mentioned:

preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", $data);
david at lionhead dot nl 18-Aug-2008 05:54
My version of quoted_printable encode, as the convert.quoted-printable-encode filter breaks on outlook express. This one seems to work on express/outlook/thunderbird/gmail.

function quoted_printable_encode($txt) {
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9'))
            $line.=$txt[$i];
        else
            $line.="=".sprintf("%02X",ord($txt[$i]));
        if (strlen($line)>=75) {
            $tmp.="$line=\n";
            $line="";
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
Bobo 12-Jul-2008 09:20
Following up to Hoffa's function, return the result like:

chunk_split($string, 76, "=\n");

to conform to the RFC, which requires that lines are no longer than 76 chars.
h atnospam hoffa dotelidot se 31-Mar-2008 05:32
I do like this to encode

function quoted_printable_encode($string) {
  $string = rawurlencode($string);
  $string = str_replace("%","=",$string);
  RETURN $string;
}

best regards / Hoffa
vita dot plachy at seznam dot cz 23-Mar-2008 08:22
<?php
$text = <<<EOF
This function enables you to convert text to a quoted-printable string as well as to create encoded-words used in email headers (see http://www.faqs.org/rfcs/rfc2047.html).

No line of returned text will be longer than specified. Encoded-words will not contain a newline character. Special characters are removed.
EOF;

define('QP_LINE_LENGTH', 75);
define('QP_LINE_SEPARATOR', "\r\n");

function quoted_printable_encode($string, $encodedWord = false)
{
    if(!preg_match('//u', $string)) {
        throw new Exception('Input string is not valid UTF-8');
    }

    static $wordStart = '=?UTF-8?Q?';
    static $wordEnd = '?=';
    static $endl = QP_LINE_SEPARATOR;

    $lineLength = $encodedWord
        ? QP_LINE_LENGTH - strlen($wordStart) - strlen($wordEnd)
        : QP_LINE_LENGTH;

    $string = $encodedWord
        ? preg_replace('~[\r\n]+~', ' ', $string)    // we need encoded word to be single line
        : preg_replace('~\r\n?~', "\n", $string);    // normalize line endings
    $string = preg_replace('~[\x00-\x08\x0B-\x1F]+~', '', $string);    // remove control characters

    $output = $encodedWord ? $wordStart : '';
    $charsLeft = $lineLength;

    $chr = isset($string{0}) ? $string{0} : null;
    $ord = ord($chr);

    for ($i = 0; isset($chr); $i++) {
        $nextChr = isset($string{$i + 1}) ? $string{$i + 1} : null;
        $nextOrd = ord($nextChr);

        if (
            $ord > 127 or    // high byte value
            $ord === 95 or    // underscore "_"
            $ord === 63 && $encodedWord or    // "?" in encoded word
            $ord === 61 or    // equal sign "="
            // space or tab in encoded word or at line end
            $ord === 32 || $ord === 9 and $encodedWord || !isset($nextOrd) || $nextOrd === 10
        ) {
            $chr = sprintf('=%02X', $ord);
        }

        if ($ord === 10) {    // line feed
            $output .= $endl;
            $charsLeft = $lineLength;
        } elseif (
            strlen($chr) < $charsLeft or
            strlen($chr) === $charsLeft and $nextOrd === 10 || $encodedWord
        ) {    // add character
            $output .= $chr;
            $charsLeft-=strlen($chr);
        } elseif (isset($nextOrd)) {    // another line needed
            $output .= $encodedWord
                ? $wordEnd . $endl . "\t" . $wordStart . $chr
                : '=' . $endl . $chr;
            $charsLeft = $lineLength - strlen($chr);
        }

        $chr = $nextChr;
        $ord = $nextOrd;
    }

    return $output . ($encodedWord ? $wordEnd : '');
}

echo quoted_printable_encode($text/*, true*/);
ludwig at gramberg-webdesign dot de 24-Sep-2007 12:13
my approach for quoted printable encode using the stream converting abilities

<?php
/**
 * @param string $str
 * @return string
 * */
function quoted_printable_encode($str) {
    $fp = fopen('php://temp', 'w+');
    stream_filter_append($fp, 'convert.quoted-printable-encode');
    fwrite($fp, $str);
    fseek($fp, 0);
    $result = '';
    while(!feof($fp))
        $result .= fread($fp, 1024);
    fclose($fp);
    return $result;
}
?>
roelof 24-Jul-2007 07:06
I modified the below version of legolas558 at users dot sausafe dot net and added a wrapping option.

<?php
/**
 *    Codeer een String naar zogenaamde 'quoted printable'. Dit type van coderen wordt
 *    gebruikt om de content van 8 bit e-mail berichten als 7 bits te versturen.
 *
 *    @access public
 *    @param string    $str    De String die we coderen
 *    @param bool      $wrap   Voeg linebreaks toe na 74 tekens?
 *    @return string
 */

function quoted_printable_encode($str, $wrap=true)
{
    $return = '';
    $iL = strlen($str);
    for($i=0; $i<$iL; $i++)
    {
        $char = $str[$i];
        if(ctype_print($char) && !ctype_punct($char)) $return .= $char;
        else $return .= sprintf('=%02X', ord($char));
    }
    return ($wrap === true)
        ? wordwrap($return, 74, " =\n")
        : $return;
}

?>
legolas558 at users dot sausafe dot net 21-Feb-2007 11:09
As soletan at toxa dot de reported, that function is very bad and does not provide valid enquoted printable strings. While using it I saw spam agents marking the emails as QP_EXCESS and sometimes the email client did not recognize the header at all; I really lost time :(. This is the new version (we use it in the Drake CMS core) that works seamlessly:

<?php

//L: note $encoding that is uppercase
//L: also your PHP installation must have ctype_alpha, otherwise write it yourself
function quoted_printable_encode($string, $encoding='UTF-8') {
// use this function with headers, not with the email body as it misses word wrapping
       $len = strlen($string);
       $result = '';
       $enc = false;
       for($i=0;$i<$len;++$i) {
        $c = $string[$i];
        if (ctype_alpha($c))
            $result.=$c;
        else if ($c==' ') {
            $result.='_';
            $enc = true;
        } else {
            $result.=sprintf("=%02X", ord($c));
            $enc = true;
        }
       }
       //L: so spam agents won't mark your email with QP_EXCESS
       if (!$enc) return $string;
       return '=?'.$encoding.'?q?'.$result.'?=';
}

I hope it helps ;)

?>
soletan at toxa dot de 20-Feb-2007 03:54
Be warned! The method below for encoding text does not work as requested by RFC1521!

Consider a line consisting of 75 'A' and a single é (or similar non-ASCII character) ... the method below would encode and return a line of 78 octets, breaking with RFC 1521, 5.1 Rule #5: "The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long."

Good QP-encoding takes a bit more than this.
legolas558 12-Feb-2007 10:32
Please note that in the below encode function there is a bug!

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<0x20))
?>

$c should be checked against less or equal to encode spaces!

so the correct code is

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<=0x20))
?>

Fix the code or post this note, please
MagicalTux at ookoo dot org 06-Feb-2007 03:44
I checked Thomas Pequet / Memotoo.com's quoted_printable_encode() function, and it's rather non-respective to standards...

Here's my own, fixed version :

<?php
function quoted_printable_encode($string, $linelen = 0, $linebreak="=\r\n", $breaklen = 0, $encodecrlf = false) {
        // Quoted printable encoding is rather simple.
        // Each character in the string $string should be encoded if:
        //  Character code is <0x20 (space)
        //  Character is = (as it has a special meaning: 0x3d)
        //  Character is over ASCII range (>=0x80)
        $len = strlen($string);
        $result = '';
        for($i=0;$i<$len;$i++) {
                if ($linelen >= 76) { // break lines over 76 characters, and put special QP linebreak
                        $linelen = $breaklen;
                        $result.= $linebreak;
                }
                $c = ord($string[$i]);
                if (($c==0x3d) || ($c>=0x80) || ($c<0x20)) { // in this case, we encode...
                        if ((($c==0x0A) || ($c==0x0D)) && (!$encodecrlf)) { // but not for linebreaks
                                $result.=chr($c);
                                $linelen = 0;
                                continue;
                        }
                        $result.='='.str_pad(strtoupper(dechex($c)), 2, '0');
                        $linelen += 3;
                        continue;
                }
                $result.=chr($c); // normal characters aren't encoded
                $linelen++;
        }
        return $result;
}

$test = 'This is a test !! héhéhé ....'."\r\n";
$test.= 'You can write really long pieces of text without having to worry about mail transfert. Quoted printable supports special way to handle such lines,  by instering an escaped linebreak. This linebreak, once converted back to 8bit, will disappear.';

echo quoted_printable_encode(utf8_encode($test))."\r\n";
?>

By default, the function encodes text to be used as a quoted-printable-encoded body, however by tweaking the parameters, you can get subject-header encoding and stuff like that.
Thomas Pequet / Memotoo.com 19-Oct-2006 06:15
If you want a function to do the reverse of "quoted_printable_decode()", follow the link you will find the "quoted_printable_encode()" function:
http://www.memotoo.com/softs/public/PHP/quoted printable_encode.inc.php

Compatible "ENCODING=QUOTED-PRINTABLE"
Example:
quoted_printable_encode(ut8_encode("c'est quand l'été ?"))
-> "c'est quand l'=C3=A9t=C3=A9 ?"
umu 06-Feb-2006 02:38
...deed.ztinmehc-ut.zrh@umuumu@hrz.tu-chemnitz.deed...

and write [^=]{0,2} in the last regular expression
to avoid the soft linebreak "=" being the 77th char in line,
see my imap_8bit() emulation at
http://www.php.net/manual/en/function.imap-8bit.php#61216
steffen dot weber at computerbase dot de 22-Jul-2005 02:08
As the two digit hexadecimal representation SHOULD be in uppercase you want to use "=%02X" (uppercase X) instead of "=%02x" as the first argument to sprintf().
bendi at interia dot pl 29-Mar-2005 01:08
This function appeared twice already and in both versions it's got error in rule replacing chunk_split, because it misses the last line in encoded text if it's shorter than 73 characters.

My solution (got rid of replace_callback)
<?
function quoted_printable_encode( $sString ) {
   /*instead of replace_callback i used <b>e</b> modifier for regex rule, which works as eval php function*/
   $sString = preg_replace( '/[^\x21-\x3C\x3E-\x7E\x09\x20]/e', 'sprintf( "=%02x", ord ( "$0" ) ) ;',  $sString );
   /*now added to this rule one or more chars which lets last line to be matched and included in results*/
   preg_match_all( '/.{1,73}([^=]{0,3})?/', $sString, $aMatch );
   return implode( '=' . CR, $aMatch[0] );
}

?>
dmitry at koterov dot ru 19-Feb-2005 05:26
Previous comment has a bug: encoding of short test does not work because of incorrect usage of preg_match_all(). Have somebody read it at all? :-)

Correct version (seems), with additional imap_8bit() function emulation:

if (!function_exists('imap_8bit')) {
 function imap_8bit($text) {
   return quoted_printable_encode($text);
 }
}

function quoted_printable_encode_character ( $matches ) {
   $character = $matches[0];
   return sprintf ( '=%02x', ord ( $character ) );
}

// based on http://www.freesoft.org/CIE/RFC/1521/6.htm
function quoted_printable_encode ( $string ) {
   // rule #2, #3 (leaves space and tab characters in tact)
   $string = preg_replace_callback (
     '/[^\x21-\x3C\x3E-\x7E\x09\x20]/',
     'quoted_printable_encode_character',
     $string
   );
   $newline = "=\r\n"; // '=' + CRLF (rule #4)
   // make sure the splitting of lines does not interfere with escaped characters
   // (chunk_split fails here)
   $string = preg_replace ( '/(.{73}[^=]{0,3})/', '$1'.$newline, $string);
   return $string;
}
drm at melp dot nl 09-Feb-2005 03:32
A easier, improved way of encoding for quoted-printable transfer:

------
function quoted_printable_encode_character ( $matches ) {
   $character = end ( $matches );
   return sprintf ( '=%02x', ord ( $character ) );
}

// based on http://www.freesoft.org/CIE/RFC/1521/6.htm
function quoted_printable_encode ( $string ) {
   // rule #2, #3 (leaves space and tab characters in tact)
   $string = preg_replace_callback (
      '/[^\x21-\x3C\x3E-\x7E\x09\x20]/',
      'quoted_printable_encode_character',
      $string
   );

   $newline = "=\r\n"; // '=' + CRLF (rule #4)

   // make sure the splitting of lines does not interfere with escaped characters
   // (chunk_split fails here)
   preg_match_all ( '/.{73}([^=]{0,3})/', $string, $match ); // Rule #1
   return implode ( $newline, $match[0] );
}
-----
tamas dot tompa at kirowski dot com 20-Feb-2004 07:46
i have found a bug in pob at medienrecht dot NOSPAM dot org
's qp_enc function. in quoted printable messages need to convert the first pont in the lines too...
here is the fixed code:

function qp_enc( $input = "", $line_max = 76, $space_conv = false ) {

    $hex = array('0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F');
    $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
    $eol = "\r\n";
    $escape = "=";
    $output = "";

        while( list(, $line) = each($lines) ) {
                //$line = rtrim($line); // remove trailing white
space -> no =20\r\n necessary
                $linlen = strlen($line);
                $newline = "";
                for($i = 0; $i < $linlen; $i++) {
                        $c = substr( $line, $i, 1 );
                        $dec = ord( $c );
                        if ( ( $i == 0 ) && ( $dec == 46 ) ) { //
convert first point in the line into =2E
                                $c = "=2E";
                        }
                        if ( $dec == 32 ) {
                                if ( $i == ( $linlen - 1 ) ) { // convert
 space at eol only
                                        $c = "=20";
                                } else if ( $space_conv ) {
                                        $c = "=20";
                                }
                        } elseif ( ($dec == 61) || ($dec < 32 ) ||
($dec > 126) ) { // always encode "\t", which is *not* required
                                $h2 = floor($dec/16);
                                $h1 = floor($dec%16);
                                $c = $escape.$hex["$h2"].$hex["$h1"];
                        }
                        if ( (strlen($newline) + strlen($c)) >=
$line_max ) { // CRLF is not counted
                                $output .= $newline.$escape.$eol; //
soft line break; " =\r\n" is okay
                                $newline = "";
                                // check if newline first character will
be point or not
                                if ( $dec == 46 ) {
                                        $c = "=2E";
                                }
                        }
                        $newline .= $c;
                } // end of for
                $output .= $newline.$eol;
        } // end of while
        return trim($output);
}
pob at medienrecht dot NOSPAM dot org 18-Jul-2001 01:06
If you do not have access to imap_* and do not want to use
�$message = chunk_split( base64_encode($message) );�
because you want to be able to read the �source� of your mails, you might want to try this:
(any suggestions very welcome!)

function qp_enc($input = "quoted-printable encoding test string", $line_max = 76) {

    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
    $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
    $eol = "\r\n";
    $escape = "=";
    $output = "";

    while( list(, $line) = each($lines) ) {
        //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
        $linlen = strlen($line);
        $newline = "";
        for($i = 0; $i < $linlen; $i++) {
            $c = substr($line, $i, 1);
            $dec = ord($c);
            if ( ($dec == 32) && ($i == ($linlen - 1)) ) { // convert space at eol only
                $c = "=20";
            } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
                $h2 = floor($dec/16); $h1 = floor($dec%16);
                $c = $escape.$hex["$h2"].$hex["$h1"];
            }
            if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
                $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
                $newline = "";
            }
            $newline .= $c;
        } // end of for
        $output .= $newline.$eol;
    }
    return trim($output);

}

$eight_bit = "\xA7 \xC4 \xD6 \xDC \xE4 \xF6 \xFC \xDF         =          xxx             yyy       zzz          \r\n"
            ." \xA7      \r \xC4 \n \xD6 \x09    ";
print $eight_bit."\r\n---------------\r\n";
$encoded = qp_enc($eight_bit);
print $encoded;
madmax at express dot ru 03-Aug-2000 05:41
Some  browser (netscape, for example)
send 8-bit quoted printable text like this:
=C5=DD=A3=D2=C1= =DA

"= =" means continuos word.
 php function not detect this situations and translate in string like:
 abcde=f
gustavf at spamstop dot com 07-Jul-2000 10:25
This function does not recognize lowercase letters as part of the Quoted Printable encoding. RFC 1521 specifies:

Uppercase letters must be used when sending hexadecimal data, though a robust implementation may choose to recognize lowercase letters on receipt.
printf
quoted_printable_encode
Обработка строк


Кодирует 8-битную строку в с помощью метода quoted-printable

quoted_printable_decode
quotemeta
Обработка строк
PHP Manual

quoted_printable_encode

(PHP 5 >= 5.3.0)

quoted_printable_encode — Кодирует 8-битную строку в с помощью метода quoted-printable

Описание

string quoted_printable_encode ( string $str )

Возвращает строку, закодированную в формат quoted-printable в соответствии с разделом 6.7 » RFC2045.

Эта функция подобна функции imap_8bit(), за исключением того что не требует для своей работы модуля IMAP.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает закодированную строку.

Смотрите также

  • quoted_printable_decode() - Преобразует строку, закодированную методом quoted-printable в 8-битовую строку
  • iconv_mime_encode() - Сжимает поле MIME-заголовка

User Contributed Notes

ericth at NOSPAM dot pennyworth dot com 07-Oct-2011 01:46
I have re-written the PHP 5.3.8 function for quoted_printable_encode into PHP for use with PHP < 5.3.  Tested with PHP 5.2.11.

<?php
define('PHP_QPRINT_MAXL', 75);

function php_quot_print_encode($str)
{
    $lp = 0;
    $ret = '';
    $hex = "0123456789ABCDEF";
    $length = strlen($str);
    $str_index = 0;

    while ($length--) {
        if ((($c = $str[$str_index++]) == "\015") && ($str[$str_index] == "\012") && $length > 0) {
            $ret .= "\015";
            $ret .= $str[$str_index++];
            $length--;
            $lp = 0;
        } else {
            if (ctype_cntrl($c)
                || (ord($c) == 0x7f)
                || (ord($c) & 0x80)
                || ($c == '=')
                || (($c == ' ') && ($str[$str_index] == "\015")))
            {
                if (($lp += 3) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 3;
                }
                $ret .= '=';
                $ret .= $hex[ord($c) >> 4];
                $ret .= $hex[ord($c) & 0xf];
            }
            else
            {
                if ((++$lp) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 1;
                }
                $ret .= $c;
            }
        }
    }

    return $ret;
}

?>
arnaudv6 15-Aug-2011 08:56
One will like to know and clearly read that RFC2045 specifies a line shall not exceed 75 characters.
Accordingly, quoted_printable_encode() splits line at this limit.
senacle 28-Jan-2011 06:24
If you need to encode the subject of your mail message, use as follow :

<?php
quoted_printable_encode($subject, 58, "subject");

    function quoted_printable_encode($input, $line_max = 75, $subject) {
        /**    The Quoted Printable encodes only with 75 characters per ligne.
        *    For encoding the subject of message, we must split the subject every 58 characters,
        *    because of adding =?iso-8859-1?Q? at the beginning and ?= at the end of each split.

            *    @param    string        $input            string to encode
            *    @param    int        $line_max            max number of char per ligne
            *    @param    string        $subject            specify if we encode a subject or any other string

            *    @access    public
            */
        $hex = array('0','1','2','3','4','5','6','7',
                            '8','9','A','B','C','D','E','F');
        $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
        $linebreak = "\r\n";
        /* the linebreak also counts as characters in the mime_qp_long_line
        * rule of spam-assassin */
        $line_max = $line_max - strlen($linebreak);
        $escape = "=";
        $output = "";
        $cur_conv_line = "";
        $length = 0;
        $whitespace_pos = 0;
        $addtl_chars = 0;

        // iterate lines
        for ($j=0; $j<count($lines); $j++) {
            $line = $lines[$j];
            $linlen = strlen($line);

            // iterate chars
            for ($i = 0; $i < $linlen; $i++) {
                $c = substr($line, $i, 1);
                $dec = ord($c);

                $length++;

                if ($dec == 32) {
                    // space occurring at end of line, need to encode
                    if (($i == ($linlen - 1))) {
                        $c = "=20";
                        $length += 2;
                    }

                    $addtl_chars = 0;
                    $whitespace_pos = $i;
                } else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
                    $h2 = floor($dec/16); $h1 = floor($dec%16);
                    $c = $escape . $hex["$h2"] . $hex["$h1"];
                    $length += 2;
                    $addtl_chars += 2;
                }

                // length for wordwrap exceeded, get a newline into the text
                if ($length >= $line_max) {
                    $cur_conv_line .= $c;

                    // read only up to the whitespace for the current line
                    $whitesp_diff = $i - $whitespace_pos + $addtl_chars;

                    /* the text after the whitespace will have to be read
                    * again ( + any additional characters that came into
                    * existence as a result of the encoding process after the whitespace)
                    *
                    * Also, do not start at 0, if there was *no* whitespace in
                    * the whole line */
                    if (($i + $addtl_chars) > $whitesp_diff) {
                        if ($subject == "subject") {
                            $output .= "=?ISO-8859-1?Q?".substr($cur_conv_line, 0,
                                    (strlen($cur_conv_line) - $whitesp_diff))."?=";
                        } else {
                            $output .= substr($cur_conv_line, 0,
                                    (strlen($cur_conv_line) - $whitesp_diff)).$linebreak;
                        }
                        $i = $i - $whitesp_diff + $addtl_chars;
                    } else {
                    /* emit continuation --mirabilos */
                        if ($subject == "subject") {
                            $output .= "=?ISO-8859-1?Q?".$cur_conv_line."?=";
                        } else {
                            $output .= $cur_conv_line. '=' . $linebreak;
                        }
                    }

                    $cur_conv_line = "";
                    $length = 0;
                    $whitespace_pos = 0;
                } else {
                // length for wordwrap not reached, continue reading
                    $cur_conv_line .= $c;
                }
            } // end of for

            $length = 0;
            $whitespace_pos = 0;
            if ($subject == "subject") {
                $output .= "=?ISO-8859-1?Q?".$cur_conv_line."?=";
            } else {
                $output .= $cur_conv_line;
                if ($j<=count($lines)-1) {
                    $output .= $linebreak;
                }
            }
            $cur_conv_line = "";

            } // end for

        return trim($output);
    } // end quoted_printable_encode
?>
Thorsten Glaser 24-Sep-2010 06:05
Two bugs:

1) your linebreak is wrong

                $linebreak = "\r\n";

2) continuation of lines with no whitespace is broken

                                        /*
                                         * the text after the whitespace will have to
                                         * be read again ( + any additional characters
                                         * that came into existence as a result of the
                                         * encoding process after the whitespace)
                                         *
                                         * Also, do not start at 0, if there was *no*
                                         * whitespace in the whole line
                                         */
                                        if (($i + $addtl_chars) > $whitesp_diff) {
                                                $output .= substr($cur_conv_line, 0,
                                                    (strlen($cur_conv_line) - $whitesp_diff)) .
                                                    $linebreak;
                                                $i = $i - $whitesp_diff + $addtl_chars;
                                        } else {
                                                /* emit continuation --mirabilos */
                                                $output .= $cur_conv_line .
                                                    '=' . $linebreak;
                                        }
tzangerl [dot] pdc {dot} kth dot se 09-Apr-2010 02:05
A function that QP-encodes an input string (written for PHP < 5.3) and
wordwraps it at the same time, in order to avoid classification according to the MIME QP LONG LINE rule of SpamAssassin.  Thanks for Matt Jeffers to point out errors in the below quoted_printable script!

<?php
function quoted_printable_encode($input, $line_max = 75) {
   $hex = array('0','1','2','3','4','5','6','7',
                          '8','9','A','B','C','D','E','F');
   $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
   $linebreak = "=0D=0A=\r\n";
   /* the linebreak also counts as characters in the mime_qp_long_line
    * rule of spam-assassin */
   $line_max = $line_max - strlen($linebreak);
   $escape = "=";
   $output = "";
   $cur_conv_line = "";
   $length = 0;
   $whitespace_pos = 0;
   $addtl_chars = 0;

   // iterate lines
   for ($j=0; $j<count($lines); $j++) {
     $line = $lines[$j];
     $linlen = strlen($line);

     // iterate chars
     for ($i = 0; $i < $linlen; $i++) {
       $c = substr($line, $i, 1);
       $dec = ord($c);

       $length++;

       if ($dec == 32) {
          // space occurring at end of line, need to encode
          if (($i == ($linlen - 1))) {
             $c = "=20";
             $length += 2;
          }

          $addtl_chars = 0;
          $whitespace_pos = $i;
       } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
          $h2 = floor($dec/16); $h1 = floor($dec%16);
          $c = $escape . $hex["$h2"] . $hex["$h1"];
          $length += 2;
          $addtl_chars += 2;
       }

       // length for wordwrap exceeded, get a newline into the text
       if ($length >= $line_max) {
         $cur_conv_line .= $c;

         // read only up to the whitespace for the current line
         $whitesp_diff = $i - $whitespace_pos + $addtl_chars;

        /* the text after the whitespace will have to be read
         * again ( + any additional characters that came into
         * existence as a result of the encoding process after the whitespace)
         *
         * Also, do not start at 0, if there was *no* whitespace in
         * the whole line */
         if (($i + $addtl_chars) > $whitesp_diff) {
            $output .= substr($cur_conv_line, 0, (strlen($cur_conv_line) -
                           $whitesp_diff)) . $linebreak;
            $i =  $i - $whitesp_diff + $addtl_chars;
          } else {
            $output .= $cur_conv_line . $linebreak;
          }

        $cur_conv_line = "";
        $length = 0;
        $whitespace_pos = 0;
      } else {
        // length for wordwrap not reached, continue reading
        $cur_conv_line .= $c;
      }
    } // end of for

    $length = 0;
    $whitespace_pos = 0;
    $output .= $cur_conv_line;
    $cur_conv_line = "";

    if ($j<=count($lines)-1) {
      $output .= $linebreak;
    }
  } // end for

  return trim($output);
} // end quoted_printable_encode
?>
quoted_printable_decode
quotemeta
Обработка строк


Экранирует специальные символы

quoted_printable_encode
rtrim
Обработка строк
PHP Manual

quotemeta

(PHP 4, PHP 5)

quotemeta — Экранирует специальные символы

Описание

string quotemeta ( string $str )

Возвращает модифицированную строку, в которой перед каждым символом из следующего списка:

. \ + * ? [ ^ ] ( $ )
вставлен обратный слэш (\).

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает экранированную строку, или FALSE, если в качестве параметра str была указана пустая строка.

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • addslashes() - Экранирует строку с помощью слэшей
  • addcslashes() - Экранирует cтроку слэшами в стиле языка C
  • htmlentities() - Преобразует все возможные символы в соответствующие HTML-сущности
  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • nl2br() - Вставляет HTML-код разрыва строки перед каждым переводом строки
  • stripslashes() - Удаляет экранирование символов
  • stripcslashes() - Удаляет экранирование символов, произведенное функцией addcslashes
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • preg_quote() - Экранирует символы в регулярных выражениях

User Contributed Notes

kumarkulandai at gmail dot com 26-Oct-2009 11:29
<?php
$str = "Hello world. (can you hear me?)";
echo quotemeta($str);
?>

The output of the code above will be:
Hello world\. \(can you hear me\?\)
George Adams 16-Feb-2006 08:57
Took me a while to realize this was NOT the command I wanted for escaping potentially harmful characters in a string that would be used as part of a system command.  Instead, I needed either escapeshellarg() (http://www.php.net/manual/en/function.escapeshellarg.php) or escapeshellcmd() (http://www.php.net/manual/en/function.escapeshellcmd.php)
15-May-2001 03:41
This function escapes characters that have special meaning in regular expressions.  preg_quote() <http://php.net/manual/en/function.preg-quote.php> has similar functionality, but is more powerful since it escapes more characters (including one user-specified character).
quoted_printable_encode
rtrim
Обработка строк


Удаляет пробелы (или другие символы) из конца строки

quotemeta
setlocale
Обработка строк
PHP Manual

rtrim

(PHP 4, PHP 5)

rtrim — Удаляет пробелы (или другие символы) из конца строки

Описание

string rtrim ( string $str [, string $charlist ] )

Эта функция возвращает строку str с удаленными из конца строки пробелами.

Если второй параметр не передан, rtrim() удаляет следующие символы:

  • " " (ASCII 32 (0x20)), обычный пробел.
  • "\t" (ASCII 9 (0x09)), символ табуляции.
  • "\n" (ASCII 10 (0x0A)), символ перевода строки.
  • "\r" (ASCII 13 (0x0D)), символ возврата каретки.
  • "\0" (ASCII 0 (0x00)), NUL-байт.
  • "\x0B" (ASCII 11 (0x0B)), вертикальная табуляция.

Список параметров

str

Входная строка.

charlist

С помощью параметра charlist можно также указать удаляемые символы. Просто перечислите все символы, которые вы хотите удалить. Можно указать конструкцию .. для обозначения диапазона символов.

Возвращаемые значения

Возвращает модифицированную строку.

Список изменений

Версия | Описание
4.1.0 | Добавлен параметр charlist.

Примеры

Пример #1 Пример использования rtrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// удаляем управляющие ASCII-символы с конца $binary
// (от 0 до 31 включительно)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?>

Результат выполнения данного примера:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "        These are a few words :) ..."
string(26) "        These are a few words :)"
string(9) "Hello Wor"
string(15) "    Example string"

Смотрите также

  • trim() - Удаляет пробелы (или другие символы) из начала и конца строки
  • ltrim() - Удаляет пробелы (или другие символы) из начала строки

User Contributed Notes

krzysiek dot 333 at gmail dot com 01-May-2012 09:58
function read_more($in,$len=160){
    if(strlen($in)>$len){
        return preg_replace('/[\s\.,][^\s\.,]*$/u', '', substr($in, 0, $len)).'...';
    }else{
        return $in;
    }
}

echo read_mode("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. Quisque semper justo at risus. Donec venenatis, turpis vel hendrerit interdum, dui ligula ultricies purus, sed posuere libero dui id orci.");
/* Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque...*/
NBS Studio 22-Feb-2010 05:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
info at nbs-studio dot com 22-Feb-2010 05:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
pinkgothic at gmail dot com 22-Jan-2010 05:36
I have an obsessive love for php's array functions given how extremely easy they've made complex string handling for me in various situations... so, have another string-rtrim() variant:

<?php

function strrtrim($message, $strip) {
    // break message apart by strip string
    $lines = explode($strip, $message);
    $last  = '';
    // pop off empty strings at the end
    do {
        $last = array_pop($lines);
    } while (empty($last) && (count($lines)));
    // re-assemble what remains
    return implode($strip, array_merge($lines, array($last)));
}

?>

Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee!
harmor 04-Apr-2008 03:05
I'm sure there's a better way to strip strings from the end of strings.

<?php
/**
 * Strip a string from the end of a string
 *
 * @param string $str      the input string
 * @param string $remove   OPTIONAL string to remove
 *
 * @return string the modified string
  */
function rstrtrim($str, $remove=null)
{
    $str    = (string)$str;
    $remove = (string)$remove;

    if(empty($remove))
    {
        return rtrim($str);
    }

    $len = strlen($remove);
    $offset = strlen($str)-$len;
    while($offset > 0 && $offset == strpos($str, $remove, $offset))
    {
        $str = substr($str, 0, $offset);
        $offset = strlen($str)-$len;
    }

    return rtrim($str);

} //End of function rstrtrim($str, $remove=null)

echo rstrtrim('Hello World!!!', '!')   .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!')  .'<br />'; //"Hello World!"
echo rstrtrim('Hello World!!!', '!!!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!!!').'<br />'; //"Hello World!!!"
?>
YAS 08-May-2006 06:01
To remove an unwanted character - example "." - if exist or not.

The example above doesn't include the case where there is no "."
If there is not "." at the example above the last word will be deleted.

Have fun with this code.

<?php
$text = "This string contains. some unwanted characters on the end .";
$text = trim($text);
$last = $text{strlen($text)-1};
if (!strcmp($last,"."))
{
  $text = rtrim($text, 'a..z');
  $text = rtrim($text, '.');
}
?>
gbelanger at exosecurity dot com 17-Feb-2006 02:31
True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim()

---

Here's a quick way to recursively trim every element of an array, useful after the file() function :

<?php
# Reads /etc/passwd file an trims newlines on each entry
$aFileContent = file("/etc/passwd");
foreach ($aFileContent as $sKey => $sValue) {
    $aFileContent[$sKey] = rtrim($sValue);
}

print_r($aFileContent);
?>
Unimagined at UnaimaginedDesigns dot Com 16-Jan-2005 12:49
I needed a way to trim all white space and then a few chosen strings from the end of a string.  So I wrote this class to reuse when stuff needs to be trimmed.

<?php

class cleaner {

function cleaner ($cuts,$pinfo) {
$ucut = "0";
$lcut = "0";
while ($cuts[$ucut]) {
$lcut++;
$ucut++;
}
$lcut = $lcut - 1;
$ucut = "0";
$rcut = "0";
$wiy = "start";

while ($wiy) {

if ($so) {
$ucut = "0";
$rcut = "0";
unset($so);
}

if (!$cuts[$ucut]) {
$so = "restart";
} else {
$pinfo = rtrim($pinfo);
$bpinfol = strlen($pinfo);
$tcut = $cuts[$ucut];
$pinfo = rtrim($pinfo,"$tcut");
$pinfol = strlen($pinfo);

    if ($bpinfol == $pinfol) {
    $rcut++;
    if ($rcut == $lcut) {
    unset($wiy);
    }
    $ucut++;
    } else {
    $so = "restart";
    }
}
}

$this->cleaner = $pinfo;
}

}

$pinfo = "Well... I'm really bored...<br /><br>&nbsp;    \n\t&nbsp;<br><br /><br>&nbsp;    \r\r&nbsp;<br>\r<br /><br>\r&nbsp;    &nbsp;\n<br>      <br />\t";

$cuts = array('\n','\r','\t',' ',' ','&nbsp;','<br />','<br>','<br/>');

$pinfo = new cleaner($cuts,$pinfo);
$pinfo = $pinfo->cleaner;

print $pinfo;

?>

That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string.  It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines.
todd at magnifisites dot com 19-Aug-2003 06:19
This shows how rtrim works when using the optional charlist parameter:
rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the "new" last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly "rtrimmed" string is returned.
<?php
  // Example 1:
  rtrim('This is a short short sentence', 'short sentence');
  // returns 'This is a'
  // If you were expecting the result to be 'This is a short ',
  // then you're wrong; the exact string, 'short sentence',
  // isn't matched.  Remember, character-by-character comparison!
  // Example 2:
  rtrim('This is a short short sentence', 'cents');
  // returns 'This is a short short '
?>
HW 05-Jun-2003 06:32
<?php
$text = "This string contains some unwanted characters on the end.";
$text1 = rtrim($text, 'a..z');
$text1 = rtrim($text1, '.');
echo $text1; // only the '.' is trimmed.
$text2 = rtrim($text, 'a..z.');
echo $text2; // The whole last word is trimmed.
?>
quotemeta
setlocale
Обработка строк


Устанавливает настройки локали

rtrim
sha1_file
Обработка строк
PHP Manual

setlocale

(PHP 4, PHP 5)

setlocale — Устанавливает настройки локали

Описание

string setlocale ( int $category , string $locale [, string $... ] )
string setlocale ( int $category , array $locale )

Устанавливает настройки локали.

Список параметров

category

Параметр category это именованная константа, определяющая категорию функций, на которые будет влиять установка локали:

  • LC_ALL - все нижеперечисленное
  • LC_COLLATE - функции сравнения строк, смотри strcoll()
  • LC_CTYPE - функции преобразования и классификации строк, например strtoupper()
  • LC_MONETARY - для функции localeconv()
  • LC_NUMERIC - задает символ десятичного разделения (см. также localeconv())
  • LC_TIME - форматирование даты/времени функцией strftime()
  • LC_MESSAGES для системынх сообщений (доступна если PHP был скомпилирован с поддержкой libintl)

locale

Если в качестве locale передана пустая строка "" или NULL, имена локалей будут взяты из одноименных переменных окружения или переменной с именем "LANG".

Если в качестве locale передан NULL или "0", локаль изменена не будет, а будет возвращено текущее значение.

Если в качестве locale передан массив, или после этого аргумента следуют дополнительные аргументы, функция будет использовать элементы массива или аргументы по порядку в качестве имен локали до тех пор, пока установка локали не будет успешной. Это удобно, если одна и та же локаль имеет разное имя в различных системах, или для создания запасного варианта при отсутствии какой-либо локали в системе.

...

(Необязательные аргументы в виде строк или массивов для установки настроек локали до первой успешной попытки.)

Замечание:

На Windows, setlocale(LC_ALL, '') устанавливает имена локалей из системных региональных/языковых настроек (доступных через Панель Управления).

Возвращаемые значения

Возвращает имя вновь установленной локали или FALSE если система не поддерживает установку локали, указанная локаль не существует или передано недопустимое имя категории.

Недопустимое имя категории также вызывает предупредение. Имена локалей и категорий описаны в » RFC 1766 и » ISO 639. Разные системы имеют различных схемы именования локалей.

Замечание:

Возвращаемое функцией setlocale() значение зависит от системы, на которой запущен PHP. Она возвращает точно то же значение, что и системная функция setlocale.

Список изменений

Версия | Описание
5.3.0 | Эта функция в настоящее время бросает уведомления E_DEPRECATED, если строка передается в параметре category вместо одной из констант LC_*.
4.3.0 | Доступна передача нескольких локалей.
4.2.0 | Передача category в виде строки больше не поддерживается, рекомендуется использовать перечисленные выше константы. Передача этих констант как строк (в кавычках) вызовет вывод предупреждения.

Примеры

Пример #1 Примеры использования setlocale()

<?php
/* Установка голландской локали */
setlocale(LC_ALL, 'nl_NL');

/* выводит: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* попытка использовать различные локали для  немецкого языка (с PHP 4.3.0) */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "На этой системе немецкая локаль имеет имя '$loc_de'";
?>

Пример #2 Примеры использования setlocale() в Windows

<?php
/* Установка голландской локали */
setlocale(LC_ALL, 'nld_nld');

/* выводит: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* попытка использовать различные локали для  немецкого языка (с PHP 4.3.0) */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Предпочитаемая немецкая локаль на этой системе: '$loc_de'";
?>

Примечания

Внимание

Информация о локали модифицируется во всем процессе, а не по каждому потоку отдельно. Если вы используете PHP на многопоточном сервере, таком как IIS или Apache под Windows, вы можете обнаружить неожиданные изменения в настройках локали во время выполнения скриптов, никогда и не вызывавших setlocale(). Это происходит из-за того, что другие скрипты, запущенные в параллельных потоках данного процесса, в то же самое время поменяли настройки локали для всего процесса с помощью setlocale().

Подсказка

Пользователи Windows найдут полезной информацию о значениях locale на сайте Microsoft MSDN. Поддерживаемые языки перечислены здесь: » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp, а значения стран/регионов здесь: » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp.

User Contributed Notes

qeremy 23-May-2012 11:20
Be careful when using this "demon" function, or it'll waste your time cos' of a hidden problem...

What?

If you use this function in a file that included to all project, and if you write functions like this getUID(), getMyImageSize, getIIIIII etc... then I think you have a problem at this point.

Let me explain;

the_master.php // included to all project and contains this line;

<?php
setlocale(LC_ALL, "tr_TR.UTF-8");

// and after many function defined in these lines, i.e.;

function getUID() {
   return (int) $_SESSION["user_id"];
}
?>
...
...

Let's call our function, but...
<?php
$user_id = getUID();
?>

Fatal error: Call to undefined function getUID() in /var/www/...

Yes, we screw up all project. :)

Actually, I don't know what is the exact problem here but I know the solution.

SOLUTION:

1. Do not use "I" (capital "i") character in any function name
or
2. Simply use setlocale like this;  setlocale(LC_TIME, "tr_TR.UTF-8") // I need just locale time config and used this

So, why not use capital i?

I tested a few function name like getUİD(). Yes, it works! (capital i in Türkish İ). But İ thİnk, many programmer have not thİs char İn theİr keyboards. :)

Additionally, if you use this char in any const name or var name (such as $UID = getuid();) also your var's and const's will be undefined...
Ludovico Grossi 17-Apr-2012 01:15
Please note that LC_NUMERIC (or LC_ALL) will convert the decimal separator every time you put it in a string, EVEN IF THE STRING IS A QUERY.
This is a problem for every locale that uses the comma as a decimal separator. Look at this example:

<?php
setlocale(LC_ALL, "it_IT"); // locale with comma for decimals
$decimal_number = 0.5;
$query = "SELECT * FROM Table WHERE decimal_field > ".(float)$decimal_number; // casting to float is useless, since the conversion to a string is done after
?>

Then, the query fill fail because it will be converted to:

SELECT * FROM Table WHERE decimal_field > 0,5
(note the comma!)

I suggest to be sure that LC_NUMERIC is set to a standard locale, then use other formatting functions to display formatted numbers when needed.

<?php
setlocale(LC_ALL, 'it_IT');
setlocale(LC_NUMERIC, 'en_US'); // let's overwrite the decimal separator
?>
russ at eatmymonkeydust dot com 08-Dec-2011 03:45
If you are looking for a getlocale() function simply pass 0 (zero) as the second parameter to setlocale().

Beware though if you use the category LC_ALL and some of the locales differ as a string containing all the locales is returned:

<?php
echo setlocale(LC_ALL, 0);

// LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;
// LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C

echo setlocale(LC_CTYPE, 0);

// en_US.UTF-8

setlocale(LC_ALL, "en_US.UTF-8");
echo setlocale(LC_ALL, 0);

// en_US.UTF-8

?>

If you are looking to store and reset the locales you could do something like this:

<?php

$originalLocales = explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, "nb_NO.utf8");

// Do something

foreach ($originalLocales as $localeSetting) {
  if (strpos($localeSetting, "=") !== false) {
    list ($category, $locale) = explode("=", $localeSetting);
  }
  else {
    $category = LC_ALL;
    $locale   = $localeSetting;
  }
  setlocale($category, $locale);
}

?>

The above works here (Ubuntu Linux) but as the setlocale() function is just wrapping the equivalent system calls, your mileage may vary on the result.
ts at websafe dot pl 09-Oct-2011 05:54
If Your linux box returns false on setlocale (so setlocale is not working as expected):

var_dump(setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8'));

make sure the glibc package is installed :-)
phcorp 26-Jul-2011 06:16
To find the locale of a Unix system:
<?php system('locale -a') ?>
flavioacvalverde at gmail dot com 15-Jun-2011 09:28
For Portugal I had to use

<?php setlocale(LC_ALL, 'Portuguese_Portugal.1252'); ?>

using php with IIS on Windows server.
tomas dot hampl at gmail dot com 23-Apr-2011 01:35
On Linux, setlocale() depends on the installed locales. To see which locales are available to PHP, run this from the terminal:

"locale -a"

Provided list are all locales that are available on your server for PHP to use. To add a new one, run

locale-gen <locale name> (this may need sudo / root permissions), for example to add a Czech locale, run something like this:

"sudo locale-gen cs_CZ.utf8"

Then you can use this locale declaration:

setlocale(LC_ALL, 'cs_CZ.utf8');
leif at neland dot dk 16-Aug-2010 04:38
Regarding dash'es in locale, it appears they should be omitted entirely.

In /etc/locale.gen I have

da_DK.ISO-8859-15 ISO-8859-15

but locale -a gives

da_DK.iso885915

which is the format setlocale()  wants.

(Debian)
garygendron at yahoo dot com 28-Jun-2010 08:04
For a php Mysql query, you could also use, for french canadian, in this example :

$query = 'SET lc_time_names = "fr_CA"';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT @@lc_time_names';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT id, created, YEAR(created) as year, MONTH(created) as month,' .
' CONCAT_WS(" ", MONTHNAME(created), YEAR(created)) as archive' .
' FROM #__TABLE as e' .
' GROUP BY archive' .
' ORDER BY id DESC';

Your data will be displayed in any locale setting you want. You may even $_GET[lc_time_name] from your multilanguage website.
Omer Sabic 21-Mar-2010 07:27
On Linux/Apache, when you install and try to use a new locale, the setlocale() function with the new locale will fail sometimes, but not always. To furthermore complicate, setlocale() will always complete with any of the previously installed locales. This would seem a really weird behaviour, which you can fix by restarting Apache, as Kari Sderholm aka Haprog mentioned, but I felt it needed to be properly pointed out.
Kari Sderholm aka Haprog 16-May-2009 04:28
It took me a while to figure out how to get a Finnish locale correctly set on Ubuntu Server with Apache2 and PHP5.

At first the output for "locale -a" was this:
C
en_US.utf8
POSIX

I had to install a finnish language pack with
"sudo apt-get install language-pack-fi-base"

Now the output for "locale -a" is:
C
en_US.utf8
fi_FI.utf8
POSIX

The last thing you need to do after installing the correct language pack is restart Apache with "sudo apache2ctl restart". The locale "fi_FI.utf8" can then be used in PHP5 after restarting Apache.

For setting Finnish timezone and locale in PHP use:
<?php
date_default_timezone_set('Europe/Helsinki');
setlocale(LC_ALL, array('fi_FI.UTF-8','fi_FI@euro','fi_FI','finnish'));
?>
wisborg 27-Apr-2009 05:06
It is correct as stated below that it is common that the UTF-8 should be used without the dash. However on some systems (e.g. MacOS 10.4) the dash is essential.
brice/axice/be 20-Feb-2009 05:19
Pay attention to the syntax.
- UTF8 without dash ('-')
- locale.codeset and not locale-codeset.

Stupid newbie error but worth knowing them when starting with gettext.

<?php
$codeset = "UTF8";  // warning ! not UTF-8 with dash '-'

// for windows compatibility (e.g. xampp) : theses 3 lines are useless for linux systems

putenv('LANG='.$lang.'.'.$codeset);
putenv('LANGUAGE='.$lang.'.'.$codeset);
bind_textdomain_codeset('mydomain', $codeset);

// set locale
bindtextdomain('mydomain', ABSPATH.'/locale/');
setlocale(LC_ALL, $lang.'.'.$codeset);
textdomain('mydomain');
?>

where directory structure of locale is (for example) :
locale/fr_FR/LC_MESSAGES/mydomain.mo
locale/en_US/LC_MESSAGES/mydomain.mo

and ABSPATH is the absolute path to the locale dir

further note, under linux systems, it seems to be necessary to create the locale at os level using 'locale-gen'.
bardouty at gmail dot com 06-Jan-2009 03:44
For Apache on Windows (wamp), or Linux RedHat (lampp):
if you expect the locale from the environment of PHP process instead of defining it by your code, you shall request the value of locale with setlocale and a null value.
On windows it is defined in system, not as an env variable, so you cannot see it with getenv(), but the behavior is the same : print with a decimal number with "," if requesting the locale, with "." otherwise.

This is different from the red warning above about locale set by another thread.
It seems that unless you request the setlocale, the locale conv array is not set with the environment. As a result the formatting of numbers is not following the locale in environment.

<?php
print getenv("LANG");
print $_ENV['LANG'];
print "calling localeconv() directly\n";
print_r(localeconv());
printf("%f",-123.456);
print "\ncalling setlocale() before localeconv()\n";
print(setlocale(LC_ALL,null));
print_r(localeconv());
printf("%f",-123.456);
?>
calling localeconv() directly
Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] =>
    [currency_symbol] =>
    [mon_decimal_point] =>
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] =>
    [int_frac_digits] => 127
    [frac_digits] => 127
    [p_cs_precedes] => 127
    [p_sep_by_space] => 127
    [n_cs_precedes] => 127
    [n_sep_by_space] => 127
    [p_sign_posn] => 127
    [n_sign_posn] => 127
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
        )

)
-123.456000
calling setlocale() before localeconv()
French_France.1252
Array
(
    [decimal_point] => ,
    [thousands_sep] =>
    [int_curr_symbol] => EUR
    [currency_symbol] => €
    [mon_decimal_point] => ,
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] => -
    [int_frac_digits] => 2
    [frac_digits] => 2
    [p_cs_precedes] => 0
    [p_sep_by_space] => 1
    [n_cs_precedes] => 0
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 1
    [grouping] => Array
        (
            [0] => 3
        )

    [mon_grouping] => Array
        (
            [0] => 3
        )

)
-123,456000
Un_passant 16-Nov-2008 03:56
For debian/ubuntu, don't forget the charset UFT8.

// Works on Ubuntu 8.04 Server
setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
benny at bennyborn dot de 09-Oct-2008 04:24
I had the problem (Debian), that the language de_DE was installed, but setlocale always returned false. I installed the language AFTER compiling PHP - that was the point. If you add some languages afterwards, you have to recompile php ;)
Charlo Dante 07-Oct-2008 02:23
Edwin Martin wrote already a note for Debian users, but it didn't work for me.

What DID work was this:

apt-get install locales-all

which installs more than the same apt-get without the '-all'

With 'locales-all' I got all languages running well.
Leigh Morresi 01-Oct-2008 11:27
Setting locale that is not supported by your system will result in some string operations returning a question mark "?" in your strings where it needs to perform transliteration.

1) Always check the return of setlocale() to ensure it has set to something supported

2) on Linux you can use the "locale -a" command to find a list of supported locales
alvaro at demogracia dot com 22-Sep-2008 09:33
A generalization for mk (26-Jan-2004) and totu (09-Sep-2002). The issue is not restricted to MySQL. For instance, when PHP needs to cast a floating point variable to string, it obeys the LC_NUMERIC settings:

<?php

$foo = 29.95;

echo "Locale: " . setlocale(LC_NUMERIC, 0) . "\n";
echo "Foo: $foo\n";

setlocale(LC_NUMERIC, 'Spanish_Spain.28605');
echo "Locale: " . setlocale(LC_NUMERIC, 0) . "\n";
echo "Foo: $foo\n";

?>

Under Windows, this code prints:

Locale: C
Foo: 29.95
Locale: Spanish_Spain.28605
Foo: 29,95
buana95 at yahoo dot com 21-Aug-2008 10:30
This will works for Indonesian on all platform (Windows, Linux and others Nix server):

<?php
echo '<pre>' . "\n";

//Add english as default (if all Indonesian not available)

setlocale(LC_ALL, 'id_ID.UTF8', 'id_ID.UTF-8', 'id_ID.8859-1', 'id_ID', 'IND.UTF8', 'IND.UTF-8', 'IND.8859-1', 'IND', 'Indonesian.UTF8', 'Indonesian.UTF-8', 'Indonesian.8859-1', 'Indonesian', 'Indonesia', 'id', 'ID', 'en_US.UTF8', 'en_US.UTF-8', 'en_US.8859-1', 'en_US', 'American', 'ENG', 'English');

//will output something like: Minggu, 17 Agustus 2008
echo strftime("%A, %d %B %Y") . "\n";

echo '</pre>' . "\n";
?>
Arjon 27-Jul-2008 09:12
Please take heed and read the warning above if you are running on a XAMPP or any other Windows apache server! It just took me far too long to figure this out; and all the while there was a warning right on the page.

If you're experiencing shifting locale settings (check with setlocale(LC_ALL,0), returning the current locale stuff) and you're running a windows server, then it's not just you! Again, I urge everyone to read the red, but oh so easy not to read, warning message on this page.
michal dot kocarek at brainbox dot cz 27-Jul-2008 08:33
Note about using UTF-8 locale charset on Windows systems:

According to MSDN, Windows setlocale()'s implementation does not support UTF-8 encoding.

Citation from "MSDN setlocale, _wsetlocale" page (http://msdn.microsoft.com/en-us/library/x99tb11d.aspx):
The set of available languages, country/region codes, and code pages includes all those supported by the Win32 NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8. If you provide a code page like UTF-7 or UTF-8, setlocale will fail, returning NULL.

So basically, code like
<?php setlocale(LC_ALL, 'Czech_Czech Republic.65001'); // 65001 is UTF-8 codepage ?>
does not work on Windows at all.

(written in time of PHP 5.2.4)
de ronino at kde (reverse it) 25-Jun-2008 02:43
I experienced the behavior stated in the above Warning box: Running PHP5 on a multithreaded Apache made the current locale change sometimes all of a sudden within a script, so strftime() output wasn't in the required format.

I recompiled Apache with the prefork MPM and now it works like a charm. Took me a long time to find out the reason as I overlooked the warning box searching for either a bug report or a programming error of mine...
jonas at jonashaag dot de 27-May-2008 12:11
On Ubuntu, you have to take p.e. "de_DE.utf8", all available languages you can get with:
    locale -a
Georg 04-Apr-2008 01:31
To set locale to 'de_DE' on my Debian 4 machine I had to:
- uncomment 'de_DE' in file /etc/locale.gen and afterwards
- run locale-gen from the shell
bryn AT lunarvis DOT com 21-Jan-2008 05:04
Posting this in the hope it might be useful to others, as I could find very little info anywhere. If you want to use a Welsh locale and have the suitable language support installed, you pass 'cym' (abbreviated form of Cymraeg) to setlocale:

<?php
setlocale(LC_TIME, 'cym');
$welsh= gmstrftime("%A, %B %Y - %H:%M",time());
echo $welsh;
?>

The above certainly applies to Windows systems, but should also apply to Unix if the required support is installed.

Cheers,

Bryn.
ostapk 27-Dec-2007 02:39
There is a new PECL extension under development called intl (it will be available in PHP5.3). Meanwhile all who rely on the setlocale() and friends should be aware about the limitations of them as covered in this post on the onPHP5.com blog: http://www.onphp5.com/article/22
Periklis 13-Sep-2007 02:33
In *some* Windows systems, setting LC_TIME only will not work, you must either set LC_ALL or both LC_CTYPE and LC_TIME. BUT if you have already set LC_TIME using setlocale earlier in the script, dates will not be affected! For example:
<?php
setlocale(LC_TIME, 'greek');
setlocale(LC_CTYPE, 'greek');
?>
will not work, while
<?php
setlocale(LC_CTYPE, 'greek');
setlocale(LC_TIME, 'greek');
?>
will do the job.
mvanbaak 09-May-2007 05:03
To complement Sven K's tip about debian:

You can also install the package locales-all
That one holds all the locales there are in compiled form.
szepeshazi at gmail dot com 18-Feb-2007 07:11
For those of you who are unfortunate enough (like me) to work in Windows environment, and try to set the locale to a language _and_ to UTF-8 charset, and were unable to do it, here is a workaround.

For example to output the date in hungarian with UTF-8 charset, this will work:

    $dateString = "%B %d., %A";
    setlocale(LC_ALL,'hungarian');
    $res=strftime($dateString);
    echo(iconv('ISO-8859-1', 'UTF-8', $res));

If anybody knows how to set the locale on Windows to the equivalent of "hu_HU.UTF-8" on unix, please do tell me.
lifeless 20-Nov-2006 09:40
if your server is an ubuntu (debian like)
you need to install the locales you want (default is english and your language) go to aptitude and install -language-pack-*-base it will resolve dependencies and will try to install a suggested package, remove it if you don't care and proceed.
Clayton Smith 26-Sep-2006 11:15
If you already have all the locales installed and "locale -a" is only showing a few languages, then edit /etc/locale.gen and add a line, e.g., es_MX ISO-8859-1.  After you add the line, run the command locale-gen for it to generate the locales based on those settings.
Sven K 07-Jun-2006 03:08
If your system doesn't show any installed locales by "locale -a", try installing them by "dpkg-reconfigure locales" (on debian).
08-Mar-2006 12:17
The example from bruno dot cenou at revues dot org below shows the possibility, but I want to spell it out: you can add charset info to setlocale.

Example:

Into my utf-8-encoded page I want to insert the name of the current month, which happens to be March, in German "März" - with umlaut. If you use

   setlocale(LC_TIME, 'de_DE');
   echo strftime("%B");

this will return "M&auml;rz", but that html-entity will look like this on a utf-8 page: "M?rz". Not what I want.

But if you use

   setlocale(LC_TIME, 'de_DE.UTF8');  // note the charset info !
   echo strftime("%B");

this returns "M√§rz", which, on utf-8, looks like it should: "März".
bruno dot cenou at revues dot org 20-Feb-2006 06:31
A little function to test available locales on a sytem :

<?php
function list_system_locales(){
    ob_start();
    system('locale -a');
    $str = ob_get_contents();
    ob_end_clean();
    return split("\\n", trim($str));
}

$locale = "fr_FR.UTF8";
$locales = list_system_locales();

if(in_array($locale, $locales)){
        echo "yes yes yes....";
}else{
        echo "no no no.......";
}

?>
Edwin Martin 20-Feb-2006 04:29
Debian users: Addition to Gabor Deri's note: if setlocale doesn't work in your locale and you're on Debian, and Gabor Deri's note doesn't work, you have to install the locales package.

As root, type: "apt-get install locales" and it will be installed.
glenn at europlan dot no 29-Nov-2005 11:55
In most Unix/Linux system, you could use:

locale -a

This will list all available locales on the server.
birkholz at web dot de 14-Aug-2005 08:42
When i tried to get the current locale (e.g. after i set the lang to german with setlocale(LC_ALL, 'de_DE'); ), the following did not work on my suse linux 9.0-box:
$currentLocale = setlocale(LC_ALL, NULL);
This code did a reset to the server-setting.

$currentLocale = setlocale(LC_ALL, 0); works perfectly for me, but the manual says NULL and 0 are equal in this case, but NULL seems to act like "".
pigmeu at pigmeu dot net 18-Oct-2004 01:42
!!WARNING!!

The "locale" always depend on the server configuration.

i.e.:
When trying to use "pt_BR" on some servers you will ALWAYS get false. Even with other languages.

The locale string need to be supported by the server. Sometimes there are diferents charsets for a language, like "pt_BR.utf-8" and "pt_BR.iso-8859-1", but there is no support for a _standard_ "pt_BR".

This problem occours in Windows platform too. Here you need to call "portuguese" or "spanish" or "german" or...

Maybe the only way to try to get success calling the function setlocale() is:
setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese", ...);

But NEVER trust on that when making functions like date conversions or number formating. The best way to make sure you are doing the right thing, is using the default "en_US" or "en_UK", by not calling the setlocale() function. Or, make sure that your server support the lang you want to use, with some tests.

Remember that: Using the default locale setings is the best way to "talk" with other applications, like dbs or rpc servers, too.

[]s

Pigmeu
dv at josheli dot com 12-Aug-2004 04:04
On Novell Netware, the language codes require hyphens, not underscores, and using anything other than LC_ALL doesn't work directly.

So... (from their support list)....

You have to set TIME, NUMERIC etc. info in two steps as given below rather than one. This is due to the limitation of setlocale function of LibC.
<?php
   setlocale(LC_ALL, 'es-ES');
   $loc = setlocale(LC_TIME, NULL);
   echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
  // jeuves 22 diciembre 1978
?>
This should work.

or of course, reset LC_ALL...
<?php
setlocale(LC_ALL, 'es-ES');
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
setlocale(LC_ALL, '');
// jeuves 22 diciembre 1978
?>
bogdan at iHost dot ro 02-Mar-2004 02:53
On some systems (at least FreeBSD 4.x) the format for a `locale' is, for example, ro_RO.ISO8859-2. If you use ro_RO instead setlocale will return FALSE. Just browse in /usr/share/locale and see what is the name of the directory holding your `locale' and use that name in your scripts:

<?php
  clearstatcache();
  $pos = strrpos ($_SERVER["PHP_SELF"], "/");
  $fisier = substr ($_SERVER["PHP_SELF"], $pos + 1);
  $result = filemtime ($fisier);
  $local = setlocale (LC_TIME, 'ro_RO.ISO8859-2');
  if ($local == "ro_RO.ISO8859-2") {
    $modtime = strftime '%e&nbsp;%B&nbsp;%Y&nbsp;%H:%M', $result);
  } else {
    $modtime = strftime ('%d.%m.%Y&nbsp;%H:%M', $result);
  }
  printf ("Ultima&nbsp;actualizare: %s\\n", $modtime);
?>
mk at totu dot com 26-Jan-2004 04:59
Be carefull - setting a locale which uses commas instead of dots in numbers may cause a mysql db not to understand the query:
<?php
setlocale(LC_ALL,"pl");
$price = 1234 / 100; // now the price looks like 12,34
$query = mysql_query("SELECT Id FROM table WHERE price='".$price."'");
?>
Even if there is a price 12.34 - nothing will be found
r dot nospam dot velseboer at quicknet dot nospam dot nl 08-Sep-2002 07:02
be careful with the LC_ALL setting, as it may introduce some unwanted conversions. For example, I used

setlocale (LC_ALL, "Dutch");

to get my weekdays in dutch on the page. From that moment on (as I found out many hours later) my floating point values from MYSQL where interpreted as integers because the Dutch locale wants a comma (,) instead of a point (.) before the decimals. I tried printf, number_format, floatval.... all to no avail. 1.50 was always printed as 1.00 :(

When I set my locale to :

 setlocale (LC_TIME, "Dutch");

my weekdays are good now and my floating point values too.

I hope I can save some people the trouble of figuring this out by themselves.

Rob
jorg-spamm at omnimedia dot no 03-Jul-2002 11:23
I needed to compile and install some extra locales to get this to work on RH7.3. Probably just me not doing a proper installation, but this is what it took to fix it:

localedef -ci no_NO -f ISO_8859-1 no_NO
elindset at hoved dot net 12-May-2002 02:59
In FreeBSD I had to use no_NO.ISO8859-1 instead of just no_NO..

<?PHP
    setlocale (LC_ALL, 'no_NO.ISO8859-1');
    echo strftime ("%A %e %B %Y", time());
?>
misc dot anders at feder dot dk 19-Jun-2001 06:13
Under FreeBSD, locale definitions are stored in the /usr/share/locale/ directory. Danish time formats and weekdays, for instance, are stored in /usr/share/locale/da_DK.ISO_8859-1/LC_TIME.
noog at libero dot it 23-Nov-2000 03:13
On windows:
Control Panel->International Settings
You can set your locale and customize it
And locale-related PHP functions work perfectly
Morgan Christiansson &lt;mog at linux dot nu&gt; 29-Mar-2000 12:56
check /usr/share/locale/ if you want more info about the locale available with your *NIX box

there is also a file called /usr/share/locale/locale.alias with a list of aliases
such as swedish for sv_SE

so on all boxes i have accounts on (rh 6.0 and slack 3.4) you can just use setlocale("LC_ALL","swedish"); or other prefered language in plain english.

However, the weekdays were in all lowercase :(

Note: export LC_ALL=swedish made a lot of programs swedish for me, it's also possible to make them russian or japanese :)
Lucas Thompson <lucas at slf dot cx> 31-Jan-2000 02:57
The Open Group has an excellent document available on the setlocale() library function, most of which applies to the PHP function of the same name.

http://www.opengroup.org/onlinepubs/7908799/xbd/locale.html

WARNING: This document might be a little too complex for people who came from HTML to PHP.

If you migrated from the world of C programming you'll be a locale master after reading this document.
rtrim
sha1_file
Обработка строк


Возвращает SHA1-хэш файла

setlocale
sha1
Обработка строк
PHP Manual

sha1_file

(PHP 4 >= 4.3.0, PHP 5)

sha1_file — Возвращает SHA1-хэш файла

Описание

string sha1_file ( string $filename [, bool $raw_output = false ] )

Вычисляет SHA1-хэш файла, имя которого задано аргументом filename, используя алгоритм » US Secure Hash Algorithm 1 и возвращает этот хэш.

Список параметров

filename

Имя хэшируемого файла.

raw_output

Если установлен в TRUE, возвращает 20-символьный хэш в бинарном формате.

Возвращаемые значения

Возвращает строку в случае успеха, иначе возвращается FALSE.

Примеры

Пример #1 Пример использования sha1_file()

<?php
foreach(glob('/home/Kalle/myproject/*.php') as $ent)
{
    if(is_dir($ent))
    {
        continue;
    }

    echo $ent . ' (SHA1: ' . sha1_file($ent) . ')', PHP_EOL;
}
?>

Список изменений

Версия | Описание
5.1.0 | Функция теперь работает с потоковым API. Это означает, что ее можно использовать с обертками, например, sha1_file('http://example.com/..')
5.0.0 | Добавлен параметр raw_output

Смотрите также

  • sha1() - Возвращает SHA1-хэш строки
  • md5_file() - Возвращает MD5-хэш файла
  • crc32() - Вычисляет полином CRC32 для строки

User Contributed Notes

xijque at gmail dot com 05-Jul-2011 07:13
Just for the record -

As some have pointed out, you have two ways to generate the hash of a file:
Method 1 [this function]: sha1_file($file)
Method 2: sha1(file_get_contents($file))

It's important to realize that these two methods are NOT the same thing. If they were, I seriously doubt this function would exist.

The key difference, as far as I can tell, is how the file's contents are loaded. The second method loads the entirety of $file into memory before passing it to sha1($str). Method two, however, loads the contents of $file as they are needed to create the hash.

If you can guarantee that you'll only ever have to hash relatively small files, this difference means very little. If you have larger ones, though, loading the entirety of file into memory is a bad idea: best case, you slow down your server as it tries to handle the request; worse case, you run out of memory and don't get your hash at all.

Just try to keep this in mind if you decide to load the file's contents yourself, in lieu of using this function. On my system, I was able to use this function to generate the hash of a 2.6GB file in 22 seconds, whereas I could not with the second method, due to an out-of-memory error (which took 185 seconds).
Goodlookinguy at NRG&#39;s RPG dot com 25-Nov-2008 07:01
In php 5.1.2 and above, the alternative to using this could be this little bit I wrote.  It can be used for other hashes as well.

<?php
/*        $by   : Nicholas
        $date : 11/25/08
        $site : http://nrgsrpg.com
    $copyright: This can be redistributed at will.
*///    $des  : For Hashing Files in all sorts of ways
class hashing {
    public static function filehash($file,$hash) {
        if (file_exists($file)) {
            return hash($hash,file_get_contents($file));
        }
        else {
            return "Error Occurred: File Does Not Exist";
        }
    }
}

echo hashing::filehash("index.php","sha1")."<br />";
echo hashing::filehash("index.php","whirlpool")."<br />";
echo hashing::filehash("index.php","sha512");
?>

Have fun!
vista_ at live dot se 23-Nov-2008 04:05
<?php
     if(!function_exists('sha1_file'))
     {
          function sha1_file($file = null)
          {
               if(is_null($file) || !file_exists($file))
               {
                    return trigger_error('File is null or does not exists');
               }

               return sha1(file_get_contents($file));
          }
     }
?>

Remember, it's important to write a corret url like this:
/home/snackzon/public_html/php/sha1.php
schiros at invisihosting dot com 06-Sep-2007 07:02
If you've got a script that allows user file upload, and you want to prevent multiple uploads of the same file:

    <?
        session_start();
        $isDuplicate = false;
        if(isset($_FILES["filename"]["tmp_name"]) && file_exists($_FILES["filename"]["tmp_name"])) {
            $fileHash = sha1_file($_FILES["filename"]["tmp_name"]);
            if(!isset($_SESSION["check_filelist"])) {
                $_SESSION["check_filelist"] = array($fileHash);
            }
            elseif(in_array($fileHash,$_SESSION["check_filelist"])) {
                $isDuplicate = true;
            }
            else {
                $_SESSION["check_filelist"][] = $fileHash;
            }

            if($isDuplicate) {
                echo "You've already uploaded that file";
            }
            else{
                // do some stuff
            }
        }

    ?>
admin at cmsrevolution dot com 04-Aug-2006 08:02
checking the sha1 of the file. ideal for download scripts making sure the file the user is downloading is not currupt
by checking the sha1 key

<?php
$filename = './Path/To/Your/File.zip';

if (file_exists($filename)) {
echo"i see the file";
} else {
echo "recheck the link file maybe broken";
}
$file = sha1_file('./Path/To/Your/File.zip');

echo"<br>is file hash valid?";
echo"hash = add the hash here<br>";
echo"hash of file :";
print($file);
?>
gubatron at gmail dot com 10-Feb-2006 07:02
P2P programs like LimeWire utilize sha1 to identify files. However they do it in base32. Here's an utility class if you want to write a Gnutella client in PHP5

/**
Utility base32 SHA1 class for PHP5
Copyright (C) 2006  Karl Magdsick (original author for Python)
                    Angel Leon (ported to PHP5)
                    Lime Wire LLC

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
class SHA1 {
  static $BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

  /** Given a file it creates a magnetmix */
  static function fileSHA1($file) {
    $raw = sha1_file($file,true);
    return SHA1::base32encode($raw);
  } //fileSHA1

  /** Takes raw input and converts it to base32 */
  static function base32encode($input) {
    $output = '';
    $position = 0;
    $storedData = 0;
    $storedBitCount = 0;
    $index = 0;

    while ($index < strlen($input)) {
      $storedData <<= 8;
      $storedData += ord($input[$index]);
      $storedBitCount += 8;
      $index += 1;

      //take as much data as possible out of storedData
      while ($storedBitCount >= 5) {
        $storedBitCount -= 5;
        $output .= SHA1::$BASE32_ALPHABET[$storedData >> $storedBitCount];
        $storedData &= ((1 << $storedBitCount) - 1);
      }
    } //while

    //deal with leftover data
    if ($storedBitCount > 0) {
      $storedData <<= (5-$storedBitCount);
      $output .= SHA1::$BASE32_ALPHABET[$storedData];
    }

    return $output;
  } //base32encode

}
setlocale
sha1
Обработка строк


Возвращает SHA1-хэш строки

sha1_file
similar_text
Обработка строк
PHP Manual

sha1

(PHP 4 >= 4.3.0, PHP 5)

sha1 — Возвращает SHA1-хэш строки

Описание

string sha1 ( string $str [, bool $raw_output = false ] )

Возвращает SHA1-хэш строки str, вычисленный по алгоритму » US Secure Hash Algorithm 1.

Список параметров

str

Входная строка.

raw_output

Если необязательный аргумент raw_output имеет значение TRUE, хэш возвращается в виде бинарной строки из 20 символов, иначе он будет возвращен в виде 40-символьного шестнадцатеричного числа.

Возвращаемые значения

Возвращает SHA1-хэш в виде строки.

Список изменений

Версия | Описание
5.0.0 | Добавлен параметр raw_output.

Примеры

Пример #1 Пример использования sha1()

<?php
$str = 'яблоко';

if (sha1($str) === '88b184adea10bf987b15257a5d6c5cb94eba69d3') {
    echo "Желаете зеленое или красное яблоко?";
}
?>

Примечания

Замечание: Безопасное хэширование паролей

В связи с быстрой природой хэширующего алгоритма не рекомендуется использовать эту функцию для обеспечения безопасности паролей. Подробнее об этом можно прочитать здесь.

Смотрите также

  • sha1_file() - Возвращает SHA1-хэш файла
  • crc32() - Вычисляет полином CRC32 для строки
  • md5() - Возвращает MD5-хэш строки
  • hash() - Генерирует хеш-код (дайджест сообщения)

User Contributed Notes

? 02-Jun-2011 05:05
SSHA LDAP password generation algorithm for standard PHP > 5.0

public function hashSSHA($password)
    {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 4);
        $hash = base64_encode( sha1($password . $salt, true) . $salt );
        return $hash;
    }
?>
mgcummings at yahoo dot com 21-Mar-2011 12:46
Thought I might save someone else some time trying to figure out how to generate a hash like MySQL5 PASSWORD() makes using just PHP.

$hash = '*' . sha1(sha1($pass), TRUE));
rich dot sage at gmail dot com 25-Nov-2010 12:59
If you're using Dovecot for mail retrieval and you want to generate SHA1 passwords yourself, you'll need to set the raw_output value to true, then base64_encode the output:

<?php
function makeDovecotPassword($input)
{
  return '{SHA}' . base64_encode(sha1($input, true));
}
?>
Anonymous 24-Apr-2010 06:03
I have created simple functions that allow you to create tokens that expire within a certain amount of time.

Call generateTimedHash with your data to encode and a salt:

<?php
$token = generateTimedHash("This is data.", "SALTY");
?>

Now you can call verifyTimedHash, with your token, data, salt, and lifetime of the token. The function will return true if the token is correct and within the lifetime of the token. It will return false if the token is incorrect and/or the token has expired. To verify a token that expires 30 seconds after it is created, use this:

<?php
$valid = verifyTimedHash($token, "This is data.", "SALTY", 30);
?>

The functions:

<?php
function generateTimedHash($data, $salt)
{
    // Salt the token with a defined salt and the time
    return sha1($data . $salt . time());
}

function verifyTimedHash($token, $data, $salt, $life)
{
    // Get the current time
    $time = time();

    // Verify hash with current time
    if ($token == sha1($data . $salt . $time))
        return true;

    // If that didn't work, try verifiying it, each time subtracting 1 from $time, $life times
    for ($offset = 1; $offset <= $life; $offset++)
        if ($token == sha1($data . $salt . ($time - $offset)))
            return true;

    return false;
}
?>
Anonymous 28-Oct-2009 05:48
Another solution to the salted hash with salt included directly in the hash, while keeping the same length of the result. If you want to generate a hash, call the function without the second argument. If you want to check a password against a hash, use the hash as the second argument. In this case, the function returns the hash itself on success, or boolean false on failure. You can also specify a hash algorithm as the third argument (otherwise SHA-1 will be used).

<?php
function __hash($password, $obscured = NULL, $algorithm = "sha1")
{
  // whether to use user specified algorithm
  $mode = in_array($algorithm, hash_algos());
  // generate random salt
  $salt = uniqid(mt_rand(), true);
  // hash it
  $salt = $mode ? hash($algorithm, $salt) : sha1($salt);
  // get the length
  $slen = strlen($salt);
  // compute the actual length of salt we will use
  // 1/8 to 1/4 of the hash, with shorter passwords producing longer salts
  $slen = max($slen >> 3, ($slen >> 2) - strlen($password));
  // if we are checking password against a hash, harvest the actual salt from it, otherwise just cut the salt we already have to the proper size
  $salt = $obscured ? __harvest($obscured, $slen, $password) : substr($salt, 0, $slen);
  // hash the password - this is maybe unnecessary
  $hash = $mode ? hash($algorithm, $password) : sha1($password);
  // place the salt in it
  $hash = __scramble($hash, $salt, $password);
  // and hash it again
  $hash = $mode ? hash($algorithm, $hash) : sha1($hash);
  // cut the result so we can add salt and maintain the same length
  $hash = substr($hash, $slen);
  // ... do that
  $hash = __scramble($hash, $salt, $password);
  // and return the result
  return $obscured && $obscured !== $hash ? false : $hash;
}
?>

It uses a random, variable length salt, depending on the length of the password. The functions __scramble() and __harvest() are used to place salt into the hash or pull it out respectively. You can write your own, and of course the strength of the result greatly depends on them. They can be relatively simple yet still quite secure:

<?php
function __scramble($hash, $salt, $password)
{
  return substr($hash, 0, strlen($password)) . $salt . substr($hash, strlen($password));
}

function __harvest($obscured, $slen, $password)
{
  return substr($obscured, min(strlen($password), strlen($obscured) - $slen), $slen);
}
?>

Or they can be ridiculously complicated (my favourite kind):

<?php
function __scramble($hash, $salt, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = ""; $m = 0;
  for ($i = 0; $i < strlen($salt); $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % (strlen($hash) + strlen($salt));
    while (array_key_exists($j, $index))
      $j = ++$j % (strlen($hash) + strlen($salt));
    $index[$j] = $i;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < strlen($hash) + strlen($salt); $i++)
    $out .= array_key_exists($i, $index) ? $salt[$index[$i]] : $hash[$m++];
  return $out;
}

function __harvest($obscured, $slen, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = "";
  for ($i = 0; $i < $slen; $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % strlen($obscured);
    while (in_array($j, $index))
      $j = ++$j % strlen($obscured);
    $index[$i] = $j;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < $slen; $i++)
    $out .= $obscured[$index[$i]];
  return $out;
}
?>
paul 15-Apr-2009 06:57
I believe this offers best amount of protection using a random salt, that has to be stored so it can be used later for verification.

If no salt is given (which can be retrieved by halving the output and taking the first half), then it will generate a random salt, hash it, place it in a position relative to the length of password (between 0 and length of hash type(sha1? md5?)) within the hashed password, and then hash the complete string.

This results in a password hash using a salt that is dynamically placed dependant on password length. The salt used is then appended to the front of the finished hash so it can be retrieved later on for verifying.

Seeing as users will choose a typical password of between 5 and say 15 characters long, this gives them an extra 10 times the amount of dictionary attacks to try out with the hash as it could be placed in any position, because this is a random generated salt too, it means at least 10 dictionary attacks (with possiblity of upto 40) for each instance a password is created, to try and work out your sha1 encrypted password.

If you change your password say every month, even if someone gets a look in at your file through a local exploit, the amount of time to work out your password would far outweigh the frequency at which you change it.

Nothing is secure, but this should take them longer to work out then the time you change it. That is at least by todays technologies.

Paul

<?php
    function createHash($inText, $saltHash=NULL, $mode='sha1'){
        // hash the text //
        $textHash = hash($mode, $inText);
        // set where salt will appear in hash //
        $saltStart = strlen($inText);
        // if no salt given create random one //
        if($saltHash == NULL) {
            $saltHash = hash($mode, uniqid(rand(), true));
        }
        // add salt into text hash at pass length position and hash it //
        if($saltStart > 0 && $saltStart < strlen($saltHash)) {
            $textHashStart = substr($textHash,0,$saltStart);
            $textHashEnd = substr($textHash,$saltStart,strlen($saltHash));
            $outHash = hash($mode, $textHashEnd.$saltHash.$textHashStart);
        } elseif($saltStart > (strlen($saltHash)-1)) {
            $outHash = hash($mode, $textHash.$saltHash);
        } else {
            $outHash = hash($mode, $saltHash.$textHash);
        }
        // put salt at front of hash //
        $output = $saltHash.$outHash;
        return $output;
    }
?>
mVamer 07-Jan-2009 05:49
If I correctly understand what ranko84 is on about, this would be a simpler function with roughly the same result.

<?php
function obscure($password, $algorythm = "sha1")
{
        // Get some random salt, or verify a salt.
        // Added by (grosbedo AT gmail DOT com)
        if ($salt == NULL)
        {
            $salt = hash($algorythm, uniqid(rand(), true));
        }

    // Determine the length of the hash.
    $hash_length = strlen($salt);

    // Determine the length of the password.
    $password_length = strlen($password);

    // Determine the maximum length of password. This is only needed if
    // the user enters a very long password. In any case, the salt will
    // be a maximum of half the end result. The longer the hash, the
    // longer the password/salt can be.
    $password_max_length = $hash_length / 2;

    // Shorten the salt based on the length of the password.
    if ($password_length >= $password_max_length)
    {
        $salt = substr($salt, 0, $password_max_length);
    }
    else
    {
        $salt = substr($salt, 0, $password_length);
    }

    // Determine the length of the salt.
    $salt_length = strlen($salt);

    // Determine the salted hashed password.
    $salted_password = hash($algorythm, $salt . $password);

    // If we add the salt to the hashed password, we would get a hash that
    // is longer than a normally hashed password. We don't want that; it
    // would give away hints to an attacker. Because the password and the
    // length of the password are known, we can just throw away the first
    // couple of characters of the salted password. That way the salt and
    // the salted password together are the same length as a normally
    // hashed password without salt.
    $used_chars = ($hash_length - $salt_length) * -1;
    $final_result = $salt . substr($salted_password, $used_chars);

    return $final_result;
}
?>
ranko84 at gmail dot com 16-Dec-2008 08:11
Small update..., well more like fix to the obscure function, replace
<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
    }
}
?>

with

<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        if ($hRPosition == 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition);
        }
        else
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }
}
?>

I've been getting few requests to explain how it's used so, this might be little long.

Problems:
1. In most solutions with hash and salt, you were bound to have one extra row in your database that would state, preferably random, salt for that hashed data. If attacker would manage to get drop of your database he would get hashed data and salt that is used with plain data to make it obscure, and then cracking that hashed data would be same as if you didn't add any salt to it.
2. I stumbled upon some functions that would hash data, then input salt into random places in hash and store it in database, but they would still have to write down random parameter used to scramble salt so they could reuse it when validating data. Getting simple database drop wouldn't help much here, but if they would manage to get their hands on obscuring function too, they could easily see what is salt and what hash.

Solutions:
1. Why use extra row to store salt when you can input it in hash. I'm not sure how attackers determine what type of hash are they facing, but I guess it has connection to hash length. In that case, why make attackers job easier and store in database data_hash+salt where they could assume just by it's length it has salt in there.
Reason behind $keepLength. If it's set to 1, strlen of hashed data plus salt would be equal to strlen of hashed data leading attacker to believe there is no salt.
If you leave $keepLength on NULL, strlen of final result would be strlen(used_hash_algorithm)+$hSLength.
$minhPass is there to reserve enough place for string that has to be hashed, so someone using this function wouldn't accidentally delete it by setting too high salt length ($hSLength), for example... if you set it 30000 it will keep working normal.

2. If you think about it, constant, but variable value when making input would be same data that is being input.
In case we're trying to hash password, and have user A with password "notme", password strlen equals to 5, and if we use default parameters of the function, with $keepLength set to 1, process would be:
random salt, hash it, add first 5 characters of hashed_salt at beginning of plain password, add last 5 characters of hashed_salt at end of plain password, hash it. Replace first 5 characters of hashed_password with first 5 character of hashed_salt, do same with last 5 characters of hashed_password, return hashed_password.
In case that string is longer than 10 characters function would use simple mathematics to reduce it to numbers lower than 10, well... lower than number that is stated in $hSLength.
And good thing is that every time user enters correct password it has same length so it's not necessary to write it anywhere.

So what is achieved in the end?
1. Attacker might not know that hash is salted, and you don't have that extra row in your database stating THIS IS SALT FOR THIS HASH.
2. If he does find out that it is, he wouldn't know what is hashed password and what is salt.
3. If he manages to get access to obscure function, only thing that might help him is value of $hSLength, where if $hSLength is set to 10 he would have to crack 10 variations of hashed string since he doesn't know how long password of user he's trying to crack is.
For example first variation would be hashed_password without last 10 characters, second variation would be hashed_password without first character and last 9 characters...
4. Even in case he has enough power to crack all 10 variations, resulting string that he might get doesn't necessarily has to be exactly long as password of original user in which case, attacker fails again.
Andre D 08-Oct-2008 06:28
Here's a better version of the getDigestNotation() function I posted earlier. (The first version had a bug in the argument checking.)

<?php
function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;
        $minCharLength = 2;

        while (strlen($chars) >= ($minCharLength *= 2)) {
            $bitsPerCharacter++;
        }

        unset($minCharLength);
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>
Andr D 06-Oct-2008 12:01
Sometimes you want the digest in both readable notation (such as hexadecimal) and raw binary. At other times you want the digest in a notation other than hexadecimal.

The following getDigestNotation() function takes a binary string and returns it in base 2, 4, 8, 16, 32, or 64 notation. It works with sha1(), md5(), hash(), or anything else that can output a raw binary string.

It works similar to the session.hash_bits_per_character php.ini configuration option.

You can specify which characters to use for each position, or use the default, which matches session.hash_bits_per_character (0-9, a-z, A-Z, "-", ","). The practical range of bits to use per character ($bitsPerCharacter) is 1 to 6; you may use more, but you will have to provide your own base character string ($chars) that is at least pow(2, $bitsPerCharacter) characters long. So even with 7 bits per character you need to specify a value for $chars that is 128 characters long, which exceeds the number of printable ASCII characters.

The output's radix relates to the value of $bitsPerCharacter as follows:
1: base-2 (binary)
2: base-4
3: base-8 (octal)
4: base-16 (hexadecimal)
5: base-32
6: base-64

<?php
$raw = sha1(uniqid(mt_rand(), TRUE), TRUE);

echo getDigestNotation($raw, 6);

function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;

        do {
            $bitsPerCharacter++;
        } while (strlen($chars) > pow(2, $bitsPerCharacter));
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>

Lastly, depending on the digest length, there may be fewer bits remaining for the last character than $bitsPerCharacter, so the last character will be smaller. The same thing happens with PHP's session ID generator, when 5 or 6 is used for session.hash_bits_per_character.
ranko84 at gmail dot com 08-May-2008 07:12
Thanks for the feedback. This should do the trick, I hope.
I think that I haven't understood this sentence completely "In this case you will need the salt to reside in the database along with the username and password." As in, were you refering to previous method, this method or this function.
Salt already resides in database along with username, password, or any string you decide to hash. This function just scrambles it depending on length of string (password) user enters so that attacker has trouble finding out what is salt and what is hash, if attacker even suspects that there is salt (reasons behind $keepLength, or defining $hSLength where you could set it to 24 leading attacker to believe he's facing sha256, not sha1).

<?php
function obscure ($hString, $hDecode = NULL, $hSLength = 10, $keepLength = NULL, $minhPass = 10, $hMethod = sha1)
{
    if ($hDecode == NULL)
    {
        for ($i = 0; $i<16; $i++)
        {

            $hSalt = rand(33, 255);
            $hRandomSalt .= chr($hSalt);
        }
        $hRandomSalt = hash($hMethod, $hRandomSalt);
    }
    else
    {
        $hRandomSalt = $hDecode;
    }

    if ($keepLength != NULL)
    {

        if ($hSLength > (strlen($hRandomSalt) - $minhPass))
        {
            $hSLength = (strlen($hRandomSalt) - $minhPass);
        }
    }
    else if ($hSLength < 0)
    {
        $hSLength = 0;
    }

    $hLPosition = strlen($hString);

    while ($hLPosition > $hSLength)
    {
        $hNumber = substr($hLPosition, -1);

        $hLPosition = $hLPosition * ($hNumber/10);
    }

    $hLPosition = (integer)$hLPosition;
    $hRPosition = $hSLength - $hLPosition;

    $hFSalt = substr($hRandomSalt, 0, $hLPosition);
    $hLSalt = substr($hRandomSalt, -$hRPosition, $hRPosition);

    $hPassHash = hash($hMethod, ($hLSalt . $hString . $hFSalt));

    if ($keepLength != NULL)
    {
        if ($hSLength != 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }

    return $hFSalt . $hPassHash . $hLSalt;
}
?>
Murali 08-May-2008 12:18
I think ranko's method is tougher to crack if there is a directory attack. However there is one small change I would suggest. Instead of having the hsalt as a limited array, it is better to generate a random string and use that as the salt. In this case you will need the salt to reside in the database along with the username and password.

Thanks Ranko...
ranko84 at gmail dot com 07-May-2008 04:17
If your still using sha1, here is a function that will hopefully help a little.

Sorry for any grammatical mistakes and for naming convention, I'm not very original and in most cases get myself confused after some time with them too :(

Benefits: even if attacker manages to generate string that will result in same hash, if that string doesn't have same amount of characters as original, it won't validate.

<?php
function obscure ($hString, $hDecode = NULL, $hSLength = 10, $keepLength = NULL, $minhPass = 10, $hMethod = sha1)
{
    if ($hDecode == NULL)
    {
        $hSalt = array("\\", "!", "0", "\"", "1", "#", "2", "$", "3", "%", "4", "&", "5", "/", "6", "(", "7", ")", "8", "=", "9", "?", "*");

        for ($i = 0; $i<16; $i++)
        {
            $hRandomIndex = array_rand($hSalt);
            $hRandomSalt .= $hSalt[$hRandomIndex];
        }
        $hRandomSalt = hash($hMethod, $hRandomSalt);
    }
    else
    {
        $hRandomSalt = $hDecode;
    }

    if ($keepLength != NULL)
    {

        if ($hSLength > (strlen($hRandomSalt) - $minhPass))
        {
            $hSLength = (strlen($hRandomSalt) - $minhPass);
        }
    }
    else if ($hSLength < 0)
    {
        $hSLength = 0;
    }

    $hLPosition = strlen($hString);

    while ($hLPosition > $hSLength)
    {
        $hNumber = substr($hLPosition, -1);

        $hLPosition = $hLPosition * ($hNumber/10);
    }

    $hLPosition = (integer)$hLPosition;
    $hRPosition = $hSLength - $hLPosition;

    $hFSalt = substr($hRandomSalt, 0, $hLPosition);
    $hLSalt = substr($hRandomSalt, -$hRPosition, $hRPosition);

    $hPassHash = hash($hMethod, ($hLSalt . $hString . $hFSalt));

    if ($keepLength != NULL)
    {
        if ($hSLength != 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }

    return $hFSalt . $hPassHash . $hLSalt;
}
?>

How to use?
$hString is string you want to hash, probably password.
$hDecode is already hashed string (password). When you use function obscure() to generate hash, you will probably enter it in database. When user wants to log in, you pass plain password with $hString, and hashed password from database in $hDecode.
$hSLength is length of salt. It's caped by method you use to hash, so in case you use sha1, you can pass value 100, but it will still use 40 characters.
$keepLength can be used to cap final output at max characters that hash function gives. In case sha1, hash would give output of 40 characters. If you set $keepLength to '1' final outputted hash would have 40 characters by cutting pieces of hashed password. Why would you want to do it? So that attacker doesn't know it's salted :)
$minhPass - it is usually defined only if you decide to set $keepLength so that you can define minimum amount of characters of hashed password you want to keep. Default is 10. It's used because you can accidentally set, in combination with $keepLength, $hSLength too high which would cause that all characters of hashed password are cut out and leave only salt which would always validate true without regard what password user enters.
$hMethod defines which method you want to use to hash plain text since this function is build using hash(). If you want to use sha512, function will adapt to it.

Quick example:
Hashing a password - obscure ($plain_password);
Validating password - obscure ($plain_password, $hashedPassword);

I tried to be as brief as possible, best way to see how it's used... test it, otherwise mail me if you have questions.
nathan 25-Feb-2008 08:11
The suggestion below to double-hash your password is not a good idea.  You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account).

Double hashing is *worse* security than a regular hash.  What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).

sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant.  You have not increased security at all.
brian at realm3 dot com 15-Feb-2008 06:47
Those wishing to generate an HMAC-SHA1 type key can now use hash_hmac()

http://us2.php.net/manual/en/function.hash-hmac.php
ERASEthemasterswordsman at gmail dot com 10-Feb-2008 06:09
Please note that hashing a has is not completely secure, but can be used as an extra precaution (but not recommended):

<?php

sha1(md5($string));

?>
NoName 13-Sep-2007 03:26
Regarding the twistSTR - the problem is that currently it is relatively easy to generate a collision for any alphanumeric plaintext of a given, short length via e.g. a rainbow table. You're bettter off using a sufficiently lengthy and random salt.
novum123 at ribbonbazaar dot com 29-Nov-2006 08:54
So far as the dictionary attacks are concerned, I thought up the following function:

<?php
function twistSTR($array){
  $twisted="";
  $array_strlen=array();

  foreach ($array as $element){
    $array_strlen[]=strlen($element);
  }

  for ($i=0; $i<max($array_strlen); $i++){
    foreach ($array as $element){
      if ($i<strlen($element)){
        $twisted=$twisted.$element{$i};
      }
    }
  }

  return $twisted;
}
?>

The twistSTR function basically takes an array input of strings and alternates each character of each string among all the other strings.  For example:

<?php
echo twistSTR(array("this","and","that"));//output: tathnhidast
?>

It can be applied in the following manner:

<?php
if ($un===$_POST["username"] && $pwd===sha1(twistSTR(array($salt,$_POST["password"])))){
?>

It's not amazingly difficult to reverse engineer the actual output, but then again, that's not the point.  The point is that when a password is entered into one of those databases, they are going to enter for example "thisandthat", not "tathnhidast".
Dan Casey 16-Nov-2006 08:54
For all the php4 users who thought you were limited to sha1.

<?php

$phrase = "Hello World";

$sha1a =  base64_encode(sha1($phrase));
$sha1b =  base64_encode(bin2hex(mhash(MHASH_SHA1,$phrase)));
$sha256b= base64_encode(bin2hex(mhash(MHASH_SHA256,$phrase)));

echo ("SHA1..:" . $sha1a . "\n");
echo ("SHA1..:" . $sha1b . "\n");
echo ("SHA256:" . $sha256b . "\n");
?>
# php sha.php
SHA1..:MGE0ZDU1YThkNzc4ZTUwMjJmYWI3MDE5NzdjNWQ4NDBiYmM0ODZkMA==
SHA1..:MGE0ZDU1YThkNzc4ZTUwMjJmYWI3MDE5NzdjNWQ4NDBiYmM0ODZkMA==
SHA256:YTU5MWE2ZDQwYmY0MjA0MDRhMDExNzMzY2ZiN2IxOTBkNjJjNjV...........
Gregory Boshoff 18-Oct-2006 04:23
Note that the sha1 algorithm has been compromised and is no longer being used by government agencies.

As of PHP 5.1.2 a new set of hashing functions are available.

http://www.php.net/manual/en/function.hash.php

The new function hash() supports a new range of hashing methods.

echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');

It is recommended that developers start to future proof their applications by using the stronger sha-2, hashing methods such as sha256, sha384, sha512 or better.

As of PHP 5.1.2 hash_algos() returns an array of system specific or registered hashing algorithms methods that are available to PHP.

print_r(hash_algos());
erling dot westenvik at gmail dot com 17-May-2006 06:15
Regarding php at REMOVEMEkennel17 dot co dot uk's note below:

The phrase: "To get the correct behaviour", would perhaps be better off if it read: "To get the wanted (but not recommended) behaviour".

Always honor the expected data types for functions: sha1 expects a string as input, and returns a string on exit. NULL, TRUE and FALSE are not string data types. The string "" is a string as good as "any". By following the "logic" that sha1("") should return "", then what should sha1("a") return? "b"? "c"?

An authentication system that allows for blank passwords is not really an authentication system in the first place. What you are describing is merely a way to tell the application that you want to see data in some specific context, like sorted by user name, etc. Create other tools for this purpose and leave the authentication system to deal with what it is supposed to do: Granting users access to restricted data and blocking other users from seeing the same data.

Don't store passwords in clear text, but salt and encrypt them. That way it makes perfect sense having <?php $sStoredPwd === sha1($sStoredSalt . $_POST["sTypedPwd"]); ?>, even with a blank "password". No other person than the user itself, not even the programmer, should know the password or be able to guess it. If the user forgets the password, a new one must be generated.

Regards,
Erling
spam at barad-dur dot nl 23-Oct-2005 04:59
For servers that don't have the mhash or crypto++-php extensions I wrote an implementation of the SHA256 algorithm as found in the FIPS 180-2 standard.
Source code can be found at http://dev.barad-dur.nl/sha256/
php at REMOVEMEkennel17 dot co dot uk 19-Sep-2005 06:52
It should be noted that sha1("") does not return an empty string.  This means that if you are running a system that does not require users to have a password, the following code will not work as expected:

<?php
if ($StoredPassword == sha1($NewPassword))
    // Password good
?>

If $StoredPassword and $NewPassword are both blank, then the password should be treated as good, but because sha1("") != "" it will be treated as bad. To get the correct behaviour you need to use:

<?php
if (($StoredPassword == "" && $NewPassword == "") || ($StoredPassword == sha1($NewPassword)))
    // Password good
?>

(Note: I use a custom IsBlank() function instead of comparison against the empty string, so NULL values are also matched.)

For reference, here are a couple of special values put through sha1().  Note that sha1("") == sha1(NULL) == sha1(false), and also that sha1(0) != sha1(false)

"" -> da39a3ee5e6b4b0d3255bfef95601890afd80709
NULL -> da39a3ee5e6b4b0d3255bfef95601890afd80709
0 -> b6589fc6ab0dc82cf12099d1c2d40ab994e8410c
1 -> 356a192b7913b04c54574d18c28d46e6395428ab
false -> da39a3ee5e6b4b0d3255bfef95601890afd80709
true -> 356a192b7913b04c54574d18c28d46e6395428ab
Dan 05-Sep-2005 10:12
I've noticed websites are now starting to require passwords of a certain length that MUST contain at least 1 non-alphanumeric character. This in itself makes dictionary attacks kind of useless. My web site requires that as well. It uses md5, and appends a site code into the md5 as well. And the include file that contains that site key is outside the public folders. I sure hope I've done enough to keep the bad boys out.
arachnid at notdot dot net 31-Aug-2005 01:12
WTM's post below is misinformed. The purpose of adding the random data (known as a 'salt', as multiple posters have pointed out further below) is to prevent dictionary based attacks, allowing the attacker use a pre-prepared database of passwords and hashes against all your stored passwords, instead of having to recalculate for each user.

Adding the salt in a more 'complicated' way is a poor security tactic - if the attacker discovers your method, the security advantage is lost, and you have no way of changing it without rehashing all your passwords.
WTM 03-Aug-2005 07:30
Actually, the post by Helpful Harry won't improve your security except for the most simple break in attempts.  Since the random seed is attached to the end of the password hash, if you steal the hashed password, you steal the seed.

That means you can write a simple php program to call the pw_check function Harry included from a loop, feeding it dictionary words or random characters.

Of course, if you modified the program to use the seed in a more complicated way, "they" would have to know the new function's operation.  But then again, if someone can steal your password database, they can probably steal your website code (or guess it).
Helpful Harry 06-Jul-2005 10:21
check out these randomized sha1 password storage functions, they output a string of 50 characters, the first 40 characters being a sha1 output based on the last 10 characters - those being a random seed

to encode a password run pw_encode with the password, it'll return a different pseudo-random string every time - store this value.

to check a password run pw_check with the password attempt and the stored value, it'll return true on a match and false otherwise

these functions eliminate the pesky problem of dictionary matches being run on your password lists

<?php

function pw_encode($password)
{
   for ($i = 1; $i <= 10; $i++)
       $seed .= substr('0123456789abcdef', rand(0,15), 1);
   return sha1($seed.$password.$seed).$seed;
}

function pw_check($password, $stored_value)
{
   if (strlen($stored_value) != 50)
      return FALSE;
   $stored_seed = substr($stored_value,40,10);
   if (sha1($stored_seed.$password.$stored_seed).$stored_seed == $stored_value)
     return TRUE;
   else
     return FALSE;
}

?>
alex at milivojevic dot org 28-Apr-2005 02:12
Regarding my previous comment, if you want to be on the safe side and use only ASCII printable seeds (shouldn't matter for SSHA seeds), something like this could be used:

<?php
$salt = substr(base64_encode(pack("H*", sha1(mt_rand()))), 0, 4);
?>
alex at milivojevic dot org 28-Apr-2005 10:45
If you don't have mhash library and/or PHP module (for example, Red Hat systems, which includes Fedora), and you don't feel like adding it, you can use something like this to generate and verify SSHA hashes.

<?php

$password = "test";

// Generate SSHA hash
mt_srand((double)microtime()*1000000);
$salt = pack("CCCC", mt_rand(), mt_rand(), mt_rand(), mt_rand());
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $salt)) . $salt);
echo $hash . "\n";

// Verify SSHA hash
$ohash = base64_decode(substr($hash, 6));
$osalt = substr($ohash, 20);
$ohash = substr($ohash, 0, 20);
$nhash = pack("H*", sha1($password . $osalt));
if ($ohash == $nhash) {
   echo "Password OK\n";
 } else {
   echo "Password verifiaction failed\n";
 }

?>
svn at datapirate dot de 20-Feb-2005 05:26
Wanna use SHA-2 algorithm? Try this:

Download Tar-Ball from http://www.adg.us/computers/sha.html
Compile (may occur some warnings) and test it:

cc -O2 -DSHA2_UNROLL_TRANSFORM -Wall -o sha2 sha2prog.c sha2.c
./sha2test.pl

Copy it to /usr/local/bin/ (don't forget to check permissions)

Here are two functions that could be used with:

function sha2($bits, $string){
    $sha2bin="/usr/local/bin/sha2";
    $echocmd="echo";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    $r=exec($echocmd." ".escapeshellarg($string)."|".$sha2bin." -q -".$bits, $sha2);
    return($sha2[0]);
}

function sha2_file($bits, $filename){
    $sha2bin="/usr/local/bin/sha2";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    if(!file_exists($filename)||!is_readable($filename))return(false);
    $r=exec($sha2bin." -q -".$bits." ".escapeshellarg($filename), $sha2);
    return($sha2[0]);
}

and use it like below:

<?php
$str = 'apple';
if (sha2(256, $str) === '303980bcb9e9e6cdec515230791af8b0ab1aaa244b58a8d99152673aa22197d0') {
   echo "Would you like a green or red apple?";
   exit;
}
?>
hans at pennywaffer dot net 19-Dec-2004 08:18
You can also use sha1() to create a fixed sized ID based on the folderpath containing the performing script. Imagine an environment where multiple instances of a script are running simultaneously, making use of session variables (a good example would be thumbnaildirectories that each contain an instance of a thumbnailmanager). To prevent your $_SESSION array from getting influenced by other scripts that are on the same server and run from the same browserwindow (and thus having the same session ID), use the following approach:

session_start();
$myDir = sha1(dirname(__FILE__));
$_SESSION[$myDir]['var'] = etc;

instead of just using $_SESSION['var'] = etc;

This way your userauthentication and shoppingcart data won't get mixed up. The use of sha1() also prevents strange symbols or spaces in the folderpath messing up the ID, and makes sure the ID has a constant size  regardless the length of the path.
sinatosk at gmail dot com 22-Nov-2004 12:43
Heres an SHA1 function that will work on it's own completely. This is for users who are using below PHP 4.3.0. it works same as PHP5 ( being able to return raw output ).

<?php

/*
** Date modified: 1st October 2004 20:09 GMT
*
** PHP implementation of the Secure Hash Algorithm ( SHA-1 )
*
** This code is available under the GNU Lesser General Public License:
** http://www.gnu.org/licenses/lgpl.txt
*
** Based on the PHP implementation by Marcus Campbell
** http://www.tecknik.net/sha-1/
*
** This is a slightly modified version by me Jerome Clarke ( sinatosk@gmail.com )
** because I feel more comfortable with this
*/

function sha1_str2blks_SHA1($str)
{
    $strlen_str = strlen($str);

    $nblk = (($strlen_str + 8) >> 6) + 1;

    for ($i=0; $i < $nblk * 16; $i++) $blks[$i] = 0;

    for ($i=0; $i < $strlen_str; $i++)
    {
        $blks[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8);
    }

    $blks[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8);
    $blks[$nblk * 16 - 1] = $strlen_str * 8;

    return $blks;
}

function sha1_safe_add($x, $y)
{
    $lsw = ($x & 0xFFFF) + ($y & 0xFFFF);
    $msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);

    return ($msw << 16) | ($lsw & 0xFFFF);
}

function sha1_rol($num, $cnt)
{
    return ($num << $cnt) | sha1_zeroFill($num, 32 - $cnt);
}

function sha1_zeroFill($a, $b)
{
    $bin = decbin($a);

    $strlen_bin = strlen($bin);

    $bin = $strlen_bin < $b ? 0 : substr($bin, 0, $strlen_bin - $b);

    for ($i=0; $i < $b; $i++) $bin = '0'.$bin;

    return bindec($bin);
}

function sha1_ft($t, $b, $c, $d)
{
    if ($t < 20) return ($b & $c) | ((~$b) & $d);
    if ($t < 40) return $b ^ $c ^ $d;
    if ($t < 60) return ($b & $c) | ($b & $d) | ($c & $d);

    return $b ^ $c ^ $d;
}

function sha1_kt($t)
{
    if ($t < 20) return 1518500249;
    if ($t < 40) return 1859775393;
    if ($t < 60) return -1894007588;

    return -899497514;
}

function sha1($str, $raw_output=FALSE)
{
    if ( $raw_output === TRUE ) return pack('H*', sha1($str, FALSE));

    $x = sha1_str2blks_SHA1($str);
    $a =  1732584193;
    $b = -271733879;
    $c = -1732584194;
    $d =  271733878;
    $e = -1009589776;

    $x_count = count($x);

    for ($i = 0; $i < $x_count; $i += 16)
    {
        $olda = $a;
        $oldb = $b;
        $oldc = $c;
        $oldd = $d;
        $olde = $e;

        for ($j = 0; $j < 80; $j++)
        {
            $w[$j] = ($j < 16) ? $x[$i + $j] : sha1_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1);

            $t = sha1_safe_add(sha1_safe_add(sha1_rol($a, 5), sha1_ft($j, $b, $c, $d)), sha1_safe_add(sha1_safe_add($e, $w[$j]), sha1_kt($j)));
            $e = $d;
            $d = $c;
            $c = sha1_rol($b, 30);
            $b = $a;
            $a = $t;
        }

        $a = sha1_safe_add($a, $olda);
        $b = sha1_safe_add($b, $oldb);
        $c = sha1_safe_add($c, $oldc);
        $d = sha1_safe_add($d, $oldd);
        $e = sha1_safe_add($e, $olde);
    }

    return sprintf('%08x%08x%08x%08x%08x', $a, $b, $c, $d, $e);
}

?>
rsemirag at yahoo dot com 02-Nov-2004 10:34
If you're struggling to generate an SHA encoded password for LDAP (PHP < 5.0), what you end up needing is this:

$userpassword = base64_encode(pack("H*", sha1($pass)));

I found this in the OpenLDAP FAQ (many thanks to Google and Ace), though I'm using the iPlanet LDAP server.

Ray Semiraglio
brian_bisaillon at rogers dot com 25-Feb-2004 08:19
Source code to create SSHA passwords...

public function HashPassword($password)
{
  mt_srand((double)microtime()*1000000);
  $salt = mhash_keygen_s2k(MHASH_SHA1, $password, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  $hash = "{SSHA}".base64_encode(mhash(MHASH_SHA1, $password.$salt).$salt);
  return $hash;
}

Source code to validate SSHA passwords...

public function ValidatePassword($password, $hash)
{
  $hash = base64_decode(substr($hash, 6));
  $original_hash = substr($hash, 0, 20);
  $salt = substr($hash, 20);
  $new_hash = mhash(MHASH_SHA1, $password . $salt);
   if (strcmp($original_hash, $new_hash) == 0)
     ... do something because your password is valid ...
  else
    echo 'Unauthorized: Authorization has been refused for the credentials you provided. Please login with a valid username and password.';
    ... be sure to clear your session data ...
}

Note: The format is compatible with OpenLDAP's SSHA scheme if I'm not mistaken.
mark at dot BANSPAM dot pronexus dot nl 30-Jan-2004 06:28
Looking for a simple function to implement HMAC-SHA1 but don't want to use the entire PEAR Message lib?

//Calculate HMAC-SHA1 according to RFC2104
// http://www.ietf.org/rfc/rfc2104.txt
function hmacsha1($key,$data) {
    $blocksize=64;
    $hashfunc='sha1';
    if (strlen($key)>$blocksize)
        $key=pack('H*', $hashfunc($key));
    $key=str_pad($key,$blocksize,chr(0x00));
    $ipad=str_repeat(chr(0x36),$blocksize);
    $opad=str_repeat(chr(0x5c),$blocksize);
    $hmac = pack(
                'H*',$hashfunc(
                    ($key^$opad).pack(
                        'H*',$hashfunc(
                            ($key^$ipad).$data
                        )
                    )
                )
            );
    return bin2hex($hmac);
}

It is very useful for client-authentication. see also http://cookies.lcs.mit.edu/pubs/webauth:tr.pdf
Optionally you can change $hashfunc to 'md5' to make this an HMAC-MD5 function ;-)
If you want raw or base64 output instead of hexadecimal, just change the last return line.

Cheers,
Mark

p.s. the "$hmac =" line used to be 1 line but I had to cut it up in order to fit it here ;)
labarks 15-Nov-2003 03:06
Append this to the your sha1lib file to make it more portable.  If your version of php does support sha1() then it will try to use Mhash or else it will use the sha1lib.  Use $sha1 if you want to display which is being used.

if ( function_exists('sha1') )
    $sha1 = "sha1";

if ( !function_exists('sha1') && function_exists('mhash'))
{
    function sha1($hash_source)
    {
           $hash = mhash(MHASH_SHA1, $hash_source);
          $hex_hash = bin2hex($hash);
           return $hex_hash;
    }
    $sha1 = "Mhash";
}
if ( !function_exists('sha1') && !function_exists('mhash'))
{
    function sha1( $string, $raw_output = false )
    {
        $library = new Sha1Lib();

        return $raw_output ? $library->str_sha1($string) : $library->hex_sha1($string);
    }
    $sha1 = "sha1lib";
}
andreas at schmeiler dot de 16-Oct-2003 11:50
To use the sha1 function in php versions <4.3 do the following:

install the mhash library (see http://mhash.sourceforge.net)

then, sha1 can be implemented as follows:

function sha1($hash_source) {
   $hash = mhash(MHASH_SHA1, $hash_source);
   $hex_hash = bin2hex($hash);
   return $hex_hash;
}
bobm at hp dot com 23-Apr-2003 09:12
To achieve raw binary format prior to PHP5, you can do this...

$raw = pack("H*", sha1($str));

Regards,

Bob Mader
sha1_file
similar_text
Обработка строк


Вычисляет степень похожести двух строк

sha1
soundex
Обработка строк
PHP Manual

similar_text

(PHP 4, PHP 5)

similar_text — Вычисляет степень похожести двух строк

Описание

int similar_text ( string $first , string $second [, float &$percent ] )

Вычисляет степень похожести двух строк по алгоритму, описанному Oliver [1993]. Эта реализация алгоритма не использует стека, использованного в оригинале, вместо этого применяются рекурсивные вызовы, что в некоторых случаях может ускорить процесс. Сложность алгоритма составляет O(N**3), где N - длина более длинной из двух строк.

Список параметров

first

Первая строка.

second

Вторая строка.

percent

При передаче по ссылке третьего аргумента, similar_text() присваивоит ему степень похожести двух строк в процентах.

Возвращаемые значения

Возвращается количество совпадающих символов в двух строках.

Смотрите также

  • levenshtein() - Вычисляет расстояние Левенштейна между двумя строками
  • soundex() - Возвращает ключ soundex для строки

User Contributed Notes

daniel dot karbach at localhorst dot tv 17-Dec-2010 06:48
Please note that this function calculates a similarity of 0 (zero) for two empty strings.

<?php
similar_text("", "", $sim);
echo $sim; // "0"
?>
romain dot boyer at gmail dot com 08-Aug-2007 05:59
Like levenchtein(), You can do :

(strlen($string2) - similar_text($string,$string2))

to see how much characters have been changed.
Paul 18-Jan-2007 08:50
The speed issues for similar_text seem to be only an issue for long sections of text (>20000 chars).

I found a huge performance improvement in my application by just testing if the string to be tested was less than 20000 chars before calling similar_text.

20000+ took 3-5 secs to process, anything else (10000 and below) took a fraction of a second.
Fortunately for me, there was only a handful of instances with >20000 chars which I couldn't get a comparison % for.
dmitry dot polushkin at gmail dot com 07-Mar-2006 08:08
Well... hard to explain, why I have written this function, but maybe it will be usefull.
<?php
// returns the percentage of the string "similarity"
function str_compare($str1, $str2) {
    $count = 0;

    $str1 = ereg_replace("[^a-z]", ' ', strtolower($str1));
    while(strstr($str1, '  ')) {
        $str1 = str_replace('  ', ' ', $str1);
    }
    $str1 = explode(' ', $str1);

    $str2 = ereg_replace("[^a-z]", ' ', strtolower($str2));
    while(strstr($str2, '  ')) {
        $str2 = str_replace('  ', ' ', $str2);
    }
    $str2 = explode(' ', $str2);

    if(count($str1)<count($str2)) {
        $tmp = $str1;
        $str1 = $str2;
        $str2 = $tmp;
        unset($tmp);
    }

    for($i=0; $i<count($str1); $i++) {
        if(in_array($str1[$i], $str2)) {
            $count++;
        }
    }

    return $count/count($str2)*100;
}
?>
louis #at# mulliemedia.com 06-Jun-2004 05:01
Note that this function will calculate the percentage blindly, without regard to the LENGHT of the string.

This may become important if you try to print similar names to SMALL strings :
e.g.
I want to print out the value if it is 90 percent similar to the other one : the value is HE, the correct value is HEC

The similar_text() function will return approximately 66.7 %, and it will not print it because it is smaller than 90 %, although almost all of the string was matched.
hate at spam dot com dot BR 09-May-2004 09:21
In PHP4+, you don't need to pass the percent variable as reference..
Instead, use this way:

<?php
similar_text($string1, $string2, $p);
echo "Percent: $p%";
?>

In PHP5, you'll get a ugly warning message when passing this variable as reference.. But it's configurable in php.ini (allow_call_time_pass_reference = Off)

That's it... Another great function! :)
julius at infoguiden dot no 06-Feb-2003 06:46
If you have reserved names in a database that you don't want others to use, i find this to work pretty good.
I added strtoupper to the variables to validate typing only. Taking case into consideration will decrease similarity.

<?php
$query = mysql_query("select * from $table") or die("Query failed");

while ($row = mysql_fetch_array($query)) {
      similar_text(strtoupper($_POST['name']), strtoupper($row['reserved']), $similarity_pst);
      if (number_format($similarity_pst, 0) > 90){
        $too_similar = $row['reserved'];
        print "The name you entered is too similar the reserved name &quot;".$row['reserved']."&quot;";
        break;
       }
    }
?>
georgesk at hotmail dot com 08-Mar-2002 08:14
Well, as mentioned above the speed is O(N^3), i've done a longest common subsequence way that is O(m.n) where m and n are the length of str1 and str2, the result is a percentage and it seems to be exactly the same as similar_text percentage but with better performance... here's the 3 functions i'm using..

<?php
function LCS_Length($s1, $s2)
{
  $m = strlen($s1);
  $n = strlen($s2);

  //this table will be used to compute the LCS-Length, only 128 chars per string are considered
  $LCS_Length_Table = array(array(128),array(128));

  //reset the 2 cols in the table
  for($i=1; $i < $m; $i++) $LCS_Length_Table[$i][0]=0;
  for($j=0; $j < $n; $j++) $LCS_Length_Table[0][$j]=0;

  for ($i=1; $i <= $m; $i++) {
    for ($j=1; $j <= $n; $j++) {
      if ($s1[$i-1]==$s2[$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j-1] + 1;
      else if ($LCS_Length_Table[$i-1][$j] >= $LCS_Length_Table[$i][$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j];
      else
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i][$j-1];
    }
  }
  return $LCS_Length_Table[$m][$n];
}

function str_lcsfix($s)
{
  $s = str_replace(" ","",$s);
  $s = ereg_replace("[��������]","e", $s);
  $s = ereg_replace("[������������]","a", $s);
  $s = ereg_replace("[��������]","i", $s);
  $s = ereg_replace("[���������]","o", $s);
  $s = ereg_replace("[��������]","u", $s);
  $s = ereg_replace("[�]","c", $s);
  return $s;
}

function get_lcs($s1, $s2)
{
  //ok, now replace all spaces with nothing
  $s1 = strtolower(str_lcsfix($s1));
  $s2 = strtolower(str_lcsfix($s2));

  $lcs = LCS_Length($s1,$s2); //longest common sub sequence

  $ms = (strlen($s1) + strlen($s2)) / 2;

  return (($lcs*100)/$ms);
}
?>

you can skip calling str_lcsfix if you don't worry about accentuated characters and things like that or you can add up to it or modify it for faster performance, i think ereg is not the fastest way?
hope this helps.
Georges
daniel at reflexionsdesign dot com 09-Oct-2001 06:30
If performance is an issue, you may wish to use the levenshtein() function instead, which has a considerably better complexity of O(str1 * str2).
mogmios at hushmail dot com 01-Feb-2000 05:39
Don't forget your passing the double as a reference. If you use this and soundex() together you can get a pretty good guess as to how well two words match. Is useful for simple bot-like programs.

<?php
$i = similar_text($first_word, $second_word, &$p);
echo("Matched: $i  Percentage: $p%");
?>
sha1
soundex
Обработка строк


Р’РѕР·РІСЂР°С‰Р°РµС‚ РєР»СЋС‡ soundex РґР»СЏ СЃС‚СЂРѕРєРё

similar_text
sprintf
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє
PHP Manual

soundex

(PHP 4, PHP 5)

soundex — Р’РѕР·РІСЂР°С‰Р°РµС‚ РєР»СЋС‡ soundex РґР»СЏ СЃС‚СЂРѕРєРё

РћРїРёСЃР°РЅРёРµ

string soundex ( string $str )

Р’РѕР·РІСЂР°С‰Р°РµС‚ РєР»СЋС‡ soundex РґР»СЏ СЃС‚СЂРѕРєРё str.

Р”РІСѓРј СЃР»РѕРІР°Рј, РёРјРµСЋС‰РёРј СЃС…РѕР¶РµРµ РїСЂРѕРёР·РЅРѕС€РµРЅРёРµ, СЃРѕРѕС‚РІРµС‚СЃС‚РІСѓРµС‚ РѕРґРёРЅ Рё С‚РѕС‚ Р¶Рµ РєР»СЋС‡ soundex. РС‚Рѕ СЃРІРѕР№СЃС‚РІРѕ РјРѕР¶РµС‚ Р±С‹С‚СЊ РёСЃРїРѕР»СЊР·РѕРІР°РЅРѕ, РЅР°РїСЂРёРјРµСЂ, РїСЂРё РїРѕРёСЃРєРµ РїРѕ Р±Р°Р·Рµ РґР°РЅС‹С…, РєРѕРіРґР° РёР·РІРµСЃС‚РЅРѕ РїСЂРѕРёР·РЅРѕС€РµРЅРёРµ СЃР»РѕРІР° Рё РЅРµРёР·РІРµСЃС‚РЅРѕ РµРіРѕ РЅР°РїРёСЃР°РЅРёРµ. Р”Р°РЅРЅР°СЏ С„СѓРЅРєС†РёСЏ РІРѕР·РІСЂР°С‰Р°РµС‚ СЃС‚СЂРѕРєСѓ РёР· 4 СЃРёРјРІРѕР»РѕРІ, РЅР°С‡РёРЅР°СЋС‰СѓСЋСЃСЏ СЃ Р±СѓРєРІС‹.

Р”Р°РЅРЅР°СЏ СЂРµР°Р»РёР·Р°С†РёСЏ С„СѓРЅРєС†РёРё soundex РѕРїРёСЃР°РЅР° Р”РѕРЅР°Р»СЊРґРѕРј РљРЅСѓС‚РѕРј (Donald Knuth) РІ РєРЅРёРіРµ "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), СЃС‚СЂ. 391-392.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

str

Р’С…РѕРґРЅР°СЏ СЃС‚СЂРѕРєР°.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ РєР»СЋС‡ soundex РІ РІРёРґРµ СЃС‚СЂРѕРєРё.

РџСЂРёРјРµСЂС‹

РџСЂРёРјРµСЂ #1 РџСЂРёРјРµСЂС‹ soundex

<?php
soundex("Euler")       == soundex("Ellery");    // E460
soundex("Gauss")       == soundex("Ghosh");     // G200
soundex("Hilbert")     == soundex("Heilbronn"); // H416
soundex("Knuth")       == soundex("Kant");      // K530
soundex("Lloyd")       == soundex("Ladd");      // L300
soundex("Lukasiewicz") == soundex("Lissajous"); // L222
?>

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • levenshtein() - Р’С‹С‡РёСЃР»СЏРµС‚ СЂР°СЃСЃС‚РѕСЏРЅРёРµ Р›РµРІРµРЅС€С‚РµР№РЅР° РјРµР¶РґСѓ РґРІСѓРјСЏ СЃС‚СЂРѕРєР°РјРё
  • metaphone() - Р’РѕР·РІСЂР°С‰Р°РµС‚ РєР»СЋС‡ metaphone РґР»СЏ СЃС‚СЂРѕРєРё
  • similar_text() - Р’С‹С‡РёСЃР»СЏРµС‚ СЃС‚РµРїРµРЅСЊ РїРѕС…РѕР¶РµСЃС‚Рё РґРІСѓС… СЃС‚СЂРѕРє

User Contributed Notes

nicolas dot zimmer at einfachmarke dot de 03-Aug-2008 03:47
Since soundex() does not produce optimal results for German language
we have written a function to implement the so called KГ¶lner Phonetik
(Cologne Phonetic).

Please find the code below in the hope it might be useful:

<?php
/**
 * A function for retrieving the KГ¶lner Phonetik value of a string
 *
 * As described at http://de.wikipedia.org/wiki/KГ¶lner_Phonetik
 * Based on Hans Joachim Postel: Die KГ¶lner Phonetik.
 * Ein Verfahren zur Identifizierung von Personennamen auf der
 * Grundlage der Gestaltanalyse.
 * in: IBM-Nachrichten, 19. Jahrgang, 1969, S. 925-931
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @package phonetics
 * @version 1.0
 * @link http://www.einfachmarke.de
 * @license GPL 3.0 <http://www.gnu.org/licenses/>
 * @copyright  2008 by einfachmarke.de
 * @author Nicolas Zimmer <nicolas dot zimmer at einfachmarke.de>
 */

function cologne_phon($word){

  /**
  * @param  string  $word string to be analyzed
  * @return string  $value represents the KГ¶lner Phonetik value
  * @access public
  */

    //prepare for processing
    $word=strtolower($word);
    $substitution=array(
            "Г¤"=>"a",
            "Г¶"=>"o",
            "Гј"=>"u",
            "Гџ"=>"ss",
            "ph"=>"f"
            );

    foreach ($substitution as $letter=>$substitution) {
        $word=str_replace($letter,$substitution,$word);
    }

    $len=strlen($word);

    //Rule for exeptions
    $exceptionsLeading=array(
    4=>array("ca","ch","ck","cl","co","cq","cu","cx"),
    8=>array("dc","ds","dz","tc","ts","tz")
    );

    $exceptionsFollowing=array("sc","zc","cx","kx","qx");

    //Table for coding
    $codingTable=array(
    0=>array("a","e","i","j","o","u","y"),
    1=>array("b","p"),
    2=>array("d","t"),
    3=>array("f","v","w"),
    4=>array("c","g","k","q"),
    48=>array("x"),
    5=>array("l"),
    6=>array("m","n"),
    7=>array("r"),
    8=>array("c","s","z"),
    );

    for ($i=0;$i<$len;$i++){
        $value[$i]="";

        //Exceptions
        if ($i==0 AND $word[$i].$word[$i+1]=="cr") $value[$i]=4;

        foreach ($exceptionsLeading as $code=>$letters) {
            if (in_array($word[$i].$word[$i+1],$letters)){

                    $value[$i]=$code;

}                }

        if ($i!=0 AND (in_array($word[$i-1].$word[$i],
$exceptionsFollowing))) {

            value[$i]=8;

}

        //Normal encoding
        if ($value[$i]==""){
                foreach ($codingTable as $code=>$letters) {
                    if (in_array($word[$i],$letters))$value[$i]=$code;
                }
            }
        }

    //delete double values
    $len=count($value);

    for ($i=1;$i<$len;$i++){
        if ($value[$i]==$value[$i-1]) $value[$i]="";
    }

    //delete vocals
    for ($i=1;$i>$len;$i++){//omitting first characer code and h
        if ($value[$i]==0) $value[$i]="";
    }

    $value=array_filter($value);
    $value=implode("",$value);

    return $value;

}

?>
shortcut 13-Nov-2006 11:24
The answer to whether soundex works except for the first letter in klancy vs clancy is to always prefix words with the same letter.

aklancy will match aclancy
bklancy will match bclancy

soundex seems to only check the 1st 2 syllables.??
ie:  spectacular matches spectacle

just a thought if you rely on soundex.

k-
04-Oct-2005 12:25
Since the first letter is included in the phonetic representation in the output, it is worth pointing out that if you want a soundex key to work without the problems of klansy and clansy sounding different, take the substring from the first letter, as the first letter is the main constant of the word, and the numerical value is that of the phontic structure of the word.
crchafer-php at c2se dot com 13-Sep-2005 08:25
Rewritten, maybe -- but the algorithm has some obvious
optimisations which can be done, for example...

        function text__soundex( $text ) {
                $k = ' 123 12  22455 12623 1 2 2';
                $nl = strlen( $tN = strtoupper( $text ) );
                $p = trim( $k{ ord( $tS = $tN{0} ) - 65 } );
                for( $n = 1; $n < $nl; ++$n )
                        if( ( $l = trim( $k{ ord( $tN{ $n } ) - 65 } ) ) != $p )
                                $tS .= ( $p = $l );
                return substr( $tS . '000', 0, 4 );
        }

// Notes:
// $k is the $key, essentially $SoundKey inverted
// $tN is the uppercase of the text to be optimised
// $tS is the partaully generated output
// $l is the current letter, $p the previous
// $n and $nl are iteration indicies
// 65 is ord('A'), precalculated for speed
// none ascii letters are not supported
// watch the brackets, quite a mixture here

(Code has suffered only basic tests, though it appears to
match the output of PHP's soundex(), speed untested --
though this should be /much/ faster than a4_perfect's
rewrite due to the removal of most loops and compares.)

C
2005-09-13
a4_perfect at mail dot ru 01-Aug-2005 06:18
Even be rewritten, function of [administrator at zinious dot com] is slower than soundex() for approx 30 times:

<?php
function MakeSoundEx($stringtomakesoundexof)
{
  $temp_Name = strtoupper($stringtomakesoundexof);
  $SoundKey = array(1=>"BPFV", "CSKGJQXZ", "DT", "L", "MN", "R", "AEHIOUWY");
  $temp_Last = "";
  $temp_Soundex = substr($temp_Name, 0, 1);

  for ($x = 1; $x <= sizeof($SoundKey); $x++)
    for ($i = 0; $i < strlen($SoundKey[$x]); $i++)
      if ($temp_Soundex == substr($SoundKey[$x], $i - 1, 1))
        $temp_Last = (string)($x==7?"":$x);

  for ($n = 1; $n < strlen($temp_Name); $n++)
    if (strlen($temp_Soundex) < 4)
    {
      for ($x = 1; $x <= sizeof($SoundKey); $x++)
        for ($i = 0; $i < strlen($SoundKey[$x]); $i++)
          if (substr($temp_Name, $n-1, 1)==substr($SoundKey[$x], $i-1, 1))
          {
            if($x<7 && $temp_Last!=(string)$x)
              $temp_Soundex = $temp_Soundex.$x;
            $temp_Last = (string)($x);
          }
      }

  return $temp_Soundex . str_repeat("0", 4-strlen($temp_Soundex));
}
?>
Marc Quinton. 06-Jan-2005 06:53
a French soundex version ; could be used for other foreigns languages where soudex lacks. Perhaps, a class with each language specifics could be writen.

http://www.php-help.net/sources-php/a.french.adapted.soundex.289.html
justin at NO dot blukrew dot SPAM dot com 21-Sep-2004 04:18
I originally looked at soundex() because I wanted to compare how individual letters sounded. So, when pronouncing a string of generated characters it would be easy to to distinguish them from eachother.  (ie, TGDE is hard to distinguish, whereas RFQA is easier to understand). The goal was to generate IDs that could be easily understood with a high degree of accuracy over a radio of varying quality. I quickly figured out that soundex and metaphone wouldn't do this (they work for words), so I wrote the following to help out. The ID generation function iteratively calls chrSoundAlike() to compare each new character with the preceeding characters. I'd be interested in recieving any feedback on this. Thanks.

<?php
function chrSoundAlike($char1, $char2, $opts = FALSE) {
    $char1 = strtoupper($char1);
    $char2 = strtoupper($char2);
    $opts  = strtoupper($opts);

    // Setup the sets of characters that sound alike.
    // (Options: include numbers, include W, include both, or default is none of those.)
    switch ($opts) {
    case 'NUMBERS':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'STRICT':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'BOTH':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    default:
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U'));
        break;
    }

    // See if $char1 is in a set.
    $matchset = array();
    for ($i = 0; $i < count($sets); $i++) {
        if (in_array($char1, $sets[$i])) {
            $matchset = $sets[$i];
        }
    }

    // IF char2 is in the same set as char1, or if char1 and char2 and the same, then return true.
    if (in_array($char2, $matchset) OR $char1 == $char2) {
        return TRUE;
    } else {
        return FALSE;
    }
}
?>
mail at gettheeawayspam dot iaindooley dot com 10-Jul-2003 11:04
The soundex 'different letter in front' problem can be solved by using levenshtein() on the soundex codes. in my application, which is searching a database of album names for entries that match a particular user provided string, i do the following:

1. Search the database for the exact name
2. Search the database for entries where the name occurs anyway as a string
3. Search the database for entries where any of the words in the name (if the user has typed in more than one word) is present, except for little words (and, the, of etc)
4. Then, if all this fails, I go to plan b:

- calculate the levenshtein distance (levenshtein()) between the user search term and each of the entries in the database as a percentage of the length of the user search term entered

- calculate the levenshtein distance between the metphone codes of the user search term entered and each field in the database as a percentage of the length of the metaphone code of the user search term entered

- calculate the levenshtein distance between the soundex codes of the user search term entered and each field in the database as a percentage of the length of the soundex code of the original user search term entered

if any of these percentages is less than 50 (means that two soundex codes with different first letters will be accepted!!) then the entry is accepted as a possible match.
php.net AT djwice DoT com 25-Jun-2003 05:01
Ik made the Soundex in JavaScript.
http://www.vanderharg.nl/soundex.php

Explanation of the algoritm is on the above page.
It returns two values if a name has "van der" or something alike in it. One with that in the Soundex test and one without.

The use of regular expressions makes the ectual soundex algoritm short. Two conditions of the algoritm I did remove because in this implementation they are redundant.

<script language="javascript">
var koppelteken = ""; // kan ook  - zijn.
var vv=new Array(
        "de la ",
        "in het ",
        "in 't ",
        "op den ",
        "op het ",
        "op de ",
        "op te ",
        "op 't ",
        "up te",
        "uit de ",
        "van den ",
        "van der ",
        "van het ",
        "van de ",
        "van 't ",

        "opte ",
        "upte ",
        "con ",
        "den ",
        "der ",
        "ten ",
        "ter ",
        "van ",

        "de ",
        "di ",
        "du ",
        "la ",
        "le ",
        "te ",
        "vd ",

        "l' ",
        "l'",
        "'t ");

function removePrefix(name)
{
    i=0;
    var strippedresult = "";
    while ((strippedresult=="")&&(i<vv.length))
    {
        if (name.substr(0,vv[i].length)==vv[i].toUpperCase())
            strippedresult = name.substr(vv[i].length);
        i++;
    }
    return strippedresult;
}

function Soundex(name)
{
    if (name.length>1)
    {
        // zet om naar hoofdletters.
            name=name.toUpperCase();

        // converteer leestekens
            re = new RegExp ('[ДАБГ]+', 'gi');
            name = name.replace(re, 'A');
            re = new RegExp ('[ЛИЙ]+', 'gi');
            name = name.replace(re, 'E');
            re = new RegExp ('[ПМН]+', 'gi');
            name = name.replace(re, 'I');
            re = new RegExp ('[ЦТУХ]+', 'gi');
            name = name.replace(re, 'O');
            re = new RegExp ('[ЬЩЪ]+', 'gi');
            name = name.replace(re, 'U');
            re = new RegExp ('[Э]+', 'gi');
            name = name.replace(re, 'Y');

        // behandel voorvoegsels
            var result=Soundex(removePrefix(name));
            if (result!="") result+="\n";

        // eerste letter
            result += name.substr(0,1);

        // codeer de rest in cijfers
            name=name.substr(1);

        // haal A, E, I, O, U, H, W, en Y er uit.
            re = new RegExp ('[AEIOUHWY ]+', 'gi');
            name = name.replace(re, '');

        // Zet om naar cijfers met tabel.
            // haal dubbele cijfers er uit.
            re = new RegExp ('[BFPV]+', 'gi');
            name = name.replace(re, '1');
            re = new RegExp ('[ЗCGJKQSXZ]+', 'gi');
            name = name.replace(re, '2');
            re = new RegExp ('[DT]+', 'gi');
            name = name.replace(re, '3');
            re = new RegExp ('[L]+', 'gi');
            name = name.replace(re, '4');
            re = new RegExp ('[MN]+', 'gi');
            name = name.replace(re, '5');
            re = new RegExp ('[R]+', 'gi');
            name = name.replace(re, '6');

        // vul aan tot 3 cijfers.
            while (name.length<3)
                name += "0";

        // kap af op 3 cijfers
            if (name.length>3)
                name=name.substr(0,3);

        return result+koppelteken+name;
    }
    else return "";
}
</script>
pee whitt at dental dot ufl dor edu 09-Jun-2003 06:12
fie at myrealbox dot com-

regarding your soudex syllable request- i think counting vowel clusters in the word will result in an accurate count of syllables.  so no soudex feature is necessary, just count through the chars in the word, and everytime you run from vowel to consanant, increment the syllable count.

using this logic, this sentence is categorized as follows.
2 1 2 1 1 (3) (0) (4) (0) 2

where (#) marks a word that is incorrectly categorized.  i'm sure usiong a little thinking one could figure out the logic in those cases that would result in an accurate count.  counting changes from vowel to consanant would yield-
(1) 1 2 1 2 1 (4) 1 2

taking the average and then cieling of the two types would fix most of the errors.
fie at myrealbox dot com 08-Mar-2003 05:29
eek... hosting got taken down on that server.. here's the code for the previous

function cg_sylc($nos){
  $nos = strtoupper($nos);
  $syllables = 0;

  $before = strlen($nos);
  $nos = str_replace(array('AA','AE','AI','AO','AU',
  'EA','EE','EI','EO','EU','IA','IE','II','IO',
  'IU','OA','OE','OI','OO','OU','UA','UE',
  'UI','UO','UU'), "", $nos);
  $after = strlen($nos);
  $diference = $before - $after;
  if($before != $after) $syllables += $diference / 2;

  if($nos[strlen($nos)-1] == "E") $syllables --;
  if($nos[strlen($nos)-1] == "Y") $syllables ++;

  $before = $after;
  $nos = str_replace(array('A','E','I','O','U'),"",$nos);
  $after = strlen($nos);
  $syllables += ($before - $after);

  return $syllables;
}

function cg_SoundEx($SExStr){
  $syl = cg_sylc($SExStr);
  $SExStr = strtoupper($SExStr);

    for($i = 1, $ii = 2,print $SExStr[0]; ;$ii++){

      if(($SExStr[$i] != $SExStr[$ii])){
          $tsstr .= $SExStr[$ii];
          $i ++;
      }
      if($SExStr[$ii] == false){
        break;
      }
    }

  $tsstr = str_replace(array('A', 'E', 'H', 'I', 'O', 'U', 'W', 'Y'), "", $tsstr);
  $tsstr = str_replace(array('B', 'F', 'P', 'V'), "1", $tsstr);
  $tsstr = str_replace(array('C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z', 'З'), "2", $tsstr);
  $tsstr = str_replace(array('D', 'T'), "3", $tsstr);
  $tsstr = str_replace(array('L'), "4", $tsstr);
  $tsstr = str_replace(array('M', 'N', 'С'), "5", $tsstr);
  $tsstr = str_replace(array('R'), "6", $tsstr);

  while($iii < 3){
    if($tsstr[$iii] != false){
      $ttsstr .= $tsstr[$iii];
    } else {
      $ttsstr .= "0";
    }
    $iii ++;
  }
  $ttsstr .= $syl;
  print $ttsstr;
}
fie at myrealbox dot com 25-Feb-2003 05:34
administrator at zinious dot com:

Sorry but your code wasnt soundex compliant
here were my results with your code, my code, and the default..

string: rest
R620 perform administrator's function 0.009452
R230 perform cg's function 0.001779
R230 perform default soundex function 9.4999999999956E-005

string: reset
R620 perform administrator's function 0.0055900000000001
R230 perform cg's function 0.00091799999999997
R230 perform default soundex function 0.00010600000000005

i dunno why the default, every once in a while, will for some reason be 9.xxx. very odd i think..
my code is at the bottom.. these tests were before the soundex modification as i discribe below..
btw for all the original specs on the soundex algorithm goto
http://www.star-shine.net/~functionifelse/GFD/?word=soundex

dalibor dot toth at podravka dot hr:

yes it is perhaps sad that it gives you the same code,
even metaphone has that problem..
but one might not want to be so accurate.. if somone
is on search engine.. lets call it shmoogle looking
for "php array reset" and search for "php array rest"
then shmoogle might return stuff about beds and such..
(if they were all stupid and didnt use the first words
as more important) so anyways shmoogle might need it to
be less accurate in such cases.. but nonetheless..
my fix for this is to add the number of syllables at the end of the string making it 5 characters long..
this would work as fallows..

code at: http://star-shine.net/~functionifelse/cg_soundex.php

or if you wanted to just use the default soundex function

$str = soundex($str).cg_sylc($str);

revolutionary more or less.. problly less...
This function is only meant for one word though.. i'd like to see someone
modify it to use split and run it through a loop to get each words cg_soundex
that'll be fun ;)
i would also like to sujest to the php zend apache kinda people who make php
to add an optional additional variable the user can specify as fallows

soundex("string",SYL);

which would return the number of syllables at the end of the string
highly accurate sound testing woo! also you could add VOW for vowels
and CONS for consonant or whatever else someone would want..
but i really think the number of syllables will be pleanty efficiant.
umm.. if this helps anyone your welcome.. ummm.. good luck in all
your php adventures.. oh... and the final results

syllables
1 rest
2 reset
metaphone
RST rest
RST reset
soundex
R230 rest
R230 reset

string: rest
R2301 perform cg's function 0.00211
R230 perform default soundex function 0.00011299999999997

string: reset
R2302 perform cg's function 0.001691
R230 perform default soundex function 0.00010399999999999

the default function is a tad bit faster..
so maybe they will add this option and we'll have speed and accuracy.

SILENT WIND OF DOOM WOOSH!
jr 16-Jan-2003 09:25
a workaround for the mysql/php differences in implementation of soundex is to do the soundex comparison entirely within mysql.

for example:
$sql = "SELECT * FROM table WHERE substring(soundex(field), 1, 4) =  substring(soundex('".$wordsearch."'), 1, 4)";
info at nederlandsch dot net 20-Dec-2002 05:26
MySQL soundex (3.23.49) doesn't examine the first character at all to see whether it should be skipped. Therefore the Dutch name of The Hague, the country's government seat, 's-Gravenhage will give a soundex value of '261 in MySQL and S615 in PHP.
bestworldweb At yahoo NOSPAM dot co.nz 09-Dec-2002 10:27
Mysql seems to use 0 in the letter V instead of 1, which is what php uses (and most soundex functions)
fred AT oicgroup.net 11-Nov-2002 03:35
I am finding a peculiarity in using the Soundex function in PHP (4.2.2) against the one in MySql (3.23.39) .  For instance, a soundex on the word "purchased" in PHP results in 'P622'.  The same word using the MySql Soundex function results in 'P623'.  The word 'five' using PHP results in 'F100' while MySql results in 'F000'.  I have only caught a couple that are different so far - don't know if it's a bug in either PHP or MySql or something than can be adjusted/accounted for in code.

Fred Dirkse
OIC Group, Inc.
www.oicgroup.net
dalibor dot toth at podravka dot hr 30-Sep-2002 03:50
Apart from Clansy nad Klansy, using strings "rest" and "reset" with soundex() gives you: 1. R230, 2. R230. Pitty...
dcallaghan at linuxmail dot org 10-Jun-2002 04:25
Although the standard soundex string is 4 characters long, and this is what's returned by the php function, some database programs return an arbitrary number of strings. MySQL, for instance.

The MySQL documentation covers this, recommending that you may wish to use substring to output the standard 4 characters. Let's take 'Dostoyevski' as an example.

select soundex("Dostoyevski")
returns D2312
select substring(soundex("Dostoyevski"), 1, 4);
returns D231

PHP will return the value as 'D231'

So, to use the soundex function to generate a WHERE parameter in a MySQL SELECT statement, you might try this:
$s = soundex('Dostoyevski');
SELECT * FROM authors WHERE substring(soundex(lastname), 1 , 4) = "' . $s  . '"';

Or, if you want to bypass the php function
$result = mysql_query("select soundex('Dostoyevski')");
$s = mysql_result($result, 0, 0);
witold4249 at rogers dot com 17-May-2002 10:11
A MUCH easier way to check for similarity between words and avoid the problems that come up with Klancy/Clancy would be to simply add any letter infront of the string

ie:  OKlancy/OClancy
17-May-2002 10:07
A MUCH easier way to do the above search would be to simply add any letter in front of the string and then compare them.

ie. Klancy => LKlancy
    Clancy => LClancy
bb79 at no_spam dot com 10-Apr-2002 01:29
To search for words like Clansy and Klansy, just reverse the strings:

  $s1 = "Clansy";
  $s2 = "Klansy";
  if((soundex($s1) == soundex($s2)) ||
     (soundex(strrev($s1)) == soundex(strrev($s2))))
    echo("Match");
administrator at zinious dot com 09-Apr-2002 08:21
I wrote this function a long time ago in CGI-perl and then translated (if you can call it that) into PHP.  A little clunky to say the least, but should handle true soundex specs 100%:

// ---begin code---

function MakeSoundEx($stringtomakesoundexof)
{
    $temp_Name = $stringtomakesoundexof;
    $SoundKey1 = "BPFV";
    $SoundKey2 = "CSKGJQXZ";
    $SoundKey3 = "DT";
    $SoundKey4 = "L";
    $SoundKey5 = "MN";
    $SoundKey6 = "R";
    $SoundKey7 = "AEHIOUWY";

        $temp_Name = strtoupper($temp_Name);
    $temp_Last = "";
    $temp_Soundex = substr($temp_Name, 0, 1);

    $n = 1;
    for ($i = 0; $i < strlen($SoundKey1); $i++)
    {
            if ($temp_Soundex == substr($SoundKey1, i - 1, 1))
        {
            $temp_Last = "1";
            }
    }
    for ($i = 0; $i < strlen($SoundKey2); $i++)
    {
            if ($temp_Soundex == substr($SoundKey2, i - 1, 1))
        {
            $temp_Last = "2";
            }
    }
    for ($i = 0; $i < strlen($SoundKey3); $i++)
    {
            if ($temp_Soundex == substr($SoundKey3, i - 1, 1))
        {
            $temp_Last = "3";
            }
    }
    for ($i = 0; $i < strlen($SoundKey4); $i++)
    {
            if ($temp_Soundex == substr($SoundKey4, i - 1, 1))
        {
            $temp_Last = "4";
            }
    }
    for ($i = 0; $i < strlen($SoundKey5); $i++)
    {
            if ($temp_Soundex == substr($SoundKey5, i - 1, 1))
        {
            $temp_Last = "5";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "6";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "";
            }
    }

    for ($n = 1; $n < strlen($temp_Name); $n++)
    {
        if (strlen($temp_Soundex) < 4)
        {
            for ($i = 0; $i < strlen($SoundKey1); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey1, $i - 1, 1) && $temp_Last != "1")
                {
                    $temp_Soundex = $temp_Soundex."1";
                    $temp_Last = "1";
                }
            }
            for ($i = 0; $i < strlen($SoundKey2); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey2, $i - 1, 1) && $temp_Last != "2")
                {
                    $temp_Soundex = $temp_Soundex."2";
                    $temp_Last = "2";
                }
            }
            for ($i = 0; $i < strlen($SoundKey3); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey3, $i - 1, 1) && $temp_Last != "3")
                {
                    $temp_Soundex = $temp_Soundex."3";
                    $temp_Last = "3";
                }
            }
            for ($i = 0; $i < strlen($SoundKey4); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey4, $i - 1, 1) && $temp_Last != "4")
                {
                    $temp_Soundex = $temp_Soundex."4";
                    $temp_Last = "4";
                }
            }
            for ($i = 0; $i < strlen($SoundKey5); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey5, $i - 1, 1) && $temp_Last != "5")
                {
                    $temp_Soundex = $temp_Soundex."5";
                    $temp_Last = "5";
                }
            }
            for ($i = 0; $i < strlen($SoundKey6); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey6, $i - 1, 1) && $temp_Last != "6")
                {
                    $temp_Soundex = $temp_Soundex."6";
                    $temp_Last = "6";
                }
            }
            for ($i = 0; $i < strlen($SoundKey7); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey7, $i - 1, 1))
                {
                    $temp_Last = "";
                }
            }
        }
    }

    while (strlen($temp_Soundex) < 4)
    {
        $temp_Soundex = $temp_Soundex."0";
    }

    return $temp_Soundex;
}

// --- end code---
cap at capsi dot cx 13-Dec-1999 07:16
soundex() unfortunately is very sensitive about the first character. It is not possible to use it and have Clansy and Klansy return the same value. If you want to do a phonetic search on such names you will still need to write a routine to evaluate C452 as being similar to K452.
similar_text
sprintf
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє


Возвращает отформатированную строку

soundex
sscanf
Обработка строк
PHP Manual

sprintf

(PHP 4, PHP 5)

sprintf — Возвращает отформатированную строку

Описание

string sprintf ( string $format [, mixed $args [, mixed $... ]] )

Возвращает строку, созданную с использованием строки формата format.

Список параметров

format

Строка формата состоит из нуля и более директив: обычных символов (за исключением %), которые копируются напрямую в результирующую строку, и описателей преобразований, каждый из которых заменяется на один из параметров. Это относится как к sprintf(), так и к printf().

Каждый описатель преобразований состоит из знака процента (%), за которым следует один или более дополнительных элементов (в том порядке, в котором они здесь перечислены):

  1. Необязательный описатель знака, указывающий как знак (- или +) будет применен к числу. По умолчанию, используется только знак минус, если число отрицательное. Этот описатель заставляет положительные числа также отображать знак плюс, он был добавлен в PHP 4.3.0.
  2. Необязательный описатель заполнения, который определяет, какой символ будет использоваться для дополнения результата до необходимой длины. Это может быть пробел или 0. По умолчанию используется пробел. Альтернативный символ может быть указан с помощью одиночной кавычки ('). См. примеры ниже.
  3. Необязательный описатель выравнивания, определяющий выранивание влево или вправо. По умолчанию выравнивается вправо, - используется для выравнивания влево.
  4. Необязательное число, описатель ширины, определяющий минимальное число символов, которое будет содержать результат этого преобразования.
  5. Необязательный описатель точности, указанный в форме точки ('.'), после которой следует необязательная строка из десятичных чисел, определяющая, сколько десятичных разрядов отображать для чисел с плавающей точкой. При использовании со строками этот описатель выступает в роли обрезающей точки, устанавливающей максимальный лимит символов.

  6. Описатель типа, определяющий, как трактовать тип данных аргумента. Допустимые типы:

    • % - символ процента. Аргумент не используется.
    • b - аргумент трактуется как целое и выводится в виде двоичного числа.
    • c - аргумент трактуется как целое и выводится в виде символа с соответствующим кодом ASCII.
    • d - аргумент трактуется как целое и выводится в виде десятичного числа со знаком.
    • e - аргумент трактуется как число в в научной нотации (например, 1.2e+2). Описатель точности указывает на количество знаков после запятой, начиная с версии PHP 5.2.1. В более ранних версиях он обозначал количество значащих цифр (на один знак меньше).
    • E - аналогично %e, но использует заглавную букву (например, 1.2E+2).
    • u - аргумент трактуется как целое и выводится в виде десятичного числа без знака.
    • f - аргумент трактуется как число с плавающей точкой и также выводится в зависимости от локали.
    • F - аргумент трактуется как число с плавающей точкой и также выводится, но без зависимости от локали. Доступно, начиная с версии PHP 4.3.10 и PHP 5.0.3.
    • g - выбирает самую краткую запись из %e и %f.
    • G - выбирает самую краткую запись из %E и %f.
    • o - аргумент трактуется как целое и выводится в виде восьмеричного числа.
    • s - аргумент трактуется как строка.
    • x - аргумент трактуется как целое и выводится в виде шестнадцатиричного числа (в нижнем регистре).
    • X - аргумент трактуется как целое и выводится в виде шестнадцатиричного числа (в верхнем регистре).

В строке формата поддерживается нумерация и изменение порядка параметров. Например:

Пример #1 Изменение порядка параметров

<?php
$num = 5;
$location = 'дереве';

$format = '%d обезьян сидят на %s';
printf($format, $num, $location);
?>
Этот код выведет "5 обезьян сидят на дереве". Теперь представьте, что строка формата содержится в отдельном файле, который потом будет переведен на другой язык, и мы переписываем ее в таком виде:

Пример #2 Изменение порядка параметров

<?php
$format = 'На %s сидят %d обезьян';
printf($format, $num, $location);
?>
Появляется проблема: порядок описателей преобразования не соответствует порядку аргументов. Мы не хотим менять код, и нам нужно указать, какому аргументу соответствует тот или иной описатель преобразования.

Пример #3 Изменение порядка параметров

<?php
$format = 'На %2$s сидят %1$d обезьян';
printf($format, $num, $location);
?>
Нумерация аргументов имеет еще одно применение: она позволяет вывести один и тот же аргумент несколько раз без передачи функции дополнительных параметров.

Пример #4 Изменение порядка параметров

<?php
$format = 'На %2$s сидят %1$d обезьян.
           Как здорово, когда на %2$s сидят %1$d обезьян.';
printf($format, $num, $location);
?>
При изменении порядка параметров описатель позиции n$ должен идти сразу за знаком процента (%) прежде всех остальных описателей, как показано в примере ниже.

Пример #5 Использование описателя позиции и совместо с другими описателями

<?php
$format= 'На %2$s сидят %1$04d обезьян';
printf($format, $num, $location);
?>

Результат выполнения данного примера:

На дереве сидят 0005 обезьян

args

...

Возвращаемые значения

Возвращает строку, отформатированную в соответствии со строкой format.

Список изменений

Версия | Описание
4.0.6 | Добавлена поддержка нумерации/изменения порядка аргументов

Примеры

Пример #6 sprintf(): заполнение нулями

<?php
$n =  43951789;
$u = -43951789;
$c = 65; // ASCII 65 is 'A'

// заметьте, двойной %% выводится как одинарный '%'
printf("%%b = '%b'\n", $n); // двоичное представление
printf("%%c = '%c'\n", $c); // выводит символ ascii, аналогично функции chr()
printf("%%d = '%d'\n", $n); // обычное целое число
printf("%%e = '%e'\n", $n); // научная нотация
printf("%%u = '%u'\n", $n); // беззнаковое целое представление положительного числа
printf("%%u = '%u'\n", $u); // беззнаковое целое представление отрицательного числа
printf("%%f = '%f'\n", $n); // представление числа с плавающей точкой
printf("%%o = '%o'\n", $n); // восьмеричное представление
printf("%%s = '%s'\n", $n); // строка
printf("%%x = '%x'\n", $n); // шестнадцатеричное представление (нижний регистр)
printf("%%X = '%X'\n", $n); // шестнадцатеричное представление (верхний регистр)

printf("%%+d = '%+d'\n", $n); // описатель знака с положительным целым числом
printf("%%+d = '%+d'\n", $u); // описатель знака с отрицательным целым числом
?>

Результат выполнения данного примера:

%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'

Пример #7 printf(): описатели строк

<?php
$s = 'monkey';
$t = 'many monkeys';

printf("[%s]\n",      $s); // обычный вывод строки
printf("[%10s]\n",    $s); // выравнивание вправо с пробелами
printf("[%-10s]\n",   $s); // выравнивание влево с пробелами
printf("[%010s]\n",   $s); // дополнение нулями также работает со строками
printf("[%'#10s]\n",  $s); // использование собственного дополняющего символа '#'
printf("[%10.10s]\n", $t); // выравнивание влево с обрезкой в 10 символов
?>

Результат выполнения данного примера:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]

Пример #8 sprintf(): целые числа, дополненные нулями

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Пример #9 sprintf(): форматирование денежных величин

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money выведет "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted выведет "123.10"
?>

Пример #10 sprintf(): научная нотация

<?php
$number = 362525200;

echo sprintf("%.3e", $number); // выведет 3.625e+8
?>

Смотрите также

  • printf() - Выводит отформатированную строку
  • sscanf() - Разбирает строку в соответствии с заданным форматом
  • fscanf() - Обрабатывает данные из файла в соответствии с форматом
  • vsprintf() - Возвращает отформатированную строку
  • number_format() - Форматирует число с разделением групп

User Contributed Notes

krzysiek dot 333 at gmail dot com - zryty dot hekko dot pl 20-Aug-2011 12:48
Encoding and decoding IP adress to format: 1A2B3C4D (mysql column: char(8) )

<?php
function encode_ip($dotquad_ip)
{
    $ip_sep = explode('.', $dotquad_ip);
    return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}

function decode_ip($int_ip)
{
    $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
    return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>
timo dot frenay at gmail dot com 02-May-2011 05:38
Here is how to print a floating point number with 16 significant digits regardless of magnitude:

<?php
    $result = sprintf(sprintf('%%.%dF', max(15 - floor(log10($value)), 0)), $value);
?>

This works more reliably than doing something like sprintf('%.15F', $value) as the latter may cut off significant digits for very small numbers, or prints bogus digits (meaning extra digits beyond what can reliably be represented in a floating point number) for very large numbers.
andrejsstepanovs at gmail dot com 21-Apr-2011 07:13
Use this function to ignore warning "Too few arguments".

<?php
/**
 * Ignores php E_WARNING "sprintf(): Too few arguments".
 * If parameters is too fiew, then this function add extra empty parameter and try again.
 * Working in recursion.
 *
 * @param string $template
 * @param mixed $parameters
 * @return string
 */
function my_sprintf($template, $parameters){
   if(!function_exists('handleError')){//initialize new error handler function
      function handleError($errno, $errstr, $errfile, $errline, array $errcontext){
         throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
      }
      set_error_handler('handleError');
   }

   if(!is_array($parameters)){//manage parameters to allow string
      $parameters = array($parameters);
   }

   try{//trying to execute function. if warning is received, then add parameter
      eval('$return = sprintf($template, "'.implode('","', $parameters).'");');
      return $return;
   }catch(ErrorException $e){
      array_push($parameters, null);
      return my_sprintf($template, $parameters);
   }
}
?>
carmageddon at gmail dot com 02-Feb-2011 06:38
If you want to convert a decimal (integer) number into constant length binary number in lets say 9 bits, use this:

$binary = sprintf('%08b', $number );

for example:
<?php
$bin = sprintf('%08b',511 );
echo $bin."\n";
?>

would output 111111111
And 2 would output 00000010

I know the leading zeros are useful to me, perhaps they are to someone else too.
dwieeb at gmail dot com 01-Sep-2010 11:54
If you use the default padding specifier (a space) and then print it to HTML, you will notice that HTML does not display the multiple spaces correctly. This is because any sequence of white-space is treated as a single space.

To overcome this, I wrote a simple function that replaces all the spaces in the string returned by sprintf() with the character entity reference "&nbsp;" to achieve non-breaking space in strings returned by sprintf()

<?php
//Here is the function:
function sprintf_nbsp() {
   $args = func_get_args();
   return str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}

//Usage (exactly like sprintf):
$format = 'The %d monkeys are attacking the [%10s]!';
$str = sprintf_nbsp($format, 15, 'zoo');
echo $str;
?>

The above example will output:
The 15 monkeys are attacking the [       zoo]!

<?php
//The variation that prints the string instead of returning it:
function printf_nbsp() {
   $args = func_get_args();
   echo str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}
?>
geertdd at gmail dot com 01-Sep-2010 12:53
Note that when using a sign specifier, the number zero is considered positive and a "+" sign will be prepended to it.

<?php
printf('%+d', 0); // +0
?>
nate at frickenate dot com 13-Nov-2009 11:45
Here's a clean, working version of functions to allow using named arguments instead of numeric ones. ex: instead of sprintf('%1$s', 'Joe');, we can use sprintf('%name$s', array('name' => 'Joe'));. I've provided 2 different versions: the first uses the php-like syntax (ex: %name$s), while the second uses the python syntax (ex: %(name)s).

<?php

/**
 * version of sprintf for cases where named arguments are desired (php syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %second$s ; first: %first$s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)([a-zA-Z_]\w*)(?=\$)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key], $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

/**
 * version of sprintf for cases where named arguments are desired (python syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %(second)s ; first: %(first)s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)\(([a-zA-Z_]\w*)\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

?>
Astone 15-Sep-2009 11:41
When you're using Google translator, you have to 'escape' the 'conversion specifications' by putting <span class="notranslate"></span> around them.

Like this:

<?php

function getGoogleTranslation($sString, $bEscapeParams = true)
{
    // "escape" sprintf paramerters
    if ($bEscapeParams)
    {
        $sPatern = '/(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
        $sEscapeString = '<span class="notranslate">$0</span>';
        $sString = preg_replace($sPatern, $sEscapeString, $sString);
    }

    // Compose data array (English to Dutch)
    $aData = array(
        'v'            => '1.0',
        'q'            => $sString,
        'langpair'    => 'en|nl',
    );

    // Initialize connection
    $rService = curl_init();

    // Connection settings
    curl_setopt($rService, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/language/translate');
    curl_setopt($rService, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($rService, CURLOPT_POSTFIELDS, $aData);

    // Execute request
    $sResponse = curl_exec($rService);

    // Close connection
    curl_close($rService);

    // Extract text from JSON response
    $oResponse = json_decode($sResponse);
    if (isset($oResponse->responseData->translatedText))
    {
        $sTranslation = $oResponse->responseData->translatedText;
    }
    else
    {
        // If some error occured, use the original string
        $sTranslation = $sString;
    }

    // Replace "notranslate" tags
    if ($bEscapeParams)
    {
        $sEscapePatern = '/<span class="notranslate">([^<]*)<\/span>/';
        $sTranslation = preg_replace($sEscapePatern, '$1', $sTranslation);
    }

    // Return result
    return $sTranslation;
}

?>

Thanks to MelTraX for defining the RegExp!
Jay Gilford 25-Aug-2009 05:13
I created this function a while back to save on having to combine mysql_real_escape_string onto all the params passed into a sprintf. it works literally the same as the sprintf other than that it doesn't require you to escape your inputs. Hope its of some use to people

<?php
function mressf()
{
    $args = func_get_args();
    if (count($args) < 2)
        return false;
    $query = array_shift($args);
    $args = array_map('mysql_real_escape_string', $args);
    array_unshift($args, $query);
    $query = call_user_func_array('sprintf', $args);
    return $query;
}
?>

Regards
Jay
Jaygilford.com
jfgrissom at gmail dot com 11-Jul-2009 09:51
I had a nightmare trying to find the two's complement of a 32 bit number.

I got this from http://www.webmasterworld.com/forum88/13334.htm (credit where credit is due... =P  )

Quote: ...find out the 2's complement of any number, which is -(pow(2, n) - N) where n is the number of bits and N is the number for which to find out its 2's complement.

This worked magic for me... previously I was trying to use

sprintf ("%b",$32BitDecimal);
But it always returned 10000000000000000000000 when the $32BitDecimal value got above 2,000,000,000.

This -(pow(2, n) - N)
Worked remarkably well and was very accurate.

Hope this helps someone fighting with two's complement in PHP.
John Walker 09-Jul-2009 05:56
To add to other notes below about floating point problems, I noted that %f and %F will apparently output a maximum precision of 6 as a default so you have to specify 1.15f (eg) if you need more.

In my case, the input (from MySQL) was a string with 15 digits of precision that was displayed with 6. Likely what happens is that the rounding occurs in the conversion to a float before it is displayed. Displaying it as 1.15f (or in my case, %s) shows the correct number.
viktor at textalk dot com 18-Feb-2009 08:16
A more complete and working version of mb_sprintf and mb_vsprintf. It should work with any "ASCII preserving" encoding such as UTF-8 and all the ISO-8859 charsets. It handles sign, padding, alignment, width and precision. Argument swapping is not handled.

<?php
if (!function_exists('mb_sprintf')) {
  function mb_sprintf($format) {
      $argv = func_get_args() ;
      array_shift($argv) ;
      return mb_vsprintf($format, $argv) ;
  }
}
if (!function_exists('mb_vsprintf')) {
  /**
   * Works with all encodings in format and arguments.
   * Supported: Sign, padding, alignment, width and precision.
   * Not supported: Argument swapping.
   */
  function mb_vsprintf($format, $argv, $encoding=null) {
      if (is_null($encoding))
          $encoding = mb_internal_encoding();

      // Use UTF-8 in the format so we can use the u flag in preg_split
      $format = mb_convert_encoding($format, 'UTF-8', $encoding);

      $newformat = ""; // build a new format in UTF-8
      $newargv = array(); // unhandled args in unchanged encoding

      while ($format !== "") {

        // Split the format in two parts: $pre and $post by the first %-directive
        // We get also the matched groups
        list ($pre, $sign, $filler, $align, $size, $precision, $type, $post) =
            preg_split("!\%(\+?)('.|[0 ]|)(-?)([1-9][0-9]*|)(\.[1-9][0-9]*|)([%a-zA-Z])!u",
                       $format, 2, PREG_SPLIT_DELIM_CAPTURE) ;

        $newformat .= mb_convert_encoding($pre, $encoding, 'UTF-8');

        if ($type == '') {
          // didn't match. do nothing. this is the last iteration.
        }
        elseif ($type == '%') {
          // an escaped %
          $newformat .= '%%';
        }
        elseif ($type == 's') {
          $arg = array_shift($argv);
          $arg = mb_convert_encoding($arg, 'UTF-8', $encoding);
          $padding_pre = '';
          $padding_post = '';

          // truncate $arg
          if ($precision !== '') {
            $precision = intval(substr($precision,1));
            if ($precision > 0 && mb_strlen($arg,$encoding) > $precision)
              $arg = mb_substr($precision,0,$precision,$encoding);
          }

          // define padding
          if ($size > 0) {
            $arglen = mb_strlen($arg, $encoding);
            if ($arglen < $size) {
              if($filler==='')
                  $filler = ' ';
              if ($align == '-')
                  $padding_post = str_repeat($filler, $size - $arglen);
              else
                  $padding_pre = str_repeat($filler, $size - $arglen);
            }
          }

          // escape % and pass it forward
          $newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post;
        }
        else {
          // another type, pass forward
          $newformat .= "%$sign$filler$align$size$precision$type";
          $newargv[] = array_shift($argv);
        }
        $format = strval($post);
      }
      // Convert new format back from UTF-8 to the original encoding
      $newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8');
      return vsprintf($newformat, $newargv);
  }
}
?>
splogamurugan at gmail dot com 06-Feb-2009 05:59
$format = 'There are %1$d monkeys in the %s and %s ';
printf($format, 100, 'Chennai', 'Bangalore');

Expecting to output
"There are 100 monkeys in the Chennai and bangalore"

But, this will output
"There are 100 monkeys in the 100 and Chennai"

Because, the second and Third specifiers takes 1rst and 2nd arguments. Because it is not assigned with any arguments.
remy dot damour at -please-no-spam-laposte dot net 15-Jan-2009 11:15
With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'.

Ie. to print '%' character you need to escape it with itself:
<?php
printf('%%%s%%', 'koko'); #output: '%koko%'
?>
MelTraX 05-Nov-2008 01:40
<?php
  // parses a string meant for printf and returns an array of found parameters (or NULL if it contains syntax errors)
  function parsePrintfParameters($string) {
    $valid = '/^(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
    $originalString = $string;

    $result = array();
    while(strlen($string)) {
      if(!$string = preg_replace('/^[^%]*/', '', $string))
        break;

      if(preg_match($valid, $string, $matches)) {
        $result[] = $matches[0];
        $string = substr($string, strlen($matches[0]));
      } else {
        error(sprintf('"%s" has an error near "%s".', $originalString, $string));
        return NULL;
      }
    }
    return $result;
  }
?>
savannah at seznam dot cz 12-Oct-2008 04:29
If you have problems using utf-8 with string paddings, you can use this function:

<?php
/**
 * Formats string using sprintf, but correctly handles %s  with space paddings
 *
 * uses conversion to iso-8859-2 and back
 *
 * it is, however, much slower, so use only when needed!
 *
 * @param string $format
 */
function utf_8_sprintf ($format) {
  $args = func_get_args();

  for ($i = 1; $i < count($args); $i++) {
    $args [$i] = iconv('UTF-8', 'ISO-8859-2', $args [$i]);
  }

  return iconv('ISO-8859-2', 'UTF-8', call_user_func_array('sprintf', $args));
}

// test

echo sprintf ("[%-20s]\n", 'escrzyaie'); //  how it should look without special chars
echo sprintf ("[%-20s]\n", 'ěščřžýáíé'); // not correctly handled by php
echo utf_8_sprintf ("[%-20s]\n", 'ěščřžýáíé'); // using above function

/*
produces:
[escrzyaie           ]
[ěščřžýáíé  ]
[ěščřžýáíé           ]
*/

?>
the trick is to convert arguments to iso8859-2 and result back to utf-8.
php at mikeboers dot com 01-Oct-2008 01:42
And continuing on the same theme of a key-based sprintf...

I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of Python's string formatting with a dictionary. The improvement over the several past attempts is that this one still respects all of the formating options, as you can see in my example.

And the error handling is really crappy (just an echo). I just threw this together so do with it what you will. =]

<?php

function sprintf_array($string, $array)
{
    $keys    = array_keys($array);
    $keysmap = array_flip($keys);
    $values  = array_values($array);

    while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
    {
        if (!isset($keysmap[$m[1]]))
        {
            echo "No key $m[1]\n";
            return false;
        }

        $string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
    }

    array_unshift($values, $string);
    var_dump($values);
    return call_user_func_array('sprintf', $values);
}

echo sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));

?>

Cheers!
ant at loadtrax dot com 18-Jun-2008 02:19
Rounding seems a little inconsistent, so beware:

$ php -a

php> print round(1.0*20*1.175/100,2);
0.24
php > print sprintf("%.2f",1.0*20*1.175/100);
0.23
php > print sprintf("%.0f",1.0*20*1.175);
24

I get round this by doing the round first, then doing the sprintf.
jaimthorn at yahoo dot com 11-Jun-2008 07:01
I needed a piece of code similar to the one Matt posted below, on the 10th of March, 2008.  However, I wasn't completely satisfied with Matt's code (sorry, Matt!  No offense intended!), because

1) I don't like to initialize variables when it's not really needed, and
2) it contains two bugs.

What are the bugs?

First, Matt's code tests for count($vars) > 0, but if $var == "Hello world!", then count($var) == 1, but the foreach() will crash because $var has to be an array.  So instead, my code tests for is_array($var).

Second, if a key in $vars is a prefix of any of the later keys in the array (like 'object' is the beginning of 'objective') then the str_replace messes things up.  This is no big deal if your keys are hard-coded and you can make sure the keys don't interfere, but in my code the keys are variable.  So I decided to first sort the array on a decreasing length of the key.

<?php

function cmp($a, $b)
{
    return strlen($b) - strlen($a);
}

function sprintf2($str, $vars, $char = '%')
{
    if(is_array($vars))
    {
        uksort($vars, "cmp");

        foreach($vars as $k => $v)
        {
            $str = str_replace($char . $k, $v, $str);
        }
    }

    return $str;
}

echo sprintf2( 'Hello %your_name, my name is %my_name! I am %my_age, how old are you? I like %object and I want to %objective_in_life!'
             , array( 'your_name'         => 'Matt'
                    , 'my_name'           => 'Jim'
                    , 'my_age'            => 'old'
                    , 'object'            => 'women'
                    , 'objective_in_life' => 'write code'
                    )
             );

?>

If possible, and if you're willing, you can also embed the key fields in the text between percent-signs, rather than prefixing the keys with one.  Sorting is no longer necessary, and the execution time is less than half of the code above:

<?php

function sprintf3($str, $vars, $char = '%')
{
    $tmp = array();
    foreach($vars as $k => $v)
    {
        $tmp[$char . $k . $char] = $v;
    }
    return str_replace(array_keys($tmp), array_values($tmp), $str);
}

echo sprintf3( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
             , array( 'your_name'         => 'Matt'
                    , 'my_name'           => 'Jim'
                    , 'my_age'            => 'old'
                    , 'object'            => 'women'
                    , 'objective_in_life' => 'write code'
                    )
             );
?>

If you're willing to embed the keys in the text, you may also be willing to embed the keys themselves in percent signs, thus shaving off another 30% of the execution time:

<?php

function sprintf4($str, $vars)
{
    return str_replace(array_keys($vars), array_values($vars), $str);
}

echo sprintf4( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
             , array( '%your_name%'         => 'Matt'
                    , '%my_name%'           => 'Jim'
                    , '%my_age%'            => 'old'
                    , '%object%'            => 'women'
                    , '%objective_in_life%' => 'write code'
                    )
             );
?>

Of course, by now the sprintf function is no longer something you'd want to write to mum and dad about...
ranema at ubuntu dot polarhome dot com 30-Mar-2008 07:40
It's very comfortible for long Sql queries:

<?php
$_gQuery = "UPDATE `x` SET `a` = %i AND `b` = '%s' WHERE `my` = '%s';"; // ........

mysql_query( sprintf( $_gQuery, 10, 'a', 'rrrr' ) );
?>

But if you have a short query, then it would be much faster to append your data by using `.`.

<?php
$_gQuery = 'SELECT COUNT(*) FROM `' . $_gName . '`;';
?>
matt 10-Mar-2008 09:13
Was looking for a assoc way of using sprintf but couldnt find one, probably wasnt looking hard enough so came up with this. Very very simple indeed...

<?php

function sprintf2($str='', $vars=array(), $char='%')
{
    if (!$str) return '';
    if (count($vars) > 0)
    {
        foreach ($vars as $k => $v)
        {
            $str = str_replace($char . $k, $v, $str);
        }
    }

    return $str;
}

echo sprintf2('Hello %your_name my name is %my_name! I am %my_age, how old are you? I like %object!', array(
    'your_name' => 'Ben',
    'my_name' => 'Matt',
    'my_age' => '21',
    'object' => 'food'
));

// Hello Ben my name is Matt! I am 21, how old are you? I like food!

?>

Looks nice anyway :)
andyhaslam at hotmail dot com 05-Feb-2008 09:46
An interesting bug, if you do the following:

$val = 2345.35;
$val = sprintf("%01.2f", $val);
echo $val;

Output is "2.00", instead of "2345.35". The solution is to use an intermediate variable:

$val = 2345.35;
$val2 = sprintf("%01.2f", $val);
$val = $val2;
echo $val;
scott dot gardner at mac dot com 10-Jan-2008 01:22
In the last example of Example#6, there is an error regarding the output.

printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters

This outputs right-justified.

In order to output left-justified:

printf("[%-10.10s]\n", $t);
me at umarfarooq dot net 06-Sep-2007 11:29
/**
This function returns a formated  string with the legnth you specify
@string holds the string which you want to format
@len holds the length you want to format
**/
function formatString($string, $len)
{
    if (strlen($string) < $len)
    {
        $addchar=($len - strlen($string)) ;
        for ($i = 0; $i < $addchar; $i++)
        {
            $string=sprintf("$string%s", "0");
        }
    }

    if (strlen($string) > $len)
    {
        $string=substr($string,0,$len);
    }

    return $string;
}
Thomas Breuss 11-May-2007 12:03
Note:
If you want to use % in sprintf, you have to "quote" it like %%.

Example:
echo sprintf("Green => %d%%'", 50);

Output:
Green => 50%
eagle at electric-force dot net 27-Mar-2007 11:25
Display an binary string like an Hex Editor.

<?php
function BinToHexView($binstr) {
    $HexView = "";

    $binpos = 0;
    $binsize = strlen($binstr);
    $binr = ( ($binsize-$binpos-16) > 16 ? 16 : $binsize-$binpos-16 );

    while ($binr > 0) {
        $hline = "";
        $dline = "";
        $HexView .= sprintf("%04x", $binpos);
        for ($c=0;$c<$binr;$c++) {
            $hline .= sprintf("%02x",ord($binstr[$binpos+$c]))." ";
        }
        for ($c=0;$c<$binr;$c++) {
            $ord = ord($binstr[$binpos+$c]);
            $dline .= ( $ord<32 || $ord>126 ? "." : $binstr[$binpos+$c] );
        }
        $HexView .= sprintf("  %-48s  %-16s\n", $hline, $dline);
        $binpos += $binr;
        $binr = ( ($binsize-$binpos-16) > 16 ? 16 : $binsize-$binpos-16 );
    }

    return $HexView;
}
?>
29-Jan-2007 10:15
In response to juan at ecogomera dot com:

I think what you want is:

$x = 3327
$y=decbin($x);
echo $y."<br>";
$z = sprintf("%012d", $x);
echo $z;

3327
110011111111
000000003327

Right? You were double-converting the number. First to binary, then again to decimal. You should be converting the source number directly into the required base.
SWestrup 09-Nov-2006 11:46
In response to Anonymous, who claimed that:

  printf("[%s]\n", str_pad('Hello', 20));

and

  printf("[%-20s]\n", 'Hello');

are the same thing: you've missed the point.

They're only the same when the amount of padding is a known constant. When its a variable (or an expression), its often much more convenient to be able to write:

  printf("[%-*s]\n", 3*$n+2, "Hello");

than what you have to go through now, which is either:

  $t = 3*$n+2;
  printf("[%-{$t}s]\n","Hello");

or

  printf("[%s]\n", str_pad('Hello', 3*$n+2));
Anonymous 16-Oct-2006 04:04
In response to Fredrik Rambris in the com top domain:

<?php

//Your code:

printf("[%s]\n", str_pad('Hello', 20));

//Is the same as:

printf("[%-20s]\n", 'Hello');

?>
Fredrik Rambris in the com top domain 28-Sep-2006 02:48
The C implementation of printf (alteast in glibc) can handle field length as arguments like this:

printf("[%-*s]\n", (int)20, "Hello");

To have the same result in PHP you need to run

printf("[%s]\n, str_pad("Hello", 20) );

It would be nice if one could use the field length directly like in C.
Moore (at) Hs-Furtwangen (dot) De 12-Aug-2006 11:54
Here a litle function that might come handy one time:
It gives back a String and adds a <BR> (you can change it to <br />) to every line end. And it adds $num blanks to the front of the next line.

<?php
 function nl2brnl($text, $num)
  {
   return preg_replace("/\\r\\n|\\n|\\r/", sprintf("% -".(5+$num)."s","<BR>\\n"), $text);
  }

$a = " one\\n two\\r\\n three";

$b = nl2brnl($a, 2);

var_dump($b);

/* output will be:
string(30) " one<BR>
   two<BR>
   three"
*/

echo "  <P>\\n   ";
echo $b

/* output will be:
  <P>
   one<BR>
   two<BR>
   three
*/
?>
Is helpfull for avouding code_soup.
bknakkerNO at SPAMgmail dot com 10-Aug-2006 02:54
Note that in PHP5 (.1.4 for me) sprintf will not use the __toString function of an object.

<?php
class pr{
private $l;
public function __construct($l)
{
$this->l=$l;
}
public function __toString()
{
return $this->l;
}
}
echo new pr('This works!!'); //This will display 'This works!!'
echo sprintf(new pr('This doesnt')); // will display 'Object'
?>

Be careful with that!
Ulf Wostner 06-Aug-2006 10:35
<?php
#-----------------------------------------------------
# Viewing Two's Complement using sprintf formatting.
#-----------------------------------------------------
# Systems using Two's Complements have exactly one number that equals its own Two's Complement.
# On a 32-bit system look at  1000 0000 0000 0000  for  -2147483648
# Take the one's complement, to get 0111 1111 1111 1111, add 1
# to get the Two's Complement: 1000 0000 0000 0000
#  We are back to the original number, the so-called Weird Number for 32-bits.

# For a 64-bit system, format that number as binary, width 64, padded with 0's.

printf("%064b\n", -2147483648);

# Output with added spaces:
# 11111111 11111111 11111111 11111111 10000000 00000000 00000000 00000000

# And here is the Two's Complement on a 64-bit system.

printf("%064b\n", +2147483648);

# Output with added spaces:
# 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000000
# They share those last 32 bits, accounting for the 32-bit Weird Number.

#----------------------------------------------------------
# Is PHP running  32-bit or 64-bit?
#----------------------------------------------------------
# Sure, we can look at the max int, but  The Weird Number  also tells if we are in 32-bit, 64-bit, or ...

function getBitCount() {
  $how_many_bits = 1;  $n = 2;
  while(True) {
    $how_many_bits += 1;   $n *= 2;  # powers of 2
    # matches its own two's complement?
    if( sprintf("%b", $n) == sprintf("%b", -$n)  )
      return 1 + $how_many_bits;
  }
  return;
}
?>
egingell at sisna dot com 26-Apr-2006 01:51
<?
/**
 * [string or int] vprint ( string $format [, mixed $ary [, bool $return]] )
 *
 * Closely mimics the functionality of sprintf(), printf(), vprintf(), and vsprintf().
 *
 * Replaces %[bcdeufFosxX] with each element of $ary
 *     See http://us3.php.net/manual/en/function.sprintf.php for details on replacement types.
 *
 * If there are not enough elements in $ary (or it is left out) to satisfy $format,
 *     it will be padded to the correct length.
 *
 * Since v*printf() doesn't mind having too many elements in the array, $format will be left alone.
 *
 * If $ary is a string, it will be recast into an array.
 *
 * If $return is set to a value considered to be false (0, '', null, false, and array()),
 *     then the output will be sent to STDOUT and the strlen() of the output string will be returned;
 *     otherwise, the output string will be returned.
 *
 * It's buggy when using the argument swapping functionality, unless you do it propperly.
 *
 * May break when using modifiers (%.4e, %02s, etc), unless you do it propperly.
 **/
function vprint($format, $ary = array(), $return = true) {
    // Sanity?!
    if (!is_array($ary)) $ary = array($ary);

    // Find %n$n.
    preg_match_all('#\\%[\\d]*\\$[bcdeufFosxX]#', $format, $matches);

    // Weed out the dupes and count how many there are.
    $counts = count(array_unique($matches[0]));

    // Count the number of %n's and add it to the number of %n$n's.
    $countf = preg_match_all('#\\%[bcdeufFosxX]#', $format, $matches) + $counts;

    // Count the number of replacements.
    $counta = count($ary);

    if ($countf > $counta) {
        // Pad $ary if there's not enough elements.
        $ary = array_pad($ary, $countf, "&nbsp;");
    }

    if ($return) {
        return vsprintf($format, $ary);
    } else {
        return vprintf($format, $ary);
    }
}

?>
mauf at franzoni dot info 16-Feb-2006 07:21
The format of floating values has been previously reporting as depending on platform (linux / windows) yet I see it changes within two linux systems depending on the version:
In V4.2.2 "%3.2" displays 3 integers and two decimals (i.e. the first digit represents just the number of integer digits), on V4.4.1 the same displays (and justifies the string to) a three character string (i.e. the first digit is the total lenght of the number, including the decimal dot).

Maybe someone may better specify which version this happens from.
darkfalconIV at hotmail dot com 18-Dec-2005 12:57
henke dot andersson

You can accomplish feeding it array if you use call_user_func_array. Not exactly a `clean' option, but it does work.
tim dot brouckaert dot NOSPAM at gmail dot com 12-Oct-2005 05:35
If you want to center align some text using the printf or sprintf functions, you can just use the following:

function center_text($word){
    $tot_width = 30;
    $symbol = "-";
    $middle = round($tot_width/2);
    $length_word = strlen($word);
    $middle_word = round($length_word / 2);
    $last_position = $middle + $middle_word;
    $number_of_spaces = $middle - $middle_word;

    $result = sprintf("%'{$symbol}{$last_position}s", $word);
        for ($i = 0; $i < $number_of_spaces; $i++){
            $result .= "$symbol";
        }
    return $result;
}

$string = "This is some text";
print center_text($string);

off course you can modify the function to use more arguments.
webmaster at cafe-clope dot net 14-Aug-2005 09:47
trying to fix the multibyte non-compliance of sprintf, I came to that :

<?php
function mb_sprintf($format) {
    $argv = func_get_args() ;
    array_shift($argv) ;
    return mb_vsprintf($format, $argv) ;
}

function mb_vsprintf($format, $argv) {
    $newargv = array() ;

    preg_match_all("`\%('.+|[0 ]|)([1-9][0-9]*|)s`U", $format, $results, PREG_SET_ORDER) ;

    foreach($results as $result) {
        list($string_format, $filler, $size) = $result ;
        if(strlen($filler)>1)
            $filler = substr($filler, 1) ;
        while(!is_string($arg = array_shift($argv)))
            $newargv[] = $arg ;
        $pos = strpos($format, $string_format) ;
        $format = substr($format, 0, $pos)
                  . ($size ? str_repeat($filler, $size-strlen($arg)) : '')
                    . str_replace('%', '%%', $arg)
                    . substr($format, $pos+strlen($string_format))
                    ;
    }

    return vsprintf($format, $newargv) ;
}

?>

handle with care :
1. that function was designed mostly for utf-8. i guess it won't work with any static mb encoding.
2. my configuration sets the mbstring.func_overload configuration directive to 7, so you may wish to replace substr, strlen, etc. with mb_* equivalents.
3. since preg_* doesn't complies with mb strings, I used a '.+' in the regexp to symbolize an escaped filler character. That means, %'xy5s pattern will match, unfortunately. It is recomended to remove the '+', unless you are intending to use an mb char as filler.
4. the filler fills at left, and only at left.
5. I couldn't succeed with a preg_replace thing : the problem was to use the differents lengths of the string arguements in the same replacement, string or callback. That's why the code is much longuer than I expected.
6. The pattern wil not match any %1\$s thing... just was too complicated for me.
7. Although it has been tested, and works fine within the limits above, this is much more a draft than a end-user function. I would enjoy any improvment.

The test code below shows possibilities, and explains the problem that occures with an mb string argument in sprintf.

<?php
header("content-type:text/plain; charset=UTF-8") ;
$mb_string = "x�x�x" ;
echo sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(sprintf("%010s", $mb_string)), " characters]\n" ;
echo mb_sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(mb_sprintf("%010s", $mb_string)), " characters]\n" ;
echo "\n" ;
echo mb_sprintf("%''10s\n%'010s\n%'�10s\n%10d\n%'x10s\n%010s\n% 10s\n%010s\n%'1s\n", "zero", "one", "two", 3, "four", "��ve", "%s%i%x", "��ve�", "eight") ;
?>
david at rayninfo dot co dot uk 16-Jun-2005 11:33
Using sprintf to force leading leading zeros

foreach (range(1, 10) as $v) {echo "<br>tag_".sprintf("%02d",$v);}

displays
tag_01
tag_02
tag_03
.. etc
ian dot w dot davis at gmail dot com 30-May-2005 07:03
Just to elaborate on downright's point about different meanings for %f, it appears the behavior changed significantly as of 4.3.7, rather than just being different on different platforms. Previously, the width specifier gave the number of characters allowed BEFORE the decimal. Now, the width specifier gives the TOTAL number of characters. (This is in line with the semantics of printf() in other languages.) See bugs #28633 and #29286 for more details.
Pacogliss 02-May-2005 12:08
Just a reminder for beginners : example 6 'printf("[%10s]\n",    $s);' only works (that is, shows out the spaces) if you put the html '<pre></pre>' tags ( head-scraping time saver ;-).
christian at wenz dot org 18-Apr-2005 12:20
@ henke dot andersson at comhem dot se: Use vprintf()/vsprintf() for that.
henke dot andersson at comhem dot se 15-Apr-2005 08:07
Mind that it doesn't allow you to use a array as multiple arguments like this:
<?php
printf('%s %s',array('a','b')) ?>
downright at comcast dot net 31-Jan-2005 02:03
Just thought I'd give a heads up for anyone doing cross platform applications.

sprintf spacing is different numerically with Windows and Linux.

Linux aligned correctly:
$ol = sprintf ("%-6s|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f\n",

Windows aligned correctly:
$ol = sprintf ("%-6s|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f\n",

As you can see the strings are fine for spacing, however, the numbers need a difference of 3 in order to have the same amount of spaces.

I noticed this after using sprintf to format a header for a web app I was working on.  On windows it fit, however, when it came to linux it was MUCH larger than the header.
jrpozo at conclase dot net 21-Jan-2005 07:13
Be careful if you use the %f modifier to round decimal numbers as it (starting from 4.3.10) will no longer produce a float number if you set certain locales, so you can't accumulate the result. For example:

setlocale(LC_ALL, 'es_ES');
echo(sprintf("%.2f", 13.332) + sprintf("%.2f", 14.446))

gives 27 instead of 27.78, so use %F instead.
timo at frenay dot net 10-Jan-2005 10:58
Note that the documentation is unclear about the details of the sign specifier. First of all, the character for this is "+".

Also note that the following does NOT print "+00.00" as you might expect:

<?php
    printf('%+02.2f', 0);
?>

The sign is included in the width. This can't be solved by increasing the width:

<?php
    printf('%+03.2f', 0);
?>

This will put the padding 0 before the sign.
Here is a possible solution:

<?php
    $value = 0;
    printf('%s%02.2f', ($value < 0) ? '-' : '+', abs($value));
?>
Gkeeper80 11-Aug-2004 03:58
When using sprintf with padding, it's important to note that specifying the length of your padding does not restrict the length of your output.

For example:
$var = 'test';
$output sprintf("%03s", $var);

print $output;

Produces:
test

NOT:
est

This may seem intuitive for working with numbers, but not neccesarily when working with strings.
rex 15-Jun-2004 02:47
Note, if you are just looking for something to pad out a string consider str_pad.

From testing, it seems faster and was more intuitive to use (for example, making it pad the begining or end of a string... with sprintf you would have to use negative indexes)
php at sharpdreams dot com 08-May-2004 02:13
Note that when using the argument swapping, you MUST number every argument, otherwise sprintf gets confused. This only happens if you use number arguments first, then switch to a non-numbered, and then back to a numbered one.

<?php
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Wont work:
// Sprintf will complain about not enough arguments.
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%3\$s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Will work: note the %3\$s
?>
tobias at silverxnet dot de 16-Apr-2004 07:09
Regarding the previous posting:
I just wanted to give an explanation. This should be because the float to string / integer to string conversion (you are using a string, multiplying it with a float value what php automatically causes to convert the string to a float value). This is a general "problem" (or not), but not that hard to explain.
Where an integer or float starts with 0, in a string it does obviously with 1. So if you are using a string your value will increase by one (You started with a string, so it does not increase but contain the real result. If you start using a float value by not using '' around the value, you have to output the float value as well. This is just the PHP conversion.)

Try putting
$x = strval( $x );
after
$x = $x * 100;
and using your example again. You will see that the output will change to 13664 = 13664 because of the general string conversion. It seems that PHP is converting a float to a string by inceasing by one. By doing the same with intval instead of strval the output changes to 13663 = 13663.

! sprintf seems to behave wrong when using the conversation to an integer value and NOT doing the conversation at all. So use intval to convert to an integer value or strval to convert to a string value BEFORE using sprintf. This should be solving the problems.
kekec at kukac dot hu 29-Mar-2004 09:16
A really working one:
<?php
function cutzero($value) {
   return preg_replace("/(\.?)0+$/", "", $value);
}
?>
05-Mar-2004 10:54
both of your cut-zero functions are just way too complicated. if it's a string where only the zeros at the end should be truncated, why not use a syntax as simple as rtrim("4.7000","0") ?
Rene dot Leonhardt at agritec24 dot com 16-May-2003 10:02
Your cutzero function could be faster ;-)
   return (double)$value;

But if you must have a function:
   return preg_replace('/0+$/', '', $value);
kouber at php dot net 08-May-2003 02:55
If you want to cut all the zeros off the end of a float, but not losing any sensitive information, use this:

<?
function cutzero($value) {
    return preg_replace("/(\.\d+?)0+$/", "$1", $value)*1;
}
?>

Some examples:

<?
cutzero("4.7600");     // returns 4.76
cutzero("4.7604")      // returns 4.7604
cutzero("4.7000");     // returns 4.7
cutzero("4.0000");     // returns 4
?>
info at nospam dot webtip dot dk 18-Feb-2003 05:06
If you want to format a phonenumber with spaces, use chunk_split() which splits a string into smaller chunks. It's much simpler than using sprintf.

$phone = "12345678";

chunk_split ($phone, 2);

will return 12 34 56 78
moritz dot geselle at invision-team dot de 02-Dec-2002 02:52
a little note to the argument swapping examples which took me a while to get:
if you use single quotes for the format string (like you should do, since there aren't any variable conversions to do as long as you don't need any special chars), the given examples won't work because of the backslash before the $ (needs to be escaped in double quoted strings - but not in single quoted!)

so this:

$format = "The %2\$s contains %1\$d monkeys";
printf($format,$num,$location);

with a single quoted format string would look like this:

$format = 'The %2$s contains %1$d monkeys';
printf($format,$num,$location);

(no escapes)

I hope that helps to avoid confusion ;)
no dot email dot address at example dot com 16-Sep-2002 06:29
Using argument swapping in sprintf() with gettext: Let's say you've written the following script:

<?php
$var = sprintf(gettext("The %2\$s contains %1\$d monkeys"), 2, "cage");
?>

Now you run xgettext in order to generate a .po file. The .po file will then look like this:

#: file.php:9
#, ycp-format
msgid "The %2\\$s contains %1\\$d monkeys"
msgstr ""

Notice how an extra backslash has been added by xgettext.

Once you've translated the string, you must remove all backslashes from the ID string as well as the translation, so the po file will look like this:

#: file.php:9
#, ycp-format
msgid "The %2$s contains %1$d monkeys"
msgstr "Der er %1$d aber i %2$s"

Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off.
abiltcliffe at bigfoot.com 10-Sep-2002 11:01
To jrust at rustyparts.com, note that if you're using a double-quoted string and *don't* escape the dollar sign with a backslash, $s and $d will be interpreted as variable references. The backslash isn't part of the format specifier itself but you do need to include it when you write the format string (unless you use single quotes).
Andrew dot Wright at spamsux dot atnf dot csiro dot au 03-Jul-2002 02:22
An error in my last example:
$b = sprintf("%30.s", $a);
will only add enough spaces before $a to pad the spaces + strlen($a) to 30 places.

My method of centering fixed text in a 72 character width space is:

$a = "Some string here";
$lwidth = 36; // 72/2
$b = sprintf("%".($lwidth + round(strlen($a)/2)).".s", $a);
eden_zero_x at hotmail dot com 26-Jun-2002 02:05
Well I came up with this one, extremely simple. instead of writing <span class="class">hello</a>
you can write: print class('class','hello'); using sprintf
-----------------------------
function class_ ($class, $text=false)
 {
    return sprintf ("<span class=\"%s\">%s</span>",
        $class,
        ($text ? $text : $class)
    );
 }
-----------------------------
shgyn at binabakti dot or dot id 01-Jun-2002 07:57
Previously submitted sci() function to get scientific representation of a number is not working with 0 and negative numbers. So, here is the modified version:

function sci($x, $d=-1) {
    $min=($x<0)?"-":"";
    $x=abs($x);
    $e=floor(($x!=0)?log10($x):0);
    $x*=pow(10,-$e);
    $fmt=($d>=0)?".".$d:"";
    $e=($e>=0)?"+".sprintf("%02d",$e):"-".sprintf("%02d",-$e);
    return sprintf("$min%".$fmt."fe%s",$x,$e);
}
fuchschr at surfeu dot at 20-Feb-2002 08:54
To have a string with leading zeros use this:
$string_i = sprintf("%04s",$value)

Gives you an output with leading zeros and 4 digits.
i.e.
0001
0002
...
0010
an so on
cv at corbach dot de 10-Feb-2002 07:36
To make radu.rendec@ines.ro's excellent function work on signed numbers you must change the first line to:

$e = floor(log10(abs($x)));
anqmb(at)yahoo.co.jp 05-Dec-2001 04:51
Watch out the mysterious rounding rule.
<?php
$a = 4.5;
$b = sprintf("%d",$a);
$c = 4.5;
$d = sprintf("%.0f",$c);
$e = 0.45;
$f = sprintf("%.1f",$e);
print ("$b,$d,$f\n");
?>

The code above prints "4,5,0.5".
(Perl version prints "4,4,0.5".)
keeper at odi dot com dot br 26-Nov-2001 09:26
Took me a while to find this out.
hope will save someones time.
IT ADD A CARACRER TO THE END OF A STRING

$x = sprintf("%'x-10s", "a");
echo $x;
tjchamberlain.hotmail@com 25-Mar-2001 11:16
It is worth noting that "%5.2f" will result in a string 8 characters long (5 then the '.' then 2), not 5 characters as you might expect.
prolixmp3 at navigators dot lv 23-Mar-2001 10:55
If you are going to create a counter which uses _symbols_ before actual digits (see, f.e., SpyLog.com counters - they are filling space with "." before, so the count like 12345 looks like "........12345"), you can use the following:

$txt = "Abracadabra"; // actual string
$fit = 16; // how many digits to use
$fill = "."; // what to fill
$digits = sprintf ("%'{$fill}{$fit}s", $txt);

Paul (a.k.a. Mr.Prolix)
voudras at nospam dot swiftslayer dot org 17-Nov-2000 06:58
Little note about sprintf and its ilk.
if you attempt something like
$string = "dingy%sflem%dwombat";
$nbr = 5;
$name = "voudras";

$msg = sprintf("%d $string %s", $nbr, $name);

sprintf will complain about a lack in the number of arguments, this would be because of the %'s in the actual string. This can be a great benifit, but is also rather confusing if you dont realize this feature, and are passing questionable variables to sprintf (for, say perhaps logging). One way around this is using
ereg_replace("%","%%", $string); before
sending it off to sprintf. This is actually how i came across this as a problem - i had realized some time ago that i would have to test my $string for
%'s, but when running the %->%% replacement on a very large serialized object, my application timed out.
    My solution was to use
sprintf("%d %s %s", $nbr, $string, $name);
but, there was a reason i originally had done this the other way - i suppose i'll find out soon enough
soundex
sscanf
Обработка строк


Разбирает строку в соответствии с заданным форматом

sprintf
str_getcsv
Обработка строк
PHP Manual

sscanf

(PHP 4 >= 4.0.1, PHP 5)

sscanf — Разбирает строку в соответствии с заданным форматом

Описание

mixed sscanf ( string $str , string $format [, mixed &$... ] )

Функция sscanf() похожа на функцию printf(), но используется не для вывода, а для ввода данных. sscanf() интерпретирует строку str в соответствии с форматом format, указанным в документации к функцииsprintf().

Любые пробельные символы в строке формата соответствуют любым пробельным символам во входной строке. Это значит, что, например, символ табуляции \t в строке формата соответствует символу пробела во входной строке.

Список параметров

str

Обрабатываемая строка (string).

format

Формат, в соответствии с которым будет интерпретирована строка str, описанный в документации к функции sprintf() со следующими отличиями:

  • На функцию не влияют настройки локали.
  • F, g, G и b не поддерживаются.
  • D обозначает десятичное число.
  • i обозначает целое число с автоматическим определением системы счисления.
  • n обозначает обработанное количество символов на данный момент.

...

Необязательные переменные, передаваемые по ссылке, которым будут присвоены считанные значения.

Возвращаемые значения

Если переданы только эти два аргумента, будет возвращен массив. В противном случае, считанные из строки значения будут присвоены переменным, переданным через дополнительные аргументы, и будет возвращено количество присвоенных значений. Дополнительные аргументы должны передаваться по ссылке.

Если ожидается больше подстрок в параметре format, чем доступно в параметре str, то будет возвращено значение -1.

Примеры

Пример #1 Пример использования sscanf()

<?php
// получаем серийный номер
list($serial) = sscanf("SN/2350001", "SN/%d");
// и дату изготовления
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Узел $serial был изготовлен: $year-" . substr($month, 0, 3) . "-$day\n";
?>

Если переданы необязательные аргументы, значения будут присвоены им, а возвращено будет количество присвоенных значений.

Пример #2 sscanf() - использование необязательных аргументов

<?php
// получить имя автора и сформировать запись в формате DocBook
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>\n";
?>

Смотрите также

  • fscanf() - Обрабатывает данные из файла в соответствии с форматом
  • printf() - Выводит отформатированную строку
  • sprintf() - Возвращает отформатированную строку

User Contributed Notes

nmmm at nmmm dot nu 23-Nov-2011 05:11
This is more like C/C++ example, but works on PHP too.

<?php
$qs = "index.php?id=34&name=john";

print_r(   sscanf($qs, "%[^?]?%[^?]")   );

$qs = "id=34&name=john";

print_r(   sscanf($qs, "id=%[^&]&name=%[^&]")   );
?>
Igor Feghali 22-Oct-2008 10:56
parses an input string with fixed field sizes that contains data with spaces:

<?php
$result = sscanf("  Vendor: My Vendo Model: Super Model Foo  Rev: 1234",
                 '  Vendor: %8[ -~] Model: %16[ -~] Rev: %4c',
                 $vendor, $model, $rev);
?>

$vendor => My Vendo
$model => Super Model Foo
$rev => 1234
leg 13-Aug-2008 09:20
@mikewillitsgmail.com:

<?php

$out = sscanf('file_name.gif', 'file_%[^.].%s', $fpart1, $fpart2);

echo '<pre>';
print_r($fpart1);
echo '<hr />';
print_r($fpart2);
echo '</pre>';

?>

output:

name
-
gif

The "^." part avoid the first searched string to be too greedy. But doesn't protect you against an "file_test.name.gif" input, with bad results!
--==[FReeZ]==-- 27-May-2008 01:59
sscanf() in PHP also supports the more advanced patterns like in C++.
That means you can use it a lot more, after readining the details from http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html

Example usage:
$date = 'january-2008';
sscanf($date, '%[a-z]-%d', $month, $year);
printf('Parsed values: "%s", "%d"', $month, $year);

// Outputs Parsed values: "january", "2008"
mikewillitsgmail.com 15-Mar-2008 11:13
FYI - if you are trying to scan from a string which contains a filename with extension. For instance:

<?php

$out = sscanf('file_name.gif', 'file_%s.%s', $fpart1, $fpart2);

?>

The scanned string in the $fpart1 parameter turns out to be 'name.gif' and $fpart2 will be NULL.

To get around this you can simply replace the "." with a space or another "white-space like" string sequence.

I didn't see any other comments on regarding string literals which contain a '.' so I thought I'd mention it. The subtle characteristics of having "white-space delimited" content I think can be a source of usage contention. Obviously, another way to go is regular expressions in this instance, but for newer users this may be helpful.

Just in case someone else spent 10 minutes of frustration like I did. This was seen on PHP Version 5.2.3-1ubuntu6.3.

Searching the bug reports shows another users misunderstanding: http://bugs.php.net/bug.php?id=7793
Hayley Watson 13-Aug-2007 08:38
Just to note something not explicitly mentioned in the documentation.

sscanf() matches as much of the passed string as it can against the format. If it gets part way through and discovers that the next part of the string fails to match the format it gives up; it will return the parts that it did match, and NULL for the remainder.
Rodrigo Araújo 12-Oct-2006 01:02
Important warning about the last note by "anonymouse" (quoting):
----------------------------------------------------------------------
sscanf($string_to_parse,'%d %[^$]s',$num,$text);

This conversion command says "look for an integer, then a space, then any string up to the end of the string"
----------------------------------------------------------------------

This won't do what you think. You have the ^ and $ characters inside square brackets: $text will be empty if $string_to_parse contains for example "123 $".

What that pattern really means is: match an signed integer, followed by a whitespace, followed by a string *NOT* containing a dollar sign, followed by an 's'.

To do what you want i'm afraid you really must use ereg. Scanf is *not* a regular expression parser. It was designed to be used in plain C, where you don't have arbitrary length strings natively. Also, in scanf patterns you don't have an equivalent to matching the beginning/end of string, like you have with ^ and $ in regular expressions.

In PHP, you should use something like:
if (ereg('^([+-]?[0-9]+) (.+)$', $string_to_parse, $regs)) {
  $num = $regs[1];
  $text = $regs[2];
}
This regular expression assumes you want a signed integer at the beginning, and you don't mind if it starts with 0 when it is non-zero, e.g. 0123, +0321 or -0456 is also valid.
anonymouse 01-Aug-2006 09:38
I've seen several examples of people using brackets to define what look like regexp character classes. In my limited testing I don't think they are genuine character classes but they seem to be similar.

My task was to use sscanf() to parse an array of strings with the format:

number SPACE string_which_may_also_have_spaces

The normal %s conversion command treats spaces as some kind of delimiter. So, you can get the strings if you know beforehand how many "words" there will be. But, my input was variable.

Here's what I came up with: (note use of the dollar-sign 'end of string' hidden delimiter)

sscanf($string_to_parse,'%d %[^$]s',$num,$text);

This conversion command says "look for an integer, then a space, then any string up to the end of the string"
skeltoac 22-Mar-2006 08:28
To parse a line from an Apache access log in common format:

<?php
$log = array();
$n = sscanf(trim($line), '%s %s %s [%[^]]] "%s %s %[^"]" %d %s "%[^"]" "%[^"]"',
    $log['ip'],
    $log['client'],
    $log['user'],
    $log['time'],
    $log['method'],
    $log['uri'],
    $log['prot'],
    $log['code'],
    $log['bytes'],
    $log['ref'],
    $log['agent']
);
?>
Fuzzmaster 23-Sep-2005 07:14
Building a better Phone Format.  This function, a variation of prev. posts (in theory):

Should stip all non-numeric characters.
Treat partial numbers as extensions.
Treat 8 - 9 digit numbers as phone+ext.

Be kind I'm a newbie.

<?php

    // ##### Format String as Phone Number
    Function formatPH($ph)
          {
           $ph = ereg_replace ('[^0-9]+', '', $ph); // ##### Strip all Non-Numeric Characters
           $phlen = strlen($ph);
           switch (TRUE)
             {
              case ($phlen < 7):
                $ext = $ph;
                break;
              case ($phlen == 7):
                sscanf($ph, "%3s%4s", $pfx, $exc);
                break;
              case ($phlen > 7 AND $phlen < 10):
                sscanf($ph, "%3s%4s%s", $pfx, $exc, $ext);
                break;
              case ($phlen == 10):
                sscanf($ph, "%3s%3s%4s", $area, $pfx, $exc);
                break;
              case ($phlen == 11):
                sscanf($ph, "%1s%3s%3s%4s", $cty, $area, $pfx, $exc);
                break;
              case ($phlen > 11):
                sscanf($ph, "%1s%3s%3s%4s%s", $cty, $area, $pfx, $exc, $ext);
                break;
             }
           $out = '';
           $out .= isset($cty) ? $cty.' ' : '';
           $out .= isset($area) ? '('.$area.') ' : '';
           $out .= isset($pfx) ? $pfx.' - ' : '';
           $out .= isset($exc) ? $exc.' ' : '';
           $out .= isset($ext) ? 'x'.$ext : '';
           return $out;
          }

?>
Brainiac361 22-Aug-2005 01:49
The %[^[]]-trick may seem to work, but it doesn't!

What happens is that sscanf will simply match any characters but an opening square bracket (which is rather rare and that's why it might just seem to work).
But even worse it will expect a ]-character next and continue to match anything.

Now what you can do is make sscanf look for any character but a character that is really never used... a good choice is the linebreak "%[^\\n]", especially in combination with fscanf.

What you can also do is copy and paste any unused ascii character like #001 or something.
joshmckenneyATgmailDOT(0{ 14-Jul-2005 03:21
added country code (1) to phone number function:

function formatPhone($phone) {
       if (empty($phone)) return "";
       if (strlen($phone) == 7)
               sscanf($phone, "%3s%4s", $prefix, $exchange);
       else if (strlen($phone) == 10)
               sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
       else if (strlen($phone) > 10)
               if(substr($phone,0,1)=='1') {
                                 sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                             }
                             else{
                                 sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
                                }
       else
               return "unknown phone format: $phone";
       $out = "";
       $out .= isset($country) ? $country.' ' : '';
       $out .= isset($area) ? '(' . $area . ') ' : '';
       $out .= $prefix . '-' . $exchange;
       $out .= isset($extension) ? ' x' . $extension : '';
       return $out;
}
Vincent Jansen 16-Jun-2005 01:04
If you just wants filter out information between two parts of a string, i used the following, it works better for me then the sscanf function.

<?php
function scanstr($zoekstr,$part1,$part2) {
$firstpos=strpos ($zoekstr, $part1)+strlen($part1);
$lastpos=strpos ($zoekstr, $part2);
$scanresult=substr ($zoekstr, $firstpos, $lastpos-$firstpos);
    return($scanresult);
}
echo scanstr ("var1=hello&var2=test&var3=more","var2=","&var3");
?>
codeslinger at compsalot dot com 06-Feb-2005 06:03
Security Note:

Although it is a very powerful technique, keep in mind that it is easily deceived.

Many successful exploits have been based on scanf attacks.  It should not be used on untrusted input without a lot of additional validation.
steve (atsign) rapaport *fullstop* com 18-Sep-2004 04:27
The classic example
<?php
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
?>

works fine if you already know the variable names you want to fill, and the format string you want to fill them with.  If you want both of those to be dynamically configurable (as in reading a file with a flexible format), you may have a use for this code:

Assumes your variables are listed in the variable
$varstr = "var1, var2, var3"
(you don't know what the variable names will be,
 perhaps they're a subset of a long list of valid ones)

Assumes your input line is in $line, and your sscanf spec is in $spec.  Both of these may also be in your input.

Integrity checks omitted for clarity.

<?php
        $vars = explode(',', $varstr);

        $values = @sscanf($line, $spec);
        // Do input integrity checks

        foreach ($vars as $var) {
            $var = trim($var);
            $next = each($values);
            $$var = $next['value'];
            if ($$var) $result_array[$var] = $$var;
        }
?>

This took me some time to write successfully, so I'm including it for posterity.  Non-obvious is the use of
$next.

Cheers,

Steve
marcus at synchromedia dot co dot uk 24-Mar-2003 09:38
In PHP >= 4.3.0, if you use additional reference parameters, you will get this warning:

PHP Warning:  Call-time pass-by-reference has been deprecated - argument passed by value

This clearly has the potential to cause unexpected consequences (vars left empty), and will break existing code. So don't do it! These docs need updating to say this too.

The syntax:

    list($a, $b) = sscanf("hello world", "%s %s");

will work as expected, and doesn't seem to cause any problems with Apache that I've noticed.
sbarnum.pointsystems@com 19-Feb-2003 01:29
This is a better phone format function than the one above, handles leading zeroes correctly, by using the "%s" instead of "%d" argument to sscanf().  Again, this function assumes that the input has been stripped of all non-integer values.

function formatPhone($phone) {
        if (empty($phone)) return "";
        if (strlen($phone) == 7)
                sscanf($phone, "%3s%4s", $prefix, $exchange);
        else if (strlen($phone) == 10)
                sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
        else if (strlen($phone) > 10)
                sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
        else
                return "unknown phone format: $phone";
        $out = "";
        $out .= isset($area) ? '(' . $area . ') ' : "";
        $out .= $prefix . '-' . $exchange;
        $out .= isset($extension) ? ' x' . $extension : "";
        return $out;
}
sbarnum.pointsystems@com 19-Nov-2002 07:21
More fun with phones!  This assumes that the phone number is 10 digits, with only numeric data, but it would be easy to check the length of the string first.

function formatPhone($phone) {
        if (empty($phone)) return "";
        sscanf($phone, "%3d%3d%4d", $area, $prefix, $exchange);
        $out = @$area ? "($area) " : "";
        $out .= $prefix . '-' . $exchange;
        return $out;
}
jon at fuck dot org 13-Sep-2002 11:27
this function is a great way to get integer rgb values from the html equivalent hex.

list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
jamesDOTwatsonATrealismstudiosDOTcom 10-Jul-2002 12:31
You're making a common mistake in believing that sscanf (and the whole scanf family) are more intelligent than they really are, sscanf always starts checking from the first character of the string, the first character that doesn't match the format string causes it to bail out early, if you want to match later in the string you'll have to do something like this:

sscanf(strstr($lit[$x],"Vol."),"Vol. %d",&$vol[$x]);

(check the docs on strstr if you're unsure of how it works)

or if you want you can add some simple error correction

$temp=strstr($lit[$x],"Vol.");
if ($temp)
    sscanf($temp,"Vol. %d",&$vol[$x]);
else
    $vol[$x]=$default_vol;
elgabos at umail dot ucsb dot edu 27-Feb-2002 03:38
After playing around with this for a while, I found that if you use %[^[]] instead of %s (since php has problems with spaces when using %s) it works nicely.

For those that aren't familiar with regular expressions, %[^[]] basically matches anything that isn't nothing.

Hope this helps. - Gabe
narainsbrain at yahoo dot com 14-Oct-2001 03:25
apparently, sscanf always splits at spaces, even if spaces are not specified in the format. consider this script:

<?php
$str = "This is a\tsentence with\ttabs";
$scanned = sscanf($str, "%s\t%s\t%s");
echo join(" : ", $scanned);
?>

this echoes "This : is : a", not the expected "This is a : sentence with : tabs."
this behaviour is fine if your strings don't contain spaces, but if they do you'd be better off using explode().
owenh at halo5 dot com 28-Nov-2000 04:21
<?php list($phone11, $phone12, $phone13) = sscanf($arow[9],"(%d) %d-%d"); ?>

If thoes variables dont have data in them it seems to cause segfaults on apache.  ( just to save you some trouble shooting time here is my fix:
<?php sscanf($arow[9],"(%d) %d-%d", &$phone11,&$phone12, &$phone13); ?>
clcollie at mindspring dot com 12-Sep-2000 04:59
Actually sscanf()_always_ returns an array if you specify less return variables than format specifiers. i may change this to return a scalar if only a single format specifier exists.
  Note that sscanf() is (almost) the complete functional equivalent of its "C" counterpart, so you can do the following to get the expected effect :

   sscanf("SN/2350001","SN/%d",&$serial)

The array return was a nicety for PHP.
sprintf
str_getcsv
Обработка строк


Выполняет разбор CSV-строки в массив

sscanf
str_ireplace
Обработка строк
PHP Manual

str_getcsv

(PHP 5 >= 5.3.0)

str_getcsv — Выполняет разбор CSV-строки в массив

Описание

array str_getcsv ( string $input [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]] )

Данная функция выполняет разбор строки в формате CSV и возвращает массив с полученными из строки полями.

Список параметров

input

Обрабатываемая строка.

delimiter

Устанавливает разделитель поля (только один символ).

enclosure

Устанавливает символ ограничителя поля (только один символ).

escape

Устанавливает экранирующий символ (только один символ). По умолчанию равен обратному слэшу (\).

Возвращаемые значения

Возвращает индексированный массив, содержащий полученные из строки поля.

Смотрите также

  • fgetcsv() - Читает строку из файла и производит разбор данных CSV

User Contributed Notes

xoneca at gmail dot com 27-Nov-2011 04:26
Note that this function can also be used to parse other types of constructions. For example, I have used to parse .htaccess AddDescription lines:

    AddDescription "My description to the file." filename.jpg

Those lines can be parsed like this:

<?php

$line = 'AddDescription "My description to the file." filename.jpg';

$parsed = str_getcsv(
    $line, # Input line
    ' ',   # Delimiter
    '"',   # Enclosure
    '\\'   # Escape char
);

var_dump( $parsed );

?>

The output:

array(3) {
  [0]=>
  string(14) "AddDescription"
  [1]=>
  string(27) "My description to the file."
  [2]=>
  string(12) "filename.jpg"
}
ioplex at gmail dot com 29-Sep-2011 08:38
Note that the CSV format handled by this function is not even close to being the same as the CSV emitted and consumed by spreadsheet programs. In truth, one could argue that the real CSV "specification" is actually just the behavior of Microsoft Excel and not an RFC that was written 20 years after Excel used CSV (although thankfully RFC 4180 is actually the same as Excel behavior with the exception that Excel actually uses a tab as a separator by default).

CSV used by spreadsheet programs like Excel do not use escape characters to escape stray separator characters. Again, the default separator character is actually a tab and not a comma (but historically this is usually still referred to it as CSV). Excel uses quotes to enclose an element that has literal separator characters in it (and an extra quote to escape each literal quote within the quotes - strange but true). Another quirk is that Excel will not trim extra space around elements including line breaks. Meaning you can have multiple lines of text within an element by just putting it in quotes. See the Wikipedia entry for "Comma-separated values" for good examples that have quotes and escaped quotes and newlines and so on.

Note that if you want to generate data that Excel will load into cells when someone clicks on a link, use tab as a separator, quote elements that have tabs or quotes and escape literal quotes with an extra preceding quote.

The following routine can be used to properly quote an element and escape quotes with an extra quote in the way Excel expects:

<?php
    function escapeCsvElement($str, $sep) {
        $quot = false;
        $si = 0;
        $slen = strlen($str);
        $ret = '';
        while ($si < $slen) {
            $ch = $str[$si];
            if ($ch == $sep)
                $quot = true;
            if ($ch == '"') {
                $quot = true;
                $ret .= '"';
            }
            $ret .= $ch;
            $si++;
        }
        if ($quot)
            return '"' . $ret . '"';
        return $str;
    }
?>

Then write each row to the browser terminated by carriage-return / newline linebreaks and send headers like:

<?php
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename=' . $filename);
?>

This is what Excel and other spreadsheet programs expect to automatically load your cell data as expected without triggering the file import wizard.

As for parsing real CSV, the *getcsv functions are not going to work. To parse the quotes and escaped quotes and literal line breaks and so on, that would be handled best with a proper state-machine parser.
w_barath@hotmail,com 02-Aug-2011 07:19
For people who haven't got access to str_getcsv() in their version of PHP and want to convert strings from CSV, I have seen many huge swaths of code and regexes to do this extremely simple task.  Here's minimal, fast code:

<?php
function csv2array($input,$delimiter=',',$enclosure='"',$escape='\\'){
    $fields=explode($enclosure.$delimiter.$enclosure,substr($input,1,-1));
    foreach ($fields as $key=>$value)
        $fields[$key]=str_replace($escape.$enclosure,$enclosure,$value);
    return($fields);
}

function array2csv($input,$delimiter=',',$enclosure='"',$escape='\\'){
    foreach ($input as $key=>$value)
        $input[$key]=str_replace($enclosure,$escape.$enclosure,$value);
    return $enclosure.implode($enclosure.$delimiter.$enclosure,$input).$enclosure;
}

$data=array("one","\"two\"");
for ($i=0;$i<100;$i++) $data=array(array2csv($data),$i);
echo "Encoded $i times...".var_export($data,true)."\n";
for ($j=0;$j<$i;$j++) $data=csv2array($data[0]);
echo "Decoded $i times...".var_export($data,true)."\n";
?>

Pretty straightforward.  ;-)

Yes, I intentionally changed the function names,
M. Bunge (TLC Communications, DE) 22-Jun-2011 05:08
Just another way to convert a csv file to an associative array.

<?php
//
// Convert csv file to associative array:
//

function csv_to_array($input, $delimiter='|')
{
    $header = null;
    $data = array();
    $csvData = str_getcsv($input, "\n");

    foreach($csvData as $csvLine){
        if(is_null($header)) $header = explode($delimiter, $csvLine);
        else{

            $items = explode($delimiter, $csvLine);

            for($n = 0, $m = count($header); $n < $m; $n++){
                $prepareData[$header[$n]] = $items[$n];
            }

            $data[] = $prepareData;
        }
    }

    return $data;
}

//-----------------------------------
//
//Usage:

$csvArr = csv_to_array(file_get_contents('test.csv'));

?>
durik at 3ilab dot net 16-Jan-2011 11:39
As the str_getcsv(), unlike to fgetcsv(), does not parse the rows in CSV string, I have found following easy workaround:

<?php
$Data = str_getcsv($CsvString, "\n"); //parse the rows
foreach($Data as &$Row) $Row = str_getcsv($Row, ";"); //parse the items in rows
?>

Why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly.
Anonymous 25-Oct-2010 12:25
If your version of PHP doesn't have `str_getcsv` and you don't need custom $escape or $eol values, try this:

<?php if (!function_exists('str_getcsv')) {

function str_getcsv($input, $delimiter=',', $enclosure='"', $escape=null, $eol=null) {
  $temp=fopen("php://memory", "rw");
  fwrite($temp, $input);
  fseek($temp, 0);
  $r = array();
  while (($data = fgetcsv($temp, 4096, $delimiter, $enclosure)) !== false) {
    $r[] = $data;
  }
  fclose($temp);
  return $r;
}

} ?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (depely AT IAMNOTABOT prestaconcept.net) on 04-MAR-2011 with the following note: "The previous anonymous function only read the first line".]
Jay Williams 10-Aug-2010 01:50
Here is a quick and easy way to convert a CSV file to an associated array:

<?php
/**
 * @link http://gist.github.com/385876
 */
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

?>
hpartidas at deuz dot net 25-May-2010 09:50
I found myself wanting to parse a CSV and didn't have access to str_getcsv, so I wrote substitute for PHP < 5.3, hope it helps someone out there stuck in the same situation.

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
        if (is_string($input) && !empty($input)) {
            $output = array();
            $tmp    = preg_split("/".$eol."/",$input);
            if (is_array($tmp) && !empty($tmp)) {
                while (list($line_num, $line) = each($tmp)) {
                    if (preg_match("/".$escape.$enclosure."/",$line)) {
                        while ($strlen = strlen($line)) {
                            $pos_delimiter       = strpos($line,$delimiter);
                            $pos_enclosure_start = strpos($line,$enclosure);
                            if (
                                is_int($pos_delimiter) && is_int($pos_enclosure_start)
                                && ($pos_enclosure_start < $pos_delimiter)
                                ) {
                                $enclosed_str = substr($line,1);
                                $pos_enclosure_end = strpos($enclosed_str,$enclosure);
                                $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
                                $output[$line_num][] = $enclosed_str;
                                $offset = $pos_enclosure_end+3;
                            } else {
                                if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
                                    $output[$line_num][] = substr($line,0);
                                    $offset = strlen($line);
                                } else {
                                    $output[$line_num][] = substr($line,0,$pos_delimiter);
                                    $offset = (
                                                !empty($pos_enclosure_start)
                                                && ($pos_enclosure_start < $pos_delimiter)
                                                )
                                                ?$pos_enclosure_start
                                                :$pos_delimiter+1;
                                }
                            }
                            $line = substr($line,$offset);
                        }
                    } else {
                        $line = preg_split("/".$delimiter."/",$line);

                        /*
                         * Validating against pesky extra line breaks creating false rows.
                         */
                        if (is_array($line) && !empty($line[0])) {
                            $output[$line_num] = $line;
                        }
                    }
                }
                return $output;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
?>
vincent dot enjalbert at gmail dot com 19-Feb-2010 03:37
For multiline array, just use :

<?php
$csvData = file_get_contents($fileName);
$csvNumColumns = 22;
$csvDelim = ";";
$data = array_chunk(str_getcsv($csvData, $csvDelim), $csvNumColumns);
?>
Raymond 14-Dec-2009 05:49
Here's a little function to convert a multi-line CSV string to an array:

<?php
function csv_to_array($csv, $delimiter = ',', $enclosure = '"', $escape = '\\', $terminator = "\n") {
    $r = array();
    $rows = explode($terminator,trim($csv));
    $names = array_shift($rows);
    $names = str_getcsv($names,$delimiter,$enclosure,$escape);
    $nc = count($names);
    foreach ($rows as $row) {
        if (trim($row)) {
            $values = str_getcsv($row,$delimiter,$enclosure,$escape);
            if (!$values) $values = array_fill(0,$nc,null);
            $r[] = array_combine($names,$values);
        }
    }
    return $r;
}
?>
Jrg Wagner 12-Oct-2009 02:23
Here is a very concise replacement for str_getcsv.
No escaping of the enclosure char though, but an additional possibility to preserve the enclosing characters around a field.
Note that the fourth parameter therefore has a different meaning!

<?php
function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
  $resArr = array();
  $n = 0;
  $expEncArr = explode($enclose, $str);
  foreach($expEncArr as $EncItem){
    if($n++%2){
      array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
    }else{
      $expDelArr = explode($delim, $EncItem);
      array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
      $resArr = array_merge($resArr, $expDelArr);
    }
  }
  return $resArr;
}
?>
dave_walter at yahoo dot com 04-Jun-2009 09:51
Just to clarify, my str_putcsv() function was only ever designed to complement the functionality of the str_getcsv() built-in function, which can only handle converting one line of input into a single level array. For example, this code:

<?php
    var_dump( str_getcsv( "a,b,c\nd,e,f", "," ));
?>

generates this output:

array(5) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(3) "c
    d"
    [3]=>
    string(1) "e"
    [4]=>
    string(1) "f"
}

Even fgetcsv() and fputcsv() only work with a single line. All the examples show them being used within a loop of some sort.

I was also avoiding the artificial restriction on the length of the CSV string introduced by Ulf's modification.
Ulf 28-May-2009 06:24
As Dave's function also had the problem with only one line being returned here's a slightly changed version:

<?php
function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
  // Open a memory "file" for read/write...
  $fp = fopen('php://temp', 'r+');
  // ... write the $input array to the "file" using fputcsv()...
  fputcsv($fp, $input, $delimiter, $enclosure);
  // ... rewind the "file" so we can read what we just wrote...
  rewind($fp);
  // ... read the entire line into a variable...
  $data = fread($fp, 1048576); // [changed]
  // ... close the "file"...
  fclose($fp);
  // ... and return the $data to the caller, with the trailing newline from fgets() removed.
  return rtrim( $data, "\n" );
}
?>
It assumes that one line won't exceed 1Mb of data. That should be more than enough.
Anonymous 16-Mar-2009 10:02
For some reason o'connor's code only reads one line of a csv for me... I had to replace the line

      $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

with this:

      $data;
      while (!feof($fp))
      {
        $data[] = fgetcsv($fp, 0, $delimiter, $enclosure); //  $escape only got added in 5.3.0
      }

...to get all of the data out of my string (some post data pasted into a textbox and processed only with stripslashes).
dave_walter at NOSPAM dot yahoo dot com 06-Feb-2009 03:32
Drawing inspiration from daniel dot oconnor at gmail dot com, here's an alternative str_putcsv() that leverages existing PHP core functionality (5.1.0+) to avoid re-inventing the wheel.

<?php
if(!function_exists('str_putcsv')) {
    function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
        // Open a memory "file" for read/write...
        $fp = fopen('php://temp', 'r+');
        // ... write the $input array to the "file" using fputcsv()...
        fputcsv($fp, $input, $delimiter, $enclosure);
        // ... rewind the "file" so we can read what we just wrote...
        rewind($fp);
        // ... read the entire line into a variable...
        $data = fgets($fp);
        // ... close the "file"...
        fclose($fp);
        // ... and return the $data to the caller, with the trailing newline from fgets() removed.
        return rtrim( $data, "\n" );
    }
}
?>
Jeremy 20-Jan-2009 05:20
After using several methods in the past to create CSV strings without using files (disk IO sucks), I finally decided it's time to write a function to handle it all. This function could use some cleanup, and the variable type test might be overkill for what is needed, I haven't thought about it too much.

Also, I took the liberty of replacing fields with certain data types with strings which I find much easier to work with. Some of you may not agree with those. Also, please note that the type "double" or float has been coded specifically for two digit precision because if I am using a float, it's most likely for currency.

I am sure some of you out there would appreciate this function.

<?php
    function str_putcsv($array, $delimiter = ',', $enclosure = '"', $terminator = "\n") {
        # First convert associative array to numeric indexed array
        foreach ($array as $key => $value) $workArray[] = $value;

        $returnString = '';                 # Initialize return string
        $arraySize = count($workArray);     # Get size of array

        for ($i=0; $i<$arraySize; $i++) {
            # Nested array, process nest item
            if (is_array($workArray[$i])) {
                $returnString .= str_putcsv($workArray[$i], $delimiter, $enclosure, $terminator);
            } else {
                switch (gettype($workArray[$i])) {
                    # Manually set some strings
                    case "NULL":     $_spFormat = ''; break;
                    case "boolean":  $_spFormat = ($workArray[$i] == true) ? 'true': 'false'; break;
                    # Make sure sprintf has a good datatype to work with
                    case "integer":  $_spFormat = '%i'; break;
                    case "double":   $_spFormat = '%0.2f'; break;
                    case "string":   $_spFormat = '%s'; break;
                    # Unknown or invalid items for a csv - note: the datatype of array is already handled above, assuming the data is nested
                    case "object":
                    case "resource":
                    default:         $_spFormat = ''; break;
                }
                                $returnString .= sprintf('%2$s'.$_spFormat.'%2$s', $workArray[$i], $enclosure);
$returnString .= ($i < ($arraySize-1)) ? $delimiter : $terminator;
            }
        }
        # Done the workload, return the output information
        return $returnString;
    }

?>
daniel dot oconnor at gmail dot com 19-Jan-2009 04:48
Don't have this? Ask fgetcsv() to do it for you.

5.1.0+

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
        $fiveMBs = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
        fputs($fp, $input);
        rewind($fp);

        $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

        fclose($fp);
        return $data;
    }
}
?>
Anonymous 12-Jan-2009 08:55
Thanks Rob, have used your code. It needs a minor tweak so that the delimiter option is processed as it should be. Line 5 should read:

<?php    $expr="/$delimiter(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added ?>

instead of:

<?php    $expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added ?>

JS, London
Rob 07-Nov-2008 08:54
This does the same as the example below, giving you an array, but it allows to parse csv with commas in between quotes (used for addresses)... and it takes out the quotes from an array entry as well.

<?php
function parse_csv($file, $options = null) {
    $delimiter = empty($options['delimiter']) ? "," : $options['delimiter'];
    $to_object = empty($options['to_object']) ? false : true;
    $expr="/$delimiter(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added
    $str = $file;
    $lines = explode("\n", $str);
    $field_names = explode($delimiter, array_shift($lines));
    foreach ($lines as $line) {
        // Skip the empty line
        if (empty($line)) continue;
        $fields = preg_split($expr,trim($line)); // added
        $fields = preg_replace("/^\"(.*)\"$/s","$1",$fields); //added
        //$fields = explode($delimiter, $line);
        $_res = $to_object ? new stdClass : array();
        foreach ($field_names as $key => $f) {
            if ($to_object) {
                $_res->{$f} = $fields[$key];
            } else {
                $_res[$f] = $fields[$key];
            }
        }
        $res[] = $_res;
    }
    return $res;
}
?>

[EDIT BY danbrown AT php DOT net: Includes bugfixes provided by "Anonymous" on 12-JAN-09 and "joelfromlollypins.com" on 19-JAN-09.]
william dot j dot weir at gmail dot com 18-Sep-2008 03:19
If your happy enough having just a multi-dimensional array, this should work fine. I had wanted to use the one provided by keananda but it was choking on pr($lines).

<?php
function f_parse_csv($file, $longest, $delimiter) {
  $mdarray = array();
  $file    = fopen($file, "r");
  while ($line = fgetcsv($file, $longest, $delimiter)) {
    array_push($mdarray, $line);
    }
  fclose($file);
  return $mdarray;
  }
?>

$longest is a number that represents the longest line in the csv file as required by fgetcsv().  The page for fgetcsv() said that the longest line could be set to 0 or left out, but I couldn't get it to work without. I just made it extra large when I had to use it.
keananda at gmail dot com 15-Sep-2008 04:29
For those who need this function but not yet installed in their environment, you can use my function bellow.

You can parse your csv file into an associative array (by default) for each lines, or into an object.
<?php
function parse_csv($file, $options = null) {
    $delimiter = empty($options['delimiter']) ? "," : $options['delimiter'];
    $to_object = empty($options['to_object']) ? false : true;
    $str = file_get_contents($file);
    $lines = explode("\n", $str);
    pr($lines);
    $field_names = explode($delimiter, array_shift($lines));
    foreach ($lines as $line) {
        // Skip the empty line
        if (empty($line)) continue;
        $fields = explode($delimiter, $line);
        $_res = $to_object ? new stdClass : array();
        foreach ($field_names as $key => $f) {
            if ($to_object) {
                $_res->{$f} = $fields[$key];
            } else {
                $_res[$f] = $fields[$key];
            }
        }
        $res[] = $_res;
    }
    return $res;
}
?>

NOTE:
Line number 1 of the csv file will be considered as header (field names).

TODO:
- Enclosure handling
- Escape character handling
- Other features/enhancements as you need

EXAMPLE USE:
Content of /path/to/file.csv:
CODE,COUNTRY
AD,Andorra
AE,United Arab Emirates
AF,Afghanistan
AG,Antigua and Barbuda

<?php
$arr_csv = parse_csv("/path/to/file.csv");
print_r($arr_csv);
?>
// Output:
Array
(
    [0] => Array
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => Array
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => Array
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => Array
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
)

<?php
$obj_csv = parse_csv("/path/to/file.csv", array("to_object" => true));
print_r($obj_csv);
?>
// Output:
Array
(
    [0] => stdClass Object
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => stdClass Object
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => stdClass Object
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => stdClass Object
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
    [4] => stdClass Object
        (
            [CODE] =>
            [COUNTRY] =>
        )
)

// If you use character | (pipe) as delimiter in your csv file, use:
<?php
$arr_csv = parse_csv("/path/to/file.csv", array("delimiter"=>"|"));
?>

==NSD==
colin_mckinnon at slc dot co dot uk 09-Jun-2008 09:00
Regarding RFC 4180 - I asked the author about the specifics of the format described which poses a number of technical difficulties in building a parser - his response is shown below:

quote:

Please do keep one thing in mind - this RFC
was meant to define the MIME type for CSV rather than the format. It
happens to be that no format definition existed and I was forced to
define one. As the RFC states:

"This section documents the format that seems to be followed by most
implementations"
csv at rfc dot org 05-May-2008 01:15
RFC 4180 which deals with CSVs states the escape character is supposed to be a double quotation mark: (page 2)
   7.  If double-quotes are used to enclose fields, then a double-quote
       appearing inside a field must be escaped by preceding it with
       another double quote.  For example:

       "aaa","b""bb","ccc"
peev[dot]alexander at gmail dot com 20-Apr-2008 02:22
CSV parsing and storage is not that hard to implement - see my example functions ( I believe they do a pretty good job - I use them in a production environment ):

<?php

if( !function_exists("parse_csv") ){
    function parse_csv($string){
/* Author : Alexander Peev, posted at PHP.NET */
        if( !function_exists("parse_csv_aux") ){
            function parse_csv_aux( $string ){
                $product = "";
                $in_quote = FALSE;
                $skipped_quote = FALSE;
                for(  $i = 0 ; $i < strlen($string) ; $i++  ){
                    if( $string{$i} == "\"" ){
                        if($in_quote){
                            if($skipped_quote){
                                $product .= "\"";
                                $skipped_quote = FALSE;
                            }
                            else if( !$skipped_quote ){
                                $skipped_quote = TRUE;
                            }
                        }
                        else{
                            if($skipped_quote) $skipped_quote = FALSE;
                            $in_quote = TRUE;
                        }
                    }
                    else if( $string{$i} == ";" ){
                        if($in_quote){
                            $product .= ";";
                        }
                        else{
                            $product .= " ; ";
                        }
                    }
                    else{
                        if($in_quote){
                            $in_quote = FALSE;
                            $product .= $string{$i};
                        }
                        else{
                            $product .= $string{$i};
                        }
                    }
                }
                return $product;
            }
        }
        $data = array();
        if(  is_string($string) && ( stripos($string, "\n") !== FALSE )  ){
            $data = explode("\n", parse_csv_aux($string) );
            foreach($data as $key => $row){
                $columns = array();
                //$row = strtr(  $row, array( "\";\"" => "\";\"", ";" => " ; " )  );
                if( stripos($row, " ; ") !== FALSE ){
                    $columns = explode( " ; ", $row );
                    if( !is_array($columns) )$columns = array( strval($columns) );
                    $data[$key] = $columns;
                }
            }
            return $data;
        }
        else if(  is_string($string) && ( stripos( ($string =  parse_csv_aux($string)), " ; ") !== FALSE )  ){
            $columns = explode( " ; ", $string );
            if( !is_array($columns) )$columns = array( strval($columns) );
            return array($columns);
        }
        else return strval($string);
    } /* end function parse_csv */
} /* end not function exists parse_csv */

if( !function_exists("store_csv") ){
    function store_csv($data){
/* Author : Alexander Peev, posted at PHP.NET */
        if( !function_exists("store_csv_aux") ){
            function store_csv_aux( $string ){
                $string = strtr( $string, array( "\n" => "" ) );
                $product = "";
                $in_quote = FALSE;
                for(  $i = 0 ; $i < strlen($string) ; $i++  ){
                    if( $string{$i} == "\"" ){
                        if($in_quote){
                            $product .= "\"\"";
                        }
                        else{
                            $product .= "\"\"\"";
                            $in_quote = TRUE;
                        }
                    }
                    else if( $string{$i} == ";" ){
                        if($in_quote){
                            $product .= ";";
                        }
                        else{
                            $product .= "\";";
                            $in_quote = TRUE;
                        }
                    }
                    else{
                        if($in_quote){
                            $product .= "\"";
                            $in_quote = FALSE;
                            $product .= $string{$i};
                        }
                        else{
                            $product .= $string{$i};
                        }
                    }
                }
                if($in_quote)$product .= "\"";
                return $product;
            }
        }
        if(!is_array($data))return strval($data);
        $passed_rows = FALSE;
        $product = "";
        foreach($data as $row){
            if( $passed_rows )$product .= "\n";
            if( is_array($row) ){
                $columns = "";
                $passed_cols = FALSE;
                foreach($row as $column){
                    if( $passed_cols )$columns .= ";";
                    $columns .= store_csv_aux( $column );
                    $passed_cols =TRUE;
                }
                $product .= strval($columns);
            }
            else{
                $product .= strtr( strval($row), array("\n" => "") );
            }
            $passed_rows = TRUE;
        }
        return $product;
    } /* end function store_csv */
} /* end not function exists store_csv */

?>
justin at cam dot org 15-Feb-2007 10:25
There's a discussion of how to perform this task in the user notes for the split() function.
http://www.php.net/manual/en/function.split.php
sscanf
str_ireplace
Обработка строк


Регистро-независимый вариант функции str_replace

str_getcsv
str_pad
Обработка строк
PHP Manual

str_ireplace

(PHP 5)

str_ireplace — Регистро-независимый вариант функции str_replace()

Описание

mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Эта функция возвращает строку или массив, в котором все вхождения search в subject заменены на replace (без учета регистра символов). Если не нужны сложные правила поиска/замены, использование этой функции предпочтительнее preg_replace() с модификатором i.

Список параметров

Если search и replace - массивы, то str_ireplace() использует каждое значение из соответствующего массива для поиска и замены в subject. Если в массиве replace меньше элементов, чем в search, в качестве строки замены для оставшихся значений будет использована пустая строка. Если search - массив, а replace - строка, то эта строка замены будет использована для каждого элемента массива search. Обратный случай смысла не имеет.

Если search или replace являются массивами, их элементы будут обработаны от первого к последнему.

search

Искомое значение, также известное как needle (иголка). Для множества искомых значений можно использовать массив.

replace

Значение замены, будет использовано для замены искомых значений search. Для множества значений можно использовать массив.

subject

Строка или массив, в котором производится поиск и замена, также известный как haystack (стог сена).

Если subject является массивом, то поиск с заменой будет осуществляться над каждым элементом subject, а результатом функции также будет являться массив.

count

Если передан, то будет установлен в количество произведенных замен.

Возвращаемые значения

Возвращает строку или массив с замененными значениями.

Список изменений

Версия | Описание
5.0.0 | Добавлен параметр count.

Примеры

Пример #1 Пример использования str_ireplace()

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Предостережение

Замечание о порядке замены

Так как str_ireplace() осуществляет замену слева направо, то при использовании множественных замен она может заменить ранее вставленное значение на другое. Пример №2 в документации str_replace() поясняет как это работает на практике.

Смотрите также

  • str_replace() - Заменяет все вхождения строки поиска на строку замены
  • preg_replace() - Выполняет поиск и замену по регулярному выражению
  • strtr() - Преобразует заданные символы или заменяет подстроки

User Contributed Notes

chud37.com 11-Jan-2012 12:52
After searching through the forums and laboriously testing all the highlight functions (as I was too lazy to write my own, I wanted a quick solution), I found that none of them did what I wanted at all.

I just wanted a function that took a string and did not modify it in anyway, apart from just surrounding the matching words with some kind of highlighting HTML.  At best all the ones of the forums here changed the text but also the case as well.  The example given by sawdust *did* work except when given a single  character when it continued to loop-replace the letter 'a' in the inserted 'background-color:'.  So, here is a fool proof, no-nonsense replace method that should work always.

<?php
function highlight($haystack, $needle) {
     if (strlen($haystack) < 1 || strlen($needle) < 1) {return $haystack;}
    preg_match_all("/$needle+/i", $haystack, $match);
    $exploded = preg_split("/$needle+/i",$haystack);
    $replaced = "";
    foreach($exploded as $e)
            foreach($match as $m)
            if($e!=$exploded[count($exploded)-1]) {$replaced .= $e . "<font style=\"background-color:yellow\">" . $m[0] . "</font>";} else {$replaced .= $e;}
    return $replaced;
}
?>
Psudo - thepsudo at gmail dot com 29-Jun-2011 09:53
For highlighting without the overhead of regex and without destroying capitalization, try this:

<?php
function highlight($needle, $haystack){
    $ind = stripos($haystack, $needle);
    $len = strlen($needle);
    if($ind !== false){
        return substr($haystack, 0, $ind) . "<b>" . substr($haystack, $ind, $len) . "</b>" .
            highlight($needle, substr($haystack, $ind + $len));
    } else return $haystack;
}
?>

This example uses HTML bold tags, but you can easily change the highlighting method.
holblin at holblin dot com 09-Mar-2011 01:11
Warning with highlighting ...

I used :

<?php
$text = preg_replace('/('.$q.')/i','<span class=highlighting "">$1</span>' , $text);
?>

Because this line do not allow to highlight uppercase and lowercase correctly (transform uppercase to lowercase for exemple)

<?php
 $text = str_ireplace( $q , '<span class=highlighting "">'.$q.'</span>', $text);
?>

But when $q contain some regex you have some problems ... for exemple :
<?php $q = '('; ?>

So you must use preg_replace to highlight correctly the text and you must create a function for escape bad regex caracters !

I think that a better function can be found but this works I guess :

<?php
function regex_escape( $q )
{
    return preg_replace('/([\[\]\(\)\{\}\-\.\*\?\|\^\$])/', '\$1', $q);
}
?>
stepanic dot matija at gmail dot com 21-Oct-2010 08:57
FIX-ed problem with highlighting second 'o' OR 'a', in this string

<?php
function highlight_string ($haystack, $needle, $highlight_class) {
         // return $haystack if there is no highlight color or strings given, nothing to do.

        $first_encode='XXXXXXXXXXXXXXX';     //ENCODE string

        $second_encode='YYYYYYYYYYYYYYY';

        preg_match_all("/$needle+/i", $haystack, $matches);
        if (is_array($matches[0]) && count($matches[0]) >= 1) {
            foreach ($matches[0] as $match) {
                $haystack = str_replace($match, $first_encode.$match.$second_encode, $haystack);
            }
        }

        $haystack=str_replace(array($first_encode,$second_encode),
array('<font class="'.$highlight_class.'" >','</font>'),$haystack);

        return $haystack;
}
?>
triplepoint at gmail dot com 23-Sep-2010 10:06
Regarding maintaining the case of the find/replace for search-highlighting purposes:

if the performance hit of a regular expression isn't a big problem, there's something like:

<?php
function highlight_matches($find_text, $text) {
  return preg_replace("/($find_text)/i", '<span class="search_item">$1</span>', $text);
}
?>
info at daniel-marschall dot de 22-Jun-2009 07:15
If you want to keep the original capitalization when replacing some text (e.g. for highlighting the search-string in the the search result), you can use this code I wrote:

<?php

// http://devboard.viathinksoft.de/viewtopic.php?f=34&t=771
// Bugfix-Release #3 (June, 22th 2009)
function ext_str_ireplace($findme, $replacewith, $subject)
{
     // Replaces $findme in $subject with $replacewith
     // Ignores the case and do keep the original capitalization by using $1 in $replacewith
     // Required: PHP 5

     $rest = $subject;
     $result = '';

     while (stripos($rest, $findme) !== false) {
          $pos = stripos($rest, $findme);

          // Remove the wanted string from $rest and append it to $result
          $result .= substr($rest, 0, $pos);
          $rest = substr($rest, $pos, strlen($rest)-$pos);

          // Remove the wanted string from $rest and place it correctly into $result
          $result .= str_replace('$1', substr($rest, 0, strlen($findme)), $replacewith);
          $rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme));
     }

     // After the last match, append the rest
     $result .= $rest;

     return $result;
}

?>
ishutko at gmail dot com 16-Mar-2009 01:49
For function work with cirilic

setlocale (LC_ALL, 'ru_RU');
sawdust 04-Dec-2008 07:28
Here's a different approach to search result keyword highlighting that will match all keyword sub strings in a case insensitive manner and preserve case in the returned text. This solution first grabs all matches within $haystack in a case insensitive manner, and the secondly loops through each of those matched sub strings and applies a case sensitive replace in $haystack. This way each unique (in terms of case) instance of $needle is operated on individually allowing a case sensitive replace to be done in order to preserve the original case of each unique instance of $needle.

<?php
function highlightStr($haystack, $needle, $highlightColorValue) {
     // return $haystack if there is no highlight color or strings given, nothing to do.
    if (strlen($highlightColorValue) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
        return $haystack;
    }
    preg_match_all("/$needle+/i", $haystack, $matches);
    if (is_array($matches[0]) && count($matches[0]) >= 1) {
        foreach ($matches[0] as $match) {
            $haystack = str_replace($match, '<span style="background-color:'.$highlightColorValue.';">'.$match.'</span>', $haystack);
        }
    }
    return $haystack;
}
?>
Michael dot Bond at mail dot wvu dot edu 14-Nov-2008 06:44
This function will highlight search terms (Key Words in Context).

The difference between this one and the ones below is that it will preserve the original case of the search term as well. So, if you search for "american" but in the original string it is "American" it will retain the capital "A" as well as the correct case for the rest of the string.

<?php
function kwic($str1,$str2) {

    $kwicLen = strlen($str1);

    $kwicArray = array();
    $pos          = 0;
    $count       = 0;

    while($pos !== FALSE) {
        $pos = stripos($str2,$str1,$pos);
        if($pos !== FALSE) {
            $kwicArray[$count]['kwic'] = substr($str2,$pos,$kwicLen);
            $kwicArray[$count++]['pos']  = $pos;
            $pos++;
        }
    }

    for($I=count($kwicArray)-1;$I>=0;$I--) {
        $kwic = '<span class="kwic">'.$kwicArray[$I]['kwic'].'</span>';
        $str2 = substr_replace($str2,$kwic,$kwicArray[$I]['pos'],$kwicLen);
    }

    return($str2);
}
?>
info at daniel-marschall dot de 02-Oct-2008 10:32
Example for str_ireplace(). It will print "RePlaCeMe" in red color, but after this, it would be written in lower case because of the string $search.

<?php

$search  = 'replaceme';
$replace = '<font color="#FF0000">'.$search.'</font>';
$text    = 'Please RePlaCeMe, OK?';

echo str_ireplace($search, $replace, $text);

?>

Example for ext_str_ireplace(). It will print "RePlaCeMe" in red color, and will not change the capitalization:

<?php

$search  = 'replaceme';
$replace = '<font color="#FF0000">$1</font>';
$text    = 'Please RePlaCeMe, OK?';

echo ext_str_ireplace($search, $replace, $text);

?>
Anonymous 05-Jun-2008 12:58
I modified a script from notes on the eregi_replace() function page.  This is a highlight script that worked good for me.

$text - is the text to search
$words - are the words to highlight (search text)
$the_place - is so that you can tell your users what "area" was searched.

<?php
function highlight_this($text, $words, $the_place) {
    $words = trim($words);
    $wordsArray = explode(' ', $words);
    foreach($wordsArray as $word) {
        if(strlen(trim($word)) != 0)
            $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);
    }
    //added to show how many keywords were found
    echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $count . "</strong> matches within the " . $the_place. ".</div><br>";

    //end script modification
    return $text;
}
?>
mvpetrovich 15-Feb-2008 03:28
Here are some minor tweaks to-n00b-at-battleofthebits-dot-org's excellent function.
1) The token was set to an ASCII value 1 (which could be changed as was previously noted)
2) The $c++ was not needed
3) The while statement is not necessary for the final replacement
4) Note that this does not allow use of arrays for search and replace terms.  That could be implemented using loops.

<?php
if(!function_exists('str_ireplace')){
  function str_ireplace($search,$replace,$subject){
    $token = chr(1);
    $haystack = strtolower($subject);
    $needle = strtolower($search);
    while (($pos=strpos($haystack,$needle))!==FALSE){
      $subject = substr_replace($subject,$token,$pos,strlen($search));
      $haystack = substr_replace($haystack,$token,$pos,strlen($search));
    }
    $subject = str_replace($token,$replace,$subject);
    return $subject;
  }
}
?>
hfuecks at nospam dot org 04-Jul-2005 02:07
Note that character case is being defined by your server's locale setting, which effects strings containing non-ASCII characters.

See strtolower() - http://www.php.net/strtolower and comments - internally str_ireplace converts $search and $replace to lowercase to find matches.
daevid at daevid dot com 05-Apr-2005 01:14
here's a neat little function I whipped up to do HTML color coding of SQL strings.

<?php
/**
 * Output the HTML debugging string in color coded glory for a sql query
 * This is very nice for being able to see many SQL queries
 * @access     public
 * @return     void. prints HTML color coded string of the input $query.
 * @param     string $query The SQL query to be executed.
 * @author     Daevid Vincent [daevid@LockdownNetworks.com]
 *  @version     1.0
 * @date        04/05/05
 * @todo     highlight SQL functions.
 */
function SQL_DEBUG( $query )
{
    if( $query == '' ) return 0;

    global $SQL_INT;
    if( !isset($SQL_INT) ) $SQL_INT = 0;

    //[dv] this has to come first or you will have goofy results later.
    $query = preg_replace("/['\"]([^'\"]*)['\"]/i", "'<FONT COLOR='#FF6600'>$1</FONT>'", $query, -1);

    $query = str_ireplace(
                            array (
                                    '*',
                                    'SELECT ',
                                    'UPDATE ',
                                    'DELETE ',
                                    'INSERT ',
                                    'INTO',
                                    'VALUES',
                                    'FROM',
                                    'LEFT',
                                    'JOIN',
                                    'WHERE',
                                    'LIMIT',
                                    'ORDER BY',
                                    'AND',
                                    'OR ', //[dv] note the space. otherwise you match to 'COLOR' ;-)
                                    'DESC',
                                    'ASC',
                                    'ON '
                                  ),
                            array (
                                    "<FONT COLOR='#FF6600'><B>*</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>SELECT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>UPDATE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>DELETE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INSERT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INTO</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>VALUES</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>FROM</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>LEFT</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>JOIN</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>WHERE</B></FONT>",
                                    "<FONT COLOR='#AA0000'><B>LIMIT</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>ORDER BY</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>AND</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>OR</B> </FONT>",
                                    "<FONT COLOR='#0000AA'><B>DESC</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>ASC</B></FONT>",
                                    "<FONT COLOR='#00DD00'><B>ON</B> </FONT>"
                                  ),
                            $query
                          );

    echo "<FONT COLOR='#0000FF'><B>SQL[".$SQL_INT."]:</B> ".$query."<FONT COLOR='#FF0000'>;</FONT></FONT><BR>\n";

    $SQL_INT++;

} //SQL_DEBUG
?>
aidan at php dot net 30-May-2004 10:36
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
str_getcsv
str_pad
Обработка строк


Дополняет строку другой строкой до заданной длины

str_ireplace
str_repeat
Обработка строк
PHP Manual

str_pad

(PHP 4 >= 4.0.1, PHP 5)

str_pad — Дополняет строку другой строкой до заданной длины

Описание

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Эта функция возвращает строку input, дополненную слева, справа или с обоих сторон до заданной длины. Если необязательный аргумент pad_string не передан, то input будет дополнен пробелами, иначе он будет дополнен символами из pad_string до нужной длины

Список параметров

input

Входная строка.

pad_length

Если значение pad_length отрицательно, меньше или равно длине входной строки, то дополнения не происходит.

pad_string

Замечание:

pad_string может быть урезана, если необходимое количество дополняемых символов не делится нацело на длину строки pad_string.

pad_type

Необязательный аргумент pad_type может иметь значение STR_PAD_RIGHT, STR_PAD_LEFT или STR_PAD_BOTH. Если не указан, то по умолчанию используется STR_PAD_RIGHT.

Возвращаемые значения

Возвращает дополненную строку.

Примеры

Пример #1 Пример использования str_pad()

<?php
$input = "Alien";
echo str_pad($input, 10);                      // выводит "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // выводит "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // выводит "__Alien___"
echo str_pad($input, 6 , "___");               // выводит "Alien_"
?>

User Contributed Notes

sergey 12-Oct-2011 02:45
You can use trim functions for clearpad string:

ltrim("0001230", "0") -> 1230
rtrim("0123000", "0") -> 0123
trim("0012300")     -> 123
gene at swipesy dot com 24-Sep-2011 09:18
This is how I pad using &nbsp; :

str_replace(" ", "&nbsp;&nbsp;", str_pad($foo, 10, " ", STR_PAD_LEFT))

Seems to work well using two &nbsp; tags for each character added, at least for my use. YMMV.
goellerk at bucks dot edu 07-Jun-2010 12:43
Apparently, as of 5.3.2 the notations "STR_PAD_LEFT" and "STR_PAD_RIGHT" are case sensitive.

$yr = "10";
$yr = str_pad($yr,2,'0',str_pad_left);
print "yr = '$yr'";
yr = '  '

$yr = "10";
$yr = str_pad($yr,2,'0',STR_PAD_LEFT);
print "yr = '$yr'";
yr = '10'
hernanc 24-Apr-2009 08:45
To get Monday and Sunday's dates of the current week in Y-m-d format  do:

<?php
$mon_date = date('Y-m-d',strtotime(date('Y') . 'W' . str_pad(date('W'), 2, '0',STR_PAD_LEFT) .'1'));
$sun_date =  date('Y-m-d',strtotime(date('Y') . 'W' . str_pad(date('W'), 2, '0',STR_PAD_LEFT).'7'));
?>
Kari &#34;Haprog&#34; Sderholm 21-Mar-2009 06:43
Here's a quick and simple way to make an mb_str_pad function that works when you have correctly set your internal encoding.

I'm not sure how well this works in all possible scenarios but atleast it worked for me using UTF-8 as internal encoding and using this function on strings containing scandinavian characters "åäöÅÄÖ" that are double byte in UTF-8.

<?php
function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
    $diff = strlen($input) - mb_strlen($input);
    return str_pad($input, $pad_length+$diff, $pad_string, $pad_type);
}
?>
matrebatre 16-Oct-2008 11:28
Here is a simple function to convert numbers into strings like this:

0 => 0000
1 => 0001
20 => 0020
432 => 0432

<?php

function number_pad($number,$n) {
return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
}

?>

$n indicates how many characters you want.
albert dot serra at camaleongroup dot com 22-Jul-2008 06:36
<?php
/** Description
   * padclear, clear a pad varchar(9) "*****HOME" -> varchar(4) "HOME"
   * _no use for INT_ : varchar(5) "00100" -> int(3) "100", use $number = (int) "00100";
   *
   * @param string, string original
   * @param char, character to replace
   * @param charreplace, final character
   * @param type, [STR_PAD_RIGHT|STR_PAD_LEFT] see str_pad
   * @return string, transformed string with charreplace
   */
  function padclear($string, $char, $charreplace = null,$type = STR_PAD_RIGHT) {

      $strlen = strlen($string) - 1;
      $i = ($type == STR_PAD_RIGHT) ? 0 : $strlen;
      $stop = ($type == STR_PAD_RIGHT) ? $strlen : 0;
      $difpos = null;
      while(is_null($difpos) && $i != $stop) {
        $difpos = ($string[$i] != $char) ? $i : null;
        if($type == STR_PAD_RIGHT) $i++;
        else $i--;
      }

      if($type == STR_PAD_RIGHT) {
        $ant = str_replace($char,$charreplace,substr($string,0,$difpos));
         $nxt = substr($string,$difpos,$strlen);
      } else {
        $ant = substr($string,0,$difpos);
        $nxt = str_replace($char,$charreplace,substr($string,$difpos,$strlen));
      }

      return $ant . $nxt;
  }

  $string = "HOME*******";
  echo padclear($string,'*','',STR_PAD_LEFT);  // HOME
  $string = "*****HOME";
  echo padclear($string,'*','',STR_PAD_RIGHT); // HOME
?>
bxi at apparoat dot nl 20-Mar-2008 06:17
In case you want to pad 2 strings together with a character you can use:

<?php
function pad_between_strings($string1, $string2, $length, $char = " ") {
    $fill_length = $length - ( strlen($string1) + strlen($string2) );
    return $string1 . str_repeat($char, $fill_length) . $string2;
}
?>
Spudley 18-Jul-2007 08:47
Warning: If your string includes non-ascii characters (eg the British pounds sign), str_pad() will treat these as two characters when calculating the padding.

So for example:
<?php
str_pad($currency_symbol.$showtottopay,12," ",STR_PAD_LEFT);
?>
will produce a different length string depending on whether $currency_symbol is pounds or dollars.

Hope this helps someone -- it caused me a lot of problems with misaligned columns in my invoices until I worked it out.
christian dot reinecke at web dot de 01-Apr-2007 10:43
Fills the first argument (mostly a number, f.e. from a <select> loop to display a date or time) with zeroes.

<?php
function zerofill($mStretch, $iLength = 2)
{
    $sPrintfString = '%0' . (int)$iLength . 's';
    return sprintf($sPrintfString, $mStretch);
}
?>

sprintf() is indeed faster than str_pad.
Charles 05-Dec-2006 03:53
More corrections to the original flap / Tomek Krzeminski code below (well someone has to check it!) -- the code is a bit mangled but it is still the same:

<?php

function mb_str_pad($ps_input, $pn_pad_length, $ps_pad_string = " ", $pn_pad_type = STR_PAD_RIGHT, $ps_encoding = NULL) {
  $ret = "";

  if (is_null($ps_encoding))
    $ps_encoding = mb_internal_encoding();

  $hn_length_of_padding = $pn_pad_length - mb_strlen($ps_input, $ps_encoding);
  $hn_psLength = mb_strlen($ps_pad_string, $ps_encoding); // pad string length

  if ($hn_psLength <= 0 || $hn_length_of_padding <= 0) {
    // Padding string equal to 0:
    //
    $ret = $ps_input;
    }
  else {
    $hn_repeatCount = floor($hn_length_of_padding / $hn_psLength); // how many times repeat

    if ($pn_pad_type == STR_PAD_BOTH) {
      $hs_lastStrLeft = "";
      $hs_lastStrRight = "";
      $hn_repeatCountLeft = $hn_repeatCountRight = ($hn_repeatCount - $hn_repeatCount % 2) / 2;

      $hs_lastStrLength = $hn_length_of_padding - 2 * $hn_repeatCountLeft * $hn_psLength; // the rest length to pad
      $hs_lastStrLeftLength = $hs_lastStrRightLength = floor($hs_lastStrLength / 2);      // the rest length divide to 2 parts
      $hs_lastStrRightLength += $hs_lastStrLength % 2; // the last char add to right side

      $hs_lastStrLeft = mb_substr($ps_pad_string, 0, $hs_lastStrLeftLength, $ps_encoding);
      $hs_lastStrRight = mb_substr($ps_pad_string, 0, $hs_lastStrRightLength, $ps_encoding);

      $ret = str_repeat($ps_pad_string, $hn_repeatCountLeft) . $hs_lastStrLeft;
      $ret .= $ps_input;
      $ret .= str_repeat($ps_pad_string, $hn_repeatCountRight) . $hs_lastStrRight;
      }
    else {
      $hs_lastStr = mb_substr($ps_pad_string, 0, $hn_length_of_padding % $hn_psLength, $ps_encoding); // last part of pad string

      if ($pn_pad_type == STR_PAD_LEFT)
        $ret = str_repeat($ps_pad_string, $hn_repeatCount) . $hs_lastStr . $ps_input;
      else
        $ret = $ps_input . str_repeat($ps_pad_string, $hn_repeatCount) . $hs_lastStr;
      }
    }

  return $ret;
  }

?>
rafaeljaquestudojunto at gmail dot com 11-Sep-2006 05:43
Looking forward to make some dynamic tabulation, i've noticed that the output appeared twice. I suppose that the parser recognize \t, \n and any other special character as a single character...

So.. If you need 4 tabulatins, just make...

<?php

print str_pad('',4,"\t");

?>
Silvio Ginter (silvio dot ginter at gmx dot de) 15-Nov-2005 08:43
Hello,

for anyone who needs this, I wrote this extension to str_pad. For details, just look at the comments.

<?php

$string = 'this is a test';
$oldLen = strlen($string);
$direction = STR_PAD_BOTH;
echo $string.'<br>';
echo str_const_len($string, 101, '#', $direction).'<br>';
echo $string.'<br>';
echo str_const_len($string, $oldLen, '#', $direction).'<br>';
echo $string.'<br><br>'."\n";

/*     This function is an extension to str_pad, it manipulates the referenced
    string '$str' and stretches or reduces it to the specified length. It
    returns the number of characters, that were added or stripped. */
function str_const_len(&$str, $len, $char = ' ', $str_pad_const = STR_PAD_RIGHT) {
    $origLen = strlen($str);
    if (strlen($str) < $len) {     /* stretch string */
        $str = str_pad($str, $len, $char, $str_pad_const);
    }
    else {                         /* reduce string */
        switch ($str_pad_const) {
            case STR_PAD_LEFT:
                $str = substr($str, (strlen($str) - $len), $len);
                break;
            case STR_PAD_BOTH:
                $shorten = (int) ((strlen($str) - $len) / 2);
                $str = substr($str, $shorten, $len);
                break;
            default:
                $str = substr($str, 0, $len);
                break;
        }
    }
    return ($len - $origLen);
}
?>
private dot email at optusnet dot com dot au 10-Aug-2005 05:04
I wrote these 3 functions that live in a library i include in every programme. I find them useful, and the syntax is easy.

<?php

$str = "test";

function str_pad_right ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_RIGHT );
    return $str;
}

function str_pad_left ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_LEFT );
    return $str;
}

function str_pad_both ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + ( $int * 2 );
    $str = str_pad ( $string , $i , $padchar , STR_PAD_BOTH );
    return $str;
}

echo str_pad_left ( $str , "-" , 3 ); // Produces: ---test
echo str_pad_right ( $str , "-" , 3 ); // Produces: test---
echo str_pad_both ( $str , "-" , 3 ); // Produces: ---test---
?>

Hope this can help someone!
zubfatal <root at it dot dk> 27-Mar-2005 09:28
<?php
    /**
     * str_pad_html - Pad a string to a certain length with another string.
     * accepts HTML code in param: $strPadString.
     *
     * @name        str_pad_html()
     * @author        Tim Johannessen <root@it.dk>
     * @version        1.0.0
     * @param        string    $strInput    The array to iterate through, all non-numeric values will be skipped.
     * @param        int    $intPadLength    Padding length, must be greater than zero.
     * @param        string    [$strPadString]    String to pad $strInput with (default: &nbsp;)
     * @param        int        [$intPadType]        STR_PAD_LEFT, STR_PAD_RIGHT (default), STR_PAD_BOTH
     * @return        string    Returns the padded string
    **/
    function str_pad_html($strInput = "", $intPadLength, $strPadString = "&nbsp;", $intPadType = STR_PAD_RIGHT) {
        if (strlen(trim(strip_tags($strInput))) < intval($intPadLength)) {

            switch ($intPadType) {
                 // STR_PAD_LEFT
                case 0:
                    $offsetLeft = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    $offsetRight = 0;
                    break;

                // STR_PAD_RIGHT
                case 1:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;

                // STR_PAD_BOTH
                case 2:
                    $offsetLeft = intval(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2);
                    $offsetRight = round(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2, 0);
                    break;

                // STR_PAD_RIGHT
                default:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;
            }

            $strPadded = str_repeat($strPadString, $offsetLeft) . $strInput . str_repeat($strPadString, $offsetRight);
            unset($strInput, $offsetLeft, $offsetRight);

            return $strPadded;
        }

        else {
            return $strInput;
        }
    }

?>
tacomage at NOSPAM dot devilishly-deviant dot net 07-Jul-2004 08:04
If you want to pad a string to a certain screen length with &nbsp; or other HTML entities, but don't want to risk messing up any HTML characters inside the string, try this:

<?php
function str_pad_as_single($input, $len, $pad, $flag=STR_PAD_RIGHT)
{
  $trans=array('$'=>$input,' '=>$pad);
  $output=str_pad('$',$len-strlen($input)+1,' ',$flag);
  $output=strtr($output,$trans);
  return $output;
}
echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;');
// will output <img src="some.gif">&nbsp;&nbsp;

echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_BOTH);
// will output &nbsp;<img src="some.gif">&nbsp;

echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_LEFT);
// will output &nbsp;&nbsp;<img src="some.gif">
?>

It works by using single characters for str_pad, then replacing the characters with the full strings using strtr, so the two strings can't interfere with each other.  It also conveniently has the same syntax as str_pad.  Yes, I realize that spacing an image with text isn't the best idea, but it's just an example, it'll apply to other HTML as well :-P
giorgio dot balestrieri at mail dot wind dot it 09-Mar-2004 08:49
For number formatting (like writing numbers with leading zeroes etc.) , sprintf is much faster than str_pad.
Consider the following snippet (it take some minutes to run):

<?php
  echo "str_pad test started, please wait...\n";

  $intStart = time();
  for ($idx = 1; $idx <= 10000000; $idx++)
    $strFoo = str_pad($idx, 10, "0", STR_PAD_LEFT);
  $intEnd = time();

  echo "str_pad cycle completed in " . ($intEnd - $intStart) . " seconds\n";
  echo "sprintf test started, please wait...\n";

  $intStart = time();
  for ($idx = 1; $idx <= 10000000; $idx++)
    $strFoo = sprintf("%010d", $idx);
  $intEnd = time();

  echo "sprintf cycle completed in " . ($intEnd - $intStart) . " seconds\n";
?>

The str_pad cyle runs 80-100% slower on my pc...
bob [at] bobarmadillo [dot] com 03-Dec-2002 09:22
In a lot of cases you're better off using str_repeat if you want to use something like   - it repeats the entire string.

Using str_repeat, I wrote a full string pad function that should closely mimic str_pad in every other way:

<?php
function full_str_pad($input, $pad_length, $pad_string = '', $pad_type = 0) {
 $str = '';
 $length = $pad_length - strlen($input);
 if ($length > 0) { // str_repeat doesn't like negatives
  if ($pad_type == STR_PAD_RIGHT) { // STR_PAD_RIGHT == 1
   $str = $input.str_repeat($pad_string, $length);
  } elseif ($pad_type == STR_PAD_BOTH) { // STR_PAD_BOTH == 2
   $str = str_repeat($pad_string, floor($length/2));
   $str .= $input;
   $str .= str_repeat($pad_string, ceil($length/2));
  } else { // defaults to STR_PAD_LEFT == 0
   $str = str_repeat($pad_string, $length).$input;
  }
 } else { // if $length is negative or zero we don't need to do anything
  $str = $input;
 }
 return $str;
}

$pad_me = "Test String";
echo '|'.full_str_pad($pad_me, 20, ' ')."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_RIGHT)."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_BOTH)."|\n";
?>
david dot rensonnet at swing dot be 02-Dec-2002 03:18
my solution to saveloywill at netscape dot net:

$myvar2="Alien";
$myvar=str_pad($myvar2,15," ",STR_PAD_RIGHT);
$myvar=str_replace(" ","&nbsp;",$myvar);

this way, only complete spaces will show up.

enjoy!
david rensonnet
Fahad dot Gilani at anu dot edu dot au 02-Dec-2002 02:22
Basically, *all* of you guys have a 'long' way of padding text with html tags (which includes &nbsp;) You dont even have to do a str_replace... try the following code and this will work with ANY html tag there is out there and you don't have to worry about tag character lengths so on and so forth:
<?
  $text = "This is pretty interesting!";
  $pad_string = "&nbsp;";

  //Pad text on both sides
  $text = str_pad($text, strlen($text)+(20*strlen($pad_string)), $pad_string, STR_PAD_BOTH);
  print $text." Dont you think?";
?>
Will produce:
          This is pretty interesting!           Dont you think?

Cheers,
Fahad
no dot spam at no dot spam dot no 26-Sep-2002 04:28
there could already be spaces in the string.

1) strlen the string
2) replace spaces with "AUniqueString"
3) strlen the new string
4) compare the two strlen's
5) pad as needed considering the new strlen
6) finally, replace all "AUniqueString" 's with &nbsp; 's

hack & a half, slow as well i bet
cd579 at hotmail dot com 22-Aug-2002 01:53
Why not just use a space[' '] instead of a character that COULD be inside the string, and risk messing it up?  Example:

$string = 'test';

$string = str_pad($string, 10, " ", STR_PAD_BOTH);
// $string now equals '      test'

$string = str_replace(" ", "&nbsp;", $string);
mreilly at NOSPAM dot mac dot com 20-Aug-2002 11:23
When provided with a string of characters as the pad value, str_pad uses all the characters as fill, and can leave partial strings. (eg. If the pad value is 'ABC' and it needs 5 characters to pad with, it outputs 'ABCAB'.) This is a problem when you want to pad with non-breaking spaces, the code for which is 6 characters long.

This can be resolved by first padding the string with a single character that won't be found in the strings such as * then doing a str_replace of * with &nbsp;.
saveloywill at netscape dot net 10-Aug-2002 12:50
Here is my solution to the above problem.
Simply place the code in question inbetween  html <pre> tags, like this:

<?php
print "<pre>";
$input = "Alien";
print str_pad($input, 10);
print "*";
print "</pre>";
?>

Thanks.
pozytron#mac#com 08-Jul-2002 02:20
The trouble with cj@NOSPAM.ceejayoz.com's version over pestilenc@hotmail.com's is that many of the times it is used, it will end up with fragments of the "&nbsp;" code.

For example, the following code:
<?php
echo str_pad("TESTSTRING",60,"&nbsp;",STR_PAD_BOTH);
?>

produces the following HTML output:
&nbsp;&nbsp;&nbsp;&nbsp;&TESTSTRING&nbsp;&nbsp;&nbsp;&nbsp;&
cj at NOSPAM dot ceejayoz dot com 17-Jun-2002 12:38
Another solution to no_email@php.net's problem would be to simply multiply the padding string by 6.

e.g.

$string = str_pad($string, 10, "&nbsp;", STR_PAD_BOTH);

becomes

$string = str_pad($string, 60, "&nbsp;", STR_PAD_BOTH);

which will avoid problems with the above solution, which will mess up text that has the * in it (or whichever character you're replacing)
pestilenc at hotmail dot com 06-Jun-2002 04:26
For me this worked.
$string = 'help';

#First, str_pad() with unique character.
$string = str_pad($string, 10, "*", STR_PAD_BOTH);
#$string = '***help***';

#Second, str_replace with '&nbsp;'
$string = str_replace("*", "&nbsp;", $string);
no_email at php dot net 30-May-2002 10:34
To convert your string couldnt you just use strval($var)?

What if you want non-breaking spaces? If I try to str_pad with "&nbsp;" PHP thinks my padding string is 6 characters, whn in HTML it is only one.
jared at dctkc dot com 03-May-2002 04:25
matthew.somerville's code did NOT work for me.
neither did bert@catsburg.com's.
neither did any other documentation.
(if I isolated the code by itself, they all worked; but in the context I was using it, $value was numeric, and there is NO WAY to force it to be a string in PHP).

I had to roll my own. I used 'trim' to _force_
the value of $value to be string, because as
long as PHP thought it was numeric, I could
not use any form of left-padding with zeros.

This worked (I use sprintf to left-pad
$value with zeros to a length of 4):

sprintf("%04s",trim($value));
matthew dot somerville at trinity dot oxford dot ac dot uk 05-Aug-2001 06:53
I find:

$mystr = substr("0000$mystr",-4)

(where the 0s are padding characters and -4 is the negative of the maxlength to pad to) is even simpler.
str_ireplace
str_repeat
Обработка строк


Возвращает повторяющуюся строку

str_pad
str_replace
Обработка строк
PHP Manual

str_repeat

(PHP 4, PHP 5)

str_repeat — Возвращает повторяющуюся строку

Описание

string str_repeat ( string $input , int $multiplier )

Возвращает строку input, повторенную multiplier раз.

Список параметров

input

Повторяемая строка.

multiplier

Количество раз, которые нужно повторить строку input.

multiplier должен быть больше или равен нулю. Если он равен нулю, возвращается пустая строка.

Возвращаемые значения

Возвращает повторяющуюся строку.

Примеры

Пример #1 Пример использования str_repeat()

<?php
echo str_repeat("-=", 10);
?>

Результат выполнения данного примера:

-=-=-=-=-=-=-=-=-=-=

Смотрите также

  • for
  • str_pad() - Дополняет строку другой строкой до заданной длины
  • substr_count() - Возвращает число вхождений подстроки

User Contributed Notes

divinity76 at gmail dot com 18-Nov-2011 06:58
no idea how many times i have written this.
function br($times=1,$definition="<br/>\n")
{
echo str_repeat($definition,$times);
}
Anonymous 23-Oct-2011 04:51
hi guys ,
i've faced this example :
<?php

$my_head = str_repeat("°~", 35);
echo $my_head;

?>

so , the length should be 35x2 = 70 !!!
if we echo it :

<?php
$my_head = str_repeat("°~", 35);
echo strlen($my_head); // 105
echo mb_strlen($my_head, 'UTF-8'); // 70
?>

be carefull with characters and try to use mb_* package to make sure everything goes well ...
r3d dot w0rm at yahoo dot com 22-Feb-2010 12:52
str_repeat() Function Integer Overflow

For more info see :

http://bugs.php.net/bug.php?id=51105
Damien Bezborodov 28-Apr-2009 12:45
Here is a simple one liner to repeat a string multiple times with a separator:

<?php
implode($separator, array_fill(0, $multiplier, $input));
?>

Example script:
<?php

// How I like to repeat a string using standard PHP functions
$input = 'bar';
$multiplier = 5;
$separator = ',';
print implode($separator, array_fill(0, $multiplier, $input));
print "\n";

// Say, this comes in handy with count() on an array that we want to use in an
// SQL query such as 'WHERE foo IN (...)'
$args = array('1', '2', '3');
print implode(',', array_fill(0, count($args), '?'));
print "\n";
?>

Example Output:
bar,bar,bar,bar,bar
?,?,?
claude dot pache at gmail dot com 10-Feb-2009 02:25
Here is a shorter version of Kees van Dieren's function below, which is moreover compatible with the syntax of str_repeat:

<?php
function str_repeat_extended($input, $multiplier, $separator='')
{
    return $multiplier==0 ? '' : str_repeat($input.$separator, $multiplier-1).$input;
}
?>
Kees van Dieren 16-Jan-2009 01:26
Needed a function to repeat a string with a separator.

<?php
/**
 * Repeats <tt>$string</tt> <tt>$multiplier</tt> times, separated with <tt>$sep</tt>.
 *
 * str_repeat_sep('?', ',', 3) ==> "?,?,?"
 * str_repeat_seap('..', '/', 3) ==> "../../.."
 *
 * @param string $string
 * @param string $sep
 * @param int $multiplier
 * @return string
 */
function str_repeat_sep($string, $sep, $multiplier) {
  $ret = "";
  for($i=0;$i<$multiplier;$i++) {
    if ($i) $ret.=$sep;
    $ret.=$string;
  }
  return $ret;
}
?>
Alper Kaya 30-Jun-2007 03:09
If you want to hide a part of your password, you can use this code. It's very simple and might be required in your user management panel.

<?php
$password = "12345abcdef";
$visibleLength = 4; // 4 chars from the beginning

echo substr($password,0,4).str_repeat("*", (strlen($password)-$visibleLength));
?>
15-Sep-2005 07:32
In reply to what Roland Knall wrote:

It is much simpler to use printf() or sprintf() for leading zeros.

<?php
   printf("%05d<br>\n",  1); // Will echo 00001
   sprintf("%05d<br>\n",  1); // Will return 00001
?>
21-Jul-2003 10:45
str_repeat does not repeat symbol with code 0 on some (maybe all?) systems (tested on PHP Version 4.3.2 , FreeBSD 4.8-STABLE i386 ).

Use <pre>
while(strlen($str) < $desired) $str .= chr(0);
</pre> to have string filled with zero-symbols.
dakota at dir dot bg 25-Jun-2002 03:06
Note that the first argument is parsed only once, so it's impossible to do things like this:

echo str_repeat(++$i, 10);

The example will produce 10 times the value of $i+1, and will not do a cycle from $i to $i+10.
bryantSPAMw at geocities dot SPAM dot com 25-Oct-2001 04:16
(For the benefit of those searching the website:)

This is the equivalent of Perl's "x" (repetition) operator, for eg.  str_repeat("blah", 8) in PHP does the same thing as "blah" x 8 in Perl.
str_pad
str_replace
Обработка строк


Заменяет все вхождения строки поиска на строку замены

str_repeat
str_rot13
Обработка строк
PHP Manual

str_replace

(PHP 4, PHP 5)

str_replace — Заменяет все вхождения строки поиска на строку замены

Описание

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Эта функция возвращает строку или массив, в котором все вхождения search в subject заменены на replace.

Если не нужны сложные правила поиска/замены (например, регулярные выражения), использование этой функции предпочтительнее preg_replace().

Список параметров

Если search и replace - массивы, то str_replace() использует каждое значение из соответствующего массива для поиска и замены в subject. Если в массиве replace меньше элементов, чем в search, в качестве строки замены для оставшихся значений будет использована пустая строка. Если search - массив, а replace - строка, то эта строка замены будет использована для каждого элемента массива search. Обратный случай смысла не имеет.

Если search или replace являются массивами, их элементы будут обработаны от первого к последнему.

search

Искомое значение, также известное как needle (иголка). Для множества искомых значений можно использовать массив.

replace

Значение замены, будет использовано для замены искомых значений search. Для множества значений можно использовать массив.

subject

Строка или массив, в котором производится поиск и замена, также известный как haystack (стог сена).

Если subject является массивом, то поиск с заменой будет осуществляться над каждым элементом subject, а результатом функции также будет являться массив.

count

Если передан, то будет установлен в количество произведенных замен.

Возвращаемые значения

Эта функция возвращает строку или массив с замененными значениями.

Список изменений

Версия | Описание
5.0.0 | Добавлен параметр count.
4.3.3 | Поведение этой функции изменилось. В старых версиях существовала ошибка при одновременной передаче массивов в аргументах search и replace. Ошибка заключается в том, что пустые элементы массива search пропускались без перемещения к следующему элементу массива replace. Эта ошибка была исправлена в PHP 4.3.3. Если ваши скрипты использовали эту ошибку, то в них нужно удалить пустые элементы из массива search перед вызовом этой функции.
4.0.5 | Большинство параметров теперь могут принимать тип array.

Примеры

Пример #1 Примеры использования str_replace()

<?php
// присваивает <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// присваивает: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

// присваивает: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// присваивает: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>

Пример #2 Примеры потенциальных трюков с str_replace()

<?php
// Порядок замены
$str     = "Строка 1\nСтрока 2\rСтрока 3\r\nСтрока 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';

// Обрабатывает сначала \r\n для избежания их повторной замены.
echo $newstr = str_replace($order, $replace, $str);

// Выводит F, т.к. A заменяется на B, затем B на C, и так далее...
// В итоге E будет заменено F, так как замена происходит слева направо.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Выводит: яблорехкорех орех (по вышеуказанной причине)
$letters = array('я', 'о');
$fruit   = array('яблоко', 'орех');
$text    = 'я о';
$output  = str_replace($letters, $fruit, $text);
echo $output;
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Предостережение

Замечание о порядке замены

Так как str_replace() осуществляет замену слева направо, то при использовании множественных замен она может заменить ранее вставленное значение на другое. Смотрите также примеры на этой странице.

Замечание:

Эта функция чувствительна к регистру. Используйте str_ireplace() для замены, нечувствительной к регистру.

Смотрите также

  • str_ireplace() - Регистро-независимый вариант функции str_replace
  • substr_replace() - Заменяет часть строки
  • preg_replace() - Выполняет поиск и замену по регулярному выражению
  • strtr() - Преобразует заданные символы или заменяет подстроки

User Contributed Notes

eggmatters at gmail dot com 24-May-2012 01:02
I noticed that if you use mysql_real_escape_string() before performing str_replace, it won't work. This may be dependent on the string being replaced. Specifically, the following, won't work:

<?php
$formattedPost = mysql_real_escape_string($formattedPost);
$formattedPost = str_replace("\\r\\n", "<br>", $comment);
?>

Do this instead:

<?php
$formattedPost = str_replace("\\r\\n", "<br>", $comment);
$formattedPost = mysql_real_escape_string($formattedPost);
?>
christof dot rieger at r-tron dot de 25-Apr-2012 08:41
In many countries the numeric format is 1.000,33 in english it is 1,000.33

This function converts numeric arguments always into the PHP confirm numeric format. If only one seperator is into the numericstring so it is interpreted as the decimalpoint.

 function dp($zahl)
{
  if ((strpos($zahl,".") > "-1") | (strpos($zahl,",") > "-1")) {
    if ((strpos($zahl,".") > "-1") & (strpos($zahl,",") > "-1")) {
      if (strpos($zahl,".") > strpos($zahl,",")){
          return str_replace(",","",$zahl);
    } else {
          return str_replace(",",".",str_replace(".","",$zahl));
      }
  } else {
      if (strpos($zahl,".") > "-1") {
        if (strpos($zahl,".") == strrpos($zahl,".")) {
            return $zahl;
      } else {
          return str_replace(".","",$zahl);
        }
    } else {
        if (strpos($zahl,",") == strrpos($zahl,",")) {
          return str_replace(",",".",$zahl);
      } else {
          return str_replace(",","",$zahl);
        }
    } }
} else {
    return $zahl;
} }
alice2287 at live dot com 10-Apr-2012 08:50
I was surprisingly unable to find a function for performing replaces on strings that allowed for the specification of a limit on the number of occurrences of $search to replace. Here's a function that allows you to do so, and a second function that does the same while starting the replace from the last occurrence of $search:

<?php
function str_replace_limit($search,$replace,$subject,$limit,&$count = null)
{
    $count = 0;
    if ($limit <= 0) return $subject;
    $occurrences = substr_count($subject,$search);
    if ($occurrences === 0) return $subject;
    else if ($occurrences <= $limit) return str_replace($search,$replace,$subject,$count);
    //Do limited replace
    $position = 0;
    //Iterate through occurrences until we get to the last occurrence of $search we're going to replace
    for ($i = 0; $i < $limit; $i++)
        $position = strpos($subject,$search,$position) + strlen($search);
    $substring = substr($subject,0,$position + 1);
    $substring = str_replace($search,$replace,$substring,$count);
    return substr_replace($subject,$substring,0,$position+1);
}

function str_replace_limit_reverse($search,$replace,$subject,$limit,&$count = null)
{
    $count = 0;
    $search = strrev($search);
    $replace = strrev($replace);
    $subject = strrev($subject);
    return strrev(str_replace_limit($search,$replace,$subject,$limit,$count));
}
?>
Denzel Morris 06-Apr-2012 02:43
Maybe obvious to veteran PHP programmers but less so to novice PHP programmers is the fact that this is invalid:
<?php
str_replace($search, $replace, $subject, 1);
?>
At a glance it appears to be a reasonable request, until you realize that the fourth parameter must be a variable in order to be passed as a reference. A replacement:
<?php
str_replace($search, $replace, $subject, $temp = 1);
// or
$temp = 1;
str_replace($search, $replace, $subject, $temp);
?>
cc at cc dot com 31-Mar-2012 05:26
I found a pretty low tech solution to avoid the "gotcha" without worrying about the array order of how things are replaced. I could not "order" the replacement array easily because it was being read from a database table.

Anyway if you add an identifiable token to each replaced word, then just filter this out at the very end, no nested search terms are found. I just dynamically add the %% after the first char of each word before pumping it into the str_ireplace function.

$find = array("as1", "as2", "as3", "flex");
$replace = array("<a href = \"#as1\">A%%uto S%%entry R%%ev. A%%</a>", "<a href = \"#as2\">A%%uto S%%entry E%%xp</a>", "<a href = \"#as3\">A%%uto S%%entry f%%lex</a>", "<a style = \"color: red;\" href = \"#flex\">f%%lex</a>");
$text = str_ireplace($find, $replace, $text);
echo str_ireplace("%%", "", $text);

In this case I am using %% as my token as this is an unlikely char combo for me.
Kai Hoerner 30-Mar-2012 10:34
If you want to replace only a specific occurance of a needle, you can use this handy function:

<?php
function str_replace_occurance($search, $replace, $subject, $occurance) {
   $pos = 0;
   for ($i = 0; $i <= $occurance; $i++) {
       $pos = strpos($subject, $search, $pos);
   }
   return substr_replace($subject, $replace, $pos, strlen($search));
}

$str = "hello world! hello again! say hello!";
$str = str_replace_occurance('hello', 'hi', $str, 1);
$str = str_replace_occurance('hello', 'lets do this', $str, 2);
echo $str, PHP_EOL;

?>

Example output: "hi world! lets do this again! say hello!"
windowshater 24-Nov-2011 12:15
I hope this helps someone who has gone insane for 4 hours...

If you have someone posting weird windows curly quotes into your forms and you cannot replace them using str_replace.

I tried using mb_convert_encoding to convert the string to UTF-8 and then to do a str_replace but still no joy.

I tried to str_replace using the \xe2\x80\x98 codes and also using the chr(145), chr(146), chr(147) codes.

Nothing worked... It would replace the quotes but then ADD a question mark in a diamond !!!! no idea why..

in the end i just url encoded the string and replaced teh html codes:

$search_weird_chars = array(    '%E2%80%99',
                        '%E2%80%99',
                        '%E2%80%98',
                        '%E2%80%9C',
                        '%E2%80%9D'
                        );

$this->post_array[$key] = urlencode($this->post_array[$key]);

                $this->post_array[$key] = str_replace($search_weird_chars, "'", $this->post_array[$key]);

                $this->post_array[$key] = urldecode($this->post_array[$key]);

this works although it is a totally retarded thing to have to do .. oh well. :-)
moostende at gmail dot com 26-Sep-2011 11:20
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:

<?php
$challenge = '-aaa----b-c-----d--e---f';
echo str_replace('--', '-', $challenge).'<br>';
echo preg_replace('/--+/', '-', $challenge).'<br>';
?>

This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
matthew at euphoriccode dot com 09-Sep-2011 10:52
If you are looking to implement str with password generation the following function will help;

<?php
function gen_pass_process($girth = 17) {
     $str = '';
     for($1 = 0; $i<$girth; $i++) {
          $str . = chr(rand(48,122));
     }
     return $str;
}
?>
didiergm 29-Jul-2011 03:25
php 5.3.2 (may exist before, but it never saw it until today)

the replace is always evaluated before the search takes place.

So if like me you use str_replace to replace some macros in the html code, and these replacement call a function, you must be aware that the functions always runs, not only when  the search is found.

for example:

str_replace (
   array ('%macro1%', '%macro2%'),
   array (myfunction1(), myfunction2(),
   thesource);

myfunction1() and myfunction2() are called regardless of the fact that the source contains %macro1%' or '%macro2%' or not. I genuinely believed that myfunction1 would only be called if %macro1% was found (resp myfunction2 and %macro2%)

I noticed it because myfunction1 was running a database query to increment a value and I noticed that this value was incremented w/o need. It took me a wee while to get to the bottom of it
mbullard at accuvista dot co dot uk 14-Jul-2011 02:42
Insert space after comma.

If you have a form that stores results in a database field as comma separated values, when you display this data you can use the following to insert a space after each comma:

<?php
$find[] = ',';
$replace[] = '&#44;&nbsp;';
$text = str_replace($find, $replace, $row_rsRecordset['Field']);
print_r($text);
?>

Notes:
1) To get round the Replacement Order Gotcha, the comma is also replaced with its code equivalent: &#44;
2) You can adapt the $replace section to suit your needs: swap out the &nbsp; code with <br/> or replace comma and space with &nbsp;&middot;&nbsp; etc.
hakre 06-Jul-2011 08:08
I was looking for a str_replace function supporting callbacks. As I didn't found one I wrote one my own. Works exactly like str_replace, but the replace parameter is a callback or an array of callbacks (instead of string/strings in str_replace). The callback function accepts two arguments, the string that is being replaced and the count of the replacement being done.

<?php
/**
 * str_ureplace
 *
 * str_replace like function with callback
 *
 * @param string|array search
 * @param callback|array $replace
 * @param string|array $subject
 * @param int $replace_count
 * @return string|array subject with replaces, FALSE on error.
 */
function str_ureplace($search, $replace, $subject, &$replace_count = null) {
    $replace_count = 0;

    // validate input
    $search = array_values((array) $search);
    $searchCount = count($search);
    if (!$searchCount) {
        return $subject;
    }
    foreach($search as &$v) {
        $v = (string) $v;
    }
    unset($v);
    $replaceSingle = is_callable($replace);
    $replace = $replaceSingle ? array($replace) : array_values((array) $replace);
    foreach($replace as $index=>$callback) {
        if (!is_callable($callback)) {
            throw new Exception(sprintf('Unable to use %s (#%d) as a callback', gettype($callback), $index));
        }
    }

    // search and replace
    $subjectIsString = is_string($subject);
    $subject = (array) $subject;
    foreach($subject as &$haystack) {
        if (!is_string($haystack)) continue;
        foreach($search as $key => $needle) {
            if (!$len = strlen($needle))
                continue;
            $replaceSingle && $key = 0;
            $pos = 0;
            while(false !== $pos = strpos($haystack, $needle, $pos)) {
                $replaceWith = isset($replace[$key]) ? call_user_func($replace[$key], $needle, ++$replace_count) : '';
                $haystack = substr_replace($haystack, $replaceWith, $pos, $len);
            }
        }
    }
    unset($haystack);

    return $subjectIsString ? reset($subject) : $subject;
}
?>
ahmed dot 3abdolah at gmail dot com 24-Jun-2011 11:05
Hello , this is a simple function programed by str_replace for crypting password and ....etc .
You can do verry much think with str_replace :
look at this:
<?PHP
/*
 *This Function Is programed By MR-O
 *The first arabic Function for crypting
*/
function abo($variable){
$variable =str_replace("1",1 ^ 52 ,$variable);
$variable =str_replace("2",2 ^ 5 ,$variable);
$variable =str_replace("3",3 ^ 8 ,$variable);
$variable =str_replace("4",4 ^ 18 ,$variable);
$variable =str_replace("5",5 ^ 30 ,$variable);
$variable =str_replace("6",6 ^ 42 ,$variable);
$variable =str_replace("7",7 ^ 26 ,$variable);
$variable =str_replace("8",8 ^ 62 ,$variable);
$variable =str_replace("9",9 ^ 1 ,$variable);
$variable =str_replace("0",0 ^ 3 ,$variable);
$variable =str_replace("a","m8" ,$variable);
$variable =str_replace("b","2s" ,$variable);
$variable =str_replace("c","9e" ,$variable);
$variable =str_replace("d","6s" ,$variable);
$variable =str_replace("e","a3" ,$variable);
$variable =str_replace("f","m3" ,$variable);
$variable =str_replace("g","6f" ,$variable);
$variable =str_replace("h","9c" ,$variable);
$variable =str_replace("i","85" ,$variable);
$variable =str_replace("j","32" ,$variable);
$variable =str_replace("k","1a" ,$variable);
$variable =str_replace("l","6e" ,$variable);
$variable =str_replace("m","5f" ,$variable);
$variable =str_replace("n","9r" ,$variable);
$variable =str_replace("o","z0" ,$variable);
$variable =str_replace("p","y6" ,$variable);
$variable =str_replace("q","9i" ,$variable);
$variable =str_replace("r","y9" ,$variable);
$variable =str_replace("s","5g" ,$variable);
$variable =str_replace("t","p3" ,$variable);
$variable =str_replace("u","d5" ,$variable);
$variable =str_replace("v","t8" ,$variable);
$variable =str_replace("w","2x" ,$variable);
$variable =str_replace("x","6w" ,$variable);
$variable =str_replace("y","v9" ,$variable);
$variable =str_replace("z","zv" ,$variable);
$variable =str_replace("A","m8" ,$variable);
$variable =str_replace("B","24d" ,$variable);
$variable =str_replace("C","9e" ,$variable);
$variable =str_replace("D","6s2" ,$variable);
$variable =str_replace("E","qw" ,$variable);
$variable =str_replace("F","oe" ,$variable);
$variable =str_replace("G","0t" ,$variable);
$variable =str_replace("H","o9" ,$variable);
$variable =str_replace("I","74" ,$variable);
$variable =str_replace("J","dd" ,$variable);
$variable =str_replace("K","2b" ,$variable);
$variable =str_replace("L","rt" ,$variable);
$variable =str_replace("M","0c" ,$variable);
$variable =str_replace("N","2w" ,$variable);
$variable =str_replace("O","te" ,$variable);
$variable =str_replace("P","sc" ,$variable);
$variable =str_replace("Q","uy" ,$variable);
$variable =str_replace("R","hp" ,$variable);
$variable =str_replace("S","h1" ,$variable);
$variable =str_replace("T","s5" ,$variable);
$variable =str_replace("U","fs" ,$variable);
$variable =str_replace("V","e1s" ,$variable);
$variable =str_replace("W","1y" ,$variable);
$variable =str_replace("X","dv" ,$variable);
$variable =str_replace("Y","w2" ,$variable);
$variable =str_replace("Z","w5" ,$variable);
$variable = str_replace('1','5b',$variable);
$variable = str_replace('2','b1',$variable);
$variable = str_replace('3','0j',$variable);
$variable = str_replace('4','1e',$variable);
$variable = str_replace('5','z2',$variable);
$variable = str_replace('6','15e',$variable);
$variable = str_replace('7','d2',$variable);
$variable = str_replace('8','e5b',$variable);
$variable = str_replace('9','y8',$variable);
$variable = str_replace('0','g1y7',$variable);
echo $variable ;
}

?>

thanks , MR-O .
biohazard dot ge at gmail dot com 20-May-2011 02:33
Replace and match strings between two needles in large haystack quicker (?):

<?php
//Assume you have input:

$input = "<p> Images
 <img src='some/image_1.jpg'> This is a cat
and <img src=some/image_2.jpg> That is a bat
and <img src="some/image_3.jpg"> What is this
and <img src=some/image_4.jpg> What is that
</p>
";

between_replace ('<img src="','">', $input, "{*}");
between_replace ('<img src=\'','\'>', $input, "{*}");
between_replace ('<img src=','>', $input, "'{*}'");

//As result we have

//$input == "<p> Images
// <img src='some/image_1.jpg'> This is a cat
//and <img src='some/image_2.jpg'> That is a bat
//and <img src='some/image_3.jpg'> What is this
//and <img src='some/image_4.jpg'> What is that
//</p>
//";

$result = between_fetch ("<img src='","'>", $input);

// $result == array ('some/image_1.jpg', 'some/image_2.jpg', 'some/image_3.jpg', 'some/image_4.jpg');
?>

Not a good example but only with them and str_replace I parsed word converted html for epub. This is what people invent not willing to get familiar with regular expressions...

<?php

    function between_replace ($open, $close, &$in, $with, $limit=false, $from=0)
    {
        if ($limit!==false && $limit==0)
        {
            return $in;
        }
        $open_position = strpos ($in, $open, $from);
        if ($open_position===false)
        {
            return false;
        };
        $close_position = strpos ($in, $close, $open_position+strlen($open));
        if ($close_position===false)
        {
            return false;
        };
        $current = false;
        if (strpos($with,'{*}')!==false)
        {
            $current = substr ($in, $open_position+strlen($open), $close_position-$open_position-strlen($open));
            $current = str_replace ('{*}',$current,$with);
            //debug_echo ($current);
        }
        else
        {
            $current = $with;
        }
        $in = substr_replace ($in, $current, $open_position+strlen($open), $close_position-$open_position-strlen($open));
        $next_position = $open_position + strlen($current) + 1;
        if ($next_position>=strlen($in))
        {
            return false;
        }
        if ($limit!==false)
        {
            $limit--;
        }
        between_replace ($open, $close, $in, $with, $limit, $next_position);
        return $in;
    }

    function between_fetch ($open, $close, &$in, &$result=null, $with='', $limit=false, $from=0)
    {
        if ($limit!==false && $limit==0)
        {
            return $in;
        };
        if (!is_array($result))
        {
            $result = array ();
        }
        $open_position = strpos ($in, $open, $from);
        if ($open_position===false)
        {
            return false;
        };
        $close_position = strpos ($in, $close, $open_position+strlen($open));
        if ($close_position===false)
        {
            return false;
        };
        $current = substr ($in, $open_position+strlen($open), $close_position-$open_position-strlen($open));
        $next_position = $open_position + strlen($current) + 1;
        if ($with!='')
        {
            $current = str_replace('{*}', $current, $with);
        }
        $result[] = $current;
        if ($next_position>=strlen($in))
        {
            return false;
        }
        if ($limit!==false)
        {
            $limit--;
        }
        between_fetch ($open, $close, $in, $result, $with, $limit, $next_position);
        return $in;
    }

?>
jay_knows_(all)uk at hotmail dot com 16-Feb-2011 07:16
This strips out horrible MS word characters.

Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.

There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.

<?php

function msword_conversion($str)
{
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
// $str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
// $str = str_replace(chr(147), '"', $str);    // left double quote
// $str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '-–', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
// $str = str_replace(chr(152), '~', $str);    // tilde accent
// $str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
// $str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
$str = str_replace('°C', '&deg;C', $str);    // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace('£', '&pound;', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('–', '&ndash;', $str);

return $str;
}

?>
Oleg Butuzov butuzov at made dot com dot ua 01-Feb-2011 07:26
Sometimes we need replace just first occurrence , a small function that can help you.

<?php
    $string = 'alpharomero alpha arlekino';

    var_dump(str_replace_once('alpha','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    var_dump(str_replace_once('a','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    var_dump(str_replace_once('abnormal','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    var_dump(str_replace_once('n','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    function str_replace_once($str_pattern, $str_replacement, $string){

        if (strpos($string, $str_pattern) !== false){
            $occurrence = strpos($string, $str_pattern);
            return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
        }

        return $string;
    }
?>
mevdschee 29-Jan-2011 03:19
say you want every "a" replaced by "abba" and every "b" replaced by "baab" in the string "ab" you do:

<?php
$search = array("a","b");
$replace = array("abba","baab");
echo str_replace($search,$replace,"ab");
?>

that results in "abaabbaababaab" and not the expected "abbabaab"

I wrote this little snippet to solve the replacements-in-replacement problem:

<?php
function search_replace($s,$r,$sql)
{ $e = '/('.implode('|',array_map('preg_quote', $s)).')/';
  $r = array_combine($s,$r);
  return preg_replace_callback($e, function($v) use ($s,$r) { return $r[$v[1]]; },$sql);
}

echo search_replace($search,$replace,"ab");
?>

that results in the expected "abbabaab"
Viam 17-Jan-2011 09:57
This way it is possible to make a encryption of some sort
A small script i wrote.
Proof of concept:

<?php
//Data to be encrypted.Take note that it has to be text.
$Input_data  = "i want a apple";//Place the text here
$Encrypter_variables= array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
$Variables_replace = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "%", "!", "@", "#", "$", "^", "&", "*","~", "+", ":", "-", "=", "?", "'", ".", "<");
$New_data = str_replace($Encrypter_variables, $Variables_replace, $Input_data);

echo $New_data;//Displays the encrypted data,In this case it is 9 ?1$: 1 1&&@5

//Data to be decrypted
$Output_data  = "9 ?1$: 1 1&&@5";////Place the encrypted data here
$Decrypter_variables =  array("1", "2", "3", "4", "5", "6", "7", "8", "9", "%", "!", "@", "#", "$", "^", "&", "*","~", "+", ":", "-", "=", "?", "'", ".", "<");
$Variables_assign  = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
$Newer = str_replace($Decrypter_variables, $Variables_assign  , $Output_data);

echo $Newer;//Displays the decrypted data Which is i want a apple
?>
Steve 13-Jan-2011 06:22
Just a note about the json_decode solution from nikolaz dot tang at hotmail dot com
It may return an instance of stdClass, which may not quite be what you want.  (using multi-dimensional arrays)

IF you want to be sure, stick to the proper recursive solution.
nikolaz dot tang at hotmail dot com 11-Nov-2010 08:57
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:

<?php
function str_replace_json($search, $replace, $subject){
     return json_decode(str_replace($search, $replace,  json_encode($subject)));

}
?>

This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.

Compared to:

<?php
function str_replace_deep($search, $replace, $subject)
{
    if (is_array($subject))
    {
        foreach($subject as &$oneSubject)
            $oneSubject = str_replace_deep($search, $replace, $oneSubject);
        unset($oneSubject);
        return $subject;
    } else {
        return str_replace($search, $replace, $subject);
    }
}
?>
jpoirier at hotmail.fr 25-Jun-2010 05:40
I've found something interesting about the $count param:

As of 5.0.0 the last parameter (count) is passed by reference (it is optional). So 2 choices :
1)passed not by reference - it's limit
2)passed by reference : the var is is_null() - all occurences are replaced the number is returned in "count", otoh if the var !is_null() -> use as limit.

On version 5.3.0 the 4th parameter, count, does not work when not passed
by reference.

http://bugs.php.net/bug.php?id=11457

Hope this help
apmuthu at usa dot net 19-Jun-2010 12:31
If we have a html template that contains placeholders in curly braces that need to be replaced in runtime, the following function will do it using str_replace:

<?php

function parse_template($filename, $data) {
// example template variables {a} and {bc}
// example $data array
// $data = Array("a" => 'one', "bc" => 'two');
    $q = file_get_contents($filename);
    foreach ($data as $key => $value) {
        $q = str_replace('{'.$key.'}', $value, $q);
    }
    return $q;
}

?>
cableray 11-Jun-2010 12:03
If you wish to get around the 'gotcha', you could do something like this:

<?php

$find=array('a', 'p', '^', '*');
$replace = array('^', '*', 'apple', 'pear');
str_replace($find, $replace, 'a p');

?>

The idea here is that you first replace the items you want with unique identifiers (that you are unlikely to find in the subject) and then search for those identifiers and then replace them.
christian dot reinecke at web dot de 14-May-2010 12:06
If you need to replace a string in another, but only once but still in all possible combinations (f.e. to replace "a" with "x" in "aba" to get array("xba", "abx")) you can use this function:
<?php
function getSingleReplaceCombinations($replace, $with, $inHaystack)
{
    $splits = explode($replace, $inHaystack);
    $result = array();
    for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {
        $previous = array_slice($splits, 0, $i);
        $next     = array_slice($splits, $i);

        $combine  = array_pop($previous) . $with . array_shift($next);
        $result[] = implode($replace, array_merge($previous, array($combine), $next));
    }
    return $result;
}
var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as mentioned above
?>
It may not be the best in performance, but it works.
jbarnett at jmbelite dot com 26-Apr-2010 01:23
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your "replacements" in reverse.

So instead of starting from "A" and ending with "E":

<?php
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
// replaces A to B, B to C, C to D, D to E, E to F (makes them all F)
// start from "E" and end with "A":

$search  = array('E', 'D', 'C', 'B', 'A');
$replace = array('F', 'E', 'D', 'C', 'B');
// replaces E to F, D to E, C to D, B to C, A to B (prevents from
// multiple replacements of already replaced values)
?>

So basically start from the "end" and put the replacements in an order where the "replaced value" won't equal a value that exists later in the "search array".
pjcdawkins at googlemail dot com 23-Apr-2010 05:23
Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and $subject. The keys and other structure of $subject are preserved.

<?php
// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
  if(!is_array($search) || !is_array($replace)){
    $search=array($search);
    $replace=array($replace);
  }
  $match=array_search($subject,$search,true);
  if($match!==false && array_key_exists($match,$replace))
    $subject=$replace[$match];
  return $subject;
}

// Main function:
function deepReplace($search,$replace,$subject){
  if(!is_array($subject))
    return _replaceWithAnything($search,$replace,$subject);
  foreach($subject as &$val){
    if(is_array($val)){
      $val=deepReplace($search,$replace,$val);
      continue;
    }
    $val=_replaceWithAnything($search,$replace,$val);
  }
  return $subject;
}
?>
fleshgrinder at gmx dot at 16-Apr-2010 05:50
Fast function to replace new lines from a given string. This is interesting to replace all new lines from e. g. a text formatted in HTML retrieved from database and printing it without the unnecessary new lines. This results in slightly faster rendering in the Web browser.

<?php

/**
 * Replace all linebreaks with one whitespace.
 *
 * @access public
 * @param string $string
 *   The text to be processed.
 * @return string
 *   The given text without any linebreaks.
 */
function replace_newline($string) {
  return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}

?>
Wes Foster 17-Dec-2009 01:32
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);

$string = 'I like to eat an apple with my dog in my chevy';

echo str_replace_assoc($replace,$string);

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

<?php
function strReplaceAssoc(array $replace, $subject) {
   return str_replace(array_keys($replace), array_values($replace), $subject);
}
?>

[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]
jonathon at compwright dot com 12-Nov-2009 09:23
If you get a blank page when passing an object to str_replace() (relying on __toString() to convert the object to a string) then you may need to force string context using (string), like so:

<?php
private function _load_vars($vars, &$source = false) {
    if(!$source) $source =& $this->code;
        foreach((array)$vars as $key => $var) {
            $source = str_replace("{".$key."}", (string) $var, $source);
        }
    }
}
?>

I was running Ubuntu Server with PHP 5.2.6 and getting apache segfaults and mysterious blank pages when $var happened to be certain objects.
Chris 01-Nov-2009 08:22
Compress a string's internal spaces:
<?php
$str = ' This is    a    test   ';
$count = 1;
while($count)
    $str = str_replace('  ', ' ', $str, $count);
?>
Decko 15-Oct-2009 01:41
As mentioned earlier you should take the order into account when substituting multiple values.

However it is worth noticing that str_replace doesn't seem to re-read the string when doing single replacements. Take the following example.

<?php
  $s = '/a/a/';
  $s = str_replace('/a/', '/', $s);
?>

You would expect the following.

First replacement '/a/a/' -> '/a/'
Second replacement '/a/'->'/'

This is not the case, the actual result will be '/a/'.

To fix this, you will have to put str_replace in a while-loop.

<?php
  $s = '/a/a/';
  while(strpos($s, '/a/') !== false)
    $s = str_replace('/a/', '/', $s); //eventually $s will == '/'
?>
Alberto Lepe 15-Jun-2009 07:44
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):

For example:

<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>

I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)

To make this work, use "strtr" instead:

<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>

This returns: "ZDDB"
moz667 at gmail dot com 21-May-2009 09:49
<?php
/*
This is a function for made recursive str_replaces in an array
*/
function recursive_array_replace($find, $replace, &$data) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                recursive_array_replace($find, $replace, $data[$key]);
            } else {
                $data[$key] = str_replace($find, $replace, $value);
            }
        }
    } else {
        $data = str_replace($find, $replace, $data);
    }
}

$a = array();
$a['a'] = "a";
$a['b']['a'] = "ba";
$a['b']['b'] = "bb";
$a['c'] = "c";
$a['d']['a'] = "da";
$a['d']['b'] = "db";
$a['d']['c'] = "dc";
$a['d']['d'] = "dd";

echo "Before Replaces";
print_r($a);

recursive_array_replace("a", "XXXX", $a);

echo "After Replaces";
print_r($a);
?>
michael dot moussa at gmail dot com 29-Jan-2009 06:38
As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string.  This may produce unexpected output.

Example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo str_replace($search, $replace, $subject); // output: 'FFFFFF'
?>

In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet.  The expected output for this sample is 'BCDEF'; however, the actual output is 'FFFFF'.

To more clearly illustrate this, consider the following example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';

echo str_replace($search, $replace, $subject); // output: 'F'
?>

Since 'A' is the only letter in the $search array that appears in $subject, one would expect the result to be 'B'; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.

The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.

<?php
/**
* When using str_replace(...), values that did not exist in the original string (but were put there by previous
* replacements) will be replaced continuously.  This string replacement function is designed replace the values
* in $search with those in $replace while not factoring in prior replacements.  Note that this function will
* always look for the longest possible match first and then work its way down to individual characters.
*
* The "o" in "stro_replace" represents "original", indicating that the function operates only on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in the $replace array
*/
function stro_replace($search, $replace, $subject)
{
    return strtr( $subject, array_combine($search, $replace) );
}

$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo stro_replace($search, $replace, $subject); // output: 'BCDEF'
?>

Some other examples:

<?php
$search = array(' ', '&');
$replace = array('&nbsp;', '&amp;');
$subject = 'Hello & goodbye!';

// We want to replace the spaces with &nbsp; and the ampersand with &amp;
echo str_replace($search, $replace, $subject); // output: "Hello&amp;nbsp&amp;&amp;nbspgoodbye!" - wrong!

echo stro_replace($search, $replace, $subject); // output: "Hello&nbsp;&amp;&nbsp;goodbye!" - correct!

/*
    Note:  Run the above code in the CLI or view source on your web browser - the replacement strings for stro_replace are HTML entities which the browser interprets.
*/
?>

<?php
$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');
$subject = 'MIKE AND ERICA LIKE AMERICA';

// We want to replace the name "ERICA" with "JON" and the word "AMERICA" with "PHP"
echo str_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE AMJON", which is not correct

echo stro_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE PHP", which is correct
?>
nospam at nospam dot com 02-Dec-2008 02:55
Replacement for str_replace in which a multiarray of numerically keyed data can be properly evaluated with the given template without having a search for 11 be mistaken for two 1's next to each other

<?php

function data_template($input, $template) {
  if ($template) { // template string
    if ($split = str_split($template)) { // each char as array member
      foreach ($split as $char) { // each character
        if (is_numeric($char)) { // test for digit
          if ($s != 1) { // new digit sequence
            $i++;
            $s = 1;
          }
          $digits[$i] .= $char; // store digit
        } else { // not a digit
          if ($s != 2) { // new non-digit sequence
            $i++;
            $s = 2;
          }
          $strings[$i] .= $char; // store string
        }
      }
      if ($i && $input && is_array($input)) { // input data
        foreach ($input as $sub) { // each subarray
          if (is_array($sub)) {
            $out = ''; // reset output
            for ($j = 0; $j <= $i; $j++) { // each number/string member
              if ($number = $digits[$j]) { // number
                $out .= $sub[$number]; // add value from subarray to output
              } else { // string
                $out .= $strings[$j]; // add to output
              }
            }
            $a[] = $out;
          }
        }
        return $a;
      } // input
    } // split
  } // template
}

$input = array(array(1=>'yellow', 2=>'banana', 11=>'fruit'), array(1=>'green', 2=>'spinach', 11=>'vegetable'), array(1=>'pink', 2=>'salmon', 11=>'fish'));

print_r (data_template($input, '2: a 1, healthy 11'));

/*
Array
(
    [0] => banana: a yellow, healthy fruit
    [1] => spinach: a green, healthy vegetable
    [2] => salmon: a pink, healthy fish
)
*/

// str_replace would have wanted to output 'banana: a yellow, healthy yellowyellow

?>

Not sure if this will help anyone but I wrote it for my application and thought I would share just in case
nick at NOSPAM dot pitchinteractive dot com 06-Oct-2008 04:12
I tried max at efoxdesigns dot com solution for str_replace_once but it didn't work quite right so I came up with this solution (all params must be strings):

<?php
function str_replace_once($search, $replace, $subject) {
    $firstChar = strpos($subject, $search);
    if($firstChar !== false) {
        $beforeStr = substr($subject,0,$firstChar);
        $afterStr = substr($subject, $firstChar + strlen($search));
        return $beforeStr.$replace.$afterStr;
    } else {
        return $subject;
    }
}
?>
paolo A T doppioclick D O T com 05-Sep-2008 04:15
For PHP 4 < 4.4.5 and PHP 5 < 5.2.1 you may occur (like me) in this bug:

http://www.php-security.org/MOPB/MOPB-39-2007.html
troy at troyonline dot com 22-Jun-2008 10:18
Yet another deep replace function:

<?php
    function str_replace_deep( $search, $replace, $subject)
    {
        $subject = str_replace( $search, $replace, $subject);

        foreach ($subject as &$value)
            is_array( $value) and $value =str_replace_deep( $search, $replace, $value);

        return $subject;
    }
?>
David Gimeno i Ayuso (info at sima dot cat) 09-Aug-2007 12:22
With PHP 4.3.1, at least, str_replace works fine when working with single arrays but mess it all with two or more dimension arrays.

<?php
$subject = array("You should eat this","this","and this every day.");
$search  = "this";
$replace = "that";
$new     = str_replace($search, $replace, $subject);

print_r($new); // Array ( [0] => You should eat that [1] => that [2] => and that every day. )

echo "<hr />";

$subject = array(array("first", "You should eat this")
                ,array("second","this")
                ,array("third", "and this every day."));
$search  = "this";
$replace = "that";
$new     = str_replace($search, $replace, $subject);

print_r($new); // Array ( [0] => Array [1] => Array [2] => Array )

?>
tim at hysniu dot com 05-Jun-2007 11:27
I found that having UTF-8 strings in as argument didnt
work for me using heavyraptors function.
Adding UTF-8 as argument on htmlentities
fixed the problem.

cheers, tim at hysniu.com

<?php
function replace_accents($str) {
  $str = htmlentities($str, ENT_COMPAT, "UTF-8");
  $str = preg_replace(
'/&([a-zA-Z])(uml|acute|grave|circ|tilde);/',
'$1',$str);
  return html_entity_decode($str);
}

?>
kole 25-Feb-2007 05:48
My input is MS Excel file but I want to save ‘,’,“,” as ',',",".

    $badchr        = array(
        "\xc2", // prefix 1
        "\x80", // prefix 2
        "\x98", // single quote opening
        "\x99", // single quote closing
        "\x8c", // double quote opening
        "\x9d"  // double quote closing
    );

    $goodchr    = array('', '', '\'', '\'', '"', '"');

    str_replace($badchr, $goodchr, $strFromExcelFile);

Works for me.
rlee0001 at sbcglobal dot net 16-Feb-2007 12:30
This is a more rigid alternative to spectrereturns at creaturestoke dot com's replace_different function:

<?php

        function str_replace_many ($search, $replacements, $subject) {
            $index = strlen($subject);
            $replacements = array_reverse($replacements);

            if (count($replacements) != substr_count($subject, $search)) {
                return FALSE;
            }

            foreach ($replacements as $replacement) {
                $index = strrpos(substr($subject, 0, $index), $search);
                $prefix = substr($subject, 0, $index);
                $suffix = substr($subject, $index + 1);
                $subject = $prefix . $replacement . $suffix;
            }

            return $subject;
        }
?>

This will return false if there are a different number of $replacements versus number of occurrences of $search in $subject. Additionally, $search much be exactly one character (if a string is provided, only the first character in the string will be used). Examples:

<?php
        echo str_replace_many('?',array('Jane','banana'),'? is eating a ?.');
?>

prints: "Jane is eating a banana."
15-Jan-2007 01:42
Before spending hours searching your application why it makes UTF-8 encoding into some malformed something with str_replace, make sure you save your PHP file in UTF-8 (NO BOM).

This was at least one of my problems.
matt wheaton 30-Mar-2006 07:40
As an effort to remove those Word copy and paste smart quotes, I've found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.

There is an "invisible" character after the â€ for the right side double smart quote that doesn't seem to display here. It is chr(157).

<?php
  $find[] = 'â€œ';  // left side double smart quote
  $find[] = 'â€';  // right side double smart quote
  $find[] = 'â€˜';  // left side single smart quote
  $find[] = 'â€™';  // right side single smart quote
  $find[] = 'â€¦';  // elipsis
  $find[] = 'â€”';  // em dash
  $find[] = 'â€“';  // en dash

  $replace[] = '"';
  $replace[] = '"';
  $replace[] = "'";
  $replace[] = "'";
  $replace[] = "...";
  $replace[] = "-";
  $replace[] = "-";

  $text = str_replace($find, $replace, $text);
?>
David Gimeno i Ayuso (info at sima-pc dot com) 25-Aug-2003 06:12
Take care with order when using arrays in replacement.

<?php
$match=array("ONE","TWO","THREE");
$replace=array("TWO WORDS","MANY LETTERS","OTHER IDEAS");
$sample="ONE SAMPLE";
echo str_replace($match,$replace,$sample);
?>

It will show: "MANY LETTERS WORDS SAMPLE"

That is, after replacing "ONE" with "TWO WORDS", process follows with next array item and it changes "TWO" with "MANY LETTERS".
str_repeat
str_rot13
Обработка строк


Выполняет преобразование ROT13 над строкой

str_replace
str_shuffle
Обработка строк
PHP Manual

str_rot13

(PHP 4 >= 4.2.0, PHP 5)

str_rot13 — Выполняет преобразование ROT13 над строкой

Описание

string str_rot13 ( string $str )

Выполняет над строкой str преобразование ROT13 и возвращает полученную строку.

Преобразование ROT13 заключается в простом сдвиге каждой латинской буквы на 13 позиций в алфавите, остальные символы не изменяются. Обратное преобразование выполняется той же функцией, так как передача закодированной строки в качестве аргумента вернет ее оригинальную версию.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает ROT13 версию переданной строки.

Примеры

Пример #1 Пример использования str_rot13()

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

Список изменений

Версия | Описание
4.3.0 | В функции была исправлена ошибка, которая заключалась в том, что str также изменялась, как при передаче по ссылке.

User Contributed Notes

shaun 11-Feb-2012 02:44
I was reminded again of the desire for a generic str_rot function. Character manipulation loops in PHP are slow compared to their C counterparts, so here's a tuned version of the previous function I posted. It's 1.6 times as fast, mainly by avoiding chr() calls.

<?php
function str_rot($s, $n = 13) {
    static $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $n = (int)$n % 26;
    if (!$n) return $s;
    if ($n == 13) return str_rot13($s);
    for ($i = 0, $l = strlen($s); $i < $l; $i++) {
        $c = $s[$i];
        if ($c >= 'a' && $c <= 'z') {
            $s[$i] = $letters[(ord($c) - 71 + $n) % 26];
        } else if ($c >= 'A' && $c <= 'Z') {
            $s[$i] = $letters[(ord($c) - 39 + $n) % 26 + 26];
        }
    }
    return $s;
}
?>

But using strtr() you can get something 10 times as fast as the above :

<?php
function str_rot($s, $n = 13) {
    static $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    $n = (int)$n % 26;
    if (!$n) return $s;
    if ($n < 0) $n += 26;
    if ($n == 13) return str_rot13($s);
    $rep = substr($letters, $n * 2) . substr($letters, 0, $n * 2);
    return strtr($s, $letters, $rep);
}
?>

This technique is faster because PHP's strtr is implemented in C using a byte lookup table (it has O(m + n) complexity). However, PHP 6 will use Unicode, so I guess(?) strtr will then have to be implemented with a search for each character (O(m * n)). Using strtr might still be faster since it offloads the character manipulation to C rather than PHP, but I don't really know. Take your pick.

Happy coding!

(Benchmark code):

<?php
for ($k = 0; $k < 10; $k++) {
    $s = 'The quick brown fox jumps over the lazy dog.';
    $t = microtime(1);
    for ($i = 0; $i < 1000; $i++) $s = str_rot($s, $i);
    $t = microtime(1) - $t;
    echo number_format($t, 3) . "\n";
}
?>
shaunspiller at spammenotgmail dot com 26-Sep-2009 08:54
Here's my implementation of a str_rot that takes a custom offset. It's faster than the others here because it allocates the output string in one go instead of tacking on characters one at a time. It can handle positive or negative offsets of any size, and it fixes everything up to ensure only upper and lower case letters are translated and that they wrap around correctly within the alphabet.

<?php
function str_rot($s, $n = 13) {
    $n = (int)$n % 26;
    if (!$n) return $s;
    for ($i = 0, $l = strlen($s); $i < $l; $i++) {
        $c = ord($s[$i]);
        if ($c >= 97 && $c <= 122) {
            $s[$i] = chr(($c - 71 + $n) % 26 + 97);
        } else if ($c >= 65 && $c <= 90) {
            $s[$i] = chr(($c - 39 + $n) % 26 + 65);
        }
    }
    return $s;
}
?>
peter at NOSPAM jamit dot com 07-Sep-2009 07:31
This ROT13 variant is different from my earlier version in that it retains 'ethnicity'. For example, a Chinese text when encrypted will remain Chinese, and the string will not be making sense (the real meaning will be encrypted). Just look at the code and you will understand.

<?php

function unichar2ords($char, $encoding = 'UTF-8') {
    $char = mb_convert_encoding($char, 'UCS-4', $encoding);
    $val = unpack('N', $char);
    return $val[1];
    }

function ords2unichar($ords, $encoding = 'UTF-8'){
    $char = pack('N', $ords);
    return mb_convert_encoding($char, $encoding, 'UCS-4');
    }

function mbStringToArray ($string, $encoding = 'UTF-8') {
    if (empty($string)) return false;
    for ($strlen = mb_strlen($string, $encoding); $strlen > 0; ) {
        $array[] = mb_substr($string, 0, 1, $encoding);
        $string  = mb_substr($string, 1, $strlen, $encoding);
        $strlen  = $strlen - 1;
        }
    return $array;
    }

function unicodeRotN($str, $offset, $encoding = 'UTF-8') {
    $val = '';
    $array = mbStringToArray ($str, $encoding = 'UTF-8');
    $len = count($array);
    for ($i = 0; $i < $len; $i++) {
        $val .= ords2unichar(unichar2ords($array[$i], $encoding) + $offset, $encoding);
        }
    return $val;
    }

// example

$original = '中國是我的家'; // means "China is my home"

$encrypted = unicodeRotN($string, 13); // 为團昼戞皑寃 means "Ñ Ai injustice for the Mission Day" (Google translation)

$decrypted = unicodeRotN($encrypted, -13); // 中國是我的家

?>
peter at NOSPAM jamit dot com 07-Sep-2009 01:11
Here is my ROT13 function that works for all possible characters and not just ASCII. It can be used on Chinese, Japanese, ....

<?php

function rot13encrypt ($str) {
    return str_rot13(base64_encode($str));
    }

function rot13decrypt ($str) {
    return base64_decode(str_rot13($str));
    }

// example

$string = '中國是我的家';

$encrypted = rot13encrypt ($string); // produces 5Yvg5MlY5cvi5bvE55dR5n62

$decrypted = rot13decrypt ($encrypted); // produces 中國是我的家

?>
grawity+phpnet at gmail dot com 31-Dec-2007 05:39
resubmitting updated function in re:#76975
<?php
function asc_shift($str,$offset=0) {
    $new = '';
    for ($i = 0; $i < strlen($str); $i++)
        $new .= chr(ord($str[$i])+$offset);
    return $new;
}
?>
because as of PHP 6, $str{$i} is deprecated.
nick at lazy-river dot net 08-Aug-2007 09:01
This is recursive function to shift the component letters of a string left or right in the ascii table.

I've left it simple as it suits my needs, but you may want to include error checking for a null string and also put bounds in place, or make it actually rotate around the whole character set rather than just shifting the string up or down.

function asc_shift($string, $amount) {
  $key = substr($string, 0, 1);
  if(strlen($string)==1) {
    return chr(ord($key) + $amount);
  } else {
    return chr(ord($key) + $amount) . asc_shift(substr($string, 1, strlen($string)-1), $amount);
  }
}

For example:
<?php
echo asc_shift("TESTING12345@", 5);
?>

shifts every character up 5 ascii positions, resulting in this string:

YJXYNSL6789:E

In reverse:

<?php
echo asc_shift("YJXYNSL6789:E", -5);
?>

shifts every character down 5 ascii positions, resulting in this string:

TESTING12345@
arwab at surrealwebs dot com 11-Jul-2007 01:11
here's my rot function, it works anyway
<?php
/**
 * preforms the rotation algorithm on the passed in string
 */
function _rot( $str , $dist=13 ){
    if( !is_numeric($dist) || $dist < 0){
        $dist = 13;
    }

    $u_lower =  65; $u_upper =  90;
    $l_lower =  97; $l_upper = 122;

    $char_count = ($u_upper - $u_lower) +1;

    while( $dist > $char_count ){
        $dist -= $char_count;
    }

    $newstr = '';

    for( $i=0; $i<strlen($str); ++$i){
        $c = ord($str[$i]);

        /*
         * Check if the character is within the bounds of our function (a-zA-z)
         * if not it gets tacked on to the string as is and we move on to the
         * next one.
         */
        if( $c<$u_lower || $c>$l_upper || ( $c>$u_upper && $c <$l_lower ) ){
            $newstr .= chr($c);
            continue;
        }

        $lower = ( $c<=$u_upper?$u_lower:$l_lower);
        $upper = ( $c<=$u_upper?$u_upper:$l_upper);

        $c += $dist;

        if( $c > $upper){
            $c = (($c - $upper) + ($lower-1));
        }

        $newstr .= chr($c);
    }

    return $newstr;
}
?>
electro at whatever dot com 31-May-2007 12:21
<?php

/**
 * Rotate each string characters by n positions in ASCII table
 * To encode use positive n, to decode - negative.
 * With n = 13 (ROT13), encode and decode n can be positive.
 *
 * @param string $string
 * @param integer $n
 * @return string
 */
function rotate($string, $n) {

    $length = strlen($string);
    $result = '';

    for($i = 0; $i < $length; $i++) {
        $ascii = ord($string{$i});

        $rotated = $ascii;

        if ($ascii > 64 && $ascii < 91) {
            $rotated += $n;
            $rotated > 90 && $rotated += -90 + 64;
            $rotated < 65 && $rotated += -64 + 90;
        } elseif ($ascii > 96 && $ascii < 123) {
            $rotated += $n;
            $rotated > 122 && $rotated += -122 + 96;
            $rotated < 97 && $rotated += -96 + 122;
        }

        $result .= chr($rotated);
    }

    return $result;
}

$enc = rotate('string', 6);
echo "Encoded: $enc<br/>\n";
echo 'Decoded: ' . rotate($enc, -6);

?>
maximius at gmail dot com 25-May-2007 04:30
Perhaps someone will find this useful ;)

<?
           function rotN($s, $n){
                $s2 = "";
                for($i = 0; $i < strlen($s); $i++){
                    $char2 = $char = ord($s{$i});
                    $cap = $char & 32;

                    $char &= ~ $cap;
                    $char = $char > 64 && $char < 123 ? (($char - 65 + $n) % 26 + 65) : $char;
                    $char |= $cap;
                    if($char < 65 && $char2 > 64 || ($char > 90 && $char < 97 && ($char2 < 91 || $char2 > 96))) $char += 26;
                    else if($char > 122 && $char2 < 123) $char -= 52;
                    if(strtoupper(chr($char2)) === chr($char2)) $char = strtoupper(chr($char)); else $char = strtolower(chr($char));
                    $s2 .= $char;
                }
                return $s2;
            }
?>
It takes any string, $s, and any ROT value, $n. Just like str_rot13, it's both an encoder and decoder. To decode an encoded string, just pass -$n instead of $n.
str_replace
str_shuffle
Обработка строк


Переставляет символы в строке случайным образом

str_rot13
str_split
Обработка строк
PHP Manual

str_shuffle

(PHP 4 >= 4.3.0, PHP 5)

str_shuffle — Переставляет символы в строке случайным образом

Описание

string str_shuffle ( string $str )

str_shuffle() перемешивает символы в строке. Выбирается одна возможная перестановка из всех возможных.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает перемешанную строку.

Примеры

Пример #1 Пример использования str_shuffle()

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// выведет что-то вроде этого: bfdaec
echo $shuffled;
?>

Смотрите также

  • shuffle() - Перемешивает массив
  • rand() - Генерирует случайное число

User Contributed Notes

qeremy [atta] gmail [dotta] com 24-Feb-2012 11:58
A proper unicode string shuffle;

<?php
function str_shuffle_unicode($str) {
    $tmp = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    shuffle($tmp);
    return join("", $tmp);
}
?>

$str = "Şeker yârim"; // My sweet love

echo str_shuffle($str); // i�eymrŢekr �

echo str_shuffle_unicode($str); // Şr mreyeikâ
Anonymous 21-Jun-2010 10:32
Shuffle for all encoding formats

<?php

function unicode_shuffle($string, $chars, $format = 'UTF-8')
{
    for($i=0; $i<$chars; $i++)
        $rands[$i] = rand(0, mb_strlen($string, $format));

        $s = NULL;

    foreach($rands as $r)
        $s.= mb_substr($string, $r, 1, $format);

    return $s;
}

?>
andre at admolin dot com 01-Apr-2010 11:11
Here are nice functions for invert/randomize/alter the capitalization of a string.

<?php
function invert_case( $str ) {
    for( $i = 0; $i < strlen( $str ); ++$i ) {
        $ret .= ( $str[ $i ] == strtolower( $str[ $i ] ) ) ? strtoupper( $str[ $i ] ) : strtolower( $str[ $i ] );
    }

    return $ret;
}

function rand_case( $str ) {
    for( $i = 0; $i < strlen( $str ); ++$i ) {
        $ret .= ( rand( 0, 1 ) == 0 ) ? strtolower( $str[ $i ] ) : strtoupper( $str[ $i ] );
    }

    return $ret;
}

function alter_case( $str ) {
    for( $i = 0; $i < strlen( $str ); ++$i ) {
        $ret .= ( $i % 2 == 0 ) ? strtoupper( $str[ $i ] ) : strtolower( $str[ $i ] );
    }

    return $ret;
}
?>

Examples:

<?php
# o RATO ROEU A ROUPA DO REI DE ROMA.
echo invert_case( 'O rato roeu a roupa do rei de roma.' );

# o RATo RoEU A ROUpA Do reI De rOma.
echo rand_case( 'O rato roeu a roupa do rei de roma.' );

# O RaTo rOeU A RoUpA Do rEi dE RoMa.
echo alter_case( 'O rato roeu a roupa do rei de roma.' );
?>
benshelock at gmail dot com 09-Apr-2009 01:51
<?php
$a = str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890');
echo substr($a,0,6);
?>
Creates a nice 6 digit unique ID similar to that of tinyurl.
merreborn at mailinator dot com 24-Jan-2008 11:46
Re: jojersztajner at OXYGEN dot POLAND

"It may be useful if you want to create an accessible CAPTCHA."

This is a flawed concept, since:

1) It's not really accessible -- your scrambled text would produce incomprehensible output if passed through a screen reader (just imagine what a computer saying "uinervtisy" would sound like)

2) It's in no way secure.  A simple script with access to a copy of /usr/dict/words can reduce the space of possible solutions to no more than a handful.

i.e., it's trivial for a script to generate a command like the following, which solves the "uinervtisy" example 100% of the time:

php@server:~$ egrep -i '^u[inervts]{8}y$' /usr/share/dict/words
university
php@server:~$

Novel idea, but it would take a clever spammer all of 5 minutes to defeat it completely.
jojersztajner at OXYGEN dot POLAND 16-Jun-2007 03:27
Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.

Hree's a cdoe taht slerbmcas txet in tihs way:
<?php
    function scramble_word($word) {
        if (strlen($word) < 2)
            return $word;
        else
            return $word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
    }

    echo preg_replace('/(\w+)/e', 'scramble_word("\1")', 'A quick brown fox jumped over the lazy dog.');
?>

It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.
CygnusX1 14-Feb-2007 01:17
To cobine functionality and simplicity of the two functions below we can have:

<?php
function generatePasswd($numAlpha=6,$numNonAlpha=2)
{
   $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';
   return str_shuffle(
      substr(str_shuffle($listAlpha),0,$numAlpha) .
      substr(str_shuffle($listNonAlpha),0,$numNonAlpha)
    );
}
?>
dzafel at op dot pl 29-Dec-2006 01:16
Very, very simple random password generator, without using rand() function:

<?php
function random_password($chars = 8) {
   $letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return substr(str_shuffle($letters), 0, $chars);
}
?>
nmoyroud at teledetection dot fr 03-Nov-2005 04:38
Just another update to password builder function. With this version, you can choose the number of alphanumeric characters to add and the number of non-alphanumeric characters. You obtain a more secure password. You can add another characters to the non-alphanumeric list if you need.
If you want a password with 8 alphanumeric and 3 non-alphanumeric characters in a random order, just call :
random_passwd(8,3);

function generatePasswd($numAlpha=6,$numNonAlpha=2) {
    $pwd = '';
    $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';

    $start = mt_rand(1, (strlen($listAlpha)-$numAlpha));
    $string = str_shuffle($listAlpha);
    $pwd .= substr($string,$start,$numAlpha);

    $start = mt_rand(1, (strlen($listNonAlpha)-$numNonAlpha));
    $string = str_shuffle($listNonAlpha);
    $pwd .= substr($string,$start,$numNonAlpha);

    return str_shuffle($pwd);
}
support at wiredlabs dot net 15-Aug-2005 02:03
Just an update to sfalcon's function.  Chooses a random number within the length and then selects a random segment not the current segment of 1 to $numchar. Also added upper-case chars.

function random_passwd($numchar=8) {
    $str = "abcefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $start = mt_rand(1, (strlen($str)-$numchar));
    $string = str_shuffle($str);
    $password = substr($string,$start,$numchar);
    return($password);
}
Qube, Efnet #php 05-Aug-2005 04:20
(correction)
I balked at the loop method used below in inverting and randomising capitalisation and released that we just need to flip the bit (3rd bit or 6th depending on what way you look at it) and it would cause the case change in a character.

Full code and example:
http://www.pgregg.com/projects/php/code/str_case.php
(append an s to the url to get the .phps source)

I came up with a method and thanks to arpad (optimising as ever! :) we now have:

Invert case:
preg_replace('/[a-z]/ie', '\'$0\' ^ str_pad(\'\', strlen(\'$0\'), \' \')', $input);

Randomise case:
preg_replace('/[a-z]/ie', '(rand(0,1) ? \'$0\' ^ str_pad(\'\', strlen(\'$0\'), \' \') : \'$0\')', $input);

and for good measure:
Upper case:
preg_replace('/[a-z]/e', '\'$0\' & str_pad(\'\', strlen(\'$0\'), chr(223))', $input);

Lower case:
preg_replace('/[A-Z]/e', '\'$0\' | str_pad(\'\', strlen(\'$0\'), \' \')', $input);
rudigreen at gmail dot com 01-Jul-2005 07:20
Here are 2 functions, one inverts the case of a string and the other one randomizes the captilization in a string, kinda
useful string operations.

<?

//Inverts the case of a string
function invert_case($str)
{
    $nstr = '';
    for($i=0;$i<strlen($str);$i++)
    {
        $char = substr($str,$i,1);
        //If it's lower case make it upper case
        if($char == strtolower($char))
        {
            $char = strtoupper($char);
        }
        else //if it's upper than make it lower
        {
            $char = strtolower($char);
        }
        $nstr .= $char;
    }
    return $nstr;
}

//Randomly capilizes/uncaptilizes chars in a string
function rand_case($str)
{
    $nstr = '';
    for($i=0;$i<strlen($str);$i++)
    {
        $char = substr($str,$i,1);
        $char = invert_case($char);
        //2 options, to change or not to change
        rand(0,1) == 1 ? $char = invert_case($char) : null;
        $nstr .= $char;
    }
    return $nstr;
}

//Example:
echo rand_case("pHp rooLz! gUyZ"); //produces something random
echo invert_case("pHP STRiNG sEx");//produces Php strIng SeX
?>
Michiel van den boogaard 17-Jan-2005 02:03
Shortend function for PHP < 4.3
<?php
function RandomPass($numchar)
{
    $word = "a,b,c,d,e,f,g,h,i,j,k,l,m,1,2,3,4,5,6,7,8,9,0";
    $array=explode(",",$word);
    shuffle($array);
    $newstring = implode($array,"");
    return substr($newstring, 0, $numchar);
}
?>
aidan at php dot net 26-Aug-2004 03:31
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
sfalcon_(at)_pymesweb_(dot)_com 26-Aug-2004 08:28
You can use str_shuffle to make simple and nice random passwords:

function random_passwd($numchar) {
      $string =str_shuffle("abcefghijklmnopqrstuvwxyz1234567890");
      $password = substr($string,1,$numchar);

      return($password);
}

echo random_passwd('8') // Will return something like "xa3dh214" =)
str_rot13
str_split
Обработка строк


Преобразует строку в массив

str_shuffle
str_word_count
Обработка строк
PHP Manual

str_split

(PHP 5)

str_split — Преобразует строку в массив

Описание

array str_split ( string $string [, int $split_length = 1 ] )

Преобразует строку в массив.

Список параметров

string

Входная строка.

split_length

Максимальная длина фрагмента.

Возвращаемые значения

Если указан необязательный аргумент split_length, возвращаемый массив будет содержать части исходной строки длиной split_length каждая, иначе каждый элемент будет содержать один символ.

Если split_length меньше 1, возвращается FALSE. Если split_length больше длины строки string, то вся строка будет возвращена в первом и единственном элементе массива.

Примеры

Пример #1 Пример использования str_split()

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

Результат выполнения данного примера:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

Смотрите также

  • chunk_split() - Разбивает строку на фрагменты
  • preg_split() - Разбивает строку по регулярному выражению
  • explode() - Разбивает строку с помощью разделителя
  • count_chars() - Возвращает информацию о символах, входящих в строку
  • str_word_count() - Возвращает информацию о словах, входящих в строку
  • for

User Contributed Notes

qeremy [atta] gmail [dotta] com 24-Feb-2012 12:23
A proper unicode string split;

<?php
function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
?>

$s = "Ilık süt"; // Mild milk

print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));

Array
(
    [0] => Il�
    [1] => �k
    [2] => sü
    [3] => t
)

Array
(
    [0] => Ilı
    [1] => k s
    [2] => üt
)
anon 15-Jun-2010 08:53
I needed a function that could split a string from the end with any left over chunk being at the beginning of the array (the beginning of the string).

<?php
function str_rsplit($str, $sz)
{
    // splits a string "starting" at the end, so any left over (small chunk) is at the beginning of the array.
    if ( !$sz ) { return false; }
    if ( $sz > 0 ) { return str_split($str,$sz); }    // normal split

    $l = strlen($str);
    $sz = min(-$sz,$l);
    $mod = $l % $sz;

    if ( !$mod ) { return str_split($str,$sz); }    // even/max-length split

    // split
    return array_merge(array(substr($str,0,$mod)), str_split(substr($str,$mod),$sz));
}

$str = 'aAbBcCdDeEfFg';
str_split($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,-5); // return: {'aAb','BcCdD','eEfFg'}

?>
seebz.net 03-May-2010 06:27
here an equivalent function for unicode string :

<?php
function uni_strsplit($string, $split_length=1)
{
    preg_match_all('`.`u', $string, $arr);
    $arr = array_chunk($arr[0], $split_length);
    $arr = array_map('implode', $arr);
    return $arr;
}
nemostein at hotmail dot com 28-Aug-2009 11:51
The manual don't says what is returned when you parse a different type of variable.

This is the example:

<?php

$str1 = "Long"; // More than 1 char
$str2 = "x"; // Only 1 char
$str3 = ""; // Empty String
$str4 = 34; // Integer
$str5 = 3.4; // Float
$str6 = true; // Bool
$str7 = null; // Null

$spl1 = str_split($str1);
$spl2 = str_split($str2);
$spl3 = str_split($str3);
$spl4 = str_split($str4);
$spl5 = str_split($str5);
$spl6 = str_split($str6);
$spl7 = str_split($str7);

echo count($spl1); // 4
echo count($spl2); // 1
echo count($spl3); // 1
echo count($spl4); // 2
echo count($spl5); // 3
echo count($spl6); // 1
echo count($spl7); // 1

print_r($spl1);
print_r($spl2);
print_r($spl3);
print_r($spl4);
print_r($spl5);
print_r($spl6);
print_r($spl7);

/*

Array
(
    [0] => L
    [1] => o
    [2] => n
    [3] => g
)
Array
(
    [0] => x
)
Array
(
    [0] =>
)
Array
(
    [0] => 3
    [1] => 4
)
Array
(
    [0] => 3
    [1] => .
    [2] => 4
)
Array
(
    [0] => 1
)
Array
(
    [0] =>
)

*/

?>
mattias at lsahlin dot se 19-Mar-2009 06:46
For those it may concern:

We encountered trubble when trying to str_split a UTF-8 encoded string, containing such Swedish letters as å, å and ö.

It seems that this function splits according to byte-length and not character length. So if the letter "Å" takes 2 bytes, then str_split() will only return the first bite of the character "Å".

We ain't 100% sure that this is the case but this was anyhow the result we got. So we used the multi-byte functions instead.
thax 23-Nov-2008 06:44
Regarding ricordatis comment on preg_match_all('/./u',...) instead of preg_split('//u',...):
You'll have to use the pattern '/./us' with preg_match_all to get exactly the same behaviour w.r.t. newlines. Don't know if this is still faster, though. Oh, and the expected result is in $array[0].
rrelmy 04-Aug-2008 07:20
revised function from tatsudoshi

Fixed some bugs, more php5 style compliant
<?php
if(!function_exists('str_split')) {
    function str_split($string,$string_length=1) {
        if(strlen($string)>$string_length || !$string_length) {
            do {
                $c = strlen($string);
                $parts[] = substr($string,0,$string_length);
                $string = substr($string,$string_length);
            } while($string !== false);
        } else {
            $parts = array($string);
        }
        return $parts;
    }
}
?>
ricordati at web dot de 01-Aug-2008 07:21
To split unicode text, preg_match_all('/./u', $text, $array); seems faster for large strings than the use of preg_split('//u', $text); suggested by "edgaras dot janusauskas at gmail dot com" below.
vec [ at t] g dot com 21-Jun-2008 08:38
the fastast way (that fits my needs) to replace str_split() in php 4 i found is this:

<?php
if(!function_exists('str_split')) {
  function str_split($string, $split_length = 1) {
    $array = explode("\r\n", chunk_split($string, $split_length));
    array_pop($array);
    return $array;
  }
}
?>

i also tested the provided functions in the comments..

(the differences are 0.001 to 0.00001 sec)
saeedco 21-May-2008 03:20
This function supportes utf8

(improvement of function str_split_php4)

i tried this function successfully with these languages
1- Chinese
2- Japanese
3- Arabic
4- Turkish
5- Urdu
6- Russian
7- Persian

<?php
function str_split_php4_utf8($str) {
    // place each character of the string into and array
    $split=1;
    $array = array();
    for ( $i=0; $i < strlen( $str ); ){
        $value = ord($str[$i]);
        if($value > 127){
            if($value >= 192 && $value <= 223)
                $split=2;
            elseif($value >= 224 && $value <= 239)
                $split=3;
            elseif($value >= 240 && $value <= 247)
                $split=4;
        }else{
            $split=1;
        }
            $key = NULL;
        for ( $j = 0; $j < $split; $j++, $i++ ) {
            $key .= $str[$i];
        }
        array_push( $array, $key );
    }
    return $array;
}
?>
lskatz at gmail dot com 07-May-2008 11:42
A good use of str_split is reverse translating an amino acid sequence.

<?php
/* reverse translate an aa sequence using its dna counterpart */
function reverseTranslate($aaSeq,$ntSeq){
  $nt=str_split($ntSeq,3);
  $aa=str_split($aaSeq,1);
  $gapChar=array('*','-');

  $numAa=count($aa);
  $ntIndex=0;
  $newNtSeq="";
  for($i=0;$i<$numAa;$i++){
    // if the aa is a gap, then just put on a gap character
    if(in_array($aa[$i],$gapChar)){
      $newNtSeq.='---';
    }
    else{
      $newNtSeq.=$nt[$ntIndex];
      $ntIndex++;
    }
  }
  return $newNtSeq;
}
?>
kevin at metalaxe dot com 14-Mar-2008 08:49
Response to "Richard Ayotte 18-Jan-2008 09:27":

Slight tweak to prevent the need to call another preg_replace, there were also some bugs in this that I'm surprised didn't get noticed (causing duplicate replaces between the preg_replace calls) :)

Please feel free to optimize further. I'm not the best with lookahead/behinds yet. I also removed the :upper/lower: and it seemed to speed things up too.

<?php
$test = 'CustomerIDWithSomeOtherJETWords';

preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', ' $0', $test));
?>

Shaves off a little time anyway. :)
Ap.Muthu 07-Feb-2008 04:20
Syntax corrected version:-

<?php
    if(! function_exists('str_split'))
    {
        function str_split($text, $split = 1)
        {
            $array = array();

            for ($i = 0; $i < strlen($text); $i += $split)
            {
                $array[] = substr($text, $i, $split);
            }

            return $array;
        }
    }
?>
Richard Ayotte 18-Jan-2008 06:27
Slight mod to the CamelCaseFormat regex that behaves better with strings with multiple upper case letters immediately following each other.

CustomerID -> Customer ID and not Customer I D

<?php
$test = 'CustomerIDWithSomeOtherJETWords';

preg_replace('/(?!^)[[:upper:]][[:lower:]]/', ' $0', preg_replace('/(?!^)[[:upper:]]+/', ' $0', $test));
?>

Customer ID With Some Other JET Words
Anonymous 03-Jan-2008 12:04
Version of str_split by rlpvandenberg at hotmail dot com is god-damn inefficient and when $i+$j > strlen($text) [last part of string] throws a lot of notice errors. This should work better:

    if(! function_exists('str_split'))
    {
        function str_split($text, $split = 1)
        {
            $array = array();

            for ($i = 0; $i < strlen($text);)
            {
                $array[] = substr($text, $i, $split);
                $i += $split;
            }

            return $array;
        }
    }
rlpvandenberg at hotmail dot com 19-Dec-2007 11:22
The previous suggestion is almost correct (and will only working for strlen=1. The working PHP4 function is:

<code>
function str_split($text, $split = 1){
    //place each character of the string into and array
    $array = array();
    for ($i=0; $i < strlen($text); $i++){
        $key = "";
        for ($j = 0; $j < $split; $j++){
            $key .= $text[$i+$j];
        }
        $i = $i + $j - 1;
        array_push($array, $key);
    }
    return $array;
}
</code>
skore at skore dot de 30-Nov-2007 09:16
dacmeaux at gmail dot com's version might work well for a $split value of 1, but above that, it just repeats the one character per array field and based on the $split value. The following does it right:

<?php
function str_split_php4( $text, $split = 1 ) {
    // place each character of the string into and array
    $array = array();
    for ( $i=0; $i < strlen( $text ); ){
        $key = NULL;
        for ( $j = 0; $j < $split; $j++, $i++ ) {
            $key .= $text[$i];
        }
        array_push( $array, $key );
    }
    return $array;
}
?>
mohd at ba7rain dot net 29-Nov-2007 02:24
this function can perform a reverse str_split. I write it for PHP4 but you can rename It for other versions..

if ( !function_exists('str_split') ) {
function str_split($string,$split_length=1){
    $sign = (($split_length<0)?-1:1);
    $strlen = strlen($string);
    $split_length = abs($split_length);
    if ( ($split_length==0) || ($strlen==0) ){
            $result = false;
            //$result[] = "";
    }
    elseif ($split_length >= $strlen){
        $result[] = $string;
    }
    else {
        $length = $split_length;
        for ($i=0; $i<$strlen; $i++){
            $i=(($sign<0)?$i+$length:$i);
            $result[] = substr($string,$sign*$i,$length);
            $i--;
            $i=(($sign<0)?$i:$i+$length);
            if ( ($i+$split_length) > ($strlen) ){
                $length = $strlen-($i+1);
            }
            else {
                $length = $split_length;
            }
        }
    }
    return $result;
}
}
www dot wesley at gmail dot com 25-Nov-2007 04:12
in response to Sam's CamelCase function:

<?php
$test = 'CamelCaseFormat';

echo preg_replace('/(?!^)[[:upper:]]/',' \0',$test);
?>
atolia at gmail----- dot com 10-Nov-2007 01:48
i use this in PHP4

function str_split($str){
   return preg_split('//',$str);
}
magisano at cs dot unibo dot it 06-Nov-2007 08:14
Even shorter version:

//place each character (or group of) of the
string into and array

function str_split_php4($sText, $iSplit = 1)
{
    $iSplit=(integer) $iSplit;       // sanity check
    if ($iSplit < 1) {  return false; }
    $aResult = array();
    for($i=0, $limit=strlen($sText); $i < $limit; $i+=$iSplit) {
        $aResult[]=substr($sText, $i, $iSplit);
    }
    return $aResult;
}
dacmeaux at gmail dot com 01-Nov-2007 01:57
I was looking for a function that would split a string into an array like str_split() and found Razor's function above. Just though that I would simplify the code a little.

<?php
function str_split_php4($text, $split = 1){
    //place each character of the string into and array
    $array = array();
    for($i=0; $i < strlen($text); $i++){
        $key = NULL;
        for ($j = 0; $j < $split; $j++){
            $key .= $text[$i];
        }
        array_push($array, $key);
    }
    return $array;
}
?>

Both mine and worksRazor's work well, I just prefer to use less code. I could have written one myself, but I was just being lazy.
Sam 25-Sep-2007 01:24
A good way to use this method to convert CamelCase text into nice text would be-

<?php
        /**
         Returns a formatted string based on camel case.
         e.g. "CamelCase" -> "Camel Case".
        */
        function FormatCamelCase( $string ) {
                $output = "";
                foreach( str_split( $string ) as $char ) {
                        strtoupper( $char ) == $char and $output and $output .= " ";
                        $output .= $char;
                }
                return $output;
        }
?>
edgaras dot janusauskas at gmail dot com 22-Aug-2007 05:30
To split unicode text, use preg_split('//u', $text);
kjensen at iaff106 dot com 11-Aug-2007 12:59
Here is what I use. I started with examples here but modified to my own version:

<?php
if (phpversion () < "5"){ // define PHP5 functions if server uses PHP4

function str_split($text, $split = 1)
{
if (!is_string($text)) return false;
if (!is_numeric($split) && $split < 1) return false;
$len = strlen($text);
$array = array();
$s = 0;
$e=$split;
while ($s <$len)
    {
        $e=($e <$len)?$e:$len;
        $array[] = substr($text, $s,$e);
        $s = $s+$e;
    }
return $array;
}
}
?>
l0c4lh0st DOT nl AT gmail DOT com 12-Jun-2007 05:28
how I can conwert
$string
 '1, 2, 5, 6, 10, 13, 23'
from ENUM at mySQL to

$array
[0] -> false
[1] -> true
[2] -> true
[3] -> false
[4] -> false
[5] -> true
[6] -> true
[7] -> false
[8] -> false
[9] -> false
[10] -> true
[11] -> false
[12] -> false
[13] -> true
[14] -> false
[15] -> false
...
[23] -> true

<?php
function enum_to_array($psEnum)
{
    $aReturn = array();
    $aTemp = explode(', ', $psEnum);
    for ($i = $aTemp[0]; $i <= $aTemp[count($aTemp)-1]; $i++)
    {
        $aReturn[$i] = in_array($i, $aTemp);
    }
}
?>
dhayes 07-Jun-2007 12:17
@razor: this'll work for php4
<?php
$str = 'two words';
$array = explode("\r\n", chunk_split($str,1));
?>
Razor 10-May-2007 12:02
heres my version for php4 and below

<?php

function str_split_php4($text, $split = 1)
{
    if (!is_string($text)) return false;
    if (!is_numeric($split) && $split < 1) return false;

    $len = strlen($text);

    $array = array();

    $i = 0;

    while ($i < $len)
    {
        $key = NULL;

        for ($j = 0; $j < $split; $j += 1)
        {
            $key .= $text{$i};

            $i += 1;
        }

        $array[] = $key;
    }

    return $array;
}

?>
26-Feb-2007 08:32
Problem with the post below me is, that the string can not contain the splitter "-1-".

Btw, here's my version.
<?php
function strsplit($str, $l=1) {
    do {$ret[]=substr($str,0,$l); $str=substr($str,$l); }
    while($str != "");
    return $ret;
}
?>
webmaster at nsssa dot ca 28-Oct-2006 07:45
I noticed in the post below me that his function would return an array with an empty key at the end.

So here is just a little fix for it.

<?php

//Create a string split function for pre PHP5 versions
function str_split($str, $nr) {

     //Return an array with 1 less item then the one we have
     return array_slice(split("-l-", chunk_split($str, $nr, '-l-')), 0, -1);

}

?>
05-Oct-2006 05:14
//fast & short version od str_split PHP3, 4x
function string_split($str, $nr){
    return split("-l-", chunk_split($str, $nr, '-l-'));
}
//example :
print_r(string_split('123412341234', 4));
ference at super_delete_brose dot co dot uk 31-Aug-2006 12:22
If you are looking for a way to split multibyte strings then this may come in handy:

<?php
$text  = "süpérbrôsé";

function mb_str_split($str, $length = 1) {
  if ($length < 1) return FALSE;

  $result = array();

  for ($i = 0; $i < mb_strlen($str); $i += $length) {
    $result[] = mb_substr($str, $i, $length);
  }

  return $result;
}

$solo = mb_str_split($text);
$quintet = mb_str_split($text, 5);

print_r($solo);
print_r($quintet);
?>

Spits out:

Array
(
    [0] => s
    [1] => ü
    [2] => p
    [3] => é
    [4] => r
    [5] => b
    [6] => r
    [7] => ô
    [8] => s
    [9] => é
)
Array
(
    [0] => süpér
    [1] => brôsé
)
fstorm2 at gmail dot com 29-Aug-2006 02:08
If you use PHP 4 and don't need the split_length parameter, here's the shortest replacement:

<?php

preg_split('#(?<=.)(?=.)#s', $str);

?>
http://www.matt-fletcher.co.uk/ 21-Aug-2006 04:44
A simple way to split credit card numbers into chunks of four numbers:

<?php
echo implode(' ',str_split($card_number,4));
?>
malmsteenforce at tlen dot pl 19-Jul-2006 10:52
<?
//fast & short version od str_split

function string_split($str)
      {
        $str_array=array();
        $len=strlen($str);
        for($i=0;$i<$len;$i++) $str_array[]=$str{$i};
        return $str_array;
       }
//example :
var_dump (string_split("split this"));
?>
user at mockme dot com 25-Mar-2006 05:53
found this great example on a php board for those not using php5, as an alternative to the posts below this

<?php
if(!function_exists('str_split')){
    function str_split($string,$split_length=1){
        $count = strlen($string);
        if($split_length < 1){
            return false;
        } elseif($split_length > $count){
            return array($string);
        } else {
            $num = (int)ceil($count/$split_length);
            $ret = array();
            for($i=0;$i<$num;$i++){
                $ret[] = substr($string,$i*$split_length,$split_length);
            }
            return $ret;
        }
    }
}
?>
simple 15-Mar-2006 07:54
if (!function_exists("str_split")) {
    function str_split($string, $length = 1) {
        if ($length <= 0) {
            trigger_error(__FUNCTION__."(): The the length of each segment must be greater then zero:", E_USER_WARNING);
            return false;
        }
        $splitted  = array();
        while (strlen($string) > 0) {
            $splitted[] = substr($string, 0, $length);
            $string = substr($string, $length);
        }
        return $splitted;
    }
}
14-Mar-2006 05:49
Note to function by carlosreche at yahoo dot com.

The while:
<?php
...
               while ($str_length--) {
                   $splitted[$i] = $string[$i++];
               }
...
?>
.. result in index starting at 1.
Ie: str_split("ABC") gives
Array
(
    [1] => A
    [2] => B
    [3] => C
)
While php5's str_split("ABC") gives
Array
(
    [0] => A
    [1] => B
    [2] => C
)
And his str_split("ABC",2) gives index starting at 0.
Change to this (or something similar):
<?php
...
               while ($str_length--) {
                   $splitted[$i] = $string[$i];
                   $i++;
               }
...
?>
.... or use heavyraptor's function. A bit more sclick,..
heavyraptor 10-Mar-2006 02:07
I think that the last post by carlosreche at yahoo dot com is too complicated.
It's much easier if you do it like this:

<?php
if (!function_exists("str_split")) {
  function str_split($str,$length = 1) {
    if ($length < 1) return false;
    $strlen = strlen($str);
    $ret = array();
    for ($i = 0; $i < $strlen; $i += $length) {
     $ret[] = substr($str,$i,$length);
    }
    return $ret;
  }
}
?>

I hope it helps for those with PHP <5
carlosreche at yahoo dot com 15-Feb-2006 04:23
For those who work with PHP < 5:

<?php

if (!function_exists("str_split")) {
    function str_split($string, $length = 1) {
        if ($length <= 0) {
            trigger_error(__FUNCTION__."(): The the length of each segment must be greater then zero:", E_USER_WARNING);
            return false;
        }
        $splitted  = array();
        $str_length = strlen($string);
        $i = 0;
        if ($length == 1) {
            while ($str_length--) {
                $splitted[$i] = $string[$i++];
            }
        } else {
            $j = $i;
            while ($str_length > 0) {
                $splitted[$j++] = substr($string, $i, $length);
                $str_length -= $length;
                $i += $length;
            }
        }
        return $splitted;
    }
}

?>
Hage Yaapa 04-Feb-2006 06:27
The very handy str_split() was introduced in PHP 5, but a lot of us are still forced to use PHP 4 at our host servers. And I am sure a lot of beginners have looked or are looking for a function to accomplish what str_split() does.

Taking advantge of the fact that strings are 'arrays' I wrote this tiny but useful e-mail cloaker in PHP, which guarantees functionality even if JavaScript is disabled in the client's browser. Watch how I make up for the lack of str_split() in PHP 4.3.10.

<?php

// cloackEmail() accepts a string, the email address to be cloaked
function cloakEmail($email) {

// We create a new array called $arChars, which will contain the individula characters making up the email address. The array is blank for now.
    $arChars = array();

// We extract each character from the email 'exploiting' the fact that strings behave like an array: watch the '$email[$i]' bit, and beging to fill up the blank array $arChars
    for ($i = 0; $i < strlen($email); $i++) { $arChars[] = $email[$i]; }

// Now we work on the $arChars array: extract each character in the array and print out it's ASCII value prefixed with '&#' to convert it into an HTML entity
    foreach ($arChars as $char) { print '&#'.ord($char); }

// The result is an email address in HTML entities which, I hope most email address harvesters can't read.

}
print cloakEmail('someone@nokikon.com');
?>

###### THE CODE ABOVE WITHOUT COMMENTS ######

<?php
function cloakEmail($email) {
    $arChars = array();
    for ($i = 0; $i < strlen($email); $i++) { $arChars[] = $email[$i]; }
    foreach ($arChars as $char) { print '&#'.ord($char); }
}
print cloakEmail('someone@nokikon.com');
?>
In creating this little utility, I demonstrated how the lack of str_split() can be made up in PHP < 5. If you got how it was accomplished, you could write a function to do exactly what str_split() does in PHP 5 and even name it 'str_split()'. :)
organek at hektor dot umcs dot lublin dot pl 21-May-2005 04:57
[Editor's Note: Or just: php.net/wordwrap]
This is a little function to split a string into shorter strings with max lenght $n in such way, that it don't split words (it search for spaces), it's usefull for articles or sth.
Result is put in $ttab variable, and function result is number of "pages".

<?php
function divide_text($text, $n, &$ttab) {

    $ttab = array();
    $l = strlen($text); // text length
    $cb = 0;    //copy begin from..
    $p = 0; // parts

    if ($l  <= $n) {
        $ttab[0] = $text;
        return 1;
    } else {
        $ctrl = 1;
        while(((($p-1) * $n) < $l) && ($ctrl < 100)) {
        $crtl++; // control variable, to protect from infinite loops

        $tmp = substr($text, $cb, $n);

        // we're looking for last space in substring
        $lastpos = strrpos($tmp," ");

        if ( (is_bool($lastbool) && !$lastpos) || ( $l - $cb <= $n)) {
            $ttab[$p] = $tmp;

        } else  {
            $tmpgood = trim(substr($tmp, 0,$lastpos));  // if they were another spaces at the end..
            $ttab[$p] = $tmpgood;
            $cb += $lastpos + 1 ;

        }; // if
        $p++;
        }; //for
        return $p;
    }; // if

} // divide text

?>
aidan at php dot net 20-May-2004 09:53
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
str_shuffle
str_word_count
Обработка строк


Возвращает информацию о словах, входящих в строку

str_split
strcasecmp
Обработка строк
PHP Manual

str_word_count

(PHP 4 >= 4.3.0, PHP 5)

str_word_count — Возвращает информацию о словах, входящих в строку

Описание

mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )

Подсчитывает количество слов, входящих в строку string. Если необязательный аргумент format не передан, возвращается целое число, равное количеству слов. В случае, если указан аргумент format, возвращается массив, содержимое которого зависит от значения format. Ниже описаны допустимые значения аргумента format и соответствующие им возвращаемые значения.

Для этой функции "слово" обозначает строку с алфавитными символами, зависящую от локали, которая также может содержать символы "'" и "-", но не может начинаться с них.

Список параметров

string

Строка

format

Указывает возвращаемое значение данной функции. На данный момент поддерживаются следующие значения:

  • 0 - возвращает количество найденных слов
  • 1 - возвращается массив, содержащий все слова, входящие в строку string
  • 2 - возвращается массив, индексами которого являются позиции в строке string, а значениями - соответствующие слова.

charlist

Список дополнительных символов, которые будут рассматриваться как "слово"

Возвращаемые значения

Возвращает массив или целое число, в зависимости от указанного параметра format.

Список изменений

Версия | Описание
5.1.0 | Добавлен параметр charlist

Примеры

Пример #1 Пример использования str_word_count()

<?php

$str = "Hello fri3nd, you're
       looking          good today!";

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));

echo str_word_count($str);

?>

Результат выполнения данного примера:

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)

Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7

Смотрите также

  • explode() - Разбивает строку с помощью разделителя
  • preg_split() - Разбивает строку по регулярному выражению
  • split() - Разбиение строки на массив по регулярному выражению
  • count_chars() - Возвращает информацию о символах, входящих в строку
  • substr_count() - Возвращает число вхождений подстроки

User Contributed Notes

cito at wikatu dot com 03-Feb-2012 09:29
<?php

/***
 * This simple utf-8 word count function (it only counts)
 * is a bit faster then the one with preg_match_all
 * about 10x slower then the built-in str_word_count
 *
 * If you need the hyphen or other code points as word-characters
 * just put them into the [brackets] like [^\p{L}\p{N}\'\-]
 * If the pattern contains utf-8, utf8_encode() the pattern,
 * as it is expected to be valid utf-8 (using the u modifier).
 **/

// Jonny 5's simple word splitter
function str_word_count_utf8($str) {
  return count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
?>
Samer Ata 05-Jan-2012 09:21
This is my own version of to get SEO meta description from wordpress post content. it is also generic usage function to get the first n words from a string.

<?php
function my_meta_description($text,$n=10)
{
$text=strip_tags($text);  // not neccssary for none HTML
// $text=strip_shortcodes($text); // uncomment only inside wordpress system
$text = trim(preg_replace("/\s+/"," ",$text));
$word_array = explode(" ", $text);
if (count($word_array) <= $n)
return implode(" ",$word_array);
else
{
$text='';
foreach ($word_array as $length=>$word)
{
    $text.=$word ;
    if($length==$n) break;
    else $text.=" ";
}
}
return $text;
?>
Stano110 at azet dot sk 10-Jul-2011 06:36
This function count words, is quick and works well with utf-8: (this is corrected version from my previous post)

<?php
function count_words($string)
{
    $string = htmlspecialchars_decode(strip_tags($string));
    if (strlen($string)==0)
        return 0;
    $t = array(' '=>1, '_'=>1, "\x20"=>1, "\xA0"=>1, "\x0A"=>1, "\x0D"=>1, "\x09"=>1, "\x0B"=>1, "\x2E"=>1, "\t"=>1, '='=>1, '+'=>1, '-'=>1, '*'=>1, '/'=>1, '\\'=>1, ','=>1, '.'=>1, ';'=>1, ':'=>1, '"'=>1, '\''=>1, '['=>1, ']'=>1, '{'=>1, '}'=>1, '('=>1, ')'=>1, '<'=>1, '>'=>1, '&'=>1, '%'=>1, '$'=>1, '@'=>1, '#'=>1, '^'=>1, '!'=>1, '?'=>1); // separators
    $count= isset($t[$string[0]])? 0:1;
    if (strlen($string)==1)
        return $count;
    for ($i=1;$i<strlen($string);$i++)
        if (isset($t[$string[$i-1]]) && !isset($t[$string[$i]])) // if new word starts
            $count++;
    return $count;
}
?>
Stano110 at azet dot sk 10-Jul-2011 05:05
This function count words, is quick and works well with utf-8:

    function count_words($string)
    {
        //$string = htmlspecialchars_decode(strip_tags($string)); // optional
        $t = array(' '=>1, '_'=>1, "\x20", "\xA0", "\x0A", "\x0D", "\x09", "\x0B", '='=>1, '+'=>1, '-'=>1, '*'=>1, '/'=>1, '\\'=>1, ','=>1, '.'=>1, ';'=>1, ':'=>1, '"'=>1, '\''=>1, '['=>1, ']'=>1, '{'=>1, '}'=>1, '('=>1, ')'=>1, '<'=>1, '>'=>1, '&'=>1, '%'=>1, '$'=>1, '@'=>1, '#'=>1, '^'=>1, '!'=>1, '?'=>1); // separators
        $count= isset($t[$string[0]])? 0:1;
        for ($i=1;$i<strlen($string);$i++)
            if (isset($t[$string[$i-1]]) && !isset($t[$string[$i]])) // if new word starts
                $count++;
        return $count;
    }
Zulfugar Ismayilzadeh admin at mid dot az 14-Apr-2011 04:52
This function count words. But this function works with UTF-8 too.

<?php

/**
 * @author Zulfugar Ismayilzadeh
 * @copyright 2011
 */

function count_words($string){

   $string = trim(preg_replace("/\s+/"," ",$string));

   $word_array = explode(" ", $string);

   $num = count($word_array);

   return $num;

}

$str = "Hello fri3nd, you're               looking good today!";

echo count_words($str);

?>
matthewkastor at live dot com 05-Apr-2011 07:08
This needs improvement, but works well as is.

<?php
/**
 * Generates an alphabetical index of unique words, and a count of their occurrences, in a file.
 *
 * This works on html pages or plain text files.
 * This function uses file_get_contents, so it
 * is possible to use a url instead of a local filename.
 *
 * Change the search pattern at
 * <code> $junk = preg_match('/[^a-zA-Z]/', $word); </code>
 * if you want to keep words with numbers or other characters. The pattern
 * I've set searches for anything that is not an upper or lowercase letter,
 * you may want something else.
 *
 * The array returned will look something like this:
 * <code>
 * Array
 * (
 *     [0] => Array
 *        (
 *            [word] => a
 *            [count] => 21
 *        )
 *
 *     [1] => Array
 *        (
 *            [word] => ability
 *            [count] => 1
 *        )
 * )
 * </code>
 *
 * @param string $file The file ( or url ) you want to create an index from.
 * @return array
 */
function index_page($file) {
    $index = array();
    $find = array(
        '/\r/',
        '/\n/',
        '/\s\s+/'
    );
    $replace = array(
        ' ',
        ' ',
        ' '
    );
    $work = file_get_contents($file);
    $work = preg_replace('/[>][<]/', '> <', $work);
    $work = strip_tags($work);
    $work = strtolower($work);
    $work = preg_replace($find, $replace, $work);
    $work = trim($work);
    $work = explode(' ', $work);
    natcasesort($work);
    $i = 0;
    foreach($work as $word) {
        $word = trim($word);
        $junk = preg_match('/[^a-zA-Z]/', $word);
        if($junk == 1) {
            $word = '';
        }
        if( (!empty($word)) && ($word != '') ) {
            if(!isset($index[$i]['word'])) { // if not set this is a new index
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            } elseif( $index[$i]['word'] == $word ) {  // count repeats
                $index[$i]['count'] += 1;
            } else { // else this is a different word, increment $i and create an entry
                $i++;
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            }
        }
    }
    unset($work);
    return($index);
}
?>

example usage:

<?php
$file = 'http://www.php.net/';
// or use a local file, see file_get_contents() for valid filenames and restrictions.

$index = index_page($file);
echo '<pre>'.print_r($index,true).'</pre>';
?>
dmVuY2lAc3RyYWhvdG5pLmNvbQ== (base64) 18-Oct-2010 04:39
to count words after converting a msword document to plain text with antiword, you can use this function:

<?php
function count_words($text) {
    $text = str_replace(str_split('|'), '', $text); // remove these chars (you can specify more)
    $text = trim(preg_replace('/\s+/', ' ', $text)); // remove extra spaces
    $text = preg_replace('/-{2,}/', '', $text); // remove 2 or more dashes in a row
    $len = strlen($text);

    if (0 === $len) {
        return 0;
    }

    $words = 1;

    while ($len--) {
        if (' ' === $text[$len]) {
            ++$words;
        }
    }

    return $words;
}
?>

it strips the pipe "|" chars, which antiword uses to format tables in its plain text output, removes more than one dashes in a row (also used in tables), then counts the words.

counting words using explode() and then count() is not a good idea for huge texts, because it uses much memory to store the text once more as an array. this is why i'm using while() { .. } to walk the string
lballard dot cat at gmail dot com 26-Sep-2010 08:17
word limiter:

$str = "my hella long string" ;
$length = 3;
$shortened =
implode(' ',array_slice(str_word_count($str,1),0,$length));
brettz9 - see yahoo 12-Feb-2010 11:33
Words also cannot end in a hyphen unless allowed by the charlist...
charliefrancis at gmail dot com 29-Jul-2009 04:56
Hi this is the first time I have posted on the php manual, I hope some of you will like this little function I wrote.

It returns a string with a certain character limit, but still retaining whole words.
It breaks out of the foreach loop once it has found a string short enough to display, and the character list can be edited.

<?php
function word_limiter( $text, $limit = 30, $chars = '0123456789' ) {
    if( strlen( $text ) > $limit ) {
        $words = str_word_count( $text, 2, $chars );
        $words = array_reverse( $words, TRUE );
        foreach( $words as $length => $word ) {
            if( $length + strlen( $word ) >= $limit ) {
                array_shift( $words );
            } else {
                break;
            }
        }
        $words = array_reverse( $words );
        $text = implode( " ", $words ) . '&hellip;';
    }
    return $text;
}

$str = "Hello this is a list of words that is too long";
echo '1: ' . word_limiter( $str );
$str = "Hello this is a list of words";
echo '2: ' . word_limiter( $str );
?>

1: Hello this is a list of words&hellip;
2: Hello this is a list of words
pdziok at gmail dot com 05-Jul-2009 12:08
I like your function eanimator but it got a little mistake - before the dots it putted another space.
This is a version with "bug" repaired:

<?php
function WordLimiter($text,$limit=20){
    $explode = explode(' ',$text);
    $string  = '';

    $dots = '...';
    if(count($explode) <= $limit){
        $dots = '';
    }
    for($i=0;$i<$limit;$i++){
        $string .= $explode[$i]." ";
    }
    if ($dots) {
        $string = substr($string, 0, strlen($string));
    }

    return $string.$dots;
}
?>
jazz090 13-Apr-2009 10:39
Personally, I dont like using this function becuase the characters it omits are sometime nessesery for instance MS Word counts ">" or "<" alone as single word where this function doesnt. I like using this however, it counts EVERYTHING:

<?php
function num_words($string){
    preg_match_all("/\S+/", $string, $matches);
    return count($matches[0]);
}
?>
splogamurugan at gmail dot com 05-Feb-2009 02:32
We can also specify a range of values for charlist.

<?php
$str = "Hello fri3nd, you're
       looking          good today!
       look1234ing";
print_r(str_word_count($str, 1, '0..3'));
?>

will give the result as

Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )
eanimator at yahoo dot com 11-Jan-2009 12:37
My quick and rough wordLimiter function.

<?php
function WordLimiter($text,$limit=20){
    $explode = explode(' ',$text);
    $string  = '';

    $dots = '...';
    if(count($explode) <= $limit){
        $dots = '';
    }
    for($i=0;$i<$limit;$i++){
        $string .= $explode[$i]." ";
    }

    return $string.$dots;
}
?>
manrash at gmail dot com 22-Dec-2008 03:06
For spanish speakers a valid character map may be:

<?php
$characterMap = 'áéíóúüñ';

$count = str_word_count($text, 0, $characterMap);
?>
om+www dot php dot net at miakinen dot net 07-Sep-2008 01:23
The previous function str_word_count_utf8 implemented only the first parameter, $string. Here is an implementation which also supports the second parameter, $format. The $charlist is not supported, though it could be possible to give the possibility to change the MASK.

<?php
    define("WORD_COUNT_MASK", "/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");

    function str_word_count_utf8($string, $format = 0)
    {
        switch ($format) {
        case 1:
            preg_match_all(WORD_COUNT_MASK, $string, $matches);
            return $matches[0];
        case 2:
            preg_match_all(WORD_COUNT_MASK, $string, $matches, PREG_OFFSET_CAPTURE);
            $result = array();
            foreach ($matches[0] as $match) {
                $result[$match[1]] = $match[0];
            }
            return $result;
        }
        return preg_match_all(WORD_COUNT_MASK, $string, $matches);
    }
?>

Note that in the case $format=2 the numeric positions are expressed in octets, not in characters.
om+www dot php dot net at miakinen dot net 06-Sep-2008 02:29
Here is a code for a function str_word_count() compatible with UTF-8. I'm sorry that the comments are in French because I am not very good in English: anyway, these comments only try to explain things that are in PCRE or Unicode documentations.

<?php
    /*
     * Explications du masque pour preg_match_all.
     *
     * La fonction str_word_count standard considère qu'un mot est
     * une séquence de caractères qui contient tous les caractères
     * alphabétiques, et qui peut contenir, mais pas commencer
     * par "'" et "-".
     *
     * Avec Unicode et UTF-8, une lettre peut être un caractères
     * ASCII non accentué tel que "e" ou "E", mais aussi un "é" ou
     * un "É", lequel peut se représenter sous la forme de deux
     * caractères : d'abord le "E" non accentué, puis l'accent tout
     * seul. Une lettre "E" ou "É" fait partie de la classe « L »,
     * un accent de la classe « Mn ».
     *
     * Par ailleurs, "-" n'est plus le seul trait d'union possible.
     * Plutôt que de les lister individuellement, j'ai choisi de
     * tester les caractères de la classe « Pd ». Un inconvénient
     * est que cela inclut aussi le tiret cadratin et d'autres,
     * mais cet inconvénient existait déjà avec str_word_count et
     * le tiret ascii, et en outre il ne concerne pas le français
     * (contrairement à l'anglais, il y a toujours des espaces
     * autour de ces tirets).
     *
     * Enfin, "'" n'est pas non plus la seule apostrophe possible.
     * Mais contrairement aux tirets je teste juste l'apostrophe
     * typographique U+2019 à part au lieu de tester la classe « Pf »
     * car cette dernière contient trop de signes de ponctuation
     * à exclure de la définition d'un mot.
     *
     * Un mot commence donc par une lettre \p{L}, éventuellement
     * accentuée (suivie par un nombre quelconque de \p{Mn}), et
     * ensuite on peut rencontrer un nombre quelconques d'autres
     * lettres (\p{L} et \p{Mn}), de tirets (\p{Pd}) ou d'apostrophes
     * (' et \x{2019}). Tout ceci, bien sûr, dans un masque compatible
     * avec UTF-8 (/u à la fin).
     *
     * Pour les références, voir :
     * http://fr2.php.net/manual/fr/regexp.reference.php #regexp.reference.unicode
     * http://fr2.php.net/manual/fr/reference.pcre.pattern.modifiers.php
     */
    define("WORD_COUNT_MASK", "/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");

    function str_word_count_utf8($str)
    {
        return preg_match_all(WORD_COUNT_MASK, $str, $matches);
    }
luce 06-Sep-2008 02:52
Fix Cathy function bug.

Original Cathy function :
[code]
<?php
    function limit_text($text, $limit) {
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }
?>
[/code]

This function return undefined index if $limit < $text.

For fix it :
[code]
<?php
    function limit_text($text, $limitstr, $limitwrd) {
      if (strlen($text) > $limitstr) {
          $words = str_word_count($text, 2);
          if ($words > $limitwrd) {
              $pos = array_keys($words);
              $text = substr($text, 0, $pos[$limitwrd]) . '...';
          }
      }
      return $text;
    }
?>
[/code]
aspu.ru 17-Jun-2008 04:21
str_word_count: mixed (string string, [int format], [string charlist])

It can help you to solve problem with digest and some locales. Best regards.
robocop at robotix dot fr 30-Mar-2008 06:21
function count_words($texte)
{
$texte=trim($texte);
$motsinutiles = array(' * ', ' - ', ' : ', '\n');
$texte = str_replace($motsinutiles, '', $texte);
$texte = preg_replace("/\s\s+/", " ", $texte);
$decoupeapostrophes = count(explode('\'', $texte)); //On découpe la chaine en apostrophes
   if($decoupeapostrophes==0) $nombreapostrophes = 0;
   if ($decoupeapostrophes%2==0) {$nombreapostrophes = $decoupeapostrophes/2;}
   else  $nombreapostrophes = ($decoupeapostrophes/2)-0.5;
$nombreespace = count(explode(' ', $texte));

return $nombreespace+$nombreapostrophes;
}
security_man 24-Dec-2007 01:13
there was a glitch in the code cathy put a post or two ago... should be:

    function limit_text($text, $limit) {
    $text = strip_tags($text);
      $words = str_word_count($text, 2);
      $pos = array_keys($words);
      if (count($words) > $limit) {
          $text = substr($text, 0, $pos[$limit]) . ' ...';
      }
    return $text;
    }

I also added the strip tags in case there is html in there to gum up the works
Adeel Khan 08-Dec-2007 08:01
<?php

/**
 * Returns the number of words in a string.
 * As far as I have tested, it is very accurate.
 * The string can have HTML in it,
 * but you should do something like this first:
 *
 *    $search = array(
 *      '@<script[^>]*?>.*?</script>@si',
 *      '@<style[^>]*?>.*?</style>@siU',
 *      '@<![\s\S]*?--[ \t\n\r]*>@'
 *    );
 *    $html = preg_replace($search, '', $html);
 *
 */

function word_count($html) {

  # strip all html tags
  $wc = strip_tags($html);

  # remove 'words' that don't consist of alphanumerical characters or punctuation
  $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#";
  $wc = trim(preg_replace($pattern, " ", $wc));

  # remove one-letter 'words' that consist only of punctuation
  $wc = trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#", " ", $wc));

  # remove superfluous whitespace
  $wc = preg_replace("/\s\s+/", " ", $wc);

  # split string into an array of words
  $wc = explode(" ", $wc);

  # remove empty elements
  $wc = array_filter($wc);

  # return the number of words
  return count($wc);

}

?>
Cathy 19-Jul-2007 01:16
A cute little function for truncating text to a given word limit:
<?php
    function limit_text($text, $limit) {
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }
?>
geertdd at gmail dot com 13-Jun-2007 09:04
This is an update to my previously posted word_limiter() function. The regex is even more optimized now. Just replace the preg_match line. Change to:

<?php
preg_match('/^\s*(?:\S+\s*){1,'. (int) $limit .'}/', $str, $matches);
geertdd at gmail dot com 28-May-2007 04:52
Here's a very fast word limiter function that preserves the original whitespace.

<?php

function word_limiter($str, $limit = 100, $end_char = '&#8230;') {

    if (trim($str) == '')
        return $str;

    preg_match('/\s*(?:\S*\s*){'. (int) $limit .'}/', $str, $matches);

    if (strlen($matches[0]) == strlen($str))
        $end_char = '';

    return rtrim($matches[0]) . $end_char;
}

?>

For the thought process behind this function, please read: http://codeigniter.com/forums/viewthread/51788/

Geert De Deckere
joshua dot blake at gmail dot com 02-Mar-2007 05:02
I needed a function which would extract the first hundred words out of a given input while retaining all markup such as line breaks, double spaces and the like. Most of the regexp based functions posted above were accurate in that they counted out a hundred words, but recombined the paragraph by imploding an array down to a string. This did away with any such hopes of line breaks, and thus I devised a crude but very accurate function which does all that I ask it to:

function Truncate($input, $numWords)
{
  if(str_word_count($input,0)>$numWords)
  {
    $WordKey = str_word_count($input,1);
    $PosKey = str_word_count($input,2);
    reset($PosKey);
    foreach($WordKey as $key => &$value)
    {
        $value=key($PosKey);
        next($PosKey);
    }
    return substr($input,0,$WordKey[$numWords]);
  }
  else {return $input;}
}

The idea behind it? Go through the keys of the arrays returned by str_word_count and associate the number of each word with its character position in the phrase. Then use substr to return everything up until the nth character. I have tested this function on rather large entries and it seems to be efficient enough that it does not bog down at all.

Cheers!

Josh
josh at joshblake.net 01-Mar-2007 03:57
I was interested in a function which returned the first few words out of a larger string.

In reality, I wanted a preview of the first hundred words of a blog entry which was well over that.

I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc.

So, this is what I came up with:

function WordTruncate($input, $numWords) {
if(str_word_count($input,0)>$numWords)
{
    $WordKey = str_word_count($input,1);
    $WordIndex = array_flip(str_word_count($input,2));
    return substr($input,0,$WordIndex[$WordKey[$numWords]]);
}
else {return $input;}
}

While I haven't counted per se, it's accurate enough for my needs. It will also return the entire string if it's less than the specified number of words.

The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position.

Josh.
30-Jan-2007 08:15
Here is a php work counting function together with a javascript version which will print the same result.

<?php
      //Php word counting function
      function word_count($theString)
      {
        $char_count = strlen($theString);
        $fullStr = $theString." ";
        $initial_whitespace_rExp = "^[[:alnum:]]$";

        $left_trimmedStr = ereg_replace($initial_whitespace_rExp,"",$fullStr);
        $non_alphanumerics_rExp = "^[[:alnum:]]$";
        $cleanedStr = ereg_replace($non_alphanumerics_rExp," ",$left_trimmedStr);
        $splitString = explode(" ",$cleanedStr);

        $word_count = count($splitString)-1;

        if(strlen($fullStr)<2)
        {
          $word_count=0;
        }
        return $word_count;
      }
?>

<?php
      //Function to count words in a phrase
      function wordCount(theString)
      {
        var char_count = theString.length;
        var fullStr = theString + " ";
        var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
        var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
        var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
        var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
        var splitString = cleanedStr.split(" ");

        var word_count = splitString.length -1;

        if (fullStr.length <2)
        {
          word_count = 0;
        }
        return word_count;
      }
?>
Aurelien Marchand 06-Oct-2006 09:06
I found a more reliable way to print, say the first 100 words and then print elipses. My code goes this way;

$threshold_length = 80; // 80 words max
$phrase = "...."; // populate this with the text you want to display
$abody = str_word_count($phrase,2);
if(count($abody) >= $threshold_length){ // gotta cut
  $tbody = array_keys($abody);
  echo "<p>" . substr($phrase,0,$tbody[$threshold_length]) . "... <span class=\"more\"><a href=\"?\">read more</a></span> </p>\n";
} else { // put the whole thing
  echo "<p>" . $phrase . "</p>\n";
}

For any questions, com.iname@artaxerxes2
lwright at psu dot edu 17-Aug-2006 11:51
If you are looking to count the frequency of words, try:

<?php

$wordfrequency = array_count_values( str_word_count( $string, 1) );

?>
rabin at rab dot in 04-Apr-2006 11:03
There is a small bug in the "trim_text" function by "webmaster at joshstmarie dot com" below. If the string's word count is lesser than or equal to $truncation, that function will cut off the last word in the string.

[EDITOR'S NOTE: above referenced note has been removed]

This fixes the problem:

<?php
function trim_text_fixed($string, $truncation = 250) {
    $matches = preg_split("/\s+/", $string, $truncation + 1);
    $sz = count($matches);
    if ( $sz > $truncation ) {
        unset($matches[$sz-1]);
        return implode(' ',$matches);
    }
    return $string;
}
?>
webmaster at joshstmarie dot com 25-Sep-2005 04:58
Trying to make an effiecient word splitter, and "paragraph limiter", eg, limit item text to 100, or 200 words and so-forth.

I don't know how well this compares, but it works nicely.

function trim_text($string, $word_count=100)
{
    $trimmed = "";
    $string = preg_replace("/\040+/"," ", trim($string));
    $stringc = explode(" ",$string);
    echo sizeof($stringc);
    if($word_count >= sizeof($stringc))
    {
        // nothing to do, our string is smaller than the limit.
      return $string;
    }
    elseif($word_count < sizeof($stringc))
    {
        // trim the string to the word count
        for($i=0;$i<$word_count;$i++)
        {
            $trimmed .= $stringc[$i]." ";
        }

        if(substr($trimmed, strlen(trim($trimmed))-1, 1) == '.')
          return trim($trimmed).'..';
        else
          return trim($trimmed).'...';
    }
}

$text = "some  test          text goes in here, I'm not sure, but ok.";
echo trim_text($text,5);
MadCoder 15-Aug-2005 09:12
Here's a function that will trim a $string down to a certian number of words, and add a...   on the end of it.
(explansion of muz1's 1st 100 words code)

----------------------------------------------
function trim_text($text, $count){
$text = str_replace("  ", " ", $text);
$string = explode(" ", $text);
for ( $wordCounter = 0; $wordCounter <= $count;wordCounter++ ){
$trimed .= $string[$wordCounter];
if ( $wordCounter < $count ){ $trimed .= " "; }
else { $trimed .= "..."; }
}
$trimed = trim($trimed);
return $trimed;
}

Usage
------------------------------------------------
$string = "one two three four";
echo trim_text($string, 3);

returns:
one two three...
jtey at uoguelph dot ca 14-Aug-2005 04:21
In the previous note, the example will only extract from the string, words separated by exactly one space.  To properly extract words from all strings, use regular expressions.

Example (extracting the first 4 words):
<?php
$string = "One    two three       four  five six";
echo implode(" ", array_slice(preg_split("/\s+/", $string), 0, 4));
?>

The above $string would not have otherwise worked when using the explode() method below.
jtey at uoguelph dot ca 14-Aug-2005 07:59
In reply to muz1's post below:

You can also take advantage of using other built in PHP functions to get to your final result.  Consider the following:
<?php
$string = "One two three four five six seven eight nine ten.";
// the first n words to extract
$n = 3;
// extract the words
$words = explode(" ", $string);
// chop the words array down to the first n elements
$firstN = array_slice($words, 0, $n);
// glue the 3 elements back into a spaced sentence
$firstNAsAString = implode(" ", $firstN);
// display it
echo $firstNAsAString;
?>

Or to do it all in one line:
<?php
echo implode(" ", array_slice(explode(" ", $string), 0, $n));
?>
muz1 at muzcore dot com 12-Aug-2005 12:56
This function is awesome however I needed to display the first 100 words of a string. I am submitting this as a possible solution but also to get feedback as to whether it is the most efficient way of doing it.

<?
                                    $currString = explode(" ", $string);
for ($wordCounter=0; $wordCounter<100; $wordCounter++) { echo $currString[$wordCounter]." "; }
?>
16-Jan-2005 06:38
This function seems to view numbers as whitespace. I.e. a word consisting of numbers only won't be counted.
aix at lux dot ee 14-Nov-2004 02:53
One function.
<?php
if (!function_exists('word_count')) {
function word_count($str,$n = "0"){
    $m=strlen($str)/2;
    $a=1;
    while ($a<$m) {
        $str=str_replace("  "," ",$str);
        $a++;
        }
    $b = explode(" ", $str);
    $i = 0;
    foreach ($b as $v) {
        $i++;
        }
    if ($n==1) return $b;
    else  return $i;

    }
}
$str="Tere Tartu linn";
$c  = word_count($str,1); // it return an array
$d  = word_count($str); // it return int - how many words was in text
print_r($c);
echo $d;
?>
aidan at php dot net 26-Jun-2004 03:02
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
Kirils Solovjovs 22-Feb-2004 09:06
Nothing of this worked for me. I think countwords() is very encoding dependent. This is the code for win1257. For other layots you just need to redefine the ranges of letters...

<?php
function countwords($text){
        $ls=0;//was it a whitespace?
        $cc33=0;//counter
        for($i=0;$i<strlen($text);$i++){
                $spstat=false; //is it a number or a letter?
                $ot=ord($text[$i]);
                if( (($ot>=48) && ($ot<=57)) ||  (($ot>=97) && ($ot<=122)) || (($ot>=65) && ($ot<=90)) || ($ot==170) ||
                (($ot>=192) && ($ot<=214)) || (($ot>=216) && ($ot<=246)) || (($ot>=248) && ($ot<=254))  )$spstat=true;
                if(($ls==0)&&($spstat)){
                        $ls=1;
                        $cc33++;
                }
                if(!$spstat)$ls=0;
        }
        return $cc33;
}

?>
Artimis 15-Oct-2003 02:32
Never use this function to count/separate alphanumeric words, it will just split them up words to words, numbers to numbers.  You could refer to another function "preg_split" when splitting alphanumeric words.  It works with Chinese characters as well.
andrea at 3site dot it 19-May-2003 04:55
if string doesn't contain the space " ", the explode method doesn't do anything, so i've wrote this and it seems works better ... i don't know about time and resource

<?php
function str_incounter($match,$string) {
$count_match = 0;
for($i=0;$i<strlen($string);$i++) {
if(strtolower(substr($string,$i,strlen($match)))==strtolower($match)) {
$count_match++;
}
}
return $count_match;
}
?>

example

<?php
$string = "something:something!!something";
$count_some = str_incounter("something",$string);
// will return 3
?>
megat at megat dot co dot uk 18-Apr-2003 06:29
[Ed: You'd probably want to use regular expressions if this was the case --alindeman @ php.net]

Consider what will happen in some of the above suggestions when a person puts more than one space between words. That's why it's not sufficient just to explode the string.
olivier at ultragreen dot net 11-Apr-2003 06:10
I will not discuss the accuracy of this function but one of the source codes above does this.

<?php
function wrdcnt($haystack) {
 $cnt = explode(" ", $haystack);
 return count($cnt) - 1;
}
?>

That could be replace by

<?php
function wrdcnt($haystack) {
 return substr_count($haystack,' ') + 1;
}
?>

I doubt this does need to be a function :)
philip at cornado dot com 06-Apr-2003 07:30
Some ask not just split on ' ', well, it's because simply exploding on a ' ' isn't fully accurate.  Words can be separated by tabs, newlines, double spaces, etc.  This is why people tend to seperate on all whitespace with regular expressions.
rcATinterfacesDOTfr 16-Jan-2003 07:58
Here is another way to count words :
$word_count = count(preg_split('/\W+/', $text, -1, PREG_SPLIT_NO_EMPTY));
brettNOSPAM at olwm dot NO_SPAM dot com 09-Nov-2002 12:06
This example may not be pretty, but It proves accurate:

<?php
//count words
$words_to_count = strip_tags($body);
$pattern = "/[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-\-|:|\&|@)]+/";
$words_to_count = preg_replace ($pattern, " ", $words_to_count);
$words_to_count = trim($words_to_count);
$total_words = count(explode(" ",$words_to_count));
?>

Hope I didn't miss any punctuation. ;-)
gorgonzola at nospam dot org 31-Oct-2002 02:48
i tried to write a wordcounter and ended up with this:

<?php
//strip html-codes or entities
$text = strip_tags(strtr($text, array_flip(get_html_translation_table(HTML_ENTITIES))));
//count the words
$wordcount = preg_match_all("#(\w+)#", $text, $match_dummy );
?>
str_split
strcasecmp
Обработка строк


Бинарно-безопасное сравнение строк без учета регистра

str_word_count
strchr
Обработка строк
PHP Manual

strcasecmp

(PHP 4, PHP 5)

strcasecmp — Бинарно-безопасное сравнение строк без учета регистра

Описание

int strcasecmp ( string $str1 , string $str2 )

Бинарно-безопасное сравнение строк без учета регистра.

Список параметров

str1

Первая строка

str2

Вторая строка

Возвращаемые значения

Возвращает отрицательное число, если str1 меньше, чем str2, положительное число, если str1 больше, чем str2, и 0 если строки равны.

Примеры

Пример #1 Пример использования strcasecmp()

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 равно $var2 при сравнении без учета регистра';
}
?>

Смотрите также

  • strcmp() - Бинарно-безопасное сравнение строк
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • substr_compare() - Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
  • strncasecmp() - Бинарно-безопасное сравнение первых n символов строк без учета регистра
  • stristr() - Регистро-независимый вариант функции strstr
  • substr() - Возвращает подстроку

User Contributed Notes

chris at cmbuckley dot co dot uk 28-Dec-2011 04:59
A simple multibyte-safe case-insensitive string comparison:

<?php

function mb_strcasecmp($str1, $str2, $encoding = null) {
    if (null === $encoding) { $encoding = mb_internal_encoding(); }
    return strcmp(mb_strtoupper($str1, $encoding), mb_strtoupper($str2, $encoding));
}

?>

Caveat: watch out for edge cases like "ß".
alvaro at demogracia dot com 29-Jul-2010 05:35
Don't forget this is a single-byte function: in Unicode strings it'll provide incoherent results as soon as both strings differ only in case. There doesn't seem to exist a built-in multi-byte alternative so you need to write your own, taking into account both character encoding and collation.
27-Aug-2002 06:53
The sample above is only true on some platforms that only use a simple 'C' locale, where individual bytes are considered as complete characters that are converted to lowercase before being differentiated.

Other locales (see LC_COLLATE and LC_ALL) use the difference of collation order of characters, where characters may be groups of bytes taken from the input strings, or simply return -1, 0, or 1 as the collation order is not simply defined by comparing individual characters but by more complex rules.

Don't base your code on a specific non null value returned by strcmp() or strcasecmp(): it is not portable. Just consider the sign of the result and be sure to use the correct locale!
str_word_count
strchr
Обработка строк


Псевдоним strstr

strcasecmp
strcmp
Обработка строк
PHP Manual

strchr

(PHP 4, PHP 5)

strchr — Псевдоним strstr()

Описание

Эта функция является псевдонимом: strstr().

User Contributed Notes

webmaster at lyndonstate dot edu 12-Nov-2003 12:01
Alternative Way:
To get all the text before the first occurence.

-----------------------------------------------
INCLUDING A NEEDLE:

$string1 = "I need cookies & soda.";
$needle = "cookies";

//find length of the needle
$needle_len = strlen($needle);

//find postion
$position_num = strpos($string1,$needle) + $needle_len;

//cut the string
$result_string = substr("$string1",0,$position_num);

//display it
echo"$result_string"; // I need cookies

-----------------------------------------------
SHORTER VERSION:

$result_string = substr("$string1",0,strpos($string1,$needle)+strlen($needle));

echo"$result_string";//I need cookies

-----------------------------------------------
EXCLUDING THE NEEDLE:

$result_string = substr("$string1",0,strpos($string1,$needle));

echo"$result_string";// I need

-----------------------------------------------
FREE EMAIL JUNK?

This is probably useful for processing emails.
For example, someone sends email to your server from Yahoo account.
Free email always comes with wasted stuff like...
"Do you Yahoo!? The New Yahoo! Shopping - with improved product search ".
We can delete the phrase like this:

$needle="Do you Yahoo!?";

$result_string = substr("$emailstring",0,strpos($emailstring, $needle));
joaobett at oninet dot pt 10-Jan-2003 08:43
//If you want to get the text before the occurence of the character
//you want to find, simply use the function strRev twice:

$stringA = "user@example.com";
$toFind = "@";

$stringA = strrev($stringA); //The first time
$result = strchr($stringA,$toFind);
$result = strrev($result); //The second time
echo $result; //prints user@

//You can use it this way instead:
echo strrev( strchr(strrev($stringA),$toFind) );

-joao
strcasecmp
strcmp
Обработка строк


Бинарно-безопасное сравнение строк

strchr
strcoll
Обработка строк
PHP Manual

strcmp

(PHP 4, PHP 5)

strcmp — Бинарно-безопасное сравнение строк

Описание

int strcmp ( string $str1 , string $str2 )

Эта функция учитывает регистр символов.

Список параметров

str1

Первая строка.

str2

Вторая строка.

Возвращаемые значения

Возвращает отрицательное число, если str1 меньше, чем str2, положительное число, если str1 больше, чем str2, и 0 если строки равны.

Смотрите также

  • strcasecmp() - Бинарно-безопасное сравнение строк без учета регистра
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • substr_compare() - Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
  • strncmp() - Бинарно-безопасное сравнение первых n символов строк
  • strstr() - Находит первое вхождение подстроки
  • substr() - Возвращает подстроку

User Contributed Notes

jendoj at gmail dot com 07-May-2012 11:00
If you rely on strcmp for safe string comparisons, both parameters must be strings, the result is otherwise extremely unpredictable.
For instance you may get an unexpected 0, or return values of NULL, -2, 2, 3 and -3.

strcmp("5", 5) => 0
strcmp("15", 0xf) => 0
strcmp(61529519452809720693702583126814, 61529519452809720000000000000000) => 0
strcmp(NULL, false) => 0
strcmp(NULL, "") => 0
strcmp(NULL, 0) => -1
strcmp(false, -1) => -2
strcmp("15", NULL) => 2
strcmp(NULL, "foo") => -3
strcmp("foo", NULL) => 3
strcmp("foo", false) => 3
strcmp("foo", 0) => 1
strcmp("foo", 5) => 1
strcmp("foo", array()) => NULL + PHP Warning
strcmp("foo", new stdClass) => NULL + PHP Warning
strcmp(function(){}, "") => NULL + PHP Warning
hrodicus at gmail dot com 28-Feb-2011 06:40
Note a difference between 5.2 and 5.3 versions

echo (int)strcmp('pending',array());
will output -1 in PHP 5.2.16 (probably in all versions prior 5.3)
but will output 0 in PHP 5.3.3

Of course, you never need to use array as a parameter in string comparisions.
hm2k at php dot net 02-Aug-2010 04:41
Don't forget the similar_text() function...

http://php.net/manual/en/function.similar-text.php
Rob Wiesler 21-Jul-2009 12:48
One big caveat - strings retrieved from the backtick operation may be zero terminated (C-style), and therefore will not be equal to the non-zero terminated strings (roughly Pascal-style) normal in PHP. The workaround is to surround every `` pair or shell_exec() function with the trim() function. This is likely to be an issue with other functions that invoke shells; I haven't bothered to check.

On Debian Lenny (and RHEL 5, with minor differences), I get this:

====PHP====
<?php
$sz = `pwd`;
$ps = "/var/www";

echo "Zero-terminated string:<br />sz = ".$sz."<br />str_split(sz) = "; print_r(str_split($sz));
echo "<br /><br />";

echo "Pascal-style string:<br />ps = ".$ps."<br />str_split(ps) = "; print_r(str_split($ps));
echo "<br /><br />";

echo "Normal results of comparison:<br />";
echo "sz == ps = ".($sz == $ps ? "true" : "false")."<br />";
echo "strcmp(sz,ps) = ".strcmp($sz,$ps);
echo "<br /><br />";

echo "Comparison with trim()'d zero-terminated string:<br />";
echo "trim(sz) = ".trim($sz)."<br />";
echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo "<br />";
echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")."<br />";
echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps);
?>

====Output====
Zero-terminated string:
sz = /var/www
str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => )

Pascal-style string:
ps = /var/www
str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )

Normal results of comparison:
sz == ps = false
strcmp(sz,ps) = 1

Comparison with trim()'d zero-terminated string:
trim(sz) = /var/www
str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
trim(sz) == ps = true
strcmp(trim(sz),ps) = 0
wsogmm at seznam dot cz 16-May-2009 08:45
Just a short comment to the note of arnar at hm dot is: md5() is a hash function and therefore it may happen (although it is very unlikely) that the md5() checksums of  two different strings will be equal (hash collision) ...
arnar at hm dot is 15-May-2009 07:51
Sometimes when you compare two strings that look "the same", you will find that they aren't. If you don't want to bother finding out why, then this is a simple solution:

$string = implode(str_split($string));

Converting the strings to md5 is also a nice method to see if they're equal.

md5($str1)."\n";
md5($str2)."\n\n";

____________
Arnar Yngvason
ThinkSoftware
nullhility at gmail dot com 15-Mar-2009 02:36
For those that are confused about the way this function works:

<?php
$str1 = 'a';
$str2 = 'b';
var_dump(strcmp($str1, $str2)); //int(-1)
?>

Alphabetically 'a' precedes 'b'. If we view the strings as values 'a' is less than 'b' and therefore the function returns -1.

If we were searching through an alphabetically sorted list we'd have a numerical index ($i) and compare the search string ($sstr) against each member of the string list ($slist), using strcmp we can check whether to go "up"($i++) or "down"($i--) through this list.

Here's the example function:
<?php
function strInList ($sstr)
{
    $slist = array('a', 'b', 'c', 'd', 'e' /* etc */);

    $i = sizeof($slist) / 2; //start the index in the middle

    while ($i < sizeof($slist) && $i >= 0) { //constrain $i to the scope of $slist

        $cmp = strcmp($slist[$i], $sstr);

        if ($cmp > 0) { //alphabetically, $slist[$i] procedes $sstr
            $i--; //move DOWN the list
        } else if ($cmp < 0) { //alphabetically, $slist[$i] precedes $sstr
            $i++; //move UP the list
        } else if ($cmp == 0) { //$slist[$i] occurs neither before nor after $sstr
            return true; //successful match
        }
    }
    return false; //The index fell out of the list scope, with no match made
}
?>
g-lock at nv-net.ru 18-Jun-2008 11:08
Here is my function to compare russian words.
You can replace $abc to your alphabet.

function strcmp_rus($str1, $str2)
{
    $abc = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ
абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
    $len = min(strlen($str1), strlen($str2));
    for ($i = 0; $i < $len; $i++)
    {
        $s1 = strlen($abc);
        $s2 = strlen($abc);
        for ($j = 0; $j < strlen($abc); $j++) if ($str1[$i] == $abc[$j]) $s1 = $j;
        for ($k = 0; $k < strlen($abc); $k++) if ($str2[$i] == $abc[$k]) $s2 = $k;
        if ($s1 < $s2) return -1;
        else if ($s1 > $s2) return 1;
    }
    return 0;
}
nobody@nogroup 23-Aug-2007 07:59
To Monsieur Egmont and 'php or die', use setlocale and strcoll to compare strings in languages such as German, Swedish that use accented characters, and strings of non-latin script.
M. Egmond 22-Aug-2006 03:21
php dot or dot die at phpuser dot net wrote that he had an unexpected difference in comparing between case sensitive and insensitive. They key there is that the case insensitive comparison converts both strings to lowercase before comparing. Since the underscore character is in a different place when compared to an uppercase or lowercase string, the result is different.

There is no 'clear' order of punctuation and other characters in or around the alphabet. Most code assumes ASCII order in which case there are several characters before both upper- and lowercase, a few inbetween, and some after both upper- and lowercase.

Note also many other/older implementations of sorting sort accented character wrong since they appear after all other alphabetical characters in most charactersets. There is probably a function in PHP to take this into account though.

Therefore I would not recommend to make a detailed assumption on how punctuation and other characters sort in relation to alphabetical characters. If sorting these characters at a specific place and in a specific order is important for you, you should probably write a custom string comparison function that does it the way you want. Usually it's sufficient to have a consistent sorting order though, which is what you get by using either strcmp, or strcasecmp consistently.
jeff at skrysak dot com 03-Aug-2006 07:36
The definition of return values of this function is listed correctly on this page, however, there is a common misconception in the notes posted here previously from users.

A previous poster said:
If $str1 == $str2 strcmp return 0.
If $str1  > $str2 strcmp return 1.
If $str1  < $str2 strcmp return -1.

That is incorrect, please look at the definition of the function
at the top of this page. It returns less than 0 if str1 is less than str2. Note the phrase "less than", it does not return just -1, but any negative value. The same happens when str1 is greater than str2, but it returns a positive, non-zero value. It returns a positive value that can be 1, or any number thereafter.

strcmp() returns a number that is the difference between the two strings starting with the last character that was found to be similar.

Here is an example:

$output = strcmp("red", "blue");

The variable $output with contain a value of 16
robertb at littleNOSPAMcutie dot net 05-Apr-2006 07:19
S dot Radovanovic suggested:

"So my conclusion is that when comparing string, you'd better not make use of == (use strmp or === instead). For integer comparisons the == equation can be usefull, since our values will always be casted to an integer (1 == "1" returns true)."

When I tried this, I ran into a problem with parameters passed in the URL.  I forgot that a parameter that is not supplied wouldn't be a string, so this code -- which I expected to default to the current year -- didn't work:

<?php
// Did we get a parameter?
if ($year === '') {
    // Default to current year
    $temp = getdate();
    $year = $temp['year'];
}

$fname = "magic{$year}.txt";

if (file_exists($fname) == FALSE) {
  echo "<h2>Data file doesn't exist</h2>";
  exit;
}
?>

Since $year was uninitialized, it didn't exactly equal '', and the file wasn't found.  I went back to == in this case.

However, I did heed your advice when looking for a particular value ($debug === 'Y'), instead of looking for the lack of a value.  Thanks!
php dot or dot die at phpuser dot net 15-Feb-2006 02:19
I've a strange problem. I tried to compare string in the same order oracle does.
The strange thing is:
strcmp('ACQUE_SOTTERRANEE','ACQUE_SOTT_ORAC')
//result is -1
strcasecmp('ACQUE_SOTTERRANEE','ACQUE_SOTT_ORAC')
//result is 6

I'm surprised for the opposite result!
The correct order (oracle ascending order) is:
1- ACQUE_SOTTERRANEE
2- ACQUE_SOTT_ORAC
francis at flourish dot org 08-Dec-2005 06:57
If you want to strings according to locale, use strcoll instead.
element @ no spam dot net 19-Feb-2005 03:42
When using strcmp to compare results received from a form, keep in mind that the way you decide to encapsulate the value of the form will have an effect on your strcmp() results.

Example:

<input type="post" name="user[0]" value="abc">
<input type="post" name="user[1]" value='abc'>

strcmp() will not return the values sent from this form as "0".

However, by using single-quotes or double-quotes to encapsulate BOTH values, strcmp() will return a "0" result.
S dot Radovanovic at TriMM dot nl 07-Feb-2005 06:36
One thing to note in comparison with ==

When we make a comparison with == php automaticly converts strings to integers when either side of the comparison is an integer, f.e.:
<?
$value = 0;
if($value == "submit") {
    echo "Let's submit";
}
?>
Above would be succesful, since "submit" is converted to an integer (eq 0) and the equation is would return true; (that's why (1 == "1submit") would also return true)

That's why we should use strcmp or === (checks type also), for string comparisons.

So my conclusion is that when comparing string, you'd better not make use of == (use strmp or === instead). For integer comparisons the == equation can be usefull, since our values will always be casted to an integer (1 == "1" returns true).
x123 at bestof-inter dot net 29-Oct-2004 06:43
Please tell what you mean by "alphabetically" and when you say
"because of the way it works, it is not very useful..." or
"I get strange results, 1 for strings that are equal, etc." :
give an example where it does not work and/or show where your script works better!
(To test some PHP code, it is sufficient to have a file of 3 lines:
<form action='' method=POST><input type=submit value=Evaluate>
<textarea id=c><?=$c=stripslashes($_POST['c'])?></textarea>
<br>Result of the above:<pre><?=eval($c)?></pre></form>)

Imagine how much time is lost for visitors trying to figure out what your program does differently from strcmp ?

Imagine how much resources are wasted if PHP users are made to think that PHP functions don't work well and use the EXTREMELY inefficient routines proposed below (e.g. a string comparision routine that uses substr(...,$i,1) to access individual caracters...!)

If the documentation says 'binary safe' this should mean that strings are compared byte by byte (according to internal format)
- if strcmp() does instead use locale collation tables, this should be clearly mentioned in the documentation.
pabloATnkstudiosDOTnet 01-Jun-2004 11:36
Just note that the documentation about the function returns is a little confused.

So...

If $str1 == $str2 strcmp return 0.
If $str1  > $str2 strcmp return 1.
If $str1  < $str2 strcmp return -1.

Pablo Rosciani
http://pablo.rosciani.com.ar
jcanals at totsoft dot com 30-Jan-2004 06:05
Some notes about the spanish locale. I've read some notes that says  "CH", "RR" or "LL" must be considered as a single letter in Spanish. That's not really tru. "CH", "RR" and "LL" where considered a single letter in the past (lot of years ago), for that you must use the "Tradictional Sort". Nowadays, the Academy uses the Modern Sort and recomends not to consider anymore "CH", "RR" and "LL" as a single letter. They must be considered two separated letters and sort and compare on that way.

Ju just have to take a look to the Offial Spanish Language Dictionary and you can see there that from many years ago there is not the separated section for "CH", "LL" or "RR" ... i.e. words starting with CH must be after the ones starting by CG, and before the ones starting by CI.
gregd at sad dot net 08-Sep-2003 11:49
In cases when you need to compare a line from a just parsed file stream to match a user-defined "nametag" (useful for parsing ini and configuration files), keep in mind the 'end of line' tags as well:

// nametag to look for in a file (notice a required "\r\n" at the end)
$nametag = "[System]\r\n";

// ...assuming the file has been aready opened for reading and the stream is bound to $filehandle... parse the file until an EOF or $nametag encountered.

while (!feof ($handle))
{
    $buffer = fgets($filehandle);
    if (strcmp($nametag, $buffer) == 0)
    {
        // at this point "[System]" is found, do additional parsings...
        break;
    }
}
admin[nospam] at pretend dot tk 17-Jun-2003 07:44
Reguarding the above note on language specific string comparisons, LL and RR are also single letters in the Spanish language.
mnunemacher at datility dot net 27-Apr-2003 03:40
Because of the way this function works, it's not very useful for ordering strings alphabetically. If you're trying to alphabetize a list of strings (like a dictionary does), you may want to use the following functions instead:
-----------------

// Returns 1 if $str1 comes before $str2 alphabetically
// Returns -1 if $str1 comes after $str2 alphabetically
// Returns 0 if $str1 and $str2 are the same
function orderAlpha ( $str1, $str2 ) {
   $limit = null;

   if ( strlen( $str1 ) > strlen( $str2 ) ) {
      $limit  = strlen( $str2 );
   } else {
      $limit = strlen( $str1 );
   }

   for ( $i = 0;$i < $limit;$i++ ) {
      if ( substr( $str1, $i, 1 ) > substr( $str2, $i, 1 ) ) {
         return 1;
      } else if ( substr( $str1, $i, 1 ) < substr( $str2, $i, 1 ) ) {
         return -1;
      }
   }

   if ( strlen( $str1 ) > strlen( $str2 ) ) {
      return 1;
   } else if ( strlen( $str1 ) < strlen( $str2 ) ) {
      return -1;
   }

   return 0;
}

// Case insensitive version of orderAlpha
function orderiAlpha ( $str1, $str2 ) {
   return orderAlpha( strtolower( $str1 ), strtolower( $str2 ) );
}
-----------------
ahmed at somantic dot net 23-Mar-2003 12:52
For some reason the strcmp fails for this function if the $item_to_compare->ID = "AB123" or some similar string. This happened even though $ID = "AB123":
<pre>

function item_exists($ID)
{
   // returns 0 for error
   global $item_list; // this is an array of class objects

   if (is_array($item_list))
   {
      foreach ($item_list as $key => $item_to_compare)
      {
         if (!strcmp($item_to_compare->ID, $ID))
         {
            unset ($item_list);
            return $key;
         }
      }
   }
   // Else fail
   unset ($item_list);
   return 0;
}

</pre>

So I was forced to do this:

<pre>

function item_exists($ID)
{
   // returns 0 for error
   global $item_list;

   if (is_array($item_list))
   {
      for($i = 0; $i < count($item_list); $i++)
      {
         if (!strcmp($item_list[$i]->ID, $ID))
         {
            unset ($item_list);
            return $i;
         }
      }
   }
   // Else fail
   unset ($item_list);
   return 0;
}

</pre>
izhan dot khalib at acpibhd dot com 16-Dec-2002 11:13
I have tried the  strcmp function. Pls be very carefull. The string comparison must exactly "equal". So many people had confused.

I.e

My program read a string from test.txt file to get the
"[company name]" string.

// get contents of a file into a string
$filename = "test.txt";
$fd = fopen ($filename, "rb");
$contents = fread ($fd, filesize ($filename));

for($i=0;$i<strpos($contents, "]")+1;$i++)
{
//print $contents[$i];
//$a=trim($contents[$i]);
$a=$contents[$i];
echo $a;
//echo $i;
}

$str2="[companyname]";

// this comparison will resulted on greater (1), $result=1
//please remember $tempvariable[2] != $tempvariable (is not equal)
$result = strcmp(strtolower($a),strtolower($str2));

//this comparison working properly, $result=0
//$result = strcmp(strtolower($a),strtolower($str2[12]));

echo $result;

if ($a==$str2[12]) //double check the equality of string
{
echo "read the NextLine"; }
 else {
 echo "not equal";
 }
//end

fclose ($fd);
?>

I hope the above example will help you.
madsen at sjovedyr dot dk 02-Oct-2002 11:59
It's definitely worth noting that the return-values of strcmp() when used for i.e. password-checking is the oposite of that of the ==-operator.

I.e.:
$pw1 = "yeah";
$pw2 = "yeah";

if (strcmp($pw1, $pw2)) {   // This returns false.
    // $pw1 and $pw2 are NOT the same.
} else {
    // $pw1 and $pw2 are the same.
}

Where the use of the == operator would give us.:
if ($pw1==$pw2) {    // This returns true.
    // $pw1 and $pw2 are the same.
} else {
    // $pw1 and $pw2 are NOT the same.
}

Additionally, to check if $pw1 and $pw2 are of the same type you can use the === operator.
27-Aug-2002 06:45
In summary, strcmp() does not necessarily use the ASCII code order of each character like in the 'C' locale, but instead parse each string to match language-specific character entities (such as 'ch' in Spanish, or 'dz' in Czech), whose collation order is then compared. When both character entities have the same collation order (such as 'ss' and '�' in German), they are compared relative to their code by strcmp(), or considered equal by strcasecmp().
The LC_COLLATE locale setting is then considered: only if LC_COLLATE=C or LC_ALL=C does strcmp() compare strings by character code.
Generally, most locales define the following order:
control, space, punctuation and underscore, digit, alpha (lower then upper with Latin scripts; or final, middle, then isolated, initial with Arabic script), symbols, others...
With strcasecmp(), the alpha subclass is ignored and consider all forms of letters as equal.
Note also that some locales behave differently with accented characters: some consider they are the same letter as the unaccented letter (with a minor collation order, e.g. French, Italian, Spanish), some consider they are distinct letters with an independant collation order (e.g. in the C locale, or in Nordic languages).
Finally, the collation string is not considering individual characters but instead groups of characters that form a single letter:
- for example "ch" or "CH" in Spanish which is always after all other strings beginning with 'c' or 'C', including "cz", but before 'd' or 'D';
- 'ss' and '�' in German;
- 'dz', 'DZ' and 'Dz' in some Central European languages written with the Latin script...
- UTF-8, UTF-16 (Unicode), S-JIS, Big5, ISO2022 character encoding of a locale (the suffix in the locale name) first decode the characters into the UCS4/ISO10646 code position before applying the rules of the language indicated by the main locale...
So be extremely careful to what you consider a "character", as it may just mean a encoding byte with no significance in the string collation algorithm: the first character of the string "cholera" in Spanish is "ch", not "c" !
anonymous at anon dot com 14-Jun-2001 04:51
As mentioned above...be careful of trailing whitespace when making string comparisons...to be sure that you are rid of it all, use the trim() function.
owen at cips dot nokia dot com 03-Nov-2000 04:23
Regarding bizarre return values from str*cmp(), I was having similar troubles until I realized that I was attempting to compare a string with HTML formatting with its plain-text equivilant. The formatted string was an <OPTION> value, so the HTML was rendered without the <b> and <i> formatting I was using. Consequently the formatted and unformatted strings were rendered identically in the browser. D'oh!
phpnotes at travelersweb dot com 31-Jul-2000 08:18
Here is a quick note to explain what is meant by > and <.  I wrote a script to compare results.  If a string is  closer to 'A' in the alphabet, it is < the other string.  Here is the output hope this save saves people lots of time:
acc = acc     |  ac < acc
accc > acc    | acd > acc
acb < acc     |  acb < accc
acb < accd   |  bcc > acc
bcc > acc     |  bcca > acc
bcc > acca   |  1bcc < acca
bcc < bcc1    |  bcc1 > bcc
1bcc < bcc    |  1bcc < 1bcd
1bcd > 1bcc  |  _bcc < bcc
bcc > _bcc    |   ;bcc < bcc
bcc > ;bcc     |  bcc < bcc;
bcc; = bcc;
Jesse at bend dot com 26-Jul-2000 10:15
Well, I am using PHP 4.0 and both strcmp and strcasecmp appear to be giving me very arbitrary and incomprehensible results. When I input strings, it appears that "equal" strings return "1", as well as some unequal strings, and that if the first argument is "smaller" then I *tend* to get negative numbers, but sometimes I get 1, and if larger I *tend* to get numbers larger than 1..

both strcmp and strcasecmp are thus rendered totally unuseable for me in order to either alphebetize or compare strings for inequality.
frewuill at merlin-corp dot com 28-Feb-2000 02:49
Hey be sure the string you are comparing has not special characters like '\n' or something like that.
strchr
strcoll
Обработка строк


Сравнение строк с учетом текущей локали

strcmp
strcspn
Обработка строк
PHP Manual

strcoll

(PHP 4 >= 4.0.5, PHP 5)

strcoll — Сравнение строк с учетом текущей локали

Описание

int strcoll ( string $str1 , string $str2 )

Обратите внимание, что эта функция учитывает регистр символов, и, в отличие от strcmp() не безопасна для обработки данных в двоичной форме.

strcoll() при сравнении использует установки текущей локали. Если установлена локаль C или POSIX, эта функция аналогична strcmp().

Список параметров

str1

Первая строка.

str2

Вторая строка.

Возвращаемые значения

Возвращает отрицательное число, если str1 меньше, чем str2, положительное число, если str1 больше, чем str2, и 0, если они равны.

Список изменений

Версия | Описание
4.2.3 | Теперь эта функция работает и на win32.

Смотрите также

  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • strcmp() - Бинарно-безопасное сравнение строк
  • strcasecmp() - Бинарно-безопасное сравнение строк без учета регистра
  • substr() - Возвращает подстроку
  • stristr() - Регистро-независимый вариант функции strstr
  • strncasecmp() - Бинарно-безопасное сравнение первых n символов строк без учета регистра
  • strncmp() - Бинарно-безопасное сравнение первых n символов строк
  • strstr() - Находит первое вхождение подстроки
  • setlocale() - Устанавливает настройки локали

User Contributed Notes

sakkarinlaohawisut15 at hotmail dot com 22-Mar-2003 11:31
strcoll()'s behavior is sometimes a little bit confusing. It depends on LC_COLLATE in your locale.

<?php

 $a = 'a';
 $b = 'A';

 print strcmp ($a, $b) . "\n"; // prints 1

setlocale (LC_COLLATE, 'C');
 print "C: " . strcoll ($a, $b) . "\n"; // prints 1

 setlocale (LC_COLLATE, 'de_DE');
 print "de_DE: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'de_CH');
print "de_CH: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'en_US');
 print "en_US: " . strcoll ($a, $b) . "\n"; // prints -2

?>

This is useful e. g. if want to sort an array by using strcoll:

<?php

 $a = array ('a', 'A', '�', '�', 'b', 'B');

 setlocale (LC_COLLATE, 'C');
 usort ($a, 'strcoll');
 print_r ($a);

?>

This is like sort($a):
 Array
 (
    [0] => A
    [1] => B
  [2] => a
    [3] => b
    [4] => �
    [5] => �
 )

<?php

 setlocale (LC_COLLATE, 'de_DE');
usort ($a, 'strcoll');
 print_r ($a)

?>
This is completely different:
 Array
 (
    [0] => a
    [1] => A
    [2] => �
    [3] => �
    [4] => b
  [5] => B
 )
27-Aug-2002 07:05
Note that some platforms implement strcmp() and strcasecmp() according to the current locale when strings are not binary equal, so that strcmp() and strcoll() will return the same value! This depends on how the PHP strcmp() function is compiled (i.e. if it uses the platform specific strcmp() found in its standard library!).
In that case, the only difference between strcoll() and strcmp() is that strcoll() may return 0 for distinct strings(i.e. consider strings are equal) while strcmp() will differentiate them if they have distinct binary encoding! This typically occurs on Asian systems.
What you can be sure is that strcmp() will always differentiate strings that are encoded differently, but the relative order may still use the current locale setting for collation order!
strcmp
strcspn
Обработка строк


Возвращает длину участка в начале строки, не соответствующего маске

strcoll
strip_tags
Обработка строк
PHP Manual

strcspn

(PHP 4, PHP 5)

strcspn — Возвращает длину участка в начале строки, не соответствующего маске

Описание

int strcspn ( string $str1 , string $str2 [, int $start [, int $length ]] )

Возвращает длину участка в начале строки str1, который не содержит ни одного символа из строки str2.

Список параметров

str1

Первая строка.

str2

Вторая строка.

start

Начальная позиция сравнения строки.

length

Длина сравнения строки.

Возвращаемые значения

Возвращает длину фрагмента в виде целого числа.

Список изменений

Версия | Описание
4.3.0 | Добавлены параметры start и length

Примеры

Пример #1 Пример использования strcspn()

<?php
$a = strcspn('abcd',  'apple');
$b = strcspn('abcd',  'banana');
$c = strcspn('hello', 'l');
$d = strcspn('hello', 'world');

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>

Результат выполнения данного примера:

int(0)
int(0)
int(2)
int(2)

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strspn() - Возвращает длину участка в начале строки, полностью соответствующего маске

User Contributed Notes

legacyprog at routinz dot net 09-Dec-2010 07:20
When you use the third parameter remember that the function will return the number of characters it bypassed, which will *not* be the position in your source string.  It's a simple fix to just add your third parameter value to the function result to get the position in the first string where the scan stopped, but I didn't think of it at first.
Anonymous 16-Oct-2009 10:55
strcspn() can also be thought of as analogous to the following regular expression:
<?php
// where ... represents the mask of characters
preg_match('/[^ ...]/', substr($subject, $start, $length) );
?>
By this analogy, strcspn() can be used in place of some regular expressions to match a pattern without the overhead of a regex engine -- for example, ways to verify if an input string represents a binary value:
<?php
preg_match('/^[01]+$/i', $subject);
// or...
!preg_match('/[^01]/i', $subject);

// ...or using strcspn()
!strcspn($subject, '01');
?>
Dmitry Mazur 04-Mar-2009 10:17
The second parameter simply is the set of the "stop"-characters.
In other words, this function will return the index (starting from 0) of a first occurence of the stop-character.
PHP at NospamImmortalSoFar dot com 07-Oct-2006 06:31
Also useful for breaking down expressions - for example parsing SQL: values ('this', fn("that,)()", 4))

$sep = strcspn ($list, "'\"`");     //    Start of quoted string
$list = substr ($list, $sep);
$find = substr ($list, 0, 1);
while (($sep = strpos ($list, $find, $sep+1)) > 0 && substr ($list, $sep-1, 1) == '\\')
    {}
//  $sep now spans the entire string, regardless of embedded quotes

Once the strings have been removed, an expression can then be parsed for commas and brackets without worrying about them:

while ($out != '')
{
    $sep = strcspn ($list, "(),");      //  Next seperator
...
}
AT-HE (at_he AT hotmai1 DOT com) 27-Dec-2005 02:07
this function can be used like strspn(), except while that can be used to compare a string with an allowed pattern, this one can be use to compare a string with a FORBIDDEN pattern

so, to know if any forbidden character has a position inside our string, we can use (not tested with backslashes)...

<?php
// LARGE VERSION
$forbidden="\"\\?*:/@|<>";
if (strlen($filename) != strcspn($filename,$forbidden)) {
    echo "you cant create a file with that name!";
}

// SHORT VERSION
if (strlen($filename) - strcspn($filename,"\"\\?*:/@|<>")) {
    echo "i told you, you cant create that file";
}
?>
maskedcoder at hotmail dot com 10-Oct-2005 04:13
useful for finding beginning of quotes and/or tags in a variable containing html.
    $pos = strcspn($data, '<"\'');
will find the first occurance of either the beginning of a tag, or a double- or single-quoted string.
strcoll
strip_tags
Обработка строк


Удаляет HTML и PHP-теги из строки

strcspn
stripcslashes
Обработка строк
PHP Manual

strip_tags

(PHP 4, PHP 5)

strip_tags — Удаляет HTML и PHP-теги из строки

Описание

string strip_tags ( string $str [, string $allowable_tags ] )

Эта функция пытается возвратить строку str, из которой удалены все NUL-байты, HTML и PHP теги. Для удаления тегов используется тот же автомат, что и в функции fgetss().

Список параметров

str

Входная строка.

allowable_tags

Второй необязательный параметр может быть использован для указания тегов, которые не нужно удалять.

Замечание:

Комментарии HTML и PHP-теги также будут удалены. Это жестко записано в коде и не может быть изменено с помощью параметра allowable_tags.

Замечание:

Этот параметр не должен содержать пробелов. strip_tags() рассматривает тег как нечувствительную к регистру строку, находящуюся между < и первым пробелом или >. Это означает, что strip_tags("<br/>", "<br>") вернет пустую строку.

Возвращаемые значения

Возвращает строку без тегов.

Список изменений

Версия | Описание
5.0.0 | strip_tags() теперь безопасна для обработки бинарных данных
4.3.0 | Комментарии HTML теперь всегда удаляются

Примеры

Пример #1 Пример использования strip_tags()

<?php
$text = '<p>Параграф.</p><!-- Комментарий --> <a href="#fragment">Еще текст</a>';
echo strip_tags($text);
echo "\n";

// Разрешаем <p> и <a>
echo strip_tags($text, '<p><a>');
?>

Результат выполнения данного примера:

Параграф. Еще текст
<p>Параграф.</p> <a href="#fragment">Еще текст</a>

Примечания

Внимание

Из-за того, что strip_tags() не проверяет валидность HTML, то частичные или сломанные теги могут послужить удалением большего количества текста или данных, чем ожидалось.

Внимание

Эта функция не изменяет атрибуты тегов, разрешенных с помощью allowable_tags, включая такие атрибуты как style и onmouseover, которые могут быть использованы озорными пользователями при посылке текста, отображаемого также и другим пользователям.

Смотрите также

  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности

User Contributed Notes

garrygrierson at hotmail dot co dot uk 29-Mar-2012 11:09
or you can use the sledgehammer approach to get rid of everything betwean any tags:

preg_replace ( "'<[^>]+>'U", "", $textstring);
matthew at poleposition dot uk dot com 06-Feb-2012 01:15
Here is a far better function for the atypical process of stripping tags:

<?php
function strip_html_tags( $text )
{
    $text = preg_replace(
        array(
          // Remove invisible content
            '@<head[^>]*?>.*?</head>@siu',
            '@<style[^>]*?>.*?</style>@siu',
            '@<script[^>]*?.*?</script>@siu',
            '@<object[^>]*?.*?</object>@siu',
            '@<embed[^>]*?.*?</embed>@siu',
            '@<applet[^>]*?.*?</applet>@siu',
            '@<noframes[^>]*?.*?</noframes>@siu',
            '@<noscript[^>]*?.*?</noscript>@siu',
            '@<noembed[^>]*?.*?</noembed>@siu',
          // Add line breaks before and after blocks
            '@</?((address)|(blockquote)|(center)|(del))@iu',
            '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
            '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
            '@</?((table)|(th)|(td)|(caption))@iu',
            '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
            '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
            '@</?((frameset)|(frame)|(iframe))@iu',
        ),
        array(
            ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',"$0", "$0", "$0", "$0", "$0", "$0","$0", "$0",), $text );

    return strip_html_tags( $text , '<b><a>' );
}
?>
Cubist 05-Jan-2012 07:31
Function to simply test if a given location index is inside a tag in the string

<?php
function in_tag($str,$index) {
    //test if $index occurs inside an html tag in $str

    $before = substr($str,0,$index);
    $after = substr($str,$index);

    $prev_lt = strrpos($before,'<');
    $next_lt = strpos($after,'<') + $index;

    $prev_gt = strrpos($before,'>');
    $next_gt = strpos($after,'>') + $index;

    return ($prev_gt < $prev_lt) && ($next_lt > $next_gt);
}
?>
Maddy Vora 13-Nov-2011 11:01
Here is the function created for strip tags with sub string

<?php
function displaySubStringWithStrip($string, $length=NULL)
{
    if ($length == NULL)
            $length = 50;

    $stringDisplay = substr(strip_tags($string), 0, $length);
    if (strlen(strip_tags($string)) > $length)
        $stringDisplay .= ' ...';
    return $stringDisplay;
}

?>
shimy1984 20-Oct-2011 09:40
The following is an easy way to use strip_tags() with a simple array or a multidimensional array.

<?php

function strip_tags_array($data, $tags = null)
{
    $stripped_data = array();
    foreach ($data as $value)
    {
        if (is_array($value))
        {
            $stripped_data[] = strip_tags_array($value, $tags);
        }
        else
        {
            $stripped_data[] = strip_tags($value, $tags);
        }
    }
    return $stripped_data;
}

?>
dhgouveia at hotmail dot com 10-Oct-2011 04:09
this is just for strip the inside tags

<?php
$allow = '<p><ul><li><b><strong>';

$str = '<p style="text-align:center">Paragraph</p><strong>Bold</strong><br/><span style="color:red">Red</span><h1>Header</h1>';

$result = strip_tags($str,$allow);
$result = clean_inside_tags($result,$allow);

echo '<textarea>'.$result.'</textarea>';

//Clean the inside of the tags
function clean_inside_tags($txt,$tags){

    preg_match_all("/<([^>]+)>/i",$tags,$allTags,PREG_PATTERN_ORDER);

    foreach ($allTags[1] as $tag){
        $txt = preg_replace("/<".$tag."[^>]*>/i","<".$tag.">",$txt);
    }

    return $txt;
}

?>
Anonymous 16-Jun-2011 01:12
If you want to strip ANSI escape color codes.
<?php
function strip_ansi($string) {
  return preg_replace('/\e\[[;?0-9]*[0-9A-Za-z]/', '', $string);
}
?>
aleksey at favor dot com dot ua 24-Feb-2011 01:06
strip_tags destroys the whole HTML behind the tags with invalid attributes. Like <img src="/images/image.jpg""> (look, there is an odd quote before >.)

So I wrote function which fixes unsafe attributes and replaces odd " and ' quotes with &quot; and &#39;.

<?php
function fix_unsafe_attributes($s) {
  $out = false;
  while (preg_match('/<([A-Za-z])[^>]*?>/', $s, $i, PREG_OFFSET_CAPTURE)) { // find where the tag begins
    $i = $i[1][1]+1;
    $out.= substr($s, 0, $i);
    $s = substr($s, $i);

    // scan attributes and find odd " and '
    while (((($i1 = strpos($s, '"')) || 1) && (($i2 = strpos($s, '\'')) || 1)) && ($i1 !== false || $i2 !== false) &&
           (($i = (int)(($i1 !== false) && ($i2 !== false) ? ($i1 < $i2 ? $i1 : $i2) : ($i1 == false ? $i2 : $i1))) !== false) &&
           ((($c = strpos($s, '>')) === false) || ($i < $c))) {

      $c = $s{$i};
      if (($i < 1) || ($s{$i-1} != '=')) {
        $out.= substr($s, 0, $i).($s{$i} == '"' ? '&quot;' : '&#39;'); // replace odd " and '
        $s = substr($s, $i+1);
      }else {
        $i++;
        $out.= substr($s, 0, $i);
        $s = substr($s, $i);

        if (($i = strpos($s, $c)) !== false) {
          $i++;
          $out.= substr($s, 0, $i);
          $s = substr($s, $i);
        }
      }
    }
  }
  return $out.$s;
}
?>

Maybe this function can be rewritten with simple regular expression but I have no luck to make it quickly.
Abdul Al-hasany 02-Feb-2011 11:44
As noted in the documentation strip_tags would strip php and comments tags even if they are add to $allowable_tags.

Here is a little workaround for this issue:
<?php
function stripTags($text, $tags)
{

  // replace php and comments tags so they do not get stripped
  $text = preg_replace("@<\?@", "#?#", $text);
  $text = preg_replace("@<!--@", "#!--#", $text);

  // strip tags normally
  $text = strip_tags($text, $tags);

  // return php and comments tags to their origial form
  $text = preg_replace("@#\?#@", "<?", $text);
  $text = preg_replace("@#!--#@", "<!--", $text);

  return $text;
}
?>

The function would replace the tags to hashes so strip_tags would not identify them as normal tags, and then when strip_tags does its job the tags are modified back to their original form.
Montana 31-Jan-2011 10:46
IMO, the function should allow you to remove any tag that you specify.  The structure could be something like this:

strip_tags($string,$allow_or_remove_listed,$list)

As an example:

<?php
$str = "<p><strong>This is a string.</strong> <a href="http://www.example.com/">Some Random Website</a>";
$str = strip_tags($str,"remove","<strong>");
echo $str;
?>

would remove the <strong> tag.
frank at silverwolf media ddoott comm 19-Nov-2010 02:30
Note that strip_tags may stumble when it encounters two consecutive quotes. Regardless of whether that's a bug or a feature (different PHP versions seem to behave differently) here's a workaround:

<?php
  $wtf = '
    <p>First line</p>
    <a href=\"foo">bar</a>
    <p>Second line</p>
    <a href=\"foo\"">bar</a>
    <p>Third line</p>
  ';
  echo 'Raw: ' . $wtf . "\n";
  echo 'strip_tags(): ' . strip_tags ($wtf);
  echo 'Regexp: ' . preg_replace ('/<[^>]*>/', '', $wtf);
?>

Raw output:

  <p>First line</p>
  <a href=\"foo">bar</a>
  <p>Second line</p>
  <a href=\"foo\"">bar</a>
  <p>Third line</p>

strip_tags() output:

  First line
  bar
  Third line

preg_replace() output:

  First line
  bar
  Second line
  bar
  Third line
tom at cowin dot us 27-Aug-2010 07:04
With most web based user input of more than a line of text, it seems I get 90% 'paste from Word'. I've developed this fn over time to try to strip all of this cruft out. A few things I do here are application specific, but if it helps you - great, if you can improve on it or have a better way - please - post it...

<?php

    function strip_word_html($text, $allowed_tags = '<b><i><sup><sub><em><strong><u><br>')
    {
        mb_regex_encoding('UTF-8');
        //replace MS special characters first
        $search = array('/&lsquo;/u', '/&rsquo;/u', '/&ldquo;/u', '/&rdquo;/u', '/&mdash;/u');
        $replace = array('\'', '\'', '"', '"', '-');
        $text = preg_replace($search, $replace, $text);
        //make sure _all_ html entities are converted to the plain ascii equivalents - it appears
        //in some MS headers, some html entities are encoded and some aren't
        $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
        //try to strip out any C style comments first, since these, embedded in html comments, seem to
        //prevent strip_tags from removing html comments (MS Word introduced combination)
        if(mb_stripos($text, '/*') !== FALSE){
            $text = mb_eregi_replace('#/\*.*?\*/#s', '', $text, 'm');
        }
        //introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be
        //'<1' becomes '< 1'(note: somewhat application specific)
        $text = preg_replace(array('/<([0-9]+)/'), array('< $1'), $text);
        $text = strip_tags($text, $allowed_tags);
        //eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one
        $text = preg_replace(array('/^\s\s+/', '/\s\s+$/', '/\s\s+/u'), array('', '', ' '), $text);
        //strip out inline css and simplify style tags
        $search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu', '#<(em|i)[^>]*>(.*?)</(em|i)>#isu', '#<u[^>]*>(.*?)</u>#isu');
        $replace = array('<b>$2</b>', '<i>$2</i>', '<u>$1</u>');
        $text = preg_replace($search, $replace, $text);
        //on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears
        //that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains
        //some MS Style Definitions - this last bit gets rid of any leftover comments */
        $num_matches = preg_match_all("/\<!--/u", $text, $matches);
        if($num_matches){
              $text = preg_replace('/\<!--(.)*--\>/isu', '', $text);
        }
        return $text;
    }
?>
cyex at hotmail dot com 08-Jul-2010 03:40
I thought someone else might find this useful... a simple way to strip BBCode:

<?php

$bbcode_str = "Here is some [b]bold text[/b] and some [color=#FF0000]red text[/color]!";

$plain_text = strip_tags(str_replace(array('[',']'), array('<','>'), $bbcode_str));

//Outputs: Here is some bold text, and some red text!

?>
php at wizap dot com 16-Apr-2010 04:58
This could be overkill but this strips all HTML tags and gives you the option to preserve the ones you define. It also takes into account tags like <script> removing all the javascript, too! You can also strip out all the content between any tag that has an opening and closing tag, like <table>, <object>, etc.

<?php
    function remove_HTML($s , $keep = '' , $expand = 'script|style|noframes|select|option'){
        /**///prep the string
        $s = ' ' . $s;

        /**///initialize keep tag logic
        if(strlen($keep) > 0){
            $k = explode('|',$keep);
            for($i=0;$i<count($k);$i++){
                $s = str_replace('<' . $k[$i],'[{(' . $k[$i],$s);
                $s = str_replace('</' . $k[$i],'[{(/' . $k[$i],$s);
            }
        }

        //begin removal
        /**///remove comment blocks
        while(stripos($s,'<!--') > 0){
            $pos[1] = stripos($s,'<!--');
            $pos[2] = stripos($s,'-->', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 3;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,'',$s);
        }

        /**///remove tags with content between them
        if(strlen($expand) > 0){
            $e = explode('|',$expand);
            for($i=0;$i<count($e);$i++){
                while(stripos($s,'<' . $e[$i]) > 0){
                    $len[1] = strlen('<' . $e[$i]);
                    $pos[1] = stripos($s,'<' . $e[$i]);
                    $pos[2] = stripos($s,$e[$i] . '>', $pos[1] + $len[1]);
                    $len[2] = $pos[2] - $pos[1] + $len[1];
                    $x = substr($s,$pos[1],$len[2]);
                    $s = str_replace($x,'',$s);
                }
            }
        }

        /**///remove remaining tags
        while(stripos($s,'<') > 0){
            $pos[1] = stripos($s,'<');
            $pos[2] = stripos($s,'>', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 1;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,'',$s);
        }

        /**///finalize keep tag
        for($i=0;$i<count($k);$i++){
            $s = str_replace('[{(' . $k[$i],'<' . $k[$i],$s);
            $s = str_replace('[{(/' . $k[$i],'</' . $k[$i],$s);
        }

        return trim($s);
    }
?>
LWC 01-Mar-2010 07:07
Here is support for stripping content for the reverse strip_tags function:

<?php
function strip_only($str, $tags, $stripContent = false) {
    $content = '';
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) {
        if ($stripContent)
             $content = '(.+</'.$tag.'[^>]*>|)';
         $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
    }
    return $str;
}

$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?>

Note this function always assumed no two tags start the same way (e.g. <bla> and <blas>) and therefore censors blas along with bla.
Steve 16-Sep-2009 10:03
Here is a function like strip_tags, only it removes only the tags (with attributes) specified:

<?php
function strip_only($str, $tags) {
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
    return $str;
}

$str = '<p style="text-align:center">Paragraph</p><strong>Bold</strong><br/><span style="color:red">Red</span><h1>Header</h1>';

echo strip_only($str, array('p', 'h1'));
echo strip_only($str, '<p><h1>');
?>

Both return:
Paragraph<strong>Bold</strong><br/><span style="color:red">Red</span>Header

Hope this helps somebody else
roly426 at gmail dot com 09-Jun-2009 03:41
To check for broken tags an easier approach would be to use xml_parse(). You can also get a descriptive error with xml_get_error_code().
magus at otserv dot com dot br 07-Jun-2009 12:41
Here's a function that verify if in a string have broken HTML tags, returning true if do. Useful for previning broken tags to affect the page.

<?php
# Example usage: broken_tags("<b>This is a string</u>") returns TRUE, broken_tags("<b>This is a string</b>") returns FALSE.
function broken_tags($str)
{
    preg_match_all("/(<\w+)(?:.){0,}?>/", $str, $v1);
    preg_match_all("/<\/\w+>/", $str, $v2);
    $open = array_map('strtolower', $v1[1]);
    $closed = array_map('strtolower', $v2[0]);
    foreach ($open as $tag)
    {
        $end_tag = preg_replace("/<(.*)/", "</$1>", $tag);
        if (!in_array($end_tag, $closed)) return true;
        unset($closed[array_search($end_tag, $closed)]);
    }
    return false;
}
?>
brettz9 AAT yah 05-Apr-2009 08:10
Works on shortened <?...?> syntax and thus also will remove XML processing instructions.
hongong at webafrica dot org dot za 26-Mar-2009 12:52
An easy way to clean a string of all CDATA encapsulation.

<?php
function strip_cdata($string)
{
    preg_match_all('/<!\[cdata\[(.*?)\]\]>/is', $string, $matches);
    return str_replace($matches[0], $matches[1], $string);
}
?>

Example: echo strip_cdata('<![CDATA[Text]]>');
Returns: Text
nathan@8 08-Mar-2009 10:55
Improperly formatted javascript being add to tags and the limit of 15 instences of recursion before memory allocation runs out are some of the concerns involved in coding.  Here is the code that I created to leave tags intact but strip scripting from only inside the tags...

<?php
function strip_javascript($filter){

    // realign javascript href to onclick
    $filter = preg_replace("/href=(['\"]).*?javascript:(.*)?
\\1/i", "onclick=' $2 '", $filter);

    //remove javascript from tags
    while( preg_match("/<(.*)?javascript.*?\(.*?((?>[^()]+)
|(?R)).*?\)?\)(.*)?>/i", $filter))
        $filter = preg_replace("/<(.*)?javascript.*?\(.*?((?>
[^()]+)|(?R)).*?\)?\)(.*)?>/i", "<$1$3$4$5>", $filter);

    // dump expressions from contibuted content
    if(0) $filter = preg_replace("/:expression\(.*?((?>[^
(.*?)]+)|(?R)).*?\)\)/i", "", $filter);

    while( preg_match("/<(.*)?:expr.*?\(.*?((?>[^()]+)|(?
R)).*?\)?\)(.*)?>/i", $filter))
        $filter = preg_replace("/<(.*)?:expr.*?\(.*?((?>[^()]
+)|(?R)).*?\)?\)(.*)?>/i", "<$1$3$4$5>", $filter);

    // remove all on* events
    while( preg_match("/<(.*)?\s?on.+?=?\s?.+?(['\"]).*?\\2
\s?(.*)?>/i", $filter) )
       $filter = preg_replace("/<(.*)?\s?on.+?=?\s?.+?
(['\"]).*?\\2\s?(.*)?>/i", "<$1$3>", $filter);

    return $filter;
}
?>

As you can see this does not clean up correctly... it does
however remove dangerous stuff...

<a href=javascript: { {({}{}()())}alert('xss') ) ) }>

<div onload..;,;..'alert(\"xss_attack\");'>

<a href='javascript:{ alert(\"xss_attack\"); otherxss();}'
 onclick= 'alert(\"xss_attack\");' onhover='alert
(\"xss_attack\");' onmouseout=alert(\"xss_attack\")
class='thisclass'> link</a>

style='width:expression(alert(\"xss_attack\"));'

This can be completed before using strip_tags().
kai at froghh dot de 06-Mar-2009 08:45
a function that decides if < is a start of a tag or a lower than / lower than + equal:

<?php
function lt_replace($str){
    return preg_replace("/<([^[:alpha:]])/", '&lt;\\1', $str);
}
?>

It's to be used before strip_slashes.
mehul dot g12 at gmail dot com 03-Mar-2009 03:22
Strip tags doesn't work fine if we have '<' symbol in the string followed immediately by any letter. but it doed work fine if there is a space after '<' symbol. e.g.

<?php
strip_tags('<p>1<4</p>');  //won't work fine
strip_tags('<p>1 < 4</p>');  //will work fine
?>

to solve this problem, I used a simple logic. This code will replace '<' by html char, if it not a part of html tag.

My version of strip_tags is as follow:

<?php
function my_strip_tags($str) {
    $strs=explode('<',$str);
    $res=$strs[0];
    for($i=1;$i<count($strs);$i++)
    {
        if(!strpos($strs[$i],'>'))
            $res = $res.'&lt;'.$strs[$i];
        else
            $res = $res.'<'.$strs[$i];
    }
    return strip_tags($res);
}
?>
CEO at CarPool2Camp dot org 17-Feb-2009 11:10
Note the different outputs from different versions of the same tag:

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br>');
var_dump($new);  // OUTPUTS string(21) "<br>EachNew<br />Line"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br/>');
var_dump($new); // OUTPUTS string(16) "Each<br/>NewLine"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br />');
var_dump($new); // OUTPUTS string(11) "EachNewLine"
?>
Leendert W 26-Jan-2009 02:51
Maybe also a usefull function for someone.

<?php
function removeUnsafeAttributesAndGivenTags($input, $validTags = '')
{
    $regex = '#\s*<(/?\w+)\s+(?:on\w+\s*=\s*(["\'\s])?.+?
\(\1?.+?\1?\);?\1?|style=["\'].+?["\'])\s*>#is';
    return preg_replace($regex, '<${1}>',strip_tags($input, $validTags));
}
?>
phzzyzhou at gmail dot com 17-Jan-2009 02:01
strip_tags will strip '<' and the string behind, like this

<?php
$str = <<<EOF
123 < 456
<a>link</a>
bbb
EOF;

echo strip_tags($str);
?>

will output:
123

---------------------------------
this function will repiar this

<?php
function will_strip_tags($str) {
    do {
        $count = 0;
        $str = preg_replace('/(<)([^>]*?<)/' , '&lt;$2' , $str , -1 , $count);
    } while ($count > 0);
    $str = strip_tags($str);
    $str = str_replace('>' , '&gt;' , $str);
    return $str;
}

echo will_strip_tags($str);
?>

will output:
123 &lt; 456
link
bbb
tleblan at pricegrabber dot com 13-Jan-2009 07:03
I think it is worth mentioning that if some tags are allowed using the second parameter, this function does not allow to strip attributes within the allowed tags and hence should not be used against XSS vulnerabilities.

One can still execute javascript by 2 means:
- by inserting attributes that typically accept javascript
  >> onClick="alert('XSS');"
- by using styles
  >> style="width:expression(alert('XSS'));" (works on IE7 and probably other versions)
mariusz.tarnaski at wp dot pl 12-Nov-2008 08:05
Hi. I made a function that removes the HTML tags along with their contents:

Function:
<?php
function strip_tags_content($text, $tags = '', $invert = FALSE) {

  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
  $tags = array_unique($tags[1]);

  if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE) {
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    }
    else {
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
    }
  }
  elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
  }
  return $text;
}
?>

Sample text:
$text = '<b>sample</b> text with <div>tags</div>';

Result for strip_tags($text):
sample text with tags

Result for strip_tags_content($text):
 text with

Result for strip_tags_content($text, '<b>'):
<b>sample</b> text with

Result for strip_tags_content($text, '<b>', TRUE);
 text with <div>tags</div>

I hope that someone is useful :)
lucky760 at VideoSift dot com 20-Oct-2008 10:21
It's come to my attention that PHP's strip_tags has been doing something funky to some video embed codes that our members submit. I'm not sure the exact situation, but whenever there is a <param> tag that is very long, strip_tags() will completely remove the tag even though it's specified as an allowable tag.

Here's an example of the existing problem:
<?php
// a single very long <param> tag
$html =<<<EOF
<param name="flashVars" value="skin=http%3A//cdn-i.dmdentertainm
...[snip]...
vie%20of%20All-Time"/>
EOF;

echo strip_tags($html, '<param>');
// this outputs an empty string
?>

This is the function I built to fix and extend the functionality of strip_tags(). The args are:
- $i_html - the HTML string to be parsed
- $i_allowedtags - an array of allowed tag names
- $i_trimtext - whether or not to strip all text outside of the allowed tags

<?php

function real_strip_tags($i_html, $i_allowedtags = array(), $i_trimtext = FALSE) {
  if (!is_array($i_allowedtags))
    $i_allowedtags = !empty($i_allowedtags) ? array($i_allowedtags) : array();
  $tags = implode('|', $i_allowedtags);

  if (empty($tags))
    $tags = '[a-z]+';

  preg_match_all('@</?\s*(' . $tags . ')(\s+[a-z_]+=(\'[^\']+\'|"[^"]+"))*\s*/?>@i', $i_html, $matches);

  $full_tags = $matches[0];
  $tag_names = $matches[1];

  foreach ($full_tags as $i => $full_tag) {
    if (!in_array($tag_names[$i], $i_allowedtags))
      if ($i_trimtext)
        unset($full_tags[$i]);
      else
        $i_html = str_replace($full_tag, '', $i_html);
  }

  return $i_trimtext ? implode('', $full_tags) : $i_html;
}
?>

And here's an example with the a block of full video embed code with <object><embed><param> and some extraneous HTML:

<?php
$html =<<<EOF
<em><div><object type="application/x-shock
...[snip]...
me.html">Wal-Mart Makes The Worst Movie of All-Time</a> -- powered by whatever</div></em>
EOF;

$good_html = real_strip_tags($html, array('object', 'embed', 'param'), TRUE);

?>

Now $good_html contains only the specified tags and none of the "powered by" type text. I hope someone finds this as useful as I needed it to be. :)
southsentry at yahoo dot com 25-Sep-2008 09:15
I was looking for a simple way to ban html from review posts, and the like. I have seen a few classes to do it. This line, while it doesn't strip the post, effectively blocks people from posting html in review and other forms.

<?php
if (strlen(strip_tags($review)) < strlen($review)) {
    return false;
}
?>

If you want to further get by the tricksters that use & for html links, include this:

<?php
if (strlen(strip_tags($review)) < strlen($review)) {
        return false;
} elseif ( strpos($review, "&") !== false) {
        return 5;
}
?>

I hope this helps someone out!
Liam Morland 23-Aug-2008 05:58
Here is a suggestion for getting rid of attributes: After you run your HTML through strip_tags(), use the DOM interface to parse the HTML. Recursively walk through the DOM tree and remove any unwanted attributes. Serialize the DOM back to the HTML string.

Don't make the default permit mistake: Make a list of the attributes you want to ALLOW and remove any others, rather than removing a specific list, which may be missing something important.
Kalle Sommer Nielsen 30-Mar-2008 02:05
This adds alot of missing javascript events on the strip_tags_attributes() function from below entries.

Props to MSDN for lots of them ;)

<?php
function strip_tags_attributes($sSource, $aAllowedTags = array(), $aDisabledAttributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'))
    {
        if (empty($aDisabledAttributes)) return strip_tags($sSource, implode('', $aAllowedTags));

        return preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $aDisabledAttributes) . ")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($sSource, implode('', $aAllowedTags)));
    }
?>
bstrick at gmail dot com 15-Jan-2008 09:52
This will strip all PHP and HTML out of a file.  Leaves only plain txt.

<?php
// Open the search file
$file = fopen($filename, 'r');

// Get rid of all PHP code.
$search = array('/<\?((?!\?>).)*\?>/s');

$text = fread($file, filesize($filename));

$new = strip_tags(preg_replace($search, '', $text));

echo $new;

fclose($file);
?>

- Strick
David 05-Nov-2006 11:29
<?php

    /**
     * strip_selected_tags ( string str [, string strip_tags[, strip_content flag]] )
     * ---------------------------------------------------------------------
     * Like strip_tags() but inverse; the strip_tags tags will be stripped, not kept.
     * strip_tags: string with tags to strip, ex: "<a><p><quote>" etc.
     * strip_content flag: TRUE will also strip everything between open and closed tag
     */
    public function strip_selected_tags($str, $tags = "", $stripContent = false)
    {
        preg_match_all("/<([^>]+)>/i",$tags,$allTags,PREG_PATTERN_ORDER);
        foreach ($allTags[1] as $tag){
            if ($stripContent) {
                $str = preg_replace("/<".$tag."[^>]*>.*<\/".$tag.">/iU","",$str);
            }
            $str = preg_replace("/<\/?".$tag."[^>]*>/iU","",$str);
        }
        return $str;
    }

?>
jausions at php dot net 18-Sep-2006 11:57
To sanitize any user input, you should also consider PEAR's HTML_Safe package.

http://pear.php.net/package/HTML_Safe
admin at automapit dot com 09-Aug-2006 10:01
<?php
function html2txt($document){
$search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
               '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
               '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
               '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments including CDATA
);
$text = preg_replace($search, '', $document);
return $text;
}
?>

This function turns HTML into text... strips tags, comments spanning multiple lines including CDATA, and anything else that gets in it's way.

It's a frankenstein function I made from bits picked up on my travels through the web, thanks to the many who have unwittingly contributed!
JeremysFilms.com 07-Apr-2006 01:57
A simple little function for blocking tags by replacing the '<' and '>' characters with their HTML entities.  Good for simple posting systems that you don't want to have a chance of stripping non-HTML tags, or just want everything to show literally without any security issues:

<?php

function block_tags($string){
    $replaced_string = str_ireplace('<','&lt',$string);
    $replaced_string = str_ireplace('>','&gt',$replaced_string);
    return $replaced_string;
}

echo block_tags('<b>HEY</b>'); //Returns &ltb&gtHEY&lt/b&gt

?>
cesar at nixar dot org 07-Mar-2006 11:44
Here is a recursive function for strip_tags like the one showed in the stripslashes manual page.

<?php
function strip_tags_deep($value)
{
  return is_array($value) ?
    array_map('strip_tags_deep', $value) :
    strip_tags($value);
}

// Example
$array = array('<b>Foo</b>', '<i>Bar</i>', array('<b>Foo</b>', '<i>Bar</i>'));
$array = strip_tags_deep($array);

// Output
print_r($array);
?>
salavert at~ akelos 13-Feb-2006 02:21
<?php
       /**
    * Works like PHP function strip_tags, but it only removes selected tags.
    * Example:
    *     strip_selected_tags('<b>Person:</b> <strong>Salavert</strong>', 'strong') => <b>Person:</b> Salavert
    */

    function strip_selected_tags($text, $tags = array())
    {
        $args = func_get_args();
        $text = array_shift($args);
        $tags = func_num_args() > 2 ? array_diff($args,array($text))  : (array)$tags;
        foreach ($tags as $tag){
            if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
                $text = str_replace($found[0],$found[1],$text);
          }
        }

        return $text;
    }

?>

Hope you find it useful,

Jose Salavert
webmaster at tmproductionz dot com 01-Feb-2006 07:28
<?php

function remove_tag ( $tag , $data ) {

    while ( eregi ( "<" . $tag , $data ) ) {

        $it    = stripos ( $data , "<" . $tag   ) ;

        $it2   = stripos ( $data , "</" . $tag . ">" ) + strlen ( $tag ) + 3 ;

        $temp  = substr ( $data , 0    , $it  ) ;

        $temp2 = substr ( $data , $it2 , strlen ( $data ) ) ;

        $data = $temp . $temp2 ;

    }

    return $data ;

}

?>

this code will remove only and all of the specified tag from a given haystack.
10-Aug-2005 12:08
<?php
/**removes specifed tags from the text where each tag requires a
     *closing tag and if the later
     *is not found then everything after will be removed
     *typical usage:
     *some html text, array('script','body','html') - all lower case*/
    public static function removeTags($text,$tags_array){
        $length = strlen($text);
        $pos =0;
        $tags_array = $array_flip($tags_array);
        while ($pos < $length && ($pos = strpos($text,'<',$pos)) !== false){
            $dlm_pos = strpos($text,' ',$pos);
            $dlm2_pos = strpos($text,'>',$pos);
            if ($dlm_pos > $dlm2_pos)$dlm_pos=$dlm2_pos;
            $which_tag = strtolower(substr($text,$pos+1,$dlm_pos-($pos+1)));
            $tag_length = strlen($srch_tag);
            if (!isset($tags_array[$which_tag])){
                //if no tag matches found
                ++$pos;
                continue;
            }
            //find the end
            $sec_tag = '</'.$which_tag.'>';
            $sec_pos = stripos($text,$sec_tag,$pos+$tag_length);
            //remove everything after if end of the tag not found
            if ($sec_pos === false) $sec_pos = $length-strlen($sec_tag);
            $rmv_length = $sec_pos-$pos+strlen($sec_tag);
            $text = substr_replace($text,'',$pos,$rmv_length);
            //update length
            $length = $length - $rmv_length;
            $pos++;
        }
        return $text;
    }
?>
anonymous 27-May-2005 12:45
Someone can use attributes like CSS in the tags.
Example, you strip all tagw except <b> then a user can still do <b style="color: red; font-size: 45pt">Hello</b> which might be undesired.

Maybe BB Code would be something.
eric at direnetworks dot com 20-Dec-2004 06:36
the strip_tags() function in both php 4.3.8 and 5.0.2 (probably many more, but these are the only 2 versions I tested with) have a max tag length of 1024.  If you're trying to process a tag over this limit, strip_tags will not return that line (as if it were an illegal tag).   I noticed this problem while trying to parse a paypal encrypted link button (<input type="hidden" name="encrypted" value="encryptedtext">, with <input> as an allowed tag), which is 2702 characters long.  I can't really think of any workaround for this other than parsing each tag to figure out the length, then only sending it to strip_tags() if its under 1024, but at that point, I might as well be stripping the tags myself.
@dada 29-Sep-2004 05:41
if you  only want to have the text within the tags, you can use this function:

<?php
function showtextintags($text)

{

$text = preg_replace("/(\<script)(.*?)(script>)/si", "dada", "$text");
$text = strip_tags($text);
$text = str_replace("<!--", "&lt;!--", $text);
$text = preg_replace("/(\<)(.*?)(--\>)/mi", "".nl2br("\\2")."", $text);

return $text;

}
?>

it will show all the text without tags and (!!!) without javascripts
Anonymous User 22-Aug-2004 09:24
Be aware that tags constitute visual whitespace, so stripping may leave the resulting text looking misjoined.

For example,

"<strong>This is a bit of text</strong><p />Followed by this bit"

are seperable paragraphs on a visual plane, but if simply stripped of tags will result in

"This is a bit of textFollowed by this bit"

which may not be what you want, e.g. if you are creating an excerpt for an RSS description field.

The workaround is to force whitespace prior to stripping, using something like this:

<?php
      $text = getTheText();
      $text = preg_replace('/</',' <',$text);
      $text = preg_replace('/>/','> ',$text);
      $desc = html_entity_decode(strip_tags($text));
      $desc = preg_replace('/[\n\r\t]/',' ',$desc);
      $desc = preg_replace('/  /',' ',$desc);
?>
Isaac Schlueter php at isaacschlueter dot com 15-Aug-2004 11:16
I am creating a rendering plugin for a CMS system (http://b2evolution.net) that wraps certain bits of text in acronym tags.  The problem is that if you have something like this:
<a href="http://www.php.net" title="PHP is cool!">PHP</a>

then the plugin will mangle it into:

<a href="http://www.<acronym title="PHP: Hypertext Processor">php</acronym>.net" title="<acronym title="PHP: Hypertext Processor">PHP</acronym> is cool!>PHP</a>

This function will strip out tags that occur within other tags.  Not super-useful in tons of situations, but it was an interesting puzzle.  I had started out using preg_replace, but it got riduculously complicated when there were linebreaks and multiple instances in the same tag.

The CMS does its XHTML validation before the content gets to the plugin, so we can be pretty sure that the content is well-formed, except for the tags inside of other tags.

<?php
if( !function_exists( 'antiTagInTag' ) )
{
    // $content is the string to be anti-tagintagged, and $format sets the format of the internals.
    function antiTagInTag( $content = '', $format = 'htmlhead' )
    {
        if( !function_exists( 'format_to_output' ) )
        {    // Use the external function if it exists, or fall back on just strip_tags.
            function format_to_output($content, $format)
            {
                return strip_tags($content);
            }
        }
        $contentwalker = 0;
        $length = strlen( $content );
        $tagend = -1;
        for( $tagstart = strpos( $content, '<', $tagend + 1 ) ; $tagstart !== false && $tagstart < strlen( $content ); $tagstart = strpos( $content, '<', $tagend ) )
        {
            // got the start of a tag.  Now find the proper end!
            $walker = $tagstart + 1;
            $open = 1;
            while( $open != 0 && $walker < strlen( $content ) )
            {
                $nextopen = strpos( $content, '<', $walker );
                $nextclose = strpos( $content, '>', $walker );
                if( $nextclose === false )
                {    // ERROR! Open waka without close waka!
                    // echo '<code>Error in antiTagInTag - malformed tag!</code> ';
                    return $content;
                }
                if( $nextopen === false || $nextopen > $nextclose )
                { // No more opens, but there was a close; or, a close happens before the next open.
                    // walker goes to the close+1, and open decrements
                    $open --;
                    $walker = $nextclose + 1;
                }
                elseif( $nextopen < $nextclose )
                { // an open before the next close
                    $open ++;
                    $walker = $nextopen + 1;
                }
            }
            $tagend = $walker;
            if( $tagend > strlen( $content ) )
                $tagend = strlen( $content );
            else
            {
                $tagend --;
                $tagstart ++;
            }
            $tag = substr( $content, $tagstart, $tagend - $tagstart );
            $tags[] = '<' . $tag . '>';
            $newtag = format_to_output( $tag, $format );
            $newtags[] = '<' . $newtag . '>';
            $newtag = format_to_output( $tag, $format );
        }

        $content = str_replace($tags, $newtags, $content);
        return $content;
    }
}
?>
leathargy at hotmail dot com 26-Oct-2003 10:15
it seems we're all overlooking a few things:
1) if we replace "</ta</tableble>" by removing </table, we're not better off. try using a char-by-char comparison, and replaceing stuff with *s, because then this ex would become "</ta******ble>", which is not problemmatic; also, with a char by char approach, you can skip whitespace, and kill stuff like "< table>"... just make sure <&bkspTable> doesn't work...
2) no browser treats { as <.[as far as i know]
3) because of statement 2, we can do:

<?php
$remove=array("<?","<","?>",">");
$change=array("{[pre]}","{[","{/pre}","]}");
$repairSeek = array("{[pre]}", "</pre>","{[b]}","{[/b]}","{[br]}");
// and so forth...

$repairChange("<pre>","</pre>","<b>","<b>","<br>");
// and so forth...

$maltags=array("{[","]}");
$nontags=array("{","}");
$unclean=...;//get variable from somewhere...
$unclean=str_replace($remove,$change,$unclean);
$unclean=str_replace($repairSeek, $repairChange, $unclean);
$clean=str_replace($maltags, $nontags, $unclean);

////end example....
?>

4) we can further improve the above by using explode(for our ease):

<?php
function purifyText($unclean, $fixme)
{
$remove=array();
$remove=explode("\n",$fixit['remove']);
//... and so forth for each of the above arrays...
// or you could just pass the arrays..., or a giant string
//put above here...
return $clean
}//done
?>
dougal at gunters dot org 10-Sep-2003 01:03
strip_tags() appears to become nauseated at the site of a <!DOCTYPE> declaration (at least in PHP 4.3.1). You might want to do something like:

$html = str_replace('<!DOCTYPE','<DOCTYPE',$html);

before processing with strip_tags().
guy at datalink dot SPAMMENOT dot net dot au 14-Mar-2002 10:19
Strip tags will NOT remove HTML entities such as &nbsp;
chrisj at thecyberpunk dot com 18-Dec-2001 12:57
strip_tags has doesn't recognize that css within the style tags are not document text. To fix this do something similar to the following:

$htmlstring = preg_replace("'<style[^>]*>.*</style>'siU",'',$htmlstring);
strcspn
stripcslashes
Обработка строк


Удаляет экранирование символов, произведенное функцией addcslashes

strip_tags
stripos
Обработка строк
PHP Manual

stripcslashes

(PHP 4, PHP 5)

stripcslashes — Удаляет экранирование символов, произведенное функцией addcslashes()

Описание

string stripcslashes ( string $str )

Удаляет экранирующие обратные слэши. Распознает экранирование в стиле C (\n, \r ..., восьмеричное и шестнадцатиричное представление).

Список параметров

str

Строка, с которой нужно убрать экранирование.

Возвращаемые значения

Возвращает неэкранированную строку.

Смотрите также

  • addcslashes() - Экранирует cтроку слэшами в стиле языка C

User Contributed Notes

jsmneo at dreamworkstudio dot net 04-Jul-2008 07:53
you might want to do a double stripslashes to completely remove 3 consecutive slashes

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses($stripped);
would output:
'this is a string with three\ slashes'

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses(stripslashes($stripped));
would output:
'this is a string with three slashes'
uramihsayibok, gmail, com 17-May-2008 09:09
> /*QUOTE
> stripcslashes('He\xallo') == 'He'."\n".'llo'
> stripcslashes('H\xaello') == 'H'.chr(0xAE).'llo'
> */
>
> You Can Use
>
> stripcslashes('H\xa0ello') == 'H'.chr(0xA0).'ello'
Correct. But not what (I think) you were trying to show.

>
> as xa0 = xa = chr(xA)
Not so correct.

Does 9==90? No, because that added zero *after* the number means something.
It's when you add a zero *before* the number does it not affect the value.

I'd like to assume that was a typo, but with the Internet as it is, who knows...
> You Can Use
>
> stripcslashes('H\x0aello') == 'H'.chr(0x0A).'ello'
fix'd
kenny at tnsnurse dot com 07-May-2008 09:28
Well, if you're reading data imported from another product, like Microsoft(ughh), you may encounter slashes, etc.. in your data anyway. Our company uses Microsoft Dynamics and I have to read their Vendor tables. Apparently, Dynamics and SQL Server allow all kinds of garbage in their fields. I've even seen tic marks used in the data in the key fields.
spider853 at gmail dot com 27-Dec-2007 03:47
/*QUOTE
stripcslashes('He\xallo') == 'He'."\n".'llo'
stripcslashes('H\xaello') == 'H'.chr(0xAE).'llo'
*/

You Can Use

stripcslashes('H\xa0ello') == 'H'.chr(0xA0).'ello'

as xa0 = xa = chr(xA)
abodeman BLAH at yahoo dot com 14-Jul-2003 12:27
stripcslashes does not accept hexadecimal escape sequences of more than two digits, even though C does. This means that all of the following are true (in C the second and third examples would contain the characters '\x48e' and '\x323' respectively):

stripcslashes('H\x65llo') == 'Hello'
stripcslashes('\x48ello') == 'Hello'
stripcslashes('1\x323') == '123'

stripcslashes does accept hexadecimal escape sequences of only one digit, as long as the following digit is not a valid hexadecimal digit, so both of the following are true:

stripcslashes('He\xallo') == 'He'."\n".'llo'
stripcslashes('H\xaello') == 'H'.chr(0xAE).'llo'

The fact that stripcslashes is limited to two hexadecimal digits looks like a bug at first glance, but it can be a feature. You can, for example, do a simple str_replace(':', '\x3a', $str) to replace all colons in a string with '\x3a' without having to worry about whether or not the next character will be interpreted as a hexadecimal digit.

If this "bug" is ever fixed, there will be no way in PHP to escape the colon in the string 'a:b' with a hexadecimal representation, since the 'b' would be interpreted as the hexadecimal digit 11. The string 'a\x3ab' would be interpreted as 'a'.chr(0x3AB).
nospam at nowhere dot com 05-Nov-2002 03:57
if you allow users to submit fields with apostrophy's inside, what you should do is pass that string into "stripcslashes()" to remove any slashes that may be automatically added by whatever that is causing it. As usual, you should verify this for yourself by creating a form and output the raw data in plain text format to make sure you have it right. The reason why MySQL does seem to ignore this problem is because it takes the "\'" and treat it as "'".
strip_tags
stripos
Обработка строк


Возвращает позицию первого вхождения подстроки без учета регистра

stripcslashes
stripslashes
Обработка строк
PHP Manual

stripos

(PHP 5)

stripos — Возвращает позицию первого вхождения подстроки без учета регистра

Описание

int stripos ( string $haystack , string $needle [, int $offset = 0 ] )

Ищет позицию первого вхождения подстроки needle в строку haystack.

В отличие от strpos(), эта функция не учитывает регистр символов.

Список параметров

haystack

Строка, в которой производится поиск.

needle

Заметьте, что needle может содержать строку из одного или более символов.

Если needle не является строкой, он приводится к целому и трактуется как код символа.

offset

Если этот параметр указан, то поиск будет начат с указанного количества символов с начала строки. В отличии от strrpos() и strripos() данный параметр не может быть отрицательным.

Возвращаемые значения

Возвращает позицию, в которой находится искомая строка, относительно начала строки haystack (независимо от смещения (offset). Также обратите внимание на то, что позиция строки отсчитывается от 0, а не от 1.

Возвращает FALSE, если искомая строка не найдена.

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Пример использования stripos()

<?php
$findme    = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// Конечно, 'a' не входит в 'xyz'
if ($pos1 === false) {
    echo "Строка '$findme' не найдена в строке '$mystring1'";
}

// Заметьте, что используется ===.  Использование == не даст верного
// результата, так как 'a' в нулевой позиции.
if ($pos2 !== false) {
    echo "Нашел '$findme' в '$mystring2' в позиции $pos2";
}
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strpos() - Возвращает позицию первого вхождения подстроки
  • strrpos() - Возвращает позицию последнего вхождения подстроки в строке
  • strripos() - Возвращает позицию последнего вхождения подстроки без учета регистра
  • stristr() - Регистро-независимый вариант функции strstr
  • substr() - Возвращает подстроку
  • str_ireplace() - Регистро-независимый вариант функции str_replace

User Contributed Notes

emperorshishire at gmail dot com 24-Feb-2009 07:31
I found myself needing to find the first position of multiple needles in one haystack.  So I wrote this little function:

<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
    foreach($needles as $needle) {
        $found[$needle] = stripos($haystack, $needle, $offset);
    }
    return $found;
}

// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
   array(3) {
     ["fox"]=>
     int(16)
     ["dog"]=>
     int(40)
     ["."]=>
     int(43)
     ["duck"]=>
     bool(false)
   }
*/
?>
grf at post dot cz 20-Mar-2007 04:57
this would to work with any language, i hope.
tested on czech (eastern europe) lang.

<?php
/****************************************
*    SAFE HIGHLIGHT
****************************************/
/**
 * function finds and encase every string in a $needleArr array with
 * strings $shearLft (from the left side) and $shearRgt (guess from which
 * side).
 * already encased needles are IGNORED for any other step, so order
 * of needles in $needleArr is pretty important.
 *
 * function is searching needles in case-insensitive mode,
 * but case in the subject is saved.
 *
 * can you do it better? so, do it.
 *
 * @param array $needleArr array of needles
 * @param string $shearLft left shear
 * @param string $shearRgt right shear
 * @param string $subject subject
 * @param string $encoding encoding ('utf-8' is default)
 *
 * @author griffin
 */
function safeHighlight( $needleArr, $shearLft, $shearRgt, $subject, $encoding = 'utf-8')
{

    // encoding
    $e = $encoding;

    // oh, no needles
    if( !is_array( $needleArr))
        return $subject;

    // empty keys throw-off, only unique, reindex
    $nA = array_values(
            array_unique(
                array_diff( $needleArr, array(''))
            )
        );

    // needle count
    if( !($nC = count( $nA)))
        return $subject; // nothing to hl

    // shear length
    if( !(($rLL = mb_strlen( $rL = $shearLft, $e))
    + ($rRL = mb_strlen( $rR = $shearRgt, $e))))
        return $subject; // no shears

    // subject length
    if( !($sL = mb_strlen( $s = $subject, $e)))
        return null; // empty subject

    // subject in lowercase (we need to aviod
    // using mb_stripos due to PHP version)
    $sW = mb_strtolower( $s, $e);

    // masking ~ 0=not changed, 1=changed
    $m = str_repeat( '0', $sL);

    // loop for each needle
    for( $n=0; $n<$nC; $n++)
    {

        // needle string loWercase
        $nW = mb_strtolower( $nA[ $n], $e);

        $o = 0; // offset
        $nL = mb_strlen( $nW, $e); // needle length

        // search needle
        while( false !== ($p = mb_strpos( $sW, $nW, $o, $e)))
        {
            // oh hurrey, needle found on $p position

            // is founded needle already modified? (in full-length)
            for( $q=$p; $q<($p+$nL); $q++)
                if( $m[ $q])
                {
                    // ai, caramba. already modified, jump over
                    $o+= $nL;

                    // continue for while() loop - not for for() loop!
                    continue 2;
                }

            // explode subject and mask into three parts
            // partA|needle|partB
            $sE[0] = mb_substr( $s, 0, $p, $e);
            $sE[1] = mb_substr( $s, $p, $nL, $e);
            $sE[2] = mb_substr( $s, $p+$nL, $sL-$p-$nL, $e);

            // mask
            // partA|partB (needle not needed)
            $mE[0] = mb_substr( $m, 0, $p, $e);
            $mE[1] = mb_substr( $m, $p+$nL, $sL-$p-$nL, $e);

            // apply shears
            $sE[1] = $rL.$sE[1].$rR;

            // update sunject length
            $sL+= $rLL + $rRL;

            // update mask
            $m = $mE[0] . str_repeat( '1', $rLL + $nL + $rRL) . $mE[1];

            // implode into a subject
            $s = implode( $sE);

            // update lowercase subject
            $sW = mb_strtolower( $s, $e);

            // increase offset
            $o+= $rLL + $nL + $rRL;

            // end of string reached
            if( $o>=$sL)
                break;

        } // while()

    } // for( $n=0; $n<$nC; $n++)

    // oouu yeaaa, kick the subject out of the function
    return $s;

} // function safeHighlight()
/****************************************
*    END: SAFE HIGHLIGHT
****************************************/
?>
stripcslashes
stripslashes
Обработка строк


Удаляет экранирование символов

stripos
stristr
Обработка строк
PHP Manual

stripslashes

(PHP 4, PHP 5)

stripslashes — Удаляет экранирование символов

Описание

string stripslashes ( string $str )

Удаляет экранирующие символы.

Замечание:

Если включена директива magic_quotes_sybase, вместо обратных слэшей будут удаляться двойные одинарные кавычки.

Функцию stripslashes() можно использовать, например, если директива конфигурации magic_quotes_gpc имеет значение on (она была включена по умолчанию в версиях до PHP 5.4), и экранирование символов не требуется. Например, данные не вставляются в базу данных, а просто выводятся в браузер.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает строку с вырезанными обратными слэшами. (\' становится ' и т.п.) Двойные обратные слэши (\\) становятся одинарными (\).

Примеры

Пример #1 Пример использования stripslashes()

<?php
$str = "Ваc зовут O\'reilly?";

// выводит: Вас зовут O'reilly?
echo stripslashes($str);
?>

Замечание:

stripslashes() не рекурсивна. Если вы хотите применить ее к многомерному массиву, то вам необходимо использовать рекурсивную функцию.

Пример #2 Использование stripslashes() с массивом

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

// Пример
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);

// Вывод
print_r($array);
?>

Результат выполнения данного примера:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

Смотрите также

  • addslashes() - Экранирует строку с помощью слэшей
  • get_magic_quotes_gpc() - Получение текущего значения настройки конфигурации magic_quotes_gpc

User Contributed Notes

tarmo at goyf dot de 06-Mar-2012 02:58
When matching strings with approstrophes against the mysql database, my query kept failing while it worked fine when I copied the same query directly to perform the database query. After several hours I found that stripslashes() made the string longer and hence it wasn't "equal" for the query.

This code shows the behavior (copy into "test.php"). Replacing stripslashes worked for me.

<?php
echo '<h2>Post-Data</h2>';
var_dump($_POST);

$f1 = trim(filter_var(stripslashes($_POST[form]), FILTER_SANITIZE_STRING));
echo '<h2>stripslashes</h2>';
var_dump($f1);

$f2 = trim(str_replace("|","'",filter_var(str_replace("\'","|",$_POST[form]), FILTER_SANITIZE_STRING)));
echo '<h2>workaround</h2>';
var_dump($f2);

echo '<form action="test.php" method="post">
    <input type="text" name="form">
    <input type="submit">
    </form>';
?>

Entering "foo'bar" creates this output:
// Post-Data
// array(1) { ["form"]=> string(8) "foo\'bar" }
// stripslashes
// string(11) "foo'bar"
// workaround
// string(7) "foo'bar"
jeremysawesome 10-Dec-2010 12:39
I'm using this to clean the $_POST array:
<?php
array_walk_recursive($_POST, create_function('&$val', '$val = stripslashes($val);'));
?>
jeremycook0 at googlemail dot com 01-Aug-2010 08:04
Here's a way of stripping slashes in PHP 5.3 using a recursive closure:

<?php
  if (get_magic_quotes_gpc()) {
      $strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
          return is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
      };
      $_GET = array_map($strip_slashes_deep, $_GET);
      $_POST = array_map($strip_slashes_deep, $_POST);
      $_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
  }
?>

Note that the variable '$strip_slashes_deep' has to be passed to the closure by reference. I think that this is because at the time the closure is created the variable '$strip_slashes_deep' doesn't exist: the closure itself becomes the value of the variable. Passing by reference solves this issue. This closure could easily be adapted to use other methods of stripping slashes such as preg_replace().
hawkeye at conreports dot de 21-Jan-2010 05:01
Another way to strip slashes only if necessary, independent of magic_quotes_gpc by comparing the count of (possibly) escaped characters and original characters.

<?php
function smartstripslashes($str) {
  $cd1 = substr_count($str, "\"");
  $cd2 = substr_count($str, "\\\"");
  $cs1 = substr_count($str, "'");
  $cs2 = substr_count($str, "\\'");
  $tmp = strtr($str, array("\\\"" => "", "\\'" => ""));
  $cb1 = substr_count($tmp, "\\");
  $cb2 = substr_count($tmp, "\\\\");
  if ($cd1 == $cd2 && $cs1 == $cs2 && $cb1 == 2 * $cb2) {
    return strtr($str, array("\\\"" => "\"", "\\'" => "'", "\\\\" => "\\"));
  }
  return $str;
}
?>
eugene at ultimatecms dot co dot za 23-Nov-2009 05:03
This is a simple function to remove the slashes added by functions such as magic_quotes_gpc and mysql_escape_string etc.

<?php

function no_magic_quotes($query) {
        $data = explode("\\",$query);
        $cleaned = implode("",$data);
        return $cleaned;
}

// I'm using mysql_escape_string as a simple example, but this function would work for any escaped string.
$query = "It's amaizing! Who's to say this isn't a simple function?";
$badstring = mysql_escape_string($query);

echo '<b>Without funtion:</b> '.$badstring;
echo '<br><br>';
echo '<b>With function:</b> '.no_magic_quotes($badstring);

?>

Output:
Without funtion: It\'s amaizing! Who\'s to say this isn\'t a simple function?

With function: It's amaizing! Who's to say this isn't a simple function?
michal at roszka dot pl 31-Aug-2009 08:00
The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:

a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Let's have two simple scripts:

Script A:
<?php echo $_POST['example']; ?>

Script B:
<?php echo stripslashes($_POST['example']); ?>

Let's have four different configurations and corresponding output:

Case #1:

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = Off

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #2

 * magic_quotes_gpc = On
 * magic_quotes_sybase = Off

A: a backslash ( \\ ), a single-quote ( \' ), a double-quote ( \" ) and a null character ( \\0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Case #3

 * magic_quotes_gpc = On
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( '' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #4

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Conclusions:

1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);

<?php
function disable_magic_quotes_gpc()
{
    if (TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
    {
        $mqs = strtolower(ini_get('magic_quotes_sybase'));

        if (TRUE == empty($mqs) || 'off' == $mqs)
        {
            // we need to do stripslashes on $_GET, $_POST and $_COOKIE
        }
        else
        {
            // we need to do str_replace("''", "'", ...) on $_GET, $_POST, $_COOKIE
        }
    }
    // otherwise we do not need to do anything
}
?>

Important notes:

1) arrays need to be processed recursively;

2) both stripslashes and str_replace functions always return strings, so:

* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.

On the other hand you only need to process strings, so use the is_string function to check;

3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.

4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
JacobRas.nl 28-Jul-2009 05:41
Hi,

Here's an function that strips not only \', but also \\' and \\\' and so on (depending on $times). $text = the text that needs to be stripped, $times = how much backslashes should be stripped.

<?php

function stripslashes_deep ($text, $times) {

    $i = 0;

    // loop will execute $times times.
    while (strstr($text, '\\') && $i != $times) {

        $text= stripslashes($text);
        $i++;

    }

    return $text;

}

?>

Example: $text = \\'quote\\' . <?php stripslashes_deep($text, 2); ?> will return 'quote'.
Note: <?php stripslashes_deep($text, 3); ?> will also return 'quote'.
shredder at technodrome dot com 09-May-2009 03:50
Hi,

Here are recursive addslashes / stripslashes functions.
given a string - it will simply add / strip slashes
given an array - it will recursively add / strip slashes from the array and all of it subarrays.
if the value is not a string or array - it will remain unmodified!

<?php

function add_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return addslashes( $variable ) ;

    elseif ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = add_slashes_recursive( $value ) ;

    return $variable ;
}

function strip_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return stripslashes( $variable ) ;
    if ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = strip_slashes_recursive( $value ) ;

    return $variable ;
}

?>
dragon[dot]dionysius[at]gmail[dot]com 24-Mar-2009 08:07
I use this function in my class to stripslashes arrays including NULL-check:

<?php
    private function stripslashes_deep($value) {
        if(is_array($value)) {
            foreach($value as $k => $v) {
                $return[$k] = $this->stripslashes_deep($v);
            }
        } elseif(isset($value)) {
            $return = stripslashes($value);
        }
        return $return;
    }
?>
Tom Worster 23-Mar-2009 07:26
A replacement that should be safe on utf-8 strings.
<?php
  preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $s);
?>
o-zone at zerozone dot it 19-Mar-2009 03:53
If you need to remove all slashes from a string, here's a quick hack:

<?php
function stripallslashes($string) {
    while(strchr($string,'\\')) {
        $string = stripslashes($string);
    }
}
?>

Hope it's usefull , O-Zone
techdesk100 28-Apr-2008 07:58
Function which checks if $input has correct slashes,
otherwise adds slashes. For cases when you are not sure the input is not already addslashed.

    public function addslashes_once($input){
        //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
        $pattern = array("\\'", "\\\"", "\\\\", "\\0");
        $replace = array("", "", "", "");
        if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input))){
            return addslashes($input);
        }
        else{
            return $input;
        }
    }
Aditya P Bhatt (adityabhai at gmail dot com) 27-Mar-2008 10:03
Here is simple example code which you can use as a common function in your functions file:

<?php
function stripslashes_if_gpc_magic_quotes( $string ) {
    if(get_magic_quotes_gpc()) {
        return stripslashes($string);
    } else {
        return $string;
    }
}
?>
Evgeny 26-Feb-2008 07:52
extended version of stripslashes_deep. This allow to strip one also in the array_keys

    function stripslashes_deep($value) {
        if (is_array($value)) {
            if (count($value)>0) {
                $return = array_combine(array_map('stripslashes_deep', array_keys($value)),array_map('stripslashes_deep', array_values($value)));
            } else {
                $return = array_map('stripslashes_deep', $value);
            }
            return $return;
        } else {
            $return = stripslashes($value);
            return $return ;
        }
    }
tokyoahead 10-Jan-2008 09:39
I am using this here to clear data in a CMS against SQL injections and other mayhem. The flow is:

1. input into form
2. get from $_GET/$_POST
3. cleanup($data, true)
4. save to SQL
5. load from SQL
6. cleanup($data, false)
7. show in form for new edit or on the website

<?php
function cleanup($data, $write=false) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = cleanup_lvl2($value, $write);
        }
    } else {
        $data = cleanup_lvl2($data, $write);
    }
    return $data;
}

function cleanup_lvl2($data, $write=false) {
    if (isset($data)) { // preserve NULL
        if (get_magic_quotes_gpc()) {
            $data = stripslashes($data);
        }
        if ($write) {
            $data = mysql_real_escape_string($data);
        }
    }
    return $data;
}
?>
alex dot launi at gmail dot com 21-Dec-2007 07:16
kibby: I modified the stripslashes_deep() function so that I could use it on NULL values.

function stripslashes_deep($value)
{
    if(isset($value)) {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);
    }
    return $value;
}
lukas.skowronski at gmail dot com 20-Jun-2007 04:15
If You want to delete all slashes from any table try to use my function:

function no_slashes($array)
    {
        foreach($array as $key=>$value)
            {
                if(is_array($value))
                    {
                        $value=no_slashes($value);
                        $array_temp[$key]=$value;
                    }
                else
                    {
                        $array_temp[$key]=stripslashes($value);
                    }
            }
        return $array_temp;
    }
dragonfly at networkinsight dot net 11-Mar-2007 03:22
If you are having trouble with stripslashes() corrupting binary data, try using urlencode() and urldecode() instead.
JAB Creations 05-Mar-2007 08:49
When writing to a flatfile such as an HTML page you'll notice slashes being inserted. When you write to that page it's interesting how to apply stripslashes...

I replaced this line...
<?php fwrite($file, $_POST['textarea']); ?>

With...
<?php if (get_magic_quotes_gpc()) {fwrite ($file, stripslashes($_POST['textarea']));}?>

You have to directly apply stripslashes to $_POST, $_GET, $_REQUEST, and $_COOKIE.
gregory at nutt dot ca 22-Feb-2007 06:48
Here is code I use to clean the results from a MySQL query using the stripslashes function.

I do it by passing the sql result and the sql columns to the function strip_slashes_mysql_results.  This way, my data is already clean by the time I want to use it.

    function db_query($querystring, $array, $columns)
    {
      if (!$this->connect_to_mysql())
       return 0;

     $queryresult = mysql_query($querystring, $this->link)
        or die("Invalid query: " . mysql_error());

      if(mysql_num_rows($queryresult))
      {
          $columns = mysql_field_names ($queryresult);

          if($array)
          {
              while($row = mysql_fetch_row($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
          else
          {
              while($row = mysql_fetch_object($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
      }
      else
        return 0;
    }

    function strip_slashes_mysql_results($result, $columns)
    {
        foreach($columns as $column)
        {
              if($this->debug)
                  printp(sprintf("strip_slashes_mysql_results: %s",strip_slashes_mysql_results));
              $result->$column = stripslashes($result->$column);
        }
        return $result;
    }
Allen 06-Feb-2007 11:41
In response to Tim's solution, it is only good for one-dimensional array.  If the variables happened to be multi-dimensional arrays, we still have to use function like 'stripslashes_deep'.
stoic 02-Jan-2007 08:31
in response to crab dot crab at gmail dot com:

$value need not be passed by reference. The 'stripped' value is returned. The passed value is not altered.
Kibby 14-May-2006 01:41
Okay, if using stripslashes_deep, it will definitely replace any NULL to "".  This will affect to coding that depends isset().  Please provide a workaround based on recent note.
hauser dot j at gmail dot com 21-Feb-2006 02:13
Don't use stripslashes if you depend on the values NULL.

Apparently stripslashes converts NULL to string(0) ""

<?php
$a = null;
var_dump($a);

$b = stripslashes($a);
var_dump($b);
?>
Will output

NULL
string(0) ""
alf at mitose dot net 25-Oct-2005 05:09
Take care using stripslashes() if the text you want to insert in the database contain \n characters ! You'll see "n" instead of (not seeing) "\n".

It should be no problem for XML, but is still boring ...
10-Feb-2005 07:45
If you want to deal with slashes in double-byte encodings, such as shift_jis or big5, you may use this:

<?
function stripslashes2($string) {
    $string = str_replace("\\\"", "\"", $string);
    $string = str_replace("\\'", "'", $string);
    $string = str_replace("\\\\", "\\", $string);
    return $string;
}
?>
mattyblah at gmail dot com 10-Sep-2004 08:51
It should be of note that if you are stripping slashes to get rid of the slashes added by magic_quotes_gpc then it will also remove slashes from \. This may not seem that bad but if you have someone enter text such as 'testing\' with a slash at the end, this will cause an error if not corrected. It's best to strip the slashes, then add a slash to every single slash using $text = str_replace('\\', '\\\\', $text);
hash at samurai dot fm 30-Nov-2003 09:34
Might I warn readers that they should be vary careful with the use of stripslashes on Japanese text. The shift_jis character set includes a number of two-byte code charcters that contain the hex-value 0x5c (backslash) which will get stripped by this function thus garbling those characters.

What a nightmare!
stripos
stristr
Обработка строк


Регистро-независимый вариант функции strstr

stripslashes
strlen
Обработка строк
PHP Manual

stristr

(PHP 4, PHP 5)

stristr — Регистро-независимый вариант функции strstr()

Описание

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Возвращает всю строку haystack начиная с первого вхождения needle включительно.

Список параметров

haystack

Строка, в которой производится поиск

needle

Если needle не является строкой, он приводится к целому и трактуется как код символа.

before_needle

Если установлен в TRUE, stristr() возвращает часть строки haystack до первого вхождения needle (не включая needle).

needle и haystack обрабатываются без учета регистра.

Возвращаемые значения

Возвращает указанную подстроку. Если подстрока needle не найдена, возвращается FALSE.

Список изменений

Версия | Описание
5.3.0 | Добавлен необязательный параметр before_needle.
4.3.0 | stristr() теперь бинарно-безопасна.

Примеры

Пример #1 Пример использования stristr()

<?php
  $email = 'USER@EXAMPLE.com';
  echo stristr($email, 'e'); // выводит ER@EXAMPLE.com
  echo stristr($email, 'e', true); // Начиная с PHP 5.3.0, выводит US
?>

Пример #2 Проверка на вхождение строки

<?php
  $string = 'Hello World!';
  if(stristr($string, 'earth') === FALSE) {
    echo '"earth" не найдена в строке';
  }
// выводит: "earth" не найдена в строке
?>

Пример #3 Использование "нестроки" в поиске

<?php
  $string = 'APPLE';
  echo stristr($string, 97); // 97 = a в нижнем регистре
// выводит: APPLE
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strstr() - Находит первое вхождение подстроки
  • strrchr() - Находит последнее вхождение символа в строке
  • stripos() - Возвращает позицию первого вхождения подстроки без учета регистра
  • strpbrk() - Ищет в строке любой символ из заданного набора
  • preg_match() - Выполняет проверку на соответствие регулярному выражению

User Contributed Notes

greg at no_ggmac_reply dot com 13-Jan-2011 01:20
Beware the example given here:

if stristr($message,'viagra')
or stristr($message,'cialis')
)
{
die();
}

stristr does not search for words, it finds matching substrings.  So, for example, the check for 'cialis' will trigger on 'specialist'
jahforlove at gmail dot com 15-Oct-2010 10:58
Use it to emulate the before_needle php V5.3 :

<?php
//$h = haystack, $n = needle
if($pos=stripos($h,$n)) $string=substr($h,0,$pos);
?>
andy 08-Mar-2010 09:44
Quick way to use this with an array for a needle:

<?php
$arr = array('search_term1','search_term2','search_term3');

foreach($arr as $key => $search_needle) {

   if(stristr($haystack, $search_needle) != FALSE) {
        echo 'execute this code if found';
   }

}
?>
carel at ckbt dot org 13-May-2009 08:18
if stristr($message,'viagra')
or stristr($message,'cialis')
)
{
die();
}

Works quite well in any Shoutbox, Forum, Guestbook, Mailform, etcetera.

Just enter between the definitions and sending the message to the DB, et voila. ^_^
tomas dot nesrovnal at yourspirit dot cz 18-Dec-2008 12:36
Active item item in menu:

<?php
function aim($page) {
    if(stristr($_SERVER['REQUEST_URI'], $page)) {
        return ' class="active"';
    }
}
?>

usage:

<style type="text/css">
.active {color: red;}
</style>

<?php
print '<a href="http://example.com/page/hello-world/"'. aim('hello-world') .'>HW</a>';
?>
giz at gbdesign dot net 06-Oct-2007 05:02
Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.

Got round this by casting the value to a string.

<?php
if( !stristr( $file, (string) $myCustomer->getCustomerID()  ) ) {
  // Permission denied
}
?>
art at awilton dot dotcom 07-Nov-2005 09:17
handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.

<?php

 $i = implode(" ",$argv); //implode all the settings sent via clie
 $e = explode("-",$i); // no lets explode it using our defined seperator '-'

       //now lets parse the array and return the parameter name and its setting
       // since the input is being sent by the user via the command line
       //we will use stristr since we don't care about case sensitivity and
       //will convert them as needed later.

    while (list($index,$value) = each($e)){

       //lets grap the parameter name first using a double reverse string
       // to get the begining of the string in the array then reverse it again
       // to set it back. we will also "trim" off the "=" sign

     $param = rtrim(strrev(stristr(strrev($value),'=')),"=");

       //now lets get what the parameter is set to.
       // again "trimming" off the = sign

     $setting = ltrim(stristr($value,'='),"=");

       // now do something with our results.
       // let's just echo them out so we can see that everything is working

      echo "Array index is ".$index." and value is ".$value."\r\n";
      echo "Parameter is ".$param." and is set to ".$setting."\r\n\r\n";

}

?>

when run from the CLI this script returns the following.

[root@fedora4 ~]# php a.php -val1=one -val2=two -val3=three

Array index is 0 and value is a.php
Parameter is  and is set to

Array index is 1 and value is val1=one
Parameter is val1 and is set to one

Array index is 2 and value is val2=two
Parameter is val2 and is set to two

Array index is 3 and value is val3=three
Parameter is val3 and is set to three

[root@fedora4 ~]#
triadsebas at triads dot buildtolearn dot net 21-Jul-2005 05:39
You can use strstr() or stristr() to validate data!
Check this out:
<?php
function validate_email($input) {
  if (!stristr($input, '@')) {
    return false;
  }
  return true;
}

function validate_url($input) {
  if (!stristr($input, 'http://')) {
    return false;
  }
  return true;
}
?>
Simple example:
<?php
if (!validate_email($_POST['email'])) {
  print 'You did not enter a valid email adress';
}
if (!validate_url($_POST['url'])) {
  print 'You did not enter a valid url.';
}
?>
notepad at codewalkers dot com 05-Jun-2005 01:02
<?php

function stristr_reverse($haystack, $needle) {
  $pos = stripos($haystack, $needle) + strlen($needle);
  return substr($haystack, 0, $pos);
}
$email = 'USER@EXAMPLE.com';
echo stristr_reverse($email, 'er');
// outputs USER

?>
Techdeck at Techdeck dot org 12-Nov-2002 12:26
An example for the stristr() function:

<?php
$a = "I like php";
if (stristr("$a", "LikE PhP")) {
print ("According to \$a, you like PHP.");
}
?>

It will look in $a for "like php" (NOT case sensetive. though, strstr() is case-sensetive).

For the ones of you who uses linux.. It is similiar to the "grep" command.
Actually.. "grep -i".
dpatton.at.confluence.org 02-Oct-2002 09:36
There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.

The following will generate a warning message in 4.0.6 and 4.2.3:
  stristr("haystack", "");
     OR
  $needle = "";  stristr("haystack", $needle);

This will _not_ generate an "Empty Delimiter" warning message in
4.0.6, but _will_ in 4.2.3:
  unset($needle); stristr("haystack", $needle);

Here's a URL that documents what was changed:
http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver
stripslashes
strlen
Обработка строк


Возвращает длину строки

stristr
strnatcasecmp
Обработка строк
PHP Manual

strlen

(PHP 4, PHP 5)

strlen — Возвращает длину строки

Описание

int strlen ( string $string )

Возвращает длину строки string.

Список параметров

string

Строка (string), для которой измеряется длина.

Возвращаемые значения

Длина строки string в случае успеха, и 0, если string пуста.

Список изменений

Версия | Описание
5.3.0 | Ранние версии этой функции рассматривали массивы как строку Array, возвращая таким образом 5 в качестве длины этой строки, и вызывали ошибку уровня E_NOTICE.

Примеры

Пример #1 Пример использования strlen()

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

Примечания

Замечание:

strlen() возвращает NULL при использовании на массивах, а также выводит ошибку уровня E_WARNING.

Смотрите также

  • count() - Подсчитывает количество элементов массива или что-то в объекте
  • mb_strlen() - Получает длину строки

User Contributed Notes

PhoneixS 13-May-2011 04:09
A little test values:
<?php var_dump(strlen(null), strlen(123), strlen(-1), strlen('')); ?>

And the results are:
int(0) int(3) int(2) int(0)

Conclusion:
The values are converted to string before check the lenght.
canschi dot sergiu at yahoo dot com 08-Jan-2011 01:52
Hello all,

May I pos my firs  function as novice in php here .
This funtion count all characters in a strign without spaces , so only chars, no spaces .

<?php
function countchar ($string) {

$result = strlen ($string)  -   substr_count($string, ' ');
echo $result;
}

countchar ($a);
?>

Hope to be useful for somebody !
basil at gohar dot us 08-Jun-2010 02:03
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:

<?php

$attributes = array('one', 'two', 'three');

if (strlen($attributes) == 0 && !is_bool($attributes)) {
    echo "We are in the 'if'\n";  //  PHP 5.3
} else {
    echo "We are in the 'else'\n";  //  PHP 5.2
}

?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.
Vladimir Zafirov 27-May-2009 09:28
You can also just say:
<?php
  strlen(utf8_decode($a))
?>
The utf8_decode($a) will take care of converting the utf characters that have more than one byte in to one symbol and the strlen() will count those correctly as length 1.
anto dot justus at gmail dot com 24-Apr-2009 08:14
It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users.

<?php
function utf8_strlen($str)
    {
    $count = 0;

    for($i = 0; $i < strlen($str); $i++)
        {
        $value = ord($str[$i]);
        if($value > 127)
            {
            if($value >= 192 && $value <= 223)
                $i++;
            elseif($value >= 224 && $value <= 239)
                $i = $i + 2;
            elseif($value >= 240 && $value <= 247)
                $i = $i + 3;
            else
                die('Not a UTF-8 compatible string');
            }

        $count++;
        }

    return $count;
    }
?>
Amaroq 19-Mar-2009 11:51
When dealing with submitted forms that you've imposed a character limit on, you must remember that functions that count characters consider "\r\n" to be two characters.

<?php
//These will both output 2.
echo strlen("\r\n");
echo mb_strlen("\r\n");
?>

If I had thought of this starting out, I would have saved myself several hours of trouble trying to get php to cut a message to the same length that my auxiliary javascript validation imposed on it.
Anonymous 15-Feb-2009 09:51
simple speed test for UTF-8 strings:

<?php

header("Content-type: text/html; charset=UTF-8");
ini_set('mbstring.internal_encoding', 'UTF-8');

?><pre><?

function utf8_strlen($s) {
    $c = strlen($s); $l = 0;
    for ($i = 0; $i < $c; ++$i) if ((ord($s[$i]) & 0xC0) != 0x80) ++$l;
    return $l;
}

function utf0_strlen($s) {
    $l = 0; $i = 0;
    while ($n = ord($s[$i++])) if (($n & 0xC0) != 0x80) ++$l;
    return $l;
}

function utfs_strlen($s) {
    $c = strlen($s);
    $l = 0;
    for($i = 0; $i < $c; $i++) {
        $v = ord($s[$i]);
        if($v > 127) {
            if($v >= 192 && $v <= 223) ++$i;
            elseif($v >= 224 && $v <= 239) $i += 2;
            elseif($v >= 240 && $v <= 247) $i += 3;
            else die('Not a UTF-8 compatible string');
        }
        ++$l;
    }
    return $l;
}

function spl_strlen($s) {
  return count(preg_split("//u", $s)) - 2;
}

function dcd_strlen($s) {
    return strlen(utf8_decode($s));
}

function preg_strlen($s) {
  return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $s, $d);
}

$src = '=123! !ы"в#$%&\'()*+,—./:;<=>?@[\]^_`{|}~'.
    '    йцукенгшщзхъфывапролджтьбю'.chr(0).'ы';

$tc = 10000; //test count

$l = mb_strlen($src, 'UTF-8'); //real testing string length

$lst = array('strlen', 'mb_strlen', 'dcd_strlen',
    'preg_strlen', 'utfs_strlen', 'utf8_strlen',
    'utf0_strlen', 'spl_strlen'); // list of functions

foreach ($lst as $f) {
    $t = microtime(1);
    for($i = 0; $i < $tc; $i++) $f($src);
    $t = microtime(1) - $t;
    printf("%14s : %0.6f : %03u%s\n",
        $f, $t, $q = $f($src), $q != $l ? ' - failed!' : '');
}
?></pre>

main results:
        strlen : 0.009419 : 112 failed!
     mb_strlen : 0.016377 : 075
    dcd_strlen : 0.063055 : 075
   preg_strlen : 1.106809 : 075
   utfs_strlen : 1.701586 : 075
   utf8_strlen : 2.321344 : 075
   utf0_strlen : 2.578518 : 073 failed!
    spl_strlen : 3.789029 : 075
jonathan dot protzenko at gmail dot com 23-Aug-2008 07:35
paolo dot mosna at gmail dot com's solution for getting the length of a unicode string didn't work for me. Instead, I used the following dirty function (which can be surely improved, but I'm giving the idea) :

<?php
function ustrlen($s) {
  $a = preg_split("//u", $s);
  $i = -2;
  foreach ($a as $b)
    $i++;
  return $i;
}
?>

This will return the correct length for any unicode string.
radu_keepwalking at yahoo dot com 15-Apr-2008 04:37
Another way to preview a text with or without html tags, and end not cut in a middle of a word.

<?php
function preview_text($TEXT, $LIMIT, $TAGS = 0) {

    // TRIM TEXT
    $TEXT = trim($TEXT);

    // STRIP TAGS IF PREVIEW IS WITHOUT HTML
    if ($TAGS == 0) $TEXT = preg_replace('/\s\s+/', ' ', strip_tags($TEXT));

    // IF STRLEN IS SMALLER THAN LIMIT RETURN
    if (strlen($TEXT) < $LIMIT) return $TEXT;

    if ($TAGS == 0) return substr($TEXT, 0, $LIMIT) . " ...";
    else {

        $COUNTER = 0;
        for ($i = 0; $i<= strlen($TEXT); $i++) {

            if ($TEXT{$i} == "<") $STOP = 1;

            if ($STOP != 1) {

                $COUNTER++;
            }

            if ($TEXT{$i} == ">") $STOP = 0;
            $RETURN .= $TEXT{$i};

            if ($COUNTER >= $LIMIT && $TEXT{$i} == " ") break;

        }

        return $RETURN . "...";
    }

}
?>
mail4adry at inwind dot it 21-Aug-2007 01:53
This can be useful to put a preview of an article on the front page when the rest of the article is displayed on another page:

<?php
function getPreviewText($text) {
    // Strip all tags
    $desc = strip_tags(html_entity_decode($text), "<a><em>");
    $charlen = 0; $crs = 0;
    if(strlen_HTML($desc) == 0)
        $preview = substr($desc, 0, 69);
    else
    {
        $i = 0;
        while($charlen < 80)
        {
            $crs = strpos($desc, " ", $crs)+1;
            $lastopen = strrpos(substr($desc, 0, $crs), "<");
            $lastclose = strrpos(substr($desc, 0, $crs), ">");
            if($lastclose > $lastopen)
            {
                // we are not in a tag
                $preview = substr($desc, 0, $crs);
                $charlen = strlen_noHTML($preview);
            }
            $i++;
        }
    }
    return $preview."&#8230;"
}
?>

will display text cut as near as possible to character 80 respecting each <a> and <em> tags and ending with ...
mail4adry at inwind dot it 21-Aug-2007 09:28
<?php
/**
 * return length of a string regardeless of html tags in it
 *
 * @param string $html
 * @return string
 */
function strlen_noHtml($string){
    $crs = 0;
    $charlen = 0;
    $len = strlen($string);
    while($crs < $len)
    {
        $offset = $crs;
        $crs = strpos($string, "<", $offset);
        if($crs === false)
        {
           $crs = $len;
           $charlen += $crs - $offset;
        }
        else
        {
            $charlen += $crs - $offset;
            $crs = strpos($string, ">", $crs)+1;
        }
    }
    return $charlen;
}

/**
 * return length of a string regarding html tags in it
 *
 * @param string $html
 * @return string
 */
function strlen_Html($string){
    $crs = 0;
    $charlen = 0;
    $len = strlen($string);
    while($crs < $len)
    {
        $scrs = strpos($string, "<", $crs);
        if($scrs === false)
        {
           $crs = $len;
        }
        else
        {
            $crs = strpos($string, ">", $scrs)+1;
            if($crs === false)
                $crs = $len;
            $charlen += $crs - $scrs;
        }
    }
    return $charlen;
}
?>

Example:

<?php
$text = "<p>Test 'a' paragraph.</p><!-- Comment --> Other text";

echo "strlen without HTML chars:".strlen_noHtml($text);
echo "<br>";
echo "strlen of HTML chars:".strlen_html($text);
?>

Will output:
strlen without HTML chars:30
strlen of HTML chars:23
bradmwalker at cableone dot net 01-Jul-2007 03:48
want a predicate that tests a string for emptiness? use strlen instead of empty(). strlen only returns a false-equivalent value for ''.

example:

<?php
// takes string_array and returns an array without any values w/empty strings
function filter_empties ($string_array) {
    // note: the immensely retarded empty() function returns true on string '0'
    // use strlen as empty string predicate
    return count($string_array) ? array_filter ($string_array, 'strlen') : $string_array;
}
?>
topera at gmail dot com 27-Jun-2007 08:32
<?php
//------------------------------------------
// This function returns the necessary
// size to show some string in display
// For example:
// $a = strlen_layout("WWW"); // 49
// $a = strlen_layout("..."); // 16
// $a = strlen_layout("Hello World"); // 99
//------------------------------------------
function strlen_pixels($text) {
    /*
        Pixels utilized by each char (Verdana, 10px, non-bold)
        04: j
        05: I\il,-./:; <espace>
        06: J[]f()
        07: t
        08: _rz*
        09: ?csvxy
        10: Saeko0123456789$
        11: FKLPTXYZbdghnpqu
        12: AÇBCERV
        13: <=DGHNOQU^+
        14: w
        15: m
        16: @MW
    */

    // CREATING ARRAY $ps ('pixel size')
    // Note 1: each key of array $ps is the ascii code of the char.
    // Note 2: using $ps as GLOBAL can be a good idea, increase speed
    // keys:    ascii-code
    // values:  pixel size

    // $t: array of arrays, temporary
    $t[] = array_combine(array(106), array_fill(0, 1, 4));

    $t[] = array_combine(array(73,92,105,108,44), array_fill(0, 5, 5));
    $t[] = array_combine(array(45,46,47,58,59,32), array_fill(0, 6, 5));
    $t[] = array_combine(array(74,91,93,102,40,41), array_fill(0, 6, 6));
    $t[] = array_combine(array(116), array_fill(0, 1, 7));
    $t[] = array_combine(array(95,114,122,42), array_fill(0, 4, 8));
    $t[] = array_combine(array(63,99,115,118,120,121), array_fill(0, 6, 9));
    $t[] = array_combine(array(83,97,101,107), array_fill(0, 4, 10));
    $t[] = array_combine(array(111,48,49,50), array_fill(0, 4, 10));
    $t[] = array_combine(array(51,52,53,54,55,56,57,36), array_fill(0, 8, 10));
    $t[] = array_combine(array(70,75,76,80), array_fill(0, 4, 11));
    $t[] = array_combine(array(84,88,89,90,98), array_fill(0, 5, 11));
    $t[] = array_combine(array(100,103,104), array_fill(0, 3, 11));
    $t[] = array_combine(array(110,112,113,117), array_fill(0, 4, 11));
    $t[] = array_combine(array(65,195,135,66), array_fill(0, 4, 12));
    $t[] = array_combine(array(67,69,82,86), array_fill(0, 4, 12));
    $t[] = array_combine(array(78,79,81,85,94,43), array_fill(0, 6, 13));
    $t[] = array_combine(array(60,61,68,71,72), array_fill(0, 5, 13));
    $t[] = array_combine(array(119), array_fill(0, 1, 14));
    $t[] = array_combine(array(109), array_fill(0, 1, 15));
    $t[] = array_combine(array(64,77,87), array_fill(0, 3, 16));

    // merge all temp arrays into $ps
    $ps = array();
    foreach($t as $sub) $ps = $ps + $sub;

    // USING ARRAY $ps
    $total = 1;
    for($i=0; $i<strlen($text); $i++) {
        $temp = $ps[ord($text[$i])];
        if (!$temp) $temp = 10.5; // default size for 10px
        $total += $temp;
    }
    return $total;
}
?>

Rafael Pereira dos Santos
paolo dot mosna at gmail dot com 10-Jan-2007 07:58
Title: Strlen() ant bytes string lenght.
Just to remember that strlen() return the number of characters of a string. Often the strlen() function is used to compute the length in bytes of a string. This is correct until string is single byte encoded. If multi-byte char-set is used this constraint i no more verified. So when you require the number of bytes of a ASCII or UTF-8 encoded string, it is better to use following function:

<?php
    /**
     * Count the number of bytes of a given string.
     * Input string is expected to be ASCII or UTF-8 encoded.
     * Warning: the function doesn't return the number of chars
     * in the string, but the number of bytes.
     *
     * @param string $str The string to compute number of bytes
     *
     * @return The length in bytes of the given string.
     */
    function strBytes($str)
    {
      // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT

      // Number of characters in string
      $strlen_var = strlen($str);

      // string bytes counter
      $d = 0;

     /*
      * Iterate over every character in the string,
      * escaping with a slash or encoding to UTF-8 where necessary
      */
      for ($c = 0; $c < $strlen_var; ++$c) {

          $ord_var_c = ord($str{$d});

          switch (true) {
              case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
                  // characters U-00000000 - U-0000007F (same as ASCII)
                  $d++;
                  break;

              case (($ord_var_c & 0xE0) == 0xC0):
                  // characters U-00000080 - U-000007FF, mask 110XXXXX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=2;
                  break;

              case (($ord_var_c & 0xF0) == 0xE0):
                  // characters U-00000800 - U-0000FFFF, mask 1110XXXX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=3;
                  break;

              case (($ord_var_c & 0xF8) == 0xF0):
                  // characters U-00010000 - U-001FFFFF, mask 11110XXX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=4;
                  break;

              case (($ord_var_c & 0xFC) == 0xF8):
                  // characters U-00200000 - U-03FFFFFF, mask 111110XX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=5;
                  break;

              case (($ord_var_c & 0xFE) == 0xFC):
                  // characters U-04000000 - U-7FFFFFFF, mask 1111110X
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=6;
                  break;
              default:
                $d++;
          }
      }

      return $d;
    }
?>

This function has been adapted form the JSON function used to convert character in UTF-8 representation.

With this new function we solved problem in JSON and in PEAR/SOAP php libraries.
liquix at hjelpesentral dot no 17-Aug-2006 05:57
An easy function to make sure the words in a sentence is not above the maximum lengt of characters. This is used to prevent that users posting for an example comments on your page and drag the page width out.

Returns true or false
<?php
function wordlength($txt, $limit)
{
   $words = explode(' ', $txt);

   foreach($words as $v)
   {
       if(strlen($v) > $limit)
       {
            return false;
       }
   }

   return true;
}
?>

Uses like this:
<?php

$txt = "Onelongword and some small ones";

if(!wordlength($txt, 10))
{
    die("One of the words where too long");
}

?>

That will return false since one of the words in $txt is too long. (Maximum set to 10)
Hage Yaapa 12-Jan-2006 03:51
Sometimes you really wanna make sure no user edits the 'maxlength' attribute of the HTML page and POSTs a 5 Mb string to your script. Probably, advanced programmers already take precautions, this one is just a very simple tip for beginners on how to check the character lenth of the POST variables in an effective manner.

<?php

// ALWAYS clean the POST variables of any HTML tags first.
// And here we do it in one easy step.
 $_POST = array_map('strip_tags', $_POST);

// These are the POST variables in the example
 $alias = $_POST['alias'];
 $name = $_POST['name'];
 $status = $_POST['status'];
 $year = $_POST['year'];

// We create an array that contains the expected character length
// for each POST variable
 $exlen = array (
      'alias'=>12,
      'name'=>30,
      'status'=>10,
      'year'=>4
);

// Now check if any of them exceeds the expected length
 foreach ($exlen as $key=>$val) {
      if (strlen($$key) > $val) {
            // The user has definitely edited the HTML! He has a lot of time, could be bad.
          // This section can edited according to your needs - very simple to complex.
          // Log the event or send an e-mail to the admin at the basic.
          // However, in this example we just print a warning.
          print 'WARNING: The FBI is looking for you, dude!';
          exit;
          // The best part is that the script won't look for any other
          // POST variables other than the ones which we are expecting already.
      }
}
?>

Similarly, with the use of Regular Expressions you could check the data type and string format too.
bartek at proteus,pl 19-Jul-2005 05:08
> Just a precisation, maybe obvious, about the strlen() behaviour:
> with binary strings (i.e. returned by the pack() finction) is made
> a byte count... so strlen returns the number of bytes contained
> in the binary string.

This is not always true. strlen() might be shadowed by mb_strlen().
If that is the case it might treat binary data as unocode string and return wrong value (I just found it out after fighting with egroupware email attachment handling bug).

So, if your data is binary I would suggest using somthing like this (parts of the code from egroupware):

<?php
$has_mbstring = extension_loaded('mbstring') ||@dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX);
$has_mb_shadow = (int) ini_get('mbstring.func_overload');

if ($has_mbstring && ($has_mb_shadow & 2) ) {
   $size = mb_strlen($this->output_data,'latin1');
} else {
   $size = strlen($this->output_data);
}
?>
--
Bartek
triadsebas at triads dot buildtolearn dot net 17-Jul-2005 05:49
A nice use of the strlen() function, the following function will check if one of the words in $input is longer than $maxlenght,  $maxlenght is standard 40.
<?php
function check_input($input, $maxlenght= 40)
$temp_array = explode(" ", $input);
foreach ($temp_array as $word) {
if (strlen($word) > $maxlenght) {
return false;
}
}
return true;
}
?>
Example:
<?php
if (!check_input($_POST['message'])) {
print 'One of your words in your message in longer than 40 chars. Please edit your message.';
}
?>
http://nsk.wikinerds.org 22-Apr-2005 09:02
Beware: strlen() counts new line characters at the end of a string, too!

<?php
  $a = "123\n";
  echo "<p>".strlen($a)."</p>";
?>

The above code will output 4.
packe100 at hotmail dot com 14-Mar-2005 07:07
Just a precisation, maybe obvious, about the strlen() behaviour: with binary strings (i.e. returned by the pack() finction) is made a byte count... so strlen returns the number of bytes contained in the binary string.
php at capcarrere dot org 06-Feb-2005 06:32
Hi,

if you want to trim a sentence to a certain number of
characters so that it is displayed nicely in a HTML page
(in a table for instance), then you actually want to count
the number of characters displayed rather than the
actual number of characters of the string.

For instance:
"L&agrave; bas" should really be 5 character long,
rather than 10.

Also you don't want to cut a special char in the middle.
For instance:
If 3 is the maximum number of characters,

"L&agrave; bas"  should be cut as "L&agrave; ..."
and not "L&a...";

So here is a simple method to dothat:

<?php
function nicetrim ($s) {
// limit the length of the given string to $MAX_LENGTH char
// If it is more, it keeps the first $MAX_LENGTH-3 characters
// and adds "..."
// It counts HTML char such as &aacute; as 1 char.
//

  $MAX_LENGTH = 22;
  $str_to_count = html_entity_decode($s);
  if (strlen($str_to_count) <= $MAX_LENGTH) {
    return $s;
  }

  $s2 = substr($str_to_count, 0, $MAX_LENGTH - 3);
  $s2 .= "...";
  return htmlentities($s2);
}
?>
chernyshevsky at hotmail dot com 05-Sep-2004 03:36
The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:

<?php
$length = strlen(utf8_decode($s));
?>

utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright.
dtorop932 at hotmail dot com 03-Dec-2003 02:25
To follow up on dr-strange's utf8_strlen(), here are two succinct alternate versions.  The first is slower for multibyte UTF-8, faster for single byte UTF-8.  The second should be much faster for all but very brief strings, and can easily live inline in code.  Neither validates the UTF-8.

Note that the right solution is to use mb_strlen() from the mbstring module, if one is lucky enough to have that compiled in...

<?php
// choice 1
function utf8_strlen($str) {
  $count = 0;
  for ($i = 0; $i < strlen($str); ++$i) {
    if ((ord($str[$i]) & 0xC0) != 0x80) {
      ++$count;
    }
  }
  return $count;
}

// choice 2
function utf8_strlen($str) {
  return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $dummy);
}
?>
Patrick 01-Aug-2003 02:36
Just a general pointer that I have hit upon after some struggle:

Most blobs can easily be treated as strings, so to retreat info on a blob or to manipulate it in any way, I recommend trying out string-related functions first. They've worked well for me.
suchy at ecl dot pl 13-May-2003 03:22
a little modification of rasmus solution

<?php
$tmp=0; $s="blah";
while($c=$s[$tmp++]) { echo $c; }
?>

but what happens when the string contains zeros?

<?php $s="blah0blah"; ?>
the script stops....

here is sample of code and the string is correcly parsed using strlen() even when containing zeros:

<?php
$s="blah0blah";
$si=0;
$s_len=strlen($s);
for ($si=0;$si<$s_len;$si++)
{
 $c=$s[$si];
 echo $c;
}
?>
dr - strange at shaw dot ca 02-Oct-2002 07:08
It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users.

<?php
function utf8_strlen($str)
    {
    $count = 0;

    for($i = 0; $i < strlen($str); $i++)
        {
        $value = ord($str[$i]);
        if($value > 127)
            {
            if($value >= 192 && $value <= 223)
                $i++;
            elseif($value >= 224 && $value <= 239)
                $i = $i + 2;
            elseif($value >= 240 && $value <= 247)
                $i = $i + 3;
            else
                die('Not a UTF-8 compatible string');
            }

        $count++;
        }

    return $count;
    }
?>
26-May-2001 12:11
Note that PHP does not need to traverse the string to know its length with strlen(). The length is an attribute of the array used to store the characters. Do not count on strings being terminated by a NULL character. This may not work with some character encodings, and PHP strings are binary-safe !
PHP4 included a NULL character after the last position in the string, however, this does not change the behavior of strlen or the binary safety: this NULL character is not stored.

However PHP4 allows now to reference the position after the end of the string for both read and write access:

* when reading at that position (e.g. $s[strlen($s)]), you get a warning with PHP3, and you'll get 0 with PHP4 not returning a warning.

* you can assign it directly in PHP4 with one character to increase the string length by one character:

<?php
$s[strlen($s)]=65; //append 'A'
$s[]=65; //append 'A'
$s[strlen($s)]=0; //append NUL (stored!)
$s[]=0; //append NUL (stored!)
?>

Such code did not work in PHP3, where the only way to extend the string length was by using a concat operator.

However, reading or writing past the end of the string, using an array index superior to the current string length will still raise a warning in PHP4.
stristr
strnatcasecmp
Обработка строк


Сравнение строк без учета регистра с использованием алгоритма "natural order"

strlen
strnatcmp
Обработка строк
PHP Manual

strnatcasecmp

(PHP 4, PHP 5)

strnatcasecmp — Сравнение строк без учета регистра с использованием алгоритма "natural order"

Описание

int strnatcasecmp ( string $str1 , string $str2 )

Эта функция реализует алгоритм сравнения, упорядочивающий алфавитно-цифровые строки подобно тому, как это сделал бы человек. Эта функция подобна strnatcmp(), за исключением того, что сравнение происходит без учета регистра символов. Для получения дополнительной информации см. » Natural Order String Comparison

Список параметров

str1

Первая строка.

str2

Вторая строка.

Возвращаемые значения

Подобно другим функциям сравнения строк, данная функция возвращает отрицательное число, если str1 меньше, чем str2, положительное число, если str1 больше, чем str2, и 0 если строки равны.

Смотрите также

  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • strcmp() - Бинарно-безопасное сравнение строк
  • strcasecmp() - Бинарно-безопасное сравнение строк без учета регистра
  • substr() - Возвращает подстроку
  • stristr() - Регистро-независимый вариант функции strstr
  • strncasecmp() - Бинарно-безопасное сравнение первых n символов строк без учета регистра
  • strncmp() - Бинарно-безопасное сравнение первых n символов строк
  • strstr() - Находит первое вхождение подстроки
  • setlocale() - Устанавливает настройки локали

User Contributed Notes

chatfielddaniel at googlemail dot com 14-Apr-2011 04:07
The function treats '_' as after letters and numbers when it would be placed before logically.
thomas at uninet dot se 25-Jul-2006 12:49
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.
strlen
strnatcmp
Обработка строк


Сравнение строк с использованием алгоритма "natural order"

strnatcasecmp
strncasecmp
Обработка строк
PHP Manual

strnatcmp

(PHP 4, PHP 5)

strnatcmp — Сравнение строк с использованием алгоритма "natural order"

Описание

int strnatcmp ( string $str1 , string $str2 )

Эта функция реализует алгоритм сравнения, упорядочивающий алфавитно-цифровые строки подобно тому, как это сделал бы человек, такой алгоритм называется "natural ordering". Сравнение происходит с учетом регистра.

Список параметров

str1

Первая строка.

str2

Вторая строка.

Возвращаемые значения

Подобно другим функциям сравнения строк, данная функция возвращает отрицательное число, если str1 меньше, чем str2, положительное число, если str1 больше, чем str2, и 0 если строки равны.

Примеры

Пример, показывающий отличие этого алгоритма от обычных функций сравнения (используемых в strcmp()), приведен ниже:

<?php
$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");
echo "Стандартный алгоритм сравнения\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nАлгоритм \"natural order\"\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?>

Результат выполнения данного примера:

Стандартный алгоритм сравнения
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Алгоритм "natural order"
Array
(
    [0] => img1.png
    [1] => img2.png
    [2] => img10.png
    [3] => img12.png
)
Для получения дополнительной информации см. » Natural Order String Comparison

Смотрите также

  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • strcasecmp() - Бинарно-безопасное сравнение строк без учета регистра
  • substr() - Возвращает подстроку
  • stristr() - Регистро-независимый вариант функции strstr
  • strcmp() - Бинарно-безопасное сравнение строк
  • strncmp() - Бинарно-безопасное сравнение первых n символов строк
  • strncasecmp() - Бинарно-безопасное сравнение первых n символов строк без учета регистра
  • strnatcasecmp() - Сравнение строк без учета регистра с использованием алгоритма "natural order"
  • strstr() - Находит первое вхождение подстроки
  • natsort() - Сортирует массив, используя алгоритм "natural order"
  • natcasesort() - Сортирует массив, используя алгоритм "natural order" без учета регистра символов

User Contributed Notes

Zero 04-Dec-2010 02:14
If you want to compare $_SESSION variables to a string use this

<?php
if(isset($_SESSION['usertype']))
{
     echo "usertype " .$_SESSION['usertype'];

     $ut = $_SESSION['usertype'];

     if(strnatcmp($ut,"admin"))
     {
          echo "hello admin";
     }
}
?>
thomas at uninet dot se 25-Jul-2006 12:50
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.
strnatcasecmp
strncasecmp
Обработка строк


Бинарно-безопасное сравнение первых n символов строк без учета регистра

strnatcmp
strncmp
Обработка строк
PHP Manual

strncasecmp

(PHP 4 >= 4.0.2, PHP 5)

strncasecmp — Бинарно-безопасное сравнение первых n символов строк без учета регистра

Описание

int strncasecmp ( string $str1 , string $str2 , int $len )

Эта функция подобна strcasecmp(), за исключением того, что можно указать максимальное количество символов в обоих строках, которые будут участвовать в сравнении.

Список параметров

str1

Первая строка.

str2

Вторая строка.

len

Количество символов, участвующих в сравнении.

Возвращаемые значения

Возвращает отрицательное число, если str1 меньше, чем str2, положительное число, если str1 больше, чем str2, и 0 если строки равны.

Смотрите также

  • strncmp() - Бинарно-безопасное сравнение первых n символов строк
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • substr_compare() - Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
  • strcasecmp() - Бинарно-безопасное сравнение строк без учета регистра
  • stristr() - Регистро-независимый вариант функции strstr
  • substr() - Возвращает подстроку

User Contributed Notes

khootz 27-Nov-2006 08:23
i assume you can also use the ! (not) operator

<?php

if (!strncasecmp($string, 'Trudeau', 4)){
       print "true";
}

?>

since booleans in PHP translate 0 to FALSE and any other integer to TRUE.

!0  = !false = true
!1  = !true = false
!-1 = !true = false
djdykes 31-Aug-2005 03:43
Hi all,

be aware when comparing strings using the strcmp family. if you write code like this...

if (strncasecmp($string, 'Trudeau', 4))
 print "true";

The above code returns 1 which evaluates to boolean 'true'

that statement will always be true... because these functions return 0 only when equal. so a better test would be

if ( (strncasecmp($string, 'Trudeau', 4)) == 0)
 print "true";

always test these functions equality with 0

regards
strnatcmp
strncmp
Обработка строк


Бинарно-безопасное сравнение первых n символов строк

strncasecmp
strpbrk
Обработка строк
PHP Manual

strncmp

(PHP 4, PHP 5)

strncmp — Бинарно-безопасное сравнение первых n символов строк

Описание

int strncmp ( string $str1 , string $str2 , int $len )

Эта функция подобна strcmp(), за исключением того, что можно указать максимальное количество символов в обоих строках, которые будут участвовать в сравнении.

Эта функция учитывает регистр символов.

Список параметров

str1

Первая строка.

str2

Вторая строка.

len

Количество символов, используемых в сравнении.

Возвращаемые значения

Возвращает отрицательное число, если str1 меньше, чем str2, положительное число, если str1 больше, чем str2, и 0 если строки равны.

Смотрите также

  • strncasecmp() - Бинарно-безопасное сравнение первых n символов строк без учета регистра
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • substr_compare() - Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
  • strcmp() - Бинарно-безопасное сравнение строк
  • strstr() - Находит первое вхождение подстроки
  • substr() - Возвращает подстроку

User Contributed Notes

bobvin at pillars dot net 19-May-2011 07:25
For checking matches at the beginning of a short string, strpos() is about 15% faster than strncmp().

Here's a benchmark program to prove it:

<?php
$haystack = "abcdefghijklmnopqrstuvwxyz";
$needles = array('abc', 'xyz', '123');
foreach ($needles as $needle) {
  $times['strncmp'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strncmp($haystack, $needle, 3) === 0;
  }
  $times['strncmp'][$needle] += microtime(true);
}
foreach ($needles as $needle) {
  $times['strpos'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strpos($haystack, $needle) === 0;
  }
  $times['strpos'][$needle] += microtime(true);
}
var_export($times);
?>
elloromtz at gmail dot com 19-Apr-2010 05:25
if length is 0 regardless what the two strings are, it will return 0

<?php
strncmp("xybc","a3234",0); // 0
strncmp("blah123","hohoho", 0); //0
?>
codeguru at crazyprogrammer dot cba dot pl 24-Jan-2008 11:07
I ran the following experiment to compare arrays.

1 st - using (substr($key,0,5 == "HTTP_") & 2 nd - using (!strncmp($key, 'HTTP_', 5))

I wanted to work out the fastest way to get the first few characters from a array

BENCHMARK ITERATION RESULT IS:
if (substr($key,0,5 == "HTTP_").... -   0,000481s
if (!strncmp($key, 'HTTP_', 5)).... -     0,000405s

strncmp() is 20% faster than substr() :D

<?php
// SAMPLE FUNCTION
function strncmp_match($arr)
{
foreach ($arr as $key => $val)
    {
    //if (substr($key,0,5 == "HTTP_")
    if (!strncmp($key, 'HTTP_', 5))
        {
    $out[$key] = $val;
        }
    }
return $out;
}

// EXAMPLE USE
?><pre><?php
print_r(strncmp_match($_SERVER));
?></pre>

will display code like this:

Array
(
    [HTTP_ACCEPT] => XXX
    [HTTP_ACCEPT_LANGUAGE] => pl
    [HTTP_UA_CPU] => x64
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_USER_AGENT] => Mozilla/4.0
                                    (compatible; MSIE 7.0;
                                     Windows NT 5.1;
                                    .NET CLR 1.1.4322;
                                    .NET CLR 2.0.50727)
    [HTTP_HOST] => XXX.XXX.XXX.XXX
    [HTTP_CONNECTION] => Keep-Alive
    [HTTP_COOKIE] => __utma=XX;__utmz=XX.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
)
Anonymous 17-Apr-2002 04:46
strncmp("sample","sam",4) returns 1 because the final requirement is if one string terminates before len, then the other must also terminate at that position.

You can imagine that all your strings have one more final, invisible "termination" character.  If that termination character happens to be within in len, then it must match, too.

For instance, write that termination character with, say, the sequence "\0". Then you can equivalently consider that function call as strncmp("sample\0","sam\0",4).

So, the "p" in "sample" does not match the termination character in "sam".
strncasecmp
strpbrk
Обработка строк


Ищет в строке любой символ из заданного набора

strncmp
strpos
Обработка строк
PHP Manual

strpbrk

(PHP 5)

strpbrk — Ищет в строке любой символ из заданного набора

Описание

string strpbrk ( string $haystack , string $char_list )

strpbrk() ищет в строке haystack символы из набора char_list.

Список параметров

haystack

Строка, в которой производится поиск char_list.

char_list

Данный параметр чувствителен к регистру.

Возвращаемые значения

Возвращает строку, начиная с найденного символа, или FALSE, если он не был найден.

Примеры

Пример #1 Пример использования strpbrk()

<?php

$text = 'This is a Simple text.';

// Этот код выдаст "is is a Simple text.", т.к. символ 'i' встретится раньше
echo strpbrk($text, 'mi');

// Этот код выдаст "Simple text.", т.к. символы чувствительны к регистру
echo strpbrk($text, 'S');
?>

Смотрите также

  • strpos() - Возвращает позицию первого вхождения подстроки
  • strstr() - Находит первое вхождение подстроки
  • preg_match() - Выполняет проверку на соответствие регулярному выражению

User Contributed Notes

b dot pleshka at gmail dot com 04-Jan-2012 12:55
Simple code to define symbol (@) in the string

<?php
$name = "username@example.com";
if (strpbrk($name, '@') != FALSE) {
    echo "There is @";
}
else {
    echo "There isn't @";
}
?>
root at mantoru dot de 07-Feb-2008 07:55
A simpler (and slightly faster) strpbrkpos function:

<?php
function strpbrkpos($haystack, $char_list) {
    $result = strcspn($haystack, $char_list);
    if ($result != strlen($haystack)) {
        return $result;
    }
    return false;
}
?>
pzb at novell dot com 28-Jul-2007 04:09
One undocumented requirement:
If $char_list contains null characters ("\0"), only characters before the null will be used.  While PHP handles nulls in strings just fine, the data is passed to a function that is not null safe.
Evan 03-Jul-2007 08:33
If you're not looking to duplicate the rest of the string, but instead just want the offset, in the spirit of the str*pos() functions:

<?php

function strpbrkpos($s, $accept) {
  $r = FALSE;
  $t = 0;
  $i = 0;
  $accept_l = strlen($accept);

  for ( ; $i < $accept_l ; $i++ )
    if ( ($t = strpos($s, $accept{$i})) !== FALSE )
      if ( ($r === FALSE) || ($t < $r) )
        $r = $t;

  return $v;
}

?>
user at example dot net 03-Jul-2007 12:25
For PHP versions before 5:

<?php

    function strpbrk( $haystack, $char_list )
    {
        $strlen = strlen($char_list);
        $found = false;
        for( $i=0; $i<$strlen; $i++ ) {
            if( ($tmp = strpos($haystack, $char_list{$i})) !== false ) {
                if( !$found ) {
                    $pos = $tmp;
                    $found = true;
                    continue;
                }
                $pos = min($pos, $tmp);
            }
        }
        if( !$found ) {
            return false;
        }
        return substr($haystack, $pos);
    }

?>

Sadly this is about ten times slower than the native implementation.
jamie dot mcardle at stpetersgv dot org 07-Jun-2007 02:54
I wanted to use this function to look for an @ in a db entry - didn't work because I don't have this version of PHP yet, but I thought I had my issue licked. Darn it.
aidan at php dot net 21-Aug-2004 01:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
strncmp
strpos
Обработка строк


Возвращает позицию первого вхождения подстроки

strpbrk
strrchr
Обработка строк
PHP Manual

strpos

(PHP 4, PHP 5)

strpos — Возвращает позицию первого вхождения подстроки

Описание

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

Ищет позицию первого вхождения подстроки needle в строку haystack.

Список параметров

haystack

Строка, в которой производится поиск

needle

Если needle не является строкой, он приводится к целому и трактуется как код символа.

offset

Если этот параметр указан, то поиск будет начат с указанного количества символов с начала строки. В отличии от strrpos() и strripos() данный параметр не может быть отрицательным.

Возвращаемые значения

Возвращает позицию, в которой находится искомая строка, относительно начала строки haystack (независимо от смещения (offset). Также обратите внимание на то, что позиция строки отсчитывается от 0, а не от 1.

Возвращает FALSE, если искомая строка не найдена.

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Использование ===

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Заметьте, что используется ===.  Использование == не даст верного
// результата, так как 'a' находится в нулевой позиции.
if ($pos === false) {
    echo "Строка '$findme' не найдена в строке '$mystring'";
} else {
    echo "Строка '$findme' найдена в строке '$mystring'";
    echo " в позиции $pos";
}
?>

Пример #2 Использование !==

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Оператор !== также можно использовать.  Использование != не даст верного
// результата, так как 'a' находится в нулевой позиции. Выражение (0 != false) приводится
// к false.
if ($pos !== false) {
     echo "Строка '$findme' найдена в строке '$mystring'";
         echo " в позиции $pos";
} else {
     echo "Строка '$findme' не найдена в строке '$mystring'";
}
?>

Пример #3 Использование смещения

<?php
// Можно искать символ, игнорируя символы до определенного смещения
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, не 0
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • stripos() - Возвращает позицию первого вхождения подстроки без учета регистра
  • strrpos() - Возвращает позицию последнего вхождения подстроки в строке
  • strripos() - Возвращает позицию последнего вхождения подстроки без учета регистра
  • strstr() - Находит первое вхождение подстроки
  • strpbrk() - Ищет в строке любой символ из заданного набора
  • substr() - Возвращает подстроку
  • preg_match() - Выполняет проверку на соответствие регулярному выражению

User Contributed Notes

mtroy dot student at gmail dot com 25-Apr-2012 04:46
when you want to know how much of substring occurrences, you'll use "substr_count".
But, retrieve their positions, will be harder.
So, you can do it by starting with the last occurrence :

function strpos_r($haystack, $needle)
{
    if(strlen($needle) > strlen($haystack))
        trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);

    $seeks = array();
    while($seek = strrpos($haystack, $needle))
    {
        array_push($seeks, $seek);
        $haystack = substr($haystack, 0, $seek);
    }
    return $seeks;
}

it will return an array of all occurrences a the substring in the string

Example :

$test = "this is a test for testing a test function... blah blah";
var_dump(strpos_r($test, "test"));

// output

array(3) {
  [0]=>
  int(29)
  [1]=>
  int(19)
  [2]=>
  int(10)
}

Paul-antoine
Malézieux.
martijn at martijnfrazer dot nl 25-Feb-2012 03:58
This is a function I wrote to find all occurrences of a string, using strpos recursively.

<?php
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {
    $offset = strpos($haystack, $needle, $offset);
    if($offset === false) {
        return $results;
    } else {
        $results[] = $offset;
        return strpos_recursive($haystack, $needle, ($offset + 1), $results);
    }
}
?>

This is how you use it:

<?php
$string = 'This is some string';
$search = 'a';
$found = strpos_recursive($string, $search);

if($found) {
    foreach($found as $pos) {
        echo 'Found "'.$search.'" in string "'.$string.'" at position <b>'.$pos.'</b><br />';
    }
} else {
    echo '"'.$search.'" not found in "'.$string.'"';
}
?>
rjeggens at ijskoud dot org 24-Jan-2012 07:38
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

strpos() !== false

is a different beast then:

strpos() === true

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
gjh42 - simonokewode at hotmail dot com 07-Nov-2011 07:59
A pair of functions to replace every nth occurrence of a string with another string, starting at any position in the haystack. The first works on a string and the second works on a single-level array of strings, treating it as a single string for replacement purposes (any needles split over two array elements are ignored).

Can be used for formatting dynamically-generated HTML output without touching the original generator: e.g. add a newLine class tag to every third item in a floated list, starting with the fourth item.

<?php
/* String Replace at Intervals   by Glenn Herbert (gjh42)    2010-12-17
 */

//(basic locator by someone else - name unknown)
//strnposr() - Find the position of nth needle in haystack.
function strnposr($haystack, $needle, $occurrence, $pos = 0) {
    return ($occurrence<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurrence-1,strpos($haystack, $needle, $pos) + 1);
}

//gjh42
//replace every nth occurrence of $needle with $repl, starting from any position
function str_replace_int($needle, $repl, $haystack, $interval, $first=1, $pos=0) {
  if ($pos >= strlen($haystack) or substr_count($haystack, $needle, $pos) < $first) return $haystack;
  $firstpos = strnposr($haystack, $needle, $first, $pos);
  $nl = strlen($needle);
  $qty = floor(substr_count($haystack, $needle, $firstpos + 1)/$interval);
  do { //in reverse order
    $nextpos = strnposr($haystack, $needle, ($qty * $interval) + 1, $firstpos);
    $qty--;
    $haystack = substr_replace($haystack, $repl, $nextpos, $nl);
  } while ($nextpos > $firstpos);
  return $haystack;
}
  //$needle = string to find
  //$repl = string to replace needle
  //$haystack = string to do replacing in
  //$interval = number of needles in loop
  //$first=1 = first occurrence of needle to replace (defaults to first)
  //$pos=0 = position in haystack string to start from (defaults to first)

//replace every nth occurrence of $needle with $repl, starting from any position, in a single-level array
function arr_replace_int($needle, $repl, $arr, $interval, $first=1, $pos=0, $glue='|+|') {
  if (!is_array($arr))  return $arr;
  foreach($arr as $key=>$value){
    if (is_array($arr[$key])) return $arr;
  }
  $haystack = implode($glue, $arr);
  $haystack = str_replace_int($needle, $repl, $haystack, $interval, $first, $pos);
  $tarr = explode($glue, $haystack);
  $i = 0;
  foreach($arr as $key=>$value){
    $arr[$key] = $tarr[$i];
    $i++;
  }
  return $arr;
}
?>
If $arr is not an array, or a multilevel array, it is returned unchanged.
Mark Oates 25-Oct-2011 08:36
When using GLOB_BRACE to find files on a local computer, note that including the drive lettername within the braces may cause the behavior to not work as expected:

<?php

$location = "{c:/foo/*.txt,c:/foo/bar/*.txt}"; // < will NOT work

$location = "c:{/foo/*.txt,/foo/bar/*.txt}"; // < works

$location = "c:/{foo/*.txt,foo/bar/*.txt}"; // < works

$location = "{/foo/*.txt,/foo/bar/*.txt}"; // < works

print_r(glob($location, GLOB_BRACE));

?>
jim at terrys dot net 29-Sep-2011 11:53
strpos that accepts an array for $needle

<?php
// strpos that takes an array of values to match against a string
// note the stupid argument order (to match strpos)
function strpos_arr($haystack, $needle) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false) return $pos;
    }
    return false;
}
?>
----------------------------
http://www.show-ip.org
a at bc dot de 23-Jun-2011 08:32
A simple way to get the FIRST occurence of any $needle.
Needed if more than one $needle could occur in $haystack and you want the first occurence of any $needle.
<?php
function strpos_arr($haystack, $needle) {
    $First = strlen($haystack);
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        $pos = strpos($haystack, $what);
        if($pos !== false)
        {
            if($pos < $First) $First = $pos;
        }
    }
    return $First == strlen($haystack) ? false : $First;
}
?>
akarmenia at gmail dot com 05-Mar-2011 04:44
My version of strpos with needles as an array. Also allows for a string, or an array inside an array.

<?php
function strpos_array($haystack, $needles) {
    if ( is_array($needles) ) {
        foreach ($needles as $str) {
            if ( is_array($str) ) {
                $pos = strpos_array($haystack, $str);
            } else {
                $pos = strpos($haystack, $str);
            }
            if ($pos !== FALSE) {
                return $pos;
            }
        }
    } else {
        return strpos($haystack, $needles);
    }
}

// Test
echo strpos_array('This is a test', array('test', 'drive')); // Output is 10

?>
jaimthorn at yahoo dot com 09-Feb-2011 02:09
A complete set of strn*pos functions that look for the nth occurrence of the needle in the haystack. I prefer this implementation of strnpos because it doesn't give visible warnings when supplied with a needle of length 0 (which is, admittedly, non-standard behavior).  Based on a version I [originally posted on 05-MAR-2010]; this new version conforms more to the semantics of strpos.

<?php

/**
 *  This function implements all the strn*pos functions, which return the $nth occurrence of $needle
 *  in $haystack, or false if it doesn't exist / when illegal parameters have been supplied.
 *
 *  @param  string  $haystack       the string to search in.
 *  @param  MIXED   $needle         the string or the ASCII value of the character to search for.
 *  @param  integer $nth            the number of the occurrence to look for.
 *  @param  integer $offset         the position in $haystack to start looking for $needle.
 *  @param  bool    $insensitive    should the function be case insensitive?
 *  @param  bool    $reverse        should the function work its way backwards in the haystack?
 *  @return MIXED   integer         either the position of the $nth occurrence of $needle in $haystack,
 *               or boolean         false if it can't be found.
 */
function strnripos_generic( $haystack, $needle, $nth, $offset, $insensitive, $reverse )
{
    //  If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
    if( ! is_string( $needle ) ) {
        $needle = chr( (int) $needle );
    }

    //  Are the supplied values valid / reasonable?
    $len = strlen( $needle );
    if( 1 > $nth || 0 === $len ) {
        return false;
    }

    if( $insensitive ) {
        $haystack = strtolower( $haystack );
        $needle   = strtolower( $needle   );
    }

    if( $reverse ) {
        $haystack = strrev( $haystack );
        $needle   = strrev( $needle   );
    }

    //  $offset is incremented in the call to strpos, so make sure that the first
    //  call starts at the right position by initially decreasing $offset by $len.
    $offset -= $len;
    do
    {
        $offset = strpos( $haystack, $needle, $offset + $len );
    } while( --$nth  && false !== $offset );

    return false === $offset || ! $reverse ? $offset : strlen( $haystack ) - $offset;
}

/**
 *  @see    strnripos_generic
 */
function strnpos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, false, false );
}

/**
 *  @see    strnripos_generic
 */
function strnipos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, true, false );
}

/**
 *  @see    strnripos_generic
 */
function strnrpos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, false, true );
}

/**
 *  @see    strnripos_generic
 */
function strnripos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, true, true );
}

$haystack = 'Dit is een HoTtentotTentenTentenToonstellingTest!';

echo strnpos  ( $haystack, 't', 5 ), ' === ', strnpos  ( $haystack, 116, 5 ), PHP_EOL;
echo strnipos ( $haystack, 't', 5 ), ' === ', strnipos ( $haystack, 116, 5 ), PHP_EOL;
echo strnrpos ( $haystack, 't', 5 ), ' === ', strnrpos ( $haystack, 116, 5 ), PHP_EOL;
echo strnripos( $haystack, 't', 5 ), ' === ', strnripos( $haystack, 116, 5 ), PHP_EOL;
echo PHP_EOL;
echo strnpos  ( $haystack, 'T', 5 ), ' === ', strnpos  ( $haystack,  84, 5 ), PHP_EOL;
echo strnipos ( $haystack, 'T', 5 ), ' === ', strnipos ( $haystack,  84, 5 ), PHP_EOL;
echo strnrpos ( $haystack, 'T', 5 ), ' === ', strnrpos ( $haystack,  84, 5 ), PHP_EOL;
echo strnripos( $haystack, 'T', 5 ), ' === ', strnripos( $haystack,  84, 5 ), PHP_EOL;
?>
Anonymous 19-Aug-2010 02:50
beware the mindless "if needle is not string" :

root@voice1:/www/voice_ed#php -r 'var_dump(strpos("X1234567",5));'
bool(false)
root@voice1:/www/voice_ed#php -r 'var_dump(strpos("X1234567","5"));'
int(5)
root@voice1:/www/voice_ed#
gambajaja at yahoo dot com 17-Aug-2010 03:25
<?php
$my_array = array ('100,101', '200,201', '300,301');
$check_me_in = array ('100','200','300','400');
foreach ($check_me_in as $value_cmi){
    $is_in=FALSE; #asume that $check_me_in isn't in $my_array
    foreach ($my_array as $value_my){
        $pos = strpos($value_my, $value_cmi);
        if ($pos===0)
            $pos++;
        if ($pos==TRUE){
            $is_in=TRUE;
            $value_my2=$value_my;
            }
    }
    if ($is_in) echo "ID $value_cmi in \$check_me_in I found in value '$value_my2' \n";
}
?>

The above example will output
ID 100 in $check_me_in I found in value '100,101'
ID 200 in $check_me_in I found in value '200,201'
ID 300 in $check_me_in I found in value '300,301'
usulaco at gmail dot com 11-Aug-2010 05:04
Parse strings between two others in to array.

<?php
function g($string,$start,$end){
     preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
     $out = array();

     foreach($m[1] as $key => $value){
       $type = explode('::',$value);
       if(sizeof($type)>1){
          if(!is_array($out[$type[0]]))
             $out[$type[0]] = array();
          $out[$type[0]][] = $type[1];
       } else {
          $out[] = $value;
       }
     }
  return $out;
}
print_r(g('Sample text, [/text to extract/] Rest of sample text [/WEB::http://google.com/] bla bla bla. ','[/','/]'));
?>

results:
Array
(
    [0] => text to extract
    [WEB] => Array
        (
            [0] => http://google.com
        )

)

Can be helpfull to custom parsing :)
james [at] bandit co.nz 28-May-2010 04:38
strpos that accepts an array for $needle

<?php
// strpos that takes an array of values to match against a string
// note the stupid argument order (to match strpos)
function strpos_arr($haystack, $needle) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false) return $pos;
    }
    return false;
}
?>
olmstead31 at yahoo dot com 23-Mar-2010 07:48
I found that whatever I was using as a test with strpos it came out false exept if $pos was == 1

I figured it gives me a numeric value if found else it is null or false
here is what i did to make my code work:

<?php
//EXAMPLE 1:
$quiamime = ',64,68,70,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to 0
if (!is_numeric($posi)){
 //code here
}else{
  //else code here
}

//EXAMPLE 2:
$quiamime = ',68,70,64,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to 6
if (!is_numeric($posi)){
 //code here
}else{
  //else code here
}

//EXAMPLE 3:
$quiamime = ',68,70,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to NULL or FALSE
if (!is_numeric($posi)){
 //code here
}else{
  //else code here
}
?>
daevid at daevid dot com 26-Jan-2010 02:46
Dan Brown and I had a discussion on the PHP list about the speed difference between the popular three string searching techniques. He wrote a simple timing test, and I adapted it further. The end result is that all three are very close and not even noticeable for sets < 1M. Although, technically strpos() is about twice as fast (as the docs allude to above). Here it is for your own amusement and testing purposes.

<?php
for ($i = 0; $i < 1000000; $i++ )
    $o[] =
sprintf('%04d-%02d-%02d',rand(0000,9999),rand(00,99),rand(00,99));
#print_r($o);
echo "array of ".number_format($i)."\n";
###################################################################
$now = microtime(true);
for($i=0;$i<count($o);$i++) {
       if(preg_match('/^[0]{4,}\-/U',$o[$i])) {
               //echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
       }
}
$rank['preg_match'] = (microtime(true) - $now);
###################################################################
$later = microtime(true);
for($i=0;$i<count($o);$i++) {
        if(substr($o[$i],0,4) == "0000") {
                //echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
        }
}
$rank['substr'] = (microtime(true) - $later);
###################################################################
$after = microtime(true);
for($i=0;$i<count($o);$i++) {
        if(strpos($o[$i], '0000') === 0) {
                //echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
        }
}
$rank['strpos'] = (microtime(true) - $after);
###################################################################
asort($rank);
print_r($rank);
?>

array of 10,000
Array
(
    [strpos] => 0.00766682624817
    [substr] => 0.0116670131683
    [preg_match] => 0.0124950408936
)

array of 100,000
Array
(
    [strpos] => 0.0817799568176
    [substr] => 0.120522975922
    [preg_match] => 0.125612974167
)

array of 1,000,000
Array
(
    [strpos] => 0.805890083313
    [substr] => 1.19799995422
    [preg_match] => 1.25615906715
)

I ran out of memory with more than 1M array elements.
Achintya 06-Nov-2009 02:03
A function I made to find the first occurrence of a particular needle not enclosed in quotes(single or double). Works for simple nesting (no backslashed nesting allowed).

<?php
function strposq($haystack, $needle, $offset = 0){
    $len = strlen($haystack);
    $charlen = strlen($needle);
    $flag1 = false;
    $flag2 = false;
    for($i = $offset; $i < $len; $i++){
        if(substr($haystack, $i, 1) == "'"){
            $flag1 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, 1) == '"'){
            $flag2 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, $charlen) == $needle && !$flag1 && !$flag2){
            return $i;
        }
    }
    return false;
}

echo strposq("he'llo'character;\"'som\"e;crap", ";"); //16
?>
yasindagli at gmail dot com 05-Oct-2009 09:05
This function finds postion of nth occurence of a letter starting from offset.

<?php
function nth_position($str, $letter, $n, $offset = 0){
    $str_arr = str_split($str);
    $letter_size = array_count_values(str_split(substr($str, $offset)));
    if( !isset($letter_size[$letter])){
        trigger_error('letter "' . $letter . '" does not exist in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    } else if($letter_size[$letter] < $n) {
        trigger_error('letter "' . $letter . '" does not exist ' . $n .' times in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    }
    for($i = $offset, $x = 0, $count = (count($str_arr) - $offset); $i < $count, $x != $n; $i++){
        if($str_arr[$i] == $letter){
            $x++;
        }
    }
    return $i - 1;
}

echo nth_position('foobarbaz', 'a', 2); //7
echo nth_position('foobarbaz', 'b', 1, 4); //6
?>
digitalpbk [at] gmail.com 30-Sep-2009 08:37
This functions throws an "Offset not contained in string" error if the offset is not in between 0 and the length of string.
KimKha 29-Sep-2009 01:56
The following function use to redirect to URL correctly if the URL have "http://" or "https://", or to relative URL on your site.

<?php
function forward($url = NULL){
    $root = "http://example.com/mydir/";

    if($url == NULL) // Go to homepage
        $url = $root;
    else {
        $pos = strpos($url, "http://");
        if ($pos === false)
            $pos = strpos($url, "https://");

        if ($pos === false || $pos > 0) // Go to relative URL on your site
            $url = $root . $url;
    }

    header('Location:'.$url);
}
?>
juniordez at gmail dot com 16-Sep-2009 09:47
Function to get the string pos ($search), before the position ($pos) passed as parameter.

<?php

function strposReverse( $str, $search, $pos ){
        $str = strrev($str);
        $search = strrev($search);
        $pos = (strlen($str) - 1) - $pos;

        $posRev = strpos( $str, $search, $pos );
        return (strlen($str) - 1) - $posRev - (strlen($search) - 1);
    }
?>
ah dot d at hotmail dot com 11-Aug-2009 01:29
A strpos modification to return an array of all the positions of a needle in the haystack

<?php
function strallpos($haystack,$needle,$offset = 0){
    $result = array();
    for($i = $offset; $i<strlen($haystack); $i++){
        $pos = strpos($haystack,$needle,$i);
        if($pos !== FALSE){
            $offset =  $pos;
            if($offset >= $i){
                $i = $offset;
                $result[] = $offset;
            }
        }
    }
    return $result;
}
?>

example:-

<?php
$haystack = "ASD is trying to get out of the ASDs cube but the other ASDs told him that his behavior will destroy the ASDs world";

$needle = "ASD";

print_r(strallpos($haystack,$needle));

//getting all the positions starting from a specified position

print_r(strallpos($haystack,$needle,34));
?>
bob at mailinator dot com 03-Jun-2009 11:26
I found in a certain bit of my code that under certain circumstances, $needle could be an empty string. This caused strpos to generate an error message.
To get round it, I had to first test to see if $needle was an empty string, and then (ie 'else') go forward and do the strpos test if not.
vbracco at gmail dot com 04-Apr-2009 06:45
This function find position of first occurrence of any $needles in a string $haystack.
Return the position as an integer. If needles is not found, strposa() will return boolean  FALSE.

<?php
function strposa($haystack ,$needles=array(),$offset=0){
    $chr = array();
    foreach($needles as $needle){
        $chr[] = strpos($haystack,$needle,$offset);
    }
    if(empty($chr)) return false;
    return min($chr);
}

$string = "This is my string, very simple.";

echo strposa($string,array(".",","," ")); // 2
echo strposa($string,array("T")); // 0
echo strposa($string,array("Q","W")); // false
?>
lkj dot korn AT NOSPAMgmail d0t c0m 03-Apr-2009 12:57
Note that strpos() will return false if you supply an integer (thus, this presumably applies to float, too) as needle. For example:

<?php
$id = 2; $text = '12345';
if(strpos($text, $id) === false){
  echo 'Yes, is false';
}
?>

Will output 'Yes, is false', a behavior which may not be very intuitive (you'd think it would be covered by PHP's type juggling feature).
This can be easily fixed by adding $id = (string)$id; above the strpos() statement.
teddanzig at yahoo dot com 23-Mar-2009 09:48
routine to return -1 if there is no match for strpos

<?php
//instr function to mimic vb instr fucntion
function InStr($haystack, $needle)
{
    $pos=strpos($haystack, $needle);
    if ($pos !== false)
    {
        return $pos;
    }
    else
    {
        return -1;
    }
}
?>
peterzuzek at gmail dot com 08-Feb-2009 11:01
A function that return the first occurance of a number in a string, if anyone needs it.

Translation/prevod:
Funkcija, ki vrača pozicijo prve številke v besedi, če jo kdo potrebuje.

<?php

    function firstNumPos($str) {
        $poses = array(); // will be storing positions of the numbers

        for($i = 0; $i < 10; ++$i) { // cycle through numbers
            if(($a = strpos($str, (string)$i)) !== false) {
                $poses[] = $a;    // append the position of
                                // the first occurance of the number
            }
        }
        if(isset($poses[0])) { // if array not empty
            sort($poses);        // sort to get the lowest one on the 'bottom'
            return $poses[0];    // and return it
        }
        return false; // otherwise return false

    } // firstNumPos()

?>
jburns131 at jbwebware dot com 27-Dec-2008 04:48
The Situation:

I wanted to return TRUE if strpos returned position 0, and only position 0, without the added overhead of preg_match.

The Solution:

As PHP treats 0 (zero) as NULL, and strpos returns the int 0 (but not NULL), I used type casting and the "===" comparison operator (as it compares types) to resolve my issue.

<?php

$hayStack = "dbHost";
$needle  = "db"
$needlePos = strpos($hayStack, $needle);

if((string)$needlePos === (string)0) {
    echo "db is in position zero";
} else {
    echo "db is NOT in position zero";
}

?>

Returns:
db is in position zero

<?php

$hayStack = "another_db_host";
$needle  = "db"
$needlePos = strpos($hayStack, $needle);

if((string)$needlePos === (string)0) {
    echo "db is in position zero";
} else {
    echo "db is NOT in position zero";
}

?>

This returns:
db is in NOT position zero
Tim 17-Nov-2008 05:52
If you would like to find all occurences of a needle inside a haystack you could use this function strposall($haystack,$needle);. It will return an array with all the strpos's.

<?php
/**
 * strposall
 *
 * Find all occurrences of a needle in a haystack
 *
 * @param string $haystack
 * @param string $needle
 * @return array or false
 */
function strposall($haystack,$needle){

    $s=0;
    $i=0;

    while (is_integer($i)){

        $i = strpos($haystack,$needle,$s);

        if (is_integer($i)) {
            $aStrPos[] = $i;
            $s = $i+strlen($needle);
        }
    }
    if (isset($aStrPos)) {
        return $aStrPos;
    }
    else {
        return false;
    }
}
?>
atomkirk at hotmail dot com 22-Oct-2008 06:19
careful that when you put a strpos in an if statement that you take note that if the string is in the 0 position it will return false, causing your control structure to think its not in the string.
samundra dot shr at gmail dot com 27-Sep-2008 11:40
This is the code,I wrote today, I wanted to strip all the newlines, and format the output in a single line so as to lower the filesize of my php source files.

<?php
/****************************************
@ Code By : Samundra Shrestha
@ Dated : September 28,2008
P.S. Remember to remove all single line comments from the source file
        otherwise the file may get corrupted.
******************************************/
if(!isset($_POST['change']) || !isset($_POST['filename']))
{
    print "<b>".strtoupper("Paste the fullpath of the file")."</b>";
    print "<form name='FrmChange' method='post' action='".$_SERVER['PHP_SELF']."'>";
    print "<input type='textbox' name='filename' size='50px' maxlength='255'>";
    print "<input type='submit' name='change' value='Start'>";
    print "</form>";
}
else
{
$filename=$_POST['filename'];
if(!$fpin=@fopen($filename,"r"))
{
    print "<b>Error ! File Doesn't Exists</b>";
    exit();
}
$text="";
$i=0;
/*Put the contents of file into the string*/
while(!feof($fpin))
{
    $text.=fread($fpin,1024);
}
$count=strlen($text);
$pos=strpos($text,"\n"); //Gives the First occurence of newline
while($i<$count)
{
    if($i<$pos-1)
    {
        $newtext.=$text{$i}; //C Style of String Indexing
    }
    else
    {
        $pos=strpos($text,"\n",$i+1);
    }
    $i++;
}
$newtext.="?>";   //necessary as somehow it is removed from the original source file.
$fp=fopen("sample.txt","wb+");
fwrite($fp,$newtext);
fclose($fp);
print "File Changed Successfully.";
}
?>

The resultant code is all in one new line saved in file sample.txt

I hope, this comes handy to someone.

Cheers,
Samundra Shrestha
mickRacky 19-Sep-2008 11:17
here's a php implementation of stdc++ string class find_first_of using strpos.

<?php
function find_first_of($haystack, $needlesAsString, $offset=0)
{
  $max = strlen($needlesAsString);
  $index = strlen($haystack)+1;
  for($ii=0; $ii<$max;$ii++){
    $result = strpos($haystack,$needlesAsString[$ii], $offset);
    if( $result !== FALSE  && $result < $index)
      $index = $result;
  }
  return ( $index > strlen($haystack)? FALSE: $index);
}
?>

Example:
<?php
$test="Ralph: One of these days, Alice!!";
$look_for=":!,";   // punctuation marks

$ss = 0;
while( $answer=find_first_of($test,$look_for,$ss) ) {
  echo $answer . "\n";
  $ss = $answer+1;
 }
?>

This prints out:
5
24
31
32
Chuzasoft Inc. ARGENTINA 05-Aug-2008 12:16
Hi! Don't you people miss the pretty comparison operator 'LIKE' from mySql in PHP??.
I've made this funtion to emulate that method. It's for search a match string into another String
using the '%' caracter just like you do un the LIKE syntax.
For example:

<?php
$mystring = "Hi, this is good!";
$searchthis = "%thi% goo%";

$resp = milike($mystring,$searchthis);

if ($resp){
   echo "milike = VERDADERO";
} else{
   echo "milike = FALSO";
}

?>
Will print:
milike = VERDADERO

and so on...

this is the function:

<?php
function milike($cadena,$busca){
    if($busca=="") return 1;

    $vi = split("%",$busca);
     $offset=0;
    for($n=0;$n<count($vi);$n++){
        if($vi[$n]== ""){
            if($vi[0]== ""){
                   $tieneini = 1;
            }
        } else {
            $newoff=strpos($cadena,$vi[$n],$offset);
            if($newoff!==false){
                if(!$tieneini){
                    if($offset!=$newoff){
                        return false;
                    }
                }
                if($n==count($vi)-1){
                    if($vi[$n] != substr($cadena,strlen($cadena)-strlen($vi[$n]), strlen($vi[$n]))){
                        return false;
                    }

                } else {
                    $offset = $newoff + strlen($vi[$n]);
                 }
            } else {
                return false;
            }
        }
    }
    return true;
}
?>

Good luck!
paul at thiswayupdesign dot co dot uk 18-Jun-2008 03:48
I wasn't aware of the !== operator, only the === for false. I was using this code on strpos:

<?php
while( ! ($start=@strpos($source,$startTag,$end)) === false) {
  // ...
}
?>

This gave a false if the string was found at position 0, which is weird.

However using

<?php
while(($start=@strpos($source,$startTag,$end)) !== false) {
  // ...
}
?>

Gives no such error and seems to work correctly
pawhox 26-May-2008 06:19
Hello! I was founding a function, which finds any occurence of a string (no: first occurence). I wasn't, so I maked this function! It may be very useful.

<?php

int strnpos(string $haystack, mixed $needle, int $occurence);

?>

Example:

<?php

strnpos("I like the bananas. You like coke. We like chocolate.", "like", 2); // 24

?>

Here's code of this function:

<?php

function strnpos($base, $str, $n)
    {
        if ($n <= 0 || intval($n) != $n || substr_count($base, $str) < $n)  return FALSE;

        $str = strval($str);
        $len = 0;

        for ($i=0 ; $i<$n-1 ; ++$i)
        {
            if ( strpos($base, $str) === FALSE ) return FALSE;

            $len += strlen( substr($base, 0, strpos($base, $str) + strlen($str)) );

            $base = substr($base, strpos($base, $str) + strlen($str) );
        }
        return strpos($base, $str) + $len;
    }

?>
ilaymyhat-rem0ve at yahoo dot com 01-Apr-2008 04:17
This might be useful.

<?php
class String{

    //Look for a $needle in $haystack in any position
    public static function contains(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        return $result !== FALSE;
    }

    //intuitive implementation .. if not found returns -1.
    public static function strpos(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        if ($result === FALSE )
        {
            return -1;
        }
        return $result;
    }

}//String
?>
Suggested re-write for pink WARNING box 11-Jan-2008 03:45
WARNING

As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.

To know that a substring is absent, you must use:

=== FALSE

To know that a substring is present (in any position including 0), you can use either of:

!== FALSE  (recommended)
 > -1  (note: or greater than any negative number)

To know that a substring is at the start of the string, you must use:

=== 0

To know that a substring is in any position other than the start, you can use any of:

 > 0  (recommended)
!= 0  (note: but not !== 0 which also equates to FALSE)
!= FALSE  (disrecommended as highly confusing)

Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false.
Benjie 14-Oct-2007 04:49
str_replace evaluates its arguments exactly once.

for example:

<?php
$page = str_replace("##randompicture##", getrandompicture(), $page);
?>

will call getrandompicture() once, ie it will insert the same random picture for each occurrence of ##randompicture## :(

Here is my quick and dirty workaround:

<?php
function add_random_pictures($text) {

  while (($i = strpos($text, "##randompicture##")) !== false) {
    $text = substr_replace($text, getrandompicture(), $i, strlen("##randompicture##"));
  }
  return $text;

}

$page = add_random_pictures($page);
?>
Wagner Christian 17-Aug-2007 01:11
If you plan to use an integer as needle you need first to convert your integer into a String else it's not going to work.

For exemple :
<?php
$id  = 1;
$my_text = "hel124lo";
$first_position =strpos($my_text ,substr($id,0));
?>

There are for sure some another solutions to convert an integer into a string in php.
user at nomail dot com 15-May-2007 02:21
This is a bit more useful when scanning a large string for all occurances between 'tags'.

<?php
function getStrsBetween($s,$s1,$s2=false,$offset=0) {
    /*====================================================================
    Function to scan a string for items encapsulated within a pair of tags

    getStrsBetween(string, tag1, <tag2>, <offset>

    If no second tag is specified, then match between identical tags

    Returns an array indexed with the encapsulated text, which is in turn
    a sub-array, containing the position of each item.

    Notes:
    strpos($needle,$haystack,$offset)
    substr($string,$start,$length)

    ====================================================================*/

    if( $s2 === false ) { $s2 = $s1; }
    $result = array();
    $L1 = strlen($s1);
    $L2 = strlen($s2);

    if( $L1==0 || $L2==0 ) {
        return false;
    }

    do {
        $pos1 = strpos($s,$s1,$offset);

        if( $pos1 !== false ) {
            $pos1 += $L1;

            $pos2 = strpos($s,$s2,$pos1);

            if( $pos2 !== false ) {
                $key_len = $pos2 - $pos1;

                $this_key = substr($s,$pos1,$key_len);

                if( !array_key_exists($this_key,$result) ) {
                    $result[$this_key] = array();
                }

                $result[$this_key][] = $pos1;

                $offset = $pos2 + $L2;
            } else {
                $pos1 = false;
            }
        }
    } while($pos1 !== false );

    return $result;
}
?>
Rich Deeson 26-Apr-2007 08:58
Here's a somewhat more efficient way to truncate a string at the end of a word. This will end the string on the last dot or last space, whichever is closer to the cut off point. In some cases, a full stop may not be followed by a space eg when followed by a HTML tag.

<?php
    $shortstring = substr($originalstring, 0, 400);
    $lastdot = strrpos($shortstring, ".");
    $lastspace = strrpos($shortstring, " ");
    $shortstring = substr($shortstring, 0, ($lastdot > $lastspace? $lastdot : $lastspace));
?>

Obviously, if you only want to split on a space, you can simplify this:

<?php
    $shortstring = substr($originalstring, 0, 400);
    $shortstring = substr($shortstring, 0, strrpos($shortstring, " "));
?>
sinai [at] simnet [dot] is 11-Apr-2007 05:35
If you want to check for either IE6 or 7 individually.

<?php

function browserIE($version)
{
  if($version == 6 || $version == 7)
  {
    $browser = strpos($_SERVER['HTTP_USER_AGENT'], "MSIE ".$version.".0;");

    if($browser == true)
    {
      return true;
    }
    else
    {
      return false;
    }
  else
  {
    return false;
}

?>
gal_chen123 at hotmail dot co dot il 03-Apr-2007 09:57
this function returns the text between 2 strings:

<?php
function get_between ($text, $s1, $s2) {
    $mid_url = "";
    $pos_s = strpos($text,$s1);
    $pos_e = strpos($text,$s2);
    for ( $i=$pos_s+strlen($s1) ; ( ( $i < ($pos_e)) && $i < strlen($text) ) ; $i++ ) {
        $mid_url .= $text[$i];
    }
    return $mid_url;
}
?>

if $s1 or $s2 are not found, $mid_url will be empty
to add an offset, simply compare $pos_s to the offset, and only let it continue if the offset is smaller then $pos_s.
jamie at jamiechong dot ca 19-Jan-2007 12:15
Try this function to find the first position of needle before a given offset.

For example:
<?php
$s = "This is a test a is This";
$offset = strpos($s, "test");

strnpos($s, "is", $offset);  // returns 17
strnpos($s, "is", -$offset); // returns 5

// Works just like strpos if $offset is positive.
// If $offset is negative, return the first position of needle
// before before $offset.
function strnpos($haystack, $needle, $offset=0)
{
    if ($offset>=0)
        $result=strpos($haystack, $needle, $offset);
    else
    {
        $offset=strlen($haystack)+$offset;
        $haystack=strrev($haystack);
        $needle=strrev($needle);
        $result=strpos($haystack, $needle, $offset);
        if ($result!==false)
        {
            $result+=strlen($needle);
            $result=strlen($haystack)-$result;
        }
    }
    return $result;
}

?>
koteskie at gmail dot com 18-Dec-2006 02:31
I've been looking at previous posts and came up with this function to find the start and end off an certain occurance or all occurances of needle within haystack.

I've made some minor tweaks to the code itself, like  counting the length of needle only once and counting the result set array instead of using a count variable.

I also added a length parameter to the result set to use in a following substr_replace call etc...

<?php

function strpos_index($haystack = '',$needle = '',$offset = 0,$limit = 99,$return = null)
{
    $length = strlen($needle);
    $occurances = array();
    while((($count = count($occurances)) < $limit) && (false !== ($offset = strpos($haystack,$needle,$offset))))
    {
        $occurances[$count]['length'] = $length;
        $occurances[$count]['start'] = $offset;
        $occurances[$count]['end'] = $offset = $offset + $length;
    }
    return $return === null ? $occurances : $occurances[$return];
}

?>
spinicrus at gmail dot com 14-Oct-2006 10:58
if you want to get the position of a substring relative to a substring of your string, BUT in REVERSE way:

<?php

function strpos_reverse_way($string,$charToFind,$relativeChar) {
    //
    $relativePos = strpos($string,$relativeChar);
    $searchPos = $relativePos;
    $searchChar = '';
    //
    while ($searchChar != $charToFind) {
        $newPos = $searchPos-1;
        $searchChar = substr($string,$newPos,strlen($charToFind));
        $searchPos = $newPos;
    }
    //
    if (!empty($searchChar)) {
        //
        return $searchPos;
        return TRUE;
    }
    else {
        return FALSE;
    }
    //
}

?>
admin at xylotspace dot com 26-Sep-2006 07:33
Yay! I came up with a very useful function. This finds a beginning marker and an ending marker (the first after the beginning marker), and returns the contents between them. You specify an initial position in order to tell it where to start looking. You can use a while() or for() loop to get all occurence of a certain string within a string (for example, taking all hyperlinks in a string of HTML code)...

<?php
function get_middle($source, $beginning, $ending, $init_pos) {
    $beginning_pos = strpos($source, $beginning, $init_pos);
    $middle_pos = $beginning_pos + strlen($beginning);
    $ending_pos = strpos($source, $ending, $beginning_pos + 1);
    $middle = substr($source, $middle_pos, $ending_pos - $middle_pos);
    return $middle;
}
?>

For example, to find the URL of the very first hyperlink in an HTML string $data, use:

$first_url = get_middle($data, '<a href="', '"', 0);

It's done wonders for scraping HTML pages with certain tools on my website.
Virtual Hunter root(at)autocrash(dot)ru 23-Dec-2005 07:44
If you want to find positions of all needle's in haystack,
you can use this one:

<?php
while (($pos=strpos($haystack,$needle,$pos+1))!==false) $pos_array[$i++]=$pos;
?>

But mind, that it will find from second char. You must use $pos=-1; before you want search from first char.

<?php
$haystack="one two three one two three one two three one two three one";
$needle="one";

$pos=-1;
while (($pos=strpos($haystack,$needle,$pos+1))!==false) $pos_array[$i++]=$pos;
?>

RESULT:

$pos_array[0] = 0
$pos_array[1] = 14
$pos_array[2] = 28
$pos_array[3] = 42
$pos_array[4] = 56
csaba at alum dot mit dot edu 21-Nov-2005 06:00
<?php
function nthPos ($str, $needles, $n=1) {
    //    finds the nth occurrence of any of $needles' characters in $str
    //  returns -1 if not found; $n<0 => count backwards from end
    //  e.g. $str = "c:\\winapps\\morph\\photos\\Party\\Phoebe.jpg";
    //       substr($str, nthPos($str, "/\\:", -2)) => \Party\Phoebe.jpg
    //       substr($str, nthPos($str, "/\\:", 4)) => \photos\Party\Phoebe.jpg
    $pos = -1;
    $size = strlen($str);
    if ($reverse=($n<0)) { $n=-$n; $str = strrev($str); }
    while ($n--) {
    $bestNewPos = $size;
    for ($i=strlen($needles)-1;$i>=0;$i--) {
        $newPos = strpos($str, $needles[$i], $pos+1);
        if ($newPos===false) $needles = substr($needles,0,$i) . substr($needles,$i+1);
        else $bestNewPos = min($bestNewPos,$newPos); }
    if (($pos=$bestNewPos)==$size) return -1; }
    return $reverse ? $size-1-$pos : $pos;
}
?>

Csaba Gabor from Vienna
dale at ucsc dot edu 11-Nov-2005 02:28
if you want need a fast function to find the first occurrence of any ch element of an needle array this function might be of use:
<?php
$eurl = strpos_needle_array($text, array('"'=>0,'\''=>0,'>'=>0, ' '=>0, "\n"=>0), $surl);

function strpos_needle_array(& $text, $needle_ary, $offset=0){
    for($ch_pos=$offset;$ch_pos<strlen($text);$ch_pos++){
        if(isset($needle_ary[$text[$ch_pos]])){
            return $ch_pos;
        }
    }
    return false;
}
?>
info at quantummechanic dot com 06-Oct-2005 05:42
this function takes a space-deliminted string as a list of potential needles and runs it against another string as a haystack.

the number of positive matches of needles within the haystack is returned as a rounded percentile.

<?php
function keyMatch($needles,$haystack) {
    $nArray=split(" ",$needles);
    $found=0;
    $best=count($nArray);
      for($i=0;$i<count($nArray);$i++) {
        $pzn=strpos(strtoupper($haystack),strtoupper($nArray[$i]));
        if ($pzn>-1) { $found++; }
       }
    $pct=($found*100)/$best;
    return round($pct);
}

$test = keyMatch("the quick wolf","the quick brown fox jumps over the lazy dog");
echo($test);
?>

RESULT:

67

(because "the" and "quick" were found but "wolf" was not)
arias at elleondeoro dot com 07-Feb-2005 06:33
If you want to get all positions in an array, you can use this function. If the optional parameter count is especified, the function will put there the number of matches.

<?php
function strallpos($pajar, $aguja, $offset=0, &$count=null) {
  if ($offset > strlen($pajar)) trigger_error("strallpos(): Offset not contained in string.", E_USER_WARNING);
  $match = array();
  for ($count=0; (($pos = strpos($pajar, $aguja, $offset)) !== false); $count++) {
    $match[] = $pos;
    $offset = $pos + strlen($aguja);
  }
  return $match;
}
?>
admin at bwongar dot com 20-Jan-2005 06:17
I created a useful function that returns an array with the positions within a string. For more info, read the comments:
<?php
// Returns an array in this fashion:
// array(count => position)
function strpos_array($haystack, $needle){
   $kill    = 0;    // Kills while loop when changed
   $offset    = 0;    // Offset for strpos()
   $i        = 0;    // Counter, not iterator

   while ($kill === 0) {
       $i++;
       $result = strpos($haystack, $needle, $offset);

       if ($result === FALSE) {        // If result is false (no more instances found), kill the while loop
           $kill = 1;
       } else {
           $array[$i] = $result;    // Set array
           $offset = $result + 1;    // Offset is set 1 character after previous occurence
       }

   }

   return $array;

}
?>
takapz at flor dot it 03-Dec-2004 09:28
here a little function for tag parsing

<?php
function parsing($tag,$string) {
        $start=strpos($string,"<" . $tag . ">" );
        $start=$start + strlen("<" . $tag . ">");
         $end=(strpos($string, "</" . $tag . ">"));
         $num=  ($end - $start);
         $valore=substr($string,$start,$num);
          return $valore;
}
?>
philip 25-Aug-2004 03:52
Many people look for in_string which does not exist in PHP, so, here's the most efficient form of in_string() (that works in both PHP 4/5) that I can think of:
<?php
function in_string($needle, $haystack, $insensitive = 0) {
    if ($insensitive) {
        return (false !== stristr($haystack, $needle)) ? true : false;
    } else {
        return (false !== strpos($haystack, $needle))  ? true : false;
    }
}
?>
php .at. wwwcrm .dot. com 19-Aug-2004 10:33
Watch out for type!

The following code will return "not matched", which is a little counter-intuitive.

<?php
$val1=123;
$val2="123,456,789";
if (strpos($val2, $val1)!==false) echo "matched";
else echo "not matched";
?>

When $val1 is cast to string, it behaves as you might expect:

<?php
$val1=(string)123;
$val2="123,456,789";
if (strpos($val2, $val1)!==false) echo "matched";
else echo "not matched";
?>

Hope this saves someone the couple of hours that it took me to spot it :-)

Regards,
Alex Poole
bishop 21-Apr-2004 03:38
Code like this:
<?php
if (strpos('this is a test', 'is') !== false) {
    echo "found it";
}
?>

gets repetitive, is not very self-explanatory, and most people handle it incorrectly anyway. Make your life easier:

<?php
function str_contains($haystack, $needle, $ignoreCase = false) {
    if ($ignoreCase) {
        $haystack = strtolower($haystack);
        $needle   = strtolower($needle);
    }
    $needlePos = strpos($haystack, $needle);
    return ($needlePos === false ? false : ($needlePos+1));
}
?>

Then, you may do:
<?php
// simplest use
if (str_contains('this is a test', 'is')) {
    echo "Found it";
}

// when you need the position, as well whether it's present
$needlePos = str_contains('this is a test', 'is');
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}

// you may also ignore case
$needlePos = str_contains('this is a test', 'IS', true);
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}
?>
amy_w at gmx dot de 02-Apr-2004 09:41
You can use this function to find ANY occurence of a string in an array - no matter if it is just part of one of the array elements.

it returns the key of the first found occurence or false

<?php
function search_array($needle,$haystacks) {
    $found=false;
    foreach ($haystacks as $key => $haystack) {
        if (!(strpos($haystack,$needle)===false)) {
            $found=$key;
            break;
        }
    }
    return ($found);
}
?>
ebypdx at comcast dot net 09-Mar-2004 05:26
counting the occurrences of a substring, recursive-style instead of looping.

<?php
function countSubstrs($haystack, $needle)
{
    return (($p = strpos($haystack, $needle)) === false) ? 0 : (1 + countSubstrs(substr($haystack, $p+1), $needle));
}
?>
kingbusiness at hotmail dot com 18-Dec-2003 10:34
A simple function to find the number of occurances in a string within a string

<?php
function StringCount($searchstring, $findstring)
{
    return (strpos($searchstring, $findstring) === false ? 0 :  count(split($findstring, $searchstring)) - 1);
}
?>
justin at visunet dot ie 01-Oct-2003 09:20
Function:
stripos_words($haystack,'words in string')

This function finds and reports positions of all words in supplied haystack. It returns the results as an array. The array has the following structure.

Array
(
    [69] => Array
        (
            [start] => 69
            [end] => 74
            [word] => honey
        )

    [226] => Array
        (
            [start] => 226
            [end] => 232
            [word] => cobweb
        )
}

Where, for convenience, the main key also contains the positions of each found word occurrence.

If you want the main key to be 0,1,2,3,etc then set the third parameter ($pos_as_key) to false;

Hope this is of help to someone.

Cheers,
Justin :)

<?php
function stripos_words($haystack,$needles='',$pos_as_key=true)
{
    $idx=0; // Used if pos_as_key is false

    // Convert full text to lower case to make this case insensitive
    $haystack = strtolower($haystack);

    // Split keywords and lowercase them
    foreach ( preg_split('/[^\w]/',strtolower($needles)) as $needle )
    {
        // Get all occurences of this keyword
        $i=0; $pos_cur=0; $pos_found=0;
        while (  $pos_found !== false && $needles !== '')
        {
            // Get the strpos of this keyword (if thereis one)
            $pos_found = strpos(substr($haystack,$pos_cur),$needle);
            if ( $pos_found !== false )
            {
                // Set up key for main array
                $index = $pos_as_key ? $pos_found+$pos_cur : $idx++;

                // Populate main array with this keywords positional data
                $positions[$index]['start'] = $pos_found+$pos_cur;
                $pos_cur += ($pos_found+strlen($needle));
                $positions[$index]['end']   = $pos_cur;
                $positions[$index]['word'] = $needle;
                $i++;
            }
        }
    }

    // If we found anything then sort the array and return it
    if ( isset($positions) )
    {
        ksort($positions);
        return $positions;
    }

    // If nothign was found then return false
    return false;
}
?>
strpbrk
strrchr
Обработка строк


Находит последнее вхождение символа в строке

strpos
strrev
Обработка строк
PHP Manual

strrchr

(PHP 4, PHP 5)

strrchr — Находит последнее вхождение символа в строке

Описание

string strrchr ( string $haystack , mixed $needle )

Возвращает подстроку строки haystack начиная с последнего вхождения needle до конца строки.

Список параметров

haystack

Строка, в которой производится поиск

needle

Если needle состоит более чем из одного символа, используется только первый символ. Это поведение отличается от strstr().

Если needle не является строкой, он приводится к целому и трактуется как код символа.

Возвращаемые значения

Функция возвращает фрагмент строки, или FALSE, если подстрока needle не найдена.

Список изменений

Версия | Описание
4.3.0 | Эта функция теперь бинарно-безопасна.

Примеры

Пример #1 Пример использования strrchr()

<?php
// получить последнюю директорию из $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// получить все после последнего перевода строки
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strstr() - Находит первое вхождение подстроки
  • strrpos() - Возвращает позицию последнего вхождения подстроки в строке

User Contributed Notes

matthewkastor at live dot com 30-Mar-2011 01:07
<?php
/**
 * Removes the preceeding or proceeding portion of a string
 * relative to the last occurrence of the specified character.
 * The character selected may be retained or discarded.
 *
 * Example usage:
 * <code>
 * $example = 'http://example.com/path/file.php';
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);
 * foreach($cwd_relative as $string) {
 *     echo "$string <br>".PHP_EOL;
 * }
 * </code>
 *
 * Outputs:
 * <code>
 * http://example.com/path/
 * http://example.com/path
 * /file.php
 * file.php
 * </code>
 *
 * @param string $character the character to search for.
 * @param string $string the string to search through.
 * @param string $side determines whether text to the left or the right of the character is returned.
 * Options are: left, or right.
 * @param bool $keep_character determines whether or not to keep the character.
 * Options are: true, or false.
 * @return string
 */
function cut_string_using_last($character, $string, $side, $keep_character=true) {
    $offset = ($keep_character ? 1 : 0);
    $whole_length = strlen($string);
    $right_length = (strlen(strrchr($string, $character)) - 1);
    $left_length = ($whole_length - $right_length - 1);
    switch($side) {
        case 'left':
            $piece = substr($string, 0, ($left_length + $offset));
            break;
        case 'right':
            $start = (0 - ($right_length + $offset));
            $piece = substr($string, $start);
            break;
        default:
            $piece = false;
            break;
    }
    return($piece);
}
?>
corey [works at] effim [dot coooom] 28-Sep-2009 10:03
Easiest way to get the domain off of an email:

<?php

$domain = strrchr($email, '@');

// gets @gmail.com, with the preceding @.

?>

It's not perfect (see above in the manual), but it's pretty damn good.
franzemmanuel at gmail dot com 23-May-2009 05:30
this functions returns the full path of the current directory.

<?php

function CurrentFullPath()
{
    $root = $_SERVER['DOCUMENT_ROOT'] ;
    $self = $_SERVER['PHP_SELF'] ;
    return $root.mb_substr($self,0,-mb_strlen(strrchr($self,"/"))) ;
}

echo CurrentFullPath() ;

/*

If path is $path = "/home/me/www/pictures/control.php" ;

It will return :

/home/me/www/pictures

*/

?>
pnoexz at gmail dot com 05-Nov-2008 07:07
Here is my function that returns the type of a file. I fint it easier to add other types of files, and simplier than the rest i have seen around.

<?php
function findExt($filename){
    $exts = array(
        '.jpg' => 'image',
        '.png' => 'image',
        '.php' => 'php',
        '.html' => 'html',
        '.swf' => 'flash',
        '.gz' => 'compressed',
        '.tar' => 'compressed',
    );
    $ext = strrchr($filename,'.');
    if ($exts[$ext]) { return $exts[$ext]; }
    else { return "unknown"; }
}
?>
equand at gmail dot com 29-May-2008 07:29
a KiSS variant of a previous note

<?php
function fcheck($f = "test.doc")
{
 $fd = array(".xls" => "Microsoft Excel Worksheet",".doc" => "Microsoft Word Document",".pdf" => "Adobe Reader PDF File");
 $s = $fd[strrchr($f,'.')];
 if (!empty($s))
 {
  return $s;
 }
 else
 {
  return "Unknown file type";
 }
}

?>
Emmanuel Quiban 21-May-2008 07:32
strrchr is useful also in determining file extensions.

Here is a sample code that determines the file type based on its file extension. This is useful in displaying the files in your page, without using the database for the file description list.

<?php
 /* File Extension Display using arrays
     by: Emmanuel Quiban (Philippines)
     BSCS 2002, AdU
     21-May-2008
 */

 // Sample file
 $filesample = "Mydocu.doc";

 //Array for file description. You can expand the array list further with other file types you want
 $filedes = array(
                "Microsoft Excel Worksheet",
                "Microsoft Word Document",
                "Adobe Reader PDF File");

 //Array for file extensions. Please take note that positions between the two arrays should be in sync with each other for correct file description.
 $fileext = array(".xls", ".doc", ".pdf");

 //This gets the file extension
 $ext = strrchr($filesample,'.');

 //This conditional statement checks if the file extension given is in the array and matches it with the file description
 if (in_array($ext,$fileext)) {

        //Search the array
        $ext2 = array_search($ext, $fileext);

        //Since the result of the array_search is in integer, you can now assign it as an array value
        $filetype = $filedes[$ext2];

        //Show the result
        echo $filetype;
 } else {
        $filetype = "Unknown file type";
 }
?>
-----
The output of the script above is:
Microsoft Word Document

Let's say even if the filename looks like "My.Docu.doc", strrchr still gets the value ".doc" because it gets the last occurance of the dot.
-----

You can also make it as a function, like this:

<?php
 /* File Extension Display using arrays
     by: Emmanuel Quiban (Philippines)
     BSCS 2002, AdU
     21-May-2008
 */
 function getFileType($yourfile){

 $filedes = array(
                "CompuServe GIF Image",
                "JPEG Image",
                "Portable Network Graphics (PNG) Image"
                );

 $fileext = array(".gif",".jpg",".png");

 $ext = strrchr($yourfile,'.');
 if (in_array($ext,$fileext)) {
        $ext2 = array_search($ext, $fileext);
        $filetype = $filedes[$ext2];
 } else {
        $filetype = "Unknown file type";
 }

 return $filetype;
 }
?>
subbz2k at yahoo dot de 01-Aug-2007 04:32
i just recently did a function, that uses strrchr to format - let's say a currency - with 2 decimals. can also be done using number_format but you may NOT always want an automatic rounding of your decimals. thats there this function comes in handy:

<?php
function formatTwoDecimals($value, $trim)
{
   $after_comma = substr(strrchr($value, $trim), 0, 3);
   $in_front_of_comma = (int) $value;
   $final = $in_front_of_comma . $after_comma;

   return $final;
}

echo formatTwoDecimals("365.6078985", ".");
?>

this will produce
365.60

instead of
365.61
which will show up then you use number_format.
repley at freemail dot it 11-Aug-2006 06:57
Final get file name and extension into an array with or without dot, using strrchr and strrchr_reverse.
Note our use of !==. Now work if the position of $needle in $haystack was the 0th (first) character like ".htaccess"
<?
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   //Note our use of !==. Now work if the position of $needle in $haystack was the 0th (first) character.
   if(strrpos($haystack, $needle) !== false){
       //Everything before last $needle in $haystack.
       $left =  substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);
       //Switch value of $r_inclusive from 0 to 1 and viceversa.
       $r_inclusive = ($r_inclusive == 0) ? 1 : 0;
       //Everything after last $needle in $haystack.
       $right =  substr(strrchr($haystack, $needle), $r_inclusive);
       //Return $left and $right into an array.
       $a = array($left, $right);
       return $a;
   }else{
       return false;
   }
}
?>

Repley
readless at gmx dot net 06-Jun-2006 07:55
to: repley at freemail dot it

the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany

<?php
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if(strrpos($haystack, $needle)){
       //Everything before last $needle in $haystack.
       $left =  substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);

       //Switch value of $r_inclusive from 0 to 1 and viceversa.
       $r_inclusive = ($r_inclusive == 0) ? 1 : 0;

       //Everything after last $needle in $haystack.
       $right =  substr(strrchr($haystack, $needle), $r_inclusive);

       //Return $left and $right into an array.
       return array($left, $right);
   } else {
       if(strrchr($haystack, $needle)) return array('', substr(strrchr($haystack, $needle), $r_inclusive));
       else return false;
   }
}
?>
repley at freemail dot it 18-May-2006 03:09
Get file name and extension into an array with or without dot, using strrchr and strrchr_reverse.

<?
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if(strrpos($haystack, $needle)){
       //Everything before last $needle in $haystack.
       $left =  substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);

       //Switch value of $r_inclusive from 0 to 1 and viceversa.
       $r_inclusive = ($r_inclusive == 0) ? 1 : 0;

       //Everything after last $needle in $haystack.
       $right =  substr(strrchr($haystack, $needle), $r_inclusive);

       //Return $left and $right into an array.
       $a = array($left, $right);
       return $a;
   }else{
       return false;
   }
}

//start test
$haystack = "unknown.txt.log.......gif.....jpeg";
$needle = ".";
$l_inclusive = 1; //1 for inclusive mode, 0 for NOT inclusive mode
$r_inclusive = 1; //1 for inclusive mode, 0 for NOT inclusive mode

$a = strxchr($haystack, $needle, $l_inclusive, $r_inclusive);
if($a){echo "Left: <strong>" . $a[0] . "</strong><br /> Right: <strong>" . $a[1] . "</strong>";}else{echo "Failed!";}
//end test
?>

Thanks to all.

Repley
sekati at gmail dot com 08-Apr-2006 05:43
just a small addition to carlos dot lage at gmail dot com note which makes it a bit more useful and flexible:

<?php
// return everything up to last instance of needle
// use $trail to include needle chars including and past last needle
function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
// usage:
$ns = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 0));
$ns2 = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 1));
echo($ns . "<br>" . $ns2);
?>
freakinunreal at hotmail dot com 24-Dec-2005 10:54
to marcokonopacki at hotmail dot com.

I had to make a slight change in your function for it to return the complete needle inclusive.

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

   // Returns everything before $needle (inclusive).
   //return substr($haystack,0,strpos($haystack,$needle)+1);
   // becomes
   return substr($haystack,0,strpos($haystack,$needle)+strlen($needle));
}

Note: the +1 becomes +strlen($needle)

Otherwise it only returns the first character in needle backwards.
arcesis - gmail - com 11-Nov-2005 06:26
A quick way to get file's extension (if it has one, otherwise you get an empty string), which can be used when you want to rename the file but keep the old extension. Or for similar purposes. Temporary variable is used just because it's slightly faster to store the value than to run the strrchr() function again.

<?php
$ext = substr(($t=strrchr("file.ext",'.'))!==false?$t:'',1);
?>
Primo Anderson Do S�tio 29-Jul-2005 10:24
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );

Result:
.php

$other_filename = 'strrchr_test.asp.php';
print  strrchr( $other_filename, '.' );

Result:
.php
carlos dot lage at gmail dot com 03-Apr-2005 11:45
I used dchris1 at bigpond dot net dot au 's reverse strrchr and reduced it to one line of code and fixed it's functionality - the real strrchr() returns FALSE if the needle is not found, not the haystack :)

<?php
// reverse strrchr()
function reverse_strrchr($haystack, $needle)
{
                return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
}
?>
dchris1 at bigpond dot net dot au 16-Feb-2004 07:16
The function provided by marcokonopacki at hotmail dot com isn't really a reverse-version of strrchr(), rather a reverse version of strchr(). It returns everything from the start of $haystack up to the FIRST instance of the $needle. This is basically a reverse of the behavior which you expect from strchr(). A reverse version of strrchr() would return everything in $haystack up to the LAST instance of $needle, eg:

<?php
// reverse strrchr() - PHP v4.0b3 and above
function reverse_strrchr($haystack, $needle)
{
    $pos = strrpos($haystack, $needle);
    if($pos === false) {
        return $haystack;
    }
    return substr($haystack, 0, $pos + 1);
}
?>

Note that this function will need to be modified slightly to work with pre 4.0b3 versions of PHP due to the return type of strrpos() ('0' is not necessarily 'false'). Check the documentation on strrpos() for more info.

A function like this can be useful for extracting the path to a script, for example:

<?
$string = "/path/to/the/file/filename.php";

echo reverse_strrchr($string, '/'); // will echo "/path/to/the/file/"
?>
andfarm at thibs dot menloschool dot org 23-May-2003 04:24
strrchr is also very useful for finding the extension of a file. For example:

$ext = strrchr($filename, ".");

and $ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "evilfile.jpg.vbs", then this construction will just return the last extension.
marcokonopacki at hotmail dot com 14-Apr-2003 12:43
<?

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

    // Returns everything before $needle (inclusive).
    return substr($haystack,0,strpos($haystack,$needle)+1);

}

$string = "FIELD NUMBER(9) NOT NULL";

echo strrrchr($string,")"); // Will print FIELD (9)

?>
juancri at tagnet dot org 16-Nov-2002 03:02
this functions returns the name of the current directory.
<?php
function currentd() {
    return substr(strrchr(`pwd`, '/'), 1);
}
?>
strpos
strrev
Обработка строк


РџРµСЂРµРІРѕСЂР°С‡РёРІР°РµС‚ СЃС‚СЂРѕРєСѓ Р·Р°РґРѕРј РЅР°РїРµСЂРµРґ

strrchr
strripos
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє
PHP Manual

strrev

(PHP 4, PHP 5)

strrev — РџРµСЂРµРІРѕСЂР°С‡РёРІР°РµС‚ СЃС‚СЂРѕРєСѓ Р·Р°РґРѕРј РЅР°РїРµСЂРµРґ

РћРїРёСЃР°РЅРёРµ

string strrev ( string $string )

Р’РѕР·РІСЂР°С‰Р°РµС‚ СЃС‚СЂРѕРєСѓ string, РїРµСЂРµРІРµСЂРЅСѓС‚СѓСЋ Р·Р°РґРѕРј РЅР°РїРµСЂРµРґ.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

string

РџРµСЂРµРІРѕСЂР°С‡РёРІР°РµРјР°СЏ СЃС‚СЂРѕРєР°.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ РїРµСЂРµРІРµСЂРЅСѓС‚СѓСЋ СЃС‚СЂРѕРєСѓ.

РџСЂРёРјРµСЂС‹

РџСЂРёРјРµСЂ #1 РџСЂРёРјРµСЂ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёСЏ strrev()

<?php
echo strrev("Hello world!"); // РІС‹РІРѕРґРёС‚ "!dlrow olleH"
?>

User Contributed Notes

dyaskur at gmail dot com 27-Mar-2012 11:09
This is funny function for write upside down:
<?php

function strflip($text)
{
  $text=strrev($text);
  $text=strtolower($text);

$arr = array(
"a" => "&#x250;",
"b" => "q",
"c" => "&#x254;",
"d" => "p",
"e" => "&#x01DD;",
"f" => "&#x25F;",
"g" => "&#x387;",
"h" => "&#x0265;",
"i" => "&#x0131;",
"j" => "&#x027E;",
"k" => "&#x029E;",
"l" => "&#x0283;",
"m" => "&#x026F;",
"n" => "u",
"p" => "d",
"q" => "b",
"r" => "&#x0279;",
"t" => "&#x0287;",
"u" => "n",
"v" => "&#x028C;",
"w" => "&#x028D;",
"y" => "&#x028E;",
"B" => "D"
);
$result = strtr($text,$arr);
return $result;
}
$text = "My name is Dyas Yaskur";
echo strflip($text); //Й№nКћsЙђКЋ sЙђКЋp sД± ЗќЙЇЙђu КЋЙЇ
?>
qeremy [atta] gmail [dotta] com 24-Feb-2012 04:34
An easy way for unicode string reversing;

<?php
function strrev_utf8($str) {
    return join("", array_reverse(
        preg_split("//u", $str)
    ));
}

$str = "Ећeker yГўrim!"; // My sugar love
echo $str."\n";
echo strrev($str)."\n"; // !mirпїЅпїЅy rekeпїЅпїЅ
echo strrev_utf8($str); // !mirГўy rekeЕћ
?>
lwc at trashymail dot com 19-Jun-2008 05:00
manfred at werkzeugH dot at, your version works, but do you think it has an advantage over mine? Just wondering if I should update my scripts.

carmel.alex at gmail.com, your version fails with utf8_strrev($string, true). It's something about spaces.

For example, you turn
This software was protected by 2000 patents since 2001
into
2001 ecnis stnetap2000 yb detcetorp saw erawtfos sihT

(note the "stnetap2000").
manfred at werkzeugH dot at 27-May-2008 04:35
here is my version for strings with utf8-characters represented as numerical entities  (e.g. &#1234;)

function utf8_entities_strrev($str, $preserve_numbers = true)
{
  //split string into string-portions (1 byte characters, numerical entitiesor numbers)

  $parts=Array();
  while ($str)
  {
    if ($preserve_numbers && preg_match('/^([0-9]+)(.*)$/',$str,$m))
    {
      // number-flow
      $parts[]=$m[1];
      $str=$m[2];
    }
    elseif (preg_match('/^(\&#[0-9]+;)(.*)$/',$str,$m))
    {
      // numerical entity
      $parts[]=$m[1];
      $str=$m[2];
    }
    else
    {
      $parts[]=substr($str,0,1);
      $str=substr($str,1);
    }
  }

  $str=implode(array_reverse($parts),"");

  return $str;
}
Anonymous 18-Dec-2007 02:30
MOD10, Modulus10 or also called LUHN10 will generate a valid check digit.

<?php
$inv = "34586";
echo $inv . checkdigit($inv);

// Outputs 345868

function checkdigit($num) {
$sum = 0;
$pos = 0;
$rev = strrev($num);
$len = strlen($num);
if ($len % 2 == 0) $len += 1;
while ($pos < $len) {
$odd = $rev[$pos] * 2;
if ($odd > 9) {
$odd -= 9;
}
$sum += $odd;
if ($pos != ($len - 2)) {
$sum += $rev[$pos +1];
}
$pos += 2;
}
return ((floor($sum/10) + 1) * 10 - $sum) % 10;
}
?>
carmel.alex at gmail.com 20-Dec-2006 10:38
to lwc at mytrashmail dot com,  take it easy.

function utf8_strrev($str, $reverse_numbers = true){
    $pattern = $reverse_numbers ? '/./us' : '/(\d+)?./us';
    preg_match_all($pattern, $str, $ar);
    return join('',array_reverse($ar[0]));
}
lwc at mytrashmail dot com 13-Oct-2006 04:01
just as well for UTF-8 usages = I meant also for NONE UTF-8 usages (to keep the numbers unchanged)
lwc at mytrashmail dot com 13-Oct-2006 01:35
/*
Here's a function that adds to carmel.alex's utf-8 encoding support the ability NOT to reverse numbers (for example when you output a phrase as a parameter for a SWF file that can't handle RTL languages itself, but obviously any numbers should remain the same as in the original phrase).

Note that it can be used just as well for UTF-8 usages if you want the numbers to remain intact:
*/

function utf8_strrev($str, $reverse_numbers) {
  preg_match_all('/./us', $str, $ar);
  if ($reverse_numbers)
    return join('',array_reverse($ar[0]));
  else {
      $temp = array();
      foreach ($ar[0] as $value) {
         if (is_numeric($value) && !empty($temp[0]) && is_numeric($temp[0])) {
            foreach ($temp as $key => $value2) {
               if (is_numeric($value2))
                 $pos = ($key + 1);
               else
                  break;
            }
            $temp2 = array_splice($temp, $pos);
            $temp = array_merge($temp, array($value), $temp2);
         } else
            array_unshift($temp, $value);
      }
      return implode('', $temp);
  }
}

// "It says this site is copyrighted just from 2001" (in Hebrew)
$str = "Ч›ЧЄЧ•Ч‘ Ч©Ч”ЧђЧЄЧЁ Ч”Ч–Ч” ЧћЧ•Ч’Чџ Ч‘Ч–Ч›Ч•Ч™Ч•ЧЄ Ч™Ч•Ч¦ЧЁЧ™Чќ ЧЁЧ§ ЧћЧђЧ– 2001";
// Reverse everything
$str_blind_reverse = utf8_strrev($str, true);
// Reverse everything but don't change the year 2001 to 1002...
$str_logical_reverse = utf8_strrev($str, false);
carmel.alex at gmail.com 28-Feb-2006 12:54
This function support utf-8 encoding

function utf8_strrev($str){
    preg_match_all('/./us', $str, $ar);
    return join('',array_reverse($ar[0]));
}
tex at i18nguy dot com 22-Aug-2005 09:36
Just a correction to the previous commenter. In ISO 8859-15, the Euro is 0xA4 (164 decimal). It is a 1 byte character.
MagicalTux at FF dot st 12-May-2005 06:20
I will make Screend at hf dot webex dot com's comment more clear and understandable.

strrev only works for singlebyte character-sets. Multibytes charactersets are not compatibles with strrev.

US-ASCII and ISO-8859-1 are compatible with strrev, however BIG5, SJIS, UTF-8 aren't.

Despite what you can think, ISO-8859-15 *is* multibyte (the euro symbol - Ђ - is coded on two bytes).

There's no mb_strrev function in PHP, so you can't strrev() a multibyte string. Try to convert it to something else with iconv() if it can be represented in a singlebyte character set.
avarab at gmail dot com 07-May-2005 12:53
strrev() can be very useful in cases where it makes more sense to do something from the end of a string rather than the beginning (well duh!) such as apply certain regular expressions. Here's a small function to add commas to numbers that works in such a way.

<?php
echo commafy("1500000.1254"); // prints 1,500,000.1254

function commafy($_) {
        return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,' , strrev( $_ ) ) );
}
?>

I originally wrote it in Perl, does it show? ;=)
Screend at hf dot webex dot com 30-Mar-2004 08:17
this function can only reverse the 1-byte words,like english,it seems,using
<?php
$str=strrev("єєЧЦ");
echo $str;
?>
do not get a right result.
but,you can change 2-bytes characters into a ASCLL,the converse it.
strrchr
strripos
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє


Возвращает позицию последнего вхождения подстроки без учета регистра

strrev
strrpos
Обработка строк
PHP Manual

strripos

(PHP 5)

strripos — Возвращает позицию последнего вхождения подстроки без учета регистра

Описание

int strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Ищет позицию последнего вхождения подстроки needle в строку haystack.

В отличие от strrpos(), strripos() не учитывает регистр символов.

Список параметров

haystack

Строка, в которой производится поиск.

needle

Если параметр needle не является строкой, то он будет преобразован к целому и обработан как код символа.

offset

Если указан, то поиск начнется с данного количества символов с начала строки. Если передано отрицательное значение, поиск начнется с указанного количества символов от конца строки, но по прежнему будет производится поиск последнего вхождения.

Возвращаемые значения

Возвращает номер позиции последнего вхождения needle относительно начала строки haystack (независимо от направления поиска и смещения (offset)). Также обратите внимание на то, что позиция строки отсчитывается от 0, а не от 1.

Возвращает FALSE, если искомая строка не найдена.

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Пример использования strripos()

<?php
$haystack = 'ababcd';
$needle   = 'aB';

$pos      = strripos($haystack, $needle);

if ($pos === false) {
    echo "К сожалению, ($needle) не найдена в ($haystack)";
} else {
    echo "Поздравляем!\n";
    echo "Последнее вхождение ($needle) найдено в ($haystack) в позиции ($pos)";
}
?>

Результат выполнения данного примера:

   Поздравляем!
   Последнее вхождение (aB) найдено в (ababcd) в позиции (2)

Смотрите также

  • strpos() - Возвращает позицию первого вхождения подстроки
  • stripos() - Возвращает позицию первого вхождения подстроки без учета регистра
  • strrpos() - Возвращает позицию последнего вхождения подстроки в строке
  • strrchr() - Находит последнее вхождение символа в строке
  • stristr() - Регистро-независимый вариант функции strstr
  • substr() - Возвращает подстроку

User Contributed Notes

Anonymous 31-Aug-2010 01:05
Generally speaking, linear searches are from start to end, not end to start - which makes sense from a human perspective. If you need to find strings in a string backwards, reverse your haystack and needle rather than manually chopping it up.
admin at e-xxi dot net 08-Mar-2010 07:00
strripos() has very strange behaviour when you provide search position. For some reason it searches forward from the given position, instead of searching backward, that is more logical.

For example if you want to find instanse of $what, previous to the last, strripos($where, $what, $last_what_pos-1) will not wark as expected. It will return $last_what_pos again and again. And that has no sence at all.

To prevent this, I just used $prev_last_what_pos = strripos(substr($where,0,$last_what_pos), $what);
dimmav at in dot gr 25-Sep-2008 09:31
Suppose you just need a stripos function working backwards expecting that strripos does this job, you better use the following code of a custom function named strbipos:

<?php
function strbipos($haystack="", $needle="", $offset=0) {
// Search backwards in $haystack for $needle starting from $offset and return the position found or false

    $len = strlen($haystack);
    $pos = stripos(strrev($haystack), strrev($needle), $len - $offset - 1);
    return ( ($pos === false) ? false : $len - strlen($needle) - $pos );
}

// Test
$body = "01234Xy7890XYz456xy90";
$str = "xY";
$len = strlen($body);
echo "TEST POSITIVE offset VALUES IN strbipos<br>";
for ($i = 0; $i < $len; $i++) {
    echo "Search in [$body] for [$str] starting from offset [$i]: [" . strbipos($body, $str, $i) . "]<br>";
}
?>

Note that this function does exactly what it says and its results are different comparing to PHP 5 strripos function.
peev[dot]alexander at gmail dot com 20-Apr-2008 02:14
OK, I guess this will be the final function implementation for PHP 4.x versions ( my previous posts are invalid )

<?php

if(!function_exists("stripos")){
    function stripos(  $str, $needle, $offset = 0  ){
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  );
    }/* endfunction stripos */
}/* endfunction exists stripos */

if(!function_exists("strripos")){
    function strripos(  $haystack, $needle, $offset = 0  ) {
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  );
        if(  $offset < 0  ){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    );
        }
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE;
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   );
        return $pos;
    }/* endfunction strripos */
}/* endfunction exists strripos */
?>
peev[dot]alexander at gmail dot com 23-Nov-2007 03:05
Oops, I forgot to return "false" if the needle is not found. Here is the proper function.

<?php
if(!function_exists("strripos")){
    function strripos($haystack, $needle, $offset=0) {
        if($offset<0){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(  substr( $haystack, $offset )  );
        }
        $pos = strlen($haystack) - (strpos($temp_cut, strrev($needle)) + $offset + strlen($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }

        if(strpos($temp_cut, strrev($needle))===false){
             return false;
        }
        else return $pos;
    }/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
peev[dot]alexander at gmail dot com 17-Oct-2007 05:23
I think you shouldn't underestimate the length of $needle in the search of THE FIRST POSITION of it's last occurrence in the string. I improved the posted function, with added support for offset. I think this is an exact copy of the real function:

<?php
if(!function_exists("strripos")){
    function strripos($haystack, $needle, $offset=0) {
        if($offset<0){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(  substr( $haystack, $offset )  );
        }
        $pos = strlen($haystack) - (strpos($temp_cut, strrev($needle)) + $offset + strlen($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
ElectroFox 02-Aug-2007 01:59
Sorry, I made that last post a bit prematurely.  One more thing wrong with the simple php4 version is that it breaks if the string is not found.  It should actually look like this:

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        $pos = strlen($haystack) - strpos(strrev($haystack), strrev($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }
}
?>

Note, we now check to see if the $needle was found, and if it isn't, we return 0.
ElectroFox 02-Aug-2007 01:39
Actually, the above, "Simple way to implement this function in PHP 4" by Yanik Lupien, should be:

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        return strlen($haystack) - strpos(strrev($haystack), strrev($needle));
    }
}

?>

Note the reversal (<?php strrev($needle)?>) of the search string.  This was left out in Yanik's example, and without it, you'll simply get the length of the haystack, as the forward string will not likely be found in the reversed haystack.

Thus; if we reverse the haystack, any instance of the search string ($needle) therein will also be reversed, so we must reverse it to look for it. :)
Yanik Lupien 03-Jul-2007 10:47
Simple way to implement this function in PHP 4

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        return strlen($haystack) - strpos(strrev($haystack), $needle);
    }
}

?>
aidan at php dot net 30-May-2004 10:36
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
strrev
strrpos
Обработка строк


Возвращает позицию последнего вхождения подстроки в строке

strripos
strspn
Обработка строк
PHP Manual

strrpos

(PHP 4, PHP 5)

strrpos — Возвращает позицию последнего вхождения подстроки в строке

Описание

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Ищет позицию последнего вхождения подстроки needle в строку haystack.

Список параметров

haystack

Строка, в которой производится поиск.

needle

Если needle не является строкой, то он приводится к целому и трактуется как код символа.

offset

Если указан, то поиск начнется с данного количества символов с начала строки. Если передано отрицательное значение, поиск начнется с указанного количества символов от конца строки, но по прежнему будет производится поиск последнего вхождения.

Возвращаемые значения

Возвращает номер позиции последнего вхождения needle относительно начала строки haystack (независимо от направления поиска и смещения (offset)). Также обратите внимание на то, что позиция строки отсчитывается от 0, а не от 1.

Возвращает FALSE, если искомая строка не найдена.

Список изменений

Версия | Описание
5.0.0 | Параметр needle может быть строкой из более чем одного символа.
5.0.0 | Добавлен параметр offset.

Примеры

Пример #1 Проверка существования искомой строки

Легко ошибиться и перепутать возвращаемые значения в случаях "символ найден в нулевой позиции" и "символ не найден". Вот так можно узнать разницу:

<?php

$pos = strrpos($mystring, "b");
if ($pos === false) { // обратите внимание: три знака равенства
    // не найдено...
}

?>

Пример #2 Поиск со смещением

<?php
$foo = "0123456789a123456789b123456789c";

var_dump(strrpos($foo, '7', -5));  // Поиск происходит в обратном направлении и
                                   // начинается с пятой позиции с конца. Результат: int(17)

var_dump(strrpos($foo, '7', 20));  // Начинает поиск с 20 позиции в строке.
                                   // Результат: int(27)

var_dump(strrpos($foo, '7', 28));  // Результат: bool(false)
?>

Смотрите также

  • strpos() - Возвращает позицию первого вхождения подстроки
  • stripos() - Возвращает позицию первого вхождения подстроки без учета регистра
  • strripos() - Возвращает позицию последнего вхождения подстроки без учета регистра
  • strrchr() - Находит последнее вхождение символа в строке
  • substr() - Возвращает подстроку

User Contributed Notes

maxmike at gmail dot com 11-Jul-2009 10:05
I've got a simple method of performing a reverse strpos which may be of use.  This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.

Here is an example of backwards stepping through instances of a string with this function:

<?php
function backwardStrpos($haystack, $needle, $offset = 0){
    $length = strlen($haystack);
    $offset = ($offset > 0)?($length - $offset):abs($offset);
    $pos = strpos(strrev($haystack), strrev($needle), $offset);
    return ($pos === false)?false:( $length - $pos - strlen($needle) );
}

$pos = 0;
$count = 0;
echo "Test1<br/>";
while(($pos = backwardStrpos("012340567890", "0", $pos)) !== false){
     echo $pos."<br/>";
    $pos--;
    if($pos < 0){
        echo "Done<br/>";break;
    }
}
echo "---===---<br/>\nTest2<br/>";
echo backwardStrpos("12341234", "1", 2)."<br/>";
echo backwardStrpos("12341234", "1", -2);
?>

Outputs:
Test1
11
5
0
Done
---===---
Test2
0
4

With Test2 the first line checks from the first 3 in "12341234" and runs backwards until it finds a 1 (at position 0)

The second line checks from the second 2 in "12341234" and seeks towards the beginning for the first 1 it finds (at position 4).

This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.
alexandre at NOSPAM dot pixeline dot be 20-Dec-2008 08:35
I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.

This did the trick:

<?php
    // Detect and remove a trailing slash
    $root_folder = ((strrpos($root_folder, '/') + 1) == strlen($root_folder)) ? substr($root_folder, 0, - 1) : $root_folder;
?>
eagleeye at eeisi dot com 02-Jul-2008 05:44
I had a problem where I was using the following in my .htaccess file.

php_value auto_prepend_file "pre.php"
php_value auto_append_file "post.php"

Not knowing how to prevent the htaccess directives from cascading, without having to put an override .htaccess in each subfolder, I figured, just prevent output in my pre and post scripts if we weren't in the root folder!

I did it using this line of code:

if (strrpos($_SERVER["REQUEST_URI"], "/") != 0) return;

Prevents execution of the rest of the script, and most importantly, doesn't output anything before any other headers may be sent by things in other folders (like my wiki site).
dixonmd at gmail dot com 24-Dec-2007 02:42
<?php
        $pos = strlen(string $haystack) - strpos (strrev(string $haystack), strrev(string $needle)) - strlen(string $needle);
?>

         If in the needle there is more than one character then in php 4 we can use the above statement for finding the position of last occurrence of a substring in a string instead of strrpos. Because in php 4 strrpos uses the first character of the substring.

eg :
<?php
        $haystack = "you you you you you";
        $needle = "you";
        $pos1 = strlen($haystack) - strpos (strrev($haystack), strrev($needle)) - strlen($needle);
        echo $pos1 . "<br>";
        $pos2 strrpos($haystack, $needle);
        echo $pos2 . "<br>";
?>
t dot hornberger at yatego dot com 17-Oct-2007 04:50
the function posted is false, hier the correction:

function rstrpos ($haystack, $needle, $offset)
{
    $size = strlen ($haystack);
    $pos = strpos (strrev($haystack), strrev($needle), $size - $offset);

    if ($pos === false)
        return false;

    return $size - $pos - strlen($needle);
}
Daniel Brinca 15-Oct-2007 05:41
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards  (lastIndexOf type function):

//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
    $size = strlen ($haystack);
    $pos = strpos (strrev($haystack), $needle, $size - $offset);

    if ($pos === false)
        return false;

    return $size - $pos;
}

Note: supports full strings as needle
pb at tdcspace dot dk 23-Sep-2007 07:26
what the hell are you all doing. Wanna find the *next* last from a specific position because strrpos is useless with the "offset" option, then....

ex: find 'Z' in $str from position $p,  backward...

while($p > -1 and $str{$p} <> 'Z') $p--;

Anyone will notice $p = -1 means: *not found* and that you must ensure a valid start offset in $p, that is >=0 and < string length. Doh
brian at enchanter dot net 16-Jul-2007 07:47
The documentation for 'offset' is misleading.

It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string."

This is confusing if you think of strrpos as starting at the end of the string and working backwards.

A better way to think of offset is:

- If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle).

- If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found.

If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this:

strrpos($text, " ", -(strlen($text) - 50));

If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.
jafet at g dot m dot a dot i dot l dot com 12-Apr-2007 07:08
It would probably be good if someone would care to merge these little thoughts together...

<?php
function super_conforming_strrpos($haystack, $needle, $offset = 0)
{
    # Why does strpos() do this? Anyway...
    if(!is_string($needle)) $needle = ord(intval($needle));
    if(!is_string($haystack)) $haystack = strval($haystack);
    # Setup
    $offset = intval($offset);
    $hlen = strlen($haystack);
    $nlen = strlen($needle);
    # Intermezzo
    if($nlen == 0)
    {
        trigger_error(__FUNCTION__.'(): Empty delimiter.', E_USER_WARNING);
        return false;
    }
    if($offset < 0)
    {
        $haystack = substr($haystack, -$offset);
        $offset = 0;
    }
    elseif($offset >= $hlen)
    {
        trigger_error(__FUNCTION__.'(): Offset not contained in string.', E_USER_WARNING);
        return false;
    }
    # More setup
    $hrev = strrev($haystack);
    $nrev = strrev($needle);
    # Search
    $pos = strpos($hrev, $nrev, $offset);
    if($pos === false) return false;
    else return $hlen - $nlen - $pos;
}
?>
jafet at g dot m dot a dot i dot l dot com 12-Apr-2007 01:57
Full strpos() functionality, by yours truly.

<?php
function conforming_strrpos($haystack, $needle, $offset = 0)
{
    # Why does strpos() do this? Anyway...
    if(!is_string($needle)) $needle = ord(intval($needle));
    $haystack = strval($haystack);
    # Parameters
    $hlen = strlen($haystack);
    $nlen = strlen($needle);
    # Come on, this is a feature too
    if($nlen == 0)
    {
        trigger_error(__FUNCTION__.'(): Empty delimiter.', E_USER_WARNING);
        return false;
    }
    $offset = intval($offset);
    $hrev = strrev($haystack);
    $nrev = strrev($needle);
    # Search
    $pos = strpos($hrev, $nrev, $offset);
    if($pos === false) return false;
    else return $hlen - $nlen - $pos;
}
?>

Note that $offset is evaluated from the end of the string.

Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.
mijsoot_at_gmail_dot_com 06-Mar-2007 01:43
To begin, i'm sorry for my English.
So, I needed of one function which gives me the front last position of a character.
Then I said myself that it should be better to make one which gives the "N" last position.

$return_context = "1173120681_0__0_0_Mijsoot_Thierry";

// Here i need to find = "Mijsoot_Thierry"

//echo $return_context."<br />";// -- DEBUG

function findPos($haystack,$needle,$position){
    $pos = strrpos($haystack, $needle);
    if($position>1){
        $position --;
        $haystack = substr($haystack, 0, $pos);
        $pos = findPos($haystack,$needle,$position);
    }else{
        // echo $haystack."<br />"; // -- DEBUG
        return $pos;
    }
    return $pos;
}

var_dump(findPos($return_context,"_",2)); // -- TEST
Christ Off 29-Jan-2007 10:50
Function to truncate a string
Removing dot and comma
Adding ... only if a is character found

function TruncateString($phrase, $longueurMax = 150) {
    $phrase = substr(trim($phrase), 0, $longueurMax);
    $pos = strrpos($phrase, " ");
    $phrase = substr($phrase, 0, $pos);
    if ((substr($phrase,-1,1) == ",") or (substr($phrase,-1,1) == ".")) {
        $phrase = substr($phrase,0,-1);
    }
    if ($pos === false) {
        $phrase = $phrase;
    }
    else {
        $phrase = $phrase . "...";
    }
return $phrase;
}
Guilherme Garnier 15-Jan-2007 02:44
Actually, there is a little problem on your code: if $needle is not found inside $haystack, the function should return FALSE, but it is actually returning strlen($haystack) - strlen($needle). Here is a corrected version of it:

<?php
function stringrpos($haystack,$needle,$offset=NULL)
{
   if (strpos($haystack,$needle,$offset) === FALSE)
      return FALSE;

   return strlen($haystack)
           - strpos( strrev($haystack) , strrev($needle) , $offset)
           - strlen($needle);
}
?>
php NO at SPAMMERS willfris SREMMAPS dot ON nl 20-Dec-2006 06:48
<?php
/*******
 ** Maybe the shortest code to find the last occurence of a string, even in php4
 *******/
function stringrpos($haystack,$needle,$offset=NULL)
{
    return strlen($haystack)
           - strpos( strrev($haystack) , strrev($needle) , $offset)
           - strlen($needle);
}
// @return   ->   chopped up for readability.
?>
purpleidea 27-Nov-2006 12:07
I was having some issues when I moved my code to run it on a different server.
The earlier php version didn't support more than one character needles, so tada, bugs. It's in the docs, i'm just pointing it out in case you're scratching your head for a while.
dmitry dot polushkin at gmail dot com 03-Nov-2006 10:05
Returns the filename's string extension, else if no extension found returns false.
Example: filename_extension('some_file.mp3'); // mp3
Faster than the pathinfo() analogue in two times.
<?php
function filename_extension($filename) {
    $pos = strrpos($filename, '.');
    if($pos===false) {
        return false;
    } else {
        return substr($filename, $pos+1);
    }
}
?>
kavih7 at yahoo dot com 08-Jun-2006 12:53
<?php
###################################################
#
# DESCRIPTION:
# This function returns the last occurance of a string,
# rather than the last occurance of a single character like
# strrpos does. It also supports an offset from where to
# start the searching in the haystack string.
#
# ARGS:
# $haystack (required) -- the string to search upon
# $needle (required) -- the string you are looking for
# $offset (optional) -- the offset to start from
#
# RETURN VALS:
# returns integer on success
# returns false on failure to find the string at all
#
###################################################

function strrpos_string($haystack, $needle, $offset = 0)
{
    if(trim($haystack) != "" && trim($needle) != "" && $offset <= strlen($haystack))
    {
        $last_pos = $offset;
        $found = false;
        while(($curr_pos = strpos($haystack, $needle, $last_pos)) !== false)
        {
            $found = true;
            $last_pos = $curr_pos + 1;
        }
        if($found)
        {
            return $last_pos - 1;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}
?>
shimon at schoolportal dot co dot il 03-May-2006 11:31
In strrstr function in php 4 there is also no offset.
<?
// by Shimon Doodkin
function chrrpos($haystack, $needle, $offset=false)
{
 $needle=$needle[0];
 $l=strlen($haystack);
 if($l==0)  return false;
 if($offset===false)  $offset=$l-1;
 else
 {
  if($offset>$l) $offset=$l-1;
  if($offset<0) return false;
 }
 for(;$offset>0;$offset--)
  if($haystack[$offset]==$needle)
   return $offset;
 return false;
}
?>
gordon at kanazawa-gu dot ac dot jp 13-Sep-2005 09:56
The "find-last-occurrence-of-a-string" functions suggested here do not allow for a starting offset, so here's one, tried and tested, that does:

function my_strrpos($haystack, $needle, $offset=0) {
    // same as strrpos, except $needle can be a string
    $strrpos = false;
    if (is_string($haystack) && is_string($needle) && is_numeric($offset)) {
        $strlen = strlen($haystack);
        $strpos = strpos(strrev(substr($haystack, $offset)), strrev($needle));
        if (is_numeric($strpos)) {
            $strrpos = $strlen - $strpos - strlen($needle);
        }
    }
    return $strrpos;
}
genetically altered mastermind at gmail 22-Aug-2005 10:30
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
fab 10-Aug-2005 04:07
RE: hao2lian

There are a lot of alternative - and unfortunately buggy - implementations of strrpos() (or last_index_of as it was called) on this page. This one is a slight modifiaction of the one below, but it should world like a *real* strrpos(), because it returns false if there is no needle in the haystack.

<?php

function my_strrpos($haystack, $needle) {
   $index = strpos(strrev($haystack), strrev($needle));
   if($index === false) {
        return false;
   }
   $index = strlen($haystack) - strlen($needle) - $index;
   return $index;
}

?>
lwoods 06-Aug-2005 12:03
If you are a VBScript programmer ("ex-" of course), you will find that 'strrpos' doesn't work like the VBScript 'instrRev' function.

Here is the equivalent function:

VBScript:

k=instrrev(s,">",j);

PHP Equivalent of the above VBScript:

$k=strrpos(substr($s,0,$j),'>');

Comments:

You might think (I did!) that the following PHP function call would be the equivant of the above VBScript call:

$kk=strrpos($s,'>',$j);

NOPE!  In the above PHP call, $j defines the position in the string that should be considered the BEGINNING of the string, whereas in the VBScript call, j is to be considered the END of the string, as far as this search is concerned.  Anyway, the above 'strrpos' with the 'substr' will work.
(Probably faster to write a for loop!)
hao2lian 02-Aug-2005 07:50
Yet another correction on the last_index_of function algorithm:

function last_index_of($haystack, $needle) {
    $index = strpos(strrev($haystack), strrev($needle));
    $index = strlen($haystack) - strlen($needle) - $index;
    return $index;
}

"strlen(index)" in the most recent one should be "strlen($needle)".
jonas at jonasbjork dot net 06-Apr-2005 01:25
I needed to remove last directory from an path, and came up with this solution:

<?php

  $path_dir = "/my/sweet/home/";
  $path_up = substr( $path_dir, 0, strrpos( $path_dir, '/', -2 ) )."/";
  echo $path_up;

?>

Might be helpful for someone..
08-Mar-2005 11:14
In the below example, it should be substr, not strrpos.

<PHP?

$filename = substr($url, strrpos($url, '/') + 1);

?>
escii at hotmail dot com ( Brendan ) 10-Jan-2005 07:12
I was immediatley pissed when i found the behaviour of strrpos ( shouldnt it be called charrpos ?) the way it is, so i made my own implement to search for strings.

<?
function proper_strrpos($haystack,$needle){
        while($ret = strrpos($haystack,$needle))
        {
                if(strncmp(substr($haystack,$ret,strlen($needle)),
                                $needle,strlen($needle)) == 0 )
                        return $ret;
                $haystack = substr($haystack,0,$ret -1 );
        }
        return $ret;
}
?>
griffioen at justdesign dot nl 17-Nov-2004 10:57
If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don't have mb_strrpos working, try this:

    function lastIndexOf($haystack, $needle) {
        $index        = strpos(strrev($haystack), strrev($needle));
        $index        = strlen($haystack) - strlen(index) - $index;
        return $index;
    }
nexman at playoutloud dot net 07-Oct-2004 09:22
Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.

    function strepos($haystack, $needle, $offset=0) {
        $pos_rule = ($offset<0)?strlen($haystack)+($offset-1):$offset;
        $last_pos = false; $first_run = true;
        do {
            $pos=strpos($haystack, $needle, (intval($last_pos)+(($first_run)?0:strlen($needle))));
            if ($pos!==false && (($offset<0 && $pos <= $pos_rule)||$offset >= 0)) {
                $last_pos = $pos;
            } else { break; }
            $first_run = false;
        } while ($pos !== false);
        if ($offset>0 && $last_pos<$pos_rule) { $last_pos = false; }
        return $last_pos;
    }

If my math is off, please feel free to correct.
  - A positive offset will be the minimum character index position of the first character allowed.
  - A negative offset will be subtracted from the total length and the position directly before will be the maximum index of the first character being searched.

returns the character index ( 0+ ) of the last occurence of the needle.

* boolean FALSE will return no matches within the haystack, or outside boundries specified by the offset.
harlequin AT gmx DOT de 26-May-2004 09:59
this is my function for finding a filename in a URL:

<?php
    function getfname($url){
        $pos = strrpos($url, "/");
        if ($pos === false) {
            // not found / no filename in url...
            return false;
        } else {
            // Get the string length
            $len = strlen($url);
            if ($len < $pos){
                        print "$len / $pos";
                // the last slash we found belongs to http:// or it is the trailing slash of a URL
                return false;
            } else {
                $filename = substr($url, $pos+1, $len-$pos-1);
            }
        }
        return $filename;
    }
?>
tsa at medicine dot wisc dot edu 24-May-2004 05:17
What the heck, I thought I'd throw another function in the mix.  It's not pretty but the following function counts backwards from your starting point and tells you the last occurrance of a mixed char string:

<?php
function strrposmixed ($haystack, $needle, $start=0) {
   // init start as the end of the str if not set
   if($start == 0) {
       $start = strlen($haystack);
   }

   // searches backward from $start
   $currentStrPos=$start;
   $lastFoundPos=false;

   while($currentStrPos != 0) {
       if(!(strpos($haystack,$needle,$currentStrPos) === false)) {
           $lastFoundPos=strpos($haystack,$needle,$currentStrPos);
           break;
       }
       $currentStrPos--;
   }

   if($lastFoundPos === false) {
       return false;
   } else {
       return $lastFoundPos;
   }
}
?>
dreamclub2000 at hotmail dot com 04-Feb-2004 12:17
This function does what strrpos would if it handled multi-character strings:

<?php
function getLastStr($hay, $need){
  $getLastStr = 0;
  $pos = strpos($hay, $need);
  if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
    while($pos) {
      $getLastStr = $getLastStr + $pos + strlen($need);
      $hay = substr ($hay , $pos + strlen($need));
      $pos = strpos($hay, $need);
    }
    return $getLastStr - strlen($need);
  } else {
    return -1; //if $need wasn�t found it returns "-1" , because it could return "0" if it�s found on position "0".
  }
}
?>
ZaraWebFX 14-Oct-2003 11:06
this could be, what derek mentioned:

<?
function cut_last_occurence($string,$cut_off) {
    return strrev(substr(strstr(strrev($string), strrev($cut_off)),strlen($cut_off)));
}

//    example: cut off the last occurence of "limit"
    $str = "select delta_limit1, delta_limit2, delta_limit3 from table limit 1,7";
    $search = " limit";
    echo $str."\n";
    echo cut_last_occurence($str,"limit");
?>
lee at 5ss dot net 29-Aug-2003 07:21
I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters.  This is a recursive function.  I have not tested to see if it is more or less efficient than the others on the page.  I hope this helps someone!

<?php
//Find last occurance of needle in haystack
function str_rpos($haystack, $needle, $start = 0){
    $tempPos = strpos($haystack, $needle, $start);
    if($tempPos === false){
        if($start == 0){
            //Needle not in string at all
            return false;
        }else{
            //No more occurances found
            return $start - strlen($needle);
        }
    }else{
        //Find the next occurance
        return str_rpos($haystack, $needle, $tempPos + strlen($needle));
    }
}
?>
ara at bluemedia dot us 14-Jul-2003 01:09
derek@slashview.com notes a great replacement for strrpos because of the single character needle limitation in the strrpos function. He made a slight error in the code. He adds the length of the needle string instead of subtracting it from the final position. The function should be:

<?php
function strlastpos($haystack, $needle) {
# flip both strings around and search, then adjust position based on string lengths
return strlen($haystack) - strlen($needle) - strpos(strrev($haystack), strrev($needle));
}
?>
no_spammage_at_wwwcrm_dot_com 24-Apr-2003 08:07
This function does what strrpos would if it handled multi-character strings:

<?php
//function recurses until it finds last instance of $needle in $haystack

function getLastStr($haystack, $needle, $first_time=1){

                  $test=strstr($haystack, $needle);//is the needle there?
                  if ($test) return getLastStr($test, $needle, 0);//see if there is another one?
                  else if ($first_time) return false;//there is no occurence at all
                  else return $haystack;//that was the last occurence

                }
?>
FIE 15-Feb-2003 05:03
refering to the comment and function about lastIndexOf()...
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle... i rewrote it as fallows:

<?php
function strlpos($f_haystack,$f_needle) {
      $rev_str = strrev($f_needle);
      $rev_hay = strrev($f_haystack);
      $hay_len = strlen($f_haystack);
      $ned_pos = strpos($rev_hay,$rev_str);
      $result  = $hay_len - $ned_pos - strlen($rev_str);
      return $result;
}
?>

this one fallows the strpos syntax rather than java's lastIndexOf.
I'm not positive if it takes more resources assigning all of those variables in there but you can put it all in return if you want, i dont care if i crash my server ;).

~SILENT WIND OF DOOM WOOSH!
rob at pulpchat dot com 22-Jan-2003 02:23
For those of you coming from VBScript, I have
converted the instrrev function to PHP:

<?php
function instrrev($n,$s) {
  $x=strpos(chr(0).strrev($n),$s)+0;
  return (($x==0) ? 0 : strlen($n)-$x+1);
}
?>

Remember that, unlike PHP and Javascript, VBScript
returns 0 for no string found and 1 for the first
character position, etc.

Hopefully this will save some time if you are
converting ASP pages to PHP.
php dot net at insite-out dot com 17-Dec-2002 11:47
I was looking for the equivalent of Java's lastIndexOf(). I couldn't find it so I wrote this:

<?php
/*
Method to return the last occurrence of a substring within a
string
*/
function last_index_of($sub_str,$instr) {
    if(strstr($instr,$sub_str)!="") {
        return(strlen($instr)-strpos(strrev($instr),$sub_str));
    }
    return(-1);
}
?>

It returns the numerical index of the substring you're searching for, or -1 if the substring doesn't exist within the string.
su.noseelg@naes, only backwards 13-Dec-2002 10:39
Maybe I'm the only one who's bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here's an example to explain what I don't like:

The quick brown fox jumps over the lazy
dog.

So that's why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with '&nbsp;'.

<?php
function no_orphans($TheParagraph) {
    if (substr_count($TheParagraph," ") > 1) {
    $lastspace = strrpos($TheParagraph," ");
    $TheParagraph = substr_replace($TheParagraph,"&nbsp;",$lastspace,1);
    }
return $TheParagraph;
}
?>

So, it would change "The quick brown fox jumps over the lazy dog." to "The quick brown fox jumps over the lazy&nbsp;dog." That way, the last two words will always stay together.
DONT SPAM vardges at iqnest dot com 30-Oct-2002 01:22
that function can be modified to this

<?php
function strrpos_str ($string, $searchFor, $startFrom = 0)
{
    $addLen = strlen ($searchFor);
    $endPos = $startFrom - $addLen;

    while (true)
    {
        if (($newPos = strpos ($string, $searchFor, $endPos + $addLen)) === false) break;
        $endPos = $newPos;
    }

    return ($endPos >= 0) ? $endPos : false;
}

// example
$str = "abcabcabc";
$search = "ab";

$pos = strrpos_str ($str, $search);
if ($pos === false) echo "not found";
else echo $pos; // returns 6 in this case
?>
28-May-2002 12:46
Cause:
Find position of last occurrence of a string in a string...
and I needed it, I hacked a little code to do this:

Maybe it is helpful for you.

<?php
 function _strrpos_needle($sourcestring,$needle){

    /* just for easier understanding */
    $tempString=$sourcestring;

    do {
      $tempPos=strpos($tempString,$needle);
      $tempString=substr($tempString,$tempPos+strlen($needle));
      $realPos=$realPos+$tempPos;
    } while (!is_bool($tempPos));

    return $realPos;

  }
?>
derek at slashview dot com 01-Feb-2002 04:06
To find the position of the start of the last occurence of a string, we can do this:
$pos=strlen($haystack) - (strpos(strrev($haystack), strrev($needle)) + strlen($needle));
The idea is to reverse both $needle and $haystack, use strpos to find the first occurence of $needle in $haystack, then count backwards by the length of $needle. Finally, subtract $pos from length of $haystack. A lot easier to figure out if you use a test string to visualize it.  :)
strripos
strspn
Обработка строк


Возвращает длину участка в начале строки, полностью соответствующего маске

strrpos
strstr
Обработка строк
PHP Manual

strspn

(PHP 4, PHP 5)

strspn — Возвращает длину участка в начале строки, полностью соответствующего маске

Описание

int strspn ( string $subject , string $mask [, int $start [, int $length ]] )

Возвращает длину участка от начала строки subject, содержащий только символы из mask.

Если параметры start и length не указаны, то будет исследована вся строка subject. Если они указаны, то эффект будет аналогичен вызову strspn(substr($subject, $start, $length) $mask) (подробнее см. функцию substr).

Строка кода:

<?php
$var = strspn("42 is the answer to the 128th question.", "1234567890");
?>
присвоит 2 переменной $var, так как "42" - это начальный участок строки subject, состоящий только из символов "1234567890".

Список параметров

subject

Исследуемая строка.

mask

Список из разрешенных символов.

start

Позиция начала поиска в subject.

Если start указан и неотрицателен, то strspn() начнет искать в строке subject начиная с позиции start. К примеру, в строке 'abcdef', символом с позицией 0 является 'a', символом с позицией 2 является 'c' и т.д.

Если start указан и отрицателен, то strspn() начнет поиск в строке subject с позиции, отстоящей на start символов с конца subject.

length

Длина исследуемого фрагмента subject.

Если length указан и неотрицателен, то строка subject будет исследована в течение length после стартовой позиции.

Если length указана и отрицательна, то строка subject будет исследована начиная со стартовой позиции до позиции, отстоящей на length символов с конца subject.

Возвращаемые значения

Возвращает длину первого участка subject, состоящего целиком из символов в mask.

Список изменений

Версия | Описание
4.3.0 | Добавлены параметры start и length

Примеры

Пример #1 Пример использования strspn()

<?php
// subject не начинается ни из какого символа из mask
var_dump(strspn("foo", "o"));

// проверить два символа из subject начиная с позиции 1
var_dump(strspn("foo", "o", 1, 2));

// проверить один символ из subject начиная с позиции 1
var_dump(strspn("foo", "o", 1, 1));
?>

Результат выполнения данного примера:

int(0)
int(2)
int(1)

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strcspn() - Возвращает длину участка в начале строки, не соответствующего маске

User Contributed Notes

mrsohailkhan at gmail dot com 01-Feb-2011 12:56
very dificult to get from the definition directly, while i search for that,i came to know that

strspn() will tell you the length of a string consisting entirely of the set of characters in accept set. That is, it starts walking down str until it finds a character that is not in the set (that is, a character that is not to be accepted), and returns the length of the string so far.

and

strcspn() works much the same way, except that it walks down str until it finds a character in the reject set (that is, a character that is to be rejected.) It then returns the length of the string so far.

<?php
$acceptSet = "aeiou";
$rejectSet  = "y";

$str1 ="a banana";
$str2 ="the bolivian navy on manuvers in the south pacific";

echo $n = strspn($str1,$acceptSet);// $n == 1, just "a"

echo $n = strcspn($str2,$rejectSet);// n = 16, "the bolivian nav"
?>

hope this example will help in understanding the concept of strspn() and strcspn().
AT-HE (at_he.hotmail) 28-Nov-2010 02:45
you can use this function with strlen to check illegal characters, string lenght must be the same than strspn (characters from my string contained in another)

<?php

$digits='0123456789';

if (strlen($phone) != strspn($phone,$digits))
 echo "illegal characters";

?>
Dmitry Mazur 04-Mar-2009 10:23
The second parameter is a set of allowed characters.
strspn will return an zero-based index of a first non-allowed character.
barry dot balkowski at gmail dot com 08-Aug-2008 02:12
It took me some time to understand the way this function works…
I’ve compiled my own explanation with my own words that is more understandable for me personally than the official one or those that can be found in different tutorials on the web.
Perhaps, it will save someone several minutes…

<?php
strspn(string $haystack, string $char_list [, int $start [, int $length]])
?>

The way it works:
 -   searches for a segment of $haystack that consists entirely from supplied through the second argument chars
 -   $haystack must start from one of the chars supplied through $char_list, otherwise the function will find nothing
 -   as soon as the function encounters a char that was not mentioned in $chars it understands that the segment is over and stops (it doesn’t search for the second, third and so on segments)
 -   finally, it measures the segment’s length and return it (i.e. length)

In other words it finds a span (only the first one) in the string that consists entirely form chars supplied in $chars_list and returns its length
B Crawford 02-Oct-2007 05:20
This function is significantly faster for checking illegal characters than the equivalent preg_match() method.
strrpos
strstr
Обработка строк


Находит первое вхождение подстроки

strspn
strtok
Обработка строк
PHP Manual

strstr

(PHP 4, PHP 5)

strstr — Находит первое вхождение подстроки

Описание

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Возвращает подстроку строки haystack начиная с первого вхождения needle (и включая его) и до конца строки haystack.

Замечание:

Эта функция учитывает регистр символов. Для поиска без учета регистра используйте stristr().

Замечание:

Если нужно лишь определить, встречается ли подстрока needle в haystack, используйте более быструю и менее ресурсоемкую функцию strpos().

Список параметров

haystack

Входная строка.

needle

Если needle не является строкой, он приводится к целому и трактуется как код символа.

before_needle

Если установлен в TRUE, strstr() возвращает часть строки haystack до первого вхождения needle (исключая needle).

Возвращаемые значения

Возвращает часть строки, или FALSE, если needle не найдена.

Список изменений

Версия | Описание
5.3.0 | Добавлен необязательный параметр before_needle.
4.3.0 | strstr() теперь бинарно безопасна.

Примеры

Пример #1 Пример использования strstr()

<?php
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // выводит @example.com

$user = strstr($email, '@', true); // Начиная с PHP 5.3.0
echo $user; // выводит name
?>

Смотрите также

  • stristr() - Регистро-независимый вариант функции strstr
  • strrchr() - Находит последнее вхождение символа в строке
  • strpos() - Возвращает позицию первого вхождения подстроки
  • strpbrk() - Ищет в строке любой символ из заданного набора
  • preg_match() - Выполняет проверку на соответствие регулярному выражению

User Contributed Notes

peter at olds dot co 20-Feb-2012 10:16
I was in need of getting the first and last part of a string pre 5.3 so I wrote this:

<?php
$fir = $first = explode( " ", $cmd[1] );
unset( $fir[0] );
$end = ltrim( implode( " ", $fir ) );
?>

I needed it split with a " " but can obviously change for your needs. But with this format your output for the string:

"PHP is the best programming language out there"

Will give you the following results:

<?php
$first[0] // PHP
$end // is the best programming language out there
?>

Works really well :)
xydon1 at yahoo dot com 31-Aug-2011 03:03
I explained this to my newbies the difference though it would be good to demonstrate this here. If you are evaluating a list you cannot use strstr as it looks for any occurance. The correct way is the function which evaluates a true or false on the exact value to check.

In the following example I have a list of promotion ids I want to evaluate whether or not a promotion exists:

<?php
//Wrong
$promotion = strstr("25,56","2");
if($promotion){
  echo "found";
}else{
  echo "not found";
}

//right
function detectPromotion($string,$promotion){
  foreach(explode(",",$string) as $promotionToCheck){
    echo "checkin ".$promotionToCheck."==".$promotion."<br/>";
    if($promotionToCheck==$promotion){
      $promotionFound=true;
    }
  }
  return $promotionFound;
}

echo detectPromotion("2,56","2");
?>
gruessle at gmail dot com 20-Apr-2011 01:39
Been using this for years:

<?php
/**
*
* @author : Dennis T Kaplan
*
* @version : 1.0
* Date : June 17, 2007
* Function : reverse strstr()
* Purpose : Returns part of haystack string from start to the first occurrence of needle
* $haystack = 'this/that/whatever';
* $result = rstrstr($haystack, '/')
* $result == this
*
* @access public
* @param string $haystack, string $needle
* @return string
**/

function rstrstr($haystack,$needle)
    {
        return substr($haystack, 0,strpos($haystack, $needle));
    }
?>

You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
<?php

function rstrstr($haystack,$needle, $start=0)
    {
        return substr($haystack, $start,strpos($haystack, $needle));
    }

?>
w3b_monk3y at yahoo dot com 20-Jan-2009 12:28
If you want to emulate strstr's new before_needle parameter pre 5.3 strtok is faster than using strpos to find the needle and cutting with substr. The amount of difference varies with string size but strtok is always faster.
tim 25-Nov-2007 04:42
I simplified prafe at prafesplace dot com's function:

<?php
function strstrbi($haystack, $needle, $before_needle=FALSE, $include_needle=TRUE, $case_sensitive=FALSE) {
 //Find the position of $needle
 if($case_sensitive) {
  $pos=strpos($haystack,$needle);
 } else {
  $pos=strpos(strtolower($haystack),strtolower($needle));
 }

 //If $needle not found, abort
 if($pos===FALSE) return FALSE;

 //Adjust $pos to include/exclude the needle
 if($before_needle==$include_needle) $pos+=strlen($needle);

 //get everything from 0 to $pos?
 if($before_needle) return substr($haystack,0,$pos);

 //otherwise, go from $pos to end
 return substr($haystack,$pos);
}
?>

It's now 600 bytes, down from 2k.

Also, here are replacements for strstr and stristr:

<?php
function strstr($haystack, $needle, $before_needle=FALSE) {
 //Find position of $needle or abort
 if(($pos=strpos($haystack,$needle))===FALSE) return FALSE;

 if($before_needle) return substr($haystack,0,$pos+strlen($needle));
 else return substr($haystack,$pos);
}

function stristr($haystack, $needle, $before_needle=FALSE) {
 //Find position of $needle or abort
 if(($pos=strpos(strtolower($haystack),strtolower($needle)))===FALSE) return FALSE;

 if($before_needle) return substr($haystack,0,$pos+strlen($needle));
 else return substr($haystack,$pos);
}
?>
brett dot jr dot alton at gmail dot com 25-Nov-2007 08:02
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

<?php
$haystack = 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php
?>
prafe at prafesplace dot com 21-Nov-2007 09:14
If you want to use the $before_needle parameter that's only in PHP 5.3.0, I found a way to use it in lower versions.

The code is a bit hefty, but it works. It also has added $include_needle and $case_sensitive.

<?php
// ==== I don't guarantee this is faster than the PHP 6 before needle, ====
// ====  but it works for PHP below 6 atleast. ====
// ==== IT ALSO HAS INCLUDE NEEDLE BOOLEAN.. ====
function strstrbi($haystack,$needle,$before_needle,
$include_needle,$case_sensitive)
{
  $strstr = ($case_sensitive) ? 'strstr' : 'stristr';
  if($before_needle!=true && $before_needle!=false && isset($before_needle)){
      die('PHP: Error in function '.chr(39).'$strstrbi'. chr(39).' :  parameter '. chr(39).'$before_needle'.chr(39).' is not a supplied as a boolean.');
  } // END BOOLEAN CHECK '$before_needle'

  if($include_needle!=true && $include_needle!=false && isset($include_needle)){
    die('PHP: Error in function '.chr(39).'$strstrbi'. chr(39).' : parameter '. chr(39).'$include_needle'.chr(39). ' is not a supplied as a boolean.');
  } // END BOOLEAN CHECK '$include_needle'

  if($case_sensitive!=true && $case_sensitive!=false && isset($case_sensitive)){
    die('PHP: Error in function '.chr(39).'$strstrbi' .chr(39).' : parameter '. chr(39).'$case_sensitive'.chr(39).' is not a supplied as a boolean.');
  } // END BOOLEAN CHECK '$case_sensitive'

  if(!isset($before_needle)){
    $before_needle=false;
  }

  if(!isset($include_needle)){
    $include_needle=true;
  }

  if(!isset($case_sensitive)){
    $case_sensitive=false;
  }

  switch($before_needle){
    case true:
      switch($include_needle){
        case true:
          $temp=strrev($haystack);
          $ret=strrev(substr($strstr($temp,$needle),0));
          break;
        // END case true : $include_needle
        case false:
          $temp=strrev($haystack);
          $ret=strrev(substr($strstr($temp,$needle),1));
          break;
        // END case false : $include_needle
      }
      break;
    // END case true : $before_needle
    case false:
      switch($include_needle){
        case true:
          $ret=$strstr($haystack,$needle);
          break;
        // END case true: $include_needle
        case false:
          $ret=substr($strstr($haystack,$needle),1);
          break;
        // END case false: $include_needle
    }
    break;
    // END case false : $before_needle
  }

  if(!empty($ret)){
    return $ret;
  }else{
    return false;
  }
}
// === END FUNCTION 'strstrbi'

// Example

$email  = 'user@example.com';
$domain = strstrbi($email, '@', false, false, false);
echo $domain; // prints example.com

$user = strstrbi($email, '@', true, false, false);
echo $user; // prints user
?>
root at mantoru dot de 10-Nov-2007 03:22
Please note that $needle is included in the return string, as shown in the example above. This ist not always desired behavior, _especially_ in the mentioned example. Use this if you want everything AFTER $needle.

<?php
function strstr_after($haystack, $needle, $case_insensitive = false) {
    $strpos = ($case_insensitive) ? 'stripos' : 'strpos';
    $pos = $strpos($haystack, $needle);
    if (is_int($pos)) {
        return substr($haystack, $pos + strlen($needle));
    }
    // Most likely false or null
    return $pos;
}

// Example
$email = 'name@example.com';
$domain = strstr_after($email, '@');
echo $domain; // prints example.com
?>
gigaman2003 at halfempty dot co dot uk 24-Feb-2007 12:48
Often you will need to find all occurrences of a string (for security escapes and such)

So I wrote this function to return an array with the locations of all the occurrences. Almost like an advanced strstr.

<?php
function findall($needle, $haystack)
{
    //Setting up
    $buffer=''; //We will use a 'frameshift' buffer for this search
    $pos=0; //Pointer
    $end = strlen($haystack); //The end of the string
    $getchar=''; //The next character in the string
    $needlelen=strlen($needle); //The length of the needle to find (speeds up searching)
    $found = array(); //The array we will store results in

    while($pos<$end)//Scan file
    {
        $getchar = substr($haystack,$pos,1); //Grab next character from pointer
        if($getchar!="\n" || buffer<$needlelen) //If we fetched a line break, or the buffer is still smaller than the needle, ignore and grab next character
        {
            $buffer = $buffer . $getchar; //Build frameshift buffer
            if(strlen($buffer)>$needlelen) //If the buffer is longer than the needle
            {
                $buffer = substr($buffer,-$needlelen);//Truncunate backwards to needle length (backwards so that the frame 'moves')
            }
            if($buffer==$needle) //If the buffer matches the needle
            {
                $found[]=$pos-$needlelen+1; //Add the location of the needle to the array. Adding one fixes the offset.
            }
        }
        $pos++; //Increment the pointer
    }
    if(array_key_exists(0,$found)) //Check for an empty array
    {
        return $found; //Return the array of located positions
    }
    else
    {
        return false; //Or if no instances were found return false
    }
}
?>

Haven't had the chance to speed test it, but many optimizations should be possible. It just works enough for me. Hope it saves someone a lot of time.
06-Jun-2005 09:13
suggestion for [leo dot nard at free dot fr]:
to be able to cut the string without having the html entities being cut in half, use this instead:

<?php

$oldstr = "F&ouml;r att klippa av en str&auml;ng som inneh&aring;ller skandinaviska (eller Franska, f&ouml;r den delen) tecken, kan man g&ouml;ra s&aring;h&auml;r...";

$length = 50;

# First, first we want to decode the entities (to get them as usual chars), then cut the string at for example 50 chars, and then encoding the result of that again.

# Or, as I had it done, in one line:
$newstr = htmlentities(substr(html_entity_decode($oldstr), 0, $length));
$newstr2 = substr($oldstr, 0, $length);
# It's not quite as much code as the snippet you've coded to remove the half-portions... ;)
# Hopefully somebody finds this useful!
echo "Without the decode-encode snippet:
$newstr2

With the decode-encode snippet:
$newstr";
?>

The above outputs this:

Without the decode-encode snippet:
F&ouml;r att klippa av en str&auml;ng som inneh&ar

With the decode-encode snippet:
F&ouml;r att klippa av en str&auml;ng som inneh&aring;ller skandin

First post in this db ;)
Best regards, Mikael R�nn, FIN
leo dot nard at free dot fr 24-May-2005 02:12
When encoding ASCII strings to HTML size-limited strings, sometimes some HTML special chars were cut.

For example, when encoding "��" to a string of size 10, you would get: "à&a" => the second character is cut.

This function will remove any unterminated HTML special characters from the string...

<?php
function cut_html($string)
{
    $a=$string;

    while ($a = strstr($a, '&'))
    {
        echo "'".$a."'\n";
        $b=strstr($a, ';');
        if (!$b)
        {
            echo "couper...\n";
            $nb=strlen($a);
            return substr($string, 0, strlen($string)-$nb);
        }
        $a=substr($a,1,strlen($a)-1);
    }
    return $string;
}
?>
Romuald Brunet 21-Jan-2004 12:25
Regarding the note of the manual concerning the speed of strstr against strpos, for people who wants to check a needle occurs within haystack, it apprears that strstr() is in facts faster than strpos().

Example:
<?php
// [VERY] Quick email check:
if ( strstr("email@domain.tld", "@") ) {
// Ok
}
?>

is faster than

<?php
if ( strpos("email@domain.tld", "@") !== FALSE ) {
// Ok
}

Without using the true equality with !==, strpos() is faster. But then if the haystack starts with needle the condition whould not be met.
php at silisoftware dot com 14-Feb-2003 03:37
PHP versions before 4.3.0 (tested on 4.2.2 and 4.2.3) return the $haystack from $needle only up to the first null character. So for example:

<?php
$string = strstr("one#two\x00three", "#");
// PHP 4.2.x:  $string contains "#two"
// PHP 4.3.0:  $string contains "#two\x00three"
?>

If you're trying to match nulls, you will probably get back an empty string:

<?php
$string = strstr("one#two\x00three", "\x00");
// PHP 4.2.x:  $string contains ""
// PHP 4.3.0:  $string contains "\x00three"
?>
strspn
strtok
Обработка строк


Разбивает строку на токены

strstr
strtolower
Обработка строк
PHP Manual

strtok

(PHP 4, PHP 5)

strtok — Разбивает строку на токены

Описание

string strtok ( string $str , string $token )
string strtok ( string $token )

strtok() разбивает строку str на подстроки (токены), используя в качестве разделителей символы из token. Например, строку "This is an example string" можно разбить на отдельные слова используя пробел в качестве разделителя.

Заметьте, что исходная строка передается только при первом вызове этой функции. Последующим вызовам передаются только разделители, так как эта функция сохраняет исходную строку и запоминает позицию в этой строке между вызовами. Для работы с новой строкой нужно снова вызвать функцию с двумя аргументами. Обратите внимание, что в параметре token можно использовать несколько разделителей. Строка будет делиться по любому найденному символу, присутствующему в этом параметре.

Список параметров

str

Строка (string), разбиваемая на подстроки (токены).

token

Разделитель строки str.

Возвращаемые значения

Токен (string).

Примеры

Пример #1 Пример использования strtok()

<?php
$string = "This is\tan example\nstring";
/* В качестве разделителей используем пробел, табуляцию и перевод строки */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

Начиная с PHP 4.1.0, был изменен способ обработки пустых подстрок. До версии 4.1.0 эта функция возвращала пустые подстроки, а начиная с 4.1.0 эти подстроки пропускаются.

Пример #2 Старый способ обработки пустых подстрок функцией strtok()

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Результат выполнения данного примера:

    string(0) ""
    string(9) "something"

Пример #3 Новый способ обработки пустых подстрок функцией strtok()

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Результат выполнения данного примера:

    string(9) "something"
    bool(false)

Примечания

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Смотрите также

  • split() - Разбиение строки на массив по регулярному выражению
  • explode() - Разбивает строку с помощью разделителя

User Contributed Notes

emmanuel dot antico at gmail dot com 15-Mar-2012 01:18
get the last part of a string after a given character in one line

<?php
$class_name = strrev(strtok(strrev('java.lang.Object'), '.'));
echo $class_name;
?>

will output:

Object
pradador at me dot com 13-May-2011 12:10
Here's a simple class that allows you to iterate through string tokens using a foreach loop.

<?php
/**
 * The TokenIterator class allows you to iterate through string tokens using
 * the familiar foreach control structure.
 *
 * Example:
 * <code>
 * <?php
 * $string = 'This is a test.';
 * $delimiters = ' ';
 * $ti = new TokenIterator($string, $delimiters);
 *
 * foreach ($ti as $count => $token) {
 *     echo sprintf("%d, %s\n", $count, $token);
 * }
 *
 * // Prints the following output:
 * // 0. This
 * // 1. is
 * // 2. a
 * // 3. test.
 * </code>
 */
class TokenIterator implements Iterator
{
    /**
     * The string to tokenize.
     * @var string
     */
    protected $_string;

    /**
     * The token delimiters.
     * @var string
     */
    protected $_delims;

    /**
     * Stores the current token.
     * @var mixed
     */
    protected $_token;

    /**
     * Internal token counter.
     * @var int
     */
    protected $_counter = 0;

    /**
     * Constructor.
     *
     * @param string $string The string to tokenize.
     * @param string $delims The token delimiters.
     */
    public function __construct($string, $delims)
    {
        $this->_string = $string;
        $this->_delims = $delims;
        $this->_token = strtok($string, $delims);
    }

    /**
     * @see Iterator::current()
     */
    public function current()
    {
        return $this->_token;
    }

    /**
     * @see Iterator::key()
     */
    public function key()
    {
        return $this->_counter;
    }

    /**
     * @see Iterator::next()
     */
    public function next()
    {
        $this->_token = strtok($this->_delims);

        if ($this->valid()) {
            ++$this->_counter;
        }
    }

    /**
     * @see Iterator::rewind()
     */
    public function rewind()
    {
        $this->_counter = 0;
        $this->_token   = strtok($this->_string, $this->_delims);
    }

    /**
     * @see Iterator::valid()
     */
    public function valid()
    {
        return $this->_token !== FALSE;
    }
}
?>
elarlang at gmail dot com 22-Mar-2011 10:45
If you have memory-usage critical solution, you should keep in mind, that strtok function holds input string parameter (or reference to it?) in memory after usage.

<?php
function tokenize($str, $token_symbols) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }
}
?>
Test-cases with handling ~10MB plain-text file:
Case #1 - unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // mem usage 9.75383758545 MB (memory_get_usage() / 1024 / 1024));
tokenize($str, $token_symbols); // mem usage 9.75400161743 MB
unset($str); // 9.75395584106 MB
?>
Case #1 result: memory is still used

Case #2 - call strtok again
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75401306152 MB
tokenize($str, $token_symbols); // 9.75417709351
strtok('', ''); // 9.75421524048
?>
Case #2 result: memory is still used

Case #3 - call strtok again AND unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75410079956 MB
tokenize($str, $token_symbols); // 9.75426483154 MB
unset($str);
strtok('', ''); // 0.0543975830078 MB
?>
Case #3 result: memory is free

So, better solution for tokenize function:
<?php
function tokenize($str, $token_symbols, $token_reset = true) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }

    if($token_reset)
        strtok('', '');
}
?>
fabiolimasouto at gmail dot com 20-Nov-2010 05:54
this example will hopefully help you understand how this function works:

<?php
$selector = 'div.class#id';
$tagname = strtok($selector,'.#');
echo $tagname.'<br/>';

while($tok = strtok('.#'))
{
 echo $tok.'<br/>';
}

?>

Outputs:
div
class
id
php at ciutureanu dot ro 08-Sep-2010 08:08
I wrote a function which adds links based on a list of keywords => hrefs, avoiding attributes inside HTML tags which matches those keywords.

<?php
    function addLinks($str_in, $replaces) {
        $str_out = '';
        $tok = strtok($str_in, '<>');
        $must_replace = (substr($str_in, 0, 1) !== '<');
        while ($tok !== false) {
            if ($must_replace) {
                foreach ($replaces as $tag => $href) {
                    if (preg_match('/\b' . $tag . '\b/', $tok)) {
                        $tok = preg_replace('/\b(' . $tag . ')\b/', '<a title="' . $href . '" href="' . $href . '">\1</a>', $tok, 1);
                        unset($replaces[$tag]);
                    }
                }
            } else {
                $tok = "<$tok>";
            }
            $str_out .= $tok;
            $tok = strtok('<>');
            $must_replace = !$must_replace;
        }
        return $str_out;
    }

    $replaces = array(
        'Obama' => 'http://en.wikipedia.org/wiki/Barack_Obama',
        'php' => 'http://www.php.net/',
    );
    $s = 'This php function will <em title="Obama">replace</em> only first occurance of Obama, but not the second occurance of Obama';
    echo "$s<hr />" . addLinks($s, $replaces);
?>
benighted at gmail dot com 06-Nov-2009 06:47
Simple way to tokenize search parameters, including double or single quoted keys.  If only one quote is found, the rest of the string is assumed to be part of that token.

<?php
            $token = strtok($keywords,' ');
            while ($token) {
                // find double quoted tokens
                if ($token{0}=='"') { $token .= ' '.strtok('"').'"'; }
                // find single quoted tokens
                if ($token{0}=="'") { $token .= ' '.strtok("'")."'"; }

                $tokens[] = $token;
                $token = strtok(' ');
            }
?>

Use substr(1,strlen($token)) and remove the part that adds the trailing quotes if you want your output without quotes.
azeem 02-Sep-2009 12:14
Here is a java like StringTokenizer class using strtok function:

<?php

/**
 * The string tokenizer class allows an application to break a string into tokens.
 *
 * @example The following is one example of the use of the tokenizer. The code:
 * <code>
 * <?php
 *    $str = 'this is:@\t\n a test!';
 *    $delim = ' !@:'\t\n; // remove these chars
 *    $st = new StringTokenizer($str, $delim);
 *    while ($st->hasMoreTokens()) {
 *        echo $st->nextToken() . "\n";
 *    }
 *    prints the following output:
 *      this
 *      is
 *      a
 *      test
 * ?>
 * </code>
 */
class StringTokenizer {

    /**
     * @var string
     */
    private $token;

    /**
     * @var string
     */
    private $delim;
    /**
     * Constructs a string tokenizer for the specified string
     * @param string $str String to tokenize
     * @param string $delim The set of delimiters (the characters that separate tokens)
     * specified at creation time, default to ' '
     */
    public function __construct(/*string*/ $str, /*string*/ $delim = ' ') {
        $this->token = strtok($str, $delim);
        $this->delim = $delim;
    }

    public function __destruct() {
        unset($this);
    }

    /**
     * Tests if there are more tokens available from this tokenizer's string. It
     * does not move the internal pointer in any way. To move the internal pointer
     * to the next element call nextToken()
     * @return boolean - true if has more tokens, false otherwise
     */
    public function hasMoreTokens() {
        return ($this->token !== false);
    }

    /**
     * Returns the next token from this string tokenizer and advances the internal
     * pointer by one.
     * @return string - next element in the tokenized string
     */
    public function nextToken() {
        $current = $this->token;
        $this->token = strtok($this->delim);
        return $current;
    }
}
?>
yanick dot rochon at gmail dot com 15-Jun-2009 09:37
Here is a small function I wrote as I needed to extract some named tokens from a string (a la Google). For example, I needed to format a string like "extension:gif size:64M animated:true author:'John Bash'" into

array(
  'extension' => 'gif',
  'size' => '64M',
  'animated' => true,
  'author' => 'John Bash'
)

So, here's the code:

<?php

header('Content-type: text/plain; charset=utf-8');

/**
 * NOTE : use mbstring.func_overload for multi-byte support with this function
 *
 * @param string $string             the string to tokenize
 * @param int $offset                the starting offset
 * @param string $defaultTokenName   the default token name if none specified
 * @param string $groupDelimiters    the characters to delimit token groups
 * @param string $groupNameDelimiter the character(s) to delimit token group names
 * @return array
 */
function getTokens(
        $string,
        $offset = 0,
        $defaultTokenName = null,
        $groupDelimiters = '\'"',
        $groupNameDelimiter = ':')
{

    if ($offset >= strlen($string)) {
        //echo "offset out of range";
        return false;
    }

    $spaces = " \t\n\r";   // space characters

    // add group delimiters to spaces...
    $groupSpaces = $spaces . $groupNameDelimiter;
    $delimiters = $groupSpaces . $groupDelimiters;

    //var_dump($groupSpaces);

    $string = ltrim(substr($string, $offset), $groupSpaces);
    $token_strings = array();

    //echo "String is : " . $string . "\n";

    // 1. split all tokens...
    while ($offset < strlen($string)) {
        $lastOffset = $offset;
        $escaped = false;

        if (false !== strpos($groupDelimiters, $char = $string[$offset])) {
            $groupChar = $char;
        } else {
            $groupChar = null;
        }

        if (null !== $groupChar) {
            while (($offset < strlen($string)) && (($groupChar !== ($char = $string[++$offset])) || $escaped)) {
                //$offset++;
                $escaped = ('\\' === $char);
            }
            $offset++;
            //echo "*** Grouped : " . substr($string, $lastOffset, $offset - $lastOffset) . "\n";
        } else {
            while (($offset < strlen($string)) && ((false === strpos($delimiters, $char = $string[$offset])) || $escaped)) {
                $offset++;
                $escaped = ('\\' === $char);
            }
            //echo "*** Non-group : " . substr($string, $lastOffset, $offset - $lastOffset) . "\n";
        }
        //skip spaces...
        while (($offset < strlen($string)) && ((false !== strpos($groupSpaces, $char = $string[$offset])) || $escaped)) {
            $offset++;
            $escaped = ('\\' === $char);
        }

        $token_strings[] = substr($string, $lastOffset, $offset - $lastOffset);
        //echo "Next token = '" . end($token_strings) . "'\n";
    }

    $tokens = array();
    $tokenName = null;
    foreach ($token_strings as $token_str) {
        // clean $token_str
        $token_str = trim(stripslashes($token_str), $spaces);
        $str_value = trim($token_str, $delimiters);
        switch (strtolower($str_value)) {
            case 'true': $str_value = true; break;
            case 'false': $str_value = false; break;
            default: break;
        }

        // is it a token name?
        if (':' === substr($token_str, -1, 1)) {
            if (!empty($tokenName)) {
                $tokens[$tokenName] = '';
            }
            $tokenName = trim($token_str, $delimiters);
        } else {
            if (!empty($tokenName)) {
                if (isset($tokens[$tokenName])) {
                    $tokens[$tokenName] = array(
                        $tokens[$tokenName],
                        $str_value
                    );
                } else {
                    $tokens[$tokenName] = $str_value;
                }
                $tokenName = null;
            } elseif (empty($defaultTokenName)) {
                $tokens[] = trim($token_str, $delimiters);;
            } else {
                if (isset($tokens[$defaultTokenName])) {
                    $tokens[$defaultTokenName] = array(
                        $tokens[$defaultTokenName],
                        $str_value
                    );
                } else {
                    $tokens[$defaultTokenName] = $str_value;
                }
            }
        }
    }
    if (!empty($tokenName)) {
        $tokens[$tokenName] = '';
    }

    return $tokens;
}

$str = "check1: test "
     . "check2:'hello world' "
     . 'check3: "foo" '
     . "check4: \\\"try this\\\""
     . '"buz" '
     . 'check1:true';

?>
KrazyBox 06-Mar-2009 06:11
As of the change in strtok()'s handling of empty strings, it is now useless for scripts that rely on empty data to function.

Take for instance, a standard header. (with UNIX newlines)

http/1.0 200 OK\n
Content-Type: text/html\n
\n
--HTML BODY HERE---

When parsing this with strtok, one would wait until it found an empty string to signal the end of the header. However, because strtok now skips empty segments, it is impossible to know when the header has ended.
This should not be called `correct' behavior, it certainly is not. It has rendered strtok incapable of (properly) processing a very simple standard.

This new functionality, however, does not affect Windows style headers. You would search for a line that only contains "\r"
This, however, is not a justification for the change.
Logikos 03-Jan-2009 10:12
This looks very simple, but it took me a long time to figure out so I thought I'd share it incase someone else was wanting the same thing:

this should work similar to substr() but with tokens instead!

<?php
/* subtok(string,chr,pos,len)
 *
 * chr = chr used to seperate tokens
 * pos = starting postion
 * len = length, if negative count back from right
 *
 *  subtok('a.b.c.d.e','.',0)     = 'a.b.c.d.e'
 *  subtok('a.b.c.d.e','.',0,2)   = 'a.b'
 *  subtok('a.b.c.d.e','.',2,1)   = 'c'
 *  subtok('a.b.c.d.e','.',2,-1)  = 'c.d'
 *  subtok('a.b.c.d.e','.',-4)    = 'b.c.d.e'
 *  subtok('a.b.c.d.e','.',-4,2)  = 'b.c'
 *  subtok('a.b.c.d.e','.',-4,-1) = 'b.c.d'
 */
function subtok($string,$chr,$pos,$len = NULL) {
  return implode($chr,array_slice(explode($chr,$string),$pos,$len));
}
?>

explode breaks the tokens up into an array, array slice alows you to pick then tokens you want, and then implode converts it back to a string

although its far from a clone, this was inspired by mIRC's gettok() function
magne 25-Jun-2008 11:43
Quick and dirty function to tokenize:

function stringTokenize($sBuffer, $sSplit) {
        $iCount = 0;

        if(strlen($sBuffer) == 0)
            return;

        $sToken = strtok($sBuffer, $sSplit);
        $aTokens[$iCount] = $sToken;

        while ($sToken !== false) {
            $sToken = strtok($sSplit);
            if(strlen($sToken) > 0) {
                $iCount++;
                $aTokens[$iCount] = $sToken;
            }
        }    // end while

        return $aTokens;
    }
Aditya P Bhatt (adityabhai at gmail dot com) 27-Mar-2008 10:16
<head>
<title>Tokenise the incoming string</title>
</head>
<body bgcolor=white>
The input was
<?php
$name = "SOME TEXT EXAMPLE"; // You can change string here
print ("$name.<P>In pieces, thats:<br>");

$toke = strtok($name," \t");
    while ($toke) {
        print ("$toke<BR>");
        $toke = strtok(" \t");
    }
$oneword = implode("_",explode(" ",$name));
print ("<br>or as one word: $oneword");

?>
</body>
Geert 14-Apr-2006 06:37
Shauns function needs a little update because it produces an error message that the variables $text and $words were not defined. Written like this it won't produce an error:

<?php
function summarize($paragraph, $limit){
  $tok = strtok($paragraph, " ");
  $text="";
  $words='0';
  while($tok){
   $text .= " ".$tok;
   $words++;
   if(($words >= $limit) && ((substr($tok, -1) == "!")||(substr($tok, -1) == ".")))
     break;
   $tok = strtok(" ");
  }
return ltrim($text);
}
?>
mac.com@nemo 18-Feb-2006 01:49
This function takes a string and returns an array with words (delimited by spaces), also taking into account quotes, doublequotes, backticks and backslashes (for escaping stuff).
So

$string = "cp   'my file' to `Judy's file`";
var_dump(parse_cli($string));

would yield:

array(4) {
  [0]=>
  string(2) "cp"
  [1]=>
  string(7) "my file"
  [2]=>
  string(5) "to"
  [3]=>
  string(11) "Judy's file"
}

Way it works, runs through the string character by character, for each character looking up the action to take, based on that character and its current $state.
Actions can be (one or more of) adding the character/string to the current word, adding the word to the output array, and changing or (re)storing the state.
For example a space will become part of the current 'word' (or 'token') if $state is 'doublequoted', but it will start a new token if $state was 'unquoted'.
I was later told it's a "tokeniser using a finite state automaton". Who knew :-)

<?php

#_____________________
# parse_cli($string) /
function parse_cli($string) {
    $state = 'space';
    $previous = '';     // stores current state when encountering a backslash (which changes $state to 'escaped', but has to fall back into the previous $state afterwards)
    $out = array();     // the return value
    $word = '';
    $type = '';         // type of character
    // array[states][chartypes] => actions
    $chart = array(
        'space'        => array('space'=>'',   'quote'=>'q',  'doublequote'=>'d',  'backtick'=>'b',  'backslash'=>'ue', 'other'=>'ua'),
        'unquoted'     => array('space'=>'w ', 'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'quoted'       => array('space'=>'a',  'quote'=>'w ', 'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'doublequoted' => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'w ', 'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'backticked'   => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'w ', 'backslash'=>'e',  'other'=>'a'),
        'escaped'      => array('space'=>'ap', 'quote'=>'ap', 'doublequote'=>'ap', 'backtick'=>'ap', 'backslash'=>'ap', 'other'=>'ap'));
    for ($i=0; $i<=strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $type = array_search($char, array('space'=>' ', 'quote'=>'\'', 'doublequote'=>'"', 'backtick'=>'`', 'backslash'=>'\\'));
        if (! $type) $type = 'other';
        if ($type == 'other') {
            // grabs all characters that are also 'other' following the current one in one go
            preg_match("/[ \'\"\`\\\]/", $string, $matches, PREG_OFFSET_CAPTURE, $i);
            if ($matches) {
                $matches = $matches[0];
                $char = substr($string, $i, $matches[1]-$i); // yep, $char length can be > 1
                $i = $matches[1] - 1;
            }else{
                // no more match on special characters, that must mean this is the last word!
                // the .= hereunder is because we *might* be in the middle of a word that just contained special chars
                $word .= substr($string, $i);
                break; // jumps out of the for() loop
            }
        }
        $actions = $chart[$state][$type];
        for($j=0; $j<strlen($actions); $j++) {
            $act = substr($actions, $j, 1);
            if ($act == ' ') $state = 'space';
            if ($act == 'u') $state = 'unquoted';
            if ($act == 'q') $state = 'quoted';
            if ($act == 'd') $state = 'doublequoted';
            if ($act == 'b') $state = 'backticked';
            if ($act == 'e') { $previous = $state; $state = 'escaped'; }
            if ($act == 'a') $word .= $char;
            if ($act == 'w') { $out[] = $word; $word = ''; }
            if ($act == 'p') $state = $previous;
        }
    }
    if (strlen($word)) $out[] = $word;
    return $out;
}

?>
rawat dot arun at gmail dot com 25-Aug-2005 07:31
I was trying to compare two strings of equal length using strtok. However using them at same time leads into erratic output. Therefore the output of each strok can first be stored in an array and then be used for comparison. Here is small code for it.
<?php
$string = "This is an XYZ example string";
$tok = strtok($string, ' ');
while ($tok !== false) { $toks[] = $tok; $tok = strtok(' '); }
$string_1= "This is an unknown example string";
$tok1= strtok($string_1, ' ');while ($tok1 !== false) {
$toks1[] = $tok1;$tok1 = strtok(' '); }
$ctr=0;
while (each ($toks))
if ($toks[$ctr]==$toks1[$ctr])
{echo "W=$toks[$ctr]<br />"; echo "W1=$toks1[$ctr]<br />";
  $ctr++;  } else $ctr++;     ?>
Thanks,
Arun
brian dot cairns dot remove dot this at commerx dot com 26-May-2005 12:11
I was looking for a function to tokenize a string, taking double-quoted inline strings into account (for breaking up search queries, for example), but none of the ones I found seemed particularly efficient or elegant, so I wrote my own.  Here it is:

<?
// split a string into an array of space-delimited tokens, taking double-quoted strings into account
function tokenizeQuoted($string)
{
    for($tokens=array(), $nextToken=strtok($string, ' '); $nextToken!==false; $nextToken=strtok(' '))
    {
        if($nextToken{0}=='"')
            $nextToken = $nextToken{strlen($nextToken)-1}=='"' ?
                substr($nextToken, 1, -1) : substr($nextToken, 1) . ' ' . strtok('"');
        $tokens[] = $nextToken;
    }
    return $tokens;
}
?>

Example:

$tokens = tokenizeQuoted('this is "my test string" single "words" work too');

Results in $tokens containing:

Array
(
    [0] => this
    [1] => is
    [2] => my test string
    [3] => single
    [4] => words
    [5] => work
    [6] => too
)

Hope this helps someone.
soletan at toxa dot de 28-Apr-2005 04:47
strtok's new behaviour isn't more correct than the old one.

Example: When parsing a string for a quoted-string (e.g. RFC822-header without wanting to install mailparse from PECL!) then I walk char by char and whenever I encounter a double-quote I take strtok to find the related closing double-quote in string quite easily ... this is done for improved performance.
But what if there's an empty quoted-string ...

Another example is then having lines like

name="quoted-value"; second="another one";

I get the name using strtok with '=', then I check value to be quoted, which is true and thus I take the method described before to get the quoted string. Then all what's left is

; second="another one";

now I advance and drop any whitespaces after current value assignment ... well users shouldn't obey to never ever in life have no whitespaces before that damn semicolon for sure, and that's why I drop that with strtok (using ';') again to get to the next optional assignment with another

$s = strtok( '' )

I KNOW, there are ways to work around this using trim and the alikes. But that doesn't explain why strtok is now working "correct" while it didn't do before ...
cs2xz at bath dot ac dot uk 07-Apr-2005 06:30
There is a method to remove all the punctuations and only put the words into an array called "$token", where variable $invalid lists all the punctuations and "\xxx" are the octal numbers of punctuations. At the end, dispalys total number of words in $string and the 4th words in the string.

$string = "Hello,     $%^\n\\\"jeff!!!!\"/. 'How are you!'";
$invalid = "\40\41\42\43\44\45\46\47\48\49\50\51\52\53 \54\55\56\57\72\73\74\75\76 \77\100\133\134\135\136\137\138\139\140 \173\174\175\176\n\r\t";

$tok = strtok($string, $invalid);
while ($tok) {
   echo "Word=$tok<br>";
   $token[]=$tok;
   $tok = strtok($invalid);
}

// displays the number of words in the string and the 4th word
echo "Number of token: " . count($token) . "<br>";
echo $token[3];
James 28-Sep-2004 06:51
Be very careful with using strtok if there's any chance that you may be calling other functions that may use strtok as well.  If any other function that you call while parsing the string decides to call strtok as well, it will clobber the internal string pointer being used by strtok and you may get unexpected results.  Here's some code to explain what I mean:

function parse_string2($string2) {
    for($tok = strtok($string2, '.'); $tok !== false; $tok = strtok(".")) {
        echo $tok;
    }
}

$string1 = "1.2.3.4.!.8.9";
$string2 = "5.6.7";

for($word = strtok($string1, '.'); $word !== false; $word = strtok(".")) {
    if ($word == '!') {
        echo parse_string2($string2);
    } else {
        echo $word;
    }
}

If I didn't know the internals of the function parse_string2 (say someone else develops that), but all I know is that parse_string2 should print out 567, then my expected output might be:

123456789

Instead, you only get: 1234567.

It would be interesting if they could implement a strtok_r where you could explicitly denote which string to tokenize.
manicdepressive at mindless dot com 19-Jun-2004 06:01
<pre><?php
/** get leading, trailing, and embedded separator tokens that were 'skipped'
if for some ungodly reason you are using php to implement a simple parser that
needs to detect nested clauses as it builds a parse tree */

$str = "(((alpha(beta))(gamma))";

$seps = '()';
$tok = strtok( $str,$seps ); // return false on empty string or null
$cur = 0;
$dumbDone = FALSE;
$done = (FALSE===$tok);
while (!$done) {
   // process skipped tokens (if any at first iteration) (special for last)
   $posTok = $dumbDone ? strlen($str) : strpos($str, $tok, $cur );
   $skippedMany = substr( $str, $cur, $posTok-$cur ); // false when 0 width
   $lenSkipped = strlen($skippedMany); // 0 when false
   if (0!==$lenSkipped) {
      $last = strlen($skippedMany) -1;
      for($i=0; $i<=$last; $i++){
         $skipped = $skippedMany[$i];
         $cur += strlen($skipped);
         echo "skipped: $skipped\n";
      }
   }
   if ($dumbDone) break; // this is the only place the loop is terminated

   // process current tok
   echo "curr tok: ".$tok."\n";

   // update cursor
   $cur += strlen($tok);

   // get any next tok
   if (!$dumbDone){
      $tok = strtok($seps);
      $dumbDone = (FALSE===$tok);
      // you're not really done till you check for trailing skipped
   }
};
?></pre>
DethMetal Jeff 10-Mar-2004 10:18
If you need to parse through a very large delimited text file (such as a word list) combine strtok with file_get_contents.  It is much faster than all of the other alternatives i have found (using file() to parse the file into an array, reading the file line by line using fgets())

  $dictionary=file_get_contents('path/to/dictionary', 1);

  //check that the file was read properly
  if(!$dictionary){
    return("read error");
  }

  //dictionary is \n delimited
  $tok=strtok($dictionary, "\n");
  //loop through until we reach the end of the string
  while($tok){
    //do whatever it is you need to do with the $tok string here
    $tok=strtok("\n"); //get next string
  }
torsten at KILL_ALL_SPAM dot dargers dot de 20-Dec-2003 08:00
Beware! This function cannot be used to start a recursion during the loop. Sh..

You have to collect the results in an array and then cycle the recursion through that array.

Example:
$word=strtok($line,TOKENS);
while ($word) {

   // DO NOT START RECURSION HERE USING $word PARAMETER

  $words[] = $word;

}

foreach( $words as $word ) {

   *RECURSE*($word);

}

// This seems very silly but as the function is not instantiated between recursions it cannot work directly.
jrust AT rustyparts DOT com 23-May-2003 07:09
Had a website which was using way too many of the old functionality of strtok to convert to the new >PHP 4.1.0 way so I wrote this function to mimic the way strtok was done prior to 4.1.0

function strtok_old($string, $delim = null) {
    static $origDelim, $origString, $origPos;
    if (!isset($origDelim)) {
        $origDelim = null;
    }
    if (!isset($origString)) {
        $origString = null;
    }
    if (!isset($origPos)) {
        $origPos = null;
    }

    // continuing an already started strtok
    if ($string == $origDelim) {
        $string = $origString;
        $delim = $origDelim;
    }
    // else starting from scratch
    else {
        $origString = $string;
        $origDelim = $delim;
        $origPos = 0;
    }

    if ($origPos !== false && $origPos < strlen($string)) {
        $newPos = strpos($string, $delim, $origPos);
    }
    else {
        $newPos = false;
    }

    // the token wasn't found, go to end of string
    if ($newPos === false) {
        $newPos = strlen($string);
    }

    $return = substr($string, $origPos, ($newPos - $origPos));
    $origPos = ++$newPos;
    return $return;
}
shaun at phplabs dot com 04-Dec-2002 09:57
Here's some code to extract the first part of a long paragraph, e.g. to use as a summary. Starting at the beginning of the paragraph it gets as many complete sentences as are necessary to contain $limit words. For example, with $limit at 20 it would return the first two sentences of the paragraph you're reading right now (the first 20 words plus the rest of the sentence in which the limit was hit).

function summarize($paragraph, $limit){
  $tok = strtok($paragraph, " ");
  while($tok){
    $text .= " $tok";
    $words++;
    if(($words >= $limit) && ((substr($tok, -1) == "!")||(substr($tok, -1) == ".")))
      break;
    $tok = strtok(" ");
  }
return ltrim($text);
}

Might be a better way to do this, but it worked for me. Hope you find it useful!
desolate19 at NOSPAM dot hotmail dot com 02-May-2002 03:28
Here is yet another explanation of strtok for the explode/split comments.

You can do things with strtok that you can't do with explode/split. explode breaks a string using another string, split breaks a string using a regular expression.  strtok breaks a string using single _characters_ , but the best part is you can use multiple characters at the same time.

For example, if you are accepting user input and aren't sure how the user will decide to divide up their data you could choose to tokenize on spaces, hyphens, slashes and backslashes ALL AT THE SAME TIME:

<?PHP

$teststr = "blah1 blah2/blah3-blah4\\blah5";

$tok = strtok($teststr," /-\\");
while ($tok !== FALSE)
{
  $toks[] = $tok;
  $tok = strtok(" /-\\");
}

while (list($k,$v) = each($toks))
{
  print ("$k => $v&lt;BR&gt;\n");
}

?>

/* OUTPUT:
0 => blah1
1 => blah2
2 => blah3
3 => blah4
4 => blah5
*/

You can't do that with explode, and this should be faster than using split because split uses regular expressions.

And for the comments about explode/split putting your output into an array... as you can see, it's not hard to work with arrays in PHP.
11-Dec-2001 12:57
The example is unnecessarily confusing for beginners.

1) It is NOT strtok that fails when the returned string evaluates
to false in conditional expression, it is the loop test. A correct test is
while($tok !== false)

2) the same functionality (AS THE EXAMPLE) can be obtained with
explode. Note that if you only need the first few tokens you can
put a limit on explode!! read the manual :)
array explode (string separator, string string [, INT LIMIT])

What you can NOT do with explode (or split) is changing the
separator after a token is returned, as for example, when parsing a
string along a simple format :

$styleStr = "color:#FFFFFF;font-size:12";
$key = strtok($styleStr,":");
while ($key !== false){
 $styleTab[$key]= strtok(";"); // do not change the target
 $key = strtok(":"); // string, just the separator list
}

$styleTab is array("color"=>"#FFFFFF","font-size"=>"12")

If you need the remaining of the string do :
$remaining = strtok(''); //(empty separator)

Ivan
slt at municipium dot com dot pl 14-Feb-2001 11:12
As 'mckay' wrote, strtok 2nd argument is a list of tokens, not a string delimiter. It's not so obvious as one may think and it may be confusing for beginners like me. So, in the docs, it should state sth. like that
strtok(string where2search, char token2cut).
And for the above split-lover =) 'tysonlt' -> it's better to use explode bcoz it's lighter than split (to quote original manual: "(...) use explode(), which doesn't incur the overhead of the regular expression engine")
regards,
     StarLight
tysonlt at spamless dot webmedia dot com dot au 03-Oct-2000 03:34
Why use strtok at all?

If it's so flaky, why not just use split?

eg.
$token_array = split("$delim", $string);

Then you can use all the nice array functions on it! :)
David dot Mazur at student dot kuleuven dot ac dot be 16-Aug-2000 04:40
If you want to tokenize only part of the string, and store the "untokenized" part in some
variable, you have to call strtok one last time with separator "" (i.e. the empty string).
strstr
strtolower
Обработка строк


Преобразует строку в нижний регистр

strtok
strtoupper
Обработка строк
PHP Manual

strtolower

(PHP 4, PHP 5)

strtolower — Преобразует строку в нижний регистр

Описание

string strtolower ( string $str )

Возвращает строку string, в которой все буквенные символы переведены в нижний регистр.

Принадлежность того или иного символа к буквенным определяется с учетом текущей локали. Это означает, что, например, в используемой по умолчанию локали "C", символ Ä не будет преобразован.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает строку в нижнем регистре.

Примеры

Пример #1 Пример использования strtolower()

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // выводит: mary had a little lamb and she loved it so
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strtoupper() - Преобразует строку в верхний регистр
  • ucfirst() - Преобразует первый символ строки в верхний регистр
  • ucwords() - Преобразует в верхний регистр первый символ каждого слова в строке
  • mb_strtolower() - Приведение строки к нижнему регистру

User Contributed Notes

utilmind at gmail 17-May-2012 05:46
Everyone knows that strtolower/strtoupper does not translate cyrillic charactes (cp1251 code page). But I just was surprised that strtolower works twice(!) slower that translating characters with "strtr()".

Here is what I use to translate cyrillic (works for Russian, Ukrainian, Belorussian and cyrillic balcan languages, like Serbian etc):

<?php
// Arrays (REMOVE THE LINE BREAKS! THIS NOT WON'T BE POSTED WITH SUCH LONG LINES!)
$chars_hi = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ
АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯЁЂЃЄЅІЇЈЉЊЋЌЎЏҐ';
$chars_lo = 'abcdefghijklmnopqrstuvwxyz
абвгдежзийклмнопрстуфхцчшщъыьэюяёђѓєѕіїјљњћќўџґ';

// functions
function uppercase($s) {
  global $chars_hi, $chars_lo;
  return strtr($s, $chars_lo, $chars_hi);
}

function lowercase($s) {
  global $chars_hi, $chars_lo;
  return strtr($s, $chars_hi, $chars_lo);
}
?>

Remember, it works TWICE FASTER than strtoupper/strtolower! So maybe someone will would like to translate the arrays for another code pages different than cp1251
on at niepodam dot pl 24-Oct-2011 07:23
If the input string is in different language that server locale, then you should use mb_strtolower() function.
RCube 31-Mar-2011 04:57
To convert an entire array to lower, I prefer this method;

<?php
function arraytolower(array $array, $round = 0){
  return unserialize(strtolower(serialize($array)));
}
?>

3 lines of code seem a lot less overhead than 10-40.
If there's any intrinsic problem with this method, please post it.
marcin at maydesign dot pl 22-Jun-2010 03:16
strtolower(); doesn't work for polish chars

<?php strtolower("mĄkA"); ?>
will return: mĄka;

the best solution - use mb_strtolower()

<?php mb_strtolower("mĄkA",'UTF-8'); ?>
will return: mąka
sanderwind at gmail dot com 11-Jun-2010 06:03
Very easy way to only make the first character lowercase:

<?php
  function lcfirst($string) {
      $string{0} = strtolower($string{0});
      return $string;
  }
?>
ewertonp at hotmail dot com 30-Sep-2009 11:50
Here is my solution to lowercase strings Latin strings with accents. In this case I've used Brazilian Portuguese locale:

<?PHP

setlocale(LC_ALL, 'pt_BR');

echo strtolower('ÉÁÇÚÍÑ');
// output: éáçúíñ

echo ucfirst(strtolower('éÁÇÚÍÑ'));
// output: Éáçúíñ

?>
leha_grobov 25-Jun-2009 08:03
the strtolower version to support most amount of languages including russian, french and so on:

<?php
function strtolower_utf8($string){
  $convert_to = array(
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
    "v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
    "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
    "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
    "ь", "э", "ю", "я"
  );
  $convert_from = array(
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
    "V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
    "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
    "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
    "Ь", "Э", "Ю", "Я"
  );

  return str_replace($convert_from, $convert_to, $string);
}
?>
Khigashi 22-Jun-2009 02:53
Here is my code, I made because of the accents contained in the latin languages [like the Portuguese of Brazil =)]

<?php
function deepLower($texto){
    //Letras minúsculas com acentos
    $texto = strtr($texto, "
    ĄĆĘŁŃÓŚŹŻABCDEFGHIJKLMNOPRSTUWYZQ
    XVЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ
    ÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖÛÙÚÜÇ
    ", "
    ąćęłńóśźżabcdefghijklmnoprstuwyzq
    xvёйцукенгшщзхъфывапролджэячсмитьбю
    âàáäãêèéëîíìïôõòóöûùúüç
    ");
    return strtolower($texto);
}
?>
hans111 {AT} yahoo {DOT} com 13-May-2009 03:02
Could be useful, if mb string library is not available for whatever the reason:
<?php
    function utf8_strtolower($string) {
        return utf8_encode(strtolower(utf8_decode($string)));
    }
##equally.....
    function utf8_ucfirst($string) {
        return utf8_encode(ucfirst(utf8_decode($string)));
    }
#.....etc...
?>
It has worked for me, just make sure you feed the functions with the proper encoded text (utf-8)

[These functions] only work when translation is between common characters in ISO 8859-1 and UTF-8, that means they will work well with western languages but not cyrillic or asian.
coder at bulgaria dot bg 03-Apr-2009 04:08
for cyrillic and UTF 8 use  mb_convert_case

exampel

<?php
$string = "Австралия";
$string = mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
echo $string;

//output is: австралия
?>
ghutix6 at gmail dot com 15-Mar-2009 01:50
Here is function for working polish lower letters (plus example):

<?php

  function lower_pl($str)
   {
     return strtr($str, "ĄĆĘŁŃÓŚŹŻABCDEFGHIJKLMNOPRSTUWYZQXV", "ąćęłńóśźżabcdefghijklmnoprstuwyzqxv");
   }

  $word ="ŻÓŁTKO";
  $word = lower_pl ($word);

  echo ("<p>$word</p>");

?>

This will turn into: <p>żółtko</p>.
dbers26 at gmail dot com 07-Jan-2009 01:34
the function  arraytolower will create duplicate entries since keys are case sensitive.

<?php
$array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array = arraytolower($array);
?>
/*
Array
(
    [test1] => asgafasdaad
    [TEST2] => ASddhshsDGb
    [TeSt3] => asdasda@asdadadASDASDgh
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
*/

I prefer this method

<?php
  function arraytolower($array, $include_leys=false) {

    if($include_leys) {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array2[strtolower($key)] = arraytolower($value, $include_leys);
        else
          $array2[strtolower($key)] = strtolower($value);
      }
      $array = $array2;
    }
    else {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array[$key] = arraytolower($value, $include_leys);
        else
          $array[$key] = strtolower($value);
      }
    }

    return $array;
  }
?>

which when used like this

<?php
$array = $array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array1 = arraytolower($array);
$array2 = arraytolower($array,true);

print_r($array1);
print_r($array2);
?>

will give output of

Array
(
    [test1] => asgafasdaad
    [TEST2] => asddhshsdgb
    [TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
    [test1] => asgafasdaad
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
s0urce at anonyme dot com 23-Oct-2008 03:05
for someone who needs - arraytolower:

<?php
function arraytolower($array,$round = 0){
    foreach($array as $key => $value){
        if(is_array($value)) $array[strtolower($key)] =  $this->arraytolower($value,$round+1);
        else $array[strtolower($key)] = strtolower($value);
        }
        return $array;
    }
?>

converts the whole array in a levels. keys and values.
rodrigoATsistemasparainternetDOTcomDOTbr 09-Sep-2008 06:25
<?php
function fullLower($str){
   // convert to entities
   $subject = htmlentities($str,ENT_QUOTES);
   $pattern = '/&([a-z])(uml|acute|circ';
   $pattern.= '|tilde|ring|elig|grave|slash|horn|cedil|th);/e';
   $replace = "'&'.strtolower('\\1').'\\2'.';'";
   $result = preg_replace($pattern, $replace, $subject);
   // convert from entities back to characters
   $htmltable = get_html_translation_table(HTML_ENTITIES);
   foreach($htmltable as $key => $value) {
      $result = ereg_replace(addslashes($value),$key,$result);
   }
   return(strtolower($result));
}

echo fullLower("Ã É Ò Õ ÚÙÛ");

//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
concepton at gmail dot com 10-Aug-2008 09:50
comment to "alexfort at list dot ru"

i think better to use this one

<?php
function strtolower_ru($text) {
    $alfavitlover = array('ё','й','ц','у','к','е','н','г', 'ш','щ','з','х','ъ','ф','ы','в', 'а','п','р','о','л','д','ж','э', 'я','ч','с','м','и','т','ь','б','ю');
    $alfavitupper = array('Ё','Й','Ц','У','К','Е','Н','Г', 'Ш','Щ','З','Х','Ъ','Ф','Ы','В', 'А','П','Р','О','Л','Д','Ж','Э', 'Я','Ч','С','М','И','Т','Ь','Б','Ю');

    return str_replace($alfavitupper,$alfavitlover,strtolower($text));
}
?>
alexfort at list dot ru 04-Aug-2008 05:43
<?php
//solution to the Cyrillic and uft-8
function strtolower_Cyrillic($word) {
    $alfavitlover = explode(',', 'ё,й,ц,у,к,е,н,г,ш,щ,з,х,ъ,ф,ы,
    в,а,п,р,о,л,д,ж,э,я,ч,с,м,и,т,ь,б,ю');
    $alfavitupper = explode(',', 'Ё,Й,Ц,У,К,Е,Н,Г,Ш,Щ,З,Х,Ъ,Ф,Ы,
    В,А,П,Р,О,Л,Д,Ж,Э,Я,Ч,С,М,И,Т,Ь,Б,Ю');
    for($wr=0;$wr<=count($alfavitlover);$wr++) {
        $word = str_replace($alfavitupper[$wr], $alfavitlover[$wr], $word);
    }
    return $word;
}
echo strtolower_Cyrillic('СаШа+МаШа');
?>
tushar at sel2in dot com 28-Jul-2008 08:57
Quick and works for accented characters like á

Tested on linux and win apache+php5

<?php
function strtolower2($s){
    $ln = strlen($s);
    $ln1 = $ln -1;
    for($i=0; $i < $ln; $i++){
        $k = ord(substr($s, $i, 1));
        if($k>=65 && $k <= 90){
            if($i > 0){
                $l1 = substr($s, 0, $i);
            }else{
                $l1 ='';
            }
            $l1 = $l1 . chr($k+32);
            if($i < $ln1){
                $l1 = $l1 . substr($s, $i  + 1);
            }
            $s = $l1;

        }
    }
    return $s;
}
?>
Piotr 10-Mar-2008 01:24
///charset=iso-8859-2
 function strtolower_iso8592($string)
    {
        $low=array("ˇ" => "±", "Ć" => "ć", "Ę" => "ę", "Ł" => "ł", "Ó" => "ó", "¦" => "¶", "Ż" => "ż", "¬" => "Ľ", "Ń" => "ń");
        return strtolower(strtr($string,$low));

    }
toringe at infostill dot com 25-Oct-2007 03:27
This will work for all languages using ISO8859_1 - more code than many other but fast.

<?php
function strtolower_iso8859_1($s){
    $i = strlen($s);
    while ($i > 0) {
        --$i;
        $c =ord($s[$i]);
        if (($c & 0xC0) == 0xC0) {
            // two most significante bits on
            if (($c != 215) and ($c != 223)){ // two chars OK as is
                // to get lowercase set 3. most significante bit if needed:
                $s[$i] = chr($c | 0x20);
            }
        }
    }
    return strtolower($s);
}
?>
patricia at steuerungb dot de 17-Oct-2007 06:29
When you're not sure, how the current locale is set, you might find the following function useful. It's strtolower for utf8-formatted text:

<?php
function strtolower_utf8($inputString) {
    $outputString    = utf8_decode($inputString);
    $outputString    = strtolower($outputString);
    $outputString    = utf8_encode($outputString);
    return $outputString;
}
?>

It's not suitable for every occasion, but it surely gets in handy. I use it for lowering German 'Umlauts' like ä and ö.
mr dot blober at gmail dot com 16-Jun-2007 11:39
simple example for Polish characters
<?php
function strtolower_pl($str)
{
return strtr(strtolower($str), '[ĄĆĘŁŃÓŚŹŻ]', '[ąćęłńóśźż]');
}
?>
rok dot kralj at gmail dot com 04-Jun-2007 11:49
Slovenian characters

<?php
    function strtolower_slovenian($string)
    {
        $low=array("Č" => "č", "Ž" => "ž", "Š" => "š");
        return strtolower(strtr($string,$low));
    }

?>
marco at recchiuti dot it 22-May-2007 12:43
Maybe it is not so elegant, but it Works.
It's just a fast Idea and it is what I need.
Any hacks for other characters (link !, ? etc etc) should help.

function RemoveShouting($string)
{
     $frase = "";
     $astri = explode(".", $string);
     foreach ($astri as $elem)
    $frase .= " ".ucfirst(trim(strtolower($elem))).". ";

    return trim($frase);
}

Cheers!
M
mario dot kostelac at gmail dot com 29-Apr-2007 04:42
This is strtolower function for Croatian characters:
function strToLowerCro($string){
    $string = strtolower($string);
    $patterns[0] = '/Č/';
    $patterns[1] = '/Ć/';
    $patterns[2] = '/Ž/';
    $patterns[3] = '/Š/';
    $patterns[4] = '/Đ/';
    $replacements[0] = 'č';
    $replacements[1] = 'ć';
    $replacements[2] = 'ž';
    $replacements[3] = 'š';
    $replacements[4] = 'đ';
    $string = preg_replace($patterns, $replacements, $string);
    return $string;
}
Enjoy...
HQ063 31-Mar-2007 12:37
Similar to last function, but for spanish
    function strtolower_es($string)
    {
        $low=array("Á" => "á", "É" => "é", "Í" => "í", "Ó" => "ó", "Ú" => "ú", "Ü" => "ü", "Ñ" => "ñ");
        return strtolower(strtr($string,$low));
    }
Dinçer Akay 20-Dec-2006 02:32
Turkish Character
<?php
    function strtolower_tr($string)
    {
        $low=array("Ü" => "ü", "Ö" => "ö", "Ğ" => "ğ", "Ş" => "ş", "Ç" => "ç", "İ" => "i", "I" => "ı");
        return strtolower(strtr($string,$low));
    }

?>
Enzo_01 at abv dot bg 06-Nov-2006 11:31
two functions what works with cyrilic text

function cyr_strtolower($a) {
        $offset=32;
        $m=array();
        for($i=192;$i<224;$i++)$m[chr($i)]=chr($i+$offset);
        return strtr($a,$m);
}
function cyr_strtoupper($a) {
        $offset=32;
        $m=array();
        for($i=192;$i<224;$i++)$m[chr($i+$offset)]=chr($i);
        return strtr($a,$m);
}

ex:
 cyr_strtoupper("абвгде"); // АБВГДЕ
 cyr_strtolower("АБВГДЕ"); // абвгде
eduardor2k at redr2k dot com 08-Aug-2006 02:34
I changed it a bit and i found that it's better to put everything in lowercase, and rebuild the text the same way a teacher corrects a text, for now it only checks that the first letter after a point "." must be
in upper case.

    function RemoveShouting($string)
    {
        $string = strtolower(trim($string));

        for($i=0;$i<strlen($string);$i++){

            if($i==0){$string[$i] = strtoupper($string[$i]);}

            if($string[$i] == "."){
                while($string[$i+1] == " "){
                    $i++;
                }
                $string[$i+1] = strtoupper($string[$i+1]);
                $i++;
            }
        }

    return $string;
    }

this function would change:
Hi mi name is PETER. SOME TIMES I FORGOT TO DISABLE CAPS LOCK.

into:

Hi mi name is peter. Some times i forgot to disable caps lock.
spiceee ddotty spiceee com 06-Mar-2006 04:53
If you ever need to strtolower a string with href tags on it and doesn't want to mess with the characters inside a tag, this is for you.

<?php

function loweroutsidetags ($str) {
    $chars = preg_split ("//", $str);
    $tolower = true;
    $str = '';

    foreach ($chars as $k) {
        if ($k == '<') { $tolower = false; }
        if ($tolower) { $k = strtolower ($k); }
        $str .= $k;
        if ($k == '>') { $tolower = true; }
    }
    return $str;
}

?>

this:
echo loweroutsidetags('aALalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">')

will give:
aalalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">
red at iklanumum dot com 23-Feb-2006 06:43
I've seen this as a common use from script developers, so I would like to share the alternative way to compare 2 string (CASE INSENSITIVE) without using strtolower for faster process.

Use strcasecmp() for comparison purpose rather than comparing uncertain case of 2 string variables, because strcasecmp() is approximately 60% faster, moreover, the greater its string length the greater the difference,!
Ex. case :
$var1;    -> could be a mixture of upper & lower case
$var2;    -> could be a mixture of upper & lower case

To compare whether $var1 is exactly the same as $var2 (case insensitive manner):
Use -> if (strcasecmp($var1,$var2)==0)
rather than -> if (strtolower($var1)==strtolower($var2))
Patrick 19-Jan-2006 10:57
If you're considering using the below unhtmlentities function from phpContrib, I would suggest this one as an alternative:

<?php
function unhtmlentities($string)
{
   // replace numeric entities
   $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
   $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
   // replace literal entities
   $trans_tbl = get_html_translation_table(HTML_ENTITIES);
   $trans_tbl = array_flip($trans_tbl);
   return strtr($string, $trans_tbl);
}
?>

That was copied exactly from the html_entity_decode manual page.  It'll handle numeric entities correctly, the below function won't.
fackelkind 11-Jan-2006 12:03
Nifty? :D

<?php
        function is_lowercase ($str){
                return ($str == strtolower ($str));
        }
?>
mhuggins57 at yahoo dot com 19-Jul-2005 04:04
There's a ucfirst "function" to make the first character uppercase, but there's no "lcfirst" function to make the first character lowercase.  Here's my own code to accomplish this.

<?
function lcfirst($str) {
    return strtolower(substr($str, 0, 1)) . substr($str, 1);
}
?>

I found this particularly useful for generating XML nodes with the Reflection class.
kmcdermott at perimeterinstitute dot ca 08-Dec-2004 01:04
To do case insensitive comparisons in a database, strtolower() can be a quick and dirty solution:

$Sql = "SELECT * FROM tablename WHERE LOWER(column_name) = '".strtolower($my_var)."'";
phpContrib (A T) esurfers d o t c o m 24-Sep-2004 11:07
<?php

$b=html_entity_decode(strtolower(htmlentities($a)));

?>

will convert to lowercase most accented vocals
(it will convert � into &Agrave; into &agrave; into �)

This is not fast and clean code, it is just a quick oneliner to help you if you need a quick way to do it

�

Users with older versions of PHP can use:
$b=unhtmlentities(strtolower(htmlentities($a)));

// with unhtmlentities() as defined in the html_entity_decode() manual page:

function unhtmlentities ($string) {
    $trans_tbl =get_html_translation_table (HTML_ENTITIES );
    $trans_tbl =array_flip ($trans_tbl );
    return strtr ($string ,$trans_tbl );
}
bkimble at ebaseweb dot com 19-Jan-2003 10:39
Heres a small function I wrote to stop people from submitting data that is ALL IN CAPS SO THEY CAN GET MORE ATTENTION THAT THE REST OF THE USER SUBMITTED DATA on my website :) If you can make it better, by all means do so. This function splits up words delimited by a space, and makes only the first letter of each word capitalized. You can easily modify it so it's only the very first word of the string. I've also added some exceptions so you don't make things like roman numerals look like "Iii" or "Xcmii" or something.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();
 foreach ($words as $word)
 {
  if (!$higher_exceptions[$word]) $word = strtolower($word);
  if (!$lower_exceptions[$word]) $word[0] = strtoupper($word[0]);
  array_push($newwords, $word);
 }
 return join(" ", $newwords);
}

BK
tty01_at_rambler_dot_ru 19-Sep-2002 07:58
Another solution for Double-Byte-Characters, based on iconv() functions, not sensible to the current locale, works on win32.

/* Converts charset */
function myConvertCharset($str, $from, $to)
{
    if(@function_exists('iconv'))
    {
        return iconv($from, $to, $str);
    }
    else if(@function_exists('recode_string'))
    {
        return recode_string($from . '..'  . $to, $str);
    }
    else
    {
        print "function iconv not exists";
        return $str;
    }
}
/* Converts a string to lowercase */
function my_strtolower($s)
{
    $t = "windows-1251";
    $d = "UTF-8";
    return myConvertCharset(strtolower(myConvertCharset($s, $d, $t)), $t, $d);
}

print my_strtolower("СЛОВО  Uppercase");
12-Sep-2002 05:17
This function is sensible to the current locale, namely the LC_CTYPE category (the default LC_CTYPE category is set from the LANG environment variable or by an explicit LC_CTYPE setting, but it can be overriden by the LC_ALL environment setting). If no locale setting is done in the enironment, the default locale will be C, for which the lowercase/uppercase conversion is based on the default character set of the system: this may convert only ASCII letters, or also ISO-8859-1 letters depending on the system...
strtok
strtoupper
Обработка строк


РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ

strtolower
strtr
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє
PHP Manual

strtoupper

(PHP 4, PHP 5)

strtoupper — РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ

РћРїРёСЃР°РЅРёРµ

string strtoupper ( string $string )

Р’РѕР·РІСЂР°С‰Р°РµС‚ СЃС‚СЂРѕРєСѓ string, РІ РєРѕС‚РѕСЂРѕР№ РІСЃРµ Р±СѓРєРІРµРЅРЅС‹Рµ СЃРёРјРІРѕР»С‹ РїРµСЂРµРІРµРґРµРЅС‹ РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ.

РџСЂРёРЅР°РґР»РµР¶РЅРѕСЃС‚СЊ С‚РѕРіРѕ РёР»Рё РёРЅРѕРіРѕ СЃРёРјРІРѕР»Р° Рє Р±СѓРєРІРµРЅРЅС‹Рј РѕРїСЂРµРґРµР»СЏРµС‚СЃСЏ СЃ СѓС‡РµС‚РѕРј С‚РµРєСѓС‰РµР№ Р»РѕРєР°Р»Рё. РС‚Рѕ РѕР·РЅР°С‡Р°РµС‚, С‡С‚Рѕ, РЅР°РїСЂРёРјРµСЂ, РІ РёСЃРїРѕР»СЊР·СѓРµРјРѕР№ РїРѕ СѓРјРѕР»С‡Р°РЅРёСЋ Р»РѕРєР°Р»Рё "C", СЃРёРјРІРѕР» Г¤ РЅРµ Р±СѓРґРµС‚ РїСЂРµРѕР±СЂР°Р·РѕРІР°РЅ.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

string

Р’С…РѕРґРЅР°СЏ СЃС‚СЂРѕРєР°.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ СЃС‚СЂРѕРєСѓ РІ РІРµСЂС…РЅРµРј СЂРµРіРёСЃС‚СЂРµ.

РџСЂРёРјРµСЂС‹

РџСЂРёРјРµСЂ #1 РџСЂРёРјРµСЂ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёСЏ strtoupper()

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // РІС‹РІРѕРґРёС‚: MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

РџСЂРёРјРµС‡Р°РЅРёСЏ

Р—Р°РјРµС‡Р°РЅРёРµ: РС‚Р° С„СѓРЅРєС†РёСЏ Р±РµР·РѕРїР°СЃРЅР° РґР»СЏ РѕР±СЂР°Р±РѕС‚РєРё РґР°РЅРЅС‹С… РІ РґРІРѕРёС‡РЅРѕР№ С„РѕСЂРјРµ.

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • strtolower() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РІ РЅРёР¶РЅРёР№ СЂРµРіРёСЃС‚СЂ
  • ucfirst() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ РїРµСЂРІС‹Р№ СЃРёРјРІРѕР» СЃС‚СЂРѕРєРё РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ
  • ucwords() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ РїРµСЂРІС‹Р№ СЃРёРјРІРѕР» РєР°Р¶РґРѕРіРѕ СЃР»РѕРІР° РІ СЃС‚СЂРѕРєРµ
  • mb_strtoupper() - РџСЂРёРІРµРґРµРЅРёРµ СЃС‚СЂРѕРєРё Рє РІРµСЂС…РЅРµРјСѓ СЂРµРіРёСЃС‚СЂСѓ

User Contributed Notes

davaco at net dot hr 06-Jan-2012 07:46
Simple function for uppercase encoding of croatian text! :)

<?php
function strtoupper_hr($a) {
    return strtr(mb_strtoupper($a, "utf-8"), array(
      " ЕЎ" => " Е ",
      " Д‘" => " Дђ",
      " Еѕ" => " ЕЅ",
      " ДЌ" => " ДЊ",
      " Д‡" => " Д†"
    ));
}
?>
james at snasta dot ie 10-Nov-2011 06:44
In the Irish language certain initial mutations can never be capitalized вЂ” the following simple function can be used to capitalize text in Irish.

i.e. Muintir na hГ‰ireann -> MUINTIR NA hГ‰IREANN

<?php
function strtoupper_ga($a) {
    return strtr(mb_strtoupper($a, "utf-8"), array(
      " MB" => " mB",
      " GC" => " gC",
      " ND" => " nD",
      " BHF" => " bhF",
      " NG" => " nG",
      " BP" => " bP",
      " DT" => " dT",
      " HA" => " hA",
      " HE" => " hE",
      " HI" => " hI",
      " HO" => " hO",
      " HU" => " hU",
      " HГЃ" => " hГЃ",
      " HГ‰" => " hГ‰",
      " HГЌ" => " hГЌ",
      " HГ“" => " hГ“",
      " HГљ" => " hГљ"
    ));
}
?>
markus dot geiger at mayflower dot de 20-Jun-2011 09:42
NOTE: To uppercase a unicode string you simply could use mb_strtoupper($str,  'UTF-8') instead of all that bloated PHP functions ;=)
dev dot gabiu at gmail dot com 17-May-2011 04:22
This would be my short version for French characters:

<?php
function fullUpper($string){
  return strtr(strtoupper($string), array(
      "Г " => "ГЂ",
      "ГЁ" => "Г€",
      "Г¬" => "ГЊ",
      "ГІ" => "Г’",
      "Г№" => "Г™",
          "ГЎ" => "ГЃ",
      "Г©" => "Г‰",
      "Г" => "ГЌ",
      "Гі" => "Г“",
      "Гє" => "Гљ",
          "Гў" => "Г‚",
      "ГЄ" => "ГЉ",
      "Г®" => "ГЋ",
      "Гґ" => "Г”",
      "Г»" => "Г›",
          "Г§" => "Г‡",
    ));
}
?>
christoph dot hochstrasser at gmail dot com 15-Mar-2011 08:12
For beginners: here is the most simple Camelize function for PHP. It converts underscore or dash separated strings to camelCase, optionally with a Parameter to convert them to PascalCase (often needed for Class names).

<?php

function camelize($string, $pascalCase = false)
{
  $string = str_replace(array('-', '_'), ' ', $string);
  $string = ucwords($string);
  $string = str_replace(' ', '', $string);

  if (!$pascalCase) {
    return lcfirst($string);
  }
  return $string;
}
?>
smieat 01-May-2010 04:39
perfect solutions for turkish utf-8 (including i I conversations):

<?php
function strtolowertr($metin){
    return mb_convert_case(str_replace('I','Д±',$metin), MB_CASE_LOWER, "UTF-8");
}

function strtouppertr($metin){
    return mb_convert_case(str_replace('i','Д°',$metin), MB_CASE_UPPER, "UTF-8");
}

function ucwordstr($metin) {
    return ltrim(mb_convert_case(str_replace(array(' I',' Д±', ' Д°', ' i'),array(' I',' I',' Д°',' Д°'),' '.$metin), MB_CASE_TITLE, "UTF-8"));
}

function ucfirsttr($metin) {
    $metin = in_array(crc32($metin[0]),array(1309403428, -797999993, 957143474)) ? array(strtouppertr(substr($metin,0,2)),substr($metin,2)) : array(strtouppertr($metin[0]),substr($metin,1));
return $metin[0].$metin[1];
}
?>
php at emanaton dot com 06-Nov-2009 08:38
I liked jesdisciple's approach to a camel case function, but needed something a little more high powered, so here is my stab at this need:

<?php
/**
 * Convert a string to camel case, optionally capitalizing the first char and optionally setting which characters are
 * acceptable.
 *
 * First, take existing camel case and add a space between each word so that it is in Title Form; note that
 *   consecutive capitals (acronyms) are considered a single word.
 * Second, capture all contigious words, capitalize the first letter and then convert the rest into lower case.
 * Third, strip out all the non-desirable characters (i.e, non numerics).
 *
 * EXAMPLES:
 * $str = 'Please_RSVP: b4 you-all arrive!';
 *
 * To convert a string to camel case:
 *  strtocamel($str); // gives: PleaseRsvpB4YouAllArrive
 *
 * To convert a string to an acronym:
 *  strtocamel($str, true, 'A-Z'); // gives: PRBYAA
 *
 * To convert a string to first-lower camel case without numerics but with underscores:
 *  strtocamel($str, false, 'A-Za-z_'); // gives: please_RsvpBYouAllArrive
 *
 * @param  string  $str              text to convert to camel case.
 * @param  bool    $capitalizeFirst  optional. whether to capitalize the first chare (e.g. "camelCase" vs. "CamelCase").
 * @param  string  $allowed          optional. regex of the chars to allow in the final string
 *
 * @return string camel cased result
 *
 * @author Sean P. O. MacCath-Moran   www.emanaton.com
 */
function strtocamel($str, $capitalizeFirst = true, $allowed = 'A-Za-z0-9') {
    return preg_replace(
        array(
            '/([A-Z][a-z])/e', // all occurances of caps followed by lowers
            '/([a-zA-Z])([a-zA-Z]*)/e', // all occurances of words w/ first char captured separately
            '/[^'.$allowed.']+/e', // all non allowed chars (non alpha numerics, by default)
            '/^([a-zA-Z])/e' // first alpha char
        ),
        array(
            '" ".$1', // add spaces
            'strtoupper("$1").strtolower("$2")', // capitalize first, lower the rest
            '', // delete undesired chars
            'strto'.($capitalizeFirst ? 'upper' : 'lower').'("$1")' // force first char to upper or lower
        ),
        $str
    );
}
Jaason 10-Jul-2009 01:48
convert polish special letters into big and small chars;p

<?php
function toUpper($string) {
    return (strtoupper(strtr($string, 'Д™ГіД…Е›Е‚ЕјЕєД‡Е„','ДГ“Д„ЕљЕЃЕ»Е№Д†Еѓ' )));
    };

function toLower($string) {
    return (strtolower(strtr($string,'ДГ“Д„ЕљЕЃЕ»Е№Д†Еѓ', 'Д™ГіД…Е›Е‚ЕјЕєД‡Е„' )));
    };
?>
chris at table4 dot com 19-Jan-2009 07:31
Simple function to change the case of your string and any accented html characters contained within it.

Inspired by fullUpper(), by silent at gmx dot li... just a little bit more atomic.

<?php

function convertCase($str, $case = 'upper')
{ //yours, courtesy of table4.com  :)
  switch($case)
  {
    case "upper" :
    default:
      $str = strtoupper($str);
      $pattern = '/&([A-Z])(UML|ACUTE|CIRC|TILDE|RING|';
      $pattern .= 'ELIG|GRAVE|SLASH|HORN|CEDIL|TH);/e';
      $replace = "'&'.'\\1'.strtolower('\\2').';'"; //convert the important bit back to lower
    break;

    case "lower" :
      $str = strtolower($str);
    break;
  }

  $str = preg_replace($pattern, $replace, $str);
  return $str;
}
?>

Depending on what you are trying to achieve you would call like this:

<?php

//with entities...
$str = convertCase(htmlentities($str, ENT_QUOTES, "ISO-8859-1"));

?>
spaceman at foo dot at 17-Apr-2008 09:59
It has been mentioned in a previous comment that all you need to do to let PHP's strtoupper() do the conversion - instead of writing more or less complicated functions yourself - is to specify the locale in which you're doing the case conversion:

<?php setlocale(LC_CTYPE, "de_AT") ?>

It is important to note that setlocale() will silently fail if it can't find the specified locale on your system, so *always* check its return value. Try different spellings: using "de_AT" as an example, there are various combinations that may or may not work for you: "de", "de_AT.utf8", "de_AT.iso-8859-1", "de_AT.latin1", "de_AT@euro", etc).

If you can't find an appropriate locale setting, check your system configuration (locales are a system-wide setting, PHP gets them from the OS). On Windows, locales can be set from the Control Panel; on Linux it depends on your distribution. You can try "sudo dpkg-reconfigure locales" on Debian-based distros, or configure them manually. On Ubuntu Dapper, I had to copy entries over from /usr/share/i18n/SUPPORTED to /var/lib/locales/supported.d/local, then do the dpkg-reconfigure.

After you're done, restart the web server.

That said, there are special cases where you want to do the conversion manually. In German, for example, the letter 'Гџ' (szlig) only exists as a lower-case character, and so doesn't get converted by strtoupper. The convential way to express a 'Гџ' in an uppercase string is "SS". This function will take care of this exception (for Latin1 and most of Latin9, at least):

<?php

define("LATIN1_UC_CHARS", "ГЂГЃГ‚ГѓГ„Г…Г†Г‡Г€Г‰ГЉГ‹ГЊГЌГЋГЏГђГ‘Г’Г“Г”Г•Г–ГГ™ГљГ›ГњГќ");
define("LATIN1_LC_CHARS", "Г ГЎГўГЈГ¤ГҐГ¦Г§ГЁГ©ГЄГ«Г¬ГГ®ГЇГ°Г±ГІГіГґГµГ¶ГёГ№ГєГ»ГјГЅ");

function uc_latin1 ($str) {
    $str = strtoupper(strtr($str, LATIN1_LC_CHARS, LATIN1_UC_CHARS));
    return strtr($str, array("Гџ" => "SS"));
}

?>
jesdisciple at gmail dot com 08-Mar-2008 05:02
This function takes a space-delimited list of words and returns it as one camelcase word.
<?php
function strtocamel($str){
    $str = explode(' ', strtolower($str));
    for($i = 1; $i < count($str); $i++){
        $str[$i] = strtoupper(substr($str[$i], 0, 1)) . substr($str[$i], 1);
    }
    return implode('', $str);
}
?>

Example:
<?php
echo strtocamel('Str tO CAMEL');
?>
This will output 'strToCamel'.  To also make the first letter uppercase, change '$i = 1' to '$i = 0'.
silent at gmx dot li 15-Oct-2007 05:25
ISO-8859-1 (Latin 1) full with all special characters:

<?php
function fullUpper($str){
   // convert to entities
   $subject = htmlentities($str,ENT_QUOTES);
   $pattern = '/&([a-z])(uml|acute|circ';
   $pattern.= '|tilde|ring|elig|grave|slash|horn|cedil|th);/e';
   $replace = "'&'.strtoupper('\\1').'\\2'.';'";
   $result = preg_replace($pattern, $replace, $subject);
   // convert from entities back to characters
   $htmltable = get_html_translation_table(HTML_ENTITIES);
   foreach($htmltable as $key => $value) {
      $result = ereg_replace(addslashes($value),$key,$result);
   }
   return(strtoupper($result));
}

echo fullUpper("try this: Г¤Г¶ГјГџ");
?>

results in

TRY THIS: Г„Г–ГњГџ
Oliv. 11-Oct-2007 07:20
accents convertion trick :

<?php

    function ucfirstHTMLentity($matches){
        return "&".ucfirst(strtolower($matches[1])).";";
    }
    function fullUpper($str){
        $subject = strtoupper(htmlentities($str, null, 'UTF-8'));
        $pattern = '/&([A-Z]+);/';
        return preg_replace_callback($pattern, "ucfirstHTMLentity", $subject);
    }

        print fullUpper($_REQUEST["txt"]);

?>
xguimax at gmail dot com 05-Oct-2007 01:17
Portuguese version of String Capitalize in PHP.

    function strProper($str)
    {
        $noUp = array('um','uma','o','a','de','do','da','em');
        $str = trim($str);
        $str = strtoupper($str[0]) . strtolower(substr($str, 1));
        for($i=1; $i<strlen($str)-1; ++$i) {
            if($str[$i]==' ') {
                for($j=$i+1; $j<strlen($str) && $str[$j]!=' '; ++$j); //find next space
                $size = $j-$i-1;
                $shortWord = false;
                if($size<=3) {
                    $theWord = substr($str,$i+1,$size);
                    for($j=0; $j<count($noUp) && !$shortWord; ++$j)
                        if($theWord==$noUp[$j])
                            $shortWord = true;
                }
                if( !$shortWord )
                    $str = substr($str, 0, $i+1) . strtoupper($str[$i+1]) . substr($str, $i+2);
            }
            $i+=$size;
        }
        return $str;
    }
marcinhacia at gazeta dot pl 31-Jul-2007 08:15
In response to strtoupper:

There is a simpler way to change the first letter of a string to uppercase:

<?php
$string='this is a much more simpler way to capitalise the first character of a string';
echo ucfirst($string); // This is a much more...
?>
16-May-2007 01:40
<?php
$string='this is a simpler way to capitalise the first character of a string';
$string[0]=strtoupper($string[0]);
echo $string; // This is a simpler way...
?>
RUNET 17-Apr-2007 05:33
Russian

function str_to_upper($str){
    return strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\xE0\xE1\xE2\xE3\xE4\xE5".
    "\xb8\xe6\xe7\xe8\xe9\xea".
    "\xeb\xeC\xeD\xeE\xeF\xf0".
    "\xf1\xf2\xf3\xf4\xf5\xf6".
    "\xf7\xf8\xf9\xfA\xfB\xfC".
    "\xfD\xfE\xfF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\xC0\xC1\xC2\xC3\xC4\xC5".
    "\xA8\xC6\xC7\xC8\xC9\xCA".
    "\xCB\xCC\xCD\xCE\xCF\xD0".
    "\xD1\xD2\xD3\xD4\xD5\xD6".
    "\xD7\xD8\xD9\xDA\xDB\xDC".
    "\xDD\xDE\xDF");
}
Cory 23-Jul-2006 09:05
This function converts any series of english words to Proper Casing.  It also accounts for words such as 'a' and 'the'.  To change what words are ignored, just change the $noUp array.

function strProper($str) {
    $noUp = array('a','an','of','the','are','at','in');
    $str = trim($str);
    $str = strtoupper($str[0]) . strtolower(substr($str, 1));
    for($i=1; $i<strlen($str)-1; ++$i) {
        if($str[$i]==' ') {
            for($j=$i+1; $j<strlen($str) && $str[$j]!=' '; ++$j); //find next space
            $size = $j-$i-1;
            $shortWord = false;
            if($size<=3) {
                $theWord = substr($str,$i+1,$size);
                for($j=0; $j<count($noUp) && !$shortWord; ++$j)
                    if($theWord==$noUp[$j])
                        $shortWord = true;
            }
            if( !$shortWord )
                $str = substr($str, 0, $i+1) . strtoupper($str[$i+1]) . substr($str, $i+2);
        }
        $i+=$size;
    }
    return $str;
}
sjrd at redaction-developpez dot com 03-Jun-2006 11:12
Angus Lord's function has got a problem with html entities such as &amp;, for they're converted into &Amp;, which is incorrect.

The following code fixes the problem:

<?php
function to_upper($string)
{
  $new_string = "";
  while (eregi("^([^&]*)(&)(.)([a-z0-9]{2,9};|&)(.*)", $string, $regs))
  {
    $entity = $regs[2].strtoupper($regs[3]).$regs[4];
    if (html_entity_decode($entity) == $entity)
      $new_string .= strtoupper($regs[1]).$regs[2].$regs[3].$regs[4];
    else
      $new_string .= strtoupper($regs[1]).$entity;
    $string = $regs[5];
  }
  $new_string .= strtoupper($string);
  return $new_string;
}
?>
bart at insane dot at 10-May-2006 04:31
When using UTF-8 and need to convert to uppercase with
special characters like the german Г¤,Г¶,Гј (didn't test for french,polish,russian but think it should work, too) try this:

function strtoupper_utf8($string){
    $string=utf8_decode($string);
    $string=strtoupper($string);
    $string=utf8_encode($string);
    return $string;
}
tree2054 at hotmail dot com 14-Feb-2006 10:11
An even simpler version of h3's rewrite:

<?php
function isupper($i) { return (strtoupper($i) === $i);}
function islower($i) { return (strtolower($i) === $i);}
?>
Gцrkem PAЗACI(gorkempacaci[et]gmail.com) 05-Jan-2006 06:36
These functions can be used on Turkish(iso-8859-9):
Turkce(iso-8859-9) icin su fonksiyonlar kullanilabilir:

$tr_low_letters = str_split("abcзdefgрhэijklmnoцpqrsюtuьvwxyz");
$tr_up_letters = str_split("ABCЗDEFGРHIЭJKLMNOЦPQRSЮTUЬVWXYZ");
function tr_uppercase($str) {
    global $tr_low_letters, $tr_up_letters;
    return str_replace($tr_low_letters, $tr_up_letters, $str);
}
function tr_lowercase($str) {
    global $tr_low_letters, $tr_up_letters;
    return str_replace($tr_up_letters, $tr_low_letters, $str);
}
function tr_fuppercase($str) {//only first letter uppercase
    return tr_uppercase($str[0]) . tr_lowercase(substr($str,1));
}
Vadim from Baku 27-Nov-2005 01:55
The following function counts uppercase letters in English and Cyrillic. It works great with cyrillic when strtolower doesn't work due to enviroment settings.(Thank you Sean!).

preg_match_all("@[A-ZА-Я]@",$str,$m,PREG_OFFSET_CAPTURE)

It is probably displayed incorrectly due to page encoding, but there are range from the first uppercase letter of the latin alphabet to the last one and range from the first uppercase cyrillic alphabet letter to the last one in the pattern. Not sure but similar approach can work for other alphabets.
Beniamin 25-Nov-2005 06:04
Here is correct str2upper function for polish programmers (plus str2lower function):

<?php
function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xB3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xA3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );
}

function str2lower($text){
   return strtr($text,
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xA3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F",  // win 1250
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xB3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F" // win 1250
   );
}
?>
julas 01-Aug-2005 03:46
The code for Polish programmers was spolied a little bit - \xB3 should be turned into \xA3, not the opposite. So the correct code is:

function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xA3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xB3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );
}
kirsman 07-Jul-2005 10:37
For polish programmers:

function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xA3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xB3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );
30-May-2005 06:11
// 2005/5/30 Justin
    // Chinese_Traditional toupper
    function CT_to_upper($string)
    {
        $isChineseStart = false;

          $new_string = "";
         $i = 0;
          while($i < strlen($string))
          {
               if (ord(substr($string,$i,1)) <128)
               {
                   if( $isChineseStart == false )
                       $new_string .= strtoupper(mb_substr($string,$i,1));
                   else
                       $new_string .= substr($string,$i,1);
               }
               else
               {
                   if( $isChineseStart == false )
                       $isChineseStart = true;
                   else
                       $isChineseStart = false;

                     $new_string .= substr($string,$i,1);
               }
               $i++;
          }
          return $new_string;
    }
    //
Justin_Lin at mail2000 dot com dot tw 30-May-2005 06:09
The following is my code for translate a given string to upper case and it will support chinese traditional :

// 2005/5/30 Justin
// Chinese_Traditional toupper
function CT_to_upper($string)
{
    $isChineseStart = false;

    $new_string = "";
    $i = 0;
    while($i < strlen($string))
    {
           if (ord(substr($string,$i,1)) <128)
            {
           if( $isChineseStart == false )
                $new_string .= strtoupper(mb_substr($string,$i,1));
           else
                $new_string .= substr($string,$i,1);
             }
             else
             {
           if( $isChineseStart == false )
                  $isChineseStart = true;
           else
                $isChineseStart = false;
             $new_string .= substr($string,$i,1);
             }
             $i++;
      }
      return $new_string;
}
//
willyann at gmail dot com 24-May-2005 09:31
chinese

function to_upper($string) {
  $new_string = "";
  $i = 0;
  while($i < strlen($string)) {
   if (ord(substr($string,$i,1)) <128)
   {
     $new_string .= strtoupper(substr($string,$i,1));
     $i++;
   } else {
     $new_string .= substr($string,$i,2);
     $i=$i+2;
   }
  }
  return $new_string;
}
12-Mar-2005 05:08
Ah, the last code were spoiled, here is the fixed one:

<?php

function str_to_upper($str){
    return strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\x9C\x9A\xE0\xE1\xE2\xE3".
    "\xE4\xE5\xE6\xE7\xE8\xE9".
    "\xEA\xEB\xEC\xED\xEE\xEF".
    "\xF0\xF1\xF2\xF3\xF4\xF5".
    "\xF6\xF8\xF9\xFA\xFB\xFC".
    "\xFD\xFE\xFF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
    "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
    "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
    "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
    "\xDB\xDC\xDD\xDE\x9F");
}

?>

So, this function changes also other letters into uppercase, strtoupper() does only change: a-z to: A-Z.
30-Oct-2004 03:23
If you only need to extend the conversion by the characters of a certain language, it's possible to control this using an environment variable to change the locale:

setlocale(LC_CTYPE, "de_DE");
p dot thomas at inlive dot info 02-Apr-2004 04:02
Some bench :

String Copy, OUT=IN : 21.398067474365 ms

String TRANSFORMATION :

- strtolower : 383.09001922607 ms
- strtolower( strtr) : 267.36092567444 ms
- preg_replace : 16624.928951263 ms
- stringUpDown : 4013.0908489227 ms

IN : jehrjzh rй'и'и_- &йз(r&)ай БВГДЕЖЗИЙКЛМНОПРСТУФХЦ EAZREZREZ^m
OUT : jehrjzh rй'и'и_- &йз(r&)ай бвгдежзийклмнопрстуфхц eazrezrez^m

Platform : AMD 1 Ghz, Win2K, EasyPHP
martine 06-Feb-2004 07:41
This may save you time and effort (if you need to convert european languages such as Czech, Portugees, German or Swedish)

the function mb_strtoupper() converts all accented characters in the latin alphabet, ie. љ, с, ь, э etc. This is easier than some of the suggestions below. It should also convert case properly for russian, etc.
mec at stadeleck dot org 02-Dec-2002 06:54
something I myself first not thought about:
if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever).
urudz at strategma dot bg 21-Apr-2002 09:49
on linux
php gets LC_LOCAL env variable therefor you must set this

export LC_ALL=bg_BG.CP1251
export LANG=bg_BG.CP1251

before starting of apache i have put this to lines in /etc/rc.d/rc.httpd
-----

cat /etc/rc.d/rc.httpd
#!/bin/sh
#
# Start the Apache web server
#

export LC_ALL=bg_BG.CP1251
export LANG=bg_BG.CP1251

case "$1" in
   'start')
      /usr/sbin/apachectl startssl ;;
   'stop')
      /usr/sbin/apachectl stop ;;
   'restart')
      /usr/sbin/apachectl restart ;;
   *)
      echo "usage $0 start|stop|restart" ;;
esac
-------

in windows you must define your "locale"
in control panel  > regional options > general

best regards urudz :>
strtolower
strtr
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє


РџСЂРµРѕР±СЂР°Р·СѓРµС‚ Р·Р°РґР°РЅРЅС‹Рµ СЃРёРјРІРѕР»С‹ РёР»Рё Р·Р°РјРµРЅСЏРµС‚ РїРѕРґСЃС‚СЂРѕРєРё

strtoupper
substr_compare
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє
PHP Manual

strtr

(PHP 4, PHP 5)

strtr — РџСЂРµРѕР±СЂР°Р·СѓРµС‚ Р·Р°РґР°РЅРЅС‹Рµ СЃРёРјРІРѕР»С‹ РёР»Рё Р·Р°РјРµРЅСЏРµС‚ РїРѕРґСЃС‚СЂРѕРєРё

РћРїРёСЃР°РЅРёРµ

string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )

Р•СЃР»Рё СѓРєР°Р·Р°РЅС‹ С‚СЂРё Р°СЂРіСѓРјРµРЅС‚Р°, СЌС‚Р° С„СѓРЅРєС†РёСЏ РІРѕР·РІСЂР°С‰Р°РµС‚ РєРѕРїРёСЋ str, РІ РєРѕС‚РѕСЂРѕР№ РІСЃРµ РІС…РѕР¶РґРµРЅРёСЏ РєР°Р¶РґРѕРіРѕ СЃРёРјРІРѕР»Р° (РѕРґРЅРѕР±Р°Р№С‚РЅРѕРіРѕ) РёР· from Р±С‹Р»Рё Р·Р°РјРµРЅРµРЅС‹ РЅР° СЃРѕРѕС‚РІРµС‚СЃС‚РІСѓСЋС‰РёР№ СЃРёРјРІРѕР» РІ РїР°СЂР°РјРµС‚СЂРµ to, С‚.Рµ. РєР°Р¶РґРѕРµ РІС…РѕР¶РґРµРЅРёРµ РёР· $from[$n] Р·Р°РјРµРЅСЏРµС‚СЃСЏ РЅР° $to[$n], РіРґРµ $n СЌС‚Рѕ РєРѕСЂСЂРµРєС‚РЅРѕРµ СЃРјРµС‰РµРЅРёРµ СЃС‚СЂРѕРєРё РІ РѕР±РѕРёС… Р°СЂРіСѓРјРµРЅС‚Р°С….

Р•СЃР»Рё РґР»РёРЅС‹ СЃС‚СЂРѕРє from Рё to РѕС‚Р»РёС‡Р°СЋС‚СЃСЏ, "Р»РёС€РЅРёРµ" СЃРёРјРІРѕР»С‹ РІ Р±РѕР»РµРµ РґР»РёРЅРЅРѕР№ СЃС‚СЂРѕРєРµ РЅРµ РёСЃРїРѕР»СЊР·СѓСЋС‚СЃСЏ. Р”Р»РёРЅР° РІРѕР·РІСЂР°С‰Р°РµРјРѕРіРѕ Р·РЅР°С‡РµРЅРёСЏ Р±СѓРґРµС‚ С‚Р°РєРѕР№ Р¶Рµ, РєР°Рє Рё РґР»РёРЅР° str.

strtr() РјРѕР¶РµС‚ РІС‹Р·С‹РІР°С‚СЊСЃСЏ СЃ РґРІСѓРјСЏ Р°СЂРіСѓРјРµРЅС‚Р°РјРё. Р’ СЌС‚РѕРј СЃР»СѓС‡Р°Рµ from РґРѕР»Р¶РµРЅ Р±С‹С‚СЊ РјР°СЃСЃРёРІРѕРј (array), РІ С„РѕСЂРјРµ array('from' => 'to', ...). Р¤СѓРЅРєС†РёСЏ РІРѕР·РІСЂР°С‚РёС‚ СЃС‚СЂРѕРєСѓ, РІ РєРѕС‚РѕСЂРѕР№ РІСЃРµ РєР»СЋС‡Рё РјР°СЃСЃРёРІР° Р±СѓРґСѓС‚ Р·Р°РјРµРЅРµРЅС‹ РёС… СЌР»РµРјРµРЅС‚Р°РјРё. strtr() РІ РїРµСЂРІСѓСЋ РѕС‡РµСЂРµРґСЊ Р·Р°РјРµРЅСЏРµС‚ Р±РѕР»РµРµ РґР»РёРЅРЅС‹Рµ РєР»СЋС‡Рё, РїСЂРёС‡РµРј РѕРґРЅР° Рё С‚Р° Р¶Рµ СЃС‚СЂРѕРєР° РїРѕРёСЃРєР° РёСЃРїРѕР»СЊР·СѓРµС‚СЃСЏ С‚РѕР»СЊРєРѕ РѕРґРёРЅ СЂР°Р·.

Р’ СЌС‚РѕРј СЃР»СѓС‡Р°Рµ, РєР»СЋС‡Рё Рё Р·РЅР°С‡РµРЅРёСЏ РјРѕРіСѓС‚ РёРјРµС‚СЊ Р»СЋР±СѓСЋ РґР»РёРЅСѓ, Р·Р° РёСЃРєР»СЋС‡РµРЅРёРµРј С‚РѕРіРѕ, С‡С‚Рѕ РєР»СЋС‡Рё РЅРµ РґРѕР»Р¶РЅС‹ Р±С‹С‚СЊ РїСѓСЃС‚С‹РјРё. РљСЂРѕРјРµ С‚РѕРіРѕ, РґР»РёРЅР° РІРѕР·РІСЂР°С‰Р°РµРјРѕРіРѕ Р·РЅР°С‡РµРЅРёСЏ РјРѕР¶РµС‚ РѕС‚Р»РёС‡Р°С‚СЊСЃСЏ РѕС‚ str. РћРґРЅР°РєРѕ, СЃС‚РѕРёС‚ СѓС‡РµСЃС‚СЊ С‚РѕС‚ С„Р°РєС‚, С‡С‚Рѕ СЌС‚Р° С„СѓРЅРєС†РёСЏ РјР°РєСЃРёРјР°Р»СЊРЅРѕ СЌС„С„РµРєС‚РёРІРЅР° РІ С‚РѕРј СЃР»СѓС‡Р°Рµ, РµСЃР»Рё РІСЃРµ РєР»СЋС‡Рё РёРјРµСЋС‚ РѕРґРёРЅР°РєРѕРІС‹Р№ СЂР°Р·РјРµСЂ.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

str

Р—Р°РјРµРЅСЏРµРјР°СЏ СЃС‚СЂРѕРєР° (string).

from

РЎС‚СЂРѕРєР° (string), РєРѕС‚РѕСЂР°СЏ Р±СѓРґРµС‚ Р·Р°РјРµРЅРµРЅР° РЅР° СЃС‚СЂРѕРєСѓ to.

to

РЎС‚СЂРѕРєР° (string), Р·Р°РјРµРЅСЏСЋС‰Р°СЏ СЃС‚СЂРѕРєСѓ from.

replace_pairs

РџР°СЂР°РјРµС‚СЂ replace_pairs РјРѕР¶РµС‚ Р±С‹С‚СЊ РёСЃРїРѕР»СЊР·РѕРІР°РЅ РІРјРµСЃС‚Рѕ to Рё from, РІ СЌС‚РѕРј СЃР»СѓС‡Р°Рµ РѕРЅ СЏРІР»СЏРµС‚СЃСЏ РјР°СЃСЃРёРІРѕРј (array) Рё РёРјРµРµС‚ С„РѕСЂРјСѓ array('from' => 'to', ...).

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ СЃС‚СЂРѕРєСѓ (string) СЃ РїСЂРѕРёР·РІРµРґРµРЅРЅС‹РјРё РІ РЅРµР№ Р·Р°РјРµРЅР°РјРё.

Р•СЃР»Рё replace_pairs СЃРѕРґРµСЂР¶РёС‚ РєР»СЋС‡, СЏРІР»СЏСЋС‰РёР№СЃСЏ РїСѓСЃС‚РѕР№ СЃС‚СЂРѕРєРѕР№ (""), С‚Рѕ Р±СѓРґРµС‚ РІРѕР·РІСЂР°С‰РµРЅРѕ Р·РЅР°С‡РµРЅРёРµ FALSE.

РџСЂРёРјРµСЂС‹

РџСЂРёРјРµСЂ #1 РџСЂРёРјРµСЂ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёСЏ strtr()

<?php
//Р’ СЌС‚РѕР№ С„РѕСЂРјРµ strtr() РѕСЃСѓС‰РµСЃС‚РІР»СЏРµС‚ РїРѕР±Р°Р№С‚РЅРѕРµ РїСЂРµРѕР±СЂР°Р·РѕРІР°РЅРёРµ
//РўР°РєРёРј РѕР±СЂР°Р·РѕРј, Р·РґРµСЃСЊ РїРѕРґСЂР°Р·СѓРјРµРІР°РµС‚СЃСЏ РѕРґРЅРѕР±Р°Р№С‚РЅР°СЏ РєРѕРґРёСЂРѕРІРєР°:
$addr = strtr($addr, "Г¤ГҐГ¶", "aao");
?>

РЎР»РµРґСѓСЋС‰РёР№ РїСЂРёРјРµСЂ РґРµРјРѕРЅСЃС‚СЂРёСЂСѓРµС‚ РїРѕРІРµРґРµРЅРёРµ С„СѓРЅРєС†РёРё strtr() РїСЂРё РІС‹Р·РѕРІРµ С‚РѕР»СЊРєРѕ СЃ РґРІСѓРјСЏ Р°СЂРіСѓРјРµРЅС‚Р°РјРё. РћР±СЂР°С‚РёС‚Рµ РІРЅРёРјР°РЅРёРµ РЅР° РїСЂРёРѕСЂРёС‚РµС‚ Р·Р°РјРµРЅ ("h" РЅРµ РёСЃРїРѕР»СЊР·СѓРµС‚СЃСЏ, С‚Р°Рє РєР°Рє СЃСѓС‰РµСЃС‚РІСѓСЋС‚ Р±РѕР»РµРµ РґР»РёРЅРЅС‹Рµ СЃРѕРІРїР°РґРµРЅРёСЏ) Рё РєР°Рє Р·Р°РјРµРЅРµРЅРЅС‹Р№ С‚РµРєСЃС‚ Р±РѕР»СЊС€Рµ РЅРµ СѓС‡Р°СЃС‚РІСѓРµС‚ РІ РїРѕРёСЃРєРµ.

РџСЂРёРјРµСЂ #2 РџСЂРёРјРµСЂ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёСЏ strtr() СЃ РґРІСѓРјСЏ Р°СЂРіСѓРјРµРЅС‚Р°РјРё

<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

Р РµР·СѓР»СЊС‚Р°С‚ РІС‹РїРѕР»РЅРµРЅРёСЏ РґР°РЅРЅРѕРіРѕ РїСЂРёРјРµСЂР°:

hello all, I said hi

РС‚Рё РґРІР° СЂРµР¶РёРјР° РґРѕРІРѕР»СЊРЅРѕ СЃРёР»СЊРЅРѕ СЂР°Р·Р»РёС‡Р°СЋС‚СЃСЏ. РџСЂРё РІС‹Р·РѕРІРµ strtr() СЃ С‚СЂРµРјСЏ Р°СЂРіСѓРјРµРЅС‚Р°РјРё Р·Р°РјРµРЅСЏСЋС‚СЃСЏ Р±Р°Р№С‚С‹, Р° РїСЂРё РІС‹Р·РѕРІРµ СЃ РґРІСѓРјСЏ Р°СЂРіСѓРјРµРЅС‚Р°РјРё РјРѕРіСѓС‚ Р±С‹С‚СЊ Р·Р°РјРµРЅРµРЅС‹ Рё Р±РѕР»РµРµ РґР»РёРЅРЅС‹Рµ РїРѕРґСЃС‚СЂРѕРєРё.

РџСЂРёРјРµСЂ #3 РЎСЂР°РІРЅРµРЅРёРµ РїРѕРІРµРґРµРЅРёСЏ С„СѓРЅРєС†РёРё strtr()

<?php
echo strtr("baab", "ab", "01"),"\n";

$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>

Р РµР·СѓР»СЊС‚Р°С‚ РІС‹РїРѕР»РЅРµРЅРёСЏ РґР°РЅРЅРѕРіРѕ РїСЂРёРјРµСЂР°:

1001
ba01

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • str_replace() - Р—Р°РјРµРЅСЏРµС‚ РІСЃРµ РІС…РѕР¶РґРµРЅРёСЏ СЃС‚СЂРѕРєРё РїРѕРёСЃРєР° РЅР° СЃС‚СЂРѕРєСѓ Р·Р°РјРµРЅС‹
  • preg_replace() - Р’С‹РїРѕР»РЅСЏРµС‚ РїРѕРёСЃРє Рё Р·Р°РјРµРЅСѓ РїРѕ СЂРµРіСѓР»СЏСЂРЅРѕРјСѓ РІС‹СЂР°Р¶РµРЅРёСЋ

User Contributed Notes

antimoz at gmail dot com 09-Feb-2012 03:08
Here is my array for char normalization:
<?php
        $normalizeChars = array(
            'ГЃ'=>'A', 'ГЂ'=>'A', 'Г‚'=>'A', 'Гѓ'=>'A', 'Г…'=>'A', 'Г„'=>'A', 'Г†'=>'AE', 'Г‡'=>'C',
            'Г‰'=>'E', 'Г€'=>'E', 'ГЉ'=>'E', 'Г‹'=>'E', 'ГЌ'=>'I', 'ГЊ'=>'I', 'ГЋ'=>'I', 'ГЏ'=>'I', 'Гђ'=>'Eth',
            'Г‘'=>'N', 'Г“'=>'O', 'Г’'=>'O', 'Г”'=>'O', 'Г•'=>'O', 'Г–'=>'O', 'Г'=>'O',
            'Гљ'=>'U', 'Г™'=>'U', 'Г›'=>'U', 'Гњ'=>'U', 'Гќ'=>'Y',

            'ГЎ'=>'a', 'Г '=>'a', 'Гў'=>'a', 'ГЈ'=>'a', 'ГҐ'=>'a', 'Г¤'=>'a', 'Г¦'=>'ae', 'Г§'=>'c',
            'Г©'=>'e', 'ГЁ'=>'e', 'ГЄ'=>'e', 'Г«'=>'e', 'Г'=>'i', 'Г¬'=>'i', 'Г®'=>'i', 'ГЇ'=>'i', 'Г°'=>'eth',
            'Г±'=>'n', 'Гі'=>'o', 'ГІ'=>'o', 'Гґ'=>'o', 'Гµ'=>'o', 'Г¶'=>'o', 'Гё'=>'o',
            'Гє'=>'u', 'Г№'=>'u', 'Г»'=>'u', 'Гј'=>'u', 'ГЅ'=>'y',

            'Гџ'=>'sz', 'Гѕ'=>'thorn', 'Гї'=>'y'
        );
?>
Sam 01-Feb-2012 10:33
Case Insensitive strtr

<?php
function stritr($string, $one, $two=null) {
    if (is_string($one)) {
        return strtr($string, strtoupper($one) . strtolower($one), "$two$two");
    } else if (is_array($one)) {
        $strReturn = $string
        foreach ($one as $key => $val) {
            $strReturn = preg_replace("'$key'i", $val, $strReturn);
        }
        return $strReturn;
    }
    return $string;
}
?>
Michael Schuijff 24-Oct-2011 10:02
I found that this approach is often faster than strtr() and won't change the same thing in your string twice (as opposed to str_replace(), which will overwrite things in the order of the array you feed it with):

<?php
function replace ($text, $replace) {
    $keys = array_keys($replace);
    $length = array_combine($keys, array_map('strlen', $keys));
    arsort($length);

    $array[] = $text;
    $count = 1;
    reset($length);
    while ($key = key($length)) {
        if (strpos($text, $key) !== false) {
            for ($i = 0; $i < $count; $i += 2) {
                if (($pos = strpos($array[$i], $key)) === false) continue;
                array_splice($array, $i, 1, array(substr($array[$i], 0, $pos), $replace[$key], substr($array[$i], $pos + strlen($key))));
                $count += 2;
            }
        }
        next($length);
    }
    return implode($array);
}
?>
Chris 04-Feb-2011 12:49
Hope this is useful when you need to see ASCII control characters:
<?php
$xlate = array(chr(0) => '^@/NUL/null', chr(1) => '^A/SOH/start of heading', chr(2) => '^B/STX/start of text', chr(3) => '^C/ETX/end of text', chr(4) => '^D/EOT/end of transmisssion', chr(5) => '^E/ENQ/enquiry', chr(6) => '^F/ACK/acknowledge', chr(7) => '^G/BEL/bell', chr(8) => '^H/BS/backspace', chr(9) => '^I/TAB/horizontal tab', chr(10) => '^J/LF/NL/line feed/new line', chr(11) => '^K/VT/vertical tab', chr(12) => '^L/FF/NP/form feed/new page/', chr(13) => '^M/CR/carrige return', chr(14) => '^N/SO/shift out', chr(15) => '^O/SI/shift in', chr(16) => '^P/DLE/data link escape', chr(17) => '^Q/DC1/device control 1', chr(18) => '^R/DC2/device control 2', chr(19) => '^S/DC3/device control 3', chr(20) => '^T/DC4/device control 4', chr(21) => '^U/NAK/negative acknowledge', chr(22) => '^V/SYN/synchronous idle', chr(23) => '^W/ETB/end of transmission block', chr(24) => '^X/CAN/cancel', chr(25) => '^Y/EM/end of medium', chr(26) => '^Z/SUB/substiute', chr(27) => '^[/ESC/escape', chr(28) => '^\/FS/file separator', chr(29) => '^]/GS/group separator', chr(30) => '^^/RS/record separator', chr(31) => '^_/US/unit separator', chr(32) => 'Space');

$x = 0;
$pad = strlen(strlen($str));
while(isset($str[$x]))
   echo 'character ', str_pad($x+1, $pad), ' = ', strtr($str[$x], $xlate), ' (ascii ', ord($str[$x++]), ')';
?>
sales at mk2solutions dot com 29-Jun-2010 11:59
This is what we use for prepping data that is going to be used for shortURLs or just needs to be completely cleaned
<?php

$GLOBALS['normalizeChars'] = array(
    'Е '=>'S', 'ЕЎ'=>'s', 'Гђ'=>'Dj','ЕЅ'=>'Z', 'Еѕ'=>'z', 'ГЂ'=>'A', 'ГЃ'=>'A', 'Г‚'=>'A', 'Гѓ'=>'A', 'Г„'=>'A',
    'Г…'=>'A', 'Г†'=>'A', 'Г‡'=>'C', 'Г€'=>'E', 'Г‰'=>'E', 'ГЉ'=>'E', 'Г‹'=>'E', 'ГЊ'=>'I', 'ГЌ'=>'I', 'ГЋ'=>'I',
    'ГЏ'=>'I', 'Г‘'=>'N', 'Г’'=>'O', 'Г“'=>'O', 'Г”'=>'O', 'Г•'=>'O', 'Г–'=>'O', 'Г'=>'O', 'Г™'=>'U', 'Гљ'=>'U',
    'Г›'=>'U', 'Гњ'=>'U', 'Гќ'=>'Y', 'Гћ'=>'B', 'Гџ'=>'Ss','Г '=>'a', 'ГЎ'=>'a', 'Гў'=>'a', 'ГЈ'=>'a', 'Г¤'=>'a',
    'ГҐ'=>'a', 'Г¦'=>'a', 'Г§'=>'c', 'ГЁ'=>'e', 'Г©'=>'e', 'ГЄ'=>'e', 'Г«'=>'e', 'Г¬'=>'i', 'Г'=>'i', 'Г®'=>'i',
    'ГЇ'=>'i', 'Г°'=>'o', 'Г±'=>'n', 'ГІ'=>'o', 'Гі'=>'o', 'Гґ'=>'o', 'Гµ'=>'o', 'Г¶'=>'o', 'Гё'=>'o', 'Г№'=>'u',
    'Гє'=>'u', 'Г»'=>'u', 'ГЅ'=>'y', 'ГЅ'=>'y', 'Гѕ'=>'b', 'Гї'=>'y', 'Ж’'=>'f'
);

function cleanForShortURL($toClean) {
    $toClean     =     str_replace('&', '-and-', $toClean);
    $toClean     =    trim(preg_replace('/[^\w\d_ -]/si', '', $toClean));//remove all illegal chars
    $toClean     =     str_replace(' ', '-', $toClean);
    $toClean     =     str_replace('--', '-', $toClean);

    return strtr($toClean, $GLOBALS['normalizeChars']);
}

This process cleans up any special characters and also coverts strings to a readable safe URL format.
?>
elloromtz at gmail dot com 19-Apr-2010 05:08
If you supply 3 arguments and the 2nd is an array, strtr will search the "A" from "Array" (because you're treating it as a scalar string) and replace it with the 3rd argument:

strtr('Analogy', array('x'=>'y'),  '_'); //'_nalogy'

so in reality the above code has the same affect as:

strtr('Analogy', 'A' , '_');
Anonymous 25-Nov-2009 12:09
Here's a one-liner to strip out non-standard ascii characters, inspired by joeldegan AT yahoo's post below.

<?php
  $new = preg_replace("/[^\x9\xA\xD\x20-\x7F]/", "", $old);
?>
nvyktor 09-Sep-2009 07:02
Hi all,

as u probably know the is some truoble with the (for example) hungarian special characters. If I used the htmlentities() function, the simple chars had benn converted to the basic format, for example: & aacute;. However this was very simple, some cases it needs more transformation.

As I would like to use the correct caracters even in php, html, js, and more, a wrote this short code to solve this issue:

<?php
function charcode ($text) {
    $text = htmlentities($text); //to convert the simple spec chars
    $search = array("& otilde;","&O tilde;","& ucirc;","&U circ;");
    $replace = array("& #337;","& #336;","& #369;","& #368;");
    $text = str_replace($search, $replace, $text);
    return $text;
}
?>

Now I am able to display any spec chars in any browser with any character encoding set.

Hope U will find this helpful.

Vyktor
allixsenos at gmail dot com 16-May-2009 08:55
fixed "normaliza" functions written below to include Slavic Latin characters... also, it doesn't return lowercase any more (you can easily get that by applying strtolower yourself)...

also, renamed to normalize()

<?php

function normalize ($string) {
    $table = array(
        'Е '=>'S', 'ЕЎ'=>'s', 'Дђ'=>'Dj', 'Д‘'=>'dj', 'ЕЅ'=>'Z', 'Еѕ'=>'z', 'ДЊ'=>'C', 'ДЌ'=>'c', 'Д†'=>'C', 'Д‡'=>'c',
        'ГЂ'=>'A', 'ГЃ'=>'A', 'Г‚'=>'A', 'Гѓ'=>'A', 'Г„'=>'A', 'Г…'=>'A', 'Г†'=>'A', 'Г‡'=>'C', 'Г€'=>'E', 'Г‰'=>'E',
        'ГЉ'=>'E', 'Г‹'=>'E', 'ГЊ'=>'I', 'ГЌ'=>'I', 'ГЋ'=>'I', 'ГЏ'=>'I', 'Г‘'=>'N', 'Г’'=>'O', 'Г“'=>'O', 'Г”'=>'O',
        'Г•'=>'O', 'Г–'=>'O', 'Г'=>'O', 'Г™'=>'U', 'Гљ'=>'U', 'Г›'=>'U', 'Гњ'=>'U', 'Гќ'=>'Y', 'Гћ'=>'B', 'Гџ'=>'Ss',
        'Г '=>'a', 'ГЎ'=>'a', 'Гў'=>'a', 'ГЈ'=>'a', 'Г¤'=>'a', 'ГҐ'=>'a', 'Г¦'=>'a', 'Г§'=>'c', 'ГЁ'=>'e', 'Г©'=>'e',
        'ГЄ'=>'e', 'Г«'=>'e', 'Г¬'=>'i', 'Г'=>'i', 'Г®'=>'i', 'ГЇ'=>'i', 'Г°'=>'o', 'Г±'=>'n', 'ГІ'=>'o', 'Гі'=>'o',
        'Гґ'=>'o', 'Гµ'=>'o', 'Г¶'=>'o', 'Гё'=>'o', 'Г№'=>'u', 'Гє'=>'u', 'Г»'=>'u', 'ГЅ'=>'y', 'ГЅ'=>'y', 'Гѕ'=>'b',
        'Гї'=>'y', 'Е”'=>'R', 'Е•'=>'r',
    );

    return strtr($string, $table);
}

?>
Sidney Ricardo 05-Sep-2008 11:54
This work fine to me:

<?php
function normaliza ($string){
    $a = 'ГЂГЃГ‚ГѓГ„Г…Г†Г‡Г€Г‰ГЉГ‹ГЊГЌГЋГЏГђГ‘Г’Г“Г”Г•Г–ГГ™ГљГ›ГњГќГћ
ГџГ ГЎГўГЈГ¤ГҐГ¦Г§ГЁГ©ГЄГ«Г¬ГГ®ГЇГ°Г±ГІГіГґГµГ¶ГёГ№ГєГ»ГЅГЅГѕГїЕ”Е•';
    $b = 'aaaaaaaceeeeiiiidnoooooouuuuy
bsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
    $string = utf8_decode($string);
    $string = strtr($string, utf8_decode($a), $b);
    $string = strtolower($string);
    return utf8_encode($string);
}
?>
jorge at seisbits dot com 11-Jul-2008 12:04
If you try to make a strtr of not usual charafters when you are in a utf8 enviroment, you can do that:

function normaliza ($string){
    $string = utf8_decode($string);
    $string = strtr($string, utf8_decode(" Г‚ГЉГЋГ”Г›ГЂ"), "-AEIOU");
    $string = strtolower($string);
    return $string;
}
dot dot dot dot dot alexander at gmail dot com 25-Mar-2008 04:09
OK, I debugged the function (had some errors)
Here it is:

if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                if(  count( $one ) <= 0  )break;
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $one[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $one[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
dot dot dot dot dot alexander at gmail dot com 25-Mar-2008 10:44
Here is the stritr I always needed... I wrote it in 15 minutes... But only after the idea struck me. Hope you find it helpful, and enjoy...
<?php
if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $positions[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $positions[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
?>
Jean-Marc Libs 26-Feb-2008 09:49
A couple of people have suggested examples of use of strstr() in order to do conversions from one charset to the other.

I would like to point out that this is the purpose of iconv().
troelskn at gmail dot com 23-Jan-2008 03:39
Here's another transcribe function. This one converts cp1252 (aka. Windows-1252) into iso-8859-1 (aka. latin1, the default PHP charset). It only transcribes the few exotic characters, which are unique to cp1252.

function transcribe_cp1252_to_latin1($cp1252) {
  return strtr(
    $cp1252,
    array(
      "\x80" => "e",  "\x81" => " ",    "\x82" => "'", "\x83" => 'f',
      "\x84" => '"',  "\x85" => "...",  "\x86" => "+", "\x87" => "#",
      "\x88" => "^",  "\x89" => "0/00", "\x8A" => "S", "\x8B" => "<",
      "\x8C" => "OE", "\x8D" => " ",    "\x8E" => "Z", "\x8F" => " ",
      "\x90" => " ",  "\x91" => "`",    "\x92" => "'", "\x93" => '"',
      "\x94" => '"',  "\x95" => "*",    "\x96" => "-", "\x97" => "--",
      "\x98" => "~",  "\x99" => "(TM)", "\x9A" => "s", "\x9B" => ">",
      "\x9C" => "oe", "\x9D" => " ",    "\x9E" => "z", "\x9F" => "Y"));
ajitsingh4u at gmail dot com 06-Aug-2007 07:36
/**
* Replaces special characters with single quote,double quote and comma for charset iso-8859-1
*
* replaceSpecialChars()
* @param string $str
* @return string
*/
function replaceSpecialChars($str)
{
    //`(96) вЂ™(130) вЂћ(132) вЂ(145) вЂ™(146) вЂњ(147) вЂќ(148) Вґ(180)   // equivalent ascii values of these characters.
    $str = strtr($str, "`вЂ™вЂћвЂвЂ™Вґ", "'','''");
    $str = strtr($str, 'вЂњвЂќ', '""');
    return $str;
}
peter dot goodman at gmail dot com 28-Jun-2007 08:17
To the previous comment: great function, one character mapping it is missing is though is:

chr(226) => 'Гў'
horak.jan AT centrum.cz 22-May-2007 07:11
Here is a function to convert middle-european windows charset (cp1250) to the charset, that php script is written in:

<?php
    function cp1250_to_utf2($text){
        $dict  = array(chr(225) => 'ГЎ', chr(228) =>  'Г¤', chr(232) => 'ДЌ', chr(239) => 'ДЏ',
            chr(233) => 'Г©', chr(236) => 'Д›', chr(237) => 'Г', chr(229) => 'Дє', chr(229) => 'Дѕ',
            chr(242) => 'Е€', chr(244) => 'Гґ', chr(243) => 'Гі', chr(154) => 'ЕЎ', chr(248) => 'Е™',
            chr(250) => 'Гє', chr(249) => 'ЕЇ', chr(157) => 'ЕҐ', chr(253) => 'ГЅ', chr(158) => 'Еѕ',
            chr(193) => 'ГЃ', chr(196) => 'Г„', chr(200) => 'ДЊ', chr(207) => 'ДЋ', chr(201) => 'Г‰',
            chr(204) => 'Дљ', chr(205) => 'ГЌ', chr(197) => 'Д№',    chr(188) => 'ДЅ', chr(210) => 'Е‡',
            chr(212) => 'Г”', chr(211) => 'Г“', chr(138) => 'Е ', chr(216) => 'Е', chr(218) => 'Гљ',
            chr(217) => 'Е®', chr(141) => 'Е¤', chr(221) => 'Гќ', chr(142) => 'ЕЅ',
            chr(150) => '-');
        return strtr($text, $dict);
    }
?>
joeldegan AT yahoo 07-Apr-2006 08:49
After battling with strtr trying to strip out MS word formatting from things pasted into forms I ended up coming up with this..

it strips ALL non-standard ascii characters, preserving html codes and such, but gets rid of all the characters that refuse to show in firefox.

If you look at this page in firefox you will see a ton of "question mark" characters and so it is not possible to copy and paste those to remove them from strings..  (this fixes that issue nicely, though I admit it could be done a bit better)

<?
function fixoutput($str){
    $good[] = 9;  #tab
    $good[] = 10; #nl
    $good[] = 13; #cr
    for($a=32;$a<127;$a++){
        $good[] = $a;
    }
    $len = strlen($str);
    for($b=0;$b < $len+1; $b++){
        if(in_array(ord($str[$b]), $good)){
            $newstr .= $str[$b];
        }//fi
    }//rof
    return $newstr;
}
?>
martin[dot]pelikan[at]gmail[dot]com 29-Dec-2005 07:20
// if you are upset with windows' ^M characters at the end of the line,
// these two lines are for you:
$trans = array("\x0D" => "");
$text = strtr($orig_text,$trans);

// note that ctrl+M (in vim known as ^M) is hexadecimally 0x0D
tomhmambo at seznam dot cz 20-Dec-2005 02:54
<?
// Windows-1250 to ASCII
// This function replace all Windows-1250 accent characters with
// thier non-accent ekvivalents. Useful for Czech and Slovak languages.

function win2ascii($str)    {

    $str = StrTr($str,
        "\xE1\xE8\xEF\xEC\xE9\xED\xF2",
        "\x61\x63\x64\x65\x65\x69\x6E");

    $str = StrTr($str,
        "\xF3\xF8\x9A\x9D\xF9\xFA\xFD\x9E\xF4\xBC\xBE",
        "\x6F\x72\x73\x74\x75\x75\x79\x7A\x6F\x4C\x6C");

    $str = StrTr($str,
        "\xC1\xC8\xCF\xCC\xC9\xCD\xC2\xD3\xD8",
        "\x41\x43\x44\x45\x45\x49\x4E\x4F\x52");

    $str = StrTr($str,
        "\x8A\x8D\xDA\xDD\x8E\xD2\xD9\xEF\xCF",
        "\x53\x54\x55\x59\x5A\x4E\x55\x64\x44");

    return $str;
}
?>
Ezbakhe Yassin <yassin88 at gmail dot com> 31-Aug-2005 03:55
Here you are a simple function to rotate a variable according to an array of possible values. You can make a strict comparison (===).

<?php
function rotateValue($string, $values, $strict = TRUE)
{
    if (!empty($string) AND is_array($values))
    {
        $valuesCount = count($values);

        for ($i = 0; $i < $valuesCount; $i++)
        {
            if ($strict ? ($string === $values[$i]) : ($string == $values[$i]))
            {
                return $values[($i + 1) % $valuesCount];
            }
        }
    }

    return FALSE;
}
?>

For example:

- rotateValue("A", array("A", "B", "C")) will return "B"
- rotateValue("C", array("A", "B", "C")) will return "A"
ru dot dy at gmx dot net 10-Jul-2005 04:20
Posting umlaute here resulted in a mess. Heres a version of the same function that works with preg_replace only:
<?php
  function getRewriteString($sString) {
     $string = strtolower(htmlentities($sString));
     $string = preg_replace("/&(.)(uml);/", "$1e", $string);
     $string = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $string);
     $string = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($string));
     $string = trim($string, "-");
     return $string;
  }
?>
-sven (www.bitcetera.com) 20-Apr-2005 11:48
And while we're at it, yet another transcriber (the code formerly known as accent remover). It does accents and umlauts, but also ligatures and runes known to ISO-8859-1. The translation strings must be on one line without any whitespaces in it. They are rendered hardwrapped here because this documentation doesn't allow long lines in notes.

function transcribe($string) {
    $string = strtr($string,
       "\xA1\xAA\xBA\xBF\xC0\xC1\xC2\xC3\xC5\xC7
        \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
        \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD\xE0
        \xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB\xEC
        \xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
        \xF9\xFA\xFB\xFD\xFF",
        "!ao?AAAAAC
        EEEEIIIIDN
        OOOOOUUUYa
        aaaaceeeei
        iiidnooooo
        uuuyy");
    $string = strtr($string, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe", "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae", "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th"));
    return($string);
}

(Funky: ISO-8859-1 does not cover the french "oe" ligature.)
info at oscaralexander dot com 13-Apr-2005 12:32
Here's a nice function for parsing a string to something suitable for URL rewriting (mod_rewrite). It translates all accented characters to their non-accented equivalents and replaces all other non-alphanumeric character with dashes:

function getRewriteString($sString) {
    $string    = htmlentities(strtolower($string));
    $string    = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $string);
    $string    = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($string));
    $string    = trim($string, "-");
    return $string;
}
Stian 02-Mar-2005 01:58
elonen forgot the ш character (\xf8)
A (more) complete accent remover:

$txt = strtr($txt,
 "\xe1\xc1\xe0\xc0\xe2\xc2\xe4\xc4\xe3\xc3\xe5\xc5".
 "\xaa\xe7\xc7\xe9\xc9\xe8\xc8\xea\xca\xeb\xcb\xed".
 "\xcd\xec\xcc\xee\xce\xef\xcf\xf1\xd1\xf3\xd3\xf2".
 "\xd2\xf4\xd4\xf6\xd6\xf5\xd5\x8\xd8\xba\xf0\xfa\xda".
 "\xf9\xd9\xfb\xdb\xfc\xdc\xfd\xdd\xff\xe6\xc6\xdf\xf8",
 "aAaAaAaAaAaAacCeEeEeEeEiIiIiIiInNo".
 "OoOoOoOoOoOoouUuUuUuUyYyaAso");
elonen at iki dot fi 25-Feb-2005 12:24
Yet another accent remover, this time pretty complete and without any 8-bit characters in the script itself:

$txt = strtr($txt,
 "\xe1\xc1\xe0\xc0\xe2\xc2\xe4\xc4\xe3\xc3\xe5\xc5".
 "\xaa\xe7\xc7\xe9\xc9\xe8\xc8\xea\xca\xeb\xcb\xed".
 "\xcd\xec\xcc\xee\xce\xef\xcf\xf1\xd1\xf3\xd3\xf2".
 "\xd2\xf4\xd4\xf6\xd6\xf5\xd5\x8\xd8\xba\xf0\xfa".
 "\xda\xf9\xd9\xfb\xdb\xfc\xdc\xfd\xdd\xff\xe6\xc6\xdf",
 "aAaAaAaAaAaAacCeEeEeEeEiIiIiIiInNoOoOoOoOoOoOoouUuUuUuUyYyaAs");
patrick at p-roocks dot de 06-Feb-2005 02:31
As Daijoubu suggested use str_replace instead of this function for large arrays/subjects. I just tried it with a array of 60 elements, a string with 8KB length, and the execution time of str_replace was faster at factor 20!

Patrick
Daijoubu 12-Jan-2005 03:19
Wouldn't:
<?php
$s = str_replace(array_key($replace_array), array_value($replace_array), $s);
?>
be faster?
Perhaps even faster using 2 seperate arrays...
11-Dec-2004 05:20
If you are going to call strtr a lot, consider using str_replace instead, as it is much faster. I cut execution time in half just by doing this.

<?
// i.e. instead of:
$s=strtr($s,$replace_array);

// use:
foreach($replace_array as $key=>$value) $s=str_replace($key,$value,$s);
?>
oliver at modix dot de 22-Oct-2004 01:08
Replace control characters in a binary string:
<?

function cc_replace($in) {
        for ($i = 0; $i <= 31; $i++) {
                $from  .= chr($i);
                $to    .= ".";
        }
        return strtr($in, $from, $to);
}

?>
ktogias at math dot upatras dot gr 23-Sep-2004 03:32
This function is usefull for
accent insensitive regexp
searches into greek (iso8859-7) text:
(Select View -> Character Encoding -> Greek (iso8859-7)
at your browser to see the correct greek characters)

function gr_regexp($mystring){
        $replacement=array(
                array("¶","Б","б","Ь"),
                array("ё","Е","е","Э"),
                array("№","З","з","Ю"),
                array("є","Й","й","Я","ъ","А"),
                array("ј","П","п","ь"),
                array("ѕ","Х","х","э","ы","а"),
                array("ї","Щ","щ","ю")
        );
        foreach($replacement as $group){
                foreach($group as $character){
                        $exp="[";
                        foreach($group as $expcharacter){
                                $exp.=$expcharacter;
                        }
                        $exp.="]";
                        $trans[$character]=$exp;
                }
        }
        $temp=explode(" ", $mystring);
        for ($i=0;$i<sizeof($temp);$i++){
                $temp[$i]=strtr($temp[$i],$trans);
                $temp[$i]=addslashes($temp[$i]);
        }
        return implode(".*",$temp);
}

$match=gr_regexp("Укпхлйкпмхсмйгкьфсхрб кбй ФжйжйсйЬ");

//The next query string can be sent to MySQL
through mysql_query()
$query=
      "Select `column` from `table` where `column2` REGEXP
                         '".$match."'";
from-php-net dot ticket at raf256 dot com 04-Jun-2004 04:59
Hi, before I found strtr() function I quickly wrote own repleacement, if someone is interested,

// by http://www.raf256.com - Rafal Maj
function ConvCharset($from,$to,$s) {
  $l=strlen($s);
  $S=''; // out put
  for ($i=0; $i<$l; $i++) {
    $c=$s[$i]; // curr char
    $x=strpos($from, $c);
    if ($x!==FALSE) $c=$to[$x];
    $S.=$c;
  }
  return $S;
}
volkris at tamu dot edu 19-Mar-2004 06:25
Regarding christophe's conversion, note that the \x## values should be in double quotes, not single, so that the escape will be applied.
stewey at ambitious dot ca 04-Mar-2004 06:11
This version of macRomanToIso (originally posted by: marcus at synchromedia dot co dot uk) offers a couple of improvements. First, it removes the extra slashes '\' that broke the original function. Second, it adds four quote characters not supported in ISO 8859-1. These are the left double quote, right double quote, left single quote and right single quote.

Be sure to remove the line breaks from the two strings going into strtr or this function will not work properly.

Be careful what text you apply this to. If you apply it to ISO 8859-1 encoded text it will likely wreak havoc. I'll save you some trouble with this bit of advice: don't bother trying to detect what charset a certain text file is using, it can't be done reliably. Instead, consider making assumptions based upon the HTTP_USER_AGENT, or prompting the user to specify the character encoding used (perhaps both).

<?php

/**
 * Converts MAC OS ROMAN encoded strings to the ISO 8859-1 charset.
 *
 * @param    string    the string to convert.
 * @return    string    the converted string.
 */
function macRomanToIso($string)
{
    return strtr($string,
"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b
\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97
\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa1\xa4\xa6\xa7
\xa8\xab\xac\xae\xaf\xb4\xbb\xbc\xbe\xbf\xc0\xc1
\xc2\xc7\xc8\xca\xcb\xcc\xd6\xd8\xdb\xe1\xe5\xe6
\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf1\xf2\xf3
\xf4\xf8\xfc\xd2\xd3\xd4\xd5",
"\xc4\xc5\xc7\xc9\xd1\xd6\xdc\xe1\xe0\xe2\xe4\xe3
\xe5\xe7\xe9\xe8\xea\xeb\xed\xec\xee\xef\xf1\xf3
\xf2\xf4\xf6\xf5\xfa\xf9\xfb\xfc\xb0\xa7\xb6\xdf\xae
\xb4\xa8\xc6\xd8\xa5\xaa\xba\xe6\xf8\xbf\xa1\xac
\xab\xbb\xa0\xc0\xc3\xf7\xff\xa4\xb7\xc2\xca\xc1
\xcb\xc8\xcd\xce\xcf\xcc\xd3\xd4\xd2\xda\xdb\xd9
\xaf\xb8\x22\x22\x27\x27");
}

?>
christophe at publicityweb dot com 26-Feb-2004 12:04
Latin1 (iso-8859-1) DONT define chars \x80-\x9f (128-159),
but Windows charset 1252 defines _some_ of them
-- like the infamous msoffice 'magic quotes' (\x92 146).
Dont use those invalid control chars in webpages,
but their html (unicode) entities. See ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
or http://www.microsoft.com/typography/unicode/1252.htm
PS: a '?' in the code means the win-cp1252 dont define the given char.

$badlatin1_cp1252_to_htmlent =
  array(
    '\x80'=>'&#x20AC;', '\x81'=>'?', '\x82'=>'&#x201A;', '\x83'=>'&#x0192;',
    '\x84'=>'&#x201E;', '\x85'=>'&#x2026;', '\x86'=>'&#x2020;', \x87'=>'&#x2021;',
    '\x88'=>'&#x02C6;', '\x89'=>'&#x2030;', '\x8A'=>'&#x0160;', '\x8B'=>'&#x2039;',
    '\x8C'=>'&#x0152;', '\x8D'=>'?', '\x8E'=>'&#x017D;', '\x8F'=>'?',
    '\x90'=>'?', '\x91'=>'&#x2018;', '\x92'=>'&#x2019;', '\x93'=>'&#x201C;',
    '\x94'=>'&#x201D;', '\x95'=>'&#x2022;', '\x96'=>'&#x2013;', '\x97'=>'&#x2014;',
    '\x98'=>'&#x02DC;', '\x99'=>'&#x2122;', '\x9A'=>'&#x0161;', '\x9B'=>'&#x203A;',
    '\x9C'=>'&#x0153;', '\x9D'=>'?', '\x9E'=>'&#x017E;', '\x9F'=>'&#x0178;'
  );
$str = strtr($str, $badlatin1_cp1252_to_htmlent);
rortiz_reyes at hotmail dot com 26-Jan-2004 09:15
If you have trouble accessing a file which has an accented or tilde letter (б,й,н,у,ъ, or с) via Internet Explorer use the following translation table:

$trans = array("б" => "%E1", "й" => "%E9", "н" => "%ED", "у" => "%F3","ъ" => "%FA", "с" => "%D1",
"Б" => "%A1", "Й" => "%A9", "Н" => "%AD", "У" => "%B3","Ъ" => "%BA", "с" => "%F1");

To obtain the translation for other special characters not used in English (for example, щ), type a fictitious filename on the Netscape 7.1 address bar (including URL, for example www.url.com/щ.jpg) and press enter.  Netscape traslates the character while Explorer simply can't handle it.

Seems like another bug on Explorer 6.0...

Regards,

Ricardo Ortiz R.
j at pureftpd dot org 30-Nov-2003 08:24
Here's a very useful function to translate Microsoft characters into Latin 15, so that people won't see any more square instead of characters in web pages .

function demicrosoftize($str) {
    return strtr($str,
"\x82\x83\x84\x85\x86\x87\x89\x8a" .
"\x8b\x8c\x8e\x91\x92\x93\x94\x95" .
"\x96\x97\x98\x99\x9a\x9b\x9c\x9e\x9f",
"'f\".**^\xa6<\xbc\xb4''" .
"\"\"---~ \xa8>\xbd\xb8\xbe");
}
Fernando "Malk" Piancastelli 29-Oct-2003 01:31
Here's a function to replace linebreaks to html <p> tags. This was initially designed to receive a typed text by a form in a "insert new notice" page and put in a database, then a "notice" page could get the text preformatted with paragraph tags instead of linebreaks that won't appear on browser. The function also removes repeated linebreaks the user may have typed in the form.

function break_to_tags(&$text) {

       // find and remove repeated linebreaks

       $double_break = array("\r\n\r\n" => "\r\n");
       do {
              $text = strtr($text, $double_break);
              $position = strpos($text, "\r\n\r\n");
       } while ($position !== false);

       // find and replace remanescent linebreaks by <p> tags

       $change = array("\r\n" => "<p>");
       $text = strtr($text, $change);
}

[]'s
Fernando
Sanate at seznam dot cz 17-Jul-2003 05:51
// Hello to all Czech and Slovak people!
// I hope this function can be useful and easier to find here,
// than at the original source (and opposite direction). :
//                  http://www.kosek.cz/clanky/tipy/qa07.html
// s pozdravem   Filip Rydlo  z Pohodasoftware.Cz

function latin2_to_win1250($text) {  // chce text v iso-88592
$text = StrTr($text, "\xA\xAB\xAE\xB\xBB\xBE",
                            "\x8A\x8D\x8E\x9A\x9D\x9E");
return $text;
}
mykel at has dot it 05-Feb-2003 06:08
strtr is a usefull encoding mechinism instead of using str_rot13. you can impliment it when you write usernames to a file, for example. but know that it is easy to crack your encription.
an example:
<?php
$unencripted = "hello";
$from = "abcdefghijklmnopqrstuvwxyz";
$to =    "zyxwvutsrqponmlkjihgfedcba";
$temp = strtr($unencripted, $from, $to);
/* will return svool */
?>
hotmail - marksteward 26-Nov-2002 07:39
Referring to note from 11 October 2000, Thorn (Ю, ю), Eth (Р, р), Esset (Я) and Mu (µ) aren't really accented letters.  Њ, њ, Ж, ж are ligatures.  Best to do the following:

function removeaccents($string){
 return strtr(
  strtr($string,
   'ЉЋљћџАБВГДЕЗИЙКЛМНОПСТУФХЦШЩЪЫЬЭабвгдезийклмнопстуфхцшщъыьэя',
   'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'),
  array('Ю' => 'TH', 'ю' => 'th', 'Р' => 'DH', 'р' => 'dh', 'Я' => 'ss',
   'Њ' => 'OE', 'њ' => 'oe', 'Ж' => 'AE', 'ж' => 'ae', 'µ' => 'u'));
}

This would be no good for sorting, as thorn and eth aren't actually found under th and dh.  Also especially redundant because of Unicode!  Still, I'm sure somone can find use for it - perhaps to constrict filenames...

Mark
m dot frank at beam dot ag 22-Nov-2002 05:12
to get the ascii equivalent of unicode characters simply use the

utf8_decode() function
marco dot colombo at nexor dot it 12-Nov-2002 06:20
Suppose you're trying to remove any character not in your set, i've found this very helpfull:

function my_remove($string, $my_set, $new=" ", $black="#")
{

  $first = strtr( $string, $my_set,
                    str_repeat($black, strlen($my_set)) );

  $second = strtr( $string, $first,
                    str_repeat($new, strlen($first)) );

  return $second;
};

NOTE that all non-wanted character will be replace with $new,
note also that $black must NOT to exist in $my_set.

Molok
bisqwit at iki dot fi 10-Aug-2002 10:18
#!/bin/sh
# This shell script generates a strtr() call
# to translate from a character set to another.
# Requires: gnu recode, perl, php commandline binary
#
# Usage:
#  Set set1 and set2 to whatever you prefer
#  (multibyte character sets are not supported)
#  and run the script. The script outputs
#  a strtr() php code for you to use.
#
# Example is set to generate a
# cp437..latin9 conversion code.
#
set1=cp437
set2=iso-8859-15
result="`echo '<? for($c=32;$c<256;$c++)'\
              'echo chr($c);'\
         |php -q|recode -f $set1..$set2`"
echo "// This php function call converts \$string in $set1 to $set2";
cat <<EOF  | php -q
<?php
\$set1='`echo -n "$result"\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$set2='`echo -n "$result"|recode -f $set2..$set1\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$erase=array();
\$l=strlen(\$set1);
for(\$c=0;\$c<\$l;++\$c)
  if(\$set1[\$c]==\$set2[\$c])\$erase[\$set1[\$c]]='';
if(count(\$erase))
{
  \$set1=strtr(\$set1,\$erase);
  \$set2=strtr(\$set2,\$erase);
}
if(!strlen(\$set1))echo 'IRREVERSIBLE';else
echo "strtr(\\\$string,\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set2),
     "',\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set1),
     "');";
EOF
gabi at unica dot edu 17-Jul-2002 05:32
To convert special chars to their html entities strtr you can use strtr in conjunction with get_html_translation_table(HTML_ENTITIES) :

$trans = get_html_translation_table(HTML_ENTITIES);
$html_code = strtr($html_code, $trans);

This will replace in $html_code the Б by &Aacute; , etc.
symlink23-remove-my-spleen at yahoo dot com 18-Apr-2002 09:33
As noted in the str_rot13 docs, some servers don't provide the str_rot13() function. However, the presence of strtr makes it easy to build your own facsimile thereof:

if (!function_exists('str_rot13')) {
    function str_rot13($str) {
        $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $to   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';

        return strtr($str, $from, $to);
    }
}

This is suitable for very light "encryption" such as hiding email addressess from spambots (then unscrambling them in a mail class, for example).

$mail_to=str_rot13("$mail_to");
erik at eldata dot se 23-Nov-2001 09:08
As an alternative to the not-yet-existing function stritr mentioned in the first note above You can easily do this:

strtr("abc","ABCabc","xyzxyz")

or more general:

strtr("abc",
strtoupper($fromchars).strtolower($fromchars),
$tochars.$tochars);

Just a thought.
strtoupper
substr_compare
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє


Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра

strtr
substr_count
Обработка строк
PHP Manual

substr_compare

(PHP 5)

substr_compare — Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра

Описание

int substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = false ]] )

substr_compare() сравнивает строку main_str (начиная с позиции offset) со строкой str. В сравнении участвуют максимум length символов.

Список параметров

main_str

Основная сравниваемая строка.

str

Следующая сравниваемая строка.

offset

Стартовая позиция сравнения. Если отрицательна, то обозначает смещение с конца строки.

length

Длина сравнения. По умолчанию используется максимальная из длин str и main_str минус offset.

case_insensitivity

Если case_sensitivity имеет значение TRUE, сравнение выполняется с учетом регистра.

Возвращаемые значения

Возвращает отрицательное число, если строка main_str (начиная с символа offset) меньше, чем str; положительное число, если она больше str; 0 если строки равны. Если offset больше или равен длине main_str или length передан и меньше 1, substr_compare() выводит предупреждение и возвращает FALSE.

Список изменений

Версия | Описание
5.1.0 | Добавлена возможность использования отрицательных значений в offset.

Примеры

Пример #1 Пример использования substr_compare()

<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // предупреждение
?>

User Contributed Notes

sleek 23-May-2005 05:07
Modified version of the original posted function. Use this one:

<?php
if (!function_exists('substr_compare')) {
    function substr_compare($main_str, $str, $offset, $length = NULL, $case_insensitivity = false) {
        $offset = (int) $offset;

        // Throw a warning because the offset is invalid
        if ($offset >= strlen($main_str)) {
            trigger_error('The start position cannot exceed initial string length.', E_USER_WARNING);
            return false;
        }

        // We are comparing the first n-characters of each string, so let's use the PHP function to do it
        if ($offset == 0 && is_int($length) && $case_insensitivity === true) {
            return strncasecmp($main_str, $str, $length);
        }

        // Get the substring that we are comparing
        if (is_int($length)) {
            $main_substr = substr($main_str, $offset, $length);
            $str_substr = substr($str, 0, $length);
        } else {
            $main_substr = substr($main_str, $offset);
            $str_substr = $str;
        }

        // Return a case-insensitive comparison of the two strings
        if ($case_insensitivity === true) {
            return strcasecmp($main_substr, $str_substr);
        }

        // Return a case-sensitive comparison of the two strings
        return strcmp($main_substr, $str_substr);
    }
}
?>
strtr
substr_count
Обработка строк


Возвращает число вхождений подстроки

substr_compare
substr_replace
Обработка строк
PHP Manual

substr_count

(PHP 4, PHP 5)

substr_count — Возвращает число вхождений подстроки

Описание

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

substr_count() возвращает число вхождений подстроки needle в строку haystack. Заметьте, что параметр needle чувствителен к регистру.

Замечание:

Эта функция не подсчитывает перекрывающиеся подстроки. Смотрите пример ниже!

Список параметров

haystack

Строка, в которой ведется поиск

needle

Искомая подстрока

offset

Смещение начала отсчета

length

Максимальная длина строки в которой будет производится поиск подстроки после указанного смещения. Если сумма смещения и максимальной длины будет больше длины haystack, то будет выведено предупреждение.

Возвращаемые значения

Эта функция возвращает integer.

Список изменений

Версия | Описание
5.1.0 | Добавлены параметры offset и length

Примеры

Пример #1 Пример использования substr_count()

<?php
$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

// строка уменьшается до 's is a test', поэтому вывод будет 1
echo substr_count($text, 'is', 3);

// текст уменьшается до 's i', поэтому вывод будет 0
echo substr_count($text, 'is', 3, 3);

// генерирует предупреждение, так как  5+10 > 14
echo substr_count($text, 'is', 5, 10);

// выводит только 1, т.к. перекрывающиеся подстроки не учитываются
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>

Смотрите также

  • count_chars() - Возвращает информацию о символах, входящих в строку
  • strpos() - Возвращает позицию первого вхождения подстроки
  • substr() - Возвращает подстроку
  • strstr() - Находит первое вхождение подстроки

User Contributed Notes

chrisstocktonaz at gmail dot com 26-Aug-2009 04:52
In regards to anyone thinking of using code contributed by zmindster at gmail dot com

Please take careful consideration of possible edge cases with that regex, in example:

$url = 'http://w3.host.tld/path/to/file/..../file.extension';
$url = 'http://w3.host.tld/path/to/file/../file.extension?malicous=....';

This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:

...
$i = 0;
while (substr_count($url, '../') && ++$i < strlen($url))
...

-Chris
jrhodes at roket-enterprises dot com 18-Jun-2009 01:37
It was suggested to use

substr_count ( implode( $haystackArray ), $needle );

instead of the function described previously, however this has one flaw.  For example this array:

array (
  0 => "mystringth",
  1 => "atislong"
);

If you are counting "that", the implode version will return 1, but the function previously described will return 0.
zmindster at gmail dot com 23-Mar-2009 01:53
For some who seeked for an easy way to resolve URL composed of /../ like http://w3.host.tld/path/to/the/file/../../file.extension, here is a solution

<?php
$url = 'http://w3.host.tld/path/to/file/../file.extension';

while (substr_count($url, "../"))
{
    $url = preg_replace('#/[^/]+/\.\.#', '', $url);
}
//outputs 'http://w3.host.tld/path/to/file.extension'
?>

and seems to work perfectly!
gigi at phpmycoder dot com 12-Jan-2009 08:17
below was suggested a function for substr_count'ing an array, yet for a simpler procedure, use the following:

<?php
substr_count ( implode( $haystackArray ), $needle );
?>
Anonymous 11-Jul-2008 06:49
It should be noted that unlike the other substr functions, the offset value cannot be a negative value.

<?php
echo substr_count('abcdefg', 'efg', 4, 3); // 1
echo substr_count('abcdefg', 'efg', -3, 3); // warning
?>
danjr33 at gmail dot com 24-Jul-2007 06:37
I ran into trouble using this function when I moved a script from a server with PHP5 to a server with only PHP4.
As the last two parameters were added with 5.1.0, I wrote a substitute function:
<?php
function substr_count5($str,$search,$offset,$len) {
    return substr_count(substr($str,$offset,$len),$search);
}
?>
Use it exactly as substr_count() is used in PHP5. (This will work in PHP5 as well.)
info at fat-fish dot co dot il 05-May-2007 04:07
a simple version for an array needle (multiply sub-strings):
<?php

function substr_count_array( $haystack, $needle ) {
     $count = 0;
     foreach ($needle as $substring) {
          $count += substr_count( $haystack, $substring);
     }
     return $count;
}
?>
flobi at flobi dot com 25-Oct-2006 07:07
Making this case insensitive is easy for anyone who needs this.  Simply convert the haystack and the needle to the same case (upper or lower).

substr_count(strtoupper($haystack), strtoupper($needle))
XinfoX X at X XkarlX X-X XphilippX X dot X XdeX 21-Dec-2003 01:27
Yet another reference to the "cgcgcgcgcgcgc" example posted by "chris at pecoraro dot net":

Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.

The example

 $number_of_full_pattern = preg_match_all('/(cgc)/', "cgcgcgcgcgcgcg", $chunks);

works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:

 $number_of_full_pattern = preg_match_all('/(cg(?=c))/', "cgcgcgcgcgcgcg", $chunks);

In this case the variable $number_of_full_pattern has the value 6.
Firstly a string "cg" will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a 'c' can be matched. Despite of the occurence of the character 'c' the pointer is not moved.
substr_compare
substr_replace
Обработка строк


Заменяет часть строки

substr_count
substr
Обработка строк
PHP Manual

substr_replace

(PHP 4, PHP 5)

substr_replace — Заменяет часть строки

Описание

mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

substr_replace() заменяет часть строки string, начинающуюся с символа с порядковым номером start и (необязательной) длиной length, строкой replacement и возвращает результат.

Список параметров

string

Входная строка.

Также можно указать массив строк, в этом случае замены будут происходить с каждой предоставленной строкой. В этом случае параметры replacement, start и length могут быть как скалярными значениями - в этом случае эти значения будут применены к каждой строке, так и массивами - в этом случае соответствующие элементы массивов будут применены к каждой предоставленной строке.

replacement

Строка замены.

start

Если start положителен, замена начинается с символа с порядковым номером start строки string.

Если start отрицателен, замена начинается с символа с порядковым номером start, считая от конца строки string.

length

Если аргумент положителен, то он представляет собой длину заменяемой подстроки в строке string. Если этот аргумент отрицательный, он определяет количество символов от конца строки string, на которых заканчивается замена. Этот аргумент необязателен и по умолчанию равен strlen(string);, т.е. замена до конца строки string. Разумеется, если length равен нулю, то это эквивалентно вставке replacement в string на указанной позиции start.

Возвращаемые значения

Возвращает результирущую строку. Если string является массивом, то возвращает массив.

Список изменений

Версия | Описание
4.3.3 | Все параметры теперь могут являться массивами.

Примеры

Пример #1 Простой пример использования substr_replace()

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Оригинал: $var<hr />\n";

/* Обе следующих строки заменяют всю строку $var на 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Вставляет 'bob' в начало $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* Обе следующих строки заменяют 'MNRPQR' in $var на 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Удаляет 'MNRPQR' из $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

Пример #2 Использование substr_replace() для одновременной множественной замены строк

<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');

// Простой случай: заменяем XXX на YYY в каждой строке.
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";

// Более сложный случай с уникальными заменами.
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";

// Замены с разными количествами символов.
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>

Результат выполнения данного примера:

A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • str_replace() - Заменяет все вхождения строки поиска на строку замены
  • substr() - Возвращает подстроку
  • Доступ к символу в строке и его изменение

User Contributed Notes

tuppisau at gmail dot com at example dot com 23-Feb-2012 06:54
If anyone is in need, here is a simple function to chop string without chopping the word and leaving the sentence incomplete. This function chops the desired length of string and after that finds the last white space in the chopped string. After that it again chops the string to the position where the last white space was found and replace it with our desired filler:

<?php
function str_replacer($_string, $_length, $_replacer = ' ...'){
    // Remove any HTML tags present in the string
    $_string = strip_tags($_string);
    if(strlen($_string) > $_length){
        // Find the position for last white space after the string has been shortened to our desired length
        // This helps us to shorten the string without chopping the character or word from the middle
        // ASCII value for the white space is 32
        $_last_white_space_pos = strripos(substr($_string, 0, $_length), 32);
        return substr_replace($_string, $_replacer, $_last_white_space_pos);
    }
    else{
        return $_string;
    }
}
?>

// How to call
<?php echo str_replacer('My name is John, what is yours?', 25) ?>

This will result in:
My name is John, what is ...
elloromtz at gmail dot com 17-Apr-2010 11:23
It's worth noting that when start and length are both negative -and- the length is less than or equal to start, the length will have the effect of being set as 0.

<?php
substr_replace('eggs','x',-1,-1); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
?>

Same as:
<?php
substr_replace('eggs','x',-1,0); //eggxs
?>

<?php
substr_replace('huevos','x',-2,-2); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
?>

Same as:
<?php
substr_replace('huevos','x',-2,0); //huevxos
?>

Another note, if length is negative and start offsets the same position as length, length (yet again) will have the effect as being set as 0. (Of course, as mentioned in the manual, when length is negative it actually represents the position before it)

<?php
substr_replace('abcd', 'x', 0, -4); //xabcd
?>

Same as:
<?php
substr_replace('abcd','x',0,0); //xabcd
?>

<?php
substr_replace('abcd', 'x', 1, -3); //axbcd
?>

Same as:
<?php
substr_replace('abcd', 'x', 1, 0); //axbcd
?>
den dot gierling at web dot de 19-Feb-2010 10:32
My problem was that substr_replace() always added $replacement, so i wrote my own function.
This function only adds $replacement, if substr() took action.
The parameter $length is optional - like substr()'s.
Or I was too stupid using $start and $length...

<?php
function substr_replace_provided($string,$replacement,$start,$length=NULL)
{
    $tmp=substr($string,$start,$length);
    if($string!==$tmp) {
        $string = $tmp.$replacement;
    }
    return $string;
}
?>
kalim dot fleet at gmail dot com 10-Oct-2009 09:49
This will truncate a longer string to a smaller string of specified length while replacing the middle portion with a separator exactly in the middle.

<?php

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '/.../';
$separatorlength = strlen($separator) ;
$maxlength = 25 - $separatorlength;
$start = $maxlength / 2 ;
$trunc =  strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij/.../56789z.jpg"

?>
admiral at nuclearpixel dot com 06-Oct-2009 11:54
Hey everyone, I was noticing that there are a lot of ways below that people are using to write their own string truncation functions, but it kinda seemed like a lot of them went a bit too far out to make any sense to a n00b. Not that I am one anymore, but I though I'd add a note on this topic myself, in hopes that it might help others understand things a little better.

Here's a concept that some people don't know about, or remember to use often enough; You can actually pull individual characters out of a string by referencing that string as though it were an array. Example: If I have the string $s = 'cat', I can use $s[0] to actually get out only the first character of that string, 'c'. I use that same principle below, but I just use a loop to iterate through a string and add the characters to the output variable one by one until the $lenth param has been reached, or until the end of the string.

I hope this can help someone out!

-Admiral Potato

<?php

function admiralsTruncate($string, $length){
    settype($string, 'string');
    settype($length, 'integer');
    for($a = 0; $a < $length AND $a < strlen($string); $a++){
        $output .= $string[$a];
    }
    return($output);
}

$my_string = 'cfcd208495d565ef66e7dff9f98764da';

echo admiralsTruncate($my_string, 6);    // outputs: cfcd20

echo '<br>';

echo admiralsTruncate($my_string, 9);    // outputs: cfcd20849

?>
gcdreak at farfaraway dot com 14-Apr-2009 07:56
This is a good method to check file chmod value:
<?php

$file = "../files/sample.txt";
$rights = decoct(fileperms($file));
echo "File rights: ".substr_replace($rights, "", 0, 3);

?>
billg AT microsoft.com 07-Apr-2009 07:31
Forget all of the mb_substr_replace() implementations mentioned in this page, they're all buggy.

Here is a version that mimics the behavior of substr_replace() exactly:

<?php

if (function_exists('mb_substr_replace') === false)
{
    function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
    {
        if (extension_loaded('mbstring') === true)
        {
            $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);

            if ($start < 0)
            {
                $start = max(0, $string_length + $start);
            }

            else if ($start > $string_length)
            {
                $start = $string_length;
            }

            if ($length < 0)
            {
                $length = max(0, $string_length - $start + $length);
            }

            else if ((is_null($length) === true) || ($length > $string_length))
            {
                $length = $string_length;
            }

            if (($start + $length) > $string_length)
            {
                $length = $string_length - $start;
            }

            if (is_null($encoding) === true)
            {
                return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
            }

            return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
        }

        return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
    }
}

?>
juichenieder-phnet at yahoo dot co dot uk 25-Mar-2009 10:58
I've just taken a look at the post by ntoniazzi and I have a very small correction to make.

In the second if statement, it should be a triple equals, so:

<?php if ($length === null) ?>

It requires the triple equals, for the case of pure insertion, where $length = 0, the double equals, will catch this, causing the string to be cut short.  I hope this helps someone.
NiX0n at fragfest dot cx 09-Oct-2008 09:41
The preemptive test to see if $string is "too long" shouldn't add strlen($replacement) to $max.  $max should represent the absolute maximum length of string returned.  The size of the $replacement is irrelevant in that determination.

The rest of the function (unchanged below) operates as defined above.  Meaning, the size of the $replacement is subtracted from the $max, so that the returned string is exactly the length of $max.

<?php
function truncate($string, $max = 20, $replacement = '')
{
    if (strlen($string) <= $max)
    {
        return $string;
    }
    $leave = $max - strlen ($replacement);
    return substr_replace($string, $replacement, $leave);
}
?>
spcl dot delivery at gmail dot com 27-Jul-2008 04:14
the version of my predecessor will add $rep even if the string is shorter than max. fixed version:

<?php
function truncate($string, $max = 20, $rep = '')
{
    if (strlen($string) <= ($max + strlen($rep)))
    {
        return $string;
    }
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}
?>

To preserve the filename extension you can call it like this:

truncate([filename], 30, '...' . end(explode('.', [filename])))
eblejr AT phrebh DOT com 04-Jun-2008 08:42
PHP version of Java's removeCharAt() function:

<?php
function removeCharAt($str, $int){
  return substr_replace($str,"",$int,1);
}
?>
William Barry 23-Apr-2008 12:18
I recently ran across a situation where I need to strip a heavily nested html list such that only the top level was preserved.  I started with a regular expression solution, but found that I kept matching the wrong closing ul with an outer opening ul.

This was my alternative solution, and it seems to work well:

<?php

function stripNestedLists($str)
{
    $str2 = $str;
    $lastStr = $str2;

    do
    {
        // Find the first closing ul
        $cul = strpos($str2, '</ul>');
        $ul = 0;
        $lastUL = 0;
        do
        {
            // Find the next opening ul
            $lastUL = $ul;
            $ul = strpos($str2, '<ul', $ul+1);
        }
        while ($ul !== false && $ul < $cul);

        $lastStr = $str2;
        $str2 = substr_replace($str2, '', $lastUL, $cul-$lastUL+5);
        $str2 = trim($str2);
    }
    while (strlen($str2) > 0);

    return $lastStr;
}

?>

Hope this helps someone.
jaimthorn at yahoo dot com 25-Mar-2008 10:53
I recently needed a routine that would remove the characters in one string from another, like the regex

<?php
   $result = preg_replace("/[$chars]/", "", $string);
?>

and I needed it to be fast, and accept pretty much all input.  The regex above won't work when strlen($chars) == 0.  I came up with this, admittedly pretty horrible-looking code, that is quite fast:

<?php

function RemoveChars($string, $chars)
{
    return isset($chars{0}) ? str_replace($chars{0}, "", strtr($string, $chars, str_pad($chars{0}, strlen($chars), $chars{0}))) : $string;
}

?>

According to my own measurements, the regex in ONLY faster for when strlen($chars) == 1; for longer strings, my routine is faster.  What does it do?  Let's say you want to remove the period, the comma and the exclamation mark from a string, like so:
$result = RemoveChars("Isn't this, like, totally neat..!?", ".?!");
The str_pad function creates a string equal in length to the string that contains the character to be removed, but consisting only of the first character of that string:
The input is ".,!"
The output is "..."
The strtr function translates all characters in the string-to-be-processed ("Isn't this...") that also occur in the input (".,!") to the characters in the same position in the output ("...").  In other words:
Isn't this, like, totally neat..!?
becomes
Isn't this. like. totally neat....
Finally, the first character from the input (".,!") which happens to be, again, the period, is removed from that string by the str_replace call:
Isn't this like totally neat?
The function needs to check is $chars has at least one character, or else the str_pad function will fail.  If it's empty, then the unprocessed string is returned.
ntoniazzi at sqli dot com 14-Feb-2008 01:07
Almost... In the previous note, change this :
<?php
    function mb_substr_replace($string, $replacement, $start, $length=null, $encoding=null) {
        if ($encoding == null) $encoding = mb_internal_encoding();
        if($start < 0) $start = mb_strlen($string) + $start;
    [...]
?>
ntoniazzi at sqli dot com 13-Feb-2008 09:58
There is a mistake in the mb_substr_replace function below, when the $length parameter is given negative. Here is a working version.

<?php
//Check to see if it exists in case PHP has this function later
if (!function_exists("mb_substr_replace")){
    //Same parameters as substr_replace with the extra encoding parameter.
    function mb_substr_replace($string, $replacement, $start, $length=null, $encoding=null) {
        if ($encoding == null) $encoding = mb_internal_encoding();
        if ($length == null) {
            return mb_substr($string, 0, $start, $encoding) . $replacement;
        }
        else {
            if($length < 0) $length = mb_strlen($string, $encoding) - $start + $length;
            return
                mb_substr($string, 0, $start, $encoding) .
                $replacement .
                mb_substr($string, $start + $length, mb_strlen($string, $encoding), $encoding);
        }
    }
}
?>
alishahnovin at hotmail dot com 07-Aug-2007 12:56
I like the truncate function below...however, I found a few issues. Particularly if you have content that may have any kind of punctuation in it (?, !, ?!?, --, ..., .., ;, etc.)

The older function would end up looking like "blah blah?..." or "blah blah,..." which doesn't look so nice to me...

Here's my fix. It removes all trailing punctuation (that you include in the $punctuation string below) and then adds an ellipse. So even if it has an ellipse with 3 dots, 2 dots, 4 dots, it'll be removed, then re-added.

<?php
function truncate($text,$numb,$etc = "...") {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));

$punctuation = ".!?:;,-"; //punctuation you want removed

$text = (strspn(strrev($text),  $punctuation)!=0)
        ?
        substr($text, 0, -strspn(strrev($text),  $punctuation))
        :
$text;

$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}
?>

I also needed a sort of "middle" truncate. The above function truncates around the end, but if you want to truncate around the middle (ie "Hello this is a long string." --> "Hello this ... long string.") you can use this (requires the truncate function):

<?php
function mtruncate($text, $numb, $etc = " ... ") {
    $first_part = truncate(truncate($text, strlen($text)/2, ""), $numb/2, "");
    $second_part = truncate(strrev(truncate(strrev($text), strlen($text)/2, "")), $numb/2, "");
    return $first_part.$etc.$second_part;
}
?>
joecorcoran at gmail dot com 07-Aug-2007 06:50
I've made a minor amendment to the function in the post below, to strip away the full stop (period) if the truncation occurs at the exact end of a sentence (the full stop spoils the ellipsis):

<?php

function truncate($text,$numb) {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
    //This strips the full stop:
    if ((substr($text, -1)) == ".") {
        $text = substr($text,0,(strrpos($text,".")));
    }
$etc = "...";
$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}

//Call function
truncate($text, 75);
www.kigoobe.com 21-Mar-2007 02:00
The two truncate functions provided below, have some major short comings.

1. They may cut a word in half
2. In case you are using htmlentities to get user input or are using wysiwyg editors to get user input, you can get truncated text like "he told C&eac..." instead of "he told Cécile" or "he told".

Here is what I use -

<?php
function truncate($text,$numb) {
// source: www.kigoobe.com, please keep this if you are using the function
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
$etc = " ...";
$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}

// Now, to use this function, you can call that as -
truncate($text, 75);
?>
chuayw2000 at hotmail dot com 09-Dec-2005 03:33
I don't know if this function is multibyte safe but I've written a function that will do the same in multibyte mode.

<?php
//Check to see if it exists in case PHP has this function later
if (!function_exists("mb_substr_replace")){
   //Same parameters as substr_replace with the extra encoding parameter.
    function mb_substr_replace($string,$replacement,$start,$length=null,$encoding = null){
        if ($encoding == null){
            if ($length == null){
                return mb_substr($string,0,$start).$replacement;
            }
            else{
                return mb_substr($string,0,$start).$replacement.mb_substr($string,$start + $length);
            }
        }
        else{
            if ($length == null){
                return mb_substr($string,0,$start,$encoding).$replacement;
            }
            else{
                return mb_substr($string,0,$start,$encoding). $replacement. mb_substr($string,$start + $length,mb_strlen($string,$encoding),$encoding);
            }
        }
    }
}
?>
michael(at)webstaa(dot)com 05-Dec-2005 08:47
I created this because of the need to mask a credit-card number like **** **** **** 8862

string mask ( string str, int start [, int length] )

mask() masks a copy of str delimited by the start and (optionally) length parameters with asterisks (*) in place of non-whitespace characters

<?php
    function mask ( $str, $start = 0, $length = null ) {
        $mask = preg_replace ( "/\S/", "*", $str );
        if ( is_null ( $length )) {
            $mask = substr ( $mask, $start );
            $str = substr_replace ( $str, $mask, $start );
        } else {
            $mask = substr ( $mask, $start, $length );
            $str = substr_replace ( $str, $mask, $start, $length );
        }
        return $str;
    }
?>
hermes at andycostell dot com 27-Aug-2005 11:48
I suggest changing the function suggested by Guru Evi slightly. I found that it doesn't work as written here.

Original:
function add_3dots($string,$repl,$start,$limit) {
   if(strlen($string) > $limit) {
       return substr_replace(strip_tags($string),$repl,$start,$limit);
   } else {
       return $string;
   };
};

I suggest:
function add_3dots($string,$repl,$limit) {
       if(strlen($string) > $limit) {
           return substr_replace(strip_tags($string),$repl,$limit-strlen($repl));
       } else {
           return $string;
       }
    }

Usage:

$max_length=10;//the max number of characters you want to display
$too_long_string="BLAH BLAH BLAH BLAH BLAH etc.";//the string you want to shorten (if it's longer than the $limit)
$shorter_string=add_3_dots($too_long_string,"...",$max_length);
Guru Evi 13-Jul-2005 12:44
If your string is not long enough to meet what you specify in start and length then the replacement string is added towards the end of the string.

I wanted to replace the end of the string with ... if the string was too long to display (for instance article preview on a website). The problem was that my string was sometimes not that long and it still added the replacement string. So I wrote a function to replace substr_replace in my website:

function add_3dots($string,$repl,$start,$limit) {
    if(strlen($string) > $limit) {
        return substr_replace(strip_tags($string),$repl,$start,$limit);
    } else {
        return $string;
    };
};

I use strip_tags to strip out the HTML otherwise you might get a screwed up HTML (when a tags open in the string, but because you cut-off it doesn't)
tekrat at 2d dot com 06-Jan-2005 08:55
Here's a slightly revised version of the truncation function above.

Theres isn't much of a reason to  add in the $rep at the end of the original string is less then the truncation break point.
<?php
    function truncate($substring, $max = 50, $rep = '...') {
                if(strlen($substring) >= 1){
                        $string = $substring;
                }
        $leave = $max - strlen ($rep);

        if(strlen($string) > $max){
            return substr_replace($string, $rep, $leave);
        }else{
            return $string;
        }

    }
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix by (ogt AT parasane DOT com) (which was me ;-P) from 21-JAN-05 at 11:02 EST.]
danieldoorduin at hotmail dot com 10-Dec-2004 02:48
Using substr_replace() can be avoided by using substr() instead:

<?
$string = substr($string, 0, $position_needle).$replace.substr($string, $position_needle+$length_needle);
?>

This can be useful when you need to replace parts of multibyte strings like strings encoded with utf-8. There isn't a multibute variant for substr_replace(), but for php substr() there is mb_substr(). For more information on multibyte strings see http://nl3.php.net/manual/en/ref.mbstring.php
titbits at nospam-4logical dot co dot uk 04-Aug-2004 02:28
A simple but useful 'pluralize' function using substr_replace:

  function pluralize($noun) {
    if ($noun{strlen($noun) -1} == "y")
      $noun = substr_replace($noun, "ies", strlen($noun) -1);
    else
      $noun .= "s";

    return $noun;
  }

Handy when displaying dynamic text.
dmron 17-Jun-2004 04:34
Regarding "...", even the short functions are too long and complicated, and there's no need to use substr_replace. substr() works better and is  way faster prior to 4.3.5 as the below poster stated.

function shorten( $str, $num = 100 ) {
  if( strlen( $str ) > $num ) $str = substr( $str, 0, $num ) . "...";
  return $str;
}
philip 13-May-2004 12:55
The substr_replace() function is extremely slow in PHP versions prior to 4.3.5 and 5.0.0 so consider using an alternative before this time.
tony at outshine dot com 10-May-2004 02:25
The comment by geniusdex is a good one.  Short, simple functions are the best.  But if the string is not longer than the limit set, NOTHING is returned.  Here is the function re-done to always return a string:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        $str = substr_replace($str, $dots, $len - $dotlen);
    }
    return $str;
}
?>
geniusdex ( at ) brz ( dot ) nu 23-Feb-2004 07:33
This is my version of making dotted strings:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        substr_replace($str, $dots, $len - $dotlen);
    }
}
?>
Thijs Wijnmaalen (thijs[at]nllinux.nl) 20-Jan-2004 11:05
I wrote a function that you can use for example in combination with a search script to cut off the articles that are too long.

<?php
function substr_index($text, $maxChars = 20, $splitter
= '...') {

$theReturn = $text;
$lastSpace = false;

if (strlen($text) > $maxChars) {
$theReturn = substr($text, 0, $maxChars - 1);

if (in_array(substr($text, $maxChars - 1, 1),
array(' ', '.', '!', '?'))) {
$theReturn .= substr($text, $maxChars, 1);
} else {
$theReturn = substr($theReturn, 0, $maxChars -
strlen($splitter));
$lastSpace = strrpos($theReturn, ' ');

if ($lastSpace !== false) {
$theReturn = substr($theReturn, 0, $lastSpace);
}

if (in_array(substr($theReturn, -1, 1), array(','))) {
$theReturn = substr($theReturn, 0, -1);
}
$theReturn .= $splitter;
}
}
return $theReturn;
}
?>
neon at lordneon dot com 05-Nov-2003 04:40
The easiest way (I think) to add trailing dots after a string which in my case are too long is:

<?
function dots($num, $string) {
    if (strlen($string) < $num) {
        $string = substr_replace($string, '...', '-10', $num);
    }
    return $string;
}

Then on your page do something like:
<? echo dots("30" $row['title']); ?>

if the string is greater than the specific number it'll replace 3 dots.

I hope this helps =)
?>
david at ethinkn dot com 05-Jul-2003 05:36
Here is a simple function to shorten a string and add an ellipsis

<?php

/**
 * truncate() Simple function to shorten a string and add an ellipsis
 *
 * @param string $string Origonal string
 * @param integer $max Maximum length
 * @param string $rep Replace with... (Default = '' - No elipsis -)
 * @return string
 * @author David Duong
 **/
function truncate ($string, $max = 50, $rep = '') {
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}

echo truncate ('akfhslakdhglksjdgh', 10, '...');
// Returns akfhsla... (10 chrs)

?>
thomasNOSPAM at sportentranceNOSPAM dot com 08-Oct-2002 03:01
To abbreviate links into '...' if they outreach a certain amount of space; use the preg_replace function instead.

For instance you grabbed the headlines of a news site for use on your own page and the lines are to long:

asuming the raw material is stored in $unedited;

$edited = preg_replace("/(>)([[:print:]]{52,})(<)/e", "'\\1'.substr_replace('\\2 ', '...', '48').'\\3'", $unedited);
echo $edited;

This will shorten strings longer than 52 characters into 51 characters, with the last being three dots...
klaas at group94 dot com 13-Feb-2002 10:38
THE DOT DOT DOT ISSUE

PROBLEM:
You want to abbreviate a string.
E.g. You want "BritneySpears" to show as "BritneySpe...", being only the ten first characters followed by "..."

SOLUTION:
<?
$oRIGINAL = "BritneySpears";
$sHORTER = substr_replace($oRIGINAL, '...', 10);
echo ($sHORTER);
?>

This will result in BritneySpe...
28-Sep-2001 08:30
If you would like to remove characters from the start or end of a string, try the substr() function.

For example, to remove the last three characters from a string:
$string = "To be or not to be.";
$string = substr ($string, 0, -3);
mrbrown8 at juno dot com 16-Apr-2001 12:16
Just to add to the examples, if replacement is longer than length, only the length number of chars are removed from string and all of replacement is put in its place, and therefor strlen($string) is inreased.

$var = 'ABCDEFGH:/MNRPQR/';
/*  Should return ABCDEFGH:/testingRPQR/   */
echo substr_replace ($var, 'testing', 10, 2);
jgainey at infoave dot net 13-Mar-2001 06:29
[Editor's note: for a much simpler solution, use number_format()]

I had a situation in which I needed to add a comma to the third position of a number(the price of something).

<?php
$price = "12000";
$price = substr_replace ($price, ',', -3, 0)";
?>

the result would be 12,000
the -3 counts from right to left. a regular 3 would count from left to right
I hope this helps...
substr_count
substr
Обработка строк


Возвращает подстроку

substr_replace
trim
Обработка строк
PHP Manual

substr

(PHP 4, PHP 5)

substr — Возвращает подстроку

Описание

string substr ( string $string , int $start [, int $length ] )

Возвращает подстроку строки string, начинающейся с start символа по счету и длиной length символов.

Список параметров

string

Входная строка. Должна содержать хотя бы один символ.

start

Если start неотрицателен, возвращаемая подстрока начинается с позиции start от начала строки, считая от нуля. Например, в строке 'abcdef', в позиции 0 находится символ 'a', в позиции 2 - символ 'c', и т.д.

Если start отрицательный, возвращаемая подстрока начинается с позиции, отстоящей на start символов от конца строки string.

Если string меньше либо содержит ровно start символов, будет возвращено FALSE.

Пример #1 Использование отрицательного параметра start

<?php
$rest = substr("abcdef", -1);    // возвращает "f"
$rest = substr("abcdef", -2);    // возвращает "ef"
$rest = substr("abcdef", -3, 1); // возвращает "d"
?>

length

Если length положительный, возвращаемая строка будет не длиннее length символов, начиная с параметраstart (в зависимости от длины string).

Если length отрицательный, то будет отброшено указанное этим аргументом число символов с конца строки string (после того как будет вычислена стартовая позиция, если start отрицателен). Если при этом позиция начала подстроки, определяемая аргументом start, находится в отброшенной части строки или за ней, возвращается false.

Если указан параметр length и является одним из 0, FALSE или NULL, то будет возвращена пустая строка.

Если параметр length опущен, то будет возвращена подстрока, начинающаяся с позиции, указанной параметром start и длящейся до конца строки.

Пример #2 Использование отрицательного параметра length

<?php
$rest = substr("abcdef", 0, -1);  // возвращает "abcde"
$rest = substr("abcdef", 2, -1);  // возвращает "cde"
$rest = substr("abcdef", 4, -4);  // возвращает false
$rest = substr("abcdef", -3, -1); // возвращает "de"
?>

Возвращаемые значения

Возвращает извлеченную часть строки, или FALSE в случае возникновения ошибки или пустую строку string.

Список изменений

Версия | Описание
5.2.2 - 5.2.6 | Если параметр start указывает на позицию с отрицательной обрезкой, возвращается FALSE. Другие версии возвращают строку с начала.

Примеры

Пример #3 Базовое использование substr()

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Получить доступ к отдельному символу в строке
// можно также с помощью "квадратных скобок"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

Пример #4 substr() и приведение типов

<?php
class apple {
    public function __toString() {
        return "green";
    }
}

echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
?>

Результат выполнения данного примера:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

Ошибки

Возвращает FALSE в случае ошибки.

<?php
var_dump(substr('a', 1)); // bool(false)
?>

Смотрите также

  • strrchr() - Находит последнее вхождение символа в строке
  • substr_replace() - Заменяет часть строки
  • preg_match() - Выполняет проверку на соответствие регулярному выражению
  • trim() - Удаляет пробелы (или другие символы) из начала и конца строки
  • mb_substr() - Возвращает часть строки
  • wordwrap() - Переносит строку по указанному количеству символов
  • Посимвольный доступ и изменение строки

User Contributed Notes

maxim at inbox dot ru 27-Jan-2012 04:43
Here is a recursion function to get parts of passed string which are in a char. Func looks pretty, and works fast, tell me please if you find more opt way.
<?php
$s = "info= &make&,endvcc &new& &another&info";
echo str_cut($s,"&",",");
//output:
//make,new,another

function str_cut($s,$a,$d="")
{
    $f=strpos($s,$a)+1;
    $l=strpos($s,$a,$f);
    $out= substr($s,$f,$l-$f);
                if
    (strpos($s,$a,$l+1)!==false)
    {$s=substr($s,$l+1);$out.=$d.str_cut($s,$a,$d);}
return $out;
}
?>

it is possible to output in array, you have to returns a var as an array.
Also you can add an extra needle, which would be compare with the end of strings :
replace to
$l=strpos($s,$b,$f)-$f;
and dont forget to pass into recursion call $b value, but i did like that
$b=func_get_arg(func_num_args()-1);
care! the last argument should be $a, because $b getting last arg. like that:
function str_cut($s,$d="",$a)
but i think this method of getting $b not the best way for perfomance.
Sorry for my English.
munirsunni(at)gmail(dot)com 23-Nov-2011 02:30
<?php

//Here is the function created for strip tags with sub string

function displaySubStringWithStrip($string, $length=NULL)
{
    if ($length == NULL)
            $length = 50;

    $stringDisplay = substr(strip_tags($string), 0, $length);
    if (strlen(strip_tags($string)) > $length)
        $stringDisplay .= ' ...';
    return $stringDisplay;
}

?>
leon weidauer 08-Jul-2011 01:07
When using a value of a wrong type as second parameter , substr() does not return FALSE but NULL although the docs say, it should return FALSE on error.

Prior to PHP 5.3, substr() tries to cast the second parameter to int and doesn't throw any errors. Since PHP 5.3 a warning is thrown.
Quicker 06-May-2011 04:17
If you need to parse utf-8 strings char by char, try this one:

<?php
     $utf8marker=chr(128);
     $count=0;
     while(isset($string{$count})){
       if($string{$count}>=$utf8marker) {
         $parsechar=substr($string,$count,2);
         $count+=2;
       } else {
         $parsechar=$string{$count};
         $count++;
       }
       /* do what you like with parsechar ... , eg.:*/  echo $parsechar."<BR>\r\n";
     }
?>

- it works without mb_substr
- it is fast, because it grabs characters based on indexes  when possible and avoids any count and split functions
slow at acedsl dot com 28-Mar-2011 01:47
Anyone coming from the Python world will be accustomed to making substrings by using a "slice index" on a string.  The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third "step" argument.)

<?php

function py_slice($input, $slice) {
    $arg = explode(':', $slice);
    $start = intval($arg[0]);
    if ($start < 0) {
        $start += strlen($input);
    }
    if (count($arg) === 1) {
        return substr($input, $start, 1);
    }
    if (trim($arg[1]) === '') {
        return substr($input, $start);
    }
    $end = intval($arg[1]);
    if ($end < 0) {
        $end += strlen($input);
    }
    return substr($input, $start, $end - $start);
}

print py_slice('abcdefg', '2') . "\n";
print py_slice('abcdefg', '2:4') . "\n";
print py_slice('abcdefg', '2:') . "\n";
print py_slice('abcdefg', ':4') . "\n";
print py_slice('abcdefg', ':-3') . "\n";
print py_slice('abcdefg', '-3:') . "\n";

?>

The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be  counterintuitive. (Eg, py_slice('abcdefg', '2:4') yields 'cd' not 'cde'). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.

The output from the examples:
c
cd
cdefg
abcd
abcd
efg
southern 25-Feb-2011 06:56
substr is case sensitive.  To make it case-insensitive, use something like:

<?php
if (substr($text,0,6)==strtoupper($find_me))
{
echo "Case insensitive $find_me detected.";
}
?>
nikolai dot wuestemann at t-online dot de 14-Jan-2011 08:56
If you want to have a string BETWEEN two strings, just use this function:

<?php
function get_between($input, $start, $end)
{
  $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1));
  return $substr;
}

//Example:

$string = "123456789";
$a = "12";
$b = "9";

echo get_between($string, $a, $b);

//Output:
//345678
?>
Cristianlf 29-Oct-2010 02:10
I needed a function like lpad from oracle, or right from SQL
 then I use this code :

<?php
function right($string,$chars)
{
    $vright = substr($string, strlen($string)-$chars,$chars);
    return $vright;

}

    echo right('0r0j4152',4);
?>

Result:
 4152
------------------------------------------------
This function is really simple, I just wanted to share, maybe helps someone out there.

regards,
magickey 18-Oct-2010 02:23
Simple UTF-8 Multibyte solution (without mb_substr)

<?php
  $string="texto en español";
  echo substr($string,0,14); //Outputs: texto en espa�
?>

<?php
  $string="texto en español";
  echo utf8_encode(substr(utf8_decode($string),0,14)); //Outputs: texto en españ
?>
joseph dot davidson dot 707 at gmail dot com 09-Oct-2010 12:58
Using substr() to examine characters of a string without altering the string.

<?php
$string = 'This is my string';
$length = strlen($string);
$myChar = 'm';

for($i = 0; $i < $length; $i++) {

    $showString_i = substr($string, $i, 1);
    if($myChar == $showString_i) return $i;
}
?>

can also examine subs.
uranetz 23-Sep-2010 02:20
Find differences between wokr of substr function when string length less then -start
ex:
$id=4;
var_dump(substr($id, -3));
at PHP Version 5.2.12 at windows it outputs: string(1) "4"
but at PHP Version 5.2.4-2ubuntu5.10: bool(false)
jeff dot swain at pcmmllc dot com 19-Jul-2010 05:00
I noticed a slight issue when parsing out long strings using the substr function.

Here is my string: $merge = "UPDATE AssistanceRequest SET RequestorID = '4301' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

To parse out the WHERE portion I used:
$whereClause = substr($merge, strpos($merge,'WHERE', (strlen($merge) - strpos($merge,'WHERE'))));
Normally the function returned: $whereClause = "WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

This $whereClause gives me the WHERE clause to modify the MSSQL database records being manipulated. So that when I used $whereClause as the WHERE clause to create subsequent SQL, I used the following syntax: $setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' " . $whereClause;

This should have returned: $setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

As long as the length of the original $merge string was less than 104 characters, the $setDeleteFlag sql came out correctly. However, when the length of the original $merge string exceeded 104 characters, I got this returned:

$setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

The result was that the bIsDirty field for every record in the database was set to 'DELETE'. I fixed it by breaking apart the substr to create the original $whereClause so that it looked like this:

$wherePosition = strpos($merge,'WHERE');
$whereClause = substr($merge, $wherePosition, strlen($merge) - $wherePosition);
$setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' " . $whereClause;

I do have to note that I run PHP 5.x on my development server, while I think the production host is still on 4.x. I did not seem to have an issue in development, but I don't think I tested strings longer than 104 characters. Maybe this issue has been corrected in version 5.x.
kueb at NOSPAM dot gmx dot de 15-Apr-2010 05:50
I had some problems with the order of the closing of tags.

Example:
<p>some <b><i>very</i>long</b> text to show my problem</p>
would be converted to (if the script would cut the part after "very":
<p>some <b><i>very</p></b></i>

My second problem was, that the script didn't recognized tags like <a href="#" title="title">

So my version based on bennys and erez' work looks like this:

<?php
function mb_substrws($text, $length = 180) {
    if((mb_strlen($text) > $length)) {
        $whitespaceposition = mb_strpos($text, ' ', $length) - 1;
        if($whitespaceposition > 0) {
            $chars = count_chars(mb_substr($text, 0, ($whitespaceposition + 1)), 1);
            if ($chars[ord('<')] > $chars[ord('>')]) {
                $whitespaceposition = mb_strpos($text, ">", $whitespaceposition) - 1;
            }
            $text = mb_substr($text, 0, ($whitespaceposition + 1));
        }
        // close unclosed html tags
        if(preg_match_all("|(<([\w]+)[^>]*>)|", $text, $aBuffer)) {
            if(!empty($aBuffer[1])) {
                preg_match_all("|</([a-zA-Z]+)>|", $text, $aBuffer2);
                if(count($aBuffer[2]) != count($aBuffer2[1])) {
                    $closing_tags = array_diff($aBuffer[2], $aBuffer2[1]);
                    $closing_tags = array_reverse($closing_tags);
                    foreach($closing_tags as $tag) {
                            $text .= '</'.$tag.'>';
                    }
                }
            }
        }

    }
    return $text;
}
?>
lwjct at hotmail dot com 25-Mar-2010 01:39
It doesn't support Chinese characters under utf-8 so well.

with utf-8, each Chinese character counts with 3 in length.
with utf-16, each one counts as 2 in length.
Jarrod Nettles (jarrod at squarecrow dot com) 01-Feb-2010 12:46
I've seen numerous requests over the years from people trying to put together templating systems using XML parsers or regular expressions - you can create a simple template system with the following class. It could easily be expanded to take advantage of parameters, conditionals, etc.

<?php

class Template
{
    const OPEN_BRACKET = "{";
    const CLOSE_BRACKET = "}";

    public static function inject(array $source, $template)
    {
        $ob_size = strlen(self::OPEN_BRACKET);
        $cb_size = strlen(self::CLOSE_BRACKET);

        $pos = 0;
        $end = strlen($template);

        while($pos <= $end)
        {
            if($pos_1 = strpos($template, self::OPEN_BRACKET, $pos))
            {
                if($pos_1)
                {
                    $pos_2 = strpos($template, self::CLOSE_BRACKET, $pos_1);

                    if($pos_2)
                    {
                        $return_length = ($pos_2-$cb_size) - $pos_1;

                        $var = substr($template, $pos_1+$ob_size, $return_length);

                        $template = str_replace(self::OPEN_BRACKET.$var.self::CLOSE_BRACKET, $source[$var], $template);

                        $pos = $pos_2 + $cb_size;
                    }
                    else
                    {
                        throw new exception("Incorrectly formed template - missing closing bracket. Please check your syntax.");
                        break;
                    }
                }
            }
            else
            {
                //exit the loop
                break;
            }
        }

        return $template;
    }

}

//array of values to inject into the template
$array = array("NAME" => "John Doe",
                "DOB"    => "12/21/1986",
                "ACL" => "Super Administrator");

//template using '{' and '}' to signify variables
$template = "This is your template, {NAME}. You were born on {DOB} and you are a {ACL} on this system.";

echo Template::inject($array, $template);
?>
vnonov at gmail dot com / Viktor Nonov 28-Jan-2010 10:32
<?php

//removes string from the end of other

function removeFromEnd($string, $stringToRemove) {
    $stringToRemoveLen = strlen($stringToRemove);
    $stringLen = strlen($string);

    $pos = $stringLen - $stringToRemoveLen;

    $out = substr($string, 0, $pos);

    return $out;
}

$string = 'picture.jpg.jpg';
$string = removeFromEnd($string, '.jpg');
?>
biner(gf) 19-Nov-2009 09:46
<?php
//substring without words breaking

$str = "aa bb ccc ddd ee fff gg hhh iii";

echo substr(($str=wordwrap($str,$,'$$')),0,strpos($str,'$$'));
?>
info /a/ nopticon /dot/ com 08-Oct-2009 11:52
<?php

// Substring without losing word meaning and
// tiny words (length 3 by default) are included on the result.
// "..." is added if result do not reach original string length

function _substr($str, $length, $minword = 3)
{
    $sub = '';
    $len = 0;

    foreach (explode(' ', $str) as $word)
    {
        $part = (($sub != '') ? ' ' : '') . $word;
        $sub .= $part;
        $len += strlen($part);

        if (strlen($word) > $minword && strlen($sub) >= $length)
        {
            break;
        }
    }

    return $sub . (($len < strlen($str)) ? '...' : '');
}

?>
kaj dot strom at kapsi dot fi 05-Oct-2009 04:42
One thing to keep in mind when using string indexes and UTF-8 is that string indexes are NOT multi-byte safe.

<?php
$string = 'äää1';
echo $string[3];
?>

Outputs:
¤

When it logically should output "1". This is not a bug, as PHP 'normal' string functions are not intended to be multi-byte safe. This can be solved by using this function

<?php
/**
 *
 * @param string $string String to "search" from
 * @param int $index Index of the letter we want.
 * @return string The letter found on $index.
 */
function charAt($string, $index){
    if($index < mb_strlen($string)){
        return mb_substr($string, $index, 1);
    }
    else{
        return -1;
    }
}
?>
gkhelloworld at gmail dot com 26-Jul-2009 03:44
Shortens the filename and its expansion has seen.

$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}

// RETURN: Hellothisfileha...andthisfayl.exe
// other simples on rollyz.net
gkhelloworld at gmail dot com 26-Jul-2009 03:40
Shortens the filename and its expansion has seen.

$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}

// RETURN: Hellothisfileha...andthisfayl.exe
// other simples on rollyz.net
gkhelloworld at gmail dot com 26-Jul-2009 03:39
Shortens the filename and its expansion has seen.

<?php
$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}
// RETURN: Hellothisfileha...andthisfayl.exe
?>
kaysar in ymail in com 07-Jun-2009 11:58
Drop extensions of a file (even from a file location string)

<?php

$filename = "c:/some dir/abc defg. hi.jklmn";

echo substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));

?>

output: c:/some dir/abc defg. hi

Hope it may help somebody like me.. (^_^)
benny at bennyborn dot de 06-May-2009 01:52
If you need a word-sensitive and also html-tags aware version of substr, this one should do the job. It works fine for me

<?php
/**
* word-sensitive substring function with html tags awareness
* @param text The text to cut
* @param len The maximum length of the cut string
* @returns string
**/
function substrws( $text, $len=180 ) {

    if( (strlen($text) > $len) ) {

        $whitespaceposition = strpos($text," ",$len)-1;

        if( $whitespaceposition > 0 )
            $text = substr($text, 0, ($whitespaceposition+1));

        // close unclosed html tags
        if( preg_match_all("|<([a-zA-Z]+)>|",$text,$aBuffer) ) {

            if( !empty($aBuffer[1]) ) {

                preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2);

                if( count($aBuffer[1]) != count($aBuffer2[1]) ) {

                    foreach( $aBuffer[1] as $index => $tag ) {

                        if( empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag)
                            $text .= '</'.$tag.'>';
                    }
                }
            }
        }
    }

    return $text;
}
?>
Andreas Bur (andreas dot buro at gmail dot com) 29-Apr-2009 06:25
For getting a substring of UTF-8 characters, I highly recommend mb_substr

<?php
        $utf8string = "cakeæøå";

        echo substr($utf8string,0,5);
        // output cake#
        echo mb_substr($utf8string,0,5,'UTF-8');
        //output cakeæ
?>
webmaster at oehoeboeroe dot nl 18-Apr-2009 02:07
You might expect substr('123456', 6) to return an empty string. Instead it returns boolean FALSE.

This behavior should be mentioned in the Return Values section of the manual. Instead it is only mentioned in the Parameters section.

If you need an empty string instead of a boolean FALSE you should typecast the result to a string.

<?php
$a = substr('123456', 6);              // equivalent to $a = FALSE
$a = (string) substr('123456', 6);   // equivalent to $a = '';
?>
Jakob S. 15-Apr-2009 07:13
If you need to get the first $num Chars of $str and remove them from $str you'll want to use following function:

<?php
function string_shift(&$str,$num) {
    $cutOff=substr($str,0,$num);
    $str=substr($str,$num);
    return $cutOff;
}
?>
sajjad at sajjad dot biz 08-Apr-2009 12:28
Substring utf-8 strings!
very simple!

<?php
function substru($str,$from,$len){
    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'. $from .'}'.'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'. $len .'}).*#s','$1', $str);
}
?>
link 21-Mar-2009 05:52
And as always there is bound to be a bug:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;($i<=$end && isset($textarray[$i]));$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
link 20-Mar-2009 07:19
I created some functions for entity-safe splitting+lengthcounting:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;$i<=$end;$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
ralphingATNOSPAMDOTpocztaDOTonetDOTpl 10-Mar-2009 05:08
this function return string between two delimiters
i found it very useful to get text between html tags

<?php
function strbet($inputStr, $delimeterLeft, $delimeterRight, $debug=false) {
    $posLeft=strpos($inputStr, $delimeterLeft);
    if ( $posLeft===false ) {
        if ( $debug ) {
            echo "Warning: left delimiter '{$delimeterLeft}' not found";
        }
        return false;
    }
    $posLeft+=strlen($delimeterLeft);
    $posRight=strpos($inputStr, $delimeterRight, $posLeft);
    if ( $posRight===false ) {
        if ( $debug ) {
            echo "Warning: right delimiter '{$delimeterRight}' not found";
        }
        return false;
    }
    return substr($inputStr, $posLeft, $posRight-$posLeft);
}
?>
jude dot dadzie at gmail dot com 24-Feb-2009 07:30
Here's a simple direct way of extracting the information you need from a string...

Suppose your string is "C:/www/vhosts/example.com/images/image1.jpg" which points to an image. Let's assume you want the part "images/image1.jpg". We have to do the ff:

<?php
$image="C:/www/vhosts/example.com/images/image1.jpg"

$image=substr($image,strpos($image,'image', (strlen($image)-strpos($image,'image'))));

echo $image."<br/>"; //will give 'images/image1.jpg'
?>
wrapbit at yahoo dot com 31-Oct-2008 01:00
<?php
$cfg[csvEnc] = '"';
$cfg[csvEsc] = '\\';
$cfg[csvTerm] = ",";

if( !function_exists("parse_csv_aux") ){
    function parse_csv_aux( $string ){
        global $cfg;
        $product = "";
        $in_quote = FALSE;
        $skipped_quote = FALSE;
        for($i = 0 ; $i < strlen($string) ; $i++){
            if( $string{$i} == $cfg[csvEnc] ){
                if($in_quote){
                    if($skipped_quote){
                        $product .= $cfg[csvEnc];
                        $skipped_quote = FALSE;
                    }
                    else if( !$skipped_quote ){
                        $skipped_quote = TRUE;
                    }
                    $in_quote = FALSE;
                }
                else{
                    if($skipped_quote) $skipped_quote = FALSE;
                    $in_quote = TRUE;
                }
            }
            else if( $string{$i} == "," ){
                if($in_quote){
                    $product .= ",";
                }
                else{
                    $product .= " ~ ";
                }
            }
            else{
                if($in_quote){
                    //$in_quote = FALSE;
                    $product .= $string{$i};
                }
                else{
                    $product .= $string{$i};
                }
            }
        }
        return $product;
    }
}

if( !function_exists("parse_csv") ){
    function parse_csv($string){
        global $cfg;
        $data = array();
        if( is_string($string) && ( stripos($string, "\n") !== FALSE )    ){
            $data = explode("\n", parse_csv_aux($string) );
            foreach($data as $key => $row){
                $columns = array();
                //$row = strtr(    $row, array( "\";\"" => "\";\"", ";" => " ; " )    );
                if( stripos($row, " ~ ") !== FALSE ){
                    $columns = explode( " ~ ", $row );
                    if( !is_array($columns) )$columns = array( strval($columns) );
                    $data[$key] = $columns;
                }
            }
            return $data;
        }
        else if( is_string($string) && ( stripos( ($string = parse_csv_aux($string)), " ~ ") !== FALSE )    ){
            $columns = explode( " ~ ", $string );
            if( !is_array($columns) )$columns = array( strval($columns) );
            return array($columns);
        }
        else return strval($string);
    } /* end function parse_csv */
} /* end not function exists parse_csv */

if( !function_exists("store_csv_aux") ){
    function store_csv_aux( $string ){
        global $cfg;
        $string = strtr( $string, array( "\n" => "" ) );
        $product = "";
        $in_quote = FALSE;
        for( $i = 0 ; $i < strlen($string) ; $i++ ){
            if( $string{$i} == $cfg[csvEnc] ){
                if($in_quote){
                    $product .= "\"{$cfg[csvEnc]}";
                }
                else{
                    $product .= "\"\"{$cfg[csvEnc]}";
                    $in_quote = TRUE;
                }
            }
            else if( $string{$i} == "," ){
                if($in_quote){
                    $product .= ",";
                }
                else{
                    $product .= "\",";
                    $in_quote = TRUE;
                }
            }
            else{
                if($in_quote){
                    $product .= $cfg[csvEnc];
                    $in_quote = FALSE;
                    $product .= $string{$i};
                }
                else{
                    $product .= $string{$i};
                }
            }
        }
        if($in_quote)$product .= $cfg[csvEnc];
        return $product;
    }
}

if( !function_exists("store_csv") ){
    function store_csv($data){
        global $cfg;
        if(!is_array($data))return strval($data);
        $passed_rows = FALSE;
        $product = "";
        foreach($data as $row){
            if( $passed_rows )$product .= "\n";
            if( is_array($row) ){
                $columns = "";
                $passed_cols = FALSE;
                foreach($row as $column){
                    if( $passed_cols )$columns .= ",";
                    $columns .= store_csv_aux( $column );
                    $passed_cols =TRUE;
                }
                $product .= strval($columns);
            }
            else{
                $product .= strtr( strval($row), array("\n" => "") );
            }
            $passed_rows = TRUE;
        }
        return $product;
    } /* end function store_csv */
} /* end not function exists store_csv */
?>

[EDIT BY danbrown AT php DOT net: This is a bugfix rewrite of a function originally written by "Alexander Peev".]
bill at eupeople dot net 30-Oct-2008 04:52
hi, really basic function to take blob with full http url's and turn then into "more info" links, handy for page layout etc ;)

<?php
function urltolink($data){

    while (strpos($wdata, "http")) {

    $op=strpos($wdata, "http");
    $rdata=substr($wdata, 0, $op);
    $ndata=substr($wdata, $op, strlen($wdata)-$op);

    $cp=strpos($ndata, "\n");
    $link=substr($ndata, 0, $cp);
    $oc=$op+$cp;
    $wdata=substr($wdata, $oc, strlen($wdata)-$oc);

    $edata=$edata."$rdata <a href=\"$link\">more info</a><br />";
    }
    return $edata;
}
?>
mar dot czapla at gmail dot com 24-Oct-2008 02:31
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers.
For example when using ip2country, or eliminating same range of ip addresses from your website :D

<?php

function ip2no($val)
{
    list($A,$B,$C,$D)    =    explode(".",$val);
    return
        substr("000".$A,-3).
        substr("000".$B,-3).
        substr("000".$C,-3).
        substr("000".$D,-3);
}

$min        =    ip2no("10.11.1.0");
$max        =    ip2no("111.11.1.0");
$visitor    =    ip2no("105.1.20.200");

if($min<$visitor && $visitor<$max)
    {    echo 'Welcome !';    }
else
    {    echo 'Get out of here !';    }

?>
mr.davin 29-Sep-2008 10:01
Simple use of substr to determine possession:

<?php
function possessive ($word) {
    return  $word.(substr($word, -1) == 's' ? "'" : "'s");
}

// Davis => Davis'
// Paul => Paul's
?>
NULL_byte 19-Sep-2008 03:21
<?php

function insert_substr($str, $pos, $substr) {
    $part1 = substr($str, 0, -$pos);
    $part2 = substr($str, -$pos);
    return $part1.$substr.$part2;
}

?>
baldaris69 at yahoo dot com 29-Aug-2008 12:57
***Caution newbie***
To extract a file Extension this fuction could be useful.

<?php
$file_extension = substr($filename , strrpos($filename , '. ') +1);
?>

Suppose your file name is Baldaris.jpeg

strrpos will return the last dot position in the string 9 so

so the compiler will execute substr($filename , 10)

$file_extension will have value jpeg

pretty cool...

Cheer's

Baldaris
post [at] jannik - zappe [dot] de 05-Aug-2008 07:59
Just a little function to cut a string by the wanted amount. Works in both directions.

<?php
function cutString($str, $amount = 1, $dir = "right")
{
  if(($n = strlen($str)) > 0)
  {
    if($dir == "right")
    {
      $start = 0;
      $end = $n-$amount;
    } elseif( $dir == "left") {
      $start = $amount;
      $end = $n;
    }

    return substr($str, $start, $end);
  } else return false;
}
?>

Enjoy ;)
jamesvanboxtel at wsu dot edu 31-Jul-2008 02:17
Here is a quick function to get the substring of a string up to and including the last occurrence of $needle

<?php
function substrtruncate($string, $needle)
{
    return substr($string, 0, strrpos($string, $needle)+1);
}

$current_dir = substrtruncate($_SERVER['SCRIPT_NAME'], '/');
?>
Anonymous 29-Jul-2008 11:18
I wrote this simple function to limit the middle characters of a string to a specified length.

<?php
$input = "hello world"
echo(limitchrmid($imput,10)) // hel ... rld

//limit chars middle
function limitchrmid($value,$lenght){
    if (strlen($value) >= $lenght ){
        $lenght_max = ($lenght/2)-3;
        $start = strlen($value)- $lenght_max;
        $limited = substr($value,0,$lenght_max);
        $limited.= " ... ";
        $limited.= substr($value,$start,$lenght_max);
    }
    else{
        $limited = $value;
    }
    return $limited;
}
?>
svihel 27-Jun-2008 01:09
joao dot martins at plako dot net
26-Mar-2008 09:14

ben at enemy dot dk
10-Feb-2008 05:48

Updated function. The previous one will return empty value if the $string has no letter spaces. This is usefull if some of your strings have only one word.

<?php
function cutText($string, $setlength) {
    $length = $setlength;
    if($length<strlen($string)){
        while (($string{$length} != " ") AND ($length > 0)) {
            $length--;
        }
        if ($length == 0) return substr($string, 0, $setlength);
        else return substr($string, 0, $length);
    }else return $string;
}
?>
serzh at nm dot ru 03-Jun-2008 03:13
easy and quick way to limit length of a text by not cutting full words:

textLimit('some words', 7) is 'some...'

<?php
function textLimit($string, $length, $replacer = '...')
{
  if(strlen($string) > $length)
  return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;

  return $string;
}
?>
Anonymous 17-Mar-2008 03:53
Split a string to an array of strings specified by an array of lengths:

<?php
function split_by_lengths($inString, $arrayLengths)
{
    $output = array();
    foreach ($arrayLengths as $oneLength)
    {
        $output[] = substr($inString, 0, $oneLength);
        $inString = substr($inString, $oneLength);
    }
    return ($output);
}
?>
split_by_lengths('teststringtestteststring', array(4,6,4,4,6)) returns:
array('test','string','test','test','string')

Don't use it on user input without some error handling!
kriskra at gmail dot com 29-Feb-2008 05:21
The javascript charAt equivalent in php of felipe has a little bug. It's necessary to compare the type (implicit) aswell or the function returns a wrong result:
<?php
function charAt($str,$pos) {
    return (substr($str,$pos,1) !== false) ? substr($str,$pos,1) : -1;
}
?>
Anonymous 22-Feb-2008 05:12
I've used the between, after, before, etc functions that biohazard put together for years and they work great.  I've also added to it a new function that I use a lot and thought others might like it as well.  It uses his before/after functions so they are required to use it.

<?php
$example_html = "<p>test1 Test2</p><title>hi there</title><p>Testing</p>";
$paragraph_text = multi_between('<p>', '</p>', $example_html);

//Prints an arry of:
//Array ( [1] => test1 Test2 [2] => Testing )
print_r($paragraph_text);

function multi_between($this, $that, $inthat)
{
   $counter = 0;
   while ($inthat)
   {
      $counter++;
      $elements[$counter] = before($that, $inthat);
      $elements[$counter] = after($this, $elements[$counter]);
      $inthat = after($that, $inthat);
   }
   return $elements;
}
//Get the help functions from biohazard's post below.
?>
highstrike at gmail dot com 05-Jan-2008 08:47
Because i didnt see a function that would cut a phrase from a text (article or whatever) no matter where, front/middle/end and add ... + keeping the words intact, i wrote this:

Usage:
- The parameter $value if array will need the whole text and the portion you want to start from, a string. EG: cuttext(array($text, $string), 20). If the string is "have" and is near the beginning of the text, the function will cut like "I have a car ...", if the string is in the middle somewhere it will cut like "... if you want to have your own car ..." and if its somewhere near the end it will cut like "... and you will have one."
- The $length parameter is self explanatory.

Note: if you have just a string "127hh43h2h52312453jfks2" and you want to cut it, just use the function like so: cuttext($string, 10) and it will cut it like "127hh43h2h..."

<?php

////////////////////////////////////////////////////////
// Function:         cuttext
// Description: Cuts a string and adds ...

function cuttext($value, $length)
{
    if(is_array($value)) list($string, $match_to) = $value;
    else { $string = $value; $match_to = $value{0}; }

    $match_start = stristr($string, $match_to);
    $match_compute = strlen($string) - strlen($match_start);

    if (strlen($string) > $length)
    {
        if ($match_compute < ($length - strlen($match_to)))
        {
            $pre_string = substr($string, 0, $length);
            $pos_end = strrpos($pre_string, " ");
            if($pos_end === false) $string = $pre_string."...";
            else $string = substr($pre_string, 0, $pos_end)."...";
        }
        else if ($match_compute > (strlen($string) - ($length - strlen($match_to))))
        {
            $pre_string = substr($string, (strlen($string) - ($length - strlen($match_to))));
            $pos_start = strpos($pre_string, " ");
            $string = "...".substr($pre_string, $pos_start);
            if($pos_start === false) $string = "...".$pre_string;
            else $string = "...".substr($pre_string, $pos_start);
        }
        else
        {
            $pre_string = substr($string, ($match_compute - round(($length / 3))), $length);
            $pos_start = strpos($pre_string, " "); $pos_end = strrpos($pre_string, " ");
            $string = "...".substr($pre_string, $pos_start, $pos_end)."...";
            if($pos_start === false && $pos_end === false) $string = "...".$pre_string."...";
            else $string = "...".substr($pre_string, $pos_start, $pos_end)."...";
        }

        $match_start = stristr($string, $match_to);
        $match_compute = strlen($string) - strlen($match_start);
    }

    return $string;
}

?>
morgangalpin att gmail dotty com 24-Sep-2007 10:55
Adding the $limit parameter introduced a bug that was not present in the original. If $limit is small or negative, a string with a length exceeding the limit can be returned. The $limit parameter should be checked. It takes slightly more processing, but it is dwarfed in comparison to the use of strlen().

<?php
  function short_name($str, $limit)
  {
    // Make sure a small or negative limit doesn't cause a negative length for substr().
    if ($limit < 3)
    {
      $limit = 3;
    }

    // Now truncate the string if it is over the limit.
    if (strlen($str) > $limit)
    {
      return substr($str, 0, $limit - 3) . '...';
    }
    else
    {
      return $str;
    }
  }
?>
corphi 12-Sep-2007 04:06
I prefer
<?php
function short_name($str, $limit)
{
    return strlen($str) > $limit ? substr($str, 0, $limit - 3) . '...' : $str;
}
?>

Now, every returned string has a maximum length of $limit chars (instead of $limit + 3).
Petez 31-Aug-2007 03:56
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

<?php
/* substr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = substr($string,0,11);
    if ($opening == 'Lorem ipsum'){
        true;
    }else{
        false;
    }
}
$endtime1 = endTimer();

/* direct access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    if ($string[0] == 'L' && $string[1] == 'o' && $string[2] == 'r' && $string[3] == 'e' && $string[4] == 'm' && $string[5] == ' ' && $string[6] == 'i' && $string[7] == 'p' && $string[8] == 's' && $string[9] == 'u' && $string[10] == 'm'){
        true;
    }else{
        false;
    }
}
$endtime2 = endTimer();

/* strstr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = strstr($string,'Lorem ipsum');
    if ($opening == true){
        true;
    }else{
        false;
    }
}
$endtime3 = endTimer();

echo $endtime1."\r\n".$endtime2."\r\n".$endtime3;
?>

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

(substr) 3.24
(direct access) 11.49
(strstr) 4.96

(With standard deviations 0.01, 0.02 and 0.04)

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
ein at anti-logic dot com 30-Jul-2007 03:06
If you need to divide a large string (binary data for example) into segments, a much quicker way to do it is to use streams and the php://memory stream wrapper.

For example, if you have a large string in memory, write it to a memory stream like
<?php
$segment_length = 8192; // this is how long our peice will be
$fp = fopen("php://memory", 'r+'); // create a handle to a memory stream resource
fputs($fp, $payload); // write data to the stream
$total_length=ftell($fp); // get the length of the stream
$payload_chunk = fread ( $fp, $segment_length  );
?>

Working with large data sets, mine was 21MB, increased the speed several factors.
Robert Chapin 26-Jun-2007 02:40
All the references to "curly braces" on this page appear to be obsolete.

According to http://us.php.net/manual/en/language.types.string.php

"Using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6."

Robert Chapin
Chapin Information Services
lanny at freemail dot hu 26-Jun-2007 03:31
Starting from version 5.2.3 if $start is negative and larger then the length of the string, the result is an empty string, while in earlier versions the result was the string itself!

substr ("abcdef", -1000);

result in 5.2.0
'abcdef'

result in 5.2.3
''

This is a small inconsistency, one of those things that makes the life of a PHP programmer like hell.
Antoine 10-May-2007 09:08
The functions submitted below are a waste of time and memory. To convert a string to an integer or a trimmed float, use the built in conversion instead of parsing the string, e.g :

<?php
$x = "27.2400";
echo (float)$x; // 27.24
echo (int)$x; // 27
?>
siavashg at gmail dot com 06-Mar-2007 01:51
A further addition to Jean-Felix function to extract data between delimeters.

The previous function wouldn't return the correct data if the delimeters used where long than one char. Instead the following function should do the job.

<?php
function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) {
   $posLeft  = stripos($inputstr,$delimeterLeft)+strlen($delimeterLeft);
   $posRight = stripos($inputstr,$delimeterRight,$posLeft+1);
   return  substr($inputstr,$posLeft,$posRight-$posLeft);
}
?>
ijavier aka(not imatech) igjav 14-Feb-2007 02:20
<?php
/*
    An advanced substr but without breaking words in the middle.
    Comes in 3 flavours, one gets up to length chars as a maximum, the other with length chars as a minimum up to the next word, and the other considers removing final dots, commas and etcteteras for the sake of beauty (hahaha).
   This functions were posted by me some years ago, in the middle of the ages I had to use them in some corporations incorporated, with the luck to find them in some php not up to date mirrors. These mirrors are rarely being more not up to date till the end of the world... Well, may be am I the only person that finds usef not t bre word in th middl?

Than! (ks)

This is the calling syntax:

    snippet(phrase,[max length],[phrase tail])
    snippetgreedy(phrase,[max length before next space],[phrase tail])

*/

function snippet($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}

// It behaves greedy, gets length characters ore goes for more

function snippetgreedy($text,$length=64,$tail="...") {
    $text = trim($text);
    if(strlen($text) > $length) {
        for($i=0;$text[$length+$i]!=" ";$i++) {
            if(!$text[$length+$i]) {
                return $text;
            }
        }
        $text = substr($text,0,$length+$i) . $tail;
    }
    return $text;
}

// The same as the snippet but removing latest low punctuation chars,
// if they exist (dots and commas). It performs a later suffixal trim of spaces

function snippetwop($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}

/*
echo(snippet("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetwop("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetgreedy("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea"));
*/
?>
persisteus at web dot de 13-Feb-2007 07:45
Here is also a nice (but a bit slow) alternative for colorizing an true color image:

<?php
// $colorize = hexadecimal code in String format, f.e. "10ffa2"
// $im = the image that have to be computed

$red = hexdec(substr($colorize, 0, 2));
$green = hexdec(substr($colorize, 2, 2));
$blue = hexdec(substr($colorize, 4, 2));

$lum_c = floor(($red*299 + $green*587 + $blue*144) / 1000);

for ($i = 0; $i < $lum_c; $i++)
{
  $r = $red * $i / $lum_c;
  $g = $green * $i / $lum_c;
  $b = $blue * $i / $lum_c;
  $pal[$i] = $r<<16 | $g<<8 | $b;
}
$pal[$lum_c] = $red<<16 | $green<<8 | $blue;
for ($i = $lum_c+1; $i < 255; $i++)
{
  $r = $red + (255-$red) * ($i-$lum_c) / (255-$lum_c);
  $g = $green + (255-$green) * ($i-$lum_c) / (255-$lum_c);
  $b = $blue + (255-$blue) * ($i-$lum_c) / (255-$lum_c);
  $pal[$i] = $r<<16 | $g<<8 | $b;
}

$sy = imagesy($im);
$sx = imagesx($im);
for($y=0;$y<$sy;$y++)
{
  for($x=0;$x<$sx;$x++)
  {
    $rgba = imagecolorat($im, $x, $y);
    $a = ($rgba & 0x7F000000) >> 24;
    $r = ($rgba & 0xFF0000) >> 16;
    $g = ($rgba & 0x00FF00) >> 8;
    $b = ($rgba & 0x0000FF);

    $lum = floor(($r*299+$g*587+$b*144)/1000);

    imagesetpixel($im, $x, $y, $a<<24 | $pal[$lum]);
  }
}
?>
egingell at sisna dot com 19-Oct-2006 03:19
<?php

/**
 * string substrpos(string $str, mixed $start [[, mixed $end], boolean $ignore_case])
 *
 * If $start is a string, substrpos will return the string from the position of the first occuring $start to $end
 *
 * If $end is a string, substrpos will return the string from $start to the position of the first occuring $end
 *
 * If the first character in (string) $start or (string) $end is '-', the last occuring string will be used.
 *
 * If $ignore_case is true, substrpos will not care about the case.
 * If $ignore_case is false (or anything that is not (boolean) true, the function will be case sensitive.
 *        Both of the above: only applies if either $start or $end are strings.
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', 5, '5');
 *        // Prints 'is a string with 01234';
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', '5', 5);
 *        // Prints '56789'
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-string')
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', true)
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', false)
 *        // Prints 's is a string with 0123456789 numbers in it and two strings.'
 *
 * Warnings:
 *        Since $start and $end both take either a string or an integer:
 *            If the character or string you are searching $str for is a number, pass it as a quoted string.
 *        If $end is (integer) 0, an empty string will be returned.
 *        Since this function takes negative strings ('-search_string'):
 *            If the string your using in $start or $end is a '-' or begins with a '-' escape it with a '\'.
 *            This only applies to the *first* character of $start or $end.
 */

// Define stripos() if not defined (PHP < 5).
if (!is_callable("stripos")) {
    function stripos($str, $needle, $offset = 0) {
        return strpos(strtolower($str), strtolower($needle), $offset);
    }
}

function substrpos($str, $start, $end = false, $ignore_case = false) {
    // Use variable functions
    if ($ignore_case === true) {
        $strpos = 'stripos'; // stripos() is included above in case it's not defined (PHP < 5).
    } else {
        $strpos = 'strpos';
    }

    // If end is false, set it to the length of $str
    if ($end === false) {
        $end = strlen($str);
    }

    // If $start is a string do what's needed to make it an integer position for substr().
    if (is_string($start)) {
        // If $start begins with '-' start processing until there's no more matches and use the last one found.
        if ($start{0} == '-') {
            // Strip off the '-'
            $start = substr($start, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = $strpos($str, $start, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            // If $start begins with '\-', strip off the '\'.
            if ($start{0} . $start{1} == '\-') {
                $start = substr($start, 1);
            }
            $pos = $strpos($str, $start);
        }
        $start = $pos !== false ? $pos : 0;
    }

    // Chop the string from $start to strlen($str).
    $str = substr($str, $start);

    // If $end is a string, do exactly what was done to $start, above.
    if (is_string($end)) {
        if ($end{0} == '-') {
            $end = substr($end, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = strpos($str, $end, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            if ($end{0} . $end{1} == '\-') {
                $end = substr($end, 1);
            }
            $pos = $strpos($str, $end);
        }
        $end = $pos !== false ? $pos : strlen($str);
    }

    // Since $str has already been chopped at $start, we can pass 0 as the new $start for substr()
    return substr($str, 0, $end);
}

?>
feedback at realitymedias dot com 15-Oct-2006 05:47
This function can replace substr() in some situations you don't want to cut right in the middle of a word. strtrim will cut between words when it is possible choosing the closest possible final string len to return. the maxoverflow parameter lets you choose how many characters can overflow past the maxlen parameter.

<?php

function strtrim($str, $maxlen=100, $elli=NULL, $maxoverflow=15) {
    global $CONF;

    if (strlen($str) > $maxlen) {

        if ($CONF["BODY_TRIM_METHOD_STRLEN"]) {
            return substr($str, 0, $maxlen);
        }

        $output = NULL;
        $body = explode(" ", $str);
        $body_count = count($body);

        $i=0;

        do {
            $output .= $body[$i]." ";
            $thisLen = strlen($output);
            $cycle = ($thisLen < $maxlen && $i < $body_count-1 && ($thisLen+strlen($body[$i+1])) < $maxlen+$maxoverflow?true:false);
            $i++;
        } while ($cycle);
        return $output.$elli;
    }
    else return $str;
}

?>
joseph dot morphy at gmail dot com 16-Aug-2006 09:31
<?php
//function to get a substring between between two other substrings

function substring_between($haystack,$start,$end) {
    if (strpos($haystack,$start) === false || strpos($haystack,$end) === false) {
        return false;
    } else {
        $start_position = strpos($haystack,$start)+strlen($start);
        $end_position = strpos($haystack,$end);
        return substr($haystack,$start_position,$end_position-$start_position);
    }
}

//use of this function to get the title of an html document

$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
fclose($handle);

$contents = htmlspecialchars($contents);
$title = substring_between($contents,'&lt;title&gt;','&lt;/title&gt;');

?>
shadzar 13-Feb-2006 05:21
a function to read in a file and split the string into its individual characters and display them as images for a webcounter.

can be used anywhere you need to split a string where a seperator is not present and versions where the str_split() function is also not present.

<?php
//start counter
$filename = "counter_file.txt";
$pathtoiamges = "http://www.yoursite.com/counter/";//where is your iamges
$extension = ".gif";//what filetype are your images in
//--------------do not change below this line-------------------
$counter=file_get_contents($filename);
$counter++;
$count=$counter;
$current=0;
$visit=array("");//array to hold individual characters
//split string into individual characters
//same as str_split($str) in PHP5
while (strlen($count)>0)
    {
    $current++;
    $visit[$current]=substr($count,0,1);//get current digit
    $count=substr($count,1,strlen($count));//reduce number string to remove last stored digit
    }
//display images of digits
foreach ($visit as $vis)
    {
    if ($vis!=""){echo "<img src=\"". $pathtoimages . $vis . .$extension . "\">";}
    }
$list = fopen($filename, "w+");
fwrite($list, $counter);
fclose($list);
//end counter
?>

requires a file to store the counter and 10 images to represent the digits (0-9) if used as a counter.
wishie at gmail dot com 03-Feb-2006 06:37
Here's a function I wrote that'll insert a string into another string with an offset.

<?php
// $insertstring - the string you want to insert
// $intostring - the string you want to insert it into
// $offset - the offset

function str_insert($insertstring, $intostring, $offset) {
    $part1 = substr($intostring, 0, $offset);
    $part2 = substr($intostring, $offset);

    $part1 = $part1 . $insertstring;
    $whole = $part1 . $part2;
    return $whole;
}
?>
Bradley from California 10-Jan-2006 01:34
Add on to (a function originally written by) "Matias from Argentina": str_format_number function.

Just added handling of $String shorter then $Format by adding a side to start the fill and a string length to the while loop.

<?php
function str_format_number($String, $Format, $Start = 'left'){
    //If we want to fill from right to left incase string is shorter then format
    if ($Start == 'right') {
        $String = strrev($String);
        $Format = strrev($Format);
    }
    if($Format == '') return $String;
    if($String == '') return $String;
    $Result = '';
    $FormatPos = 0;
    $StringPos = 0;
    while ((strlen($Format) - 1) >= $FormatPos && strlen($String) > $StringPos) {
        //If its a number => stores it
        if (is_numeric(substr($Format, $FormatPos, 1))) {
            $Result .= substr($String, $StringPos, 1);
            $StringPos++;
            //If it is not a number => stores the caracter
        } else {
            $Result .= substr($Format, $FormatPos, 1);
        }
        //Next caracter at the mask.
        $FormatPos++;
    }
    if ($Start == 'right') $Result = strrev($Result);
    return $Result;
}
?>
eallik at hotmail dot com 04-Jan-2006 07:22
Be careful when comparing the return value of substr to FALSE. FALSE may be returned even if the output is a valid string.

substr("0", 0); // equals "0", comparision with FALSE evaluates to true, because "0" == 0 == FALSE
mr at bbp dot biz 14-Dec-2005 02:54
Here's a little addon to the html_substr function posted by fox.

Now it counts only chars outside of tags, and doesn't cut words.

Note: this will only work in xhtml strict/transitional due to the checking of "/>" tags and the requirement of quotations in every value of a tag. It's also only been tested with the presence of br, img, and a tags, but it should work with the presence of any tag.

<?php
function html_substr($posttext, $minimum_length = 200, $length_offset = 20, $cut_words = FALSE, $dots = TRUE) {

    // $minimum_length:
    // The approximate length you want the concatenated text to be

    // $length_offset:
    // The variation in how long the text can be in this example text
    // length will be between 200 and 200-20=180 characters and the
    // character where the last tag ends

    // Reset tag counter & quote checker
    $tag_counter = 0;
    $quotes_on = FALSE;
    // Check if the text is too long
    if (strlen($posttext) > $minimum_length) {
        // Reset the tag_counter and pass through (part of) the entire text
        $c = 0;
        for ($i = 0; $i < strlen($posttext); $i++) {
            // Load the current character and the next one
            // if the string has not arrived at the last character
            $current_char = substr($posttext,$i,1);
            if ($i < strlen($posttext) - 1) {
                $next_char = substr($posttext,$i + 1,1);
            }
            else {
                $next_char = "";
            }
            // First check if quotes are on
            if (!$quotes_on) {
                // Check if it's a tag
                // On a "<" add 3 if it's an opening tag (like <a href...)
                // or add only 1 if it's an ending tag (like </a>)
                if ($current_char == '<') {
                    if ($next_char == '/') {
                        $tag_counter += 1;
                    }
                    else {
                        $tag_counter += 3;
                    }
                }
                // Slash signifies an ending (like </a> or ... />)
                // substract 2
                if ($current_char == '/' && $tag_counter <> 0) $tag_counter -= 2;
                // On a ">" substract 1
                if ($current_char == '>') $tag_counter -= 1;
                // If quotes are encountered, start ignoring the tags
                // (for directory slashes)
                if ($current_char == '"') $quotes_on = TRUE;
            }
            else {
                // IF quotes are encountered again, turn it back off
                if ($current_char == '"') $quotes_on = FALSE;
            }

            // Count only the chars outside html tags
            if($tag_counter == 2 || $tag_counter == 0){
                $c++;
            }

            // Check if the counter has reached the minimum length yet,
            // then wait for the tag_counter to become 0, and chop the string there
            if ($c > $minimum_length - $length_offset && $tag_counter == 0 && ($next_char == ' ' || $cut_words == TRUE)) {
                $posttext = substr($posttext,0,$i + 1);
                if($dots){
                   $posttext .= '...';
                }
                return $posttext;
            }
        }
    }
    return $posttext;
}

?>
felipe at spdata dot com dot br 29-Nov-2005 04:48
JavaScript charAt PHP equivalent

<?php
    function charAt($str, $pos)
    {
        return (substr($str, $pos, 1)) ? substr($str, $pos, 1) : -1;
    }
?>

If found, return the charecter at the specified position, otherwise return -1
frank at jkelloggs dot dk 25-Jul-2005 02:37
Regarding the utf8_substr function from lmak: The pattern '/./u' doesn't match newline characters. This means that the substring from 0 to the total length of the string will miss the number of characters in the end matching the number of newlines in the string. To fix this one can add the s modifier (PCRE_DOTALL) in the pattern:

<?php
function utf8_substr($str,$start)
{
   preg_match_all("/./su", $str, $ar);

   if(func_num_args() >= 3) {
       $end = func_get_arg(2);
       return join("",array_slice($ar[0],$start,$end));
   } else {
       return join("",array_slice($ar[0],$start));
   }
}
?>
julius at infoguiden dot no 04-Jul-2005 11:23
This function shortens the string down to maximum lengt defined in $max_lengt. If the string is longer the function finds the last occurance of a space and adds three dots at the end to illustrate that it is more text. If the string is without spaces it stops at exacly max lengt, also adding three dots. If the string is shorter than max lengt it returns the string as it is. This is useful for previewing long strings.

<?php
function str_stop($string, $max_length){
    if (strlen($string) > $max_length){
        $string = substr($string, 0, $max_length);
        $pos = strrpos($string, " ");
        if($pos === false) {
               return substr($string, 0, $max_length)."...";
           }
        return substr($string, 0, $pos)."...";
    }else{
        return $string;
    }
}
?>
php_net at thomas dot trella dot de 29-Jun-2005 08:07
I needed to cut a string after x chars at a  html converted utf-8 text (for example Japanese text like &#23344;&#35632;&#24368;&#33072;&#27440;&#32591;).
The problem was, the different length of the signs, so I wrote the following function to handle that.
Perhaps it helps.

<?php

function html_cutstr ($str, $len)
{
    if (!preg_match('/\&#[0-9]*;.*/i', $str))
    {
        $rVal = strlen($str, $len);
        break;
    }

    $chars = 0;
    $start = 0;
    for($i=0; $i < strlen($str); $i++)
    {
        if ($chars >= $len)
        break;

        $str_tmp = substr($str, $start, $i-$start);
        if (preg_match('/\&#[0-9]*;.*/i', $str_tmp))
        {
            $chars++;
            $start = $i;
        }
    }
    $rVal = substr($str, 0, $start);
    if (strlen($str) > $start)
    $rVal .= " ...";
    return $rVal;
}
?>
ivanhoe011 at gmail dot com 07-Jun-2005 08:31
If you need just a single character from the string you don't need to use substr(), just use curly braces notation:

<?php
    // both lines will output the 3rd character
    echo substr($my_string, 2, 1);
    echo $my_string{2};
?>

curly braces syntax is faster and more readable IMHO..
rob NOSPAM at clancentric dot net 07-Jun-2005 03:43
I have developed a function with a similar outcome to jay's

Checks if the last character is or isnt a space. (does it the normal way if it is)
It explodes the string into an array of seperate works, the effect is... it chops off anything after and including the last space.

<?php
function limit_string($string, $charlimit)
{
    if(substr($string,$charlimit-1,1) != ' ')
    {
        $string = substr($string,'0',$charlimit);
        $array = explode(' ',$string);
        array_pop($array);
        $new_string = implode(' ',$array);

        return $new_string.'...';
    }
    else
    {
        return substr($string,'0',$charlimit-1).'...';
    }
}
?>
bleakwind at msn dot com 25-May-2005 10:11
This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut() ...

Note:
1.Use it like this bite_str(string str, int start, int length [,byte of on string]);
2.First character's position is 0. Second character position is 1, and so on...
3.$byte is one character length of your encoding, For example: utf-8 is "3", gb2312 and big5 is "2"...you can use the function strlen() get it...
Enjoy it :) ...

--- Bleakwind
QQ:940641
http://www.weaverdream.com

PS:I'm sorry my english is too poor... :(

<?php
// String intercept By Bleakwind
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string, $start, $len, $byte=3)
{
    $str     = "";
    $count   = 0;
    $str_len = strlen($string);
    for ($i=0; $i<$str_len; $i++) {
        if (($count+1-$start)>$len) {
            $str  .= "...";
            break;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
            $count = $count+2;
            $i     = $i+$byte-1;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
            $str  .= substr($string,$i,1);
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
            $str  .= substr($string,$i,$byte);
            $count = $count+2;
            $i     = $i+$byte-1;
        }
    }
    return $str;
}

// Test
$str = "123456���ֽ�123456�ַ���123456��ȡ����";
for($i=0;$i<30;$i++){
    echo "<br>".bite_str($str,$i,20);
}
?>
fanfatal at fanfatal dot pl 16-May-2005 11:45
Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and bbcode tags

<?php

/**
 * string csubstr ( string string, int start [, int length] )
 *
 * @author FanFataL
 * @param string string
 * @param int start
 * @param [int length]
 * @return string
 */
function csubstr($string, $start, $length=false) {
    $pattern = '/(\[\w+[^\]]*?\]|\[\/\w+\]|<\w+[^>]*?>|<\/\w+>)/i';
    $clean = preg_replace($pattern, chr(1), $string);
    if(!$length)
        $str = substr($clean, $start);
    else {
        $str = substr($clean, $start, $length);
        $str = substr($clean, $start, $length + substr_count($str, chr(1)));
    }
    $pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
    if(preg_match('/'.$pattern.'/is', $string, $matched))
        return $matched[0];
    return $string;
}

?>

Using this is similar to simple substr.

Greatings ;]
...
woutermb at gmail dot com 21-Mar-2005 11:19
Well this is a script I wrote, what it does is chop up long words with malicious meaning into several parts. This way, a chat in a table will not get stretched anymore.

<?php

function text($string,$limit=20,$chop=10){

$text = explode(" ",$string);
while(list($key, $value) = each($text)){
    $length = strlen($value);
    if($length >=20){
        for($i=0;$i<=$length;$i+=10){
            $new .= substr($value, $i, 10);
            $new .= " ";
        }
         $post .= $new;
    }
    elseif($length <=15){
        $post .= $value;
    }
    $post .= " ";
}
return($post);
}

// for example, this would return:
$output = text("Well this text doesn't get cut up, yet thisssssssssssssssssssssssss one does.", 10, 5);

echo($output); // "Well this text doesn't get cup up, yet thiss sssss sssss sssss sssss sss one does."
?>

I hope it was useful.. :)
steve at unicycle dot co dot nz 13-Mar-2005 09:34
To quickly trim an optional trailing slash off the end of a path name:

if (substr( $path, -1 ) == '/') $path = substr( $path, 0, -1 );
Matias from Argentina 24-Feb-2005 12:55
Hello,
Here you are a function to format your
numeric strings. Enjoy it.

<?php
function str_format_number($String, $Format){
    if ($Format == '') return $String;
    if ($String == '') return $String;

    $Result = '';
    $FormatPos = 0;
    $StringPos = 0;
    While ((strlen($Format) - 1) >= $FormatPos){
        //If its a number => stores it
        if (is_numeric(substr($Format, $FormatPos, 1))){
            $Result .= substr($String, $StringPos, 1);
            $StringPos++;
        //If it is not a number => stores the caracter
        } Else {
            $Result .= substr($Format, $FormatPos, 1);
        }
        //Next caracter at the mask.
        $FormatPos++;
    }

    return $Result;
}

// For phone numbers at Buenos Aires, Argentina
// Example 1:
    $String = "541143165500";
    $Format = "+00 00 0000.000";
    Echo str_format_number($String, $Format); // Returns "+54 11 4316.5500"

// Example 2:
    $String = "541143165500";
    $Format = "+00 00 0000.0000000";
    Echo str_format_number($String, $Format); // Returns "+54 11 4316.5500"

// Example 3:
    $String = "541143165500";
    $Format = "+00 00 0000.000 a";
    Echo str_format_number($String, $Format); // Returns "+54 11 4316.550 a"

?>

How it works explanation:

str_format_number($String, $Format)
Spects two parameters $String and $Format,
both should be strings.
$String: coulbe any kind of data type,
but it's oriented to numeric string, like
phone numbers.
$Format: should be a conjunction between
numbers (any one) and others caracters.

str_format_number takes each caracter
of $Format, if it isn't a number stores
it to be returned later, but if it is a
number takes the caracter of $String
placed in the position corresponding to
the amount of numbers in $Format so far
starting from zero.

If $Format has less numbers than $string
caracters the rest of the caracters at
the end of $String should be ignored.
If $Format has more numbers than $string
caracters the no caracter will be used,
so those will be ignored.
crashmanATgreenbomberDOTcom 21-Feb-2005 06:34
A fellow coder pointed out to me that $string{-n} will no longer return the character at postion -n is. Use $string{strlen($string) - n) instead.
andrewmclagan at gmail dot com 20-Feb-2005 01:58
Hi there here is a little function i wrote to limit the number of lines in a string, i could not find anything else like it out there

<?php
function lineLimiter ($string = "", $max_lines = 1) {

         $string = ereg_replace("\n", "##", $string);

         $totalLines = (substr_count($string, '##') + 1);

         $string = strrev($string);

         $stringLength = strlen($string);

         while ($totalLines > $max_lines) {
             $pos = 0;
             $pos = strpos ( $string, "##") + 2;
             //$pos = $pos - $stringLength;
             $string = substr($string, $pos);
             $totalLines--;
         }
         $string = strrev($string);
          $string = ereg_replace("##", "\n", $string);
         return $string;
    }
?>
vitalic#pisem.net 15-Dec-2004 03:26
Split $string after each $pos, by $space
Example: <?php spaceStr('1836254','-',3); ?>
Would return '183-625-4';

<?php
function spaceStr($string,$space,$pos)
{
       $cpos=$pos;
       while ($cpos<strlen($string))
       {
         $string=substr($string,0,$cpos).$space.substr($string,$cpos);
         $cpos+=strlen($space)+$pos;
       };
       return $string;
}

?>
kovacsendre at no_spam_thanks_kfhik dot hungary 02-Nov-2004 07:38
Here are the replacement functions for substr() and strlen() I use when support for html entities is required:

<?php

function html_strlen($str) {
  $chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  return count($chars);
}

function html_substr($str, $start, $length = NULL) {
  if ($length === 0) return ""; //stop wasting our time ;)

  //check if we can simply use the built-in functions
  if (strpos($str, '&') === false) { //No entities. Use built-in functions
    if ($length === NULL)
      return substr($str, $start);
    else
      return substr($str, $start, $length);
  }

  // create our array of characters and html entities
  $chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE);
  $html_length = count($chars);

  // check if we can predict the return value and save some processing time
  if (
       ($html_length === 0) /* input string was empty */ or
       ($start >= $html_length) /* $start is longer than the input string */ or
       (isset($length) and ($length <= -$html_length)) /* all characters would be omitted */
     )
    return "";

  //calculate start position
  if ($start >= 0) {
    $real_start = $chars[$start][1];
  } else { //start'th character from the end of string
    $start = max($start,-$html_length);
    $real_start = $chars[$html_length+$start][1];
  }

  if (!isset($length)) // no $length argument passed, return all remaining characters
    return substr($str, $real_start);
  else if ($length > 0) { // copy $length chars
    if ($start+$length >= $html_length) { // return all remaining characters
      return substr($str, $real_start);
    } else { //return $length characters
      return substr($str, $real_start, $chars[max($start,0)+$length][1] - $real_start);
    }
  } else { //negative $length. Omit $length characters from end
      return substr($str, $real_start, $chars[$html_length+$length][1] - $real_start);
  }

}

?>

Example:

html_substr("&aacute;bla&#54;bla", 1, 4) -> "bla&#54;"

If you happen to find any bugs, please let me know.
lmak at NOSPAM dot iti dot gr 17-Aug-2004 11:59
Regarding windix's function to handle UTF-8 strings: one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8 (available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32). This way the function works for other encodings too (like Greek for example).

The modified function would read like this:

<?php
function utf8_substr($str,$start)
{
   preg_match_all("/./u", $str, $ar);

   if(func_num_args() >= 3) {
       $end = func_get_arg(2);
       return join("",array_slice($ar[0],$start,$end));
   } else {
       return join("",array_slice($ar[0],$start));
   }
}
?>
phplist at boonedocks dot net 28-Aug-2003 01:39
If 'start' is negative and greater than the length of the string, PHP seems to return the first 'length' characters of the string. For example, substr('test',-10,1) returns 't'.
05-Jul-2003 05:39
If you want to substring the middle of a string with another and keep the words intact:

<?php
/**
 * Reduce a string by the middle, keeps whole words together
 *
 * @param string $string
 * @param int $max (default 50)
 * @param string $replacement (default [...])
 * @return string
 * @author david at ethinkn dot com
 * @author loic at xhtml dot ne
 * @author arne dot hartherz at gmx dot net
 */

function strMiddleReduceWordSensitive ($string, $max = 50, $rep = '[...]') {
    $strlen = strlen($string);

    if ($strlen <= $max)
        return $string;

    $lengthtokeep = $max - strlen($rep);
    $start = 0;
    $end = 0;

    if (($lengthtokeep % 2) == 0) {
        $start = $lengthtokeep / 2;
        $end = $start;
    } else {
        $start = intval($lengthtokeep / 2);
        $end = $start + 1;
    }

    $i = $start;
    $tmp_string = $string;
    while ($i < $strlen) {
        if ($tmp_string[$i] == ' ') {
            $tmp_string = substr($tmp_string, 0, $i) . $rep;
            $return = $tmp_string;
        }
        $i++;
    }

    $i = $end;
    $tmp_string = strrev ($string);
    while ($i < $strlen) {
        if ($tmp_string[$i] == ' ') {
            $tmp_string = substr($tmp_string, 0, $i);
            $return .= strrev ($tmp_string);
        }
        $i++;
    }
    return $return;
    return substr($string, 0, $start) . $rep . substr($string, - $end);
}

echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30) . "\n";
// Returns: ABCDEEF GHIJK[...]asdf sadf sad s (33 chrs)
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30, '...') . "\n";
// Returns: ABCDEEF GHIJK...asdf sadf sad s (32 chrs)
?>
substr_replace
trim
Обработка строк


Удаляет пробелы (или другие символы) из начала и конца строки

substr
ucfirst
Обработка строк
PHP Manual

trim

(PHP 4, PHP 5)

trim — Удаляет пробелы (или другие символы) из начала и конца строки

Описание

string trim ( string $str [, string $charlist ] )

Эта функция возвращает строку str с удаленными из начала и конца строки пробелами. Если второй параметр не передан, trim() удаляет следующие символы:

  • " " (ASCII 32 (0x20)), обычный пробел.
  • "\t" (ASCII 9 (0x09)), символ табуляции.
  • "\n" (ASCII 10 (0x0A)), символ перевода строки.
  • "\r" (ASCII 13 (0x0D)), символ возврата каретки.
  • "\0" (ASCII 0 (0x00)), NUL-байт.
  • "\x0B" (ASCII 11 (0x0B)), вертикальная табуляция.

Список параметров

str

Обрезаемая строка (string).

charlist

Можно также задать список символов для удаления с помощью необязательного аргумента charlist. Просто перечислите все символы, которые вы хотите удалить. Можно указать конструкцию .. для обозначения диапазона символов.

Возвращаемые значения

Обрезаемая строка.

Список изменений

Версия | Описание
4.1.0 | Добавлен необязательный параметр charlist.

Примеры

Пример #1 Пример использования trim()

<?php

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

$trimmed = trim($hello, 'HdWr');
var_dump($trimmed);

// удаляем управляющие ASCII-символы с начала и конца $binary
// (от 0 до 31 включительно)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?>

Результат выполнения данного примера:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(9) "ello Worl"
string(14) "Example string"

Пример #2 Обрезание значений массива с помощью trim()

<?php
function trim_value(&$value)
{
    $value = trim($value);
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

Результат выполнения данного примера:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(7) "banana "
  [2]=>
  string(11) " cranberry "
}
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(9) "cranberry"
}

Примечания

Замечание: Возможные трюки: удаление символов из середины строки

Так как trim() удаляет символы с начала и конца строки string, то удаление (или неудаление) символов из середины строки может ввести в недоумение. trim('abc', 'bad') удалит как 'a', так и 'b', потому что удаление 'a' сдвинет 'b' к началу строки, что также позволит ее удалить. Вот почему это "работает", тогда как trim('abc', 'b') очевидно нет.

Смотрите также

  • ltrim() - Удаляет пробелы (или другие символы) из начала строки
  • rtrim() - Удаляет пробелы (или другие символы) из конца строки
  • str_replace() - Заменяет все вхождения строки поиска на строку замены

User Contributed Notes

albertdiones at gmail dot com 30-May-2012 09:05
When trimming &nbsp;

use this:

trim(html_entity_decode($string)," \t\n\r\0\x0B\xA0")
cwt at cwtp dot no 03-Apr-2012 10:23
I needed a quick function to check if a string was "trimmable".
Maybe some of you could need this:

function trim_check($str){
    if(strlen($str) > strlen(trim($str))) return true;
    else return false;
}
AirborneAgain 08-Mar-2012 05:50
Alternate way to trim and combine duplicate whitespace characters in a string:
<?php
      $text = "   john      q.      doe   ";
      $text = trim(implode(' ', preg_split('/\s+/', $text)));
?>
Rodrigo Cunille 23-Feb-2012 04:30
Here is a way to eliminate all the intermediate whitespaces in a string, but leaving just one whitespace in order to keep data such as names in a correct order.

example:
<?php
$text = "john      doe      doe";

//here is the function
    while(substr_count($text,"  ") != 0){
        $text = str_replace("  "," ",$text);
    }

//The result would be: john doe doe

?>
Eric de Ruiter 06-Feb-2012 02:20
If you want to trim html whitespace (&nbsp; entities and <br /> tags) you can use this function. Input should be valid utf8.

<?php

  function htmltrim($string)
  {
    $pattern = '(?:[ \t\n\r\x0B\x00\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}]|&nbsp;|<br\s*\/?>)+';
    return preg_replace('/^' . $pattern . '|' . $pattern . '$/u', '', $string);
  }

?>
Jesse Oberlin 07-Nov-2011 06:37
trim_chars
(trim string or character off beginning and end of a string)

<?php
function  trim_chars($string,$char,$whitespace_first=null){
    $string = ($whitespace_first ? trim($string) : $string);
    $trimmed = ( substr($string,-1)==$char ? substr($string,($string[0]==$char ? 1 : 0),-1) : substr($string,($string[0]==$char ? 1 : 0)) );
    return ( $trimmed == $string ? $trimmed : trim_str($trimmed,$char) );
}
?>

usage:
<?php
  echo trim_chars('&%$abc&%$', '&%$');
  echo trim_chars(' &%$abc&%$ ', '&%$', true);
  echo trim_chars(' %%%abc%%% ', '&%$', false);
  echo trim_chars('&%$abc&%$ ', '&%$', false);
?>

outputs:
  'abc'
  'abc'
  ' &%$abc&%$ '
  'abc&%$ '
Lea Hayes 10-Aug-2011 05:22
Combined filter and trim array.

<?php
function _trim_value(&$value) {
    if (is_string($value))
        $value = trim($value);
}

function array_filter_and_trim($arr) {
    array_walk($arr, '_trim_value');
    return array_filter($arr);
}
?>
gerjoo at gmail dot com 03-Jun-2011 08:38
On my application I had several users submit what to me appeared as "empty strings", whereas in fact they were submitting the &shy; character.

Trim, by default, does not strip this character (Though arguably it should). The following code strips this character from your input:

<?php

// As the &shy; character is invisible we'll simply use the ASCII numeric representation, and decode via chr():
$string = trim($string, chr(173));

// If you wish to strip all occurences this will work:
$string = str_replace(chr(173), "", $string);

?>

Gerard
akarmenia at gmail dot com 05-Apr-2011 06:49
Here's a function to trim strings recursively within an array.

<?php

// Trim a string or an array of strings recursively
function trim_r($array) {
    if (is_string($array)) {
        return trim($array);
    } else if (!is_array($array)) {
        return '';
    }
    $keys = array_keys($array);
    for ($i=0; $i<count($keys); $i++) {
        $key = $keys[$i];
        if ( is_array($array[$key]) ) {
            $array[$key] = trim_r($array[$key]);
        } else if ( is_string($array[$key]) ) {
            $array[$key] = trim($array[$key]);
        }
    }
    return $array;
}

// Test
$a = array(' cat ', ' dog ' => ' mouse ', 234);
print_r(trim_r($a));

?>

Array
(
    [0] => cat
    [ dog ] => mouse
    [1] => 234
)
gmutale at yahoo dot com 01-Oct-2010 02:11
To trim all strings and remove CR.

<?php
$arr = array('apple', 'orange');
$arr2 = array('name' => 'James', 'zipcode' => '1234', $arr);
$data = array($arr2, 'peach');

array_walk_recursive($data, 'trim_all');
print_r($data);

function trim_all(&$value)
{
  if (is_array($value))
  {
    array_walk_recursive($value, 'trim_all');
  }
  else
  {
    $value = trim(str_replace("\r\n", "\n", $value));
  }
}
?>
Knut Kohl 25-Aug-2010 05:59
Please consider the following:

<?php
$a = '0';

if (trim($a)) {
  echo 'Never ever ...';
} else {
  echo 'YES, "(bool)trim(\'0\')" is FALSE';
}
?>

So never forget to use:

if (trim($a) != '') ...

This cast costs me some time...
ludko2 at gmail dot com 09-Jul-2010 02:28
Non-breaking spaces can be troublesome with trim:

<?php
// turn some HTML with non-breaking spaces into a "normal" string
$myHTML = "&nbsp;abc";
$converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));

// this WILL NOT work as expected
// $converted will still appear as " abc" in view source
// (but not in od -x)
$converted = trim($converted);

// &nbsp; are translated to 0xA0, so use:
$converted = trim($converted, "\xA0"); // <- THIS DOES NOT WORK

// EDITED>>
// UTF encodes it as chr(0xC2).chr(0xA0)
$converted = trim($converted,chr(0xC2).chr(0xA0)); // should work

// PS: Thanks to John for saving my sanity!
?>
Onur Nizam ( onur dot nizam at yahoo dot com ) 16-May-2010 07:45
While inserting data from web forms to databases, trimming the posted values to remove the spaces from the left and right sides can be a good idea to avoid the user faults. This code have to be located before the DB operations.

<?php

/* Stripping whitespaces from left and right sides of all posted data.
 * Put this before working with posted data.
 *
*/

// Remove whitespaces from left and right sides.
function removeSpaces($str) {
  $newStr = trim($str);
  return $newStr;
}

// If any data posted to the page, send them for trimming.
if ($_POST) {
  foreach ($_POST as $var => $value) {
    $value=removeSpaces($value);
    $_POST[$var] = $value;
  }
}

?>
james [at] bandit -dot- co -dot- nz 09-Apr-2010 04:29
Trims occurances of every word in an array from the beginning and end of a string + whitespace and optionally extra single characters as per normal trim()

<?php
function trim_words($what, $words, $char_list = '') {
    if(!is_array($words)) return false;
    $char_list .= " \t\n\r\0\x0B"; // default trim chars
    $pattern = "(".implode("|", array_map('preg_quote', $words)).")\b";
    $str = trim(preg_replace('~'.$pattern.'$~i', '', preg_replace('~^'.$pattern.'~i', '', trim($what, $char_list))), $char_list);
    return $str;
}

// for example:
$trim_list = array('AND', 'OR');

$what = ' OR x = 1 AND b = 2 AND ';
print_r(trim_words($what, $trim_list)); // => "x = 1 AND b = 2"

$what = ' ORDER BY x DESC, b ASC, ';
print_r(trim_words($what, $trim_list, ',')); // => "ORDER BY x DESC, b ASC"
?>
thek at o2 dot pl 17-Feb-2010 02:36
There is a trap when making "form prefilters". Something like
$_POST = array_map('trim', $_POST)
may be not what we wanted, because when there are arrays in form made by field[] this "prefilter" return not an array but, according to his behavior, string. So as a effect we see in var_dump not array but field = "Array" what can mess up our validation.
holek dot n at gmail dot com 09-Sep-2009 03:59
Admendum to this note:
<?php
// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
?>
I had a big time with my WWW parser, which produced XML errors because of illegal characters in the outside files. So I decided to wipe them out.
If you want to remove all illegal SGML characters (ASCII coces 0 to 31 inclusive and 127 to 159 inclusive) from the whole string, (remember that trim doesn't work inside a string, just on the borders) here's how to do that:

<?php
$title = "Autobus zamiast \x1EHetmana\x1D";
$replaceArray = array(array(), array()); // this is a replace array for illegal SGML characters;
for ($i=0; $i<32; $i++)                  // produces a correct XML output
{
    $replaceArray[0][] = chr($i);
    $replaceArray[1][] = "";
}
for ($i=127; $i<160; $i++)
{
    $replaceArray[0][] = chr($i);
    $replaceArray[1][] = "";
}
$title = str_replace($replaceArray[0], $replaceArray[1], $title); // get rid of illegal SGML chars
echo $title; // prints out "Autobus zamiast Hetmana"
?>

Now $title can be printed into an XML/XHTML file without worries.
jamesp at westcoastaerospace dot com 06-Aug-2009 09:54
As another poster has pointed out, chr(160) is also important to filter out. This is the ascii representation of an html "hard space", and it will show up sometimes in your datasources, especially if the data was copied-and-pasted from a web browser from a page that used hard spaces to force layout.

This is not just a Windows problem. I am on a Mac and I have had to deal with it too (although the data in question may have indeed originally come from a windows user, I don't know.)
chrisstocktonaz at gmail dot com 22-May-2009 12:39
Note for trimming arrays that you can easily use array_map if you don't want to specify the characters.

<?php
var_dump(array_map('trim', Array(' Test ', 'Test ', ' Test')));
?>
Andrew 15-May-2009 09:01
It should be mentioned that if you use the second charlist parameter, you are overriding the defaults, not adding to them. You would need to either explicitly add them to the charlist or call trim twice, like so:

<?php

$str = trim(trim($str), './@#$');

?>
andycbio at gmail dot com 21-Apr-2009 03:37
A cell read from an Excel sheet appeared to have a whitespace, and this was not getting trimmed. By converting to hex, it seems the char was a hard return.

Successfully trimmed it by:

<?php
trim($value, "\xc2\xa0");
?>

The actual hex values may vary by character set, check with bin2hex() for what's actually there.
info at jlammertink dot nl 08-Apr-2009 01:35
I made this function to trim texts.
Removes al double horizontal and vertical whitespace chars.

<?php
function trimText($str)
{
    $str = trim($str);
    $str = preg_replace('/\h+/', ' ', $str);
    $str = preg_replace('/\v{3,}/', PHP_EOL.PHP_EOL, $str);

    return $str;
}
?>
Anonymous 21-Mar-2009 03:48
small fix for the trimString function to proof against slash and backslash:

<?php
function trimString($input, $string){
        $input = trim($input);
        $string = str_replace("\\", "\\\\", $string);
        $string = str_replace('/', '\\/', $string);
        $startPattern = "/^($string)+/i";
        $endPattern = "/($string)+$/i";
        return trim(preg_replace($endPattern, '', preg_replace($startPattern,'',$input)));
}
?>
dev dot ivangc at gmail dot com 26-Feb-2009 06:23
If what you need is delete a string instead of character, this function could help you:

<?php
function trimString($input, $string){
        $input = trim($input);
        $startPattern = "/^($string)+/i";
        $endPattern = "/($string)+$/i";
        return trim(preg_replace($endPattern, '', preg_replace($startPattern,'',$input)));
}
?>

Use:
<?php
echo trimString("      Hello world!. I said hello", "hello")
?>
Will return:
world!. I said
dead dot screamer at seznam dot cz 27-Jan-2009 03:29
some of "trim array" functions
this trim strings, arrays and objects:
<?php
function trimA($str, $set=null)
{
    if(is_Array($str) || is_Object($str))
        foreach($str as &$s)
            $s=trimA($s,$set);
    elseif($set===null)$str=trim($str);
    else $str=trim($str,$set);
    return $str;
}
?>
josecruz at josecruz dot com dot br 21-Nov-2008 05:50
A simple function to clear extra white spaces along a string.
<?php
function TrimStr($str)
{
    $str = trim($str);
    for($i=0;$i < strlen($str);$i++)
    {

        if(substr($str, $i, 1) != " ")
        {

            $ret_str .= trim(substr($str, $i, 1));

        }
        else
        {
            while(substr($str,$i,1) == " ")

            {
                $i++;
            }
            $ret_str.= " ";
            $i--; // ***
        }
    }
    return $ret_str;
}
?>

[EDIT BY danbrown AT php DOT net: Contains a fix provided by (info AT deep-soft DOT com) to address the issue where "it deletes the first char after spaces (because of while)."]
colnector at colnect dot com 26-Aug-2008 06:21
The following function will assist you in case you wish to trim a string but keep the parts trimmed. I'm using it to strip phrases for translation on my site.

Example:
cleanPhrase('  (this () is it)');

Will return:
Array
(
    [left] =>   (
    [right] => )
    [clean] => this () is it
)

<?php
    /**
     * Trims some of the characters from the phrase
     *
     * @param string $phrase - to be "cleaned"
     * @param string $dirtyChars - the characters that need be removed
     * @return string
     */
    public static function cleanPhrase($phrase, $dirtyChars = " \t\n()[]:.\"'") {
        $len = strlen($phrase);
        for($i=0; $i < $len; $i++) {
            $pos = strpos($dirtyChars, substr($phrase, $i, 1));
            if ($pos === false) break;
        }
        for($j=$len-1; $j >= 0; $j--) {
            $pos = strpos($dirtyChars, substr($phrase, $j, 1));
            if ($pos === false) break;
        }

        $res = array();
        $res['left'] = substr($phrase, 0, $i);
        $res['right'] = substr($phrase, $j+1);
        $res['clean'] = substr($phrase, $i, $j-$i+1);

        return $res;
    }
?>
aalaap at gmail dot com 17-Jun-2008 11:42
If you want to remove all excessive spaces and leave just a single one, like the way HTML text gets rendered in the browser, this function (modified from one posted here earlier) will work:

function str_squeeze($test) {
    return trim(ereg_replace( ' +', ' ', $test));
}

The result is that a string such as "hello___how_are__you_" (where the _ is a space) will result in a more sane "hello_how_are_you".
luciano[dot]longo[at]gmail 25-Apr-2008 10:17
Yet another array trim, recursive too.
I think this one is pretty usefull, though it lacks charlist, you can add that functionality if you need to, it's not that hard ;)
Anyway, one feature that I added, and I find pretty usefull, is that it can splice an empty position if you want to

<?php
function array_trim_recursive(&$array, $splice_empty = true) {
    foreach($array as $k => &$v) {
        if(is_array($v)) {
            array_trim_recursive($v, $splice_empty);
        } else {
            $array[$k] = trim($v);
            iif(!$v && $splice_empty) {
                array_splice($array, $k, 1);
            }
        }
    }
}
?>
davidsteinsland [at] gmail [dot] com 25-Apr-2008 10:19
I've noticed that many needs to remove multiple lines in the end of a string, so I made this function. Pretty easy, actually. It removes all unnecessary newlines (or something else, if $char is set)

<?php
function remove_unnecessary ($str, $char = "\n") {
    while (true) {
        if (substr ($str, -(strlen($char))) == $char) {
            $str = substr ($str, 0, -(strlen($char)));
        } else {
            break;
        }
    }

    return $str;
}

$Str = "Hello\nHello\n\n\n\n\n\n\n\n\n";

// Outputs: Hello\nHello
echo remove_unnecessary ($Str);
?>
me at robhaswell dot co dot uk 16-Apr-2008 04:50
admin at semaster dot ru's array_trim function is flawed in that it will change the type of nulls and numeric variables (to strings).

Here is a better version, although it lacks charlist support:

<?php
function array_trim($var) {
    if (is_array($var))
        return array_map("array_trim", $var);
    if (is_string($var))
        return trim($var);
    return $var;
}
?>

-Rob
carl at rusco dot com 24-Dec-2007 09:53
as mentioned, a str_replace(' ', '', $string) does execute faster than Robin Leffmann's ereg_replace; however, the regular expression Leffmann supplied has the ability of also stripping out only -single- whitespaces as by his comment, whereas the blunt str_replace will simply sweep all of them away, single as cascading. one tool for each job.
Pinco Pallino 01-Sep-2007 12:08
As already commented by thers the solution from Robin Leffmann to remove "all"
the spaces from a string not only does not trim the "other" chars besides plain
spaces but is at all not faster than jayoungh5's proposal.

The only faster way I can imagine of is:

function trimall($str, $charlist = " \t\n\r\0\x0B")
{
  return str_replace(str_split($charlist), '', $str);
}

However jayoungh5's one might still be faster for very large sets of characters
to be stripped.
hkb at hkb dot it 24-Aug-2007 03:03
I have made this simple function to trim the whole string instead of just the beginning and end...

<?php

function strTrimTotal($input) {

    $input = trim($input);

    for($i=0;$i<strlen($input);$i++) {

        if(substr($input, $i, 1) != " ") {

            $output .= trim(substr($input, $i, 1));

        } else {

            $output .= " ";

        }

    }

    return $output;
}

?>
lxg 16-Aug-2007 05:26
masteremployment's solution in a function, and with preg_replace() instead of ereg_replace():

<?php
function removeWhitespace($string)
{
    if (!is_string($string))
        return false;

    $string = preg_quote($string, '|');
    return preg_replace('|  +|', ' ', $string);
}
?>
Hayley Watson 09-Aug-2007 10:49
Robin Leffman's code could be improved further...
<?php
$string = 'This string  has   no    whitespaces.';
echo str_replace(' ', '', $string );
?>

Of course, like Leffman's code, that only removes space characters, not necessarily all whitespace (or characters in some arbitrary $whiteSpace string). For that
<?php
function trimlrm ($hayStack, $whiteSpaceChars)
{
    $char = $whiteSpaceChars[0];
    $chars = str_repeat($char, strlen($whiteSpaceChars);
    $trimmed = strtr($hayStack, $whiteSpaceChars, $chars)));
    return str_replace($char, '', $trimmed);
}
?>
would probably work, but like the others, fails to give '..' the same specialness that it has in trim().
moehbass at gmail dot com 06-Jul-2007 12:48
Responding to Robin Leffmann:
jayoungh5 wrote a function to trim whitespace on the left, on the right, in the middle, everywhere (Below). It iterates through the string's characters. Yours, claimed to be faster, uses a regex function. I think it should be slower since I believe that dealing with a regex is iterative in nature and add to that the possibility of recursion! Perhaps your function is shorter in code lines.
I am not absolutely positive, so take this as a clue but research for a more solid truth.
Robin Leffmann 26-Jun-2007 05:13
Here's a faster way to do what's described below:

<?php
$string = 'This string  has   no    whitespaces.';
echo ereg_replace( ' +', '', $string );
?>

Output: Thisstringhasnowhitespaces.

If you want it to replace only single whitespaces instead of both single and cascading dito, remove the + in the first parameter of ereg_replace().
Hayley 19-Mar-2007 02:36
trim's code can of course be simplified with some use of the trim() function....

<?php
$str = "  Words with  lots      of  spaces    ";
$str = preg_replace('/\s\s+/', ' ', trim($str));
?>

Doing the trim() first reduces the workload being put on the more expensive preg_replace().
24-Jan-2007 08:04
I use this to remove leading, trailing and "more than one" space in between words.

$pat[0] = "/^\s+/";
$pat[1] = "/\s{2,}/";
$pat[2] = "/\s+\$/";
$rep[0] = "";
$rep[1] = " ";
$rep[2] = "";
$str = "  Words with   lots      of  spaces     ";
$str = preg_replace($pat,$rep,$str);
// Output
"Words with lots of spaces"
Piopier 12-Jan-2007 06:06
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
asbo/at\iserv/dot\net 19-Nov-2006 12:40
If you need to trim a string from the beginning and end of a string, then this function maybe prove handy.

<?php
function lrclean($str,$rm) {
  $i = strlen($rm);
  do {
    if (substr($str,0,$i) == $rm) {$str = substr($str,$i);}
  } while (substr($str,0,$i) == $rm);

  do {
    if (substr($str,-$i,$i) == $rm) {$str = substr($str,0,-$i);}
  } while (substr($str,-$i,$i) == $rm);

  return $str;
}

// prints 'text'
echo lrclean('xyztextxyz','xyz');
?>
phazei at excite dot com 10-Jul-2006 04:39
I had some issues using <? array_map('trim',$array) ?> when there was an array in array.  All arrays were replaced by the string "Array", drove me crazy.
Hopefully this will help someone:
<?php
function trim_array($totrim) {
    if (is_array($totrim)) {
        $totrim = array_map("trim_array", $totrim);
    } else {
        $totrim = trim($totrim);
    }
    return $totrim;
}
?>
USE:
<?php
$trimmed_array = trim_array($untrimmed_array);
?>

This function should recurse all embeded arrays.
rchaube at staff dot atlantic dot net 18-Feb-2006 01:03
I was accepting text pasted from a csv file into a textarea in my code. I found that even using trim was not able to get rid of the whitespace characters at the end of the string.
Finally, using this helped:

$result = trim($source,"\x7f..\xff\x0..\x1f");

Hope this saves someone few hours. All thanks to previous comment from HW for this
asharm4 at ilstu dot edu 17-Jan-2006 09:30
This staetment removes the trailing and leading whitespaces from the string..Really useful when handling the form values submitted by a visitor or analyzing a log file.

$trimmed_string = preg_replace ( "/\s\s+/" , " " , $untrimmed_string );

Note : thsi would only remove leading and trailing whitespaces. For the whitespaces in the string use any of the above methods.
Martin Kealey 14-Dec-2005 02:10
Using "trim" to minimize the format of a decimal number strikes me as awkward. I would just use:

   $str += 0;

This even has the added benefit of ensuring that you have at least one digit (and thus have a valid number) even if the original was empty.
warhog at warhog dot net 07-Dec-2005 12:28
I was wondering about much of the examples given below, but the current (2005-12-07) function definition in the manual is not correct.

The function trim is defined as

trim(string string [, string charlist])

you must give the string-parameter and you can optionally add a parameter charlist - these chars are the chars to strip from the beginning and the end of the file.
(its self-evident that the default of this parameter is "\n\t\r\h\v\0 ")

hope that'll help - and that the docs are updated.. i don't know since which php-version that optional parameter can be used - i know that it works with PHP >= 4.3 & >= 5.0 . Maybe it's beeing there since 10 years and just an enormous insider :-)
davis_utah at yahoo dot com 01-Sep-2005 11:30
Just a word of caution when looping through a batch of strings (in the thousands or more). Using trim to take off a left over character (like a comma in a csv output) will result in a much slower execution. It is better to use a tiny bit of conditional logic instead.

I believe the reason this is the case is because of having to create a new spot in memory to temporarily handle the result of trim.

Hope this helps.
rifter at cox dot net 16-Jul-2005 12:49
Chris wrote:
> Here's a neat function to trim off extraneous zeros and  the > decimal, leaving important numbers intact:
> ...

  Actually use:
<?php
...
  return rtrim(trim($num, '0'), '.');
...
?>
This ensures that a left leading decimal place doesn't get removed i.e. 00.010 should return .01 and not 01.
chris dot cowart at gmail dot com 05-Jul-2005 10:20
Here's a neat function to trim off extraneous zeros and  the decimal, leaving important numbers intact:

<?php

function clean_num($num){
  return trim(trim($num, '0'), '.');
}

echo clean_num('06000.3050');
echo clean_num('500.00');

?>

Output:
6000.305
500

I find it very handy to use when pulling data from decimal fields in MySQL and putting them into <input> fields. Makes everything cleaner :)
14-Jun-2005 09:54
here's a heads up folks.

in the event that you want to check the result of a trim for being empty the following code fails::

$emptyvar = " ";
if ( empty(trim($emptyvar)) )
{
    echo "It was empty";
}

this code works as expected::

$emptyvar = " ";
$check = trim($emptyvar);
if ( empty($check) )
{
    echo "It was empty";
}
okumurya at hotmail dot com 05-Jun-2005 04:01
fread/fwrite blocks program when no data available.
so, you consider use select system call.
following is example.

<?php
  /**
   *
   * write/read pipe
   *
   * @param resource $w_fp write file handle
   * @param resource $r_fp read file handle
   * @param string $input
   * @return string
   */
  function _writeread_pipe(&$w_fp, &$r_fp, $input) {
    $output = '';
    $write_bytes = 0;

    //
    while (True) {
      if (!isset($r_fp) && !isset($w_fp)) break;

      $read = isset($r_fp) ? array($r_fp) : Null;
      $write = isset($w_fp) ? array($w_fp) : Null;

      // select pipes
      $r = stream_select($read,
                         $write,
                         $except = Null,
                         30
                         );
      if ($r === False) {
        return PEAR::raiseError('process timeout');
      }

      // read pipe
      if (isset($read) && isset($read[0])) {
        do {
          $buf = fread($r_fp, 1024);
          if (strlen($buf) == 0) {
            fclose($r_fp);
            $r_fp = Null;
            break;
          }
          $output .= $buf;
        } while (True);
      }

      // write pipe
      if (isset($write) && isset($write[0])) {
        $r = fwrite($w_fp, substr($input, $write_bytes));
        if ($r === False) {
          return PEAR::raiseError('process write error');
        }

        $write_bytes += $r;
        if ($write_bytes == strlen($input)) {
          fclose($w_fp);
          $w_fp = Null;
        }
      }
    }

    return $output;
  }

?>
dmr37 at cornell dot edu 17-May-2005 12:47
Note that manithu's post on 29-Mar-2005 02:49 for identifying strings that only contain whitespaces will also identify strings like "0" and " 0   " as being empty.  If you want to check whether something ONLY has whitespaces, use the following:

<?php

if (trim($foobar)=='') {
   echo 'The string $foobar only contains whitespace!';
}

?>
admin at semaster dot ru 30-Mar-2005 07:37
Another recursive trim function for multi-dimensional arrays ( uses only trim function :)

function array_trim($arr, $charlist=null){
    foreach($arr as $key => $value){
        if (is_array($value)) $result[$key] = array_trim($value, $charlist);
        else $result[$key] = trim($value, $charlist);
    }
    return $result;
}
manithu 29-Mar-2005 11:49
An faster (and eleganter) way than using regular expressions to check if a string only contains whitespaces is to use trim().

Example:

<?php

if (!trim($foobar)) {
    echo 'The string $foobar is empty!';
}

?>

I hope this helps somebody.
04-Mar-2005 10:25
It is important to stress that trim() only removes whitespace characters from the *beginning* and *end* of str.  To remove whitespace characters embedded within a string (newlines, for instance) you can use str_replace(), searching for and destroying both \n and \r characters.
Hayley Watson 07-Feb-2005 04:46
Another way to trim all the elements of an array
<?php
$newarray = array_map('trim', $array);
?>
abderzack host provider hotmail dot com 12-Nov-2004 07:44
To eliminate all the empty strings from my array, I used the array_filter, that way :

1.
I defined a function returning true iff the passed as parameter string is NOT empty.
function notEmpty($string)
{
return !empty($string);
}

2.Use array filter :
$myarray = array_filter($myarray ,"notEmpty");

That's it.
Of course, if you want to prove your mama you can write unreadable code, you can create an anonymous function, by using the create_function, instead of declaring the function notEmpty.

Hope that will help you.
webmaster __AT__ digitalanime __DOT__ nl 26-May-2004 02:50
To:
mrizzo at advancedsl dot com dot ar

And what about array_map()? :)

<?php
$myarray = array(
    'hello' => '    bye    ',
    'hey' => '      howdie',
    'haai' => '      today'
);

array_map('trim', $myarray);
?>

:)
jubi at irc dot pl 20-Apr-2004 06:48
To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

<?

$text = preg_replace('/\s+/', ' ', $text);

?>

------------
JUBI
http://www.jubi.buum.pl
mrizzo at advancedsl dot com dot ar 16-Jul-2003 02:00
About trim all elements in an array.

array_filter($db, 'trim') doesn't work becouse it does NOT modify array's elements, it only returns a copy from those elements which return true on the callback function.

I think that:
foreach ($db as $key=>$value) { $db[$key]=trim($value); }
still being the best option.
rwelti at yahoo dot com 02-Jul-2003 05:45
Regarding the editor's note to rhelic above about how to trim all elements in an array:

I wanted a perl "chomp" of newlines for all elements in an array.
I tried array_filter for a long time, but  rhelic's straightforward way is what worked.

// chomp newlines off all elements in stations array
$stations = array_filter($stations, 'trim');   // editor's way - nope
foreach ($stations as $key => $value) {
            $stations[$key] = trim($value); }  // works fine

using PHP 4.3.1 on Solaris
HW 05-Jun-2003 06:32
You can combine character ranges and individual characters in trim()'s second argument (ditto for ltrim and rtrim). All of the specified characters and ranges will be used concurrently (i.e., if a character on either end of the string matches any of the specified charaters or character ranges, it will be trimmed). The characters and character ranges can be in any order (except of course that the character ranges need to be specified in increasing order) and may overlap.
E.g., trim any nongraphical non-ASCII character:
trim($text,"\x7f..\xff\x0..\x1f");
olivierdsm at hotmail dot com 02-Jun-2003 10:42
I just wanted to say that when you want to do a LDAP query based on a form value (i mean something like : <form method="POST" action="script_createnewticket.php" name="demande2">) dynamicaly updated from a popup javascript , (for example <a onclick=" opener.document.forms['demande2'].elements['thename3'].value='my name') it doesn't work.

It took me 2 days to find out that when you use trim, to "convert" the value, then it works.

-------------------------
$thename4=trim($thename3);

$ds=ldap_connect("$myldapserver");  // connects to the LDAP SERVER
if (!($ds = ldap_connect("$myldapserver") ) ) {
die ("Could not connect to LDAP server");
}
    $r=ldap_bind($ds, "cn=".$NTusername, $NTpassword);
    $sr = ldap_search($ds, '  ', "uid=".$thename4);
    $info = ldap_get_entries($ds, $sr);
-------------------------------------

only on this case you will get results.
Strange and good to know
bishop 25-Apr-2003 03:56
[Editor: I botched my last note; please delete and use this one]

Non-breaking spaces can be troublesome with trim (as per an earlier comment):

// turn some HTML with non-breaking spaces into a "normal" string
$myHTML = "&nbsp;abc";
$converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));

// this WILL NOT work as expected
// $converted will still appear as " abc" in view source
// (but not in od -x)
$converted = trim($converted);

// &nbsp; are translated to 0xA0, so use:
$converted = trim($converted, "\xA0");

// PS: Thanks to John for saving my sanity!
Joshua dot Logsdon at ohiou dot edu 30-Jan-2003 03:51
In response to the line mentioned above...
$clean = trim($binary,"\0x00..\0x1F");

I was also able to get
$clean = trim($binary,"\0x00-\0x1F");

to function.
daggillies at yahoo dot com 03-Jun-2002 11:57
NOTE:

All the above examples using ereg_replace with an escape code of \v are BROKEN! \v is NOT an escape code in PHP. Using a regexp of \v e.g.
$str=ereg_replace("[\r\t\n\v]","",$str);

will remove any instances of the letter 'v' from your string. So 'Activity' becomes 'Actiity'. Probably not what you want.

Here is a small function I use to strip whitespace from the end of strings and squash repeated whitespace down to a single space in the middle of strings:

function wsstrip(&$str)
{
$str=ereg_replace (' +', ' ', trim($str));
$str=ereg_replace("[\r\t\n]","",$str);
}

David Gillies
San Jose
Costa Rica
j dot metzger at steptown dot com 26-May-2002 10:21
Be careful when you use the charlist with the hex-codes...

use e.g. \x22 instead of \0x22 (this last thing won't work).

An example to strip quotes ' " ' (double quotes) and " ' " (single quotes) is to do this:

$example[0]='"hello"';
$example[1]="'baby'"

foreach ($example as $key => $val)
  $example[$key]=trim($val,"\x22\x27");

# this works brilliant, but be aware:
# $example[$key]=trim($val,"\0x22\0x27");
# won't work !!!

-> tested on php 4.2.1
REMOVETHISNOSPAMkilling at bluecarrots dot com 19-Mar-2002 09:30
If you want to totally stop windows (dunno about other os's) peeps from adding spaces (say, you need to check there name against a special one to stop impersonations) use this:

$nick = ereg_replace("[\r\n\t\v\ �]", "", trim($nick));

It has the alt code 0160 added to it
tbm.at.home.dot.nl 14-Mar-2002 11:30
Windows uses two characters for definining newlines, namely ASCII 13 (carriage return, "\r") and ASCII 10 (line feed, "\n") aka CRLF. So if you have a string with CRLF's, trim() won't recognize them as being one newline. To solve this you can use str_replace() to replace the CRLF's with with a space or something.

<?php
// string with bunch of CRLF's
$my_string = "Liquid\r\nTension Experiment\r\n\r\n\r\n";

// replace CRLF's with spaces
$my_wonderful_string = str_replace("\r\n", " ", $my_string);
// would result in "Liquid Tension Experiment   "

// or just delete the CRLF's (by replacing them with nothing)
$my_wonderful_string = str_replace("\r\n", "", $my_string);
// would result in "LiquidTension Experiment"
?>
substr
ucfirst
Обработка строк


РџСЂРµРѕР±СЂР°Р·СѓРµС‚ РїРµСЂРІС‹Р№ СЃРёРјРІРѕР» СЃС‚СЂРѕРєРё РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ

trim
ucwords
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє
PHP Manual

ucfirst

(PHP 4, PHP 5)

ucfirst — РџСЂРµРѕР±СЂР°Р·СѓРµС‚ РїРµСЂРІС‹Р№ СЃРёРјРІРѕР» СЃС‚СЂРѕРєРё РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ

РћРїРёСЃР°РЅРёРµ

string ucfirst ( string $str )

Р’РѕР·РІСЂР°С‰Р°РµС‚ СЃС‚СЂРѕРєСѓ str, РІ РєРѕС‚РѕСЂРѕР№ РїРµСЂРІС‹Р№ СЃРёРјРІРѕР» РїРµСЂРµРІРµРґРµРЅ РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ, РµСЃР»Рё СЌС‚РѕС‚ СЃРёРјРІРѕР» СЏРІР»СЏРµС‚СЃСЏ Р±СѓРєРІРѕР№.

РџСЂРёРЅР°РґР»РµР¶РЅРѕСЃС‚СЊ С‚РѕРіРѕ РёР»Рё РёРЅРѕРіРѕ СЃРёРјРІРѕР»Р° Рє Р±СѓРєРІРµРЅРЅС‹Рј РѕРїСЂРµРґРµР»СЏРµС‚СЃСЏ СЃ СѓС‡РµС‚РѕРј С‚РµРєСѓС‰РµР№ Р»РѕРєР°Р»Рё. РС‚Рѕ РѕР·РЅР°С‡Р°РµС‚, С‡С‚Рѕ, РЅР°РїСЂРёРјРµСЂ, РІ РёСЃРїРѕР»СЊР·СѓРµРјРѕР№ РїРѕ СѓРјРѕР»С‡Р°РЅРёСЋ Р»РѕРєР°Р»Рё "C", СЃРёРјРІРѕР» Г¤ РЅРµ Р±СѓРґРµС‚ РїСЂРµРѕР±СЂР°Р·РѕРІР°РЅ.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

str

Р’С…РѕРґРЅР°СЏ СЃС‚СЂРѕРєР°.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ СЂРµР·СѓР»СЊС‚РёСЂСѓСЋС‰СѓСЋ СЃС‚СЂРѕРєСѓ.

РџСЂРёРјРµСЂС‹

РџСЂРёРјРµСЂ #1 РџСЂРёРјРµСЂ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёСЏ ucfirst()

<?php
$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • lcfirst() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ РїРµСЂРІС‹Р№ СЃРёРјРІРѕР» СЃС‚СЂРѕРєРё РІ РЅРёР¶РЅРёР№ СЂРµРіРёСЃС‚СЂ
  • strtolower() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РІ РЅРёР¶РЅРёР№ СЂРµРіРёСЃС‚СЂ
  • strtoupper() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ
  • ucwords() - РџСЂРµРѕР±СЂР°Р·СѓРµС‚ РІ РІРµСЂС…РЅРёР№ СЂРµРіРёСЃС‚СЂ РїРµСЂРІС‹Р№ СЃРёРјРІРѕР» РєР°Р¶РґРѕРіРѕ СЃР»РѕРІР° РІ СЃС‚СЂРѕРєРµ

User Contributed Notes

Martynas 30-May-2012 06:15
This function is multilanguage. It converts only the first character of the string to uppercase (UTF-8). Other chars in string will be unchanged.
Usage: my_ucfirst("ЕЎlepetД—s ABC 123 abc");
// Returns Е lepetД—s ABC 123 abc

<?php
function substr_unicode($str, $s, $l = null) {
    return join("", array_slice(
        preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
}

function my_ucfirst($string, $e ='utf-8') {
        $orig_string = $string;
        if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
            $string = mb_strtolower($string, $e);
            $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
        } else {
            $string = ucfirst($string);
        }

        $string1 = substr_unicode($string, 0, 1);
        $string2 = substr_unicode($orig_string, 1);
        $string = $string1 . $string2;

        return $string;
    }
?>
idont at remember dot it 18-May-2012 11:21
In case you need a French version of ucfirst:

"Г©tГ© indien" => "EtГ© indien"
"Г§a va?" => "Г‡a va?"

<?php
function frenchUcfirst($v) {
  $lowCase  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
  $lowCase .= "\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFF\\u0161";
  $upperCase = "AAAAAA\\xC7EEEEIIIINOOOOOOUUUUYYS";
  return strtoupper(strtr(substr($v, 0, 1), $lowCase, $upperCase)) . substr($v, 1);
}
?>

Note:
- Latin non french accented characters follow the same rule:
"Г¤ndГҐ" => "AndГҐ"
- Non ASCII characters in the function are in HEX format to avoid encoding issue...
drpain at webster dot org dot za 12-Mar-2012 07:48
<?php

// Custom function returns a string with the first word in a bigger fontsize, with a default of 22px.

function ucsentance($string, $fontSize=22) {

  // Do some basic processing on the data and find the first space before returning the modified string.
  $trimmed = trim($string);
  $getSpace = strpos($trimmed,' ');
  $firstWord = substr($trimmed, 0, $getSpace);
  $firstWord = ucfirst($firstWord);
  $afterFirstWord = substr($trimmed, $getSpace);
  $output = "<b style='font-size: " . $fontSize . "px;'>" . $firstWord . "</b>" . $afterFirstWord;
  return $output;
}

// Example of it's use
$string = "Hello World, I am a bouncy castle!";
echo ucsentance($string);
?>

This will yield <b style="font-size: 22px;">Hello</b> World, I am a bouncy castle!
qeremy [atta] gmail [dotta] com 27-Feb-2012 04:41
A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
    $tmp = preg_split("//u", $str, 2, PREG_SPLIT_NO_EMPTY);
    return mb_convert_case(
        str_replace("i", "Д°", $tmp[0]), MB_CASE_TITLE, "UTF-8").
        $tmp[1];
}

$str = "iyilik gГјzelLД°K";
echo ucfirst($str) ."\n";   // Iyilik gГјzelLД°K
echo ucfirst_turkish($str); // Д°yilik gГјzelLД°K
?>
vlknmtn at gmail dot com 17-Aug-2011 04:31
Turkish solution:

<?php
mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

function tr_ilkbuyuk($text)
{
    $text = str_replace("I","Д±",$text);
    $text = mb_strtolower($text, 'UTF-8');

    if($text[0] == "i")
        $tr_text = "Д°".substr($text, 1);
    else
        $tr_text = mb_convert_case($text, MB_CASE_TITLE, "UTF-8");

    return trim($tr_text);
}

function tr_ucwords($text)
{
    $p = explode(" ",$text);
    if(is_array($p))
    {
        $tr_text = "";
        foreach($p AS $item)
            $tr_text .= " ".tr_ilkbuyuk($item);

        return trim($tr_text);
    }
    else
        return tr_ilkbuyuk($text);
}

$deger = "Д±iЕџllЕџlsdg";

echo tr_ucwords($deger);

?>
Quicker 10-May-2011 01:53
if you want to ucfirst for utf8 try this one:

<?php
function ucfirst_utf8($stri){
 if($stri{0}>="\xc3")
     return (($stri{1}>="\xa0")?
     ($stri{0}.chr(ord($stri{1})-32)):
     ($stri{0}.$stri{1})).substr($stri,2);
 else return ucfirst($stri);
}
?>

It is quick, not language (but utf8) dependend and does not use any mb-functions such as mb_ucfirst.
chris at bjelleklang dot org 26-Jan-2011 03:03
For those who want a multibyte-compliant ucfirst() without wanting to mess with encodings, this should do the trick:

<?php
function mb_ucasefirst($str){
    $str[0] = mb_strtoupper($str[0]);
    return $str;
}
?>
pete at namecube dot net 11-Apr-2010 07:08
for anyone wanting to ucfirst each word in a sentence this works for me:

<?php
function ucfirst_sentence($str)
{
    return preg_replace('/\b(\w)/e', 'strtoupper("$1")', $str);
}
?>
wilfried dot loche at fr dot adp dot com 22-Jan-2010 02:22
If someone looks for the equivalent on Oracle DB, here it is: INITCAP. Hope this helps!
octavius 26-Sep-2009 05:18
For lithuanian text with utf-8 encoding I use two functions (thanks [mattalexxpub at gmail dot com] and Svetoslav Marinov)

<?php
function my_ucfirst($string, $e ='utf-8') {
    if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
        $string = mb_strtolower($string, $e);
        $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
    }
    else {
        $string = ucfirst($string);
    }
    return $string;
}

function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            my_ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}
?>
bgschool 30-Jul-2009 04:39
Simple function for use ucfirst with utf-8 encoded cyrylic text

<?php
    public function capitalize_first($str) {
        $line = iconv("UTF-8", "Windows-1251", $str); // convert to windows-1251
        $line = ucfirst($line);
        $line = iconv("Windows-1251", "UTF-8", $line); // convert back to utf-8

        return $line;
    }
?>
svetoslavm at gmail dot com 20-Nov-2008 07:40
For some reason this worked for me.

Mac OS 10.5.1
PHP 5.2.6

<?php
   /**
     * ucfirst UTF-8 aware function
     *
     * @param string $string
     * @return string
     * @see http://ca.php.net/ucfirst
     */
    function my_ucfirst($string, $e ='utf-8') {
        if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
            $string = mb_strtolower($string, $e);
            $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
        } else {
            $string = ucfirst($string);
        }
        return $string;
    }
?>

Svetoslav Marinov
http://slavi.biz
mattalexxpub at gmail dot com 09-Nov-2008 05:10
This is what I use for converting strings to sentence case:

<?php
function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}

print sentence_case('HMM. WOW! WHAT?');

// Outputs: "Hmm. Wow! What?"
?>
prokur.net - there is my email 29-Jun-2008 03:01
I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful
<?php

if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) {
    function mb_ucfirst($string) {
        $string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
        return $string;
    }
}

?>

it also check is mb support enabled or not
NoName 12-Mar-2008 12:23
For strings with diactrical marks (umlauts, etc.), consider mb_convert_case().
charliefortune 20-Feb-2008 03:48
Here's a function to capitalize segments of a name, and put the rest into lower case. You can pass the characters you want to use as delimiters.

i.e. <?php echo nameize("john o'grady-smith"); ?>

returns John O'Grady-Smith

<?php

function nameize($str,$a_char = array("'","-"," ")){
    //$str contains the complete raw name string
    //$a_char is an array containing the characters we use as separators for capitalization. If you don't pass anything, there are three in there as default.
    $string = strtolower($str);
    foreach ($a_char as $temp){
        $pos = strpos($string,$temp);
        if ($pos){
            //we are in the loop because we found one of the special characters in the array, so lets split it up into chunks and capitalize each one.
            $mend = '';
            $a_split = explode($temp,$string);
            foreach ($a_split as $temp2){
                //capitalize each portion of the string which was separated at a special character
                $mend .= ucfirst($temp2).$temp;
                }
            $string = substr($mend,0,-1);
            }
        }
    return ucfirst($string);
    }

?>
webmaster at onmyway dot cz 11-Feb-2008 03:31
Inspired by the lcfirst function a simple mb_lcfirst to cope with multibyte strings:

<?php
function mb_lcfirst($str, $enc = null)
{
  if($enc === null) $enc = mb_internal_encoding();
  return mb_strtolower(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
?>
Uwe 26-Jul-2007 08:08
@adefoor, Ken and Zee

Changing the case can only be done by understanding the text. Take for example "USA", "Sunday", "March", "I am ...", abbreviations like "prob." and so on.
adefoor at gmail dot com 12-Jul-2007 11:57
Ken and zee

One thing I would do to make this more unviersally work would be to add strtolower() around your $sentence.  Doing this will allow you to convert an all caps text block as well as an all lowercase text block.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst(strtolower($sentence));
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
Ken Kehler 14-Mar-2007 12:03
@ zee: this should solve your !, ?, and any punctuations you want to add. It can probably be cleaned up a bit.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst($sentence);
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
zee 30-Jan-2007 04:09
Another way to capitalize first letter of every sentence in a text, I hope it will help someone. It won't convert non-English characters, though, and ignores sentences ending with ! or ? etc.

<?php

$text="this is a sentence. this is another sentence.";

$split=explode(". ", $text);
foreach ($split as $sentence) {
$sentencegood=ucfirst($sentence);
$text=str_replace($sentence, $sentencegood, $text);
}

echo $text; // This is a sentence. This is another sentence.

?>
Carel at divers information with dotcom 06-Jan-2007 02:55
I made a small change. Now it takes care of points in numbers

function ucsentence ($string){
   $string = explode ('.', $string);
   $count = count ($string);
   for ($i = 0; $i < $count; $i++){
       $string[$i]  = ucfirst (trim ($string[$i]));
       if ($i > 0){
           if ((ord($string[$i]{0})<48) || (ord($string[$i]{0})>57)) {
              $string[$i] = ' ' . $string[$i];
           }
       }
   }
   $string = implode ('.', $string);
   return $string;
}
26-Oct-2006 07:45
Some simple function for cyrillic and latin letters both:

function rucfirst($str) {
    if(ord(substr($str,0,1))<192) return ucfirst($str);
    else
    return chr(ord(substr($str,0,1))-32).substr($str,1);
}
Michael 12-Sep-2006 06:01
This is what you would expect php to deliver if there was a built-in function named ucsentence.

function ucsentence ($string){
    $string = explode ('.', $string);
    $count = count ($string);
    for ($i = 0; $i < $count; $i++){
        $string[$i]  = ucfirst (trim ($string[$i]));
        if ($i > 0){
            $string[$i] = '&nbsp;&nbsp;' . $string[$i];
        }
    }
    $string = implode ('.', $string);
    return $string;
}
Northie 05-Sep-2006 04:39
Sentence Case:

<?php

function SentenceCase($str) {
    $sentences = explode(". ",$str);
    for($i=0;$i<count($sentences);$i++) {
        $sentences[$i][0] = strtoupper($sentences[$i][0]);
    }

    return implode(". ",$sentences);
}

?>
27-Jul-2006 02:31
lcfirst - In case you need to get the original string back after a ucfirst.

    function lcfirst( $str ) {
        $str[0] = strtolower($str[0]);
        return $str;
    }
Markus Ernst 31-Mar-2006 12:34
A combination of the below functions to enable ucfirst for multibyte strings in a shared hosting environment (where you can not always count on mbstring to be installed):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    if (function_exists('mb_strtoupper')) {
        $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
        return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
    }
    else {
        $str = utf8_decode($str);
        $str[0] = strtr($str[0],
            "abcdefghГЅijklmnopqrstuvwxyz".
            "\x9C\x9A\xE0\xE1\xE2\xE3".
            "\xE4\xE5\xE6\xE7\xE8\xE9".
            "\xEA\xEB\xEC\xED\xEE\xEF".
            "\xF0\xF1\xF2\xF3\xF4\xF5".
            "\xF6\xF8\xF9\xFA\xFB\xFC".
            "\xFE\xFF",
            "ABCDEFGHГќIJKLMNOPQRSTUVWXYZ".
            "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
            "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
            "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
            "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
            "\xDB\xDC\xDE\x9F");
        return utf8_encode($str);
    }
}
?>
Bartuc 26-Feb-2006 05:28
Here is the fixed function for Turkish alphabet..

<?php

function uc_first($str){
   $str[0] = strtr($str,
   "abcdefghэijklmnopqrstuvwxyz".
   "\x9C\x9A\xE0\xE1\xE2\xE3".
   "\xE4\xE5\xE6\xE7\xE8\xE9".
   "\xEA\xEB\xEC\xED\xEE\xEF".
   "\xF0\xF1\xF2\xF3\xF4\xF5".
   "\xF6\xF8\xF9\xFA\xFB\xFC".
   "\xFE\xFF",
   "ABCDEFGHIЭJKLMNOPQRSTUVWXYZ".
   "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
   "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
   "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
   "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
   "\xDB\xDC\xDE\x9F");
   return $str;
}

?>
Markus Ernst 12-Jan-2006 06:39
plemieux' function did not work for me without passing the encoding to every single mb function (despite ini_set('default_charset', 'utf-8') at the top of the script). This is the example that works in my application (PHP 4.3):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
    return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
}
?>
plemieux 29-Sep-2005 11:05
Simple multi-bytes ucfirst():

<?php
function my_mb_ucfirst($str) {
    $fc = mb_strtoupper(mb_substr($str, 0, 1));
    return $fc.mb_substr($str, 1);
}
?>
info [at] spwdesign [dot] com 23-Jun-2005 12:48
This is a simple code to get all the 'bad words', stored in a database, out of the text. You could use str_ireplace but since that's installed on PHP5 only, this works as well. It strtolowers the text first then places capitals with ucfirst() where it thinks a capital should be placed, at a new sentence. The previous sentence is ended by '. ' then.

<?php
function filter($text){
    $filters=mysql_query("SELECT word,result FROM filter");
    while($filter=mysql_fetch_array($filters)){
        $text=str_replace($filter[word],$filter[result],strtolower($text));
        $parts=explode(". ",$text);
        for($i=0;$i<count($parts);$i++){
            $parts[$i]=ucfirst($parts[$i]);
        }
        $text=implode(". ",$parts);
    }
    return $text;
}
?>
12-Mar-2005 05:11
Ah, the last code were spoiled, here is the fixed one:

<?php

function uc_first($str){
    $str[0] = strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\x9C\x9A\xE0\xE1\xE2\xE3".
    "\xE4\xE5\xE6\xE7\xE8\xE9".
    "\xEA\xEB\xEC\xED\xEE\xEF".
    "\xF0\xF1\xF2\xF3\xF4\xF5".
    "\xF6\xF8\xF9\xFA\xFB\xFC".
    "\xFD\xFE\xFF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
    "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
    "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
    "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
    "\xDB\xDC\xDD\xDE\x9F");
    return $str;
}

?>

So, this function changes also other letters into uppercase, ucfirst() does only change: a-z to: A-Z.
Stig-Arne Grцnroos 25-Dec-2004 10:46
This function does not work as expected with characters from non-English alphabets (I only tested it with scandinavian letters, едц => ЕДЦ). It leaves them as lowercase.

Someone already commented that the function doesn't work on html entities, which is somewhat understandable. This bug however takes place before I convert the strings to html.
steven at tux dot appstate dot edu 21-Jun-2004 12:14
Note: the return for this function changed in versions 4.3 when a string is passed of length 0.  In <4.2 false is returned and in >4.3 a string of length 0 is returned.

Example:

$name = ucfirst("");
var_dump($name);

$name = ucfirst("owen");
var_dump($name);

Results for <4.2:
bool(false) string(4) "Owen"

Results for >4.3:
string(0) "" string(4) "Owen"
Ami Hughes (ami at mistress dot name) 07-Apr-2004 08:34
In the event you sort of need multiple delimiters to apply the same action to, you can preg_replace this "second delimiter" enveloping it with your actual delimiter.

A for instance, would be if you wanted to use something like Lee's FormatName function in an input box designed for their full name as this script was only designed to check the last name as if it were the entire string.  The problem is that you still want support for double-barreled names and you still want to be able to support the possibility that if the second part of the double-barreled name starts with "mc", that it will still be formatted correctly.

This example does a preg_replace that surrounds the separator with your actual delimiter.  This is just a really quick alternative to writing some bigger fancier blah-blah function.  If there's a shorter, simpler way to do it, feel free to inform me.  (Emphasis on shorter and simpler because that was the whole point of this.) :D

Here's the example.  I've removed Lee's comments as not to confuse them with my own.

<?php

   function FormatName($name=NULL)
   {
       if (empty($name))
           return false;

       $name = strtolower($name);
       $name = preg_replace("[\-]", " - ",$name); // Surround hyphens with our delimiter so our strncmp is accurate
       if (preg_match("/^[a-z]{2,}$/i",$name))  // Simple preg_match if statement
       {

           $names_array = explode(' ',$name);  // Set the delimiter as a space.

           for ($i = 0; $i < count($names_array); $i++)
           {
               if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]',$names_array[$i]))
               {
                   $names_array[$i][2] = strtoupper($names_array[$i][2]);
               }
               $names_array[$i] = ucfirst($names_array[$i]);

           }

           $name = implode(' ',$names_array);
           $name = preg_replace("[ \- ]", "-",$name); //  Remove the extra instances of our delimiter
           return ucwords($name);

       }
   }

?>
lazaro_tolentino at hotmail dot com 01-Apr-2004 01:16
this is a advance ucfirst function, for upper especifics words, with config in array of seperator
/**
 * @return string
 * @param string $str frase que passarб pelo parce
 * @desc Pega uma frase e devolve a mesma com as palavras com suas
 * maiusculas  obedecendo um criterio configurado no array $string_sep
 *
 * @since 2004-04-01 15:04 adicionado a variavel $tring_sep que й um
 * array contendo todos os separadores a serem usados
*/
function str_upper_lower($str)
{
    /**
    * array contendo todos os separadores
    */
    $string_sep=array(' ','-','/','_','.');
    /**
    * coloca todas as palavras com letras minusculas
    */
    $str=strtolower($str);

    /**
    * testa todos os separadores
    */
    for ($i=0;$i<count($string_sep);$i++)
    {
        $sep=$string_sep[$i];
        /**
        * separa a frase usando os separador atual
        */
        $array_words = explode($sep, $str);

        /**
        * variavel que conterб o valor temporario
        */
        $tmp_str = '';
        $i2=0;
        foreach ($array_words as $word)
        {
            /**
            * se a quantidade de caracteres for maior que dois, ou se conter ponto,
            *  devolve upper da primeira letra
            */
            $tmp_str .=(strlen($word)>2 || strpos($word,'.')?ucfirst($word):$word);
            /**
            * nгo adiciona o separador no fim de strings
            */
            if ($i2<count($array_words)-1)
            {
                $tmp_str .= $sep;
            }
            $i2++;
        }
        $str = $tmp_str;
    }
    return $str;
}
Lee Benson 05-Mar-2004 02:37
Here's a function I threw together when needing to validate name entries (both first name and last name).

This allows simple formatting for names prefixed with "Mc" (like McDonald, McCulloch, etc) and names prefixed with O (like O'Reilly, O'Conner, etc)..

It also allows double-barrelled names to be formatted correctly, in the Smith-Jones way.

Here's the function...

<?php

    function FormatName($name=NULL) {

        /* Formats a first or last name, and returns the formatted
        version */

        if (empty($name))
            return false;

        // Initially set the string to lower, to work on it
        $name = strtolower($name);

        // Run through and uppercase any multi-barrelled names

        $names_array = explode('-',$name);

        for ($i = 0; $i < count($names_array); $i++) {

            // "McDonald", "O'Conner"..
            if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]',$names_array[$i])) {
            $names_array[$i][2] = strtoupper($names_array[$i][2]);

            }

            // Always set the first letter to uppercase, no matter what
            $names_array[$i] = ucfirst($names_array[$i]);

        }

        // Piece the names back together
        $name = implode('-',$names_array);

        // Return upper-casing on all missed (but required) elements of the $name var
        return ucwords($name);

    }

?>

If you have any other "rules" to follow for international/foreign naming rules, you can add them to the foreach loop, and it should still follow all of the other rules.

It's a quick fix, but it seems to do the job nicely.

Examples...

<?php

$name = "o'cONNER-MCdOnAld";
echo FormatName($name);

?>

Returns: O'Conner-McDonald
04-Mar-2004 09:46
Of course ucfirst() will _not_ convert html entities such as &uuml; (u-Umlaut as ь) to &Uuml; which would represent Ь.
bkimble at ebaseweb dot com 08-Jun-2003 05:02
Here is a handy function that makes the first letter of everything in a sentence upercase. I used it to deal with titles of events posted on my website ... I've added exceptions for uppercase words and lowercase words so roman numeral "IV" doesn't get printed as "iv" and words like "a" and "the" and "of" stay lowercase.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();

 foreach ($words as $word)
 {
        if (!$higher_exceptions[$word])
                $word = strtolower($word);
        if (!$lower_exceptions[$word])
                $word = ucfirst($word);
         array_push($newwords, $word);

 }

 return join(" ", $newwords);
}
trim
ucwords
РћР±СЂР°Р±РѕС‚РєР° СЃС‚СЂРѕРє


Преобразует в верхний регистр первый символ каждого слова в строке

ucfirst
vfprintf
Обработка строк
PHP Manual

ucwords

(PHP 4, PHP 5)

ucwords — Преобразует в верхний регистр первый символ каждого слова в строке

Описание

string ucwords ( string $str )

Возвращает строку str, в которой первый символ каждого слова переведен в верхний регистр, если этот символ является буквой.

Эта функция считает словами последовательности символов, разделенных пробельными символами, которыми являются пробел, разрыв страницы, перевод строки, возврат каретки, горизонтальная и вертикальная табуляция.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает модифицированную строку.

Примеры

Пример #1 Пример использования ucwords()

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strtoupper() - Преобразует строку в верхний регистр
  • strtolower() - Преобразует строку в нижний регистр
  • ucfirst() - Преобразует первый символ строки в верхний регистр
  • mb_convert_case() - Производит смену регистра символов в строке

User Contributed Notes

qeremy [atta] gmail [dotta] com 27-Feb-2012 05:09
A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
    $tmp = preg_split("//u", $str, 2, PREG_SPLIT_NO_EMPTY);
    return mb_convert_case(
        str_replace("i", "İ", $tmp[0]), MB_CASE_TITLE, "UTF-8").
        $tmp[1];
}

function ucwords_turkish($str) {
    return preg_replace("/(\\w+)/ue", "ucfirst_turkish('\\\\1').'$2'", $str);
}

$str = "iyilik güzelLİK şeker ";
echo ucwords($str) ."\\n";   // Iyilik GüzelLİK şeker
echo ucwords_turkish($str); // İyilik GüzelLİK Şeker
?>
haijerome at gmail dot com 21-Nov-2011 09:14
Thanks a lot brother.

I tested it with a few variations. It works perfectly. Its really great and simple usage of the existing functions. It would be glad to all PHP folks and good to PHP if these kind of functions will be in PHP library on upcoming releases.

<?php

$name1 = "mark-yves robert";
$name2 = "mark-yves robert-bryan";

echo '<br/>Name 1 (mark-yves robert) =>'.
ucwordspecific($name1,'-'); //returns Mark-Yves Robert

echo '<br/>Name 2 (mark-yves robert-bryan)

=>'.ucwordspecific($name2,'-');
//returns Mark-Yves Robert-Bryan

function ucwordspecific($str,$delimiter){
$delimiter_space = '- ';
return str_replace($delimiter_space,$delimiter,ucwords

(str_replace($delimiter,$delimiter_space,$str)));
}

?>

Proud to be a PHP enthusiast always :-)
Anonymous 20-Nov-2011 11:06
Make the first letter of any word in capital even they are separated by hyphen.

 Eg : donzé pierre-yves      => Donzé Pierre-Yves
        joye-cagnard frédéric => Joye-Cagnard Frédéric

<?php

 $str = "donzé pierre-yves";
 echo ucwordsHyphen($str); /*returns Donzé Pierre-Yves*/

function ucwordsHyphen($str){
    return str_replace('- ','-',ucwords(str_replace('-','- ',$str)));
}
?>

 Thanks.
haijerome at gmail dot com 11-Nov-2011 11:38
Recently i got a request from a client to make the first letter of any word in capital even they are separated by hyphen.

Eg : donzé pierre-yves      => Donzé Pierre-Yves
       joye-cagnard frédéric => Joye-Cagnard Frédéric

ucwords("donzé pierre-yves") can make it display
Donzé Pierre-yves but actually i need even the first letter of the second word to be in capital.

So in order to get this i have just written a function below and it works fine. But i hope there would be a better and easier way to do this if so kindly share.

<?php

$str = "donzé pierre-yves";
echo ucwordsHyphen($str); /*returns Donzé Pierre-Yves*/

function ucwordsHyphen($str){
                    $converted_str = "";
                    $str_array = explode(" ",$str);
                    foreach($str_array as $key=>$value):
                        if(strpos($value, '-')):
                             $value = str_replace("-", " ", $value);
                             $value = ucwords(strtolower($value));
                             $value = str_replace(" ", "-", $value);
                        else:
                            $value = ucwords(strtolower($value));
                        endif;
                        $converted_str .= " ".$value;
                    endforeach;
                   return $converted_str;
            }
 ?>

Thanks.
And Proud to be a PHP Programmer always :-)
ahmet363 at gmail dot com 16-Oct-2011 11:14
Turkish character with the ucwords function...

<?php
function ucwords_tr($gelen){

  $sonuc='';

  $kelimeler=explode(" ", $gelen);

  foreach ($kelimeler as $kelime_duz){

    $kelime_uzunluk=strlen($kelime_duz);
    $ilk_karakter=mb_substr($kelime_duz,0,1,'UTF-8');

    if($ilk_karakter=='Ç' or $ilk_karakter=='ç'){

      $ilk_karakter='Ç';

    }elseif ($ilk_karakter=='Ğ' or $ilk_karakter=='ğ') {

      $ilk_karakter='Ğ';

    }elseif($ilk_karakter=='I' or $ilk_karakter=='ı'){

      $ilk_karakter='I';

    }elseif ($ilk_karakter=='İ' or $ilk_karakter=='i'){

      $ilk_karakter='İ';

    }elseif ($ilk_karakter=='Ö' or $ilk_karakter=='ö'){

      $ilk_karakter='Ö';

    }elseif ($ilk_karakter=='Ş' or $ilk_karakter=='ş'){

      $ilk_karakter='Ş';

    }elseif ($ilk_karakter=='Ü' or $ilk_karakter=='ü'){

      $ilk_karakter='Ü';

    }else{

      $ilk_karakter=strtoupper($ilk_karakter);

    }

    $digerleri=mb_substr($kelime_duz,1,$kelime_uzunluk,'UTF-8');
    $sonuc.=$ilk_karakter.kucuk_yap($digerleri).' ';

  }

  $son=trim(str_replace('  ', ' ', $sonuc));
  return $son;

}

function kucuk_yap($gelen){

  $gelen=str_replace('Ç', 'ç', $gelen);
  $gelen=str_replace('Ğ', 'ğ', $gelen);
  $gelen=str_replace('I', 'ı', $gelen);
  $gelen=str_replace('İ', 'i', $gelen);
  $gelen=str_replace('Ö', 'ö', $gelen);
  $gelen=str_replace('Ş', 'ş', $gelen);
  $gelen=str_replace('Ü', 'ü', $gelen);
  $gelen=strtolower($gelen);

  return $gelen;
}

echo ucwords_tr('ŞEKardi ŞEMŞİYE ĞELENÖ ÖMER'); // Şekardi Şemşiye Ğelenö Ömer
echo ucwords_tr('şEKER iMSAK şÖLEN'); // Şeker İmsak Şölen
Philippe 30-Sep-2011 05:54
Because I needed a function that did the same as the function proper in Excel I created this little function :

<?php
function proper($string){

    $string = strtolower($string);

    $lettersAndNumbers = 'abcdefghijklmnopqrstuvwxyz01234565789';

    $string[0] = strtoupper($string[0]);

    for ($index = 1;$index < strlen($string);$index++){
      if (strpos($lettersAndNumbers, $string[$index]) === false){
        if ($index +1 < strlen($string)){
          $string[$index+1] = strtoupper($string[$index+1]);
          $index++;
        }
      }
    }

    return($string);

  }
?>
isis 16-Sep-2011 03:17
Just another custom separator function:

<?php
function ucwords_custom($str, $sep)
{
    return implode($sep, array_map('ucfirst', explode($sep, $str)));

?>
gabe at fijiwebdesign dot com 24-Aug-2011 11:49
Another ucwords function with custom separator.

<?php
function ucwords_custom($str, $sep)
{
    return preg_replace_callback('/' . preg_quote($sep) . './i', create_function(
        '$match',
        'return strtoupper($match[0][1]);'
    ), $str);
}
?>

or simpler with PHP5.3

<?php
function ucwords_custom2($str, $sep = ' ')
{
    return preg_replace_callback('/' . preg_quote($sep) . './i', function($match) {
        return strtoupper($match[0][1]);
    }, $str);
}
?>
Sebstian Espinosa 04-Aug-2011 04:16
Is more simple to use str_replace to use ucwords without using space as separator like:

<?php

function ucwordsEx($str, $separator){

      $str = str_replace($separator, " ", $str);
      $str = ucwords(strtolower($str));
      $str = str_replace(" ", $separator, $str);
      return $str;

}
/*
Example:
*/
echo ucwordsEx("HELLO-my-NAME-iS-maNolO", "-");
/*
Prints: "Hello My Name Is Manolo"
*/

?>
jmarois at ca dot ibm dot com 12-Feb-2010 08:51
My quick and dirty ucname (Upper Case Name) function.

<?php
//FUNCTION

function ucname($string) {
    $string =ucwords(strtolower($string));

    foreach (array('-', '\'') as $delimiter) {
      if (strpos($string, $delimiter)!==false) {
        $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return $string;
}
?>
<?php
//TEST

$names =array(
  'JEAN-LUC PICARD',
  'MILES O\'BRIEN',
  'WILLIAM RIKER',
  'geordi la forge',
  'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>

You can add more delimiters in the for-each loop array if you want to handle more characters.
Kovik 27-Dec-2009 07:37
ucwords() only uses whitespace as a delimiter. I found that I needed the ability to use other delimiters for denoting words.

Example: Transforming "content-type" into "Content-Type".

<?php
/**
 * Capitalize all words
 * @param string Data to capitalize
 * @param string Word delimiters
 * @return string Capitalized words
 */
function capitalizeWords($words, $charList = null) {
    // Use ucwords if no delimiters are given
    if (!isset($charList)) {
        return ucwords($words);
    }

    // Go through all characters
    $capitalizeNext = true;

    for ($i = 0, $max = strlen($words); $i < $max; $i++) {
        if (strpos($charList, $words[$i]) !== false) {
            $capitalizeNext = true;
        } else if ($capitalizeNext) {
            $capitalizeNext = false;
            $words[$i] = strtoupper($words[$i]);
        }
    }

    return $words;
}
?>

Testing:
<?php
echo capitalizeWords('this is a test');  // This Is A Test
echo capitalizeWords('this-is-a-test');  // This-is-a-test
echo capitalizeWords('this is a test', ' ');  // This Is A Test
echo capitalizeWords('this-is-a-test', '-');  // This-Is-A-Test
echo capitalizeWords('this-is a-test', ' ');  // This-is A-test
echo capitalizeWords('this-is a-test', '-');  // This-Is a-Test
echo capitalizeWords('this-is a-test', ' -');  // This-Is A-Test
?>
mariodivece at yahoo dot com 25-Nov-2009 09:04
Here's a simple function to convert a pascal cased, camel cased or underscore-separated string (usually for identifiers) that works well. It'd be nice if someone could provide the regex equivalent.

<?php

class StringHelper
{
    const CONVENTION_AUTO = 0;
    const CONVENTION_PASCAL = 1;
    const CONVENTION_CAMEL = 2;
    const CONVENTION_USCORE = 3;

    /**
     * Converts a camel-cased, pascal-cased or underscore-separated word into a human-readable string
     * @param string $str
     * @param int $convention
     * @return string
     */
    public static function toWords($str, $convention = self::CONVENTION_AUTO)
    {
        if ($convention === self::CONVENTION_AUTO)
        {
            if (self::strContains($str, '_'))
            {
                $convention = self::CONVENTION_USCORE;
            }
            else
            {
                $convention = self::CONVENTION_PASCAL;
            }
        }

        if ($convention === self::CONVENTION_USCORE)
        {
            return str_replace('_', ' ', $str);
        }

        if ($convention === self::CONVENTION_PASCAL || $convention === self::CONVENTION_CAMEL)
        {
            $baseStr = ucfirst($str);
            $whitespaceBefore = strtoupper($str) . "01234567890";

            $retStr = "";
            for ($i = 0; $i < strlen($baseStr); $i++)
            {
                $chr = $baseStr[$i];
                if (strstr($whitespaceBefore, $chr) !== false)
                {
                    $retStr .= " " . $chr;
                }
                else
                {
                    $retStr .= $chr;
                }
            }

            return trim($retStr);
        }
        else
        {
            throw new Exception(692, '$convention must be one of the CONVENTION-prefixed constants');
        }

    }

}

?>
robert at broofa dot com 08-Jul-2009 06:42
Some recipes for switching between underscore and camelcase naming:

<?php
// underscored to upper-camelcase
// e.g. "this_method_name" -> "ThisMethodName"
preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string);

// underscored to lower-camelcase
// e.g. "this_method_name" -> "thisMethodName"
preg_replace('/_(.?)/e',"strtoupper('$1')",$string);

// camelcase (lower or upper) to underscored
// e.g. "thisMethodName" -> "this_method_name"
// e.g. "ThisMethodName" -> "this_method_name"
strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
?>

Of course these aren't 100% symmetric.  For example...
  * this_is_a_string -> ThisIsAString -> this_is_astring
  * GetURLForString -> get_urlfor_string -> GetUrlforString
Greg S 26-Apr-2009 09:16
I did the same thing as Catalin, but for French names.

Here's what I'm doing :

For each word (not considering the single-quote as a word boundary character) :
- Put the word in lower case
- If the word is "de", return, else, put the first letter in upper-case
- See if the second character of the word is a single-quote
- Yes ? Put the next char in upper case
- And if the char before the single quote is D, put it back to lower case (-> d)

This complies with the French rules for capitalization in names.

Sample results :
-d'Afoo Bar
-de Foo Bar
-O'Foo Bar
-Foo'bar

<?php
function my_ucwords($s) {
        $s = preg_replace_callback("/(\b[\w|']+\b)/s", fixcase_callback, $s);

        return $s;

    }

    function fixcase_callback($word) {

        $word = $word[1];

        $word = strtolower($word);

        if($word == "de")
            return $word;

        $word = ucfirst($word);

        if(substr($word,1,1) == "'") {
            if(substr($word,0,1) == "D") {
                $word = strtolower($word);
            }
            $next = substr($word,2,1);
            $next = strtoupper($next);
            $word = substr_replace($word, $next, 2, 1);
        }

        return $word;
    }
?>
vista_ at live dot se 17-Nov-2008 02:02
<?php
      if(!function_exists('mb_ucwords'))
      {
            function mb_ucwords($str)
            {
                  return mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
            }
      }
?>
dyer85 at gmail dot com 07-Nov-2008 03:33
When attempting to adopt a solution similar to Catalin's post (20-Oct-2008 10:14), I ran into some additional problems. Just a heads up, Catalin's wasn't capitalizing correctly when a name like "O'reilley" appeared at the start of the string or a new line. Also, it doesn't account for locale-sensitivity.

I also needed to recognize additional Irish surnames, such as "McArthur/MacArthur" or "FitzGerald". I also didn't want to misinterpret French as an Irish surname, so, "S'il vous plaît" shouldn't result in the "i" in "S'il" capitalized.

I modified Catalin's version, but it's still not perfect. This version happened to suit my needs, so be sure to assess your own needs before using.

<?php

function my_ucwords($str)
{
    $str = ucwords($str);

    // Not perfect
    return preg_replace(
        '/
            (?: ^ | \\b )         # assertion: beginning of string or a word boundary
            ( O\' | Ma?c | Fitz)  # attempt to match Irish surnames
            ( [^\W\d_] )          # match next char; we exclude digits and _ from \w
        /xe',
        "'\$1' . strtoupper('\$2')",
        $str);
}

?>
strazds at gmail dot com 01-Nov-2008 02:45
ucwords for UTF-8 strings:

<?php
function mb_ucwords($str) {
    $str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
    return ($str);
}
?>
Catalin 20-Oct-2008 07:14
I have looked for a work-around that would upper-case letter after an ' too.

For example,

ucword("o'lunney's");

would output "O'lunney's" and I wanted it to output "O'Lunney's".

Here is my function:

<?php
function my_ucwords($string) {
        $string = ucwords(strtolower($string));
        $string = preg_replace_callback("/( [ a-zA-Z]{1}')([a-zA-Z0-9]{1})/s",create_function('$matches','return $matches[1].strtoupper($matches[2]);'),$string);
        return $string;
}
?>

Hope it helps someone.
Alex 27-Aug-2008 09:43
A modified sentenceNormalizer by gregomm

Features:
1- Removes duplicated question marks, exclamations and periods
2- Capitalize first letter of a sentence.
3- Split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the end of each sentence
5- Retains newlines

--removed from orginal function--
undestand the meaning of "¡" and "¿" in languages like spanish.
undestand the htmlentitity version of this simbols.
--removed from orginal function--

<?php
function sentenceNormalizer($sentence_split) {
    $sentence_split = preg_replace(array('/[!]+/','/[?]+/','/[.]+/'),
                                   array('!','?','.'),$sentence_split);

    $textbad = preg_split("/(\!|\.|\?|\n)/", $sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE);
    $newtext = array();
    $count = sizeof($textbad);

    foreach($textbad as $key => $string) {
        if (!empty($string)) {
            $text = trim($string, ' ');
            $size = strlen($text);

            if ($size > 1){
                $newtext[] = ucfirst(strtolower($text));
            }
                elseif ($size == 1) {
                    $newtext[] = ($text == "\n") ? $text : $text . ' ';
                }
        }
    }

    return implode($newtext);
}
?>
majd87 at gmail dot com 05-Aug-2008 06:58
I modified Q1712's code (below) to use regular expressions
instead of characters to properly capitalize words that fall
directly after an unwanted character. See his post for details.

This version allows me to use it around html elements, etc.

<?php
    function my_ucwords($string){

        $invalid_characters = array('"',
                                    '\(',
                                    '\[',
                                    '\/',
                                    '<.*?>',
                                    '<\/.*?>');

        foreach($invalid_characters as $regex){
            $string = preg_replace('/('.$regex.')/','$1 ',$string);
        }

        $string=ucwords($string);

        foreach($invalid_characters as $regex){
            $string = preg_replace('/('.$regex.') /','$1',$string);
        }

        return $string;
    }
?>

Moreover, to get a proper title case, i combine it with this function:

This Function is obtained from:
http://codesnippets.joyent.com/posts/show/716

<?php
    function title_case($title) {
        $smallwordsarray = array(
            'of','a','the','and','an','or','nor','but','is','if','then',
'else','when',
            'at','from','by','on','off','for','in','out',
'over','to','into','with'
        );

        $words = explode(' ', $title);
        foreach ($words as $key => $word)
        {
            if ($key == 0 or !in_array($word, $smallwordsarray))
            $words[$key] = $this->my_ucwords(strtolower($word));
        }

        $newtitle = implode(' ', $words);
        return $newtitle;
    }
?>
Hope you find it useful.
gregomm at gmail dot com 23-May-2008 12:38
An improved of ucsentence. In fact its a function to avoid ugly data entry. It's based on code taken from this page. Can be inproved for better performance, of course...

Features:
1- removes duplicated question marks, an exclamations
2- Capitalize first letter of a sentence.
3- split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the begining of each sentence
5- undestand the meaning of "¡" and "¿" in languages like spanish.
6- undestand the htmlentitity version of this simbols.

    function sentenceNormalizer( $sentence_split ) {

        $sentence_split = preg_replace("/[!]+/","!",$sentence_split);
        $sentence_split = preg_replace("/[¡]+/","¡",$sentence_split);
        $sentence_split = preg_replace("/[?]+/","?",$sentence_split);
        $sentence_split = preg_replace("/[¿]+/","¿",$sentence_split);

        $textbad = preg_split("/(\<[a-zA-Z0-9-]*\>".
"\!(\s)?|\.(\s)?|\?(\s)?|¿(\s)?|¡(\s)?".
"|&iquest;(\s)?|&iexcl;(\s)?)/",
         $sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE);
        $newtext = array();
        $count = sizeof($textbad);

        $prevStr ="";

        for ($i = 0; $i < $count; $i++){

            $text = trim($textbad[$i]);
            $size = strlen($text);

            if ($size>1){

                $sentencegood=ucfirst(strtolower($text));

                if ($i>0 && $prevStr != '¿' && $prevStr != '¡' && $prevStr !="&iquest;" && $prevStr !="&iexcl;"){
                    $sentencegood =" ".$sentencegood;
                }
                $newtext[] = $sentencegood;
                $prevStr =$text;

            }elseif($size==1 ){

                if ($i>0 && ($text == '¿' || $text == '¡' || $prevStr =="&iquest;" || $prevStr =="&iexcl;") ){
                    $newtext[] =" ".$text;
                }else{
                    $newtext[] =$text;
                }
                $prevStr =$text;
            }

        }

        $textgood = implode($newtext);
        return $textgood;
    }
caio dot ariede at gmail dot com 25-Mar-2008 11:53
To capitalize e-mail address, I made this function.

<?php

    function capitalize_email($email)
    {
        $domain = strtolower(strstr($email, '@'));
        $user = strtolower(substr($email, 0, strrpos($email, '@')));
        $user = preg_replace('!((?:\b|_).)!e', 'strtoupper("$1");', $user);
        return $user.$domain;
    }

    echo capitalize_email('blabla.example@example.com');

    // Blabla.Example@example.com

?>
NoName 12-Mar-2008 12:03
For strings with diactrical marks (umlauts, etc.), consider mb_convert_case.
blake at goinoutwest dot com 29-Jan-2008 05:14
Relating to the mb_ucwords() function posted by Anonymous.  In order for this to actually be multi-byte compliant, you would also need to use mb_substr() and mb_strlen() instead of substr and strlen respectively.

Here it is corrected and extended even further to allow multiple word separators and a list of exceptions to correct after title casing. It's a bit tedious and inelegant, but things frequently are when dealing with human languages.

function mb_ucwords($str) {
    $exceptions = array();
    $exceptions['Hp'] = 'HP';
    $exceptions['Ibm'] = 'IBM';
    $exceptions['Gb'] = 'GB';
    $exceptions['Mb'] = 'MB';
    $exceptions['Cd'] = 'CD';
    $exceptions['Dvd'] = 'DVD';
    $exceptions['Usb'] = 'USB';
    $exceptions['Mm'] = 'mm';
    $exceptions['Cm'] = 'cm';
    //    etc.

    $separator = array(" ","-","+");

    $str = mb_strtolower(trim($str));
    foreach($separator as $s){
        $word = explode($s, $str);

        $return = "";
        foreach ($word as $val){
            $return .= $s . mb_strtoupper($val{0}) . mb_substr($val,1,mb_strlen($val)-1);
        }
        $str = mb_substr($return, 1);
    }

    foreach($exceptions as $find=>$replace){
        if (mb_strpos($return, $find) !== false){
            $return = str_replace($find, $replace, $return);
        }
    }
    return mb_substr($return, 1);
}
Anonymous 16-Dec-2007 03:09
Function to do what ucwords is intended to do - just correctly also for international char sets:

function mb_ucwords($s)
{
    $s = mb_strtolower(trim($s));
    $w = explode(" ", $s);

    $return = "";
    foreach ($w as $val)
    {
        $return .= " " . mb_strtoupper($val{0}) . substr($val,1,strlen($val)-1);
    }
    return trim($return);
}

Building on an earlier snippet here.
kendsnyder at gmail dot com 30-Jul-2007 01:02
Here is a function to capitalize a last name, accounting for hyphens, apostrophes, "Mc" and "Mac":

<?php
function CapitalizeLastName($name) {
    $name = strtolower($name);
    $name = join("'", array_map('ucwords', explode("'", $name)));
    $name = join("-", array_map('ucwords', explode("-", $name)));
    $name = join("Mac", array_map('ucwords', explode("Mac", $name)));
    $name = join("Mc", array_map('ucwords', explode("Mc", $name)));
    return $name;
}
?>

I speed tested it against functions that used preg_replace() with an "e" modifier, preg_replace_callback(), and a character-by-character parsing.  Unexpectedly, this function using join(), array_map() and explode() was fastest.
emailfire at gmail dot com 23-May-2007 04:27
To use ucwords with an exception:

<?php
function ucwordss($str, $exceptions) {
$out = "";
foreach (explode(" ", $str) as $word) {
$out .= (!in_array($word, $exceptions)) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " ";
}
return rtrim($out);
}
?>

For example:

<?php
$string = "my cat is going to the vet";
$ignore = array("is", "to", "the");
echo ucwordss($string, $ignore);
// My Cat is Going to the Vet
?>
Q1712 at online dot ms 05-May-2007 12:49
ucwords() only excepts whitespace in front of a word, although some chars like '"' or '(' normally have no space between them and the following word:
<?php
$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo ucwords(strtolower($title));
?>
prints: Elvis "the King" Presley - (let Me Be Your) Teddy Bear

To avoid this i use a small function adding and deleting blanks behind these chars, and using ucwords() in between:

<?php
function my_ucwords($string)
  {
    $noletters='"([/'; //add more if u need to
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i], $noletters[$i].' ', $string);
    $string=ucwords($string);
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i].' ', $noletters[$i], $string);
    return $string;
  }

$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo my_ucwords(strtolower($title));
?>

prints: Elvis "The King" Presley - (Let Me Be Your) Teddy Bear
chris at cmbuckley dot co dot uk 13-Feb-2007 09:16
To get some sort of title case with lower-case articles, prepositions etc., try something like this (removing the carriage returns in the regular expression):

<?php
    function lower_articles($str) {
        return preg_replace(
            "/(?<=(?<!:|’s)\W)
            (A|An|And|At|For|In|Of|On|Or|The|To|With)
            (?=\W)/e",
            'strtolower("$1")',
            $str
        );
    }
?>

I added the lookbehind (?<!:|’s) because I use this for film titles, where words following those terms should be capitalised (e.g. Lemony Snicket’s A Series of Unfortunate Events, American Pie Presents: The Naked Mile).
barnaby ritchley at exeye dot co dot uk 03-Jan-2007 08:53
A very easy way to convert to title case:

function titleCase($string)
     {
     return ucwords(strtolower($string));
     }

$myString = "SOME TEXT";

echo titleCase($myString);

//will print, "My Text"
max at phoenixweb dot it 15-Sep-2006 07:35
I have rewritten a UCSMART function adding a feature to translate special ASCII char (windows occidental ascii charset):

You can edit/add/delete char by use the first two string (be carefull to preserve the order of the string).

Enjoy!

<?
$ASCII_SPC_MIN = "àáâãäåæçèéêëìíîïðñòóôõöùúûüýÿžš";
$ASCII_SPC_MAX = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝŸŽŠ";

function str2upper($text) {
    global $ASCII_SPC_MIN,$ASCII_SPC_MAX;
    return strtr(strtoupper($text),$ASCII_SPC_MIN,$ASCII_SPC_MAX);
}
function str2lower($text) {
    global $ASCII_SPC_MIN,$ASCII_SPC_MAX;
    return strtr(strtolower($text),$ASCII_SPC_MAX,$ASCII_SPC_MIN);
}
function ucsmart($text) {
    global $ASCII_SPC_MIN;
    return preg_replace(
        '/([^a-z'.$ASCII_SPC_MIN.']|^)([a-z'.$ASCII_SPC_MIN.'])/e',
        '"$1".str2upper("$2")',
        str2lower($text)
    );
}
?>

Massimiliano Cuttini
marco at hotelsandgo dot com 09-Sep-2006 09:35
ucwords that works also with apices: '
for example: "aquila d'abruzzo" became "Aquila d'Abruzzo"
The second part after the // comment can removed! Is optimized for italian language (leave lowercase articles, prepositions, conjunctions) but easily changeable. Notice che "'s"!! for example "hotel 2000's" becames "Hotel 2000's".

    function my_ucwords($s)
        {
        $a=strtolower($s);
        $s=ucfirst($a);
        for($x=0; $x<strlen($s)-1; $x++)
            if(!ctype_alpha($s[$x])) $s[$x+1]=strtoupper($s[$x+1]);

        //Lascia minuscoli articoli, preposizioni, congiunzioni
        $minuscole=array("il", "lo", "la", "i", "gli", "le",                //ARTICOLI DETERMINATIVI
                 "un", "uno", "una",                        //ARTICOLI INDETERMINATIVI
                 "e",  "d", "l", "s", "un",                    //CONGIUNZIONI e CONTRATTI
                 "di", "a", "da", "in", "con", "su", "per", "tra", "fra",    //PREPOSIZIONI SEMPLICI
                 "del", "dello", "della", "dei", "degli", "delle",        //PREPOSIZIONI ARTICOLATE
                 "a", "al", "allo", "alla", "ai", "agli", "alle",
                 "da", "dal", "dallo", "dalla", "dai", "dagli", "dalle",
                 "in", "nel", "nello", "nella", "nei", "negli", "nelle",
                 "con", "col", "collo", "colla", "coi", "cogli", "colle",
                 "su", "sul", "sullo", "sulla", "sui", "sugli", "sulle",
                 "per", "pel", "pei");

        foreach($minuscole as $value)
            {
            $pos=strpos($a, $value);
            if( ( $pos>0 && $pos<strlen($s)-1 && !ctype_alpha($a[$pos-1]) && !ctype_alpha($a[$pos+1]) )    //CARATTERE IN MEZZO
            ||  ( $pos==strlen($s)-1 && !ctype_alpha($a[$pos-1]) ) )                    //CASO PARTICOLARE: carattere in fondo. x es: "hotel 2000's"
                $s[$pos]=strtolower($s[$pos]);
            }

        return $s;
        }

    function my_ucwords_essential($s)
        {
        $a=strtolower($s);
        $s=ucfirst($a);
        for($x=0; $x<strlen($s)-1; $x++)
            if(!ctype_alpha($s[$x])) $s[$x+1]=strtoupper($s[$x+1]);

        return $s;
        }

Can be rewritten better, I Know
philip at fcknet dot dk 08-Aug-2006 05:11
Before noticing this function I made the following function (that does the same as ucwords):

<?php
function firstUpper($string)
{
    $string = str_replace(array("Æ","Ø","Å"), array("æ","ø","å"), strtolower($string));
    $ord = explode(" ", $string);

    $return = "";
    foreach ($ord as $val)
    {

        $return .= " " . str_replace(array("æ","ø","å"), array("Æ","Ø","Å"), strtoupper($val{0})) . substr($val,1,strlen($val)-1);
    }
    return $return;
}
?>

It also converts Danish letters without using the setlocale function.
starmonkey [at] evolove [dot] net 05-Aug-2006 08:17
Simple helper function to walk through a nested array of strings and upper case them:

<?php
/**
 * Helper function to convert an array of strings to upper case words
 */
function _capitalize($input) {
    if(is_array($input)) {
        // recurse through array elements (using a reference)
        foreach($input as &$value) {
            $value = _capitalize($value);
        }
        return $input;
    } elseif(is_string($input)) {
        // process this string
        return ucwords($input);
    } else {
        // all other data types, leave alone
        return $input;
    }
}
?>
Ismet Togay 30-May-2006 05:07
Response to arif:

We do not need that long functions. In order to make ucwords() worked properly in Turkish words that contain speacial characters, we can use the following command in our php codes:

setlocale(LC_ALL, 'tr_TR');

This will set locale to Turkish.
lev at phpfox dot com 06-May-2006 01:44
In the function ucsmart() posted by ieure at php dot net on 04-Dec-2005 11:57, I found a similar problem in this function to what he found in igua's.

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z]|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

"igua's code adds a backslash in front of the first single quote for me. This doesn't alter the content in any way other than changing case."

Actually, it did end up changing the content for me (php 5.0.4) in the way that this function escapes a single quotation (apostrophe) in the MIDDLE of a word.

For example:

who's online?

Became:

Who\'s Online?

The fix is simple however, and merely requires fine-tuning the regular expression:

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z\']|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

(note: while previewing this note before adding it, I am noticing php's website is not correctly displaying the change I made as I wrote it. After the first a-z in the expression, the single quotation should be escaped... If it isn't you will get a parse error! And apoligies if my text here is colored as php code; not my fault!)

This will not escape a single quotation mark which occurs in the middle of a word... Though, you may find that might need to add other characters inside the regular expression if you use other special characters inside your words and if you get funky output.

It's a great expression though! Simple, yet very powerful. Kudos!
arif 29-Mar-2006 12:12
it can be used for Turkish alphabet.

function strtoupperTR($str){
   return strtr($str,
   "abcçdefgğhıijklmnoöpqrsştuüvwxyz",
   "ABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ");
}
function strtolowerTR($str){
   return strtr($str,
   "ABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ",
   "abcçdefgğhıijklmnoöpqrsştuüvwxyz");
}

function ucwordsTR($str)
{
   return preg_replace('/([^a-zığüşçö]|^)([a-zığüşçö])/e', '"$1".strtoupperTR("$2")',
                       strtolowerTR($str));
}
24-Dec-2005 07:34
"ieure at php dot net", your idea is pure poetry!

The function below will standardize the capitalization on people's names and the titles of reports and essays . You may need to adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.

function my_ucwords($str, $is_name=false) {
   // exceptions to standard case conversion
   if ($is_name) {
       $all_uppercase = '';
       $all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|And';
   } else {
       // addresses, essay titles ... and anything else
       $all_uppercase = 'Po|Rr|Se|Sw|Ne|Nw';
       $all_lowercase = 'A|And|As|By|In|Of|Or|To';
   }
   $prefixes = 'Mc';
   $suffixes = "'S";

   // captialize all first letters
   $str = preg_replace('/\\b(\\w)/e', 'strtoupper("$1")', strtolower(trim($str)));

   if ($all_uppercase) {
       // capitalize acronymns and initialisms e.g. PHP
       $str = preg_replace("/\\b($all_uppercase)\\b/e", 'strtoupper("$1")', $str);
   }
   if ($all_lowercase) {
       // decapitalize short words e.g. and
       if ($is_name) {
           // all occurences will be changed to lowercase
           $str = preg_replace("/\\b($all_lowercase)\\b/e", 'strtolower("$1")', $str);
       } else {
           // first and last word will not be changed to lower case (i.e. titles)
           $str = preg_replace("/(?<=\\W)($all_lowercase)(?=\\W)/e", 'strtolower("$1")', $str);
       }
   }
   if ($prefixes) {
       // capitalize letter after certain name prefixes e.g 'Mc'
       $str = preg_replace("/\\b($prefixes)(\\w)/e", '"$1".strtoupper("$2")', $str);
   }
   if ($suffixes) {
       // decapitalize certain word suffixes e.g. 's
       $str = preg_replace("/(\\w)($suffixes)\\b/e", '"$1".strtolower("$2")', $str);
   }
   return $str;
}

// A name example
print my_ucwords("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);
// Output: Marie-Lou van der Planc-St.John

// A title example
print my_ucwords("to be or not to be");
// Output: "To Be or Not to Be"
ieure at php dot net 04-Dec-2005 02:57
Whoa guys, tone things down a bit here. No need to loop and implode. This is a one-line solution:

function ucsmart($text)
{
    return preg_replace('/([^a-z]|^)([a-z])/e', '"$1".strtoupper("$2")',
                        strtolower($text));
}

igua's code adds a backslash in front of the first single quote for me. This doesn't alter the content in any way other than changing case.
gothicbunny at hotmail dot com 08-Nov-2005 04:16
Here is a simple, yet winded, opposite to ucwords.

<?php
/*
    # lcwords v1.000
    # Convert the first word character to lowercase (opposite to ucwords)
    # input string
    # return string
*/
function lcwords($string)
{
    /* Some temporary variables */
    #loop variable
    $a = 0;
    #store all words in this array to be imploded and returned
    $string_new = array();
    #create array of all words
    $string_exp = explode(" ",$string);
    foreach($string_exp as $astring)
    {
        for($a=0;$a<strlen($astring);$a++)
        {
            #check that the character we are at {pos $a} is a word
            #i.e. if the word was !A the code would fail at !
            #then loop to the next character and succeed at A
            #check at character position $a
            if(preg_match("'\w'",$astring[$a]))
            {
                $astring[$a] = strtolower($astring[$a]);
                #end the loop
                break;
            }
        }
        $string_new[] = $astring;
    }
    #recreate the string from array components using space deliminator
    return implode(" ",$string_new);
}
?>

Of course a simplier way would be to use a callback, but I like working with long code :)
20-Oct-2005 04:14
Here's a  piece that allows you to use the contents of a directory..  capitalizes the words and make links.. this particular example splits file names at _ and only selects file with .htm extensions (thought you could use any extension and call it using  include()  or soom such)
ie my_file_name.htm will produce
<a href="my_file_name.htm">My File Name</a>

<?php
$path = "/home/path/to/your/directory";
   $mydir = dir($path);
   while(($file = $mydir->read()) !== false) {
     if(substr($file, -4)=='.htm'){
    $trans = array("_" => " ", ".htm" => ""); // creates the editing array
    $newlist = strtr($file, $trans); // edits using editing array
    echo "<a href=\"".$file."\">".ucwords($newlist)."</a><br>";
     }
    }
   ?>
Static Bit 18-Sep-2005 08:01
// programming/repair -> Programming/Repair
// mcdonald    o'neil   -> McDonand O'Neil
// art    of street        -> Art of Street

function NomeProprio($nome)
   {
   //two space to one
   $nome = str_replace("  ", " ", $nome);
   $nome = str_replace("  ", " ", $nome);
   $nome = str_replace("  ", " ", $nome);

   $intervalo = 1;
   for ($i=0; $i < strlen($nome); $i++)
       {
       $letra = substr($nome,$i,1);
       if (((ord($letra) > 64) && (ord($letra) < 123)) || ((ord($letra) > 48) && (ord($letra) < 58)))
          {
          $checa_palavra = substr($nome, $i - 2, 2);
          if (!strcasecmp($checa_palavra, 'Mc') || !strcasecmp($checa_palavra, "O'"))
             {
             $novonome .= strtoupper($letra);
             }
            elseif ($intervalo)
             {
             $novonome .= strtoupper($letra);
             }
            else
             {
             $novonome .= strtolower($letra);
             }
          $intervalo=0;
          }
         else
          {
          $novonome .= $letra;
          $intervalo = 1;
          }
       }
   $novonome = str_replace(" Of ", " of ", $novonome);
   $novonome = str_replace(" Da ", " da ", $novonome);
   $novonome = str_replace(" De ", " de ", $novonome);
   $novonome = str_replace(" Do ", " do ", $novonome);
   $novonome = str_replace(" E " , " e " , $novonome);
   return $novonome;
   }
radley25 at nospam dot spamcop dot net 04-Jul-2005 08:06
In response to joshuamallory at yahoo dot com:

Using CSS to fix a PHP fault is not the ideal way to solve a problem. CSS is browser dependent and can only be used when the data is presented in a web page. A better fix would be something like this:

<?php
function better_ucwords($string) {
   $string = ucwords($string);
   $string = preg_replace('#[\\/][a-z]#e', "strtoupper('$0')", $string);
   return $string;
}
?>
igua no-spam at coveruniverse dot com 08-Mar-2005 04:30
The code posted by neil doesn't fully do what is wanted. Try adding some more question marks at the end and it will return a not wanted string.

Below code will uppercase all your words regardless of the delimiter.

<?php
$text = "What?No 'delimiters',shit \"happens\" here.this solves all problems???";
preg_match_all('/[A-Za-z]+|[^A-Za-z]+/', $text, $data);
for ($i = 0; $i < count($data[0]); $i++) {
  $data[0][$i] = ucfirst($data[0][$i]);
}
$text = implode("", $data[0]);
print $text;
?>
arjini at gmail dot com 23-Jan-2005 12:20
Not so much ucwords() related as it is capital letter related. I often use camel casing (as do wikis), I needed a reason to reverse the camel casing.

function unCamelCase($str){
    $bits = preg_split('/([A-Z])/',$str,false,PREG_SPLIT_DELIM_CAPTURE);
    $a = array();
    array_shift($bits);
    for($i = 0; $i < count($bits); ++$i)
        if($i%2)
            $a[] = $bits[$i - 1].$bits[$i];
    return $a;
}

print_r(unCamelCase('MyFancyCamelCasedWord'));

Array
(
    [0] => My
    [1] => Fancy
    [2] => Camel
    [3] => Cased
    [4] => Word
)
joshuamallory at yahoo dot com 14-Nov-2004 08:08
If you want to format a string like...

<?php
    $string = "computer programming/repair";
    print ucwords($string);
?>

Output: Computer Programming/repair

Notice the word after the slash (Programming/repair) isn't capitalized. To fix this, use CSS...

<?php
    $string = "computer programming/repair";
    print '<p style="text-transform:capitalize">';
    print ucwords($string);
    print '<p>';
?>
babel - nospamplease - sympatico - ca 10-Feb-2004 08:26
Correction to the code of firewire at itsyourdomain dot com:

preg_replace_callback('/\b(\w)(\w+)?/',
   create_function('$a',
   'return strtoupper($a[1]) . ((sizeof($a) > 2 ) ?
       strtolower($a[2]) : "");'),
    'p.s.: hello.this is my string.');

Will work with punctuation as well as spaces.
deepdene at email dot com 09-Dec-2002 11:20
A function knowing about name case (i.e. caps on McDonald etc)

function name_case($name)
{
    $newname = strtoupper($name[0]);
    for ($i=1; $i < strlen($name); $i++)
    {
        $subed = substr($name, $i, 1);
        if (((ord($subed) > 64) && (ord($subed) < 123)) ||
            ((ord($subed) > 48) && (ord($subed) < 58)))
        {
            $word_check = substr($name, $i - 2, 2);
            if (!strcasecmp($word_check, 'Mc') || !strcasecmp($word_check, "O'"))
            {
                $newname .= strtoupper($subed);
            }
            else if ($break)
            {

                $newname .= strtoupper($subed);
            }
            else
            {
                $newname .= strtolower($subed);
            }
             $break=0;
        }
        else
        {
            // not a letter - a boundary
             $newname .= $subed;
            $break=1;
        }
    }
    return $newname;
}
firewire at itsyourdomain dot com 19-Nov-2002 03:13
For those that want to capitalize based on a regular expression.
print preg_replace_callback('/(\s|^)[a-z]/', create_function('$a', 'return strtoupper($a[0]);'), 'hello this is my string');

This is a quick untested example.
anton at titov dot net 25-Sep-2002 10:56
for those, who not avoid regular expressions, solution of discussed problem:

$text=preg_replace('/(\W)(\w)/e', '"\\1".strtoupper("\\2")', ucfirst(strtolower($text)));
fille at fukt dot bth dot se 27-Aug-2002 08:04
[Editor's note: For details on the bug see
http://bugs.php.net/bug.php?id=14655]

This function has a bug, and while waiting for the bug fix, here is a work-around pice of code.

When using international letters, you will get into troubles with the ucwords() function.

Example:

$string="xxx�xx" will be "Xxx�Xxx" after beeing processed by ucwords().

To get around it, I wrote some extra code that checks the string once more, and lowercases all letters that is not in the beginning of a word.

$string=ucwords($string);
//Bugfix from here on
for($i=0;$i<strlen($string);$i++)
    if((ctype_upper($string[$i]) &&( $string[$i-1]==" " || $i==0 ))!=TRUE)
        $string[$i]=strtolower($string[$i]);

Thia code is also an optional way of doing the same work on a string that is totally UPPERCASE.
27-Aug-2002 07:20
Beware of language when using this function to collate personal names! This may not work with some languages and this depends on the current locale!
So it's best to simply use strtoupper() or strtolower(strtoupper()) to collate names for searches in a database. Avoid using strtolower() directly, as it won't collate some characters like the german '�' into 'ss'.
Capitalizing names is very language dependant: don't do it on address fields such as city names. Prefer uppercasing, or keep the original case if the string must be displayed to a user!
18-Jan-2002 06:14
This seems to be what people want:

function uc_all($string) {
    $temp = preg_split('/(\W)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
    foreach ($temp as $key=>$word) {
        $temp[$key] = ucfirst(strtolower($word));
    }
    return join ('', $temp);
}

[ed note: fixed the code to be correct]
Julienc at psychologie-fr dot com 03-Nov-2001 07:06
Its still possible to clean a bit more the previous sample:

$string=strtolower($string); $break=true;
for ($i=0; $i < strlen($string); $i++) { $subed=$string[$i];
if (((ord($subed) > 64) && (ord($subed) < 123)) || ((ord($subed) > 48) && (ord($subed) < 58))) {
if ($break) { $string[$i] = strtoupper($subed); }
$break=false; } else { $break=true; }
}

- Julien
mistcat at mistcat dot com 28-Mar-2001 02:00
Actually that code would work if you changed this line:
$words[0][] = $lastword;
to
$words[0][] = $lastword[0];
neil at no-spam-ents24 dot com 21-Mar-2001 05:10
The code posted above by Joerg Krause only works for a string which ends with one of the delimiters. A possible fix is:

<?php
$text = "What?No delimiters,shit happens here.this solves all problems.";
preg_match_all("/(\w+[,. ?])+/U", $text, $words);
preg_match("/(\w+)$/", $text, $lastword);
$words[0][] = $lastword;
foreach($words[0] as $part) $uwords[] = ucfirst($part);
$text = implode("", $uwords);
echo $text;
?>
ucfirst
vfprintf
Обработка строк


Записывает отформатированную строку в поток

ucwords
vprintf
Обработка строк
PHP Manual

vfprintf

(PHP 5)

vfprintf — Записывает отформатированную строку в поток

Описание

int vfprintf ( resource $handle , string $format , array $args )

Записывает строку, отформатированную в соответствии с параметром format в поток handle.

Данная функция похожа на fprintf(), но принимает не переменное число аргументов, а массив.

Список параметров

handle

format

Описание параметра format смотрите в документации к функции sprintf().

args

Возвращаемые значения

Возвращает длину выведенной строки.

Примеры

Пример #1 vfprintf(): дополнение нулями целых чисел

<?php
if (!($fp = fopen('date.txt', 'w')))
    return;

vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
// запишет дату в формате ISO в date.txt
?>

Смотрите также

  • printf() - Выводит отформатированную строку
  • sprintf() - Возвращает отформатированную строку
  • sscanf() - Разбирает строку в соответствии с заданным форматом
  • fscanf() - Обрабатывает данные из файла в соответствии с форматом
  • vsprintf() - Возвращает отформатированную строку
  • number_format() - Форматирует число с разделением групп

User Contributed Notes

There are no user contributed notes for this page.
ucwords
vprintf
Обработка строк


Выводит отформатированную строку

vfprintf
vsprintf
Обработка строк
PHP Manual

vprintf

(PHP 4 >= 4.1.0, PHP 5)

vprintf — Выводит отформатированную строку

Описание

int vprintf ( string $format , array $args )

Выводит значения массива, отформатированные в соответствии с аргументом format, описанном в документации функции sprintf().

Эта функция подобна printf(), но она принимает не переменное число аргументов, а массив.

Список параметров

format

Описание параметра format смотрите в документации к функции sprintf().

args

Возвращаемые значения

Возвращает длину выведенной строки.

Примеры

Пример #1 vprintf(): дополнение нулями целых чисел

<?php
vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

Смотрите также

  • printf() - Выводит отформатированную строку
  • sprintf() - Возвращает отформатированную строку
  • vsprintf() - Возвращает отформатированную строку

User Contributed Notes

taken from &#34;Php Phrasebook&#34; 15-Jun-2008 10:55
<?php
$string = 'The site runs on PHP '.phpversion();
preg_match('/php ((\d)\.\d\.\d+)/i',$string,$matches);
print_r($matches);
vprintf('Match: %s<br /> Version %s; Major:%d.',$matches);
?>

output:
Array ( [0] => PHP 5.2.5 [1] => 5.2.5 [2] => 5 )
Match: PHP 5.2.5 Version 5.2.5; Major:5.

For preg_match:

If matches  is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1]  will have the text that matched the first captured parenthesized subpattern, and so on.
badcop666 at hotmail dot com 28-Nov-2007 05:38
For blocks of text, sprintf() is slow according to my tests.

Also, having the mapping between place-holders and the list of actual variables or datastructures often makes this code difficult to read. But the printf() family are widely supported and have a huge range of nice features. Performance is a cold mistress though!

From an ease-of-reading and maintenance, debugging point of view, I much prefer HEREDOC and "...{$variable}..." methods.

For a block of HTML markup with place holders, the fastest by far was:-

?>
<div> markup etc<?= $variable ?>more markup
<?

My tests comprised 20 runs of a loop of 1 million iterations with output buffering, ditching the buffer on each loop.

The timings ranged from average 2.1msec/million repetitions for the <?= $var ?> method up to 7.6msec/million using printf().

I'll try some benchmarking tools too, since I just wrote this myself and it could be introducing bias, but they've run on dev servers with low load.

Hopefully interesting.
tehjosh at gamingg dot net 29-Jul-2007 07:19
To toolofthesystem at gmail dot com:

You don't need to use output buffering with vprintf() because you can use vsprintf(), which has the same functionality as vprintf(), except that it returns the resulting string instead of outputting it.
toolofthesystem at gmail dot com 27-Mar-2007 08:42
This function comes useful sometimes when trying to list information returned from MySQL:

function print_sql($query,$printf){
    $sql_sql = mysql_query($query);
    while($sql = mysql_fetch_row($sql_sql)){
        vprintf($printf,$sql);
    }
}

Unfortunately, this seems to sneak its way past output buffering when I tried creating an argument to allow it to be contained in a returned string... either that or I didn't do it right.
soylent at soylentgreens dot com 10-Dec-2006 01:49
I wanted to achieve (something like) this:

<?
$format = "A %s %s %s.\n";

$array1 = Array("monkey", "cow", "rooster");
$array2 = Array("eats", "goes", "crows");
$array3 = Array("bananas", "moo", "in the morning");

printf($format, $array1, $array2, $array3);
?>

Output:
A monkey eats bananas.
A cow goes moo.
A rooster crows in the morning.

but I couldn't find any php function to put in for printf that would work (vprintf comes close).  So I created this little function (and used it to create a select box):

<?

/*
  printf_arrays( string format, [array args[, array ...]] )
*/

function printf_arrays($format) {
    $args = func_get_args();
    array_shift($args); // get rid of format
    for($i=0; $i<count($args[0]); $i++) {
        $pfargs = Array();
        foreach($args as $arr) $pfargs[] = (is_array($arr) && $arr[$i]) ? $arr[$i] : '';
        vprintf($format, $pfargs);
    }
}

$months = Array(
  '01'=>'Jan',
  '02'=>'Feb',
  /* etc. */
);

?>

<select name="month">
  <? printf_arrays('<option value="%s">%s</option>', array_keys($months), array_values($months)) ?>
</select>

Anyone else have any better ideas?  Is there a built-in php function I missed that does this already?
caleb at tekhawk dot com 29-Nov-2006 02:19
i know that you can use %1$s or %3$s to select the first or third string but how can you or can you use array names to select it

something like %'user'$s $'email'$s

i tend to add things to my databases over time and this could save loads of recoding
WebMaestro (asiby at hotmail dot com) 13-Mar-2005 12:40
<?php
$fruits = array(1, 'banana',1, 'apples', 3, 'oranges', 2, 'peaches');

vprintf("I have %d %s, %d %s, %d %s and %d %s.", $fruits);
?>

Output:

I have 1 banana, 1 apples, 3 oranges and 2 peaches.
vfprintf
vsprintf
Обработка строк


Возвращает отформатированную строку

vprintf
wordwrap
Обработка строк
PHP Manual

vsprintf

(PHP 4 >= 4.1.0, PHP 5)

vsprintf — Возвращает отформатированную строку

Описание

string vsprintf ( string $format , array $args )

Эта функция подобна sprintf(), но она принимает не переменное число аргументов, а массив.

Список параметров

format

Описание параметра format смотрите в документации к функции sprintf().

args

Возвращаемые значения

Возвращает значения массива в виде строки, отформатированные в соответствии с параметром format, описанном в документации к функции sprintf().

Примеры

Пример #1 vsprintf(): дополнение нулями целых чисел

<?php
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

Смотрите также

  • sprintf() - Возвращает отформатированную строку
  • vprintf() - Выводит отформатированную строку

User Contributed Notes

strata_ranger at hotmail dot com 29-Jun-2010 11:15
Here's a simple variation on vsprintf() suitable for use with database queries where the results were retrieved as an associative array keyed by column names.

<?php

function dbsprintf($format, $fields, $row)
// $format - sprintf() compatible format string
// $row - Array containing key/value pairs of data
// $fields - Array containing key names (from $row) that are to be used as arguments
{
  // Loop through $fields and insert the corresponding values from $row
  foreach($fields as &$value)
  {
    $value = $row[$value];
  } unset($value);

  // Format the string and return
  return vsprintf($format, $fields);
}

// Some data
$row = Array('id' => '12', 'name' => 'World');

// Outputs "Hello World!"
echo dbsprintf('Hello, %s!', Array('name'), $row);
// Outputs "Hello 12!"
echo dbsprintf('Hello, %s!', Array('id'), $row);

?>
jeppe dot dyrby at gmail dot com 04-Mar-2009 04:52
Heres a new version of the vnsprintf function, i call it dsprintf, but that should matter.

<?php
function dsprintf() {
  $data = func_get_args(); // get all the arguments
  $string = array_shift($data); // the string is the first one
  if (is_array(func_get_arg(1))) { // if the second one is an array, use that
    $data = func_get_arg(1);
  }
  $used_keys = array();
  // get the matches, and feed them to our function
  $string = preg_replace('/\%\((.*?)\)(.)/e',
    'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string);
  $data = array_diff_key($data,$used_keys); // diff the data with the used_keys
  return vsprintf($string,$data); // yeah!
}

function dsprintfMatch($m1,$m2,&$data,&$used_keys) {
  if (isset($data[$m1])) { // if the key is there
    $str = $data[$m1];
    $used_keys[$m1] = $m1; // dont unset it, it can be used multiple times
    return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should
  } else {
    return "%".$m2; // else, return a regular %s, or %d or whatever is used
  }
}
$str = "Hello, %(place)s, how is it hanning at %(place)s? %s works just as well";
$find = array(
  'place' => 'world',
  'sprintf',
  'not used'
);
echo dsprintf($str, $find);
// 'Hello, world, how is it hanning at world? sprintf works just as well'
?>
www dot wesley at gmail dot com 15-Nov-2008 12:02
Here's the new version of vnsprintf()

Thanks to "César Kästli" and "Jan Ulrych"

<?php
function vnsprintf( $format, array $data)
{
    preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    $offset = 0;
    $keys = array_keys($data);
    foreach( $match as &$value )
    {
        if ( ( $key = array_search( $value[1][0], $keys, TRUE) ) !== FALSE || ( is_numeric( $value[1][0] ) && ( $key = array_search( (int)$value[1][0], $keys, TRUE) ) !== FALSE) )
        {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( 1 + $key);
        }
    }
    return vsprintf( $format, $data);
}

$example = array(
    0 => 'first',
    'second' => 'second',
    'third',
    4.2 => 'fourth',
    'fifth',
    -6.7 => 'sixth',
    'seventh',
    'eighth',
    '9' => 'ninth',
    'tenth' => 'tenth',
    '-11.3' => 'eleventh',
    'twelfth'
);

echo vnsprintf( '%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s %10$s %11$s %12$s<br />', $example); // acts like vsprintf
echo vnsprintf( '%+0$s %second$s %+1$s %+4$s %+5$s %-6.5$s %+6$s %+7$s %+9$s %tenth$s %-11.3$s %+10$s<br />', $example);
?>
jan dot ulrych at gmail dot com 14-Jul-2008 01:45
Thanks a lot for vnsprintf function.

However, there is a little bug which occurs only when the  number of parameters in the $data is greater than 10.

The replacement is not performed correctly when two or more replacements should be performed. When the referenced parameter is at position greater or equal to 10 in $data array and it precedes any other referenced parameter in $format string then the subsequent replacement(s) are not performed correctly.

The $offset value should be calculated as
 $offset -= $len - strlen( 1 + $key);

as we substitute string (or float) identifier in the original $format string by value 1 + $key, not $key.
www dot wesley at gmail dot com 16-Jun-2008 01:56
vnsprintf is equal to vsprintf except for associative, signed or floating keys.

vnsprintf supports for example "%assocKey$05d", "%-2$'+10s" and "%3.2$05u", vsprintf doesn't

vnsprintf( '%2$d', $array) [2nd value] is equal to vsprintf( '%2$d', $array) [2nd value]
vnsprintf( '%+2$d', $array) [key = 2] is equal to vnsprintf( '%2.0$d', $array) [key = 2]
vnsprintf( '%+2$d', $array) [key = 2] is different of vsprintf( '%+2$d', $array) [unsupported]

When you use signed or floating keys, vnsprintf searchs for the signed truncated key of the original array

Note¹: vnsprintf does not support for example "%someKeyf" (floating number, key = someKey) or "%+03d" (signed decimal number, key = 3), you should use "%someKey$f" or "%+03$d" respectively.
Note²: "%+03d" (or "%1$+03d") will be interpreted as signed zero-padded decimal number

<?php
function vnsprintf( $format, array $data)
{
    preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    $offset = 0;
    $keys = array_keys($data);
    foreach ( $match as &$value )
    {
        if ( ( $key = array_search( $value[1][0], $keys) ) !== FALSE || ( is_numeric( $value[1][0]) && ( $key = array_search( (int)$value[1][0], $keys) ) !== FALSE ) ) {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( $key);
        }
    }
    return vsprintf( $format, $data);
}

$examples = array(
    2.8=>'positiveFloat',    // key = 2 , 1st value
    -3=>'negativeInteger',    // key = -3 , 2nd value
    'my_name'=>'someString'    // key = my_name , 3rd value
);

echo vsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // [unsupported]
echo vnsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // output : "someString"

echo vsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // output : "negativeInteger"

echo vsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : "negativeInteger"
echo vnsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : [= vsprintf]

echo vsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // output : "negativeInteger"
?>
iisys_ at hotmail dot com 19-Nov-2006 10:29
I've made this simple function for more compatibility with different applications.
As arguments, it can accept an array or single arguments.

<?php
function asprintf() {
    $a = func_get_args();
    $format = array_shift($a);
    if (is_array($a[0])) {
        $a = $a[0];
    }
    return vsprintf($format, $a);
}

# Examples.

$sql_arguments = array('fields' => '*', 'table' => 'users', 'field' => 'user', 'value' => 'exploited');

echo asprintf("SELECT %s FROM %s WHERE %s = '%s'", $sql_arguments);
# Would output: SELECT * FROM users WHERE user = 'exploited'

echo asprintf("SELECT %s FROM %s WHERE %s = '%s'", '*', 'users', 'user', 'exploited');
# Would output the same.
?>
Roadster 30-Sep-2006 07:44
Please note: The same functionality (sortof) can be attained between version 4.0.4 and 4.1.0 using call_user_func_array.

Example:

call_user_func_array("sprintf", $arg)

First element of $arg is the format. This rescued me in a situation where version 4.1.0 wasn't available.
jon at ardentcreative dot co dot uk 17-Feb-2006 03:56
This can be used for quick and dirty internationalization:

<?php
$GLOBALS['strings']['example'] = "There are %d people.";

// Loads a phrase from the translations list in lang/$lang/phrases.php
function t() {
    $args = func_get_args();
    $nArgs = func_num_args();

    $phrase = array_shift($args);
    $nArgs--;

    include_once("../lang/" . lang() . "/phrases.php");
    if (isset($GLOBALS['strings'][$phrase])) {
        return vsprintf($GLOBALS['strings'][$phrase], $args);
    } else {
        return '<span style="color: #ff0000">Untranslated string: ' . $phrase . '</span>';
    }
}
?>
toneee at g mail dot com 19-Dec-2005 09:27
I found this function to be useful for formatting sql queries.

I do something like this:

function sql_build($template, $params = array()) {
  global $sql_templates;
  if (isset($sql_templates[$template])) {
    $sql = vsprintf($sql_templates[$template], $params);
    return $sql;
  }
  return false;
}

// Fetch list of contacts, for a given section id
$sql_templates['contacts_by_section'] = <<<ENDSQL
select
  id,
  name,
  email,
  address,
  photo_id
from
  contacts
where
  section_id = %d
ENDSQL;

You also give yourself an added layer of security on the sql due to the sprintf formatting. For example, using %d will not allow any sql injection for that parameter.
tbS dot P dot A dot M at S dot U dot K dot Staylorbarstow dot com 01-Mar-2005 11:49
Simple but useful routine:

<?php
function vsprintf_iter($fmt,$data) {
    if (!is_array($data)) return false;
    $ret = '';
    foreach ($data as $d) {
        $ret .= vsprintf($fmt,$d);
    }
    return $ret;
}
?>
jed at NOSPAM dot jed dot bz 22-May-2004 06:48
vsprintf() accepts arrays with any keys, so the array_shift() technique is unnecessary when writing a printf-type function. Any parameters you require are easily unset from the array you retrieve with func_get_args():

<?php

function mysprintf($format) {
    $args = func_get_args();
    unset($args[0]); /* get rid of "$format" */
    return vsprintf($format, $args);
}

/* I use this technique in production code as follows: */
function logf($target, $string) {
    $args = func_get_args();
    unset($args[0], $args[1]);
    fprintf($GLOBALS['config']['logtargets'][$target],
        "[%s] %s\n", date('H:i'), wordwrap(vsprintf($string, $args), 75, '\n\r '));
}

/* e.g.:
    logf(DEBUG, "Oops! %s", mysql_error());
 */

?>

array_shift() and other costly array operations aren't required, as far as I know. I could be wrong.
drm at melp dot nl 29-Jan-2004 09:02
When combining with func_get_args as above, you might want to consider using array_shift:

<?
function someFunc () {
   $args = func_get_args ();
   $format = array_shift ( $args );
   // do something
   return vsprintf ( $format, $args );
}
?>

keeps it clean ;)
samviseNOSPAM at hobbitonNOSPAM dot it 02-Jul-2002 06:55
i wrote a short function that make use of vsprintf. It is useful in first coding/debugging of php scripts, because it is called like a simple printf and it display in italic (you can change it of course ;-) ) every debug messages, making it easy to remove them when your code is ready.

here goes :

<?php
function printd() {
        $debug_array=func_get_args();
        $debug_numargs=func_num_args();
        $debug_fmt=$debug_array[0];
        for ( $i = 0 ; $i < $debug_numargs ; $i++ )
                $debug_array[$i] = $debug_array[$i+1];
        $debug_text=vsprintf($debug_fmt, $debug_array);
        printf("--> debug <i>%s</i>\n",
                $debug_text);
}
?>
vprintf
wordwrap
Обработка строк


Переносит строку по указанному количеству символов

vsprintf
Расширения, относящиеся к переменным и типам
Обработка строк
PHP Manual

wordwrap

(PHP 4 >= 4.0.2, PHP 5)

wordwrap — Переносит строку по указанному количеству символов

Описание

string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

Переносит строку по указанному количеству символов.

Список параметров

str

Входная строка.

width

Допустимая ширина строки.

break

Символ переноса строки можно указать с помощью необязательного параметра break.

cut

Если параметр cut установлен в TRUE, строка всегда будет переноситься на указанной ширине или раньше. Поэтому, если исходная строка содержит слово длиннее заданной ширины строки, то оно будет разорвано. (Смотрите второй пример).

Возвращаемые значения

Возвращает строку, с вставленными символами переноса на указанной ширине.

Список изменений

Версия | Описание
4.0.3 | Добавлен необязательный параметр cut.

Примеры

Пример #1 Пример использования wordwrap()

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

Результат выполнения данного примера:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Пример #2 Пример использования wordwrap()

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";
?>

Результат выполнения данного примера:

A very
long
wooooooo
ooooord.

Смотрите также

  • nl2br() - Вставляет HTML-код разрыва строки перед каждым переводом строки
  • chunk_split() - Разбивает строку на фрагменты

User Contributed Notes

ytwguru at gmail dot com 01-May-2012 11:01
I've seen a few solutions to the same problem.  Here's a solution to breaking long text with a space.  In this case it breaks after matching 27 characters.

$content = preg_replace("/([^\s]{27})/", "$1 ", $content);

You can probably write a function for this...
ju1ius 18-Feb-2012 03:58
Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.

<?php
function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
{
  if($cut) {
    // Match anything 1 to $width chars long followed by whitespace or EOS,
    // otherwise match anything $width chars long
    $search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
    $replace = '$1$2'.$break;
  } else {
    // Anchor the beginning of the pattern with a lookahead
    // to avoid crazy backtracking when words are longer than $width
    $pattern = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
    $replace = '$1'.$break;
  }
  return preg_replace($search, $replace, $string);
}
?>
Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input.
mail at dasprids dot de 08-Oct-2011 05:35
A completly working, multibyte-safe, version of wordwrap (as I contributed it to the Zend Framework in Zend_Text_MultiByte). It's mostly a port of the original PHP wordwrap function, backed by a lot of unit tests:

<?php
/**
 * Word wrap
 *
 * @param  string  $string
 * @param  integer $width
 * @param  string  $break
 * @param  boolean $cut
 * @param  string  $charset
 * @return string
 */
function iconv_wordwrap($string, $width = 75, $break = "\n", $cut = false, $charset = 'utf-8')
{
    $stringWidth = iconv_strlen($string, $charset);
    $breakWidth  = iconv_strlen($break, $charset);

    if (strlen($string) === 0) {
        return '';
    } elseif ($breakWidth === null) {
        throw new Zend_Text_Exception('Break string cannot be empty');
    } elseif ($width === 0 && $cut) {
        throw new Zend_Text_Exception('Can\'t force cut when width is zero');
    }

    $result    = '';
    $lastStart = $lastSpace = 0;

    for ($current = 0; $current < $stringWidth; $current++) {
        $char = iconv_substr($string, $current, 1, $charset);

        if ($breakWidth === 1) {
            $possibleBreak = $char;
        } else {
            $possibleBreak = iconv_substr($string, $current, $breakWidth, $charset);
        }

        if ($possibleBreak === $break) {
            $result    .= iconv_substr($string, $lastStart, $current - $lastStart + $breakWidth, $charset);
            $current   += $breakWidth - 1;
            $lastStart  = $lastSpace = $current + 1;
        } elseif ($char === ' ') {
            if ($current - $lastStart >= $width) {
                $result    .= iconv_substr($string, $lastStart, $current - $lastStart, $charset) . $break;
                $lastStart  = $current + 1;
            }

            $lastSpace = $current;
        } elseif ($current - $lastStart >= $width && $cut && $lastStart >= $lastSpace) {
            $result    .= iconv_substr($string, $lastStart, $current - $lastStart, $charset) . $break;
            $lastStart  = $lastSpace = $current;
        } elseif ($current - $lastStart >= $width && $lastStart < $lastSpace) {
            $result    .= iconv_substr($string, $lastStart, $lastSpace - $lastStart, $charset) . $break;
            $lastStart  = $lastSpace = $lastSpace + 1;
        }
    }

    if ($lastStart !== $current) {
        $result .= iconv_substr($string, $lastStart, $current - $lastStart, $charset);
    }

    return $result;
}
?>
paul at preinheimer dot com 25-Sep-2011 04:04
If your goal is to allow a browser to word-wrap nicely, while maintaining a fluid layout, you'll want to break with: &#8203

It's a zero width space character: http://en.wikipedia.org/wiki/Zero-width_space

This way the browser can break where it needs to, without adding a visual distraction of spaces within the text.

e.g.
<?php
//Using &#8203; here allows the browser to break the line of text, without the visual distraction.
$line = wordwrap($line, 10, "&#8203;", true);
?>

#PROTIP: leave a comment, so the next person to read your code has a clue what you've done.
info at hsdn dot org 08-Jul-2011 08:41
Wordwrap with UTF-8 supports, returns as array.

<?php

function mb_wordwrap_array($string, $width)
{
    if (($len = mb_strlen($string, 'UTF-8')) <= $width)
    {
        return array($string);
    }

    $return = array();
    $last_space = FALSE;
    $i = 0;

    do
    {
        if (mb_substr($string, $i, 1, 'UTF-8') == ' ')
        {
            $last_space = $i;
        }

        if ($i > $width)
        {
            $last_space = ($last_space == 0) ? $width : $last_space;

            $return[] = trim(mb_substr($string, 0, $last_space, 'UTF-8'));
            $string = mb_substr($string, $last_space, $len, 'UTF-8');
            $len = mb_strlen($string, 'UTF-8');
            $i = 0;
        }

        $i++;
    }
    while ($i < $len);

    $return[] = trim($string);

    return $return;
}

?>
dynastoned 08-Jun-2011 05:08
I wrote this because people leaving comments would spam or make words that were too long and it was breaking the tables in my design.

So for instance if someone wanted to type "hahahhahahahhahahhahahhahahhahahahhaha" it would go past the specified table width and break the design.

To curb this problem I needed a way to break words that were longer than 15 characters in length.  So I figured if I added a space every 15 characters that would solve my problem.  This is how I did it.

Example:

<?php

// comment the user left
$comment = "hi im here to break your page bahahahhahahhahhahhahahha.  i hope this makes you mad lolllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll.";

// breaking down each word in the $comment into arrays using explode().
$array = explode(" ", $comment);

// here i used the for loop to enable me to run each word one by one through wordwrap() and add a space into the word if it is longer than 15 characters.
for ($i = 0, $array_num = count($array); $i < $array_num; $i++) {
    $word_split = wordwrap($array[$i], 15, " ", true);
    echo "$word_split ";
}

// result = hi im here to break your page bahahahhahahhah hahhahahha. i hope this makes you mad lolllllllllllll lllllllllllllll lllllllllllllll lllllllllllllll lllllllll.

?>
mulllhausen 28-Apr-2011 12:16
here is another function acts like wordwrap but ignores html tags. it basically takes out all the tags from the string, wordwrappes the string, then puts the tags back in. enjoy ;)

<?php

function html_wordwrap($str, $width = 75, $break = "\n", $cut = false)
{
    //same functionality as wordwrap, but ignore html tags
    $unused_char = find_unused_char($str); //get a single character that is not used in the string
    $tags_arr = get_tags_array($str);
    $q = '?';
    $str1 = ''; //the string to be wrapped (will not contain tags)
    $element_lengths = array(); //an array containing the string lengths of each element
    foreach($tags_arr as $tag_or_words)
    {
        if(preg_match("/<.*$q>/", $tag_or_words)) continue;
        $str1 .= $tag_or_words;
        $element_lengths[] = strlen($tag_or_words);
    }
    $str1 = wordwrap($str1, $width, $unused_char, $cut);
    foreach($tags_arr as &$tag_or_words)
    {
        if(preg_match("/<.*$q>/", $tag_or_words)) continue;
        $tag_or_words = substr($str1, 0, $element_lengths[0]);
        $str1 = substr($str1, $element_lengths[0]);
        array_shift($element_lengths); //delete the first array element - we have used it now so we do not need it
    }
    $str2 = implode('', $tags_arr);
    $str3 = str_replace($unused_char, $break, $str2);
    return $str3;
}
function get_tags_array($str)
{
    //given a string, return a sequential array with html tags in their own elements
    $q = '?';
    return preg_split("/(<.*$q>)/",$str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
}
function find_unused_char($str)
{
    //find an unused character in a string
    $possible_chars = array('|', '!', '@', '#', '$', '%', '^', '&', '*', '~');
    foreach($possible_chars as $char) if(strpos($str, $char) === false) return $char;
    die('you must add another SINGLE unused character, not one of [|!@#$%^&*~], to the $possible_chars array in function find_unused_char');
}

?>
altin_bardhi at yahoo dot co dot uk 27-Jan-2011 04:03
Here I have come out with a possibly very useful wordwrap code snippet.

Apparently what this piece of code does is: it takes the entered text and looks for words longer than the defined ‘$chunk_length’ if it finds any, it splits the long words and then it concatenates the whole string back to a new string with longer words separated by a dash character in this case.

After it has accomplished this task it then inserts an HTML line break after a specified ‘$line_length’ (Depending on your containers width requirements)

<?php

//Start function explode_ wrap
function explode_wrap($text, $chunk_length, $line_length){

//Explode all the words separated by spaces in a string
$string_chunks = explode(' ', $text);

// Get each split word from the array $sring_chunks_array => key => value
foreach ($string_chunks as $chunk => $value) {

if(strlen($value) >= $chunk_length){

//Split the chunks/words which are longer than $chunk_length
$new_string_chunks[$chunk] = chunk_split($value, $chunk_length, ' - ');

}else {

//Do not split the normal length words
$new_string_chunks[$chunk] = $value;

}

}//End foreach loop

//Concatenate back the all the words
$new_text=implode(' ', $new_string_chunks);

return wordwrap($new_text, $line_length, '<br />');

}//End function

?>
holdoffhunger at gmail dot com 12-Dec-2010 09:47
Say you have a string you want to output to the user, but you want to wordwrap the words with WBR and ampersand-shy-semicolon tags.  This will cause the word to break in half in HTML, instead of causing the page to be huge in width.  This is extremely useful for displaying full link URLs, as many of them run on forever, and in PHP-BB, that means an entire thread will look ugly, because of one guy posting a link.  On the other hand, both the WBR and ampersand-shy-semicolon tags ignore any spaces near them.  That means, if you parsed all your PHP-BB inputted data, a sentence would like this: "Thisisasentence."  It effectively cuts out the spaces.  The solution?  Do an str_replace, finding every " " (one space) and replacing it with ("  ") spaces, and then wordwrap the entire string with WBR/shy tags, every four spaces.  This guarantees that spaces within HTML will be recognized properly in all browsers, while also guaranteeing that no words will fail to wordwrap.
nbenitezl[arroba]gmail[dot]com 02-Dec-2010 04:56
Hi, this function is like wordwrap but it ignores html tags, it works like wordwrap when called with fourth parameter as true. It's based on a function I find here but improved to closer match the output of wordwrap (i.e. removed spaces at start of line) and also to improve performance.

Hope it can be useful for you :-)
<?php
function htmlwrap(&$str, $maxLength, $char='<br />'){
    $count = 0;
    $newStr = '';
    $openTag = false;
    $lenstr = strlen($str);
    for($i=0; $i<$lenstr; $i++){
        $newStr .= $str{$i};
        if($str{$i} == '<'){
            $openTag = true;
            continue;
        }
        if(($openTag) && ($str{$i} == '>')){
            $openTag = false;
            continue;
        }
        if(!$openTag){
            if($str{$i} == ' '){
                if ($count == 0) {
                    $newStr = substr($newStr,0, -1);
                    continue;
                } else {
                    $lastspace = $count + 1;
                }
            }
            $count++;
            if($count==$maxLength){
                if ($str{$i+1} != ' ' && $lastspace && ($lastspace < $count)) {
                    $tmp = ($count - $lastspace)* -1;
                    $newStr = substr($newStr,0, $tmp) . $char . substr($newStr,$tmp);
                    $count = $tmp * -1;
                } else {
                    $newStr .= $char;
                    $count = 0;
                }
                $lastspace = 0;
            }
        }
    }

    return $newStr;
}
?>
venimus at gmail dot com 09-Sep-2010 02:21
To cut long texts up to certain length without breaking words you can use this simple function

<?php

function cutstr($str, $length, $ellipsis=''){
   $cut=(array)explode('\n\n',wordwrap($str),$length,'\n\n'));
   return $cut[0].((strlen($cut)<strlen($str))?$ellipsis:'');
}

?>

Third parameter is added to the output string if it was cut, usually you should use '...'
Sam B 02-Jul-2010 08:41
The multibyte wordwrap functions in the comments all seem to break in the middle of word.  This one should break on spaces, where possible.

<?php
/**
 * Multibyte capable wordwrap
 *
 * @param string $str
 * @param int $width
 * @param string $break
 * @return string
 */
function mb_wordwrap($str, $width=74, $break="\r\n")
{
    // Return short or empty strings untouched
    if(empty($str) || mb_strlen($str, 'UTF-8') <= $width)
        return $str;

    $br_width  = mb_strlen($break, 'UTF-8');
    $str_width = mb_strlen($str, 'UTF-8');
    $return = '';
    $last_space = false;

    for($i=0, $count=0; $i < $str_width; $i++, $count++)
    {
        // If we're at a break
        if (mb_substr($str, $i, $br_width, 'UTF-8') == $break)
        {
            $count = 0;
            $return .= mb_substr($str, $i, $br_width, 'UTF-8');
            $i += $br_width - 1;
            continue;
        }

        // Keep a track of the most recent possible break point
        if(mb_substr($str, $i, 1, 'UTF-8') == " ")
        {
            $last_space = $i;
        }

        // It's time to wrap
        if ($count > $width)
        {
            // There are no spaces to break on!  Going to truncate :(
            if(!$last_space)
            {
                $return .= $break;
                $count = 0;
            }
            else
            {
                // Work out how far back the last space was
                $drop = $i - $last_space;

                // Cutting zero chars results in an empty string, so don't do that
                if($drop > 0)
                {
                    $return = mb_substr($return, 0, -$drop);
                }

                // Add a break
                $return .= $break;

                // Update pointers
                $i = $last_space + ($br_width - 1);
                $last_space = false;
                $count = 0;
            }
        }

        // Add character from the input string to the output
        $return .= mb_substr($str, $i, 1, 'UTF-8');
    }
    return $return;
}
?>
Ivan Lisnik 11-Jun-2010 03:26
here is my example of UTF-8 wordwrap
<?php
function wordwrap($str, $width, $break)
{
    $return = '';
    $br_width = mb_strlen($break, 'UTF-8');
    for($i = 0, $count = 0; $i < mb_strlen($str, 'UTF-8'); $i++, $count++)
    {
        if (mb_substr($str, $i, $br_width, 'UTF-8') == $break)
        {
            $count = 0;
            $return .= mb_substr($str, $i, $br_width, 'UTF-8');
            $i += $br_width - 1;
        }

        if ($count > $width)
        {
            $return .= $break;
            $count = 0;
        }

        $return .= mb_substr($str, $i, 1, 'UTF-8');
    }

    return $return;
}
?>
kouber at php dot net 27-May-2010 02:34
If you need a function to cut only words longer than N characters, feel free to use the function below:

<?php
function wrap($str, $width=75, $break="\n") {
  return preg_replace('#(\S{'.$width.',})#e', "chunk_split('$1', ".$width.", '".$break."')", $str);
}

echo wrap('aaaa bbb cc dddd-dddd', 3, ' ');
?>

The above example will output: "aaa a  bbb  cc ddd d-d ddd "
Lourvestruck at hotmail dot com 16-Apr-2010 02:19
I have a page with an image floating on the right, and text printed out beside the image (to the left). I used wordwrap to wrap the text so that it doesn't go over the image, but sometimes the text would go down beyond the image (vertically beyond the image, where the height of the text was more than the height of the image), resulting in wrapped text that doesn't need to be wrapped. So I came up with this method that takes a number max-lines to wordwrap, and then the rest either no wrapping, or wordwrapping at a different number of characters:

<?php
// Wrap the text so it fits within the 35c width (to fit beside the picture)
$text = wordwrap($text, 35, "<br/>");

// The text comes below the picture, where we want wrapping to stop...
$maxLines = 18;
$newWidth = 80;
$lastPos = 1;
for ($i=0;$i<$maxLines;$i++)
{
    $lastPos = strpos($text, '<br/>', $lastPos+1);
    if ($lastPos === FALSE)
        break;
}

$text = substr($text, 0, $lastPos) . "<br/>" . wordwrap(str_replace('<br/>',' ',substr($text, $lastPos)), $newWidth, '<br/>');

print $text;
?>
homer2k at gmx dot net 30-Mar-2010 04:31
A function that considers URIs.
<?php
function wordwrapURI($str, $width = 75, $break = "\n", $cut = false)
{
    $newText = array();
    $words = explode(' ', str_replace("\n", "\n ", $str));
    foreach($words as $word) {
        if(strpos($word, 'http://') === false && strpos($word, 'www.') === false) {
            $word = wordwrap($word, $width, $break, $cut);
        }
        $newText[] = $word;
    }
    return implode(' ', $newText);
}
?>
mary dot kalinosky at thieme dot com 18-Nov-2009 03:29
I wish there were a word_unwrap() function, but this seems to work:

<?php $text = preg_replace('/[\t\r\n]+/', ' ', $text); ?>
andrnag at yandex dot ru 05-Nov-2009 10:28
This is a really working multibite wordwrap function. Teted on utf-8 English and Russian strings. It's a compilation on other functions represented here.
<?php
   function utf8_wordwrap($str, $width = 75, $break = "\n") // wordwrap() with utf-8 support
    {
        $str =  preg_split('/([\x20\r\n\t]++|\xc2\xa0)/sSX', $str, -1, PREG_SPLIT_NO_EMPTY);
        $len = 0;
        foreach ($str as $val)
        {
            $val .= ' ';
            $tmp = mb_strlen($val, 'utf-8');
            $len += $tmp;
            if ($len >= $width)
            {
                $return .= $break . $val;
                $len = $tmp;
            }
            else
                $return .= $val;
        }
        return $return;
    }
?>
ojs-hp at web dot de 30-Oct-2009 10:06
After I got some problems with my function to convert a BB-text into HTML. Long words didn't really fit into the layout and only wordwarp() also added breaks to words which would fit into the layout or destroy the other HTML-tags....
So this is my solution. Only words with strlen() >= 40 are edited with wordwarp().

<?php
function bb2html($bb) {
        $words= explode(' ', $bb); // string to array
    foreach ($words as $word) {
        $break = 0;
        for ($i = 0; $i < strlen($word); $i++) {
            if ($break >= 40) {
                $word= wordwrap($word, 40, '-<br>', true); //add <br> every 40 chars
                $break = 0;
            }
            $break++;

        }
        $newText[] = $word; //add word to array
    }
    $bb = implode(' ', $newText); //array to string
    return $bb;
}
?>
starfantasy84 at hotmail dot com 29-Jul-2009 10:16
I tried using mb functions to word wrap 10 long strings (200 unicode utf8 chars) and I hit execution timeout error. After searching and testing, I came up with this simple and fast function for unicode word wrap.

<?php
//function to break up strings without whitespace chars in between
//if $cut is true then strings will be forcefully break up even there are whitespace in between.
function unicode_wordwrap($str, $len=50, $break=" ", $cut=false){
    if(empty($str)) return "";

    $pattern="";
    if(!$cut)
        $pattern="/(\S{".$len."})/u";
    else
        $pattern="/(.{".$len."})/u";

    return preg_replace($pattern, "\${1}".$break, $str);
}
?>
Marcin Dobruk [zuku3000 at yahoo dot co dot uk] 15-Jun-2009 02:21
Word wrap from left to right (standard) and from right to left.

<?php
function myWordWrap ($string, $length=3, $wrap=',', $from='left') {
    if ($from=='left') $txt=wordwrap($string, $length, $wrap, true);
    if ($from=='right') {
        // string to array
        $arr_l=array();
        for ($a=0;strlen($string)>$a;$a++) $arr_l[$a]=$string{$a};
        // reverse array
        $arr_r=array_reverse($arr_l);
        // array to string
        $string_r='';
        foreach ($arr_r as $arr_line => $arr) $string_r.=$arr;
        // add wrap to reverse string
        $string_r=wordwrap($string_r, $length, $wrap, true);
        // reverse string to array
        $arr_r=array();
        for ($a=0;strlen($string_r)>$a;$a++) $arr_r[]=$string_r{$a};
        // reverse array again
        $arr_l=array_reverse($arr_r);
        // string with wrap
        $txt='';
        foreach ($arr_l as $arr_line => $arr) $txt.=$arr;
        }
    return $txt;
    }
?>
r dot hartung at roberthartung dot de 23-Mar-2009 04:26
I was wondering about my CMS to break up code but only non-HTML code - I didn't found anything so I came up with this little solution:

<?php
function wordWrapIgnoreHTML($string, $length = 45, $wrapString = "\n")
   {
     $wrapped = '';
     $word = '';
     $html = false;
     $string = (string) $string;
     for($i=0;$i<strlen($string);$i+=1)
     {
       $char = $string[$i];

       /** HTML Begins */
       if($char === '<')
       {
         if(!empty($word))
         {
           $wrapped .= $word;
           $word = '';
         }

         $html = true;
         $wrapped .= $char;
       }

       /** HTML ends */
       elseif($char === '>')
       {
         $html = false;
         $wrapped .= $char;
       }

       /** If this is inside HTML -> append to the wrapped string */
       elseif($html)
       {
         $wrapped .= $char;
       }

       /** Whitespace characted / new line */
       elseif($char === ' ' || $char === "\t" || $char === "\n")
       {
         $wrapped .= $word.$char;
         $word = '';
       }

       /** Check chars */
       else
       {
         $word .= $char;

         if(strlen($word) > $length)
         {
           $wrapped .= $word.$wrapString;
           $word = '';
         }
       }
     }

    if($word !== ''){
        $wrapped .= $word;
    }

     return $wrapped;
   }

$str = '<a href="http://www.example.de">';
$str .= 'Test-STRRRRRRRRRRRRRRRRRRIIIIIIIIIIIIIIIIIIIIIIING</a>';
$str .= '<!-- COMMENT_INSIDE_ANOTHER';
$str .= '_LONG_STRING //-->';

echo wordWrapIgnoreHTML($str, 25, '[BREAK]');

// Output: <a href="http://www.roberthartung.de">
// Test-STRRRRRRRRRRRRRRRRRRI[BREAK]
// IIIIIIIIIIIIIIIIIIIIIING
// </a><!-- ... //-->
?>

[NOTE BY danbrown AT php DOT net: Contains a bug fix provided by (jaw AT condidact DOT dk) on 02-APR-09 to address an issue where "the last word in a non-html-wrapped string will be omitted."]
Matt at newbiewebdevelopment dot idk 04-Mar-2009 01:53
My version of multibyte wordwrap

<?php
function mb_wordwrap($string, $width=75, $break="\n", $cut = false) {
    if (!$cut) {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.',}\b#U';
    } else {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
    }
    $string_length = mb_strlen($string,'UTF-8');
    $cut_length = ceil($string_length / $width);
    $i = 1;
    $return = '';
    while ($i < $cut_length) {
        preg_match($regexp, $string,$matches);
        $new_string = $matches[0];
        $return .= $new_string.$break;
        $string = substr($string, strlen($new_string));
        $i++;
    }
    return $return.$string;
}

$mb_string = "こんにちは";//Hello in Japanese
$cut_mb_string = mb_wordwrap($mb_string,1," ",true); //こ ん に ち は
print($cut_mb_string);
?>
admin at studio-gepard dot pl 09-Dec-2008 05:09
<?php
function substr_word($str, $start, $end) {
    //function taking sub string from $str in between $start chars and $end chars.

    $String = wordwrap($str, ($end - $start), '[cut]', false);   //add [cut] for each word after $end chars
    $ExplodedString = explode('[cut]', $String);      //make an array with elements long for $end chars
    $end=ceil(strlen($text)/$end);   //how many elements of array are there. (celi > round >floor)

    $i=floor($end/$start);                            //take an element with start position

    $String = $ExplodedString[$i];
    if ($String[0]==" ") { substr($String, 1); } if ($String[0]==" ") { substr($String, 1); } if ($String[0]==" ") { substr($String, 1); }

    return $String;
}
?>
Usage example:
<?php

   $from=strpos($text,$word)-100;
   $to=strpos($text,$word)+400;
   $text=substrpos($text, $from, $to);

?>
will return text 100 chars before and 400 chars after searched word without breaking the words in text.
Good for seach scirpts for your website - imagine that $word is keyword you search for.

[NOTE BY danbrown AT php DOT net:  Contains a fix provided by (admin AT studio-gepard DOT pl).]
php at maranelda dot org 16-Sep-2008 04:17
Anyone attempting to write a text email client should be aware of the following:

<?php

$a = "some text that must wrap nice";

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that must
//  wrap nice

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that
//  must
//  wrap
//  nice

?>

Subsequent uses of wordwrap() on already wrapped text will take the end-of-line characters into account when working out line length, thus reading each line that just fit nicely the first time around as being one character too long the second. This can be a problem when preparing a text email that contains (eg.) a forwarded email which has already been word-wrapped.

Solutions below which explode() the text on end-of-lines and wordwrap() the resulting strings separately take care of this nicely.
mn_nospamplz_bayazit at g_mail dot com 30-Aug-2008 06:21
This should wrap long lines of code, maintaining the proper level of indentation, plus an extra tab to indicate it's been wrapped.

<?php
function codewrap($code, $maxLength = 80)
{
    $lines = explode("\n", $code);
    $count = count($lines);
    for($i=0; $i<$count; ++$i) {
        preg_match('`^\s*`', $code, $matches);
        $lines[$i] = wordwrap($lines[$i], $maxLength, "\n$matches[0]\t");
    }
    return implode("\n", $lines);
}
?>
mathijs DOT van DOT veluw AT SMScity.com 28-May-2008 04:56
I needed an UTF8/Unicode compatible wordwrap with the same features.
As i searched the internet several times, and havent found anything. I created one my self.

<?php
    public static function utf8Wordwrap($str, $width=75, $break="\n", $cut=false)
    {
        $splitedArray    = array();
        $lines            = explode("\n", $str);
        foreach ($lines as $line) {
            $lineLength = strlen($line);
            if ($lineLength > $width) {
                $words = explode("\040", $line);
                $lineByWords = '';
                $addNewLine = true;
                foreach ($words as $word) {
                    $lineByWordsLength        = strlen($lineByWords);
                    $tmpLine                = $lineByWords.((strlen($lineByWords) !== 0) ? ' ' : '').$word;
                    $tmplineByWordsLength    = strlen($tmpLine);
                    if ($tmplineByWordsLength > $width && $lineByWordsLength <= $width && $lineByWordsLength !== 0) {
                        $splitedArray[]    = $lineByWords;
                        $lineByWords    = '';
                    }

                    $newLineByWords            = $lineByWords.((strlen($lineByWords) !== 0) ? ' ' : '').$word;
                    $newLineByWordsLength    = strlen($newLineByWords);
                    if ($cut && $newLineByWordsLength > $width) {
                        for ($i = 0; $i < $newLineByWordsLength; $i = $i + $width) {
                            $splitedArray[] = mb_substr($newLineByWords, $i, $width);
                        }
                        $addNewLine = false;
                    } else {
                        $lineByWords = $newLineByWords;
                    }
                }
                if ($addNewLine) {
                    $splitedArray[] = $lineByWords;
                }
            } else {
                $splitedArray[] = $line;
            }
        }
        return implode($break, $splitedArray);
    }
?>

Hope someone else can use this also.
(Also all improvements are welcome)
admin at jcink dot com 25-Apr-2008 01:56
I wanted something that would word wrap just one word. People were doing ffffffffffffffffff in my comments page on my site, annoyingly stretching the page. but I didn't want to wrap at a certain fixed length, just wanted to break up words like that only. Here's what I came up with if anyone wants it.

<?php
function one_wordwrap($string,$width){
  $s=explode(" ", $string);
  foreach ($s as $k=>$v) {
    $cnt=strlen($v);
    if($cnt>$width) $v=wordwrap($v, $width, "<br />", true);
      $new_string.="$v ";
  }
  return $new_string;
}
?>
$del=' at '; 'sanneschaap' dot $del dot 'gmail dot com' 17-Apr-2008 01:41
These functions let you wrap strings comparing to their actual displaying width of proportional font. In this case Arial, 11px. Very handy in some cases since CSS3 is not yet completely supported. 100 strings = ~5 ms

My old sheep word wrap function (posted at the bottom of this page, is kinda old dated and this one is faster and more accurate).

<?php
//the width of the biggest char @
$fontwidth = 11;

//each chargroup has char-ords that have the same proportional displaying width
$chargroup[0] = array(64);
$chargroup[1] = array(37,87,119);
$chargroup[2] = array(65,71,77,79,81,86,89,109);
$chargroup[3] = array(38,66,67,68,72,75,78,82,83,85,88,90);
$chargroup[4] = array(35,36,43,48,49,50,51,52,53,54,55,56,57,60,61,62,63, 69,70,76,80,84,95,97,98,99,100,101,103,104,110,111,112, 113,115,117,118,120,121,122,126);
$chargroup[5] = array(74,94,107);
$chargroup[6] = array(34,40,41,42,45,96,102,114,123,125);
$chargroup[7] = array(44,46,47,58,59,91,92,93,116);
$chargroup[8] = array(33,39,73,105,106,108,124);

//how the displaying width are compared to the biggest char width
$chargroup_relwidth[0] = 1; //is char @
$chargroup_relwidth[1] = 0.909413854;
$chargroup_relwidth[2] = 0.728241563;
$chargroup_relwidth[3] = 0.637655417;
$chargroup_relwidth[4] = 0.547069272;
$chargroup_relwidth[5] = 0.456483126;
$chargroup_relwidth[6] = 0.36589698;
$chargroup_relwidth[7] = 0.275310835;
$chargroup_relwidth[8] = 0.184724689;

//build fast array
$char_relwidth = null;
for ($i=0;$i<count($chargroup);$i++){
    for ($j=0;$j<count($chargroup[$i]);$j++){
        $char_relwidth[$chargroup[$i][$j]] = $chargroup_relwidth[$i];
    }
}

//get the display width (in pixels) of a string
function get_str_width($str){
    global $fontwidth,$char_relwidth;
    $result = 0;
    for ($i=0;$i<strlen($str);$i++){
        $result += $char_relwidth[ord($str[$i])];
    }
    $result = $result * $fontwidth;
    return $result;
}

//truncates a string at a certain displaying pixel width
function truncate_str_at_width($str, $width, $trunstr='...'){
    global $fontwidth,$char_relwidth;
    $trunstr_width = get_str_width($trunstr);
    $width -= $trunstr_width;
    $width = $width/$fontwidth;
    $w = 0;
    for ($i=0;$i<strlen($str);$i++){
        $w += $char_relwidth[ord($str[$i])];
        if ($w > $width)
            break;
    }
    $result = substr($str,0,$i).$trunstr;
    return $result;
    // texas is the reason rules at 10am :)
}
?>
joachim 16-Apr-2008 02:42
There seems to be a difference between php 5.1 and 5.2 in how wordwrap counts characters (all on Mac OSX 10.5.2):

/Applications/MAMP/bin/php5/bin/php --version
PHP 5.1.6 (cli) (built: Sep  8 2006 10:25:04)

/Applications/MAMP/bin/php5/bin/php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft
(50)_UT

php --version
PHP 5.2.5 (cli) (built: Feb 20 2008 12:30:47)

php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft (50)_UT
thomas at tgohome dot com 19-Feb-2008 12:21
I wrote a justification function for a project of mine. It uses the wordwrap function and provides four justification options:

* Left; typically, the leftmost words receive the most padding
* Right; vice versa; the rightmost words receive the most padding
* Both; tries to evenly distribute the padding among leftmost and rightmost words
* Average; most complicated, uses an average of the three previous algorithms. I'd say this one produces the best result as it's more distributed in the center.

It does not justify the last line.

<?php
define('JPAD_LEFT', 1);     // More spaces are added on the left of the line
define('JPAD_RIGHT', 2);    // More spaces are added on the right of the line
define('JPAD_BOTH', 4);     // Tries to evenly distribute the padding
define('JPAD_AVERAGE', 8);  // Tries to position based on a mix of the three algorithms

function justify($input, $width, $mode = JPAD_AVERAGE)
{
    // We want to have n characters wide of text per line.
    // Use PHP's wordwrap feature to give us a rough estimate.
    $justified = wordwrap($input, $width, "\n", false);
    $justified = explode("\n", $justified);

    // Check each line is the required width. If not, pad
    // it with spaces between words.
    foreach($justified as $line)
    {
        if(strlen($line) != $width)
        {
            // Split by word, then glue together
            $words = explode(' ', $line);
            $diff  = $width - strlen($line);

            while($diff > 0)
            {
                // Process the word at this diff
                if     ($mode == JPAD_BOTH)  $words[$diff / count($words)] .= ' ';
                else if($mode == JPAD_AVERAGE)
                    $words[(($diff / count($words)) +
                            ($diff % count($words)) +
                            (count($words) - ($diff % count($words))))
                            / 3] .= ' ';
                else if($mode == JPAD_LEFT)  $words[$diff % count($words)] .= ' ';
                else if($mode == JPAD_RIGHT) $words[count($words) - ($diff % count($words))] .= ' ';

                // Next diff, please...
                $diff--;
            }
        }
        else
        {
            $words = explode(' ', $line);
        }

        $final .= implode(' ',  $words) . "\n";
    }

    // Return the final string
    return $final;
}
?>

Examples of output for the average algorithm:

Lorem ipsum dolor            sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud  exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in    reprehenderit in voluptate velit
esse cillum dolore       eu fugiat nulla pariatur.
Excepteur sint occaecat    cupidatat non proident,
sunt in culpa qui  officia deserunt mollit anim id
est laborum.

(50 characters wide)
golanzakaiATpatternDOTcoDOTil 07-Oct-2007 10:39
<?php
    /**
     * Wordwrap without unnecessary word splitting using multibyte string functions
     *
     * @param string $str
     * @param int $width
     * @param string $break
     * @return string
     * @author Golan Zakai <golanzakaiATpatternDOTcoDOTil>
     */
    function _wordwrap( $str, $width, $break ) {
        $formatted = '';
        $position = -1;
        $prev_position = 0;
        $last_line = -1;

        /// looping the string stop at each space
        while( $position = mb_stripos( $str, " ", ++$position, 'utf-8' ) ) {
            if( $position > $last_line + $width + 1 ) {
                $formatted.= mb_substr( $str, $last_line + 1, $prev_position - $last_line - 1, 'utf-8' ).$break;
                $last_line = $prev_position;
            }
            $prev_position = $position;
        }

        /// adding last line without the break
        $formatted.= mb_substr( $str, $last_line + 1, mb_strlen( $str ), 'utf-8' );
        return $formatted;
    }
?>
fatchris 29-Jun-2007 02:11
If your string has some html entities, then it might split one in half. e.g.

<?php
/*
Outputs (Renders):

Préf&-
eacute;rence-
s e-mails

*/

echo wordwrap("Pr&eacute;f&eacute;rences e-mails");

?>

To solve this, you can use the following function:

<?php

function wordwrap2( $str, $width = 75, $break = '\n', $cut = true ) {
  $str = html_entity_decode( $str ); //first decode
  $out = wordwrap( $str, $width, $break, $cut ); //now wordwrap
  $out = htmlentities( $out ); //re-encode the entities
  $out = str_replace( htmlentities( $break ), $break, $out ); //put back the break
  return $out;
}

?>
phpsales at gmail dot com 16-May-2007 09:53
<?php
########################################
# Break long words with out cutting HTML tags.
########################################

/* Break Long Words (string, int, char) */

function breakLongWords($str, $maxLength, $char){
    $wordEndChars = array(" ", "\n", "\r", "\f", "\v", "\0");
    $count = 0;
    $newStr = "";
    $openTag = false;
    for($i=0; $i<strlen($str); $i++){
        $newStr .= $str{$i};

        if($str{$i} == "<"){
            $openTag = true;
            continue;
        }
        if(($openTag) && ($str{$i} == ">")){
            $openTag = false;
            continue;
        }

        if(!$openTag){
            if(!in_array($str{$i}, $wordEndChars)){//If not word ending char
                $count++;
                if($count==$maxLength){//if current word max length is reached
                    $newStr .= $char;//insert word break char
                    $count = 0;
                }
            }else{//Else char is word ending, reset word char count
                    $count = 0;
            }
        }

    }//End for
    return $newStr;
}
?>
Rekcor 27-Mar-2007 06:36
Improved version of egyptechno[at]gmail.com's wordCut.

In this improved function, the length of $sMessage is taken into consideration while cutting the text, so the returned string is never longer than $iMaxLength. Besides that, whole words are cut as well.

<?php
/**
 * function wordCut($sText, $iMaxLength, $sMessage)
 *
 * + cuts an wordt after $iMaxLength characters
 *
 * @param  string   $sText       the text to cut
 * @param  integer  $iMaxLength  the text's maximum length
 * @param  string   $sMessage    piece of text which is added to the cut text, e.g. '...read more'
 *
 * @returns string
 **/
function wordCut($sText, $iMaxLength, $sMessage)
{
   if (strlen($sText) > $iMaxLength)
   {
       $sString = wordwrap($sText, ($iMaxLength-strlen($sMessage)), '[cut]', 1);
       $asExplodedString = explode('[cut]', $sString);

       echo $sCutText = $asExplodedString[0];

       $sReturn = $sCutText.$sMessage;
   }
   else
   {
       $sReturn = $sText;
   }

   return $sReturn;
}
?>
Peter 19-Dec-2006 05:00
The main concern when you have a text in a cell is for long words that drags the cell margins. This function will break words in a text that have more then $nr characters using the "-" char.

<?php
function processtext($text,$nr=10)
    {
        $mytext=explode(" ",trim($text));
        $newtext=array();
        foreach($mytext as $k=>$txt)
        {
            if (strlen($txt)>$nr)
            {
                $txt=wordwrap($txt, $nr, "-", 1);
            }
            $newtext[]=$txt;
        }
        return implode(" ",$newtext);
    }
?>
tylernt at gmail dot com 28-Nov-2006 11:39
I wrote this to keep long strings from making my tables wider than the browser window. To lessen the impact on performance, only call this function on strings longer than 'X' characters.

<?php
// This function will insert the 'wbr' (optional linebreak) tag
// to wrap words in $string longer than 10 characters,
// but will not break inside HTML tags
function mywordwrap($string)
{
$length = strlen($string);

for ($i=0; $i<=$length; $i=$i+1)
    {
    $char = substr($string, $i, 1);
    if ($char == "<")
        $skip=1;
    elseif ($char == ">")
        $skip=0;
    elseif ($char == " ")
        $wrap=0;

    if ($skip==0)
        $wrap=$wrap+1;

    $returnvar = $returnvar . $char;

    if ($wrap>9) // alter this number to set the maximum word length
        {
        $returnvar = $returnvar . "<wbr>";
        $wrap=0;
        }
    }

return $returnvar;

}
?>
Edward 18-Oct-2006 06:12
I needed a function to justify the text - not just wrap it. I came up with this:

<?php
function justify($text, $width, $break) {
        $marker = "__$%@random#$()__";

        // lines is an array of lines containing the word-wrapped text
        $wrapped = wordwrap($text, $width, $marker);
        $lines = explode($marker, $wrapped);

        $result = "";
        foreach ($lines as $line_index=>$line) {
                $line = trim($line);

                $words = explode(" ", $line);
                $words = array_map("trim", $words);
                $wordcount = count($words);
                $wordlength = strlen(implode("", $words));

                if (3*$wordlength < 2*$width) {
                        // don't touch lines shorter than 2/3 * width
                        continue;
                }

                $spaces = $width - $wordlength;

                $index = 0;
                do {
                        $words[$index] = $words[$index] . " ";
                        $index = ($index + 1) % ($wordcount - 1);
                        $spaces--;
                } while ($spaces>0);

                $lines[$line_index] = implode("", $words);
        }

        return implode($break, $lines);
}
?>
egyptechno [at] gmail.com 04-Oct-2006 03:12
Another function to cut text afterr $limit letters ,

function :

<?php
function wordCut($text, $limit, $msg){
    if (strlen($text) > $limit){
        $txt1 = wordwrap($text, $limit, '[cut]');
        $txt2 = explode('[cut]', $txt1);
        $ourTxt = $txt2[0];
        $finalTxt = $ourTxt.$msg;
    }else{
        $finalTxt = $text;
    }
    return $finalTxt;
}
?>

return :
The limited text

description :
It takes the text, add the string '[cut]' every $limit text by wordwrap, then we explode the text with '[cut]' and takes the first element in the array which we need !

how to use :
wordCut($my_text, 200, '... read more');

EgypTechno
feedback at realitymedias dot com 01-Oct-2006 11:50
Here is a way to use wordwrap to add spaces to long "words", without breaking link tags -- I came up with this as there apparently is no way to reproduce this effect with a regular expression.

This is mostly used in users-posts where your output layout could be broken with words that are longer than what the container object can take - it will not effect html tags (such as <a href="aaaaaaaaaaaaaaaaaaaaaaaaa"> so you don't end up with broken links !

<?php
$body = 'this is a text with aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa looooooooooooooooooooooooooooong word! <a href="http://www.example.com/with/a/loooooooooooooooooooooong/url'> ... </a>';

foreach(explode(" ", strip_tags($body)) as $key => $line) {
  if (strlen($line) > 35) $body = str_replace($line, wordwrap($line, 25, " ", 1), $body);
}
/*(In case you would like the same thing without the tags protection, there is a regular expression way; */

$body = preg_replace("/([^\s]{35})/","$1 ",$body);
?>
19-Jul-2006 09:47
I've written another implemention of textwrap, becourse the last one didnt work for me.

<?php
function textwrap ($text, $length, $break) {
    $pure=strip_tags($text);
    $words=str_word_count($pure, 1);
    foreach ($words as $word) {
        if (strlen($word) > $length) {
            $newword=wordwrap($word, $length, $break, TRUE);
            $text=str_replace($word, $newword, $text);
        }
    }
    return $text;
}
?>
EngrKhalid 10-Feb-2006 08:54
I found this function helpful to cut long words without adding spaces:

<?php
function fWrap ( $vText, $vMax ) {
    $vWords = explode(" ", $vText);
    foreach ( $vWords as $i =>$w ) {
        if ( strlen ( $vWords[$i] ) > $vMax ) { $vWords[$i] = wordwrap( $vWords[$i], $vMax, "<wbr>", 1 ); }
    }
    return implode(" ", $vWords);
}
?>

Regards.
Dave Lozier - dave at fusionbb.com 30-Nov-2005 12:48
If you'd like to break long strings of text but avoid breaking html you may find this useful. It seems to be working for me, hope it works for you. Enjoy. :)

<?php
    function textWrap($text) {
        $new_text = '';
        $text_1 = explode('>',$text);
        $sizeof = sizeof($text_1);
        for ($i=0; $i<$sizeof; ++$i) {
            $text_2 = explode('<',$text_1[$i]);
            if (!empty($text_2[0])) {
                $new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1  ', $text_2[0]);
            }
            if (!empty($text_2[1])) {
                $new_text .= '<' . $text_2[1] . '>';
            }
        }
        return $new_text;
    }
?>
frans-jan at van-steenbeek dot R-E-M-O-V-E dot net 16-Nov-2005 06:17
Using wordwrap is usefull for formatting email-messages, but it has a disadvantage: line-breaks are often treated as whitespaces, resulting in odd behaviour including lines wrapped after just one word.

To work around it I use this:

<?php
 function linewrap($string, $width, $break, $cut) {
  $array = explode("\n", $string);
  $string = "";
  foreach($array as $key => $val) {
   $string .= wordwrap($val, $width, $break, $cut);
   $string .= "\n";
  }
  return $string;
 }
?>

I then use linewrap() instead of wordwrap()

hope this helps someone
tjomi4 at yeap dot lv 23-Sep-2005 03:26
utf8_wordwrap();

usage: utf8_wordwrap("text",3,"<br>");
coded by tjomi4`, thanks to SiMM.
web: www.yeap.lv

<?php

function utf8_wordwrap($str,$len,$what){
# usage: utf8_wordwrap("text",3,"<br>");
# by tjomi4`, thanks to SiMM.
# www.yeap.lv
$from=0;
$str_length = preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
$while_what = $str_length / $len;
while($i <= round($while_what)){
$string = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
$total .= $string.$what;
$from = $from+$len;
$i++;
}
return $total;
}
?>
pawan at shopsbs dot com 14-Aug-2005 10:32
I wanted to use this function to add a particular text after a certain word count. Here is how I implemented it:

<?php
$content = wordwrap($content, 200, "....<br /><!--more-->\n");
?>

Above code adds the text '...<br/><!--more-->\n' after a 200 word count. I know there are a million ways this can be done in PHP. Go PHP!
x403 at yandex dot ru 23-Jun-2005 06:35
String lenght control:

<?php
if (str_word_count($STRING) > 0)
    $div = strlen($STRING) / str_word_count($STRING);
else return " ";

if ( $div > 25 ) return wordwrap($STRING, 25, "\n", 1);

return $STRING;

// Maximum word lenght is 25 chars
?>
Kyle 31-May-2005 11:34
Yet-another-wordwrap-improvement... If you attempt to wordwrap() lines that already contain some line-breaks that you want to maintain, a simple wrapper around wordwrap can help. For example:

<?php
function preserve_wordwrap($tstr, $len = 75, $br = '\n') {
     $strs = explode($br,$tstr);
     $retstr = "";
     foreach ($strs as $str) {
          $retstr .= wordwrap($str,$len,$br) . $br;
     }
     return $retstr;
}
?>

I used a function like this for pulling quotes for my email out of a mysql database and formatting them for use in an email. Some quotes had multiple lines (e.g. a short conversation-style quote) that I wanted to maintain yet still word-wrap correctly.

[EDIT BY danbrown AT php DOT net: Contains a bugfix by (ajd AT cloudiness DOT com) on 13-JUN-05 to address the incorrect order of parameters passed to explode().]
09-May-2005 10:33
Note that wordwrap is meant for...wrapping words.  If you're simply trying to break a string into evenly sized pieces, take a look at chunk_split and str_split.
bruceboughton @ google mail 04-May-2005 03:08
I found that wordwrap deletes the spaces it wraps on. If you want to break up a string which doesn't consist of words, you may find this behaviour undesirable, as I did when trying to wordwrap a Regular Expression to 80 characters (for display along with test string, matches, etc.).

To preserve the spaces and still achieve a consistent cut length, you need to replace spaces with a suitable one-character replacement. I chose the ASCII non-printing character SUB (ASCII #26; some old telephone code meaning substitute):

<?php
$regex= str_replace(' ', chr(26), $regex);
$regex= wordwrap($regex, 80, '<br />', TRUE);
$regex= str_replace(chr(26), ' ', $regex);
?>

(Of course, you need to replace 80 with your column length and '<br />' with your break string)
grey - greywyvern - com 29-Sep-2004 12:31
Here's an HTML wrapping + nl2br function I developed.  It inserts line-breaks into long strings of characters in HTML-formatted text while ignoring tags and entities.  It also counts each entity as a single character, and only applies nl2br to text nodes.  You can also tell it to ignore whole elements, like <pre> where adding <br /> isn't necessary.

Great for formatting HTML generated by user input.  I distribute simple forum and blog scripts where codes input by the user are translated to HTML.  I send the result through this function to format it correctly and make sure they don't maliciously type in long words in order to break my layout.

http://www.greywyvern.com/code/php/htmlwrap_1.0.php.txt
sych at php dot com dot ua 20-Aug-2004 01:25
wordwrap doesn't know about UTF and considers a multi-byte utf characters as as many characters as there are bytes in there. However, it will still break correctly on " " and "#" (or all other characters in the ascii range (0-127).

However, this is not a bug as it was only meant to work on iso-8859-*.
shaun at phplabs dot com 25-Dec-2002 03:24
Here's some code which will turn text into a quoted message, that is, split a chunk of text into wrapped lines and prefix each line of text with a > sign (or some other delimiter). I found myself using this snippet so many times while writing an autoresponder that I just dropped it into a function.

<?php
function mailquote($text, $marker){
  $text = str_replace("\n", "\n$marker", wordwrap($text, 70));
  return $text;
}
?>

e.g.

mailquote($text, "> ");

> Would result in a long passage of text
> being broken into multiple lines, each
> line starting with a traditional "quote"
> marker, like this.
25-Aug-2002 12:40
Instead of using a space or a newline or <br /> as the line break separator, you may consider inserting  "Soft Hyphens" within the middle of long words, allowing elegant word breaking that can use the effective browser layout that is dependant of the effective font that the browser will use.

The "Soft Hyphen" (SHY) character is part of the STANDARD ISO-8859-1 character set: it won't be displayed (i.e. it will have width 0) if the two parts of a word can be displayed by the browser along on the same layout row. However it allows the browser to find a break in the middle of long words: in that case, it will display the first part of the word before the "Soft Hyphen", and a true Hyphen ("-") on the first layout row (if they both fit on that row), and the next part after the "Soft Hyphen" on the following layout row.

Ideally, each word should contain at least one "Soft Hyphen" between each syllable of a word, unless this would place a "Soft Hyphen" with less than 3 characters from the beginning or end of the word. So "Soft Hyphens" must not be inserted within words with 1 to 5 characters.

The Soft Hyphen is only appropriate within textual words using Latin, Greek, Cyrillic characters). For Semitic languages that use right to left scripts, the "Soft Hyphen" should be replaced by a "Soft Line Break" (also called "Zero Width Non Joiner" in Unicode).

This "Soft Line Break" always has a null display width (i.e. it is never displayed), except that it allows inserting a line break.

Some characters are already implicitly considered followed by a "Soft Line Break" in browsers: the explicit hyphen within composed words (like "week-end"), and all punctuations (with the exception of the dot, and opening punctuations like "({[" which are instead _preceded_ by an implicit "Soft Line Break").

Note also that some new browsers can insert themselves "Soft Hyphens" or "Soft Line Breaks" within long words, if the HTML page explicitly specifies the language, and the words are restricted to the natural characters of that language, using hyphenation rules and/or dictionnaries defined for that language.

Currently, the HTML standard offers no way to specify a set of hyphenation rules along with the page (so that it would work in absence of a known dictionnary for that language), so soft hyphens or line breaks should be placed in the content.
warwallace at [nospam]wargardens dot com 21-Jul-2002 09:44
It is also possible to consider this function as a tool for making text wrappable rather than simply for forcing wrapping.

In other words, use a space as the break - rather than "br /" or "p" or \n or whatever - and the text becomes wrappable.

<?php
$input = "I want to annoy you by inserting long wooooooooooooooooooooooooooooooooorrrrrrdddss into your guestbook.";
$output = wordwrap($input, 40, ' ', 1);
?>

Will insert spaces into the words longer than 40 characters make the text wrappable by the browser.
toxic79_spam at yahoo dot com 11-Jul-2002 08:02
I've noticed that if you have a string of, say, 8 characters and you set it to wrap at 8 characters with a break tag it will add the break tag after the 8th character even if the string is only 8 characters long. this was frustrating because I only wanted the break tag if there would be more text after it. it would be cool to have a flag that would stop this from happening, or a flag that would put the break tag (or whatever you use) before the number you break on, so you could set it to break every 9th character and it would only insert the tag after the 8th if there are more than 8 characters.

until then, however, here is my lame fix. $str is the string to wrap, $num is the number of characters to wrap after and $break is the text to use to wrap the string.

<?php
function my_wordwrap( $str, $num, $break )
{
    // get the wordwrapped string
    $tmp_str = wordwrap( trim( $str ), $num, $break, 1 );

    // get the string length of the breaking tag
    $strlen_break = strlen( $break );

    // if the last $strlen_break characters of the wordwrapped string is $break ...
    if ( substr( $tmp_str, ( 0 - $strlen_break )) == $break )
    {
        // strip the last $strlen_break characters off the end
        $tmp_str = substr( $tmp_str, 0, count( $tmp_str ) - $strlen_break - 1 );
    }

    // return the results
    return $tmp_str;
}
?>
ekgerke at yahoo dot com 11-Mar-2002 10:39
If the last line of string does not end with newline character, wordwrap tends to add trailing garbage.
timf at tfountain dot co dot uk 01-Jan-2002 03:18
If you're having problems with a small fixed width table/table cell being stretched by people typing entering long text (such as a URL or an email address), then one (MSIE only, unfortunately) solution is to use style="table-layout:fixed" in the <table> tag.  This will break any words that would normally expand your table and mess up your layout.

wordwrap() can't help in this situation because you want to wrap if the text is wider than X pixels, rather than X characters, which of course PHP has know way of knowing.
vsprintf
Расширения, относящиеся к переменным и типам
Обработка строк


Расширения, относящиеся к переменным и типам

  • Массивы
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Сортировка массивов
    • Функции для работы с массивами
  • Классы/Объекты — Функции работы с Классами/Объектами
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • Классы/Объекты
  • Classkit
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • classkit
  • Ctype — Функции определения типа символов
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Ctype
  • Filter — Фильтрация данных
    • Введение
    • Установка и настройка
    • Types of filters
    • Предопределенные константы
    • Примеры
    • Фильтрация данных
  • Управление функциями
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Управление функциями
  • Object Aggregation — Object Aggregation/Composition [PHP 4]
    • Введение
    • Примеры
    • Object Aggregation Функции
  • Quickhash
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashIntStringHash — The QuickHashIntStringHash class
  • Reflection
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • Расширение
    • Reflection — Класс Reflection
    • ReflectionClass — Класс ReflectionClass
    • ReflectionZendExtension — Класс ReflectionZendExtension
    • ReflectionExtension — Класс ReflectionExtension
    • ReflectionFunction — Класс ReflectionFunction
    • ReflectionFunctionAbstract — Класс ReflectionFunctionAbstract
    • ReflectionMethod — Класс ReflectionMethod
    • ReflectionObject — Класс ReflectionObject
    • ReflectionParameter — Класс ReflectionParameter
    • ReflectionProperty — Класс ReflectionProperty
    • Reflector — Интерфейс Reflector
    • ReflectionException — Класс ReflectionException
  • Функции для работы с переменными
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Функции для работы с переменными

User Contributed Notes

There are no user contributed notes for this page.
wordwrap
Массивы
Справочник функций


Массивы

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Сортировка массивов
  • Функции для работы с массивами
    • array_change_key_case — Меняет регистр ключей в массиве
    • array_chunk — Разбивает массив на части
    • array_combine — Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений
    • array_count_values — Подсчитывает количество всех значений массива
    • array_diff_assoc — Вычисляет расхождение массивов с дополнительной проверкой индекса
    • array_diff_key — Вычисляет расхождение массивов, сравнивая ключи
    • array_diff_uassoc — Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
    • array_diff_ukey — Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей
    • array_diff — Вычислить расхождение массивов
    • array_fill_keys — Создает массив и заполняет его значениями, с определенными ключами
    • array_fill — Заполняет массив значениями
    • array_filter — Фильтрует элементы массива с помощью callback-функции
    • array_flip — Меняет местами ключи с их значениями в массиве
    • array_intersect_assoc — Вычисляет схождение массивов с дополнительной проверкой индекса
    • array_intersect_key — Вычислить пересечение массивов, сравнивая ключи
    • array_intersect_uassoc — Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
    • array_intersect_ukey — Вычисляет схождение массивов, используя callback-функцию для сравнения ключей
    • array_intersect — Вычисляет схождение массивов
    • array_key_exists — Проверяет, присутствует ли в массиве указанный ключ или индекс
    • array_keys — Возвращает все или некоторое подмножество ключей массива
    • array_map — Применяет callback-функцию ко всем элементам указанных массивов
    • array_merge_recursive — Рекурсивное слияние двух или более массивов
    • array_merge — Сливает один или большее количество массивов
    • array_multisort — Сортирует несколько массивов или многомерные массивы
    • array_pad — Дополнить размер массива определенным значением до заданной величины
    • array_pop — Извлекает последний элемент массива
    • array_product — Вычислить произведение значений массива
    • array_push — Добавляет один или несколько элеметов в конец массива
    • array_rand — Выбирает одно или несколько случайных значений из массива
    • array_reduce — Итеративно уменьшает массив к единственному значению, используя callback-функцию
    • array_replace_recursive — Рекурсивно заменяет элементы первого массива элементами переданных массивов
    • array_replace — Замена элементов массива элементами других переданных массивов
    • array_reverse — Возвращает массив с элементами в обратном порядке
    • array_search — Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
    • array_shift — Извлекает первый элемент массива
    • array_slice — Выбирает срез массива
    • array_splice — Удаляет часть массива и заменяет её чем-нибудь ещё
    • array_sum — Вычисляет сумму значений массива
    • array_udiff_assoc — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
    • array_udiff_uassoc — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
    • array_udiff — Вычисляет расхождение массивов, используя для сравнения callback-функцию
    • array_uintersect_assoc — Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
    • array_uintersect_uassoc — Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию
    • array_uintersect — Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
    • array_unique — Убирает повторяющиеся значения из массива
    • array_unshift — Добавляет один или несколько элементов в начало массива
    • array_values — Выбирает все значения массива
    • array_walk_recursive — Рекурсивно применяет пользовательскую функцию к каждому элементу массива
    • array_walk — Применяет пользовательскую функцию к каждому элементу массива
    • array — Создает массив
    • arsort — Сортирует массив в обратном порядке, сохраняя ключи
    • asort — Сортирует массив, сохраняя ключи
    • compact — Создает массив, содержащий названия переменных и их значения
    • count — Подсчитывает количество элементов массива или что-то в объекте
    • current — Возвращает текущий элемент массива
    • each — Возвращает текущую пару ключ/значение из массива и смещает его указатель
    • end — Устанавливает внутренний указатель массива на его последний элемент
    • extract — Импортирует переменные из массива в текущую таблицу символов
    • in_array — Проверяет, присутствует ли в массиве значение
    • key — Выбирает ключ из массива
    • krsort — Сортирует массив по ключам в обратном порядке
    • ksort — Сортирует массив по ключам
    • list — Присваивает переменным из списка значения подобно массиву
    • natcasesort — Сортирует массив, используя алгоритм "natural order" без учета регистра символов
    • natsort — Сортирует массив, используя алгоритм "natural order"
    • next — Передвигает внутренний указатель массива на одну позицию вперёд
    • pos — Псевдоним current
    • prev — Передвигает внутренний указатель массива на одну позицию назад
    • range — Создает массив, содержащий диапазон элементов
    • reset — Устанавливает внутренний указатель массива на его первый элемент
    • rsort — Сортирует массив в обратном порядке
    • shuffle — Перемешивает массив
    • sizeof — Псевдоним count
    • sort — Сортирует массив
    • uasort — Сортирует массив, используя пользовательскую функцию для сравнения элементов с сохранением ключей
    • uksort — Сортирует массив по ключам, используя пользовательскую функцию для сравнения ключей
    • usort — Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов

User Contributed Notes

fo dot q dot who at gmail dot com 06-Apr-2011 04:37
Just another way to pass a multidimensional php array to a js array, but i think a cool one so I decided to put this on here.

<?php

function array_print($item, $key, $array_name)
{
    if(is_array($item)){
        $array_name = $array_name."['".$key."']";
        echo $array_name ."= Array();". "";
        php_array_to_js_array($item, $array_name);
    }else{
        echo $array_name."['".$key."'] = \"".$item."\";";
    }
}

function php_array_to_js_array($array, $array_name){
    array_walk($array, 'array_print', $array_name);
}

?>
<script type="text/javascript" defer="defer">
<?php
        echo "js_array = Array();";
        php_array_to_js_array($array, "js_array");

?>
</script>

there is not much to say about that, its simple and understandable, i think... if not just email me. Have a nice day pplz !!

Patrick F.
info at curtinsNOSPAMcreations dot com 05-Nov-2010 07:49
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode.  (Note that this probably adds a touch of overhead, but it sure does look nicer.)  You can of course add as many levels and as much formatting as you'd like to the string you then decode.  Don't forget that json requires " around values, not '!!  (So, you can't enclose the json string with " and use ' inside the string.)

As an example:

<?php
    $myarray['blah'] = json_decode('[
        {"label":"foo","name":"baz"},
        {"label":"boop","name":"beep"}
    ]',true);

print_r($myarray)
?>
returns:

Array
(
    [blah] => Array
        (
            [0] => Array
                (
                    [label] => foo
                    [name] => baz
                )

            [1] => Array
                (
                    [label] => boop
                    [name] => beep
                )
        )
)
dragos dot rusu at NOSPAM dot bytex dot ro 07-Mar-2010 06:15
If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:

<?php
$a = array(
    NULL => 'zero',
    1    => 'one',
    2    => 'two');

// This will show empty string for key associated with "zero" value
var_dump(array_keys($a));

// Array elements are shown
reset($a);
while( key($a) !== NULL )
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}

// Array elements are not shown
reset($a);
while( key($a) != NULL ) // '' == null   => no iteration will be executed
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}
John Marc 15-Feb-2010 01:30
Be careful when adding elements to a numeric array.
I wanted to store some info about some items from a database and decided to use the record id as a key.

<?php
$key=3000000000;
$DATA[$key]=true;
?>

This will create an array of 30 million elements and chances are, you will use up all memory with these 2 lines

<?php
$key=3000000000;
$DATA["$key"]=true;
?>

This on the other hand will force the array to be an associative array and will only create the one element
sunear at gmail dot com 04-Aug-2009 10:45
Made this function to delete elements in an array;

<?php

function array_del_elm($input_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    $del_indexes = null;

    $cur_index = 0;
    if (sort($indexes)) for($i=0; $i<count($input_array); $i++) {
        if ($i == $indexes[$cur_index]) {
            $cur_index++;
            if ($cur_index == count($indexes)) return $output_array;
            continue;
        }
        $output_array[] = $input_array[$i];
    }
    return $output_array;
}

?>

but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

<?php

function array_del_elm($target_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    unset($del_indexes);

    for($i=0; $i<count($indexes); $i++) {
        unset($target_array[$indexes[$i]]);
    }
    return $target_array;
}

?>

Fast, compliant and functional ;)
Tyler Bannister 11-Jun-2009 06:59
To delete an individual array element use the unset function

For example:

<?PHP
    $arr = array( "A", "B", "C" );
    unset( $arr[1] );
    // now $arr = array( "A", "C" );
?>

Unlink is for deleting files.
thomasdecaux at ebuildy dot com 15-May-2009 01:14
To browse a simple array:

<?php

foreach ($myArray AS $myItem)
{

}

?>

To browse an associative array:

<?php

foreach ($myArray AS $key=>$value)
{

}

?>

http://www.ebuildy.com
macnimble at gmail dot com 27-Mar-2009 06:59
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:

<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
#   create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
  $l = $t = array();
  foreach ($a AS $key => $val):
    if (!$val[$p]) $t[$key] =& $l[$key];
    else $l[$val[$p]][$c][$key] =& $l[$key];
    $l[$key] = (array)$l[$key] + $val;
  endforeach;
  return $a = array('tree' => $t, 'leaf' => $l);
}

# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
#     ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');

array_stack($node);

$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';

echo '<pre>',print_r($node['tree'],TRUE),'</pre>';
?>

Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
andyd273 at gmail dot com 24-Feb-2009 01:12
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:

            function array2js($array,$show_keys)
            {
                $dimensoes = array();
                $valores = array();

                $total = count ($array)-1;
                $i=0;
                foreach($array as $key=>$value){
                    if (is_array($value)) {
                        $dimensoes[$i] = array2js($value,$show_keys);
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    } else {
                        $dimensoes[$i] = '"'.addslashes($value).'"';
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    }
                    if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
                    if ($i==$total) $dimensoes[$i].= '}';
                    $i++;
                }
                return implode(',',$dimensoes);
            }
Endel Dreyer 20-Jan-2009 04:16
Function to convert PHP arrays to JavaScript Array Object:
Useful in some cases.

<?php
function array2js($array,$show_keys=false)
{
    $dimensoes = array();
    $valores = array();

    $total = count ($array)-1;
    $i=0;
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $dimensoes[$i] = array2js($value,$show_keys);
        } else {
            $dimensoes[$i] = '"'.addslashes($value).'"';
            if ($show_keys) '"'.$key.'":'.$dimensoes[$i];
        }
        if ($i==0) $dimensoes[$i] = '['.$dimensoes[$i];
        if ($i==$total) $dimensoes[$i].= ']';
        $i++;
    }
    return implode(',',$dimensoes);
}
?>
Anonymous 26-Nov-2008 10:36
@jorge at andrade dot cl
This variant is faster:
<?php
function array_avg($array,$precision=2){
    if(!is_array($array))
        return 'ERROR in function array_avg(): this is a not array';

    foreach($array as $value)
        if(!is_numeric($value))
            return 'ERROR in function array_avg(): the array contains one or more non-numeric values';

    $cuantos=count($array);
  return round(array_sum($array)/$cuantos,$precision);
}
?>
jorge at andrade dot cl 12-Nov-2008 12:03
To calculate the average of a array

<?php
function array_avg($array,$precision="2"){
    $a=0;
    if(is_array($array)){
        foreach($array as $value):
            if(!is_numeric($value)){
                $a++;
            }
        endforeach;
        if($a==0){
            $cuantos=count($array);
            return round(array_sum($array)/$cuantos,$precision);
        }else{
            return "ERROR in function array_avg(): the array contains one or more non-numeric values";
        }
    }else{
        return "ERROR in function array_avg(): this is a not array";
    }
}
?>
alan dot lake at lakeinfoworks dot com 22-Oct-2008 08:46
To delete an array key (and its value) from an array:

<?php
    function array_delete(&$ary,$key_to_be_deleted)
    {
        $new = array();
        if(is_string($key_to_be_deleted)) {
            if(!array_key_exists($key_to_be_deleted,$ary)) {
                return;
            }
            foreach($ary as $key => $value) {
                if($key != $key_to_be_deleted) {
                    $new[$key] = $value;
                }
            }
            $ary = $new;
        }
        if(is_array($key_to_be_deleted)) {
            foreach($key_to_be_deleted as $del) {
                array_delete(&$ary,$del);
            }
        }
    }
?>
webmaster at infoproducts dot x10hosting dot com 10-Oct-2008 07:13
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
Jack A 07-Oct-2008 08:14
Note that arrays are not allowed in class constants and trying to do so will throw a fatal error.
contact at greyphoenix dot biz 30-Jun-2008 09:36
<?php
//Creating a multidimensional array

$theVariable = array("Search Engines" =>
array (
    0=> "http//google.com",
    1=> "http//yahoo.com",
    2=> "http//msn.com/"),

"Social Networking Sites" =>
array (
    0 => "http//www.facebook.com",
    1 => "http//www.myspace.com",
    2 => "http//vkontakte.ru",)
);

echo "The first array value is " . $theVariable['Search Engines'][0];
?>

-- Output--
The first array value is http://google.com
applegrew at rediffmail dot com 28-May-2008 08:23
For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array("A", "B", "C");

//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");

//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");

Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";
Расширения, относящиеся к переменным и типам
Введение
Расширения, относящиеся к переменным и типам


Введение

Эти функции позволяют различными способами оперировать массивами. Массивы идеально подходят для хранения, изменения и работы с наборами переменных.

Поддерживаются одно- и многомерные массивы, как созданные пользователем, так и возвращенные в качестве результата какой-либо функцией. Используя специальные функции можно записать в массив результы запроса к базам данных. Так же существуют функции, возвращающие массивы в качестве результата.

За дополнительными сведениями о создании и использовании массивов в PHP, смотрите главу Массивы данного руководства. Смотрите также операции над массивами.

User Contributed Notes

There are no user contributed notes for this page.
Массивы
Установка и настройка
Массивы


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Массивы


Предопределенные константы

Перечисленные ниже константы всегда доступны как часть ядра PHP.

CASE_LOWER (integer)
CASE_LOWER используется с array_change_key_case() для конвертации ключей массива в нижний регистр. Это действие по умолчанию для array_change_key_case().
CASE_UPPER (integer)
CASE_UPPER используется c array_change_key_case() для конвертации ключей массива в верхний регистр.

Флаги, изменяющие порядок сортировки:

SORT_ASC (integer)
SORT_ASC используется с array_multisort() для сортировки в порядке возрастания.
SORT_DESC (integer)
SORT_DESC используется с array_multisort() для сортировки в порядке убывания.

Флаги сортировки, используемые различными функциями:

SORT_REGULAR (integer)
SORT_REGULAR используется для обычного сравнения элементов массива.
SORT_NUMERIC (integer)
SORT_NUMERIC используется для сравнения элементов, как цифр.
SORT_STRING (integer)
SORT_STRING используется для сравнения элементов как строк.
SORT_LOCALE_STRING (integer)
SORT_LOCALE_STRING используется для сравнения элементов как строк на базе текущей локали. Добавлено в PHP 4.4.0 и 5.0.2.
SORT_NATURAL (integer)
SORT_NATURAL используется для сравнения элементов как строк, используя естественное упорядочивание, такое как natsort(). Добавлено в PHP 5.4.0.
SORT_FLAG_CASE (integer)
SORT_FLAG_CASE может быть объединена (побитовое ИЛИ) с SORT_STRING или SORT_NATURAL для регистронезависимой сортировки строк. Добавлено в PHP 5.4.0.

COUNT_NORMAL (integer)
COUNT_RECURSIVE (integer)
EXTR_OVERWRITE (integer)
EXTR_SKIP (integer)
EXTR_PREFIX_SAME (integer)
EXTR_PREFIX_ALL (integer)
EXTR_PREFIX_INVALID (integer)
EXTR_PREFIX_IF_EXISTS (integer)
EXTR_IF_EXISTS (integer)
EXTR_REFS (integer)

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Сортировка массивов
Массивы


Сортировка массивов

В PHP есть несколько функций для сортировки массивов, на этой странице дается их общее описание.

Основные различия между функциями:

  • В одних функциях массивы array сортируются по ключам элементов, в других по значениям: $array['ключ'] = 'значение';
  • В каких-то функциях связь между ключами и значениями после сортировки сохраняется, в каких-то нет. Это может приводить к тому, что ключи будут сбрасываться в числовые значения (0, 1, 2, ...).
  • Различия в порядке сортировки: алфавитный, возрастающий, убывающий, числовой, натуральный, случайный или определенный пользователем
  • Примечание: Все функции сортировки модифицируют переданный массив, а не возвращают отсортированную копию
  • Если функции определяют два элемента как равные, порядок сортировки в этом случае не определен (нестабильная сортировка)

Свойства функций сортировки
Имя функции | Сортирует по | Сохраняет связь ключ - значение | Порядок сортировки | Похожие функции
array_multisort() | значению | ассоциативные да, числовые нет | первый массив или настройки сортировки | array_walk()
asort() | значению | да | по возрастанию | arsort()
arsort() | значению | да | по убыванию | asort()
krsort() | ключу | да | по убыванию | ksort()
ksort() | ключу | да | по возрастанию | asort()
natcasesort() | ключу | да | натуральный, чувствителен к регистру | natsort()
natsort() | значению | да | натуральный | natcasesort()
rsort() | значению | нет | по убыванию | sort()
shuffle() | значению | нет | случайный | array_rand()
sort() | значению | нет | по возрастанию | rsort()
uasort() | значению | да | определяется пользователем | uksort()
uksort() | ключу | да | определяется пользователем | uasort()
usort() | значению | нет | определяется пользователем | uasort()

User Contributed Notes

oculiz at gmail dot com 12-Mar-2011 09:57
Another way to do a case case-insensitive sort by key would simply be:

<?php
uksort($array, 'strcasecmp');
?>

Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.
K.i.n.g.d.r.e.a.d 06-Apr-2010 06:29
If you search a feature which sorts an array incasesensitive by key, try this:

<?php
function isort($a,$b) {
    return strtolower($a)>strtolower($b);
}
uksort($array, "isort");
?>
Dirk 29-Mar-2010 01:32
If you need to perform any of these sort functions on an array containing two or more equivalent values, you can get the equivalents to fall next to each other within the overall ordering (similar to how MySQL's ORDER BY works...) instead of breaking the sort() function, by using ksort() as a second parameter to arbitrarily distinguish any equivalent values by their unique keys:

<?php

sort($array, ksort($array));

?>

Seems like this effect should be built in.  At least the workaround is so short...
Предопределенные константы
Функции для работы с массивами
Массивы


Функции для работы с массивами

Смотрите также

См. также is_array(), explode(),
implode(), split(),
preg_split() и unset().

Содержание

  • array_change_key_case — Меняет регистр ключей в массиве
  • array_chunk — Разбивает массив на части
  • array_combine — Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений
  • array_count_values — Подсчитывает количество всех значений массива
  • array_diff_assoc — Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_key — Вычисляет расхождение массивов, сравнивая ключи
  • array_diff_uassoc — Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_diff_ukey — Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей
  • array_diff — Вычислить расхождение массивов
  • array_fill_keys — Создает массив и заполняет его значениями, с определенными ключами
  • array_fill — Заполняет массив значениями
  • array_filter — Фильтрует элементы массива с помощью callback-функции
  • array_flip — Меняет местами ключи с их значениями в массиве
  • array_intersect_assoc — Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_intersect_key — Вычислить пересечение массивов, сравнивая ключи
  • array_intersect_uassoc — Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_intersect_ukey — Вычисляет схождение массивов, используя callback-функцию для сравнения ключей
  • array_intersect — Вычисляет схождение массивов
  • array_key_exists — Проверяет, присутствует ли в массиве указанный ключ или индекс
  • array_keys — Возвращает все или некоторое подмножество ключей массива
  • array_map — Применяет callback-функцию ко всем элементам указанных массивов
  • array_merge_recursive — Рекурсивное слияние двух или более массивов
  • array_merge — Сливает один или большее количество массивов
  • array_multisort — Сортирует несколько массивов или многомерные массивы
  • array_pad — Дополнить размер массива определенным значением до заданной величины
  • array_pop — Извлекает последний элемент массива
  • array_product — Вычислить произведение значений массива
  • array_push — Добавляет один или несколько элеметов в конец массива
  • array_rand — Выбирает одно или несколько случайных значений из массива
  • array_reduce — Итеративно уменьшает массив к единственному значению, используя callback-функцию
  • array_replace_recursive — Рекурсивно заменяет элементы первого массива элементами переданных массивов
  • array_replace — Замена элементов массива элементами других переданных массивов
  • array_reverse — Возвращает массив с элементами в обратном порядке
  • array_search — Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
  • array_shift — Извлекает первый элемент массива
  • array_slice — Выбирает срез массива
  • array_splice — Удаляет часть массива и заменяет её чем-нибудь ещё
  • array_sum — Вычисляет сумму значений массива
  • array_udiff_assoc — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_udiff — Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_uintersect_assoc — Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc — Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию
  • array_uintersect — Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_unique — Убирает повторяющиеся значения из массива
  • array_unshift — Добавляет один или несколько элементов в начало массива
  • array_values — Выбирает все значения массива
  • array_walk_recursive — Рекурсивно применяет пользовательскую функцию к каждому элементу массива
  • array_walk — Применяет пользовательскую функцию к каждому элементу массива
  • array — Создает массив
  • arsort — Сортирует массив в обратном порядке, сохраняя ключи
  • asort — Сортирует массив, сохраняя ключи
  • compact — Создает массив, содержащий названия переменных и их значения
  • count — Подсчитывает количество элементов массива или что-то в объекте
  • current — Возвращает текущий элемент массива
  • each — Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • end — Устанавливает внутренний указатель массива на его последний элемент
  • extract — Импортирует переменные из массива в текущую таблицу символов
  • in_array — Проверяет, присутствует ли в массиве значение
  • key — Выбирает ключ из массива
  • krsort — Сортирует массив по ключам в обратном порядке
  • ksort — Сортирует массив по ключам
  • list — Присваивает переменным из списка значения подобно массиву
  • natcasesort — Сортирует массив, используя алгоритм "natural order" без учета регистра символов
  • natsort — Сортирует массив, используя алгоритм "natural order"
  • next — Передвигает внутренний указатель массива на одну позицию вперёд
  • pos — Псевдоним current
  • prev — Передвигает внутренний указатель массива на одну позицию назад
  • range — Создает массив, содержащий диапазон элементов
  • reset — Устанавливает внутренний указатель массива на его первый элемент
  • rsort — Сортирует массив в обратном порядке
  • shuffle — Перемешивает массив
  • sizeof — Псевдоним count
  • sort — Сортирует массив
  • uasort — Сортирует массив, используя пользовательскую функцию для сравнения элементов с сохранением ключей
  • uksort — Сортирует массив по ключам, используя пользовательскую функцию для сравнения ключей
  • usort — Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов

User Contributed Notes

topor-grabowski at viversum dot de 24-May-2012 04:51
delete all array entries with $valueToDelete as array entry; does function recursive without changing original array

<?php
  function array_delete_elements($array = null, $valueToDelete = null) {
    //no array given
    if (!isset($array)) {
      return null;
    }
    //process
    $resultList = array();
    foreach ($array as $entryKey => $entryValue) {
      if (is_array($entryValue)) {
        //entry is array and should be handled again recursive
        $resultList[$entryKey] = array_delete_elements($entryValue, $valueToDelete);
      } else {
        if ($entryValue != $valueToDelete) {
          $resultList[$entryKey] = $entryValue;
        }
      }
    }
    return $resultList;
  }
?>
kolkabes at googlemail dot com 05-May-2012 12:31
Short function for making a recursive array copy while cloning objects on the way.

<?php
function arrayCopy( array $array ) {
        $result = array();
        foreach( $array as $key => $val ) {
            if( is_array( $val ) ) {
                $result[$key] = arrayCopy( $val );
            } elseif ( is_object( $val ) ) {
                $result[$key] = clone $val;
            } else {
                $result[$key] = $val;
            }
        }
        return $result;
}
?>
dave at davidhbrown dot us 24-Sep-2011 11:57
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

The following array_rotate() function uses array_merge and array_shift to reliably rotate an array forwards or backwards, preserving keys. If you know you can trust your $array to be an array and $shift to be between 0 and the length of your array, you can skip the function definition and use just the return expression in your code.

<?php
function array_rotate($array, $shift) {
    if(!is_array($array) || !is_numeric($shift)) {
        if(!is_array($array)) error_log(__FUNCTION__.' expects first argument to be array; '.gettype($array).' received.');
        if(!is_numeric($shift)) error_log(__FUNCTION__.' expects second argument to be numeric; '.gettype($shift)." `$shift` received.");
        return $array;
    }
    $shift %= count($array); //we won't try to shift more than one array length
    if($shift < 0) $shift += count($array);//handle negative shifts as positive
    return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
}
?>
A few simple tests:
<?php
$array=array("foo"=>1,"bar"=>2,"baz"=>3,4,5);

print_r(array_rotate($array, 2));
print_r(array_rotate($array, -2));
print_r(array_rotate($array, count($array)));
print_r(array_rotate($array, "4"));
print_r(array_rotate($array, -9));
?>
Nitrogen 12-Sep-2010 08:17
I made a simple little function to make an array (containing readable data) presentable in human form.
I added some error checking, too.. (if it's not human-readable, don't include it).
<?php
function Combine($Input) {
  if(!is_array($Input)) // I only want arrays.
    return(false);

  // remove named index (only numeric index)
  $Input=array_values($Input);

  // read the array, if it's not a string or number, remove it!
  for($i=0;$i<count($Input);$i++)
    if(!is_string($Input[$i])&&!is_numeric($Input[$i]))
      unset($Input[$i]);

  // if an element got removed in the middle of the array, it leaves holes in the
  // array index, so we use array_values to reset them again.
  $Input=array_values($Input);

  // several array counts used asead.
  $Count=count($Input);

  if($Count>1)
    return(implode(', ',array_splice($Input,0,$Count-1)).' and '.$Input[0]);
  if($Count==1)
    return($Input[0]);
  if($Count==0)
    return('');
  // nothing should happen beyond this point.
}

Combine(array('A')); // A
Combine(array('A','B')); // A and B
Combine(array('A','B','C')); // A, B and C
Combine(array('A','B','9',4,5)); // A, B, 9, 4 and 5
Combine(array(3,false,5,'nine','?!?!')); // 3, 5, nine and ?!?!
// and so on...

?>

Hope this helps someone,
Nitrogen.
oliverSPAMMENOT at e-geek dot com dot au 22-Mar-2010 07:28
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

<?php
egvaluetostring($value)   //no max depth, or
egvaluetostring($value, $max_depth)   //max depth set

function egvaluetostring($value, $max_depth, $key = NULL, $depth = 0, $refChain = array()) {
  if($depth > 0)
    $tab = str_repeat("\t", $depth);
  $text .= $tab . ($key !== NULL ? $key . " => " : "");

  if (is_array($value) || is_object($value)) {
    $recursion = FALSE;
    if (is_object($value)) {
      foreach ($refChain as $refVal) {
        if ($refVal === $value) {
          $recursion = TRUE;
          break;
        }
      }
      array_push($refChain, $value);
    }

    $text .= (is_array($value) ? "array" : "object") . " ( ";

    if ($recursion) {
      $text .= "*RECURSION* ";
    }
    elseif (isset($max_depth) && $depth >= $max_depth) {
      $text .= "*MAX DEPTH REACHED* ";
    }
    else {
      if (!empty($value)) {
        $text .= "\n";
        foreach ($value as $child_key => $child_value) {
          $text .= egvaluetostring($child_value, $max_depth, (is_array($value) ? "[" : "") . $child_key . (is_array($value) ? "]" : ""), $depth+1, $refChain) . ",\n";
        }
        $text .= "\n" . $tab;
      }
    }

    $text .= ")";

    if (is_object($value)) {
      array_pop($refChain);
    }
  }
  else {
    $text .= "$value";
  }

  return $text;
}
?>
ducnm0 at gmail dot com 01-Mar-2010 05:08
A function to convert php array into JS object, supporting both object and array:

<?php
static function is_assoc($array) {
        foreach ( array_keys ( $array ) as $k => $v ) {
            if ($k !== $v)
                return true;
        }
        return false;
    }

    static function arrayPHPToJS($data) {
        if (is_null($data)) return 'null';
        if (is_string($data)) return "'" . $data . "'";
        if (self::is_assoc($data)) {
            $a=array();
            foreach ($data as $key => $val )
                $a[]="'" . $key . "' :" .self::arrayPHPtoJS($val);
            return "{" . implode ( ', ', $a ) . "}";
        }
        if (is_array($data)) {
            $a=array();
            foreach ($data as $val )
                $a[]=self::arrayPHPtoJS($val);
            return "[" . implode ( ', ', $a ) . "]";
        }
        return $data;
    }
?>
phektus at gmail dot com 02-Dec-2009 03:44
This is how I solved my array combinations problem. My particular situation is that I needed to project combinations of certain results and analyse each combination based from a consolidation of one of their attributes. The following example does not show the analysis part but it shows how I came up with my combinations ($traits).

This is actually an improvement on: http://ask.metafilter.com/64554/Finding-combinations-in-PHP
as it deals with arrays of strings, while I need to combine arrays within an array (you guessed it, database results).

Hope somebody finds this useful or teaches me a simpler way [by email] to do this. Public domain etc.

<?php
    header('Content-Type: text/plain');

    class Test {
        // holds the combinations
        var $combinations= array();

        function getCombinations($batch, $elements, $i)  {
            if ($i >= count($elements)) {
                $this->combinations[] = $batch;
            } else {
                foreach ($elements[$i] as $element) {
                    $this->getCombinations(array_merge($batch, $element), $elements, $i + 1);
                }
            }
        }
    }

    // Test it!

    $traits = array (
        array(
            array('Happy'),
            array('Sad'),
            array('Angry'),
            array('Hopeful')
        ),
        array(
            array('Outgoing'),
            array('Introverted')
        ),
        array(
            array('Tall'),
            array('Short'),
            array('Medium')
        ),
        array(
            array('Violent'),
            array('Quiet'),
            array('Psychotic')
        ),
        array(
            array('Handsome'),
            array('Plain'),
            array('Ugly')
        )
    );

    $test = new Test();
    $start = array();
    $test->getCombinations($start, $traits, 0);
    print_r($test->combinations);

?>
shadiadiph at yahoo dot com 31-Oct-2009 07:24
This is a useful function to remove an array value from an array.

<?php

function rem_array($array,$str){
foreach ($array as $key => $value) {
if ($array[$key] == "$str") unset($array[$key]);
}
return $array;
}

$selected='';
$selected ="three";
$numbers=array();
$numbers=array('one','two','three','four');
print_r($numbers);

// returns  Array ( [0] => one [1] => two [2] => three [3] => four )

// now we are going to call the function to see if the number three the $selected number is in the array $numbers and remove it.

$numbers = rem_array($numbers,$selected);

print_r ($numbers);
// returns  Array ( [0] => one [1] => two [3] => four )

?>

I am finding it usefull for drop down lists on forms where you do not want the selected value duplicated.
seva dot lapsha at gmail dot com 02-Aug-2009 06:22
Arrays are good, but inapplicable when dealing with huge amounts of data.

I'm working on rewriting some array functions to operate with plain Iterators - map, reduce, walk, flip et cetera are already there.

In addition I'm going to implement simulation of comprehensions (generators) in PHP (http://en.wikipedia.org/wiki/List_comprehension).

See the source code, examples and documentation at http://code.google.com/p/php-iterator-utils/
jan at hooda dot de 07-Dec-2008 03:49
Two simple functions to add and delete values from arrays:

<?php
      function array_add (&$array, $val) {
        array_push ($array, $val);
      }

      function array_del (&$array, $str)
      {
        if (in_array($str,$array)==true) {
          foreach ($array as $key=>$value) {
            if ($value==$str) unset($array[$key]);
          }
        }
      }
?>
renatonascto at gmail dot com 17-Sep-2008 11:11
Big arrays use a lot of memory possibly resulting in memory limit errors. You can reduce memory usage on your script by destroying them as soon as you´re done with them. I was able to get over a few megabytes of memory by simply destroying some variables I didn´t use anymore.
You can view the memory usage/gain by using the funcion memory_get_usage(). Hope this helps!
pragash_jey at yahoo dot com 06-Apr-2008 07:38
Java Like Array Implementation!

<?php
/*
 * Author : Pragash Jeyaratnam
 * Vector Class
 * PHP Version 5.2.5
 * Contact : pragash_jey@yahoo.com.
 */
class Vector
{
    /*
     * The number of valid components in this Vector object.
     */
    protected $elementCount;
    /*
     * The array buffer into which the components of the vector are stored.
     */
    protected $elementData;

    /**Default vector Constructor*/
    function __construct()
    {
        $this->elementData = array();
        $this->elementCount = count($this->elementData);
    }

    /**Append the parameter element to the vector*/
    public function add($object)
    {
        if(!empty($object))
        {
            $this->elementData[] = $object;
            $this->elementCount = count($this->elementData);
            return true;
        }
        else
            return false;

    }

    /*
     * Returns true of Vector is empty false otherwise
     */
    public function isEmpty()
    {
        return($this->elementCount==0);
    }

  /*
   * Returns the current size of this Vector
   */
   public function size()
   {
       return $this->elementCount;
   }

   /*
    *  Searches for the first occurence of the given argument
    **/
   public function indexOf($object)
   {
          if(($index =array_search($object,$this->elementData)) !==false)
              return $index;
          else
              return -1;
   }

   /*
    * This function will retain TRUE if $object is contained
    * within the vector else FALSE
    */

   public function contains($object)
   {
           return ($this->indexOf($object)>=0);
   }

   /*
    * Returns Vector Object at index $index
    * Error : Null is returned
    */

   public function get($index)
   {
           if($this->checkBound($index))
           {
               return ($this->elementData[$index]);
           }
           return NULL;
   }

   /*
    * Sets the object at $index to be $object
    **/

   public function set($index,$object)
   {
           if($this->checkBound($index))
           {
               $this->elementData[$index] =$object ;
               return true;
           }
           return false;
   }

  /*
   * Removes element at $index
   **/

      public function removeAt($index)
      {
       if ($this->checkBound($index))
           {
                 for ($i = $index; $i != $this->elementCount - 1; $i++)
                  {
                   $this->elementData[$i] = $this->elementData[$i +1];
             }
       array_pop($this->elementData);
       $this->elementCount = count($this->elementData);

       return true;
       }
       else {
            return false;
            }
      }

    /**
     * Removes all elements from the Vector.  Note that this does not
     * resize the internal data array.
     */
   public function removeAll()
   {
         if($this->elementCount ==0)
             return;
         for($i=0;$i<$this->size();$i++)
         {
             $this->set($i,NULL);
         }
   }

   /*
    * This function checks whether index
    * is within the array bound
    **/

   private function checkBound($index)
   {
         if($index > $this->elementCount-1 || $index < 0)
         {
             throw new Exception('Array Index Out Of Bound Exception');
             return false;
         }
         return true;
   }

    /*
     *Removes the first element from the Vector
     */

    public function removeFirstElement()
    {
        if($this->elementCount==0)
        {
            throw new Exception('No Such Element');
        }
        $test =array_shift($this->elementData);
        if(!empty($test))
            $this->elementCount = count($this->elementData);
    }

}
?>
Anonymous 29-Mar-2008 11:28
This is the shorter way to flatten a array:
<?php
  function array_flatten($a) {
    foreach($a as $k=>$v) $a[$k]=(array)$v;
    return call_user_func_array(array_merge,$a);
  }
?>
bas at muer dot nl 17-Mar-2008 08:17
I see a lot of people here writing complex functions to convert an array to a string, for use with Javascript or other things (possibly even databases, which would be bad).
For Javascript, the most efficient way would be JSON (http://www.php.net/json_encode). For normal use, serialize() (http://www.php.net/serialize) is your friend.
jake at blah dot inf 06-Mar-2008 06:03
@margol:

<?php
$tuple_array = array(array('key1' => 'val1'), array('key2' => 'val2'));
list($key, $val) = each(array_pop($tuple_array));
?>

But, why not use a two element array instead of a single-element associative array?

<?php
$tuple_array = array(array('key1', 'val1'), array('key2','val2'));
list($key,$val) = array_pop($tuple_array);
?>
margol at beamartyr dot net 04-Mar-2008 01:45
More intuitive tuple support would be nice  :)

But for those scratching their heads, like I did, to extract a tuple from an array of tuples, do something like:

    $tuple = array_pop($tuple_array);
    $key = key($tuple);
    $val = $tuple[$key];
yousefomar (a) yahoo dot com 28-Feb-2008 11:26
Here is how you refresh the expiration time for multiple cookies:

// get the cookie names
$keys=array_keys($_COOKIE);

// loop through all the cookies and update the exp. time
for ($i=0; $i<count($_COOKIE);$i++)
   setcookie( $keys[$i], $_COOKIE[$keys[$i]], time()+3600);

you can use this in authentication validate file to keep the session up.
ms419 at freezone dot co dot uk 14-Feb-2008 10:35
This function takes an array, a key and a value. If the key is not an array, it acts just like $array[$key] =& $value; If the key is an array, it recurses in the array, creating nested arrays as necessary.

Example:

$array = array('A' => array('B' => 'phi'));
$key = array('A', 'Z');
$value = 'gamma';

arraySet($array, $key, $value);

$array should now be:

array('A' => array('B' => 'phi', 'C' => 'gamma'));

This is useful for constructing nested arrays from sets of filesystem paths (e.g. 'A/B/C') or structured variable names (e.g. 'A.B.C' or 'A[B][C]')

Example:

arraySet($array, preg_split('/\//', $path, -1, PREG_SPLIT_NO_EMPTY), $value);

function arraySet(array &$array, $key, &$value)
{
    if (is_array($key)) {
        $keyComponent = array_shift($key);

        if (empty($key)) {
            $array[$keyComponent] =& $value;
            return;
        }

        if (!is_array($array[$keyComponent])) {
            $array[$keyComponent] = array();
        }

        PHP_CodeSniffer_arraySet($array[$keyComponent], $key, $value);
        return;
    }

    $array[$key] =& $value;
}
dennis at DONTSPAMME dot born05 dot nl 13-Feb-2008 07:22
I haven't completely figured out when or why an array gets referenced or copied, but it gave me quite the headache..

So i wrote a function which recursively copies an array while preserving keys and also clones objects if encountered

<?php
    /**
     * make a recursive copy of an array
     *
     * @param array $aSource
     * @return array    copy of source array
     */
    function array_copy ($aSource) {
        // check if input is really an array
        if (!is_array($aSource)) {
            throw new Exception("Input is not an Array");
        }

        // initialize return array
        $aRetAr = array();

        // get array keys
        $aKeys = array_keys($aSource);
        // get array values
        $aVals = array_values($aSource);

        // loop through array and assign keys+values to new return array
        for ($x=0;$x<count($aKeys);$x++) {
            // clone if object
            if (is_object($aVals[$x])) {
                $aRetAr[$aKeys[$x]]=clone $aVals[$x];
            // recursively add array
            } elseif (is_array($aVals[$x])) {
                $aRetAr[$aKeys[$x]]=array_copy ($aVals[$x]);
            // assign just a plain scalar value
            } else {
                $aRetAr[$aKeys[$x]]=$aVals[$x];
            }
        }

        return $aRetAr;
    }
?>

I hope i can save someone else's aspirine with this ;)
csorfab at gmail dot com 05-Feb-2008 10:26
Here's a function I wrote to combine the values in an array in all different ways, and which returns a two-dimensional array as a byref result.

E.g.

if called:
comb(array(1, 2, 3), $r);

then $r would be:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

<?php

    function comb($arr, &$rarr, $vtemp = array()){
        foreach($arr as $key => $value){
            $vtemp2 = $vtemp;
            $vtemp2[] = $value;

            $atemp = $arr;
            unset($atemp[$key]);

            if(count($atemp) > 0){
                comb($atemp, $rarr, $vtemp2);
            } else {
                $t = array();

                foreach($vtemp2 as $val){
                    $t[] = $val;
                }

                $rarr[] = $t;
            }
        }
    }

?>
christian dot reinecke at web dot de 02-Feb-2008 01:12
Here are two more functions handling string2array and access array by string. It's useful if you want to access an array in xpath-style, such as parse_ini_file return values with $process_sections = TRUE.

<?php
function createArrayByString($string, $separator, $value = NULL)
{
    if (strlen($string) > 0) {
        $splitter = explode($separator, $string);
        $index = array_shift($splitter); // get first element
        $function = __FUNCTION__;
        return array($index => $function(implode($separator, $splitter), $separator, $value));
    }
    return $value;
}

function accessArrayByString($array, $string, $separator, $default = NULL)
{
    if (!is_array($array)) {
        return empty($string) ? $array : $default;
    }
    @list ($key, $rest) = explode($separator, $string, 2); // @ needed for last access

    $function = __FUNCTION__;
    return array_key_exists($key, $array)
         ? $function($array[$key], $rest, $separator, $default)
         : $default;
}

$string = "one.two.three.four";
$separator = ".";

$array = createArrayByString($string, $separator, "standard value");
$return = accessArrayByString($array, $string, $separator, "element not found");

var_dump($array); // should return array("one" => array("two" => array("three" => array("four" => "standard value"))))
var_dump($return); // should return "standard value";
?>

change the function name to what ever you want, the recursive call uses __FUNCTION__ for re-call.
florian at egliselasauzaie dot fr 30-Jan-2008 02:09
I've created a class which is comparable to a Vector in C++;
<?php
class Vector {
    public $nb_elements;
    public $liste;

    public function Vector() {
        $this->liste = array ();
        $this->nb_elements = count($this->liste);
    }

    public function push_back($valeur) {
        if (!empty ($valeur)) {
            $this->liste[] = $valeur;
            $this->nb_elements = count($this->liste);
            return true;
        } else {
            return false;
        }
    }
    public function insert_at($indice, $valeur) {
        if ($indice > 0 && $indice < $this->nb_elements) {
            for ($i = $this->nb_elements; $i != $indice; $i--) {
                $this->liste[$i] = $this->liste[$i -1];
            }
            $this->liste[$indice] = $valeur;
            $this->nb_elements = count($this->liste);
            return true;
        } else {
            return false;
        }
    }
    public function remove_at($indice) {
        if ($indice > 0 && $indice < $this->nb_elements) {
            for ($i = $indice; $i != $this->nb_elements - 1; $i++) {
                $this->liste[$i] = $this->liste[$i +1];
            }
            array_pop($this->liste);
            $this->nb_elements = count($this->liste);
            return true;
        } else {
            return false;
        }
    }
    public function pop() {
        $value = array_pop($this->liste);
        $this->nb_elements = count($this->liste);
        return $value;
    }
    public function shift() {
        $value = array_shift($this->liste);
        $this->nb_elements = count($this->liste);
        return true;
    }
}
?>
really quick function 25-Jan-2008 12:37
function array_flatten($a){ //flattens multi-dim arrays (distroys keys)
    $ab = array(); if(!is_array($a)) return $ab;
    foreach($a as $value){
        if(is_array($value)){
            $ab = array_merge($ab,array_flatten($value));
        }else{
            array_push($ab,$value);
        }
    }
    return $ab;
}
Jck_true (leave out the &#39;_&#39; at gmail dot com) 25-Jan-2008 02:00
A usefull function that returns a flat array.
I use it in a template system. Let the user pass a multidimensional array. Convert it using my function. Then use
<?php
$array = flatten($array,'','{$','}','->');
echo str_replace(array_keys($array),array_values($array),$template)
/**
* Flattens out an multidimension array
* Using the last parameters you can define the new key based on the old path.
* @param array $array A multidimension array
* @param string $prefix Internal perfix parameter - leave empty.
* @param string $start_string What string should start the final array key?
* @param string $end_string What string should end the final array key?
* @param string $seperator The string that should seperate the piecies in final array key path
* @return array Returns the flat array
*/
function flatten($array, $start_string= '{$',$end_string= '}',$seperator='->',$prefix="") {
  $return = array();
  foreach($array as $key=>$value) {
    if (is_array($value)) {
      $return = array_merge($return, Parser_method_replace::flatten($value, $prefix.$key.$seperator,$start_string,$end_string,$seperator));
    } else
      $return [$start_string.$prefix.$key.$end_string] = $value;
  }
  return $return;
}
}
?>
Example:
$template = 'My string with replacement {$test->subkey}';
{$test->subkey} will get replaced with $array['test']['subkey']
chaos dot global dot net at gmail dot com 02-Jan-2008 03:53
if some one will need to convert array to php code use this function:

DEFINE('OFFSET_DELIMETER', "\t");

function array2php($array, $offset = OFFSET_DELIMETER)  {
    $text = '';
    foreach($array as $k => $v) {
        if (is_array($v)) {
            $text .= "{$offset}'{$k}' => array(\n".array2php($v, $offset.OFFSET_DELIMETER)."$offset)";
        } else {
            $text .= "{$offset}'{$k}' => ".(is_string($v)? "'$v'": $v);
        }
        $text .= ",\n";
    }
    if ($len = strlen($text)) $text[$len - 2] = " ";
    return $text;
}
Hayley Watson 17-Oct-2007 04:10
Regarding cyberchrist at futura dot net's function. It makes an unnecessary array_merge(); the elements of $b that are merged with those of $a are immediately removed again by the array_diff(). The "limiting to known values" is entirely unnecessary, in other words: arrays already only contain "known values".

Also, the description and function only address the issue of whether $a is a subset of $b, not whether it is a proper subset. For $a to be a proper subset of $b, it must also be the case that $b is not a subset of $a.

Taking those points into account (and a personal aesthetic dislike of "if(test) return true; else return false;" gives:

<?php
function is_subset($a, $b)
{
    return count(array_diff($a,$b))==0;
}

function is_proper_subset($a, $b)
{
    return is_subset($a, $b) && !is_subset($b, $a);
}
?>
cyberchrist at futura dot net 15-Oct-2007 06:33
Lately, dealing with databases, I've been finding myself needing to know if one array, $a, is a proper subset of $b.

Mathematically, this is asking (in set theory) [excuse the use of u and n instead of proper Unicode):

( A u B ) n ( ~ B )

What this does is it first limits to known values, then looks for anything outside of B but in the union of A and B (which would be those things in A which are not also in B).

If any value exists in this set, then A is NOT a proper subset of B, because a value exists in A but not in B.  For A to be a proper subset, all values in A must be in B.

I'm sure this could easily be done any number of ways but this seems to work for me.  It's not got a lot of error detection such as sterilizing inputs or checking input types.

// bool array_subset( array, array )
// Returns true if $a is a proper subset of $b, returns false otherwise.

function array_subset( $a, $b )
{
    if( count( array_diff( array_merge($a,$b), $b)) == 0 )
        return true;
    else
        return false;
}
Kazuyoshi Tlacaelel 29-Aug-2007 11:56
<?php
/**
 * converts a multidimensional array to a flat array
 *
 * trying to keep the original names of the keys
 * if repeated keys are found a hash will be added to the
 * keys trying to keep as much as possible of the original
 * key context
 *
 * september 30 2007
 *
 * PHP version 5
 *
 * @license         GPL
 *
 */

$array = array ( 0 => array ( 0 => 1, 1 => 2, 2 => array ( 0 => 3, 1 => 4, 2 =>
array ( 0 => 5, 1 => 6, 2 => array ( 0 => 7, 1 => 8,),),), 3 => array (
    0 => array ( 0 => 9, 1 => 10, 2 => array ( 0 => 11, 1 => 12,
    2 => array ( 0 => 13, 1 => 14, 2 => array ( 0 => 15, 1 => 16,),),),),
    1 => array ( 0 => 17, 1 => 18,),),), 1 => array ( 0 => 19, 1 => 20,),
    2 => array ( 0 => array ( 0 => 21, 1 => 22, 2 => array ( 0 => 23, 1 => 24,
    2 => array ( 0 => 25, 1 => 26, 2 => array ( 0 => 27, 1 => 28,),),),),
    1 => array ( 0 => 29, 1 => 30,),),);

/**
 * transforms a multidimensional array to a flat array
 *
 * the parameter is referenced
 * so no returning value is needed
 * @param array $array the multidimensional array to flat
 * @return void
 */
function array_flatten(&$array)
{
    function has_arrays($array)
    {
        foreach ($array as $item) {
            if (is_array($item)) {
                return true;
            }
        }
        return false;
    }

    function copy_array(&$array, $array_key)
    {
        $array2 = $array[$array_key];
        unset($array[$array_key]);
        foreach ($array2 as $subkey => $subvalue) {
            if (array_key_exists($subkey, $array)) {
                $array[generate_unique_key($subkey)] = $subvalue;
            } else {
                $array[$subkey] = $subvalue;
            }
        }
    }

    function generate_unique_key($key)
    {
        if (strlen($key)>8) {
            $key = $key[0] . $key[1] . $key[2];
        }
        $id = $key . '_';
        $uid = uniqid();
        $len = strlen($uid);
        $max = (9 - strlen($key));
        for ($c = $len; ; $c --) {
            $id .= $uid[$c];
            if ($c == ($len - $max)) {
                break;
            }
        }
        return $id;
    }

    function get_array_indexes($array)
    {
        $ret_array = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $ret_array[] = $key;
            }
        }
        return $ret_array;
    }

    while(has_arrays($array)) {
        foreach (get_array_indexes($array) as $key) {
            copy_array($array, $key);
        }
    }
}

    array_flatten($array);
    array_multisort($array);
    var_export($array);

    /**
     *  OUTPUT
     *
     *  array (
     *    0 => 1,
     *    '1_403767b6' => 2,
     *    '0_793767b6' => 3,
     *    '1_8a3767b6' => 4,
     *    '0_454767b6' => 5,
     *    '1_564767b6' => 6,
     *    '0_035767b6' => 7,
     *    '1_345767b6' => 8,
     *    '0_e74767b6' => 9,
     *    '1_f84767b6' => 10,
     *    '0_855767b6' => 11,
     *    '1_a65767b6' => 12,
     *    '0_4e5767b6' => 13,
     *    '1_6f5767b6' => 14,
     *    '0_566767b6' => 15,
     *    '1_876767b6' => 16,
     *    '0_5b4767b6' => 17,
     *    '1_6c4767b6' => 18,
     *    '0_d43767b6' => 19,
     *    1 => 20,
     *    '0_4e3767b6' => 21,
     *    '1_5f3767b6' => 22,
     *    '0_ad4767b6' => 23,
     *    '1_ce4767b6' => 24,
     *    '0_485767b6' => 25,
     *    '1_695767b6' => 26,
     *    '0_116767b6' => 27,
     *    '1_426767b6' => 28,
     *    '0_814767b6' => 29,
     *    '1_924767b6' => 30,
     *  )
     */
?>
mo dot longman at gmail dot com 30-Jul-2007 11:27
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.
g4wx3 19-Jul-2007 02:16
I needed a function to convert a php array into a javascript array.
No problem i found it on "the net".

But the function i found wasn't good enough, instead of return a string with javascript-array it echoed directly everything.
I wanted to write the string to a file, when calling the function out of my function libary.

Secondly, there where minor "bugs" in the script, when you're original array contained characters like line breaks(\r\n,..), or quotes('), it would hack up the javascript array

Sow, i changed the function and fixed the bug.

<?php
//SUPER COOL : http://www.communitymx.com/content/article.cfm?page=3&cid=7CD16
//Checkout:  REVERSE: http://www.hscripts.com/tutorials/php/jsArrayToPHP.php
//Convert a PHP array to a JavaScript one (rev. 4)
//Changlog by g4wx3: echo replaced by $output, added function output
function output($string) //make javascript ready
    {
    $string = str_replace( array( '\\' , '\'' ), array('\\\\', '\\\'') , $string); //-> for javascript array
    $string = str_replace(  array("\r\n", "\r", "\n") , '<br>' , $string);    //nl2br
    return $string;
    }
function arrayToJS4($array, $baseName ) {
    //Write out the initial array definition
//v4    echo ($baseName . " = new Array(); \r\n ");
    $output = $baseName . " = new Array(); \r\n ";

    //Reset the array loop pointer
    reset ($array);

    //Use list() and each() to loop over each key/value
    //pair of the array
    while (list($key, $value) = each($array)) {
        if (is_numeric($key)) {
        //A numeric key, so output as usual
        $outKey = "[" . $key . "]";
        } else {
        //A string key, so output as a string
        $outKey = "['" . $key . "']";
        }

        if (is_array($value)) {
        //The value is another array, so simply call
        //another instance of this function to handle it
        $output .= arrayToJS4($value, $baseName . $outKey);
        } else {

            //Output the key declaration
//v4            echo ($baseName . $outKey . " = ");
            $output .= $baseName . $outKey . " = ";

            //Now output the value
            if (is_string($value)) {
                //Output as a string, as we did before
//v4                echo ("'" . output($value) . "'; \r\n ");
                $output .= "'" . output($value) . "'; \r\n ";
            } else if ($value === false) {
                //Explicitly output false
//v4                echo ("false; \r\n");
                $output .= "false; \r\n";
            } else if ($value === NULL) {
                //Explicitly output null
//v4                echo ("null; \r\n");
                $output .= "null; \r\n";
            } else if ($value === true) {
                //Explicitly output true
//v4                echo ("true; \r\n");
                $output .= "true; \r\n";
            } else {
            //Output the value directly otherwise
//v4            echo ($value . "; \r\n");
            $output .= $value . "; \r\n";
            }
        }
    }
return $output;
}
?>
You can use this for printing $_GET array, for example
peanutpad at msn dot com 15-Jun-2007 03:15
heres a function from http://www.linksback.org  Feedback welcome, of course!  Public domain, yadda yadda.

function mySort(&$array,$key) {
    if (!is_array($array) || count($array) == 0) return true;
    $assocSortCompare  = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';

    if (is_numeric($array[0][$key])) {
      $assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
    } else {
      $assocSortCompare.= ' return strcmp($a,$b);';
    }

    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    return usort($array,$assocSortCompare);
}
webdev at svbeatrix dot com 11-Jun-2007 09:06
Bugs happen, but how can people post functions that WON'T EVEN COMPILE!  I truly detest finding a cool code snippet or function and then having to debug them. Sorry for the rant, but I have experienced this scenario a number of times.  TEST YOUR CODE, THEN POST!

Here is a revised and corrected previously posted function ArrayDepth, which had 3 bugs and yes, would not compile.

function ArrayDepth($Array,$DepthCount=-1) {
// Find maximum depth of an array
// Usage: int ArrayDepth( array $array )
// returns integer with max depth
// if Array is a string or an empty array it will return 0
  $DepthArray=array(0);
  $DepthCount++;
  $Depth = 0;
  if (is_array($Array))
    foreach ($Array as $Key => $Value) {
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
    }
  else
    return $DepthCount;
  return max($DepthCount,max($DepthArray));
}
sid dot pasquale at gmail dot com 29-May-2007 02:57
<?php
/* This function allow you to transform a multidimensional array
   in a simple monodimensional array.
   Usage: array_walk($oldarray, 'flatten_array', &$newarray);
   For example, this code below shows to you:
        Array
        (
            [1] => Array
                (
                    [0] => 1
                    [1] => 2
                )

            [2] => Array
                (
                    [0] => 3
                    [1] => 4
                )

        )

        Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )
*/

function flatten_array($value, $key, &$array) {
    if (!is_array($value))
        array_push($array,$value);
    else
        array_walk($value, 'flatten_array', &$array);

}

$oldarray = array(
    1 => array(1,2),
    2 => array(3,4)
);
$newarray = array();
array_walk($oldarray, 'flatten_array', &$newarray);
echo "<pre>";
print_r($oldarray);
print_r($newarray);
echo "</pre>";
?>
info at dyflexis dot nl 17-Apr-2007 01:13
A modernized version of the flatten_array() functies written by

davidj at boundlessgallery dot DISLIKESPAM dot com
on 02-Apr-2004 03:10

This function is able to work with associative arrays

<?php
function flatten_array($array) {
     $size=sizeof($array);
     $keys=array_keys($array);
    for($x = 0; $x < $size; $x++) {
         $element = $array[$keys[$x]];

        if(is_array($element)) {
            $results = flatten_array($element);
                $sr = sizeof($results);
                $sk=array_keys($results);
            for($y = 0; $y < $sr; $y++) {
                $flat_array[$sk[$y]] = $results[$sk[$y]];
            }
        } else {
            $flat_array[$keys[$x]] = $element;
        }
    }

    return $flat_array;
}
?>
info at joolee dot nl 19-Mar-2007 04:49
A slight modification in the arraytostring function, posted below. This function lists an array the same way you would define it in PHP.

<?PHP
function arraytostring($array, $depth = 0)
{
   if($depth > 0)
      $tab = implode('', array_fill(0, $depth, "\t"));
   $text.="array(\n";
   $count=count($array);

   foreach ($array as $key=>$value)
   {
       $x++;

       if (is_array($value))
       {
           if(substr($text,-1,1)==')')    $text .= ',';
           $text.=$tab."\t".'"'.$key.'"'." => ".arraytostring($value, $depth+1);
           continue;
       }

       $text.=$tab."\t"."\"$key\" => \"$value\"";

       if ($count!=$x) $text.=",\n";
   }

   $text.="\n".$tab.")\n";

   if(substr($text, -4, 4)=='),),')$text.='))';

   return $text;
}
?>
Vladson 14-Mar-2007 07:18
Hope someone find it useful..

<?php
/*
    Function: eratosthenes
    Usage: array eratosthenes ( int max_value )

    Description:
    Sieve of Eratosthenes is a simple, ancient algorithm
    for finding all prime numbers up to a specified integer.
    It was created by Eratosthenes, an ancient Greek mathematician.
*/
function eratosthenes($max) {
    $sieve = array_fill(2, ($max-1), false);
    while ($key = array_search(false, $sieve)) {
        $sieve[$key] = true;
        for ($i=$key*$key; $i<=$max; $i+=$key) {
            if (array_key_exists($i, $sieve)) {
                unset($sieve[$i]);
            }
        }
    }
    return array_keys($sieve);
}
?>
aflavio at gmail dot com 28-Feb-2007 11:29
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval)-1;$x++)
          {
              $i=array_search($val,$array_remval);
              if($i===false)return false;
              $array_remval=array_merge(array_slice($array_remval, 0,$i), array_slice($array_remval, $i+1));
          }
          return $array_remval;
    }

$stack = array("orange", "banana", "apple", "raspberry", "apple");

output $stack = array("orange", "banana", "raspberry");
rune at zedeler dot dk 27-Feb-2007 08:42
Notice that keys are considered equal if they are "=="-equal. That is:

<?
$a = array();
$a[1] = 'this is the first value';
$a[true] = 'this value overrides the first value';
$a['1'] = 'so does this one';
?>
Mark Lindeman 17-Jan-2007 02:10
Very simple solution for changing the key of an associative array, of course it will fail in a lot of scenarios, but will do the trick in simple arrays:

<?php
function replace_key(&$input, $from_key, $to_key)
{
    $input = unserialize(str_replace(':"'.$from_key.'";', ':"'.$to_key.'";',serialize($input)));
}

$array =array("a"=>1, "B"=>2, "c"=>3);
replace_key($array, "B", "b");
print_r($array);
?>
Output:
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)
php_spam {at] erif dot org 28-Dec-2006 10:52
public domain, yadda yadda. :)

This function takes a flatfile-like array (like the results of a joined query) and normalizes it based on whichever parameters you like.

<?php

  function hashByFields($things,$fields) {
    $retval=null;
    $count = count($fields);
    foreach ($things as $thing) {
      $fwibble =& $retval;
      for ($j=0;$j<$count;$j++) {
        $val = $thing[$fields[$j]];
        if ($j == $count - 1) {
          $fwibble[$val] = $thing;
        } else if (!isset($fwibble[$val])) {
          $fwibble[$val] = Array();
        }
        $fwibble =& $fwibble[$val];
      }
    }
    return $retval;
  }

?>
simone dot carletti at unimc dot it 28-Nov-2006 07:09
Ever wanted to obtain a subset of an associative array from a list of parameters (stored into a non-associative array)?
Give this a try:

<?php

$params = array("name" => "Simone", "gender" => "M", "city" => "Macerata", "phone" => 123);
$fields = array("name", "city");

echo "<pre>";
print_r($params);
print_r($fields);
print_r(subArr($params, $fields));

function subArr($assocArrHaystack, $arrFields)
{
    $arrSub = array();

    foreach ($assocArrHaystack as $key => $value) {
        if (in_array($key, $arrFields)) {
            $arrSub[$key] = $value;
        }
    }

    return $arrSub;
}

?>

And the output is:

Array
(
    [name] => Simone
    [gender] => M
    [city] => Macerata
    [phone] => 123
)
Array
(
    [0] => name
    [1] => city
)
Array
(
    [name] => Simone
    [city] => Macerata
)

Enjoy!

Simone
elkabong at samsalisbury dot co dot uk 13-Nov-2006 03:43
An improvement to the array_deep_copy function I posted ages ago which takes a 'snapshot' of an array, making copies of all actual values referenced... Now it is possible to prevent it traversing the tree forever when an array references itself. You can set the default $maxdepth to anything you like, you should never call this function with the $depth specified!
<?php
/* Make a complete deep copy of an array replacing
references with deep copies until a certain depth is reached
($maxdepth) whereupon references are copied as-is...  */
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
    if($depth > $maxdepth) { $copy = $array; return; }
    if(!is_array($copy)) $copy = array();
    foreach($array as $k => &$v) {
        if(is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
        } else {
            $copy[$k] = $v;
        }
    }
}

# call it like this:

array_deep_copy($array_to_be_copied,$deep_copy_of_array,$maxdepth);
?>
Hope someone finds it useful!
ob at babcom dot biz 28-Aug-2006 08:18
Regarding my own posting 2 postings down about the function ArrayDepth() to find the maximum depth of a multidimensional array:

A number of functions for counting array dimensions have been posted. And I tried using them. Yet, if at all they only return the depth of the first branch of the array. They can not handle arrays where a later path holds a more dimension than the first.

My version will check all paths down the array and return the maximum depth. That's why I posted it.
ob at babcom dot biz 28-Aug-2006 05:56
Here are two functions Array2String() and String2Array() based on functions posted below by daenders AT yahoo DOT com.

An improvement handling NULL values correctly was posted by designatevoid at gmail dot com.

My version also solves the NULL-value-problem plus keeps support of multidimensional arrays.

<?php
// convert a multidimensional array to url save and encoded string
// usage: string Array2String( array Array )

function Array2String($Array) {
  $Return='';
  $NullValue="^^^";
  foreach ($Array as $Key => $Value) {
    if(is_array($Value))
      $ReturnValue='^^array^'.Array2String($Value);
    else
      $ReturnValue=(strlen($Value)>0)?$Value:$NullValue;
    $Return.=urlencode(base64_encode($Key)) . '|' . urlencode(base64_encode($ReturnValue)).'||';
  }
  return urlencode(substr($Return,0,-2));
}
?>

<?php
// convert a string generated with Array2String() back to the original (multidimensional) array
// usage: array String2Array ( string String)

function String2Array($String) {
  $Return=array();
  $String=urldecode($String);
  $TempArray=explode('||',$String);
  $NullValue=urlencode(base64_encode("^^^"));
  foreach ($TempArray as $TempValue) {
    list($Key,$Value)=explode('|',$TempValue);
    $DecodedKey=base64_decode(urldecode($Key));
    if($Value!=$NullValue) {
      $ReturnValue=base64_decode(urldecode($Value));
      if(substr($ReturnValue,0,8)=='^^array^')
        $ReturnValue=String2Array(substr($ReturnValue,8));
      $Return[$DecodedKey]=$ReturnValue;
     }
    else
      $Return[$DecodedKey]=NULL;
  }
  return $Return;
}
?>
ob at babcom dot biz 28-Aug-2006 04:23
Here is a function to find out the maximum depth of a multidimensional array.

<?php
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

function ArrayDepth($Array,$DepthCount=-1,$DepthArray=array()) {
  $DepthCount++;
  if (is_array($Array))
    foreach ($Array as $Key => $Value)
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
  else
    return $DepthCount;
  foreach($DepthArray as $Value)
    $Depth=$Value>$Depth?$Value:$Depth;
  return $Depth;
}
?>
ob at babcom dot biz 28-Aug-2006 04:18
Regarding the function of spam at madhermit dot net from January 9th 2006:

That function only preserves the deepest keys and values.
If you try to flatten an array with that function where the deepest instance of keys might be the same where as keys in the "key-path" are different, values will be overwritten.

So here is a function that preserves the whole key-path and the keys of the flattened array will be string keys consisting of the key-path separated by $Separator.

<?php
// flatten multidimensional array to one dimension
// preserves keys by generating a key for the flattened array which consists of the
// key-path of the multidimensional array separated by $Separator
// usage: array ArrayFlatten( array Array [, string Separator] )

function ArrayFlatten($Array,$Separator="_",$FlattenedKey='') {
  $FlattenedArray=Array();
  foreach($Array as $Key => $Value) {
    if(is_Array($Value))
      $FlattenedArray=Array_merge($FlattenedArray,
                                  ArrayFlatten($Value,$Separator,
                                               (strlen($FlattenedKey)>0
                                                ?$FlattenedKey.$Separator
                                                :"").$Key)
                                               );
    else
      $FlattenedArray[$FlattenedKey.$Separator.$Key]=$Value;
  }
  return $FlattenedArray;
}
?>
sergio at {NO_SPAM_PLEASE]inservibile dot org 16-Aug-2006 05:17
In a pratical problem, I was involved in a system of queries giving the behaviour of all combinations of some parameters. How to write those queries?
The problem was to generate automatically every possible combination of those parameters. I didn't find a function and I wrote it.
(Naturally, a different way could be to build a binary sequence, but I find this function more compact and useful).
So, consider an array of objects and suppose to need all possibile combinations of those objects. Here is the function, that could be useful for some folk.
Enjoy.

<?php
function combinations($elements) {
         if (is_array($elements)) {
            /*
            I want to generate an array of combinations, i.e. an array whose elements are arrays
            composed by the elements of the starting object, combined in all possible ways.
            The empty array must be an element of the target array.
            */
            $combinations=array(array()); # don't forget the empty arrangement!
            /*
            Built the target array, the algorithm is to repeat the operations below for each object of the starting array:
            - take the object from the starting array;
            - generate all arrays given by the target array elements merged with the current object;
            - add every new combination to the target array (the array of arrays);
            - add the current object (as a vector) to the target array, as a combination of one element.
            */
            foreach ($elements as $element) {
                    $new_combinations=array(); # temporary array, see below
                    foreach ($combinations as $combination) {
                            $new_combination=array_merge($combination,(array)$element);
                            # I cannot merge directly with the main array ($combinations) because I'm in the foreach cycle
                            # I use a temporary array
                            array_push($new_combinations,$new_combination);
                            }
                    $combinations=array_merge($combinations,$new_combinations);
                    }
            return $combinations;
            } else {
            return false;
            }
         }
?>

To test the function:

<?php
$elements=array('bitter','sour','salty','sweet');
print_r(combinations($elements));
?>

The exemple was suggested in 6th century BC.
See why on: http://en.wikipedia.org/wiki/Combinatorics#Overview_and_history
za at byza dot it 20-Jul-2006 08:52
Updated functions for moving element between associative arrays using a numeric index.

Sample:
$a=array("04"=>"alpha",4=>"bravo","c"=>"charlie","d"=>"delta");
$b=array_move($a,4,2);

Move element "bravo" after "delta" keeping keys.
Old function probably goes wrong moving "alpha": caused by array_search that match numeric index 4 with "04" (string).

Follow:

<?php
// array functions - 20/07/2006 12.28

if(!defined("ARRAY_FUNCS")) {
    // Swap 2 elements in array preserving keys.
    function array_swap(&$array,$key1,$key2) {
        $v1=$array[$key1];
        $v2=$array[$key2];
        $out=array();
        foreach($array as $i=>$v) {
            if($i===$key1) {
                $i=$key2;
                $v=$v2;
            } else if($i===$key2) {
                $i=$key1;
                $v=$v1;
            }
            $out[$i]=$v;
        }
        return $out;
    }

    //  Get a key position in array
    function array_kpos(&$array,$key) {
        $x=0;
        foreach($array as $i=>$v) {
            if($key===$i) return $x;
            $x++;
        }
        return false;
    }

    // Return key by position
    function array_kbypos(&$array,$pos) {
        $x=0;
        foreach($array as $i=>$v) {
            if($pos==$x++) return $i;
        }
        return false;
    }

    // Move an element inside an array preserving keys
    // $relpos should be like -1, +2...
    function array_move(&$array,$key,$relpos) {
        if(!$relpos) return false;
        $from=array_kpos($array,$key);
        if($from===false) return false;
        $to=$from+$relpos+($relpos>0?1:0);
        $len=count($array);
        if($to>=$len) {
            $val=$array[$key];
            unset($array[$key]);
            $array[$key]=$val;
        } else {
            if($to<0) $to=0;
            $new=array();
            $x=0;
            foreach($array as  $i=>$v) {
                if($x++==$to) $new[$key]=$array[$key];
                if($i!==$key) $new[$i]=$v;
            }
            $array=$new;
        }
        return $array;
    }

    define("ARRAY_FUNCS",true);
}
?>
g8z at yahoo dot com 19-Jul-2006 01:42
<?php
/**
filter_by_occurrence scans an array, and depending on the $exclusive parameter, includes or excludes elements occuring at least $min_occurences times, and at most $max_occurances times.

parameters:

$data_set = the array to work on
$min_occurrences = the minimum number of occurrences
$max_occurrences = the maximum number of occurrences (zero for unlimited)
$exclusive = if true, will return only results that do not occur within the specified bounds

Courtesy of the $5 Script Achive: http://www.tufat.com
**/

function filter_by_occurrence ($data_set, $min_occurrences, $max_occurrences = 0, $exclusive = false) {
    $results = array();

    // iterate through unique elements
    foreach (array_unique($data_set) as $value) {

        // count how many times element is in the array
        $count = 0;
        foreach ($data_set as $element) {
            if ($element == $value)
                $count++;
        }

        // check if meets min_occurences
        $is_in_range = false;

        if ($count >= $min_occurrences) {
            // check if meets max_occurrences (unless max_occurences is 0)
            if ( $count <= $max_occurrences || $max_occurrences == 0)
                $is_in_range = true;
        }

        // add item to array if appropriate
        if ($is_in_range && !$exclusive)
            array_push($results, $value);
        if (!$is_in_range && $exclusive)
            array_push($results, $value);
    }

    // return results
    return $results;
}

// EXAMPLE:

$test_data = array('pizza', 'ham', 'pizza', 'pizza', 'ham', 'fish', 'fish', 'fish', 'fish', 'dinosaur');

foreach (filter_by_occurrence( $test_data, 3, 0, false ) as $value)
{
    print $value . ' occurs at least 3 times. <br />';
}

?>
nick 11-Jul-2006 05:46
This little function will move an array element up or down. Unlike the similar function in a previous comment this will work for associative arrays too.

Because it uses current to traverse the array it will fail if a value is false (or 0). It could probably be rewritten to use each() but I couldn't work it out.
<?php
function array_move_element($array, $value, $direction = 'up') {

    $temp = array();

    if(end($array) == $value && $direction == 'down') {
        return $array;
    }
    if(reset($array) == $value && $direction == 'up') {
        return $array;
    }

    while ($array_value = current($array)) {

        $this_key = key($array);

        if ($array_value == $value) {
            if($direction == 'down') {
                $next_value = next($array);
                $temp[key($array)] = $next_value;
                $temp[$this_key] = $array_value;
            } else {
                $prev_value = prev($array);
                $prev_key = key($array);
                unset($temp[$prev_key]);
                $temp[$this_key] = $array_value;
                $temp[$prev_key] = $prev_value;
                next($array);
                next($array);
            }
            continue;
        } else {
            $temp[$this_key] = $array_value;
        }

        next($array);
    }
    return $temp;

}
?>
kroczu at interia dot pl 06-Jul-2006 06:53
<?
//A little function to convert array to simle xml:

function array_xml($array, $num_prefix = "num_")
{
    if(!is_array($array)) // text
    {
        return $array;
    }
    else
    {
        foreach($array as $key=>$val) // subnode
        {
            $key = (is_numeric($key)? $num_prefix.$key : $key);
            $return.="<".$key.">".array_xml($val, $num_prefix)."</".$key.">";
        }
    }

    return $return;
}

//example:

$array[0][0]                    = 1;
$array[0]['test']               = "test";
$array['test1']['test2']        = "test";
$array['test'][0]               = "test";
$array['test'][1]['test_x']     = $array;

print_r($array);

print"<xml>";

print array_xml($array);

print"</xml>";

/*

print_r($array) previev:

Array
(
    [0] => Array
        (
            [0] => 1
            [test] => test
        )
    [test1] => Array
        (
            [test2] => test
        )
    [test] => Array
        (
            [0] => test
            [1] => Array
                (
                    [test_x] => Array
                        (
                            [0] => Array
                                (
                                    [0] => 1
                                    [test] => test
                                )
                            [test1] => Array
                                (
                                    [test2] => test
                                )
                            [test] => Array
                                (
                                    [0] => test
                                )
                        )
                )
        )
)

result xml in firefox preview:

-<xml>
    -     <num_0>
            <num_0>1</num_0>
            <test>test</test>
        </num_0>
    -    <test1>
            <test2>test</test2>
        </test1>
    -    <test>
            <num_0>test</num_0>
        -    <num_1>
            -    <test_x>
                -    <num_0>
                        <num_0>1</num_0>
                        <test>test</test>
                    </num_0>
                -    <test1>
                        <test2>test</test2>
                    </test1>
                -    <test>
                        <num_0>test</num_0>
                    </test>
                </test_x>
            </num_1>
        </test>
 </xml>

*/
?>
vinaur at gmail dot com 06-Jun-2006 01:36
Regarding the array to string (parse_line) and string to array (parse_array) functions posted below by Kevin Law.

The functions will not work correctly if the array being parsed contains values that include commas and possibly parentheses.

To solve this problem I added urlencode and urldecode functions and the result looks like this:

<?php
function parse_line($array){
    $line = "";
    foreach($array AS $key => $value){
        if(is_array($value)){
            $value = "(". parse_line($value) . ")";
        }
        else
        {
            $value = urlencode($value);
        }
        $line = $line . "," . urlencode($key) . ":" . $value . "";
    }
    $line = substr($line, 1);
    return $line;
}

function parse_array($line){
   $q_pos = strpos($line, ":");
   $name = urldecode(substr($line,0,$q_pos));
   $line = trim(substr($line,$q_pos+1));
   $open_backet_pos = strpos($line, "(");

   if($open_backet_pos===false || $open_backet_pos>0){
       $comma_pos = strpos($line, ",");
       if($comma_pos===false){
           $result[$name] = urldecode($line);
           $line = "";
       }else{
           $result[$name] = urldecode(substr($line,0,$comma_pos));
           $result = array_merge($result, parse_array(substr($line,$comma_pos+1)));
           $line = "";
       }
   }else if ($open_backet_pos==0){
       $line = substr($line,1);
       $num_backet = 1;
       $line_char_array = str_split($line);
       for($index = 0; count($line_char_array); $index++){
           if($line_char_array[$index] == '('){
               $num_backet++;
           }else if ($line_char_array[$index] == ')'){
               $num_backet--;
           }
           if($num_backet == 0){
               break;
           }
       }
       $sub_line = substr($line,0,$index);
       $result[$name] = parse_array($sub_line);
       $line = substr($line,$index+2);
   }
   if(strlen($line)!=0){
       $result = array_merge($result, parse_array($line));
   }

   return $result;
}
?>
elkabong at samsalisbury dot co dot uk 24-Mar-2006 02:31
Hello all! I've just been working on a system to automatically manage virtualhosts on an Apache box and I needed to duplicate some multidimensional arrays containing references to other multidimensional array some of which also contained references. These big arrays are defaults which need to be overwritten on a per-virtualhost basis, so copying references into the virtualhost arrays was not an option (as the defults would get corrupted).

After hours of banging me head on the wall, this is what I've come up with:
<?PHP # Tested on PHP Version 5.0.4
# Recursively set $copy[$x] to the actual values of $array[$x]
function array_deep_copy (&$array, &$copy) {
    if(!is_array($copy)) $copy = array();
    foreach($array as $k => $v) {
        if(is_array($v)) {
            array_deep_copy($v,$copy[$k]);
        } else {
            $copy[$k] = $v;
        }
    }
}
# To call it do this:
$my_lovely_reference_free_array = array();
array_deep_copy($my_array_full_of_references, $my_lovely_reference_free_array);
# Now you can modify all of $my_lovely_reference_free_array without
# worrying about $my_array_full_of_references!
?>
NOTE: Don't use this on self-referencing arrays! I haven't tried it yet but I'm guessing an infinate loop will occur...

I hope someone finds this useful, I'm only a beginner so if there's any fatal flaws or improvements please let me know!
alessandronunes at gmail dot com 18-Mar-2006 02:06
The Ninmja sugestion plus multidiomensional array search (recursive):

function cleanArray($array) {
   foreach ($array as $index => $value) {
        if(is_array($array[$index])) $array[$index] = cleanArray($array[$index]);
        if (empty($value)) unset($array[$index]);
   }
   return $array;
}
Atomo64 03-Jan-2006 05:14
Here's a simple way to convert an array to a string and vice-versa.
Note that it does NOT support string keys,
for more information take a look at what it does:

<?php
class OptionAsArray
{
    function make_the_arr($value)
    {
        $newValue=array();
        $vals=explode('&',$value);
        foreach($vals as $v)
        {
            if($v{0}=='@')
            $newValue[]=$this->make_the_arr(
            urldecode(substr($v,1)));
            else
            $newValue[]=urldecode($v);
        }
        if(empty($newValue))
        return false;
        else
        return $newValue;
    }
    function make_the_value($arr)
    {
        $newValue=array();
        foreach($arr as $value)
        {
            if(is_array($value))
            $newValue[]='@'.urlencode(
            implode('&',$this->make_the_value($value)));
            else
            $newValue[]=urlencode($value);
        }
        if(empty($newValue))
        return false;
        else
        return $newValue;
    }
}
?>
jonathan at sharpmedia dot net 05-Dec-2005 06:37
/**
 * Flattens a multimentional array.
 *
 * Takes a multi-dimentional array as input and returns a flattened
 * array as output. Implemented using a non-recursive algorithm.
 * Example:
 * <code>
 * $in = array('John', 'Jim', array('Jane', 'Jasmine'), 'Jake');
 * $out = array_flatten($in);
 * // $out = array('John', 'Jim', 'Jane', 'Jasmine', 'Jake');
 * </code>
 *
 * @author        Jonathan Sharp <jonathan@sharpmedia.net>
 * @var            array
 * @returns        array
 */
function array_flatten($array)
{
    while (($v = array_shift($array)) !== null) {
        if (is_array($v)) {
            $array = array_merge($v, $array);
        } else {
            $tmp[] = $v;
        }
    }

    return $tmp;
}
stalker at ruun dot de 20-Nov-2005 01:15
I had some problems while selecting sub-arrays from multi-dimensional arrays (like the SQL-WHERE clause), so i wrote the following function:

<?php
function selectMultiArray($__multiarray,$__key,$__value) {
  foreach($__multiarray as $multipart) {
    if($multipart[$__key] == $__value) {
      $__return[] = $multipart;
    }
  }
  if(empty($__return)) {
    return FALSE;
  }
  return $__return;
}
?>

hope someones finding this helpful. If you have better was for getting to this, please answer.

greets,
St4Lk3R
msajko at gmail dot com 19-Oct-2005 01:25
array_to_string and sister function string_to_array with multi dimensional array support.

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
   $retval = '';
   $null_value = "^^^";
   foreach ($array as $index => $val) {
       if(gettype($val)=='array') $value='^^array^'.array_to_string($val);    else $value=$val;
       if (!$value)
           $value = $null_value;
       $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
   }
   return urlencode(substr($retval, 0, -2));
}

// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
   $retval = array();
   $string = urldecode($string);
   $tmp_array = explode('||', $string);
   $null_value = urlencode(base64_encode("^^^"));
   foreach ($tmp_array as $tmp_val) {
       list($index, $value) = explode('|', $tmp_val);
       $decoded_index = base64_decode(urldecode($index));
       if($value != $null_value){
           $val= base64_decode(urldecode($value));
           if(substr($val,0,8)=='^^array^') $val=string_to_array(substr($val,8));
           $retval[$decoded_index]=$val;
          }
       else
           $retval[$decoded_index] = NULL;
   }
   return $retval;
}
phpnet_spam at erif dot org 17-Oct-2005 06:36
Thought this might save someone a few hours. :)  Feedback welcome, of course!  Public domain, yadda yadda.

function assocSort(&$array,$key) {
    if (!is_array($array) || count($array) == 0) return true;
    $assocSortCompare  = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';

    if (is_numeric($array[0][$key])) {
      $assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
    } else {
      $assocSortCompare.= ' return strcmp($a,$b);';
    }

    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    return usort($array,$assocSortCompare);
}
designatevoid at gmail dot com 13-Oct-2005 06:40
Here's an improvement to the array_to_string and string_to_array functions posted by daenders AT yahoo DOT com above.

They now handle NULL values correctly.

<?php

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
    $retval = '';
    $null_value = "^^^";
    foreach ($array as $index => $value) {
        if (!$value)
            $value = $null_value;
        $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
    }
    return urlencode(substr($retval, 0, -2));
}

// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
    $retval = array();
    $string = urldecode($string);
    $tmp_array = explode('||', $string);
    $null_value = urlencode(base64_encode("^^^"));
    foreach ($tmp_array as $tmp_val) {
        list($index, $value) = explode('|', $tmp_val);
        $decoded_index = base64_decode(urldecode($index));
        if($value != $null_value)
            $retval[$decoded_index] = base64_decode(urldecode($value));
        else
            $retval[$decoded_index] = NULL;
    }
    return $retval;
}

?>
aidan at php dot net 09-Oct-2005 01:32
To convert an array to a HTML table, see:
http://aidanlister.com/repos/v/function.array2table.php

PEAR also provides a simular package with many more features,
http://pear.php.net/package/Var_Dump
za at lombardiacom dot it 27-Sep-2005 08:01
<?php
    // Swap 2 elements in array preserving keys.
    function array_swap(&$array,$key1,$key2) {
        $v1=$array[$key1];
        $v2=$array[$key2];
        $out=array();
        foreach($array as $i=>$v) {
            if($i==$key1) {
                $i=$key2;
                $v=$v2;
            } else if($i==$key2) {
                $i=$key1;
                $v=$v1;
            }
            $out[$i]=$v;
        }
        return $out;
    }

    // Move an element inside an array preserving keys.
    function array_move(&$array,$key,$position) {
        $from=array_search($key,array_keys($array));
        $to=$from+$position;
        $tot=count($array);
        if($position>0) $to++;
        if($to<0) $to=0;
        else if($to>=$tot) $to=$tot-1;
        $n=0;
        $out=array();
        foreach($array as $i=>$v) {
            if($n==$to) $out[$key]=$array[$key];
            if($n++==$from) continue;
            $out[$i]=$v;
        }
        return $out;
    }
?>
Domenic Denicola 15-Aug-2005 11:49
Another JavaScript conversion, this time to objects instead of arrays. They can be accessed the same way, but are declared much shorter, so it saves some download time for your users:

<?
function PhpArrayToJsObject($array, $objName)
{
    return 'var ' . $objName . ' = ' . PhpArrayToJsObject_Recurse($array) . ";\n";
}

function PhpArrayToJsObject_Recurse($array)
{
    // Base case of recursion: when the passed value is not a PHP array, just output it (in quotes).
    if(! is_array($array) )
    {
        // Handle null specially: otherwise it becomes "".
        if ($array === null)
        {
            return 'null';
        }

        return '"' . $array . '"';
    }

    // Open this JS object.
    $retVal = "{";

    // Output all key/value pairs as "$key" : $value
    // * Output a JS object (using recursion), if $value is a PHP array.
    // * Output the value in quotes, if $value is not an array (see above).
    $first = true;
    foreach($array as $key => $value)
    {
        // Add a comma before all but the first pair.
        if (! $first )
        {
            $retVal .= ', ';
        }
        $first = false;

        // Quote $key if it's a string.
        if (is_string($key) )
        {
            $key = '"' . $key . '"';
        }

        $retVal .= $key . ' : ' . PhpArrayToJsObject_Recurse($value);
    }

    // Close and return the JS object.
    return $retVal . "}";
}
?>

Difference from previous function: null values are no longer "" in the object, they are JavaScript null.

So for example:

<?
$theArray = array("A" => array("a", "b", "c" => array("x")), "B" => "y");
echo PhpArrayToJsObject($theArray, "myArray");
?>

Gives:

var myArray = {"A" : {0 : "a", 1 : "b", "c" : {0 : "x"}}, "B" : "y"};

You can still access them just like arrays, with myArray["A"][0] or myArray["A"]["c"][0] or whatever. Just shrinks your pages.
dieter peeters 11-Aug-2005 04:35
in response to: Domenic Denicola

I reworked your function a bit and thought i just as well could post it.

Below is the cleaner version, just cut and paste ;) The third parameter is of little use to the coder, unless javascript declaration of variables changes at some point in the future - who knows.

Only minor point is the added parameter which probably gets copied every recursive call with an empty value, though i don't know the exact ways how php handles recursion internally. Most of the time php is pretty smart when optimizing code and an empty string shouldn't take much memory anyway :)

<?php
function phpArrayToJsArray($name,$array,$prePend='var ')
{
    if (is_array($array)) { // Array recursion
        $result = $name.' = new Array();'."\n";
        foreach ($array as $key => $value) {
           $result .= phpArrayToJsArray($name.'["'.$key.'"]',$value,'');
        }
    } else {  // Base case of recursion
        $result = $name.' = "'.$array.'";'."\n";
    }
    return $prePend.$result;
}
?>
michael at imreo com 21-Jul-2005 05:20
Reply to array_cartesian_product of skopek at mediatac dot com, 13-Oct-2004 12:44:

Your function does not work in my configuration (WinXP, apache 2.0, php 4.3.11).
This part of code:
...
} else { //if next returns false, then reset and go on with previuos array...
  reset($arrays[$j]);
}
...
cause infinite loop.
Replacing to
...
} elseif (isset($arrays[$j])) {
  reset($arrays[$j]);
}
...
works good.

My complete working function (additionaly strings as keys are allowed):
<?php
function array_cartesian_product($arrays)
{
    $result = array();
    $arrays = array_values($arrays);
    $sizeIn = sizeof($arrays);
    $size = $sizeIn > 0 ? 1 : 0;
    foreach ($arrays as $array)
        $size = $size * sizeof($array);
    for ($i = 0; $i < $size; $i ++)
    {
        $result[$i] = array();
        for ($j = 0; $j < $sizeIn; $j ++)
            array_push($result[$i], current($arrays[$j]));
        for ($j = ($sizeIn -1); $j >= 0; $j --)
        {
            if (next($arrays[$j]))
                break;
            elseif (isset ($arrays[$j]))
                reset($arrays[$j]);
        }
    }
    return $result;
}
?>
daenders AT yahoo DOT com 08-Jul-2005 01:49
Several people here have posted functions for converting arrays to strings, but nobody posted a sister function that would convert it back.  Also, their data is not URL safe.  These functions are URL safe, hide the data by MIME encoding it, and are much shorter.  Enjoy.  :-)

<?php

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
    $retval = '';
    foreach ($array as $index => $value) {
        $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
    }
    return urlencode(substr($retval, 0, -2));
}

// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
    $retval = array();
    $string = urldecode($string);
    $tmp_array = explode('||', $string);
    foreach ($tmp_array as $tmp_val) {
        list($index, $value) = explode('|', $tmp_val);
        $retval[base64_decode(urldecode($index))] = base64_decode(urldecode($value));
    }
    return $retval;
}

// Example:
$array1 = array('index1' => 'val1', 'index2' => 'val2', 'index3' => 'val3');
echo '<pre>'; print_r($array1); echo '</pre>';
$string = array_to_string($array1);
echo '$string: '.$string.'<br />';
$array2 = string_to_array($string);
echo '<pre>'; print_r($array2); echo '</pre>';

?>
m227(a)poczta.onet.pl 20-Jan-2005 08:18
How to count dimensions in multi-array? (corrected)

previous version didn't work when called more than one time.
($dimcount was preserved from previous call)

This is the way I corrected this:

function countdim($array)
  {
    if (is_array(reset($array)))
      $return = countdim(reset($array)) + 1;
    else
      $return = 1;

    return $return;
  }

This function will return int number of array dimensions.
Сортировка массивов
array_change_key_case
Массивы


Меняет регистр ключей в массиве

Функции для работы с массивами
array_chunk
Функции для работы с массивами
PHP Manual

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case — Меняет регистр ключей в массиве

Описание

array array_change_key_case ( array $input [, int $case = CASE_LOWER ] )

Возвращает массив input, все ключи которого преобразованы в нижний или верхний регистр. Числовые ключи останутся нетронутыми.

Список параметров

input

Обрабатываемый массив

case

Либо CASE_UPPER, либо CASE_LOWER (используется по умолчанию)

Возвращаемые значения

Возвращает массив с ключами, преобразованными в верхний или нижний регистр, либо FALSE, если input не является массивом.

Ошибки

Генерирует ошибку уровня E_WARNING, если input не является массивом.

Примеры

Пример #1 Пример использования array_change_key_case()

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

Результат выполнения данного примера:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

Примечания

Замечание:

Если массив содержит индексы, которые станут одноименными после применения данной функции (например, "keY" и "kEY"), значение последнего одноименного индекса перекроет другие совпадающие значения из этого массива.

User Contributed Notes

qeremy [atta] gmail [dotta] com 28-Feb-2012 05:15
Unicode example;

<?php
function array_change_key_case_unicode($arr, $c = CASE_LOWER) {
    $c = ($c == CASE_LOWER) ? MB_CASE_LOWER : MB_CASE_UPPER;
    foreach ($arr as $k => $v) {
        $ret[mb_convert_case($k, $c, "UTF-8")] = $v;
    }
    return $ret;
}

$arr = array("FirSt" => 1, "yağ" => "Oil", "şekER" => "sugar");
print_r(array_change_key_case($arr, CASE_UPPER));
print_r(array_change_key_case_unicode($arr, CASE_UPPER));
?>

Array
(
    [FIRST] => 1
    [YAğ] => Oil
    [şEKER] => sugar
)
Array
(
    [FIRST] => 1
    [YAĞ] => Oil
    [ŞEKER] => sugar
)
JOE 19-Oct-2011 11:13
Script to change case of sub-arrays keys to lower . It works well for me. hope it helps.

<?php
$array=array("First"=>"val1","SecoNd"=>"val2",
"third"=>array("third-INner1"=>"val3.1"),
"fourth"=>array("FouthINNer1"=>"val4.1","FourthINNER2"=>"val4.2"));
print_r($array);
$key=array_keys($array);
foreach($key as $ki)
{
    $klower=strtolower($ki);
    $val=$array[$ki];
    if(is_array($val))
    {
        foreach($val as $kinner=>$vinner)
        {

            $tl=strtolower($kinner);
            unset($val[$kinner]);
            $val[$tl]=$vinner;
        }
    }
    unset($array[$ki]);
    $array[$klower]=$val;
}
echo "<br> After Changing Key to-LowerCase : <br>";
print_r($array);

?>
Lus Henrique Pessoa 24-Sep-2010 09:03
<?php

// improving the previous script
function ack_r3(&$array, $case=CASE_LOWER, $flag_rec=false)
    {
      $array = array_change_key_case($array, $case);
      if ( $flag_rec ) {
        foreach ($array as $key => $value) {
            if ( is_array($value) ) {
                ack_r3($array[$key], $case, true);
            }
        }
      }
    }

// same of array_change_key_case
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,false);
    var_dump($arr);

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,true);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["PHONE"]=>
    string(9) "3010-7148"
    ["E-MAIL"]=>
    string(12) "luis@net.com"
  }
}
array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
Luis Henrique Pessoa 23-Sep-2010 09:25
Script to change case of sub-arrays keys:

<?php

    function arrKey2Lower(&$arrVals) {
        foreach( $arrVals as $key => $item ) {
            $key2 = strtolower($key);
            if ( $key2 != $key) {
                unset($arrVals[$key]);
                $arrVals[$key2]=$item;
                $key=$key2;
            }

            if ( is_array($item) ) { arrKey2Lower($arrValores[$key]); }
        }
    }

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    arrKey2Lower($arr);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
info at microweb dot lt 29-Nov-2009 02:07
Simple function to change multidimensional array's all values to uppercase. If you would like to change to lowercase then change "mb_strtoupper" to  "mb_strtolower". It works perfect for me ;)

<?php
function change_case_recursive($arr){
    foreach ($arr as $key=>$val){
        if (!is_array($arr[$key])){
            $arr[$key]=mb_strtoupper($arr[$key]);
        }else{
            $arr[$key]=change_case_recursive($arr[$key]);
        }
    }
    return $arr;
}
?>
david at ramaboo dot com 02-Feb-2009 03:22
Same as array_change_key_case only with the values. This should really be part of PHP!

<?php
/**
 * @brief Returns an array with all values lowercased or uppercased.
 * @return array Returns an array with all values lowercased or uppercased.
 * @param object $input The array to work on
 * @param int $case [optional] Either \c CASE_UPPER or \c CASE_LOWER (default).
 */
function array_change_value_case(array $input, $case = CASE_LOWER) {
    switch ($case) {
        case CASE_LOWER:
            return array_map('strtolower', $input);
            break;
        case CASE_UPPER:
            return array_map('strtoupper', $input);
            break;
        default:
            trigger_error('Case is not valid, CASE_LOWER or CASE_UPPER only', E_USER_ERROR);
            return false;
    }
}
?>
charles 12-Jan-2009 11:38
<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>
anon at ymous dot com 02-Dec-2008 03:19
Below is a recursive version of this function.

<?php
    /**
     * A recursive array_change_key_case function.
     * @param array $input
     * @param integer $case
     */
    function array_change_key_case_recursive($input, $case = null){
        if(!is_array($input)){
            trigger_error("Invalid input array '{$array}'",E_USER_NOTICE); exit;
        }
        // CASE_UPPER|CASE_LOWER
        if(null === $case){
            $case = CASE_LOWER;
        }
        if(!in_array($case, array(CASE_UPPER, CASE_LOWER))){
            trigger_error("Case parameter '{$case}' is invalid.", E_USER_NOTICE); exit;
        }
        $input = array_change_key_case($input, $case);
        foreach($input as $key=>$array){
            if(is_array($array)){
                $input[$key] = array_change_key_case_recursive($array, $case);
            }
        }
        return $input;
    }
?>
andreas dot schuhmacher87 at googlemail dot com 14-Apr-2008 06:01
multibyte and multi-dimensional-array support, have fun!

<?php
    define('ARRAY_KEY_FC_LOWERCASE', 25); //FOO => fOO
    define('ARRAY_KEY_FC_UPPERCASE', 20); //foo => Foo
    define('ARRAY_KEY_UPPERCASE', 15); //foo => FOO
    define('ARRAY_KEY_LOWERCASE', 10); //FOO => foo
    define('ARRAY_KEY_USE_MULTIBYTE', true); //use mutlibyte functions

    /**
    * change the case of array-keys
    *
    * use: array_change_key_case_ext(array('foo' => 1, 'bar' => 2), ARRAY_KEY_UPPERCASE);
    * result: array('FOO' => 1, 'BAR' => 2)
    *
    * @param    array
    * @param    int
    * @return     array
    */
    function array_change_key_case_ext(array $array, $case = 10, $useMB = false, $mbEnc = 'UTF-8') {
        $newArray = array();

        //for more speed define the runtime created functions in the global namespace

        //get function
        if($useMB === false) {
            $function = 'strToUpper'; //default
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    //maybee lcfirst is not callable
                    if(!function_exists('lcfirst'))
                        $function = create_function('$input', '
                            return strToLower($input[0]) . substr($input, 1, (strLen($input) - 1));
                        ');
                    else $function = 'lcfirst';
                    break;

                //first-char-to-uppercase
                case 20:
                    $function = 'ucfirst';
                    break;

                //lowercase
                case 10:
                    $function = 'strToLower';
            }
        } else {
            //create functions for multibyte support
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    $function = create_function('$input', '
                        return mb_strToLower(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //first-char-to-uppercase
                case 20:
                    $function = create_function('$input', '
                        return mb_strToUpper(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //uppercase
                case 15:
                    $function = create_function('$input', '
                        return mb_strToUpper($input, \'' . $mbEnc . '\');
                    ');
                    break;

                //lowercase
                default: //case 10:
                    $function = create_function('$input', '
                        return mb_strToLower($input, \'' . $mbEnc . '\');
                    ');
            }
        }

        //loop array
        foreach($array as $key => $value) {
            if(is_array($value)) //$value is an array, handle keys too
                $newArray[$function($key)] = array_change_key_case_ex($value, $case, $useMB);
            elseif(is_string($key))
                $newArray[$function($key)] = $value;
            else $newArray[$key] = $value; //$key is not a string
        } //end loop

        return $newArray;
    }
?>
dot dot dot dot dot alexander at gmail dot com 30-Jan-2008 09:22
Basically this is the function if your version is lower than 4.2.0
<?php
if ( !defined('CASE_LOWER') )define('CASE_LOWER', 0);
if ( !defined('CASE_UPPER') )define('CASE_UPPER', 1);

if(!function_exists("array_change_key_case")){
    function array_change_key_case($input, $case=0){
        if(!is_array($input))return FALSE;
        $product = array();
        foreach($input as $key => $value){
            if($case){ //Upper
                $key2 = (  (is_string($key)) ? (strtoupper($key)) : ($key)  );
                $product[$key2] = $value;
            }
            else{ //Lower
                $key2 = (  (is_string($key)) ? (strtolower($key)) : ($key)  );
                $product[$key2] = $value;
            }
        }
        return $product;
    }/* endfunction array_change_key_case */
}/* endfunction exists array_change_key_case*/
?>
john at doe dot com 26-Sep-2007 12:04
<?php
function array_change_value_case($input, $case = CASE_LOWER)
{
    $aRet = array();

    if (!is_array($input))
    {
        return $aRet;
    }

    foreach ($input as $key => $value)
    {
        if (is_array($value))
        {
            $aRet[$key] = array_change_value_case($value, $case);
            continue;
        }

        $aRet[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
    }

    return $aRet;
}
?>
cm at gameswelt dot de 10-Aug-2007 04:11
I just changed the code a little bit so you havent got a code that repeats itself.

<?php

function array_change_key_case_secure($array = array(), $case = CASE_UPPER){
    $secure = array();
    $functionWrap = array(CASE_UPPER => 'strtoupper',
                            CASE_LOWER => 'strtolower');

    foreach($array as $key => $val){
        if(isset($functionWrap[$key])){
            $key = $functionWrap[$case]($key);
            $secure[$key][] = $val;
        } else {
            die('Not a known Type');
        }
    }

    foreach($secure as $key => $val){
        if(count($secure[$key]) == 1){
            $secure[$key] = $val[0];
        }
    }

    return $secure;
}

$myArray = array('A' => 'Hello',
                    'B' => 'World',
                    'a' => 'how are you?');

print_r($myArray);
$myArray = array_change_key_case_secure($myArray);
print_r($myArray);

/*
Array
(
    [A] => Hello
    [B] => World
    [a] => how are you?
)
Array
(
    [A] => Array
        (
            [0] => Hello
            [1] => how are you?
        )

    [B] => World
)
*/
aidan at php dot net 01-Jun-2004 08:06
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
Функции для работы с массивами
array_chunk
Функции для работы с массивами


Разбивает массив на части

array_change_key_case
array_combine
Функции для работы с массивами
PHP Manual

array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk — Разбивает массив на части

Описание

array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )

Разбивает массив на несколько частей размером size. Последний массив из полученных может содержать меньшее количество значений, чем указано в size.

Список параметров

input

Обрабатываемый массив

size

Размер каждой части

preserve_keys

Если установлено в TRUE, ключи оригинального массива будут сохранены. По умолчанию установлено в FALSE, что переиндексирует каждую часть с числовыми ключами

Возвращаемые значения

Возвращает многомерный массив с числовыми индексами, начинающимися с нуля, каждый элемент которого содержит size элементов из оригинального массива.

Ошибки

Если size меньше 1, будет сгенерирована ошибка уровня E_WARNING и возвращен NULL.

Примеры

Пример #1 Пример использования array_chunk()

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

Результат выполнения данного примера:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

Смотрите также

  • array_slice() - Выбирает срез массива

User Contributed Notes

nate at ruggfamily dot com 19-Jul-2010 09:00
If you just want to grab one chunk from an array, you should use array_slice().
dead dot screamer at seznam dot cz 27-Jan-2009 02:28
This function can be used to reverse effect of <?php array_Chunk()?>.
<?php
function array_Unchunk($array)
{
    return call_User_Func_Array('array_Merge',$array);
}

header('Content-Type: text/plain');
$array=array(
    array(
            'Black Canyon City',
            'Chandler',
            'Flagstaff',
            'Gilbert',
            'Glendale',
            'Globe',
    ),
    array(
            'Mesa',
            'Miami',
            'Phoenix',
            'Peoria',
            'Prescott',
            'Scottsdale',
    ),
    array(
            'Sun City',
            'Surprise',
            'Tempe',
            'Tucson',
            'Wickenburg',
    ),
);
var_Dump(array_Unchunk($array));
?>

Output:
array(17) {
  [0]=>
  string(17) "Black Canyon City"
  [1]=>
  string(8) "Chandler"
  [2]=>
  string(9) "Flagstaff"
  [3]=>
  string(7) "Gilbert"
  [4]=>
  string(8) "Glendale"
  [5]=>
  string(5) "Globe"
  [6]=>
  string(4) "Mesa"
  [7]=>
  string(5) "Miami"
  [8]=>
  string(7) "Phoenix"
  [9]=>
  string(6) "Peoria"
  [10]=>
  string(8) "Prescott"
  [11]=>
  string(10) "Scottsdale"
  [12]=>
  string(8) "Sun City"
  [13]=>
  string(8) "Surprise"
  [14]=>
  string(5) "Tempe"
  [15]=>
  string(6) "Tucson"
  [16]=>
  string(10) "Wickenburg"
}
Rasmus Schultz (http://mindplay.dk) 23-Jan-2009 01:59
Unfortunately, this function only accepts real arrays, not iterable objects... For that, you need this function:

<?php

function break_array($array, $page_size) {

  $arrays = array();
  $i = 0;

  foreach ($array as $index => $item) {
    if ($i++ % $page_size == 0) {
      $arrays[] = array();
      $current = & $arrays[count($arrays)-1];
    }
    $current[] = $item;
  }

  return $arrays;

}

?>
OIS 10-Jun-2008 05:31
Response to azspot at gmail dot com function partition.

$columns = 3;
$citylist = array('Black Canyon City', 'Chandler', 'Flagstaff', 'Gilbert', 'Glendale', 'Globe', 'Mesa', 'Miami', 'Phoenix', 'Peoria', 'Prescott', 'Scottsdale', 'Sun City', 'Surprise', 'Tempe', 'Tucson', 'Wickenburg');
print_r(array_chunk($citylist, ceil(count($citylist) / $columns)));

Output:
Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
azspot at gmail dot com 08-May-2007 04:53
Tried to use an example below (#56022) for array_chunk_fixed that would "partition" or divide an array into a desired number of split lists -- a useful procedure for "chunking" up objects or text items into columns, or partitioning any type of data resource. However, there seems to be a flaw with array_chunk_fixed — for instance, try it with a nine item list and with four partitions. It results in 3 entries with 3 items, then a blank array.

So, here is the output of my own dabbling on the matter:

<?php

function partition( $list, $p ) {
    $listlen = count( $list );
    $partlen = floor( $listlen / $p );
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for ($px = 0; $px < $p; $px++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice( $list, $mark, $incr );
        $mark += $incr;
    }
    return $partition;
}

$citylist = array( "Black Canyon City", "Chandler", "Flagstaff", "Gilbert", "Glendale", "Globe", "Mesa", "Miami",
                   "Phoenix", "Peoria", "Prescott", "Scottsdale", "Sun City", "Surprise", "Tempe", "Tucson", "Wickenburg" );
print_r( partition( $citylist, 3 ) );

?>

Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
21-Mar-2006 04:19
Here my array_chunk_values( ) with values distributed by lines (columns are balanced as much as possible) :

<?php
    function array_chunk_vertical($data, $columns) {
        $n = count($data) ;
        $per_column = floor($n / $columns) ;
        $rest = $n % $columns ;

        // The map
        $per_columns = array( ) ;
        for ( $i = 0 ; $i < $columns ; $i++ ) {
            $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
        }

        $tabular = array( ) ;
        foreach ( $per_columns as $rows ) {
            for ( $i = 0 ; $i < $rows ; $i++ ) {
                $tabular[$i][ ] = array_shift($data) ;
            }
        }

        return $tabular ;
    }

    header('Content-Type: text/plain') ;

    $data = array_chunk_vertical(range(1, 31), 7) ;
    foreach ( $data as $row ) {
        foreach ( $row as $value ) {
            printf('[%2s]', $value) ;
        }
        echo "\r\n" ;
    }

    /*
        Output :

        [ 1][ 6][11][16][20][24][28]
        [ 2][ 7][12][17][21][25][29]
        [ 3][ 8][13][18][22][26][30]
        [ 4][ 9][14][19][23][27][31]
        [ 5][10][15]
    */
?>
magick dit crow ot gmail dit com 16-Oct-2005 09:50
Mistake key did not do what I thought. A patch.

function array_bucket($array,$bucket_size)// bucket filter
{
    if (!is_array($array)) return false;
    $buckets=array_chunk($array,$bucket_size);// chop up array into bucket size units
    $I=0;
    foreach ($buckets as $bucket)
    {
        $new_array[$I++]=array_sum($bucket)/count($bucket);
    }
    return $new_array;// return new array
}
magick dit crow ot gmail dit com 15-Oct-2005 10:58
This function takes each few elements of an array and averages them together. It then places the averages in a new array. It is used to smooth out data. For example lets say you have a years worth of hit data to a site and you want to graph it by the week. Then use a bucket of 7 and graph the functions output.

function array_bucket($array, $bucket_size)  // bucket filter
{
    if (!is_array($array)) return false; // no empty arrays
    $buckets=array_chunk($array,$bucket_size);  // chop up array into bucket size units
    foreach ($buckets as $bucket) $new_array[key($buckets])=array_sum($bucket)/count($bucket);
    return $new_array;  // return new smooth array
}
webmaster at cafe-clope dot net 20-Aug-2005 04:27
based on the same syntax, useful about making columns :

<?php
function array_chunk_fixed($input, $num, $preserve_keys = FALSE) {
    $count = count($input) ;
    if($count)
        $input = array_chunk($input, ceil($count/$num), $preserve_keys) ;
    $input = array_pad($input, $num, array()) ;
    return $input ;
}

$array = array(1, 2, 3, 4, 5) ;
print_r(array_chunk($array, 2)) ;
print_r(array_chunk_fixed($array, 2)) ;
?>

---- array_chunk : fixed number of sub-items ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
        )
    [1] => Array(
            [0] => 3
            [1] => 4
        )

    [2] => Array(
            [0] => 5
        )
)

---- array_chunk : fixed number of columns ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array(
            [0] => 4
            [1] => 5
        )
)
phpm at nreynolds dot me dot uk 17-Dec-2004 04:21
array_chunk() is helpful when constructing tables with a known number of columns but an unknown number of values, such as a calendar month. Example:

<?php

$values = range(1, 31);
$rows = array_chunk($values, 7);

print "<table>\n";
foreach ($rows as $row) {
    print "<tr>\n";
    foreach ($row as $value) {
        print "<td>" . $value . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

?>

Outputs:

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

The other direction is possible too, with the aid of a function included at the bottom of this note. Changing this line:
  $rows = array_chunk($values, 7);

To this:
  $rows = array_chunk_vertical($values, 7);

Produces a vertical calendar with seven columns:

1 6  11 16 21 26 31
2 7  12 17 22 27
3 8  13 18 23 28
4 9  14 19 24 29
5 10 15 20 25 30

You can also specify that $size refers to the number of rows, not columns:
  $rows = array_chunk_vertical($values, 7, false, false);

Producing this:

1 8  15 22 29
2 9  16 23 30
3 10 17 24 31
4 11 18 25
5 12 19 26
6 13 20 27
7 14 21 28

The function:

<?php

function array_chunk_vertical($input, $size, $preserve_keys = false, $size_is_horizontal = true)
{
    $chunks = array();

    if ($size_is_horizontal) {
        $chunk_count = ceil(count($input) / $size);
    } else {
        $chunk_count = $size;
    }

    for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) {
        $chunks[] = array();
    }

    $chunk_index = 0;
    foreach ($input as $key => $value)
    {
        if ($preserve_keys) {
            $chunks[$chunk_index][$key] = $value;
        } else {
            $chunks[$chunk_index][] = $value;
        }

        if (++$chunk_index == $chunk_count) {
            $chunk_index = 0;
        }
    }

    return $chunks;
}

?>
mick at vandermostvanspijk dot nl 07-Apr-2004 03:02
[Editors note: This function was based on a previous function by gphemsley at nospam users dot sourceforge.net]

For those of you that need array_chunk() for PHP < 4.2.0, this function should do the trick:

<?php
if (!function_exists('array_chunk')) {
    function array_chunk( $input, $size, $preserve_keys = false) {
        @reset( $input );

        $i = $j = 0;

        while( @list( $key, $value ) = @each( $input ) ) {
            if( !( isset( $chunks[$i] ) ) ) {
               $chunks[$i] = array();
            }

            if( count( $chunks[$i] ) < $size ) {
                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $chunks[$i][] = $value;
                }
            } else {
                $i++;

                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $j = 0;
                    $chunks[$i][$j] = $value;
                }
            }
        }

        return $chunks;
    }
}
?>
array_change_key_case
array_combine
Функции для работы с массивами


Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений

array_chunk
array_count_values
Функции для работы с массивами
PHP Manual

array_combine

(PHP 5)

array_combine — Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений

Описание

array array_combine ( array $keys , array $values )

Создает array, используя значения массива keys в качестве ключей и значения масссива values в качестве соответствующих значений.

Список параметров

keys

Массив ключей. Некорректные значения для ключей будут преобразованы в string.

values

Массив значений

Возвращаемые значения

Возвращает скомбинированный array, либо FALSE, если количество элементов в массивах не совпадает.

Ошибки

Генерирует ошибку уровня E_WARNING, если количество элементов в keys и values не совпадает.

Список изменений

Версия | Описание
5.4.0 | Предыдущие версии выдавали E_WARNING и возвращали FALSE для пустых массивов.

Примеры

Пример #1 Простой пример использования array_combine()

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

Результат выполнения данного примера:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

Смотрите также

  • array_merge() - Сливает один или большее количество массивов
  • array_walk() - Применяет пользовательскую функцию к каждому элементу массива
  • array_values() - Выбирает все значения массива

User Contributed Notes

dejiakala at gmail dot com 27-Oct-2011 03:32
I needed to read CSV files into associative arrays with column headers as keys. Then I ran into a problem when you have empty columns at the end of a row because array_combine returns false if both arrays don't have the same number of elements. This function based on quecoder at gmail's combine_arr() below allowed me to pad either array or not when parsing my CSVs to arrays.
$a is the array of header columns and $b is an array of the current row retrieved with fgetcsv()

<?php

function array_combine_special($a, $b, $pad = TRUE) {
    $acount = count($a);
    $bcount = count($b);
    // more elements in $a than $b but we don't want to pad either
    if (!$pad) {
        $size = ($acount > $bcount) ? $bcount : $acount;
        $a = array_slice($a, 0, $size);
        $b = array_slice($b, 0, $size);
    } else {
        // more headers than row fields
        if ($acount > $bcount) {
            $more = $acount - $bcount;
            // how many fields are we missing at the end of the second array?
            // Add empty strings to ensure arrays $a and $b have same number of elements
            $more = $acount - $bcount;
            for($i = 0; $i < $more; $i++) {
                $b[] = "";
            }
        // more fields than headers
        } else if ($acount < $bcount) {
            $more = $bcount - $acount;
            // fewer elements in the first array, add extra keys
            for($i = 0; $i < $more; $i++) {
                $key = 'extra_field_0' . $i;
                $a[] = $key;
            }

        }
    }

    return array_combine($a, $b);
}
?>
Dan LaManna 17-Sep-2011 08:12
I needed a function that truncated extra values, and only went as far as keys without throwing a warning as array_combine does.

<?php
function safeArrayCombine($keys, $values) {
    $combinedArray = array();

    for ($i=0, $keyCount = count($keys); $i < $keyCount; $i++) {
         $combinedArray[$keys[$i]] = $values[$i];
    }

    return $combinedArray;
}
?>
zequez at gmail dot com 27-Mar-2011 03:51
If two keys are the same, the second one prevails.
Example:
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => 2
    [b] => 3
)
claude dot pache at gmail dot com 12-May-2010 10:04
array_combine() has a strange bug/misfeature (as of PHP 5.3.2): There is no logical reason for <? array_combine(array(), array()) ?> throwing a warning and returning FALSE, instead of returning <? array() ?> (see http://bugs.php.net/bug.php?id=34857). Here is a quick workaround:
<?php
function array_real_combine($a, $b)
{
    return $a===array() && $b===array() ? array() : array_combine($a, $b);
}
?>
bradentkeith at dot dontspam dot gmail dot com 01-Apr-2010 12:20
I needed a function that would take keys from one unequal array and combine them with the values of another. Real life application:
Select 4 product types.
Each product has a serial.
There are 4 sets of products.

    <?php
        function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
        }
    ?>

Input:
Array
(
    [0] => SMART Board
    [1] => Projector
    [2] => Speakers
    [3] => Splitter
)
, Array
(
    [0] => serial to smart board1
    [1] => serial to projector 1
    [2] => serial to speakers 1
    [3] => serials to splitter 1
    [4] => serials to smart board 2
    [5] => serials to projector 2
    [6] => serials to speakers 2
    [7] => serials to splitter 2
)

Array
(
    [0] => Array
        (
            [SMART Board] => serial to smart board1
            [Projector] => serial to projector 1
            [Speakers] => serial to speakers 1
            [Splitter] => serials to splitter 1
        )

    [1] => Array
        (
            [SMART Board] => serials to smart board 2
            [Projector] => serials to projector 2
            [Speakers] => serials to speakers 2
            [Splitter] => serials to splitter 2
        )

)
xavier at api-meal dot eu 23-Sep-2009 03:37
<?php
/**
 * Return alternatives defined by values of each parameters.
 *
 * Exemple :
 *
 * array_alternatives(array('foo','bar'), array('baz', 'qux'));
 * array(
 *     array('foo', 'baz'),
 *     array('bar', 'baz'),
 *     array('foo', 'qux'),
 *     array('bar', 'qux'),
 * );
 *
 * array_alternatives(array('a'), array('simple-minded'), array('solution'));
 * array(
 *     array('a', 'simple-minded', 'solution')
 * );
 *
 * array_alternatives(array('a'), array('red', 'blue'), array('car'));
 * array(
 *     array('a', 'red',  'car'),
 *     array('a', 'blue', 'car'),
 * );
 *
 * @param array $first_element
 * @param array $second_element
 * @return array
 * @author Xavier Barbosa
 */
function array_alternatives(array $first_element, array $second_element)
{
    $lists = func_get_args();
    $total_lists = func_num_args();

    for($i=0; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];
        if (is_array($list) === FALSE)
            throw new Exception("Parameter $i is not an array.");
        if (count($list) === 0)
            throw new Exception("Parameter $i has no element.");
        unset($list);
    }

    // Initialize our alternatives
    $alternatives = array();
    foreach($lists[0] as &$value)
    {
        array_push($alternatives, array($value));
        unset($value);
    }
    unset($lists[0]);

    // Process alternatives
    for($i=1; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];

        $new_alternatives = array();
        foreach($list as &$value)
        {
            foreach($alternatives as $_)
            {
                array_push($_, $value);
                array_push($new_alternatives, $_);
            }
        }

        // Rotate references, it's cheaper than copy array like `$alternatives = $new_alternatives;`
        $alternatives =& $new_alternatives;
        unset($new_alternatives, $list, $lists[$i]);
    }

    return $alternatives;
}
?>
quecoder at gmail 26-Aug-2008 12:00
<?php
// If they are not of same size, here is solution:

$abbreviations = array("AL", "AK", "AZ", "AR", "TX", "CA");
$states = array("Alabama", "Alaska", "Arizona", "Arkansas");
function combine_arr($a, $b)
{
    $acount = count($a);
    $bcount = count($b);
    $size = ($acount > $bcount) ? $bcount : $acount;
    $a = array_slice($a, 0, $size);
    $b = array_slice($b, 0, $size);
    return array_combine($a, $b);
}
$combined = combine_arr($abbreviations, $states);
print_r($combined);

//  Output
//  Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona
//  [AR] => Arkansas )
?>
J.D.D. 09-Aug-2008 01:31
This may be obvious, but I don't see anything about it on the manual page, so a friendly warning...  The array you are using as keys must have all unique values.  If not, array elements get dropped.

<?php
$arr_notUnique = array('one' , 'one' , 'two');
$arr_b = array('red' , 'green' , 'blue');

$arr_combo = array_combine($arr_notUnique, $arr_b);
?>

Results:  Array ( [one] => green [two] => blue )

NOT:  Array ( [one] => red [one] => green [two] => blue )
Zoran 02-Apr-2008 04:57
Also, Khalys function only works if keys of both arrays are the same because array_combine ignores keys. An easy way to ignore them is by taking array_values(). Floats can be casted to strings to avoid overwriting.

So, the PHP4 function could look something like this:
<?php
function array_combine($arr1, $arr2) {
    $out = array();

    $arr1 = array_values($arr1);
    $arr2 = array_values($arr2);

    foreach($arr1 as $key1 => $value1) {
        $out[(string)$value1] = $arr2[$key1];
    }

    return $out;
}
?>
Mike Jean 18-Mar-2008 09:59
Khaly's PHP4 code below does not work correctly in all cases. Consider when your array consists of floats:

<?php

$okay = array(0, 10, 20, 30);
$not_okay = array(0, 0.5, 1, 1.5);

$foo = array_combine($okay, $okay);
$bar = array_combine($not_okay, $not_okay);

/*

Results:

$foo = {
  [0]=> int(0)
  [10]=> int(10)
  [20]=> int(20)
  [30]=> int(30)
}

$bar = {
  [0]=> float(0.5)
  [1]=> float(1.5)
}

*/

?>

What can you do? In my case, I was just zipping up some select-box options, so I converted everything in my floats to strings.
Khaly 04-Oct-2007 02:11
This is the function for PHP4 :

<?php

function array_combine($arr1,$arr2) {
   $out = array();
   foreach($arr1 as $key1 => $value1)    {
    $out[$value1] = $arr2[$key1];
   }
   return $out
}

?>
neoyahuu at yahoo dot com 19-Mar-2007 08:36
Some tips for merging same values in an array

<?php
$array1 = array(1,2,3,4,5,6,7,8,9,10,11,12);
$array2 = array(1,2,3,13);

$merged = array_merge($array1,$array2);

// output normal array_merge
echo '<pre>After array_merge :
';
print_r($merged);
echo '</pre>';

// do double flip for merging values in an array
$merged = array_flip($merged);
$merged = array_flip($merged);

// Output after
echo '<pre>After Double Flip :
';
print_r($merged);
echo '</pre>';
?>

Output ::

After array_merge :
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 1
    [13] => 2
    [14] => 3
    [15] => 13
)

After Double Flip :
Array
(
    [12] => 1
    [13] => 2
    [14] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [15] => 13
)
ifeghali at interveritas dot net 26-Feb-2005 10:53
Use that code to group an array by its first element.

<?

function groupbyfirst($array)
{
    foreach ($array as $row)
    {
        $firstkey = array_keys($row);
        $firstkey = $firstkey[0];
        $key = $row[$firstkey];
        unset($row[$firstkey]);
        $newarray[$key][] = $row;
    }
    return $newarray;
}

?>

Example:

<?

$array =
Array(
    0 => Array('color' => 'red','name' => 'apple', 'quantity' => '3'),
    1 => Array('color' => 'green','name' => 'pear', 'quantity' => '2'),
    2 => Array('color' => 'yellow','name' => 'corn', 'quantity' => '3'),
    3 => Array('color' => 'blue','name' => 'grape', 'quantity' => '4'),
    4 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '13'),
);

$output = groupbyfirst($array);
print_r($output);

?>

will return:

Array
(
 [red] => Array ( [0] => Array ( [name] => apple [quantity] => 3 ) )
 [green] => Array ( [0] => Array ( [name] => pear [quantity] => 2 ) )
 [yellow] => Array ( [0] => Array ( [name] => corn [quantity] => 3 ), [1] => Array ( [name] => banana [quantity] => 13 ) )
 [blue] => Array ( [0] => Array ( [name] => grape [quantity] => 4 ))
)

Or you can use mysql recordset:

<?
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
    $firstkey = array_keys($row);
    $firstkey = $firstkey[0];
    $key = $row[$firstkey];
    unset($row[$firstkey]);
    $newarray[$key][] = $row;
}
?>
aidan at php dot net 20-May-2004 07:15
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
array_chunk
array_count_values
Функции для работы с массивами


Подсчитывает количество всех значений массива

array_combine
array_diff_assoc
Функции для работы с массивами
PHP Manual

array_count_values

(PHP 4, PHP 5)

array_count_values — Подсчитывает количество всех значений массива

Описание

array array_count_values ( array $input )

Функция array_count_values() возвращает массив, ключами которого являются значения массива input, а значениями - частота повторения значений input.

Список параметров

input

Массив подсчитываемых значений

Возвращаемые значения

Возвращает ассоциативный массив со значениями input в качестве ключей и их количества в качестве значений.

Ошибки

Генерирует ошибку уровня E_WARNING для каждого элемента, не являющегося string или integer.

Примеры

Пример #1 Пример использования array_count_values()

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

Результат выполнения данного примера:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

Смотрите также

  • count() - Подсчитывает количество элементов массива или что-то в объекте
  • array_unique() - Убирает повторяющиеся значения из массива
  • array_values() - Выбирает все значения массива
  • count_chars() - Возвращает информацию о символах, входящих в строку

User Contributed Notes

muhamed dot pasha at gmail dot com 15-Dec-2010 12:56
Hy,

i had a problem which was associated with the array_count_values function, but did not solve my problem realy well so i made a function by my self and maybe it can help also someone else.

The problem was that i had a table like this:
CL     PRODNUM        QN      DATE
1    4221110030    2    10.12.2010
2    4221110031    1    10.12.2010
3    5241110002    1    10.12.2010
3    5241110003    1    11.12.2010
3    5241110001    2    11.12.2010
3    6241110001    1    11.12.2010
1    2231110999    1    10.12.2010
1    2231110999    1    11.12.2010
(it go's on and on ... )

And i wanted to calculate for every unique date how much the quantity of the specific CL is.
For example the result should be like this:

10.12.2010: [1] -> 3
10.12.2010: [2] -> 1
10.12.2010: [3] -> 1

11.12.2010: [1] -> 1
11.12.2010: [2] -> 0
11.12.2010: [3] -> 4

So, i had to make a function which should look for unique values of a date and then for that date get the quantity of uniqe CL's.

For note: i put all the values of the table into an array:
<?php
$a = array();
$a['cl'] = 1;
$a['prodnum'] = '4221110030';
$a['qn'] = '2';
$a['date'] = '10.12.2010';
?>

The function looks like this:

<?php

function csav( $array, $distinctV, $searchInV, $sumValue ){

        #result array
    $result = array();

    #finding the unique dates
    $array1 = array_unique($array[$searchInV]);
    $array2 = array();
    $unique1 = array_merge($array2, $array1);

    #finding the unique CL's
    $array3 = array_unique($array[$distinctV]);
    $array4 = array();
    $unique2 = array_merge($array4, $array3);

    #for statements through the unique dates
    for($k = 0; $k < count($unique1); $k++){

        for($i = 0; $i < count($unique2); $i++){

            $sum = 0;
            for($j = 0; $j < count($array[$distinctV]); $j++){

                if($array[$distinctV][$j] == $unique2[$i] and $array[$searchInV][$j] == $unique1[$k])
                    $sum += $array[$sumValue][$j];
            }
            $result[$unique1[$k]][$unique2[$i]] = $sum;
        }

    }

    return $result;
}

?>

The use of function has to be like this:

<?php
$result = csav($a, 'cl', 'date', 'qn');
print_r($result);
?>

And the result looks like this:

Array ( [2010-12-10] => Array ( [1] => 14 [2] => 17 [3] => 4 ) [2010-12-13] => Array ( [1] => 13 [2] => 17 [3] => 4 ) [2010-12-14] => Array ( [1] => 13 [2] => 17 [3] => 4 ) [2010-12-15] => Array ( [1] => 14 [2] => 17 [3] => 4 ) [2010-12-16] => Array ( [1] => 14 [2] => 17 [3] => 2 ) )

This is it.
Hope it helps someone.
szczepan.krolgmail.c0m 17-Jan-2010 11:21
Here is a Version with one or more arrays, which have similar values in it:
Use $lower=true/false to ignore/set case Sensitiv.

<?php

$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // Possible with one or multiple Array

$res = array_icount_values ($ar1);
print_r($res);

function array_icount_values($arr,$lower=true) {
     $arr2=array();
     if(!is_array($arr['0'])){$arr=array($arr);}
     foreach($arr as $k=> $v){
      foreach($v as $v2){
      if($lower==true) {$v2=strtolower($v2);}
      if(!isset($arr2[$v2])){
          $arr2[$v2]=1;
      }else{
           $arr2[$v2]++;
           }
    }
    }
    return $arr2;
}
/*
Will print:
Array
(
    [red] => 3
    [green] => 3
    [yellow] => 4
    [blue] => 2
    [brown] => 2
    [white] => 1
    [black] => 1
)
*/
?>
bluej100@gmail 25-Mar-2008 01:37
byron at byronrode dot co dot za, here are some benchmarks.

<?php
$haystack = Array();
for ($i = 0; $i < 1000000; $i++) {
  $haystack[] = rand(1, 2000);
}

$needle = rand(1, 2000);

echo "__array_count_values()__\n";
$start = microtime(true);
$startmem = memory_get_usage();
$counts = array_count_values($haystack);
$mem = memory_get_usage()-$startmem;
echo 'Count:'.$counts[$needle]."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";

echo "__array_keys()__\n";
$start = microtime(true);
$startmem = memory_get_usage();
$keys = array_keys($haystack, $needle);
$mem = memory_get_usage()-$startmem;
echo 'Count:'.count($keys)."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";

echo '__$needle_array[]__'."\n";
$start = microtime(true);
$startmem = memory_get_usage();
$x = count($haystack);
for($i = 0; $i < $x; $i++){
  if($haystack[$i] == $needle){
    $needle_array[] = $haystack[$i];
  }
}
$mem = memory_get_usage()-$startmem;
$number_of_instances = count($needle_array);
echo 'Count:'.$number_of_instances."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";

echo '__$number_of_instances++__'."\n";
$start = microtime(true);
$startmem = memory_get_usage();
$x = count($haystack);
$number_of_instances = 0;
for($i = 0; $i < $x; $i++){
  if($haystack[$i] == $needle){
    $number_of_instances++;
  }
}
$mem = memory_get_usage()-$startmem;
echo 'Count:'.$number_of_instances."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";
?>

[www]mytemp$ php array_count_test.php
__array_count_values()__
Count:515
Time:0.0607650279999
Memory:120328

__array_keys()__
Count:515
Time:0.0869138240814
Memory:33016

__$needle_array[]__
Count:515
Time:0.259949922562
Memory:24792

__$number_of_instances++__
Count:515
Time:0.258481025696
Memory:0

However, when you use an array of strings by calling md5(rand(1, 2000)), the performance boosts become less significant:

__array_count_values()__
Count:499
Time:0.491794109344
Memory:184328

__array_keys()__
Count:499
Time:0.36399102211
Memory:30072

__$needle_array[]__
Count:499
Time:0.568728923798
Memory:22104

__$number_of_instances++__
Count:499
Time:0.574353933334
Memory:0

Results are similar for string->string haystacks with foreach traversal.
Hayley Watson 13-Mar-2008 11:37
Yet Another case-insensitive version of array_count_values()

<?php
$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');

$ar = array_count_values(array_map('strtolower', $ar));
?>
byron at byronrode dot co dot za 26-Jun-2007 05:19
I am building a script for a quiz, and could not find any answers to count the number of times a value was repeated in an array, and came up with the following function.

<?php

// Answers Array
$array = array('a', 'b', 'a', 'a', 'c', 'a', 'd', 'a', 'c', 'd');

// Start Count Function
function count_repeat_values($needle, $haystack){

    $x = count($haystack);

    for($i = 0; $i < $x; $i++){

        if($haystack[$i] == $needle){
            $needle_array[] = $haystack[$i];
        }
    }

    $number_of_instances = count($needle_array);

    return $number_of_instances;
}

echo count_repeat_values('a', $array);

// will return the value 5
?>

But after writing the function, I happened to stroll upon array_count_values() which I had completely forgotten about.

I know that i could get the value by doing this:

<?php

$array = array('a', 'b', 'a', 'a', 'c', 'a', 'd', 'a', 'c', 'd');

$answer = array_count_values($array);
echo $answer['a']

?>

Would be interesting to see which version works quicker...
majerm at gmail dot com 18-Jun-2007 07:50
<?
function array_icount_values($array) {
    $ret_array = array();
    foreach($array as $value) $ret_array[strtolower($value)]++;
    return $ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar = array_icount_values($ar);
?>

this prints:

Array
(
    [j. karjalainen] => 4
    [60] => 2
    [fastway] => 4
    [yup] => 1
)
rabies dot dostojevski at gmail dot com 21-Feb-2007 01:40
I couldn't find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:

<pre><?php
function array_icount_values($array) {
    $ret_array = array();
    foreach($array as $value) {
        foreach($ret_array as $key2 => $value2) {
            if(strtolower($key2) == strtolower($value)) {
                $ret_array[$key2]++;
                continue 2;
            }
        }
        $ret_array[$value] = 1;
    }
    return $ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar2 = array_count_values($ar); // Normal matching
$ar = array_icount_values($ar); // Case-insensitive matching
print_r($ar2);
print_r($ar);
?></pre>

This prints:

Array
(
    [J. Karjalainen] => 3
    [60] => 2
    [j. karjalainen] => 1
    [Fastway] => 2
    [FASTWAY] => 1
    [fastway] => 1
    [YUP] => 1
)
Array
(
    [J. Karjalainen] => 4
    [60] => 2
    [Fastway] => 4
    [YUP] => 1
)

I don't know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
meyermagic at gmail dot com 16-Jan-2007 06:43
Scratch that, I did something stupid. Here is a better function.

<?php
    function array_enumerate_keys($array)
    {
        $index = 0;
        $enumerated = array();
        $values = array_values($array);
        $keys = array_keys($array);
        for($index = 0; $index < count($array); $index++)
        {
            $iteration;
            for($iteration = 0; $iteration < $values[$index]; $iteration++)
            {
                $enumerated = array_merge($enumerated, array($keys[$index]));
            }
        }

        return $enumerated;
    }
?>
meyermagic at gmail dot com 16-Jan-2007 02:58
A possible inverse function for array_count_values

<?php
    function array_enumerate_keys($array)
    {
        $index;
        $enumerated;
        $values = array_values($array);
        $keys = array_keys($array);
        for($index = 0; $index < count($array); $index++)
        {
            $iteration;
            for($iteration = 0; $iteration < $values[$index]; $iteration++)
            {
                $enumerated .= $keys[$index] . ',';
            }
        }

        return explode(',', $enumerated);
    }
?>
coda at bobandgeorge dot com 14-Oct-2005 05:52
alwaysdrunk's comment only works if you can trust the client web browser. Using this function doesn't validate that every necessary field exists -- only that every field that was submitted has a value in it. Thus if an attacker wished to force a null value into one of the fields, he could (rather easily) construct a modified form without the field and submit THAT.

Besides, you really ought to be validating each field anyway if you're taking user input.
alwaysdrunk at gmail com 12-May-2005 12:14
if you have too many values in $_POST,$_GET array that needs to be controlled with isset() in oreder to understand the form is filled completely and have no empty text boxes.
you can try this,it saves time.

<?
$n = array_count_values($_POST);
if (!isset($n[''])) {
echo "The form is filled completely";
}
else
{ die("Please fill the form comlpetely"); }

//tested in php 5
?>
[Mr.A] 06-Mar-2005 02:59
I find a very simple solution to count values in multidimentional arrays (example for 2 levels) :

foreach ($array as $a) {
  foreach ($a as $b) {
    $count_values[$b]++;
  }
}
blauauge at figh7club dot com 03-Sep-2003 09:12
my solution for count  on multidimentional arrays.

<?php
  for($i = 0; $i < count($array); $i++) {
      $detail = explode("|", $array[$i]);
      echo "$i - $detail[0] - $detail[1]<br><br>";
      if($detail[1] == '1') { $wieoft1 = $wieoft1 +=1; }
      if($detail[1] == '2') { $wieoft2 = $wieoft2 +=1; }
      if($detail[1] == '3') { $wieoft3 = $wieoft3 +=1; }
  }
  echo ". $wieoft1 : $wieoft2 : $wieoft3";
?>

looks not pretty fine yet works great for me.
make it bigger for your own.
programmer at bardware dot de 19-Aug-2003 11:24
array_count_values returns the number of keys if empty(value). I expected array_count_values to return 0 for empty values.

Array looks like:
Array
        (
            [459] =>
            [543] =>
            [8959] =>
            [11273] =>
        )

array_count_values returns:
Array
(
    [] => 4
)

count(array_count_values(array)) does thus not report there are no values (other than empty) in the array.

I therefore check:
$arrFoo=array_count_values($arrBar);
if(isset($arrFoo[""]) $allempty=count($arrBar)==$arrFoo[""];
if(!$allempty)
//process the array
else
//no need to work on the array
digleu at codeway dot de 28-May-2003 02:58
I fount a solution for the count of array elements in the sense of array_count_values, but i was not able to use the function array_count_values itself because it does not say me if arrays exists in the given array, so i had to use a foreach loop and a little bit of recursivity ;)

<?php
function array_count_values_multidim($a,$out=false) {
  if ($out===false) $out=array();
  if (is_array($a)) {
    foreach($a as $e)
      $out=array_count_values_multidim($e,$out);
  }
  else {
    if (array_key_exists($a,$out))
      $out[$a]++;
    else
      $out[$a]=1;
  }
  return $out;
}
?>
pmarcIatIgeneticsImedIharvardIedu 29-Jan-2003 05:42
array_count_values function does not work on multidimentional arrays.
If $score[][] is a bidimentional array, the command
"array_count_values ($score)" return the error message "Warning: Can only count STRING and INTEGER values!".
manuzhai (AT) php (DOT) net 16-Nov-2002 06:45
You might use serialize() to serialize your objects before analyzing their frequency. :)
jon at fuck dot org 14-Aug-2002 02:31
suggested plan of attack:

<pre>
<?
class MyObject {
    function MyObject($t = 'none')
    {
      $this->$myTag = $t;
    }
}

$myArray = array();

for ($i = 1 ; $i < 11 ; $i++)
{
   $myobj = new MyObject( str_pad('n', $i, 'x') );
   $myArray[ $myobj->$myTag ] = $myobj;
}

print_r( array_count_values(array_keys($myArray)) );
?>

to sum up:
assuming each instance of an object you create has some sort of tag, e.g.,

$this->$myTag=get_class($this)

..you should be set. objects dont have value to compare the way strings and integers do, so, $myTag's value is arbitrary.
tschneider at formel4 dot de 12-Jun-2002 07:09
This does not works with objects. If you have an array filled with objects, you can not count them.

Example:

<?php
$myArray = array();
for ($i = 0 ; $i < 10 ; $i++)
{
   $myObject = new MyObject();
   $myArray[$i] = $myObject;
}

echo (array_count_values($myArray));
?>

This gives you:
Warning: Can only count STRING and INTEGER values...

Found no solution for this yet...
array_combine
array_diff_assoc
Функции для работы с массивами


Вычисляет расхождение массивов с дополнительной проверкой индекса

array_count_values
array_diff_key
Функции для работы с массивами
PHP Manual

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc — Вычисляет расхождение массивов с дополнительной проверкой индекса

Описание

array array_diff_assoc ( array $array1 , array $array2 [, array $... ] )

Сравнивает array1 с array2 и возвращает разницу. В отличие от array_diff(), ключи также участвуют в сравнении.

Список параметров

array1

Исходный массив

array2

Массив, с которым идет сравнение

...

Дополнительные массивы, с которыми осуществляется сравнение

Возвращаемые значения

Возвращает array, содержащие все значения из массива array1, которых нет в любом из последующих массивов.

Примеры

Пример #1 Пример использования array_diff_assoc()

В вышеприведённом примере вы видите, что пара "a" => "green" содержится в обоих массивах и поэтому её не содержится в выводе функции. Наоборот, пара 0 => "red" содержится в выводе функции, потому что во втором аргументе значению "red" соответствует ключ 1.

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

Пример #2 Пример array_diff_assoc()

Два значения пар key => value считаются равными только тогда, если (string) $elem1 === (string) $elem2 . Другими словами, применяется строгая проверка, означающая что строковые представления должны быть одинаковыми.

<?php
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [0] => 0
    [1] => 1
    )

Примечания

Замечание: Эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff_assoc($array1[0], $array2[0]);.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса

User Contributed Notes

news_yodpeirs at thoftware dot de 12-Jul-2011 04:25
A quite simple (yet not very efficient) way to compare the first level of arrays which have values that are not strings:
array_map('unserialize',array_diff_assoc(array_map('serialize',$arr1),array_map('serialize',$arr2)))
Might be useful for debugging (that's what I use it for).
jrajpu10 at gmail dot com 25-Oct-2008 12:57
array_diff_assoc can also be used to find the duplicates in an array

<?php
$arr = array('1','2','3','4','3','2','5');
$uniques = array_unique($arr);
// array_diff will not work here, array_diff_assoc works as it takes the key // in account.
$dups = array_diff_assoc($arr, $uniques);

print_r($dups);
?>

Note: The index of the $dups is not in strict sequential order as expected by C programmer.
cedric at daneel dot net 21-May-2007 06:01
To diff between n-dimensional array, juste use this :

<?php
function array_diff_values($tab1, $tab2)
    {
    $result = array();
    foreach($tab1 as $values) if(! in_array($values, $tab2)) $result[] = $values;
    return $result;
    }
?>
contact at pascalopitz dot com 11-Apr-2007 04:14
The direction of the arguments does actually make a difference:

<?php
$a = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
);

$b = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
    'g' => 'g',
);

print_r(array_diff_assoc($a, $b));
print_r(array_diff_assoc($b, $a));
?>

echoes:

Array
(
)
Array
(
    [g] => g
)
chinello at gmail dot com 18-Mar-2007 10:33
The following will recursively do an array_diff_assoc, which will calculate differences on a multi-dimensional level.  This not display any notices if a key don't exist and if error_reporting is set to E_ALL:

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
              if(!isset($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              elseif(!is_array($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              else
              {
                  $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                  if($new_diff != FALSE)
                  {
                        $difference[$key] = $new_diff;
                  }
              }
          }
          elseif(!isset($array2[$key]) || $array2[$key] != $value)
          {
              $difference[$key] = $value;
          }
    }
    return !isset($difference) ? 0 : $difference;
}
?>

[NOTE BY danbrown AT php DOT net: This is a combination of efforts from previous notes deleted.  Contributors included (Michael Johnson), (jochem AT iamjochem DAWT com), (sc1n AT yahoo DOT com), and (anders DOT carlsson AT mds DOT mdh DOT se).]
Alexander Podgorny 30-May-2006 02:30
NOTE: the diff_array also removes all the duplicate values that match to the values in the second array:

<?php
    $array1 = array("a","b","c","a","a");
    $array2 = array("a");

    $diff = array_diff($array1,$array2);

    // yields: array("b","c") the duplicate "a" values are removed
?>
benjamin at moonfactory dot co dot jp 11-Jan-2005 09:56
Hi all,
For php versions < 4.3...

<?php
/**
 * array_diff_assoc for version < 4.3
 **/
if (!function_exists('array_diff_assoc'))
{
    function array_diff_assoc($a1, $a2)
    {
        foreach($a1 as $key => $value)
        {
            if(isset($a2[$key]))
            {
                if((string) $value !== (string) $a2[$key])
                {
                     $r[$key] = $value;
                }
            }else
            {
                $r[$key] = $value;
            }
        }
        return $r ;
    }
}

?>
carl at thep dot lu dot se 09-May-2003 02:55
To unset elements in an array if you know the keys but not the values, you can do:

<?php
$a = array("foo", "bar", "baz", "quux");
$b = array(1, 3); // Elements to get rid of

foreach($b as $e)
  unset($a[$e]);
?>

Of course this makes most sense if $b has many elements or is dynamically generated.
array_count_values
array_diff_key
Функции для работы с массивами


Вычисляет расхождение массивов, сравнивая ключи

array_diff_assoc
array_diff_uassoc
Функции для работы с массивами
PHP Manual

array_diff_key

(PHP 5 >= 5.1.0)

array_diff_key — Вычисляет расхождение массивов, сравнивая ключи

Описание

array array_diff_key ( array $array1 , array $array2 [, array $... ] )

Сравнивает ключи array1 с ключами array2 и возвращает разницу. Эта функция схожа с array_diff() за исключением того, что сравниваются ключи, а не значения.

Список параметров

array1

Исходный массив

array2

Массив, с которым идет сравнение

...

Дополнительные массивы, с которыми осуществляется сравнение

Возвращаемые значения

Возвращает array, содержащий все элементы array1 с ключами, которых нет в во всех последующих массивах.

Примеры

Пример #1 Пример использования array_diff_key()

Два ключа пар key => value считаются равными только тогда, когда (string) $key1 === (string) $key2 . Другими словами, применяется строгая проверка, означающая что строковые представления должны быть одинаковыми.

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

Результат выполнения данного примера:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Примечания

Замечание:

Эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff_key($array1[0], $array2[0]);.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_udiff() - Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_uassoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_udiff_assoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_diff_ukey() - Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_intersect_uassoc() - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_intersect_key() - Вычислить пересечение массивов, сравнивая ключи
  • array_intersect_ukey() - Вычисляет схождение массивов, используя callback-функцию для сравнения ключей

User Contributed Notes

division-par-zero at zilon dot net 03-Oct-2008 07:02
you can use this function for return the difference of two array !

<?php
function array_unique_diff_key ($array1, $array2)
{
  if (is_array($array1) && is_array($array2))
    return array_diff_key($array1, $array2) + array_diff_key($array2, $array1);
  else if (is_array($array1)) return $array1;
  else if (is_array($array2)) return $array2;
  else return array();
}
?>
Ashton 02-Apr-2008 01:33
To return the unique elements (those with a key that exists only once in either array but not in both) try:
function array_unique_diff ($array1, $array2)
{
  array_merge(array_diff_key($array1, $array2), array_diff_key($array2, $array1));
}

Example:
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

  array_diff_key($array1, $array2)

returns

  array ( 'red' => 2, 'purple' => 4 )

  array_diff_key($array2, $array1)

returns

  array ( 'yellow' => 7, 'cyan' => 8, )

  array_unique_diff($array1, $array2);

returns

  array ( 'red' => 2, 'purple' => 4, 'yellow' => 7, 'cyan' => 8, )
sjungwirth at matrix-consultants dot com 28-Feb-2008 12:08
I needed something a little different where maybe even the keys in multidimensional arrays don't match up. Setting $assoc to false will cause only to check for missing keys, otherwise it compares values as well. This was also based on '2ge at 2ge dot us' function

<?php

function n_array_diff_assoc ($a1, $a2, $assoc=true) {
    $r = array();
    if(is_array(current($a1))):
        foreach($a1 as $k => $v):
            if(isset($a2[$k])):
                $diff = n_array_diff($a1[$k], $a2[$k], $assoc);
                if (!empty($diff)):
                    $r[$k] = $diff;
                endif;
            else:
                $r[$k] = $v;
            endif;
        endforeach;
    else:
        $r = $assoc ? array_diff_assoc($a1, $a2) : array_diff_key($a1, $a2);
    endif;
    return $r;
}
?>
coder at gs dot com 16-Feb-2008 02:00
The PHP4 version below works only unidirectionally. If you switch the arrays around i.e. (ar2, ar1) you get different results than (ar1, ar2).
AiFiLTr0 [at host] invyl [dot] ath.cx 29-Nov-2007 05:56
The recursive function suggested by '2ge at 2ge dot us' will provide you with empty arrays if there's no diff.
This variant of the function cleans up empty arrays and fixes a bug in the first suggested version. It works 100%
.
<?php
function array_diff_key_recursive ($a1, $a2) {
        foreach($a1 as $k => $v) {
            //$r[$k] = is_array($v) ? $this->array_diff_key_recursive($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        if (is_array($v))
            {
            $r[$k]=$this->array_diff_key_recursive($a1[$k], $a2[$k]);
            }else
            {
            $r=array_diff_key($a1, $a2);
            }

        if (is_array($r[$k]) && count($r[$k])==0)
            {
            unset($r[$k]);
            }
        }
        return $r;
    }
?>
contact at autonoma dot fr 29-Jun-2007 05:01
after kwutzke's comment , here is a PHP4 array_diff_key fonction for those in need

    function PHP4_array_diff_key()
    {
        $arrs = func_get_args();
        $result = array_shift($arrs);
        foreach ($arrs as $array) {
            foreach ($result as $key => $v) {
                if (array_key_exists($key, $array)) {
                    unset($result[$key]);
                }
            }
        }
        return $result;
   }

works for me, enjoy.
kwutzke @ somewhere in the net 20-Dec-2006 04:27
PHP4 array_diff_key can be copied from the array_intersect_key implementation posted by some anonymous user on 2006-07-17. The only thing you have to do is to delete the '!' in the if and rename the function.
2ge at 2ge dot us 07-Mar-2006 11:28
Hello, if you need diff key of n-dimensional arrays here is nice solution:
<?php
function n_array_diff ($a1, $a2) {
        foreach($a1 as $k => $v) {
            $r[$k] = is_array($v) ? n_array_diff($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        }
        return $r;
}
?>
it will print everything, what is missing in $a2.
vlad_mustafin at ukr dot net 13-Jan-2006 07:39
One more alternative variant :)
<?
if (!function_exists('array_diff_key')) {
    function array_diff_key() {
        $argCount   = func_num_args();
        $diff_arg_prefix = 'diffArg';
        $diff_arg_names = array();
        for ($i=0; $i < $argCount; $i++) {
            $diff_arg_names[$i] = 'diffArg'.$i;
            $$diff_arg_names[$i] = array_keys((array)func_get_arg($i));
        }
        $diffArrString = '';
        if (!empty($diff_arg_names)) $diffArrString =  '$'.implode(', $', $diff_arg_names);
        eval("\$result = array_diff(".$diffArrString.");");
        return $result;
    }
}
?>
ampf at egp dot up dot pt 25-Nov-2005 12:55
Well, you could implement in the code something more powerfull:

http://www.php.net/manual/en/function.array-diff.php#31364
ml at iceni dot pl 07-Jun-2005 12:52
You may obtain this function with PEAR Package PHP_Compat (http://pear.php.net/package/PHP_Compat)

Then using such code is quite useful
<?php
if(!function_exists('array_diff_key')){
    require_once 'PHP/Compat/Function/array_diff_key.php';
}
?>
maxence at pontapreta dot net 27-May-2005 10:38
Seems to be a great function, especially for n-dimensions arrays. The only problem is that I cannot find it in php 5.0.3 and 5.0.4. Does it really exist ?! :(

[20:27:05][maxence@conurb] ~/test2/php-5.0.4$ grep PHP_FUNCTION * -r | grep -i array_diff_key
[20:27:09][maxence@conurb] ~/test2/php-5.0.4$
eric dot broersma at phil dot uu dot nl 05-Mar-2005 06:58
<?php
function array_diff_key()
{
    $args = func_get_args();
    return array_flip(call_user_func_array('array_diff',
           array_map('array_flip',$args)));
}
?>
denis noessler 23-Nov-2004 04:07
if (!function_exists('array_diff_key'))
{
    /**
    * Computes the difference of arrays using keys for comparison
    *
    * @param    array    $valuesBase            Base elements for comparison, associative
    * @param    array    $valuesComp[,..]    Comparison elements, associative
    *
    * @param    array                        Elements, not existing in comparison element, associative
    */
    function array_diff_key()
    {
        $argCount   = func_num_args();
        $argValues  = func_get_args();
        $valuesDiff = array();

        if ($argCount < 2)
        {
            return false;
        }

        foreach ($argValues as $argParam)
        {
            if (!is_array($argParam))
            {
                return false;
            }
        }

        foreach ($argValues[0] as $valueKey => $valueData)
        {
            for ($i = 1; $i < $argCount; $i++)
            {
                if (isset($argValues[$i][$valueKey]))
                {
                    continue 2;
                }
            }

            $valuesDiff[$valueKey] = $valueData;
        }

        return $valuesDiff;
    }
}
array_diff_assoc
array_diff_uassoc
Функции для работы с массивами


Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции

array_diff_key
array_diff_ukey
Функции для работы с массивами
PHP Manual

array_diff_uassoc

(PHP 5)

array_diff_uassoc — Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции

Описание

array array_diff_uassoc ( array $array1 , array $array2 [, array $... ], callable $key_compare_func )

Сравнивает array1 c array2 и возвращает разницу. В отличие от array_diff(), для сравнения используются ключи.

В отличие от array_diff_assoc(), для сравнения ключей используется пользовательская функция, а не встроенная.

Список параметров

array1

Исходный массив

array2

Массив, с которым идет сравнение

...

Дополнительные массивы, с которыми осуществляется сравнение

key_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает array, содержащий все элементы array1, которых нет во всех остальных массивах.

Примеры

Пример #1 Пример использования array_diff_uassoc()

Пара "a" => "green" существует в обоих массивах и поэтому отсутствует в выводе функции. Наоборот, пара 0 => "red" находится в выводе функции, так как второй аргумент "red" имеет ключ, равный 1.

<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

Равенство 2 индексов проверяется функцией, предоставляемой пользователем.

Примечания

Замечание:

Эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_udiff() - Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_udiff_assoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_uintersect() - Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

User Contributed Notes

There are no user contributed notes for this page.
array_diff_key
array_diff_ukey
Функции для работы с массивами


Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей

array_diff_uassoc
array_diff
Функции для работы с массивами
PHP Manual

array_diff_ukey

(PHP 5 >= 5.1.0)

array_diff_ukey — Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей

Описание

array array_diff_ukey ( array $array1 , array $array2 [, array $ ... ], callable $key_compare_func )

Сравнивает ключи array1 с ключами array2 и возвращает разницу. Эта функция похожа на array_diff() за исключением того, что сравниваются ключи, а не значения.

В отличие от функции array_diff_key() для сравнения ключей используется функция, предоставляемая пользователем, а не встроенная функция.

Список параметров

array1

Исходный массив

array2

Массив, с которым идет сравнение

...

Дополнительные массивы, с которыми осуществляется сравнение

key_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает array, содержащий все элементы array1, отсутствующие в каком-либо из всех остальных массивов.

Примеры

Пример #1 Пример использования array_diff_ukey()

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>

Результат выполнения данного примера:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Примечания

Замечание:

Обратите внимание, что эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff_ukey($array1[0], $array2[0], 'callback_func');.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_udiff() - Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_uassoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_udiff_assoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_diff_key() - Вычисляет расхождение массивов, сравнивая ключи
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_intersect_uassoc() - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_intersect_key() - Вычислить пересечение массивов, сравнивая ключи
  • array_intersect_ukey() - Вычисляет схождение массивов, используя callback-функцию для сравнения ключей

User Contributed Notes

jordancdarwin at googlemail dot com 15-Dec-2007 01:41
Note, also that when you are using a callback function you can use the text-placeholders as this function relies on the retval of the function you give.

So, instead of 1,0,-1 you can use TRUE and FALSE if using only two options.

Just thought it may help you
array_diff_uassoc
array_diff
Функции для работы с массивами


Вычислить расхождение массивов

array_diff_ukey
array_fill_keys
Функции для работы с массивами
PHP Manual

array_diff

(PHP 4 >= 4.0.1, PHP 5)

array_diff — Вычислить расхождение массивов

Описание

array array_diff ( array $array1 , array $array2 [, array $... ] )

Сравнивает array1 с array2 и возвращает разницу.

Список параметров

array1

Исходный массив

array2

Массив, с которым идет сравнение

...

Дополнительные массивы, с которыми осуществляется сравнение

Возвращаемые значения

Возвращает array, содержащий элементы array1, отсутствующие в любом из всех остальных массивах.

Примеры

Пример #1 Пример использования array_diff()

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Множественные совпадения в $array1 обрабатываются как одно. Результат будет следующим :

Array
(
    [1] => blue
)

Примечания

Замечание:

Два элемента считаются одинаковыми тогда и только тогда, если (string) $elem1 === (string) $elem2. Другими словами, когда их строковое представление идентично.

Замечание:

Обратите внимание, что эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff($array1[0], $array2[0]);.

Смотрите также

  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса

User Contributed Notes

michiel thalen 07-Apr-2012 02:22
The fact that it will use the string representation causes alot of problems with php 5.4.

When you will have an array inside your elements, it will throw a notice error.
It will throw huge amounts of notices depending on how many items you have.

The same problem you will notice when checking with objects inside your array. It will cause catchable fatal errors.
This is also the case in php 5.3

I'm going to send a bug report, because I think php should handle this.
ballestermendez at gmail dot com 16-Mar-2012 11:40
If the element number returned is 0, this function NOT return a valid array, return NULL.
merlyn dot tgz at gmail dot com 15-Mar-2012 10:08
There is more fast implementation of array_diff, but with some limitations. If you need compare two arrays of integers or strings you can use such function:

    public static function arrayDiffEmulation($arrayFrom, $arrayAgainst)
    {
        $arrayAgainst = array_flip($arrayAgainst);

        foreach ($arrayFrom as $key => $value) {
            if(isset($arrayAgainst[$value])) {
                unset($arrayFrom[$key]);
            }
        }

        return $arrayFrom;
    }

It is ~10x faster than array_diff

php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = array_diff($a, $b);echo microtime(true) - $t;
4.4335179328918
php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = arrayDiffEmulation($a, $b);echo microtime(true) - $t;
0.37219095230103
wladimir camargo 25-Jul-2011 10:23
This is my simple function do compare two arrays. It adds the deleted values from the original array.

<?php
function array_diff_($old_array,$new_array) {
        foreach($new_array as $i=>$l){
                if($old_array[$i] != $l){
                        $r[$i]=$l;
                }
        }

        //adding deleted values
        foreach($old_array as $i=>$l){
                if(!$new_array[$i]){
                        $r[$i]="";
                }
        }
        return $r;
}
?>
eugeny dot yakimovitch at gmail dot com 30-Dec-2010 03:17
Note that array_diff is not equivalent to

<?php
function fullArrayDiff($left, $right)
{
    return array_diff(array_merge($left, $right), array_intersect($left, $right));
}
?>

since it is a set-theoretical complement as in

http://en.wikipedia.org/wiki/Complement_(set_theory)
javierchinapequeno at yahoo dot es 21-Dec-2010 11:21
Hi, I´d like to give a piece of advice to all who need to use this function to compare two arrays that have a great quantity of elements. You should sort both arrays first before comparing, it will work faster.
Thanks
webmaster at drakkofox dot net 15-Oct-2010 07:48
If you simply want to verify if a array is different of another one, use IF.

array_diff was returning a empty array when i received values from a form and compared they both(one was from a input type hidden array, and another was from input type checkbox), even if one of they were different. i tried switching places between arr1 and arr2, no good.
thefrox at gmail dot com 30-Jun-2010 05:28
Multidimensional array_diff

<?php
echo '<pre>';
$bdd['80395']= array('80396','80397','80398','777');
$folder['80395']= array('80396','80397','666','80398','154223');
$folder['80397']= array('34','35','36','45','57');

echo '<hr>';

function multidimensional_array_diff($a1,$a2)
{
  $r = array();

 foreach ($a2 as $key => $second)
 {
      foreach ($a1 as $key => $first)
      {

            if (isset($a2[$key]))
            {
                foreach ($first as $first_value)
                {
                    foreach ($second as $second_value)
                    {
                        if ($first_value == $second_value)
                        {
                            $true = true;
                            break;
                        }
                    }
                    if (!isset($true))
                    {

                        $r[$key][] = $first_value;
                    }
                    unset($true);
                }
            }
            else
            {
                $r[$key] = $first;
            }
      }
 }
  return $r;
}
print_r(single_diff_assoc($folder,$bdd));
?>

RESULT :

Array
(
    [80395] => Array
        (
            [0] => 666
            [1] => 154223
        )

    [80397] => Array
        (
            [0] => 34
            [1] => 35
            [2] => 36
            [3] => 45
            [4] => 57
        )

)
S Gower 15-Feb-2010 02:45
array_diff does not create a new array containing the values present in $array1 but not $array2 -- it simply unsets all of the value in $array1 that are in $array2 and returns it.

This means that the indexes of the returned array are typically not continuous from zero. For example:

<?php

$array1 = array('red', 'blue', 'green', 'octarine');
$array2 = array('red', 'yellow', 'green');
$diff = array_diff($array1, $array2);

print_r($diff); //Array ( [1] => blue [3] => octarine )

?>

The easiest way around this seems to be use array_merge:

<?php

print_r(array_merge($diff)) //Array ( [0] => blue [1] => octarine )

?>
pikiou at somethinggooglerelated dot com 13-Nov-2009 04:24
With previous solutions handling multi-dimensional arrays or objects through serialization, if compared variables contain references at some point, these will be serialized and stand as such after the diff function.
Here is a safer solution :
<?php
function array_diff_no_cast(&$ar1, &$ar2) {
   $diff = Array();
   foreach ($ar1 as $key => $val1) {
      if (array_search($val1, $ar2) === false) {
         $diff[$key] = $val1;
      }
   }
   return $diff;
}
?>

Example:
<?php
$referenced = Array(1,1);
$array1 = Array(&$referenced, Array(2,3));
$array2 = Array(Array(1,1), Array(4,5));
$result = array_diff_no_cast($array1, $array2);

print_r($result);   //Outputs Array(1 => Array(2,3))
//And $referenced stands unchanged (not serialized)
?>
vojtech dot hordejcuk at gmail dot com 03-Nov-2009 07:15
Based on one lad's code, I created following function for creating something like HTML diff. I hope it will be useful.

<?php
private function diff ($old, $new)
{
  $old = preg_replace ('/ +/', ' ', $old);
  $new = preg_replace ('/ +/', ' ', $new);

  $lo = explode ("\n", trim ($old) . "\n");
  $ln = explode ("\n", trim ($new) . "\n");
  $size = max (count ($lo), count ($ln));

  $equ = array_intersect ($lo, $ln);
  $ins = array_diff ($ln, $lo);
  $del = array_diff ($lo, $ln);

  $out = '';

  for ($i = 0; $i < $size; $i++)
  {
    if (isset ($del [$i]))
    {
      $out .= '<p><del>' . $del [$i] . '</del></p>';
    }

    if (isset ($equ [$i]))
    {
      $out .= '<p>' . $equ [$i] . '</p>';
    }

    if (isset ($ins [$i]))
    {
      $out .= '<p><ins>' . $ins [$i] . '</ins></p>';
    }
  }

  return $out;
}
?>
Anonymous 15-Oct-2009 11:55
Hi!
I tried hard to find a solution to a problem I'm going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.

What I needed, it's some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.

So, as an example:

A = 1,2,3
B = 2,3,4

should NOT be:

C = 1,4

but:

A = 1
B = 4

so basically, I wanted to delete coincidences on both arrays.

Now, I've some actions to do, and I know wich one I've to do with the values from one array or another.
With the normal DIFF I can't, because if I've an array like C=1,4, I dont know if I've to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don't know wich action to apply...

So I created this:

<?php
function array_diff_ORG_NEW(&$org, &$new, $type='VALUES'){
    switch($type){
        case 'VALUES':
            $int = array_values(array_intersect($org, $new)); //C = A ^ B
            $org = array_values(array_diff($org, $int)); //A' = A - C
            $new= array_values(array_diff($new, $int)); //B' = B - C
            break;
        case 'KEYS':
            $int = array_values(array_intersect_key($org, $new)); //C = A ^ B
            $org = array_values(array_diff_key($org, $int)); //A' = A - C
            $new= array_values(array_diff_key($new, $int)); //B' = B - C
            break;
    }
}
?>

This cute, works by reference, and modifies the arrays deleting coincidences on both, and leaving intact the non coincidences.

So a call to this will be somethin' like:

<?php
$original = array(1,2,3);
$new = array(2,3,4);

array_diff_ORG_NEW($original, $new, 'VALUES');
?>

And HERE, I'll have my arrays as I wanted:

$original = 1
$new = 4

Now, why I use it precisely?

Imagine you've some "Events" and some users you select when create the event, can "see" this event you create. So you "share" the event with some users. Ok?

Imagine you created and Event_A, and shared with users 1,2,3.

Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.

(numbers are users ID).

So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID's corresponding to the users to share after modifying ($new). Wich ones you've to DELETE from DDBB, and wich ones do you've to INSERT?

If you do a simple difference or somehow, you get somethin' like C=1,4.
You have no clue on wich one you've to insert or delete.

But on this way, you can know it, and that's why:

- What keeps on $original, it's somethin not existing in $new at the beggining. So you know that all what you've inside $original, have to be deleted from DDBB because what you did in the modifying process, it's to unselect those users keeping in $original.
- What keeps on $new, it's something not existing in $original at the beggining. Wich means that in the modifying process you added some new users. And those have to be inserted in DDBB. So, everything keeping inside $new, have to be inserted in the DDBB.

Conclusion:

- Remaining in $original --> delete from DB.
- Remaining in $new --> insert into DB.

And that's all!

I hope you find it useful, and I encourage PHP "makers", to add in a not distant future, somethin' like this one natively, because I'm shure that I'm not the first one needing something like this.

Best regards all,

Light.
firegun at terra dot com dot br 24-Jun-2009 10:52
Hello guys,

I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case :D

We got 2 arrays like these:

<?php
$aArray1['marcie'] = array('banana' => 1, 'orange' => 1, 'pasta' => 1);
$aArray1['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);

$aArray2['marcie'] = array('banana' => 1, 'orange' => 1);
?>

As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the result we should expect is:

<?php
$aDiff['marcie'] = array('pasta' => 1);
$aDiff['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);
?>

Ok, now some comments about this function:
 - Different from the PHP array_diff, this function DON´T uses the === operator, but the ==, so 0 is equal to '0' or false, but this can be changed with no impacts.
 - This function checks the keys of the arrays, array_diff only compares the values.

I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)

<?php
function arrayRecursiveDiff($aArray1, $aArray2) {
    $aReturn = array();

    foreach ($aArray1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $aArray2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
                if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            } else {
                if ($mValue != $aArray2[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }

    return $aReturn;
}
?>
pyerre 12-Sep-2008 06:20
be careful kids, this function can be tricky
<?php
$tab1=array(0=>"a");
$tab2=array(0=>"a",1=>"b");

print_r(array_diff($tab1,$tab2));
?>
gives
Array
(
)
Tim Trefren 04-Apr-2008 08:05
Here's a little wrapper for array_diff - I found myself needing to iterate through the edited array, and I didn't need to original keys for anything.

<?php
function arrayDiff($array1, $array2){
    # This wrapper for array_diff rekeys the array returned
    $valid_array = array_diff($array1,$array2);

    # reinstantiate $array1 variable
    $array1 = array();

    # loop through the validated array and move elements to $array1
    # this is necessary because the array_diff function returns arrays that retain their original keys
    foreach ($valid_array as $valid){
        $array1[] = $valid;
        }
    return $array1;
    }
?>
merlinyoda at dorproject dot net 28-Mar-2008 10:11
As touched on in kitchin's comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de's comment of 17-Jul-2007 10:45, array_diff's behavior may be counter-intuitive if you aren't thinking in terms of set theory.

array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren't in both A and B).

Drawing one of those Ven diagrams or Euler diagrams may help with visualization...

As far as a function for returning what you may be expecting, here's one:

<?php
function array_xor ($array_a, $array_b) {
    $union_array = array_merge($array_a, $array_b);
    $intersect_array = array_intersect($array_a, $array_b);
    return array_diff($union_array, $intersect_array)
}
?>
radim at badsi dot info 05-Sep-2007 02:03
array_diff doesn't work with arrays of objects because it compares the string-represantation of the arguments (which is always "Object" for an object).

Here is an easy way to compute the difference of two arrays of objects :

<?php

...

function array_obj_diff ($array1, $array2) {

    foreach ($array1 as $key => $value) {
        $array1[$key] = serialize ($value);
    }

    foreach ($array2 as $key => $value) {
        $array2[$key] = serialize ($value);
    }

    $array_diff = array_diff ($array1, $array2);

    foreach ($array_diff as $key => $value) {
        $array_diff[$key] = unserialize ($value);
    }

    return $array_diff;
}

array_obj_diff ($ao1, $ao2);
?>
asdf at asdf dot com 14-Aug-2007 05:21
Even tough the description of this function's behavior has changed it
does not appear as tough the function's behavior has changed.  Below is some test code and its output:

<?php

    $a = array('1','2','3','4','5');
    $b = array('1','a','b','c','d','e');
    $c = array('2','f','g','h','i','j');

    print_r(array_diff($a, $b, $c));

?>

Array
(
    [2] => 3
    [3] => 4
    [4] => 5
)
nilsandre at gmx dot de 17-Jul-2007 09:45
Again, the function's description is misleading right now. I sought a function, which (mathematically) computes A - B, or, written differently, A \ B. Or, again in other words, suppose

A := {a1, ..., an} and B:= {a1, b1, ... , bm}

=> array_diff(A,B) = {a2, ..., an}

array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).

You should include this in the documentation more precisely, I think.
mr dot kschan at gmail dot com 12-Jul-2007 09:16
just comment ... i don't know whether the following implementation of array_diff is having a much better meaning to the function name.

function ary_diff( $ary_1, $ary_2 ) {
  // compare the value of 2 array
  // get differences that in ary_1 but not in ary_2
  // get difference that in ary_2 but not in ary_1
  // return the unique difference between value of 2 array
  $diff = array();

  // get differences that in ary_1 but not in ary_2
  foreach ( $ary_1 as $v1 ) {
    $flag = 0;
    foreach ( $ary_2 as $v2 ) {
      $flag |= ( $v1 == $v2 );
      if ( $flag ) break;
    }
    if ( !$flag ) array_push( $diff, $v1 );
  }

  // get difference that in ary_2 but not in ary_1
  foreach ( $ary_2 as $v2 ) {
    $flag = 0;
    foreach ( $ary_1 as $v1 ) {
      $flag |= ( $v1 == $v2 );
      if ( $flag ) break;
    }
    if ( !$flag && !in_array( $v2, $diff ) ) array_push( $diff, $v2 );
  }

  return $diff;
}

i think array_diff should return the difference between the array independent of the order of passing the parameter.
kitchin 19-Jun-2007 02:49
Until recently, the description said:
"array_diff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved."

Now it says:
"Compares array1 against array2 and returns the difference."

Now it's not clear what the optional arguments after the first two do.  Also, the difference is not symmetric in its arguments (that is array_intersect).
gilthans at NOgmailSPAM dot com 13-Jun-2007 10:11
I needed a function to only remove the element the amount of times he appears in the second array. In other words, if you have Array(1, 1, 2) and Array(1), the return value should be Array(1, 2).
So I built this function right here:

<?php
function array_diff_once(){
    if(($args = func_num_args()) < 2)
        return false;
    $arr1 = func_get_arg(0);
    $arr2 = func_get_arg(1);
    if(!is_array($arr1) || !is_array($arr2))
        return false;
    foreach($arr2 as $remove){
        foreach($arr1 as $k=>$v){
            if((string)$v === (string)$remove){ //NOTE: if you need the diff to be STRICT, remove both the '(string)'s
                unset($arr1[$k]);
                break; //That's pretty much the only difference from the real array_diff :P
            }
        }
    }
    //Handle more than 2 arguments
    $c = $args;
    while($c > 2){
        $c--;
        $arr1 = array_diff_once($arr1, func_get_arg($args-$c+1));
    }
    return $arr1;
}
$arr1 = Array("blue", "four"=>4, "color"=>"red", "blue", "green", "green", "name"=>"jon", "green");
$arr2 = Array("4", "red", "blue", "green");
print_r(array_diff_once($arr1, $arr2));
?>
This prints:
Array ( [1] => blue [3] => green [name] => jon [4] => green )

Note that it removes the elements left to right, opposite to what you might expect; in my case the order of elements had no importance. Fixing that would require a small variation.
tim at php dot user 04-Jun-2007 08:06
The description is wrong, array_diff() returns an array consisting of all elements in $array1 that are not in $array2. The example shows this.

Thats how it works on my php anyway.
ahigerd at stratitec dot com 01-Feb-2007 02:30
An earlier comment suggested using array_merge() to reindex the array. While this will work, array_values() is about 30-40% faster and accomplishes the same task.
03-Aug-2006 12:30
array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.

<?php

//pass value you wish to delete and the array to delete from
function array_delete( $value, $array)
{
    $array = array_diff( $array, array($value) );
    return $array;
}
?>
Colin 25-Jul-2006 09:44
Undocumented return:  it appears this will return NULL if an error occurs (e.g., an argument is not an array) and is not caught.

<?
@array_diff(NULL, array(1));
@array_diff(array(1), NULL);
@array_diff();
?>

All return NULL.  (Note the "@")
ben dot lancaster at design-ontap dot co dot uk 07-Jul-2006 04:57
One common caveat of this function is that if the arrays match, an empty array is return, not a strict boolean. E.g.:

<?php
$array1 = $array2 = array('a','b','c');

var_dump(array_diff($array1,$array2));
/*
 *Returns:
 * array(0) {
 * }
 */
?>
pavlicic at NOSPAM dot hotmail dot com 09-Mar-2006 01:55
<?php

// first array
$vid_player = $vm->getVideosByPlayer($player);

// second array
$vid_playlist = $vm->getVideosByPlaylist($playlist);

// this will not work...
$vid_player = array_diff($vid_player, $vid_playlist);

// but if you do this first...
$videos = array();
foreach ( $vid_player as $player )
{
    if ( $vid_playlist != null )
    {
        foreach ( $vid_playlist as $video )
        {
            if ( $player->id == $video->id )
                $videos[] = $player;
        }
    }
}

// this will work...
$vid_player = array_diff($vid_player, $videos);

?>
The first array_diff() compares two arrays only to find out that all the objects are unique!
Jappie 22-Jan-2006 10:40
Sorry for the bug in my last comment (probably rightfully removed by the admins).
If you want to compare more than 2 arrays, or don't know how many arrays need to be compared, this is your function:

<?php
# An extention to array_diff:
# It returns an array of all values not present in all arrays given. If '$strict' is true,
# it returns all values not present or not in the same order in all arrays given. The
# arrays to compare must be placed in another array, which is used as argument '$arrays'.
# Returns false if the '$arrays' is invalid.
function array_rdiff ($arrays, $strict = false) {
    # check if argument is valid.
    if (!is_array ($arrays))
        return false;
    foreach ($arrays as $array)
        if (!is_array ($array))
            return false;

    # set working variables
    $diff    = array ();
    $amount  = count ($arrays);
    $needles = array_shift ($arrays);

    # compare
    for ($n = 0; $n < $amount; $n++) {
        for ($m = 0; $needles[$m]; $m++) {
            $found     = true;
            $positions = array ($m);
            foreach ($arrays as $haystack) {
                if (($pos = array_search ($needles[$m], $haystack)) === false)
                    $found = false;
                if ($strict)
                    $positions[] = $pos;
            }
            if (!$found)
                $diff[] = $needle;
            elseif ($strict && (count (array_unique ($positions)) > 1))
                $diff[] = $needle;
        }
        $arrays[] = $needles;
        $needles  = array_shift ($arrays);
    }
    return array_unique ($diff);
}
?>
Simon Riget at paragi.dk 21-Jan-2006 05:27
A simple multidimentional key aware array_diff function.

<?php
function arr_diff($a1,$a2){
  foreach($a1 as $k=>$v){
    unset($dv);
    if(is_int($k)){
      // Compare values
      if(array_search($v,$a2)===false) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[]=$dv;
    }else{
      // Compare noninteger keys
      if(!$a2[$k]) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[$k]=$dv;
    }
  }
  return $diff;
}
?>

This function meets my immidiate needs but I'm shure it can be improved.
doug at NOSPAM dot thrutch dot co dot uk 06-Jan-2006 04:22
After spending half an hour scratching my head wondering why this function wasn't working I realised I had the arguments the wrong way round!

I needed to remove the contents of $array1 from $array2 so I tried:

<?php
$diff    = array_diff($members1, $members2);
?>

WRONG!! A quick swap around and things worked smoothly...

<?php
$diff    = array_diff($members2, $members1);
?>

Hope this saves someone a bit of bother
air at multi dot fi 04-Jan-2006 03:41
A small thing that caused me trouble today, wich I don't see listed on this page is that array_diff keeps the placing for the uniqe values, and removes the duplicated. This gives us empty fields in the array, wich caused me a lot of trouble. The solutions was simply to use array_merge() around the array_diff.

For example:
$array1 = array('blue', 'red', 'green');
$array2 = array('red');

array_diff($array1, $array2);

Will give us:
------
Array
(
   [0] => red
   [1] =>
   [2] => green
)

But if we use:

array_merge(array_diff($array1, $array2));

We will get:
------
Array
(
   [0] => red
   [1] => green
)
Viking Coder 03-Jan-2006 09:07
To anybody wanting a double-sided array_diff - mentioned by rudigier at noxx dot at. Remember, array_diff gives you everything in the first array that isn't in the subsequent arrays.

$array1=array('blue','red','green');
$array2=array('blue','yellow','green');

array_merge(array_diff($array1, $array2),array_diff($array2, $array1));

Result
------
Array
(
    [0] => red
    [1] => yellow
)
white_phoenix at ru dot ru 14-Dec-2005 11:37
To: effectpenguin at antarctida dot ru
Re: interesting effect
<?php
function arraycpy(&$target,&$array)
{
 if (!is_array($target)) {$target = array();}
 foreach($array as $k=>$v) {if ($k != "GLOBALS") {$target[$k] = $v;}}
}
arraycpy($old,$GLOBALS);
// some actions with variables:
$homer = "beer";
arraycpy($new,$GLOBALS);
$diff = array_diff($new,$old);
var_dump($diff);
?>
array(1) {
  ["homer"]=>
  string(4) "beer"
}
Windows NT WPX_NB 5.1 build 2600 PHP/5.0.4
penguin at antarctida dot ru 06-Oct-2005 05:41
Interesting effect...
I just wanted to see, what variables are created and not unset after some actions.
So I write:

<?php
$a_var_GlobalsBefore = $GLOBALS;
?>
...some actions with variables
<?php
$a_var_GlobalsAfter = $GLOBALS;
$a_var_VariablesNotUnset = array_diff ($a_var_GlobalsAfter, $a_var_GlobalsBefore);
?>

...and _ALL_ variables puff up in smoke.

Have no idea what causes this behavior, but found a nice workaround:

<?php
$a_var_GlobalsBefore = array_keys ($GLOBALS);
?>
...some actions with variables
<?php
$a_var_GlobalsAfter = array_keys ($GLOBALS);
$a_var_VariablesNotUnset = array_diff ($a_var_GlobalsAfter, $a_var_GlobalsBefore);
?>

...and the unset variables are here.
rafmav 19-Apr-2005 04:24
Here is a few functions to do a fast diff between two arrays in a few lines.
You can use it with other functions described in the function array_merge : array_merge_replace from an other user, and two functions using it : array_merge_diff and array_merge_diff_reverse.
Note that the keys are preserved!
<?
// returns a two dimensions array with the deleted data
// and the added data
function array_diff_both($new,$old)
{
    $del=array_diff_assoc($old,$new);
    $add=array_diff_assoc($new,$old);
    return $diff=array("del"=>$del, "add"=>$add);
}

// returns a two dimensions array with the equal data,
// deleted data and the added data
function array_diff_all($arr_new,$arr_old)
{
    $arr_equ=array_intersect_assoc($arr_new,$arr_old);
    $arr_del=array_diff_assoc($arr_old,$arr_new);
    $arr_add=array_diff_assoc($arr_new,$arr_old);
    return $diff=array("equ"=>$arr_equ, "del"=>$arr_del, "add"=>$arr_add);
}
?>
rudigier at noxx dot at 09-Feb-2005 10:53
if you don't like the php diff (like me) then take look at my diff functions

if you have two arrays, lets say:

a1 = { blue, red, green }
a2 = { blue, yellow, green }

array_diff just gives me nothing, although there is a difference. instead of an empty array, i needed an array which should contain "red" and "yellow" in this case.

single_diff satisfies my wish.

function single_diff(&$a1,&$a2)
{
  $r = array(); // return

  foreach ($a1 as $pl) // payload
  {
    if (! in_array($pl, $a2, true) )
      $r[] = $pl;
  }

  foreach ($a2 as $pl) // payload
  {
    if (! in_array($pl, $a1, true) && ! in_array($pl, $r, true) )
      $r[] = $pl;
  }
  return $r;
}

--------------------
this one just keeps the keys of the arrays in mind by comparing the values directly. just in case if there are values, which might occur multiple in one of these arrays.

function single_diff_assoc(&$a1,&$a2)
{
  $r = array(); // return

  foreach ($a1 as $k => $pl) // payload
  {
    if (! isset($a2[$k]) || $a2[$k] != $pl)
      $r[$k] = $pl;
  }

  foreach ($a2 as $k => $pl) // payload
  {
    if ( (! isset($a1[$k]) || $a1[$k] != $pl ) && ! isset($r[$k]) )
      $r[$k] = $pl;
  }
  return $r;
}

recursion support might be useful, but feel free to modify this functions to your own purposes.
j dot j dot d dot mol at ewi dot tudelft dot nl 31-Dec-2004 12:34
Here is some code to take the difference of two arrays. It allows custom modifications like prefixing with a certain string (as shown) or custom compare functions.

<?php
 // returns all elements in $all which are not in $used in O(n log n) time.
  // elements from $all are prefixed with $prefix_all.
  // elements from $used are prefixed with $prefix_used.
  function filter_unused( $all, $used, $prefix_all = "", $prefix_used = "" ) {
      $unused = array();

      // prefixes are not needed for sorting
      sort( $all );
      sort( $used );

      $a = 0;
      $u = 0;

      $maxa = sizeof($all)-1;
      $maxu = sizeof($used)-1;

      while( true ) {
          if( $a > $maxa ) {
              // done; rest of $used isn't in $all
              break;
          }
          if( $u > $maxu ) {
              // rest of $all is unused
              for( ; $a <= $maxa; $a++ ) {
                  $unused[] = $all[$a];
              }
              break;
          }

          if( $prefix_all.$all[$a] > $prefix_used.$used[$u] ) {
              // $used[$u] isn't in $all?
              $u++;
              continue;
          }

          if( $prefix_all.$all[$a] == $prefix_used.$used[$u] ) {
              // $all[$a] is used
              $a++;
              $u++;
              continue;
          }

          $unused[] = $all[$a];

          $a++;
      }

      return $unused;
  }
?>
sire at coolquotescollection dot com 25-Nov-2003 05:52
Continuing from r.kirschke's excellent diff function (above), here's a function that will turn the result into nicely formatted HTML:

<?php
echo "<html><body bgcolor=white>";

$oldString = "Once there was a boy named Bart and a girl named Lisa.";
$newString = "Once upon a time there was a girl named Lisa.";

echo "Old String: " . $oldString . "<br>";
echo "New String: " . $newString . "<br>";
echo "Difference: " . diff_to_html($oldString, $newString);
// Returns a nicely formatted html string
function diff_to_html($oldString, $newString)
{
  $a1 = explode(" ", $oldString);
  $a2 = explode(" ", $newString);
  $result = arr_diff($a1, $a2);

  foreach ($result[0] as $num => $foo)
  {
    $source = $result[1][$num];
    $element = $result[0][$num];

    switch ($source)
    {
      case "1":
        $pre = "<font color=red><s>";
        $post = "</s></font>";
        break;
      case "2":
        $pre = "<font color=green>";
        $post = "</font>";
        break;
      case "b":
        $pre = "";
        $post = "";
        break;
    }
    // VERTICAL OUTPUT:
    // $return .= $num . $pre . " " . $source .
    // " " . $element . $post . "<br>";
    // READABLE OUTPUT:
    $return .= $pre . $element . $post . " ";
  }
  return $return;
}

?>
18-Nov-2003 04:54
From the page:
Note:  Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);

I've found a way to bypass that. I had 2 arrays made of arrays.
I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function:

<?php
function my_serialize(&$arr,$pos){
  $arr = serialize($arr);
}

function my_unserialize(&$arr,$pos){
  $arr = unserialize($arr);
}

 //make a copy
$first_array_s = $first_array;
$second_array_s = $second_array;

// serialize all sub-arrays
array_walk($first_array_s,'my_serialize');
array_walk($second_array_s,'my_serialize');

// array_diff the serialized versions
$diff = array_diff($first_array_s,$second_array_s);

// unserialize the result
array_walk($diff,'my_unserialize');

// you've got it!
print_r($diff);
?>
d dot u dot phpnet at holomind dot de 26-Mar-2003 11:48
I was not satisfied with the compare-funtions of array_diff() so i wrote a litte diff-clone which compares arrays and shows all different entries. You can easliy change the function formatline() for your needs.

function arr_diff( $a1, $a2, $show_matches=0);
...
output:
1 : 1 : - <head><title>Text</title></head>
1 : 1 : + <head><title>Text2</title></head>
4 : 4 : - code b
4 : 4 : + code a
8 : 8 : - code f

See details on:  (example and source)

http://www.holomind.de/phpnet/diff.php
http://www.holomind.de/phpnet/diff.src.php
r dot kirschke at gmx dot net 24-Mar-2003 01:26
Are you looking for a function which returns an edit script (a set of insert and delete instructions on how to change one array into another)? At least, that's what I hoped to find here, so here's some code based on http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps :

<?php
function diff_rek(&$a1,&$a2,$D,$k,&$vbck)
{
 $x=$vbck[$D][$k]; $y=$x-$k;
 if ($D==0)
 {
  if ($x==0) return array(array(),array());
  else
  return array(array_slice($a1,0,$x),array_fill(0,$x,"b"));
 }
 $x2=$vbck[$D-1][$k+1];
 $y2=$vbck[$D-1][$k-1]-($k-1);
 $xdif=$x-$x2; $ydif=$y-$y2;
 $l=min($x-$x2,$y-$y2);
 $x=$x-$l;
 $y=$y-$l;
 if ($x==$x2)
 {
   $res=diff_rek($a1,$a2,$D-1,$k+1,$vbck);
   array_push($res[0],$a2[$y-1]);
   array_push($res[1],"2");
   if ($l>0)
   {
    $res[0]=array_merge($res[0],array_slice($a2,$y,$l));
    $res[1]=array_merge($res[1],array_fill(0,$l,"b"));
   }
 }
 else
 {
   $res=diff_rek($a1,$a2,$D-1,$k-1,$vbck);
   array_push($res[0],$a1[$x-1]);
   array_push($res[1],"1");
   if ($l>0)
   {
    $res[0]=array_merge($res[0],array_slice($a1,$x,$l));
    $res[1]=array_merge($res[1],array_fill(0,$l,"b"));
   }
 }
 return $res;
}

function arr_diff(&$a1,&$a2)
{
 $max=70;
 $c1=count($a1);
 $c2=count($a2);
 $v[1]=0;
 for ($D=0; $D<=$max; $D++)
 {
   for ($k=-$D; $k<=$D; $k=$k+2)
  {
   if (($k==-$D) || ($k!=$D && $v[$k-1]<$v[$k+1]))
    $x=$v[$k+1];
   else
    $x=$v[$k-1]+1;
   $y=$x-$k;
   while (($x<$c1)&&($y<$c2)&&($a1[$x]==$a2[$y]))
    {
     $x++;
     $y++;
    }
    $v[$k]=$x;
    if (($x>=$c1)&&($y>=$c2))
   {
    $vbck[$D]=$v;
    return diff_rek($a1,$a2,$D,$c1-$c2,$vbck);
   };
  }
  $vbck[$D]=$v;
 };
 return -1;
}
?>

This works on arrays of all elements for which the operator "==" is defined.
arr_dif($a1,$a2) returns an array of two arrays:
$result[0] = array of elements from $a1 and $a2
$result[1] = array of chars - one for each element from $result[0]:
 "1" : The corresponding element is from $a1
 "2" : The corresponding element is from $a2
 "b" : The correspondig element is from both source arrays
The function returns -1, when the number of different elements is greater than $max

Example:
$a1=array("hello","world");
$a2=array("good","bye","world");
=> arr_diff($a1,$a2) = array(array("hello","good","bye","world"), array("1","2","2","b"));
csaba2000 at yahoo dot com 25-Feb-2003 01:58
<?php
function array_key_diff($ar1, $ar2) {  // , $ar3, $ar4, ...
    // returns copy of array $ar1 with those entries removed
    // whose keys appear as keys in any of the other function args
    $aSubtrahends = array_slice(func_get_args(),1);
    foreach ($ar1 as $key => $val)
        foreach ($aSubtrahends as $aSubtrahend)
            if (array_key_exists($key, $aSubtrahend))
                unset ($ar1[$key]);
    return $ar1;
}

$a = array("c" => "catty", "b" => "batty", "a" => "aunty", 5 => 4, 2.9 => 7, 11, "n" => "nutty");
$b = array(9, "d" => "ditty", "b" => "bratty", "a" => null, 10, 13);
$c = array_key_diff ($a, $b, array(5 => 6));
?>

$c is then equivalent to array('c' => 'catty', 6 => 11, 'n' => 'nutty')

Csaba Gabor from New York
ds2u at the hotmail dot com 23-Feb-2003 04:22
Yes you can get rid of gaps/missing keys by using:

<?php
$result = array_values(array_diff($array1,$array2));
?>

But to drop the storage of void spaces (actually a line feed) which are irritatingly indexed when reading from files - just use difference:

<?php
$array = array ();
$array[0] = "\n";
$result = array_diff($result,$array);
?>

dst
jg at sto dot com dot au 02-Nov-2002 01:54
I have found an interesting use for array_diff. I remember seing somebody having trouble deleting from an array because it left "holes".

I thought about using array_diff to fix the problem. Try running this code and see what it does:

<?php

for($i=0;$i<4;$i++)
{
print("Deleting item $i from the array<BR>");

$my_array = array("value1","value2","value3","value4");

$my_array = array_diff($my_array,array_slice($my_array,$i,1));

foreach($my_array as $value)print("    -->$value<BR>\n");
}
?>

It seems to work for every member of the array. I'm not sure how efficient it would be on really large arrays, though.

JG Estiot
drNOSPAMtdiggersSPAMNO at hotmail dot com 06-Aug-2002 01:10
array_diff does not have buggy behavior as described above.  The problem stems from calling array_diff() each time in the loop, therefore regererating a new array with an index always at the beginning EVERY time, so each will always pick the first entry.  This is not buggy, but in fact what you've told the program to do :)  The solution is not as much a solution, but properly instructing the program what to do!

Cheers!
TheoDiggers
arjanz at intermax dot nl 09-Apr-2002 11:53
In PHP 4.0.6 the array_minus_array() as shown above didn't work properly, especially when you use duplicated values:

When I wanted to substract
      'Array(1,1,2,3)'
with
      'Array (1,2,4)'

I wanted as result:

'Array(1,3)'

And not just 'Array (3)' as it would give using array_diff(), or nothing as result using the above array_minus_array function.

This worked for me:

<?php
function array_minus_array($a,$b)  {
    $c = Array();
    foreach ($a as $key => $val) {
           $posb = array_search($val,$b);
           if (is_integer($posb)) {
               unset($b[$posb]);
           } else {
               $c[] = $val;
           }
    }
    return $c;
}
?>
alex at bacan dot cl_remove_this_for_email 08-Feb-2002 12:03
For those who are looking how to substract one array for another:
you cannot use the "-" operator !!!

But you can use this function:
<?php
function array_minus_array($a, $b) {
        $c=array_diff($a,$b);
        $c=array_intersect($c, $a);
        return $c;
}
?>

So, for example:
<?php
$a[]="a";
$a[]="b";
$a[]="c";
$b[]="a";
$c=array_minus_array($a,$b);
var_dump($c);
?>

Prints out:
array(2) {
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}
which is $a-$b, as we wanted.

PD: you may also do a foreach ... if $a in_array $b ... but this is much more elegant !!!
Credits to A.Atala "mandrake", who knows everything about mathematic.
SeanECoates at !donotspam!yahoo dot ca 16-Oct-2001 10:43
I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want "." or ".." to be in the array of files I'm creating. Here's a simple way to remove them:

<?php
 $someFiles = array();
 $dp = opendir("/some/dir");
 while($someFiles[] = readdir($dp));
 closedir($dp);

 $removeDirs = array(".","..");
 $someFiles = array_diff($someFiles, $removeDirs);

 foreach($someFiles AS $thisFile) echo $thisFile."\n";
?>

S
caugustin at alcyonis dot nospam dot fr 26-Jul-2001 03:57
In version 4.0.1 to 4.0.4, array_diff() works on array of array, but not anymore in version 4.0.5 and 4.0.6.<br>
According to php team :
When I wrote array_diff I didn't think of this use. It
worked by accident. array_diff was changed to avoid
some ordering problems. The way it was there was no well
defined ordering. Due to automatic type conversion, you
you would have 3d < 99 <  370 < 3d. This made
array_diff fail, this was fixed by always using string
comparisons. That doesn't work for arrays though.
david at audiogalaxy dot com 08-Apr-2001 04:12
Note that array_diff() considers the type of the array elements when it compares them.

If array_diff() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to diff an array of integers with an array of strings.
array_diff_ukey
array_fill_keys
Функции для работы с массивами


Создает массив и заполняет его значениями, с определенными ключами

array_diff
array_fill
Функции для работы с массивами
PHP Manual

array_fill_keys

(PHP 5 >= 5.2.0)

array_fill_keys — Создает массив и заполняет его значениями, с определенными ключами

Описание

array array_fill_keys ( array $keys , mixed $value )

Создает и заполняет массив значением параметра value, используя значения массива keys в качестве ключей.

Список параметров

keys

Массив значений, которые будут использованы в качестве ключей. Некорректные ключи массива будут преобразованы в string.

value

Заполняемое значение

Возвращаемые значения

Возвращает заполненный массив

Примеры

Пример #1 Пример использования array_fill_keys()

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

Результат выполнения данного примера:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

Смотрите также

  • array_fill() - Заполняет массив значениями
  • array_combine() - Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений

User Contributed Notes

sergli at nigma dot ru 25-May-2012 11:53
<?php
$a = array("1");

var_dump(array_fill_keys($a, "test"));
?>

array(1) {
  [1]=>
  string(4) "test"
}

now string key "1" become an integer value 1, be careful.
matrebatre 20-Jun-2008 07:28
This function does the same as:
<?php
$array = array_combine($keys,array_fill(0,count($keys),$value));
?>
phydeaux 14-May-2008 10:26
Scratchy's version still doesn't work like the definition describes.  Here's one that can take a mixed variable as the second parameter, defaulting to an empty string if it's not specified.  Don't know if this is exactly how the function works in later versions but it's at least a lot closer.

function array_fill_keys($target, $value = '') {
    if(is_array($target)) {
        foreach($target as $key => $val) {
            $filledArray[$val] = is_array($value) ? $value[$key] : $value;
        }
    }
    return $filledArray;
}

This works for either strings or numerics, so if we have

$arr1 = array(0 => 'abc', 1 => 'def');
$arr2 = array(0 => 452, 1 => 128);
$arr3 = array(0 => 'foo', 1 => 'bar');

then

array_fill_keys($arr1,$arr2)
returns: [abc] => 452, [def] => 128

array_fill_keys($arr1,0)
returns: [abc] => 0, [def] => 0

array_fill_keys($arr2,$arr3)
returns: [452] => foo, [128] => bar

array_fill_keys($arr3,'BLAH')
returns: [foo] => BLAH, [bar] => BLAH

and array_fill_keys($arr1)
returns: [abc] =>, [def] =>
Scratchy 02-May-2008 02:18
RE: bananasims at hotmail dot com

I also needed a work around to not having a new version of PHP and wanting my own keys. bananasims code doesn't like having an array as the second parameter...

Here's a slightly modified version than can handle 2 arrays as inputs:

//we want these values to be keys
$arr1 = (0 => "abc", 1 => "def");
/we want these values to be values
$arr2 = (0 => 452, 1 => 128);

function array_fill_keys($keyArray, $valueArray) {
    if(is_array($keyArray)) {
        foreach($keyArray as $key => $value) {
            $filledArray[$value] = $valueArray[$key];
        }
    }
    return $filledArray;
}

array_fill_keys($arr1, $arr2);

returns:
abc => 452, def =>128
bananasims at hotmail dot com 19-Dec-2006 05:03
Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below

function array_fill_keys($array, $values) {
    if(is_array($array)) {
        foreach($array as $key => $value) {
            $arraydisplay[$array[$key]] = $values;
        }
    }
    return $arraydisplay;
}
array_diff
array_fill
Функции для работы с массивами


Заполняет массив значениями

array_fill_keys
array_filter
Функции для работы с массивами
PHP Manual

array_fill

(PHP 4 >= 4.2.0, PHP 5)

array_fill — Заполняет массив значениями

Описание

array array_fill ( int $start_index , int $num , mixed $value )

Заполняет массив num элементами со значением value, начиная с ключа start_index.

Список параметров

start_index

Первый индекс возвращаемого массива.

Если start_index отрицателен, первым индексом возвращаемого массива будет start_index, а последующие индексы будут начинаться с нуля (смотрите пример).

num

Количество вставляемых элементов, должно быть больше нуля.

value

Значение для заполнения

Возвращаемые значения

Возвращает заполненный мссив

Ошибки

Генерирует ошибку уровня E_WARNING, если num меньше единицы.

Примеры

Пример #1 Пример использования array_fill()

<?php
$a = array_fill(5, 6, 'banana');
$b = array_fill(-2, 4, 'pear');
print_r($a);
print_r($b);
?>

Результат выполнения данного примера:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)
Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)

Примечания

Смотрите также подробное описание отрицательных ключей в разделе Массивы.

Смотрите также

  • array_fill_keys() - Создает массив и заполняет его значениями, с определенными ключами
  • str_repeat() - Возвращает повторяющуюся строку
  • range() - Создает массив, содержащий диапазон элементов

User Contributed Notes

miguelxpain at gmail dot com 24-Feb-2012 06:04
I made this function named "array_getMax" that returns te maximum value and index, from array:

<?php
//using array_search_all by helenadeus at gmail dot com

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {

        if($haystack[$k]==$needle){

           $array[] = $k;
        }
    }
    return ($array);

}

function array_getMax($array){

    $conteo=array_count_values($array);

    if( count($conteo)==1 ){//returns full array when all values are the same.
        return  $array;
    }

    arsort($array);

    //$antValue=null;
    $maxValue=null;
    $keyValue=null;
    foreach($array as $key=>$value){
        if($maxValue==null){
            $maxValue=$value;
            $keyValue=$key;
            break;
        }
    }

    $resultSearch=array_search_all($maxValue, $array);

   return  array_fill_keys($resultSearch, $maxValue);

}

//example
  $arreglo=array('e1'=>99,'e2'=>'99','e3'=>1,'e4'=>1,'e5'=>98);

    var_dump(array_getMax($arreglo));

//output
/*
array(2) {
  ["e1"]=>
  int(99)
  ["e2"]=>
  int(99)
}
*/
?>

I hope some one find this usefull
caliban at darklock dot com 23-May-2005 07:42
To better handle the problem of sparse array completion mentioned a couple years ago...

What you really need in this scenario is an empty array containing all the desired keys, and a sparse array containing the keys and values you want overridden. This PHP5 function does that. (The PEAR package PHP_Compat should be able to fill in the gap -- array_combine() --  for a 4.3 install, if necessary.)

<?php
    function array_complete(
        $keys="",                // array of keys you need filled, in order
        $sparse=""                // sparse array to override blanks
    )
    {
        if(!is_array($sparse))
            $sparse=array();

        if(!is_array($keys))
            return $sparse;

        return array_merge(
            array_combine(        // create an associative array
                $keys,            // your list of keys
                array_fill(        // blank value for each key
                    0,count(
                        $keys
                    ),""
                )
            ),$sparse            // merge with your incomplete array
        );
    }
?>

This merges in your sparse array (inserting any additional keys in that array after the ones you've specified), placing its values in the key order you specify, leaving all the other values blank.

Test call: var_dump(array_complete(array("test1", "test2", "test3", "test4", "test5"), array("test3" => "test3", "test1" => "test1", "garbage" => "garbage")));

Result: array(6) {
  ["test1"]=>
  string(5) "test1"
  ["test2"]=>
  string(0) ""
  ["test3"]=>
  string(5) "test3"
  ["test4"]=>
  string(0) ""
  ["test5"]=>
  string(0) ""
  ["garbage"]=>
  string(7) "garbage"
}
csst0266 at cs dot uoi dot gr 11-Aug-2004 10:32
This is what I recently did to quickly create a two dimensional array (10x10), initialized to 0:

<?php
  $a = array_fill(0, 10, array_fill(0, 10, 0));
?>

This should work for as many dimensions as you want, each time passing to array_fill() (as the 3rd argument) another array_fill() function.
jausion at hotmail-dot-com 28-Mar-2003 11:50
For PHP < 4.2.0 users:

Add this to your script:
if (!function_exists('array_fill')) {
   require_once('array_fill.func.php');
}

and the array_fill.func.php file:

<?php

// For PHP version < 4.2.0 missing the array_fill function,
// I provide here an alternative. -Philippe

function array_fill($iStart, $iLen, $vValue) {
    $aResult = array();
    for ($iCount = $iStart; $iCount < $iLen + $iStart; $iCount++) {
        $aResult[$iCount] = $vValue;
    }
    return $aResult;
}

?>
25-Aug-2002 01:59
array_fill() cannot be used to setup only missing keys in an array. This  may be necessary for example before using implode()  on a sparse filled array.
The solution is to use this function:

<?php
function array_setkeys(&$array, $fill = NULL) {
  $indexmax = -1;
  for (end($array); $key = key($array); prev($array)) {
    if ($key > $indexmax)
      $indexmax = $key;
  }
  for ($i = 0; $i <= $indexmax; $i++) {
    if (!isset($array[$i]))
      $array[$i] = $fill;
  }
  ksort($array);
}
?>

This is usefull in some situations where you don't know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it.
array_fill_keys
array_filter
Функции для работы с массивами


Фильтрует элементы массива с помощью callback-функции

array_fill
array_flip
Функции для работы с массивами
PHP Manual

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filter — Фильтрует элементы массива с помощью callback-функции

Описание

array array_filter ( array $input [, callable $callback = "" ] )

Обходит каждое значение массива input, передавая его в callback-функцию. Если callback-функция возвращает true, данное значение возвращается в массив input. Ключи массива сохраняются.

Список параметров

input

Итерируемый массив

callback

Используемая callback-функция

Если callback-функция не передана, все значения массива input равные FALSE (см. преобразование в булевый тип) будут удалены.

Возвращаемые значения

Возвращает отфильтрованный массив.

Примеры

Пример #1 Пример использования array_filter()

<?php
function odd($var)
{
    // является ли переданное число нечетным
    return($var & 1);
}

function even($var)
{
    // является ли переданное число четным
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Нечетные:\n";
print_r(array_filter($array1, "odd"));
echo "Четные:\n";
print_r(array_filter($array2, "even"));
?>

Результат выполнения данного примера:

Нечетные:
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Четные:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Пример #2 Использование array_filter() без callback-функции

<?php

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?>

Результат выполнения данного примера:

Array
(
    [0] => foo
    [2] => -1
)

Примечания

Предостережение

Если callback-функция изменяет массив (например, добавляет или удаляет элементы), поведение этой функции неопределено.

Смотрите также

  • array_map() - Применяет callback-функцию ко всем элементам указанных массивов
  • array_reduce() - Итеративно уменьшает массив к единственному значению, используя callback-функцию
  • array_walk() - Применяет пользовательскую функцию к каждому элементу массива

User Contributed Notes

John Erck: erck0006 at junkyo dot gmail dot com 04-Apr-2012 08:09
<?php
// ARRAY FILTER RECURSIVE USING CLASS, STATIC METHOD, AND ANONYMOUS CALLBACK FUNCTION
// NOTE THAT THE CALLBACK HAS ACCESS TO BOTH THE KEY AND VALUE

// THE CLASS (FOR YOU TO COPY)
class ArrayUtil
{
    public static function FilterRecursive(Array $source, $fn)
    {
        $result = array();
        foreach ($source as $key => $value)
        {
            if (is_array($value))
            {
                $result[$key] = self::FilterRecursive($value, $fn);
                continue;
            }
            if ($fn($key, $value))
            {
                $result[$key] = $value; // KEEP
                continue;
            }
        }
        return $result;
    }
}

// EXAMPLE ANONYMOUS CALLBACK FUNCTION
$fn = function ($key, $value)
{
    if (strpos($key, 'drop') !== FALSE)
    {
        return FALSE; // DROP
    }
    return TRUE; // KEEP
};

// EXAMPLE PRE FILTER TEST DATA
$preFilter = array(
    'a' => 'one',
    'b' => array(
        'example_drop' => 'filter me out',
        'example_keep' => 'keep me',
    ),
    'c' => 'three',
);

// EXAMPLE USAGE CODE
echo '// print_r($preFilter);' . "\n";
print_r($preFilter);
$postFilter = ArrayUtil::FilterRecursive($preFilter, $fn);
echo "\n";
echo '// print_r($postFilter);' . "\n";
print_r($postFilter);

/* OUTPUT OPEN
// print_r($preFilter);
Array
(
    [a] => one
    [b] => Array
        (
            [example_drop] => filter me out
            [example_keep] => keep me
        )

    [c] => three
)

// print_r($postFilter);
Array
(
    [a] => one
    [b] => Array
        (
            [example_keep] => keep me
        )

    [c] => three
)
OUTPUT CLOSE */
spam dot 2011 at rebell dot at 21-Nov-2011 02:28
If you have not noticed already - array_filter() can be used to remove empty elements, since an empty string considered "false", if you not specify a callback

Keep in mind, that this will remove also some other values - so if you want a quick "remove empty elements from array" this function will be fine, as long as you dont have anything to keep, which casts to "false"
lisachenko dot it at HUMAN dot gmail dot com 22-Jul-2011 12:54
You can access the current key of array by passing a reference to array into callback function and call key() and next() method in the callback function:
<?php
$data = array('first' => 1, 'second' => 2, 'third' => 3);
$data = array_filter($data, function ($item) use (&$data) {
    echo "Filtering key ", key($data), '<br>', PHP_EOL;
    next($data);
    return false;
});
?>

However be careful with array internal pointer or use reset() method before calling array_filter().
noonesvk at gmail dot com 04-May-2011 02:01
Hi all,

I made a simple reindex & filter function.

reindex( array $input, [ $blacklist = array() ] )

This function is working only with array that has keys in INTEGER.

<?php

function reindex(array $source, $blacklist = array())
{
    $i = 0;
    foreach ($source as $key => $val) {
        if ($key != $i) {
            unset($source[$key]);
            $source[$i] = $val;
        }

        $i++;
    }

    foreach ($source as $key => $val) {
        foreach ($blacklist as $var) {
            if ($val === $var) {
                unset($source[$key]);
                $source = reindex($source, $blacklist);
            }
        }
    }

    return $source;
}

// Examples:

// Create a simple array
$input = array(1 => 'red', 3 => 'green', 5 => 'blue', 7 => TRUE, 9 => FALSE, 11 => NULL);

// NOTE: If you have an array (look above) and your blacklist will look like this: array(TRUE, FALSE, NULL)
//          Filter will delete array keys with value TRUE, FALSE or NULL
$blacklist = array(TRUE, FALSE, NULL);

// Output is: Array ( [0] => red [1] => green [2] => blue )
print_r( reindex($input, $blacklist) );

?>

If you don't want to filter array by keys in blacklist, just use this prototype: reindex( array $input ), it should be fine. :)

If you guys have question, feel free to contact me. Have a nice day.
breich at reich-consulting dot net 15-Dec-2010 11:19
I built the following array_remove_keys() function to
remove one or more keys from an array.

<?php

function array_remove_keys($array, $keys = array()) {

    // If array is empty or not an array at all, don't bother
    // doing anything else.
    if(empty($array) || (! is_array($array))) {
        return $array;
    }

    // If $keys is a comma-separated list, convert to an array.
    if(is_string($keys)) {
        $keys = explode(',', $keys);
    }

    // At this point if $keys is not an array, we can't do anything with it.
    if(! is_array($keys)) {
        return $array;
    }

    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }

    return array_diff_key($array, $assocKeys);
}

// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);

// Output before array_remove_keys()
var_dump($data);

// Remove address2 key.
$data = array_remove_keys($data, 'address2');

// Output after array_remove_keys()
var_dump($data);

/* Output:

array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/
?>
rolf at example dot com 08-Nov-2010 11:06
Here is how you could easily delete a specific value from an array with array_filter:

<?php
$array = array (1, 3, 3, 5, 6);
$my_value = 3;
$filtered_array = array_filter($array, function ($element) use ($my_value) { return ($element != $my_value); } );
print_r($filtered_array);
?>

output:

Array
(
    [0] => 1
    [3] => 5
    [4] => 6
)
Peter Robinett 12-Aug-2010 08:09
Because array_filter() preserves keys, you should consider the resulting array to be an associative array even if the original array had integer keys for there may be holes in your sequence of keys. This means that, for example, json_encode() will convert your result array into an object instead of an array. Call array_values() on the result array to guarantee json_encode() gives you an array.
acid24 at gmail dot com 26-Jul-2010 05:58
A function that allows filtering an array by keys:

<?php
function array_filter_key( $input, $callback ) {
    if ( !is_array( $input ) ) {
        trigger_error( 'array_filter_key() expects parameter 1 to be array, ' . gettype( $input ) . ' given', E_USER_WARNING );
        return null;
    }

    if ( empty( $input ) ) {
        return $input;
    }

    $filteredKeys = array_filter( array_keys( $input ), $callback );
    if ( empty( $filteredKeys ) ) {
        return array();
    }

    $input = array_intersect_key( array_flip( $filteredKeys ), $input );

    return $input;
}

?>

Example:

<?php
$input = array_flip( range( 'a', 'z' ) );

$consonants = array_filter_key( $arr, function( $elem ) {
    $vowels = "aeiou";
    return strpos( $vowels, strtolower( $elem ) ) === false;
} );
?>

Outputs:

array(21) {
  ["b"]=>
  int(1)
  ["c"]=>
  int(2)
  ["d"]=>
  int(3)
  ["f"]=>
  int(5)
  ["g"]=>
  int(6)
  ["h"]=>
  int(7)
  ["j"]=>
  int(9)
  ["k"]=>
  int(10)
  ["l"]=>
  int(11)
  ["m"]=>
  int(12)
  ["n"]=>
  int(13)
  ["p"]=>
  int(15)
  ["q"]=>
  int(16)
  ["r"]=>
  int(17)
  ["s"]=>
  int(18)
  ["t"]=>
  int(19)
  ["v"]=>
  int(21)
  ["w"]=>
  int(22)
  ["x"]=>
  int(23)
  ["y"]=>
  int(24)
  ["z"]=>
  int(25)
}
Ant P. 13-Mar-2010 08:58
If you're using filter_input_array, the values will be null on failure and anything else on success. Because array_filter by default removes false, 0 and "" you need to do extra work like this:
<?php
$input_array = filter_input_array(INPUT_GET, array(
  'var1' => FILTER_VALIDATE_BOOLEAN,
  'var2' => FILTER_VALIDATE_INT
));

array_filter($input_array, function($a) { return !is_null($a) });
?>
webdesign at blackbyrd dot biz 08-Oct-2009 01:00
Here's a function that will filter a multi-demensional array. This filter will return only those items that match the $value given

<?php
    /*
     * filtering an array
     */
    function filter_by_value ($array, $index, $value){
        if(is_array($array) && count($array)>0)
        {
            foreach(array_keys($array) as $key){
                $temp[$key] = $array[$key][$index];

                if ($temp[$key] == $value){
                    $newarray[$key] = $array[$key];
                }
            }
          }
      return $newarray;
    }
?>

Example:

<?php
$results = array(
   0 => array('key1' => '1', 'key2' => 2, 'key3' => 3),
   1 => array('key1' => '12', 'key2' => 22, 'key3' => 32)
);

$nResults = filter_by_value($results, 'key2', '2');
?>

Output :

array(
    0 => array('key1' => '1', 'key2' => 2, 'key3' => 3)
);
mewsterus at yahoo dot com 14-Sep-2009 10:13
Here's an easy way to get a combination of keys and values, such that if you don't specify a key you will get the value, and if you do specify a key you will get the key:

<?php
$array = array('One' => 'First', 'Second', 'Third', 'Four' => 'Fourth', 'Fifth');

var_dump(array_keys($array));

$names = array_filter(array_keys($array), 'is_string') + array_values($array);
ksort($array);

var_dump($names);
?>

Outputs:

array(5) {
  [0]=>string(3) "One"
  [1]=>int(0)
  [2]=>int(1)
  [3]=>string(4) "Four"
  [4]=>int(2)
}
array(5) {
  [0]=>string(3) "One"
  [1]=>string(6) "Second"
  [2]=>string(5) "Third"
  [3]=>string(4) "Four"
  [4]=>string(5) "Fifth"
}

Without using ksort, the keys appear before the fallback values, instead of inline and appearing like they replace them, however the keys are intact (which is why ksort works) so it's only execution order.
mchargue at usc dot edu 07-Aug-2009 02:34
Wanting to pass an additional to parameter to the callback function?  This worked for me, there's probably another way to accomplish this task but just so you see how it can be done.  (I actually used this technique to strip old dates out of an array) :

<?php
//define in global scope so functions can access
$var_to_pass = null;

function myfilter($input_var_outer,$param) {

    global $var_to_pass;
    $var_to_pass = $param;

    function mycallback($input_var_inner) {
      global $var_to_pass;
      return ($input_var_inner>$var_to_pass) ? true : false;
    }

    $return_arr = array_filter($input_var_outer,'mycallback');
    //re-key if you want
    $return_arr = array_merge(array(),$return_arr);
    return $return_arr;

}

$min = 5;
$a = array(1,3,5,7,9);

//remove elements from array that are not greater than $min
$a = myfilter($a,$min);

echo "<pre>";
print_r($a);
echo "</pre>";
?>

--

Output:
Array
(
    [0] => 7
    [1] => 9
)
chrisstocktonaz at gmail dot com 30-Apr-2009 09:34
I use the following to see if a array consist of scalar values or null, but of course you could mix it up using any of the is_ functions.

<?php
if(count($data) !== count(array_filter($data, 'is_scalar') + array_filter($data, 'is_null'))) {
  throw new Exception('Array did not consist of scalar and null values');
}
?>
nat at fishtrap dot co dot uk 18-Mar-2009 09:28
One of the nice things about this function is that you can a standard php function such as is_string

e.g.
<?php

$input =array(1 , '2', 'three', array('sausages'));

$result = array_filter($input ,'is_string');

print_r($result);

?>

Result will be

Array
(
    [1] => 2
    [2] => three
)
Craig 07-Mar-2009 10:34
I wanted a function to keep the values that were filtered out and return them separately. Basically, split the array by some callback. I wrote this for the job:

<?php
function array_split($input, &$trues, &$falses, $compare)
{
    while (($item = array_pop($input)) != NULL)
    {
        if ($compare($item)) $trues[] = $item;
        else $falses[] = $item;
    }
}
?>

very simple, something I would think would be standard, and array_filter would amount to discarding the falses.
marijnk at NOSPAM dot gwobbel dot com 05-Mar-2009 02:16
I was looking for a function that could filter values from an array using a regular expression pattern supplied, based on leon at darkk dot net dot ru I created the following:

Description:
Return array of matching values from array using regular expression.
<?php
class array_ereg {
    function array_ereg($pattern) { $this->pattern = $pattern; }
    function ereg($string) {
        return ereg($this->pattern, $string);
    }
}
?>
 Usage :
<?php
      $matches = array_filter($subject, array(new array_ereg($pattern), 'ereg'));
?>
 Example:
 <?php
     $subject = array ("Thumbs.db", "image001.png", "image001.jpg", "image002.png");
     print_r(array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg')));
?>
 Outputs:
     Array ( [1] => image001.png [3] => image002.png )
niehztog 30-Dec-2008 01:27
In case you are interested (like me) in filtering out elements with certain key-names, array_filter won't help you. Instead you can use the following:

<?php
$arr = array( 'element1' => 1, 'element2' => 2, 'element3' => 3, 'element4' => 4 );
$filterOutKeys = array( 'element1', 'element4' );

$filteredArr = array_diff_key( $arr, array_flip( $filterOutKeys ) )
?>

Result will be something like this:
['element2'] => 2
['element3'] => 3
romain dot lamarche at gmail dot com 11-Dec-2008 06:39
This function filters an array and remove all null values recursively.

<?php
  function array_filter_recursive($input)
  {
    foreach ($input as &$value)
    {
      if (is_array($value))
      {
        $value = array_filter_recursive($value);
      }
    }

    return array_filter($input);
  }
?>

Or with callback parameter (not tested) :

<?php
  function array_filter_recursive($input, $callback = null)
  {
    foreach ($input as &$value)
    {
      if (is_array($value))
      {
        $value = array_filter_recursive($value, $callback);
      }
    }

    return array_filter($input, $callback);
  }
?>
darren at dazwin dot com 08-Oct-2008 11:44
Regarding comment about trimming empty strings, the code posted will get into an infinite loop if the array is reduced to zero elements. The following might be better:

<?php
function array_trim($array) {
    while (!empty($array) and strlen(reset($array)) === 0) {
        array_shift($array);
    }
    while (!empty($array) and strlen(end($array)) === 0) {
        array_pop($array);
    }
    return $array;
}
?>
sami 03-Oct-2008 11:11
Yes, it may remove NULLS, but it also removes anything that factors to a FALSE as well; like FALSE and ZERO. :/
quecoder at gmail 27-Aug-2008 03:00
// my implementation for array_filter

function my_array_filter($array,$function,$preserve=true)
        {
            $return = array();
            foreach ($array as $k=>$v)
                {
                    if($function($v)==true) $return[$k]=$v;
                }
                if($preserve) return $return;
                else return array_values($return);
        }

function odd($value)
        {
            return ($value & 1);
        }

$oddonly = array (1,2,3,4,5,6,7,8,9);
print_r(my_array_filter($oddonly,'odd',1));

//output
//Array ( [0] => 1 [2] => 3 [4] => 5 [6] => 7 [8] => 9 )

//Khaled Mohammed
WASD 29-Jul-2008 04:53
You can easily delete all NULL elements from array with following statement:

<?php
$arr = array_filter($arr);
?>
Joan Garnet 04-Jan-2008 06:47
Be careful with this function as it preserves array indexes after applying the filter:

<?php
function f( $item ){
    return $item < 50;
}
print_r( array_filter(array( 10, 100, 20 ),"f") );
/* OUTPUT
Array
(
    [0] => 10
    [2] => 20
)*/
?>

You can easily reassign indexes like this:

<?php
function f( $item ){
    return $item < 50;
}
print_r( array_values(array_filter(array( 10, 100, 20 ),"f")) );
/* OUTPUT
Array
(
    [0] => 10
    [1] => 20
)*/
?>
nospam at jcornelius dot com 23-Oct-2007 11:51
Don't forget that using callbacks in a class requires that you reference the object name in the callback like so:

<?php

$newArray = array_filter($array, array($this,"callback_function"));

?>

Where "$this" is the reference to your object.
Martin 04-Sep-2007 10:56
This function trims empty strings from the beginning and end of an array.
It's useful when outputing plaintext files on a page and you want to skip empty lines at the beginning and end, but not within the text.

<?php
function array_trim($array) {
    while (strlen(reset($array)) === 0) {
        array_shift($array);
    }
    while (strlen(end($array)) === 0) {
        array_pop($array);
    }
    return $array;
}
?>

You might want to trim each element too.
Hayley Watson 29-Aug-2007 03:49
Just a simplification of my function from last month.

<?php
function partition($input, $callback=null)
{
    if(is_null($callback))
        $true = array_filter($input);
    else
        $true = array_filter($input, $callback);

    $false = array_diff_key($input, $true);
}
?>
Hayley Watson 26-Jul-2007 07:31
Here is my own version of Renee Sarsoo's array_split() function; given an array and a callback it returns two arrays, in which the first contains elements that passed the filter and the second contains elements that didn't. (If no callback is passed, the first array contains the nonempty elements, as you'd get from array_filter() if you don't give it a callback). Array keys are preserved.

<?php
function partition($input, $callback=null)
{
    static $not_empty=null;
    if(is_null($not_empty))
        $not_empty = create_function('$o', 'return !empty($o);');
    if(is_null($callback)) $callback = $not_empty;

    $true = array_filter($input, $callback);
    $false = array_diff_key($input, $true);

    return array($true, $false);
}
?>
Rene Saarsoo 09-Jul-2007 06:07
Sometimes you want to do something with elements you have filtered out and something else with other elements. So instead of filtering elements out to one array you would like to split array into two parts:
<?php
/**
 * Splits array into two arrays using a callback function
 *
 * It is like array_filter(), but instead of one array, two arrays are returned:
 * first one with elements for which the callback function evaluates to true,
 * and second one, for which it evaluates to false.
 *
 * If no callback is supplied, all entries of input equal to FALSE will be removed.
 *
 * Array keys are preserved.
 *
 * @param $callback the callback function to use
 * @return array(truth_array, false_array)
 */
function array_split($input, $callback=null) {
    $callback = isset($callback) ? $callback : create_function('$x', 'return $x == true;');

    $true = array();
    $false = array();
    foreach ($input as $key => $value) {
        if (call_user_func($callback, $value)) {
            $true[$key] = $value;
        }
        else {
            $false[$key] = $value;
        }
    }

    return array($true, $false);
}
?>
leon at darkk dot net dot ru 22-May-2007 12:15
Here is a way to get customizable filter

<?php
function blablabla() {
    ....
    $new = getNewUidls();
    class UidlFilter {
        function UidlFilter($uidls) { $this->uidls = $uidls; }
        function filter($metamsg) { return in_array($metamsg['uidl'], $this->uidls); }
    }
    $msglist = array_filter($msglist, array(new UidlFilter($new), 'filter');
    ....
}
?>
klaproth at creative-mindworks dot de 23-Oct-2006 07:13
As long as the array's keys are irrelevant, there is a simple way to remove blank values from the array, after filtering has been applied. The following example is used to remove all strings from an array that have a length of less than 4 characters.

<?php
function validElement($element) {
    return strlen($element) > 3;
}

$filtered_array = array_values(array_filter($input_array, "validElement"));
?>
Fladnag - bahatest at ifrance dot com 22-Oct-2006 09:19
If you have a form with multiple checkbox having ID element as value for selection in a list, you probably have a SQL request like :
$req="SELECT ... WHERE ID IN (".implode(',', array_keys($choices)).")";
without quote before and after choices keys because they are numeric values... but in fact, they can be string values, and a SQL injection problem.

with array_filter, you can easily filter bad values :
<?php
    $choices=array('A'=>'on', -1=>'on', 0=>'on', 1=>'on', 12=>'on', "1)or 1=1--"=>'on');
    print_r($choices);
    $choices=array_filter(array_keys($choices), 'is_numeric');
    print_r($choices);
?>
will print :
<?php
Array
(
    [A] => on
    [-1] => on
    [0] => on
    [1] => on
    [12] => on
    [1)or 1=1--] => on
)
Array
(
    [1] => -1
    [2] => 0
    [3] => 1
    [4] => 12
)
?>
ydotzhangatwriwindberdotorg 17-Jan-2006 01:57
I have written a function that will filter an array by the frequency of
element value in the array.  This may be useful to some people.

<?php
/////////////////////////////////////////////////////////////////
//    Filter an array by value freguebcy
//    Input: $array
//    cut-off: $frequency (>=1)
//    result option option: 1=$frequency and higher
//          0=$frequency only
//          -1=$frequency and lower
/////////////////////////////////////////////////////////////////
function filter_array($array, $frequency = 2, $include = 1){
    $freg = array_count_values($array);
    if($frequency<1){
       print "** frequency cut-off should be >= 1! **\n";
       return false;
    }
    foreach($freg as $k => $v){
        if($include == 0){
            if($frequency != $v){
                $freg[$k] = 0;
            }
        }elseif($include > 0){
            if($frequency > $v){
                $freg[$k] = 0;
            }
        }else{
            if($frequency < $v){
                $freg[$k] = 0;
            }
        }
    }
    $filtered = array_filter($freg);
    $values = array_keys($filtered);
    return array_intersect($array,$values);
}
?>
xert 26-Apr-2005 05:14
According to a simple test with array_filter($array) and array_diff($array, array('')) is array_filter 2.5 times faster than array_diff when deleting empty entries.
marc dot vanwoerkom at fernuni-hagen dot de 05-Jul-2004 08:09
Some of PHP's array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:

<?php
  array_filter() -> filter(),
  array_map() -> map(),
  array_reduce() -> foldl() ("fold left")
?>

Functional programming is a paradigm which centers around the side-effect free evaluation of functions. A program execution is a call of a function, which in turn might be defined by many other functions. One idea is to use functions to create special purpose functions from other functions.

The array functions mentioned above allow you compose new functions on arrays.

E.g. array_sum = array_map("sum", $arr).

This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.

E.g. a mathematician might state

  map(f o g) = map(f) o map(g)

the so called "loop fusion" law.

Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).

I can't get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
Maxwel Leite 11-May-2004 08:17
For any type of array. Basead in redshift code.

<?php
function array_clean ($array, $todelete = false, $caseSensitive = false) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $array[$key] = array_clean($array[$key], $todelete, $caseSensitive);
        }
        else {
            if($todelete) {
                if($caseSensitive) {
                    if(strstr($value ,$todelete) !== false)
                        unset($array[$key]);
                }
                else {
                    if(stristr($value, $todelete) !== false)
                        unset($array[$key]);
                }
            }
            elseif (empty($value)) {
                unset($array[$key]);
            }
        }
    }
    return $array;
}
?>
steven at xinu dot org 23-Feb-2004 12:39
The anonymous fellow a few posts up was trying to illustrate how to use the array_filter() function with class methods but confused things a bit. Here's a cleaner example:

<?php
class testclass
{
    function testclass()
    {
        // define the numbers array
        $numbers = array(1, 2, 3, 4, 5, 6);

        // pull out the odd numbers
        $odd = array_filter($numbers, array($this, "odd"));

        // pull out the even numbers
        $even = array_filter($numbers, array($this, "even"));
    }

    function odd($var)
    {
        return($var % 2 == 1);
    }

    function even($var)
    {
        return($var % 2 == 0);
    }
}
?>
Jeremy 29-Dec-2003 01:31
Here is a nice little function which will apply a callback function recursively over a multidimensional array. If the callback function returns false, then it replaces the value of the array with $filtered_ouput. This function gracefully handles objects inside of arrays (and objects within objects within arrays, etc). It is specifically designed for your callback function to process on the array key's (unlike normal array_filter which filters on the values), but it could work on the array values depending on your test criteria (YMMV).

<?PHP

function array_key_filter_multi($array, $callback, $filtered_output = "")
{
   $ret = array();
   foreach($array as $key=>$value) {
       if($callback($key,$value)) {
           if(is_array($value)) {
               $ret[$key] = array_key_filter_multi($value, $callback, $filtered_output);
           }
           elseif(is_object($value)) {
               $ret[$key] = array_key_filter_multi(get_object_vars($value), $callback, $filtered_output);
           }
           else {
               $ret[$key]=$value;
           }
       }
       else {
           $ret[$key]=$filtered_output;
       }
   }
   return $ret;
}

?>

We use this to filter redundant data from debugging output. An example usage is:

<?

$callback_func = create_function('$key, $value', 'return ($key == "db" || $key == "smarty") ? false : true;');
echo "<PRE>" . print_r(array_key_filter_multi($_SESSION, $callback_func, "**filtered by function**"), true) . "</PRE>";

?>

Which filters all keys with "db" or "smarty" as their name (including objects which have a reference to those variables). The output of the above in a test case I did is the following:

Array
(
    [userdata] => Array
        (
            [sid] => a130e675d380e0e9fe47897922d719ac
            [not_in_db] =>
            [user_id] => 1
            [session_id] => 154
            [permissions] => 1
            [username] => tester
        )
    [systemobjects] => Array
        (
            [db] => **filtered by function**
            [smarty] => **filtered by function**
        )
)
redshift at pandora dot be 28-Jun-2003 12:01
Hi all,
Here's a function that will look trough an array, and removes the array member when the search string is found.

<?php
function array_clean ($input, $delete = false, $caseSensitive = false)
    {
    $i = 0;
    while($i < count($input))
        {
        if($delete)
            {
            if($caseSensitive)
                {
                if(!strstr($input[$i] ,$delete))
                    {
                    $return[] = $input[$i];
                    }
                }
                else
                {
                if(!stristr($input[$i], $delete))
                    {
                    $return[] = $input[$i];
                    }
                }
            }
            else
            {
            if(!empty($input[$i]))
                {
                $return[] = $input[$i];
                }
            }
        $i++;
        }
    return $return;
    }
?>

array array_clean(array input [, string needle [, boolean case sensitive]])

if needle is left empty, the function will delete the array members that have no value (this means if it's empty).
NOTE: It rebuilds the array from scratch, so keys begin with 0, like you would create a new array.

Example:
$array = array("John", "Doe", "Macy");
$array = array_clean($array, "doe", false);

print_r($array);
would return:
array
(
    [0] => John
    [1] => Macy
)

Hopes this helps someone :-)
skd2 at ece dot msstate dot edu 14-May-2003 03:24
The following function modifies the supplied array recursively so that filtering is performed on multidimentional arrays as well, while preserving keys.

<?php
function array_cleanse(&$arr){

$temp = array();
reset($arr);
if(count($arr) == 0) return "";

foreach($arr as $key=>$val):

 (is_array($val))? array_cleanse($val) : NULL;
 ($val)? $temp[$key] = $val : NULL;

endforeach;

$arr = $temp;
reset($arr);
}
?>

$arr1 = array('a'=>20,'b'=>array(''),'c'=>array(1,0,2),'d'=>0);
array_cleanse($arr1);
$arr1 will be array('a'=>20,'c'=>array(1,2))

array_filter may not be used as it does not modify the array within itself.
11-Feb-2003 02:47
You cannot do this:
$non_empty_array = array_filter($original_array, 'empty');
Since empty() is not a function but a language construct. (http://www.php.net/manual/en/function.empty.php)
ajohnson at speakeasy dot org 27-Sep-2002 12:42
be careful with the above function "array_delete"'s use of the stristr function, it could be slightly misleading. consider the following:

<?php
function array_delete($array, $filterforsubstring){
    $thisarray = array ();
    foreach($array as $value)
        if(stristr($value, $filterforsubstring)===false && strlen($value)>0)
            $thisarray[] = $value;
    return $thisarray;
}

function array_delete2($array, $filterforstring, $removeblanksflag=0){
    $thisarray = array ();
    foreach($array as $value)
        if(!(stristr($value, $filterforstring) && strlen($value)==strlen($filterforstring))
                && !(strlen($value)==0 && $removeblanksflag))
            $thisarray[] = $value;
    return $thisarray;
}

function array_delete3($array, $filterfor, $substringflag=0, $removeblanksflag=0){
    $thisarray = array ();
    foreach($array as $value)
        if(
            !(stristr($value, $filterfor)
                && ($substringflag || strlen($value)==strlen($filterfor))
            )
            && !(strlen($value)==0 && $removeblanksflag)
        )
            $thisarray[] = $value;
    return $thisarray;
}

$array1 = array ('the OtHeR thang','this', 'that', 'OtHer','', 9, 101, 'fifty', ' oTher', 'otHer ','','other','Other','','other blank things');

echo "<pre>array :\n";
print_r($array1);

$array2=array_delete($array1, "Other");

echo "array_delete(\$array1, \"Other\"):\n";
print_r($array2);

$array2=array_delete2($array1, "Other");

echo "array_delete2(\$array1, \"Other\"):\n";
print_r($array2);

$array2=array_delete2($array1, "Other",1);

echo "array_delete2(\$array1, \"Other\",1):\n";
print_r($array2);

$array2=array_delete3($array1, "Other",1);

echo "array_delete3(\$array1, \"Other\",1):\n";
print_r($array2);

$array2=array_delete3($array1, "Other",0,1);

echo "array_delete3(\$array1, \"Other\",0,1):\n";
print_r($array2);
 ?>
ajohnson at speakeasy dot org 17-Aug-2002 01:04
I was looking for a function to delete values from an array and thought I had found it in array_filter(), however, I *didn't* want the keys to be preserved *and* I needed blank values cleaned out of the array as well. I came up with the following (with help from many of the above examples):

<?php
function array_delete($array, $filterfor){
  $thisarray = array ();
  foreach($array as $value)
    if(stristr($value, $filterfor)===false && strlen($value)>0)
      $thisarray[] = $value;
  return $thisarray;
}

$array1 = array ('OtHeR','this', 'that', 'Other','', 9, 101, 'fifty', 'other','','');

echo "<pre>array :\n";
print_r($array1);

$array2=array_delete($array1, "Other");

echo "filtered:\n";
print_r($array2);
?>
13-Jun-2002 04:14
I was looking for a function able to take some values out of an array iteratively, and found array_filter very useful although i had some trouble figuring out the proper syntax...

<?php
class someclass {
    var $current;

    /** this is our iterative function */
    function main ($variable,$array){
        if (end test){
            return true;
        }
        $variable= some treatment...
        if (in_array($variable, $array)){
             $this->current=something...($variable);
            // this is the not-well-documented part
            $array=$array_filter($array, array($this, "array_reduce");
        }
        $this->main($variable, $array);
    }

    /** this is the function used to filter */
    function reduce_list($var){
        return ($var!=$this->current);
    }
}
?>
sam,pointsystems,com 20-Feb-2002 05:12
Here's a good function to filter multidimensional arrays:

<?php
function array_filter_multi($input, $filter="", $keepMatches=true) {
        if (!is_array($input))
                return ($input==$filter xor $keepMatches==false) ? $input : false;
        while (list ($key,$value) = @each($input)){
                $res = array_filter_multi($value, $filter,$keepMatches);
                if ($res !== false)
                        $out[$key] = $res;
        }
        return $out;
}
?>

Default behavior is to remove blanks from a multi-dimensional array, but you can filter out any string (arg #2) with a positive or negative filter (arg #3).
array_fill
array_flip
Функции для работы с массивами


Меняет местами ключи с их значениями в массиве

array_filter
array_intersect_assoc
Функции для работы с массивами
PHP Manual

array_flip

(PHP 4, PHP 5)

array_flip — Меняет местами ключи с их значениями в массиве

Описание

array array_flip ( array $trans )

Функция array_flip() возвращает array наоборот, то есть ключи массива trans становятся значениями, а значения массива trans становятся ключами.

Обратите внимание, что значения массива trans должны быть корректными ключами, то есть они должны иметь тип integer или string. Если значение имеет неверный тип, будет выдано предупреждение и данная пара ключ/значение не будет обработана.

Если значение встречается несколько раз, для обработки будет использоваться последний встреченный ключ, а все остальные будут потеряны.

Список параметров

trans

Массив переворачиваемых пар ключ/значение.

Возвращаемые значения

Возвращает перевернутый массив в случае успеха, или NULL в случае ошибки.

Примеры

Пример #1 Пример использования array_flip()

<?php
$trans = array_flip($trans);
$original = strtr($str, $trans);
?>

Пример #2 Пример использования array_flip() с коллизиями

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

теперь $trans содержит:

Array
(
    [1] => b
    [2] => c
)

Смотрите также

  • array_values() - Выбирает все значения массива
  • array_keys() - Возвращает все или некоторое подмножество ключей массива
  • array_reverse() - Возвращает массив с элементами в обратном порядке

User Contributed Notes

Anonymous 05-Apr-2012 10:17
Similarly, if you want the last value without affecting the pointer, you can do:

<?php

$array = array("one","two","three");

echo next($array); // "two"

$last = array_pop(array_keys(array_flip($array)));

echo $last;  // "three"

echo current($array); // "two"

?>
kjensen at iaff106 dot com 06-Jan-2012 10:23
I needed a way to flip a multidimensional array and came up with this function to accomplish the task.  I hope it helps someone else.

<?php
function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) {
$ArrayOut=array();
foreach ($arrayIn as $Key=>$Value)
    {
        // If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true)
        if ($OrigKeyName) $Value[$OrigKeyName]=$Key;
        // Require a string value in the data part of the array that is keyed to $DesiredKey
        if (!is_string($Value[$DesiredKey])) return false;

        // If $DesiredKey2 was specified then assume a multidimensional array is desired and build it
        if (is_string($DesiredKey2))
        {
            // Require a string value in the data part of the array that is keyed to $DesiredKey2
            if (!is_string($Value[$DesiredKey2])) return false;

            // Build NEW multidimensional array
            $ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value;
        }

            // Build NEW single dimention array
        else $ArrayOut[$Value[$DesiredKey]][]=$Value;
    }
return $ArrayOut;
}//end multi_array_flip
?>
Final 16-Dec-2011 04:16
I find this function vey useful when you have a big array and you want to know if a given value is in the array. in_array in fact becomes quite slow in such a case, but you can flip the big array and then use isset to obtain the same result in a much faster way.
h3x 12-Sep-2010 01:11
this function can be used to remove null elements form an array:

<?php
$ar = array(null,'1','2',null,'3',null);
print_r($ar);
/*
result:
Array
(
    [0] =>
    [1] => 1
    [2] => 2
    [3] =>
    [4] => 3
    [5] =>
)
*/

print_r(array_flip(array_flip($ar)));
/*
result:
Array
(
    [1] => 1
    [2] => 2
    [4] => 3
)
*/
?>
Hayley Watson 20-Mar-2009 02:22
Finding the longest string in an array?

<?php
function longest_string_in_array($array)
{
    $mapping = array_combine($array, array_map('strlen', $array));
    return array_keys($mapping, max($mapping));
}
?>

Differences are obvious: returns an array of [i]all[/i] of the longest strings, instead of just picking one arbitrarily. Doesn't do the stripslashing or magic stuff because that's another job for for another function.
dan at aoindustries dot com 07-Mar-2009 12:48
From an algorithmic efficiency standpoint, building an entire array of lengths to then sort to only retrieve the longest value is unnecessary work.  The following should be O(n) instead of O(n log n).  It could also be:

<?php
function get_longest_value($array) {
    // Some don't like to initialize, I do
    $longest = NULL;
    $longestLen = -1;
    foreach ($array $value) {
        $len = strlen($value);
        if($len>$longestLen) {
            $longest = $value;
            $longestLen = $len;
        }
    }
    $longest = str_replace("\r\n", "\n", $longest);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
corz at corz dot org 08-Dec-2008 01:36
<?php
/*
    Fun function to return the longest physical *value* from an array.

    Culled from a small script designed to capture the longest $_POST variable,
    usually the textarea, which would then be dumped to a "emergency post dump file".

    corz at corz dot org
*/

$array = array("input" => "submit", "textarea" => "Some long spiel of text\r\na textarea, probably",
                        "another-input" => "make me longer", "and" => "another", "etc" => "etc.");

echo '<!DOCTYPE HTML SYSTEM><html><head><title>long</title></head><body><pre>Longest value: ',
                                            get_longest_value($array),'</pre></body></html>';

function get_longest_value($array) {
    foreach ($array as $key => $value) {
        $lengths[$key] = strlen($value);
    }
    asort($lengths);
    $lengths = array_flip($lengths);
    $longest = str_replace("\r\n", "\n", $array[array_pop($lengths)]);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
pinkgothic at gmail dot com 26-Apr-2007 01:37
In case anyone is wondering how array_flip() treats empty arrays:

<?php
print_r(array_flip(array()));
?>

results in:

Array
(
)

I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head's up for the paranoid.
snaury at narod dot ru 23-Nov-2004 11:21
When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array:

    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 3
    [5] => 2
    [6] => 1
    [7] => 1
    [8] => 3
    [9] => 3

After flipping will become:
(first seen value -> first key)

    [1] => 7
    [2] => 5
    [3] => 9

And not anything like this:
(last seen value -> last key)

    [2] => 5
    [1] => 7
    [3] => 9

In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn't (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that):

First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with:

  $array = array_flip(array_unique($array));

Well, and to achieve that "last comments" effect, just do:

  $array = array_reverse($array, true);
  $array = array_flip(array_unique($array));
  $array = array_reverse($array, true);

In the example from the very beginning array will become:

    [2] => 5
    [1] => 7
    [3] => 9

Just what I (and maybe you?) need. =^_^=
znailz at yahoo dot com 05-Aug-2003 02:42
I know a lot of people want a function to remove a key by value from an array. I saw solutions that iterate(!) though the whole array comparing value by value and then unsetting that value's key. PHP has a built-in function for pretty much everything (heard it will even cook you breakfast), so if you think "wouldn't it be cool if PHP had a function to do that...", odds are it already has. Check out this example. It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array.

<?php
$arr = array(11,12,13,12);        // sample array
$arr = array_flip($arr);
unset($arr[12]);
$arr = array(array_keys($arr));
?>

$arr contains:

Array
(
    [0] => Array
        (
            [0] => 11
            [1] => 13
        )
?>

)
array_filter
array_intersect_assoc
Функции для работы с массивами


Вычисляет схождение массивов с дополнительной проверкой индекса

array_flip
array_intersect_key
Функции для работы с массивами
PHP Manual

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_intersect_assoc — Вычисляет схождение массивов с дополнительной проверкой индекса

Описание

array array_intersect_assoc ( array $array1 , array $array2 [, array $ ... ] )

Функция array_intersect_assoc() возвращает массив, содержащий все значения массива array1, которые содержатся во всех указанных аргументах. Обратите внимание, что при сравнении используются ключи, в отличии от функции array_intersect().

Список параметров

array1

Основной проверяемый массив.

array2

Массив, с которым идет сравнение

array

Переменный список сравниваемых массивов

Возвращаемые значения

Возвращает ассоциативный массив, содержащий все элементы массива array1, которые существуют во всех переданных аргументах.

Примеры

Пример #1 Пример использования array_intersect_assoc()

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "b" => "yellow", "blue", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>

Результат выполнения данного примера:

Array
(
    [a] => green
)

В нашем примере видно, что только пара "a" => "green", содержится в обоих массивах и таким образом возвращается. Значение "red" не возвращается, потому что в массиве $array1 его ключ - 0, в то время как ключ значения "red" в массиве $array2 - 1, а ключ "b" не возвращается потому, что его значения различны в каждом массиве.

Два значения пар key => value считаются равными только, если (string) $elem1 === (string) $elem2 . Другими словами, применяется строгая проверка, означающая что строковые представления должны быть одинаковыми.

Смотрите также

  • array_intersect() - Вычисляет схождение массивов
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_intersect_uassoc() - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию
  • array_diff() - Вычислить расхождение массивов
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса

User Contributed Notes

amoo_miki at yahoo dot com 17-Jul-2009 12:58
A method to find intersection of two or more arrays when comparison is based only on keys

array_uintersect_assoc($array1  , $array2  [, $ array...  ], create_function(null, "return 0;"));

This returns an associative array containing all the keys in array1 that are present in all of the arguments.
asharm4 at ilstu dot edu 20-Apr-2006 09:20
A function to find intersection of two arrays when comparison is based on only 1 key

function array_common($array1,$array2,$compareString) {
   if (!is_array($array1) || !is_array($array2)) {
       return false;
   }
   $arrResult = array();
   foreach ($array1 as $arrInsideArray1) {
       foreach ($array2 as $arrInsideArray2) {
           $found=false;
           if ($arrInsideArray1[$compareString]==$arrInsideArray2[$compareString]) {
               $found=true;
               break;
           }
       }
       if ($found) {
           array_push($arrResult,$arrInsideArray1);
       }

   }
   return $arrResult;
}
StR: str at strgt dot cjb dot net 13-Oct-2005 05:34
To find the keys that are in 2 arrays, without caring of the values:

This is a function i needed, and it also returns the values of the first array

<?php
function array_key_intersect(&$a, &$b) {
  $array = array();
  while (list($key,$value) = each($a)) {
    if (isset($b[$key]))
      $array[$key] = $value;
  }
  return $array;
}
?>
vandor at progressive dot hu 14-Dec-2004 11:26
# ket tomb kulcs alapu metszetet szamitja ki, az erteken is ellenorzest vegez
#
# calculating (key base) intersection of arrays (value are checked)
# use: $result_array = array_intersect_assoc($a1, $a2, $a3,..);
#
##
# original code by [jochem at iamjochem dawt com] : array_diff_keys()

<?php
function array_intersect_assoc() {

    $args = func_get_args();
    $res = $args[0];

    for ($i=1;$i<count($args);$i++) {
        if (!is_array($args[$i])) {continue;}

        foreach ($res as $key => $data) {
            if ( (!array_key_exists($key, $args[$i])) || ( (isset($args[$i][$key])) && ($args[$i][$key] !== $res[$key]) ) ) {
                unset($res[$key]);
            }
        }
    }

    return $res;
}

?>

<?php
$array1 = array("a"=>"green", "b"=>"brown", "c"=>"blue", "red");
$array2 = array("a"=>"green", "b"=>"yellow", "c"=>"yellow", "red");
$a = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow');
$b = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow', 'e'=>'yellow');

$result_array = array_intersect_assoc($a, $b, $array1, $array2);
?>

$args array will look like:

(
    0 =>
        (
            a => green
            b => brown
            c => yellow
        )

    1 =>
        (
            a => green
            b => brown
            c => yellow
            e => yellow
        )

    2 =>
        (
            a => green
            b => brown
            c => blue
            0 => red
        )

    3 =>
        (
            a => green
            b => yellow
            c => yellow
            0 => red
        )

)

$result_array will look like:

(
    a => green
)
nleippe at integr8ted dot com 11-Feb-2004 04:46
A combination of the two functions [array_intersect() and array_intersect_assoc()] in order to obtain the intersection of two multidimensional arrays.

<?php
function array_intersect_assoc_recursive(&$arr1, &$arr2) {
    if (!is_array($arr1) || !is_array($arr2)) {
        return $arr1 == $arr2; // or === for strict type
    }
    $commonkeys = array_intersect(array_keys($arr1), array_keys($arr2));
    $ret = array();
    foreach ($commonkeys as $key) {
        $ret[$key] =& array_intersect_assoc_recursive($arr1[$key], $arr2[$key]);
    }
    return $ret;
}
?>
array_flip
array_intersect_key
Функции для работы с массивами


Вычислить пересечение массивов, сравнивая ключи

array_intersect_assoc
array_intersect_uassoc
Функции для работы с массивами
PHP Manual

array_intersect_key

(PHP 5 >= 5.1.0)

array_intersect_key — Вычислить пересечение массивов, сравнивая ключи

Описание

array array_intersect_key ( array $array1 , array $array2 [, array $ ... ] )

array_intersect_key() возвращает массив, содержащий все элементы array1, имеющие ключи, содержащиеся во всех последующих параметрах..

Список параметров

array1

Основной проверяемый массив.

array2

Массив, с которым идет сравнение.

array

Переменный список сравниваемых массивов

Возвращаемые значения

Возвращает ассоциативный массив, содержащий все элементы array1, имеющие ключи, содержащиеся во всех остальных параметрах. arguments.

Примеры

Пример #1 Пример использования array_intersect_key()

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));
?>

Результат выполнения данного примера:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

В нашем примере только ключи 'blue' и 'green' содержатся в обоих массивах и поэтому возвращаются. Также обратите внимание, что значения, соответствующие ключам 'blue' и 'green' различны в исходных массивах. Совпадение все равно происходит, так как сравниваются только ключи. Возвращаемые значения берутся из array1.

Два ключа пар key => value считаются равными только, если (string) $key1 === (string) $key2 . Другими словами, применяется строгая проверка, означающая, что строковые представления должны быть одинаковыми.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_udiff() - Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_uassoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_udiff_assoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_diff_key() - Вычисляет расхождение массивов, сравнивая ключи
  • array_diff_ukey() - Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_intersect_uassoc() - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_intersect_ukey() - Вычисляет схождение массивов, используя callback-функцию для сравнения ключей

User Contributed Notes

pgl at yoyo dot org 18-Jul-2011 08:01
Note that the order of the keys in the returned array is the same as the order of the keys in the source array. eg:

<?php
$array = array(
    'two'   => 'a',
    'three' => 'b',
    'one'   => 'c',
    );

$keyswant = array(
    'one'       => '',
    'three'     => '',
    );

print_r(array_intersect_key($array, $keyswant));

?>

Shows:

Array
(
    [three] => b
    [one] => c
)
chrisbloom7 at gmail dot com 11-Nov-2009 10:23
Regarding php at keithtylerdotcom solution to emulate

<?php
$z = someFuncReturningAnArray()['some_key'];
?>

His recommended solution will still return an array. To get the value of a single key in an array returned by a function, simply add implode() to the recipe:

<?php
function someFuncReturningAnArray() {
  return array(
    'a' => 'b',
    'c' => 'd',
    'e' => 'f',
    'g' => 'h',
    'i' => 'j'
  );
}

//traditional way
$temp = someFuncReturningAnArray();
$b = $temp['a'];
echo print_r($b, 1) . "\n----------\n";

//keithtylerdotcom one-line method
$b = array_intersect_key(someFuncReturningAnArray(), array('a'=>''));
echo print_r($b, 1) . "\n----------\n";

//better one line method
$b = implode('', array_intersect_key(someFuncReturningAnArray(), array('a'=>'')));
echo print_r($b, 1) . "\n----------\n";
?>
markus dot kappe at dix dot at 24-Sep-2009 04:43
<?php
    /**
     * calculates intersection of two arrays like array_intersect_key but recursive
     *
     * @param  array/mixed  master array
     * @param  array        array that has the keys which should be kept in the master array
     * @return array/mixed  cleand master array
     */
    function myIntersect($master, $mask) {
        if (!is_array($master)) { return $master; }
        foreach ($master as $k=>$v) {
            if (!isset($mask[$k])) { unset ($master[$k]); continue; } // remove value from $master if the key is not present in $mask
            if (is_array($mask[$k])) { $master[$k] = $this->myIntersect($master[$k], $mask[$k]); } // recurse when mask is an array
            // else simply keep value
        }
        return $master;
    }
?>
pdemaziere at gmail dot com 23-Feb-2009 07:52
Just a simple script if you want to use one array, which contains only zeros and ones, as mask for another one (both arrays must have the same size of course). $outcome is an array that contains only those values from $source where $mask is equal to 1.

<?php
$outcome = array_values(array_intersect_key( array_values($source), array_filter(array_values($mask)) ));
?>

PS: the array_values() function is necessary to ensure that both arrays have the same numbering/keys, otherwise your masking does not behave as you expect.

Enjoy!
CBWhiz at gmail dot com 04-Jan-2008 02:04
I have found the following helpful:
<?PHP
function array_merge_default($default, $data) {
        $intersect = array_intersect_key($data, $default); //Get data for which a default exists
        $diff = array_diff_key($default, $data); //Get defaults which are not present in data
        return $diff + $intersect; //Arrays have different keys, return the union of the two
}
?>
It's use is like both of the functions it uses, but keeps defaults and _only_ defaults. It's designed for key arrays, and i'm not sure how it will work on numeric indexed arrays.

Example:
<?PHP
$default = array(
 "one" => 1,
 "two" => 2
);
$untrusted = array(
 "one" => 42,
 "three" => 3
);
var_dump(array_merge_default($default, $untrusted));

array(2) {
  ["two"]=>
  int(2)
  ["one"]=>
  int(42)
}

?>
Rod Byrnes 05-May-2007 09:10
Here is a faster version than those shown below, with optimisation for the case when only two arrays are passed. In my tests with a 10000 item first array and a 5000 item second array (run 20 times) this function ran in 1.89 seconds compared with 2.66 for the version posted by dak. For a three array case, same as above but with the third array containing 3333 values, the timing is 3.25 for this version compared with 3.7 for dak's version.

<?php
if (!function_exists('array_intersect_key'))
{
  function array_intersect_key($isec, $keys)
  {
    $argc = func_num_args();
    if ($argc > 2)
    {
      for ($i = 1; !empty($isec) && $i < $argc; $i++)
      {
        $arr = func_get_arg($i);
        foreach (array_keys($isec) as $key)
        {
          if (!isset($arr[$key]))
          {
            unset($isec[$key]);
          }
        }
      }
      return $isec;
    }
    else
    {
      $res = array();
      foreach (array_keys($isec) as $key)
      {
        if (isset($keys[$key]))
        {
          $res[$key] = $isec[$key];
        }
      }
      return $res;
    }
  }
}
?>
17-Jul-2006 05:31
Here it is a more obvious way to implement the function:

if (!function_exists('array_intersect_key')) {
    function array_intersect_key()
    {
        $arrs = func_get_args();
        $result = array_shift($arrs);
        foreach ($arrs as $array) {
            foreach ($result as $key => $v) {
                if (!array_key_exists($key, $array)) {
                    unset($result[$key]);
                }
            }
        }
        return $result;
   }
}
Anton Backer 30-Mar-2006 11:49
Jesse: no, array_intersect_key does not accomplish the same thing as what you posted:

array_flip (array_intersect (array_flip ($a), array_flip ($b)))

because when the array is flipped, values become keys. having duplicate values is not a problem, but having duplicate keys is. array_flip resolves it by keeping only one of the duplicates and discarding the rest. by the time you start intersecting, you've already lost information.
dak 23-Jan-2006 08:31
A more efficient (and, I think, simpler) compatibility implementation:

<?php
if (!function_exists('array_intersect_key'))
{
    function array_intersect_key ($isec, $arr2)
    {
        $argc = func_num_args();

        for ($i = 1; !empty($isec) && $i < $argc; $i++)
        {
             $arr = func_get_arg($i);

             foreach ($isec as $k =>& $v)
                 if (!isset($arr[$k]))
                     unset($isec[$k]);
        }

        return $isec;
    }
}
?>
Silvio Ginter 23-Sep-2005 05:17
Based on the code posted by gaylord dot aulke at 100days.de
i wrote this one. This should implement this function in all versions equal or greater than PHP 4.0

function array_intersect_key($arr1, $arr2) {
    $res = array();
    foreach($arr1 as $key=>$value) {
        $push = true;
        for ($i = 1; $i < func_num_args(); $i++) {
            $actArray = func_get_arg($i);
            if (gettype($actArray) != 'array') return false;
            if (!array_key_exists($key, $actArray)) $push = false;
        }
        if ($push) $res[$key] = $arr1[$key];
    }
    return $res;
}
gaylord dot aulke at 100days.de 04-Jul-2005 04:04
I tried to use this function with PHP 5.0.4 under windows but the function does not seem to be implemented.
(Fatal error: Call to undefined function array_intersect_key())

This works as a workaround for 2 arrays at least:

function array_intersect_key($arr1, $arr2) {
  $res = array();
  foreach($arr1 as $key=>$value) {
    if(array_key_exists($key, $arr2)) $res[$key] = $arr1[$key];
  }
  return $res;
}
aidan at php dot net 29-May-2005 08:51
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
array_intersect_assoc
array_intersect_uassoc
Функции для работы с массивами


Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции

array_intersect_key
array_intersect_ukey
Функции для работы с массивами
PHP Manual

array_intersect_uassoc

(PHP 5)

array_intersect_uassoc — Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции

Описание

array array_intersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callable $key_compare_func )

array_intersect_uassoc() возвращает массив, содержащий значения array1, содержащиеся во всех последующих параметрах. Обратите внимание, что в отличие от array_intersect(), для сравнения используются ключи.

Список параметров

array1

Исходный сравниваемый массив

array2

Первый массив, с которым сравниваются ключи.

array

Дополнительные массивы, с которыми осуществляется сравнение.

key_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает все элементы array1, чьи значения существуют во всех аргументах.

Примеры

Пример #1 Пример использования array_intersect_uassoc()

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

Результат выполнения данного примера:

Array
(
    [b] => brown
)

Смотрите также

  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию
  • array_intersect_key() - Вычислить пересечение массивов, сравнивая ключи
  • array_intersect_ukey() - Вычисляет схождение массивов, используя callback-функцию для сравнения ключей

User Contributed Notes

There are no user contributed notes for this page.
array_intersect_key
array_intersect_ukey
Функции для работы с массивами


Вычисляет схождение массивов, используя callback-функцию для сравнения ключей

array_intersect_uassoc
array_intersect
Функции для работы с массивами
PHP Manual

array_intersect_ukey

(PHP 5 >= 5.1.0)

array_intersect_ukey — Вычисляет схождение массивов, используя callback-функцию для сравнения ключей

Описание

array array_intersect_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func )

array_intersect_ukey() возвращает массив, содержащий значения array1, имеющие ключи, содержащиеся во всех последующих параметрах.

Список параметров

array1

Основной проверяемый массив.

array2

Первый массив, с которым сравниваются ключи.

array

Дополнительные массивы, с которыми осуществляется сравнение ключей.

key_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает все элементы array1, чьи ключи существуют во всех переданных аргументах.

Примеры

Пример #1 Пример использования array_intersect_ukey()

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>

Результат выполнения данного примера:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

В нашем примере только ключи 'blue' и 'green' содержатся в обоих массивах и поэтому возвращаются. Также обратите внимание, что значения, соответствующие ключам 'blue' и 'green' отличаются между массивами. Совпадение все равно происходит, так как сравниваются только ключи. Возвращаемые значения берутся из array1.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_udiff() - Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_uassoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_udiff_assoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_diff_key() - Вычисляет расхождение массивов, сравнивая ключи
  • array_diff_ukey() - Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_intersect_uassoc() - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_intersect_key() - Вычислить пересечение массивов, сравнивая ключи

User Contributed Notes

Fred 25-Aug-2010 02:08
Using PHP Version 5.2.9-2 on Win 32

For those wondering what happens with numeric keys, here's a short example that might save you time :

<?php
$a=array(1=>'a',2=>'b',3=>'c');
$b=array(2=>'z',3=>'c',4=>'d');
$c=array_intersect_key($a,$b);
print_r($c);
?>

Will output
Array
(
    [2] => b
    [3] => c
)

It works fine, if values are different, the first array's ones are retained.
array_intersect_uassoc
array_intersect
Функции для работы с массивами


Вычисляет схождение массивов

array_intersect_ukey
array_key_exists
Функции для работы с массивами
PHP Manual

array_intersect

(PHP 4 >= 4.0.1, PHP 5)

array_intersect — Вычисляет схождение массивов

Описание

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

Функция array_intersect() возвращает массив, содержащий все значения массива array1, которые содержатся во всех аргументах. Обратите внимание, что ключи сохраняются.

Список параметров

array1

Основной проверяемый массив

array2

Массив, с которым идет сравнение значений

array

Дополнительные массивы для сравнения

Возвращаемые значения

Возвращает массив, содержащий все значения array1, которые существуют во всех переданных аргументах.

Примеры

Пример #1 Пример использования array_intersect()

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [a] => green
    [0] => red
)

Примечания

Замечание: Два элемента считаются одинаковыми тогда и только тогда, когда (string) $elem1 === (string) $elem2. Другими словами, когда их строковые представления идентичны.

Смотрите также

  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_diff() - Вычислить расхождение массивов
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса

User Contributed Notes

dml at nm dot ru 20-May-2011 05:06
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:

<?php
function array_intersect_fixed($array1, $array2) {
    $result = array();
    foreach ($array1 as $val) {
      if (($key = array_search($val, $array2, TRUE))!==false) {
         $result[] = $val;
         unset($array2[$key]);
      }
    }
    return $result;
}
?>
faharanik 30-Jun-2010 07:30
Here's my approach to intersection returning only the values present in all the arrays.
Note that each array must not contain duplicate values.
I don't know how effective it actually is, but perhaps it could help.

<?php
// $arrays - Array of arrays to intersect.

function calculate_intersection($arrays)
    {
    $intersection = Array();

    for($checked_item = 0; $checked_item < count($arrays[0]); $checked_item++)
        {
        $occurrence = 1;

        for($compared_array = 1; $compared_array < count($arrays); $compared_array++)
            {
            for($compared_item = 0; $compared_item < count($arrays[$compared_array]); $compared_item++)
                {
                if($arrays[0][$checked_item] == $arrays[$compared_array][$compared_item])
                    {
                    $occurrence++;

                    if($occurrence == count($arrays))
                        {
                        $intersection[] = $arrays[0][$checked_item];
                        }
                    }
                }
            }
        }

    return $intersection;
    }
?>
Yohann 12-Apr-2010 04:36
I used array_intersect in order to sort an array arbitrarly:

<?php
$a = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'height', 'nine', 'ten');
$b = array('four', 'one', 'height', 'five')
var_dump(array_intersect($a, $b);
?>

will output:

0 => 'one'
1 => 'four'
2 => 'five'
3 => 'height'

i hope this can help...
james -at- bandit.co -dot- nz 08-Apr-2010 06:07
I needed an array_intersect that would delete the intersecting values from the original array. Voila:

<?php
// array_intersect that splits the needle array into two - one filled with "intersected" results, and one filled with the remainder
function array_intersect_split(&$needle, $haystack, $preserve_keys = false) {
    if(!is_array($needle) || !is_array($haystack)) return false;
    $new_arr = array();
    foreach($needle as $key => $value) {
        if(($loc = array_search($value, $haystack))!==false) {
            if(!$preserve_keys) $new_arr[] = $value;
            else $new_arr[$key] = $value;
            unset($needle[$key]);
        }
    }
    return $new_arr;
}
?>
189780 at gmail dot com 02-Jan-2010 07:26
Actually array_intersect finds the dublicate values, here is my approach which is 5 times faster than built-in function array_intersect().. Give a try..

<?php
function my_array_intersect($a,$b)
{
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$a[$i];
        }
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$b[$i];
        }
        sort($m);
        $get=array();
        for($i=0;$i<sizeof($m);$i++)
        {
                if($m[$i]==$m[$i+1])
                $get[]=$m[$i];
        }
        return $get;
}
?>

Barış ÇUHADAR
189780@gmail.com
Shawn Pyle 13-Aug-2009 09:29
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.

<?php
array_intersect(array(1,2,2),array(1,2,3)); //=> array(1,2,2)
array_intersect(array(1,2,3),array(1,2,2)); //=> array(1,2)
?>
gary 21-Jun-2009 12:57
i wrote this one to get over the problem i found in getting strings intersected instead of arrays as there is no function in php.

<?php
function matched_main_numbers($string, $string2)
{
$string = "04 16 17 20 29";
$arr1 = explode(" ", $string);

$string2 = "45 34 04 29 16";
$arr2 = explode(" ", $string2);

$array = array_intersect($arr1, $arr2);
$comma_separated = implode($array);

$str = $comma_separated;

$balls = "$comma_separated";
$matched_balls = chunk_split($balls,2," ");
$matched_balls =" $matched_balls";

$number_of_matched_main_balls = strlen($str);
$number_of_matched_main_balls = ($number_of_matched_main_balls/2);
$numbers = "You matched $number_of_matched_main_balls main balls";

return $numbers;

}
?>
Oto Brglez 10-Mar-2009 07:02
If you wish to create intersection with arrays that are empty. Than the result of intersection is empty array.

If you wish to change this. I sugest that you do this.
It simply "ignores" empty arrays. Before loop use 1st array.

<?php

$a = array();
$a[] = 1;
$a[] = 2;
$a[] = 3;

$b = array();
$b[] = 4;
$b[] = 5;
$b[] = 1;

$c = array();
$c[] = 1;
$c[] = 5;
$d = array();

$kb=array('a','b','c','d');

$out = $a;
foreach($kb as $k){
    if(!empty(${$k})) $out = array_intersect($out,${$k});
};
print_r($out);
// The result is array

// The result is empty array
print_r(array_intersect($a,$b,$c,$d));

?>
karl at libsyn dot com 30-Jan-2009 09:58
Given a multidimensional array that represents AND/OR relationships (example below), you can use a recursive function with array_intersect() to see if another array matches that set of relationships.

For example: array( array( 'red' ), array( 'white', 'blue' ) ) represents "red OR ( white AND blue )".  array( 'red', array( 'white', 'blue' ) ) would work, too, BTW.

If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the following function.  It returns the matched array,
but can just return a boolean if that's all you need:

<?php
$needle = array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );

function findMatchingArray( $needle, $haystack ) {
    foreach( $needle as $element ) {
        $test_element = (array) $element;
        if( count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
            return $element;
        }

    }
    return false;
}
?>

Pretty tough to describe what I needed it to do, but it worked.  I don't know if anyone else out there needs something like this, but hope this helps.
Esfandiar -- e.bandari at gmail dot com 10-Aug-2008 12:44
Regarding array union:  Here is a faster version array_union($a, $b)

But it is not needed!  See below.

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            $a,
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>

You get the same result with $a + $b.

N.B. for associative array the results of $a+$b and $b+$a are different, I think array_diff_key is used.

Cheers, E
stuart at horuskol dot co dot uk 07-Jul-2008 03:57
A clearer example of the key preservation of this function:

<?php

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

yields the following:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.
Malte 10-Feb-2008 10:34
Extending the posting by Terry from 07-Feb-2006 04:42:

If you want to use this function with arrays which have sometimes the same value several times, it won't be checked if they're existing in the second array as much as in the first.
So I delete the value in the second array, if it's found there:

<?php
$firstarray = array(1, 1, 2, 3, 4, 1);
$secondarray = array(4, 1, 6, 5, 4, 1);

//array_intersect($firstarray, $secondarray): 1, 1, 1, 4

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }else{
        unset($secondarray[array_search($value,$secondarray)]);
    }
}

//$firstarray: 1, 1, 4

?>
aaron 17-Dec-2006 09:36
this one will work with associative arrays.  also an overwrite function to only replace those elements in the first array.

<?php

function array_union()
{
    if (func_num_args() < 2) { return; }
    $arrays = func_get_args();
    $outputArray = array_shift($arrays);
    $remaining = count($arrays);
    for ($i=0; $i<$remaining; $i++)
    {
        $nextArray = $arrays[$i];
        foreach ($nextArray as $key=>$value)
        {
            $outputArray[$key] = $value;
        }
    }
    return $outputArray;
}

function array_overwrite()
{
    if (func_num_args() < 2) { return; }
    $arrays = func_get_args();
    $outputArray = array_shift($arrays);
    $remaining = count($arrays);
    for ($i=0; $i<$remaining; $i++)
    {
        $nextArray = $arrays[$i];
        foreach ($nextArray as $key=>$value)
        {
            if (array_key_exists($key, $outputArray)) {    $outputArray[$key] = $value; }
        }
    }
    return $outputArray;
}

?>
Niels 19-Sep-2006 04:53
Here is a array_union($a, $b):

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            array_intersect($a, $b),    //         2   4
            array_diff($a, $b),         //       1   3
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>
nthitz at gmail dot com 08-Jun-2006 09:09
I did some trials and if you know the approximate size of the arrays then it would seem to be a lot faster to do this <?php array_intersect($smallerArray, $largerArray); ?> Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
terry(-at-)shuttleworths(-dot-)net 07-Feb-2006 07:42
I couldn't get array_intersect to work with two arrays of identical objects, so I just did this:

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }
}

This leaves $firstarray as the intersection.

Seems to work fine & reasonably quickly.
tom p 04-Nov-2005 06:54
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:

<?

$vals = array("Blue","Green","Pink","Yellow");
$db_field = "0,2,3";

echo implode(", ", array_flip(array_intersect(array_flip($vals), explode(",", $db_field))));

// will output "Blue, Pink, Yellow"

?>
sapenov at gmail dot com 10-Jun-2005 01:11
If you need to supply arbitrary number of arguments
to array_intersect() or other array function,
use following function:

$full=call_user_func_array('array_intersect', $any_number_of_arrays_here);
SETS INTERSECTION 18-May-2005 11:19
$a = array(1,2,3,4,5,2,6,1);  /* repeated elements --> $a is not a set */
$b = array(0,2,4,6,8,5,7,9,2,1);  /* repeated elements --> $b is not a set */

$ua = array_merge(array_unique($a));  /* now, $a is a set */
$ub = array_merge(array_unique($b));  /* now, $b is a set */

$intersect = array_merge(array_intersect($ua,$ub));

Note: 'array_merge' removes blank spaces in the arrays.
Note: order doesn't matter.

In one line:

$intersect_a_b = array_merge(array_intersect(array_merge(array_unique($a)), array_merge(array_unique($b))));

Additions/corrections wellcome...

gRiNgO
drew at iws dot co dot nz 21-Apr-2005 08:04
Just a handy tip.

If you want to produce an array from two seperate arrays on their intersects, here you go:

<?

$a = array("branches","E_SHOP");
$b = array("E_SHOP","Webdirector_1_0");

print join("/",array_merge(array_diff($a, $b), array_intersect($a, $b), array_diff($b, $a)));

?>

Gives you:

/branches/E_SHOP/Webdirectory_1_0
blu at dotgeek dot org 14-Oct-2004 05:34
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,

<?php

$orders_today[0] = array('John Doe', 'PHP Book');
$orders_today[1] = array('Jack Smith', 'Coke');

$orders_yesterday[0] = array('Miranda Jones', 'Digital Watch');
$orders_yesterday[1] = array('John Doe', 'PHP Book');
$orders_yesterday[2] = array('Z� da Silva', 'BMW Car');

?>

and wants to know if the same person bought the same thing today and yesterday and use array_intersect($orders_today, $orders_yesterday) you'll get as result:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

    [1] => Array
        (
            [0] => Jack Smith
            [1] => Coke
        )

)

?>

but we can get around that by serializing the inner arrays:
<?php

$orders_today[0] = serialize(array('John Doe', 'PHP Book'));
$orders_today[1] = serialize(array('Jack Smith', 'Coke'));

$orders_yesterday[0] = serialize(array('Miranda Jones', 'Digital Watch'));
$orders_yesterday[1] = serialize(array('John Doe', 'PHP Book'));
$orders_yesterday[2] = serialize(array('Z� da Silva', 'Uncle Tungsten'));

?>

so that array_map("unserialize", array_intersect($orders_today, $orders_yesterday)) will return:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

)

?>

showing us who bought the same thing today and yesterday =)

[]s
tompittlik at disfinite dot net 24-Jun-2004 06:27
Just a small mod to ben's code to make it work properly:

<?php

if(sort(array_unique($b + $a)) === sort($b))
 // $a is legit
}

?>

This is useful for checking for illegal characters in a username.
t dot wiltzius at insightbb dot com 23-Jun-2004 09:33
I needed to compare an array with associative keys to an array that contained some of the keys to the associative array. Basically, I just wanted to return only a few of the entries in the original array, and the keys to the entries I wanted were stored in another array. This is pretty straightforward (although complicated to explain), but I couldn't find a good function for comparing values to keys. So I wrote this relatively straightforward one:

<?php

function key_values_intersect($values,$keys) {
   foreach($keys AS $key) {
      $key_val_int[$key] = $values[$key];
      }
   return $key_val_int;
   }

$big = array("first"=>2,"second"=>7,"third"=>3,"fourth"=>5);
$subset = array("first","third");

print_r(key_values_intersect($big,$subset));

?>

This will return:

Array ( [first] => 2 [third] => 3 )
anbolb at boltblue dot com 09-Jan-2004 01:11
This is also handy for testing an array for one of a series of acceptable elements. As a simple example, if you're expecting the query string to contain one of, say, user_id, order_id or item_id, to find out which one it is you could do this:

<?php
    $valid_ids = array ('user_id', 'item_id', 'order_id');
    if ($id = current (array_intersect ($valid_ids, array_keys ($_GET))))
    {
        // do some stuff with it
    }
    else
        // error - invalid id passed, or none at all
?>

...which could be useful for constructing an SQL query, or some other situation where testing for them one by one might be too clumsy.
ben at kazez dot com 09-Dec-2003 10:49
To check whether an array $a is a subset of array $b, do the following:

<?php
if(array_unique($b + $a) === $b)
//...
?>

Actually, PHP ought to have a function that does this for you. But the above example works.
Alessandro Ranellucci alex at primafila dot net 16-Jul-2003 06:35
array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));
inerte is my hotmail.com username 26-Jun-2003 03:50
If you have a slow database query that uses JOIN, try to array_intersect() the table records.

I hung up my server countless times before using this function. Simple select from one table and put the records in an array ($records_1), then select records from any other table and put them in another array($records_2).

array_intersect() will emulate a JOIN for you.

<?php
$emulated_join = array_intersect($records_1, $records_2);
?>

Remember to test if it really offers a speed improvement, your mileage may vary (database type, hardware, version, etc...)

You could also emulate a JOIN from two text files, reading each line with the file() function.
david at audiogalaxy dot com 09-Apr-2001 04:54
Note that array_intersect() considers the type of the array elements when it compares them.

If array_intersect() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to intersect an array of integers with an array of strings.
array_intersect_ukey
array_key_exists
Функции для работы с массивами


Проверяет, присутствует ли в массиве указанный ключ или индекс

array_intersect
array_keys
Функции для работы с массивами
PHP Manual

array_key_exists

(PHP 4 >= 4.0.7, PHP 5)

array_key_exists — Проверяет, присутствует ли в массиве указанный ключ или индекс

Описание

bool array_key_exists ( mixed $key , array $search )

Функция array_key_exists() возвращает TRUE, если в массиве присутствует указанный ключ key. Параметр key может быть любым значением, которое подходит для индекса массива.

Список параметров

key

Проверяемое значение

search

Массив с проверяемыми ключами

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
5.3.0 | Данная функция больше не работает с объектами, Используйте для этого property_exists().

Примеры

Пример #1 Пример использования array_key_exists()

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

Пример #2 array_key_exists() и isset()

isset() не возвращает TRUE для ключей массива, указывающих на NULL, а array_key_exists() возвращает.

<?php
$search_array = array('first' => null, 'second' => 4);

// возвращает false
isset($search_array['first']);

// возвращает true
array_key_exists('first', $search_array);
?>

Примечания

Замечание:

Для обратной совместимости может быть использован следующий устаревший псевдоним: key_exists()

Смотрите также

  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • array_keys() - Возвращает все или некоторое подмножество ключей массива
  • in_array() - Проверяет, присутствует ли в массиве значение
  • property_exists() - Проверяет, содержит ли объект или класс указанный атрибут

User Contributed Notes

imaginary at friend dot com 09-Apr-2012 04:37
An even simpler case-insensitive alternative to array_key_exists():

<?php

array_key_exists(strtolower($key), array_change_key_case($search));
Nik Tang 05-Mar-2012 01:22
If you want to take the performance advantage of isset() while keeping the NULL element correctly detected, use this:

if (isset(..) || array_key_exists(...))
{
...
}

Benchmark (100000 runs):
array_key_exists() : 205 ms
is_set() : 35ms
isset() || array_key_exists() : 48ms

Note:
The code for this check is very fast, so you shouldn't warp the code into a single function like below, because the overhead of calling a function dominates the overall performance.

function array_check(...)
{
    return (isset(..) || array_key_exists(...))
}
Rudi 10-Nov-2011 02:10
I've got a new take on the multi key function I would like to share.

<?php
function array_multi_key_exists(array $arrNeedles, array $arrHaystack, $blnMatchAll=true){
    $blnFound = array_key_exists(array_shift($arrNeedles), $arrHaystack);

    if($blnFound && (count($arrNeedles) == 0 || !$blnMatchAll))
        return true;

    if(!$blnFound && count($arrNeedles) == 0 || $blnMatchAll)
        return false;

    return array_multi_key_exists($arrNeedles, $arrHaystack, $blnMatchAll);
}
?>

Hope you'll find it usefull.
glitch dot mr at gmail dot com 01-Oct-2011 04:15
As you might know, isset() is actually working like @$variable===NULL. As the result, it doesn't actually catch variables set to NULL. If you want to check if variable is set (even to NULL), you can use array_key_exists on $GLOBALS, like there.

<?php
   $me = null;
   $se = 1;
   unset($se);
// $he is not set

if(array_key_exists('me', $GLOBALS)) echo "\$me exists\n";
if(array_key_exists('se', $GLOBALS)) echo "\$se exists\n";
if(array_key_exists('he', $GLOBALS)) echo "\$he exists\n";

?>

In this case, only $me will be detected as $se was removed when code was running and $he was never set.
Anonymous 16-Jun-2011 01:07
I just want to note that array_key_exists() can be extremely slow for large (>200 keys) arrays.  Use isset($array($key)) instead!  My program ran in 3 minutes instead of 2 hours after switching to isset()!
manhon824 at gmail dot com 18-May-2011 09:29
I took hours for me to debug, and I finally recognized that,

You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);

Or you will get no reply.
tech at signhere envy dot de 18-Jan-2011 02:23
Hey, this function is able to rename a key inside an array.

If the key to be replaced doesn't exist inside the array, or the new key already exists in the array, the function will return FALSE.
Otherwise, the array with the renamed key will be returned.

Hope this will be useful for someone.
<?php
function array_rename_key($array, $key, $newkey){
    if( ! array_key_exists($key, $array) || array_key_exists($newkey, $array)) return FALSE;
    $uid = uniqid(''); //To clearly identify the Element.
    $preserve_value = $array[$key]; //Keep the Value
    $array[$key] = $uid; //Overwrite Value with ID
    $array = array_flip($array); //Flip the Array keys and values
    $array[$uid] = $newkey; //Set Value of the ID with new Key.
    $array = array_flip($array); //Everything back in Place.
    $array[$newkey] = $preserve_value;
    return $array;
}
?>
jens dot hoevenaars at gmail dot com 06-Nov-2010 03:21
I created this function that uses array key exist to compare a form and a table to see if something has changed.

This can be very helpfull if you need to update a table record from a form but you do not want to display all table fields.

<?php
function($data_from_db, $form_data) {
 $data = $data_from_db;
 $keys = array_keys($data);

    for($i = 0; $i < count($data); $i++) {
        if(!array_key_exists($keys[$i], $form_data)) {
            $dbobject->$keys[$i] = $data[$keys[$i]];
        } else {
            $dbobject->$keys[$i] = $form_data[$keys[$i]];
        }
    }
    return $dbobject;
}
?>

you can then use the dbobject to update the table.
moandsimon at btinternet dot com 26-Apr-2010 01:56
This uses array_key_exists.

You have a multidimensional array of the form:

$rowsoriginal[] = array('field_wrkvolmin_value' => 216, 'field_wrkvolmax_value' => 1000);
$rowsoriginal[] = array('field_wrkvolmin_value' => 27, 'field_wrkvolmax_value' => 216);

Using print_r this will look like:

Array ( [0] => Array ( [field_wrkvolmin_value] => 216 [field_wrkvolmax_value] => 1000 ) [1] => Array ( [field_wrkvolmin_value] => 27 [field_wrkvolmax_value] => 216 ) )

This can be used to create a table by iterating over the rows that looks like this:

field_wrkvolmin_value          field_wrkvolmax_value
           216                                      1000
            27                                       216

when $rowsoriginal contain a fixed but unknown amount of values.

If you want to process this in an automatic way without knowing the keys etc, into a multidimensional array of the form:

$rowstemp = array('field_wrkvolmin_value' => array(216, 27), 'field_wrkvolmax_value' => array(1000, 216));

Using print_r this will look like:

Array ( [field_wrkvolmin_value] => Array ( [0] => 216 [1] => 27 ) [field_wrkvolmax_value] => Array ( [0] => 1000 [1] => 216 ) )

This can be used to iterate over the rows of a table to create a table in the form of:

field_wrkvolmin_value            216            27
field_wrkvolmax_value           1000           216

To do this you can use the following looping and conditional structure, using array_key_exists():

<?php
$rowstemp = array();
foreach ($rowsoriginal as $row) {
    foreach ($row as $key => $value) {
        if (array_key_exists($key, $rowstemp)) {
            $rowstemp[$key][] = $value;
        }
        else {
            $valuestemp = array($value);
            $rowstemp[$key] = $valuestemp;
        }
    }
}
?>
gmdebby at gmail dot com 14-Jan-2010 05:44
A little function which take an array as keys

<?php
//note the s in the function name (keys)
function array_keys_exists($array,$keys) {
    foreach($keys as $k) {
        if(!isset($array[$k])) {
        return false;
        }
    }
    return true;
}
?>
//useful to validate a form for example
<form>
    <input type="text" name="field1" /><br />
    <input type="text" name="field2" /><br />
    <input type="text" name="field3" /><br />
    <input type="text" name="field4" /><br />
    <input type="text" name="field5" /><br />
</form>
<?php
if(!array_keys_exists($_POST,
array("field1","field2","field3","field4","field5")
)) {
    //some fields are missing, dont do anything (maybe hacking)
} else {
    //code ...
}
?>
Darkless at seznam dot cz 13-Nov-2009 09:17
a bit upgraded multi_array_key_exists function

@param needle string to be searched in keys
@param haystack array to be searched in

@return false when it was not found or string structured by name of keys devided by ":"

eg $arrays = array ('first' => array ( 'one'=> 'anything'));

for multi_array_key_exists('one',$arrays) it returns:
"first:one" by explode you can then write sth like $array[$path[0]][$path[1]]...
<?php

function multi_array_key_exists($needle, $haystack) {
      foreach ($haystack as $key=>$value) {
        if ($needle===$key) {
          return $key;
        }
        if (is_array($value)) {
          if(multi_array_key_exists($needle, $value)) {
            return $key . ":" . multi_array_key_exists($needle, $value);
          }
        }
      }
  return false;
}
?>
PHPEric 05-Aug-2009 06:51
Very simple case-insensitive array_key_exists:

bool (in_array(strtolower($needle), array_map('strtolower', array_keys($haystack))))
tom at edgedesigns dot org 21-Jul-2009 05:10
The multi_array_key_exists() function posted by alishahnovin at hotmail dot com [which has since been removed] does not always return the expected result.

This modified version does.

<?php
/**
 * multi_array_key_exists function.
 *
 * @param mixed $needle The key you want to check for
 * @param mixed $haystack The array you want to search
 * @return bool
 */
function multi_array_key_exists( $needle, $haystack ) {

    foreach ( $haystack as $key => $value ) :

        if ( $needle == $key )
            return true;

        if ( is_array( $value ) ) :
             if ( multi_array_key_exists( $needle, $value ) == true )
                return true;
             else
                 continue;
        endif;

    endforeach;

    return false;
}

?>
webmaster at oehoeboeroe dot nl 04-May-2009 01:09
The way array_key_exists handles null, float, boolean, and 'integer-representing string' keys is inconsistent in itself and, in the case of bool and float, with the way these are converted when used as array offset.

<?php
$array = array(null => 1, false => 2, true => 3, 4.6 => 4, "08" => 5, "8" => 6);
var_export($array);

echo "\nnull is " . (array_key_exists(null, $array) ? '' : 'not ') . "a key.\n";
echo 'false is ' . (array_key_exists(false, $array) ? '' : 'not ') . "a key.\n";
echo 'true is ' . (array_key_exists(true, $array) ? '' : 'not ') . "a key.\n";
echo '4.6 is ' . (array_key_exists(4.6, $array) ? '' : 'not ') . "a key.\n";
echo '"08" is ' . (array_key_exists("08", $array) ? '' : 'not ') . "a key.\n";
echo '"8" is ' . (array_key_exists("8", $array) ? '' : 'not ') . "a key.\n";
?>

Output:

array (
  '' => 1,
  0 => 2,
  1 => 3,
  4 => 4,
  '08' => 5,
  8 => 6,
)
null is a key.
false is not a key.
true is not a key.
4.6 is not a key.
"08" is a key.
"8" is a key.

Well, and you get this warning three times (on the bools and the float, but not on the null):

Warning:  array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /var/www/php/test.php on line 6
Gibson SG 25-Feb-2009 03:55
Below is a more efficient and useful case-insensitive array_key_exists function. More useful in the sense that it returns the matching key.

<?php
/**
* Case insensitive version of array_key_exists.
* Returns the matching key on success, else false.
*
* @param string $key
* @param array $search
* @return string|false
*/
function array_key_exists_nc($key, $search) {
    if (array_key_exists($key, $search)) {
        return $key;
    }
    if (!(is_string($key) && is_array($search) && count($search))) {
        return false;
    }
    $key = strtolower($key);
    foreach ($search as $k => $v) {
        if (strtolower($k) == $key) {
            return $k;
        }
    }
    return false;
}

/* Test code: */
$array = array(
    'taste' => 'sweet',
    'cOlOr' => 'yellow',
    'foo',
    'bar',
);
$keys = array(
    'Color',
    'google',
    0,
);
foreach ($keys as $key) {
    print "\t$key: "; var_dump(array_key_exists_nc($key, $array));
}

/* Output:
        Color: string(5) "cOlOr"
        google: bool(false)
        0: int(0)
*/
?>
csaba at alum dot mit dot edu 20-Jan-2009 05:13
In some functions cacheing can be extremely useful, and this is especially true in recursive functions, and all the more so in doubly recursive functions.  One way to effect cacheing is to have a static array in the function as shown below.  This will typically be useful when a function has one or two arguments and is heavily called.  Example:

<?php
function nk($n, $k) {
  // n choose k, ensuring integer math
  if ($k > $n-$k) $k = $n - $k;         // (n,k) = (n,n-k)
  if ($k<=1) return ($k==1) ? $n : !$k; // (n,1) = n; (n,0)=1; (n,-#) = 0

  static $aNK = array();                // caching section
  if ($aNK[$n][$k]) return $aNK[$n][$k];// if answer already computed => done

  // else compute answer, cache it, and return
  return ($aNK[$n][$k] = nk($n-1, $k) + nk($n-1, $k-1)); }

$n = 20;
$k = 9;
$nk = nk($n,$k);
print "nk($n, $k) = $nk";
?>

For functions of two arguments, using a two dimensional array seems to be faster than combining arguments a la "$n $k", and the form of testing shown above is also faster than array_key_exists.  However, to avoid the use of array_key_exists, special consideration must be given to empty values (several prior notes cover this) - the example above works because no cached value can be 0.

Csaba Gabor from Vienna
John 18-Jan-2009 09:27
Here is a little function for case sensitivity to elaborate on what was said by MarkL from ##php (Freenode) and mmanning at mdanderson dot org from this page:

<?php
// Case sensitive version of array_key_exists() using preg_match()
function array_ikey_exists($key,$arr)
{
    if(preg_match("/".$key."/i", join(",", array_keys($arr))))
        return true;
    else
        return false;
}
?>

Not that anyone else couldn't have written this, but a concept like this strengthens reusability.  :)

Also, I've been running into issues with escaping for Regex, so I decided to give something like this a shot:

<?php
function array_ikey_exists($key,$arr)
{
    $e = 0; //$key = addslashes($key);
    if(is_array($arr) && $arr !==array())
    {
        foreach($arr as $k => $v)
        {
            if(strtolower($k) == strtolower($key))
                $e++;
        }
        if($e>0)
            return true;
        else
            return false;
    }
    else
        return false;
}
?>

You could addslashes() to escape; it's just another approach.
david at lostair dot com 07-Dec-2008 12:07
It is important to realise that:

  isset($array ['index'])

Does not act the same as:

  array_key_exists('index', $array)

This is because if an array value is set to NULL

$array['index'] = NULL;

Then isset will return FALSE and array_key_exists will return TRUE.

It is important to realise this!
mmanning at mdanderson dot org 21-Oct-2008 08:13
Something to keep in mind is that array_key_exists is case sensitive.  So two things I'd like to say:

1. Could there be an additional option added on to the array_key_exists command so you can specify the case to be insensitive?

2. Here is how you can do this test in one command:

   if( preg_match("/<key>/i", join(",", array_keys(<array>))) ){
      <Do something>
      }

But it would be a lot nicer to just have an additional option on the array_key_exists.  Like so:

   array_key_exists(<array>, ["i"] );

Ok - so why did this come up at all?  I wrote a routine to convert any whacky UppERcAsE kind of lettering to just be lowercase letters. (ex: FgColorS becomes fgcolors and so forth.)  So I never had to guess what the user was putting in to the program.  There were two particular items (fgColors and bgColors) which I wanted to test against.  If they were not supplied, my program would supply them.  The above was the easiest way I could come up with to do this.  :-)
Karim Ratib 19-Aug-2008 05:09
Here's a function to return a reference to the first array element that has a given key. The code works for multidimensional arrays:

<?php
function &array_find_element_by_key($key, &$form) {
  if (array_key_exists($key, $form)) {
    $ret =& $form[$key];
    return $ret;
  }
  foreach ($form as $k => $v) {
    if (is_array($v)) {
      $ret =& array_find_element_by_key($key, $form[$k]);
      if ($ret) {
        return $ret;
      }
    }
  }
  return FALSE;
}
?>
jacobsingh at gmail dot com 17-Jun-2008 03:54
I saw some examples above for array_keys_exist() or functions to see if multiple keys exist in a given array and return false if any of them don't.

Here is a simpler way to do this:

<?php

function array_keys_exist($keys,$array) {
    if (count (array_intersect($keys,array_keys($array))) == count($keys)) {
        return true;
    }
}

$array = array ('filename' => 'myfile', 'filesize' => 1234, 'filepath' => '/tmp/myfile');
$keys = array('filename','filesize','filepath');

echo array_keys_exist($keys,$array);
//returns true

$keys[] = "somethingelse";

echo array_keys_exist($keys,$array);
//Returns false

?>
mankyd at gmail dot com 28-May-2008 10:29
You'll notice several notes on this page stating that isset() is significantly faster than array_key_exists(). This may be true except for one small hitch. isset() will return false for arrays keys that have there value set to NULL, which is therefore not entirely accurate.

Example:

<?php
$foo = array();
$foo['bar'] = NULL;

var_dump(isset($foo['bar']));
var_dump(array_key_exists('bar', $foo));
?>

will output:
bool(false)
bool(true)

Be aware of this!
bplessingerMONKEYleapfroginteractive.com 30-Apr-2008 09:22
I noticed that the function for recursion broke the ability to use this on objects, so I added another check to also allow it to work for objects.

<?php

function array_key_exists_r($needle, $haystack)
{
    $result = array_key_exists($needle, $haystack);
    if ($result)
        return $result;
    foreach ($haystack as $v)
    {
        if (is_array($v) || is_object($v))
            $result = array_key_exists_r($needle, $v);
        if ($result)
        return $result;
    }
    return $result;
}
?>
tmont 29-Apr-2008 02:54
The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a little benchmark to see which is faster:

<?php
    // one-dimensional arrays
    $array = array_fill(0,50000,'tommy is the best!');
    $arraykeyexists_result = array();

    $start = microtime(true);
    for ($i = 0; $i < 100000; $i++) {
        if (array_key_exists($i,$array)) {
            $arraykeyexists_result[] = 1;
        }
        else {
            $arraykeyexists_result[] = 0;
        }
    }
    $arrtime = round(microtime(true)-$start,3);

    $start = microtime(true);
    for ($i = 0; $i < 100000; $i++) {
        if (isset($array[$i])) {
            $arraykeyexists_result[] = 1;
        }
        else {
            $arraykeyexists_result[] = 0;
        }
    }
    $istime = round(microtime(true)-$start,3);

    $totaltime = $arrtime+$istime;
    $arrpercentage = round(100*$arrtime/$totaltime,3);
    $ispercentage = round(100*$istime/$totaltime,3);

    echo "array_key_exists(): $arrtime [$arrpercentage%] seconds\n";
    echo "isset():            $istime [$ispercentage%] seconds\n";

?>

On Windows, the output is similar to

array_key_exists(): 0.504 [82.895%] seconds
isset():            0.104 [17.105%] seconds

On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.
Benjamin*removethis*BeckATgmx.de 08-Mar-2008 11:24
Hi, i needed a recursive check is a key exists .. so here it is. I Hope it saves you time (-:

<?php
function array_key_exists_r($needle, $haystack)
{
    $result = array_key_exists($needle, $haystack);
    if ($result) return $result;
    foreach ($haystack as $v) {
        if (is_array($v)) {
            $result = array_key_exists_r($needle, $v);
        }
        if ($result) return $result;
    }
    return $result;
}

$test = array(
    "L0"    =>    array(
        "Über uns"    => array(
            "name" => "Über uns",
            "MenuLast" => 0,
            "subMenu" => 8,
            "href" => "/admin/pages/admin_page_edit.php?nav_gid=1.1",
            "navid" => 1.1,
            "posid" => 1,
            "klickPath" => 0,
        ),
        "Was wir tun"    => array(
            "name" => "Über uns",
            "MenuLast" => 0,
            "subMenu" => 8,
            "href" => "/admin/pages/admin_page_edit.php?nav_gid=1.1",
            "navid" => 1.1,
            "posid" => 1,
            "klickPath" => 0,
        ),
    ),
);

dumpvar(array_key_exists_r('navid', $test), 'array_key_exists_r(\'navid\', $test)');
?>
Output:
var array_key_exists_r('navid', $test)(boolean): 'true'
packard_bell_nec at hotmail dot com 31-Jan-2008 09:46
You can check whether a variable is defined by using array_key_exists()!
First, you may ask that no reserved array (would be called $LOCALS) is predefined in function scope (contrast to reserved array $GLOBALS in global scope. To solve it, you can use compact().
Then, you may ask that why property_exists() cannot be used. This is because no reserved function is predefined to create OBJECT containing variables and their values, and no reserved function is predefined to import variables into the current symbol table from an OBJECT. In addition, property_exists() breaks the naming convention of reserved function.
Finally, I show how to check whether a variable is defined by using array_key_exists():
<?php
function too(){
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
$foo = null;
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
}
too();
?>
The output will be:
0<br/>
1<br/>
mudsrcool at yahoo dot com 29-Dec-2007 04:19
If you use func_get_args, you can make a slightly prettier implementation of diogoshaw's function:

<?php

function array_keys_exist() {
    $keys = func_get_args();
    $haystack = array_shift($keys);
    foreach ($keys as $key)
        if (!array_key_exists($key, $haystack)) return false;
    return true;
}

//Pans out as:
if (array_keys_exist($_GET, 'login', 'user', 'passwd') {
   //login;
} else {
   //don't login;
}

?>
Erel Segal 13-Nov-2007 12:18
array_diff can be very slow when the arrays are big. If all you need is to check which elements in array1 are not KEYS in array2, DON'T use:

<?php
  array_diff($array1,array_keys($array2))
?>

A much quicker option is:

<?php
    foreach ($array1 as $key=>$value) {
        if (isset($array2[$key]))
            unset($array1[$key]);
    }
?>

On my computer, when $array1 has a single element and $array2 has 2600 elements, option 1 takes 50 milli-seconds, and option 2 takes 50 micro-seconds (1000 times less!).
wolf550e at gmail dot com 27-Sep-2007 12:51
array_key_exists(), at least in 5.2.4, passes the array by value. I conclude this from seeing performance worsen as the array to search got bigger. isset() doesn't have this problem.
diogoshaw at gmail dot com 15-Sep-2007 11:58
this function very good to use if you need to verify many variables:

<?php
function array_key_exists_r($keys, $search_r) {
    $keys_r = split('\|',$keys);
    foreach($keys_r as $key)
    if(!array_key_exists($key,$search_r))
    return false;
    return true;
}
?>

e.g.

<?php
if(array_key_exists_r('login|user|passwd',$_GET)) {
// login
} else {
// other
}
?>

works for me, enjoy.
dg shaw.
j_hattersleydykes {at} yahoo uk 26-Aug-2007 05:39
hey - I thought this function maybe useful to someone somewhere..
It works on an array of the keys you want to check exist. you could pass in the names of form fields and the POST array - suppose it could be useful in aiding form validation.

function array_keys_exist(array $keys, array $toCheck, $whichKey = false)
{
    foreach ($keys as $array_key)
    {
        if (! array_key_exists($array_key, $toCheck))
        {
            // return first key thats not found.
            if ($whichKey)
            {
                return $array_key;
            }
            else
            {
                return false;
            }
        }
    }
    // all keys exist
    return true;
}

hope someone finds it useful :)
sj-b at hotmail dot de 31-Jul-2007 09:14
i dont like how empty() works.
an integer with value 0 or a boolean wth
value false (same like zero) counts as
empty too.

[code]function r_empty (&$check)
{
    if (!isset($check)) return true;
    if ($check == NULL) return true;
    return false;
}[/code]

that is a good replacement for
both functions for me.
Lucknut dot xbl at googlemail dot com 18-Jul-2007 10:44
I found this function very good to use if your want your urls like index.php?login or index.php?register
e.g.
<?php
if( array_key_exists( 'home',$_GET ) ) {
    echo "Home - its where the heart is.";
} else if( array_key_exists( 'login',$_GET ) ) {
    echo "Login code here!";
} else if( array_key_exists( 'register',$_GET ) ) {
    echo "Register code here!";
} else {
    echo "Home - its where the heart is.";
}
?>
david at madole dot net 05-Jul-2007 08:11
Regarding performance differences between isset() and array_key_exists(), the differences may be there, but the function are not always interchangable.

Note that when $a[1] = null then isset($a[1]) == false but array_key_exists(1, $a) == true
eidberger at jakota dot de 11-Jun-2007 01:14
Just wondered why array_key_exists() makes me a cpu-load of 85% while isset() only needs 35%.

Not a big thing for one time execution, but in my case it have to check 1-dimensional array with ~ 15.000 entries 100 times a second. My code checks a big array for existing entrys and updates them, if needed.

Hopes it helps somebody. Notice that on many other functions, which makes coding more comfortable at the cost of speed.
php at ianco dot co dot uk 09-Apr-2007 01:58
array_key_exists is case sensitive (at least in PHP 4.3.9). To make a case-insensitive comparison you could use strtolower on both sides.
inker2576 at yahoo dot com 06-Mar-2007 08:01
Further research on this has turned up that the performance problems are a known, confirmed bug in PHP 5.1.x, and have been fixed in PHP builds after September 2006.  You can find the bug report here:  http://bugs.php.net/bug.php?id=38812

However, just because it's a fixed bug doesn't really change the conclusion.  If you're writing a script and there's any chance it could be used on a PHP 5.1.x server, you should still avoid this function and use isset() or some other kind of test if you want it to run efficiently.
serkan yersen 07-Feb-2007 04:01
marzetti.marco,
I fixed your function it's is more optimized and working better now.

function regex_array_keys($arr, $pattern){
   $results[] = false;

   if(!is_array($arr))
       return false;

   foreach($arr as $key => $val){
         if(!is_array($key))
       if(preg_match($pattern,$key))
              array_push($results,$key);
   }

   return $results;
}
Matt 01-Dec-2006 01:50
mikael dot knutsson at gmail dot com:
I don't think it does, at least in PHP5?

For example, this outputs bool(false):

$ar = array ( 'outter' => array ( 'inner' => 1 ) );
var_dump(array_key_exists('inner', $ar));

So it doesn't actually check the inner array for the key 'inner'.
mikael dot knutsson at gmail dot com 24-Nov-2006 04:05
When dealing with multi-dimensional arrays, this function checks through all keys in the array, including the "child arrays" unlike the array_keys( array, $search ) function which would only check and return from the first level of keys.

Took me a couple of minutes to figure out what was wrong and I hope it helps some people when looking for the right function.
Mike Toppa 03-Aug-2006 10:43
At least in PHP 4.4.0, array_key_exists is inconsistently sensitive to different data types. For example, if your first argument is a double and the keys in your array are integers, array_key_exists will always return false. If you then cast the first argument to an integer, or even to a string, then you can successfully match. I haven't tested all the possibilities, to see when it'll tolerate different data types and when it won't, so the easiest and safest solution is to cast your first argument to match the data type of the keys.
array_intersect
array_keys
Функции для работы с массивами


Возвращает все или некоторое подмножество ключей массива

array_key_exists
array_map
Функции для работы с массивами
PHP Manual

array_keys

(PHP 4, PHP 5)

array_keys — Возвращает все или некоторое подмножество ключей массива

Описание

array array_keys ( array $input [, mixed $search_value = NULL [, bool $strict = false ]] )

Функция array_keys() возвращает числовые и строковые ключи, содержащиеся в массиве input.

Если указан необязательный параметр search_value, функция возвращает только ключи, совпадающие с этим параметром. В обратном случае, функция возвращает все ключи массива input.

Список параметров

input

Массив, содержащий возвращаемые ключи.

search_value

Если указано, будут возвращены только ключи, содержащие данное значение.

strict

Определяет использование строгой проверки на равенство (===) при поиске.

Возвращаемые значения

Возвращает массив со всеми ключами input.

Список изменений

Версия | Описание
5.0.0 | Добавлен параметр strict.

Примеры

Пример #1 Пример использования array_keys()

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>

Результат выполнения данного примера:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

Смотрите также

  • array_values() - Выбирает все значения массива
  • array_key_exists() - Проверяет, присутствует ли в массиве указанный ключ или индекс
  • array_search() - Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи

User Contributed Notes

anthony at berglas dot org 03-Apr-2012 05:32
It should be noted that the inverse function to keys (which converts keys to values) is array_count_values (which converts values to keys).  This is needed to use things like array_intersect_key.  Could go in several places.  Took me a while to figure it out.
Na&#39;ven Enigma 10-Mar-2012 07:41
I was trying to figure out how to normalize an array with numerical keys.  Since I was doing for() for a lot of things, but only replacing it if the conditions were right, I wound up with off ball arrays I couldn't access.  That being said, I looked for a method of normalizing the array and couldn't find one, so I built my own.  I'm not sure how to go about making it recursive, but I didn't need that feature for my own, so I just went without recursion.

//This will take array([5] => "test1", [4] => "test2", [9] => "test3") into array([0] => "test1", [1] => "test2", [2] => "test3") so you can access it easier.
        function normalize_array($array){
          $newarray = array();
          $array_keys = array_keys($array);
          $i=0;
          foreach($array_keys as $key){
           $newarray[$i] = $array[$key];

          $i++;
          }
          return $newarray;
        }
qeremy [atta] gmail [dotta] com 05-Mar-2012 05:50
Simple ways to prefixing arrays;

<?php
function array_keys_prefix($arr, $pref = "") {
    $rarr = array();
    foreach ($arr as $key => $val) {
        $rarr[$pref.$key] = $val;
    }
    return $rarr;
}

function array_keys_prefix_multi($arr, $pref = "") {
    $rarr = array();
    foreach ($arr as $key => $val) {
        $rarr[] = array_keys_prefix($val, $pref);
    }
    return $rarr;
}

// $a = array("foo" => "FOO", "bar" => "BAR", "baz" => "BAZ"); // or
$a = array("foo" => "FOO", "bar" => "BAR", "baz" => array(1,2,3));
print_r(array_keys_prefix($a, "my_"));

// db fetch...
$products = array(
    array("id" => 1, "name" => "Foo"),
    array("id" => 2, "name" => "Bar")
);
print_r(array_keys_prefix_multi($products, "product_"));
?>

Array
(
    [my_foo] => FOO
    [my_bar] => BAR
    [my_baz] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)
Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Foo
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Bar
        )

)
izzecold at live dot de 10-Jan-2012 09:21
<?php

/* A Function created by myself for checking multiple array keys
For Example u got an Array like $_SESSION and u wanna know if the keys 'user','pass','email' and 'type' exists.

*/

function mKeyChecker($arr,$keys=array()) {
    if(count($keys) > 1) {
        $valid_keys = 0;
        foreach($keys as $key) {
            if(array_key_exists($key,$arr)) $valid_keys++;
        }
        if($valid_keys == count($keys)) {
            return true;
        } else {
            return false;
        }
    } else if(count($keys) == 1) {
        if(array_key_exists($key[0],$arr)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// Execution Example

if(mKeyChecker($_SESSION,array('id','user','email','type'))) {
    echo "is!";
} else {
    echo "not!";
}

?>
craig1231 at hotmail dot com 22-Dec-2011 03:41
A needed a function to find the keys which contain part of a string, not equalling a string...

<?php
function array_keys_contain($input, $search_value, $strict = false)
    {
        $tmpkeys = array();

        $keys = array_keys($input);

        foreach ($keys as $k)
        {
            if ($strict && strpos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
            elseif (!$strict && stripos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
        }

        return $tmpkeys;
    }
?>
el dot quick at gmail dot com 23-Sep-2011 08:23
Sorry for my english...

I wrote a function to get keys of arrays recursivelly...

<?php
    function recursive_keys($input, $search_value = null){

        $output = ($search_value !== null ? array_keys($input, $search_value) : array_keys($input)) ;
        foreach($input as $sub){
            if(is_array($sub)){
                $output = ($search_value !== null ? array_merge($output, recursive_keys($sub, $search_value)) : array_merge($output, recursive_keys($sub))) ;
            }
        }
        return $output ;
    }
?>

I hope it will be usefull

Regards
pat dot leblanc at gmail dot com 29-Aug-2011 02:05
It's worth noting that if you have keys that are long integer, such as '329462291595', they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.

for example:
<?php

$importantKeys = array('329462291595' =>null, 'ZZ291595' => null);

foreach(array_keys($importantKeys) as $key){
    echo gettype($key)."\n";
}

?>

will return on a 64 bits system:
<?php
    integer
    string
?>

but on a 32 bits system:
<?php
    string
    string
?>

I hope it will save someone the huge headache I had :)
rarioj at gmail dot com 04-Oct-2009 06:38
Sometimes we want to find out the last added numerical key right after we use " array_push($array, $value) " or " $array[] = $value ". This can be achieved by calling:

<?php
return array_pop(array_keys($array));
?>
ferrerna at gmail dot com 23-Jan-2009 09:14
Here's a function I needed to collapse an array, in my case from a database query.  It takes an array that contains key-value pairs and returns an array where they are actually the key and value.

<?php

function array_collapse($arr, $x, $y) {
    $carr = array();
    while ($el = current($arr)) {
        $carr[ $el[$x] ] = $el[$y];
        next($arr);
    }
    return $carr;
}

?>

Example usage (pseudo-database code):

<?php

$query = db_query('SELECT name, value FROM properties');

$result = db_returnAll($query);

/* This will return an array like so:

[
   ['name' -> 'color', 'value' -> 'blue'],
   ['name' -> 'style', 'value' -> 'wide-format'],
   ['name' -> 'weight', 'value' -> 3.6],
   ['name' -> 'name', 'value' -> 'Waerdthing']
]

*/

$propArr = array_collapse($result, 'name', 'value');

/* Now this array looks like:

[
   ['color' -> 'blue'],
   ['style' -> 'wide-format'],
   ['weight' -> 3.6],
   ['name' -> 'Waerdthing'],

*/

?>

I found this handy for using with json_encode and am using it for my project http://squidby.com
nodarinodo at mail dot ru 03-Dec-2008 11:35
<?php
    //It's a way to get keys from values )
    $es = array("is My FullName"=>"nodar chkuaselidze (nodarinodo)", "You Are" => "I don't know", "Is My Friend" => "ruxadze");
    foreach(array_values($es) as $ess){
        echo $ess." =>";

    for($i =0; $i < count(array_keys($es, $ess)); $i++){
            echo reset(array_keys($es, $ess))."<BR>";
        } }
?>
neil at 11 out of 10 24-Jul-2008 12:10
<?php

/*
 * This function will return the keys of elements in the
 * haystack where the value is found in array needle
 */

function array_value_intersect_keys( $array_haystack, $array_needle ){
    $intersected = array_intersect( $array_haystack, $array_needle );
    return array_keys( $intersected );
}

// usage

$array_haystack = array( 1 => 2, 2 => 5, 'red' => 8, 9 => 14 );

$array_needle = array( 2, 8 );

$array_keys_of_intersecting_values = array_value_intersect_keys( $array_haystack, $array_needle );

print_r( $array_keys_of_intersecting_values );
?>

returns
Array
(
    [0] => 1
    [1] => red
)
edsongarrido at gmail dot com 12-Jun-2008 05:46
/*
*
*This function will return a .csv from a given array inside the $_SESSION['my_array']
*
*$csv_name -> the name we want the csv has to
*$download -> true or false to download the csv file after done
*
*/

<?php

function createCSV($csv_name, $download) {

        $i = 1;
        $csv = "";

        /* erase the old file, if it exists */
        @unlink("../../csv/" . $csv_name . ".csv");

        /* array is in a session variable
         * this may be useful to avoid many db queries if it is the case */
        $my_array = $_SESSION['my_array'];

        /* how many fields has the given array */
        $fields = count(array_keys($my_array[0]));

        /* extracting the titles from the array */
        foreach(array_keys($my_array[0]) as $title)
        {
            /* array_keys percurs the title of each vector */
            $csv .= $title;

            /* while it is not the last field put a semi-colon ; */
            if($i < $fields)
                $csv .= ";";

            $i++;
        }

        /* insert an empty line to better visualize the csv */
        $csv .= chr(10).chr(13);
                $csv .= chr(10).chr(13);

        /* get the values from the extracted keys */
        foreach (array_keys($my_array) as $tipo)
        {

            $i = 1;

            foreach(array_keys($my_array[$tipo]) as $sub)
            {

                $csv .= $my_array[$tipo][$sub];

                if ($i < $fields)
                    $csv .= ";";

                $i++;
            }

            $csv .= chr(10).chr(13);

        }

        /* export the csv */
        $export_csv=fopen("../../csv/". $csv_name .".csv", "w+");
        fwrite($export_csv, $csv);
        fclose($export_csv);

        /* download the csv */
        if ($download == true)
            header('Location:' . "../../csv/" . $csv_name . ".csv");

        exit();

    }

?>
Hayley Watson 04-Oct-2007 06:43
An alternative to RQuadling at GMail dot com's array_remove() function:

<?php
function array_remove(array $array, $value, $strict=false)
{
    return array_diff_key($array, array_flip(array_keys($array, $value, $strict)));
}
?>
RQuadling at GMail dot com 28-Mar-2007 05:31
If you want to remove a value from an array, then there is no direct mechanism.

The following function uses the array_keys() function to find the key(s) of the value that you want to remove and then removes the elements for that key.

I've also given some examples and the output.

<?php
/**
  * array array_remove ( array input, mixed search_value [, bool strict] )
  **/
function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False) {
    $a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
    foreach($a_Keys as $s_Key) {
        unset($a_Input[$s_Key]);
    }
    return $a_Input;
}
?>

Beside scalar variables (integers, floats, strings, boolean), you can also use arrays as the values you want to remove.

<?php
// Results in array(8, 8.0, '8', '8.0')
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8));

// Results in array(8, 8.0, '8', '8.0', array('8'))
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8), True);
?>
creator at mindcreations dot com 20-Mar-2007 02:12
This function will extract keys from a multidimensional array

<?php
function multiarray_keys($ar) {

    foreach($ar as $k => $v) {
        $keys[] = $k;
        if (is_array($ar[$k]))
            $keys = array_merge($keys, multiarray_keys($ar[$k]));
    }
    return $keys;
}
?>

Example code:

<?php
$array = array("color" => array("1stcolor" => "blue", "2ndcolor" => "red", "3rdcolor" => "green"),
               "size"  => array("small", "medium", "large"));

echo "<pre>";
print_r($array);
echo "</pre>";

echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
?>

Example output:

Array
(
    [color] => Array
        (
            [1stcolor] => blue
            [2ndcolor] => red
            [3rdcolor] => green
        )

    [size] => Array
        (
            [0] => small
            [1] => medium
            [2] => large
        )

)

Array
(
    [0] => color
    [1] => 1stcolor
    [2] => 2ndcolor
    [3] => 3rdcolor
    [4] => size
    [5] => 0
    [6] => 1
    [7] => 2
)
Ray.Paseur sometimes uses GMail 21-Dec-2006 04:38
Replace a key in an associative array, preserving the original order of keys and elements:

<?php
if (!function_exists('array_combine')) { // ONLY EXISTS IN PHP5
    function array_combine($keys, $values) {
        if (count($keys) != count($values)) {
    return false; }
        foreach($keys as $key) { $array[$key] = array_shift($values); }
    return $array; }
} // END IF FUNCTION EXISTS

$keys = array_keys($array);
$values = array_values($array);
foreach ($keys as $k => $v) {
    if ($v == "MANAGEMENT FEE CHARGE") { $keys[$k] = "MANAGEMENT FEES"; }
}
$array = array_combine($keys, $values);
?>
jochem 17-Feb-2006 04:13
might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates - might be a handy introduction to automatic typecasting in php for some people (and save a few headaches):

<?php
$r = array("0"=>"0","1"=>"1","" =>"2"," "=>"3");
echo 'how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")',"\n-----------\n";
var_dump($r); print_r($r); var_export($r);
echo "\n-----------\n",'var_dump("0","1",""," ") = ',"\n-----------\n";
var_dump("0","1",""," ");
?>

OUTPUTS:

how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")
-----------
array(4) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "1"
  [""]=>
  string(1) "2"
  [" "]=>
  string(1) "3"
}
Array
(
    [0] => 0
    [1] => 1
    [] => 2
    [ ] => 3
)
array (
  0 => '0',
  1 => '1',
  '' => '2',
  ' ' => '3',
)
-----------
var_dump("0","1",""," ") =
-----------
string(1) "0"
string(1) "1"
string(0) ""
string(1) " "
Sven (bitcetera.com) 19-Dec-2005 06:43
Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:

<?php
  $array = array('first'=>'111', 'second'=>'222', 'third'=>'333');

  // get the first key: returns 'first'
  print array_shift(array_keys($array));

  // get the last key: returns 'third'
  print array_pop(array_keys($array));

  // get the first value: returns '111'
  print array_shift(array_values($array));

  // get the last value: returns '333'
  print array_pop(array_values($array));
?>
vesely at tana dot it 09-Dec-2005 01:56
The position of an element.

One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output "yes, we have bananas at position 0".

<?php
$a = array("banana" => "yellow", "apple" = "red");
$k = get_some_fruit();
if (isset($a[$k]))
{
   list($pos) = array_keys(array_keys($a), $k);
   print "yes, we have {$k}s at position $pos\n";
}
?>

Not amazingly efficient, but I see no better alternative.
ru dot dy at gmx dot net 14-Aug-2005 09:20
I was looking for a function that simply unset a variable amout of values from a one-dimensional array by key. I ended up with this (returns the array itself if no further parameter than the array is given, false with no params - does not change the source array)

usage: array_remove(array $input [, mixed key ...])

<?php

  function array_remove() {
    if ($stack = func_get_args()) {
      $input = array_shift($stack);
      foreach ($stack as $key) {
        unset($input[$key]);
      }
      return $input;
    }
    return false;
  }

?>

Test:

<?php
  $a = array('a'=>'fun', 'b'=>3.14, 'sub'=> array('1', '2', '3'), 'd'=>'what', 'e' => 'xample', 5 => 'x');
  print_r($a);
  print_r(array_remove($a, 'd', 'b', 5, 'sub'));
?>

Output:

Array
(
    [a] => fun
    [b] => 3.14
    [sub] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [d] => what
    [e] => xample
    [5] => x
)
Array
(
    [a] => fun
    [e] => xample
)

Hope this helps someone.
alex [@T] d-sn [D@T] com / Alex Galisteo 07-Aug-2005 02:46
My version of PHP does not support the strict parameter. Moreover, I need a function that could make other comparsion different than equals and stricktly equals.

The funcition array_keys_advanced can make the following comparsions: equal, not equal, strictly greater than, equal or greater than, strictly less than, equal or less than.

<?php
if (!function_exists('array_keys_advanced')) {
    //{{{ array_keys_advanced
    /**
     * Returns an array with the matching keys as values. A comparsion type can
     * be spcified, even if it should be a strict comparsion or not.
     * Note: It is not recursive.
     *
     * @param    array    $input
     * @param    string   $search_value
     * @param    bool     $strict
     * @param    string   $comparison: {EQ | NEQ | GT | EGT | LT | ELT}
     * @return   Returns an array with the matching keys as values.
     * @author   alex [@T] d-sn [D@T] com // Alex Galisteo
     */
    function array_keys_advanced() {
        $nargs = func_num_args();
        $arr = array();
        $input = null;
        $search_value = null;
        $strict = (bool) false;
        $comparison  = "EQ";
        $comparsion_types = array("EQ", "NEQ", "GT", "EGT", "LT", "ELT");
        switch ($nargs) {
        case 1:
            $input = func_get_arg(0);
            return array_keys($input);
            break;
        case 2:
            $input = func_get_arg(0);
            $search_value = func_get_arg(1);
            return array_keys($input, $search_value);
            break;
        case 3:
            $input = func_get_arg(0);
            $search_value = func_get_arg(1);
            $strict = (bool) func_get_arg(2);
            $comparsion  = "EQ";
            break;
        case 4:
            $input = func_get_arg(0);
            $search_value = func_get_arg(1);
            $strict = (bool) func_get_arg(2);
            $comparsion = strtoupper((string) func_get_arg(3));
            $comparsion = (in_array($comparsion, $comparsion_types))?
                            $comparsion : "EQ";
            break;
        default:
            return $arr;
            break;
        }
        foreach ($input as $key => $val) {
            if ($strict) {
                if ($comparsion == "EQ" && $search_value === $val) {
                    $arr[] = $key;
                }
                elseif ($comparsion == "NEQ" && $search_value !== $val)
                    $arr[] = $key;
                elseif ($comparsion == "GT" && $search_value > $val)
                    $arr[] = $key;
                elseif ($comparsion == "EGT" && $search_value >= $val)
                    $arr[] = $key;
                elseif ($comparsion == "LT" && $search_value < $val)
                    $arr[] = $key;
                elseif ($comparsion == "ELT" && $search_value <= $val)
                    $arr[] = $key;
            } else {
                if ($comparsion == "EQ" && $search_value == $val)
                    $arr[] = $key;
                elseif ($comparsion == "NEQ" && $search_value != $val)
                    $arr[] = $key;
                elseif ($comparsion == "GT" && $search_value > $val)
                    $arr[] = $key;
                elseif ($comparsion == "EGT" && $search_value >= $val)
                    $arr[] = $key;
                elseif ($comparsion == "LT" && $search_value < $val)
                    $arr[] = $key;
                elseif ($comparsion == "ELT" && $search_value <= $val)
                    $arr[] = $key;
            }
        }
        return $arr;
    }
    //}}}
} //endif function_exists
?>
webmaster [at] baz-x [dot] at 29-Jul-2005 03:43
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn't find a function I came up with my own solution.
I didn't find the propiest function to post to so I will post it here, hope you find it useful.

<?php

function array_extract($array, $extract_type = 1)
{
    foreach ( $array as $key => $value )
    {
        if ( $extract_type == 1 && is_string($key) )
        {
            // delete string keys
            unset($array[$key]);
        }
        elseif ( $extract_type == 2 && is_int($key) )
        {
            // delete integer keys
            unset($array[$key]);
        }
    }

    return $array;
}

?>

You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string

Have fun with it.
sip at email dot ee 22-Aug-2003 05:33
Note, that using array_key_exists() is rather inefficient. The overhead associated with calling a function makes it slower, than using isset($array[$key]), instead of array_key_exists($key, $array)
using isset() is usually about 1.3 times faster, according to my tests.
rodrigo at NOSPAM dot dhweb dot com dot br 04-Feb-2003 04:39
[Editor's note: For a complete solution to the printing of complex structures or hashes, see the PEAR::Var_Dump package: http://pear.php.net/package-info.php?pacid=103 , use "pear install Var_Dump" to get it]

This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don�t have control of depths.

<?php
function show_keys($ar){

   echo "<table width='100%' border='1' bordercolor='#6699CC' cellspacing='0' cellpadding='5'><tr valign='top'>";

      foreach ($ar as $k => $v ) {

         echo "<td align='center' bgcolor='#EEEEEE'>
           <table border='2' cellpadding='3'><tr><td bgcolor='#FFFFFF'><font face='verdana' size='1'>
              " . $k . "
           </font></td></tr></table>";

           if (is_array($ar[$k])) {
              show_keys ($ar[$k]);
         }

         echo "</td>";

      }

   echo "</tr></table>";

}

// Multidimensional array ->
$arvore = array();
$arvore['1'] = array();
$arvore['1']['1.1'] = array('1.1.1', '1.1.2', '1.1.3');
$arvore['1']['1.2'] = array('1.2.1', '1.2.2', '1.2.3');
$arvore['1']['1.3'] = array('1.3.1', '1.3.2', '1.3.3');
$arvore['2'] = array();
$arvore['2']['2.1'] = array('2.1.1', '2.1.2', '2.1.3');
$arvore['2']['2.2'] = array('2.2.1', '2.2.2', '2.2.3');
$arvore['2']['2.3'] = array('2.3.1', '2.3.2', '2.3.3');
$arvore['3'] = array();
$arvore['3']['3.1'] = array('3.1.1', '3.1.2', '3.1.3');
$arvore['3']['3.2'] = array('3.2.1', '3.2.2', '3.2.3');
$arvore['3']['3.3'] = array('3.3.1', '3.3.2'=>array('3.3.2.1', '3.3.2.2'), '3.3.3');
// <-

show_keys($arvore);
?>
michielbakker at msn dot com 13-Nov-2002 09:45
If you receive a bunch of variables and like to change most of them (or all of them for that matter), you can do something like this: (data has been sent to a page with POST)

<?php
$allKeys = array_keys($HTTP_POST_VARS);

for ($i=0;$i<count($allKeys);$i++)
{
      $$allKeys[$i] = strtoupper($HTTP_POST_VARS[$allKeys[$i]]);
}
?>

This makes caracters (a-z) uppercase. This is just one way to use it, ofcourse.

Hope this helps someone understand the way to use array_keys() or give any ideas. :)
glennh at webadept dot net 13-Nov-2002 04:03
All the cool notes are gone from the site.

Here's an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.

<?php
while (list($key, $value) = each
(${"HTTP_".$REQUEST_METHOD."_VARS"}))
{
        echo $key." = ".$value." ";
}
?>
jacob at keystreams dot com 20-Aug-2002 11:05
Here is a way to use array_intersect on array keys rather than values:

<?php
$a = array("apple" => "red", "banana" => "yellow");
$z = array("apple" => "green", "peach" => "orange", "banana" => "rotten");

$intersected_keys = array_intersect(array_keys($a), array_keys($z));

print_r($intersected_keys);
?>

This will print:

Array ( [0] => apple [1] => banana )
array_key_exists
array_map
Функции для работы с массивами


Применяет callback-функцию ко всем элементам указанных массивов

array_keys
array_merge_recursive
Функции для работы с массивами
PHP Manual

array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map — Применяет callback-функцию ко всем элементам указанных массивов

Описание

array array_map ( callable $callback , array $arr1 [, array $... ] )

Функция array_map() возвращает массив, содержащий элементы arr1 после их обработки callback-функцией. Количество параметров, передаваемых callback-функции, должно совпадать с количеством массивов, переданным функции array_map().

Список параметров

callback

Callback-функция, применяемая к каждому элементу в каждом массиве.

arr1

Массив, к которому применяется callback-функция.

array

Дополнительные массивы для обработки callback-функцией.

Возвращаемые значения

Возвращает массив, содержащий все элементы arr1 после применения callback-функции к каждому из них.

Примеры

Пример #1 Пример использования array_map()

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

В результате переменная $b будет содержать:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Пример #2 Использование array_map() вместе с lambda-функцией (начиная с версии PHP 5.3.0)

<?php
$func = function($value) {
    return $value * 2;
};

print_r(array_map($func, range(1, 5)));
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Пример #3 Пример использования array_map(): обработка нескольких массивов

<?php
function show_Spanish($n, $m)
{
    return("Число $n по-испански - $m");
}

function map_Spanish($n, $m)
{
    return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>

Результат выполнения данного примера:

// вывод $c
Array
(
    [0] => Число 1 по-испански - uno
    [1] => Число 2 по-испански - dos
    [2] => Число 3 по-испански - tres
    [3] => Число 4 по-испански - cuatro
    [4] => Число 5 по-испански - cinco
)

// вывод $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Обычно при обработке двух или более массивов, они имеют одинаковую длину, так как callback-функция применяется параллельно к соответствующим элементам массивов. Если массивы имеют различную длину, самый маленький из них дополняется элементами с пустыми значениями.

Интересным эффектом при использовании этой функции является создание массива массивов, что может быть достигнуто путем использования значения NULL в качестве имени callback-функции.

Пример #4 Создание массива массивов

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

Результат выполнения данного примера:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

Если массив-аргумент содержит строковые ключи, то результирующий массив будет содержать строковые ключи тогда и только тогда, если передан ровно один массив. Если передано больше одного аргумента, то результирующий массив будет всегда содержать числовые ключи.

Пример #5 Использование array_map() со строковыми ключами

<?php
$arr = array("stringkey" => "value");
function cb1($a) {
    return array ($a);
}
function cb2($a, $b) {
    return array ($a, $b);
}
var_dump(array_map("cb1", $arr));
var_dump(array_map("cb2", $arr, $arr));
var_dump(array_map(null, $arr));
var_dump(array_map(null, $arr, $arr));
?>

Результат выполнения данного примера:

array(1) {
  ["stringkey"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}
array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

Смотрите также

  • array_filter() - Фильтрует элементы массива с помощью callback-функции
  • array_reduce() - Итеративно уменьшает массив к единственному значению, используя callback-функцию
  • array_walk() - Применяет пользовательскую функцию к каждому элементу массива
  • create_function() - Создаёт анонимную (лямбда) функцию
  • информация о типе callback

User Contributed Notes

godek dot maciek at gmail dot com 19-Apr-2012 07:01
I came up with a convenient syntax for method application, particularly useful inside the array_map.
For instance, if you want to
array_map(function($object, $arg1) { return $object->method($arg1, "arg2"); }, $objects, $args1);

it is possible to provide a shorthand:
global $_; // necessary inside a function, unfortunately

array_map($_->method($_, "arg2"), $objects, $args1);

Here's the implementation (works with 5.3)

function m_caller($method) {
  $args = func_get_args();
  array_shift($args);
  return function($object) use($method, $args) {
    global $_;
    $local_args = func_get_args();
    array_shift($args);
    if(!is_object($object)) {
      // error
    }
    $reflection = new ReflectionMethod(get_class($object), $method);
    foreach($args as $key => $arg) {
      if($arg === $_) {
        $args[$key] = array_shift($local_args);
      }
    }
    return $reflection->invokeArgs($object, array_merge($args, $local_args));
  };
}

class MethodCaller {
  public function __call($name, $arguments) { return call_user_func_array('m_caller', array_merge(array($name), $arguments)); }
  public function __get($name) { return m_caller($name); }
};

$_ = new MethodCaller();
qeremy 07-Mar-2012 10:35
An alternative for recursive mapping;

<?php
function array_map_recursive($fn, $arr) {
    $rarr = array();
    foreach ($arr as $k => $v) {
        $rarr[$k] = is_array($v)
            ? array_map_recursive($fn, $v)
            : $fn($v); // or call_user_func($fn, $v)
    }
    return $rarr;
}

function sqr($x) {
    return "$x ^ 2 = ". ($x * $x);
}

$a = array(1, 2, 3, array(4, array(5)));
$b = array_map_recursive("sqr", $a);
print_r($b);
?>

Array
(
    [0] => 1 ^ 2 = 1
    [1] => 2 ^ 2 = 4
    [2] => 3 ^ 2 = 9
    [3] => Array
        (
            [0] => 4 ^ 2 = 16
            [1] => Array
                (
                    [0] => 5 ^ 2 = 25
                )

        )

)
gmail.com@mspreij 26-Feb-2012 10:48
Hope I'm not late to the party, here's my function to apply array_map to the *keys* of an array.
Extra array arguments will be used for the callback function's parameters just like with array_map, with the difference that a string is also allowed: it will just be used to create an array of appropriate length with as each value that string. Arrays are left alone (and will be padded with nulls by array_map as needed).

<?php

//_________________________________________________
// array_map_keys($callback, $array, [$args, ..]) /
function array_map_keys($callback, $array /* [, $args ..] */) {
  $args = func_get_args();
  if (! is_callable($callback)) trigger_error("first argument (callback) is not a valid function", E_USER_ERROR);
  if (! is_array($array)) trigger_error("second argument must be an array", E_USER_ERROR);
  $args[1] = array_keys($array);
  // If any additional arguments are not arrays, assume that value is wanted for every $array item.
  // array_map() will pad shorter arrays with Null values
  for ($i=2; $i < count($args); $i++) {
    if (! is_array($args[$i])) {
      $args[$i] = array_fill(0, count($array), $args[$i]);
    }
  }
  return array_combine(call_user_func_array('array_map', $args), $array);
}

// Some examples:

$arr = array('foo'=>123, 'bar'=>456);

// simply uppercase keys:
var_dump(array_map_keys('strtoupper', $arr));
// or..
var_dump(array_map_keys(function($input) {return strtoupper($input);}, $arr));
// >> array(2) { ["FOO"]=>int(123) , ["BAR"]=> int(456) }

// Add a prefix 'myvar_':
var_dump(array_map_keys(function($input, $prefix) {return $prefix.$input;}, $arr, 'myvar_'));
// >> array(2) { ["myvar_foo"]=>int(123) , ["myvar_bar"]=>int(456) }

// Apart from the (static string) prefix, we also number them:
$arr = array('foo'=>123, 'bar'=>456, 'bazz'=>789, 'yadda'=>'0AB');
var_dump(array_map_keys(function($input, $middle, $number) {return $number.':'.$middle.$input;}, $arr, 'myvar_', range(1, count($arr))));
// >> array(4) { ["1:myvar_foo"]=>int(123) , ["2:myvar_bar"]=>int(456) , ["3:myvar_bazz"]=>int(789) , ["4:myvar_yadda"]=>string(3) "0AB" }

?>
php/hotblocks/nl 28-Nov-2011 05:00
Note that the $arr argument has to be an array, not just a Traversable/Iterator.

For instance this won't work:

<?php

$documents = $mongo->db->collection->find();
// $documents is Traversable by foreach

$ids = array_map(function($document) {
  return $document['_id'];
}, $objects);
// $ids will now be NULL, because $documents wasn't an Array

?>

A solution is to first use iterator_to_array():

<?php

$ids = array_map(function($document) {
  return $document['_id'];
}, iterator_to_array($objects));
// $ids will now be an array of ['_id']s

?>

But this is not very efficient: two cycles instead of one. Another solution is to use foreach: one cycle and a lot of freedom (and in the same scope).
erik dot stetina at gmail dot com 27-Sep-2011 03:05
function to prefix given string to each element of an array:

<?php
function array_prefix_values($prefix, $array)
{
  $callback = create_function('$str','return "'.$prefix.'".$str;');
  return array_map($callback,$array);
}
?>

usage:

<?php
$dir = "./css/";
$files = scandir($dir);
$files = array_prefix_values($dir,$files);
print_r($files);
?>

output:

(
    [0] => ./css/.
    [1] => ./css/..
    [2] => ./css/default.css
    [4] => ./css/helper.css
    [6] => ./css/page_layout.css
)
spark at limao dot com dot br 08-Sep-2011 07:48
it's a usefull way to filter user input through get and post request arrays:

<?php
    $get = array_map("addslashes",$_GET);
?>
gordon dot mcvey at ntlworld dot com 28-Jan-2011 05:11
You can use array_map with PHP native functions as well as user functions.  This is very handy if you need to sanitize arrays.

<?php

$integers = array_map ('intval', $integers);
$safeStrings = array_map ('mysql_real_escape_string', $unsafeStrings);

?>
pike-php at kw dot nl 11-Jan-2011 06:04
If you're looking for a way to flatten multimaps, look at this:
<?php

    $multimap = array(
        array("name"=>"value1"),
        array("name"=>"value2"),
        array("name"=>"value3")
    );
    $flatmap = array_map("array_pop",$multimap);
    print_r($flatmap);
?>

Output:
Array
(
    [0] => value1
    [1] => value2
    [2] => value3
)
brendan DOT caffrey AT me DOT com 10-Jul-2010 03:42
Something that had me confused:

<?php
namespace test;

class Callback
{
    static function add($a) { return $a + 1; }
}

$array = array(0, 1, 2);
array_map(array('Callback', 'add'), $array); // will not work, even though you're calling this in the test namespace
array_map(array('test\Callback', 'add'), $array); // will work
?>
virtual dot greg at gmail dot com 05-Mar-2010 03:07
PHP 5.3 enables us to use inline anonymous functions with array_map, cleaning up the syntax slightly.

<?php
$data = array(
        array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'),
        array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'),
        array('id' => 3, 'name' => 'James', 'position' => 'Director')
);

$names = array_map(
        function($person) { return $person['name']; },
        $data
);

print_r($names);
?>

This was possible (although not recommended) in prior versions of PHP 5, via create_function().

<?php
$names = array_map(
        create_function('$person', 'return $person["name"];'),
        $data
);
?>

You're less likely to catch errors in the latter version because the code is passed as string arguments.

These are alternatives to using a foreach:

<?php
$names = array();

foreach ($data as $row) {
        $names[] = $row['name'];
}
?>
kelly m 17-Feb-2010 02:28
I realize this function is easy enough to make, but this is a faster version (twice the speed) of [a function] which I find incredibly useful.

<?php
function array_pluck($key, $input) {
    if (is_array($key) || !is_array($input)) return array();
    $array = array();
    foreach($input as $v) {
        if(array_key_exists($key, $v)) $array[]=$v[$key];
    }
    return $array;
}
?>

Usage:

<?php $ids = array_pluck('id', $users); ?>
onassar at gmail dot com 13-Oct-2009 07:06
Fixed a bug with array recursion.

<?php
        /**
         * arrayMap function. Customized array_map function which preserves keys/associate array indexes. Note that this costs a descent amount more memory (eg. 1.5k per call)
         *
         * @access public
         * @param callback $callback Callback function to run for each element in each array.
         * @param mixed $arr1 An array to run through the callback function.
         * @param array $array Variable list of array arugments to run through the callback function.
         * @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.
         */
        function arrayMap($callback,$arr1) {
            $results       =    array();
            $args          =    array();
            if(func_num_args()>2)
                $args          =    (array) array_shift(array_slice(func_get_args(),2));
            foreach($arr1 as $key=>$value) {
                $temp    =    $args;
                array_unshift($temp,$value);
                if(is_array($value)) {
                    array_unshift($temp,$callback);
                    $results[$key]    =    call_user_func_array(array('self','arrayMap'),$temp);
                } else {
                    $results[$key]    =    call_user_func_array($callback,$temp);
                }
            }
            return $results;
        }
?>
onassar at gmail dot com 11-Oct-2009 03:33
Wrote up my own key preservation function for array mapping. It allows n arguments to be passed, and should be easy enough to follow if you need to make any mods. If you've got any thoughts let me know.

<?php
        /**
         * arrayMap function. Customized array_map function which preserves keys/associate array indexes.
         *
         * @access public
         * @param callback $callback Callback function to run for each element in each array.
         * @param mixed $arr1 An array to run through the callback function.
         * @param array $array Variable list of array arugments to run through the callback function.
         * @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.
         */
        function arrayMap($callback,$arr1) {
            $results       =    array();
            $args          =    array();
            if(func_num_args()>2)
                $args          =    (array) array_shift(array_slice(func_get_args(),2));
            foreach($arr1 as $key=>$value) {
                if(is_array($value)) {
                    array_unshift($args,$value);
                    array_unshift($args,$callback);
                    $results[$key]    =    call_user_func_array(array('self','arrayMap'),$args);
                }
                else {
                    array_unshift($args,$value);
                    $results[$key]    =    call_user_func_array($callback,$args);
                }
            }
            return $results;
        }
?>
macnimble at gmail dot com 10-Sep-2009 12:27
I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster:

<?php
function array_prefix_keys ()
{
  $args = func_get_args();
  $prefix = array_shift($args);
  $func = create_function('$p,$k','return "$p{$k}";');
  foreach ($args AS $key => $array):
    $args[$key] = array_combine( array_map( $func
                                          , array_fill(0,count($array),$prefix)
                                          , array_keys($array)
                                          )
                               , array_values($array)
                               );
  endforeach;
  return $args;
}
$array1 = array(
  'id'     => 1,
  'title'  => 'about-us',
  'author' => 'Bill Brown',
  'dated'  => '2009-SEP-15'
);
$array2 = array(
  'id'     => 2,
  'title'  => 'about-them',
  'author' => 'Bill Smith',
  'dated'  => '2010-SEP-15'
);
echo '<pre>',print_r($array1,1),print_r($array2,1),'</pre>';
$array = array_prefix_keys("content_",$array1,$array2);
$array1 = $array[0];
$array2 = $array[1];
echo '<pre>',print_r($array1,1),print_r($array2,1),'</pre>';
?>

This will produce the following output:

Array
(
    [id] => 1
    [title] => about-us
    [author] => Bill Brown
    [dated] => 2009-SEP-15
)
Array
(
    [id] => 2
    [title] => about-them
    [author] => Bill Smith
    [dated] => 2010-SEP-15
)

Array
(
    [content_id] => 1
    [content_title] => about-us
    [content_author] => Bill Brown
    [content_dated] => 2009-SEP-15
)
Array
(
    [content_id] => 2
    [content_title] => about-them
    [content_author] => Bill Smith
    [content_dated] => 2010-SEP-15
)

Hope it helps!
Bill

[EDIT BY danbrown AT php DOT net: The original function and note was removed in favor of this update by the original author.  The original note also contained the following descriptive text.]

I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster.
ethaizone at hotmail dot com 01-Sep-2009 07:34
My English is weak but I want to share my code.
I want to change formation of array but when I use null is callback function in array_map().
It has problem in result so I write new small function for it.

<?php
function array_change_formation($arr=array()) {
    $new_arr = array();
    foreach($arr as $k => $v)
        foreach($v as $k2 => $v2)
            $new_arr[$k2][$k] = $v[$k2];
    return $new_arr;
}
?>

Input:
Array
(
    [Human] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [Pet] => Array
        (
            [0] => Cat
            [1] => Dog
            [2] => Rabbit
            [3] => Rat
        )

)

OutPut:
Array
(
    [0] => Array
        (
            [Human] => 1
            [Pet] => Cat
        )

    [1] => Array
        (
            [Human] => 2
            [Pet] => Dog
        )

    [2] => Array
        (
            [Human] => 3
            [Pet] => Rabbit
        )

    [3] => Array
        (
            [Human] => 4
            [Pet] => Rat
        )

)

I hope it can useful.
galenjr at gmail dot com 14-Jun-2009 11:19
Another way to array_map htmlentities with a specific quote style is to create a function that does it and map that function

<?php

function map_entities( $str ) {
    return htmlentities( $str, ENT_QUOTES );
}
$good_array = array_map ( 'map_entities', $bad_array );

?>
radist-hack at yandex dot ru 01-Nov-2008 01:37
To transpose rectangular two-dimension array, use the following code:

array_unshift($array, null);
$array = call_user_func_array("array_map", $array);

If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:
$array = array_reverse($array);

Here is example:

<?php
$a = array(
  array(1, 2, 3),
  array(4, 5, 6));
array_unshift($a, null);
$a = call_user_func_array("array_map", $a);
print_r($a);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 4
        )

    [1] => Array
        (
            [0] => 2
            [1] => 5
        )

    [2] => Array
        (
            [0] => 3
            [1] => 6
        )

)
Heero 16-Oct-2008 10:02
You can easily remove all HTML tags from $_GET or $_POST variables using something like this:

<?php

$_POST = array_map('strip_tags', $_POST);
$_GET = array_map('strip_tags', $_GET);

?>

This is useful when you don't want to parse HTML.
stijnleenknegt at gmail dot com 22-Jul-2008 04:17
If you want to pass an argument like ENT_QUOTES to htmlentities, you can do the follow.

<?php
$array = array_map( 'htmlentities' , $array, array_fill(0 , count($array) , ENT_QUOTES) );
?>

The third argument creates an equal sized array of $array filled with the parameter you want to give with your callback function.
GUI 26-Jun-2008 07:48
The following takes an array of objects, and returns the result of calling a member function on each object. So if I have an array of objects that all have a getName() method, calling array_map_objects("getName", $thingies) will return the array filled with the getName() value for each object.

<?php
function array_map_objects($member_function, $array) {
    $values = array();

    if(is_string($member_function) && is_array($array)) {
        $callback = create_function('$e', 'return call_user_func(array($e, "' . $member_function .'"));');
        $values = array_map($callback, $array);
    }

    return $values;
}
?>
BloodElf 27-Apr-2008 06:32
Here is a simple way to highlight the matched words in the search results:

<?php

function highlight($word) {
        static $num = 1;
        return '<span class="word' . $num++ . '">' . $word . '</span>';
}

$text = "ala bala nica turska panica";
$search = "bala turska";
$words = explode(' ', $search);

echo str_replace($words, array_map("highlight", $words), $text);
moester at gmail dot com 02-Apr-2008 01:21
Wish this was built in.  Mimics Ruby and Prototype's array pluck function.  Returns specific key/column from an array of objects.

<?php
function array_pluck($key, $array)
{
    if (is_array($key) || !is_array($array)) return array();
    $funct = create_function('$e', 'return is_array($e) && array_key_exists("'.$key.'",$e) ? $e["'. $key .'"] : null;');
    return array_map($funct, $array);
}

// usage:

$a = array(array("id"=>10, "name"=>"joe"), array("id"=>11, "name"=>"bob"));

$ids = array_pluck("id", $a);        // == array(10,11)
$names = array_pluck("name", $a);    // == array("joe", "bob")

//works on non-keyed arrays also:

$a = array(array(3,4), array(5,6));
$col2 = array_pluck(1,$a);            // == array(4,6) (grab 2nd column of data)

?>
chreekat 12-Mar-2008 03:48
I was miffed that array_map didn't have a way to pass values *and* keys to the callback, but then I realized I could do this:

function callback($k, $v) { ... }

array_map( "callback", array_keys($array), $array);
jo at ho dot nl 17-Feb-2008 02:10
Could also use things like...

array_keys(); and array_values(); offcourse...

However it's just an example off recursion via this function..
Which I found pretty handy at times dealing with arrays..

could also use:

<?php
call_user_func(array($this, __FUNCTION), $args);
?>

or

<?php
call_user_fuc_array(array($this, __FUNCTION__), $array);
?>

or

<?php
class{

   public function __construct($arg){
       if(is_array($arg)){
            new self($arg);
       }
       else{
           echo $arg.'<br/>'.PHP_EOL;
       }
   }
}
?>

Anyway.. plenty off examples..
It was just an idea for others...
avartabedian at webservice dot com dot uy 08-Feb-2008 05:39
loaded67 at hotmail dot com, there is a little error in the add func params values.

Warning: Missing argument 2 for test::add(), called in /tmp/test.php on line 34 and defined in /tmp/test.php on line 6
Array => <br/>

now it runs...

<?php
class test{

    //private $container = array();

    final public function add($key, $value=NULL){
         /* params values fix */
         $value = $value==NULL?$key:$value;
         /* recursion */
         if(is_array($value)){
               array_map(array($this, __FUNCTION__), array_keys($value), array_values($value));
         }
         /* procedural */
         else{
             echo $key.' => '.$value.'<br/>'.PHP_EOL;
             // do stuff...
             // if(!isset($this->container[$key])){
             //       $this->container[$key] = $value;
             // }
             //else{  // trigger_error() xor throw new Exception?
             //         echo 'allready exists!<br/>'.PHP_EOL;
             //}
         }
    }
}
//
$array = array (
                               'one'   => 'value1',
                               'two'   => 'value2',
                               'three' => 'value3'
                            );

$t = new test;
$t->add($array);
?>

good luck!
loaded67 at hotmail dot com 08-Feb-2008 02:59
this function is really nice for recursion in php!!!

example in a class:

<?php
class test{

    //private $container = array();

    final public function add($key, $value){
         /* recursion */
         if(is_array($value)){
               array_map(array($this, __FUNCTION__), array_keys($value), array_values($value));
         }
         /* procedural */
         else{
             echo $key.' => '.$value.'<br/>'.PHP_EOL;
             // do stuff...
             // if(!isset($this->container[$key])){
             //       $this->container[$key] = $value;
             // }
             //else{  // trigger_error() xor throw new Exception?
             //         echo 'allready exists!<br/>'.PHP_EOL;
             //}
         }
    }
}
//
$array = array (
                               'one'   => 'value1',
                               'two'   => 'value2',
                               'three' => 'value3'
                            );

$t = new test;
$t->add($array);
?>

you could easiely do this without a class too offcourse!
used in php 5.2.5
pmf 22-Jan-2008 07:02
This function behaves exactly like array_map but additionally does not reject non-array arguments. Instead, it transforms them with the array_fill function to a constant valued array of required length according to the other array arguments (if any) and executes the original array_map function.

<?php

function array_map2() {
    $args = func_get_args();

    $callback = array_shift($args);

    $args = array_map(
            create_function('$a,$max','return is_array($a)? $a: array_fill(0,$max,$a);'),
            $args,array_fill(0,count($args),array_reduce($args,
            create_function('$v,$w','return max($v,is_array($w)? count($w): 1);'))));

    array_unshift($args,$callback);

    return call_user_func_array("array_map",$args);
}

?>

Example:

<?php

$get = "first=value1&second=value2&third=value3";

print_r(array_map2("explode","=",explode("&",$get)));

?>

would print out:

<?php

Array
(
    [0] => Array
        (
            [0] => first
            [1] => value1
        )

    [1] => Array
        (
            [0] => second
            [1] => value2
        )

    [2] => Array
        (
            [0] => third
            [1] => value3
        )
)

?>

/pmf
henrique at webcoder dot com dot br 01-Nov-2007 08:02
Adding method support to function by Andref (multidimensionalArrayMap).

function array_map_r( $func, $arr )
{
    $newArr = array();

    foreach( $arr as $key => $value )
    {
        $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );
    }

    return $newArr;
}

array_map_r('function', array());
or
array_map_r(array('class', 'method'), array());
bturchik at iponweb dot net 19-Jul-2007 07:46
Maybe this one will be useful for someone:

function array_map_helper($mapper, $array) {
    $mapper = preg_replace('/^return (.*?);$/', '$1', trim($mapper));
    $result = array();
    if (preg_match('/(\(?)(.*?)\s*=>\s*(.*?)(\)?)$/', $mapper, $matches)) {
        list($full_found, $array_open, $left, $right, $array_close) = $matches;
        if ($array_open && $array_close) {
            $mapper = '$result[] = array' . $full_found . ';';
        } else {
            $mapper = '$result[' . $left . '] = ' . $right . ';';
        }
    } else {
        $mapper = '$result[] = ' . $mapper . ';';
    }

    foreach ($array as $key => $value) {
        eval($mapper);
    }

    return $result;
}

should be used like:

$array = array(array('foo' => 11, 'bar' => 22),
               array('foo' => 111, 'bar' => 222),
               array('foo' => 1111, 'bar' => 2222));
$mapped = array_map_helper('$value["foo"] => $value["bar"]', $array);

var_dump will give

array(3) {
  [11]=>
  int(22)
  [111]=>
  int(222)
  [1111]=>
  int(2222)
}

or

$mapped = array_map_helper('$value["foo"]', $array);

var_dump will give

array(3) {
  [0]=>
  int(11)
  [1]=>
  int(111)
  [2]=>
  int(1111)
}

or

$mapped = array_map_helper('$value["foo"] + $value["bar"] . " at position $key"', $array);

var_dump will give

array(3) {
  [0]=>
  string(16) "33 at position 0"
  [1]=>
  string(17) "333 at position 1"
  [2]=>
  string(18) "3333 at position 2"
}
andref dot dias at pronus dot eng dot br 24-Oct-2006 12:14
A recursive way to handle multidimensional arrays:

<?php

function multidimensionalArrayMap( $func, $arr )
    {
    $newArr = array();
    foreach( $arr as $key => $value )
        {
        $newArr[ $key ] = ( is_array( $value ) ? multidimensionalArrayMap( $func, $value ) : $func( $value ) );
        }
    return $newArr;
    }

?>
pcdinh at phpvietnam dot net 17-Mar-2006 08:50
Hi benjaminhill,

You can apply a method of a instantiated class to array_maps as follows:

class Maths {
    function addOne($input) {
        return ($input + 1);
    }
}
$maths = new Maths();
$sum = array_map(array($maths, \\\'addOne\\\'), array(1, 2));
// where $maths is the object which has been instantiated before and addOne is its method without its own parameters
var_dump($sum);

The code fragment will return:

array
  0 => 2
  1 => 3

However, I love a syntax like this:

$sum = array_map($maths->addOne($this), array(1, 2));

where $this should be interpreted as each values extracted from the subsequent array, which in this case is array(1, 2).

This syntax reminds me of Javascript syntax.

PHP\\\'s callback mechanism should be improved.
26-Aug-2005 06:57
Here's a function, very helpfull to me, that allows you to map your callback on mixed args.

<?php
function array_smart_map($callback) {
    // Initialization
    $args = func_get_args() ;
    array_shift($args) ; // suppressing the callback
    $result = array() ;

    // Validating parameters
    foreach($args as $key => $arg)
        if(is_array($arg)) {
            // the first array found gives the size of mapping and the keys that will be used for the resulting array
            if(!isset($size)) {
                $keys = array_keys($arg) ;
                $size = count($arg) ;
            // the others arrays must have the same dimension
            } elseif(count($arg) != $size) {
                return FALSE ;
            }
            // all keys are suppressed
            $args[$key] = array_values($arg) ;
        }

    // doing the callback thing
    if(!isset($size))
        // if no arrays were found, returns the result of the callback in an array
        $result[] = call_user_func_array($callback, $args) ;
    else
        for($i=0; $i<$size; $i++) {
            $column = array() ;
            foreach($args as $arg)
                $column[] = ( is_array($arg) ? $arg[$i] : $arg ) ;
            $result[$keys[$i]] = call_user_func_array($callback, $column) ;
        }

    return $result ;

}
?>

Trying with :

<?php
// $_GET is ?foo=bar1-bar2-bar3&bar=foo1
print_r(array_smart_map('explode', '-', $_GET)) ;
?>

Returns :

array(
    [foo] => array(
        0 => bar1
        1 => bar2
        2 => bar3
    )

    [bar] => array(
        1 => foo1
    )
)
david dot tulloh at infaze dot com dot au 06-Jul-2005 04:53
You can pass values to array_map by reference, essentially allowing you to use it as you would array_walk with multiple arrays as parameters.

A trivial example:
<?php
$a = array(1,2,3,4,5);
$add_func = create_function('&$x, $y', '$x+=$y;');
array_map($add_func, $a, $a);
print_r($a);
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
Vinicius Cubas Brand 23-Mar-2005 05:31
The following function does exaclty the same thing of array_map. However, maintains the same index of the input arrays

<?php
    function array_map_keys($param1,$param2,$param3=NULL)
    {
        $res = array();

        if ($param3 !== NULL)
        {
            foreach(array(2,3) as $p_name)
            {
                if (!is_array(${'param'.$p_name}))
                {
                    trigger_error(__FUNCTION__.'(): Argument #'.$p_name.' should be an array',E_USER_WARNING);
                    return;
                }
            }
            foreach($param2 as $key => $val)
            {
                $res[$key] = call_user_func($param1,$param2[$key],$param3[$key]);
            }
        }
        else
        {
            if (!is_array($param2))
            {
                trigger_error(__FUNCTION__.'(): Argument #2 should be an array',E_USER_WARNING);
                return;
            }
            foreach($param2 as $key => $val)
            {
                $res[$key] = call_user_func($param1,$param2[$key]);
            }
        }
        return $res;
    }
?>

For instance:

<?php
    $arr1 = array(
        '3' => 'a',
        '4' => 'b',
        '5' => 'c'
        );

    $arr2 = array(
        '3' => 'd',
        '4' => 'e',
        '5' => 'f'
        );

    $arr3 = array_map_keys(create_function('$a,$b','return $a.$b;'),$arr1,$arr2);

    print_r($arr3);

?>

The result will be:

Array
(
    [3] => ad
    [4] => be
    [5] => cf
)
endofyourself at yahoo dot com 19-Feb-2005 11:29
If you need to call a static method from array_map, this will NOT work:

<?PHP
array_map('myclass::myMethod' , $value);
?>

Instead, you need to do this:

<?PHP
array_map( array('myclass','myMethod') , $value);
?>

It is helpful to remember that this will work with any PHP function which expects a callback argument.
nd0 at gmx dot de 02-Jul-2004 04:42
array_map works also fine with create_function:

<?php
$a = array(1, 2, 3, 4, 5);
$b = array_map(create_function('$n', 'return $n*$n*$n;'), $a);
print_r($b);
?>

if you want to manipulate the elements of the array, instead to on a copy,
than take a look at array_walk:

<?php
$a = array(1, 2, 3, 4, 5);
array_walk($a, create_function('&$n', '$n = $n*$n*$n;'));
print_r($a);
?>

The Result of both is:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)
bishop 09-Apr-2004 05:07
Occasionally, you may find that you need to pull out a column (or several) from an array.  Here's a map-like function to do that:

<?php
function &array_shear(&$arrays, $idx1 /* ... */) {
    $indexes = func_get_args();
    array_shift($indexes);

    $newArrays = array ();

    foreach (array_keys($arrays) as $arrayKey) {
        $newArray = array ();
        foreach ($indexes as $index) {
            $newArray[$index] = $arrays[$arrayKey][$index];
            unset($arrays[$arrayKey][$index]);
        }
        $newArrays[$arrayKey] = $newArray;
    }

    return $newArrays;
}
?>

So, doing this:

<?php
$t1 = array (
          2 => array ('a', 'b', 'c'),
          1 => array ('d', 'e', 'f'),
          5 => array ('g', 'h', 'i'),
      );

$t2 = array_shear($t1, 1, 0);

?>

will result in:

<?php

$t1 = array (
  2 =>   array (    2 => 'c',  ),
  1 =>   array (    2 => 'f',  ),
  5 =>   array (    2 => 'i',  ),
);

$t2 = array (
  2 =>   array (    1 => 'b',    0 => 'a',  ),
  1 =>   array (    1 => 'e',    0 => 'd',  ),
  5 =>   array (    1 => 'h',    0 => 'g',  ),
);

?>
stephen at mu dot com dot au 06-Jan-2003 10:02
A note when doing something allong the lines of:

<?php
class foo {
  var $var;
  function bar() {
     array_map(array($this, "baz"), array(1,2,3));
  }

  function baz($arg) {
    $this->var = $this->var + $arg;
  }
}
?>

This will *not* work as expected. You need to pass $this by reference as with:

array_map(array(&$this, "baz"), array(1,2,3));

or you'll be making a copy of the object each time, changing a value, then throwing the result away.
dan at mojavelinux dot com 14-Jun-2002 10:07
Here is a better, more true version of a deep array_map.  The only negative of this function is that the array is passed by reference, so just be aware of that. (patches welcome)

<?php
function array_map_deep(&$in_array, $in_func, $in_args = array(), $in_index = 1) {
    // fix people from messing up the index of the value
    if ($in_index < 1) {
       $in_index = 1;
    }

    foreach (array_keys($in_array) as $key) {
        // we need a reference, not a copy, normal foreach won't do
        $value =& $in_array[$key];
        // we need to copy args because we are doing
        // manipulation on it farther down
        $args = $in_args;
        if (is_array($value)) {
            array_map_deep($value, $in_func, $in_args, $in_index);
        }
        else {
            array_splice($args, $in_index - 1, $in_index - 1, $value);
            $value = call_user_func_array($in_func, $args);
        }
    }

    return $in_array;
}
?>

This is a neat function because you can pass an array, a function, and an array of parameters, and finally, and index of where in the array of parameters for the callback function the contents you are mapping should get replaced.  This index is human based (starts at 1), and can be used in something like a preg_replace callback, where the contents must be the 3rd index.  Enjoy!
array_keys
array_merge_recursive
Функции для работы с массивами


Рекурсивное слияние двух или более массивов

array_map
array_merge
Функции для работы с массивами
PHP Manual

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5)

array_merge_recursive — Рекурсивное слияние двух или более массивов

Описание

array array_merge_recursive ( array $array1 [, array $... ] )

Функция array_merge_recursive() сливает элементы двух или более массивов таким образом, что значения одного массива присоединяются в конец другого. Возвращает результирующий массив.

Если входные массивы имеют одинаковые строковые ключи, то значения этих ключей сливаются в массив, и это делается рекурсивно, так что если одно из значений является массивом, то функция сливает его с соответствующим значением в другом массиве. Однако, если массивы имеют одинаковые числовые ключи, значение, упомянутое последним, не заменит исходное значение, а будет добавлено в конец массива.

Список параметров

array1

Первоначальный массив для слияния.

...

Дополнительные рекурсивно сливаемые массивы.

Возвращаемые значения

Массив значений, полученный в результате слияния аргументов вместе.

Примеры

Пример #1 Пример использования array_merge_recursive()

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

Смотрите также

  • array_merge() - Сливает один или большее количество массивов

User Contributed Notes

martyniuk dot vasyl at gmail dot com 24-Dec-2011 09:10
This is my version of array_merge_recursive without overwriting numeric keys:
<?php
function array_merge_recursive_new() {

        $arrays = func_get_args();
        $base = array_shift($arrays);

        foreach ($arrays as $array) {
            reset($base); //important
            while (list($key, $value) = @each($array)) {
                if (is_array($value) && @is_array($base[$key])) {
                    $base[$key] = array_merge_recursive_new($base[$key], $value);
                } else {
                    $base[$key] = $value;
                }
            }
        }

        return $base;
    }
?>
walf 25-May-2011 10:23
There are a lot of examples here for recursion that are meant to behave more like array_merge() but they don't get it quite right or are fairly customised. I think this version is most similar, takes more than 2 arguments and can be renamed in one place:

<?php

function array_merge_recursive_simple() {

    if (func_num_args() < 2) {
        trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
        return;
    }
    $arrays = func_get_args();
    $merged = array();
    while ($arrays) {
        $array = array_shift($arrays);
        if (!is_array($array)) {
            trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
            return;
        }
        if (!$array)
            continue;
        foreach ($array as $key => $value)
            if (is_string($key))
                if (is_array($value) && array_key_exists($key, $merged) && is_array($merged[$key]))
                    $merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value);
                else
                    $merged[$key] = $value;
            else
                $merged[] = $value;
    }
    return $merged;
}

$a1 = array(
    88 => 1,
    'foo' => 2,
    'bar' => array(4),
    'x' => 5,
    'z' => array(
        6,
        'm' => 'hi',
    ),
);
$a2 = array(
    99 => 7,
    'foo' => array(8),
    'bar' => 9,
    'y' => 10,
    'z' => array(
        'm' => 'bye',
        11,
    ),
);
$a3 = array(
    'z' => array(
        'm' => 'ciao',
    ),
);
var_dump(array_merge($a1, $a2, $a3));
var_dump(array_merge_recursive_simple($a1, $a2, $a3));
var_dump(array_merge_recursive($a1, $a2, $a3));
?>

gives:

array(7) {              array(7) {              array(7) {
  int(1)                  int(1)                  int(1)
  ["foo"]=>               ["foo"]=>               ["foo"]=>
  array(1) {              array(1) {              array(2) {
    [0]=>                   [0]=>                   [0]=>
    int(8)                  int(8)                  int(2)
  }                       }                         [1]=>
  ["bar"]=>               ["bar"]=>                 int(8)
  int(9)                  int(9)                  }
  ["x"]=>                 ["x"]=>                 ["bar"]=>
  int(5)                  int(5)                  array(2) {
  ["z"]=>                 ["z"]=>                   [0]=>
  array(1) {              array(3) {                int(4)
    ["m"]=>                 [0]=>                   [1]=>
    string(4) "ciao"        int(6)                  int(9)
  }                         ["m"]=>               }
  [1]=>                     string(4) "ciao"      ["x"]=>
  int(7)                    [1]=>                 int(5)
  ["y"]=>                   int(11)               ["z"]=>
  int(10)                 }                       array(3) {
}                         [1]=>                     [0]=>
                          int(7)                    int(6)
                          ["y"]=>                   ["m"]=>
                          int(10)                   array(3) {
                        }                             [0]=>
                                                      string(2) "hi"
                                                      [1]=>
                                                      string(3) "bye"
                                                      [2]=>
                                                      string(4) "ciao"
                                                    }
                                                    [1]=>
                                                    int(11)
                                                  }
                                                  [1]=>
                                                  int(7)
                                                  ["y"]=>
                                                  int(10)
                                                }
andyidol at gmail dot com 10-Feb-2011 07:14
Here's my function to recursively merge two arrays with overwrites. Nice for merging configurations.

<?php

function MergeArrays($Arr1, $Arr2)
{
  foreach($Arr2 as $key => $Value)
  {
    if(array_key_exists($key, $Arr1) && is_array($Value))
      $Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);

    else
      $Arr1[$key] = $Value;

  }

  return $Arr1;

}

?>
lsiq at papotam com 01-Oct-2010 01:17
<?php

//  this function merges an array with the $_SESSION
//  if you omit second parameter it merges to the root
//  if you give one 'path' array it is merged deeply

function arr2sess($arr, $path=array()){
   if (!is_array($arr)) return false;
   foreach($arr as $k => $v){
      if(is_array($arr[$k])) {
          $path[] = $k;
          arr2sess($arr[$k], $path);
      }else{
          $ref = &$_SESSION;
          if($path){
              foreach($path as $val){
                  if(!$ref[$val]) $ref[$val] = array();
                  $ref = &$ref[$val];
              }
          }
          $ref[$k] = $v;
      }
   }
}

session_start();
$x = array(k1=>12, k2=>array(kxx=>'forget me', kyy=>'I was allways here'));     // do you have any of this on $_SESSION
$rpl = array(k2=>array(kxx=>'I am a replaced value',kzz=>'I am a new value'));
arr2sess($x, array('deep','deep','in_session'));                                // you can use this way
arr2sess($x);                                                                   // or this
arr2sess($rpl);                                                                 // to merge parts with the $_SESSION

$w = array(120, q=>array(199,100));                                             // works the same way on numeric keys
arr2sess($w, array('one','two'));
arr2sess($w);

echo '<pre>';
print_r($_SESSION);

?>
mark dot roduner at gmail dot com 13-Feb-2010 11:34
<?php
/**
 * Merges any number of arrays / parameters recursively, replacing
 * entries with string keys with values from latter arrays.
 * If the entry or the next value to be assigned is an array, then it
 * automagically treats both arguments as an array.
 * Numeric entries are appended, not replaced, but only if they are
 * unique
 *
 * calling: result = array_merge_recursive_distinct(a1, a2, ... aN)
**/

function array_merge_recursive_distinct () {
  $arrays = func_get_args();
  $base = array_shift($arrays);
  if(!is_array($base)) $base = empty($base) ? array() : array($base);
  foreach($arrays as $append) {
    if(!is_array($append)) $append = array($append);
    foreach($append as $key => $value) {
      if(!array_key_exists($key, $base) and !is_numeric($key)) {
        $base[$key] = $append[$key];
        continue;
      }
      if(is_array($value) or is_array($base[$key])) {
        $base[$key] = array_merge_recursive_distinct($base[$key], $append[$key]);
      } else if(is_numeric($key)) {
        if(!in_array($value, $base)) $base[] = $value;
      } else {
        $base[$key] = $value;
      }
    }
  }
  return $base;
}
?>
drvali at hotmail dot com 05-Oct-2009 09:31
<?php
/**
 * Merges any number of arrays of any dimensions, the later overwriting
 * previous keys, unless the key is numeric, in whitch case, duplicated
 * values will not be added.
 *
 * The arrays to be merged are passed as arguments to the function.
 *
 * @access public
 * @return array Resulting array, once all have been merged
 */
function array_merge_replace_recursive() {
    // Holds all the arrays passed
    $params = & func_get_args ();

    // First array is used as the base, everything else overwrites on it
    $return = array_shift ( $params );

    // Merge all arrays on the first array
    foreach ( $params as $array ) {
        foreach ( $array as $key => $value ) {
            // Numeric keyed values are added (unless already there)
            if (is_numeric ( $key ) && (! in_array ( $value, $return ))) {
                if (is_array ( $value )) {
                    $return [] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [] = $value;
                }

            // String keyed values are replaced
            } else {
                if (isset ( $return [$key] ) && is_array ( $value ) && is_array ( $return [$key] )) {
                    $return [$key] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [$key] = $value;
                }
            }
        }
    }

    return $return;
}

$a = array (
    "a" => 1,
    "b" => 2,
    'foo',
    'bar'
);
$b = array (
    "a" => 2,
    "c" => 3,
    'foo'
);

$c = array_merge_replace_recursive ( $a, $b );
print_r ( $a );
print_r ( $b );
print_r ( $c );
?>

Output:
Array
(
    [a] => 1
    [b] => 2
    [0] => foo
    [1] => bar
)
Array
(
    [a] => 2
    [c] => 3
    [0] => foo
)
Array
(
    [a] => 2
    [b] => 2
    [0] => foo
    [1] => bar
    [c] => 3
)
gabriel dot sobrinho at gmail dot com 13-Jul-2009 07:56
I refactored the Daniel's function and I got it:

<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param array $array2
 * @return array
 * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
 * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
 */
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
  $merged = $array1;

  foreach ( $array2 as $key => &$value )
  {
    if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
    {
      $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
    }
    else
    {
      $merged [$key] = $value;
    }
  }

  return $merged;
}
?>

This fix the E_NOTICE when the the first array doesn't have the key and the second array have a value which is a array.
jonnybergstrom at googles mail domain dot comm 27-Jun-2009 08:30
This function didn't work for me - or it didn't do what I thought it would. So I wrote the below function, which merges two arrays, and returns the resulting array. The base array is the left one ($a1), and if a key is set in both arrays, the right value has precedence. If a value in the left one is an array and also an array in the right one, the function calls itself (recursion). If the left one is an array and the right one exists but is not an array, then the right non-array-value will be used.

*Any key only appearing in the right one will be ignored*
 - as I didn't need values appearing only in the right in my implementation, but if you want that you could make some fast fix.

function array_merge_recursive_leftsource(&$a1, &$a2) {
    $newArray = array();
    foreach ($a1 as $key => $v) {
        if (!isset($a2[$key])) {
            $newArray[$key] = $v;
            continue;
        }

        if (is_array($v)) {
            if (!is_array($a2[$key])) {
                $newArray[$key] = $a2[$key];
                continue;
            }
            $newArray[$key] = array_merge_recursive_leftsource($a1[$key], $a2[$key]);
            continue;
        }

        $newArray[$key] = $a2[$key];
    }
    return $newArray;
}
michiel at synetic dot nl 22-May-2009 01:54
A small improvement upon the previously posted array_merge_recursive_distinct functions (based on daniel's version). This implementation preserves the parameter input from the original, you can pass an infinite amount of array's to merge.

<?php
function &array_merge_recursive_distinct()
{
    $aArrays = func_get_args();
    $aMerged = $aArrays[0];

    for($i = 1; $i < count($aArrays); $i++)
    {
        if (is_array($aArrays[$i]))
        {
            foreach ($aArrays[$i] as $key => $val)
            {
                if (is_array($aArrays[$i][$key]))
                {
                    $aMerged[$key] = is_array($aMerged[$key]) ? PR::array_merge_recursive_distinct($aMerged[$key], $aArrays[$i][$key]) : $aArrays[$i][$key];
                }
                else
                {
                    $aMerged[$key] = $val;
                }
            }
        }
    }

    return $aMerged;
}
?>
daniel at danielsmedegaardbuus dot dk 19-Mar-2009 02:18
<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param mixed $array2
 * @return array
 * @author daniel@danielsmedegaardbuus.dk
 */
function &array_merge_recursive_distinct(array &$array1, &$array2 = null)
{
  $merged = $array1;

  if (is_array($array2))
    foreach ($array2 as $key => $val)
      if (is_array($array2[$key]))
        $merged[$key] = is_array($merged[$key]) ? array_merge_recursive_distinct($merged[$key], $array2[$key]) : $array2[$key];
      else
        $merged[$key] = $val;

  return $merged;
}
?>
n dot kaiser at online-congress dot com 05-Mar-2009 11:24
Here ist my array recursive merge function
/**
* merge a array recursive
*
* @param array   $array1: original array
* @param array   $array2: the array to insert
* @return array  the merged array
*/
public function recursiveArrayMerge($array1, $array2){
    reset ($array2);
    while(key($array2)!==null) {
        if (is_array(current($array2)) && isset($array1[key($array2)])) {
            $array1[key($array2)] = $this->recursiveArrayMerge($array1[key($array2)],current($array2));
        } else {
            $array1[key($array2)] = current($array2);
        }
        next($array2);
    }
    return $array1;
}
miniscalope at gmail dot com 04-Feb-2009 03:56
I would merge 2 arrays but keep the values unique in the result array.
I hope this will help...
<?php

function array_merge_recursive_unique($array1, $array2) {

    foreach($array2 AS $k => $v) {
        if(!isset($array1[$k]))
        {
            $array1[$k] = $v;
        }
        else
        {
            if(!is_array($v)){
                if(is_array($array1[$k]))
                {
                    if(!in_array($v,$array1[$k]))
                    {
                        $array1[$k][] = $v;
                    }
                }
                else
                {
                    if($array1[$k] != $v)
                        $array1[$k] = array($array1[$k], $v);
                 }
            }
            else
            {
                $array1[$k] =    array_merge_recursive_unique($array1,$array2[$k]);
            }

        }

    }
      unset($k, $v);
      return $array1;
}

?>
remy dot damour at -please-no-spam-laposte dot net 21-Jan-2009 06:28
If what you want is merge all values of your array that are arrays themselves to get a resulting array of depth one, then you're more looking for array_flatten function.

Unfortunately I did not find such native function in php, here is the one I wrote:

<?php
/**
 * Flatten an array so that resulting array is of depth 1.
 * If any value is an array itself, it is merged by parent array, and so on.
 *
 * @param array $array
 * @param bool $preserver_keys OPTIONAL When true, keys are preserved when mergin nested arrays (=> values with same key get overwritten)
 * @return array
 */
function array_flatten($array, $preserve_keys = false)
{
    if (!$preserve_keys) {
        // ensure keys are numeric values to avoid overwritting when array_merge gets called
        $array = array_values($array);
    }

    $flattened_array = array();
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $flattened_array = array_merge($flattened_array, call_user_func(__FUNCTION__, $v, $preserve_keys));
        } elseif ($preserve_keys) {
            $flattened_array[$k] = $v;
        } else {
            $flattened_array[] = $v;
        }
    }
    return $flattened_array;
}

// example
$a = array ('k1' => 'a', 'k2' => array('k1' => 'b', 'k4' => array('k3' => 'c')));
var_export(array_flatten($a)); // output: array(0 => 'a', 1 => 'b', 2 => 'c')
var_export(array_flatten($a, true)); // output: array('k1' => 'b', 'k3' => 'c') // first 'k1' value gets overwritten by nested 'k1' value
?>
phil dot kemmeter at gmail dot com 08-Dec-2008 10:45
I've edit this version even a little bit more, so that the function does not override any values, but inserts them at a free key in the array:

function my_array_merge ($arr,$ins) {
    if(is_array($arr))
    {
        if(is_array($ins)) foreach($ins as $k=>$v)
        {
            if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
            {
                $arr[$k] = my_array_merge($arr[$k],$v);
            }
            else {
                // This is the new loop :)
                while (isset($arr[$k]))
                    $k++;
                $arr[$k] = $v;
            }
        }
    }
    elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
    {
        $arr=$ins;
    }
    return($arr);
}

Example:

$array1 = array(
    100 => array(30),
    200 => array(20, 30)
);

$array2 = array(
    100 => array(40),
    201 => array(60, 30)
);

print_r(my_array_merge($array1,$array2));

Output with array_merge_recursive:
Array
(
    [0] => Array
        (
            [0] => 30
        )

    [1] => Array
        (
            [0] => 20
            [1] => 30
        )

    [2] => Array
        (
            [0] => 40
        )

)
This is not the result, I expect from a MERGE-Routine...

Output with the current function:

Array
(
    [100] => Array
        (
            [0] => 30
            [1] => 40
        )

    [200] => Array
        (
            [0] => 20
            [1] => 30
        )

)

This is what I want :)
scott dot clark at vizioninteractive dot com 28-Aug-2008 01:55
Needed some way to fuse two arrays together and found a function here (below from thomas) and decided to update it even further to be a little more smart.

<?php
function my_array_merge ($arr,$ins)
    {
        if(is_array($arr))
            {
                if(is_array($ins)) foreach($ins as $k=>$v)
                    {
                        if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
                            {
                                $arr[$k] = my_array_merge($arr[$k],$v);
                            }
                        else $arr[$k] = $v;
                    }
            }
        elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
            {
                $arr=$ins;
            }
        return($arr);
    }
?>
thomas at n-o-s-p-a-m dot thoftware dot de 04-May-2008 06:50
This is a simple, three line approach.

Short description: If one of the Arguments isn't an Array, first Argument is returned. If an Element is an Array in both Arrays, Arrays are merged recursively, otherwise the element in $ins will overwrite the element in $arr (regardless if key is numeric or not). This also applys to Arrays in $arr, if the Element is scalar in $ins (in difference to the previous approach).

  function array_insert($arr,$ins) {
    # Loop through all Elements in $ins:
    if (is_array($arr) && is_array($ins)) foreach ($ins as $k => $v) {
      # Key exists in $arr and both Elemente are Arrays: Merge recursively.
      if (isset($arr[$k]) && is_array($v) && is_array($arr[$k])) $arr[$k] = array_insert($arr[$k],$v);
      # Place more Conditions here (see below)
      # ...
      # Otherwise replace Element in $arr with Element in $ins:
      else $arr[$k] = $v;
    }
    # Return merged Arrays:
    return($arr);
  }

In Addition to felix dot ospald at gmx dot de in my opinion there is no need to compare keys with type-casting, as a key always is changed into an integer if it could be an integer. Just try

$a = array('1'=>'1');
echo gettype(key($a));

It will echo 'integer'. So for having Integer-Keys simply appended instead of replaced, add the Line:

  elseif (is_int($k)) $arr[] = $v;

A Condition I used is:

  elseif (is_null($v)) unset($arr[$k]);

So a NULL-Value in $ins will unset the correspondig Element in $arr (which is different to setting it to NULL!). This may be another Addition to felix dot ospald at gmx dot de: The absolute correct way to check for a Key existing in an Array is using array_key_exists() (not needed in the current context, as isset() is combined with is_array()). array_key_exists() will return TRUE even if the Value of the Element is NULL.

And the last one: If you want to use this approach for more than 2 Arrays, simply use this:

  function array_insert_mult($arr) {
    # More than 1 Argument: Append all Arguments.
    if (func_num_args() > 1) foreach (array_slice(func_get_args(),1) as $ins) $arr = array_insert($arr,$ins);
    # Return merged Arrays:
    return($arr);
  }

And if you worry about maintaining References: Simply use $ins[$k] instead of $v when assigning a Value/using a Value as Argument.
felix dot ospald at gmx dot de 26-Feb-2008 11:23
If you desire correct and performant behaviour (in contrast to the other postings) use this code. It works as documented above.
If you want that keys are always perserved and not appended or renumbered if they are numeric comment out the "if (((string) $key) === ((string) intval($key)))" case.
@spambegone at cratemedia dot com: using empty is not right way to check if an item is in the array use isset!

<?php

function array_merge_recursive2($array1, $array2)
{
    $arrays = func_get_args();
    $narrays = count($arrays);

    // check arguments
    // comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
    for ($i = 0; $i < $narrays; $i ++) {
        if (!is_array($arrays[$i])) {
            // also array_merge_recursive returns nothing in this case
            trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning null!', E_USER_WARNING);
            return;
        }
    }

    // the first array is in the output set in every case
    $ret = $arrays[0];

    // merege $ret with the remaining arrays
    for ($i = 1; $i < $narrays; $i ++) {
        foreach ($arrays[$i] as $key => $value) {
            if (((string) $key) === ((string) intval($key))) { // integer or string as integer key - append
                $ret[] = $value;
            }
            else { // string key - megre
                if (is_array($value) && isset($ret[$key])) {
                    // if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
                    // in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be null.
                    $ret[$key] = array_merge_recursive2($ret[$key], $value);
                }
                else {
                    $ret[$key] = $value;
                }
            }
        }
    }

    return $ret;
}

// Examples:

print_r(array_merge_recursive2(array('A','B','C' => array(1,2,3)), array('D','C' => array(1,4))));
/*
Array
(
    [0] => A
    [1] => B
    [C] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 1
            [4] => 4
        )
    [2] => D
)*/

print_r(array_merge_recursive2(array('A','B','0' => array(1,2,3)), array('D','0' => array(1,array(4)))));
/*
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => B
    [2] => Array
        (
            [0] => 1
            [1] => Array
                (
                    [0] => 4
                )
        )
)*/

print_r(array_merge_recursive2(array('A' => array('A' => 1)), array('A' => array('A' => array(2)))));
/*
Warning: Argument #1 is not an array - trying to merge array with scalar! Returning null! in ... on line ...
*/

var_dump(array_merge_recursive2(array('A' => array('A' => 2)), array('A' => array('A' => null))));
/*
array(1) { ["A"]=>  array(1) { ["A"]=>  NULL } }
*/

?>
spambegone at cratemedia dot com 12-Feb-2008 02:06
I've tried these array_merge_recursive functions without much success. Maybe it's just me but they don't seem to actually go more than one level deep? As with all things, its usually easier to write your own, which I did and it seems to work just the way I wanted. Anyways, my function hasn't been tested extensively, but it's a simple function, so in hopes that this might be useful to someone else I'm sharing.

Also, the PHP function array_merge_recursive() didn't work for my purposes because it didn't overwrite the values like I needed it to. You know how it works, it just turns it into an array with multiple values... not helpful if your code is expecting one string.

function array_merge_recursive_unique($array1, $array2) {

    // STRATEGY
    /*
    Merge array1 and array2, overwriting 1st array values with 2nd array
    values where they overlap. Use array1 as the base array and then add
    in values from array2 as they exist.

    Walk through each value in array2 and see if a value corresponds
    in array1. If it does, overwrite with second array value. If it's an
    array, recursively execute this function and return the value. If it's
    a string, overwrite the value from array1 with the value from array2.

    If a value exists in array2 that is not found in array1, add it to array1.
    */

    // LOOP THROUGH $array2
    foreach($array2 AS $k => $v) {

        // CHECK IF VALUE EXISTS IN $array1
        if(!empty($array1[$k])) {
            // IF VALUE EXISTS CHECK IF IT'S AN ARRAY OR A STRING
            if(!is_array($array2[$k])) {
                // OVERWRITE IF IT'S A STRING
                $array1[$k]=$array2[$k];
            } else {
                // RECURSE IF IT'S AN ARRAY
                $array1[$k] = array_merge_recursive_unique($array1[$k], $array2[$k]);
            }
        } else {
            // IF VALUE DOESN'T EXIST IN $array1 USE $array2 VALUE
            $array1[$k]=$v;
        }
    }
    unset($k, $v);

    return $array1;
}
paha at paha dot hu 12-Mar-2007 12:02
In this version the values are overwritten only if they are not an array.  If the value is an array, its elements will be merged/overwritten:

// array_merge_recursive which override value with next value.
// based on: http://www.php.net/manual/hu/function.array-merge-recursive.php 09-Dec-2006 03:38
function array_merge_recursive_unique($array0, $array1)
{
    $arrays = func_get_args();
    $remains = $arrays;

    // We walk through each arrays and put value in the results (without
    // considering previous value).
    $result = array();

    // loop available array
    foreach($arrays as $array) {

        // The first remaining array is $array. We are processing it. So
        // we remove it from remaing arrays.
        array_shift($remains);

        // We don't care non array param, like array_merge since PHP 5.0.
        if(is_array($array)) {
            // Loop values
            foreach($array as $key => $value) {
                if(is_array($value)) {
                    // we gather all remaining arrays that have such key available
                    $args = array();
                    foreach($remains as $remain) {
                        if(array_key_exists($key, $remain)) {
                            array_push($args, $remain[$key]);
                        }
                    }

                    if(count($args) > 2) {
                        // put the recursion
                        $result[$key] = call_user_func_array(__FUNCTION__, $args);
                    } else {
                        foreach($value as $vkey => $vval) {
                            $result[$key][$vkey] = $vval;
                        }
                    }
                } else {
                    // simply put the value
                    $result[$key] = $value;
                }
            }
        }
    }
    return $result;
}
bersace03 at laposte dot net 09-Dec-2006 03:38
Hi all,

Here is a function array_merge_recursive_unique which override values, but walk recursivly arrays and works for unlimited number of arrays. (i posted a previous version which had a bug in recursion).

<?php
// array_merge_recursive which override value with next value.
function array_merge_recursive_unique ($array0, $array1)
{
  $arrays = func_get_args ();
  $remains = $arrays;

  // We walk through each arrays and put value in the results (without
  // considering previous value).
  $result = array ();

  // loop available array
  foreach ($arrays as $array) {

    // The first remaining array is $array. We are processing it. So
    // we remove it from remaing arrays.
    array_shift ($remains);

    // We don't care non array param, like array_merge since PHP 5.0.
    if (is_array ($array)) {
      // Loop values
      foreach ($array as $key => $value) {
    if (is_array ($value)) {

      // we gather all remaining arrays that have such key available
      $args = array ();
      foreach ($remains as $remain) {
        if (array_key_exists ($key, $remain)) {
          array_push ($args, $remain[$key]);
        }
      }
      if (count ($args) > 2) {
        // put the recursion
        $result[$key] = call_user_func_array (__FUNCTION__, $args);
      }
      else {
        $result[$key] = $value;
      }
    }
    else {

      // simply put the value
      $result[$key] = $value;
    }
      }
    }
  }

  return $result;
}

?>

Enjoy :D
randallgirard at hotmail dot com 26-Nov-2006 01:18
I wrote the following for merging arrays, in my project mainly for configuration... Thought someone else might find it usefull.

function array_merge_recursive_keys( $first, $second, $greedy=false) {
   $inter = array_intersect_assoc(array_keys($first), array_keys($second)); # shaired keys
# the idea next, is to strip and append from $second into $first
   foreach ( $inter as $key ) {
   # recursion if both are arrays
      if ( is_array($first[$key]) && is_array($second[$key]) ) {
         $first[$key] = array_merge_recursive_keys($first[$key], $second[$key]);
      }
   # non-greedy array merging:
      else if ( is_array($first[$key] && !$greedy ) ) {
         $first[$key][] = $second[$key];
      }
      else if ( is_array($second[$key]) && !$greedy ) {
         $second[$key][] = $first[$key];
         $first[$key] = $second[$key];
      }
   # overwrite...
      else {
         $first[$key] = $second[$key];
      }
      unset($second[$key]);
   }
# merge the unmatching keys onto first
   return array_merge($first, $second);
}
thiago dot mata at yahoo dot com dot br 30-Sep-2006 12:25
<?php
    function array_merge_recursive_keep_keys( $arrElement1 , $arrElement2 , $intCount = 0 )
    {

        $arrNew = array();

        $arrElement1Keys = array_keys( $arrElement1 );
        $arrElement2Keys = array_keys( $arrElement2 );

        $arrDifKeys1 = array_diff( $arrElement1Keys, $arrElement2Keys );
        $arrDifKeys2 = array_diff( $arrElement2Keys, $arrElement1Keys );
        $arrInter     = array_intersect( $arrElement1Keys , $arrElement2Keys );

        foreach( $arrDifKeys1 as $strKey1)
        {
            $arrNew[ $strKey1 ] = $arrElement1[ $strKey1 ];
        }
        foreach( $arrDifKeys2 as $strKey2)
        {
            $arrNew[ $strKey2 ] = $arrElement2[ $strKey2 ];
        }
        foreach( $arrInter as $strInterKey )
        {
            if( is_array( $arrElement1[ $strInterKey ] ) && is_array( $arrElement2[ $strInterKey ] ) )
            {
                $intCount++;
                $arrNew[ $strInterKey ] = array_merge_recursive_keep_keys( $arrElement1[ $strInterKey ] , $arrElement2[ $strInterKey ] , $intCount );
            }
            elseif( is_array( $arrElement1[ $strInterKey ] ) || is_array( $arrElement2[ $strInterKey ] ) )
            {
                $arrNew[ $strInterKey ][]    =  $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][]    =  $arrElement2[ $strInterKey ];
            }
            else
            {
                $arrNew[ $strInterKey ] = array();
                $arrNew[ $strInterKey ][] = $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][] = $arrElement2[ $strInterKey ];
            }
        }
        return $arrNew;
    }
?>
smilingrasta 07-Jul-2006 10:04
This function tends to reindex arrays, which is not  mentioned in the function description.

I just tried to run that function on a three dimensional array, containing errormessages.
The first dim. contains the severity of the error ('warn', 'crit') the second dim the linenumber (numerical) and the third one consists of errormessages

<?php
# Array printout:
Array
 (
   [warn] => Array  // severity (associative)
    (
      [2] => Array  // linenumber (numerical)
       (
         [0] => "Category does not exist"
         [1] => "Manufacturer does not exist"
       )
    )
 )

?>

If i now merge two or more of those arrays using array_merge_recursive(), the linenumbers are not conserved. Instead of, they are all renumbered, starting with 0.

Just thought anyone may want to know about that. :)
regards, smilingrasta
Vladimir Kornea 11-May-2006 07:10
The documentation for array_merge_recursive() states that string keys are preserved while numeric keys are renumbered. What's not obvious is that string keys which happen to be numeric are NOT preserved, but renumbered:

$a = array('5' => array('blue'));
$b = array('5' => array('red'));
$c = array_merge_recursive($a, $b);
print_r($c);

Output:

Array
(
    [0] => Array
        (
            [0] => blue
        )

    [1] => Array
        (
            [0] => red
        )

)

If the key '5' were treated as a string, the resulting array would be this:

Array
(
    [5] => Array
        (
            [0] => blue
            [1] => red
        )
)
jason at ebasterpro dot com 19-Aug-2005 09:56
This modifications allows you to merge arrays of objects and objects of arrays recursively.
/**
 * arrayobj_merge_recursive2()
 *
 * Similar to array_merge_recursive2 but supports objects and arrays, keyed-valued are always overwritten.
 * Priority goes to the 2nd array. And support Object Array mixture
 *
 * @static yes
 * @public yes
 * @param $paArray1 array/object
 * @param $paArray2 array/object
 * @return array/object
 */
function arrayobj_merge_recursive2($paArray1, $paArray2)
{
    if(is_array($paArray2))
    {
        foreach ($paArray2 AS $sKey2 => $sValue2)
        {
            $paArray1[$sKey2] = arrayobj_merge_recursive2(@$paArray1[$sKey2], $sValue2);
        }
    }
    elseif(is_object($paArray2))
    {
        foreach ($paArray2 AS $sKey2 => $sValue2)
        {
             $paArray1->{$sKey2} = arrayobj_merge_recursive2(@$paArray1->{$sKey2}, $sValue2);
        }
    } else {
         return $paArray2;
    }
   return $paArray1;
}
fire at firepages dot com dot au 20-Dec-2004 07:10
PHP5 note , in PHP4 you could pass an uninitialised array to array_merge_recursive which would issue a notice but not break anything ..

while( $whatever){
 $uninitialised_array = array_merge_recursive( $uninitialised_array, $t ) ;
}

in PHP5 , if you dont initialise the array the recursion never starts so $uninitialised_array = array(); solves (good practive anyway I suppose?)
manicdepressive at mindless dot com 22-Jun-2004 07:30
Please be aware that under circumstances where you have
both the key and value common between the two arrays at a given node,
array_merge_recursive() will behave differently if that value is NULL,
as opposed to a non-null value.

i.e., I expected the results of the first two sections below to
have the same structure, but they don't.
If this might apply to you, please see for yourself.

<pre><?php

$a1 = array('a'=>'b');
$a2 = array('a'=>'b');
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>NULL);
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>'b');
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

?></pre>

This behavior also occurs if the value is the empty array.
In fact, in the above example, interchanging the empty array with
any and all occurences of NULL will yield the same result.

    code till dawn!  -mark
brian at vermonster dot com 25-May-2004 02:44
Here is a fairly simple function that replaces while recursing.

<?php
/**
 * array_merge_recursive2()
 *
 * Similar to array_merge_recursive but keyed-valued are always overwritten.
 * Priority goes to the 2nd array.
 *
 * @static yes
 * @public yes
 * @param $paArray1 array
 * @param $paArray2 array
 * @return array
 */
function array_merge_recursive2($paArray1, $paArray2)
{
    if (!is_array($paArray1) or !is_array($paArray2)) { return $paArray2; }
    foreach ($paArray2 AS $sKey2 => $sValue2)
    {
        $paArray1[$sKey2] = array_merge_recursive2(@$paArray1[$sKey2], $sValue2);
    }
    return $paArray1;
}

?>

Examples:
<?php

$array1 = array(
    'liquids' => array(
        'water' => array('cold', 'fizzy', 'clean')
        ,'beer' => 'warm'
    )
);

$array2 = array(
    'liquids' => array(
        'water' => 'hot'
        ,'milk' => 'wet'
    )
);

$result1 = array_merge_recursive2($array1, $array2);
$result2 = array_merge_recursive2($array2, $array1);
?>

Result 1 is:
Array
(
    [liquids] => Array
        (
            [water] => hot
            [beer] => warm
            [milk] => wet
        )
)

Result 2 is:
Array
(
    [liquids] => Array
        (
            [water] => Array
                (
                    [0] => cold
                    [1] => fizzy
                    [2] => clean
                )

            [milk] => wet
            [beer] => warm
        )
)
paska at kios dot sk 04-Mar-2004 02:18
This emulates replace of $_REQUEST according to variable_order=GPC.
<?
    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);
?>

Useful with stripping backslashes at beginning of main include file:
<?
if (get_magic_quotes_gpc() == 1) {

    function stripMagicSlashes($element) {
        if (is_array($element)) {
            return array_map("stripMagicSlashes", $element);
        } else {
            return stripslashes($element);
        }
    }

    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_GET    = array_map("stripMagicSlashes", $_GET);
    $_POST   = array_map("stripMagicSlashes", $_POST);
    $_COOKIE = array_map("stripMagicSlashes", $_COOKIE);

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);

}

$GLOBALS['stripped'] = true;
?>

Based on examples from users from this site.
t dot tom at succont dot de 08-Jan-2004 08:09
Here my modification of shemari's Code for Replacing Values in an Array. My modification will return the new Array, not handle it by reference.
Original Array will not be touched.

Hope it helps anyone. Most thanks goes to shemari ;o)

<?php
   /**
     * Merges two arrays and replace existing Entrys
     *
     * Merges two Array like the PHP Function array_merge_recursive.
     * The main difference is that existing Keys will be replaced with new Values,
     * not combined in a new Sub Array.
     *
     * Usage:
     *         $newArray = array_merge_replace( $array, $newValues );
     *
     * @access puplic
     * @author Tobias Tom <t.tom@succont.de>
     * @param array $array First Array with 'replaceable' Values
     * @param array $newValues Array which will be merged into first one
     * @return array Resulting Array from replacing Process
     */
function array_merge_replace( $array, $newValues ) {
    foreach ( $newValues as $key => $value ) {
        if ( is_array( $value ) ) {
               if ( !isset( $array[ $key ] ) ) {
                $array[ $key ] = array();
            }
            $array[ $key ] = $this->array_merge_replace( $array[ $key ], $value );
        } else {
            if ( isset( $array[ $key ] ) && is_array( $array[ $key ] ) ) {
                $array[ $key ][ 0 ] = $value;
            } else {
                if ( isset( $array ) && !is_array( $array ) ) {
                    $temp = $array;
                    $array = array();
                    $array[0] = $temp;
                }
                $array[ $key ] = $value;
            }
        }
    }
    return $array;
}
?>
shemari75 at mixmail dot com 18-Dec-2003 09:22
Here's a function to recursively merge any number of any-dimensional arrays.
It actually works in quite a similar way as array_merge_recursive does, but with two major differences:
- Later elements overwrite previous ones having the same keys.
- Numeric keys are not appended. Instead, they are converted into associative ones, and therefore overwritten as stated above.

Usage:
    array array_merge_n(array array1, array array2[, array ...])

<?php
    /**
     *  Merges two arrays of any dimension
     *
     *  This is the process' core!
     *  Here each array is merged with the current resulting one
     *
     *  @access private
     *  @author Chema Barcala Calveiro <shemari75@mixmail.com>
     *  @param array $array   Resulting array - passed by reference
     *  @param array $array_i Array to be merged - passed by reference
     */

    function array_merge_2(&$array, &$array_i) {
        // For each element of the array (key => value):
        foreach ($array_i as $k => $v) {
            // If the value itself is an array, the process repeats recursively:
            if (is_array($v)) {
                if (!isset($array[$k])) {
                    $array[$k] = array();
                }
                array_merge_2($array[$k], $v);

            // Else, the value is assigned to the current element of the resulting array:
            } else {
                if (isset($array[$k]) && is_array($array[$k])) {
                    $array[$k][0] = $v;
                } else {
                    if (isset($array) && !is_array($array)) {
                        $temp = $array;
                        $array = array();
                        $array[0] = $temp;
                    }
                    $array[$k] = $v;
                }
            }
        }
    }

    /**
     *  Merges any number of arrays of any dimension
     *
     *  The arrays to be merged are passed as arguments to the function,
     *  which uses an external function (array_merge_2) to merge each of them
     *  with the resulting one as it's being constructed
     *
     *  @access public
     *  @author Chema Barcala Calveiro <shemari75@mixmail.com>
     *  @return array Resulting array, once all have been merged
     */

    function array_merge_n() {
        // Initialization of the resulting array:
        $array = array();

        // Arrays to be merged (function's arguments):
        $arrays =& func_get_args();

        // Merging of each array with the resulting one:
        foreach ($arrays as $array_i) {
            if (is_array($array_i)) {
                array_merge_2($array, $array_i);
            }
        }

        return $array;
    }
?>
array_map
array_merge
Функции для работы с массивами


Сливает один или большее количество массивов

array_merge_recursive
array_multisort
Функции для работы с массивами
PHP Manual

array_merge

(PHP 4, PHP 5)

array_merge — Сливает один или большее количество массивов

Описание

array array_merge ( array $array1 [, array $... ] )

Сливает элементы одного или большего количества массивов таким образом, что значения одного массива присоединяются к концу предыдущего. Результатом работы функции является новый массив.

Если входные массивы имеют одинаковые строковые ключи, тогда каждое последующее значение будет заменять предыдущее. Однако, если массивы имеют одинаковые числовые ключи, значение, упомянутое последним, не заменит исходное значение, а будет добавлено в конец массива.

В результирующем массиве значения исходного массива с числовыми ключами будут перенумерованы в возрастающем порядке, начиная с нуля.

Список параметров

array1

Исходный сливаемый массив.

...

Дополнительные сливаемые массивы.

Возвращаемые значения

Возвращает результирующий массив.

Список изменений

Версия Описание
5.0.0
Внимание

Поведение функции array_merge() было изменено в PHP 5. В отличие от PHP 4, array_merge() принимает параметры только типа array. Однако вы можете использовать приведение типов. Смотрите следующий пример для уточнения подробностей.

Пример #1 Пример использования array_merge() в PHP 5

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

Результат выполнения данного примера:

    Array
    (
        [0] => foo
        [1] => bar
    )

Примеры

Пример #2 Пример использования array_merge()

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Пример #3 Простой пример использования array_merge()

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

Помните, что числовые ключи будут перенумерованы!

Array
(
    [0] => data
)

Если вы хотите дополнить первый массив элементами второго без перезаписи элементов первого массива и без переиндексации, используйте оператор объединения массивов +:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

Ключи из первого массива будут сохранены. Если ключ массива существует в обоих массивах, то будет использован элемент из первого массива, а соответствующий элемент из второго массива будет проигнорирован.

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Смотрите также

  • array_merge_recursive() - Рекурсивное слияние двух или более массивов
  • array_combine() - Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений
  • array operators

User Contributed Notes

Gemorroj 14-May-2012 08:37
The function behaves differently with numbers more than PHP_INT_MAX
<?php
$arr1 = array('1234567898765432123456789' => 'dd');
$arr2 = array('123456789876543212345678' => 'ddd', '35' => 'xxx');
var_dump(array_merge($arr1, $arr2));
//
$arr1 = array('1234' => 'dd');
$arr2 = array('12345' => 'ddd', '35' => 'xxx');
var_dump(array_merge($arr1, $arr2));
?>
result:
array(3) {
  ["1234567898765432123456789"]=>
  string(2) "dd"
  ["123456789876543212345678"]=>
  string(3) "ddd"
  [0]=>
  string(3) "xxx"
}
array(3) {
  [0]=>
  string(2) "dd"
  [1]=>
  string(3) "ddd"
  [2]=>
  string(3) "xxx"
}
tobias at tobias-net dot nl 05-May-2012 09:41
If you don't know how many array's you're going to merge, you could use this:

foreach ($entries as $num => $entry) {
    if ($num == sizeof ($entries)-1) continue;
    if (isset ($entries[$num]) && isset ($entries[$num+1])) {
        if (isset ($merged)) $merged = array_merge ($merged, $entries[$num], $entries[$num+1]);
        else $merged = array_merge ($entries[$num], $entries[$num+1]);
    }
}

var_dump ($merged);
izhar_aazmi at gmail dot com 28-Feb-2012 08:54
The problem that the array keys are reindexed, and further not working on array values of type object or other mixed types.

Simply, I did this:

<?php
foreach($new as $k => $v)
{
    $old[$k] = $v;
}
// This will overwrite all values in OLD with any existing
// matching value in NEW
// And keep all non matching values from OLD intact.
// No reindexing, and complete overwrite
/// Working with all kind of data
?>
alejandro dot anv at gmail dot com 20-Feb-2012 11:26
WARNING: numeric subindexes are lost when merging arrays.

Check this example:

$a=array('abc'=>'abc','def'=>'def','123'=>'123','xyz'=>'xyz');
echo "a=";print_r($a);
$b=array('xxx'=>'xxx');
echo "b=";print_r($b);
$c=array_merge($a,$b);
echo "c=";print_r($c);

The result is this:

c=Array
(
    [abc] => abc
    [def] => def
    [0] => 123
    [xyz] => xyz
    [xxx] => xxx
)
ventzy dot public at gmail dot com 07-Dec-2011 09:03
On line to merge arrays WITHOUT REINDEXING numerical keys and WITH OVERWRITING:

$result = array_diff_key($a, $b) + $b

<?php
// example

$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');

$result = array_diff_key($array1, $array2) + $array2;

//$result = array(
//  0 => 'zero_a'
//  2 => 'two_a'
//  1 => 'one_b'
//  3 => 'three_b'
//  4 => 'four_b')
?>
njp AT o2 DOT pl 22-Nov-2011 04:45
Uniques values merge for array_merge function:

<?php
function array_unique_merge() {

        $variables = '$_'.implode(',$_',array_keys(func_get_args()));

        $func = create_function('$tab', ' list('.$variables.') = $tab; return array_unique(array_merge('.$variables.'));');

        return $func(func_get_args());
    }
?>

Doesn't work on objects.

Smarter way for uniques values merge array:

<?php
function array_unique_merge() {

       return array_unique(call_user_func_array('array_merge', func_get_args()));
   }
?>

Example 1:

$a = array(1,2);
$b = array(2,3,4);

array_unique_merge($a,$b);

Return:
array(1,2,3,4);

Example 2:

$a = array(1,2);
$b = array(2,3,4);
$c = array(2,3,4,5);

array_unique_merge($a,$b);

Return:
array(1,2,3,4,5);

Doesn't work on objects.
w_barath at hotmail dot com 04-Oct-2011 04:42
I keep seeing posts for people looking for a function to replace numeric keys.

No function is required for this, it is default behavior if the + operator:

<?php
$a=array(1=>"one", "two"=>2);
$b=array(1=>"two", "two"=>1, 3=>"three", "four"=>4);

print_r($a+$b);
?>

Array
(
    [1] => one
    [two] => 2
    [3] => three
    [four] => 4
)

How this works:

The + operator only adds unique keys to the resulting array.  By making the replacements the first argument, they naturally always replace the keys from the second argument, numeric or not! =)
Krinkle 28-Sep-2011 03:01
I always confuse which does what and when. So I made this cheatsheet that you may find useful.

The existing examples show some situations but not all of these four.

<?php
$n1 = array('foo', 'bar', 'baz');
$n2 = array('lorem', 'ipsum', 'foo');

// array plus:
// - duplicate numeral keys are ignored, not overwriting
// - new keys inserted at the end
$n1 + $n2;
?>
array(3) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
}

<?php
// array_merge:
// - duplicate numeral keys are appended and keys are reindexed
// - new keys inserted at the end
array_merge( $n1, $n2 );
?>
array(6) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "lorem"
  [4]=>
  string(5) "ipsum"
  [5]=>
  string(3) "foo"
}

<?php
$a1 = array('f' => 'foo', 'b' => 'bar', 'q' => 'quux');
$a2 = array('l' => 'lorem', 'i' => 'ipsum', 'f' => 'facilisis');

// array plus:
// - duplicate associative array keys ignored, not overwriting
// - new keys inserted at the end
$a1 + $a2;
?>
array(5) {
  ["f"]=>
  string(3) "foo"
  ["b"]=>
  string(3) "bar"
  ["q"]=>
  string(4) "quux"
  ["l"]=>
  string(5) "lorem"
  ["i"]=>
  string(5) "ipsum"
}

<?php

// array plus:
// - replacements are done at the original position
// - new keys inserted at the end
array_merge( $a1, $a2 )
?>
array(5) {
  ["f"]=>
  string(9) "facilisis"
  ["b"]=>
  string(3) "bar"
  ["q"]=>
  string(4) "quux"
  ["l"]=>
  string(5) "lorem"
  ["i"]=>
  string(5) "ipsum"
}
eithed sth gmail sth com 06-Jul-2011 07:03
I'm sorry, but I've not found on this page a function that would properly merge two arrays while overwriting numeric values.

Considering two arrays:

<?php
$test1 = array(array('a','b','c'), 'a', 'b');
$test2 = array(array('d','e'), 'c');
?>

while using overwrite merge you would expect the result to be an array:
<?php $test3 = array(array('d','e'), 'c', 'b'); ?>

However most of the functions will result with this array:
<?php $test4 = array(array('d','e','c'), 'c', 'b'); ?>

So, here's a function to do that:

<?php
function array_merge_overwrite(array &$array1, array $array2 = NULL)
{
    $flag = true;
    foreach (array_keys($array2) as $key)
    {
        if (isset($array2[$key]) && is_array($array2[$key]))
        {
            if (isset($array1[$key]) && is_array($array1[$key]))
                array_merge_overwrite($array1[$key], $array2[$key]);
            else
                $array1[$key] = $array2[$key];

            $flag = false;
        }
    }

    if ($flag == true)
        $array1 = $array2;
}
?>
japicoder-NOSPAM at gmail dot com 16-Mar-2011 06:20
If you need to add the same array N times (with the same keys, of course) to an existing array, array_merge() will not work because of the same keys. The plus operator (+) still doesn't resolve the problem because of the keys.

Example:

<?php
$args = array();

for($i=0; $i < 3; $i++) {
   $args += array('first', 'second', 'three', 'four');
}

print_r($args);
?>

Will give you:

array(
  [0] => 'first'
  [1] => 'second'
  [2] => 'three'
  [3] => 'four'
)

The solution is to play with the first key of the array you are adding:

<?php
$args = array();

for($i=0; $i < 3; $i++) {
   $args += array(sizeof($args)+1 => 'first', 'second', 'three', 'four');
}

print_r($args);
?>

Now it is added as expected:

array(
  [0] => 'first'
  [1] => 'second'
  [2] => 'three'
  [3] => 'four'
  [4] => 'first'
  [5] => 'second'
  [6] => 'three'
  [7] => 'four'
  [8] => 'first'
  [9] => 'second'
  [10] => 'three'
  [11] => 'four'
)
craig ala craigatx.com 26-Oct-2010 10:25
Reiterating the notes about casting to arrays, be sure to cast if one of the arrays might be null:

<?php
header("Content-type:text/plain");
$a = array('zzzz', 'xxxx');
$b = array('mmmm','nnnn');

echo "1 ==============\r\n";
print_r(array_merge($a, $b));

echo "2 ==============\r\n";
$b = array();
print_r(array_merge($a, $b));

echo "3 ==============\r\n";
$b = null;
print_r(array_merge($a, $b));

echo "4 ==============\r\n";
$b = null;
print_r(array_merge($a, (array)$b));

echo "5 ==============\r\n";
echo is_null(array_merge($a, $b)) ? 'Result is null' : 'Result is not null';
?>

Produces:

1 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
    [2] => mmmm
    [3] => nnnn
)
2 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
)
3 ==============
4 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
)
5 ==============
Result is null
nzujev [AT] gmail [DOT] com 03-Oct-2010 02:28
Be ready to surprise like this one.
array_merge renumbers numeric keys even if key is as string.
keys '1' & '2' will be updated to 0 & 1, but '1.1' & '1.2' remain the same, but they are numeric too (is_numeric('1.1') -> true)

It's better to use '+' operator or to have your own implementation for array_merge.

<?php

$x1 = array (
    '1'     => 'Value 1',
    '1.1'   => 'Value 1.1',
);

$x2 = array (
    '2'     => 'Value 2',
    '2.1'   => 'Value 2.1',
);

$x3 = array_merge( $x1, $x2 );

echo '<pre>NOT as expected: '. print_r( $x3, true ) .'</pre>';

$x3 = $x1 + $x2;

echo '<pre>As expected: '. print_r( $x3, true ) .'</pre>';

?>

NOT as expected: Array
(
    [0] => Value 1
    [1.1] => Value 1.1
    [1] => Value 2
    [2.1] => Value 2.1
)
As expected: Array
(
    [1] => Value 1
    [1.1] => Value 1.1
    [2] => Value 2
    [2.1] => Value 2.1
)
zagadka at evorg dot dk 20-Aug-2010 05:54
Note that if you use + to merge array in order to preserve keys, that in case of duplicates the values from the left array in the addition is used.
jpakin at gmail dot com 11-Jun-2010 11:46
I had a hard time using array_merge with large datasets. By the time my web framework was in memory there wasn't enough space to have multiple copies of my dataset. To fix this I had to remove any functions which operated on the data set and made a copy in memory (pass by value).

I realize the available memory to an application instance is modifiable, but I didn't think I should have to set it below the default 16mb for a web app!

Unfortunately, a number of php functions pass by value internally, so I had to write my own merge function. This passes by reference, utilizes a fast while loop (thus doesn't need to call count() to get an upper boundary, also a php pass by value culprit), and unsets the copy array (freeing memory as it goes).

<?php

function mergeArrays(&$sourceArray, &$copyArray){
        //merge copy array into source array
                $i = 0;
        while (isset($copyArray[$i])){
            $sourceArray[] = $copyArray[$i];
            unset($copyArray[$i]);
            $i++;
        }
    }
?>

This fixed the problem. I would love to know if there is an even faster, more efficient way. Simply adding the two arrays won't work since there is an overlap of index.
me at cafuego dot net 20-May-2010 09:49
This function merges two arrays into one, alternating between the two arrays. Given:

$one = array('apple', 'pear');
$two = array('blue', 'red');
$output = array();
array_merge_zipper(&$output, $one, $two, TRUE);

$output would be:

array(
  0 => 'apple',
  1 => 'blue',
  2 => 'pear',
  3 => 'red'
);

The $same_size flag is to note whether both input arrays contain the same number of items. If not, setting the flag to FALSE will make the function merge up to the number of items in the smallest of the two input arrays.

<?php
function array_merge_zipper(&$output, $one = array(), $two = array(), $same_size= TRUE) {

  if ($same_size) {
    // Return FALSE if the arrays differ in size.
    if (count($one) != count($two))
      return FALSE;
    $number = count($one);
  } else {
    // Count as high as the smallest array.
    $number = min(count($one), count($two));
  }

  // Empty the output array.
  $output = array();

  // Merge.
  for ($i = 0; $i < $number; $i++) {
    $output[] = $one[$i];
    $output[] = $two[$i];
  }

  // Return success.
  return TRUE;
}
?>

The following function does essentially the same, but preserves array keys. It'll return FALSE if the input arrays share a key between them or if the  arrays differ in size.

<?php
function array_merge_zipper_key(&$output, $one = array(), $two = array()) {
  // Return FALSE if the arrays differ in size.
  if (count($one) != count($two))
    return FALSE;

  // Returns FALSE if the arrays share a key.
  if (count(array_keys_intersect($one, $two)))
    return FALSE;

  // Empty the output array.
  $output = array();

  // keys!
  $one_keys = array_keys($one);
  $two_keys = array_keys($two);

  // Merge.
  for ($i = 0; $i < count($one); $i++) {
    $output[$one_keys[$i]] = $one[$one_keys[$i]];
    $output[$two_keys[$i]] = $two[$two_keys[$i]];
  }

  // Return success.
  return TRUE;
}
nekroshorume at gmail dot com 18-Mar-2010 10:31
be aware there is a slight difference:

<?php
$array1 = array('lang'=>'js','method'=>'GET');
$array2 = array('lang'=>'php','browser'=>'opera','method'=>'POST');
?>

BETWEEN:

<?php array_merge($array2,$array1); ?>
outputs: Array ( [lang] => js [browser] => opera [method] => GET )

notice that the repeated keys will be overwritten by the ones of $array1, maintaining those, because it is the array that is being merged

AND

<?php array_merge($array1,$array2); ?>
outputs: Array ( [lang] => php [method] => POST [browser] => opera )

here the oposite takes place: array1 will have its elements replaced by those of array2.
riddlemd at gmail dot com 22-Jan-2010 12:43
Apparently there is a shorthand that works very much like array_merge. I figured I would leave a comment here, sense I saw it used in code but found nothing about it from google searches.

<?php
$array = array(
 'name' => 'John Doe'
);
$array += array(
 'address' => 'someplace somestreet'
);

echo $array['address']; // Outputs 'someplace somestreet'
?>

A difference from merge_array, it does NOT overwrite existing keys, regardless of key type.
Amund 24-Dec-2009 09:23
"Extend" recursively array $a with array $b values (no deletion in $a, just added and updated values)

<?php
function array_extend($a, $b) {
    foreach($b as $k=>$v) {
        if( is_array($v) ) {
            if( !isset($a[$k]) ) {
                $a[$k] = $v;
            } else {
                $a[$k] = array_extend($a[$k], $v);
            }
        } else {
            $a[$k] = $v;
        }
    }
    return $a;
}
?>
randallgirard at hotmail dot com 16-Dec-2009 02:16
I am in the middle of recoding a very complex CMS I wrote in the past, and I often used array_merge() to determine default values (example: paths, keys which refer to objects elsewhere, etc).

I was trying to decide if I should use array_merge or individual calls to isset in combination with an $opts array, to supply default values in functions. For example, here would be two simple examples:

<?php
function foo( array $opts = array() ) {
    if ( isset($opts['val1']) ) $opts['val1'] = 'value';
    if ( isset($opts['val2']) ) $opts['val2'] = 'value';
    if ( isset($opts['val3']) ) $opts['val3'] = 'value';
#    ... continue coding
}
function bar( array $opts = array() ) {
    $opts = array_merge( array(
        'val1' => 'value',
        'val2' => 'value',
        'val3' => 'value',
    ), $opts);
#    ... continue coding
}
?>

Hypothesis: isset() will be dramatically faster in both circumstances, as benchmarks I have performed in the past usually demonstrate that array iterations are typically slow and should be avoided when and where possible. (ex: using strrpos and substr rather than explode and array_pop to get a file name from a path, of course you can just use basename() but this is just for explanation purposes)

---

I performed numerous benchmarks using loops, and then hard-coded examples and got fairly similar results. My four focus points however, were supplying the values in the $opts array, and not supplying the values, with both methods.

Calls to isset() WITH the values supplied was ALWAYS the fastest (which makes sense, as no assignments are made)

Calls to isset() WITH the values supplied, and array_merge() with NO values set came very close in times, and fluctuated which was faster or slower...
(This surprised me as I expected that working with array_merge would simply take more time; But also makes sense as I think about it more as you are still utilizing an array and array_merge is probably making isset() calls in itself)

Calls to array_merge() with NO values supplied was always the SLOWEST. (which also makes sense, because all values are replaced)

---

Conclusion: Calls to isset() are faster than using array_merge(); But not by much. However, the more values supplied when calling the function determine how much closer the execution time will take. Therefor, with this type of functionality in mind, supplying DEFAULT values mean often NO, SOME, or ALL values will be included when calling the function...

Because I am worried about the execution time over easy / less code, I'll stick with the isset() method of supplying default values to an array.

---

Now that the test results are in, I thought I would share as I spent quite a bit of time testing and going over results.
allankelly 02-Oct-2009 08:36
More on the union (+) operator:
the order of arrays is important and does not agree in my test below
with the other posts. The 'unique' operation preserves the initial key-value and discards later duplicates.

PHP 5.2.6-2ubuntu4.2

<?php
$a1=array('12345'=>'a', '23456'=>'b', '34567'=>'c', '45678'=>'d');
$a2=array('34567'=>'X');
$a3=$a1 + $a2;
$a4=$a2 + $a1;
print('a1:'); print_r($a1);
print('a2:'); print_r($a2);
print('a3:'); print_r($a3);
print('a4:'); print_r($a4);
?>

a1:Array
(
    [12345] => a
    [23456] => b
    [34567] => c
    [45678] => d
)
a2:Array
(
    [34567] => X
)
a3:Array
(
    [12345] => a
    [23456] => b
    [34567] => c
    [45678] => d
)
a4:Array
(
    [34567] => X
    [12345] => a
    [23456] => b
    [45678] => d
)
Tudor 27-Sep-2009 01:10
array_merge will merge numeric keys in array iteration order, not in increasing numeric order. For example:

<?php
$a = array(0=>10, 1=>20);  // same as array(10, 20);
$b = array(0=>30, 2=>50, 1=>40);
?>

array_merge($a, $b) will be array(10, 20, 30, 50, 40) and not array(10, 20, 30, 40, 50).
Julian Egelstaff 16-Aug-2009 01:02
More about the union operator (+)...

The "array_unique" that gets applied, is actually based on the keys, not the values.  So if you have multiple values with the same key, only the last one will be preserved.

<?php

$array1[0] = "zero";
$array1[1] = "one";

$array2[0] = 0;
$array1[1] = 1;

$array3 = $array1 + $array2;

// array3 will look like:
// array(0=>0, 1=>1)
// ie: beware of the latter keys overwriting the former keys

?>
Julian Egelstaff 30-Jul-2009 11:48
In some situations, the union operator ( + ) might be more useful to you than array_merge.  The array_merge function does not preserve numeric key values.  If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1[0] = "zero";
$array1[1] = "one";

$array2[1] = "one";
$array2[2] = "two";
$array2[3] = "three";

$array3 = $array1 + $array2;

//This will result in::

$array3 = array(0=>"zero", 1=>"one", 2=>"two", 3=>"three");

?>

Note the implicit "array_unique" that gets applied as well.  In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian
enaeseth at gmail dot com 20-Jul-2009 02:27
In both PHP 4 and 5, array_merge preserves references in array values. For example:

<?php
$foo = 12;
$array = array("foo" => &$foo);
$merged_array = array_merge($array, array("bar" => "baz"));
$merged_array["foo"] = 24;
assert($foo === 24); // works just fine
?>
rossrevisited at googlemail dot com 07-Apr-2009 12:58
I was looking to merge two associative arrays together, adding the values together if the keys were the same. If there were keys unique to either array, these would be added into the merged array with their existing values.

I couldnt find a function to do this, so made this:

<?php
    function merge($array1, $array2)
    {

        if(sizeof($array1)>sizeof($array2))
        {
            echo $size = sizeof($array1);
        }else{
            $a = $array1;
            $array1 = $array2;
            $array2 = $a;

            echo $size = sizeof($array1);
        }

        $keys2 = array_keys($array2);

        for($i = 0;$i<$size;$i++)
        {
            $array1[$keys2[$i]] = $array1[$keys2[$i]] + $array2[$keys2[$i]];
        }

        $array1 = array_filter($array1);
        return $array1;
    }

?>

Enter in two arrays to the function, then the output will be both arrays merged together with values added if keys are the same.
jerry at gii dot co dot jp 12-Mar-2009 07:35
There was a previous note that alluded to this, but at least in version 5.2.4 array_merge will return NULL if any of the arguments are NULL. This bit me with $_POST when none of the controls were successful.
luke at cywh dot com 10-Mar-2009 03:46
The "array_merge_recursive" did not work exactly the way I wanted it to, so I wrote these functions. I have it under "array_merge" simply because I also have a non-recursive version as well. Took me hours to get this right, so hopefully this helps someone else.

array array_mix(array $array1 [, array $array2 [, array $... ]])

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the new value is not an array then the value gets turned into a new numerically indexed array containing the original value and the new value. Three or more occurrences get appended to the new array.

If the new value is an array, then the original value gets overwritten with the new one.

This function works exactly the same for both string and numeric based keys.

Example:

<?php
$array_a = array(
    'one' => array(
        'a1', 'a2', 'a3'
    ),
    'four' => 'one'
);

$array_b = array(
    'one' => array(
        'b1', 'b2', 'b3'
    ),
    'four' => 'two'
);

print_r(array_mix($array_a, $array_b, $array_c));
?>

See output. Notice the difference between array_mix and array_merge.

array array_mix_recursive(array $array1 [, array $array2 [, array $... ]])

Works exactly the same as "array_mix", with one exception:

If the new value is an array then array_mix is done recursively.

Example:

<?php

$array_a = array(
    'one' => array(
        'a1', 'a2', 'a3'
    ),
    'three' => array(
        'i' => 'A1', 'ii' => 'A2', 'iii' => 'A3'
    ),
    'four' => 'one'
);

$array_b = array(
    'one' => array(
        'b1', 'b2', 'b3'
    ),
    'three' => array(
        'i' => 'B1', 'ii' => 'B2', 'iii' => array('one', 'two', 'three')
    ),
    'four' => 'two'
);

print_r(array_mix_recursive($array_a, $array_b));

?>

See output.

This function works very similar to array_merge_recursive, with this obvious exception: Numeric keys are treated just like string keys.

CODE:

<?php
function array_mix() {
    $array = array();
    $arrays = func_get_args();

    foreach($arrays as $array_i) if(is_array($array_i))
        $array = array_mixer($array, $array_i);

    return $array;
}

function array_mix_recursive() {
    $array = array();
    $arrays = func_get_args();

    foreach($arrays as $array_i) if(is_array($array_i))
        $array = array_mixer($array, $array_i, true);

    return $array;
}

function array_mixer($array_o, $array_i, $recursive=false) {
    foreach($array_i as $k => $v) {
        if(! isset($array_o[$k])) {
            $array_o[$k] = $v;
        } else {
            if(is_array($array_o[$k])) {
                if(is_array($v)) {
                    if($recursive) $array_o[$k] = array_mixer($array_o[$k], $v);
                    else $array_o[$k] = $v;
                } else $array_o[$k][] = $v;
            } else {
                if(! isset($array_o[$k])) {
                    $array_o[$k] = $v;
                } else {
                    $array_o[$k] = array($array_o[$k]);
                    $array_o[$k][] = $v;
                }
            }
        }
    }

    return $array_o;
}
?>
a dot pipkin at skylermedia dot com 07-Mar-2009 08:33
I needed to merge two arrays while keeping the first arrays format and adding the values, if they exist, from the second array. I was working with several multidimensional arrays and was using one as the primary structure to insert data into a database. This is what I made. I hope it helps.
<?php
    function array_overlay($a1,$a2)
    {
        foreach($a1 as $k => $v) {
            if(!array_key_exists($k,$a2)) continue;
            if(is_array($v) && is_array($a2[$k])){
                $a1[$k] = array_overlay($v,$a2[$k]);
            }else{
                $a1[$k] = $a2[$k];
            }
        }
        return $a1;
    }
?>

I used it like this:
<?php
    $table = tableDescription(); // created an array of the table structure
    $table = array_overlay($table,$_POST); // writes the values submitted from the array into the table using array names in the form like <input type="text" name="column[Value]" value="" />
?>
carrox at inbox dot lv 31-Aug-2008 04:41
Usage of operand '+' for merging arrays:

<?php

$a=array(
'a'=>'a1',
'b'=>'a2',
'a3',
'a4',
'a5');

$b=array('b1',
'b2',
'a'=>'b3',
'b4');

$a+=$b;

print_r($a);

?>

output:
Array
(
    [a] => a1
    [b] => a2
    [0] => a3
    [1] => a4
    [2] => a5
    [3] => b5
)

numeric keys of elements of array B what not presented in array A was added.

<?php

$a=array('a'=>'a1','b'=>'a2','a3','a4','a5');
$b=array(100=>'b1','b2','a'=>'b3','b4');

$a+=$b;

print_r($a);

?>

output:

   [a] => a1
    [b] => a2
    [0] => a3
    [1] => a4
    [2] => a5
    [100] => b1
    [101] => b2
    [102] => b4

autoindex for array B started from 100, these keys not present in array A, so this elements was added to array A
ron at ronfolio dot com 11-Aug-2008 06:44
I needed a function similar to ian at fuzzygroove's array_interlace, but I need to pass more than two arrays.

Here's my version, You can pass any number of arrays and it will interlace and key them properly.

<?php
function array_interlace() {
    $args = func_get_args();
    $total = count($args);

    if($total < 2) {
        return FALSE;
    }

    $i = 0;
    $j = 0;
    $arr = array();

    foreach($args as $arg) {
        foreach($arg as $v) {
            $arr[$j] = $v;
            $j += $total;
        }

        $i++;
        $j = $i;
    }

    ksort($arr);
    return array_values($arr);
}
?>

Example usage:
<?php
$a = array('a', 'b', 'c', 'd');
$b = array('e', 'f', 'g');
$c = array('h', 'i', 'j');
$d = array('k', 'l', 'm', 'n', 'o');

print_r(array_interlace($a, $b, $c, $d));
?>

result:

Array
(
    [0] => a
    [1] => e
    [2] => h
    [3] => k
    [4] => b
    [5] => f
    [6] => i
    [7] => l
    [8] => c
    [9] => g
    [10] => j
    [11] => m
    [12] => d
    [13] => n
    [14] => o
)

Let me know if you improve on it.
david_douard at hotmail dot com 02-Jul-2008 02:41
To avoid REINDEXING issues,

use + operator :

array_merge(
          array("truc" => "salut"),
          array("machin" => "coucou")
        )

returns

array(2)
{
[0] => string() "salut"
[1] => string() "coucou"
}

whereas

array("truc" => "salut") + array("machin" => "coucou")

returns

array(2)
{
["truc"] => string() "salut"
["machin"] => string() "coucou"
}
monkey dot 05 dot 06 at NO SPAM gmail dot com 16-Jun-2008 09:25
I wrote this function to strip one or more arrays to a single one-dimensional array. Keys assigned to individual values are preserved; keys assigned to arrays are not.

<?php
  function array_merge_deep($arr) { // an array-merging function to strip one or more arrays down to a single one dimension array
    $arr = (array)$arr;
    $argc = func_num_args();
    if ($argc != 1) {
      $argv = func_get_args();
      for ($i = 1; $i < $argc; $i++) $arr = array_merge($arr, (array)$argv[$i]);
    }
    $temparr = array();
    foreach($arr as $key => $value) {
      if (is_array($value)) $temparr = array_merge($temparr, array_merge_deep($value));
      else $temparr = array_merge($temparr, array($key => $value));
    }
    return $temparr;
  }
?>

Example:

<?php
  $groceries = array("fruits" => array("apples", "bananas", "cherries", "grapes"), "dry goods" => array("bread", "flour", "yeast"), "dairy" => "milk");
  $groceries = array_merge_deep($groceries);
  echo "<pre>"; print_r($groceries); echo "</pre>";
?>

Yields the following:

Array
(
    [0] => apples
    [1] => bananas
    [2] => cherries
    [3] => grapes
    [4] => bread
    [5] => flour
    [6] => yeast
    [dairy] => milk
)
david dot lay at axlr8 dot com 08-May-2008 06:19
probably simpler versions of this (below) but thought i'd post my solution up as it might be helpful :)

<?php
function array_merge_php4_comp() {
    $n=func_num_args();
    if( $n>0 ) {
        $rval=func_get_arg(0);
        if( !is_array($rval) ) {
            $rval=(array)$rval;
        }
        if( $n>1 ) {
            for( $i=1; $i<$n; $i++ ) {
                $tval=func_get_arg($i);
                if( !is_array($tval) ) {
                    $tval=(array)$tval;
                }
                $rval=array_merge($rval, $tval);
            }
        } else {
            $rval=array_merge($rval);
        }
    } else {
        $rval=array_merge();
    }
    return $rval;
}
?>
ian at fuzzygroove dot com 29-Apr-2008 04:51
I needed a function to interlace two arrays ([a,b,c] + [d,e,f] = [a,d,b,e,c,f]) and came up with the following. This function works for arrays of varying lengths and keeps the keys sequenced properly.

<?php

$a = array ('a', 'b', 'c');
$b = array ('d', 'e', 'f', 'g', 'h', 'i');

$c = array_interlace ($a, $b);
/*
Array
(
    [0] => a
    [1] => d
    [2] => b
    [3] => e
    [4] => c
    [5] => f
    [6] => g
    [7] => h
    [8] => i
)
*/

function array_interlace ($a, $b)
{
    $c = array();

    $shorty = (count($a) > count($b)) ? $b : $a;
    $biggy = (count($a) > count($b)) ? $a : $b;

    $slen = count($shorty);
    $blen = count($biggy);

    for ($i = 0; $i < $slen; ++$i){
        $c[$i * 2] = $a[$i];
        $c[$i * 2 + 1] = $b[$i];
    }

    for ($i = $slen; $i < $blen; ++$i)
    {
        $c[] = $biggy[$i];
    }

    return $c;
}
?>
bishop 04-Apr-2008 02:02
The documentation is a touch misleading when it says: "If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way."  Even with two arrays, the resulting array is re-indexed:

[bishop@predator staging]$ cat array_merge.php
<?php
$a = array (23 => 'Hello', '42' => 'World');
$a = array_merge(array (0 => 'I say, '), $a);
var_dump($a);
?>
[bishop@predator staging]$ php-5.2.5 array_merge.php
array(3) {
  [0]=>
  string(7) "I say, "
  [1]=>
  string(5) "Hello"
  [2]=>
  string(5) "World"
}
[bishop@predator staging]$ php-4.4.7 array_merge.php
array(3) {
  [0]=>
  string(7) "I say, "
  [1]=>
  string(5) "Hello"
  [2]=>
  string(5) "World"
}
no_one at nobody dot com 03-Mar-2008 08:31
PHP is wonderfully decides if an array key could be a number, it is a number!  And thus wipes out the key when you array merge.   Just a warning.

$array1['4000'] = 'Grade 1 Widgets';
$array1['4000a'] = 'Grade A Widgets';
$array2['5830'] = 'Grade 1 Thing-a-jigs';
$array2['HW39393'] = 'Some other widget';

var_dump($array1);
var_dump($array2);

//results in...
array(2) {
  [4000]=>
  string(15) "Grade 1 Widgets"
  ["4000a"]=>
  string(15) "Grade A Widgets"
}
array(2) {
  [5830]=>
  string(20) "Grade 1 Thing-a-jigs"
  ["HW39393"]=>
  string(17) "Some other widget"
}

var_dump(array_merge($array1,$array2));
//results in...
array(4) {
  [0]=>
  string(15) "Grade 1 Widgets"
  ["4000a"]=>
  string(15) "Grade A Widgets"
  [1]=>
  string(20) "Grade 1 Thing-a-jigs"
  ["HW39393"]=>
  string(17) "Some other widget"
}
Hayley Watson 04-Nov-2007 12:38
As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.
Kevin Campbell 16-Aug-2007 03:33
The notes in Example 257 above are incorrect. It states:

If you want to completely preserve the arrays and just want to append them to each other, use the + operator

Check the array type page at http://www.php.net/manual/en/language.types.array.php which states differently. Duplicate keys are ignored with the + operator.
clancyhood at gmail dot com 21-Jul-2007 04:52
Similar to Jo I had a problem merging arrays (thanks for that Jo you kicked me out of my debugging slumber) - array_merge does NOT act like array_push, as I had anticipated

<?php

$array = array('1', 'hello');
array_push($array, 'world');

var_dump($array);

// gives '1', 'hello', 'world'

$array = array('1', 'hello');
array_merge($array, array('world'));

// gives '1', 'hello'

$array = array('1', 'hello');
$array = array_merge($array, array('world'));

// gives '1', 'hello', 'world'

?>

hope this helps someone
Joe at neosource dot com dot au 03-Jun-2007 11:51
I found the "simple" method of adding arrays behaves differently as described in the documentation in PHP v5.2.0-10.

$array1 + $array2 will only combine entries for keys that don't already exist.

Take the following example:

$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = ($ar1 + $ar2);
print_r($ar3);

Result:

Array
(
    [0] => a
    [1] => b
)

Where as:

$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = array_merge($ar1, $ar2);
print_r($ar3);

Result:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Hope this helps someone.
RQuadling at GMail dot com 21-May-2007 05:05
For asteddy at tin dot it and others who are trying to merge arrays and keep the keys, don't forget the simple + operator.

Using the array_merge_keys() function (with a small mod to deal with multiple arguments), provides no difference in output as compared to +.

<?php
$a = array(-1 => 'minus 1');
$b = array(0 => 'nought');
$c = array(0 => 'nought');
var_export(array_merge_keys($a,$b));
var_export($a + $b);
var_export(array_merge_keys($a,$b,$c));
var_export($a + $b + $c);
?>

results in ...

array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
Marce! 02-Mar-2007 04:21
I have been searching for an in-place merge function, but couldn't find one. This function merges two arrays, but leaves the order untouched.
Here it is for all others that want it:

function inplacemerge($a, $b) {
  $result = array();
  $i = $j = 0;
  if (count($a)==0) { return $b; }
  if (count($b)==0) { return $a; }
  while($i < count($a) && $j < count($b)){
    if ($a[$i] <= $b[$j]) {
      $result[] = $a[$i];
      if ($a[$i]==$b[$j]) { $j++; }
      $i++;
    } else {
      $result[] = $b[$j];
      $j++;
    }
  }
  while ($i<count($a)){
    $result[] = $a[$i];
    $i++;
  }
  while ($j<count($b)){
    $result[] = $b[$j];
    $j++;
  }
  return $result;
}
ahigerd at stratitec dot com 24-Jan-2007 06:06
An earlier comment mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
lcvalentine at gmail dot com 21-Jan-2007 10:23
I recently upgrade from PHP4 to PHP5.  While using PHP4, there was a certain set of information that we filtered into the $_SESSION global at login.  i.e.

$_SESSION = array_merge( $_SESSION, $additional_vals );

This method worked great in PHP4, but not in PHP5.  I can only assume the session immediately invalidated itself.

In fact, my tests to find this bug, led me to find out that all session changes - even those before this action - were lost.

DO NOT USE array_merge() FROM $_SESSION AND TO $_SESSION
asteddy at tin dot it 16-Jan-2007 07:51
Sorry, I forgot to translate the the name of the function when it calls itself. Here is the correct code:
<?
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
    foreach($arr2 as $k=>$v) {
        if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
            $arr1[$k]=$v;
        }
        else { // K EXISTS //
            if (is_array($v)) { // K IS AN ARRAY //
                $arr1[$k]=array_merge_keys($arr1[$k], $arr2[$k]);
            }
        }
    }
    return $arr1;
}
?>
asteddy at tin dot it 15-Jan-2007 06:06
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
    foreach($arr2 as $k=>$v) {
        if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
            $arr1[$k]=$v;
        }
        else { // K EXISTS //
            if (is_array($v)) { // K IS AN ARRAY //
                $arr1[$k]=array_unisci_chiavi($arr1[$k], $arr2[$k]);
            }
        }
    }
    return $arr1;
}
m dot kaczanowski at alianet dot pl 13-Dec-2006 10:47
To: zspencer at zacharyspencer dot com

You forget about code of this function.

<?
function safe_array_merge($a, $b) {
    foreach ($b as $v) {
        $a[] = $v;
    }
    return $a;
}
?>
zspencer at zacharyspencer dot com 09-Nov-2006 08:55
I noticed the lack of a function that will safely merge two arrays without losing data due to duplicate keys but different values.

So I wrote a quicky that would offset duplicate keys and thus preserve their data. of course, this does somewhat mess up association...

<?php
$array1=array('cats'=>'Murder the beasties!', 'ninjas'=>'Use Ninjas to murder cats!');
$array2=array('cats'=>'Cats are fluffy! Hooray for Cats!', 'ninjas'=>'Ninas are mean cat brutalizers!!!');
$array3=safe_array_merge($array1, $array2);
print_r($array3)
/*
Array {
cats => Murder the beasties!,
ninjas => Use ninjas to murder cats!,

?>
cats_0 => Cats are fluffy! Hooray for Cats!,
ninjas_0 => Ninjas are mean cat brutalizers!!!
}

function safe_array_merge ()
{
    $args = func_get_args();
    $result=array();
    foreach($args as &$array)
    {
        foreach($array as $key=>&$value)
        {
            if(isset($result[$key]))
            {
                $continue=TRUE;
                $fake_key=0;
                while($continue==TRUE)
                {
                    if(!isset($result[$key.'_'.$fake_key]))
                    {
                        $result[$key.'_'.$fake_key]=$value;
                        $continue=FALSE;
                    }
                    $fake_key++;
                }
            }
            else
            {
                $result[$key]=$value;
            }
        }
    }
    return $result;
}
?>
01-Nov-2006 06:47
A more efficient array_merge that preserves keys, truly accepts an arbitrary number of arguments, and saves space on the stack (non recursive):
<?php
function array_merge_keys(){
    $args = func_get_args();
    $result = array();
    foreach($args as &$array){
        foreach($array as $key=>&$value){
            $result[$key] = $value;
        }
    }
    return $result;
}
?>
BigueNique at yahoo dot ca 28-Sep-2006 07:10
Needed an quick array_merge clone that preserves the keys:

<?
// function array_join
// merges 2 arrays preserving the keys,
// even if they are numeric (unlike array_merge)
// if 2 keys are identical, the last one overwites
// the existing one, just like array_merge
// merges up to 10 arrays, minimum 2.
function array_join($a1, $a2, $a3=null, $a4=null, $a5=null, $a6=null, $a7=null, $a8=null, $a9=null, $a10=null) {
    $a=array();
    foreach($a1 as $key=>$value) $a[$key]=$value;
    foreach($a2 as $key=>$value) $a[$key]=$value;
    if (is_array($a3)) $a=array_join($a,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$a10);
    return $a;
}
?>
poison 12-Sep-2006 05:45
You can use array_slice() in combination with array_merge() to insert values into an array like this:

<?php
$test=range(0, 10);
$index=2;
$data="---here---";
$result=array_merge(array_slice($test, 0, $index), array($data), array_slice($test, $index));
var_dump($result);
?>
dercsar at gmail dot com 04-Sep-2006 01:34
array_merge() overwrites ALL numerical indexes. No matter if you have non-numerical indexes or more than just one array.
It reindexes them all. Period.

(Only tried in 4.3.10)
20-Jul-2006 08:45
Whoops!!!  The 2nd posting before this one about the array_merge_alternative1() I made.  Replace part of that code with this one below...

--snip--
     /* 07/20/2006 - Added the if statement to avoid the warning message spitted out by array_unique() function, "Warning: Wrong datatype in array_unique() call"... */
     if ($xyz != 0) {
        $new_array2 = array_unique($new_array1);  /* Work a lot like DISTINCT() in SQL... */
     } else {
        $new_array2 = array();
     }
--snip--

Because the unique_array() unexpectly give a warning message when it's empty...  Sorry about that...
anonyme 20-Jul-2006 06:02
I don't think that the comment on + operator for array in array_merge page, was understandable, this is just a little test to know exactly what's happend.

<?php
//test code for (array)+(array) operator
$a1 = array( '10', '11' , '12' , 'a' => '1a', 'b' => '1b');
$a2 = array( '20', '21' , '22' , 'a' => '2a', 'c' => '2c');

$a = $a1 + $a2;
print_r( $a );
//result: Array ( [0] => 10
//                [1] => 11
//                [2] => 12
//                [a] => 1a
//                [b] => 1b
//                [c] => 2c )

$a = $a2 + $a1;
print_r( $a );
//result: Array ( [0] => 20
//                [1] => 21
//                [2] => 22
//                [a] => 2a
//                [c] => 2c
//                [b] => 1b )

?>
sfletcher at abcoa dot com 19-Jul-2006 09:28
I found that array_merge() didn't work in my case as it should have because I still get duplicate values.  Again, I noticed that the values can be overwritten if the array's key are the same as stated in the manual.

So, I came up with the alternative and it work like a charm.

--snip--
   function array_merge_alternative1() {
      //echo func_num_args();  /* Get the total # of arguements (parameter) that was passed to this function... */
      //print_r(func_get_arg());  /* Get the value that was passed in via arguement/parameter #... in int, double, etc... (I think)... */
      //print_r(func_get_args());  /* Get the value that was passed in via arguement/parameter #... in arrays (I think)... */

     $loop_count1 = func_num_args();
     $junk_array1 = func_get_args();
     $xyz = 0;

     for($x=0;$x<$loop_count1;$x++) {
        $array_count1 = count($junk_array1[$x]);

        if ($array_count1 != 0) {
           for($y=0;$y<$array_count1;$y++) {
              $new_array1[$xyz] = $junk_array1[$x][$y];
              $xyz++;
           }
        }
     }

     $new_array2 = array_unique($new_array1);  /* Work a lot like DISTINCT() in SQL... */

     return $new_array2;
   }
--snip--

Cheer...
chris at luethy dot net 12-Jul-2006 05:36
Do not use this to set the $_SESSION variable.

$_SESSION = array_merge( $_SESSION, $another_array );

will break your $_SESSION until the end of the execution of that page.
freed489 at gmail dot com 18-May-2006 08:32
I needed a function to alternatly merge 2 arrays. i.e. $a1 = (a, c, e) and $a2 = (b, d, f), and now $merged = (a, b, c, d, e, f).
Hope it helps...

<?
function alternatly_merge_arrays($array1, $array2){
        $combined_array = array();
    $count = 0;
    for($i = 0; $i < count($array1) + count($array2); $i = $i + 2){
            $combined_array[$i] = $array1[$count];
        $count++;
    }//end for
    $count = 0;
    for($i = 1; $i < count($array1) + count($array2); $i = $i + 2){
        $combined_array[$i] = $array2[$count];
        $count++;
    }//end for
    return $combined_array;
}//end alternate_merge_arrays
?>
j_oaquimsilva at yahoo dot com dot br 16-Jan-2006 01:22
I forgot to comment. This function join two arrays adding first the elements equals in the two arrays, then the values of the first array and at the end the values of the second array.
<?php
function array_merge_sim ($arr1, $arr2) {

               $i=0;
               $adid_arrayS = array();
               foreach ($arr1 as $x) {

                       $j=0;
                       $nr1=count($arr1);
                       $nr2=count($arr2);

                       foreach ($arr2 as $z) {
                         if($x==$z){
                               array_push($adid_arrayS,$z);
                               if($nr2==($j+1)) array_pop($arr2);
                               else array_splice($arr2, $j,-($nr2-$j-1));
                               if($nr1==($i+1)) array_pop($arr1);
                               else array_splice($arr1, $i,-($nr1-$i-1));
                               $i--;
                         }else  $j++;
                       }
               $i++;
               }

               return array_merge($adid_arrayS,$arr1,$arr2);

}
?>
seva-php at zend dot com 04-Jan-2006 01:18
Since my comment from 12-Jul-2004 02:42 with <? function array_merge_php4() ?> was deleted and the complex one added by Barpfotenbaer (09-Jul-2005 06:33), - here is the simpler and faster solution:

<?
/* works only with PHP 5 */
function array_merge_php4($array1, $array2) {
    foreach ($args = func_get_args() as &$arg)  {
        $arg = (array)$arg;
    }
    return call_user_func_array('array_merge',$args);
}

?>
hs at nospam dot magnum-plus dot com 29-Dec-2005 02:50
The same result as produced by snookiex_at_gmail_dot_com's function
can be achieved with the 'one-liner'
<?php
$array1=array(1,2,3);
$array2=array('a','b','c');

$matrix = array_map(null, $array1, $array2);
?>
(see documentation of array_map).
The difference here is, that the shorter array gets filled with empty values.
snookiex_at_gmail_dot_com 10-Dec-2005 06:09
if you have, for instance:

$array1=array(1,2,3);
$array2=array('a','b','c');

but you want a 2x3 matrix like this:
1 a
2 b
3 c

use:
function arrays2matrix($array1,$array2){
        if(sizeof($array1) != sizeof($array2))
                return;
    for($i=0;$i<sizeof($array1);$i++)
        $res[]=array_merge($array1[$i],$array2[$i]);
    return $res;
}
ttsgosadow at gmail dot com 17-Nov-2005 02:17
I was in need of a version of array_merge to add associative arrays without losing duplicate keys. I use the following function:

[code]
function array_add( $array1, $array2 )
{
foreach( $array2 AS $key => $value )
{
    while( array_key_exists( $key, $array1 ) )
        $key .= "_";
    $array1[ $key ] = $value;
}

return $array1;
}
[/code]

In my case the $key is a date I want to sort on, and if I happen to have duplicate dates (users add things on the same timestamp) I lose that entry with array_merge. I can sort on the key without getting big missorts because of the appended '_'.
kaigillmann at gmxpro dot net 02-Nov-2005 03:56
If you need to merge two arrays without having multiple entries, try this:

<?php
function array_fusion($ArrayOne, $ArrayTwo)
{
    return array_unique(array_merge($ArrayOne, $ArrayTwo));
}
?>
topera at gmail dot com 07-Oct-2005 04:25
<?
/*
Warning: if one variable is not an array, the merged array will
have one more line!
*/

$a = "";

$b[0] = "Brazil";
$b[1] = "China";

$c = array_merge($a, $b);

print_r($c);

?>

This returns:

Array
(
    [0] =>
    [1] => Brazil
    [2] => China
)
__________________________________
Rafael Pereira dos Santos
tbs2tbs at hotmail dot com 31-Aug-2005 11:55
I wanted to share this, it's an small simple script to add things into an array using an loop/routine.
I use an more developed version to sort msessage's on a forum.

<?php

// Make vars ready
    $a=0;
    $alltopic = array();

// Start an routine
//    4 is just an example you can use an varible containing
//    the number of rows in an databse for example
    while ($a < 4)
        {
            $topic = array($a => "$a");
            $alltopic = array_merge ($alltopic, $topic);
            $a++;
        };

// Put it on screen:
    print_r($alltopic);

?>

outputs this :

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
php at moechofe dot com 20-Jul-2005 04:58
<?php

  /*
  * array_deep_merge
  *
  * array array_deep_merge ( array array1 [, array array2 [, array ...]] )
  *
  * Like array_merge
  *
  *   array_deep_merge() merges the elements of one or more arrays together so
  * that the values of one are appended to the end of the previous one. It
  * returns the resulting array.
  *   If the input arrays have the same string keys, then the later value for
  * that key will overwrite the previous one. If, however, the arrays contain
  * numeric keys, the later value will not overwrite the original value, but
  * will be appended.
  *   If only one array is given and the array is numerically indexed, the keys
  * get reindexed in a continuous way.
  *
  * Different from array_merge
  *   If string keys have arrays for values, these arrays will merge recursively.
  */
  function array_deep_merge()
  {
    switch( func_num_args() )
    {
      case 0 : return false; break;
      case 1 : return func_get_arg(0); break;
      case 2 :
        $args = func_get_args();
        $args[2] = array();
        if( is_array($args[0]) and is_array($args[1]) )
        {
          foreach( array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key )
          if( is_string($key) and is_array($args[0][$key]) and is_array($args[1][$key]) )
            $args[2][$key] = array_deep_merge( $args[0][$key], $args[1][$key] );
          elseif( is_string($key) and isset($args[0][$key]) and isset($args[1][$key]) )
            $args[2][$key] = $args[1][$key];
          elseif( is_integer($key) and isset($args[0][$key]) and isset($args[1][$key]) ) {
            $args[2][] = $args[0][$key]; $args[2][] = $args[1][$key]; }
          elseif( is_integer($key) and isset($args[0][$key]) )
            $args[2][] = $args[0][$key];
          elseif( is_integer($key) and isset($args[1][$key]) )
            $args[2][] = $args[1][$key];
          elseif( ! isset($args[1][$key]) )
            $args[2][$key] = $args[0][$key];
          elseif( ! isset($args[0][$key]) )
            $args[2][$key] = $args[1][$key];
          return $args[2];
        }
        else return $args[1]; break;
      default :
        $args = func_get_args();
        $args[1] = array_deep_merge( $args[0], $args[1] );
        array_shift( $args );
        return call_user_func_array( 'array_deep_merge', $args );
        break;
    }
  }

  /*
  * test
  */
  $a = array(
    0,
    array( 0 ),
    'integer' => 123,
    'integer456_merge_with_integer444' => 456,
    'integer789_merge_with_array777' => 789,
    'array' => array( "string1", "string2" ),
    'array45_merge_with_array6789' => array( "string4", "string5" ),
    'arraykeyabc_merge_with_arraykeycd' => array( 'a' => "a", 'b' => "b", 'c' => "c" ),
    'array0_merge_with_integer3' => array( 0 ),
    'multiple_merge' => array( 1 ),
  );

  $b = array(
    'integer456_merge_with_integer444' => 444,
    'integer789_merge_with_array777' => array( 7,7,7 ),
    'array45_merge_with_array6789' => array( "string6", "string7", "string8", "string9" ),
    'arraykeyabc_merge_with_arraykeycd' => array( 'c' => "ccc", 'd' => "ddd" ),
    'array0_merge_with_integer3' => 3,
    'multiple_merge' => array( 2 ),
  );

  $c = array(
    'multiple_merge' => array( 3 ),
  );

  echo "<pre>".htmlentities(print_r( array_deep_merge( $a, $b, $c ), true))."</pre>";

?>
ntpt at centrum dot cz 14-Jul-2005 06:44
Old behavior of array_merge can be restored by simple  variable type casting like this

array_merge((array)$foo,(array)$bar);

works good in php 5.1.0 Beta 1, not tested in other versions

seems that empty or not set variables are casted to empty arrays
Barpfotenbaer 09-Jul-2005 09:33
Topic: The modified behavior of array_merge() in PHP5: "array_merge() now only accepts parameters of type array"

A very simple way to simulate the old behavior of PHP4 to merge arrays with non-arrays:

<?php
function array_merge_php4 ()
{
$array["merged"]=array ();
for($i=0;$i<func_num_args ();$i++)
  {
  $array["tmp"]=(
    (is_array (func_get_arg ($i)))?
    (func_get_arg ($i)):
    (array (func_get_arg ($i)))
  );
  $array["merged"]=array_merge ($array["merged"],$array["tmp"]);
  }
return($array["merged"]);
}
?>
herve dot pages at free dot fr 08-Jul-2005 11:37
About the behavior of array_merge() that was modified in PHP5. The above warning says "array_merge() now only accepts parameters of type array". But it doesn't say what happens when array_merge() is given a non array parameter like in:
<?php
  error_reporting(E_STRICT);
  $a = array("red","green");
  $rgb = array_merge($a,"blue");
?>
In fact, the PHP5 version of array_merge() will perfectly accept the "blue" parameter and will return... the NULL value! Be aware that you will get no warning even with the error reporting level set to E_STRICT (which is supposed to catch "forward compatibility" troubles).
arduenn at gmail dot com 06-Jul-2005 10:56
As "rcarvalhoREMOVECAPS at clix dot pt" suggested above,

   $a = array_merge($a, null);

does renumber the $a array. However, this only works with PHP4, not with PHP5. PHP5 users might try the following:

   $b = implode(" ", $a);
   $a = explode(" ", $b);

Hope this helps someone too ;-)
alberto dot pacheco at itesm dot mx 24-May-2005 09:02
To insert an array inside another at a given position

<?php

//Insert at $pos array $items inside array $source
function array_insert($source, $pos, $items)
{
    $sub1 = array_slice($source, 0, $pos);
    $sub2 = array_slice($source, $pos);
    return array_merge($sub1,$items,$sub2);
}

// 2nd alternative (Note: it changes $source)
function array_insert($source, $pos, $items)
{
    $rest = array_splice($source, $pos);
    return $source = array_merge($source,$items,$rest);
}

?>
rafmavCHEZlibre_in_france 19-Apr-2005 04:54
Here are a few functions to make a diff between two arrays (or 2 strings, see the example) and merge it back after
<?
function array_diff_both($new,$old)
{
    $del=array_diff_assoc($old,$new);
    $add=array_diff_assoc($new,$old);
    return $diff=array("del"=>$del, "add"=>$add);
}

function array_diff_all($arr_new,$arr_old)
{
    $arr_equ=array_intersect_assoc($arr_new,$arr_old);
    $arr_del=array_diff_assoc($arr_old,$arr_new);
    $arr_add=array_diff_assoc($arr_new,$arr_old);
    return $diff=array("equ"=>$arr_equ, "del"=>$arr_del, "add"=>$arr_add);
}

function array_merge_diff($arr,$diff) {
    $arr=array_merge_replace($arr,$diff["del"]);
    $arr=array_merge_replace($arr,$diff["add"]);
    return $arr;
}
function array_merge_diff_reverse($arr,$diff) {
    $arr=array_merge_replace($arr,$diff["add"]);
    $arr=array_merge_replace($arr,$diff["del"]);
    return $arr;
}
?>
Here is an example:
<?
//calculationg
$new="hello!"; // new string

$old="hrllo!"; // old string with a typo fault

// cast string in array the goodway
// make a cast (array) to a string does not work:
// the entire string is thus considered as one element
// of the array !!
$a_new=str_split($new);
$a_old=str_split($old); // cast string in array

$diff=array_diff_both($a_new,$a_old); // the entire diff

$test=array_merge_diff($a_old,$diff);

$test_reverse=array_merge_diff_reverse($a_new,$diff);

//for output the sample
print "new= $new<br/>old= $old<br/>\$a_new= ";
print_r($a_new);

print "<br/>\$a_old= ";
print_r($a_old);

print "<br/>\$diff=\$a_new-\$a_old";
print "<br/>\$diff= ";
print_r($diff);

print "<br/>\$test=\$a_old+\$diff";
print "<br/>\$test= ";
print_r($test);
print("<br/>".implode($test));

print "<br/>\$test_reverse=\$a_new+\$diff";
print "<br/>\$test_reverse= ";
print_r($test_reverse);
print("<br/>".implode($test_reverse));
?>
En sortie de l'exemple, r�sultats:

new= hello!
old= hrllo!
$a_new= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
$a_old= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [1] => r ) [add] => Array ( [1] => e ) )
$test=$a_old+$diff
$test= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
hello!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
hrllo!

autre exemple, autre r�sultat:
new= see you!
old= sea ya!
$a_new= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
$a_old= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [2] => a [5] => a [6] => ! ) [add] => Array ( [2] => e [5] => o [6] => u [7] => ! ) )
$test=$a_old+$diff
$test= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
see you!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! [7] => ! )
sea ya!!
Vinicius Cubas Brand 14-Apr-2005 09:32
The following function merges two arrays taking as parameter an user-defined comparison function:

<?
    function array_merge_custom(&$array1,&$array2,$comparison_func)
    {
        $ret_arr = array();
        foreach ($array1 as $key1 => $element1)
        {
            $has_equal_in_2 = false;
            foreach($array2 as $key2 => $element2)
            {
                if (call_user_func($comparison_func,$element1,$element2))
                {
                    $has_equal_in_2 = true;
                }
            }
            if (!$has_equal_in_2)
            {
                $ret_arr[] = $array1[$key1];
            }
        }
        $ret_arr = array_merge($ret_arr,$array2);
        return $ret_arr;
    }

?>

For instance:

<?

    $a = array(
        array('index' => 'ball', 'blabla' => 0),
        array('index' => 'coconut'),
        array('index' => 'cow'),
        array('index' => 'son'),
        );

    $b = array(
        array('index' => 'phone'),
        array('index' => 'wallet'),
        array('index' => 'ball'),
        array('index' => 'son', 'kabum'=> 1)
        );

    $c = array_merge_custom($a,$b,create_function('$a,$b','return $a[\'index\'] == $b[\'index\'];'));
    print_r($c)
?>

Will produce:

Array
(
    [0] => Array
        (
            [index] => coconut
        )
    [1] => Array
        (
            [index] => cow
        )
    [2] => Array
        (
            [index] => phone
        )
    [3] => Array
        (
            [index] => wallet
        )
    [4] => Array
        (
            [index] => ball
        )
    [5] => Array
        (
            [index] => son
            [kabum] => 1
        )
)
jeff_1089 at yahoo dot com 06-Apr-2005 01:17
Note that casting the array doesn't always work.  For classes, it looks like the class information is lost.  The print_r's below have different behavior.  I would suggest creating an array, rather than casting in most situations. (ie.  do it like $array2).

class myclass {
    private $name;
    private $value;
    function myclass($n, $v) {
        $this->name=$n;
        $this->value=$v;
    }
}

$itema = new myclass("hair", "orange");
$itemb = new myclass("eyes", "green");
$itemc = new myclass("elbow", "dirty");
$items = array($itemb, $itemc);
print "<BR>";
$array1 = array_merge((array)$itema, $items);
$array2 = array_merge(array($itema), $items);
print "<BR>";
print "<BR>";
print_r($array1);
print "<BR>";
print "<BR>";
print_r($array2);

Array ( [] => orange [0] => myclass Object ( [name:private] => eyes [value:private] => green ) [1] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )

Array ( [0] => myclass Object ( [name:private] => hair [value:private] => orange ) [1] => myclass Object ( [name:private] => eyes [value:private] => green ) [2] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )
lito at eordes dot com 20-Mar-2005 03:54
This is a simple function to merge an array multidimensional:

<?php
  function multimerge ($array1, $array2) {
    if (is_array($array2) && count($array2)) {
      foreach ($array2 as $k => $v) {
        if (is_array($v) && count($v)) {
          $array1[$k] = multimerge($array1[$k], $v);
        } else {
          $array1[$k] = $v;
        }
      }
    } else {
      $array1 = $array2;
    }

    return $array1;
  }

$array1 = array(
  1 => "value1",
  2 => "value2",
  3 => array(
    "valor2" => "test3",
  ),
  "more" => array(
    "alot" => "A lot of values",
    ":)" => "Cont"
  )
);

$array2 = array(
  2 => "other value",
  3 => array(
    "valor3" => "more values",
  ),
  "more" => array(
    "alot" => "Change the value"
  ),
  "final" => "Final Value"
);

print_r(multimerge($array1, $array2));
?>

The output is:

Array
(
    [1] => value1
    [2] => other value
    [3] => Array
        (
            [valor2] => test3
            [valor3] => more values
        )

    [more] => Array
        (
            [alot] => Change the value
            [:)] => Cont
        )

    [final] => Final Value
)
Jimomighty 19-Mar-2005 10:48
...

function preserved_merge_array( $newArray, $otherArray ) {
    foreach( $otherArray as $key => $value)
    {
        if ( !is_array($newArray[$key]) ) $newArray[$key] = array();
        if ( is_array($value) ) $newArray[$key] = preserved_merge_array( $newArray[$key], $value );
        else $newArray[$key] = $value;
    }

    return $newArray;
}

...
Alec Solway 20-Jan-2005 10:05
Note that if you put a number as a key in an array, it is eventually converted to an int even if you cast it to a string or put it in quotes.

That is:

$arr["0"] = "Test";
var_dump( key($arr) );

will output int(0).

This is important to note when merging because array_merge will append values with a clashing int-based index instead of replacing them. This kept me tied up for hours.
nospam at veganismus dot ch 11-Jan-2005 06:38
Someone posted a function with the note:
"if u need to overlay a array that holds defaultvalues with another that keeps the relevant data"

<?
//about twice as fast but the result is the same.
//note: the sorting will be messed up!
function array_overlay($skel, $arr) {
    return $arr+$skel;
}

//example:
$a = array("zero","one","two");
$a = array_overlay($a,array(1=>"alpha",2=>NULL));
var_dump($a);
/* NULL is ignored so the output is:
array(3) {
  [1]=>
  string(5) "alpha"
  [0]=>
  string(4) "zero"
  [2]=>
  string(3) "two"
}
*/
?>
Frederick.Lemasson{AT}kik-it.com 23-Dec-2004 02:57
if you generate form select from an array, you probably want to keep your array keys and order intact,
if so you can use ArrayMergeKeepKeys(), works just like array_merge :

array ArrayMergeKeepKeys ( array array1 [, array array2 [, array ...]])

but keeps the keys even if of numeric kind.
enjoy

<?

$Default[0]='Select Something please';

$Data[147]='potato';
$Data[258]='banana';
$Data[54]='tomato';

$A=array_merge($Default,$Data);

$B=ArrayMergeKeepKeys($Default,$Data);

echo '<pre>';
print_r($A);
print_r($B);
echo '</pre>';

Function ArrayMergeKeepKeys() {
      $arg_list = func_get_args();
      foreach((array)$arg_list as $arg){
          foreach((array)$arg as $K => $V){
              $Zoo[$K]=$V;
          }
      }
    return $Zoo;
}

//will output :

Array
(
    [0] => Select Something please
    [1] => potato
    [2] => banana
    [3] => tomato
)
Array
(
    [0] => Select Something please
    [147] => potato
    [258] => banana
    [54] => tomato
)

?>
jnothman at student dot usyd dot edu dot au 24-Nov-2004 10:40
If you have a two dimensional array, or otherwise an array of arrays, the following may be handy: <?call_user_func_array('array_merge', $arr);?>

For instance:
<?php
list($GIF, $JPG, $PNG, $WBMP) = array(1,2,3,15);
$ext_map = array(
    $GIF  => array('gif'),
    $JPG  => array('jpg', 'jpeg'),
    $PNG  => array('png'),
    $WBMP => array('wbmp'),
);
$ext_list = call_user_func_array('array_merge', $ext_map);
print_r($ext_list);
?>

Output:
Array
(
    [0] => gif
    [1] => jpg
    [2] => jpeg
    [3] => png
    [4] => wbmp
)
Jae 22-Nov-2004 07:17
This is explained above but may not be exactly clear.  If you have two arrays such as:

$Array1 {

[0] => "dog"

}

$Array2 {

[0] => "cat",
[1] => "bird",
[2] => null,
...
[n-1] => null,
[n] => "gator"
}

and you don't want to lose the null values in the final array then do NOT use array_merge.  Instead simply use the + operator.

array_merge($Array1,$Array2) gives:
[0] => "dog",
[1] => "cat",
[2] => "bird",
[3] => "gator"

$Array1 + $Array2 gives:
[0] => "dog",
[1] => "cat",
[2] => "bird",
[3] => null,
...
[n-1] => null,
[3] => "gator"
17-Nov-2004 10:22
function array_overlay($skel, $arr)
{
    foreach ($skel as $key => $val) {
        if (!isset($arr[$key])) {
            $arr[$key] = $val;
        } else {
            if (is_array($val)) {
                $arr[$key] = array_overlay($val, $arr[$key]);
            }
        }
    }

    return $arr;
}

// if u need to overlay a array that holds defaultvalues with another that keeps the relevant data
nospam at veganismus dot ch 25-Sep-2004 08:48
I needed to add some values (array) to an array on each loop.
I used merge because it seemed to be the right way. But array_splice() ist much faster:

<?
$merge = array();
$splice = array();

function makearray() { //to do on each loop
 //return two values:
 return array('foo','bar');
}

for($i=0;$i<1000;$i++) $merge = array_merge($merge,makearray());
echo count($merge); //returns 2000 after about 2 sec (PHP5)

for($i=0;$i<1000;$i++) array_splice($splice, 0,0,makearray());
echo count($splice); //returns 2000 after about 0.8 sec (PHP5)
?>

Note: The sorting will be diffrent but you can use
array_splice($splice, count($splice),0,makearray());
which is still faster (1.4 sec)
bcraigie at bigfoot dot com 24-Aug-2004 12:37
It would seem that array_merge doesn't do anything when one array is empty (unset):

<?php //$a is unset
$b = array("1" => "x");

$a = array_merge($a, $b});

//$a is still unset.
?>

to fix this omit $a if it is unset:-

<?php
if(!IsSet($a)) {
    $a = array_merge($b);
} else {
  $a = array_merge($a, $b);
}
?>

I don't know if there's a better way.
niv at NOSPAM iaglans dot DE 12-Jun-2004 10:18
[Editor's Note: If the keys are truly numeric, array_merge will do the trick. But if they are strings, as the example below, you can use array_merge(array_values($array1), array_values($array2)); since it's more beautiful. -- victor@php.net]

i recognized there is no function with that you can add two number-Arrays:

Example:

<?php
// you have two arrays:

array1 = array (['0'] =>"blahblupp",
                        ['1'] => "bluppblah" );

array2 = array (['0'] =>"tirili",
                        ['1'] => "tralala" );

// and want following as a result:

result = array (['0'] =>"blahblupp",
                      ['1'] => "bluppblah",
                      ['2'] =>"tirili",
                      ['3'] => "tralala" );

// following function does the addition:

function array_add($array1, $array2)
{
    $result = $array1;
    $h = sizeof($array1);
    for ($i = 0; $i < sizeof($array2); $i++)
    {
        $result[$h] = $array2[$i];
        $h++;
    }

    return $result;
}
?>

just added because I didn't find a ready-to-use script here.
mail at nospam dot iaindooley dot com 08-Apr-2004 09:37
hey there, here is a nice little way of merging two arrays that may or may not have numerical or string indices and preserving the order and indexing of both arrays whilst making the most use of in built php functions (i actually originally wanted to use array_combine for obvious reasons but seeing as that is not available in PHP4, the little foreach loop at the end is necessary):

<?php
        function merge($arr1,$arr2)
        {
                if(!is_array($arr1))
                        $arr1 = array();
                if(!is_array($arr2))
                        $arr2 = array();
                $keys1 = array_keys($arr1);
                $keys2 = array_keys($arr2);
                $keys  = array_merge($keys1,$keys2);
                $vals1 = array_values($arr1);
                $vals2 = array_values($arr2);
                $vals  = array_merge($vals1,$vals2);
                $ret    = array();

                foreach($keys as $key)
                {
                        list($unused,$val) = each($vals);
                        $ret[$key] = $val;
                }

            return $ret;
        }
?>
frankb at fbis dot net 25-Feb-2004 04:02
to merge arrays and preserve the key i found the following working with php 4.3.1:

<?php
$array1 = array(1 => "Test1", 2 => "Test2");
$array2 = array(3 => "Test3", 4 => "Test4");

$array1 += $array2;
?>

dont know if this is working with other php versions but it is a simple and fast way to solve that problem.
KOmaSHOOTER at gmx dot de 07-Nov-2003 10:03
Here is something for splitting a sorted array into group array  ( sorting the group arrays ) and then merging them together
Note: merge is  like concat in Flash ActionScript :)
In this example i have 3 different  groups in one array

* First the mainArray is sorted for the group entrys
* building from part arrays
* building  copy arrays from  part arrays ( for making the array beginning with  [0] !! )
* merging all part arrays together

0. sorting the main array
1. apportionment from the main array
when the group is changing , a new array is build (part
array ) ! attention at the second  part array !! Array values
are are not beginning with [0]!!
2. making the copy from the part array .
array values are pushed in the new array
3. echo for every array entry
4. overwriting the old array with the new copy
5. part arrays are sorted by function (arrays had been naughted by function array_copy ( Array is beginning with [0] ! )
6. merging the part arrays

Here is the same that i posted before but a bit better solved
array_push (${"activ_array".$j}, $activ_array[$i]); makes the part arrays starting with [0] :)

<?php
$activ_array=array(
array("apfel_01","germany","xx","red"),
array("apfel_07","germany","xx","green"),
array("apfel_08","germany","xx","green"),
array("apfel_02","germany","xx","red"),
array("apfel_03","germany","xx","red"),
array("apfel_04","germany","xx","red"),
array("apfel_09","germany","xx","red_+_green"),
array("apfel_10","germany","xx","red_+_green"),
array("apfel_05","germany","xx","green"),
array("apfel_06","germany","xx","green")
);
function array_sort($array, $key , $target){
for ($i = 0; $i < sizeof($array); $i++){
 $array2 = $array;
 if($target == 'name'){
    if(! empty($array2[$i]["nameletter"])){
     //echo $myarray[$i]["nameletter"] ;
     $array2[$i]["name"] = substr($array2[$i][$key],($array2[$i]["nameletter"]-1));
    }else{
     $array2[$i]["name"] = substr($array2[$i][$key],0);
    }
   $sort_values[$i] = $array2[$i]["name"];
   }else{
   $sort_values[$i] = $array2[$i][$key];
 }
}
  asort ($sort_values);
  reset ($sort_values);
  while (list ($arr_keys, $arr_values) = each ($sort_values)) {
         $sorted_arr[] = $array[$arr_keys];
  }
  return $sorted_arr;
}
$activ_array = array_sort($activ_array,3,'imagetype');
$j=0;
// first part array
${"activ_array"."$j"} = array();
for($i=0;$i<sizeof($activ_array);$i++){
 if($activ_array[$i][3] !=$activ_array[$i-1][3] && $i >1){
   $j++;
   ${"activ_array".$j} = array();
 }
array_push (${"activ_array".$j}, $activ_array[$i]);
}
// part array sorting
for($i=0;$i<=$j;$i++){
 ${"activ_array".$i} = array_sort(${"activ_array".$i},0,'name');
}
$activ_array = array();
for($i=0;$i<=$j;$i++){
 $activ_array = array_merge($activ_array,${"activ_array".$i});
}
for($i=0;$i<sizeof($activ_array);$i++){
print_r($activ_array[$i]);
echo("<br>");
}

?>
rcarvalhoREMOVECAPS at clix dot pt 03-Nov-2003 12:43
While searching for a function that would renumber the keys in a array, I found out that array_merge() does this if the second parameter is null:

Starting with array $a like:

<?php
Array
(
    [5] => 5
    [4] => 4
    [2] => 2
    [9] => 9
)
?>

Then use array_merge() like this:

<?php
$a = array_merge($a, null);
?>

Now the $a array has bee renumbered, but maintaining the order:

<?php
Array
(
    [0] => 5
    [1] => 4
    [2] => 2
    [3] => 9
)
?>

Hope this helps someone :-)
31-Oct-2003 10:08
In all PHP 4 versions the above function deals gracefully with paramaters which are NOT arrays(). So if you pass a string or number it will be automagically converted to an one-element array as described in the manual section about Types and "implicit typecasting". So if you ever happen to put an empty/unset variable (NULL value) as parameter, array_merge() will still collapse the other arrays as intended.

From PHP5beta2 on this behaviour changed, and PHP will correctly issue a E_WARNING message, whenever one of the paramters isn't an array. So if you ever happen to be uncertain about the contents of a variable passed as parameter to array_merge() you should use explicit typecasting:

<?php
$a = array(1, 2, 3);
$b = 4;    #-- beware: this is no array!

$result = array_merge(  (array)$a, (array)$b,  ... );
?>

This way $result still would get == array(1, 2, 3, 4); where otherwise the parameters would get rejected with the warning message telling you so.
loner at psknet dot !NOSPAM!com 29-Sep-2003 03:00
I got tripped up for a few days when I tried to merge a (previously serialized) array into a object. If it doesn't make sense, think about it... To someone fairly new, it could... Anyway, here is what I did:
(It's obviously not recursive, but easy to make that way)
<?php
function array_object_merge(&$object, $array) {
    foreach ($array as $key => $value)
        $object->{$key} = $value;
}
?>

Simple problem, but concevibly easy to get stuck on.
ice at lazybytes dot net 05-Sep-2003 03:31
I, too have found array_merge_clobber() useful. I use it in a loop to append data to an array. However, when the loop first runs, there will be an error message displayed as array one is empty, so, here is a little fix:

<?php
function array_merge_clobber($arrOne,$arrTwo) {
    if(!is_array($arrOne) || !is_array($arrTwo)) return false;

    $arrNewArray = $arrOne;
    forEach ($arrTwo as $key => $val) {
        if (isSet($arrNewArray[$key])) {
            if (is_array($val) && is_array($arrNewArray[$key])) {
                $arrNewArray[$key] = array_merge_clobber($arrNewArray[$key], $val);
            }
            else {
                $arrNewArray[$key] = $val;
            }
        }
        else {
            $arrNewArray[$key] = $val;
        }
    }
    return $arrNewArray;
}
?>

Not sure if someone else has already got something similar or better, but this is simple and works for me. :)
03-Sep-2003 03:10
For those who are getting duplicate entries when using this function, there is a very easy solution:

wrap array_unique() around array_merge()

cheers,

k.
tobias_mik at hotmail dot com 25-Jul-2003 05:14
This function merges any number of arrays and maintains the keys:

<?php
function array_kmerge ($array) {
 reset($array);
 while ($tmp = each($array))
 {
  if(count($tmp['value']) > 0)
  {
   $k[$tmp['key']] = array_keys($tmp['value']);
   $v[$tmp['key']] = array_values($tmp['value']);
  }
 }
 while($tmp = each($k))
 {
  for ($i = $start; $i < $start+count($tmp['value']); $i ++)$r[$tmp['value'][$i-$start]] = $v[$tmp['key']][$i-$start];
  $start = count($tmp['value']);
 }
 return $r;
}
?>
array_merge_recursive
array_multisort
Функции для работы с массивами


Сортирует несколько массивов или многомерные массивы

array_merge
array_pad
Функции для работы с массивами
PHP Manual

array_multisort

(PHP 4, PHP 5)

array_multisort — Сортирует несколько массивов или многомерные массивы

Описание

bool array_multisort ( array &$arr [, mixed $arg = SORT_ASC [, mixed $arg = SORT_REGULAR [, mixed $... ]]] )

Функция array_multisort() может быть использована для сортировки сразу нескольких массивов или одного многомерного массива в соответствии с одной или несколькими размерностями.

Ассоциативные (string) ключи будут сохранены, но числовые ключи будут переиндексированы.

Список параметров

arr

Сортируемый массив (array).

arg

Необязательные другие массивы (array), или опции сортировки для предыдущего аргумента (array): SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING.

...

Дополнительные параметры (arg).

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Сортировка нескольких массивов

<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

В вышеприведенном примере, после того, как будет осуществлена сортировка, первый массив будет содержать 0, 10, 100, 100. Второй - 4, 1, 2, 3. Элементы второго массива, соответствующие идентичным элементам первого (100 и 100), также будут отсортированы.

array(4) {
  [0]=> int(0)
  [1]=> int(10)
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(4)
  [1]=> int(1)
  [2]=> int(2)
  [3]=> int(3)
}

Пример #2 Сортировка многомерного массива

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

В вышеприведенном примере, после сортировки, первый массив будет содержать "10", 100, 100, 11, "a" (его элементы были отсортированы в возрастающем порядке), а второй массив будет содержать 1, 3, "2", 2, 1 (элементы отсортированы как числа, в порядке убывания).

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Пример #3 Сортировка результатов из базы данных

В этом примере, каждый элемент массива data представляет собой ряд таблицы. Такой тип данных типичен для записей базы данных.

Примерные данные:

# том  | издание
volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

Данные представлены в виде массива с именем data. Обычно их можно получить, к пример, с помощью цикла из функции mysql_fetch_assoc().

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

В нашем примере мы будем сортировать по volume в убывающем порядке, а по edition - в возрастающем.

У нас есть массив строк, но array_multisort() необходим массив столбцов, поэтому сначала мы используем следующий код для получения столбцов, а потом выполним сортировку.

<?php
// Получение списка столбцов
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Сортируем данные по volume по убыванию и по edition по возрастанию
// Добавляем $data в качестве последнего параметра, для сортировки по общему ключу
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

Теперь данные отсортированы и будут выглядеть вот так:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Пример #4 Сортировка без учета регистра

Обе константы SORT_STRING и SORT_REGULAR учитывают регистр при сортировке, строки, начинающиеся с заглавной буквы будут выставлены раньше строк, начинающихся со строчной буквы.

Для выполнения безрегистрового поиска нужно заставить выполнить порядок сортировки по копии оригинального массива, переведенного в нижний регистр.

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

Результат выполнения данного примера:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

Смотрите также

  • usort() - Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов
  • Сравнение функций сортировки массивов

User Contributed Notes

rnacken at gmail dot com 11-Feb-2012 11:59
When I was working on a search engine, that had to order the results in PHP by multiple arguments, I got stuck on the issue of multisort erasing your (numeral) indexes for a while. Sometimes, it is important to keep these indexes intact. In my case, the indexes were IDs and the values were a percentage of how relevant the object was, considering an earlier query.
e.g: $searchResult = (23 => 0.3,
                    102 => 0.5,
                    11 => 0.5,
                    340 => 0.5,
                    10 => 0.9);

I wanted to use array_multisort to first sort DESC on the IDs, and then on the values DESC. i.e. I wanted to show the highest values first, but in case of two (or more) objects with the same value, the higher ID would be shown first.
e.g: $searchResult = (10 => 0.9,
                   340 => 0.5,
                   102 => 0.5,
                   11 => 0.5,
                   23 => 0.3);

The easiest way to do this, I think, is:
<?php
    // create a 2-deep array with the values and keys of $searchResult
    $array = array(
               $searchResult,
               array_keys($searchResult)
    );
    // use multisort, first on the values, then on the keys. This will erase the indexes in the $searchResult array
    array_multisort($array[0], SORT_DESC,  $array[1], SORT_DESC);
    // get the ordered keys back in the $searchResult array
    $searchResult = array_combine($array[1], $array[0]);
    unset($array); //clear some memory
?>
nick ([AT]) nickyost ([DOT]) com 15-Sep-2011 03:36
USort function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution over this function.

Hope it helps!
info at ichier dot de 28-Jul-2011 08:59
if you want to sort an array by columns, this is the function to do it.

<?php
function array_csort() {        //coded by Ichier2003
    $args = func_get_args();
    $marray = array_shift($args);
    $msortline = 'return(array_multisort(';
    foreach ($args as $arg) {
        $i++;
        if (is_string($arg)) {
            foreach ($marray as $row) {
                $sortarr[$i][] = $row[$arg];
            }
        } else {
            $sortarr[$i] = $arg;
        }
        $msortline .= '$sortarr['.$i.'],';
    }
    $msortline .= '$marray));';
    eval($msortline);
    return $marray;
}
?>
thierryzo at hotmail dot fr 29-Jun-2011 02:27
//A very simple way to sort arrays with this kind of structure.

<?php
    $myArray =array(
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "BLUE","L1" => 6),
        array("NUMCIE" => "001","REF" => "RHQ","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "002","REF" => "RXL","COLOR" => "YELLOW","L1" => 8));

    foreach($myArray as $c=>$key) {
        $sort_numcie[] = $key['NUMCIE'];
        $sort_ref[] = $key['REF'];
        $sort_color[] = $key['COLOR'];
    }

    array_multisort($sort_numcie, SORT_ASC, $sort_ref, SORT_STRING, $myArray);
    print_r($myArray);

?>

//Result array

Array
(
    [0] => Array
        (
            [NUMCIE] => 001
            [REF] => RHQ
            [COLOR] => RED
            [L1] => 4
        )

    [1] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => BLUE
            [L1] => 6
        )

    [2] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => RED
            [L1] => 4
        )

    [3] => Array
        (
            [NUMCIE] => 002
            [REF] => RXL
            [COLOR] => YELLOW
            [L1] => 8
        )

)
Jaak Tamre 22-Mar-2011 06:42
I had a problem with sorting SimpleXMLElement list. I found a nice short solution.

I have an array of ticket objects: $ticketList = $xml->Tickets;

<?php
// Sort by ValidOnDate
$tickets = array();
$valid = array();
foreach ($ticketList as $row) {
    $tickets[] = $row;
    $valid[] = DateHandler::parseDate($row->ValidOnDate);
}
array_multisort($valid, SORT_DESC, $tickets);
?>

Just make an array of object items you want to sort by and a new array for the same objects which will be reordered like the first array.

Ps: my own parseDate(date) returns unix timestamp for different date formats.
jimpoz at jimpoz dot com 21-Oct-2010 02:26
I came up with an easy way to sort database-style results. This does what example 3 does, except it takes care of creating those intermediate arrays for you before passing control on to array_multisort().

<?php
function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
?>

The sorted array is now in the return value of the function instead of being passed by reference.

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

// Pass the array, followed by the column names and sort flags
$sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
?>
m__faraz at hotmail dot com 08-Jun-2010 08:10
The last example for multisort an array by a text field works well.
However, it is case sensitive.
So here is my version of the same with case insensitivity.

<?php
$tmp = Array();
foreach($aMultiArray as &$aSingleArray)    $tmp[] = &$aSingleArray["name"];
$tmp = array_map('strtolower', $tmp);
array_multisort($tmp, $aMultiArray);
?>

Hope this helps someone out there.
zequez at gmail dot com 06-May-2010 03:19
Easiest way I find out to sort an entire multidimensional array by one element of it:

<?php
$multiArray = Array(
    Array("id" => 1, "name" => "Defg"),
    Array("id" => 2, "name" => "Abcd"),
    Array("id" => 3, "name" => "Bcde"),
    Array("id" => 4, "name" => "Cdef"));
$tmp = Array();
foreach($multiArray as &$ma)
    $tmp[] = &$ma["name"];
array_multisort($tmp, $multiArray);
foreach($multiArray as &$ma)
    echo $ma["name"]."<br/>";

/* Outputs
    Abcd
    Bcde
    Cdef
    Defg
*/
?>

^-^
alexander dot v at zend dot com 20-Jan-2010 03:42
array_multisort works normally in php 5.3, but it forces arguments to be references.

It doesn't make differences for common array_multisort() usage, but makes "problems" for sorting variable number of arrays where call_user_func_array() function is involved.

So all sorting arrays have to be collected into new one as a references to array variables:

<?php
$sortArgs = array();

for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>

This (requiring arguments to be a reference) is not actually a problem since source array will not be sorted otherwise.

Important note!
Don't forget to destroy $valuesArray variable if you use it over each array_multisort() argument processing iteration.
If you don't do it, all array_multisort() arguments will contain the same array:

<?php
for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}
?>

And the last important thing :)
Collect sorting arrays somewhere. PHP 5.3 will transfer reference into value (when $valuesArray is destroyed) and you will get "Parameter 1 to array_multisort() expected to be a reference, value given" warning again otherwise.

Final code should look like this:

<?php
$sortArgs = array();
$sortFieldValues = array();

for (...) {
    ...
    $sortFieldValues[] = &$valuesArray;
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>
d_inkubus at yahoo dot com 21-Dec-2009 03:33
Update to array_msort()--in PHP 5.3 it won't work.

The solution is to replace the array_merge($params, $order) with the following code snippet:

<?php
$order=(array)$order;
foreach($order as $order_element)
{
    $params[]=&$order_element;
}
?>

Full code to array_msort():

<?php
function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order)
    {
        $colarr[$col] = array();
        foreach ($array as $k => $row)
        {
            $colarr[$col]['_'.$k] = strtolower($row[$col]);
        }
    }
    $params = array();
    foreach ($cols as $col => $order)
    {

        $params[] =&$colarr[$col];
        $order=(array)$order;
        foreach($order as $order_element)
        {
            //pass by reference, as required by php 5.3
            $params[]=&$order_element;
        }
    }
    call_user_func_array('array_multisort', $params);
    $ret = array();
    $keys = array();
    $first = true;
    foreach ($colarr as $col => $arr)
    {
        foreach ($arr as $k => $v)
        {
            if ($first)
            {
                $keys[$k] = substr($k,1);
            }
            $k = $keys[$k];

            if (!isset($ret[$k]))
            {
                $ret[$k] = $array[$k];
            }

            $ret[$k][$col] = $array[$k][$col];
        }
        $first = false;
    }
    return $ret;
}
?>

For further reference, see these bug reports:
http://bugs.php.net/bug.php?id=49069
http://bugs.php.net/bug.php?id=49241
s dot i dot g at gmx dot com 10-Jul-2009 06:21
simple dns mx record sorting

<?php
//getting domain name
list($user, $domain) = split('[@]', $email);
getmxrr($domain, $mx_server, $mx_weight);

//sorting
for($i = 0; $i < count($mx_server); $i++)
{
    $mx[$i] = array
    (
      "server" => $mx_server[$i],
      "weight" => $mx_weight[$i],
    );
}
array_multisort($mx_weight, SORT_ASC, $mx_server, SORT_ASC, $mx);

//display result
print_r($mx);

//usage
$server = $mx[0]["server"];
?>
cagret at gmail dot com 21-Jun-2009 03:38
Update to array_msort(): instead of eval() using call_user_func_array(). If we get column sorting via $_GET it would be a serious security hole.

Now it also accepts multiple options for each column:

<?php
$arr2 = array_msort($arr1, array('name'=>array(SORT_DESC,SORT_REGULAR), 'cat'=>SORT_ASC));
?>

Btw. this function is automatically case-insensitive, as you can see use of strtolower().

<?php
function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    $params = array();
    foreach ($cols as $col => $order) {
        $params[] =& $colarr[$col];
        $params = array_merge($params, (array)$order);
    }
    call_user_func_array('array_multisort', $params);
    $ret = array();
    $keys = array();
    $first = true;
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            if ($first) { $keys[$k] = substr($k,1); }
            $k = $keys[$k];
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
        $first = false;
    }
    return $ret;

}
?>
cagret at gmail dot com 20-Jun-2009 12:16
A more inuitive way of sorting multidimensional arrays using array_msort() in just one line, you don't have to divide the original array into per-column-arrays:

<?php

$arr1 = array(
    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$arr2 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));

debug($arr1, $arr2);

arr1:
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
arr2:
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)

function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    $eval = 'array_multisort(';
    foreach ($cols as $col => $order) {
        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
    }
    $eval = substr($eval,0,-1).');';
    eval($eval);
    $ret = array();
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            $k = substr($k,1);
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;

}

?>
m dot michalczyk at gmail dot com 16-May-2009 03:45
Here is useful example based on za at byza dot it solution to sort multidimensional objects by any dimension.
za at byza dot it
<?php
/* Example structure */
class person{
    function __construct($firstName, $lastName, $title, $position){
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->title = new title($title);
        $this->position = new position($position);
    }
}
class title{
    function __construct($name){
        $this->name = $name;
    }

}
class position{
    function __construct($name){
        $this->name = $name;
    }

}

$array[] = new person('Piotr', 'Sobiepanek', 'b', 'b');
$array[] = new person('Piotr', 'Kowalski', 'b', 'a');
$array[] = new person('Piotr', 'Michalski', 'a', 'a');
$array[] = new person('Jozef', 'Smietana', 'a', 'b');
$array[] = new person('Jozef', 'Cmietana', 'a', 'b');
$array[] = new person('Marcin', 'Kondraciuk', 'c', 'b');
$array[] = new person('Maksym', 'Kondraciuk', 'c', 'd');
$array[] = new person('Ambrozy', 'Kondraciuk', 'c', 'd');
$array[] = new person('Alojzy', 'Kondraciuk', 'c', 'd');

array_sort($array, 'title->name', 'position->name', 'lastName');
print_r($array);

/* Source */

function hod(&$base, $path){
    $keys = explode("->", $path);
    $keys[0] = str_replace('$', '', $keys[0]);
    $expression = '$ret = ';
    $expression.= '$';
    foreach ($keys as $key){
        if (++$licz == 1){
            $expression.= 'base->';
        } else {
            $expression.= $key.'->';
        }
    }
    $expression = substr($expression, 0, -2);
    $expression.= ';';
    eval($expression);
    return $ret;
}

function array_sort_func($a,$b=NULL) {
   static $keys;
   if($b===NULL) return $keys=$a;
   foreach($keys as $k) {
      if($k[0]=='!') {
         $k=substr($k,1);
         if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
            return strcmp(hod($b, '$b->'.$k),hod($a, '$a->'.$k));
         }
      }
      else if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
         return strcmp(hod($a, '$a->'.$k),hod($b, '$b->'.$k));
      }
   }
   return 0;
}

function array_sort(&$array) {
   if(!$array) return $keys;
   $keys=func_get_args();
   array_shift($keys);
   array_sort_func($keys);
   usort($array,"array_sort_func");
}
?>
za at byza dot it 27-Apr-2009 10:08
I wrote a function to sort a multidimensional array by multiple columns in ascending and descending order.

Sample array:

<?php
$my_array=array(
   array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'),
   array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'),
   array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'),
   array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'),
   array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest')
);
?>

Example: <?php array_sort($my_array,'!group','surname'); ?>

Output: sort the array DESCENDING by group and then ASCENDING by surname. Notice the use of ! to reverse the sort order. Rows order will be: 2,3,5,4,1

The function code:

<?php
function array_sort_func($a,$b=NULL) {
   static $keys;
   if($b===NULL) return $keys=$a;
   foreach($keys as $k) {
      if(@$k[0]=='!') {
         $k=substr($k,1);
         if(@$a[$k]!==@$b[$k]) {
            return strcmp(@$b[$k],@$a[$k]);
         }
      }
      else if(@$a[$k]!==@$b[$k]) {
         return strcmp(@$a[$k],@$b[$k]);
      }
   }
   return 0;
}

function array_sort(&$array) {
   if(!$array) return $keys;
   $keys=func_get_args();
   array_shift($keys);
   array_sort_func($keys);
   usort($array,"array_sort_func");
}
?>
mech.cx 28-Mar-2009 12:04
I was (as near everyone here :-) looking to sort 2-dimensional arrays by certain fields in the associative sub-arrays.
What I didn't like about the documentation examples is that you need to loop through the input array to create sub arrays first, then use those in the function call.

"php a-t-the-r-a-t-e chir.ag" (http://www.php.net/manual/en/function.array-multisort.php#60401) wrote a quite cunning wrapper function, I rewrote it slightly, changing variable names and adding comments (for my sanity :-) mostly.
One snag I found: the input array is passed to array_multisort as last argument, but the changed array is not the one that is returned. Passing it by reference fixed that. This seems to be caused by the whole thing sitting inside the call_user_func_array, as shown below.

<?php

$points = array(1, 5, 2, 2);
$names  = array('peter', 'mike', 'john Zoo', 'john Ab');

$source = array (
  array ( 'points' => 1, 'name' => 'Peter'),
  array ( 'points' => 5, 'name' => 'Mike'),
  array ( 'points' => 2, 'name' => 'John Zoo'),
  array ( 'points' => 2, 'name' => 'John Ab')
);

call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, $source)); // doesn't work
print_r($source);
call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, &$source)); // works!
print_r($source);

// Call like arrayColumnSort('points', SORT_DESC, SORT_NUMERIC, 'name', SORT_ASC, SORT_STRING, $source);

// Slightly adapted from http://www.php.net/manual/en/function.array-multisort.php#60401

// arrayColumnSort(string $field, [options, ], string $field2, [options, ], .... , $array) /

//____________________
// arrayColumnSort() /
function arrayColumnSort() {
  $args  = func_get_args();
  $array = array_pop($args);
  if (! is_array($array)) return false;
  // Here we'll sift out the values from the columns we want to sort on, and put them in numbered 'subar' ("sub-array") arrays.
  //   (So when sorting by two fields with two modifiers (sort options) each, this will create $subar0 and $subar3)
  foreach($array as $key => $row) // loop through source array
    foreach($args as $akey => $val) // loop through args (fields and modifiers)
      if(is_string($val))             // if the arg's a field, add its value from the source array to a sub-array
        ${"subar$akey"}[$key] = $row[$val];
  // $multisort_args contains the arguments that would (/will) go into array_multisort(): sub-arrays, modifiers and the source array
  $multisort_args = array();
  foreach($args as $key => $val)
    $multisort_args[] = (is_string($val) ? ${"subar$key"} : $val);
  $multisort_args[] = &$array;   // finally add the source array, by reference
  call_user_func_array("array_multisort", $multisort_args);
  return $array;
}

?>
frank at overdrunk dot net 14-Jan-2009 02:38
I had a function to make a sort on a 2D array and I wanted to sort an array using a column that usualy contains numeric values but also strings.

Lets say we have this array :

Array (
  [0] => Array ( "name" = "12000" ),
  [1] => Array ( "name" = "113" ),
  [2] => Array ( "name" = "test 01" ),
  [3] => Array ( "name" = "15000 tests" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "350" ),
  [6] => Array ( "name" = "725" ),
  [7] => Array ( "name" = "hello" )
}

SORT_STRING whould have returned me this :

Array ( // Numeric values are not correctly sorted
  [0] => Array ( "name" = "113" ),
  [1] => Array ( "name" = "12000" ),
  [2] => Array ( "name" = "15000 tests" ),
  [3] => Array ( "name" = "350" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "hello" ),
  [7] => Array ( "name" = "test 01" )
}

SORT_NUMERIC would have returned me this :

Array ( // String values are not sorted, just in the same order
  [0] => Array ( "name" = "test 01" ),
  [1] => Array ( "name" = "hello" ),
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
}

So I've made this hybrid code which combines the best of both worlds by merging content sorted either way according to the first caracter of the string:

<?php
/**
 * Sorts an array according to a specified column
 * Params : array  $table
 *          string $colname
 *          bool   $numeric
 **/
function sort_col($table, $colname) {
  $tn = $ts = $temp_num = $temp_str = array();
  foreach ($table as $key => $row) {
    if(is_numeric(substr($row[$colname], 0, 1))) {
      $tn[$key] = $row[$colname];
      $temp_num[$key] = $row;
    }
    else {
      $ts[$key] = $row[$colname];
      $temp_str[$key] = $row;
    }
  }
  unset($table);

  array_multisort($tn, SORT_ASC, SORT_NUMERIC, $temp_num);
  array_multisort($ts, SORT_ASC, SORT_STRING, $temp_str);
  return array_merge($temp_num, $temp_str);
}
?>

It would return something like this :

Array (
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
  [1] => Array ( "name" = "hello" ),
  [0] => Array ( "name" = "test 01" ),
}
Zbigniew Heintze http://bigweb.pl 26-Nov-2008 11:36
<?php
/**
 * Sort DB result
 *
 * @param array $data Result of sql query as associative array
 *
 * Rest of parameters are optional
 * [, string $name  [, mixed $name or $order  [, mixed $name or $mode]]]
 * $name string - column name i database table
 * $order integer - sorting direction ascending (SORT_ASC) or descending (SORT_DESC)
 * $mode integer - sorting mode (SORT_REGULAR, SORT_STRING, SORT_NUMERIC)
 *
 * <code>
 * <?php
 * // You can sort data by several columns e.g.
 * $data = array();
 * for ($i = 1; $i <= 10; $i++) {
 *     $data[] = array( 'id' => $i,
 *                      'first_name' => sprintf('first_name_%s', rand(1, 9)),
 *                      'last_name' => sprintf('last_name_%s', rand(1, 9)),
 *                      'date' => date('Y-m-d', rand(0, time()))
 *                  );
 * }
 * $data = sortDbResult($data, 'date', SORT_DESC, SORT_NUMERIC, 'id');
 * printf('<pre>%s</pre>', print_r($data, true));
 * $data = sortDbResult($data, 'last_name', SORT_ASC, SORT_STRING, 'first_name', SORT_ASC, SORT_STRING);
 * printf('<pre>%s</pre>', print_r($data, true));
 * ?>
 * </code>
 *
 * @return array $data - Sorted data
 */
function sortDbResult(array $data /*$name, $order, $mode*/) {
    $_argList = func_get_args();
    $_data = array_shift($_argList);
    if (empty($_data)) {
        return $_data;
    }
    $_max = count($_argList);
    $_params = array();
    $_cols = array();
    $_rules = array();
    for ($_i = 0; $_i < $_max; $_i += 3)
    {
        $_name = (string) $_argList[$_i];
        if (!in_array($_name, array_keys(current($_data)))) {
            continue;
        }
        if (!isset($_argList[($_i + 1)]) || is_string($_argList[($_i + 1)])) {
            $_order = SORT_ASC;
            $_mode = SORT_REGULAR;
            $_i -= 2;
        } else if (3 > $_argList[($_i + 1)]) {
            $_order = SORT_ASC;
            $_mode = $_argList[($_i + 1)];
            $_i--;
        } else {
            $_order = $_argList[($_i + 1)] == SORT_ASC ? SORT_ASC : SORT_DESC;
            if (!isset($_argList[($_i + 2)]) || is_string($_argList[($_i + 2)])) {
                $_mode = SORT_REGULAR;
                $_i--;
            } else {
                $_mode = $_argList[($_i + 2)];
            }
        }
        $_mode = $_mode != SORT_NUMERIC
                    ? $_argList[($_i + 2)] != SORT_STRING ? SORT_REGULAR : SORT_STRING
                    : SORT_NUMERIC;
        $_rules[] = array('name' => $_name, 'order' => $_order, 'mode' => $_mode);
    }
    foreach ($_data as $_k => $_row) {
        foreach ($_rules as $_rule) {
            if (!isset($_cols[$_rule['name']])) {
                $_cols[$_rule['name']] = array();
                $_params[] = &$_cols[$_rule['name']];
                $_params[] = $_rule['order'];
                $_params[] = $_rule['mode'];
            }
            $_cols[$_rule['name']][$_k] = $_row[$_rule['name']];
        }
    }
    $_params[] = &$_data;
    call_user_func_array('array_multisort', $_params);
    return $_data;
}
?>
oOo at OoO dot com 10-Nov-2008 12:58
Since the manual doesn't specify so, I want to point out that the SORT_NUMERIC flag does also work correctly if the values are floating point numbers.
Just don't forget to also add the respective SORT_ASC or SORT_DESC flag :)
matt at idizinc dot com 23-Oct-2008 11:47
I looked on some forms for an answer to this simple problem and couldn't find one so I came up with a solution that may help in some situations.

How do you sort an array by a field in that array and resolve numeric ties randomly?

Code:
<?php

foreach($list as $temp_list)
{
   $sort_aux[] = ($temp_list['column_to_sort_by']+(rand(1, 9)/10));
}
array_multisort($sort_aux, SORT_NUMERIC, $list);

?>

Example:

$list[]=array('name'=>'Tom', 'score'=>3);
$list[]=array('name'=>'Sam', 'score'=>3);
$list[]=array('name'=>'Joey', 'score'=>1);

Explanation:
I took an existing example found above that shows how to sort an array by one of it's columns/fields.
I just added: "+(rand(1,9)/10)" To randomly add .1 through .9 to their score to resolve the tie. (Obviously this specific example only works if you're sorting by an integer... so you may need to modify it to suit your needs.)

Hope this helps someone.
isp dot php at spspft dot de 19-Oct-2008 05:44
I would like to report a kind of confusion that arose with the message

Warning: Call-time pass-by-reference has been deprecated; If you would like to pass it by reference, modify the declaration of array_multisort(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file...

from a line like this:

array_multisort (&$keyarr, &$arr );// sort against this keys

This message is not easily switched off by changing the error reporting level because it's produced at parsinig time -- not execution time.

I think this message is misleading because the arguments are passed by reference ANYWAY in array_multisort.

Anybody encountering this message should know that nothing has to be done, except deleting the ampersands (&).
I was tricked by this message because of couse I wanted to have the *sorted* array back. And couldn't find the ini file nor the declaration of array_multisort.
I think in this description of array_multisort the call by reference should be listed in the definition.

Hope this helps someone
seiffs_at_centrum-dot-cz 18-Aug-2008 08:53
There have to be two corrections to the php_multisort($data,$keys)

    // Sort Expression
    $i=0;
    $sort='';  //here
    foreach ($keys as $k){
      if($i>0){$sort.=',';}
      $sort.='$cols[\''.$k['key'].'\']'; //and here
      if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
      if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
      $i++;
    }
php {dot} net [arrt] sebble.com 11-May-2008 02:16
I was requiring a PHP function a sort my array data as part of an SQL interpreter for PHP arrays. This is the code I came up with. and works wonderfully.

I hope this helps somebody. If anyone uses this, let me know what you think, if there are any problems with it...

<?

##                ##
##  PHPMultiSort  ##
##                ##
// Takes:
//        $data,  multidim array
//        $keys,  array(array(key=>col1, sort=>desc), array(key=>col2, type=>numeric))

function php_multisort($data,$keys){

  // List As Columns
  foreach ($data as $key => $row) {
    foreach ($keys as $k){
      $cols[$k['key']][$key] = $row[$k['key']];
    }
  }
  // List original keys
  $idkeys=array_keys($data);
  // Sort Expression
  $i=0;
  foreach ($keys as $k){
    if($i>0){$sort.=',';}
    $sort.='$cols['.$k['key'].']';
    if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
    if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
    $i++;
  }
  $sort.=',$idkeys';
  // Sort Funct
  $sort='array_multisort('.$sort.');';
  eval($sort);
  // Rebuild Full Array
  foreach($idkeys as $idkey){
    $result[$idkey]=$data[$idkey];
  }
  return $result;
}

###############

// Example Data

$_DATA['table1'][] = array("name" => "Sebastian", "age" => 18, "male" => true);
$_DATA['table1'][] = array("name" => "Lawrence",  "age" => 16, "male" => true);
$_DATA['table1'][] = array("name" => "Olivia",    "age" => 10, "male" => false);
$_DATA['table1'][] = array("name" => "Dad",       "age" => 50, "male" => true);
$_DATA['table1'][] = array("name" => "Mum",       "age" => 40, "male" => false);
$_DATA['table1'][] = array("name" => "Sebastian", "age" => 56, "male" => true);
$_DATA['table1'][] = array("name" => "Lawrence",  "age" => 19, "male" => true);
$_DATA['table1'][] = array("name" => "Olivia",    "age" => 24, "male" => false);
$_DATA['table1'][] = array("name" => "Dad",       "age" => 10, "male" => true);
$_DATA['table1'][] = array("name" => "Mum",       "age" => 70, "male" => false);

###############

$res=php_multisort($_DATA['table1'], array(array('key'=>'name'),array('key'=>'age','sort'=>'desc')))
var_dump($res);

/*
array(10) {
  [8]=>
  array(3) {
    ["name"]=>
    string(3) "Dad"
    ["age"]=>
    int(10)
    ["male"]=>
    bool(true)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(3) "Dad"
    ["age"]=>
    int(50)
    ["male"]=>
    bool(true)
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(8) "Lawrence"
    ["age"]=>
    int(16)
    ["male"]=>
    bool(true)
  }
  [6]=>
  array(3) {
    ["name"]=>
    string(8...
*/
?>
No Spam 23-Apr-2008 03:02
To sort the array returned e.g. by oci_fetch_all you must divide it in seperate arrays.
Example:
<?php
$rows=oci_fetch_all($stmt,$results);
?>
now you have several arrays each named by the key name in the sql result.
E.g. array of names, array of streets, array of towns.
To sort the result by e.g. towns you would do the following:
<?php
array_multisort($results[towns],$results[names],$results[streets]);
?>
Done.
To display the result sorted by towns you could use this:
<?php
print_r(array("names"=>$results[names],"streets"=>$results[streets],
"towns"=>$result[towns]));
?>
joopm at hotmail dot com 10-Apr-2008 04:50
@ scott at bartoncomputer dot com

You could also reference the array (if you wanted the original array in the object sorted):

array_multisort($position, SORT_DESC, &$clsVar->data);

Regards, Chr.
nickl at hamiltontampa dot com 24-Feb-2008 11:02
I believe this should read:

foreach($firstarray as $sortarray){
      $column[] = $sortarray['email'];
}

//sort arrays after loop
array_multisort($column, SORT_ASC, $firstarray);

Otherwise you will get an array is inconsistent err because $column array won't equal $firstarray until the loop completes.

It was the only way I got it to work, then it was fine. If I am wrong please post a correction.
glenn at freebsd dot nl 29-Nov-2007 10:49
To sort a nested array by column (key/index):

Example: two entries in the nested array:

firstarray[0]['adres'] = "adres1"
firstarray[0]['email'] = "email2"

firstarray[1]['adres'] = "adres2"
firstarray[1]['email'] = "email1"

-----------------------------------------

Without code: output would put adres1/email2 on top

-----------------------------------------

foreach($firstarray as $sortarray)
{
$column[] = $sortarray['email'];
array_multisort($column, SORT_ASC, $firstarray);
}

-----------------------------------------

With code: output would put adres2/email1 on top
scott at bartoncomputer dot com 03-May-2007 10:18
I didn't see this noted anywhere, so I figured I'd put in a little comment regarding arrays located inside classes. For instance:

class abc
{
   var $data;
}

The following code does not act as expected:

$clsVar =& new abc();

foreach ($clsVar->data as $key => $row)
{
   $position[$key]  = $key;
}

array_multisort($position, SORT_DESC, $clsVar->data);

While I realize this could much easily be acheived using ksort(), this is merely a much more simple example of this behaviour. The exerpt above comes from a much more complicated sort using multi-scripted arrays.

Anyway the only way I could find to get around the behaviour of multisort not sorting the referenced class-array was to make a copy of it as below:

$clsVar =& new abc();
$newData = $clsVar->data;

foreach ($newData as $key => $row)
{
   $position[$key]  = $key;
}

array_multisort($position, SORT_DESC, $newData);

Now newData will contain the sorted array as expected.

Hopefully this helps someone else!
10-Apr-2007 03:01
<?php

    $strDeger = 'aaaa|bbbb|cccc';

    $arrBol = explode('|',$strDeger);

    array_multisort($arrBol, SORT_DESC);

    for($i = 0; $i <= count($arrBol); $i++) {

        echo $arrBol[$i].'<br />';

    }

?>
vermon7 27-Feb-2007 01:23
When using array_multisort() on copies of arrays, it is changing all the copies, even if you modify the copy before using array_multisort().

I've avoided this bug by serializing a copy of array before calling array_multisort, and unserializg it after array_multisort() Look at the code:

<?php

$records_copy = serialize($records) ;
array_multisort ( $records[$sort_field] , $records[$sort2_field] ) ;
$records_copy = unserialize($records_copy) ;

?>
Jon L. -- intel352 [AT] gmail [DOT] com 26-Feb-2007 08:27
This is my solution for a dynamic multisort, using POST values. This doesn't account for a need to sort by multiple columns at once, but could be modified for that purpose.

<?php
    /**
    * @desc You really should validate the posted sort direction against a list of valid possibilities.
    *         Options are SORT_ASC, SORT_DESC, etc, as shown in the documentation for array_multisort
    */
    $sort['direction'] = $_POST['sort_direction'] ? $_POST['sort_direction'] : 'SORT_ASC';
    $sort['field']       = $_POST['sort_field'] ? $_POST['sort_field'] : 'value';

    $array_to_sort = array();
    $array_to_sort['TestCase1'] = array('name'=>'Test1','value'=>'218');
    $array_to_sort['TestCase2'] = array('name'=>'Test2','value'=>'10');
    $array_to_sort['TestCase3'] = array('name'=>'Test3','value'=>'64');

    /**
    * @desc Build columns using the values, for sorting in php
    */
    $sort_arr = array();
    foreach($array_to_sort AS $uniqid => $row){
        foreach($row AS $key=>$value){
            $sort_arr[$key][$uniqid] = $value;
        }
    }

    print '<b>Before sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

    if($sort['direction']){
        array_multisort($sort_arr[$sort['field']], constant($sort['direction']), $array_to_sort);
    }

    print '<b>After sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

?>

This example prints out:

Before sorting:

Array
(
    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

)

After sorting:

Array
(
    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

)
01-Dec-2006 06:58
casting the parameter arrays for array_multisort seem to make the sorting ineffective?

for example:-
<?
        foreach((array)$report_files as $report_files_i)
        {
            $file_stat = stat($report_files_i);
            $report_files_x[] = array(
                'filename'      => $report_files_i
                ,'basename'     => basename($report_files_i)
                ,'ctime'        => date("D, M j, Y",$file_stat['ctime'])
                ,'size'         => $file_stat['size']
                );

            $basename_i[] = strtolower(basename($report_files_i)); // case insensitive

        }
        array_multisort($basename_i, SORT_ASC, $report_files_x);
?>
The above works but if you change the last time to :-
<?
        array_multisort((array)$basename_i, SORT_ASC, (array)$report_files_x);
?>
...adding the (array) cast doesn't sort the main array ...
brettz9 throu gh yah 14-Sep-2006 12:04
Often, one may have a group of arrays which have parallel data that need to be kept associated with each other (e.g., the various attribute values of a group of elements might be stored in their own arrays). Using array_multisort as is, by specifying additional fields, it is possible, as in the documentation example cited below, that this association will be lost.

To take this example set of data from the documentation:
<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
?>

The example goes on to sort it this way:
<?php
array_multisort($ar1, $ar2);
?>

In this case, although the "10" remains associated with the first '1' after being sorted, the "2" and '3' are reversed from their original order.

In order to sort by one field only (yet still have the other array(s) being correspondingly sorted), one can use array_keys (which makes an array out of the keys) to ensure that no further sub-sorting is performed. This works because array_keys is making an array for which no duplicates can exist (since keys will be unique), and thus, the subsequent fields will have no relevance as far as subsorting.

So, using the above data, we can perform this sort instead:
<?php
$ar3 = array_keys($ar1);
array_multisort($ar1, $ar3, $ar2);
?>

which, when $ar1 and $ar2 are dumped gives:

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=>  int(1)
  [1]=>  int(1)
  [2]=>  int(3)
  [3]=>  string(1) "2"
}
ricardo 04-Sep-2006 05:47
Hi,

Modded the function from KES,
goals:
- Object oriented
- string comparision using naturalordening

code:
<?
class HtmlTable{
    var $sortorder;
    var $rows;

//row adding stuf and constructor removed

    function sort($sortorder){
        if(is_array($sortorder)){
            $this->sortorder=$sortorder;
            usort($this->rows,array(&$this,'sort_compare'));
        }
    }
    function sort_compare($a,$b){//sort function
        $result=0;
        foreach($this->sortorder as $key=>$value){
            $result=strnatcmp($a[$key],$b[$key]);
            if($result==0)continue;
            if($value=='desc')$result=$result*-1;
            break;
        }
        return $result;
    }
}
?>
LPChip 28-Aug-2006 06:04
I was looking for a way to dynamically multisort my array.

By dynamically I mean that its not static what column will be sorted and if its ASC or DESC, and the ability to have more than one sorts.

This is the way a database would allow you to do.

The best way to dynamically do this, is by using eval.

The code below is partly what I used. (eg, I left out where the arrays were made and stuff, but the important part is here.)

<?

$orderby_arr = array("col1 ASC";"col2 DESC");

// prepare multisort using eval
        $eval_sort  = "array_multisort(";

        if ($orderby !="") {

            $orderby_arr_c = count($orderby_arr);

            for ($orderby_walk=0; $orderby_walk < $orderby_arr_c; $orderby_walk++) {
                $pos = strpos($orderby_arr[$orderby_walk], " ");
                $orderby_col = substr($orderby_arr[$orderby_walk], 0, $pos);
                $orderby_type = substr($orderby_arr[$orderby_walk], $pos+1);

                $eval_sort .= "\$this->OrderBy[$orderby_col]" . ", SORT_$orderby_type,";
            }
        }

        $eval_sort .= " \$this->Current_Query);";

        // if there's an array, sort it.
        if ($this->Current_Query_m != -1) eval($eval_sort);
?>
RQuadling at GMail dot com 07-Aug-2006 05:53
Extending KES's example (http://www.php.net/manual/en/function.array-multisort.php#68452) to look like array_multisort().

NOTE: Fully commented code is available at http://rquadling.php1h.com (sorry for the ads).

The syntax is the same as array_multisort().

You also have 3 additional parameters you can use:

AMC_SORT_STRING_CASELESS to sort the strings case insensitively.
AMC_LOSE_ASSOCIATION (the default behaviour) to lose the associations for the array.
AMC_KEEP_ASSOCIATION to keep the associations for the array.

Other than that, these function work together JUST like array_multisort but sorts using column(s) without the need to first extract the columns into individual arrays.

<?php
define ('AMC_SORT_STRING_CASELESS', SORT_STRING + 1);
define ('AMC_LOSE_ASSOCIATION', 1001);
define ('AMC_KEEP_ASSOCIATION', 1002);
define ('AMC_SORT_ORDER', 1003);
define ('AMC_SORT_TYPE', 1004);

function array_multisort_column(array &$a_data, $m_mixed1)
    {
    $a_Args = func_get_args();
    $i_Args = func_num_args();
    $GLOBALS['a_AMC_ordering'] = array();
    $a_Columns = array_keys(reset($a_data));
    $b_KeepAssociation = False;
    for($i_Arg = 1 ; $i_Arg < $i_Args ; )
        {
        if (in_array($a_Args[$i_Arg], $a_Columns))
            {
            $s_Column = $a_Args[$i_Arg];
            $GLOBALS['a_AMC_ordering'][$a_Args[$i_Arg]] = array
                (
                AMC_SORT_ORDER => SORT_ASC,
                AMC_SORT_TYPE => SORT_REGULAR,
                );
            while
                (
                isset($a_Args[$i_Arg + 1]) &&
                in_array
                    (
                    $a_Args[$i_Arg + 1],
                    array
                        (
                        AMC_KEEP_ASSOCIATION,
                        AMC_LOSE_ASSOCIATION,
                        AMC_SORT_STRING_CASELESS,
                        SORT_ASC,
                        SORT_DESC
                        SORT_NUMERIC,
                        SORT_REGULAR,
                        SORT_STRING,
                        ),
                    True
                    )
                )
                {
                if (in_array($a_Args[$i_Arg + 1], array(SORT_ASC, SORT_DESC), True))
                    {
                    $GLOBALS['a_AMC_ordering'][$s_Column][AMC_SORT_ORDER] = $a_Args[$i_Arg + 1];
                    }
                elseif (in_array($a_Args[$i_Arg + 1], array(SORT_REGULAR, SORT_NUMERIC, SORT_STRING, AMC_SORT_STRING_CASELESS), True))
                    {
                    $GLOBALS['a_AMC_ordering'][$s_Column][AMC_SORT_TYPE] = $a_Args[$i_Arg + 1];
                    }
                elseif (AMC_KEEP_ASSOCIATION == $a_Args[$i_Arg + 1])
                    {
                    $b_KeepAssociation = True;
                    }
                ++$i_Arg;
                }
            }
        ++$i_Arg;
        }
    $s_Sorter = ($b_KeepAssociation ? 'uasort' : 'usort');
    $b_Result = $s_Sorter($a_data, 'array_multisort_column_cmp');
    unset($GLOBALS['a_AMC_ordering']);
    return $b_Result;
    }

function array_multisort_column_cmp(array &$a_left, array &$a_right)
    {
    $i_Result = 0;
    foreach($GLOBALS['a_AMC_ordering'] as $s_Column => $a_ColumnData)
        {
        switch ($a_ColumnData[AMC_SORT_TYPE])
            {
            case SORT_NUMERIC :
                $i_ColumnCompareResult =
                    ((intval($a_left[$s_Column]) == intval($a_right[$s_Column]))
                    ?
                        0
                    :
                        ((intval($a_left[$s_Column]) < intval($a_right[$s_Column]))
                        ?
                            -1
                        :
                            1
                        )
                    );
                break;
            case SORT_STRING :
                $i_ColumnCompareResult = strcmp((string)$a_left[$s_Column], (string)$a_right[$s_Column]);
                break;
            case AMC_SORT_STRING_CASELESS :
                $i_ColumnCompareResult = strcasecmp((string)$a_left[$s_Column], (string)$a_right[$s_Column]);
                break;
            case SORT_REGULAR :
            default :
                $i_ColumnCompareResult =
                    (($a_left[$s_Column] == $a_right[$s_Column])
                    ?
                        0
                    :
                        (($a_left[$s_Column] < $a_right[$s_Column])
                        ?
                            -1
                        :
                            1
                        )
                    );
                break;
            }
        if (0 == $i_ColumnCompareResult)
            {
            continue;
            }
        $i_Result = $i_ColumnCompareResult * (($a_ColumnData[AMC_SORT_ORDER] == SORT_DESC) ? -1 : 1);
        break;
        }
    return $i_Result;
    }
?>
KES http://kes.net.ua 27-Jul-2006 05:30
<?
//sort by second column then first one
$orderBy=array('0'=>'desc', 'first'=>'asc');

function KES_cmp($a, $b) {
  global $orderBy;
  $result= 0;
  foreach( $orderBy as $key => $value ) {
    if( $a[$key] == $b[$key] ) continue;
    $result= ($a[$key] < $b[$key])? -1 : 1;
    if( $value=='desc' ) $result= -$result;
    break;
    }
  return $result;
  }

$result= array();
$result[]= array( 'first'=>6, 2);
$result[]= array( 'first'=>3, 2);
$result[]= array( 'first'=>1, 3);
$result[]= array( 'first'=>1, 2);
$result[]= array( 'first'=>6, 1);

print "<b>Source</b>";
print_r($result);

usort($result, 'KES_cmp');
print "<b>Result</b>";
print_r($result);
?>
KES 27-Jul-2006 04:35
It is very handy to have function, which sort like this:

$arrayToSort[]= array(0 => ".",               "type" => "dir");
$arrayToSort[]= array(0 => "qf",              "type" => "file");
$arrayToSort[]= array(0 => "..",              "type" => "dir");
$arrayToSort[]= array(0 => "text.txt",      "type" => "file");
$arrayToSort[]= array(0 => "hello",          "type" => "dir");

//first sort by the column 'type', then sort by the column '0'
$howToSort= array('type'=> 'asc', 0=> 'desc');

multisort($arrayToSort, $howToSort);

The result:
0           |       type
----------------------------
.           | dir
..           | dir
hello       | dir
text.txt    | file
qf          | file
Cesar Sirvent 17-May-2006 09:43
There is a problem with array_multisort in languages other than English.
For special chars, as A with accent (Á), the sorting does not correspond to what might expect from a MySQL SELECT with ORDER BY.

For example

<?php

       foreach ($students as $key => $row){
          $surname[$key] = $row['surname'];
       }
       array_multisort($surname, SORT_ASC, $students);
?>

will sort the array in this way: ABADIA, ALVAREZ, BUÑUEL, ZUBIETA, ÁLVARES

while a MySQL SELECT with ORDER BY nombre ASC will yield

ABADIA, ÁLVARES, ALVEREZ, BUÑUEL, ZUBIETA

as A and Á are considered two different representations of the same letter.
scott - evolove - net - work it out 22-Mar-2006 07:51
A very simple way to sort an array of associative arrays by some value is to use usort.

I needed to sort an array of 20 data structures by their 'distance' value:

Array
(
    [0] => Array
        (
            [blahblah] => blahblah
            [distance] => 6
        )

    [1] => Array
        (
          you get the idea....

Here's the code:

--------------------
usort($results, "distributor_compare");

/**
 * usort callback
 */
function distributor_compare($a, $b) {
    $adist = intval($a['distance']);
    $bdist = intval($b['distance']);

    if ($adist == $bdist) {
     return 0;
     }
     return ($adist < $bdist) ? -1 : 1;
}
--------------------
peter dot graham at tcat dot ac dot uk 16-Feb-2006 07:16
Many thanks to �AlberT at SuperAlberT dot it� for his useful and elegant function. I have made some small alterations so it doesn�t use pass-by-reference as this throws up warnings in newer versions of php4.

<?php

function array_key_multi_sort($arr, $l , $f='strnatcasecmp')
{
    usort($arr, create_function('$a, $b', "return $f(\$a['$l'], \$b['$l']);"));
    return($arr);
}

?>
mail at theopensource dot com 31-Jan-2006 11:34
I wanted to share with you a function that I created to make the array_multisort process much easier for myself... There was some interesting things that I encountered and I will post that in the comments.

I created this function so that all I have to do is tell it what column I want to sort through in a one level deep multidimensional array.  You can Try this code in your browser to view the results

ex/
<?php

//Here is an array example
$test[0]['name'] = "David";
$test[0]['age'] = 28;
$test[1]['name'] = "Dennis";
$test[1]['age'] = 23;
$test[2]['name'] = "Joseph";
$test[2]['age'] = 42;

//Here is the Function

function sortmddata($array, $by, $order, $type){

//$array: the array you want to sort
//$by: the associative array name that is one level deep
////example: name
//$order: ASC or DESC
//$type: num or str

$sortby = "sort$by"; //This sets up what you are sorting by

$firstval = current($array); //Pulls over the first array

$vals = array_keys($firstval); //Grabs the associate Arrays

foreach ($vals as $init){
    $keyname = "sort$init";
    $$keyname = array();
}
//This was strange because I had problems adding
//Multiple arrays into a variable variable
//I got it to work by initializing the variable variables as arrays
//Before I went any further

foreach ($array as $key => $row) {

foreach ($vals as $names){
    $keyname = "sort$names";
    $test = array();
    $test[$key] = $row[$names];
    $$keyname = array_merge($$keyname,$test);

}

}

//This will create dynamic mini arrays so that I can perform
//the array multisort with no problem
//Notice the temp array... I had to do that because I
//cannot assign additional array elements to a
//varaiable variable

if ($order == "DESC"){
if ($type == "num"){
array_multisort($$sortby,SORT_DESC, SORT_NUMERIC,$array);
} else {
array_multisort($$sortby,SORT_DESC, SORT_STRING,$array);
}
} else {
if ($type == "num"){
array_multisort($$sortby,SORT_ASC, SORT_NUMERIC,$array);
} else {
array_multisort($$sortby,SORT_ASC, SORT_STRING,$array);
}
}

//This just goed through and asks the additional arguments
//What they are doing and are doing variations of
//the multisort

return $array;
}

//Now to test it

$test = sortmddata($test,'age','ASC','num');

print_r ($test);

//This will return
//Array (
//[0] => Array ([name] => Dennis [age] => 23 )
//[1] => Array ( [name] => David [age] => 28 )
//[2] => Array ( [name] => Joseph [age] => 42 )
//)

?>

There you go... please let me know what you think if you like.
php a-t-the-r-a-t-e chir.ag 05-Jan-2006 02:10
Re: phu at kungphu, 19-Dec-2005 11:36

asort($test) will not let me specify which columns to sort ASC/DESC, NUMERIC/STRING etc.

I have data similar to what you specified. Now I want to sort $test by points DESC and name ASC. Here's my function that does it, based on suggestions on this page. It uses array_multisort (and hence acts just like it: preserving string-keys etc.)

<?php

  function arrayColumnSort()
  {
    $n = func_num_args();
    $ar = func_get_arg($n-1);
    if(!is_array($ar))
      return false;

    for($i = 0; $i < $n-1; $i++)
      $col[$i] = func_get_arg($i);

    foreach($ar as $key => $val)
      foreach($col as $kkey => $vval)
        if(is_string($vval))
          ${"subar$kkey"}[$key] = $val[$vval];

    $arv = array();
    foreach($col as $key => $val)
      $arv[] = (is_string($val) ? ${"subar$key"} : $val);
    $arv[] = $ar;

    call_user_func_array("array_multisort", $arv);
    return $ar;
  }

  $test["pete"]['points']=1;
  $test["pete"]['name']='Peter';

  $test["mike"]['points']=5;
  $test["mike"]['name']='Mike';

  $test["zoo"]['points']=2;
  $test["zoo"]['name']='John Zoo';

  $test["ab"]['points']=2;
  $test["ab"]['name']='John Ab';

  $test1 = $test;

  asort($test1);

  $test2 = arrayColumnSort("points", SORT_DESC, SORT_NUMERIC, "name", SORT_ASC, SORT_STRING, $test);

  print_r($test1); // asort
  print_r($test2); // arrayColumnSort

?>

Output from asort:

Array
(
    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

)

Output from arrayColumnSort:

Array
(
    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

)
phu at kungphu 19-Dec-2005 11:36
Notepad's example using asort/arsort will -not- work unless 'points' is defined -before- 'name'.

Running the posted code sorts by 'name', which was not the point of the previous posts.  Defining 'points' as 'apoints' also did not work; however, defining 'points' first yields correct sorting:

$test[0]['points']=1;
$test[0]['name']='Peter';

$test[1]['points']=5;
$test[1]['name']='Mike';

$test[2]['points']=2;
$test[2]['name']='John';

asort($test);

It appears asort uses the first defined element to sort a multidimensional array.
notepad at codewalkers dot com 09-Dec-2005 04:33
for you guys trying to sort scores on an associative multi-dimensional array, why are you creating your own functions?

<?php

$test[0]['name']='Peter';
$test[0]['points']=1;

$test[1]['name']='Mike';
$test[1]['points']=5;

$test[2]['name']='John';
$test[2]['points']=2;

asort($test);
// or even arsort();

?>

the above seems to work for me...
Shmee 30-Sep-2005 06:46
RWC�s code works very well until you get a �point� value greater then ten.  This is because the strcmp() function will return that 2 > 10 and 2 > 11 � 2 > 19 and so on. To compare number values over ten try a sort like this:

$test = multi_sort($test, $key = 'points');

function multi_sort($array, $akey)
{
  function compare($a, $b)
  {
     global $key;
     if ($a[$key]>$b[$key]){
         $varcmp = "1";
         return $varcmp;
     }
     elseif ($a[$key]<$b[$key]){
         $varcmp = "-1";
         return $varcmp;
     }
     elseif ($a[$key]==$b[$key]){
         $varcmp = "0";
         return $varcmp;
     }
  }
  usort($array, "compare");
  return $array;
}
RWC 25-Sep-2005 01:45
This is the simpler version of the function by AlberT.

A lot of times you have got an array like this:

$test[0]['name']='Peter';
$test[0]['points']=1;

$test[1]['name']='Mike';
$test[1]['points']=5;

$test[2]['name']='John';
$test[2]['points']=2;

You just want to sort on the index in the second dimension, ie. on points in the above example.

You can use the function below and call it like this:

$test = multi_sort($test, $key = 'points');

function multi_sort($array, $akey)
{
  function compare($a, $b)
  {
     global $key;
     return strcmp($a[$key], $b[$key]);
  }
  usort($array, "compare");
  return $array;
}

Note: to be able to use $key in the compare function, it can not simply be passed as a parameter. It has to be declared global and set somewhere outside of compare().
AlberT at SuperAlberT dot it 18-Jul-2005 06:59
a nice piece of code to do an "array_key_multi_sort()" is the following:

<?php
/**
 * orders a multidimentional array on the base of a label-key
 *
 * @param $arr, the array to be ordered
 * @param $l the "label" identifing the field
 * @param $f the ordering function to be used,
 *    strnatcasecmp() by default
 * @return  TRUE on success, FALSE on failure.
 */
function array_key_multi_sort(&$arr, $l , $f='strnatcasecmp') {
        return usort($arr, create_function('$a, $b', "return $f(\$a['$l'], \$b['$l']);"));
}
?>
kencomer at kencomer dot com 12-Jun-2005 11:48
If your data is in an associative array that you would need to separate into columns such as those retrieved with your favorite flavor of _fetch_array() in order to be able to use multisort(), you should consider using uasort() or usort() as an alternative. Here is an example of how this could be beneficial:

(key is employee number which remains intact; rows are sorted by surname, firstname)

<?php
function namecmp( $row1,$row2 )
{
    $first = strcmp($row1['surname'], $row2['surname']) ;
    if ( $first )
        return $first ;
    else
        return strcmp($row1['name'], $row2['name']) ;
}

      $test = array( '11122202' => array('empno'=>11122202,'name'=>'geezer'
                ,'surname'=>'schmidt','age'=>96,'sex'=>'male')
            ,'11122204' => array('empno'=>11122204,'name'=>'coed'
                ,'surname'=>'beaujolais','age'=>18,'sex'=>'female')
            ,'11122206' => array('empno'=>11122206,'name'=>'immortal'
                ,'surname'=>'ramos','age'=>21,'sex'=>'male')
            ,'11122208' => array('empno'=>11122208,'name'=>'babyface'
                ,'surname'=>'brown','age'=>1,'sex'=>'male')
            ,'11122210' => array('empno'=>11122210,'name'=>'exjock'
                ,'surname'=>'gatti','age'=>48,'sex'=>'male')
            ,'11122212' => array('empno'=>11122212,'name'=>'jailbait'
                ,'surname'=>'muhammed','age'=>15,'sex'=>'female') )
            ;
echo "<pre>" ;
print_r( $test ) ;
uasort($test,'namecmp') ;
echo "----sorting----<br \>";
print_r( $test ) ;
echo "</pre>" ;

?>

Array
(
    [11122202] => Array
        (
            [empno] => 11122202
            [name] => geezer
            [surname] => schmidt
            [age] => 96
            [sex] => male
        )

    [11122204] => Array
        (
            [empno] => 11122204
            [name] => coed
            [surname] => beaujolais
            [age] => 18
            [sex] => female
        )

    [11122206] => Array
        (
            [empno] => 11122206
            [name] => immortal
            [surname] => ramos
            [age] => 21
            [sex] => male
        )

    [11122208] => Array
        (
            [empno] => 11122208
            [name] => babyface
            [surname] => brown
            [age] => 1
            [sex] => male
        )

    [11122210] => Array
        (
            [empno] => 11122210
            [name] => exjock
            [surname] => gatti
            [age] => 48
            [sex] => male
        )

    [11122212] => Array
        (
            [empno] => 11122212
            [name] => jailbait
            [surname] => muhammed
            [age] => 15
            [sex] => female
        )

)
----sorting----
Array
(
    [11122204] => Array
        (
            [empno] => 11122204
            [name] => coed
            [surname] => beaujolais
            [age] => 18
            [sex] => female
        )

    [11122208] => Array
        (
            [empno] => 11122208
            [name] => babyface
            [surname] => brown
            [age] => 1
            [sex] => male
        )

    [11122210] => Array
        (
            [empno] => 11122210
            [name] => exjock
            [surname] => gatti
            [age] => 48
            [sex] => male
        )

    [11122212] => Array
        (
            [empno] => 11122212
            [name] => jailbait
            [surname] => muhammed
            [age] => 15
            [sex] => female
        )

    [11122206] => Array
        (
            [empno] => 11122206
            [name] => immortal
            [surname] => ramos
            [age] => 21
            [sex] => male
        )

    [11122202] => Array
        (
            [empno] => 11122202
            [name] => geezer
            [surname] => schmidt
            [age] => 96
            [sex] => male
        )

)
Michael Oelze at �M (myname) �T GMXdotDE 25-Apr-2005 09:15
I try array_multisort at first and it seems to work well. But then I program a page with cached datas (the arrays were saved in a session). Suddenly the sort function doesn't seem to work. There was no error in my script, so I try the reference on the variables. Then he manage to sort the arrays again.

So it seems that if you save your Arrays in a session your arrays are global variables and then 'array_multisort' doesn't sort the arrays despite it gives back 'true'.
 You must reference your variables and all work well:

session_start(); // restore variables (Arrays etc.)
.....
.....
array_multisort(&$Array1,&$Array2,&$Array3,...);
....
$_SESSION["Array1"]=$Array1;//
$_SESSION["Array2"]=$Array2;//Save Arrays in Session Data
$_SESSION["Array3"]=$Array3;//
......

Now you can store your Data Arrays in your Session and are able to sort them as you like...
stevec at NO-/ dot /-SPAM dot qiguang dot net 13-Apr-2005 08:19
Be careful when using array_multisort() on copies of arrays, as you might end up changing the original array.  Given the following code:

<?php
    $test1 = array(4,3,2,1);
    $test2 = $test1;
    $test3 = array('a', 'b', 'c', 'd');

    array_multisort($test2, SORT_ASC, $test3);

    echo 'test1:';
    print_r($test1);
    echo 'test2:';
    print_r($test2);
    echo 'test3:';
    print_r($test3);
?>

You would expect:

test1:Array
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
)
test2:Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
test3:Array
(
    [0] => d
    [1] => c
    [2] => b
    [3] => a
)

However, if you run the code, you actually get:

test1:Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
test2:Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
test3:Array
(
    [0] => d
    [1] => c
    [2] => b
    [3] => a
)

Note that the original ($test1) ends up being sorted even though it was never called by array_multisort().  To work around this, insert a statement to modify the copy ($test2) before calling array_multisort() on it.  The following code will produce the expected "correct" results:

<?php
    $test1 = array(4,3,2,1);
    $test2 = $test1;
    $test3 = array('a', 'b', 'c', 'd');

    $test2[0] = $test2[0];                // fix
    array_multisort($test2, SORT_ASC, $test3);

    echo 'test1:';
    print_r($test1);
    echo 'test2:';
    print_r($test2);
    echo 'test3:';
    print_r($test3);
?>

This seems to be a resurrection of the closed bug #8130.  Also, someone reported this behavior in bug #32031, but it was incorrectly labeled "bogus" in reference to bug #25359, which is a different issue.
joao at intrasystems dot com dot br 07-Apr-2005 12:27
Exemple of sorting multi-dimensional arrays by one of it's fields:

$result[0]['nome']='Joao';
$result[0]['order']=5;
$result[1]['nome']='Pedro';
$result[1]['order']=1;
$result[2]['nome']='Marcelo';
$result[2]['order']=3;

foreach($result as $res)
     $sortAux[] = $res['order'];

array_multisort($sortAux, SORT_ASC, $result);

print_r($result);

produces:

Array
(
    [0] => Array
        (
            [nome] => Pedro
            [order] => 1
        )

    [1] => Array
        (
            [nome] => Marcelo
            [order] => 3
        )

    [2] => Array
        (
            [nome] => Joao
            [order] => 5
        )

)
Toni 10-Nov-2004 03:30
An example to sort an array by 3 criteria:

$recordset is an array of results from a query to a database, that I sort using $matrix as auxiliary array. First numeric, Second and Third alphabetically.

<?php
for($idx=0;$idx<$toShow;$idx++){
    $matrix[0][$id]=$recordset[$id][0];
    $matrix[1][$id]=$recordset[$id][1];
    $matrix[2][$id]=$recordset[$id][10];
}

array_multisort($matrix[0], SORT_DESC, SORT_NUMERIC,$matrix[1], SORT_STRING, SORT_ASC,$matrix[2], SORT_STRING, SORT_ASC);
?>
meddle at dzygn.com 05-Oct-2004 07:40
If you want to sort a multidomensional array by key name you cannot use array_multisort. ie: for an array named $archivos that prints like this:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => test
        )

    [1] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [2] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [3] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)

If I wanted to order by "name" I'd use:

function comparar($a, $b) {
        return strnatcasecmp($a["name"], $b["name"]);
}
usort($archivos, "comparar");

This function performs a case insensitive string comparison using a "natural order" algorithm (strnatcasecmp), resulting in:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [1] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [2] => Array
        (
            [index] => 0
            [name] => test
        )

    [3] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)
kat dot n0spam at audiogalaxy dot com 23-Aug-2001 10:25
If you're having problems with array_multisort changing variables in global space when it is called inside a function and you're not passing in the function parameters by reference you can alleviate the problem by calling array_multisort with its parameters by reference.

array_multisort(&$a, SORT_DESC, &$b);

More details here in my bug report:
http://www.php.net/bugs.php?id=12936
array_merge
array_pad
Функции для работы с массивами


Дополнить размер массива определенным значением до заданной величины

array_multisort
array_pop
Функции для работы с массивами
PHP Manual

array_pad

(PHP 4, PHP 5)

array_pad — Дополнить размер массива определенным значением до заданной величины

Описание

array array_pad ( array $input , int $pad_size , mixed $pad_value )

Функция array_pad() возвращает копию массива input, дополненного до размера pad_size элементами со значением pad_value. Если параметр pad_size положителен, то массив увеличивается вправо, если отрицателен - влево. Если абсолютное значение параметра pad_size меньше или равно размеру массива input, функция не производит никаких операций. За один раз возможно добавить максимум 1048576 элементов.

Список параметров

input

Исходный массив, к которому дополняются элементы.

pad_size

Новый размер массива.

pad_value

Дополняемое значение, если длина массива input меньше pad_size.

Возвращаемые значения

Возвращает копию input, дополненного до размера указанного pad_size значением pad_value. Если параметр pad_size положителен, то массив дополняется вправо, если он отрицателен - влево. Если абсолютное значение pad_size меньше либо равно длине input, то дополнение не происходит.

Примеры

Пример #1 Пример использования array_pad()

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// результат: array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// результат: array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// операция не произведена

Смотрите также

  • array_fill() - Заполняет массив значениями
  • range() - Создает массив, содержащий диапазон элементов

User Contributed Notes

sonu50imedbvu at gmail dot com(Sonu Jaiswal) 12-Jan-2011 12:53
Just an info about the value of "$pad_size" ,

If we set the value of "$pad_size" from -3 to 3,

It will produce the output like:

<?php
$result = array_pad($input, -3, "noop");
//result is array(12, 10, 9)

$result = array_pad($input, 3, "noop");
//result is array(12, 10, 9)
?>

means array will remain the same.
tugla 18-Dec-2008 09:23
Beware, if you try to pad an associative array using numeric keys, your keys will be re-numbered.

<?php
$a = array('size'=>'large', 'number'=>20, 'color'=>'red');
print_r($a);
print_r(array_pad($a, 5, 'foo'));

// use timestamps as keys
$b = array(1229600459=>'large', 1229604787=>20, 1229609459=>'red');
print_r($b);
print_r(array_pad($b, 5, 'foo'));
?>

yields this:
------------------
Array
(
    [size] => large
    [number] => 20
    [color] => red
)
Array
(
    [size] => large
    [number] => 20
    [color] => red
    [0] => foo
    [1] => foo
)
Array
(
    [1229600459] => large
    [1229604787] => 20
    [1229609459] => red
)
Array
(
    [0] => large
    [1] => 20
    [2] => red
    [3] => foo
    [4] => foo
)
hk, StrApp Bussiness Solutions 08-Jan-2007 02:15
A simple example for array_pad()

the syntax is as follows: array_pad(array(), (+/-)int, value)

where "array" is the array to which the value is to be added,

"(+/-) int" is a value that decides the length of the array(it should be greater than the length of the array.
if its a negative number then the value will be added at the left of the array else it will be added to the right.

"values" denotes the value to be added to the array

lets try an example:

<?php

$digits = array();
$digits[0] = 1;
$digits[1] = 2;
$digits[2] = 3;
$arraypad = array_pad($digits, -4, "0");
print_r($arraypad);

?>

output:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
oaev at mail dot ru 21-Oct-2004 11:48
Easy way to get an array contains 5 random numbers from 0 to 9:

$rand_arr = array_rand( array_pad( array(), 10, 1 ), 5 );
28-Feb-2004 09:00
One way to initialize a 20x20 multidimensional array.

<?php
$a = array();
$b = array();
$b = array_pad($b,20,0);
$a = array_pad($a,20,$b);
?>
mwwaygoo at hotmail dot com 16-Jan-2004 08:02
little older, a little wiser.

ksort() will order the array back into its normal order again
so:

<?php
$myArr = array(2 => 'two', 4 => 'four');

$newArr = array_pad(array(), 6, 'FILLED');
$newArr =$myArr+$newArr;
ksort($newArr);
?>

Will give :
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => FILLED [4] => four [5] => FILLED )
goffrie at sympatico dot ca 23-Mar-2003 05:06
To daarius - you mean you have...

[2]=>"two"
[3]=>"three"

and you want...

[0]=>"FILLED"
[1]=>"FILLED"
[2]=>"two"
[3]=>"three"
[4]=>"FILLED"
[5]=>"FILLED"

If so, then the following code...

<?php
$array = array(2 => "two", 3 => "three");
$array = array_pad($array, count($array)+2, "FILLED");
$num = -(count($array)+2);
$array = array_pad($array, $num, "FILLED");
print_r($array);
?>

will return:
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => three [4] => FILLED [5] => FILLED )
The ordering should be okay,...
mwwaygoo at hotmail dot com 19-Sep-2002 09:39
OR you could do this

<?php
$myArr = array(2 => 'three', 3 => 'four');

$newArr = array_pad(array(), 4, 'FILLED');
$newArr =$myArr+$newArr;
?>

This gives your desired result BUT the ordering is a little wierd, because of the order they were added. Indexes are okay though and that is what you wanted.

print_r($newArr) outputs
Array ( [2] => three [3] => four [0] => FILLED [1] => FILLED )

hope this helps
daarius at hotmail dot com 23-Jul-2002 07:36
yes that is true. But, if the index of the array is 2=two, 3=three

and i want 4 more keys to be filled. But, not just filled anywhere, but i want to maintain the key index.

so, i would like to have 0=FILLED, 1=FILLED ... 4=FILLED, 5=FILLED

now i got 4 more keys padded with my string.

We can do this "if" we know the missing keys, but if we dont, then it would be nice for array_pad() or perhaps some new function to do this?

obviously we can achive this by looping through the array using array_key_exists(), and if you dont find the key, simply create + fill it.
regards,
Daarius...
scott*hurring.com 19-Jul-2002 04:20
to the previous commenter -- if you read the manual entry, you'd see that a negative pad_size will put the pad values at the front of the array.
ethanhunt314 at hotmail dot com 10-Dec-2000 04:25
This is useful when using next() and prev() function in a while loop to traverse an array.

For example the following code will only output up to 8.

<?php
$test[] = "1";
$test[] = "2";
$test[] = "3";
$test[] = "4";
$test[] = "5";
$test[] = "6";
$test[] = "7";
$test[] = "8";
$test[] = "9";
$test[] = "10";
$test[] = " ";
$test[] = " ";
$test[] = " ";

$count = count($test);

while($i < $count) {

$now = current($test);
echo "<p>$now</p>";

next($test);
next($test);
next($test);
prev($test);
prev($test);
prev($test);

$i++;
next($test);
}
?>

But if you use:
$test = array_pad($test, 13, " ");

you will get all of your output.
array_multisort
array_pop
Функции для работы с массивами


Извлекает последний элемент массива

array_pad
array_product
Функции для работы с массивами
PHP Manual

array_pop

(PHP 4, PHP 5)

array_pop — Извлекает последний элемент массива

Описание

mixed array_pop ( array &$array )

array_pop() извлекает и возвращает последнее значение параметра array, уменьшая размер array на один элемент. Если array пуст (или не является массивом), будет возвращён NULL. Кроме этого, если передан не массив, будет вызвано предупреждение.

Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.

Список параметров

array

Массив, из которого берется значение.

Возвращаемые значения

Возвращает последний элемент массива array. Если array пуст (или не является массивом), будет возвращен NULL.

Примеры

Пример #1 Пример использованияarray_pop()

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

После этого, в $stack будет только 3 элемента:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

и raspberry будет присвоено переменной $fruit.

Смотрите также

  • array_push() - Добавляет один или несколько элеметов в конец массива
  • array_shift() - Извлекает первый элемент массива
  • array_unshift() - Добавляет один или несколько элементов в начало массива

User Contributed Notes

sven dot uselesspart at e7o dot de 31-Mar-2012 09:40
If you get an error like "Warning: Cannot add element to the array as the next element is already occupied" you shouldn't use the array_pop-function. You can use the unset-function instead:

echo $a[count($a)-1]; // or end($a)
unset($a[count($a)-1]);

The reason is that array_pop doesn't update the internal structures of the array in the way you're expecting, only unset will work in some special cases with extended using the stack.
qeremy 07-Mar-2012 11:26
For the sake of array_unshift()
:)

<?php
function array_unpop(&$arr) {
    $args = func_get_args(); unset($args[0]);
    $tarr = array();
    foreach ($args as $arg) {
        $tarr[] = $arg;
    }
    $arr = array_merge($arr, $tarr);
}

$queue = array("orange", "banana");
array_unpop($queue, "apple", "raspberry");
print_r($queue);
?>

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
mtroy dot student at gmail dot com 16-Dec-2010 06:39
to apply arra_pop serveral times but not recursive

<?php
function array_mpop($array, $iterate)
{
    if(!is_array($array) && is_int($iterate))
        return false;

    while(($iterate--)!=false)
        array_pop($array);
    return $array;
}
?>

for test :

<?php
    $a = array("titi", "toto", "tata", "tonton", "toutou", "tutu");
    $a = array_mpop($a, 2);
    var_dump($a);
?>

result :

array(4) { [0]=> string(4) "titi" [1]=> string(4) "toto" [2]=> string(4) "tata" [3]=> string(6) "tonton" }
bellefy at yahoo dot com 27-Aug-2010 09:35
Regarding the last few comments.

To delete the first item in an array:
<?php
array_shift($array);
?>

To get the filename or the file's mtime:
<?php
$filename = basename(__FILE__);
$mod = filemtime(__FILE__);
?>
benjamin_letchford at student dot rmit dot edu dot au 27-Aug-2010 02:24
Want to delete the first element in an array? Here's a small and handy function that'll do the trick!

function array_pop_first(&$array) {
    $array = array_reverse($array);
    array_pop($array);
    $array = array_reverse($array);
}
macnimble at gmail dot com 18-Jul-2010 01:37
@Jochen

You could use PHP's pathinfo function to achieve the same results:

<?php
$mod = filemtime(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
?>
me at fxless dot org 18-Feb-2010 01:38
I have used array_pop() in a function that returns the name of the current file. This can be used, for example, in conjunction with filemtime() to get the modification time of the current file. The function I coded is a one-liner:

<?php
    function whoAmI(){
        return array_pop(explode("/", $_SERVER['PHP_SELF']));
    }
?>

If your file URI is www.example.com/bar/foobar.php, whoAmI() will return foobar.php. To use it with e.g. filemtime() you would simply write:

<?php
    $modtime = filemtime(whoAmI());
?>

Greetings,
Jochen
jim203nospamplz at plznospamaol dot com 05-Sep-2009 04:51
2 line changes to my previous submission:

$theJumpNumber = (round(count($temparray)/2) + $startingFileNumber) % count($temparray); // use of startingfilenumber randomizes the jump number
while (count($temparray) % $theJumpNumber == 0
|| !isPrime($theJumpNumber)) // !isPrime as easy way to check for no cofactors

You need to check for no cofactors so you can cycle round the complete array without duplicates. Checking !isPrime on theJumpNumber is a pretty easy way to do that. isPrime can be found by google: php isprime
sneskid at hotmail dot com 03-Aug-2009 07:22
As already mentioned, array_pop always returns a copy, never a reference, which can be a problem in some cases.

Here is a pop function that allows you to get the reference.
(keep in mind it will alter the internal pointer of the array)
<?php
function &array_rpop(&$a){
    end($a);
    $k=key($a);
    $v=&$a[$k];
    unset($a[$k]);
    return $v;
}

// try this:
$A='A';
$B=array(&$A);

//$C=&array_rpop($B); // will work
$C=&array_pop($B); // won't work

$C='C';

var_dump($A,$B,$C);
?>

I hope the PHP people will make the regular function work with references.
Igor Feghali 04-Feb-2009 09:18
Beware that array_pop() returns a copy of the element (even if the array element is a reference). That means you will get different results on PHP 4 and 5 when dealing with objects.

<?php
$a = new stdClass();
$a->foo = 'bar';

$arr = array(&$a);
$b = array_pop($arr);

$b->foo = 'baz';

var_dump($a);
?>

Output of PHP 5.2.8:
object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "baz"
}

Output of PHP 4.4.9:
object(stdClass)(1) {
  ["foo"]=>
  string(3) "bar"
}

For more information please refer to:
http://br2.php.net/manual/en/language.oop5.references.php
mcgroovin at gmail dot com 23-Oct-2008 12:13
I wrote a simple function to perform an intersect on multiple (unlimited) arrays.

Pass an array containing all the arrays you want to compare, along with what key to match by.

<?php
function multipleArrayIntersect($arrayOfArrays, $matchKey)
{
    $compareArray = array_pop($arrayOfArrays);

    foreach($compareArray AS $key => $valueArray){
        foreach($arrayOfArrays AS $subArray => $contents){
            if (!in_array($compareArray[$key][$matchKey], $contents)){
                unset($compareArray[$key]);
            }
        }
    }

    return $compareArray;
}
?>
tom at sirwhite dot com 26-May-2008 10:37
@Orsi
correct me if I'm wrong... but an easier version might be
<?php
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array:    the array (in/out)
*             $deleteIt: the value which we would like to delete
*             $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
*                          if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
    $key = array_search($deleteIt,$array,TRUE);
    if($key === FALSE)
        return FALSE;
    unset($array[$key]);
    if(!$useOldKeys)
        $array = array_values($array);
    return TRUE;
}
?>

--untested but should work.. rite?--
sonetti at hotmail dot com 05-Feb-2008 01:15
@smp_info
I think you are still tired. What would be wrong with:

<?php
$array = array('one', 'two', 'three', 'four');

//pop the last element off
array_pop($array);

//$array == array('one', 'two', 'three');
?>

As the documentation clearly notes, array_pop() not only returns the last element, but actually removes it from the array wich is passed by reference. Calling array_diff is a waste of resources.
Orsi 10-Jan-2008 07:05
Hi,

Here is a simple function which delete one element from the array (with value):
<?php
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array:    the array (in/out)
*             $deleteIt: the value which we would like to delete
*             $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
*                          if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
    $tmpArray = array();
    $found = FALSE;
    foreach($array as $key => $value)
    {
        if($value !== $deleteIt)
        {
            if(FALSE === $useOldKeys)
            {
                $tmpArray[] = $value;
            }
            else
            {
                $tmpArray[$key] = $value;
            }
        }
        else
        {
            $found = TRUE;
        }
    }

    $array = $tmpArray;

    return $found;
}
?>

Maybe it will help somebody...
smp_info at yahoo dot com 26-Nov-2007 03:44
I'm sorry, I must have been extremely tired when writing the note below.  :P

Replace $element with $array, and the code will work nicely.

The right code would be..

<?php
//$array = array('one', 'two', 'three', 'four');

//pop the last element off and return the array
$array = array_diff($array, array(array_pop($array)));

//$array = array('one', 'two', 'three');
smp_info at yahoo dot com 19-Nov-2007 04:23
I've found myself several times wanting the array (minus the popped element) returned, instead of the element returned.

The following code does this nicely:

<?php
//$array = array('one', 'two', 'three', 'four');

//pop the last element off and return the array
$array = array_diff($array, array(array_pop($element)));

//$array = array('one', 'two', 'three');
doyley3731 at gmail dot com 31-Oct-2007 04:37
I had a problem when using this function because my array was made up entirley of numbers, so I have made my own function.  Hopefully it will be useful to somebody.

function array_trim_end($array){

$num=count($array);
$num=$num-1;
unset($array[$num]);

return $array;
}
rmondragon at gmail dot com 07-Jun-2005 02:03
In a previous example ...
<?php
function array_trim ( $array, $index ) {
   if ( is_array ( $array ) ) {
     unset ( $array[$index] );
     array_unshift ( $array, array_shift ( $array ) );
     return $array;
     }
   else {
     return false;
     }
   }
?>

This have a problem. if u unset the last value and then use
<?
array_unshift ( $array, array_shift ( $array ) );
?>

will return a :  Array ( [0] => )
so u can fix it using...

<?php
if (count($array) > 0) array_unshift ( $values, array_shift ( $values ) );
?>

good luck ;)
15-Dec-2004 08:29
strrchr is a lot more useful than the other example using array_pop for finding the extension of a file. For example:

<?php
$ext = strrchr($filename, ".");
?>

$ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "filename.tar.gz", then this construction will just return the last extension.
eddie at metafoundry dot com 25-Nov-2004 08:35
Quick way to get the extension from a file name using array_pop:

$ext = array_pop(explode(".",$filename));
30-Mar-2004 01:55
A function to delete an array value that recalculates the index ( its very short and easy to understand ).
Hope this might help someone...

<?php
/* Usage:
    $array : Array
    $indey : Integer

    The value of $array at the index $index will be
    deleted by the function.
*/
function array_trim ( $array, $index ) {
   if ( is_array ( $array ) ) {
      unset ( $array[$index] );
      array_unshift ( $array, array_shift ( $array ) );
      return $array;
      }
   else {
      return false;
      }
   }
?>
Alex Dowgailenko 15-Dec-2003 03:36
array_pop() can be usefull for fetching extentions of files, especially in cases where there might be more than one period in the filename.

eg:

<?php
$filename = "textfile.txt.bak";
$tmp = explode(".", $filename);
$ext = array_pop($tmp);

print_r($ext); // Shows "bak"
?>
21-Oct-2003 01:46
Be aware that using array_pop on an associative array that uses a numeric string as a key changes the key:

<?php
$stack= array("12" => "green", "54" => "brown", "672" => "blue");
print_r($stack);
$fruit = array_pop($stack);
print_r($stack);
?>

Results of execution:
Array
(
    [12] => green
    [54] => brown
    [672] => blue
)
Array
(
    [0] => green
    [1] => brown
)

However, if there is a non-numeric character in the key, the key will be maintained:

<?php
$stack= array("g1" => "green", "b1" => "brown", "b2" => "blue");
print_r($stack);
$fruit = array_pop($stack);
print_r($stack);
?>

Results of execution:
Array
(
    [g1] => green
    [b1] => brown
    [b2] => blue
)
Array
(
    [g1] => green
    [b1] => brown
)
ryan8613(at)hotmail(dot)com 08-Jun-2003 06:10
A function that may help some out, considering it's pretty much the one mentioned previously...

<?php
function array_trim($arr, $indice) {
        if(!isset($indice)) {
                $indice = count($arr)-1;
        }
        unset($arr[$indice]);
        array_shift($arr);
        return $arr;
}
?>

It cuts the given index value off of the array, but without the shift, if  the 'index' value isn't given, it cuts off the end value.
Alex Chac�n 28-Feb-2003 05:16
alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes

<?php
function eliminarElementoArreglo ($array, $indice)
{
    if (array_key_exists($indice, $array))
    {
        $temp = $array[0];
        $array[0] = $array[$indice];
        $array[$indice] = $temp;
        array_shift($array);

        //reacomodamos �ndices
        for ($i = 0 ; $i < $indice ; $i++)
        {
            $dummy = $array[$i];
            $array[$i] = $temp;
            $temp = $dummy;
        }
    }
    return $array;
}
?>
array_pad
array_product
Функции для работы с массивами


Вычислить произведение значений массива

array_pop
array_push
Функции для работы с массивами
PHP Manual

array_product

(PHP 5 >= 5.1.0)

array_product — Вычислить произведение значений массива

Описание

number array_product ( array $array )

array_product() возвращает произведение значений массива.

Список параметров

array

Массив.

Возвращаемые значения

Возвращает произведение как тип integer или float.

Примеры

Пример #1 Примеры использования array_product()

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";

?>

Результат выполнения данного примера:

product(a) = 384
product(array()) = 1

User Contributed Notes

marcel dot glacki at stud dot fh-swf dot de 28-Sep-2010 08:36
You can use array_product to calculate the factorial of n:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  return array_product( range( 1, $n ));
}
?>

If you need the factorial without having array_product available, here is one:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  for( $p++; $n; ) $p *= $n--;
  return $p;
}
?>
bishop 28-Jul-2009 10:34
gmail @ algofoogle is right, so we can extend our own array_product() to flexibly accept the empty product value.  Zero (0) is the default (to be compatible with PHP behavior), but you could change this to 1 for mathematical purposes or null for logical.

<?php
if (! function_exists('array_product')) {
    function array_product($array, $emptyProduct = 0) {
        if (is_array($array)) {
            return (0 == count($array) ? $emptyProduct : array_reduce($array, '_array_product', 1));
        } else {
            trigger_error('Param #1 must be an array', E_USER_ERROR);
            return false;
        }
    }
    function _array_product($v,$w) { return $v * $w; }
}
?>
hdeus at yahoo dot com 06-Oct-2008 08:25
Here is how you can multiply two arrays in the form of matrixes using a bit of matrix algebra (M*M).
By calling the function multiplyMatrix, you will be multiplying two sparse matrixes (zeros need not be included in the array for the operation to be performed).

<?php
$M = array(
0=>array(1=>1,4=>1),
1=>array(2=>1,3=>1),
3=>array(1=>1),
4=>array(5=>1),
5=>array(6=>1)
);

$M1 = multiplyMatrix($M, $M); //multiplying $M by itself

echo '<pre>';print_r($M1);echo '</pre>';

function multiplyMatrix($M1, $M2)
    {
#Helena F Deus, Oct 06, 2008
##Multiply two matrixes; $M1 and $M2 can be sparse matrixes, the indexes on both should match
        if(is_file($M1)) {$matrix1 = unserialize(file_get_contents($M1));}
        else $matrix1 = $M1;

        #transpose M2
        $M2t = transpose($M2);

        foreach ($M2t as $row=>$tmp) {
            ##sum the result of the value in the col multiplied by the value in the vector on the corresponding row

                foreach ($M1 as $row1=>$tmp1) {

                    $multiply[$row1] = array_rproduct($tmp,$tmp1);

                    if(!$multiply[$row1]){
                          exit;
                        }
                }

                foreach ($multiply as $row1=>$vals) {

                    $sum[$row][$row1]=array_sum($vals);
                }

        }

    $r=transpose($sum);

    return ($r);
    }

function transpose($M)
{
foreach ($M as $row=>$cols) {

            foreach ($cols as $col=>$value) {
                 if($value)
                 $Mt[$col][$row]=$value;
            }
        }
        ksort($Mt);

return ($Mt);
}

function array_rproduct($a1, $a2)
{

    foreach ($a1 as $line=>$cols) {
        $a3[$line] = $a1[$line]*$a2[$line];
        foreach ($a2 as $line2=>$cols2) {
            $a3[$line2] = $a1[$line2]*$a2[$line2];
        }
    }
    ksort($a3);

    return ($a3);

}

?>
gmail at algofoogle 09-May-2007 09:18
Just in relation to "bishop" and the overall behaviour of array_product... The "empty product" (i.e. product of no values) is supposed to be defined as "1":

http://en.wikipedia.org/wiki/Empty_product

...however PHP's array_product() returns int(0) if it is given an empty array. bishop's code does this, too (so it IS a compatible replacement). Ideally, array_product() should probably return int(1). I guess it depends on your specific context or rationale.

You might normally presume int(0) to be a suitable return value if there are no inputs, but let's say that you're calculating a price based on "percentage" offsets:

$price = 10.0;
$discounts = get_array_of_customer_discounts();
$price = $price * array_product($discounts);

...if there are NO "discounts", the price will come out as 0, instead of 10.0
pqpqpq at wanadoo dot nl 17-Jan-2007 04:32
An observation about the _use_ of array_product with primes:

$a=$arrayOfSomePrimes=(2,3,11);
              // 2 being the first prime (these days)

$codeNum=array_product($a); // gives 66 (== 2*3*11)

echo "unique product(\$a) = " . array_product($a) . "\n";

The 66 can (only) be split into its original primes,
which can be transformed into their place in the row of primes (2,3,5,7,11,13,17,19...)  giving (1,2,3,4,5,6,7,8...)

The 66 gives the places {1,2,5} in the row of primes. The number "66" is unique as a code for {1,2,5}

So you can define the combination of table-columns {1,2,5} in "66". The bigger the combination, the more efficient in memory/transmission, the less in calculation.
bishop 29-Nov-2006 07:13
Yet another implementation of array_product() using PHP's native array_reduce():

if (! function_exists('array_product')) {
    function array_product($array) {
        if (is_array($array)) {
            return (0 == count($array) ? 0 : array_reduce($array, '_array_product', 1));
        } else {
            trigger_error('Param #1 must be an array', E_USER_ERROR);
            return false;
        }
    }
    function _array_product($v,$w) { return $v * $w; }
}
bishop 29-Nov-2006 07:04
Regarding Andre D function to test if all values in an array of booleans are true, you can also use:

<?php
$allTrue = (! in_array(false, $arrayToCheck));
?>

Both this method and Andre D's are O(n), but this method has a lower k in the average case: in_array() stops once it finds the first false, while array_product must always traverse the entire array.
marcel at computingnews dot com 15-Nov-2006 09:07
if you don't have PHP 5.xx . you can use this function.
It does not make sure that the variables are numeric.

function calculate_array_product($array="")
{
if(is_array($array))
    {
                foreach($array as $key => $value)
        {
            $productkey = $productkey + $key;
         }
       return $productkey;
    }
  return NULL;
}
Andre D 07-Aug-2006 01:56
This function can be used to test if all values in an array of booleans are TRUE.

Consider:

<?php

function outbool($test)
{
    return (bool) $test;
}

$check[] = outbool(TRUE);
$check[] = outbool(1);
$check[] = outbool(FALSE);
$check[] = outbool(0);

$result = (bool) array_product($check);
// $result is set to FALSE because only two of the four values evaluated to TRUE

?>

The above is equivalent to:

<?php

$check1 = outbool(TRUE);
$check2 = outbool(1);
$check3 = outbool(FALSE);
$check4 = outbool(0);

$result = ($check1 && $check2 && $check3 && $check4);

?>

This use of array_product is especially useful when testing an indefinite number of booleans and is easy to construct in a loop.
mattyfroese at gmail dot com 06-Jan-2006 06:25
If you don't have PHP 5

$ar = array(1,2,3,4);
$t = 1;
foreach($ar as $n){
    $t *= $n;
}
echo $t; //output: 24
array_pop
array_push
Функции для работы с массивами


Добавляет один или несколько элеметов в конец массива

array_product
array_rand
Функции для работы с массивами
PHP Manual

array_push

(PHP 4, PHP 5)

array_push — Добавляет один или несколько элеметов в конец массива

Описание

int array_push ( array &$array , mixed $var [, mixed $... ] )

array_push() использует array как стэк, и добавляет переданные значения в конец массива array. Длина array увеличивается на количество переданных значений. Имеет тот же эффект, что и выражение:

<?php
$array[] = $var;
?>
повторенное для каждой var.

Замечание: Вместо использования array_push() для добавления одного элемента в массив, лучше использовать $array[] = , потому что в этом случае не происходит затрат на вызов функции.

Замечание: array_push() вызовет предупреждение, если первый аргумент не является массивом. Это отличается от поведения конструкции $var[], в случае которой будет создан новый массив.

Список параметров

array

Входной массив.

var

Записываемое значение.

Возвращаемые значения

Возвращает новое количество элементов в массиве.

Примеры

Пример #1 Пример использования array_push()

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

Результат выполнения данного примера:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

Смотрите также

  • array_pop() - Извлекает последний элемент массива
  • array_shift() - Извлекает первый элемент массива
  • array_unshift() - Добавляет один или несколько элементов в начало массива

User Contributed Notes

Rodrigo de Aquino 30-Mar-2012 03:24
If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:

    $data[$key] = $value;

It is not necessary to use array_push.
Chicna 21-Mar-2012 10:14
I found a simple way to have an "array_push_array" function, without the references problem when we want to use call_user_func_array(), hope this help :

function array_push_array(array &$array)
{
    $numArgs = func_num_args();
    if(2 > $numArgs)
    {
      trigger_error(sprintf('%s: expects at least 2 parameters, %s given', __FUNCTION__, $numArgs), E_USER_WARNING);
      return false;
    }

    $values = func_get_args();
    array_shift($values);

    foreach($values as $v)
    {
      if(is_array($v))
      {
        if(count($v) > 0)
        {
          foreach($v as $w)
          {
            $array[] = $w;
          }
        }
      }
      else
      {
        $array[] = $v;
      }
    }

    return count($array);
}
Szorstki 27-Dec-2011 02:35
With multidimensional arrays it's easy too (somebody posted a sample, but it isn't useful for beginners). Here is a piece of code that should explain everything and much more:

<?php
//two classes of objects which will be in multidimensional array
class Org {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}
class Org2 {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}

//main array
$arr = array();

//creating first subarray manually
//the subarray name must be like first class above
$arr['Org'] = array();

//creating second subarray for objects of selected class
//in another way
$x=2222;        //only for creating the sample object
$arr[get_class(new Org2("wtf".$x))] = array();

//pushing some new objects to (sub)arrays in (main)array
for ($i=0; $i<3; $i++) {
    $org1 = new Org("tst".$i);
    $org2 = new Org2("wtf".$i);
    array_push($arr[get_class($org1)], $org1);
    array_push($arr[get_class($org2)], $org2);
}

//printing everything
foreach ($arr as $key=>$value) {
    $counter = 0;
    echo "=====".$key." (key) | value: ".$value."<br/>";
    foreach ($value as $key2=>$value2) {
        if($value2 == null) {
            //echo "counter: ".$counter." | key: ".$key2;
            unset($arr[$key][$key2]);
        } else {
            print_r($value2);
            echo " [".$counter."]  [".$key2."]<br/>";
        }
        $counter++;
    }
}

//the additional, second part
echo "<br/>--------<br/><br/>";
//deleting one of the objects from selected (sub)array
unset($arr['Org'][1]);

//printing everything again (look at the counter values)
foreach ($arr as $key=>$value) {
    $counter = 0;
    echo "=====".$key." (key) | value: ".$value."<br/>";
    foreach ($value as $key2=>$value2) {
        if($value2 == null) {
            //echo "counter: ".$counter." | key: ".$key2;
            unset($arr[$key][$key2]);
        } else {
            print_r($value2);
            echo " [".$counter."]  [".$key2."]<br/>";
        }
        $counter++;
    }
}
?>

What we get in browser/console:
=====Org (key) | value: Array
Org Object ( [name] => tst0 ) [0] [0]
Org Object ( [name] => tst1 ) [1] [1]
Org Object ( [name] => tst2 ) [2] [2]
=====Org2 (key) | value: Array
Org2 Object ( [name] => wtf0 ) [0] [0]
Org2 Object ( [name] => wtf1 ) [1] [1]
Org2 Object ( [name] => wtf2 ) [2] [2]

--------

=====Org (key) | value: Array
Org Object ( [name] => tst0 ) [0] [0]
Org Object ( [name] => tst2 ) [1] [2]
=====Org2 (key) | value: Array
Org2 Object ( [name] => wtf0 ) [0] [0]
Org2 Object ( [name] => wtf1 ) [1] [1]
Org2 Object ( [name] => wtf2 ) [2] [2]
yuri 30-Nov-2011 10:00
If you want to put an element to a specific position in an array, try this function.

<?php

function array_put_to_position(&$array, $object, $position, $name = null)
{
        $count = 0;
        $return = array();
        foreach ($array as $k => $v)
        {
                // insert new object
                if ($count == $position)
                {
                        if (!$name) $name = $count;
                        $return[$name] = $object;
                        $inserted = true;
                }
                // insert old object
                $return[$k] = $v;
                $count++;
        }
        if (!$name) $name = $count;
        if (!$inserted) $return[$name];
        $array = $return;
        return $array;
}
?>

Example :

<?php
$a = array(
 'a' => 'A',
 'b' => 'B',
 'c' => 'C',
);

print_r($a);
array_put_to_position($a, 'G', 2, 'g');
print_r($a);

/*
Array
(
    [a] => A
    [b] => B
    [c] => C
)
Array
(
    [a] => A
    [b] => B
    [g] => G
    [c] => C
)
*/
?>
aosojnik at gmail dot com 23-Nov-2009 02:56
If you want to preserve the keys in the array, use the following:

<?php
function array_pshift(&$array) {
    $keys = array_keys($array);
    $key = array_shift($keys);
    $element = $array[$key];
    unset($array[$key]);
    return $element;
}
?>
rarioj at gmail dot com 04-Oct-2009 06:44
This function "Returns the new number of elements in the array."

To find out the last index, use:

<?php
$count = array_push($array, $value);
$last_index = array_pop(array_keys($array));
?>
Anonymous 20-Sep-2009 02:00
If you need to push the elements of an array onto the end of another, simply use array_splice():

array_splice($array, count($array), 0, $otherArray);
helpmepro1 at gmail dot com 13-Jan-2009 01:43
elegant php array combinations algorithm

<?

//by Shimon Dookin

function get_combinations(&$lists,&$result,$stack=array(),$pos=0)
{
 $list=$lists[$pos];
 if(is_array($list))
  foreach($list as $word)
  {
   array_push($stack,$word);
   if(count($lists)==count($stack))
    $result[]=$stack;
   else
    get_combinations($lists,$result,$stack,$pos+1);
   array_pop($stack);
  }
}

$wordlists= array( array("shimon","doodkin") , array("php programmer","sql programmer","mql metatrader programmer") );

get_combinations($wordlists,$combinations);

echo '<xmp>';
print_r($combinations);

?>
wesleys at opperschaap dot net 10-Oct-2008 12:58
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

<?php

function array_push_array(&$arr) {
    $args = func_get_args();
    array_shift($args);

    if (!is_array($arr)) {
        trigger_error(sprintf("%s: Cannot perform push on something that isn't an array!", __FUNCTION__), E_USER_WARNING);
        return false;
    }

    foreach($args as $v) {
        if (is_array($v)) {
            if (count($v) > 0) {
                array_unshift($v, &$arr);
                call_user_func_array('array_push',  $v);
            }
        } else {
            $arr[] = $v;
        }
    }
    return count($arr);
}

$arr = array(0);
$arr2  = array(6,7,8);
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));
print_r($arr);

# error..
$arr = "test";
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));

?>
willdemaine at gmail dot com 07-Aug-2008 07:00
If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements that I see all the time:

<?php
class timer
{
        private $start;
        private $end;

        public function timer()
        {
                $this->start = microtime(true);
        }

        public function Finish()
        {
                $this->end = microtime(true);
        }

        private function GetStart()
        {
                if (isset($this->start))
                        return $this->start;
                else
                        return false;
        }

        private function GetEnd()
        {
                if (isset($this->end))
                        return $this->end;
                else
                        return false;
        }

        public function GetDiff()
        {
                return $this->GetEnd() - $this->GetStart();
        }

        public function Reset()
        {
                $this->start = microtime(true);
        }

}

echo "Adding 100k elements to array with []\n\n";
$ta = array();
$test = new Timer();
for ($i = 0; $i < 100000; $i++)
{
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push\n\n";
$test->Reset();
for ($i = 0; $i < 100000; $i++)
{
        array_push($ta,$i);
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with [] 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        array_push($ta,$i,$i,$i,$i,$i,$i,$i,$i,$i,$i);
}
$test->Finish();
echo $test->GetDiff();
?>

Output

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

0.044686794281006

Adding 100k elements to array with array_push

0.072616100311279

Adding 100k elements to array with [] 10 per iteration

0.034690141677856

Adding 100k elements to array with array_push 10 per iteration

0.023932933807373
Ariz Jacinto 27-Jun-2008 04:41
if you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following example:

    array_push($data[$key], $value);
    ...
    array_push($data[$key], $value);
bxi at apparoat dot nl 23-May-2008 04:29
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    $array[] = $x;
}
?>
takes 0.0622200965881 seconds

and

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    array_push($array, $x);
}
?>
takes 1.63195490837 seconds

so if your not making use of the return value of array_push() its better to use the $array[] way.

Hope this helps someone.
alexander dot williamson at gmail dot com 26-Mar-2008 04:06
This will work to solve the associative array issues:

$aValues[$key] = $value;

Where $key is a unique identifier and $value is the value to be stored. Since the $key works off a string or number, if you already have a $key with the same value as an existing $key, the element will be overwritten.

e.g.

$aValues["one"] = "value of one";
$aValues["two"] = "different value of two!";

gives:
array([one] => "value of one", [two] => "value of two");

but will be overwritten when using the same key (one):

$aValues["one"] = "value of one";
$aValues["one"] = "different value of two!";

will give:

array([one] => "different value of two!");

3686
darkimmortal at dkimmortal dot com 18-Feb-2008 11:31
I wrote this function for use with 'latest scores' on a quiz site, but it has many potential uses.

<?php
/**
* @desc array_push and removes elements from the beginning of the array until it is within limit
* @param    array   Array to push on to
* @param    mixed   Passed to array push as 2nd parameter
* @param    int     Limit (default = 10)
*
* @return   array   New array
*/
function array_push_limit($array,$add,$limit=10){
    array_push($array, $add);
    do {
        array_shift($array);
        $size=count($array);
    } while($size > $limit);

    return $array;
}
?>
----------
EXAMPLE:
----------
<?php
    $array=array(1, -5, 23, -66, 33, 54, 3);
    print_r(array_push_limit($array, "HELLO", 4));
?>
----------
OUTPUT:
----------
Array
(
    [0] => 33
    [1] => 54
    [2] => 3
    [3] => HELLO
)
rob AT rate for the cure dot com 15-Aug-2007 09:09
I had a problem with .htaccess and some tricky encrypted paths (for protecting true dir names of images and files) and created this quick function to auto correct paths for the document root using regex and array_diff
<?
function fixPath($path){
        $temp = trim($path);
        $temp = eregi_replace("(\./|\.\./)","/",$temp);
        $temp = eregi_replace("([^/]+(\.htm|\.php))","",$temp);
        if(!eregi($_SERVER['DOCUMENT_ROOT'],$temp,$regs)){
            $partsA = explode("/",substr($temp,0,-1));
            $partsB = explode("/",$_SERVER['DOCUMENT_ROOT']);
            //if the path does not match the dir structure diff the array and reconstruct on the TRUE doc root
            $tHolder = array_diff($partsA,$partsB);
                foreach($tHolder as $k=>$v){
                    array_push($partsB,$v);
                }

            $temp =  implode("/",$partsB)."/";
        }
        return $temp;
    }
$correctPath = fixPath('.som/phpEncrypted/Path/class/class.QMI.php');
?>

The function strips out filename, checks to see if the path resolves to the doc root, and if it does not it takes the difference in the paths and returns a path that translates to the true path. This is useful for encoding paths where you want to obfuscate the true server path (such as creating external api functions)
zbde00 at hotmail dot com 20-Jul-2007 05:59
A very good function to remove a element from array
function array_del($str,&$array)
{
    if (in_array($str,$array)==true)
    {

        foreach ($array as $key=>$value)
        {
            if ($value==$str) unset($array[$key]);
        }
    }
}
antido at gmail dot com 03-Aug-2006 01:04
Simple data object implementation:

<?php

/**
 * Data object
 *
 * @version 0.6
 * @author Tom Reitsma <antido@gmail.com>
 */
Class DataObject
{
    /**
     * @var int $ptr
     */
    private $ptr = 0;

    /**
     * @var array $data
     */
    private $data = array();

    /**
     * Class constructor
     */
    public function __construct($anArray=false)
    {
        if($anArray != false)
        {
            if(is_array($anArray))
            {
                $this->data[] = $anArray;
            }
        }
    }

    /**
     * Fetches the data under the pointer
     *
     * @return String if there is still data left under the pointer, false if the end has been reached
     */
    public function fetch()
    {
        if(isset($this->data[$this->ptr]))
        {
            return $this->data[$this->ptr++];
        }

        return false;
    }

    /**
     * Moves to the next row in the data object
     *
     * @return boolean
     */
    public function moveNext()
    {
        $newPtr = $this->ptr + 1;

        if(isset($this->data[$newPtr]))
        {
            $this->ptr = $newPtr;
            return true;
        }

        return false;
    }

    /**
     * Moves to the previous row in the data object
     *
     * @return boolean
     */
    public function movePrevious()
    {
        $newPtr = $this->ptr - 1;

        if(isset($this->data[$newPtr]))
        {
            return $this->data[$newPtr];
        }

        return false;
    }

    /**
     * Pushes an element onto the array
     *
     * @param String or an array $input
     * @return number of elements
     */
    public function push($input)
    {
        if($this->getNumRows() > 0)
        {
            return array_push($this->data, $input);
        }
        else
        {
            return $this->data[] = $input;
        }
    }

    /**
     * Counts the number of rows
     */
    public function getNumRows()
    {
        return count($this->data);
    }
}

?>
Marc Bernet 15-May-2006 09:18
A small and basic implementation of a stack without using an array.

class node
{
        var $elem;
        var    $next;
}
class stack
{
    var $next;
    function pop()
    {
        $aux=$this->next->elem;
        $this->next=$this->next->next;
        return $aux;
    }
    function push($obj)
    {
        $nod=new node;
        $nod->elem=$obj;
        $nod->next=$this->next;
        $this->next=$nod;
    }
    function stack()
    {
        $this->next=NULL;
    }
}
richard dot udo at gmail dot com 09-Feb-2006 03:05
Just a typo i think but the code below will actually produce

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => Array
        (
            [0] => d
            [1] => e
            [2] => f
        )
)
egingell at sisna dot com 28-Jan-2006 06:06
If you push an array onto the stack, PHP will add the whole array to the next element instead of adding the keys and values to the array. If this is not what you want, you're better off using array_merge() or traverse the array you're pushing on and add each element with $stack[$key] = $value.

<?php

$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);

?>
The above will output this:
Array (
  [0] => a
  [1] => b
  [2] => c
  [3] => Array (
     [0] => a
     [1] => b
     [2] => c
  )
)
steve at webthoughts d\ot ca 12-Nov-2005 04:02
Further Modification on the array_push_associative function
1.  removes seemingly useless array_unshift function that generates php warning
2.  adds support for non-array arguments

<?
// Append associative array elements
function array_push_associative(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
               $ret++;
           }
       }else{
           $arr[$arg] = "";
       }
   }
   return $ret;
}

$items = array("here" => "now");
$moreitems = array("this" => "that");

$theArray = array("where" => "do we go", "here" => "we are today");
echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';

echo "<pre>";
print_r($theArray);
echo "</pre>";

?>

Yields:

4 is the size of $theArray.
Array
(
    [where] => do we go
    [here] => now
    [this] => that
    [five] =>
)
ludvig dot ericson at gmail dot com 31-Oct-2005 05:32
Previous comment was not fully imitating the array_push behaviour,
1) does not return number of items pushed
2) can only handle one array to push

> Revised associative_push function with absolute reference of arg1 array; left unchanged if arg2 is empty.

<?php
// Append associative array elements
function array_push_associative(&$arr) {
    $args = func_get_args();
    array_unshift($args); // remove &$arr argument
    foreach ($args as $arg) {
        if (is_array($arg)) {
            foreach ($arg as $key => $value) {
                $arr[$key] = $value;
                $ret++;
            }
        }
    }

    return $ret;
}

$theArray = array();
echo array_push_associative($theArray, $items, $moreitems) . ' items added to $theArray.';
?>
john 19-Oct-2005 01:33
A variation of kamprettos' associative array push:

// append associative array elements
function associative_push($arr, $tmp) {
  if (is_array($tmp)) {
    foreach ($tmp as $key => $value) {
      $arr[$key] = $value;
    }
    return $arr;
  }
  return false;
}

$theArray = array();
$theArray = associative_push($theArray, $items);
kamprettos at yahoo dot com Teguh Iskanto 19-Sep-2005 05:33
Looking for a way to push data into an associative array and frustrated to know that array_push() can't do the job ?

here's my Scenario :
-------------------
I need to relate system command output into an associative array like these :

[sge@digital_db work]$ /usr/local/apache/htdocs/work/qhost.sh -h t1 -F | awk '{if(NR>4) print $1}' | sed  's/hl://g'
arch=lx24-amd64
num_proc=2.000000
mem_total=3.808G
swap_total=3.907G
virtual_total=7.715G
load_avg=0.000000
load_short=0.000000
load_medium=0.000000
load_long=0.000000
mem_free=3.510G
swap_free=3.907G
virtual_free=7.417G
mem_used=305.242M
swap_used=0.000
virtual_used=305.242M
cpu=0.000000
np_load_avg=0.000000
np_load_short=0.000000
np_load_medium=0.000000
np_load_long=0.000000

how I did it :
<? php

# get into the system command output
$assoc_cmd =`$work_dir/qhost.sh -h $host_resource -F | awk '{if(NR>4) print $1}'| sed  's/hl://g' ` ;

# split the "\n" character
$assoc_row = explode("\n", chop($assoc_cmd));

# get the index row
$idx_row  = count($assoc_row) - 1 ;

# initialize the associative array
$host_res_array = array();

for ($i = 0 ; $i<= $idx_row ; $i++)
        {
                # get params & values
                list($host_param,$host_val) = explode("=",$assoc_row[$i]);

                # populate / push data to assoc array
                $host_res_array[$host_param]= $host_val ;
        }

echo "<pre> Architecture : </pre>\n" ;
echo $host_res_array['arch'] ;
echo "<pre> Mem Total    : </pre>\n" ;
echo $host_res_array['mem_tot'];

?>

Hope this helps ! :)
bk at quicknet dot nl 04-Sep-2005 01:51
Add elements to an array before or after a specific index or key:

<?php

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_before($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos), $in, array_slice($src,$pos));
    else{
        foreach($src as $k=>$v){
            if($k==$pos)$R=array_merge($R,$in);
            $R[$k]=$v;
        }
    }return $R;
}

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_after($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $in, array_slice($src,$pos+1));
    else{
        foreach($src as $k=>$v){
            $R[$k]=$v;
            if($k==$pos)$R=array_merge($R,$in);
        }
    }return $R;
}

// Examples:

$src=array("A","B","C");
$in=array("X","Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "X"
  [2]=>
  string(1) "Y"
  [3]=>
  string(1) "B"
  [4]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "X"
  [3]=>
  string(1) "Y"
  [4]=>
  string(1) "C"
}*/

$src=array('a'=>"A",'b'=>"B",'c'=>"C");
$in=array('x'=>"X",'y'=>"Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, key array, before index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_before($src,$in,'b'));
/* array_push_before, key array, before key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, key array, after index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,'b'));
/* array_push_after, key array, after key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

?>
ciprian dot amariei at gmail com 30-Aug-2005 02:47
regarding the speed of oneill's solution to insert a value into a non-associative array,  I've done some tests and I found that it behaves well if you have a small array and more insertions, but for a huge array and a little insersions I sugest  using this function:

function array_insert( &$array, $index, $value ) {
   $cnt = count($array);

   for( $i = $cnt-1; $i >= $index; --$i ) {
       $array[ $i + 1 ] = $array[ $i ];
   }
   $array[$index] = $value;
}

or if you are a speed adicted programmer (same situation: big array, few insertions) use this:

array_splice ( $array, $offset, 0, $item );

item may also be an array of values ;).
Phil Davies 18-Jul-2005 03:51
As someone pointed out the array_push() function returns the count of the array not the key of the new element. As it was the latter function i required i wrote this very simple replacement.

function array_push2(&$array,$object,$key=null){
    $keys = array_keys($array);
    rsort($keys);
    $newkey = ($key==null)?$keys[0]+1:$key;
    $array[$newkey] = $object;
    return $newkey;
}
oneill at c dot dk 03-Jun-2005 01:50
To insert a value into a non-associative array, I find this simple function does the trick:

function insert_in_array_pos($array, $pos, $value)
{
  $result = array_merge(array_slice($array, 0 , $pos), array($value), array_slice($array,  $pos));
  return $result;
}

Seems an awful lot simpler than the iterative solutions given above...
aaron dot hawley at uvm dot edu 27-May-2005 11:36
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does.  There's another difference between array_push and the recommended empty bracket notation.

Empy bracket doesn't check if a variable is an array first as array_push does.  If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.
josh at digitalfruition dot com 14-Feb-2005 10:17
Note that array_push() will, as described, return the COUNT of the array after adding a new item, not necessarily the INDEX of that new item:

<?php
$array = array(3 => 'three', 5 => 'five');

echo "\$array = ";
print_r($array);
echo "\n\n";

$to_push = array(1,2,4,);
foreach($to_push as $var)
{
    echo "calling array_push(\$array,$var); retval is ";
    echo array_push($array,$var);
    echo "\n";
}

echo "\$array = ";
print_r($array);
?>

The output of above is:

$array = Array
(
    [3] => three
    [5] => five
)

calling array_push($array,1); retval is 4
calling array_push($array,2); retval is 5
calling array_push($array,4); retval is 6
$array = Array
(
    [3] => three
    [5] => five
    [7] => seven
    [8] => 1
    [9] => 2
    [10] => 4
)

Notice how when array_push($array,1) was called, the new element has a key of 8 but array_push() returns 4.
andrew at cgipro dot com 02-Feb-2005 03:18
Need a real one-liner for adding an element onto a new array name?

$emp_list_bic = $emp_list + array(c=>"ANY CLIENT");

CONTEXT...
drewdeal: this turns out to be better and easier than array_push()
patelbhadresh: great!... so u discover new idea...
drewdeal: because you can't do:   $emp_list_bic = array_push($emp_list, c=>"ANY CLIENT");
drewdeal: array_push returns a count and affects current array.. and does not support set keys!
drewdeal: yeah. My one-liner makes a new array as a derivative of the prior array
aron 24-Feb-2004 02:48
The problem with array_push is that it is pass by value.  If you are dealing with objects whose inner state may change at any time, you need a push and pop who return the actual objects, rather than copies of them.
After some difficulty and board assistance, I have these methods.  I've tested them, and they seem to work fine.

<?php
function push(&$array, &$object){
    $array[] =& $object;
}
function & pop(&$array){
    return array_pop($array);
}

// [Test Code]
class TestObject{
    var $value = 0;
    function getValue(){
        return $this->value;
    }
    function setValue($mixed){
        $this->value = $mixed;
    }
}
$myarr = array();
$tmp =& new TestObject();
$tmp2 =& new TestObject();
$tmp->setValue(2);
$tmp2->setValue(3);

push($myarr, $tmp);
push($myarr, $tmp2);
$tmp->setValue(4);
$tmp2->setValue(6);
$val = pop($myarr);
print "popped value: ".$val->getValue()."<br />";

print "values in internal array: <br />";
foreach ($myarr as $key=>$value){
    print "key: $key, object: $value, value: ";
    print  $value->getValue()."<br />";
}
// [/TestCode]
?>
skiflyer 20-Jan-2004 04:05
However, don't forget that array_push() does more than [], it also performs a count and returns the value.

Modifying your code ever so slightly (see below), this puts array_push in the lead (not suprisingly).  So my conclusion would be that if I care about the number of elements in the array, then I'd use array_push(), if I don't (which is usually the case), then I'd use the [] method.

Results...
[] method: 0.34943199
push method: 0.31505919
difference: -0.03437280

Modified section of code...
$s_test_begin = FullMicroTime();
for($i = 0; $i <= 50000; $i++) { $num_tot = array_push($test2, $i); }
$s_test_end = FullMicroTime();

$f_test_begin = FullMicroTime();
for($i = 0; $i <= 50000; $i++) { $test[] = $i; $num_tot = count($test); }
$f_test_end = FullMicroTime();
daevid at daevid dot com 16-Feb-2003 08:38
Sadly, array_push() does not create an array if the array doesn't exist.  So if you're pushing the first element onto an array, you need to check and create it manually...

<?php
if ( !is_array($myArray) ) $myArray= array();
array_push($myArray, $myElement);
?>
bart at framers dot nl 27-Sep-2001 04:16
Array_push also works fine with multidimensional arrays. Just make sure the element is defined as an array first.

<?php
$array["element"][$element]["element"] = array();
array_push ($array["element"][$element]["element"], "banana");
?>
array_product
array_rand
Функции для работы с массивами


Выбирает одно или несколько случайных значений из массива

array_push
array_reduce
Функции для работы с массивами
PHP Manual

array_rand

(PHP 4, PHP 5)

array_rand — Выбирает одно или несколько случайных значений из массива

Описание

mixed array_rand ( array $input [, int $num_req = 1 ] )

Выбирает одно или несколько случайных значений из массива. Возвращает ключ (или ключи) данных случайных элементов.

Список параметров

input

Входной массив.

num_req

Определяет количество выбираемых элементов. Попытка выбрать больше элементов, чем есть в массиве, сгенерирует ошибку уровня E_WARNING.

Возвращаемые значения

Если вы выбираете только одно значение, функция array_rand() возвращает ключ, соответствующий этому значению. В обратном случае, она возвращает массив ключей, соответствующих случайным значениям. Это сделано так образом, чтобы дать возможность выбрать из массива как случайные значения, так и случайные ключи.

Список изменений

Версия | Описание
5.2.10 | Возвращаемый массив ключей больше не возвращается в случайном порядке.
4.2.0 | Генератор случайных чисел инициализируется автоматически.

Примеры

Пример #1 Пример использования array_rand()

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

Смотрите также

  • shuffle() - Перемешивает массив

User Contributed Notes

qeremy 07-Mar-2012 01:18
An example for getting random value from arrays;

<?php
function array_random($arr, $num = 1) {
    shuffle($arr);

    $r = array();
    for ($i = 0; $i < $num; $i++) {
        $r[] = $arr[$i];
    }
    return $num == 1 ? $r[0] : $r;
}

$a = array("apple", "banana", "cherry");
print_r(array_random($a));
print_r(array_random($a, 2));
?>

cherry
Array
(
    [0] => banana
    [1] => apple
)

And example for getting random value from assoc arrays;

<?php
function array_random_assoc($arr, $num = 1) {
    $keys = array_keys($arr);
    shuffle($keys);

    $r = array();
    for ($i = 0; $i < $num; $i++) {
        $r[$keys[$i]] = $arr[$keys[$i]];
    }
    return $r;
}

$a = array("a" => "apple", "b" => "banana", "c" => "cherry");
print_r(array_random_assoc($a));
print_r(array_random_assoc($a, 2));
?>

Array
(
    [c] => cherry
)
Array
(
    [a] => apple
    [b] => banana
)
Sebmil 05-Aug-2011 12:18
Looks like this function has a strange randomness.

If you take any number of elements in an array which has 40..100 elements, the 31st one is always by far the less occuring (by about 10% less than others).

I tried this piece of code at home (PHP Version 5.3.2-1ubuntu4.9) and on my server (PHP Version 5.2.17), unfortunately i haven't any server with the last version here :

<?php
$valeurs = range(1, 40);
$proba = array_fill(1, 40, 0);
for ($i = 0; $i < 10000; ++$i)
{
    $tirage_tab = array_rand($valeurs, 10);
    foreach($tirage_tab as $key => $value)
    {
        $proba[$valeurs[$value]]++;
    }
}

asort($proba);
echo "Proba : <br/>\n";
foreach($proba as $key => $value)
{
    echo "$key : $value<br/>\n";
}
?>

In every try, the number of occurrences change a bit but the 31 is always far less (around 2200) than the others (2400-2600). I tried with 50 and 100 elements, no change. I tried with more or less elements to pick (second parameter to array_rand), same result. If you pick only one element it's even worse : 31 has half the result of the others.

For this particular case, i recommend shuffling the array and taking the nth first elements, in this test it's 60% faster and the statistics are ok.
zenko 15-Jun-2010 11:55
unset() seem to me to be a better way to have a unique key in the generated result.
Taking 1 from $i can last very long if you generate a long password (try with 20 chars) because array_rand can always "choose" a key which has already been used.
<?php

$my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "0", "1", "2", "3", "4", "5");
$parola = '';
    for ($i=0; $i<=15; $i++)
    {
        // Generates the random number from the array
        $random = array_rand($my_array);

        // Echo the count number and the random number called from array_rand
        // and print the array to see the last random char has been deleted
        echo '<br /> count ' . $i . ' => ' . $random . ' call<br />';
        print_r($my_array);

        // Add the char to parola...
        $parola .= $my_array[$random];

        // ...then unset the char from the array
        unset($my_array[$random]);

    }

    // Echo the result
    echo '<br /><br /> Parola generated : ' . $parola;
?>
Anonymous 02-Oct-2009 01:04
If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

<?php array_rand(array_flip($array), $n); ?>
darren(at)ironworks-crawley(do)co(do)uk 24-Feb-2009 07:52
adapted from herodesh's code,
will pull a number of unique from arrays.

<?php

$my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "0", "1", "2", "3", "4", "5");
        for ($i=0; $i<=10; $i++)
        {
            $random = array_rand($my_array);
                        //this generates the random number from the array
            echo "<br> count $i <br> $random call";
                    // echo the count number and the random number called from array_rand
                    if ($check[$random]<>0) {
                    $i--;
                    echo "ed already try again";
                    // if check array isnt = 0 then the random number has been already called re random by taking 1 from $i to ensure correct number of results
                    } else {
                    $check[$random]=1;
                    // set check to 1 so it knows the array number has been used
            $parola .= $my_array[$random];}
                        //here we will display the exact charachter from the array
        }
        echo "<br> $parola"; // printing result
        ?>
//delete as required
This is my first php script or code or adaption (so be kind),As its most likely bad coding. i have been looking at using php to pull and display random pictures to display on the website not pulling the same picture twice. work obviously required.changing contents of $my_array to "<img src="bla-bla1.jpg>"
Basically it just calls an array_rand as in herodesh's code, but uses a second "fake" array to flag true or false (1 or null) to compare if it has been called prior. changing $check[$random]=1 to $check[$random]++1 and if ($check[$random]<>0) to if ($check[$random]<2) obviously changes the number of times it allows the same array to be called randomly.
info at pavliga dot com 28-Dec-2008 01:52
If you want get unique range:

<?php
$n = 15;

$data = range(1, 20);
$rand = array_rand($data,$n);

for($i=0; $i<$n; $i++)
{
echo $rand[$i]."<br>";
}

?>
admin at jeremyzaretski dot com 15-Dec-2008 08:11
<?php
// a foreach friendly version of array_rand
function Select_Random_Indices($source_array, $count = 1)
{
    if($count > 0)
    {
        if($count == 1)
        {
            $result = array(array_rand($source_array, $count));
        }
        else
        {
            $result = array_rand($source_array, $count);
        }
    }
    else
    {
        $result = array();
    }

    return $result;
}

// using the above function to pick random values instead of entries
function Select_Random_Entries($source_array, $count = 1)
{
    $result = array();
    $index_array = Select_Random_Indices($source_array, $count);

    foreach($index_array as $index)
    {
        $result[$index] = $source_array[$index];
    }

    return $result;
}
?>
MadeGlobal 30-May-2008 03:16
A problem exists with the array_pick function suggested by adrian.quark - if the function only has to remove one item from the array (e.g. original array has five entries and you want it to return four), you get a problem with the different behavior of array_rand when the parameter is 1

Fixed implementation:

<?php

function array_pick($hash, $num) {
  $count = count($hash);
  if ($num <= 0) return array();
  if ($num >= $count) return $hash;
  $required = $count - $num;
  if ($required == 1) {   //array rand returns the KEY if there is only one item requested so...
      $keys = array(array_rand($hash, $required));
  } else
      $keys = array_rand($hash, $required);
  foreach ($keys as $k) unset($hash[$k]);
  return $hash;
}

?>
adrian.quark at alchemysystems dot com 04-Jan-2008 10:57
Here is a function to pick a random fixed-size subset of an array without changing the order. It's possible to be slightly faster in some cases if you know the array keys are numeric or if you're only picking a few elements, but this is a good general implementation.

<?php
/**
 * Pick $num elements from $array at random, preserving order and keys.
 */
function array_pick($hash, $num) {
        $count = count($hash);
        if ($num <= 0) return array();
        if ($num >= $count) return $hash;
        $keys = array_rand($hash, $count - $num);
        foreach ($keys as $k) unset($hash[$k]);
        return $hash;
}
?>
herodesh [-at_] gmail [-dot-] com 05-Sep-2007 03:36
this is to generate a random selection from an array with array_rand preety nice, can be used to generate random passwords or anything:

$my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "0", "1", "2", "3", "4", "5");
        for ($i=0; $i<=10; $i++)
        {
            $random = array_rand($my_array);
                        //this generates the random number from the array
            $parola .= $my_array[$random];
                        //here we will display the exact charachter from the array
        }
        echo $parola; // printing result
Hayley Watson 11-Jun-2007 08:38
To add to asp at cyberlin dot eu's comment. Not only will it return NULL but it will also trigger a warning, and not only if the number of elements requested is too large to be satisfied by the array but also if it is zero. The warning message sums the situation up: "Second argument has to be between 1 and the number of elements [inclusive] in the array".
asp at cyberlin dot eu 13-Apr-2007 01:24
array_rand() is very useful, but note:

In the case that the count of the array is smaller then the optional parameter 'num_req', it will return an empty array (or string).
Reinoud Elhorst 10-Apr-2007 03:50
Please note that (at least in PHP 4.3.11), while each key from the source array has a equal chance of being picked, the order in which they are returned is NOT random. In an array with keys from one to 10, where 2 random keys are picked, 0 is picked as the first number 18.8% of the time, and only as second number in 1.1% of the time:

$n=100000;
$a=array(1,2,3,4,5,6,7,8,9,10);
$b=array();
for($i=0;$i<sizeof($a);$i++) {
  $b[$i]=array(0,0);
}
for($i=0;$i<$n;$i++) {
  $keys=array_rand($a,2);
  $b[$keys[0]][0]++;
  $b[$keys[1]][1]++;
}
for ($i=0;$i<sizeof($b);$i++){
  printf("%d: %04.1f%% %04.1f%% %04.1f%%", $i, ($b[$i][0]/$n*100),($b[$i][1]/$n*100),($b[$i][0]+$b[$i][1])/$n*100);
}

The result is:
0: 18.8% 01.1% 19.9%
1: 17.0% 03.3% 20.3%
2: 14.3% 05.7% 20.0%
3: 12.2% 07.9% 20.1%
4: 10.0% 10.0% 20.0%
5: 07.8% 12.0% 19.8%
6: 05.5% 14.5% 20.0%
7: 03.3% 16.6% 19.9%
8: 01.2% 18.9% 20.1%
9: 10.0% 09.9% 19.9%

The workaround is adding a shuffle command to shuffle the keys:

0: 10.0% 10.0% 20.0%
1: 10.0% 10.0% 20.0%
2: 10.0% 10.0% 20.0%
3: 10.0% 10.0% 20.0%
4: 10.0% 10.0% 20.0%
5: 10.0% 10.0% 20.0%
6: 10.1% 10.0% 20.1%
7: 10.0% 10.0% 20.0%
8: 10.0% 10.0% 20.0%
9: 10.0% 10.0% 20.0%
Sven Arduwie 28-Jan-2007 05:40
Here is my array_mt_rand function.
<?php
    function array_mt_rand(array $array, $numberOfKeys = 1)
    {
        if (!is_int($numberOfKeys)) throw new Exception;
        if ($numberOfKeys < 1) throw new Exception;
        $keys = array_keys($array);
        $maximum = count($array) - 1;
        if ($numberOfKeys == 1) {
            return $keys[mt_rand(0, $maximum)];
        } else {
            $randomKeys = array();
            for ($i = 0; $i < $numberOfKeys; $i++) {
                $randomKeys[] = $keys[mt_rand(0, $maximum)];
            }
            return $randomKeys;
        }
    }
?>
Frederick Lemasson aka djassper at gmail 04-Dec-2006 12:57
To select a random Value (not a Key) from a Multi-Dimentionnal array I made a recursive function : array_multi_rand()

the following exemple randomly selects an url from a multidimentionnal array :

<?

$Expos['Google']['Science']='news.google.fr/news?topic=t';
$Expos['Google']['Economie']='news.google.fr/news?topic=b';
$Expos['Google']['Sante']='news.google.fr/news?topic=m';
$Expos['Yahoo']='fr.news.yahoo.com';
$Expos['Events']['LogicielLibre']='agendadulibre.org';
$Expos['MyBlog']='www.kik-it.com';

function array_multi_rand($Zoo){
    $Boo=array_rand($Zoo);
    if(is_array($Zoo[$Boo])){
        return array_multi_rand($Zoo[$Boo]);
    }else{
        return $Zoo[$Boo];
    }
}

echo(array_multi_rand($Expos));

?>
jan at planetromeo dot com 24-Nov-2006 08:56
Instead of using the horrible slow

select * from some_table order by rand() limit 1;

have a look at this more performant solution from
http://jan.kneschke.de/projects/mysql/order-by-rand/

SELECT * FROM some_table AS r1
JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM some_table)) AS id) AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1;
alec 10-Nov-2006 05:37
select * from some_table order by rand() limit 1;

is extremely slow for large tables. large as in a a few thousand entries.
dbrooks at icarusstudios dot com 05-Sep-2006 02:28
Instead of looping through all the rows selected to pick a random one, let the server do the work for you:

select * from some_table order by rand() limit 1;
JS 04-Sep-2006 03:07
I wanted to write something that picks a random entry from a 1column-MySQL database - simply Post Of The Moment (potm). I know there surly are many better ways to do it, but I`m rather new to PHP :)  Anyway, it`s simple and no-problem working code.
Of course I assume your DB exists and you always have something in it.

@$link = MySQL_Connect("localhost", "username", "password"); //connect to mysql
mySQL_Select_DB("database"); //..to DB
@$potms = MySQL_Query("SELECT * FROM potm"); //now we get all from our table and store it
MySQL_Close($link); //there`s no need for connection, so we should close it

$potm_array = ''; //sets variables to "zero" values
$i = 0;
while ($entry = MySQL_Fetch_Array($potms)) //now we go through our DB
       {
         $potm_array[$i] = $entry; //our temporary array from which we will random pick a field key
         $i++; //now we increment our field key
       }

$potm_id = array_rand($potw_array); //picks a random key from array
$potm = $potm_array[$potm_id]['name_of_the_field']; //now we have stored our Post Of The Moment in $potm

..hope this helps
mark at rugbyweb dot org 30-Aug-2006 01:29
I was setting up a rotating add banner and was trying to find a way to go about it using an auto_increment id from the database, so I wrote this little script:

<?php
require "mysql.php";
global $c;
print "<center>";
$qq=mysql_query("SELECT adID FROM ads WHERE adCLICKS<=adMAX",$c) or die (mysql_error()."<br>Error, please report this error quoting #QAB");
while($q=mysql_fetch_array($qq))
{
$ad1[$q['adID']]++; //Used an array and inserted the database query results into it.
}
$ad=array_rand($ad1, 1); //Did a random array function and then used it in the query below.
$er=mysql_query("SELECT * FROM ads WHERE adID='$ad'") or die (mysql_error()."<br>Error, please report this error quoting #QAB3");
if(!mysql_num_rows($er))
{
print "<A href='advertise.php'>Place an ad here!</a>";
exit;
}
$r=mysql_fetch_array($er);
print "<a href='adsout.php?ID={$r['adID']}&BLOCK=1'><img src='{$r['adAD']}' alt='{$r['adNAME']}' height='60' width='468'></a>";
?>
dragonfly at dragonflyeye dot net 07-Jul-2006 01:28
Well, I came up with a workaround for my earlier problem.  For those of you who might need to shuffle around multi-dimensional arrays (I used this to randomize a list of headlines from a MySQL database query), here's what I did to get the desired output:

$subs = //my query went here
$shfl = array_rand($subs, 5);
$shsubs = array();
for ($x=0; $x<count($shfl); $x++) {
    $shsubs[] = $subs[$shfl[$x]];
}

There may in fact be a much easier way to do this, but this is what I came up with and its working!

Thanks to everyone that makes php.net the invaluable tool for us nooobies!
dragonfly at dragonflyeye dot net 07-Jul-2006 07:57
Well, this is interesting.   I don't see anyone else commenting on this, so just in case you were planning to use this function like I was, be prepared: array_rand does not handle multidimensional arrays.  It just ends up returning a list of the X-axis values without the Y-axis arrays.  Bummer.  I'm going to have to find another way to do what I wanted.
steve at webcommons dot biz 05-Jul-2006 02:12
Following are functions for getting a random key or value (or array of random keys or values) from a filtered array.  In other words, given an array of data, these functions filter out what you don't want, then extract a random element or bunch from what's left.

$CallBack is the filtering function.

  // Utility function for functions below
  function GetRandomArrayValue($TheArray) {
      return $TheArray[array_rand($TheArray)];
  }

  // Get a random key or array of keys from a filtered array
  function GetRandomFilteredArrayKeys($aInput, $CallBack = NULL, $NumReq = 1) {
      $FilteredKeys = array_keys(array_filter($aInput, $CallBack));

      if ($NumReq <= 1) {
        return GetRandomArrayValue($FilteredKeys);
      }
      else {
        shuffle($FilteredKeys);

        return array_slice($FilteredKeys, 0, $NumReq);
      }
  }

  // Get a random value or array of values from a filtered array
  function GetRandomFilteredArrayValues($aInput, $CallBack = NULL, $NumReq = 1) {
      $aFiltered = array_filter($aInput, $CallBack);

      if ($NumReq <= 1) {
        return $aFiltered[GetRandomArrayValue(array_keys($aFiltered))];
      }
      else {
        shuffle($aFiltered);

        return array_slice($aFiltered, 0, $NumReq);
      }
  }
trukin at gmail dot com 16-Mar-2006 01:23
Modify of last note:
<?php
if (!function_exists('array_rand')) {
    function array_rand($array, $lim=1) {
        mt_srand((double) microtime() * 1000000);
        for($a=0; $a<=$lim; $a++){
            $num[] = mt_srand(0, count($array)-1);
        }
        return @$num;
    }
}
?>

mt_rand generates a better random number, and with the limit.
emailfire at gmail dot com 13-Mar-2006 01:32
<?php
if (!function_exists('array_rand')) {
function array_rand($array) {
srand((double) microtime() * 1000000);
return rand(0, count($array)-1);
}
}
?>
Will-ster 01-Jan-2006 04:18
This is something I have been playing with for quite awhile. I'm very new to php, but i finally got it to work. it's a function that will take and array[$arrquo] and find a particular keyword[$find] in the different elements of the array then take those elements that posess that keyword and display them at random

<?php
function popbyword($arrquo,$find)
{
$newarr = array('');
 foreach($arrquo as $line)
 {
  if( strstr( $line, $find ) )
  {
    array_push($newarr, $line);

  }
 }
srand((double)microtime()*1000000);
$rquote = array_rand($newarr);
echo $newarr[$rquote];
}

popbyword($images, 'Albert');
?>

In my case I had this huge array of quotes with 90 some elements. I was able to find certain keywords in those elements then ONLY display the elements that had those keywords. NEAT! Maybe only because I'm new.
farooqym at ieee dot org 01-Jan-2006 02:05
Here's an algorithm to make a weighted selection of an item from an array.
Say we have an array $items with keys as items and values as corresponding weights.
For example:
<?php
$items = array(
    item1 => 3,
    item2 => 4,
    item3 => 5,
);
?>
i.e. we want to choose item1 25% of the time, item2 33.3% of the time and item3 41.6% of the time.
Here's a function that works when the weights are positive integers:
<?php
function array_rand_weighted($values) {
    $r = mt_rand(1, array_sum($values));
    foreach ($values as $item => $weight) {
        if  ($r <= $weight) return $item;
        $r -= $weight;
    }
}
?>
Enjoy!
bjcffnet at gmail dot com 29-Aug-2005 04:29
As wazaawazaa600 at msn dot com pointed out, a multi-dimensional array doesn't work with this function. So, I hope I can help someone with this :)

<?php
/**
 * Returns a number of random elements from an array.
 *
 * It returns the number (specified in $limit) of elements from
 * $array. The elements are returned in a random order, exactly
 * as it was passed to the function. (So, it's safe for multi-
 * dimensional arrays, aswell as array's where you need to keep
 * the keys)
 *
 * @author Brendan Caffrey  <bjcffnet at gmail dot com>
 * @param  array  $array  The array to return the elements from
 * @param  int    $limit  The number of elements to return from
 *                            the array
 * @return array  The randomized array
 */
function array_rand_keys($array, $limit = 1) {
    $count = @count($array)-1;

    // Sanity checks
    if ($limit == 0 || !is_array($array) || $limit > $count) return array();
    if ($count == 1) return $array;

    // Loop through and get the random numbers
    for ($x = 0; $x < $limit; $x++) {
        $rand = rand(0, $count);

        // Can't have double randoms, right?
        while (isset($rands[$rand])) $rand = rand(0, $count);

        $rands[$rand] = $rand;
    }

    $return = array();
    $curr = current($rands);

    // I think it's better to return the elements in a random
    // order, which is why I'm not just using a foreach loop to
    // loop through the random numbers
    while (count($return) != $limit) {
        $cur = 0;

        foreach ($array as $key => $val) {
            if ($cur == $curr) {
                $return[$key] = $val;

                // Next...
                $curr = next($rands);
                continue 2;
            } else {
                $cur++;
            }
        }
    }

    return $return;
}
?>
alexkropivko at(dog) yandex dot ru 16-Jun-2005 06:21
There was a mistake at "Paul Hodel (paul at ue dot com dot br) 17-Apr-2003 04:40":
String
echo $new_input = $input[$v];

have to be:
echo $new_input[] = $input[$v];
maxnamara at yahoo dot com 13-Mar-2005 03:22
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

function my_array_rand($input,$i=2){
srand((float) microtime() * 10000000);

$rand_keys = array_rand($input, $i);

/*
print $input[$rand_keys[0]] . "\n";
print $input[$rand_keys[1]] . "\n";
*/

$res = array();

if($i > 1){

for($a=0;$a<$i;$a++){

    $res[] = $input[$rand_keys[$a]];

}

}
else{

    $res[] = $input[$rand_keys];

}

return $res;
}

$a = my_array_rand($input,3);
echo "<pre>";
print_r($a);
echo "</pre>";
?>
yhoko at yhoko dot com 27-Aug-2004 06:16
According to office at at universalmetropolis dot com I have to say that the example is wrong.

<?php
// retrieve one of the options at random from the array
$teamcolours = $teamcolours[rand(0,count($teamcolours))];
?>

The count() function will return the number of items in the array, that's the last index + 1. So if there's 2 items in the array, count() will return 2 but the indices are 0 and 1. Now since rand(x,y) randomizes between x and y inclusively the index from the above example may be out of bounds. Thus you have to subtract 1 from the count:

<?php
    // Get random item
    $teamcolours = $teamcolours[rand(0,count($teamcolours)-1)];
?>
leighm at linuxbandwagon dot com leigh morresi 08-Mar-2004 07:36
Another array based password generator, this one is a port from the python mailman version.

this generates slightly predictable but human readable passwords that people can remember
output passwords are for example "rikanumi"

<?php
// port of mailman version
function MakeRandomPassword($length=6) {
$_vowels = array ('a', 'e', 'i', 'o', 'u');
$_consonants = array ('b', 'c', 'd', 'f', 'g', 'h', 'k', 'm', 'n','p', 'r', 's', 't', 'v', 'w', 'x', 'z');
$_syllables = array ();
foreach ($_vowels as $v) {
    foreach ($_consonants as $c) {
        array_push($_syllables,"$c$v");
        array_push($_syllables,"$v$c");
    }
}

for ( $i=0;$i<=($length/2);$i++)         $newpass=$newpass.$_syllables[array_rand($_syllables) ];

return $newpass;
?>

}
tim dot meader at gsfc dot nasa dot gov 05-Mar-2004 06:31
Just thought I would contribute a password generation function
that uses array_rand. I wrote this because I
could not find anywhere a PHP equivalent of the ability
that the String::Random module in Perl has, which allows
you to specify a schema for how you want the random
string created. In other words: I want 2 Uppercase, 3
lowercase, 2 intergers...etc.  This isn't too comprehensive,
notably it doesn't account for one choosing more itterations
 of a particular type than there are in the array (ie -
choosing more than 10 numbers from output). Additionally,
this doesn't allow for any repeated characters. Hope it can
be of use... comments appreciated.

<?php
    function &doGeneratePasswords()
    {
        //////////////////////////////////////
        // lowercase L left out for clarity //
        //////////////////////////////////////
        $l_achLowercase = array("a","b","c","d","e","f","g","h",
                                  "i","j","k","m","n","o","p","q",
                                  "r","s","t","u","v","w","x",
                                  "y","z");
        $l_iNumLowercase = count($l_achLowercase);

        ////////////////////////////////////////////
        // uppercase I and O left out for clarity //
        ////////////////////////////////////////////
        $l_achUppercase = array("A","B","C","D","E","F","G","H",
                                  "J","K","L","M","N","P","Q",
                                  "R","S","T","U","V","W",
                                  "X","Y","Z");
        $l_iNumUppercase = count($l_achUppercase);

        $l_aiNumbers = array("1","2","3","4","5","6","7","8","9","0");
        $l_iNumNumbers = count($l_aiNumbers);

        $l_achSpecialChars = array("!","#","%","@","*","&");
        $l_iNumSpecialChars = count($l_achSpecialChars);

        ///////////////////////////////////////////////////////////////////
        // Make sure to create enough blank spaces as you want passwords //
        ///////////////////////////////////////////////////////////////////
        $l_astPasswds = array("","","","");

        //////////////////////////////////////////
        // Hopefully these are self explanatory //
        //////////////////////////////////////////
        $l_astPasswdSchemes = array("SLUUSLNN","LSUNLLNU","NNUSLLSN","LNLSUNLU");

        $l_iNumPasswds = count($l_astPasswdSchemes);

        for ($i=0; $i < $l_iNumPasswds; $i++) {
            $l_iSchemeLength = strlen($l_astPasswdSchemes[$i]);

            $l_achRandLowercase = array_values(array_rand($l_achLowercase, $l_iNumLowercase));
            $l_achRandUppercase = array_values(array_rand($l_achUppercase, $l_iNumUppercase));
            $l_aiRandNumbers = array_values(array_rand($l_aiNumbers, $l_iNumNumbers));
            $l_achRandSpecialChars = array_values(array_rand($l_achSpecialChars, $l_iNumSpecialChars));

            for ($j=0; $j < $l_iSchemeLength; $j++) {
                $l_chCurrentOne = $l_astPasswdSchemes[$i]{$j};

                switch ($l_chCurrentOne) {
                    case "L":
                        $l_astPasswds[$i] .= $l_achLowercase[array_shift($l_achRandLowercase)];
                        break;

                    case "U":
                        $l_astPasswds[$i] .= $l_achUppercase[array_shift($l_achRandUppercase)];
                        break;

                    case "N":
                        $l_astPasswds[$i] .= $l_aiNumbers[array_shift($l_aiRandNumbers)];
                        break;

                    case "S":
                        $l_astPasswds[$i] .= $l_achSpecialChars[array_shift($l_achRandSpecialChars)];
                        break;

                    default:
                        break;
                }
            }
        }

        return $l_astPasswds;
    }
?>
jpinedo 02-Nov-2003 01:15
An array of arrays example:

<?php
$banners[0]['imagen']="imagen0.gif";
$banners[0]['url']="www.nosenada.tal";

$banners[1]['imagen']="imagen1.gif";
$banners[1]['url']="www.nose.tal";

$banners[2]['imagen']="imagen2.gif";
$banners[2]['url']="pagina.html";

$banners[3]['imagen']="imagen3.jpg";
$banners[3]['url']="../pagina.php";

$id_banner = array_rand($banners);

echo  "Archivo:--".$banners[$id_banner]['imagen']. "<br />\n";
echo  "URL:-----".$banners[$id_banner]['url']. "<br />\n";
?>
wazaawazaa600 at msn dot com 15-Oct-2003 12:24
The function go well ever that you work with a simple array. An array of arrays (also called a table), not works with the function correctly. Example:

<?php
$a=array(array(0,1),array(1,2),array(2,3),array(3,4),array(4,5));
echo $a[0][0];echo"<br>";
echo $a[1][0];echo"<br>";

$b=array_rand($a,2);
echo $b[0][0];echo"<br>"; //This writes nothing
echo $b[1][0];echo"<br>"; //This writes nothing
?>

If you are in this situation, you will need to make your own solution.
asarnoNOSPAM@interbaun DOT com 23-Jun-2003 11:06
It is correct that using array_rand() with num_req=1 will return an integer and not an array, but why get so complicated with getting just the one value.  The K.I.S.S. method would suggest to do it this way:

<?
srand((double)microtime() * 10000000);
$originalArray = array("red", "blue", "green", "brown",
"cyan", "magenta", "purle", "cheezy");
$pickOne = array_rand($originalArray, 1);
$aRandomSelection = $originalArray[$pickOne ];
echo "$aRandomSelection was the random selection made";
?>

You only need to use the foreach if the num_req >=2. In those cases the array_rand() function will return an array of random elements which are a subset of the original array.  When num_req = 1, the array_rand() function returns an integer that signifies a randomly picked key of the original array.  Hope this clarifies things ... it works for me.
c at aufbix dot org 13-Jun-2003 01:31
If you use array_rand with num_req=1, it will return an integer, and not an array as it would in all other circumstances. You can bypass that like this:

<?php
$randelts=array_rand($feeds,$num);

for ($j=0;$j<count($randelts);$j++) {
  if ($num==1) {$subq[$j]=$feeds[$randelts];}
  else {$subq[$j]=$feeds[$randelts[$i]]}
}
?>
Paul Hodel (paul at ue dot com dot br) 17-Apr-2003 01:40
If you trying to get a randon array just use that... it's easier! And you have no repeats...

<?

srand ((float) microtime() * 10000000);

$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

$keys = array_rand ($input, sizeof($input));

while (list($k, $v) = each($keys))
{
    echo $new_input = $input[$v];
}

?>
scandar at home dot se 13-Apr-2003 09:58
Note that the int num_req parameter is the required number of element to randomly select. So if your array has 3 element and num_req=4 then array_rand() will not return anything since it is impossible to select 4 random elements out of an array that only contains 3 elements. Many people think that they will get 3 elements returned but that is of course not the case.
mickoz[at]parodius[dot]com 01-Dec-2002 08:28
For those of you thinking that it does not work for num_req = 1, it is because it return a variable and not an array.  This mainly cause some problem with people using foreach.

The correct way to handle this is explained by that example:

<?php
$some_array = array("blah","bleh","foo","lele");

$nb_value = 1;

srand ((float) microtime() * 10000000);
$rand_keys = array_rand($some_array, $nb_value);

if(!is_array($rand_keys))
{
  $rand_keys = array($rand_keys);
}

print_r($rand_keys); // verify here the array of keys
echo "\n<BR>";
?>

// You can then correctly use the foreach, as it require an array to work
// If you use foreach with one element, it won't work.

<?php
$random_array = array();

foreach($rand_keys as $value)
{
  array_push($random_array, $some_array[$value]);
}

print_r($random_array);
?>
dboy at jumpstation dot org 22-Jul-2002 06:58
If you just want to pull one random element from an array, try something like this:

<?php
mt_srand((double) microtime() * 1000000);
$myarray = array("this", "is", "a",
                 "test", "to", "see",
                 "if", "I", "can",
                 "pull", "one", "element",
                 "from", "an", "array",
                 "randomly");
$random_index = mt_rand(0, (count($myarray)-1));
?>

Then to test the randomness or what have you try a simple:

<?php
$string = ""; // Just to kill the warning
for ($i=0; $i<count($myarray); $i++) {
     $random_index = mt_rand(0, (count($myarray)-1));
     $string .= "$myarray[$random_index] ";
}
$string = rtrim($string);
echo ($string);
?>

I've gotten extremely good output from this method and would recommend it if you're just pulling one element.
josh at 3io dot com 14-Jun-2002 03:20
I modified fake_array_rand to always only return 1 element, and did some benchmarks against calling array_rand with the second parameter as 1.  I ran 100 samples for each function for each number of elements and took the average result.  While the internal array_rand is faster for a small number of elements, it scales very poorly.

1 elements: 2.0619630813599E-05 sec. for array_rand,8.4352493286133E-05 sec. for fake_array_rand
10 elements: 2.1675825119019E-05 sec. for array_rand,8.427619934082E-05 sec. for fake_array_rand
100 elements: 2.9319524765015E-05 sec. for array_rand,8.4599256515503E-05 sec. for fake_array_rand
1000 elements: 0.0001157283782959 sec. for array_rand,8.5572004318237E-05 sec. for fake_array_rand
10000 elements: 0.0016669762134552 sec. for array_rand,8.5201263427734E-05 sec. for fake_array_rand
100000 elements: 0.015599734783173 sec. for array_rand,8.5580348968506E-05 sec. for fake_array_rand
1000000 elements: 0.18011983394623 sec. for array_rand,8.6690187454224E-05 sec. for fake_array_rand

<?php
function fake_array_rand ($array)
{
        $count = count ($array);
        # Help keep the number generator random :)
        $randval and usleep ("0.$randval");

        # Seed the random number generator
        # Generate a random number
        srand ((double) microtime() * 10000000);
        $randval = rand();

        # Use the random value to 'pick' an entry from the array
        # Count the number of times that the entry is picked
        ++$index[$randval % $count];

        return $array[$randval % $count];
}
?>
uvm at sun dot he dot net 09-Jul-2001 06:09
If you're just trying to draw a random subset of n elements from an array, it seems more effecient to do something like this:

<?php
function draw_rand_array($array,$draws)
{
        $lastIndex = count($array) - 1;
        $returnArr = array();
        while($draws > 1)
        {
                $rndIndex = rand(0,$lastIndex);
                array_push($returnArr,array_splice($array,$rndIndex,1));
                $draws--;
                $lastIndex--;
        }

        return $returnArr;
}
?>

No messing with indexes when you're done... you just have an array with the elements you're looking for in it.
array_push
array_reduce
Функции для работы с массивами


Итеративно уменьшает массив к единственному значению, используя callback-функцию

array_rand
array_replace_recursive
Функции для работы с массивами
PHP Manual

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce — Итеративно уменьшает массив к единственному значению, используя callback-функцию

Описание

mixed array_reduce ( array $input , callable $function [, mixed $initial = NULL ] )

array_reduce() итеративно применяет callback-функцию function к элементам массива input и, таким образом, сводит массив к единственному значению.

Список параметров

input

Входной массив.

function

Callback-функция.

mixed callback ( mixed &$result , mixed $item )
initial

Если передан необязательный параметр initial, то он будет использован в начале процесса, или в качестве окончательного результата в случае пустого массива.

Возвращаемые значения

Возвращает получившееся значение.

Если массив пуст и не передан параметр initial, array_reduce() вернет NULL.

Список изменений

Версия | Описание
5.3.0 | Параметр initial теперь позволяет передать mixed, ранее передавался только integer.

Примеры

Пример #1 Пример использованияarray_reduce()

<?php
function rsum($v, $w)
{
    $v += $w;
    return $v;
}

function rmul($v, $w)
{
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", "No data to reduce");
?>

В результате переменная $b содержит 15, $c содержит 1200 (= 10*1*2*3*4*5*10), и $d содержит No data to reduce.

Смотрите также

  • array_filter() - Фильтрует элементы массива с помощью callback-функции
  • array_map() - Применяет callback-функцию ко всем элементам указанных массивов
  • array_unique() - Убирает повторяющиеся значения из массива
  • array_count_values() - Подсчитывает количество всех значений массива

User Contributed Notes

hans+php at pleasedontspamme dot hansdude dot com 02-Nov-2011 08:18
This function is named fold in functional programming languages such as lisp, ocaml, haskell, and erlang. Python just calls it reduce.
aercolino at yahoo dot com 21-Apr-2010 07:17
Thanks to php at keith tyler dot com, knowing that "if you do not provide $initial, the first value used in the iteration is NULL", we can write callbacks that test for is_null() and take any necessary step.

Example:

<?php
function andFunc($a, $b) {
  return (is_null($a) ? true : $a) && $b;
}
$foo = array(true, true, true);
var_dump(array_reduce($foo, "andFunc"));
?>

It returns bool(true), as expected.
php at keith tyler dot com 18-Apr-2010 03:30
It seems that $initial is a required value; if you do not provide $initial, the first value used in the iteration is NULL.

Perhaps this is not a problem for callback functions that treat NULL as an identity (e.g. addition), but is a problem for cases when NULL is not identity (such as boolean context).

Compare:

<?php
function andFunc($a,$b) {
  return $a&&$b;
}
$foo=Array(true,true,true);
var_dump(array_reduce($foo,"andFunc"));
?>

returns false! One would expect that it would return true because true&&true&&true == true!

Adding diagnostic output to andFunc() shows that the first call to andFunc is with the arguments (NULL,true). This resolves to false (as (bool)null == false) and thereby corrupts the whole reduction.

So in this case I have to set $initial=true so that the first call to andFunc() will be (true,true). Now, if I were doing, say, orFunc(), I would have to set $initial=false. Beware.

Note that the "rmul" case in the example sneakily hides this defect! They use an $initial of 10 to get 10*1*2*3*4*5=12000. So you would assume that without an initial, you would get 1200/10 = 120 = 1*2*3*4*5. Nope! You get big fat zero, because int(null)==0, and 0*1*2*3*4*5 = 0!

I don't honestly see why array_reduce starts with a null argument. The first call to the callback should be with arguments ($initial[0],$initial[1]) [or whatever the first two array entries are], not (null,$initial[0]). That's what one would expect from the description.

Incidentally this also means that under the current implementation you will incur count($input) number of calls to the callback, not count($input)-1 as you might expect.
Hayley Watson 02-Apr-2010 06:14
The note by Hrobky immediately below applies only to PHP versions prior to 5.3.0; as noted in the function's version history, $initial is now a "mixed" parameter.

What a difference a year makes :)
Hrobky 01-Apr-2009 02:34
The initial value have to be int. So it is impossible to implement non-recursive flatten like this:

<?php
  $arr = array(array(1), array(2), array(3));
  $result = array_reduce($arr, 'array_merge', array());
  // expected: $result == array (1, 2, 3)
?>

I get: Warning: array_merge() : Argument #1 is not an array.

If $initial parameter is not an int, array_reduce passes 0 (zero) to the callback function. Hayley Watson's note suggests a solution:

<?php
  $acc = array();
  foreach($arr as $a)
    $acc = array_merge($acc, $a);
  // now: $acc == array (1, 2, 3)
?>
Hayley Watson 23-Oct-2007 02:49
To make it clearer about what the two parameters of the callback are for, and what "reduce to a single value" actually means (using associative and commutative operators as examples may obscure this).

The first parameter to the callback is an accumulator where the result-in-progress is effectively assembled. If you supply an $initial value the accumulator starts out with that value, otherwise it starts out null.
The second parameter is where each value of the array is passed during each step of the reduction.
The return value of the callback becomes the new value of the accumulator. When the array is exhausted, array_reduce() returns accumulated value.

If you carried out the reduction by hand, you'd get something like the following lines, every one of which therefore producing the same result:
<?php
array_reduce(array(1,2,3,4), 'f',         99             );
array_reduce(array(2,3,4),   'f',       f(99,1)          );
array_reduce(array(3,4),     'f',     f(f(99,1),2)       );
array_reduce(array(4),       'f',   f(f(f(99,1),2),3)    );
array_reduce(array(),        'f', f(f(f(f(99,1),2),3),4) );
f(f(f(f(99,1),2),3),4)
?>

If you made function f($v,$w){return "f($v,$w)";} the last line would be the literal result.

A PHP implementation might therefore look something like this (less details like error checking and so on):
<?php
function array_reduce($array, $callback, $initial=null)
{
    $acc = $initial;
    foreach($array as $a)
        $acc = $callback($acc, $a);
    return $acc;
}
?>
Janez R. 30-Jul-2007 08:27
--REPOST, fixed some typos, please replace previous note--
In PHP ver. 4.3.1 the initial value parameter allowed for string type also. In PHP ver. 5.1.6 this param is now converted to int and callback function will receive number 0 when initial param is an empty string.

<?php
function arc ($reduced, $item)
{
  $reduced = $item.$reduced;
  return $reduced;
}

array_reduce( array(a,b,c), "arc", "" );
?>

Output in PHP 4.3.1: cba
Output in PHP 5.1.6: cba0

Possible solution:
<?php
function arc ($reduced, $item)
{
  if ($reduced === 0)  $reduced = "";
  $reduced = $item.$reduced;
  return $reduced;
}
?>
yuki [dot] kodama [at] gmail [dot] com 31-Jan-2007 08:56
This code will reduce array deeply.

<?php
function print_s($s) {
    return is_null($s) ? "NULL" : (is_array($s) ? "Array" : ($s ? "TRUE" : "FALSE"));
}
function r_and_dp($a, $b) {
    echo "phase1:" . print_s($a) . "," . print_s($b) . "<br>\n";
    if(is_array($a)) {
        $a = array_reduce($a, "r_and_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_and_dp");
    }
    echo "phase2:" . print_s($a) . "," . print_s($b) . "<br>\n";
    $a = is_null($a) ? TRUE : $a;
    $b = is_null($b) ? TRUE : $b;
    echo "phase3:" . print_s($a) . "," . print_s($b) . "<br>\n";
    return $a && $b;
}
$bools = array(TRUE, array(FALSE, TRUE), TRUE);
echo print_s(array_reduce($bools, "r_and_dp")) . "<br>\n";

// result: FALSE
?>

When using boolean, you have to carefully set an "initial" argument.

<?php
function r_or_dp($a, $b) {
    if(is_array($a)) {
        $a = array_reduce($a, "r_or_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_or_dp");
    }
    return (is_null($a) ? FALSE : $a) || (is_null($b) ? FALSE : $b);
}
?>
bdechka at yahoo dot ca 10-Jan-2007 12:57
The above code works better this way.

<?php
function reduceToTable($html, $p) {
   $html .= "<TR><TD><a href=\"$p.html\">$p</a></td></tr>\n";
   return $html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable");
echo "<table>".$tab . "</table>\n";
?>
marcel dot oehler at kubusmedia dot com 08-Feb-2006 07:26
I've just experienced some really strange behaviour of array_reduce in PHP 5.0.4:

$result = array( 0, 17, 0, 0, 33, 0, 0, 0, 0, 50);
$total = array_reduce( $result, "sumCalc", 0);

function sumCalc( $a, $b){
    return $a + $b;
}

and $total equals to 83!

I know, this could be done easier, but it should work nevertheless. Has anybody experienced something similar? I will avoid using array_reduce in the future...
Seanj.jcink.com 04-Jan-2006 06:23
The code posted below by bishop to count the characters of an array is simply... erm... well useless to me...

$array=Array("abc","de","f");
strlen(implode("",$array)); //6

works; and is much smaller. Probably much faster too.
ildar [DASH] sh [AT] mail [DOT] ru 29-Nov-2005 10:02
in rare cases when an array is a set of numeric values and result is one of sum or product of numbers the next examples may be useful

<?php

// sum of array items
echo eval('return ' . implode('+', $nums) . ';');

// product of array items
echo eval('return ' . implode('*', $nums) . ';');

?>

the reason of these codes is omitting of single used per script of callbacks
david dot tulloh at infaze dot com dot au 23-Jun-2005 01:18
The code supplied by cuntbubble is unfortunately incorrect.

Running it I got the output:
0<TR><TD><a href="page1.html">page1</a></td>
<TR><TD><a href="page2.html">page2</a></td>
<TR><TD><a href="page3.html">page3</a></td>
</table>

So php, not finding an integer, used int(0) to start the process.  I've tested to confirm this.
bishop 30-Apr-2004 08:19
Count the total number of characters in an array of strings:

<?php
$lines = array ('abc', 'd', 'ef');
$totalChars = array_reduce($lines, create_function('$v,$w','return $v + strlen($w);'), 0);
// $totalChars === 6
?>
tonicpeddler at aol dot com 01-Nov-2002 07:17
in response to php dot net at cuntbubble dot com

actually when you pass a value to a function that accepts a specific data type, php automatically evaluates that value as the data type expected
php dot net at cuntbubble dot com 17-Jan-2002 08:08
There is an error/misleading item in the documentation

[, int initial]

int is not constrained to an integer, it can be any data type (although I've not tested ALL data types)

and $v is the cumulative part, the current value of the reduction.

and I'll take the liberty to add another example, as used in my code

<?php
function reduceToTable($html, $p) {
    $html .= "<TR><TD><a href=\"$p.html\">$p</a></td>\n";
    return $html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable", "<table>\n");
echo $tab . "</table>\n";
?>

hmm, getting stuff on one line sure is tricky, it get's wordwrapped on the char count in html so &gt; counts as 4 chars not one so by the time you've counted "< you've used up 8 chars
If it get's through moderation could someone please make it look ok :)
array_rand
array_replace_recursive
Функции для работы с массивами


Рекурсивно заменяет элементы первого массива элементами переданных массивов

array_reduce
array_replace
Функции для работы с массивами
PHP Manual

array_replace_recursive

(PHP 5 >= 5.3.0)

array_replace_recursive — Рекурсивно заменяет элементы первого массива элементами переданных массивов

Описание

array array_replace_recursive ( array &$array , array &$array1 [, array &$... ] )

array_replace_recursive() заменяет значения первого массива array на соответствующие по ключам значения из всех следующих массивов. Если ключ из первого массива есть во втором, его значение будет заменено на значение из второго массива. Если ключ есть во втором массиве, но отсутствует в первом, он будет создан в первом массиве. Если ключ есть только в первом массиве, то он остается как есть. Если передано несколько массивов, они будут обработаны по порядку, последующие перезаписывают предыдущие значения.

array_replace_recursive() - рекурсивная функция: она будет рекурсивно углубляться в массивы и применять к всем внутренним значениям один и тот же процесс.

Если значение, переданное в array является скалярным, оно будет заменено значением в array1, которое может быть как скалярным так и массивом. Если оба значения, переданные в array и array1 - массивы, array_replace_recursive() будет заменять их значения рекурсивно.

Список параметров

array

Массив, элементы которого будут заменены.

array1

Массив, из которого будут взяты элементы для замены.

...

Дополнительные массивы, из которых будут браться элементы для замены.

Возвращаемые значения

Возвращает array, или NULL, если произошла ошибка.

Примеры

Пример #1 Пример использования array_replace_recursive()

<?php
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));

$basket = array_replace_recursive($base, $replacements);
print_r($basket);

$basket = array_replace($base, $replacements);
print_r($basket);
?>

Результат выполнения данного примера:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
        )

)

Пример #2 array_replace_recursive() and recursive behavior

<?php
$base = array('citrus' => array("orange") , 'berries' => array("blackberry", "raspberry"), 'others' => 'banana' );
$replacements = array('citrus' => 'pineapple', 'berries' => array('blueberry'), 'others' => array('litchis'));
$replacements2 = array('citrus' => array('pineapple'), 'berries' => array('blueberry'), 'others' => 'litchis');

$basket = array_replace_recursive($base, $replacements, $replacements2);
print_r($basket);

?>

Результат выполнения данного примера:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

    [others] => litchis
)

Смотрите также

  • array_replace() - Замена элементов массива элементами других переданных массивов

User Contributed Notes

Gregor at der-meyer dot de 29-Jul-2009 06:13
Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

<?php
if (!function_exists('array_replace_recursive'))
{
  function array_replace_recursive($array, $array1)
  {
    function recurse($array, $array1)
    {
      foreach ($array1 as $key => $value)
      {
        // create new key in $array, if it is empty or not an array
        if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key])))
        {
          $array[$key] = array();
        }

        // overwrite the value in the base array
        if (is_array($value))
        {
          $value = recurse($array[$key], $value);
        }
        $array[$key] = $value;
      }
      return $array;
    }

    // handle the arguments, merge one by one
    $args = func_get_args();
    $array = $args[0];
    if (!is_array($array))
    {
      return $array;
    }
    for ($i = 1; $i < count($args); $i++)
    {
      if (is_array($args[$i]))
      {
        $array = recurse($array, $args[$i]);
      }
    }
    return $array;
  }
}
?>

I called this function array_merge_recursive_overwrite() in my older projects, but array_replace_recursive() sounds quite better while they do the same.

If you implemented such a compatible function before and don't want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

<?php
  // as of PHP 5.3.0 array_replace_recursive() does the work for us
  if (function_exists('array_replace_recursive'))
  {
    return call_user_func_array('array_replace_recursive', func_get_args());
  }
?>
kyle [dot] florence [@t] gmail [dot] com 14-Jul-2009 04:16
This might help out people who don't have 5.3 running:

<?php

// Joins two or more arrays together recursively; key/value pairs of the first
// array are replaced with key/value pairs from the subsequent arrays.  Any
// key/value pair not present in the first array is added to the final array
function array_join()
{
    // Get array arguments
    $arrays = func_get_args();

    // Define the original array
    $original = array_shift($arrays);

    // Loop through arrays
    foreach ($arrays as $array)
    {
        // Loop through array key/value pairs
        foreach ($array as $key => $value)
        {
            // Value is an array
            if (is_array($value))
            {
                // Traverse the array; replace or add result to original array
                $original[$key] = array_join($original[$key], $array[$key]);
            }

            // Value is not an array
            else
            {
                // Replace or add current value to original array
                $original[$key] = $value;
            }
        }
    }

    // Return the joined array
    return $original;
}

?>
array_reduce
array_replace
Функции для работы с массивами


Замена элементов массива элементами других переданных массивов

array_replace_recursive
array_reverse
Функции для работы с массивами
PHP Manual

array_replace

(PHP 5 >= 5.3.0)

array_replace — Замена элементов массива элементами других переданных массивов

Описание

array array_replace ( array &$array , array &$array1 [, array &$... ] )

array_replace() замещает значения первого массива array соответствующими по ключам значениями из других переданных массивов. Если ключ из первого массива присутствует во втором массиве, его значение заменяется на значение из второго массива. Если ключ есть во втором массиве, но отсутствует в первом - он будет создан в первом массиве. Если ключ присутствует только в первом массиве, то сохранится как есть. Если для замены передано несколько массивов, они будут обработаны в порядке передачи и более поздние массивы будут перезаписывать значения из предыдущих.

array_replace() не рекурсивная: значения первого массива будут заменены вне зависимости от типа значений второго массива, даже если это будут вложенные массивы.

Список параметров

array

Массив, элементы которого требуется заменить.

array1

Массив, элементами которого будут заменяться элементы первого массива.

...

Еще массивы, из которых будут браться элементы для замены. Значения следующего массива затирают значения предыдущего.

Возвращаемые значения

Возвращает массив (array) или NULL в случае ошибки.

Примеры

Пример #1 Пример использования array_replace()

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

Результат выполнения данного примера:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

Смотрите также

  • array_replace_recursive() - Рекурсивно заменяет элементы первого массива элементами переданных массивов

User Contributed Notes

w_barath at hotmail dot com 06-Aug-2011 08:13
Yep, thinking about it replacing from back to front, this works a trick!

here's a quick repalcement for PHP <=5.3

<?php
if (!function_exists('array_replace')){ function array_replace(){
    $array=array();
    $n=func_num_args();
    while ($n-- >0) {
        $array+=func_get_arg($n);
    }
    return $array;
}}
?>
sun at drupal dot org 27-May-2011 11:42
Instead of calling this function, it's often faster and simpler to do this instead:

<?php
$array_replaced = $array2 + $array1;
?>

If you need references to stay intact:

<?php
$array2 += $array1;
?>
polecat at p0lecat dot com 29-Nov-2010 10:02
I got hit with a noob mistake. :)

When the function was called more than once, it threw a function redeclare error of course.  The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision.  A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own.  Since this site has helped me so much, I felt the need to return the favor. :)

<?php
        // Polecat's Multi-dimensional array_replace function
        // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact
        function polecat_array_replace( array &$array1, array &$array2 ) {
            // This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions
            if(!function_exists('tier_parse')){
                function tier_parse(array &$t_array1, array&$t_array2) {
                    foreach ($t_array2 as $k2 => $v2) {
                        if (is_array($t_array2[$k2])) {
                            tier_parse($t_array1[$k2], $t_array2[$k2]);
                        } else {
                            $t_array1[$k2] = $t_array2[$k2];
                        }
                    }
                    return $t_array1;
                }
            }

            foreach ($array2 as $key => $val) {
                if (is_array($array2[$key])) {
                    tier_parse($array1[$key], $array2[$key]);
                } else {
                    $array1[$key] = $array2[$key];
                }
            }
            return $array1;
        }
?>

[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

<?php
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
?>

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
polecat at p0lecat dot com 29-Nov-2010 09:57
I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
mail at romansklenar dot cz 10-Dec-2009 07:01
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

<?php
...
$count = func_num_args();

for ($i = 1; $i < $count; $i++) {
   ...
}
...
?>

Check on this code:

<?php
$base = array('id' => NULL, 'login' => NULL, 'credit' => NULL);
$arr1 = array('id' => 2, 'login' => NULL, 'credit' => 5);
$arr2 = array('id' => NULL, 'login' => 'john.doe', 'credit' => 100);
$result = array_replace($base, $arr1, $arr2);

/*
correct output:

array(3) {
   "id" => NULL
   "login" => string(8) "john.doe"
   "credit" => int(100)
}

your output:

array(3) {
   "id" => int(2)
   "login" => NULL
   "credit" => int(5)
}
*/
?>

Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...
tufan dot oezduman at googlemail dot com 06-Nov-2009 04:19
a little enhancement to dyer85 at gmail dot com's function below:
<?php
if (!function_exists('array_replace'))
{
  function array_replace( array &$array, array &$array1, $filterEmpty=false )
  {
    $args = func_get_args();
    $count = func_num_args()-1;

    for ($i = 0; $i < $count; ++$i) {
      if (is_array($args[$i])) {
        foreach ($args[$i] as $key => $val) {
            if ($filterEmpty && empty($val)) continue;
            $array[$key] = $val;
        }
      }
      else {
        trigger_error(
          __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
          E_USER_WARNING
        );
        return NULL;
      }
    }

    return $array;
  }
}
?>

this will allow you to "tetris-like" merge arrays:

<?php

$a= array(
    0 => "foo",
    1 => "",
    2 => "baz"
);
$b= array(
    0 => "",
    1 => "bar",
    2 => ""
);

print_r(array_replace($a,$b, true));

?>
results in:
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
)
dyer85 at gmail dot com 28-Jul-2009 09:45
For a backward compatible alternative, you might try something like this:

<?php

if (!function_exists('array_replace'))
{
  function array_replace( array &$array, array &$array1 )
  {
    $args = func_get_args();
    $count = func_num_args();

    for ($i = 0; $i < $count; ++$i) {
      if (is_array($args[$i])) {
        foreach ($args[$i] as $key => $val) {
          $array[$key] = $val;
        }
      }
      else {
        trigger_error(
          __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
          E_USER_WARNING
        );
        return NULL;
      }
    }

    return $array;
  }
}

?>
array_replace_recursive
array_reverse
Функции для работы с массивами


Возвращает массив с элементами в обратном порядке

array_replace
array_search
Функции для работы с массивами
PHP Manual

array_reverse

(PHP 4, PHP 5)

array_reverse — Возвращает массив с элементами в обратном порядке

Описание

array array_reverse ( array $array [, bool $preserve_keys = false ] )

Принимает массив array и возвращает новый массив, содержащем элементы исходного массива в обратном порядке.

Список параметров

array

Входной массив.

preserve_keys

Если установлено в TRUE, то ключи будут сохранены. Нечисловые ключи не подвержены этой опции и всегда сохраняются.

Возвращаемые значения

Возвращает массив с элементами в обратном порядке.

Список изменений

Версия | Описание
4.0.3 | Добавлен параметр preserve_keys.

Примеры

Пример #1 Пример использования array_reverse()

<?php
$input  = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
?>

Оба массива $result и $result_keyed содержат одинаковые значения, но обратите внимание на различиче между ключами. Содержимое $result и $result_keyed будет таким:

Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

Смотрите также

  • array_flip() - Меняет местами ключи с их значениями в массиве

User Contributed Notes

Nick Kraynev 27-Jul-2011 12:15
Another way to maintain association:

<?php
return array_compose(
    array_reverse(array_keys($array)),
    array_reverse(array_values($array))
);
?>
jferchaud at yahoo dot fr 17-Feb-2011 06:29
Return an array with elements in reverse order preserving mixed type keys.

<?php
function array_reverse_order($array){
        $array_key = array_keys($array);
        $array_value = array_values($array);

        $array_return = array();
        for($i=1, $size_of_array=sizeof($array_key);$i<=$size_of_array;$i++){
            $array_return[$array_key[$size_of_array-$i]] = $array_value[$size_of_array-$i];
        }

        return $array_return;
    }
?>
alfbennett at gmail dot com 06-Apr-2010 01:41
Needed to just reverse keys. Don't flog me if there is a better way. This was a simple solution.

<?php
function array_reverse_keys($ar){
    return array_reverse(array_reverse($ar,true),false);
}
?>
ulderico at maber dot com dot br 14-May-2009 02:33
<?php
function array_reversed($array){
  $array = array_reverse($array);
  ksort($array);
  return($array);
}
?>

So you'll have a reversed array.. instead of an array with inverted keys.
Anonymous 01-Feb-2009 12:07
Reversing array by reference (does not preserve keys!):

<?php
function arrayReverse(&$arr)
{
    $c = count($arr);
    for($i=$c-1;$i>=0;$i--)
    {
        $arr[$c+$i] = $arr[$i];
    }
    $arr = array_slice($arr,$c,$c*2);
}
?>
rdx at jouwmoeder 07-Nov-2006 03:37
As response to Ella's note:

$array[0] = 'record1';
$array[9] = 'record2';
$array[15] = 'record3';

That is ordered way easier AND faster with array_values().
array_reverse twice is unnecessary. Once array_values and all values will be saved in new keys
Ella 14-Jul-2006 05:03
You can also use array_reverse to reset array indexes without losing the order of the values. For example when you use unset() to delete values from an array, the value gets deleted but you end up with a missing index:

$array[0] = 'record1';
$array[9] = 'record2';
$array[15] = 'record3';

Just use:

$array = array_reverse(array_reverse($array));

And your indexes get rearranged:

$array[0] = 'record1';
$array[1] = 'record2';
$array[2] = 'record3';
me2resh at gmail dot com 03-Feb-2005 01:25
Here is my version of sorting multidimensional arrays with any key in it even if u want it alphapatically sorted by any key.

u can remove the strtolower part if you want to keep it case sensitive

function cmp($a, $b){
    return strcmp(strtolower($a["name"]), strtolower($b["name"]));
}
Michiel de Roo 08-Sep-2003 12:55
If you need to reverse an array by reference, you can use the following function.

<?
function &array_reverse_ref(&$a) {
    $r = array();
    for($i=0, $j=count($a); $i<count($a); $i++, $j--) {
        $r[$i] =& $a[$j-1];
    }
    return $r;
}
?>

Use it like:
<?
class t {
    var $message = "message";
}
for($i=0; $i<10; $i++) {
    $a[] = new t();
}

$ra =& array_reverse_ref($a);

$a[0]->message = "now... this works in both";
$ra[0]->message = "but.... does not work in both";

for($i=0; $i<10; $i++) {
    echo $ra[$i]->message; echo "<br>\n";
}
echo "<br>\n";
for($i=0; $i<10; $i++) {
    echo $a[$i]->message; echo "<br>\n";
}
?>
zee4speed at hotmail dot com 04-Jul-2003 10:56
another way to ->
If you want to reverse an array with numerical indexes, you can keep them by using following code:
<?
# this is your array, and you would like to reverse it however maintain their actual index values to point to the existings.
$array_to_reverse[0]="zee";
$array_to_reverse[1]="andrew";
$array_to_reverse[2]="pablo";
$array_to_reverse[3]="mike";
$array_to_reverse[4]="ahmed";
$array_to_reverse[5]="yousra";
$array_to_reverse[6]="samir";
# you want the array to look like this so you can use a command like for each to march through the array.
$array_reversed[6]="samir";
$array_reversed[5]="yousra";
$array_reversed[4]="ahmed";
$array_reversed[3]="mike";
$array_reversed[2]="pablo";
$array_reversed[1]="andrew";
$array_reversed[0]="zee";
# however if you use array_reverse you get this:
$array_reversed[0]="samir";
$array_reversed[1]="yousra";
$array_reversed[2]="ahmed";
$array_reversed[3]="mike";
$array_reversed[4]="pablo";
$array_reversed[5]="andrew";
$array_reversed[6]="zee";
# this causes element samir to be first instead of last, just like you want.  hoever, the index value that refferences samir is now 0 instead of 6
# solution to this is the following code

$array_reversed = array_reverse ($array_to_reverse);
$size_of_array = count($array_reversed);
for ($z = 0; $z < $size_of_array; $z++){
         #do what you want
         #if you want to get the index value of the un-reveresed array, simply
         $actual_index = GetActualIndex($z,$size_of_array);
         echo $z." on array_reversed is the same ".$actual_index." on array_to_reverse<BR>\n";
}

function GetActualIndex($current_index, $size_of_array){
         $reverse_location = abs($current_index + 1 - $size_of_array);
         return $reverse_location;
}
?>
m dot weber at luna-park dot de 31-Jan-2003 07:02
If you want to reverse an array with numerical indexes, you can keep them by using following code:

<?php
end($gruppenarr);
do {
  $part1=key($gruppenarr);
  $part2=current($gruppenarr);
  $gruppenarr2[$part1]=$part2;
} while(prev($gruppenarr));
?>

input is $gruppenarr
output is $gruppenarr2
rahulavhad at yahoo dot com 29-Dec-2000 08:31
This code can help in recursive reversing of the array...

<?php
$arr1 = array(2,1,array(5,2,1,array(9,8,7)),5,0);
$arr1 = array_reverse($arr1);

function Reverse_Array($array)
{    $index = 0;
    foreach ($array as $subarray)
    {    if (is_array($subarray))
        {    $subarray = array_reverse($subarray);
            $arr = Reverse_Array($subarray);
            $array[$index] = $arr;
        }
        else {$array[$index] = $subarray;}
        $index++;
    }
    return $array;
}

$arr2 = Reverse_Array($arr1);
?>
david at audiogalaxy dot com 04-Mar-2000 01:39
As a further clarification: key-value pairs have an order within an array completely separate from whatever the keys happen to be - the order in which you add them.  This is the order that functions like each() and next() will move their pointer through the array.
If you add to an array without specifying the key, like $array[] = value; then an internal counter supplies the key value and then the numerical order of your keys will be identical to the the internal order.  If you "leave holes" - jumping ahead by specifying a higher number for the key, like $array[1000] = value; the internal counter gets pushed forward appropriately.  Other than its effect on this internal counter, specifying a numerical key seems no different than specifying a string.
However, some array functions, like array_merge() and array_reverse() treat keys that are numbers differently from keys that are not.
david at audiogalaxy dot com 04-Mar-2000 12:40
With associative arrays array_reverse() keeps key => value pairs matched but reverses the order of the array as spaned by functions like each().  With numerical indexes array_reverse not only reverses position (as spaned by each) but also renumbers the keys.
Both cases seem to be what people would generally want: indeed without the renumbering behavior, someone refering to array elements by numerical key wouldn't think array_reverse did anything.
However, people who are trying to keep numerical keys associated with their values - e.g. trying to have holes in their arrays - will be foiled by the renumbering.  The most telling results come from applying array_reverse() to arrays with mixed keys (some numbers and some strings).  The strings stay attached and the rest of the keys get renumbered around them - most annoying if you are thinking what you've got is an associative array but some of your keys happen to be numbers.
array_replace
array_search
Функции для работы с массивами


Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи

array_reverse
array_shift
Функции для работы с массивами
PHP Manual

array_search

(PHP 4 >= 4.0.5, PHP 5)

array_search — Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи

Описание

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Ищет в haystack значение needle.

Список параметров

needle

Искомое значение.

Замечание:

Если needle является строкой, сравнение происходит с учетом регистра.

haystack

Массив.

strict

Если третий параметр strict установлен в TRUE, то функция array_search() будет искать идентичные элементы в haystack. Это означает, что также будут проверяться типы needle в haystack, а объекты должны быть одни и тем же экземпляром.

Возвращаемые значения

Возвращает ключ для needle, если он был найден в массиве, иначе FALSE.

Если needle присутствует в haystack более одного раза, будет возвращён первый найденный ключ. Для того, чтобы возвратить ключи для всех найденных значений, используйте функцию array_keys() с необязательным параметром search_value.

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Список изменений

Версия | Описание
4.2.0 | До PHP 4.2.0, array_search() при неудаче возвращал NULL вместо FALSE.

Примеры

Пример #1 Пример использования array_search()

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

Смотрите также

  • array_keys() - Возвращает все или некоторое подмножество ключей массива
  • array_values() - Выбирает все значения массива
  • array_key_exists() - Проверяет, присутствует ли в массиве указанный ключ или индекс
  • in_array() - Проверяет, присутствует ли в массиве значение

User Contributed Notes

spotitbiz at gmail dot com 24-May-2012 10:27
I have just tried to add the function of recursive Array Search in order to return all finding keys in an array instead of the first matching result index, and further expanded search to contain needle instead of exactly matching:

<?php
function recursiveArraySearchAll($haystack, $needle, $index = null)
{
    $aIt     = new RecursiveArrayIterator($haystack);
    $it    = new RecursiveIteratorIterator($aIt);
    $resultkeys;

    while($it->valid()) {
    if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND (strpos($it->current(), $needle)!==false)) { //$it->current() == $needle
    $resultkeys[]=$aIt->key(); //return $aIt->key();
    }

    $it->next();
    }
    return $resultkeys;  // return all finding in an array

} ;
?>

To use the function on your array search:

<?php
print_r(recursiveArraySearchAll($your-array,'your-needle-to match','your-array-index-to-search') );
?>

Simple! and Enjoy!
sneskid at hotmail dot com 15-Mar-2012 08:50
I had an array of arrays and needed to find the key of an element by comparing actual reference.
Beware that even with strict equality (===) php will equate arrays via their elements recursively, not by a simple internal pointer check as with class objects. The === can be slow for massive arrays and also crash if they contain circular references.

This function performs reference sniffing in order to return the key for an element that is exactly a reference of needle.

<?php
function array_ref_search(&$v, array &$s)
{
    if(is_object($v)){ return array_search($v, $s, true); }
    foreach($s as $rK => &$rV)
    { // reference sniff
        $tV = $v;
        if( ($rV === ($v = 1)) && ($rV === ($v = 0)) ){
        $v = $tV; return $rK; }
        $v = $tV;
    }
    return false; // use null for php < 4.2.0
}

$list   = array();
$list['A'] = &$valA; $list['B'] = &$valB;

$valA = 1; $valB = 1;
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // key 'A'

$valA = array(1,2,3); $valB = array(1,2,3);
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // key 'A' because ($valA === $valB) is true by elements

$valB[] = &$valB; // circular reference
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // crash because ($valB === $valB) causes infinite loop
?>
nateferrero at gmail dot com 27-Jan-2012 04:56
I built a function to find the numeric index of a key in an array.

<?php

/**
 * Array key index
 * @author Nate Ferrero
 */
function array_key_index(&$arr, $key) {
    $i = 0;
    foreach(array_keys($arr) as $k) {
        if($k == $key) return $i;
        $i++;
    }
}
nsstl 22-Jan-2012 09:57
Some thing that I wrote from a while, for what ever usefull purpose

This retrieves recursively a value from an array using a path-like notation.

   with:
     $delimiter         path delimiter
     $strict              if false, the search will allow gaps between path's components

<?php
function path_through_array($path, $array, $delimiter = '.', $strict = false)
{
  $path_token = explode($delimiter, $path);
  $head = array_shift($path_token);

  if (isset($array[$head]) && (0 == count($path_token)))
  {
    return $array[$head];
  }
  else if (isset($array[$head]))
  {
    return path_through_array(implode($delimiter, $path_token), $array[$head], $delimiter, $strict);
  }
  else if ($strict == true)
  {
    return false;
  }

  foreach ($array as $key=>$value)
  {
    if (is_array($value))
    {
      $found = path_through_array($path, $value, $delimiter, $strict);

      if(false != $found)
      {
        return $found;
      }
    }
  }
  return false;
}

//use:

$array1 = array('path' => array('to' => array('get' => array('something' => 'bar')), 'somethingelse'), 'foo' => 'anotherthing');

$val1 = path_through_array('path.to.get.something', $array1);                         // => will return : 'bar'
$val2 = path_through_array('path.to.get', $array1);                                       // => will return : array('something'=>'bar')
$val3 = path_through_array('path/to/get/something', $array1, '/');                  // => will return : 'bar'
$val4 = path_through_array('path.to.something', $array1);                            // => will return : 'bar'
$val5 = path_through_array('path.to.something', $array1, '.', true);               // => will return : false
Ouz zcan (mail at oguzozcan dot com) 17-Dec-2011 02:06
This is a multidimensional recursive find function :

<?php
function GetArrKey( $findArr, $key_arr, $depth=0 )
{
        if( count($key_arr) <= $depth || !array_key_exists($key_arr[$depth], $findArr) )
                return NULL;
        else if( count($key_arr) == $depth+1 )
                return $findArr[$key_arr[$depth]];

        return self::GetArrKey( $findArr[$key_arr[$depth]], $key_arr, $depth+1 );
}
?>

Using :
<?php
        $findArray = array( "first_dim" => array( "first_dim_in_1" => array( "first_dim_in_1_val_1", "first_dim_in_1_val_2", "first_dim_in_1_val_3" ), "first_dim_in_2" => array( "first_dim_in_2_val_1", "first_dim_in_2_val_2", "first_dim_in_2_val_3" ) ), "second_dim" => array( "second_dim_in" => "test", "second_dim_in_val_1"));

        var_dump( GetArrKey( $findArray, array( "first_dim", "first_dim_in_2" ) ) );

        /*
            Prints :
            array( "first_dim_in_2_val_1", "first_dim_in_2_val_2", "first_dim_in_2_val_3" )
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "first_dim", "first_dim_in_2", 0 ) ) );

        /*
            Prints :
            string(20) => "first_dim_in_2_val_1"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 0 ) ) );

        /*
            Prints :
            string(4) => "test"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 0 ) ) );

        /*
            Prints :
            string(4) => "test"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 1 ) ) );

        /*
            Prints :
            string(19) => "second_dim_in_val_1"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 1, 1 ) ) );

        /*
            Prints :
            std_object => NULL
        */

?>
revoke 11-Oct-2011 04:12
Better solution of multidimensional searching.

<?php
function multidimensional_search($parents, $searched) {
  if (empty($searched) || empty($parents)) {
    return false;
  }

  foreach ($parents as $key => $value) {
    $exists = true;
    foreach ($searched as $skey => $svalue) {
      $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
    }
    if($exists){ return $key; }
  }

  return false;
}

$parents = array();
$parents[] = array('date'=>1320883200, 'uid'=>3);
$parents[] = array('date'=>1320883200, 'uid'=>5);
$parents[] = array('date'=>1318204800, 'uid'=>5);

echo multidimensional_search($parents, array('date'=>1320883200, 'uid'=>5)); // 1
?>
stooshie at gmail dot com 06-Oct-2011 02:51
Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
    // n is only needed if counting depth of search
    global $n;
    $n++;
    // get the length of passed array
    $l = count($haystack);
    // if length is 0, problem
    if($l <= 0)
    {
        return -1;
    }
    // get the mid element
    $m = (($l+($l%2))/2);
    // if mid >= length (e.g. l=1)
    if($m >= $l)
    {
        $m = $m-1;
    }
    // get the indexed element to compare to the passed element and branch accordingly
    $compare = $haystack[$m];
    switch(true)
    {
        case($compare>$needle):
        {
            // recurse on the lower half
            $new_haystack = array_slice($haystack, 0, $m);
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current index - (length of lower half - found index in lower half)
            return $m - ($c - $r);
            break;
        }
        case($compare<$needle):
        {
            // recurse on the upper half
            $new_haystack = array_slice($haystack, $m, ($l-$m));
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current position + found index in upper half
            return $m + $r;
            break;
        }
        case($compare==$needle):
        {
            // found it, so return index
            return $m;
            break;
        }
    }
}
?>
Dave C 27-Sep-2011 01:18
Here is a version of binary search that is done via recursion instead of iteration.  Remember that your data needs to be presorted!

<?php
static function Bin_Search(&$needle, &$haystack, $start, $end) {
        if($end < $start)
        {
            return false;
        }

        $mid = (int)(($end - $start) / 2) + $start;

        if($haystack[$mid] > $needle)
        {
            return Bin_Search($needle, $haystack, $start, $mid - 1);
        }
        else if($haystack[$mid] < $needle)
        {
            return Bin_Search($needle, $haystack, $mid + 1, $end);
        }
        else
        {
            return true;
        }
}
?>
Jordan Rutty (ruttyj92[-at-][hotmailcom) 04-Jul-2011 10:41
Array AFTER/BEFORE Function

function made to mimic the jQuery function to insert items/arrays into another array before or after a specific key. It is split into two functions for reuse to find the offset of a key. it detects if the array is associative (can also be manually controlled) and adds the keys where needed. if the inserted array is associative then any overlapping keys will be replaced by the new ones.

array_insert(array &$original , mixed $insert=null , var $position='after' , $key=null [, $keep_keys=true])

options for $position = (after|before)

<?php
function key_offset(&$array, $searchKey){
    if(is_array($array) && array_key_exists($searchKey, $array)){
        $counter = 0;
        foreach($array as $key => $value){
            if($searchKey == $key){
                return $counter;
            } else {
                $counter++;
            }
        }
    }
}

function array_insert(&$original, $insert=null, $position='after', $key=null, $sens=true){
    if(!empty($insert)){
           $after = $position == 'after' ? true : false;
           $insert = (array)$insert;
           $assoc = (array_keys($insert) !== range(0, count($insert)-1));
           $keep_keys = is_string($insert) || !$assoc || $sens;

        if(!empty($key) && array_key_exists($key, $original)){
            $start = key_offset($original, $key);
               $start = $after ? $start+1 : $start;
            if(!$keep_keys){
                array_Splice($original,$start,0,$insert);
                } else {
                $keys = array_Keys($original);
                $values = array_Values($original);
                $insert = (array)$insert;
                $rKeys = array_Keys($insert);
                $rValues = array_Values($insert);
                array_Splice($keys,$start,0,$rKeys);
                array_Splice($values,$start,0,$rValues);
                    $original = array_Combine($keys,$values);
                }
        } else {
            $original = $after ? array_merge($original, $insert) : array_merge($insert, $original);
        }
    }
}

$insert = array('omg'=> 'it works', 'this_is' => 'awsome', 'r' =>103,104);
$insert2 = range(11,15);
$insert3 = array(100=>101,102,103,104);

$original=range(1,10);
array_insert($original, $insert, 'after', 4);

$original=range(1,10);
array_insert($original, $insert, 'after', 4, false);

$original=range(1,10);
array_insert($original, $insert2, 'after', 4);

$original=range(1,10);
array_insert($original, $insert3, 'after', 4);

/*
Array
(
    [0] => 104
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [omg] => it works
    [this_is] => awsome
    [r] => 103
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => it works
    [6] => awsome
    [7] => 103
    [8] => 104
    [9] => 6
    [10] => 7
    [11] => 8
    [12] => 9
    [13] => 10
)

Array
(
    [0] => 11
    [1] => 12
    [2] => 13
    [3] => 14
    [4] => 15
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [100] => 101
    [101] => 102
    [102] => 103
    [103] => 104
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)
*/
?>
willemvannus at gmail dot com 11-Feb-2011 03:23
I found a simple script to remove certain values from a array.
I use it when using the scandir function, because i don't want certain items in the array (like the ., .. folders and the thumbs.db)

<?php
$music = scandir("music");
unset($music[array_search('.',$music)]);  // Removing the . directory
unset($music[array_search('..',$music)]); // Removing the .. directory
unset($music[array_search('Thumbs.db',$music)]); // Removing the Thumbs.db file
unset($music[array_search('thumbs.db',$music)]); // Removing the thumbs.db file
?>
syrgjyn at gmail dot com 18-Jan-2011 07:51
Recently I had to get all locations of a one-dimensional non-associative array (needle, not array of needles) in another one-dimensional non-associative array (haystack) without using more memory than necessary. I haven't found any satisfactory way to do that, so I wrote the following function, inspired by the array_slice() source code.

Notes:
0. $offset, $length and $strict behave the same way as those for array_slice() and array_search();
1. this function doesn't use foreach or array_slice(), neither does it modify $needle or $haystack, so no temporary copies are needed/created, regardless of whether the arguments are passed by reference or not -- useful when dealing with very large haystacks and needles;
2. $needle and $haystack are typecast to array if they're not arrays;
3. you can specify the $start position to start searching from in the $haystack (default is 0);
4. negative $start values can be used if you want to specify the starting position from the end of $haystack.
5. you can specify the search $length, starting from $start; a negative value stops the search at that many elements from the end of the haystack;
6. pass true as the fifth argument to do a strict search (not tested on objects);
7. the function returns an array if it finds one or more occurrences of $needle in the $haystack, false on failure.
8. keys are preserved;
9. if you want to get only the first location of $needle in $haystack, returned as an integer rather than array -- in other words, to make an array_match() function instead of array_match_all() -- remove this line:

  $results = array();

and replace:

    if ($found)
    {
      $results[] = $i;
      $i += $ncount - 1;
    }
  }
  if (!empty($results))
    return $results;
  else
    return false;

with:

    if ($found)
      return $i;
  }
  return false;

And now the function:

<?php
function array_match_all($needle, $haystack, $offset = 0, $length = 0, $strict = false)
{
  if (!is_array($needle))
    $needle = (array) $needle;
  if (!is_array($haystack))
    $haystack = (array) $haystack;

  $offset = (int) $offset;
  $length = (int) $length;
  $strict = ($strict != false);
  $ncount = count($needle);
  $hcount = count($haystack);

  // Empty arrays? Really? Also, no point in dealing with a needle larger than the haystack.
  if (($hcount == 0) || ($ncount == 0) || ($ncount > $hcount))
    return false;

  // Is offset beyond the upper bound?
  if ($offset > $hcount - $ncount)
    return false;
  // If offset is specified from the end of haystack, is it beyond the lower bound?
  elseif ($offset < 0 && ($offset = $hcount + $offset) < 0)
    $offset = 0;

  // Determine the length.
  if ($length == 0)
    $length = $hcount;

  if ($length < 0)
    $length = $hcount - $offset + $length;
  elseif ($offset + $length > $hcount)
    $length = $hcount - $offset;

  // Is the needle larger than the portion of the haystack we are searching in?
  if (($length <= 1) || ($ncount > $length))
    return false;

  // Determine the actual search length.
  $length = $offset + $length - $ncount + 1;

  $results = array();
  for ($i = $offset; $i < $length; ++$i)
  {
    $found = true;
    for ($j = 0; $j < $ncount; ++$j)
    {
      if (($strict && ($haystack[$i + $j] !== $needle[$j])) || (!$strict && ($haystack[$i + $j] != $needle[$j])))
      {
        $found = false;
        break;
      }
    }
    if ($found)
    {
      $results[] = $i;
      $i += $ncount - 1;
    }
  }

  if (empty($results))
    return false;
  else
    return $results;
}
?>
stefano@takys dot it 14-Jan-2011 01:58
for searching case insensitive better this:

<?php
array_search(strtolower($element),array_map('strtolower',$array));
?>
user at www dot mp3s dot pl 28-Dec-2010 01:25
for case insensitive array_search you could use:

<?php
function array_search_i($str,$array){
    foreach($array as $key => $value) {
        if(stristr($str,$value)) return $key;
    }
    return false;
}
?>
manchimen [at) yahoo [dot) com 01-Nov-2010 02:18
Hey all - I needed a function to search for an array in a multi-dimensional array, but only the keys I wanted, not all keys. Hee if my function:

<?php
function my_array_search($needle, $haystack) {
        if (empty($needle) || empty($haystack)) {
            return false;
        }

        foreach ($haystack as $key => $value) {
            $exists = 0;
            foreach ($needle as $nkey => $nvalue) {
                if (!empty($value[$nkey]) && $value[$nkey] == $nvalue) {
                    $exists = 1;
                } else {
                    $exists = 0;
                }
            }
            if ($exists) return $key;
        }

        return false;
    }
?>

Examples:
<?php
$needle = array('date_start' => '27-10-2010', 'date_end' => '29-10-2010');

$haystack = array();
$haystack[] = array('date_start' => '25-10-2010', 'date_end' => '26-10-2010', 'promos' => array('test', 'test1');
$haystack[] = array('date_start' => '27-10-2010', 'date_end' => '28-10-2010', 'promos' => array('test2', 'test3');
$haystack[] = array('date_start' => '27-10-2010', 'date_end' => '29-10-2010', 'promos' => array('test4', 'test5');

$key = my_array_search($needle, $haystack);
// will output (bool)false for not found or (int)key_no with the key number
// this example outputs (int)2
var_dump($key);
?>

I hope this function will help someone!
GuardianGI 23-Sep-2010 12:42
I needed to check an array for a value but the value only had to match part of a string in the array value so i wrote this little function hope it helps someone out (also some documentation of what used to test if there already was such a function 'couse i was hoping array_search was this.

<?php
function my_array_search($needle = null, $haystack_array = null, $skip = 0)
{
    if($needle == null || $haystack_array == null)
        die('$needle and $haystack_array are mandatory for functie my_array_search()');
    foreach($haystack_array as $key => $eval)
    {
        if($skip != 0)$eval = substr($eval, $skip);
        if(stristr($eval, $needle) !== false) return true;
    }
    return false;
}

$arr = array('foo', 'bar');

echo 'using in_array<br />';
if(in_array('ar', $arr) === true)echo 'ar found<br />';
if(in_array('bar', $arr) === true)echo 'bar found<br />';

echo 'using array_search<br />';
if(array_search('ar', $arr) !== false)echo 'ar found<br />';
if(array_search('bar', $arr) !== false)echo 'bar found<br />';

echo 'using my_array_search<br />';
if(my_array_search('ar', $arr) !== false)echo 'ar found<br />';
if(my_array_search('bar', $arr) !== false)echo 'bar found<br />';
?>

returns:

using in_array
bar found
using array_search
bar found
using my_array_search
ar found
bar found
j dot vd dot merwe at enovision dot net 22-Sep-2010 02:42
The getParentStack is also working if you work with JSON records that are encoded. Following sample:

$in = '{"total":"2","records": [{"id":"25"},{"id":"32"}]}'; // string!!!
$json = json_decode( $in, true ); //don't forget the true here

$s = getParentStack(32, $json['records']) ;

then test this with:

if ($s != false)     // then it is found, don't test true here!!!

or test direct with:

if ( getParentStack(32, $json['records']) != false )

It works great with my JSON's thanks Robert Gonzalez
robert at robert-gonzalez dot com 22-Sep-2010 12:15
I needed a way to find the parent hierarchy of a multidimensional array. Being the rogue that I am, I got to coding before searching the manual and came up with two little functions that will return a parent stack for a first find and a complete parent stack, similar in nature to the solution presented by jette at nerdgirl dot dk without all the extra stuff or use of eval(). ;)

<?php
/**
 * Gets the parent stack of a string array element if it is found within the
 * parent array
 *
 * This will not search objects within an array, though I suspect you could
 * tweak it easily enough to do that
 *
 * @param string $child The string array element to search for
 * @param array $stack The stack to search within for the child
 * @return array An array containing the parent stack for the child if found,
 *               false otherwise
 */
function getParentStack($child, $stack) {
    foreach ($stack as $k => $v) {
        if (is_array($v)) {
            // If the current element of the array is an array, recurse it and capture the return
            $return = getParentStack($child, $v);

            // If the return is an array, stack it and return it
            if (is_array($return)) {
                return array($k => $return);
            }
        } else {
            // Since we are not on an array, compare directly
            if ($v == $child) {
                // And if we match, stack it and return it
                return array($k => $child);
            }
        }
    }

    // Return false since there was nothing found
    return false;
}

/**
 * Gets the complete parent stack of a string array element if it is found
 * within the parent array
 *
 * This will not search objects within an array, though I suspect you could
 * tweak it easily enough to do that
 *
 * @param string $child The string array element to search for
 * @param array $stack The stack to search within for the child
 * @return array An array containing the parent stack for the child if found,
 *               false otherwise
 */
function getParentStackComplete($child, $stack) {
    $return = array();
    foreach ($stack as $k => $v) {
        if (is_array($v)) {
            // If the current element of the array is an array, recurse it
            // and capture the return stack
            $stack = getParentStackComplete($child, $v);

            // If the return stack is an array, add it to the return
            if (is_array($stack) && !empty($stack)) {
                $return[$k] = $stack;
            }
        } else {
            // Since we are not on an array, compare directly
            if ($v == $child) {
                // And if we match, stack it and return it
                $return[$k] = $child;
            }
        }
    }

    // Return the stack
    return empty($return) ? false: $return;
}

// TESTING
$array = array(
    'balloon' => array(
        'red' => array(1 => 'Love', 'Valentine', 'Heart',),
        'green' => array(1 => 'Summertime', 'Hope',),
    ),
    'ribbon' => array(
        'yellow' => array(2 => 'Welcome',),
        'red' => array(3 => 'Love', 'Love',),
    ),
);

$s = getParentStack('Love', $array);
$c = getParentStackComplete('Love', $array);
var_dump($s, $c);
?>

Output:

array
  'balloon' =>
    array
      'red' =>
        array
          1 => string 'Love' (length=4)

array
  'balloon' =>
    array
      'red' =>
        array
          1 => string 'Love' (length=4)
  'ribbon' =>
    array
      'red' =>
        array
          3 => string 'Love' (length=4)
          4 => string 'Love' (length=4)
hanan dot ali dot shaikh at googlemail dot com 17-Sep-2010 01:14
In this code I write a code to find next and previous element of an array using current element of that array. Let suppose if we are in element 9 and have to access its next and previous element then this code be helpful for someone.

<?php
$myArray = array(4,5,7,9,10,11,13,19,25);

$currentElement = 9;
$firstElement = current($myArray);
$lastElement = $myArray[sizeof($myArray)-1];

$currentKey = array_search($currentElement, $myArray);
$currentValue = $myArray[$currentKey];

$previousValue = "";
$nextValue = "";
if($currentElement!=$lastElement){
    $nextKey = $currentKey + 1;
    $nextValue = $myArray[$nextKey];
}

if($currentElement!=$firstElement){
    $previousKey = $currentKey - 1;
    $previousValue = $myArray[$previousKey];
}

echo $previousValue."--".$currentValue."--".$nextValue;

?>

Thanks,
Hanan Ali
Yco 03-Aug-2010 01:35
This a simple and lazy lazy method to search a key name in an array by pattern, and return the value if it isn't empty.

<?php
function array_search_key($p, $a)
{
    foreach ($a as $k => $v) {
        if(strstr($k, $p)){
            if(!empty($v) || $v > 0){
                return $v;
            }
        }
    }
}
?>
giulio dot provasi at gmail dot com 30-Apr-2010 02:06
If you want a very simple way of searching a value through a multidimensionnal array here's a  trick :

<?php
function recursiveArraySearch($haystack, $needle, $index = null)
{
    $aIt     = new RecursiveArrayIterator($haystack);
    $it    = new RecursiveIteratorIterator($aIt);

    while($it->valid())
    {
        if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
            return $aIt->key();
        }

        $it->next();
    }

    return false;
}
?>

So let's take a misc multi-dimensionnal array :

<?php
$std = new stdClass();
$std->name     = 'luke';
$std->age     = '25';
$std->sex     = 'M';

$array     = array(    array('type'=>'dog', 'name'=>'butch', 'sex'=>'m', 'breed'=>'boxer'),
                    array('type'=>'dog', 'name'=>'fido', 'sex'=>'m', 'breed'=>'doberman'),
                    'simpleValue',
                    array('type'=>'cat', 'name'=>'tiddles','sex'=>'m', 'breed'=>'maine coon'),
                    array('type'=>'horse', 'name'=>'ed','sex'=>'m', 'breed'=>'clydesdale'),
                    $std);

echo recursiveArraySearch($array, '25', 'age');        // returns 5
echo recursiveArraySearch($array, '25', 'name');    // returns false
echo recursiveArraySearch($array, 'simpleValue');    // returns 2
echo recursiveArraySearch($array, 'fido');            // returns 1
?>
kim at steinhaug dot com 19-Mar-2010 12:44
I was looking around for a recursive search by keys in multidimensional arrays. After testing the ones in this thread seems noone accually works. So I put this one together, and it does what you expect it to do.

You need to find the value for the key "han-solo".

<?php
if( ($val = array_search_key('han-solo',$array)) !== false){
  var_dump($val);
} else {
  // No keys with the name "han-solo"
}

function array_search_key( $needle_key, $array ) {
  foreach($array AS $key=>$value){
    if($key == $needle_key) return $value;
    if(is_array($value)){
      if( ($result = array_search_key($needle_key,$value)) !== false)
        return $result;
    }
  }
  return false;
}
?>
camden dot michael at gmail dot com 03-Mar-2010 10:58
I needed a case insensitive array search function for a project...

<?php
/**
 * Performs the same function as array_search except that it is case
 * insensitive
 * @param mixed $needle
 * @param array $haystack
 * @return mixed
 */

function array_nsearch($needle, array $haystack) {
   $it = new IteratorIterator(new ArrayIterator($haystack));
   foreach($it as $key => $val) {
       if(strcasecmp($val,$needle) === 0) {
           return $key;
       }
   }
   return false;
}
?>
jette at nerdgirl dot dk 01-Mar-2010 08:07
I use this function to search the value of arrays of any dimension, and return the result with keys preserved:

<?php
function multiArrayValueSearch($haystack, $needle, &$result, &$aryPath=NULL, $currentKey='') {
  if (is_array($haystack)) {
    $count = count($haystack);
    $iterator = 0;
    foreach($haystack as $location => $straw) {
      $iterator++;
      $next = ($iterator == $count)?false:true;
      if (is_array($straw)) $aryPath[$location] = $location;
        multiArrayValueSearch($straw,$needle,$result,$aryPath,$location);
        if (!$next) {
          unset($aryPath[$currentKey]);
        }
      }
    } else {
      $straw = $haystack;
      if ($straw == $needle) {
        if (!isset($aryPath)) {
          $strPath = "\$result[$currentKey] = \$needle;";
        } else {
          $strPath = "\$result['".join("']['",$aryPath)."'][$currentKey] = \$needle;";
        }
        eval($strPath);
      }
   }
}
?>

Example:

<?php
$ary['ballon']['red'][1] = 'Love';
$ary['ballon']['red'][2] = 'Valentine';
$ary['ballon']['red'][3] = 'Heart';
$ary['ballon']['green'][1] = 'Summertime';
$ary['ballon']['green'][2] = 'Hope';
$ary['ribbon']['yellow'][2] = 'Welcome';
$ary['ribbon']['red'][3] = 'Love';
$ary['ribbon']['red'][4] = 'Love';

echo "<pre>";

//Just call the function with 3 first parameters set:
//  1) The array to search
//  2) The value to find
//  3) A variable to store the result
multiArrayValueSearch($ary,'Love',$match);

print_r($match);
echo "</pre>";
?>

Output:

Array
(
    [ballon] => Array
        (
            [red] => Array
                (
                    [1] => Love
                )

        )

    [ribbon] => Array
        (
            [red] => Array
                (
                    [3] => Love
                    [4] => Love
                )

        )

)

You can easily adapt it to suit your need of matching, by changing line 16 in the function:

<?php
if ($straw == $needle) {
?>
james at bandit.co.nz 28-Jan-2010 05:33
A couple of staple custom PHP array searching functions I rely on in most of my projects;

<?php
    // array_search with partial matches and optional search by key
    function array_find($needle, $haystack, $search_keys = false) {
        if(!is_array($haystack)) return false;
        foreach($haystack as $key=>$value) {
            $what = ($search_keys) ? $key : $value;
            if(strpos($what, $needle)!==false) return $key;
        }
        return false;
    }

    // array_search with recursive searching, optional partial matches and optional search by key
    function array_find_r($needle, $haystack, $partial_matches = false, $search_keys = false) {
        if(!is_array($haystack)) return false;
        foreach($haystack as $key=>$value) {
            $what = ($search_keys) ? $key : $value;
            if($needle===$what) return $key;
            else if($partial_matches && @strpos($what, $needle)!==false) return $key;
            else if(is_array($value) && array_find_r($needle, $value, $partial_matches, $search_keys)!==false) return $key;
        }
        return false;
    }
?>

Hope they help someone!
mrjay42 at gmail dot com 13-Nov-2009 06:09
If you search a key position in an associative array (keys are uniques), i suggest this function :
<?php
public function getKeyPositionInArray($haystack, $keyNeedle)
{
    $i = 0;
    foreach($haystack as $key => $value)
    {
        if($key == $keyNeedle)
        {
            return $i;
        }
        $i++;
    }
}
?>
codeslinger at compsalot dot com 02-Oct-2009 12:22
one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal[$index] = array('key'=>$key, 'data'=>'foo');
  $inverse[$key] = $index;

  //very fast lookup, this beats any other kind of search

  if (array_key_exists($key, $inverse))
  {
    $index = $inverse[$key];
    return $normal[$index];
  }

?>
pi3ch at gmx dot com 28-Sep-2009 09:29
The return value for array_search is confusing if the return key is zero. it is better to double check it with in_array() function.

Example:
<?php

$SampleArray = ('a', 'b', 'c');

$Key = array_search('a', $SampleArray);
$Zero = in_array('a', $SampleArray);

if($Key == NULL && !$Zero)
   echo "Key doesnt exists";
else
   echo "Key exists";

 ?>
pvenakis at efrontlearning dot net 24-Sep-2009 05:02
if $haystack is not an array, for example false from some previous action, the function returns null instead of false in php 5.3.
temporal dot pl at gmail dot com 04-Sep-2009 03:57
Sometimes you need to find a given value in a sorted array or - if not found - detect the place where it should be. After that you can for example split the array into two halves, the  greater and the smaller one.

greenmr, dennis.decoene and php at celerondude had all posted very good binary search functions but these functions all return false if the needle was not found in the haystack. I've tweaked greenmr's code a little:

<?php
function Array_BinarySearch( $needle, $haystack, $comparator , &$probe )
{
    $high = Count( $haystack ) -1;
    $low = 0;

    while ( $high >= $low )
    {
        $probe = Floor( ( $high + $low ) / 2 );
        $comparison = $comparator( $haystack[$probe], $needle );
        if ( $comparison < 0 )
        {
            $low = $probe +1;
        }
        elseif ( $comparison > 0 )
        {
            $high = $probe -1;
        }
        else
        {
            return true;
        }
    }
    //The loop ended without a match
    //Compensate for needle greater than highest haystack element
    if($comparator($haystack[count($haystack)-1], $needle) < 0)
    {
        $probe = count($haystack);
    }
    return false;
}
?>

Now, the function returns true if it finds something and false otherwise. If a needle was found, then $probe will contain it's position. Otherwise, $probe will contain position of where the needle would be if it were there :). This is possible because we pass $probe by reference.

Example:

<?php
//ultra-simple comparator :)
function CompareNumbers($obj, $needle)
{
    return $obj - $needle;
}

//use examples
$testArr = array(10, 20, 30, 40, 50);
$res = Array_BinarySearch(30, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 1 2 - found at position 2

$res = Array_BinarySearch(45, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 0 4 - not found, but it would be at position 4 (between 40 and 45)

$res = Array_BinarySearch(-3, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 0 0 - not found, but it would be at position 0 (before 10)

$res = Array_BinarySearch(300, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 0 5 - not found, but it would be at position 5 (after 50; note, that count($haystack) == 5)
?>

See original greenmr's note for additional details about usage of this binary search: http://php.net/manual/en/function.array-search.php#89413
Nguyen KimKha 23-Aug-2009 10:18
You can remove some values from array, by using unset() and array_search().

<?php

$friends = array( 'Bob', 'Ann', 'Peter' ); // Two persons named 'Bob'
$find = 'Bob';
$key = array_search( $find, $friends ); // Find key of given value
if ($key != NULL || $key !== FALSE) {
    unset($friends[$key]); // remove key from array
}

// Now, $friends = array( 'Ann', 'Peter');

?>
Frank A Cefalu frankcefalu at gmail dot com 18-Aug-2009 11:22
The original function for searching a multidimensional array didn't let you filter by arraykeys.

This one is modified so you can search by array keys or not.

If you want a general search for a value and don't care which specific key to target you dont have to specify it but example.

<?php
$array = ("shoes" => array("test1"=> "123","test2"=>"1234","test3"=>"12345"),
             "shoes2"=> array("test1"=>"324","test2"=>"3515","test3"=>"123131");

array_search_value("123",$array,"test1"); // would return shoes
array_search_value("12223",$array,"test1"); // would return false;
?>
this makes it easier to validate a multi-dimensional array to make sure certain data is present.

Enjoy!

<?php

function array_search_value($needle,$haystack,$arraykey=FALSE) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;

        if($arraykey){

            if($needle == $value[$arraykey]){
            return $value['id'];
            }

            if(array_search_value($needle,$value[$arraykey]) == true) {
            return $current_key;
            }

        }else{

            if($needle == $value)
            return $value;

            if(array_search_value($needle,$value) == true) {
                return $current_key;
            }

        }

    }
    return false;
}
?>
mikeytown2 22-Jul-2009 04:14
Made a function that I used to search the $_SERVER variable ( http://php.net/reserved.variables.server ) for matches to getcwd ( http://php.net/getcwd ) excluding some key's that I don't want.

<?php
/**
 * Returns all key/values in array that match.
 *
 * @param $needle
 *  What your searching for
 * @param $haystack
 *  Array of values
 * @param $a_not
 *  Optional array of key names to exclude
 */
function boost_array_find($needle, $haystack, $a_not = array()) {
  $out = array();
  foreach($haystack as $key=>$value) {
    if (strpos($value, $needle) !== FALSE) {
      $good = TRUE;
      foreach($a_not as $not) {
        if (strpos($key, $not) !== FALSE) {
          $good = FALSE;
        }
      }
      if ($good) {
        $out[$key] = $value;
      }
    }
  }
  return $out;
}

// Example Usage
$document_root = str_replace("\\", '/', getcwd());
$rejects = array('SCRIPT_FILENAME');
$out = boost_array_find($document_root, $_SERVER, $rejects);
print_r($out);
?>

Which should output this on most servers.
Array
(
    [DOCUMENT_ROOT] => path/to/webroot
)

On Mosso's servers it will output this
Array
(
    [PHP_DOCUMENT_ROOT] => path/to/webroot
)
Anonymous 22-Jun-2009 02:51
Here is a cool trick:

<?php
function arr_search ( $array, $expression ) {
    $result = array();
    $expression = preg_replace ( "/([^\s]+?)(=|<|>|!)/", "\$a['$1']$2", $expression );
    foreach ( $array as $a ) if ( eval ( "return $expression;" ) ) $result[] = $a;
    return $result;
}

$data = array (
    array ( "name" => "bill", "age" => 40 ),
    array ( "name" => "john", "age" => 30 ),
    array ( "name" => "jack", "age" => 50 ),
    array ( "name" => "john", "age" => 25 )
);

print_r ( arr_search ( $data, "age>=30" ) );
print_r ( arr_search ( $data, "name=='john'" ) );
print_r ( arr_search ( $data, "age>25 and name=='john'" ) );
?>

-- results --

Array
(
    [0] => Array
        (
            [name] => bill
            [age] => 40
        )

    [1] => Array
        (
            [name] => john
            [age] => 30
        )

    [2] => Array
        (
            [name] => jack
            [age] => 50
        )

)
Array
(
    [0] => Array
        (
            [name] => john
            [age] => 30
        )

    [1] => Array
        (
            [name] => john
            [age] => 25
        )

)
Array
(
    [0] => Array
        (
            [name] => john
            [age] => 30
        )

)
buddel 08-Jun-2009 08:13
the recursive function by tony have a small bug. it failes when a key is 0

here is the corrected version of this helpful function:

<?php
function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
?>
tony dot peter at wanadoo dot fr 11-May-2009 12:53
A simple recursive array_search function :

<?php
function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value))) {
            return $current_key;
        }
    }
    return false;
}
?>
n-regen 05-May-2009 10:36
If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach ($haystack as $item)
   {
      if (strpos($item, $needle) !== FALSE)
      {
         return $item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.
alex at softservice dot org 28-Apr-2009 09:07
Can be useful for searching in a multi-dimensional array:

<?php
function array_search_in_level($needle, $haystack, $key, &$result, $searchlevel = 0) {
  while(is_array($haystack) && isset($haystack[key($haystack)])) {
    if($searchlevel == 0 && key($haystack) == $key && $haystack[$key] == $needle) {
      $result = $haystack;
    } elseif($searchlevel > 0) {
      array_search_in_level($needle, $haystack[key($haystack)], $key, $result, $searchlevel - 1);
    }
    next($haystack);
  }
}
?>

Examples:

1. 2-dimensional array, search by both key and value
$arr1 = array(
  1 => array('id' => 1, 'name' => 'Alex', 'gender' => 'male'),
  ...
  12 => array('id' => 12, 'name' => 'John', 'gender' => 'male'),
);

<?php array_search_in_level('John', $arr1, 'name', $result, 1); ?>

$result is:
array(
  'id' => int 12
  'name' => string 'John' (length=4)
  'gender' => string 'male' (length=4)
)

2. 3-dimensional array, search by value only:

<?php
$arr2 = array(
  1 => array('id' => 1, 'name' => 'Alex', 'gender' => 'male'),
  /* ... */
  12 => array('id' => 12, 'name' => 'John', 'gender' => 'male', 'friends' => array('Helen', 'Julia')),
);

array_search_in_level('Helen', $arr1, 0, $result, 2);
?>

$result is:
array(
  0 => string 'Helen' (length=5)
  1 => string 'Julia' (length=5)
)
office at drsoft dot com 02-Apr-2009 04:59
If you wish to search a multidimensional array by keys:

<?php
function extract_values_by_key ( $array, $needle_key, &$out = array () ) {
    foreach ( (array) $array as $key => $value ) {
        if ( ! is_array ( $value ) && $key == $needle_key ) {
            array_push ( $out, $value );
        }
        else {
            extract_values_by_key ( $value, $needle_key, &$out );
        }
    }

    return $out;
}
?>
elie at najberg dot fr 26-Mar-2009 06:04
This is how to search a part of a val in an array :

<?php
      function array_ereg_search($val, $array) {

          $i = 0;
          $return = array();

          foreach($array as $v) {

               if(eregi($val, $v)) $return[] = $i;
               $i++;

          }

      return $return;

      }
?>
greenmr 06-Mar-2009 11:02
Incidentally, the KeyCompare() function I described above is a generalized version. Since array_bsearch() doesn't care about specific return values, just greater then, less than, or equal to zero, when you are comparing two numbers you can greatly simplify the comparison function to something like:

<?php
  function KeyCompare( $obj, $needle ) {
      return $obj['my_key'] - $needle;
  }
?>
greenmr 06-Mar-2009 10:15
As others have noted, if your array is already sorted, a binary search is the way to go. When I realized PHP doesn't have a native one, I came here to see what others had done to implement this workhorse algorithm. While I appreciate those that have posted their own solutions here, none of those implementations met my needs. Also, due mainly to non-optimal loop processing, the code offered required extra post-processing to handle various ways the search loop may have exited. Proper coding of initial conditions and the main loop eliminates this extra processing.

Also, the solutions presented assumed a simple one-dimensional array and basic comparisons. I needed to search an array of user objects, with the comparison performed on one of the object attributes. C/C++ handles the need for comparison flexibility by the binary search function taking a parameter that points to a user function that performs any arbitrarily complex comparison and returns a defined result depending on the relative magnitudes of the compared entities. Since PHP allows similar function reference parameters, I realised it would be quite easy to implement this functionality.

I won't go into an explanation of the algorithm chosen for the main binary search function, google "binary searches" if you don't understand how they work. I will mention however that the ONLY way to exit the main loop in this function is on a match, or a definite fail. The loop will never terminate while the result of the search is indeterminate.

Some solutions I've seen here and elsewhere return the index of the found element on a match, and "false" on a fail. Since PHP treats a zero the same as false in expressions, and zero is a valid array index, using false to designate "not found" gives an ambiguous result in some cases. I chose to use the value -1 to signify a search failure instead.

<?php
    function array_bsearch( $needle, $haystack, $comparator ) {
        $high = Count( $haystack ) -1;
        $low = 0;

        while ( $high >= $low ){
            $probe = Floor( ( $high + $low ) / 2 );
            $comparison = $comparator( $haystack[$probe], $needle );
            if ( $comparison < 0 ) {
                $low = $probe +1;
            } elseif ( $comparison > 0 ) {
                $high = $probe -1;
            } else {
                return $probe;
            }
        }

      // ---The loop ended without a match
      return -1;
    }
?>

In this function the parameters "$needle" and "$haystack" have the same meaning as for the native array_search() PHP function. The third parameter, "$comparator" is the name of the function to use to determine if an array element matches the needle.

The array_bsearch() function is self-contained, and doesn't need modification no matter how complex the comparison needs to be. The actual comparison is performed by a purpose-written user function that takes two parameters and returns a numerical result. array_bsearch() will call this function each time it needs to compare an array element to the needle. The first parameter passed will be the element to test, and the second will the the needle value passed to array_bsearch(). Note that if you will always search for the same thing your user function can ignore the second parameter and hard-code the test on the first parameter.

The comparison user function must return a positive number if the element is greater than the needle, a negative number if it is smaller than the needle, and zero if they match.

Given a scenario where you want to find the index of a user object loaded from MySQL in an array, where the "my_key" property equals 54. Here's how you could code it using a user function and the new array_bsearch() function.

<?php
  function KeyCompare( $obj, $needle ) {
      if ( $obj['my_key'] < $needle ) {
          return -1;
      } elseif ( $obj['my_key'] > $needle ) {
          return 1;
      } else {
          return 0;
      }
  }

  $index = array_bsearch( 54, $my_array, 'KeyCompare' );
?>

Hope this is helpful to somebody out there.
info at [hidden] dot apanel dot nl 04-Feb-2009 05:27
I made this function after I didnt find a recursive array_search function with a limit and the possibility to inverse the search. So here is it:

<?php

function search_in_array ($needle, $haystack, $inverse = false, $limit = 1) {

    # Settings
    $path = array ();
    $count = 0;

    # Check if inverse
    if ($inverse == true)
        $haystack = array_reverse ($haystack, true);

    # Loop
    foreach ($haystack as $key => $value) {

        # Check for return
        if ($count > 0 && $count == $limit)
            return $path;

        # Check for val
        if ($value === $needle) {

            # Add to path
            $path[] = $key;

            # Count
            $count++;

        } else if (is_array ($value)) {

            # Fetch subs
            $sub = search_in_array ($needle, $value, $inverse, $limit);

            # Check if there are subs
            if (count ($sub) > 0) {

                # Add to path
                $path[$key] = $sub;

                # Add to count
                $count += count ($sub);
            }
        }
    }

    return $path;
}

?>
helenadeus at gmail dot com 25-Jan-2009 01:05
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack = array('a','b','a','b');

$needle = 'a';

print_r(array_search_all($needle, $haystack));

//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {

        if($haystack[$k]==$needle){

           $array[] = $k;
        }
    }
    return ($array);

}

?>
tim_hauber at stev dot net 07-Jan-2009 08:50
A slight addition to array_search_recursive by Alireza Eliaderani below.  The original searched the entire haystack, even if it found the needle at the beginning of the haystack. I must admit I had a little trouble wrapping my head around how to break out of a loop in a recursive function.  This version returns after first occurrence of needle. changes commented.

<?php
function array_search_recursive($needle, $haystack){
    $path=array();
    foreach($haystack as $id => $val)
    {

         if($val === $needle) {
              $path[]=$id;

             break;
             # ^^this breaks out of loop when it finds needle

         } else if(is_array($val)){
             $found=array_search_recursive($needle, $val);
              if(count($found)>0){
                  $path[$id]=$found;

                 break;
                # ^^this breaks out of loop when recursive call found needle

             }
          }
      }
      return $path;
}
?>
azaozz, gmail 20-Dec-2008 05:23
Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a = array(0, "str1", "str2", "str3");
echo "
str1 = ".array_search("str1", $a).",
str2 = ".array_search("str2", $a).",
str3 = ".array_search("str3", $a).",

str1 strict = ".array_search("str1", $a, true).",
str2 strict = ".array_search("str2", $a, true).",
str3 strict = ".array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
grezvany13 [at] notitia.nl 11-Dec-2008 03:32
This function can search for an array or string within an array.

<?php
function array_search_array($needle, $haystack){
    if(is_array($needle) && is_array($haystack)) {
        $tmp = array_diff_assoc($needle, $haystack);
        if(empty($tmp)) return true;
        foreach($haystack as $value) {
            if(is_array($value)) {
                $tmp = array_diff_assoc($needle, $value);
                if(empty($tmp)) return true;
            }
        }
    }
    if(is_array($haystack) && !is_array($needle)) {
        foreach($haystack as $value) {
            if(is_array($value)) {
                $tmp = array_diff_assoc($needle, $value);
                if(empty($tmp)) return true;
            } elseif($needle == $value) return true;
        }
    } elseif($needle == $haystack) return true;
    return false;
}
?>

It's not recursive yet, so please improve it if you feel for it ;)
Alireza Eliaderani 25-Nov-2008 10:42
this function return a multidimensional path of recursively founded $needle in a multidimensional $haystack

<?php
function array_search_recursive($needle, $haystack){
    $path=array();
    foreach($haystack as $id => $val)
    {

         if($val === $needle)
              $path[]=$id;
         else if(is_array($val)){
             $found=array_search_recursive($needle, $val);
              if(count($found)>0){
                  $path[$id]=$found;
              }
          }
      }
      return $path;
}
?>
michi7x7 17-Nov-2008 11:32
If you exit the function whith "return", there is no need to break ;)

i would write it like this:

<?php

function array_search_recursive($needle, $haystack, $path=array())
{
    foreach($haystack as $id => $val)
    {
         $path2=$path;
         $path2[] = $id;

         if($val === $needle)
              return $path2;
         else if(is_array($val))
              if($ret = array_search_recursive($needle, $val, $path2))
                   return $ret;
      }
      return false;
}

$array = array(
   "a" => array(
       "b" => array("c"),
       "d" => array("e"),
       ),
    "f" => array( "g", "h"),
    );

var_dump(array_search_recursive("e", $array));

?>

var dump prints a array: (a, d, 0)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 02:39
I wrote a better array_search_recursive function.  The other functions listed work and will evaluate to true, however, they loop through the stack even after the needle is found: so this function will take the overhead off the cpu =P

<?php

  function array_search_recursive($needle, $haystack)
  {
    foreach ($haystack as $k => $v)
    {
      for ($i=0; $i<count($v); $i++)
        if ($v[$i] === $needle)
        {
          return true;
          break;
        }
    }
  }

  $access['admin'] = array('nick1');
  $access['voice'] = array('nick2', 'nick3');

  if (array_search_recursive('nick3', $access))
    echo 'yes';
  print_r($access);

?>

I wrote this for an access list that I have implemented into an IRC bot.  See more interesting stuff at dreamevilconcept's forum.
dcez at land dot ru 30-Apr-2008 01:15
Simple way to get variable name by using array_search function:

<?php

function varname($var){

    return (isset($var))? array_search($var, $GLOBALS) : false;

}

$boogie = 'tonight';

echo varname($boogie);

?>
andreas dot damm at maxmachine dot de 03-Apr-2008 04:07
Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1 = array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}
dot dot dot dot dot alexander at gmail dot com 09-Mar-2008 08:30
This is the phpfied version of the array_search function for PHP version under 4.0.5

<?php
if(!function_exists("array_search")){
    function array_search( $needle, $haystack, $strict = FALSE ){
        if( !is_array($haystack) )return FALSE;
        foreach($haystack as $key => $val){
            if(   (  ( $strict ) && ( $needle === $val )  ) || (  ( !$strict ) && ( $needle == $val )  )   )return $key;
        }
        return FALSE;
    }/* endfunction array_search */
}/* endfunction exists array_search*/
?>
mjaning at gmail dot com 05-Feb-2008 11:42
Hi! Based on Chris function, I made another to simplify code and improve diferents features...

With this function you can:
- Filter Key and Values recursively
- Call function many times using previows result
- Final result always will be an array numeric index contenting a value or sigle array key=>value.

Thanks for PHP!

<?php
function array_search_recursive($needle, $haystack, $nodes=array())
{
  foreach ($haystack as $key1=>$value1)
  {
    if (is_array($value1))
      $nodes = array_search_recursive($needle, $value1, $nodes);
   elseif (($key1 == $needle) or ($value1 == $needle))
      $nodes[] = array($key1=>$value1);
  }
  return $nodes;
}

$arg[] = array("column1"=>"Class3");
$arg[] = array("column2"=>"Class1");
$arg[] = array("column3"=>"Class3");
$arg[] = array("column4"=>"Class4");
$arg[] = array("column4"=>"Class3");
$arg[] = "column3";

$filter = array_search_recursive("Class3",$arg);
echo "<hr>";var_dump($filter);

$filter = array_search_recursive("column3",$filter);
echo "<hr>";var_dump($filter);
?>
pmmout at gmail dot com 29-Jan-2008 04:55
MultiArray find function.
After some time unsuccessful looking for algorithm to find a string in multidimensional array I wrote one:

<?php
function multidimArrayLocate($array, $text){
  foreach($array as $key => $arrayValue){
    if (is_array($arrayValue)){
      if ($key == $text) $arrayResult[$key] = $arrayValue;
      $temp[$key] = multidimArrayLocate($arrayValue, $text);
      if ($temp[$key]) $arrayResult[$key] = $temp[$key];
    }
    else{
      if ($key == $text) $arrayResult[$key] = $arrayValue;
    }
  }
  return $arrayResult;
}
?>
steev at anticulture dot co dot uk 13-Jan-2008 02:46
Just adding my two penneth to someone else's script from below. If you need to easily index your csv use this slightly modified script to parse a csv file into an associative array 2d, indexed by the first column value

<?php
function buildStock($File) {
        $handle = fopen($File, "r");
        $fields = fgetcsv($handle, 1000, ",");

        while($data = fgetcsv($handle, 1000, ",")) {
            $detail[] = $data;
        }
        echo "details";
        var_dump($detail);
        echo "<br />";

        $x = 0;
        $y = 0;

        foreach($detail as $i) {
            foreach($fields as $z) {
                //original code
                //$stock[$x][$z] = $i[$y];
                $stock[$i['0']][$z] = $i[$y];
                $y++;
            }
            $y = 0;
            $x++;
        }
        return $stock;
    }

var_dump(buildStock("conf.csv"));
?>
toni dot garcia dot gutsens at gmail dot com 02-Dec-2007 05:35
Make a recursive search on array and return the matches elements in the same structure than the original array and unset empty arrays:

<?php
function array_search_recursive($needle, $haystack,&$tree=Array(),$index=""){
        if (is_array($haystack)){
            if (count($tree)==0) $tree=array_merge(Array(),$haystack);
            foreach($haystack as $k=>$current){
                if (is_array($current)){
                    array_search_recursive($needle,$current,$tree,$index."[$k]");
                    eval("\$a=\$tree{$index}[{$k}];"); // unset all elements = empty array
                    if (count($a)==0)  //is empty?
                        eval("unset(\$tree{$index}[$k]);"); // unset array
                }
                else{
                    if ($current!=$needle){
                        eval("unset(\$tree{$index}[{$k}]);");
                    }
                }
            }
        }
        return $tree;
    }
?>
chris 20-Nov-2007 07:11
<?php

/*Another recursive array_search that works better for me
* Returns all the keys to all the needles found
*and put them in an array.
*/

function array_search_recursive($needle, $haystack, $a=0, $nodes_temp=array()){
global $nodes_found;
  $a++;
  foreach ($haystack as $key1=>$value1) {
    $nodes_temp[$a] = $key1;
    if (is_array($value1)){
      array_search_recursive($needle, $value1, $a, $nodes_temp);
    }
    else if ($value1 === $needle){
      $nodes_found[] = $nodes_temp;
    }
  }
  return $nodes_found;
}
?>
kermes [at] thesevens [dot] net 11-Sep-2007 03:09
A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
    $result = array();
    for($i = 0; $i < count($array); next($array), $i++)
        if(strtolower(current($array)) == strtolower($str))
            array_push($result, key($array);

    return $result;
}
?>

Usage would be as follows:
<?php
$testArray = array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
    print_r(array_ksearch($testArray, 'test1'));
?>
robertark at gmail dot com 01-Sep-2007 11:20
A better array_isearch would be to store all results in an array, then return the KEYS stored in $found, such as:

<?php
function array_isearch($str, $array){
  $found = array();
  foreach ($array as $k => $v)
      if (strtolower($v) == strtolower($str)) $found[] = $k;
  return $found;
}
?>

To use, simply have an array to search from then search it, for example:

<?php

function array_isearch($str, $array) {
  $found = array();
  foreach($array as $k => $v)
    if(strtolower($v) == strtolower($str)) $found[] = $k;
  return $found;
}

$stored = "these are an array";
$stored = explode(" ", $stored);

$compare = array("these", "are", "some", "results", "stored", "in", "an", "array");
foreach($stored as $store) {
  $results = array_isearch($store, $compare);
  foreach($results as $key => $result)
    echo "Key: ".$results[$key]."<br />Found: ".$compare[$result]."<br />";
}

?>

Hope this helps :-)

-Rob
php5 site builder 23-May-2007 10:14
If you encounter a situation where condition test is failing on the result of either array_search or in_array, even when using "===" and "!==", make sure to set $strict = true in your array_search() or in_array() function call.

A situation such as :

$arTemp[0] = 1;
$arTemp[1] = 0;
$arTemp[2] = 3;
$arTemp[3] = 5;
$sTempTest = 'BLAH';

$bResult = in_array($sTempTest,$arTemp);
$bResult2 = array_search($sTempTest,$arTemp);

var_dump($bResult);
var_dump($bResult2);

will result in :

boolean true
int 1

Using :

$bResult = in_array($sTempTest,$arTemp,true);
$bResult2 = array_search($sTempTest,$arTemp,true);

will yield :
boolean false
boolean false

This is necessary in any instance where you have an array value equal to the integer zero.  As soon as you put the zero in quotes or double quotes (a string), the evaluation works with in_array & array_search without the $strict parameter being set.
elvenone at gmail dot com 27-Jan-2007 05:10
<?php
                // Search an array in reverse order.
        function array_reverse_search($value, $array) {
             for($i = sizeof($array)-1; $i>=0; $i--) {
                if ($array[$i] == $value) return $i;
             }
            return -1;
        }
?>
francois at tekwire dot net 18-Jan-2007 02:34
Please note that, in PHP5, if you search for an object in an array using the array_search() function, PHP will return the first object whose properties match, not the same class and instance as your needle. In other words, the object comparison is of type '==', not '===' (see the 'Comparing objects' page).
erick dot xavier at gmail dot com 04-Jan-2007 04:57
Modifing the "multiarray_search" to unordered Array....
<?PHP
function multiarray_search($arrayVet, $campo, $valor){
    while(isset($arrayVet[key($arrayVet)])){
        if($arrayVet[key($arrayVet)][$campo] == $valor){
            return key($arrayVet);
        }
        next($arrayVet);
    }
    return -1;
}

//I.e.:

$myArr = array(
    13 => array(
        "fruit" => "banana"
    ),
    654 => array(
        "fruit" => "apple"
    ),
    2445 => array(
        "fruit" => "nothing more"
    )
);

print(multiarray_search($myArr , "fruit", "apple"));

/*
Output:
654
*/

//and

print(multiarray_search($myArr , "fruit", "orange"));

/*
Output:
-1
*/
?>
otto at twbc dot net 13-Dec-2006 11:06
Unlimited depth array regular expression search, I found it useful, perhaps someone else will too. Searches on the array values only. Key search could be easily added.

<?php
function Array_Search_Preg( $find, $in_array, $keys_found=Array() )
{
    if( is_array( $in_array ) )
    {
        foreach( $in_array as $key=> $val )
        {
            if( is_array( $val ) ) $this->Array_Search_Preg( $find, $val, $keys_found );
            else
            {
                if( preg_match( '/'. $find .'/', $val ) ) $keys_found[] = $key;
            }
        }
        return $keys_found;
    }
    return false;
}
?>
evert_18 at hotmail dot com 13-Nov-2006 06:18
This function can search in multidimensional arrays, no mather how multidimensional the array is!

<?php
function array_search(&$array,$needle)
{
    foreach($array as $key => $value)
    {
        if($value == $needle || $key == $needle)
            return(true);
        else
            if(is_array($value))
                $this->search($value,$needle);
            else
                return(false);
    }
}
?>
dmitry dot polushkin at gmail dot com 21-Oct-2006 10:03
To get the key of the found search value, use:
<?php
$a = array('a', 'b', 'c');
echo array_search(array_search('c', $a), array_keys($a));
?>
jupiter at nospam dot com 29-Sep-2006 02:25
Checks that array value STARTS with the string(needle), while other functions require an exact match OR the needle can be anywhere within.  This function can be manipulated to END with the needle if needed
<?php
// returns first key of haystackarray which array valuestring starts with needlestring, is case-sensitive
function arrayHaystackStartsWithNeedleString($haystackarray, $needlestring) {
    if (is_array($haystackarray)) {  // confirms array
        $needlelength = strlen($needlestring);  // length of string needle
        foreach ($haystackarray as $arraykey => $arrayvalue) {  // gets array value
            $arraypart = substr($arrayvalue, 0, $needlelength);  // first characters of array value
            if ($needlestring == $arraypart) {  // did we find a match
                return $arraykey;  // return will stop loop
            }  // end match conditional
        }  // end loop
    }  // end array check
    return false;  // no matches found if this far
}
?>
I haven't speed tested this, but it should be pretty quick.
Digitally Designed dot co dot uk 28-Sep-2006 02:48
My Function to search a Multidimensional array.

Pass in :

$theNeedle as what you want to find.
$theHaystack as the array
$keyToSearch as what key in the array you want to find the value in.

<?php

function myMulti_Array_Search($theNeedle, $theHaystack, $keyToSearch)
        {
        foreach($theHaystack as $theKey => $theValue)
            {
            $intCurrentKey = $theKey;

            if($theValue[$keyToSearch] == $theNeedle)
                {

                return $intCurrentKey ;
                }
            else
                {
                return 0;
                }
            }
        }

?>
lars-magne 22-Sep-2006 05:19
Further comments on the multidimensional array searches given earlier:

I needed an extended search function which could search in both keys and values in any # dimension array and return all results. Each result contains key/value hit, type (key or value), key path and value (in case result is a key).

<?php

function array_search_ext($arr, $search, $exact = true, $trav_keys = null)
{
  if(!is_array($arr) || !$search || ($trav_keys && !is_array($trav_keys))) return false;
  $res_arr = array();
  foreach($arr as $key => $val)
  {
    $used_keys = $trav_keys ? array_merge($trav_keys, array($key)) : array($key);
    if(($key === $search) || (!$exact && (strpos(strtolower($key), strtolower($search)) !== false))) $res_arr[] = array('type' => "key", 'hit' => $key, 'keys' => $used_keys, 'val' => $val);
    if(is_array($val) && ($children_res = array_search_ext($val, $search, $exact, $used_keys))) $res_arr = array_merge($res_arr, $children_res);
    else if(($val === $search) || (!$exact && (strpos(strtolower($val), strtolower($search)) !== false))) $res_arr[] = array('type' => "val", 'hit' => $val, 'keys' => $used_keys, 'val' => $val);
  }
  return $res_arr ? $res_arr : false;
}

// I.e.:
$haystack[754] = "Norwegian";
$haystack[28]['details']['Norway'] = "Oslo";
$needle = "Norw";

if($results = array_search_ext($haystack, $needle, false))
  foreach($results as $res)
    echo "Found '$needle' in $res[type] '$res[hit]', using key(s) '".implode("', '", $res['keys'])."'. (Value: $res[val])<br />\n";

/* Printed result will be:
Found 'Norw' in val 'Norwegian', using key(s) '754'. (Value: Norwegian)
Found 'Norw' in key 'Norway', using key(s) '28', 'details', 'Norway'. (Value: Oslo)
*/

?>
mark dot php at mhudson dot net 11-Sep-2006 05:49
I was going to complain bitterly about array_search() using zero-based indexes, but then I realized I should be using in_array() instead.

// if ( isset( $_GET['table'] ) and array_search( $_GET['table'], $valid_tables) ) {  // BAD: fails on first[0] element
// if ( isset( $_GET['table'] ) and ( FALSE !== array_search( $_GET['table'], $valid_tables) ) ) { OK: but wasteful and convoluted
   if ( isset( $_GET['table'] ) and in_array( $_GET['table'], $valid_tables) ) { // BETTER

The essence is this: if you really want to know the location of an element in an array, then use array_search, else if you only want to know whether that element exists, then use in_array()
ob at babcom dot biz 28-Aug-2006 02:55
This function is based on the function in comment "array_search" from July 26th 2006.

I added the possibility of defining the key which $Needle shall be searched for.

<?php
// search haystack for needle and return an array of the key path,
// FALSE otherwise.
// if NeedleKey is given, return only for this key
// mixed ArraySearchRecursive(mixed Needle,array Haystack
//                            [,NeedleKey[,bool Strict[,array Path]]])

function ArraySearchRecursive($Needle,$Haystack,$NeedleKey="",
                              $Strict=false,$Path=array()) {
  if(!is_array($Haystack))
    return false;
  foreach($Haystack as $Key => $Val) {
    if(is_array($Val)&&
       $SubPath=ArraySearchRecursive($Needle,$Val,$NeedleKey,
                                     $Strict,$Path)) {
      $Path=array_merge($Path,Array($Key),$SubPath);
      return $Path;
    }
    elseif((!$Strict&&$Val==$Needle&&
            $Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))||
            ($Strict&&$Val===$Needle&&
             $Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))) {
      $Path[]=$Key;
      return $Path;
    }
  }
  return false;
}
?>

Remove unnecessary new lines. I had to add them because of too long lines.
26-Jul-2006 07:19
<?php
/**
 * Searches haystack for needle and returns an array of the key path if it is found in the (multidimensional) array, FALSE otherwise.
 *
 * mixed array_searchRecursive ( mixed needle, array haystack [, bool strict[, array path]] )
 */

function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }

    foreach( $haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}
?>
gullevek at gullevek dot org 18-Apr-2006 10:31
There were two previous entries for having a recursive search. The first one only searched for values, second one for values with an optional key.

But both of those stopped after they found an entry. I needed, that it searches recursive, with optional key and returns me all matches found in the array.

So I wrote this function:

needle is the value you search, haystack is the array of course, key is the optional key in the array where the needle should be. path should be never set on intial call. its an internal used variable.

It returns an array $path with the array entry 'found' where you can find all found groups. In these groups you have the array which holds the keys to find the data.

I hope this helps some of you.

<?php
    function array_search_recursive_all($needle, $haystack, $key, $path = NULL)
    {
        if (!$path['level'])
            $path['level'] = 0;
        if (!$path['work'])
            $path['work'] = array();
        if (!is_array($haystack))
            $haystack = array();

        // go through the array,
        foreach ($haystack as $_key => $_value)
        {
            // only value matches
            if (is_scalar($_value) && $_value == $needle && !$key)
            {
                $path['work'][$path['level']] = $_key;
                $path['found'][] = $path['work'];
            }
            // key and value matches
            elseif (is_scalar($_value) && $_value == $needle && $_key == $key)
            {
                $path['work'][$path['level']] = $_key;
                $path['found'][] = $path['work'];
            }
            elseif (is_array($_value))
            {
                // add position to working
                $path['work'][$path['level']] = $_key;
                // we will up a level
                $path['level'] += 1;
                // call recursive
                $path = array_search_recursive_all($needle, $_value, $key, $path);
            }
        }
        // cut all that is >= level
        array_splice($path['work'], $path['level']);
        // step back a level
        $path['level'] -= 1;
        return $path;
    }
?>

If you call it with this:

<?php
    $right_side = array ('foo' => 'alpha', 'bar' => 'beta', 'delta' => 'gamma', 'gamma' => 'delta');
    $value = 'beta';
    $key = 'bar';
    $pos = array_search_recursive_all($value, $right_side, $key);
?>

You will find in $pos this data

Array
(
    [level] => -1
    [work] => Array
        (
        )

    [found] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

        )

)
RichGC 20-Mar-2006 05:54
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array = array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if ($i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSE

if (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the second

if ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1

if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1

if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
congaz at yahoo dot dk 09-Mar-2006 07:38
Search a multi-dimensional array on keys!
-------------------------------------------

I needed to search dynamically in a multi-dimen array on keys. I came up with this little neat function. It is so amazingly simple, that I actually didn't think it would work - but it does...

mixed array_searchMultiOnKeys(array, array);

<?php
function array_searchMultiOnKeys($multiArray, $searchKeysArray) {
    // Iterate through searchKeys, making $multiArray smaller and smaller.
    foreach ($searchKeysArray as $keySearch) {
        $multiArray = $multiArray[$keySearch];
        $result = $multiArray;
    }

    // Check $result.
    if (is_array($multiArray)) {
        // An array was found at the end of the search. Return true.
        $result = true;
    }
    else if ($result == '') {
        // There was nothing found at the end of the search. Return false.
        $result = false;
    }

    return $result;
// End of function,
}

// --- Test array_searchMultiOnKeys ---
$multiArray['webpages']['downloads']['music'] = 1;
$multiArray['webpages']['downloads']['pressmaterial'] = 5;
$multiArray['webpages']['links'] = 7;

array_searchMultiOnKeys($multiArray, array('webpages', 'links')); // returns 7.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads')); // returns true.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads', 'software')); // returns false.

?>

$multiArray / $searchKeysArray can be any size.

Happy hacking...
chappy at citromail dot hu 11-Feb-2006 12:26
If you're searching for strings and you need a case-insensetive script, there's one:

<?php
function array_lsearch($str,$array){
    $found=array();
    foreach($array as $k=>$v){
        if(strtolower($v)==strtolower($str)){
            $found[]=$v;
        }
    }
    $f=count($found);
    if($f===0)return false;elseif($f===1)return $found[0];else return $found;
}
?>

It returns the original string, not the lower. Also good if use strtoupper().
hansen{�}cointel.de 08-Feb-2006 06:26
may be good to take note of PHP's mind-boggling 'fuzzy' (vulgo "magic type-casting") comparison features not only in using the results, but also in the search, too:
<?php
$a=array("a","b",0,"c","d");
echo "a: ".array_search("a",$a);
echo "b: ".array_search("b",$a);
echo "c: ".array_search("c",$a);
echo "d: ".array_search("d",$a);
echo "0: ".array_search("0",$a);
echo "x: ".array_search("x",$a);
echo "1: ".array_search("1",$a);
?>
will result in:
a: 0, b: 1, c: 2, d: 2, 0: 2, x: 2, 1: false

as from "c" on, the first match found in $a is "0", as any string compared to an int is automatically cast to (int)0.
ludwig_von_rocht at yahoo dot com 23-Nov-2005 03:50
Here's a little function I wrote to find the key of the LAST occurrance of something in an array.

<?php
if(!function_exists('array_rsearch')){
    function array_rsearch($search, $array, $strict = false){
        $array = array_reverse($array, true);
        foreach($array as $key => $value){
            if($strict){
                if($value === $search)
                    return $key;
            } else {
                if(strpos($value, $search))
                    return $key;
            }
        }
        return false;
    }
}
?>
mark meves 22-Nov-2005 03:13
A quick-and-dirty array_search_all() that i used for a small
dup-checking routine.

there are many, many ways to do something like this, not
the worst of which would be to use a relational database
for a dataset any larger than this ;)

-mark meves

<?php
/**
@return array of zero or more keys form $aHaystack whose
    values match $mScalarNeedle using a
    '==', (ie not strict) comparison
*/
function array_search_all($mScalarNeedle,$aHaystack){
    return array_keys( array_filter($aHaystack,
        create_function('$v','return $v == \''.addslashes($mScalarNeedle).'\';')
    ));
}

/*
test it:
*/
$aNicknames = array('jimmy'=>1,'james'=>1,'jim'=>1,
                    'billy'=>2,'william'=>2,'bill'=>2);
foreach(array('jim','bill') as $sName){
    echo "variations for \"$sName\" :(".
        implode(', ', array_search_all($aNicknames[$sName],$aNicknames)).
    ")\n";
}
/* outputs:
variations for "jim" are (jimmy, james, jim)
variations for "bill" are (billy, william, bill)
*/
?>
pornsak at neowin dot net 21-Nov-2004 07:28
This is a modified version of Mark Meves's wonderful function. I needed something that would be able to let me force search the key name where the needle should be found.

<?php
function array_search_recursive($needle, $haystack, $key_lookin="") {

$path = NULL;

    if (!empty($key_lookin) && array_key_exists($key_lookin, $haystack) && $needle === $haystack[$key_lookin]) {
    $path[] = $key_lookin;

    } else {

        foreach($haystack as $key => $val) {
            if (is_scalar($val) && $val === $needle && empty($key_lookin)) {
            $path[] = $key;
            break;
            }

            elseif (is_array($val) && $path = array_search_recursive($needle, $val, $key_lookin)) {
            array_unshift($path, $key);
            break;
            }
        }
    }

return $path;
}
?>
scripts at webfire dot org 03-Nov-2004 09:13
* Multi-Dimensional Array Search *
If you're searching for a function to search in Multi-Arrays,
this is probably usefull for you.
-------------------------------------------------------------

<?php
function multi_array_search($search_value, $the_array)
{
    if (is_array($the_array))
    {
        foreach ($the_array as $key => $value)
        {
            $result = multi_array_search($search_value, $value);
            if (is_array($result))
            {
                $return = $result;
                array_unshift($return, $key);
                return $return;
            }
            elseif ($result == true)
            {
                $return[] = $key;
                return $return;
            }
        }
        return false;
    }
    else
    {
        if ($search_value == $the_array)
        {
            return true;
        }
        else return false;
    }
}
?>

-------------------------------------------------------------
It will return an Array with the keys from the original array
where your search-string was found or false. e.g.:
-------------------------------------------------------------

<?php
$foo[1]['a']['xx'] = 'bar 1';
$foo[1]['b']['xx'] = 'bar 2';
$foo[2]['a']['bb'] = 'bar 3';
$foo[2]['a']['yy'] = 'bar 4';
$foo['info'][1] = 'bar 5';

$result = multi_array_search('bar 3', $foo);
print_r($result);
?>

-------------------------------------------------------------

Output:

Array
(
      [0] => 2
      [1] => a
      [2] => bb
)

-------------------------------------------------------------

I hope you like it ;)
greetz Udo
�
F�lix Cloutier <felixcca at yahoo dot ca> 22-Oct-2004 05:01
There is no function to count the occurences of needle in haystack, so I made my own one...

<?php
function array_match($needle, $haystack)
{
    if( !is_array($haystack) ) return false;

    $i = 0;
    while( (in_array( $needle, $haystack )) != FALSE )
    {
        $i++;
        $haystack[array_search($needle, $haystack)] = md5($needle);
        reset($haystack);
    }

    return $i;
}
?>

I know it's a bit crappy, but don't ask me too much, I'm still only 13... ;)
Wouter van Vliet <me at woutervanvliet dot nl> 19-Aug-2004 08:55
I was looking for a way to use a user defined function for array_search and eventually came up writing my own. Which was remarkably simple :P. Let me share this:

<?php
function array_usearch($cb, $ndl, $hs, $strict=false) {
    if (!is_array($hs)) user_error('Third argument to array_usearch is expected to be an array, '.gettype($hs).' given', E_USER_ERROR);
    foreach($hs as $key=>$value) if (call_user_func_array($cb, Array($ndl, $value, $key, $strict))) return $key;
};
?>

I'm not sure if I'm following correct conventions to specify the callback as the first argument, but it seemed most logical to me to not interrupt the order of the other four arguments (mixed needle, array haystack, boole strict).

[so far for my first post to the php notes]
andrey at php dot net 07-Aug-2004 04:56
array_search() has kind of hidden behaviour which comes from the way PHP compares values of different types (PHP is a type-loose language) - so called type juggling.
for example :
<?php
$a=array(0,0,5,0,0);
var_dump(array_search(true, $a));
?>
In the array there are only integers but we give a boolean value TRUE for be the needle. The result is that array_search() returns the first non-negative value in the haystack array. The same way if we pass FALSE it will return the first value that compared with FALSE gives TRUE - for example NULL
<?php
$a=array(1,NULL,5,0,0);
var_dump(array_search(FALSE, $a));
?>
Returns:
int(1)  <-- the key of the NULL value
softexpert [at] libertysurf [dot] fr 03-May-2004 11:51
I use this for searching for a value in a bidimensional array .

<?php
function SearchBiDimArray(&$theArray, $dimNo, $searchValue, $returnIndex = true){
    if(is_array($theArray)){
        $keys = array_keys($theArray[0]);
        $key = $keys[$dimNo];
        $elcount = count($theArray);

        for($i=0; $i < $elcount; $i++){
            if($theArray[$i][$key] === $searchValue){
                if ($returnIndex){
                    return $i;
                }
                else{
                    return $theArray[$i];
                }
            }
        }

    }
    else{
        return array_search($searchValue, $theArray);
    }
}

$theArray = array();
$theArray[0]['firstproperty'] = 'avalue1';
$theArray[0]['secondproperty'] = 'anothervalue1';

$theArray[1]['firstproperty'] = 'avalue2';
$theArray[1]['secondproperty'] = 'anothervalue2';

$theArray[2]['firstproperty'] = 'avalue3';
$theArray[2]['secondproperty'] = 'anothervalue3';

print SearchBiDimArray($theArray, 1, 'anothervalue2', true);
// result is 1

print SearchBiDimArray($theArray, 1, 'anothervalue2', true);
// result is
//Array
//(
//    [firstproperty] => avalue2
//    [secondproperty] => anothervalue2
//)

?>
dcsoboda at oakland dot edu 28-Jan-2004 01:13
I've noticed problems with array_search() when it's handling extremely large arrays.

In one example, I had a 2000 slot array with a 128 char string in each slot, and was searching for a 128 char string within the array.

It regularly returned the wrong key. I even had it print the search string, along with the found key in the array, as a  test, and it would print obvious different strings.

The problem was alleviated when I ran gzcompress() on each array slot (and on my search string, obviously). In this case, no strings were longer than 67 bytes. It performed far faster and had no accuracy problems.
dennis dot decoene at removthis dot moveit dot be 17-Jan-2004 10:41
It has been said before: array_search is VERY slow. Everyone knows binary search is fast by design. Here is an implementation.

<?php
$arr=array(1,3,5,7,9,10,11,13);
$searchfor = 6;
echo binsearch($searchfor, $arr);

/**
 * @return integer
 * @param var $needle
 * @param array $haystack
 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
             It will return false if not found or the index where it was found.
             This function is superfast. Try an array with 50.000 elements and search for something,
             you will be amazed.
*/
function binsearch($needle, $haystack)
{
    $high = count($haystack);
    $low = 0;

    while ($high - $low > 1){
        $probe = ($high + $low) / 2;
        if ($haystack[$probe] < $needle){
            $low = $probe;
        }else{
            $high = $probe;
        }
    }

    if ($high == count($haystack) || $haystack[$high] != $needle) {
        return false;
    }else {
        return $high;
    }
}
?>
jwhite at ytztech dot com 18-Nov-2003 06:59
Searching arrays is a very slow process.  I've tried to use as many strings as I can for where an array is called, if possible. Here's a quick test to show the (eye-popping) difference between searching for a match between strings and arrays:

<?php

  $test_string = '';
  for ($i=1; $i <= 500000; $i++) {
    $test_string .= '['.$i.']';
  }

  $test_array = array();
  for ($i=1; $i <= 5000; $i++) {
    $test_array[] = $i;
  }

  $time_str = getmicrotime();
  for ($i=1; $i <= 500000; $i++) {
    strstr($i,$test_string);
  }
  $time_str = getmicrotime() - $time_str;

  $time_array = getmicrotime();
  for ($i=1; $i <= 5000; $i++) {
    array_search($i,$test_array);
  }
  $time_array = getmicrotime() - $time_array;

  echo "<H1>Test Results</H1>\r\n";
  echo "<P>String Test:&nbsp; $time_str seconds.</P>\r\n";
  echo "<P>Array Test:&nbsp; $time_array seconds.</P>\r\n";

   function getmicrotime(){
     list($usec, $sec) = explode(" ",microtime());
     return ((float)$usec + (float)$sec);
   }

?>

This code block takes some time to get going (because of the number of strings to place into memory), the results, even on modest hardware are staggering.  Comparing 500000 strstr() operations to 5000 array_search() operations on a P3-800 with 512 MB of RAM got the following output:

[H1]Test Results[/H1]
[P]String Test: 3.09137701988 seconds.[/P]
[P]Array Test:  4.23609495163 seconds.[/P]

The getmicrotime() function came from the note on microtime(), so that's not mine...credit to "daniel141 at yahoo dot com".

STRINGS RULE!
--
Justin White
YTZ Technical Services, LLC
php at celerondude dot com 12-Nov-2003 03:07
I think array_search uses serial search because they binary search function i wrote here seems to do a better job for records that are not always at the beginning of the array.

Here it is

<?php
function binarySearch ( $a, $t, $l, $r )
{
    if($t<$a[$l]||$t>$a[$r])return NULL;
    while ( $l < $r )
    {
        $m=intval($l+$r)/2;
        if($a[$m]==$t)return $m;
        elseif($t<$a[$m])$r=$m-1;
        elseif($t>$a[$m])$l = $m + 1;
    }
    if($t==$a[$r])
    return $r;
    return NULL;
}
?>

usage:
binarySearch ( array, target, left range, right range );

if your array is a multidimensional array, simply change the comparison method. :)
cue at openxbox dot com 09-Jun-2003 07:50
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match.  Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.  This nuance cost me a lot of time and sanity, so I hope this helps someone.  In case you don't know what I'm talking about, here's an example:

<?php
$code = array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

// this is WRONG
while (($key = array_search("a", $code)) != NULL)
{
 // infinite loop, regardless of the unset
 unset($code[$key]);
}

// this is _RIGHT_
while (($key = array_search("a", $code)) !== NULL)
{
 // loop will terminate
 unset($code[$key]);
}
?>
richard at richard-sumilang dot com 16-Apr-2003 03:59
<?php
/**
     *    Search an array recursivly
     *
     *    This function will search an array recursivly
     *    till it finds what it is looking for. An array
     *    within an array within an array within array
     *    is all good :-)
     *
     *    @author        Richard Sumilang    <richard@richard-sumilang.com>
     *    @param        string    $needle        What are you searching for?
     *    @param        array    $haystack    What you want to search in
     *    @return        boolean
     *    @access        public
     */
    function array_search_r($needle, $haystack){
        foreach($haystack as $value){
            if(is_array($value))
                $match=array_search_r($needle, $value);
            if($value==$needle)
                $match=1;
            if($match)
                return 1;
        }
        return 0;
    }
?>
Darkvie 16-Mar-2003 04:53
I wanted to search a  multidimensional array for a value & assign another element of array CONTAINING the searched value.

In the array I am using ($Projects), each item in $Projects contains a "Text_ID" & "Text_Value" field from a database result. I want to search for a "Text_ID" value (456 in this example)  & get it's "Text_Value" value assigned to a variable called $Text_Value.

Here's how I did it:
============================================

<?PHP
//Array I am going to look in:
$Projects[0] = array(123, "Text 1");
$Projects[1] = array(456, "Text 2");
$Projects[2] = array(789, "Text 3");

// This loop goes through every element in $Projects
foreach ($Projects as $key => $ArrayRow)
{
// Now: $ArrayRow[0] = $Projects[x][0] and $ArrayRow[1] = $Projects[x][1]

// Look for the value "456".  Assign to variable & stop looking if found.
if ($ArrayRow[0] == "456")  {$Text_Value= $ArrayRow[1]; break; }
}
?>

============================================
Hope this helps someone.
-Darkive
retestro_REMOVE at SPAM_esperanto dot org dot il 28-Feb-2003 08:46
If you're interested in finding a line in a file, after you read it into an array using file(), you can not use array_search since the match should be exact, and lines have line-endings ('\n', '\r' or '\n\r') - or else you know for sure what your lines contain physically.

The solution is to traverse the whole array, trim() each entry and then use array_search() - or - use something like the following small function I wrote for myself:

<?php
function search_array($needle, $haystack)
{
        if (!is_array($haystack) || !is_string($needle))
                return false;  // not valid argument types

        @reset($haystack);

        while (list ($key, $value) = each($haystack)) {
                $value = trim($value);  // remove spaces from the beginning and the end
                if ($value === $needle)
                        return $key;  // $needle was found, return the key
        }

        return false;  // no $needle was found in $haystack
}
?>

-----------------------------
Notes:
1. you should check the return value with === since 0 as a key equals to 'false'.
    i.e. if (search_array('my_line', $my_array) === false)  { ... }
2. I have no need in whitespace at the beginning of the line, therefore I use trim(). If it's important to you, use rtrim() or chop() instead.

-
- Sergey.
saltymeat at hotmail dot com 24-Jun-2002 02:03
Here's how you can use array_search() to replace all occurances of a value in an array:

<?php
function array_replace($a, $tofind, $toreplace)
{
    $i = array_search($tofind, $a);
    if ($i === false)
    {
        return $a;
    }
    else
    {
        $a[$i] = $toreplace;
        return array_replace($a, $tofind, $toreplace);
    }
}
?>

Usage:
$a = array(1,2,3);
$a = array_replace($a, 1, 4);
echo $a[0]; // Outputs 4
dakota at dir dot bg 29-May-2002 04:44
For versions later than 4.2.0, the check  isset($key) won't work properly because the function now returns false, which "isset". This change is missing in the Change Log!

So the right way to use the function is:

<?php
$key = array_search($needle, $array);
if ($key!==null&&$key!==false) {
  ...
}
?>

This example will work in both older and newer to 4.2.0 versions.

P.S.: My previous post where isset() is used won't work in newer versions.
swbrown at ucsd dot edu 02-May-2002 01:18
Be absolutely sure to check that your code that uses array_search now checks for 'false' too if you upgrade to PHP 4.2.0!

I was using array_search in my page authentication routines and this change had the fun side-effect of causing my code to always think a user had full permissions!  It was letting anyone click through to our installation of phpMyAdmin.  Not good indeed!
saconner at iastate dot edu 04-Feb-2002 01:16
In PHP versions before 4.2.0 needle was not allowed to be an array.  (funnily enough, at time of posting this note, we're still at ver 4.1.1 )
array_reverse
array_shift
Функции для работы с массивами


Извлекает первый элемент массива

array_search
array_slice
Функции для работы с массивами
PHP Manual

array_shift

(PHP 4, PHP 5)

array_shift — Извлекает первый элемент массива

Описание

mixed array_shift ( array &$array )

array_shift() извлекает первое значение массива array и возвращает его, сокращая размер array на один элемент. Все числовые ключи будут изменены таким образом, что нумерация массива начнётся с нуля, в то время как строковые ключи останутся прежними.

Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.

Список параметров

array

Входной массив.

Возвращаемые значения

Возвращает извлекаемое значение, или NULL, если array пуст или не является массивом.

Примеры

Пример #1 Пример использования array_shift()

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

Результат выполнения данного примера:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

и значение orange будет присвоено переменной $fruit.

Смотрите также

  • array_unshift() - Добавляет один или несколько элементов в начало массива
  • array_push() - Добавляет один или несколько элеметов в конец массива
  • array_pop() - Извлекает последний элемент массива

User Contributed Notes

info at chihoang dot de 20-Apr-2011 09:46
This doesn't work with a 2 dimensional array. With 2 dimensional array I do this:

<?php
$backup = $arr;
$first = array_shift ( $backup );
?>
ar at xonix dot ch 14-Aug-2010 03:54
If you need the first or last entry of an array, then this could help you.

<?php
function array_last_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    return end($arr);
}

function array_first_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    reset($arr);
    return current($arr);
}

$arr = array( '5' => 'five', '3' => 'three', '8' => 'eight',);

echo 'last entry: '.array_last_entry($arr).'<br>';

echo 'first entry: '.array_first_entry($arr).'<br>';

echo 'alternative output:<br>';

echo 'last entry: '.$arr[count($arr)-1];

echo '<br>first entry: '.$arr[0];
?>

The output will look like:
last entry: eight
first entry: five
alternative output:
last entry:
first entry:

As you can see, if you have to handle arrays with non-continuous indexes, these functions may be very helpful.
patrick at pwfisher dot com 21-Aug-2009 08:23
Here's a utility function to parse command line arguments.

<?php
/**
 * CommandLine class
 *
 * @package             Framework
 */
/**
 * Command Line Interface (CLI) utility class.
 *
 * @author              Patrick Fisher <patrick@pwfisher.com>
 * @since               August 21, 2009
 * @package             Framework
 * @subpackage          Env
 */
class CommandLine {

    /**
     * PARSE ARGUMENTS
     *
     * [pfisher ~]$ echo "<?php
     * >     include('CommandLine.php');
     * >     \$args = CommandLine::parseArgs(\$_SERVER['argv']);
     * >     echo "\n", '\$out = '; var_dump(\$args); echo "\n";
     * > ?>" > test.php
     *
     * [pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --alsofunny=spam=eggs \
     * > 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
     *
     * $out = array(12) {
     *   [0]                => string(9) "plain-arg"
     *   ["foo"]            => bool(true)
     *   ["bar"]            => string(3) "baz"
     *   ["funny"]          => string(9) "spam=eggs"
     *   ["alsofunny"]      => string(9) "spam=eggs"
     *   [1]                => string(11) "plain arg 2"
     *   ["a"]              => bool(true)
     *   ["b"]              => bool(true)
     *   ["c"]              => bool(true)
     *   ["k"]              => string(5) "value"
     *   [2]                => string(11) "plain arg 3"
     *   ["s"]              => string(9) "overwrite"
     * }
     *
     * @author              Patrick Fisher <patrick@pwfisher.com>
     * @since               August 21, 2009
     * @see                 http://www.php.net/manual/en/features.commandline.php
     *                      #81042 function arguments($argv) by technorati at gmail dot com, 12-Feb-2008
     *                      #78651 function getArgs($args) by B Crawford, 22-Oct-2007
     * @usage               $args = CommandLine::parseArgs($_SERVER['argv']);
     */
    public static function parseArgs($argv){

        array_shift($argv);
        $out                            = array();

        foreach ($argv as $arg){

            // --foo --bar=baz
            if (substr($arg,0,2) == '--'){
                $eqPos                  = strpos($arg,'=');

                // --foo
                if ($eqPos === false){
                    $key                = substr($arg,2);
                    $value              = isset($out[$key]) ? $out[$key] : true;
                    $out[$key]          = $value;
                }
                // --bar=baz
                else {
                    $key                = substr($arg,2,$eqPos-2);
                    $value              = substr($arg,$eqPos+1);
                    $out[$key]          = $value;
                }
            }
            // -k=value -abc
            else if (substr($arg,0,1) == '-'){

                // -k=value
                if (substr($arg,2,1) == '='){
                    $key                = substr($arg,1,1);
                    $value              = substr($arg,3);
                    $out[$key]          = $value;
                }
                // -abc
                else {
                    $chars              = str_split(substr($arg,1));
                    foreach ($chars as $char){
                        $key            = $char;
                        $value          = isset($out[$key]) ? $out[$key] : true;
                        $out[$key]      = $value;
                    }
                }
            }
            // plain-arg
            else {
                $value                  = $arg;
                $out[]                  = $value;
            }
        }
        return $out;
    }
}
?>
regs at voidship dot net 03-Nov-2008 12:50
Using array_shift over larger array was fairly slow.  It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn't need to reindex the array and will preserve keys if you want it to (didn't matter in my case).

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop.  It also requires sequential numeric keys.
chris {at} w3style {dot} co {dot} uk 05-Oct-2008 06:06
As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn't return the first element by reference.  This may seem like very unexpected behaviour.  If you're working with a collection of references (in my case XML Nodes) this should do the trick.

<?php

/**
 * This function exhibits the same behaviour is array_shift(), except
 * it returns a reference to the first element of the array instead of a copy.
 *
 * @param array &$array
 * @return mixed
 */
function &array_shift_reference(&$array)
{
  if (count($array) > 0)
  {
    $key = key($array);
    $first =& $array[$key];
  }
  else
  {
    $first = null;
  }
  array_shift($array);
  return $first;
}

class ArrayShiftReferenceTest extends UnitTestCase
{

  function testFunctionRemovesFirstElementOfNumericallyIndexedArray()
  {
    $input = array('foo', 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionRemovesFirstElementOfAssociativeArray()
  {
    $input = array('x' => 'foo', 'y' => 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('y' => 'bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionReturnsReferenceToFirstElementOfNumericallyIndexedArray()
  {
    $foo = 'foo';
    $input = array(&$foo, 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsReferenceToFirstElementOfAssociativeArray()
  {
    $foo = 'foo';
    $input = array('x' => &$foo, 'y' => 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsNullIfEmptyArrayPassedAsInput()
  {
    $input = array();
    $first = array_shift_reference($input);
    $this->assertNull($first, '%s: Array has no first element so NULL should be returned');
  }

}

?>
sggoyal at gmail dot com 07-Sep-2008 10:08
// To Change order of Array by Saurabh Goyal
    function change_array_order($table,$order)
    {
       //init the new table
       $new_table = array();
       foreach($order as $colname)
       {
          $new_table[$colname] = $table[$colname];
       }
       return $new_table;
    }

if array value like:-
$row = array('usr_id'=>'23','usr_name'=>'Saurabh', 'usr_surname'=>'Goyal','usr_firstname'=>'Saurabh');

//you want change order & show only particular field
change_array_order($row,array('usr_name','usr_firstname',
                                            'usr_surname'));

Regard's

Saurabh Goyal
http://sggoyal.blogspot.com
nospam at dyce dot losethisbit dot com 02-Jul-2008 05:15
Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me ;-)

<?php

function array_kshift(&$arr)
{
  list($k) = array_keys($arr);
  $r  = array($k=>$arr[$k]);
  unset($arr[$k]);
  return $r;
}

// test it on a simple associative array
$arr = array('x'=>'ball','y'=>'hat','z'=>'apple');

print_r($arr);
print_r(array_kshift($arr));
print_r($arr);

?>

Output:

Array
(
    [x] => ball
    [y] => hat
    [z] => apple
)
Array
(
    [x] => ball
)
Array
(
    [y] => hat
    [z] => apple
)
Maikel 19-Feb-2008 09:43
In response to nando_f at nothingsimple dot com

The example is correct,  array_shift do an unset to first element  because the parameter is passed by reference
Ben 02-Oct-2007 09:17
baughmankr at appstate dot edu, I think this is more efficient.

<?php
function array_shorten($arr)
{
  list($k) = array_keys($arr);
  unset($arr[$k]);
  return $arr;
}
?>
baughmankr at appstate dot edu 18-Sep-2007 02:04
I needed to remove the first set of keys and values from an associative array.  Had to write this function:

function shortenArray($_arr)
{
    $i=1;
    $_shorter=array();
    foreach ($_arr as $k => $v)
    {
        if ($i != 1)
        {
            $_shorter[$k] = $v;
        }
        $i++;
    }
    return $_shorter;
}
dmhouse at gmail dot com 08-Aug-2007 01:54
If you want a version of array_shift() that works non-destructively (i.e., an easy function to grab the first element of the array without modifying the array), try reset().
Traps 09-Jul-2007 10:52
For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

<?php

// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 1, b = 2

// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 2, b = 2

?>
C_Prevost at myob 30-Apr-2007 04:52
no, it demonstrates quite well that it removes the first element in the original array, updating the keys, and that it also returns the original first element.
richard at happymango dot me dot uk 12-Apr-2007 06:09
If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.

<?php

while($key = key($array))
{
     $value = array_shift($array);
     //code goes here
}

?>

its like foreach but each time the value is removed from the array so it eventually ends up empty

<?php

//example below

$airports = array
(
    "LGW" => "London Gatwick",
    "LHR" => "London Heathrow",
    "STN" => "London Stanstead"
);

echo count($airports)." Airport in the array<br /><br />";

while($key = key($airports))
{
    $value = array_shift($airports);
    echo $key." is ".$value."<br />";
}

echo "<br />".count($airports)." Airport left in the array";

?>

Example Outputs:

3 Airport in the array

LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead

0 Airport left in the array
François 27-Oct-2006 08:35
Note that array_shift() can be rather time consuming. Whenever possible, you should consider using array_slice() instead.
Consider the following code :

$monthlyHits = 0;
reset ($hitsArray);
foreach($hitsArray as $visitTime ) {
if ($visitTime < $monthStart ) {
array_shift($hitsArray);
$monthlyHits++;
}
}

This could be replaced by :
$monthlyHits = 0;
reset ($hitsArray);
foreach($hitsArray as $visitTime ) {
if ($visitTime < $monthStart ) {
$monthlyHits++;
}
}
$monthlyHits = array_slice($hitsArray,$monthlyHits);

Here is a benchmark I did on a 10 000 rows array :
First method, 9000 mili-seconds.
Second method, 4 mili-seconds
alreece45 at yahoo dot com 09-Aug-2006 08:13
I haven't really read into it, but if you're complaining about a change in PHP 5.0.5 that made it so you couldn't do:

<?php

$val = array_shift(preg_split());

?>

or

<?php

$val = array_shit(function_that_returns_array);

?>

Then you're not using this function correctly. This function's argument is supposed to be a pointer to a variable. It then modifies that variable and returns a value. When you specify a function, php CAN NOT modify the return value of that function. It should be common sense but apparently its not.

Also, on a efficiency note, you might want to consider using another function such as reset or perhaps making your own function such as below:

<?php

function first_element($array) {

return reset($array);

}

?>

Unless of course for some reason you need to save the microseconds this takes.

}
bmr at ediweb dot org 31-May-2006 07:27
If the array has non-numerical keys, array_shift extracts the first element, whichever is the key, and recompute the numerical keys, if there are any. Ie :

$array = array("c" => "ccc", 0 => "aaa", "d" => "ddd", 5 => "bbb");
$first = array_shift($array);
echo '$first = ' . $first . ', $array = ' . var_export($array, true);

will display :

$first = ccc, $array = array ( 0 => 'aaa', 'd' => 'ddd', 1 => 'bbb', )

It means that array_shift works with associative arrays too, and leaves the keys unchanged if they are non-numerical.
19-Sep-2005 07:57
<?php

//----------------------------------------------------------
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//----------------------------------------------------------

function create_relative_path($inSourcePath, $inRefPath)
{
    // break strings at slashes
    $s_parts            = explode('/', $inSourcePath);
    $r_parts            = explode('/', $inRefPath);

    // delete items up to the first non-equal part
    while ($s_parts[0] === $r_parts[0])
    {
        array_shift($s_parts);
        array_shift($r_parts);
    }

    // add wild card to r_parts for each remaining
    // item of s_parts
    while ($s_parts[0])
    {
        array_unshift($r_parts, '..');
        array_shift($s_parts);
    }

    return implode('/', $r_parts);
}

//----------------------------------------------------------
// Example:
//     Given a source path $sp generates the relative
//     location of $rp. $sp could be assigned using
//     $_SERVER['PHP_SELF'] but it's hardcoded for
//     the example.
//----------------------------------------------------------
$sp = '/WebServer/Documents/MyBigProject/php/project_script.php';
$rp = '/WebServer/Documents/MyLibraries/lib_script.php';

// plugging them into the function
$rel_path = create_relative_path($sp, $rp);

// yeilds
'../../../MyLibraries/lib_script.php'

// and it could be used like
include_once(create_relative_path($_SERVER['PHP_SELF'], $rp));
lukasz dot dywicki DEL at gmail dot com 27-Jul-2005 05:48
Im using this function to browse arrays from database. For example data:
<?php
$data = array(
      array('row 1-cell 1','row 1-cell 2'),
      array('row 2-cell 1','row 2-cell 2'),
      array('row 3-cell 1','row 3-cell 2'),
);

while($row=array_shift($data)) {
      echo $row[0];
}
?>
Output:
row 1-cell 1
row 2-cell 1
row 3-cell 1
arturo {dot} ronchi {at} gmail {dot} com 20-Apr-2005 06:24
Here is a little function if you would like to get the top element and rotate the array afterwards.

function array_rotate(&$arr)
{
  $elm = array_shift($arr);
  array_push($arr, $elm);
  return $elm;
}
09-Feb-2005 04:27
This function will save the key values of an array, and it will work in lower versions of PHP:

<?php

function array_shift2(&$array){
    reset($array);
    $key = key($array);
    $removed = $array[$key];
    unset($array[$key]);
    return $removed;
}

?>
James McGuigan 14-Dec-2004 11:26
while(array_shift()) can be used to process multiple arrays and/or database results in a single loop. The || short circuts and only evaluates the first statement until it runs out of data.

It can help to reduce duplicated code (the rule is code once and once only).

Note that each ($row = ) statement much be encased in ()'s otherwise you will get funny results. If you use two array_shift($array) statements and forget the ()'s, you will repeatedly get the first element of the first array for the for the count of the $array.

<?php

require_once('class.db.php');

$sql = "SELECT title FROM links";
$result = mysql_query($sql, $db->connection);

$defaults = array(
     array('title' => 'None'),
     array('title' => 'Unknown')
);

while ( ($row = mysql_fetch_assoc($result))
     || ($row = array_shift($defaults)))
{
  echo $row['title'] . "<br>";
}

?>

This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown
alex at netflex dot nl 13-Mar-2003 10:55
Hi,

if you want to shift the first element of a large array (more than 10.000?) and it must realy fast then you can use this better:

<?php
reset($array);
list($oldKey, $oldElement) = each($array);
unset($array[$oldKey]);
?>

note: the index wil not be changed (not reindexed)
array_search
array_slice
Функции для работы с массивами


Выбирает срез массива

array_shift
array_splice
Функции для работы с массивами
PHP Manual

array_slice

(PHP 4, PHP 5)

array_slice — Выбирает срез массива

Описание

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

array_slice() возвращает последовательность элементов массива array, определённую параметрами offset и length.

Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.

Список параметров

array

Входной массив.

offset

Если параметр offset неотрицателен, последовательность начнётся на указанном расстоянии от начала array. Если offset отрицателен, последовательность начнётся на расстоянии указанном расстоянии от конца array.

length

Если в эту функцию передан положительный параметр length, последовательность будет включать количество элементов меньшее или равное length, length, length. Если количество элементов массива меньше чем параметр length, то только доступные элементы массива будут присутствовать. Если в эту функцию передан отрицательный параметр length, последовательность остановится на указанном расстоянии от конца массива. Если он опущен, последовательность будет содержать все элементы с offset до конца массива array.

preserve_keys

Обратите внимание, что по умолчанию array_slice() сбрасывает ключи массива. Вы можете переопределить это поведение, установив параметр preserve_keys в TRUE.

Возвращаемые значения

Возвращает срез.

Список изменений

Версия | Описание
5.0.2 | Добавлен необязательный параметр preserve_keys.

Примеры

Пример #1 Пример использования array_slice()

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // возвращает "c", "d", и "e"
$output = array_slice($input, -2, 1);  // возвращает "d"
$output = array_slice($input, 0, 3);   // возвращает "a", "b", и "c"

// заметьте разницу в индексах массивов
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

Результат выполнения данного примера:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

Смотрите также

  • array_splice() - Удаляет часть массива и заменяет её чем-нибудь ещё
  • unset() - Удаляет переменную
  • array_chunk() - Разбивает массив на части

User Contributed Notes

masta dot hacks at gmail dot com 29-Mar-2012 08:53
This might be obvious to other people but it took me a long time to figure it out; $length takes precedence over $preserve_keys

An example:
<?php
$array = array(1, 2, 3, 4, 5);

$slice = array_slice($array, 3);
print_r($slice); //This will return array(4, 5)

//However
$slice = array($array, 3, True); //This will return array(4)
//The reason for this, is it's read like $array=$array, $offset=3, $length=True
?>
gary at wits dot sg 10-Jun-2011 11:44
I've found this useful.
The following is a function used to shuffle a very specific part of the array, by providing start and end index.

<?php
function array_shuffle_section(&$a, $s, $e) {
    $head = array_slice($a, 0, $s);
    $body = array_slice($a, $s, $e-$s+1);
    $tail = array_slice($a, $e+1);

    shuffle($body);
    $a = array_merge($head,$body,$tail);
}
?>
Nathan - thefiscster510 at gmail dot com 29-Mar-2011 10:38
If you want to remove a specified entry from an array i made this mwethod...

<?php
$array = array("Entry1","entry2","entry3");

$int = 3; //Number of entries in the array
$int2 = 0; //Starter array spot... it will begine its search at 0.
$del_num = 1; //Represents the second entry in the array... which is the one we will happen to remove this time... i.e. 0 = first entry, 1 = second entry, 2 = third...........

$newarray = array(); //Empty array that will be the new array minus the specified entry...
print_r($array) . "<br>";    //print original array contents
print_r($newarray). "<br>"; //print the new empty array

do
{
$user = $array[$int2];
$key = array_search($user, $array);
if ($key == $del_num)
{

}
else
{
$newarray[] = $array[$int2];
}

$int2 = $int2 + 1;
} while ($int2 < $int);

print_r($newarray). "<br>"; //print the new array

?>
delew 11-Feb-2011 01:17
just a little tip.
to preserve keys without providing length: use NULL

array_slice($array, $my_offset, NULL, true);
xananax at yelostudio dot com 02-Feb-2011 07:23
<?php
/**
 * Reorders an array by keys according to a list of values.
 * @param array $array the array to reorder. Passed by reference
 * @param array $list the list to reorder by
 * @param boolean $keepRest if set to FALSE, anything not in the $list array will be removed.
 * @param boolean $prepend if set to TRUE, will prepend the remaining values instead of appending them
 * @author xananax AT yelostudio DOT com
 */
function array_reorder(array &$array,array $list,$keepRest=TRUE,$prepend=FALSE,$preserveKeys=TRUE){
    $temp = array();
    foreach($list as $i){
        if(isset($array[$i])){
            $tempValue = array_slice(
                $array,
                array_search($i,array_keys($array)),
                1,
                $preserveKeys
            );
            $temp[$i] = array_shift($tempValue);
            unset($array[$i]);
        }
    }
    $array = $keepRest ?
        ($prepend?
            $array+$temp
            :$temp+$array
        )
        : $temp;
}

/** exemple ** /
$a = array(
    'a'    =>    'a',
    'b'    =>    'b',
    'c'    =>    'c',
    'd'    =>    'd',
    'e'    =>    'e'
);
$order = array('c','b','a');

array_reorder($a,$order,TRUE);
echo '<pre>';
print_r($a);
echo '</pre>';
/** exemple end **/
?>
ch1902uk 20-Jan-2011 05:22
Here's an array_slice function for associative arrays. It slices by array key from and including that key. If the $length is a string it is assumed to be another array key and the array is sliced up to but not including the end key otherwise it slices that length.

<?php

function array_slice_assoc ($array, $key, $length, $preserve_keys = true)
{
   $offset = array_search($key, array_keys($array));

   if (is_string($length))
      $length = array_search($length, array_keys($array)) - $offset;

   return array_slice($array, $offset, $length, $preserve_keys);
}

?>

Example usage:

<?php
$arr = array('a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', 'e' => 'e', 'f' => 'f');

print_r(array_slice_assoc($arr, 'b', 2, true));
/*
Array
(
    [b] => b
    [c] => c
)
*/

print_r(array_slice_assoc($arr, 'b', 'e', true));
/*
Array
(
    [b] => b
    [c] => c
    [d] => d
)
*/

print_r(array_slice_assoc($arr, 'b', -1, true));
/*
Array
(
    [b] => b
    [c] => c
    [d] => d
    [e] => e
)
*/
?>
joel dot a dot villarreal at gmail dot com 19-Oct-2010 03:41
An implementation of array_slice that do not resets the cursor.

<?php
function get_from_array($arr, $start, $length)
{
    $sliced = array();
    foreach ($arr as $k => $v)
    {
        if ($start <= $k && $k <= $start + $length - 1)
        {
            $sliced[] = $v;
            if (count($sliced) == $length) break;
        }
    }
    return $sliced;
}
?>

Cheers,
Joel A. Villarreal Bertoldi
yuwas at ht dot cx 04-Apr-2010 06:54
By combining this with str_split() and implode(),slices can also be excerpted from strings with the following simple function:
<?php
function str_slice($string,$offset,$length=999,$preserve_keys=False){
  if( $length == 999 ){ $length = strlen($string)-$offset };
  $slice_arr = array_slice(str_split($string),$offset,$length,$preserve_keys);
  return implode($slice_arr);
};
?>

Perhaps there's a better way to preset $length.
jamie at jamiechong dot ca 18-Oct-2009 04:04
A flexible array_split function:

<?php
// split the given array into n number of pieces
function array_split($array, $pieces=2)
{
    if ($pieces < 2)
        return array($array);
    $newCount = ceil(count($array)/$pieces);
    $a = array_slice($array, 0, $newCount);
    $b = array_split(array_slice($array, $newCount), $pieces-1);
    return array_merge(array($a),$b);
}

// Examples:
$a = array(1,2,3,4,5,6,7,8,9,10);
array_split($a, 2);    // array(array(1,2,3,4,5), array(6,7,8,9,10))
array_split($a, 3);    // array(array(1,2,3,4), array(5,6,7), array(8,9,10))
array_split($a, 4);    // array(array(1,2,3), array(4,5,6), array(7,8), array(9,10))

?>
jamon at clearsightdesign dot com 10-Apr-2009 05:46
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.

<?php

/*
** function array_surround by Jamon Holmgren of ClearSight Design
** Version 1.0 - 4/10/2009
** Please direct comments and questions to my first name at symbol clearsightdesign.com
**
** Returns an array with only the $before and $after number of results
** This is set to work best with MySQL data results
** Use this to find the rows immediately before and after a particular row, as many as you want
**
** Example usage:
**   $mysql_ar is an array of results from a MySQL query and the current id is $cur_id
**   We want to get the row before this one and five rows afterward
**
** $near_rows = array_surround($mysql_ar, "id", $cur_id, 1, 5)
**
**   Previous row is now $near_rows[-1]
**   Current row is now $near_rows[0]
**   Next row is $near_rows[1] ... etc
**   If there is no previous row, $near_rows[-1] will not be set...test for it with is_array($near_rows[-1])
**
*/
function array_surround($src_array, $field, $value, $before = 1, $after = 1) {
    if(is_array($src_array)) {
        // reset all the keys to 0 through whatever in case they aren't sequential
        $new_array = array_values($src_array);
        // now loop through and find the key in array that matches the criteria in $field and $value
        foreach($new_array as $k => $s) {
            if($s[$field] == $value) {
                // Found the one we wanted
                $ck = $k; // put the key in the $ck (current key)
                break;
            }
        }
        if(isset($ck)) { // Found it!
            $result_start = $ck - $before; // Set the start key
            $result_length = $before + 1 + $after; // Set the number of keys to return
            if($result_start < 0) { // Oops, start key is before first result
                $result_length = $result_length + $result_start; // Reduce the number of keys to return
                $result_start = 0; // Set the start key to the first result
            }
            $result_temp = array_slice($new_array, $result_start, $result_length); // Slice out the results we want
            // Now we have an array, but we want array[-$before] to array[$after] not 0 to whatever.
            foreach($result_temp as $rk => $rt) { // set all the keys to -$before to +$after
                $result[$result_start - $ck + $rk] = $rt;
            }
            return $result;
        } else { // didn't find it!
            return false;
        }
    } else { // They didn't send an array
        return false;
    }
}

?>

I hope you find this useful! I welcome constructive criticism or comments or of course praise ;) -- just e-mail me.

- Jamon Holmgren
Mr. P 14-Nov-2008 02:11
Note that offset is not the same thing as key. Offset always starts at 0, while keys might be any number.

So this:

<?php print_r(array_slice(array(0 => 0, 5 => 5, 13 => 13),1)); ?>

will result in this:
Array
(
    [0] => 5
    [1] => 13
)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 07:53
Using the varname function referenced from the array_search page, submitted by dcez at land dot ru. I created a multi-dimensional array splice function. It's usage is like so:

$array['admin'] = array('blah1', 'blah2');
$array['voice'] = array('blah3', 'blah4');
array_cut('blah4', $array);

...Would strip blah4 from the array, no matter where the position of it was in the array ^^ Returning this...

Array ( [admin] => Array ( [0] => blah1 [1] => blah2 ) [voice] => Array ( [0] => blah3 ) )

Here is the code...

<?php

  function varname ($var)
  {
    // varname function by dcez at land dot ru
    return (isset($var)) ? array_search($var, $GLOBALS) : false;
  }

  function array_cut($needle, $haystack)
  {
    foreach ($haystack as $k => $v)
    {
      for ($i=0; $i<count($v); $i++)
        if ($v[$i] === $needle)
        {
          return array_splice($GLOBALS[varname($haystack)][$k], $i, 1);
          break; break;
        }
    }

?>

Check out dreamevilconcept's forum for more innovative creations!
disnider at gmail dot com 25-Jun-2008 12:02
it will split array into  2 halfs :
<?

function array_split($array)
    {
        $end=count($array);

        $half = ($end % 2 )?  ceil($end/2): $end/2;

        return array(array_slice($array,0,$half),array_slice($array,$half));
    }

//testing with odd count

$array=array('a','b','c','d');

echo "Odd: <br>";
var_dump(array_split($array));

//testing with even count

$array=array('a','b','c','d','f');

echo "Even: <br>";
var_dump(array_split($array));
?>

Output:
===========

Odd:
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "c"
    [1]=>
    string(1) "d"
  }
}

Even:
array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "d"
    [1]=>
    string(1) "f"
  }
}
ted.devito at 9gmail9 dot 99com 02-May-2008 09:21
based on worldclimb's arem(), here is a recursive array value removal tool that can work with multidimensional arrays.

function remove_from_array($array,$value){
    $clear = true;
    $holding=array();

    foreach($array as $k => $v){
        if (is_array($v)) {
            $holding [$k] = remove_from_array ($v, $value);
            }
        elseif ($value == $v) {
            $clear = false;
            }
        elseif($value != $v){
            $holding[$k]=$v; // removes an item by combing through the array in order and saving the good stuff
        }
    }
    if ($clear) return $holding; // only pass back the holding array if we didn't find the value
}
worldclimb at 99gmail99 dot com 21-Mar-2008 12:51
array_slice can be used to remove elements from an array but it's pretty simple to use a custom function.

One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function's names.

<?
function arem($array,$value){
    $holding=array();
    foreach($array as $k => $v){
        if($value!=$v){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

function akrem($array,$key){
    $holding=array();
    foreach($array as $k => $v){
        if($key!=$k){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

$lunch = array('sandwich' => 'cheese', 'cookie'=>'oatmeal','drink' => 'tea','fruit' => 'apple');
echo '<pre>';
print_r($lunch);
$lunch=arem($lunch,'apple');
print_r($lunch);
$lunch=akrem($lunch,'sandwich');
print_r($lunch);
echo '</pre>';
?>

(remove 9's in email)
slimjackson at gmail dot com 29-Oct-2007 10:06
Re: 'cpa at NOSPAM dot conceptivator dot com' and 'gportlock at gembiz dot co dot uk'

limitText can be further simplified by adding a limit parameter to the explode function - eliminating the need for the use of array_slice entirely. Note that this only works for extracting the first n words of the string, and not the last.

Also, you've mistakenly used array_splice instead of array_slice in your functions.

<?php
function limitText( $text, $wordCount )
{
    $wordArray = explode(" ", $text, $wordCount);
    return implode( " ", $wordArray );
}
?>
aexchecker at yahoo dot com 04-Oct-2007 08:39
<?php
/**
 * @desc
 * Combines two arrays by inserting one into the other at a given position then
 * returns the result.
 *
 * @since   2007/10/04
 * @version v0.7 2007/10/04 18:47:52
 * @author  AexChecker <AexChecker@yahoo.com>
 * @param   array $source
 * @param   array $destination
 * @param   int [optional] $offset
 * @param   int [optional] $length
 * @return  array
 */
function array_insert($source, $destination, $offset = NULL, $length = NULL) {
    if (!is_array($source) || empty($source)) {
        if (is_array($destination) && !empty($destination)) {
            return $destination;
        }
        return array();
    }
    if (is_null($offset)) {
        return array_merge($destination, $source);
    }
    $offset = var2int($offset);
    if (is_null($length)) {
        if ($offset === 0) {
            return array_merge($source, array_slice($destination, 1));
        }
        if ($offset === -1) {
            return array_merge(array_slice($destination, 0, -1), $source);
        }
        return array_merge(
            array_slice($destination, 0, $offset),
            $source,
            array_slice($destination, ++$offset)
        );
    }
    if ($offset === 0) {
        return array_merge($source, array_slice($destination, $length));
    }
    $destination_count = count($destination);
    $length = var2int($length);
    if ($offset > 0) {
        if ($destination_count - $offset < 1) {
            return array_merge($destination, $source);
        }
    } else{
        if (($t = $destination_count + $offset) < 1) {
            return array_merge($source, $destination);
        }
        $offset = $t;
    }
    if ($length > 0) {
        $length+= $offset;
    } elseif ($length < 0 && !($length * -1 < $destination_count)) {
        return $source;
    } else {
        $length = $offset;
    }
    return array_merge(
        array_slice($destination, 0, $offset),
        $source,
        array_slice($destination, $length)
    );
}
?>
phpnotasp at gmail dot com 16-Jul-2007 02:42
It should be noted that this function does NOT modify the original array. So if you need to array_pop() or array_shift() without modifying the original array, you can use array_slice().

<?php

$input = array('a', 'b', 'c');
$output = array_slice($input, 1);

print_r($output);
print_r($input);

/*
Array
(
    [0] => b
    [1] => c
)
Array
(
    [0] => a
    [1] => b
    [2] => c
)
*/
?>
sean at getclicky dot com 19-Jun-2007 12:54
People... let's keep things simple here. :) Some of the functions to mimic >5.0.2 behavior (preserving keys) are ridiculously complicated. Look how simple it can be:

<?php
function atrim( $a, $num ) {
  while( sizeof( $a ) > $num ) array_pop( $a );
  return $a;
}
?>
cpa at NOSPAM dot conceptivator dot com 07-Jun-2007 05:15
'gportlock at gembiz dot co dot uk' has an error in his limitText function. It simply takes a text string, then cuts off the first X words and returns the rest of the string. I believe the intended use is to return only the first X words and cut off the rest.

The correct version should be (notice the inserted 0 offset):
<?php
function limitText( $text, $wordCount )
{
    $wordArray = explode(" ", $text);
    array_splice($wordArray, 0, $wordCount);
    return implode( " ", $wordArray );
}
?>
gportlock at gembiz dot co dot uk 24-May-2007 07:29
This function returns a text string that is limited by the word count. This funtion is particularly useful for paid advertising where you pay by the word.

function limitText( $text, $wordCount ){

        $wordArray = explode(" ", $text);
        array_splice($wordArray, $wordCount);
        return implode( " ", $wordArray );
}
bc at bnc-automatisering dot nl 15-Mar-2007 03:41
first at all, ur php version check does not work correctly.
version 4.3.10 (4310 > 520)

Second, $a is not initialized.
Third, to let the function work the same as slice (offset) it should be:

function narray_slice($array, $offset, $length){
    $a = 0;
    foreach ($array as $key => $value) {
        if (($a >= $offset) && ($a - $offset < $length))
            $output_array[$key] = $value;
        $a++;
    }
    return $output_array;
}
14-Mar-2007 08:09
I noticed that some other people made supportive functions for maintaining numeric keys for PHP versions less than 5.0.2. So here is my version of it.

<?php

//Slice an array but keep numeric keys
function narray_slice($array, $offset, $length) {

    //Check if this version already supports it
    if (str_replace('.', '', PHP_VERSION) >= 502)
       return array_slice($array, $offset, $length, true);

    foreach ($array as $key => $value) {

        if ($a >= $offset && $a - $offset <= $length)
            $output_array[$key] = $value;
        $a++;

    }

    return $output_array;

}

?>
aflavio at gmail dot com 01-Mar-2007 01:43
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval);$x++)
          {
              $i=array_search($val,$array_remval);
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
              }
          }
          return $array_remval;
    }

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
Apware 15-Feb-2007 04:34
A simple test of this function:

<?php

print_r(array_slice(array('a','b','c','d'), 0, 3));        // normal behaviour

print_r(array_slice(array('a','b','c','d'), 0, 10));    // result: no error, returns as many as possible

print_r(array_slice(array(), 0, 10));                    // result: no error, returns empty array

?>
19-Dec-2006 09:10
The version check on "ps at b1g dot de" function fails on my copy of PHP.  My Version of PHP is "4.3.10-18", and it ends up checking 4310 <=> 502.
Since we are looking for a version over 4.1.0, we cas use version_compare.

<?php
    // PHP >= 5.0.2 is able to do this itself
    if(function_exists('version_compare') and version_compare(PHP_VERSION, '5.0.2') >= 0) {
      return array_slice($array, $offset, $length, true);
    }
?>
ludvig ericson at http://toxik.a12.se/ 05-Nov-2006 03:49
This function can also be used for pure laziness,
<?php
$myVar = end(array_slice(anotherFunction(), 0, 1));
?>
Imagine that anotherFunction() returns, say, three indexes, and you are sure you only want the Nth index, you could use this as a poor man's way of getting by the fact that PHP can't do this:
<?php
$myVar = (anotherFunction())[1];
?>
Which is sad.
ps at b1g dot de 03-Nov-2006 02:44
The following function is the same as array_slice with preserve_keys=true, but it works with PHP versions < 5.0.2.
When PHP >= 5.0.2 is available, the function uses the faster PHP-own array_slice-function with preserve_keys=true, otherwise it uses its own  implementation.

<?php
/**
 * array_slice with preserve_keys for every php version
 *
 * @param array $array Input array
 * @param int $offset Start offset
 * @param int $length Length
 * @return array
 */
function array_slice_preserve_keys($array, $offset, $length = null)
{
    // PHP >= 5.0.2 is able to do this itself
    if((int)str_replace('.', '', phpversion()) >= 502)
        return(array_slice($array, $offset, $length, true));

    // prepare input variables
    $result = array();
    $i = 0;
    if($offset < 0)
        $offset = count($array) + $offset;
    if($length > 0)
        $endOffset = $offset + $length;
    else if($length < 0)
        $endOffset = count($array) + $length;
    else
        $endOffset = count($array);

    // collect elements
    foreach($array as $key=>$value)
    {
        if($i >= $offset && $i < $endOffset)
            $result[$key] = $value;
        $i++;
    }

    // return
    return($result);
}
?>

Good for backwards compatibility I hope somebody might find this useful.
david at bagnara dot org 18-Oct-2006 08:42
I was trying to pass an argument list through the constructors. I tried various things such as func_get_args(). My conclusion is to pass the args to the constructor as an array. Each constructor can remove the fields it wants and pass the array on.

Using the following prototype, each child class can have any number of parameters added to the beginning of the class constructor and the rest passed onto the parent.

If the default value is desired for an argument, just pass NULL.

This could possibly be better done with array_shift or the like.

<?php

class aChild extends aParent
{
    // TODO customise this list for this class
    public
        $a, $b, $c;

    function __construct( $args = array() )
    {
        //set up default values for this class
        // TODO customise this list for this class
        $default = array( "a-def", "b-def", "c-def" ) ;
        // now overwrite the default with non NULL args
        foreach( $args as $key=>$val )
        {
            // more args than needed?
            if( !isset( $default[$key] ) )
            {
                break;
            }
            // this arg not null
            if( isset( $val ) )
            {
                $default[$key] = $val ;
            }
        }
        // set this to the new values
        // TODO customise this list for this class
        list( $this->a, $this->b, $this->c ) = $default ;
        // take off the ones we used
        $args = array_slice( $args, count( $default ) ) ;
        parent::__construct( $args ) ;
    }
}

$x = new aChild( array( "aChild a", NULL, "aChild c", NULL, "aParent second", "aParent third" ) ) ;
?>
DRB 24-Aug-2006 01:08
In response to the problem mentioned in the previous post (no name 06-May-2006 12:21) the following is a working solution:

$myarray = array_slice($myarray, 1, count($myarray), true);

It is too bad that the "preserve_keys" option is not available for the array_shift and array_pop functions as this would be somewhat simpler.
06-May-2006 12:21
If you specify the fourth argument (to not reassign the keys), then there appears to be no way to get the function to return all values to the end of the array. Assigning -0 or NULL or just putting two commas in a row won't return any results.
taylorbarstow at the google mail service 07-Apr-2006 02:01
Array slice function that works with associative arrays (keys):

function array_slice_assoc($array,$keys) {
    return array_intersect_key($array,array_flip($keys));
}
andreasblixt (at) msn (dot) com 06-Sep-2005 09:53
<?php
    // Combines two arrays by inserting one into the other at a given position then returns the result
    function array_insert($src, $dest, $pos) {
        if (!is_array($src) || !is_array($dest) || $pos <= 0) return FALSE;
        return array_merge(array_slice($dest, 0, $pos), $src, array_slice($dest, $pos));
    }
?>
ssb45 at cornell dot edu 28-Jul-2005 07:20
In reply to jenny at jennys dot info:

Here is a much easier way to find the $offset of a $key in an $array:

$offset = array_search($key, array_keys($array));
fanfatal at fanfatal dot pl 08-Jul-2005 03:09
Hmm ... i wrote an usefull function whitch is such like strpos but it works on arrays ;]

<?php
/*
 *    Find position of first occurrence of a array
 *
 *    @param array $haystack
 *    @param array $needle
 *    @return int
 *    @author FanFataL
 */
function array_pos($haystack, $needle) {
    $size = count($needle);
    $sizeh = count($haystack);
    if($size > $sizeh) return false;

    $scale = $sizeh - $size + 1;

    for($i = 0; $i < $scale; $i++)
        if($needle === array_slice($haystack, $i, $size))
            return $i;

    return false;
}

// Sample:
$a = array('aa','bb','cc','dd','ee');
$b = array('cc','dd');
$pos = array_pos($a, $b);
?>

Greatings ;-)
...
david dot tulloh at infaze dot com dot au 23-Jun-2005 06:26
Nice one liner to extract a column from a 2D array.
It works by using array_slice on every row, through array_map.

<?php
// set up a small test environment
$test_subject[] = array("a", "b", "c");
$test_subject[] = array("d", "e", "f");

$column=1;

// do the actual work
$result = array_map('array_slice', $test_subject,
    array_fill(0, count($test_subject), $column),
    array_fill(0, count($test_subject), 1)
);

// and the end result
result == array ( array("b"), array("e") );
?>
liz at matrixmailing dot com 06-Jun-2005 02:16
For those with PHP < 5.0.2, and have a number as your array key, to avoid having the key reset with array_slice, add a blank character to the beginning or end of the key.
<?

$array[" ".$key] = $value;

?>
bishop 08-Dec-2004 01:58
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:

<?php

$a = array ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$b = array_pick($a, array ('d', 'b'));

// now:
// $a = array ('a' => 1, 'c' => '3');
// $b = array ('d' => 4, 'b' => '2');

function &array_pick(&$array, $keys)
{
    if (! is_array($array)) {
        trigger_error('First parameter must be an array', E_USER_ERROR);
        return false;
    }

    if (! (is_array($keys) || is_scalar($keys))) {
        trigger_error('Second parameter must be an array of keys or a scalar key', E_USER_ERROR);
        return false;
    }

    if (is_array($keys)) {
        // nothing to do
    } else if (is_scalar($keys)) {
        $keys = array ($keys);
    }

    $resultArray = array ();
    foreach ($keys as $key) {
        if (is_scalar($key)) {
            if (array_key_exists($key, $array)) {
                $resultArray[$key] = $array[$key];
                unset($array[$key]);
            }
        } else {
            trigger_error('Supplied key is not scalar', E_USER_ERROR);
            return false;
        }
    }

    return $resultArray;
}

?>
pies at sputnik dot pl 17-Sep-2004 09:29
My shot at Dams's array_slice_key() implementation:

function array_slice_key($array, $offset, $len=-1){

    if (!is_array($array))
        return FALSE;

    $length = $len >= 0? $len: count($array);
    $keys = array_slice(array_keys($array), $offset, $length);
    foreach($keys as $key) {
        $return[$key] = $array[$key];
    }

    return $return;
}
Samuele at norsam dot org 05-Apr-2004 09:44
Note that if $offset+$length>count($array) then resulting array will NOT be filled with empty elements at his end, so it is not sure that it will have exactly $length elements. Example:
<?php
$a=Array(7,32,11,24,65); // count($a) is 5
$b=array_slice($a,2,4);  // 2+4=6, and 6>count($a)
print_r($b);
?>
will return a 3-elements array:
  Array
  (
      [0] => 11
      [1] => 24
      [2] => 65
  )
23-Feb-2004 02:47
Use unset() to delete a associative array.

Ex:
<?php

$item['chaise'] = array ('qty' => 1,
                        'desc' => 'Chaise bercante 10"',
                        'avail' => 10);

$item['divan'] = array ('qty' => 1,
                        'desc' => 'Divan brun laitte"',
                        'avail' => 10);

if (isset($item['chaise'])) {
        ++$item['chaise']['qty'];
        }

unset($item['divan']);

foreach ($item as $s) {
        echo "<br />Commande " . $s['qty'] . " " . $s['desc'];
}

?>
jenny at jennys dot info 21-Feb-2004 10:12
Here's a function which returns the array offset based on the array key.  This is useful if you'd like to use array_slice to get all keys/values after key "foo".

<?
function array_offset($array, $offset_key) {
  $offset = 0;
  foreach($array as $key=>$val) {
    if($key == $offset_key)
      return $offset;
    $offset++;
  }
  return -1;
}

$array = array('foo'=>'foo', 'bar'=>'bar', 'bash'=>'bash', 'quux'=>'quux');
print_r($array);
// Prints the following:
// Array
// (
//     [foo] => foo
//     [bar] => bar
//     [bash] => bash
//     [quux] => quux
// )

$offset = array_offset($array,'bar');
// $offset now contains '1'
$new = array_slice($array,$offset+1);
print_r($new);
// Prints the following:
// Array
// (
//     [bash] => bash
//     [quux] => quux
// )
?>
webmaster_nospam at wavesport dot com 12-Nov-2002 04:48
This function may surprise you if you use arbitrary numeric values for keys, i.e.

<?php
//create an array
$ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');

print_r($ar);
// print_r describes the array as:
// Array
// (
//    [a] => apple
//    [b] => banana
//    [42] => pear
//    [d] => orange
// )

//use array_slice() to extract the first three elements
$new_ar = array_slice($ar, 0, 3);

print_r($new_ar);
// print_r describes the new array as:
// Array
// (
//    [a] => apple
//    [b] => banana
//    [0] => pear
// )
?>

The value 'pear' has had its key reassigned from '42' to '0'.

When $ar is initially created the string '42' is automatically type-converted by array() into an integer.  array_slice() and array_splice() reassociate string keys from the passed array to their values in the returned array but numeric keys are reindexed starting with 0.
t dot oddy at ic dot ac dot uk 25-Apr-2002 06:47
[Editor's Note:
It is easier to do the same thing using array_values()
]
array_slice() can be used to "re-index" an array to start from key 0.  For example, unpack creates an array with keys starting from 1;

<?php
var_dump(unpack("C*","AB"));
?>

produces

<?php
array(2) {
  [1]=>
  int(65)
  [2]=>
  int(66)
}
?>

and

<?php
var_dump(array_slice(unpack("C*","AB"),0));
?>

give you

<?php
array(2) {
  [0]=>
  int(65)
  [1]=>
  int(66)
}
?>
developer at i-space dot org 03-Feb-2002 08:22
remember that array_slice returns an array with the current element. you must use array_slice($array, $index+1) if you want to get the next elements.
richardgere at jippii dot fi 27-Jan-2002 09:14
The same thing, written by a maladroit :)

<?php
function array_slice2( $array, $offset, $length = 0 )
{
  if( $offset < 0 )
    $offset = sizeof( $array ) + $offset;

  $length = ( !$length ? sizeof( $array ) : ( $length < 0 ? sizeof( $array ) - $length : $length + $offset ) );

  for( $i = $offset; $i < $length; $i++ )
    $tmp[] = $array[$i];

  return $tmp;
}
?>
dams at php dot net 15-Dec-2001 07:09
Here is a version of Array_slice which takes into account keys.

That may be a suggestion for future developpement.

<?php
function array_slice_key($array, $offset){
  if (!is_array($array))
      return FALSE;

  if (func_num_args() == 3){
    $length = func_get_arg(2);
    $length = max(0,intval($length));
  } else {
    $length = count($array);
  }

  $i = 0;
  $return = array();
  $keys = array_slice(array_keys($array), $offset, $length);
  foreach( $keys as $key){
    $return[$key] = $array[$key];
  }
  return $return;
}
?>
array_shift
array_splice
Функции для работы с массивами


Удаляет часть массива и заменяет её чем-нибудь ещё

array_slice
array_sum
Функции для работы с массивами
PHP Manual

array_splice

(PHP 4, PHP 5)

array_splice — Удаляет часть массива и заменяет её чем-нибудь ещё

Описание

array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] )

Удаляет length элементов, расположенных на расстоянии offset из массива input, и заменяет их элементами массива replacement, если он передан в качестве параметра.

Обратите внимание, что числовые ключи в массиве input не сохраняются.

Замечание: Если параметр replacement не является массивом, он будет преобразован к нему (т.е. (array) $parameter). Это может привести к не ожиданным результатам при использовании объекта или NULL в качестве replacement.

Список параметров

input

Входной массив.

offset

Если параметр offset положителен, будут удалены элементы, находящиеся на расстоянии offset от начала input. Если offset отрицателен, будут удалены элементы, находящиеся на расстоянии offset от конца input.

length

Если параметр length опущен, будут удалены все элементы начиная с позиции offset и до конца массива. Если length указан и он положителен, то будет удалено именно столько элементов. Если же параметр length отрицателен, то конец удаляемой части элементов будет отстоять на это количество от конца массива. Совет: для того, чтобы удалить все элементы массива, начиная с позиции offset до конца массива, в то время как указан параметр replacement, используйте count($input) в качестве параметра length.

replacement

Если передан массив replacement в качестве аргумента, тогда удалённые элементы будут заменены элементами этого массива.

Если параметры offset и length таковы, что из исходного массива не будет ничего удалено, тогда элементы массива replacement будут вставлены на позицию offset. Обратите внимание, что ключи массива replacement не сохраняются.

Совет: если replacement является просто одним элементом, нет необходимости заключать его в array(), если только этот элемент сам не является массивом, объектом или NULL.

Возвращаемые значения

Возвращает массив, содержащий удалённые элементы.

Примеры

Пример #1 Примеры использования array_splice()

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input теперь array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input теперь array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input теперь array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input теперь array("red", "green", "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input теперь array("red", "green", "blue", "purple", "yellow");
?>

Пример #2 array_splice() examples

Следующие выражения одинаково меняют значения массива $input:

<?php
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
array_pop($input);
array_splice($input, -1);
array_shift($input);
array_splice($input, 0, 1);
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
$input[$x] = $y; // для массивов, где ключ равен смещению
array_splice($input, $x, 1, $y);
?>

Смотрите также

  • array_slice() - Выбирает срез массива
  • unset() - Удаляет переменную
  • array_merge() - Сливает один или большее количество массивов

User Contributed Notes

mrsohailkhan at gmail dot com 21-Oct-2011 12:34
array_splice, split an array into 2 arrays. The returned arrays is the 2nd argument actually and the used array e.g $input here contains the 1st argument of array, e.g

<?php
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 3)); // Array ( [0] => yellow )
print_r($input); //Array ( [0] => red [1] => green [2] => blue )
?>

if you want to replace any array value do simple like that,

first search the array index you want to replace

<?php $index = array_search('green', $input);// index = 1 ?>

and then use it as according to the definition

<?php
array_splice($input, $index, 1, array('mygreeen')); //Array ( [0] => red [1] => mygreeen [2] => blue [3] => yellow )
?>

so here green is replaced by mygreen.

here 1 in array_splice above represent the number of items to be replaced. so here start at index '1' and replaced only one item which is 'green'
news_yodpeirs at thoftware dot de 20-Jul-2011 08:20
Sometimes you may want to insert one array into another and just work on with the resulting array. array_splice() doesn't support this, as the resulting array isn't the returned value but the first argument, which is changed by reference.

Therefore you may use the following function, which inserts array $ins in array $src at position $pos. $rep can be used if $ins shouldn't be just inserted, but should replace some existing elements (the number of elements to be replaced is given in $rep).

<?php
function array_insert($src,$ins,$pos,$rep=0) {
  array_splice($src,$pos,$rep,$ins);
  return($src);
}
?>
doug at badblue dot com 13-Apr-2011 08:10
Unexpected behavior if you're trying to use array_splice to truncate an array.  For example:

 <?php $aOut = array_splice($aIn, 300); ?>

If sizeof($aIn) < 300, the entire $aOut array gets wiped out!  The extra conditional is needed to ensure this doesn't happen:

<?php
 if (sizeof($aIn) > MAX_WINDOW_COUNT) {
   $aOut = array_splice($aIn, MAX_WINDOW_COUNT);
 }
?>

[PHP 5.3.6]
charette dot s at gmail 21-Jul-2010 08:26
If you want to append null values wrap them in an array:

<?php

    $a = array('Hey', 'hey', 'my', 'my');
    array_splice($a, 1, 0, null);
    print_r($a);

?>
Array
(
    [0] => Hey
    [1] => hey
    [2] => my
    [3] => my
)

<?php

    $b = array('Hey', 'hey', 'my', 'my');
    array_splice($b, 1, 0, array(null));
    print_r($b);

?>
Array
(
    [0] => Hey
    [1] =>
    [2] => hey
    [3] => my
    [4] => my
)
news_yodpeirs at thoftware dot de 01-Apr-2010 01:32
Splicing with NULL as replacement may result in unexpected behavior too. Typecasting NULL into an array results in an empty array (as "(array)NULL" equals "array()"). That means, instead of creating an element with value NULL just no new element ist created (just as if there was no replacement specified).

If you want the splicing to create a new element with value NULL you have to use "array(NULL)" instead of NULL.

You should expect this if you read the explanation carefully, but just as objects are considered as a special case for replacement, NULL should be too.

The explanation of replacement better should read: "If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL."

And the note better should be: "If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement."

jmtc
daniele centamore 02-Aug-2009 07:48
just useful functions to move an element using array_splice.

<?php

// info at danielecentamore dot com

// $input  (Array) - the array containing the element
// $index (int) - the index of the element you need to move

function moveUp($input,$index) {
      $new_array = $input;

       if((count($new_array)>$index) && ($index>0)){
                 array_splice($new_array, $index-1, 0, $input[$index]);
                 array_splice($new_array, $index+1, 1);
             }

       return $new_array;
}

function moveDown($input,$index) {
       $new_array = $input;

       if(count($new_array)>$index) {
                 array_splice($new_array, $index+2, 0, $input[$index]);
                 array_splice($new_array, $index, 1);
             }

       return $new_array;
 }

$input = array("red", "green", "blue", "yellow");

$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")

$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")

?>
strata_ranger at hotmail dot com 01-Jul-2009 11:53
Should you want a similar function for splicing strings together, here is a rough equivalent:

<?php
function str_splice($input, $offset, $length=null, $splice='')
{
  $input = (string)$input;
  $splice = (string)$splice;
  $count = strlen($input);

  // Offset handling (negative values measure from end of string)
  if ($offset<0) $offset = $count + $offset;

  // Length handling (positive values measure from $offset; negative, from end of string; omitted = end of string)
  if (is_null($length)) $length = $count;
  elseif ($length < 0)  $length = $count-$offset+$length;

  // Do the splice
  return substr($input, 0, $offset) . $splice . substr($input, $offset+$length);
}

$string = "The fox jumped over the lazy dog.";

// Outputs "The quick brown fox jumped over the lazy dog."
echo str_splice($string, 4, 0, "quick brown ");

?>

Obviously this is not for cases where all you need to do is a simple search-and-replace.
dead dot screamer at seznam dot cz 12-Feb-2009 05:28
I need <?php array_Splice()?> function, that use array keys instead of order (offset and length) because of associated arrays, and this is result:

<?php
/**
 *    first variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $end is index of slice end, if this is null, $replacement will be inserted (in the same way as original array_Slice())
 *indexes of $replacement are preserved in both examples
 */
function array_KSplice1(&$input, $start, $end=null, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;
    if($end!==null)
    {
        $end=array_Search($end,$keys,true);
        // if $end not found, exit
        if($end===false)
            return false;
        // if $end is before $start, exit
        if($end<$start)
            return false;
        // index to length
        $end-=$start-1;
    }

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$end,$rKeys);
        array_Splice($values,$start,$end,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$end);
        array_Splice($values,$start,$end);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

/**
 *    second variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $length is length of slice, what will be replaced, if is zero, $replacement will be inserted (in the same way as original array_Slice())
 */
function array_KSplice2(&$input, $start, $length=0, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$length,$rKeys);
        array_Splice($values,$start,$length,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$length);
        array_Splice($values,$start,$length);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

$array=range(1,10);
var_Dump(array_KSplice1($array,3,3,array(100=>101,102,103,104)));

$array=range(1,10);
var_Dump(array_KSplice2($array,3,3,array(100=>101,102,103,104)));

?>

Both examples output:
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [100]=>
  int(101)
  [101]=>
  int(102)
  [102]=>
  int(103)
  [103]=>
  int(104)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
}
Ulrich 01-Nov-2008 05:34
If you have multidimensional array like
<?php
$arr = array(array("a"=>1,"b"=>2),array("a"=>7,"b"=>-34));
?>
you can insert elements using array(array(...)). For example:
<?php
array_splice($arr, 1, 0, array(array("a"=>100, "b"=>77)))
?>
madmax at max-worlds dot net 23-Sep-2008 06:23
Note:  If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object replacement .

Example :

<?php
class A()
{
    private $a;
    private $b;
    public function __construct()
    {
        $this->a = "foo";
        $this->b = "bar";
    }
}

$array = array();
array_splice($array, 0, 0, new A());
print_r($array);
?>

Outputs :

Array : Array
{
    [0] => foo
    [1] => bar
}

Solution : Enforce the array() on the object.

<?php
array_splice($array, 0, 0, array(new Object());
?>

Source : http://bugs.php.net/bug.php?id=44485
loushou - life dot 42 at gmail dot com 27-Jul-2008 04:39
i miss posted the actual function...
here is the real one lol

<?php

function q_sort(&$Info, $Index, $Left, $Right)
{
  echo "memory usage <b>".memory_get_usage()."</b><br/>\n";
  $L_hold = $Left;
  $R_hold = $Right;
  $Pivot = $Left;
  $PivotValue = $Info[$Left];
  while ($Left < $Right)
  {
    while (($Info[$Right][$Index] >= $PivotValue[$Index]) && ($Left < $Right))
      $Right--;
    if ($Left != $Right)
    {
      $Info[$Left] = $Info[$Right];
      $Left++;
    }
    while (($Info[$Left][$Index] <= $PivotValue[$Index]) && ($Left < $Right))
      $Left++;
    if ($Left != $Right)
    {
      $Info[$Right] = $Info[$Left];
      $Right--;
    }
  }
  $Info[$Left] = $PivotValue;
  $Pivot = $Left;
  $Left = $L_hold;
  $Right = $R_hold;
  if ($Left < $Pivot)
    q_sort($Info, $Index, $Left, $Pivot-1);
  if ($Right > $Pivot)
    q_sort($Info, $Index, $Pivot+1, $Right);
}

?>
Francis 27-Apr-2008 12:27
Do you need to sort a 2D array on just one of its variables while trying to preserve somewhat the original order?

<?php

function sort_2d_array($array, $position, $order = "ASC"){
  if (!is_array($array)) return $array;
  if (count($array) < 2) return $array;
  $new = array($array[0]);
  for ($cnt = 1; $cnt <= count($array) - 1; $cnt++){
    $stop = 0;
    $splice = 0;
    for ($newcnt = 0; $newcnt <= count($new) - 1; $newcnt++){
      if ($stop == 0){
        if ($order == "ASC")
        if ($array[$cnt][$position] < $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for ASC
        if ($order == "DESC")
        if ($array[$cnt][$position] > $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for DESC
      } // stop vying for position
    } // cycle through new array to find position
    if ($stop == 0){
      $new[] = $array[$cnt];
    } else {
      array_splice($new, $splice, 0, array($array[$cnt]));
    } // splice into new array while keeping somewhat the original order
  } // cycle through original array
  return $new;
} // sort_2d_array

?>

Application Example: In-House Search Engine
Here we are trying to find the word apple in the website by sort of the most recent occurances first, but the number of occurances first.

We've already sorted the mysql output by the date desc and have counted the no of occurances and have placed those in an array for the final query.

I've used this function to further sort the occurances but somewhat keep the original mysql sort order.

Key
[0] Record number
     [0] Record ID
     [1] Source Table
     [2] No of Occurances Pinged

  ---------------------------

[0]
     [0] 24530
     [1] Blogs
     [2] 1

[1]
     [0] 24400
     [1] Blogs
     [2] 1

[2]
     [0] 24240
     [1] Blogs
     [2] 4

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

After running...

<?php
sort_2d_array($array, 2, "DESC");
?>

We have...

[0]
     [0] 24240
     [1] Blogs
     [2] 4

[1]
     [0] 24530
     [1] Blogs
     [2] 1

[2]
     [0] 24400
     [1] Blogs
     [2] 1

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

Might be useful to someone...
nash0r 29-Feb-2008 01:04
array_splice($input, -1) / array_slice($input, 1) equivalent to array_shift($input) ?????

Try this:

<?php
$input = array('key1' => array('deep1' => 'Value'), 'key2' => array('deep2' => 'Value'), 'key3' => array('deep3' => 'Value'));

$foo_splice = array_splice($input, -1);
$foo_shift = array_shift($input);

echo "<pre>".print_r($foo_splice, true)."</pre>";
echo "<pre>".print_r($foo_shift, true)."</pre>";
?>

Output:

Array
(
    [key3] => Array
        (
            [deep3] => Value
        )

)

Array
(
    [deep1] => Value
)
pauljamescampbell at gmail dot com 06-Feb-2008 06:46
Here's my own take on an array slice method that preserves keys from an associative array.

<?php
/**
 * Array slice function that preserves associative keys
 *
 * @function associativeArraySlice
 *
 * @param  Array  $array  Array to slice
 * @param  Integer  $start
 * @param  Integer  $end
 *
 * @return  Array
 */
function associativeArraySlice($array, $start, $end) {
    // Method param restrictions
    if($start < 0) $start = 0;
    if($end > count($array)) $end = count($array);

    // Process vars
    $new = Array();
    $i = 0;

    // Loop
    foreach($array as $key => $value) {
        if($i >= $start && $i < $end) {
            $new[$key] = $value;
        }
        $i++;
    }
    return($new);
}
?>
saurabhmdh at yahoo dot co dot on 15-Sep-2007 12:29
for inserting array in 2-d array, according x position, y position

<?php
function add_module_xy($x_loc, $y_loc, $module) {
    //identify the column of the modules
    switch ($x_loc) {
      case 1:
        $x = 'left';
        break;
      case 2:
        $x = 'middle';
        break;
      case 3:
        $x = 'right';
        break;
      default:
        throw new Exception("", "Invalid horizontal position $x_loc");
    }

    $max_y_loc = count($this->module_arrays[$x]) + 1;
    if ($y_loc > $max_y_loc) {
      //if y location is greater then max array index then add module to last
      $y_loc = $max_y_loc;
    }
    $left = array_slice ($this->module_arrays[$x], 0, $y_loc-1);
    $right = array_slice ($this->module_arrays[$x], $y_loc-1);
    $insert[0] = $module;
    $array = array_merge ($left, $insert, $right);
    $this->module_arrays[$x] = $array;

  }
?>
mip at ycn dot com 08-Mar-2007 05:37
Ever wounder what array_splice is doing to your references, then try this little script and see the output.

<?php

$a = "a";
$b = "b";
$c = "c";
$d = "d";
$arr = array();
$arr[] =& $a;
$arr[] =& $b;
$arr[] =& $c;
array_splice($arr,1,0,array($d));
$sec_arr = array();
$sec_arr[] =& $d;
array_splice($arr,1,0,$sec_arr);

$arr[0] = "test"; // should be $a
$arr[3] = "test2"; // should be $b
$arr[1] = "this be d?"; // should be $d
$arr[2] = "or this be d?"; // should be $d
var_dump($arr);
var_dump($a);
var_dump($b);
var_dump($d);
?>

The output will be (PHP 4.3.3):

array(5) {
  [0]=>
  &string(4) "test"
  [1]=>
  &string(10) "this be d?"
  [2]=>
  string(13) "or this be d?"
  [3]=>
  &string(5) "test2"
  [4]=>
  &string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"

So array_splice is reference safe, but you have to be careful about the generation of the replacement array.

have fun, cheers!
ahigerd at stratitec dot com 24-Jan-2007 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
bdjumakov at gmail dot com 31-Aug-2006 12:11
Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array.

<?php
function array_move($which, $where, $array)
{
    $tmp  = array_splice($array, $which, 1);
    array_splice($array, $where, 0, $tmp);
    return $array;
}
?>
Paul 11-Feb-2006 10:06
In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.

In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).
gerry-03 at 4warding dot com 09-Feb-2006 07:35
For anybody who is wondering... jrhardytwothousandtwo's trick for inserting an element using array_splice, will also work with multi-dimensional arrays if you do the following:

<?php
  function array_insert(&$input, $offset, $replacement){
    array_splice($input, $offset, 0, 0);
    $input[$offset] = $replacement;
  }
?>

I'm not sure if this (or a derivative of it) will solve other problems that I have seen just about everybody on here trying to solve. But apart from it's hackish nature, it works well for me.
ajd at cloudiness dot com 06-Dec-2005 06:35
weikard's function below is useful but it will still strip keys from array elements where the key is an integer, whether or not it is in a string:

<?php
function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}
$f = array("three" => "zzz", "3" => "yyy");
$a = array("4.0" => "zzzz", "four" => "yyyy");
array_insert($a,0,$f);
var_dump($a);
// array(4) { ["three"]=> string(3) "zzz" [0]=> string(3) "yyy"  ["4.0"]=> string(4) "zzzz" ["four"]=> string(4) "yyyy" }
?>
weikard at gmx dot de 15-Sep-2005 05:53
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".

<?php
// [DATA]
$test_array = array (
  row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);

// [ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [0] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

But you can use the following function:

function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}

<?php
// [ACTION]

array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [rowX] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

[NOTE]

The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.
csaba at alum dot mit dot edu 13-Aug-2005 02:31
Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time.  The last two methods took significantly more time than the first two.  The most surprising lesson is that using the & incurs a time hit.

<?php
foreach ($a2 as $elem) $a1[]=$elem;
foreach ($a2 as &$elem) $a1[]=$elem;
array_splice ($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2);
?>

Csaba Gabor from Vienna
randomdestination at gmail dot com 22-Jul-2005 01:52
To split an associative array based on it's keys, use this function:

<?php
function &array_split(&$in) {
    $keys = func_get_args();
    array_shift($keys);

    $out = array();
    foreach($keys as $key) {
        if(isset($in[$key]))
            $out[$key] = $in[$key];
        else
            $out[$key] = null;
        unset($in[$key]);
    }

    return $out;
}
?>

Example:
<?php
$testin = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$testout =& array_split($testin, 'a', 'b', 'c');

print_r($testin);
print_r($testout);
?>

Will print:

Array
(
    [d] => 4
)
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Hope this helps anyone!
gideon at i6developments dot com 17-Jul-2004 09:45
array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically.

Code:
<?php
    $modarray = array_reverse($mili);
    $trig=1;
        foreach($modarray as $rubber => $glue) {
            if($rubber!="<BR>") {
            $i++;
            $b++;
            if ($i==4) {
                $trig++;
                if($trig<=2) {
                array_splice($modarray,$b,0,"<BR>");
                }elseif($trig>=3){
                array_splice($modarray,$b+($trig-2),0,"<BR>");
                }
                $i=0;
                };
                };
        };
    $fixarray = array_reverse($modarray);

?>
jtgt at gmx dot de (Richard Lachmann) 16-Jul-2004 09:18
This function will preserve keys:

<?php
function my_array_splice(&$_arr, $_index, $_long){
           $_keys=array_keys($_arr);
           $_key=array_search($_index, $_keys);
           if ( $_key !== FALSE ){
               $_keys=array_splice($_keys, $_key, $_long);
              foreach ($_keys as $_key) unset($_arr[$_key]);
          }
}
?>
rolandfoxx at yahoo dot com 30-Mar-2004 12:16
Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument.  Consider the following:

<?php
//Very truncated
class Tree {
  var $childNodes

  function addChild($offset, $node) {
    array_splice($this->childNodes, $offset, 0, $node);
    //...rest of function
  }

}

class Node {
  var $stuff
  ...
}

$tree = new Tree();
// ...set 2 nodes using other functions...
echo (count($tree->childNodes)); //Gives 2
$newNode = new Node();
// ...set node attributes here...
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); //Expect 3?  wrong!
?>

In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof  I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it.  I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.

Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
  $firstPart = array_slice($array, 0, $offset);
  $secondPart = array_slice($array, $offset);
  $insertPart = array($insert);
  $array = array_merge($firstPart, $insertPart, $secondPart);
}

Note that this function makes no allowances for when $offset equals the first or last index in the array.  That's because array_unshift and array_push work just fine in those cases.  It's only array_splice that can trip you up.  Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.
18-Aug-2003 03:57
Want to insert a new value in the middle of the array, without overwriting other elements? Try this.

<?php
$array = array(
    0 => 0,
    1 => 1,
    2 => 2,
    3 => 3,
    4 => 4,
    5 => 5
);
array_splice($array, 3, count($array), array_merge(array('x'), array_slice($array, 3)));
echo '<pre>';
print_r($array);
?>

Output:
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => x
    [4] => 3
    [5] => 4
    [6] => 5
)

As you can see, the operation add 'X' in the 4th place, pushing everything else to the next key.
kbrown at horizon dot sk dot ca 11-Aug-2003 12:40
[ Editor's Note: If you're not concerned with the indexes being contiguously numbered (such as for an associative array) then unset($ar[$ind]); will accomplish the same as the code below without requiring splice/splice/merge.  If contiguous numbering IS a concern (such as for indexed arrays), you can still save time by using: unset($ar[$ind]); $ar = array_values($ar); ]

Removing elements from arrays

This works better - much quicker

<?php
$ar = array("einstein", "bert", "colin", "descartes", "renoir");
$a = array_slice($ar, 0, $ind);
$b = array_slice($ar, $ind + 1);
$ar = array_merge($a, $b);
?>
plintus at smtp dot ru 14-Apr-2003 01:59
key-safe:

<?php
function array_kslice ($array, $offset, $length = 0) {
$k = array_slice (array_keys ($array), $offset, $length);
$v = array_slice (array_values ($array), $offset, $length);
for ($i = 0; $i < count ($k); $i ++) $r[$k[$i]] = $v[$i];
return $r;
}
?>

smth like this. hope you like it more than versions above :)
tsunaquake DOESNTLIKESPAM @ wp DOT pl 11-Nov-2002 10:56
It is possible to use a string instead of offset, eg if you want to deletre the entry $myArray['entry'] then you can simply do it like this:

<?php
array_splice($myArray, 'entry', 1);
?>

Note that you can use unset($myArray['entry']) as well but then, it doesn't enable you to remove more than one entry and it doesn't replace anything in the array, if that's what you intend to do.
18-Jun-2002 07:14
Please note that array_splice() 's second argument is an OFFSET and not an INDEX.

Lets say you want to
$array_of_items = array ('nothing','myitem','hisitem','heritem');
$sid = array_search('myitem',$array_of_items);
echo $sid; /* prints out 1, since index element 1 is "myitem" */

Now, lets say we want to remove that "myitem" from the array:

<?php
$array_of_items = array_splice($array_of_items,(1+$sid),1);
?>

Notice how you have to add a one to the $sid variable?  That is because offset item 1 is "nothing" and since $sid is currently 1 (the index of "myitem"), we add 1 more to it to find out
 its OFFSET.

DO NOT DO THIS:
 $array_of_items = array_splice($array_of_items,$sid,1);
paule at cs dot tamu dot edu 12-Jun-2002 09:59
to kokos@lac.lviv.ua:

Good point about the code not doing what you expected.

The failure to check for the insert case like you pointed out is not a bug, however. I didn't add code to handle that because the key of such an added index is more or less undefined in an unordered associative array. Put another way, if your array is associative and not auto-indexed, you most likely care enough about your keys to want to set them explicitly.
kokos at lac dot lviv dot ua 08-Jun-2002 02:55
To paule@cs.tamu.edu :
Sorry, but the fix will still not work properly - when $length=0 (e.g. trying to insert one value) the
   $new_array[$key]=$replacement;
would be immediately followed by
   $new_array[$key]=$value;
and the $replacement will be lost.

What i was trying to point out in my original post is that $input[$x]=$y is NOT equivalent to array_splice($input, $x, 1, $y) . The equivalence mentioned would be true ONLY when $input is <... ghmm... > "automatically enumerated", having its' keys exactly matching offsets of corresponding elements in the array. But, in general case, keys do not match offsets - perhaps this should be explicitly stated in the Description above.
paule at cs dot tamu dot edu 06-Jun-2002 11:21
Aiya, I feel silly. The fix for my code above assumes that your values in the associative array are strings. Ignore the fix code in my last post and use this instead:

<?php
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
                elseif($replacement!==NULL)
                    $new_array[$key]=$replacement;
?>

Sorry again. I feel sheepish.  n.n
paule at cs dot tamu dot edu 06-Jun-2002 11:09
After reading KoKos' post above, I thought that the code I posted right before his should do what he wanted. However, my original post neglected to note the little "Tip" in the documentation above, about a single element replacement.

If one changes the lines in my code above that says:

<?php
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

to instead say:

<?php
                if(is_string($replacement))
                    $new_array[$key]=$replacement;
                elseif(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

that will solve the problem.

Sorry for the omission.
kokos at lac dot lviv dot ua 06-Jun-2002 08:26
It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...

Contrary to the equivalence noted on this page
$input[$x] = $y   <==>   array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected,
even provided that you have only INTEGER keys!

The following code:
   $t=array('a','b','c','d','e');
   var_dump($t);

<?php
   unset($t[0],$t[1],$t[3]);
   $t[0]='f';
   var_dump($t);

   array_splice($t,0,1,'g');
   var_dump($t);
?>

Will produce:
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}
array(3) {
  [2]=>
  string(1) "c"
  [4]=>
  string(1) "e"
  [0]=>
  string(1) "f"
}
array(3) {
  [0]=>
  string(1) "g"
  [1]=>
  string(1) "e"
  [2]=>
  string(1) "f"
}

Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_.  :)
I think that "equivalence note" should be considered buggy.  ;)))

Best wishes.
KoKos.
paule at cs dot tamu dot edu 26-May-2002 07:02
I believe the following is a version of array_slice that solves most of the issues for people that want an associative key offset, rather than an integer.

<?php
function key_array_splice(&$input, $key_ofs, $length=NULL, $replacement=NULL)
{
    // Adjust the length if it was negative or not passed
    if($length===NULL || $length<0)
        $count = $length+count($input);

    // Cycle through the array
    foreach($input as $key=>$value){
        if(!$key_found){
            if($key===$key_ofs){
                $key_found=true;
                if($length!==NULL && $length>=0)
                    $count=$length;
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
            }else
                $new_array[$key]=$value;
        }
        if($key_found){
            if($count>0)
                $ret_array[$key]=$value;
            else
                $new_array[$key]=$value;
        }
        $count--;
    }

    // Finish up
    $input=$new_array;
    return $ret_array;
}
?>

Note that this code needs PHP 4 for the use of the "===" and "!==" operators.
jrhardytwothousandtwo at yahoo dot com 14-Feb-2002 11:54
A reference is made to INSERT'ing into an array here with array_splice, however its not explained very well.  I hope this example will help others find what took me days to research.

<?php
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";

$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);

// $original_array will now show:

// 1,2,3,blue,4,5
?>

Remember that you are telling the array to insert the element into the KEY position.  Thus the elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5.  And walla, you've inserted.  I can't say if this is of any value for named keys, or multidimensional arrays.  However it does work for single dimensional arrays.

$returned should be an empty array as nothing was returned.  This would have substance if you were doing a replace instead.
leingang AT math DOT rutgers DOT edu 15-Jan-2002 07:32
array_splice resets the internal pointer of $input.  In fact, many array functions do this.  Caveat programmor!
array_slice
array_sum
Функции для работы с массивами


Вычисляет сумму значений массива

array_splice
array_udiff_assoc
Функции для работы с массивами
PHP Manual

array_sum

(PHP 4 >= 4.0.4, PHP 5)

array_sum — Вычисляет сумму значений массива

Описание

number array_sum ( array $array )

array_sum() возвращает сумму значений массива.

Список параметров

array

Входной массив.

Возвращаемые значения

Возвращает сумму значений в виде integer или float.

Список изменений

Версия | Описание
4.2.1 | PHP более ранних, чем 4.2.1, версий модифицировал переданный в качестве аргумента массив и конвертировал строки в числа (что в большинстве случаев означало конвертирование в 0, в зависимости от их значения).

Примеры

Пример #1 Пример использования array_sum()

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

Результат выполнения данного примера:

sum(a) = 20
sum(b) = 6.9

User Contributed Notes

pablo114 at interia dot eu 06-May-2012 06:17
If you want to sum all values (horizontal or vertical) use this function:

<?php

function sumArray($array, $params = array('direction' => 'x', 'key' => 'xxx'), $exclusions = array()) {

    if(!empty($array)) {

        $sum = 0;

        if($params['direction'] == 'x') {

            $keys = array_keys($array);

            for($x = 0; $x < count($keys); $x++) {

                if(!in_array($keys[$x], $exclusions))
                    $sum += $array[$keys[$x]];

            }

            return $sum;

        } elseif($params['direction'] == 'y') {

            $keys = array_keys($array);

            if(array_key_exists($params['key'], $array[$keys[0]])) {

                for($x = 0; $x < count($keys); $x++) {

                    if(!in_array($keys[$x], $exclusions))
                        $sum += $array[$keys[$x]][$params['key']];

                }

                return $sum;

            } else return false;

        } else return false;

    } else return false;

}

?>

Some examples now:

<?php

$array1 = array('myKey1' => 2, 'myKey2' => 5, 'myKey3' => 8);
$array2 = array(array('myKey1' => 2, 'myKey2' => 5, 'myKey3' => 8), array('myKey1' => 2, 'myKey2' => 5, 'myKey3' => 8));

/*Sum an array*/
print_r(sumArray($array1)); //outputs: 15

/*Sum an array without adding "myKey2" key*/
print_r(sumArray($array1, array('direction' => 'x'), array('myKey2'))); //outputs: 10

/*Sum a multi-dimensional array horizontally without adding "myKey3" key*/
print_r(sumArray($array2[0], array('direction' => 'x'), array('myKey3'))); //outputs: 7

/*Sum a multi-dimensional array vertically (by "myKey1" key) without adding [0] row*/
print_r(sumArray($array2, array('direction' => 'y', 'key' => 'myKey1'), array('0'))); //outputs: 2

?>
igz dot dwd dot 20 at gmail dot com 15-Oct-2011 03:02
As mysql_fetch_array returns associative and numeric indexes, you can simply use a flag.

<?php
$result = mysql_query("SELECT id, name FROM mytable");
$row = mysql_fetch_array($result, MYSQL_NUM);
array_sum($row);
?>

Hope it helps.
davidcairngorm at gmail dot com 03-Sep-2011 04:37
If the array is a result from mysql_fetch_array, it contains every value twice and the sum will be double.
pligor at facebook dot com 01-Jun-2011 12:12
There was a case where I had a complex array, multi-dimesional and non-symmetric (not all elements of a sub-array were arrays themselves)
Although all the leaf elements of this array were numbers. In case you have two variables like that and you wanted to add all the values of the right variable to the left then you would need a function like below.

This is a recursive function which adds the values of two multidimensional arrays with the same key structure:

<?php
function multiDimArrayAdd(& $left, $right)    //created by George Pligor
{
    if(is_array($left) && is_array($right))
    {
        foreach($left as $key => $val)
        {
            if( is_array($val) )
            {
                multiDimArrayAdd($left[$key], $right[$key]);
            }
            $left[$key] += $right[$key];
        }
    }
}
?>
uhehesh at gmail dot com 07-Jan-2011 02:21
<?php
function avrg()
{
 $count = func_num_args();
 $args = func_get_args();
 return (array_sum($args) / $count);
}
?>

This function calculates average of numbers given as arguments. Examples:
avrg(100, 200, 300) - returns 200.
avrg(5, 6) - returns 5.5.
avrg('foo') - returns 0.
Chris 17-Feb-2010 08:24
Average array values, ignoring zero values:

<?php
function array_average_nonzero($arr) {
   return array_sum($arr) / count(array_filter($arr));
}
?>

<?php
$arr = array(1,2,3,0,0);
echo array_average_nonzero($arr); // returns 2
echo array_sum($arr) / count($arr); // returns 1.2
?>
hdeus at yahoo dot com 06-Oct-2008 07:01
Here is how you can multiply two arrays in the form of matrixes using a bit of matrix algebra (M*M).
By calling the function multiplyMatrix, you will be multiplying two sparse matrixes (zeros need not be included in the array for the operation to be performed).

<?php
$M = array(
0=>array(1=>1,4=>1),
1=>array(2=>1,3=>1),
3=>array(1=>1),
4=>array(5=>1),
5=>array(6=>1)
);

$M1 = multiplyMatrix($M, $M); //multiplying $M by itself

echo '<pre>';print_r($M1);echo '</pre>';

function multiplyMatrix($M1, $M2)
    {
#Helena F Deus, Oct 06, 2008
##Multiply two matrixes; $M1 and $M2 can be sparse matrixes, the indexes on both should match
        if(is_file($M1)) {$matrix1 = unserialize(file_get_contents($M1));}
        else $matrix1 = $M1;

        #transpose M2
        $M2t = transpose($M2);

        foreach ($M2t as $row=>$tmp) {
            ##sum the result of the value in the col multiplied by the value in the vector on the corresponding row

                foreach ($M1 as $row1=>$tmp1) {

                    $multiply[$row1] = array_rproduct($tmp,$tmp1);

                    if(!$multiply[$row1]){
                          exit;
                        }
                }

                foreach ($multiply as $row1=>$vals) {

                    $sum[$row][$row1]=array_sum($vals);
                }

        }

    $r=transpose($sum);

    return ($r);
    }

function transpose($M)
{
foreach ($M as $row=>$cols) {

            foreach ($cols as $col=>$value) {
                 if($value)
                 $Mt[$col][$row]=$value;
            }
        }
        ksort($Mt);

return ($Mt);
}

function array_rproduct($a1, $a2)
{

    foreach ($a1 as $line=>$cols) {
        $a3[$line] = $a1[$line]*$a2[$line];
        foreach ($a2 as $line2=>$cols2) {
            $a3[$line2] = $a1[$line2]*$a2[$line2];
        }
    }
    ksort($a3);

    return ($a3);

}

?>
c dot heckemueller at befestigungsfuchs dot de 05-Sep-2008 01:30
<?php
/**
 * sum values in array
 *
 * @param array $arr
 * @param string [optional]$index
 * @return int result
 */
function array_sum_key( $arr, $index = null ){
    if(!is_array( $arr ) || sizeof( $arr ) < 1){
        return 0;
    }
    $ret = 0;
    foreach( $arr as $id => $data ){
        if( isset( $index )  ){
            $ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
            $ret += $data;
        }
    }
    return $ret;
}
?>

With this function you can choose whether you sum specific keys in a multidim array, or a normalized array. it is designed to not trigger errors if a key is not set.
superman1101 27-Aug-2008 11:29
To elaborate on djyb2003 at yahoo dot fr. His function can be converted to recursive, but i've made a smaller function to do so:

<?php

 function array_sum_all($array) {
   $func = create_function("&\$arr=0,\$key=0","static \$a=0; if(is_int(\$arr)) { \$a+=\$arr; } return \$a;");
   array_walk_recursive($array,$func);
   return $func();
 }

$tab = array(
                 0 => array ("val1" => 2,"val2" => 5),
                 1 => array ("val1" => 6,"val2" => 10),
                 "toto" => array ("val1" => 15,"val2" => 50)
                );
var_dump(array_sum_all($tab)); //This will output: int(88);
?>

hope this helps someone
djyb2003 at yahoo dot fr 29-Jan-2008 06:31
here is a function that can sum values like these :

$tab = array(
                 0 => array ("val1" => 2,"val2" => 5)
                 1 => array ("val1" => 6,"val2" => 10)
                 "toto" => array ("val1" => 15,"val2" => 50)
                );

sum_subarrays_by_key( $tab, "val1" );

the function will sum all values with "val1" key in tab subarrays.

function sum_subarrays_by_key( $tab, $key ) {

        $sum = 0;

        foreach($tab as $sub_array) {
            $sum += $sub_array[$key];
        }

        return $sum;

    }

it can be transformed to be recursive and do also all depths possible in an array.

Hope it can be usefull!
Coder 16-Aug-2007 04:10
A much simpler algorithm for array_sub():

<?php
  function array_sub($arr) {
    if (!is_array($arr) || count($arr) == 0) {
      return false;
    } else {
      // get first element
      $base = array_shift($arr);

      return $base - array_sum($arr);
    }
  }
?>

This will return the exact same results that didikdwi's version.

However, didikdwi's result depends on knowing what the first value is. When this likely bug is removed, the code is:

<?php
  function array_sub($arr){
    $temp = array_sum($arr);
    return ( $temp !== false ? -$temp : false );
  }
?>
didikdwi at gmail dot com 18-Jul-2007 06:48
This is a simple approach to subtract array, both indexed and associative.

  function array_sub($arr) {
    if (!is_array($arr) || count($arr) == 0) {
      return false;
    } else {
      // get first element
      $base = array_shift($arr);

      if (count($arr) == 1) {
        // If only one element, return its
        return $base;
      }

      foreach ($arr as $val) {
        $base -= $val;
      }

      return $base;
    }
  }

// example
$arr1 = array(3, 2, 3);
echo array_sub($arr1);   // Output: -2
$arr2 = array(3.5, 2, 3);
echo array_sub($arr2);   // Output: -1.5
$arr3 = array('a' => 3, 'b' => 2, 'c' => 3);
echo array_sub($arr3);   // Output: -2
herenvardo at gmail dot com 24-Nov-2006 03:28
I'm not sure if something similar already exists, but I needed it so I made it:
<?php
  /* Performs a pitagoric sum of the elements in $arr
   The pitagoric sum of a set of values is the square root of
   the sum of the sqare power of each value. So, for a, b, c
   it's sqrt(a^2 + b^2 + c^2) */
  /* If any element of $arr is an array itself, the array_sum
   will be used. Alternatively, the values could be used by
   recursion. Returns the integer part (floor) */
  function array_pitag_sum($arr) {
    if(is_array($arr) {
      $ret = 0;
      foreach($arr as $i) {
        if(is_array($i)) {
          $s = array_sum($i);
          $ret += $s*$s;
        } else {
          $ret += $i*$i;
        }
      }
      return floor(sqrt($ret));
    } else {
      return $arr;
    }
  }
?>
Tobias Schlemmer 27-Jul-2006 11:41
<?php
$array1 = array('1'=>'1','2'=>'2','3'=>'3');
$array2 = array(          '2'=>'1','3'=>'2','4'=>'3');
$array3 = array(                  '3'=>'1','4'=>'2','5'=>'3');
$array  = array_sum_values( $array1, $array2, $array3 );
print_r($array);

/**
 * Sums the values of the arrays be there keys (PHP 4, PHP 5)
 * array array_sum_values ( array array1 [, array array2 [, array ...]] )
 */
function array_sum_values() {
    $return = array();
    $intArgs = func_num_args();
    $arrArgs = func_get_args();
    if($intArgs < 1) trigger_error('Warning: Wrong parameter count for array_sum_values()', E_USER_WARNING);

    foreach($arrArgs as $arrItem) {
        if(!is_array($arrItem)) trigger_error('Warning: Wrong parameter values for array_sum_values()', E_USER_WARNING);
        foreach($arrItem as $k => $v) {
            $return[$k] += $v;
        }
    }
    return $return;
}
/* result:
Array
(
    [1] => 1
    [2] => 3
    [3] => 6
    [4] => 5
    [5] => 3
)
*/
?>
jodymickey at yahoo dot com 01-Jun-2006 08:23
In reference to KageKonjou's array_mode function...

If you only want to know the value in the array that occurs most (and not the number of times it actually occured), you can use this short function.  It also suffers from the same problem in that if there is more than one mode, it will return only one.
<?php
    function array_mode($array)
    {
        if(!is_array($array)) return false;
        asort(array_count_values($array));
        return array_pop($array);
    }
?>
Moslehi[atsign]Gmail[dot]com 17-Mar-2006 03:13
A simple example for numeric values :

<?PHP

function array_average($arr){
$sum = array_sum($arr);
$num = sizeof($arr);
echo $sum/$num;
}

$myarray = array(1,2,3,4);
array_average($myarray); // displays 2.5 as average of 1,2,3,4

?>

[Arash Moslehi]
darianlassan at yahoo dot de 04-Nov-2005 03:57
function array_avg(&$array)
{
  //**
    returns the average value of all array-values
    or false if no values in array (or not an array)
  **//

  if (!is_array($array) || count($array)==0)
    return false;
  else
    return array_sum($array)/count($array);
} // array_avg()

Please add this function to PHP.
mroach at mroach dot com 27-Sep-2005 01:06
I ran into a situation where I only wanted to sum elements of an array for certain keys. For that, I wrote this function

<?

function array_sum_by_key()
{
    $args = func_get_args();

    $arr = array_shift($args);

    $to_sum = is_array($args[0]) ? $args[0] : $args;

    $sum = 0;

    foreach ( $arr as $k=>$v ) {
        if ( in_array($k, $to_sum) ) {
            $sum += $v;
        }
    }

    return $sum;
}

$arr = array (
    'dog' => 1,
    'cat' => 2,
    'rat' => 4,
    'mat' => 8,
    'bat' => 16
);

echo array_sum_by_key($arr, 'dog', 'mat');

// Result: 9

?>

Alternatively, you can pass the keys to sum as an array

<?

$to_sum = array('dog', 'bat');

echo array_sum_by_key($arr, $to_sum);

// Result: 17

?>
KageKonjou at GMail dot com 12-Aug-2005 09:22
Not sure where else to put this, but I added something that determines the most commonly occuring item in an array.  Known Bugs: It will always return the first value if no mode are found, and the first mode found if more are found of same or lesser count.

<?php
function array_mode($array) {
 $count = array();
 foreach ($array as $item) {
  $count[$item]++;
 }
 $mostcommon = "";
 $iter = 0;
 foreach ($count as $k => $v) {
  if ($v > $iter) {
   $mostcommon = $k;
   $iter = $v;
  }
 }
 return array("mode" => $mostcommon, "count" => $count[$mostcommon]);
}
?>
punchto at hotmail dot com 15-Mar-2005 07:06
Microsoft Excel - SUMIF()

function sumif($array,$criteria,$sum_array){
  if(is_array($array) && is_array($sum_array) && trim($criteria)!= ""){
    $array_count = (count($array) < count($sum_array)) ? count($array):count($sum_array);
    for($i=0;$i<$array_count;$i++){
      if(ereg("^<",$criteria)){
        $value = ereg_replace("^<","",$criteria);
        $result += $array[$i] < $value ? $sum_array[$i]:0;
      }
      elseif(ereg("^>",$criteria)){
        $value = ereg_replace("^>","",$criteria);
        $result += $array[$i] > $value ? $sum_array[$i]:0;
      }
      else{
        $value = $criteria;
        $result += $array[$i] == $value ? $sum_array[$i]:0;
      }

    }
    return $result ? $result:0;
  }
}
adam at laural dot com dot au 01-Mar-2005 04:37
Here's a function to return the sum of a portion of an array:

function array_partial_sum($array, $start, $length){
    $new_array = array_slice($array, $start, $length);
    return array_sum($new_array);
}

$array = array(1, 2, 3, 4, 5);
print array_partial_sum($array, 0, 3);  // prints 6
ncheung at maine dot rr dot com 07-Feb-2005 06:02
For clarity, array indices containing boolean values such as TRUE and FALSE are added up as though they are 1 and 0 respectively.
mucello NOO SPAM @ weatherimages dOt org 22-Oct-2003 03:44
If you want to find the AVERAGE of the values in your array, use the sum and count functions together.  For example, let's say your array is $foo and you want the average...

<?php
$average_of_foo = array_sum($foo) / count($foo);
?>
mcrm at NOTNEEDIT dot freemal dot it 13-Aug-2003 09:40
Hi people, if someone is searching a function that works also with multimension array, i suggest this :

<?php
function cw_array_count($a) {
  if(!is_array($a)) return $a;
  foreach($a as $key=>$value)
     $totale += cw_array_count($value);
  return $totale;
}

$a[0][E][PS][P][a1]=1;
$a[0][E][PS][P][a2]=2;
$a[0][E][PJ][P][a2]=2;
$a[1][E][PS][E][a3]=3;

echo cw_array_count($a[0]);
// or
echo cw_array_count($a[0][E]);
?>

Bye, Bye.
R.Martina
drverieevil at REMOVEMEasenne dot org 30-Jul-2003 03:14
If some array elements arent integers, function will change them to integers (content of array will not change) type and then sum them.

Example:
<?php
$foo[] = "12";
$foo[] = 10;
$foo[] = "bar";
$foo[] = "summer";
echo array_sum ($foo); //same as echo "22";
?>
array_splice
array_udiff_assoc
Функции для работы с массивами


Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию

array_sum
array_udiff_uassoc
Функции для работы с массивами
PHP Manual

array_udiff_assoc

(PHP 5)

array_udiff_assoc — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию

Описание

array array_udiff_assoc ( array $array1 , array $array2 [, array $ ... ], callable $data_compare_func )

Вычисляет расхождение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию.

Замечание: Пожалуйста, обратите внимание, что эта функция обрабатывает только одно измерение многомерного массива. Разумеется, вы можете обработать более одного измерения, используя, например, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.

Список параметров

array1

Первый массив.

array2

Второй массив.

data_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

array_udiff_assoc() возвращает array, содержащий все элементы array1, которых нет в каком-либо из всех остальных аргументов. Обратите внимание, что в отличие от array_diff() и array_udiff() в сравнении используются ключи. Сравнение данных массива производится с помощью callback-функции, предоставленной пользователем. В этом смысле, поведение этой функции отличается от array_diff_assoc(), которая используется встроенную функцию для сравнения.

Примеры

Пример #1 Пример использования array_udiff_assoc()

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

В примере выше вы видите, что пара "1" => new cr(4) имеется в обоих массивах и поэтому её нет в выводе функции.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_uassoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_udiff() - Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_udiff_uassoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_uintersect() - Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

User Contributed Notes

There are no user contributed notes for this page.
array_sum
array_udiff_uassoc
Функции для работы с массивами


Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию

array_udiff_assoc
array_udiff
Функции для работы с массивами
PHP Manual

array_udiff_uassoc

(PHP 5)

array_udiff_uassoc — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию

Описание

array array_udiff_uassoc ( array $array1 , array $array2 [, array $ ... ], callable $data_compare_func , callable $key_compare_func )

Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию.

Обратите внимание, что для сравнения используются ключи, в отличие от array_diff() и array_udiff().

Список параметров

array1

Первый массив.

array2

Второй массив.

data_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )
key_compare_func

Сравнение ключей (индексов) также осуществляется с помощью callback-функции key_compare_func. Это отличается от поведения array_udiff_assoc(), которая сравнивает индексы с помощью встроенной функции.

Возвращаемые значения

Возвращает array, содержащий все элементы array1, которых нет в каком-либо из остальных аргументов.

Примеры

Пример #1 Пример использованияarray_udiff_uassoc()

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }

    static function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

В вышеприведённом примере вы можете видеть, что пара "1" => new cr(4) присутствует в обоих массивах и поэтому отсутствует в выводе функции. Помните, что необходимо использовать две функции обратного вызова.

Примечания

Замечание: Пожалуйста, обратите внимание, что эта функция обрабатывает только одно измерение многомерного массива. Разумеется, вы можете обработать более одного измерения, используя array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_udiff() - Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_udiff_assoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_uintersect() - Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

User Contributed Notes

aidan at php dot net 28-May-2004 10:06
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
array_udiff_assoc
array_udiff
Функции для работы с массивами


Вычисляет расхождение массивов, используя для сравнения callback-функцию

array_udiff_uassoc
array_uintersect_assoc
Функции для работы с массивами
PHP Manual

array_udiff

(PHP 5)

array_udiff — Вычисляет расхождение массивов, используя для сравнения callback-функцию

Описание

array array_udiff ( array $array1 , array $array2 [, array $ ... ], callable $data_compare_func )

Вычисляет расхождение массивов, используя для сравнения данных callback-функцию. Это отличается от поведения array_diff(), которая использует встроенную функцию для сравнения данных.

Список параметров

array1

Первый массив.

array2

Второй массив.

data_compare_func

Callback-функция, используемая для сравнения.

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает массив, содержащий все элементы array1, которые не существуют в каком-либо из других аргументов.

Примеры

Пример #1 Пример использования array_udiff()

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

Примечания

Замечание: Обратите внимание, что эта функция обрабатывает только одно измерение многомерного массива. Разумеется, вы можете обработать более одного измерения, используя array_udiff($array1[0], $array2[0], "data_compare_func");.

Смотрите также

  • array_diff() - Вычислить расхождение массивов
  • array_diff_assoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_uassoc() - Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_udiff_assoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc() - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_uintersect() - Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

User Contributed Notes

b4301775 at klzlk dot com 15-Jun-2011 11:09
Quick example for using array_udiff to do a multi-dimensional diff

Returns values of $arr1 that are not in $arr2

<?php
$arr1 = array( array('Bob', 42), array('Phil', 37), array('Frank', 39) );

$arr2 = array( array('Phil', 37), array('Mark', 45) );

$arr3 = array_udiff($arr1, $arr2, create_function(
    '$a,$b',
    'return strcmp( implode("", $a), implode("", $b) ); ')
    );

print_r($arr3);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => Bob
            [1] => 42
        )

    [2] => Array
        (
            [0] => Frank
            [1] => 39
        )

)
1

Hope this helps someone
jared 07-Jul-2009 12:27
Note that php does the string conversion *before* sending the values to the callback function.
adam dot jorgensen dot za at gmail dot com 08-Oct-2008 06:51
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
grantwparks at gmail dot com 31-Dec-2007 07:15
Re: "convoluted"

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

Consider:

<?php
function compr_1($a, $b) {
    $aVal = is_array($a) ? $a['last_name'] : $a;
    $bVal = is_array($b) ? $b['last_name'] : $b;
    return strcasecmp($aVal, $bVal);
}

$aEmployees = array(
    array('last_name'  => 'Smith',
            'first_name' => 'Joe',
            'phone'      => '555-1000'),
    array('last_name'  => 'Doe',
            'first_name' => 'John',
            'phone'      => '555-2000'),
    array('last_name'  => 'Flagg',
            'first_name' => 'Randall',
            'phone'      => '666-1000')
    );

$aNames = array('Doe', 'Smith', 'Johnson');

$result = array_udiff($aEmployees, $aNames, "compr_1");

print_r($result);
?>

Allowing me to get the "employee" that's not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don't correspond to array1 and array2.  That's why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array.  (Found this out the hard way.)
Colin 02-Aug-2006 01:15
I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

<?
$a = array(
        array(
                'id' => 10,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ($a['id'] - $b['id']);
}
function compare_names($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

$ret = array_udiff($a, $b, 'compare_ids');
var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');
var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.
<?
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    int(10)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(3) "red"
  }
}
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.
<?
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(5) "Nancy"
    ["color"]=>
    string(5) "black"
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(40)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(6) "orange"
  }
}
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).
<?
array(0) {
}
?>
dmhouse at gmail dot com 20-Jan-2005 01:44
Very easy way of achieving a case-insensitive version of array_diff (or indeed array_diff_assoc, array_intersect or any of these types of functions which have a similar function that takes a callback function as one of their parameters):

array_udiff($array1, $array2, 'strcasecmp');

This works because strcasecmp() compares two strings case-insensitively, as compared to the array_diff() which compares two strings by using the == operator, which is case-sensitive.
aidan at php dot net 28-May-2004 07:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
array_udiff_uassoc
array_uintersect_assoc
Функции для работы с массивами


Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию

array_udiff
array_uintersect_uassoc
Функции для работы с массивами
PHP Manual

array_uintersect_assoc

(PHP 5)

array_uintersect_assoc — Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию

Описание

array array_uintersect_assoc ( array $array1 , array $array2 [, array $ ... ], callable $data_compare_func )

Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию.

Учтите, что в сравнении используются ключи, в отличии от array_uintersect(). Значения сравниваются с помощью callback-функции.

Список параметров

array1

Первый массив.

array2

Второй массив.

data_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает массив, содержащий все элементы array1, которые существуют во всех остальных аргументах.

Примеры

Пример #1 Пример использования array_uintersect_assoc()

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

Результат выполнения данного примера:

Array
(
    [a] => green
)

Смотрите также

  • array_uintersect() - Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_intersect_uassoc() - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

User Contributed Notes

There are no user contributed notes for this page.
array_udiff
array_uintersect_uassoc
Функции для работы с массивами


Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

array_uintersect_assoc
array_uintersect
Функции для работы с массивами
PHP Manual

array_uintersect_uassoc

(PHP 5)

array_uintersect_uassoc — Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

Описание

array array_uintersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callable $data_compare_func , callable $key_compare_func )

Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию. Обратите внимание, что в отличии от array_uintersect(), в сравнении принимают участие ключи. Для сравнения и ключей, и значений используется callback-функция.

Список параметров

array1

Первый массив.

array2

Второй массив.

data_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )
key_compare_func

Callback-функция для сравнения ключей.

Возвращаемые значения

Возвращает массив, содержащий все элементы array1, которые существуют во всех остальных аргументах.

Примеры

Пример #1 Пример использования array_uintersect_uassoc()

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

Результат выполнения данного примера:

Array
(
    [a] => green
    [b] => brown
)

Смотрите также

  • array_uintersect() - Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_intersect_uassoc() - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию

User Contributed Notes

aidan at php dot net 31-Aug-2004 03:52
Please note, the correct function synopsis is:

array array_uintersect_uassoc ( array array1, array array2 [, array ...], callback data_compare_func, callback key_compare_func)

You may specifiy as many arrays as you like, but the last two parameters must be valid call back functions.
array_uintersect_assoc
array_uintersect
Функции для работы с массивами


Вычисляет пересечение массивов, используя для сравнения значений callback-функцию

array_uintersect_uassoc
array_unique
Функции для работы с массивами
PHP Manual

array_uintersect

(PHP 5)

array_uintersect — Вычисляет пересечение массивов, используя для сравнения значений callback-функцию

Описание

array array_uintersect ( array $array1 , array $array2 [, array $ ... ], callable $data_compare_func )

Вычисляет пересечение массивов, используя для сравнения значений callback-функцию.

Список параметров

array1

Первый массив.

array2

Второй массив.

data_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает массив, содержащий все элементы array1, которые существуют во всех остальных аргументах.

Примеры

Пример #1 Пример использования array_uintersect()

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

Результат выполнения данного примера:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

Смотрите также

  • array_intersect() - Вычисляет схождение массивов
  • array_intersect_assoc() - Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию

User Contributed Notes

Nate at RuggFamily dot com 02-Feb-2007 12:03
I want to stress that in the user function, you do need to return either a 1 or a -1 properly; you cannot simply return 0 if the results are equal and 1 if they are not.

The following code is incorrect:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
return 1;
}

$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>

This code is correct:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
if ($v1 > $v2) return 1;
return -1;
}
$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>
array_uintersect_uassoc
array_unique
Функции для работы с массивами


Убирает повторяющиеся значения из массива

array_uintersect
array_unshift
Функции для работы с массивами
PHP Manual

array_unique

(PHP 4 >= 4.0.1, PHP 5)

array_unique — Убирает повторяющиеся значения из массива

Описание

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Принимает входной array и возвращает новый массив без повторяющихся значений.

Обратите внимание, что ключи сохранятся. array_unique() сначала сортирует значения как строки, сохраняет первый встреченный ключ для каждого значения и игнорирует все последующие ключи. Это не означает, что первый ключ каждого значения неотсортированного array будет сохранён.

Замечание: Два элемента считаются одинаковыми в том и только в том случае, если (string) $elem1 === (string) $elem2. Другими словами: если у них одинаковое строковое представление. Будет использован первый элемент.

Список параметров

array

Входной массив.

sort_flags

Можно испольовать необязательный второй параметр sort_flags для изменения поведения сортировки с помощью следующих значений:

Виды сортировок флагов:

  • SORT_REGULAR - нормальное сравнение элементов (типы не меняются)
  • SORT_NUMERIC - элементы сравниваются как числа
  • SORT_STRING - элементы сравниваются как строки
  • SORT_LOCALE_STRING - элементы сравниваются как строки, в зависимости от установленной локали.

Возвращаемые значения

Возвращает отфильтрованный массив.

Список изменений

Версия | Описание
5.2.10 | Значение по умолчанию параметра sort_flags изменено обратно на SORT_STRING.
5.2.9 | Добавлен необязательный параметр sort_flags, по умолчанию равный SORT_REGULAR. До версии 5.2.9, это функция сортировала массив с помощью SORT_STRING.

Примеры

Пример #1 Пример использования array_unique()

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Пример #2 array_unique() и типы:

<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

Результат выполнения данного примера:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

Смотрите также

  • array_count_values() - Подсчитывает количество всех значений массива

Примечания

Замечание: Обратите внимание, что array_unique() не предназначена для работы с многомерными массивами.

User Contributed Notes

sashasimkin at gmail dot com 25-Apr-2012 01:26
My object unique function:

<?php
function object_unique( $obj ){
    $objArray = (array) $obj;

    $objArray = array_intersect_assoc( array_unique( $objArray ), $objArray );

    foreach( $obj as $n => $f ) {
        if( !array_key_exists( $n, $objArray ) ) unset( $obj->$n );
    }

    return $obj;
}
?>

And these code:

<?php
class Test{
    public $pr0 = 'string';
    public $pr1 = 'string1';
    public $pr2 = 'string';
    public $pr3 = 'string2';
}

$obj = new Test;

var_dump( object_unique( $obj ) );
?>

returns:
object(Test)[1]
  public 'pr0' => string 'string' (length=6)
  public 'pr1' => string 'string1' (length=7)
  public 'pr3' => string 'string2' (length=7)
gma (at) qoob (dot) gr 12-Nov-2011 10:07
Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth.

i.e.
<?php
$tmp = array( 'a' => array( 1,2,3,4 ), 'b' => array( 'c' => array( 4,5,6,7 ) ) );
?>

will return with array_flat( $tmp ) --> array( 1,2,3,4,5,6,7 );

I hope that the function will help someone

<?php
/**
 * @params      : $a            array           the recursion array
 *              : $s            array           storage array
 *              : $l            integer         the depth level
 *
 */
if( !function_exists( 'array_flat' ) )
{
    function array_flat( $a, $s = array( ), $l = 0 )
    {
        # check if this is an array
        if( !is_array( $a ) )                           return $s;

        # go through the array values
        foreach( $a as $k => $v )
        {
            # check if the contained values are arrays
            if( !is_array( $v ) )
            {
                # store the value
                $s[ ]       = $v;

                # move to the next node
                continue;

            }

            # increment depth level
            $l++;

            # replace the content of stored values
            $s              = array_flat( $v, $s, $l );

            # decrement depth level
            $l--;

        }

        # get only unique values
        if( $l == 0 ) $s = array_values( array_unique( $s ) );

        # return stored values
        return $s;

    } # end of function array_flat( ...

}
?>
Friendly Code 01-Aug-2011 03:48
I required a function that removed a specific duplicate entry from an array and ignoring all others so came up with this:

<?php
function specified_array_unique($array, $value)
{
    $count = 0;

    foreach($array as $array_key => $array_value)
    {
        if ( ($count > 0) && ($array_value == $value) )
        {
            unset($array[$array_key]);
        }

        if ($array_value == $value) $count++;
    }

    return array_filter($array);
}
?>
0cool.f 23-May-2011 03:54
Hope this can help...

<?php
function array_unique_key_group($array) {
    if(!is_array($array))
        return false;

    $temp = array_unique($array);
    foreach($array as $key => $val) {
        $i = array_search($val,$temp);
        if(!empty($i) && $key != $i) {
            $temp[$i.','.$key] = $temp[$i];
            unset($temp[$i]);
        }
    }
    return $temp;
}
?>

this function return an array that is unique, but preserve every key for the element...
sorry for bad english I'm italian...

$array['asd'] = 'value';
$array['lol'] = 'value';
$array['foo'] = 'val';
$array['bar'] = 'val';

var_dump(array_unique_key_group($array));
// will be output
array(2) { ["asd,lol"]=> string(5) "value" ["foo,bar"]=> string(3) "val" }
mykelscappin at gmail dot com 30-Mar-2011 05:18
I made an array_unique function to handle deep arrays:

<?php
    function array_unique_deep($array) {
        $values=array();
        //ideally there would be some is_array() testing for $array here...
        foreach ($array as $part) {
            if (is_array($part)) $values=array_merge($values,array_unique_deep($part));
            else $values[]=$part;
        }
        return array_unique($values);
    }

    $test=array(123,456,array(789,123,array(456),789),array(123));
    print_r(array_unique_deep($test));

?>

outputs

Array
(
    [0] => 123
    [1] => 456
    [2] => 789
)
simon 11-Oct-2010 05:01
if you want to close the gaps into the keys after using array_unique() you can use array_values() afterwards. Example:

<?php
a = array("one", "two", "two", "three")
a = array_unique(a);
/* will lead to:
a[0] = "one"
a[1] = "two"
a[3] = "three"
*/
a = array_values(a);
/* Now we've got:
a[0] = "one"
a[1] = "two"
a[2] = "three"
*/
?>
michiel ed thalent nl 18-Jun-2010 05:04
If you use SORT_NUMERIC on this kind of filtering it will be significantly faster.
However the array_flip method still is twice as fast.
Anonymous 16-Jun-2010 05:46
It's often faster to use a foreache and array_keys than array_unique:

    <?php

    $max = 1000000;
    $arr = range(1,$max,3);
    $arr2 = range(1,$max,2);
    $arr = array_merge($arr,$arr2);

    $time = -microtime(true);
    $res1 = array_unique($arr);
    $time += microtime(true);
    echo "deduped to ".count($res1)." in ".$time;
    // deduped to 666667 in 32.300781965256

    $time = -microtime(true);
    $res2 = array();
    foreach($arr as $key=>$val) {
        $res2[$val] = true;
    }
    $res2 = array_keys($res2);
    $time += microtime(true);
    echo "<br />deduped to ".count($res2)." in ".$time;
    // deduped to 666667 in 0.84372591972351

    ?>
regeda at inbox dot ru 12-Apr-2010 08:11
recursive array unique for multiarrays

<?php
function super_unique($array)
{
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

  foreach ($result as $key => $value)
  {
    if ( is_array($value) )
    {
      $result[$key] = super_unique($value);
    }
  }

  return $result;
}
?>
brendel at krumedia dot de 24-Feb-2010 11:47
Prior to 5.2.9 you may create a list of unique objects this way:

<?php
for (; ; ) {
  // ...
  $uniqueObjectList[spl_object_hash($myObject)] = $myObject;
}
?>
amri [ at t] dhstudio dot eu 18-Dec-2009 02:36
I searched how to show only the duplicate elements from array, but failed.
Here is my solution:

<?php
function arrayDuplicate($array)
{
return array_unique(array_diff_assoc($array1,array_unique($array1)));
};
?>

Example:
<?php
$arr1 = array('foo', 'bar', 'xyzzy', '&', 'xyzzy',
'baz', 'bat', '|', 'xyzzy', 'plugh',
'xyzzy', 'foobar', '|', 'plonk', 'xyzzy',
'apples', '&', 'xyzzy', 'oranges', 'xyzzy',
'pears','foobar');

$result=arrayDuplicate($arr1);
print_r($result);exit;
?>

Output:

Array
(
[4] => xyzzy
[12] => |
[16] => &
[21] => foobar
)
Youssef Omar 16-Dec-2009 11:09
This is how to merge 2 comma separated lists with unique value only.

<?php
  $list1 = "4444, 5555, 6666";
  $list2 = "4444, 5555, 7777";

  // combine both lists with unique values only
  $list3 = implode("," , array_unique(array_merge(explode(",",$list1),explode(",", $list2))));

  echo $list3;
?>

The result is: 4444,5555,6666,7777
macnimble at gmail dot com 08-Sep-2009 08:24
I'm not sure why you'd use any kind of loop to get the duplicates in an array. Here's a handy little function which does exactly that using some of PHP's other array_* functions.

<?php
function array_not_unique( $a = array() )
{
  return array_diff_key( $a , array_unique( $a ) );
}
?>

Some arrays for testing:

<?php
$person = array();
$person[1] = "person_1";
$person[2] = "person_2";
$person[3] = "person_3";
$person[4] = "person_4";
$person[5] = "person_5";
$person[6] = "person_2"; # DUPE
$person[7] = "person_4"; # DUPE
$person[8] = "person_4"; # DUPE
echo '<pre>',print_r(array_not_unique($person),1),'</pre>';
$person = array();
$person[] = 1;
$person[] = 2;
$person[] = 3;
$person[] = 4;
$person[] = 5;
$person[] = 2; # DUPE
$person[] = 4; # DUPE
$person[] = 4; # DUPE
echo '<pre>',print_r(array_not_unique($person),1),'</pre>';
?>

Output:
Array
(
    [6] => person_2
    [7] => person_4
    [8] => person_4
)

Array
(
    [5] => 2
    [6] => 4
    [7] => 4
)

Hope it helps.
--Bill
steve at visual77 dot com 26-May-2009 04:41
One way to use array_unique() to handle the multidimensional array issue is to use an md5 hash of the serialized array as the key. I've seen some solutions listed here that stored the serialized string, but that requires unserialization, and moving data back and forth between two states for little reason is just a bad idea. Instead, you could try this method:

<?php
$values = array();

foreach($data as $d) {
    $values[md5(serialize($d))] = $d;
}

sort($values);
?>

This will serialize and hash the value, and store the value with the hash as they key. This will ensure that each piece is only stored once, as the second attempt to store will just overwrite the first attempt with identical data.

The sort() at the end is a bit unnecessary, but I had to use it on my project, because the function I was passing the array to couldn't handle keys that weren't valid XML node names (and some md5 hash strings will start with numbers, which is invalid for XML).
dirk dot avery a t gmail 30-Apr-2009 08:45
Although array_unique is not intended to work with multi-dimensional arrays, it does on 5.2.9.  However, it does not for 5.2.5.  Beware.
Ultimater at gmail dot com 20-Apr-2009 06:26
Let's say you have
<?php
$v=array("blue","blue","blue","blue");
if($v[0]==$v[1] && $v[1]==$v[2] && $v[2]==$v[3])
echo "Y"; else echo "N";//Y
?>

It works but the if-statement gets a bit messy if the number of array elements gets massive.
I find it is easier to use array_unique like so:
<?php
$v=array("blue","blue","blue","blue");
echo sizeof(array_unique($v))==1?"Y":"N";//Y
?>
inithello at gmail dot com 11-Mar-2009 11:47
I noticed there was no way to tell array_unique() to ignore certain duplicated keys, so I wrote the following. I imagine there's half a dozen more efficient ways to do this, but here goes:

<?php
$array = array('foo', 'bar', 'xyzzy', '&', 'xyzzy',
               'baz', 'bat', '|', 'xyzzy', 'plugh',
               'xyzzy', 'foobar', '|', 'plonk', 'xyzzy',
               'apples', '&', 'xyzzy', 'oranges', 'xyzzy',
               'pears');

$ignore_values = array('|', '&');

print_r(make_unique($array, $ignore_values));

function make_unique($array, $ignore)
{
    while($values = each($array))
    {
        if(!in_array($values[1], $ignore))
        {
            $dupes = array_keys($array, $values[1]);
            unset($dupes[0]);
            foreach($dupes as $rmv)
            {
                unset($array[$rmv]);
            }
        }
    }
    return $array;
}
?>
OUTPUT:
Array
(
    [0] => foo
    [1] => bar
    [2] => xyzzy
    [3] => &
    [5] => baz
    [6] => bat
    [7] => |
    [9] => plugh
    [11] => foobar
    [12] => |
    [13] => plonk
    [15] => apples
    [16] => &
    [18] => oranges
    [20] => pears
)
serg dot podtynnyi at gmail dot com 06-Feb-2009 11:21
//Remove duplicates from a text files and dump result in one file for example: emails list, links list etc

<?php

$data1 = file("data1.txt");
$data2 = file("data2.txt");

file_put_contents('unique.txt', implode('', array_unique(array_merge($data1,$data2))));
?>
jusvalceanu - SPAM at SPAM - yahoo dot com 06-Nov-2008 02:23
so .... my problem was multidimensional sort.

<?php
      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

?>

Array $attribs is an array contaning arrays. Each array in the $attrib array consists in multiple fields (ex: name, lenght, price, etc.) to be more simpler in speech think that $attrib is the array resulted by a search sql query done by a visitator on your online shoopping website ... (so ... each array in the $attrib is a product :P) if you want to sort only the uniq results use the above or use this:

<?php

   /* Our Array of products */
   $attribs[] = array(
                           "name"         => "Test Product 1",
                           "length"     => "42 cm",
                           "weight"     => "0,5 kg",
                           "price"     => "10 $",
                           "stock"     => "100",
                        );

   $attribs[] = array(
                           "name"         => "Test Product 2",
                           "length"     => "42 cm",
                           "weight"     => "1,5 kg",
                           "price"     => "10 $",
                           "stock"     => "200",
                        );

    /* The nice stuff */

      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

      print_r($new); // $new is our sorted array

?>

Have fun tweaking this ;)) i know you will ;))

From Romania With Love
florian at box dot net 08-Oct-2008 01:29
I came across one limitation of array_unique: it doesn't work properly if you have arrays inside your main array.

The reason is that to compare two values, the function tests if (string) $value1 == (string) $value2. So if $value1 and $value2 are both arrays, the function will evaluate the test to 'Array' == 'Array', and decide that the $values are repeated even if the arrays are different.

So a work around is to find a better conversion of an array to a string, which can be done with json:

<?php
print "define an array with repeated scalar '1' and repeated 'array(1)':";
$a_not_unique = array(
    'a' => 1,
    'b' => 1,
    'c' => 2,
    'd' => array(1),
    'e' => array(1),
    'f' => array(2),
);
print_r($a_not_unique);

print "try to use simply array_unique, which will not work since it exludes 'array(2)':";
$a_unique_wrong = array_unique($a_not_unique);
print_r($a_unique_wrong);

print "convert to json before applying array_unique, and convert back to array, which will successfully keep 'array(2)':";
$a_unique_right = $a_not_unique;
array_walk($a_unique_right, create_function('&$value,$key', '$value = json_encode($value);'));
$a_unique_right = array_unique($a_unique_right);
array_walk($a_unique_right, create_function('&$value,$key', '$value = json_decode($value, true);'));
print_r($a_unique_right);
?>

Results:
define an array with repeated scalar '1' and repeated 'array(1)':
Array
(
    [a] => 1
    [b] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )

    [e] => Array
        (
            [0] => 1
        )

    [f] => Array
        (
            [0] => 2
        )
)

try to use simply array_unique, which will not work since it exludes 'array(2)':
Array
(
    [a] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )
)

convert to json before applying array_unique, and convert back to array, which will successfully keep 'array(2)':
Array
(
    [a] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )

    [f] => Array
        (
            [0] => 2
        )
)
quecoder at gmail 25-Aug-2008 10:30
another method to get unique values is :

<?php
$alpha=array('a','b','c','a','b','d','e','f','f');

$alpha= array_keys(array_count_values($alpha));

print_r($alpha);
?>

Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
soapergem at gmail dot com 14-Aug-2008 02:39
Here's another solution for returning an array that only includes repeated values. There is one given below but it only works on numerically indexed arrays; this one is more comprehensive since I used the foreach iterator. Also, this one preserves keys--in that the returned result contains a distinct list of repeats (storing only the first instance it encounters of each duplicate value).

<?php

function array_repeated($array)
{
    if ( !is_array($array) ) {
        return false;
    }

    $duplicates = array();
    foreach ( $array as $key => $val ) {
        end($array);
        $k = key($array);
        $v = current($array);

        while ( $k !== $key ) {
            if ( $v === $val ) {
                $duplicates[$key] = $v;
                                break;
            }

            $v = prev($array);
            $k = key($array);
        }
    }

    return $duplicates;
}

?>
Dorphalsig 28-Jul-2008 09:47
I had a problem with array_unique and multidimensional arrays ... Maybe there's a better way to do this, but this will work for any dimensional arrays.

<?php
function arrayUnique($myArray)
{
    if(!is_array($myArray))
           return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

}
?>
ali at zkurd dot org 19-Jun-2008 01:41
a lot of people create functions just to fix a notice error about an undefined index and removes blank array value.

why not using foreach instead of the for loop?

example:
<?php
foreach ($arrayname as $key => $value) {
    //do what you want with $value withaout index stress
}
?>
PHP Expert 14-Apr-2008 05:34
case insensitive for PHP v4.x and up.

<?php

function in_iarray($str, $a){
foreach($a as $v){
if(strcasecmp($str, $v)==0){return true;}
}
return false;
}

function array_iunique($a){
$n = array();
foreach($a as $k=>$v){
if(!in_iarray($v, $n)){$n[$k]=$v;}
}
return $n;
}

$input = array("aAa","bBb","cCc","AaA","ccC","ccc","CCC","bBB","AAA","XXX");
$result = array_iunique($input);
print_r($result);

/*
Array
(
    [0] => aAa
    [1] => bBb
    [2] => cCc
    [9] => XXX
)
*/
?>
Ray dot Paseur at SometimesUsesGmail dot com 01-Mar-2008 07:46
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

<?php

function array_not_unique($raw_array) {
    $dupes = array();
    natcasesort($raw_array);
    reset ($raw_array);

    $old_key    = NULL;
    $old_value    = NULL;
    foreach ($raw_array as $key => $value) {
        if ($value === NULL) { continue; }
        if ($old_value == $value) {
            $dupes[$old_key]    = $old_value;
            $dupes[$key]        = $value;
        }
        $old_value    = $value;
        $old_key    = $key;
    }
return $dupes;
}

$raw_array     = array();
$raw_array[1]    = 'abc@xyz.com';
$raw_array[2]    = 'def@xyz.com';
$raw_array[3]    = 'ghi@xyz.com';
$raw_array[4]    = 'abc@xyz.com'; // Duplicate

$common_stuff    = array_not_unique($raw_array);
var_dump($common_stuff);
?>
php_array_unique [at] peterwarnock.com 19-Dec-2007 11:20
To clarify the note above Example #1, the function appears to cast the elements to strings for comparison and then return the type of the first unique element encountered.

<?php
$input = array(0, 2, "2", 3, "9", 9);
$result = array_unique($input);
var_dump($result);
?>

array(4) {
  [0]=>
  int(0)
  [1]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  string(1) "9"
}
mnbayazit 28-Oct-2007 02:18
case insensitive

<?php
function array_iunique($array) {
    return array_intersect_key($array,array_unique(
                 array_map(strtolower,$array)));
}
?>
xjazey at hotmail dot com 11-Sep-2007 11:50
This is a solution to remove duplicate values from an array

<?php

$array[0] = "Yellow";
$array[1] = "Green";
$array[2] = "Yellow";
$array[3] = "Blue";
$array[4] = "Yellow";

$array = array_keys(array_flip($array));

//$array will output Yellow Green Blue

?>
tsikano at attglobal dot net 21-Aug-2007 04:20
Suggestion for being able to use array_unique on array of arrays/objects:

<?php
foreach ($arrayOfArrays as $key=>$value) {
  $arrayOfArrays[$key] = "'" . serialize($value) . "'";
}
$arrayOfArrays = array_unique($arrayOfArrays);
foreach ($arrayOfArrays as $key=>$value) {
  $arrayOfArrays[$key] = unserialize(trim($value, "'"));
}
?>
webmaster at jukkis dot net 30-Jul-2007 04:08
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Example:
<?php
/* example object */
class myObj {
  public $id;
  public $value;
  function __construct( $id, $value ) {
    $this->id = $id;
    $this->value = $value;
  }
}

/* callback function */
function uniquecol( $obj ) {
  static $idlist = array();

  if ( in_array( $obj->id, $idlist ) )
    return false;

  $idlist[] = $obj->id;
  return true;
}

/* a couple of arrays with second array having an element with same id as the first */
$list  = array( new myObj( 1, 1  ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );

$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );

?>

In addition, use array_merge( $unique ) to reindex.
arr1 01-Nov-2006 08:59
Just to note that array_unique, treats null values as none unique values. So if your using array_unique to detect duplicate values it will also detect multiple null values.
Ome_Henk 27-Oct-2006 12:16
For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method:

<?php
$unique = array_keys(array_flip($array));
?>

It's marginally faster as:
<?php
$unique = array_merge(array_flip(array_flip($array)));
?>

And it's marginally slower as:
<?php
$unique array_flip(array_flip($array)); // leaves gaps
?>

It's still about twice as fast or fast as array_unique.

This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.
geuis dot teses at gmail dot com 09-Oct-2006 10:27
Here's the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

<?php

// Fruits, vegetables, and other food:
$var = array('apple','banana','carrot','cat','dog','egg','eggplant','fish');

$var = array_values(array_unique($var));
?>
keneks at gmail dot com 30-Sep-2006 07:01
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

It simply compares the number of elements between the original array and the array_uniqued array.

<?php
function array_search_dups($array)
{
    $dup_array = $array;
    $dup_array = array_unique($dup_array);
    if(count($dup_array) != count($array))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
?>
pulsarkowy at NOSPAM dot gmail dot com 13-Sep-2006 04:30
This function below will remove multiple values from array, remove 'empty' fields an also count how many times the given value occured.

it's rather slow and not 'elegant' but works.

usage:
<?php
$myarray = my_array_unique($myarray);
?>

in return it produces an 3 fields array:
1st is index number, 2nd is the value, 3rd is counter.

<?php
function my_array_unique($tablica)
{

$tnum=count($tablica);
$i=1;
$k=1;
$t[1]['product']="";
$t[1]['count']=1;
while($i<=$tnum) {
  if (!array_multi_search($tablica[$i], $t)) {
    $t[$k]['product']=$tablica[$i];
    $t[$k]['count']=1;
    $k++;
  }
  else {
    $y=1;
    while ($y<=count($t)) {
      if ($t[$y]['product']==$tablica[$i])
        $t[$y]['count']++;
      $y++;
    }

  }

$i++;
}

$tablica=$t;
return $tablica;
}
?>

the function uses another function that i've found on the php.net site (i'm posting it only for informational reasons - i can't remember who wrote it):

<?php
function array_multi_search( $p_needle, $p_haystack )
   {
       if( !is_array( $p_haystack ) )
       {
           return false;
       }

       if( in_array( $p_needle, $p_haystack ) )
       {
           return true;
       }

       foreach( $p_haystack as $row )
       {
           if( array_multi_search( $p_needle, $row ) )
           {
               return true;
           }
       }

       return false;
   }
?>

[EDIT BY danbrown AT php DOT net: The array_multi_search() function was originally written by 'czeslaw' and posted to the in_array() function manual entry on 18 February, 2006.]
uditsawhney at yahoo dot com 15-Jul-2006 12:14
<?php

//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Start
function array_uniquecolumn($arr)
{
    $rows   = sizeof($arr);
    $columns = sizeof($arr[0]);

    $columnkeys = array_keys($arr[0]);

    for($i=0; $i<$columns; $i++)
    {
        for($j=0;$j<$rows;$j++)
        {
            for($k = $j+1; $k<$rows; $k++)
            {
                if($arr[$j][$columnkeys[$i]] == $arr[$k][$columnkeys[$i]])
                    $arr[$k][$columnkeys[$i]] = "";
            }
        }

    }

return ($arr);

}
//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Stop

$arrUGCourse[]= array(  "CTR" => "1",

                        "UGCOURSE"=>"ABC",

                        "TSINITIATE"=>"540",

                        "COUNT"=>"34",

                        "ENTRY_DT"=>"2006-05-01",

                        "CUMULATIVE"=> 44);

$arrUGCourse[]= array(  "CTR" => "2",

                        "UGCOURSE"=>"ABC",

                        "TSINITIATE"=>"5401",

                        "COUNT"=>"341",

                        "ENTRY_DT"=>"2006-05-11",

                        "CUMULATIVE"=> 44);

print_r(array_uniquecolumn($arrUGCourse));

?>
MoD 14-Apr-2006 09:02
The shortest way i found to remove duplicate array from a column,
For example if you parse Multiple XML sources, you can remove duplicate items that contain the same link.

<?PHP
function        remove_duplicate($array, $field)
{
  foreach ($array as $sub)
    $cmp[] = $sub[$field];
  $unique = array_unique($cmp);
  foreach ($unique as $k => $rien)
    $new[] = $array[$k];
  return $new;
}
?>
agarcia at rsn dot com dot co 31-Mar-2006 12:41
This is a script for multi_dimensional arrays

<?php
function remove_dup($matriz) {
    $aux_ini=array();
    $entrega=array();
    for($n=0;$n<count($matriz);$n++)
    {
        $aux_ini[]=serialize($matriz[$n]);
    }
    $mat=array_unique($aux_ini);
    for($n=0;$n<count($matriz);$n++)
    {

            $entrega[]=unserialize($mat[$n]);

    }
    return $entrega;
}
?>
mcmeijer at yahoo dot com 27-Jan-2006 05:18
This is a recursive arrayUnique function for arrays of any dimension. (tested with 4-dimensional array)
The line '$newArray=deleteEmpty($newArray);' is optional and removes empty keys and values
<?php
function arrayUnique($myArray)
    {
    $newArray = Array();
    if (is_array($myArray))
        {
        foreach($myArray as $key=>$val)
            {
            if (is_array($val))
                {
                $val2 = arrayUnique($val);
                }
            else
                {
                $val2 = $val;
                $newArray=array_unique($myArray);
                $newArray=deleteEmpty($newArray);
                break;
                }
            if (!empty($val2))
                {
                $newArray[$key] = $val2;
                }
            }
        }
    return ($newArray);
    }

function deleteEmpty($myArray)
    {
    $retArray= Array();
    foreach($myArray as $key=>$val)
        {
        if (($key<>"") && ($val<>""))
            {
            $retArray[$key] = $val;
            }
        }
    return $retArray;
    }
?>
memandeemail at gmail dot com 03-Jan-2006 10:47
Problem:
I have loaded an array with the results of a database
query.  The Fields are 'FirstName' and 'LastName'.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array.  For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Solution:

<?php
/**
 * The same thing than implode function, but return the keys so
 *
 * <code>
 * $_GET = array('id' => '4587','with' => 'key');
 * ...
 * echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key
 * ...
 * </code>
 *
 * @param string $glue Oque colocar entre as chave => valor
 * @param array $pieces Valores
 * @param string $hifen Separar chave da array do valor
 * @return string
 * @author memandeemail at gmail dot com
 */
function implode_with_key($glue = null, $pieces, $hifen = ',') {
  $return = null;
  foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
  return substr($return,1);
}

/**
 * Return unique values from a tree of values
 *
 * @param array $array_tree
 * @return array
 * @author memandeemail at gmail dot com
 */
function array_unique_tree($array_tree) {
  $will_return = array(); $vtemp = array();
  foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'=');
  foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue];
  return $will_return;
}

$problem = array_fill(0,3,
array('FirstName' => 'John', 'LastName' => 'Smith')
);

$problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita');
$problem[] = array('FirstName' => 'John', 'LastName' => 'Tom');

print_r($problem);

print_r(array_unique_tree($problem));
?>
webcreator at centrum dot cz 28-Oct-2005 04:25
array_unique function starts its comparation from beginning and pop the key off if there is more values inside array. The last one remains. But i needed to hold priority of the order of values and let the first one in.

Here is my easy solution:

<?php
function my_array_unique($from)
{
for ($i=count($from);$i>1;$i--)
    {
    $last = $from[$i];
    $from[$i] = "";
    if (!in_array($last,$from))
        $from[$i]=$last;
    }
return array_unique($from);
}

# One empty value remains in array.
# But its very easy to separate it while using output array.
?>
passtschu AT freenet DOT de 21-Sep-2005 07:20
array_unique for multidimensional arrays. similar to the DISTINCT in SQL function.
the function can group, sum and count keys

<?PHP
/*
$array - nothing to say
$group_keys - columns which have to be grouped - can be STRING or ARRAY (STRING, STRING[, ...])
$sum_keys - columns which have to be summed - can be STRING or ARRAY (STRING, STRING[, ...])
$count_key - must be STRING - count the grouped keys
*/
function array_distinct ($array, $group_keys, $sum_keys = NULL, $count_key = NULL){
  if (!is_array ($group_keys)) $group_keys = array ($group_keys);
  if (!is_array ($sum_keys)) $sum_keys = array ($sum_keys);

  $existing_sub_keys = array ();
  $output = array ();

  foreach ($array as $key => $sub_array){
    $puffer = NULL;
    #group keys
    foreach ($group_keys as $group_key){
      $puffer .= $sub_array[$group_key];
    }
    $puffer = serialize ($puffer);
    if (!in_array ($puffer, $existing_sub_keys)){
      $existing_sub_keys[$key] = $puffer;
      $output[$key] = $sub_array;
    }
    else{
      $puffer = array_search ($puffer, $existing_sub_keys);
      #sum keys
      foreach ($sum_keys as $sum_key){
        if (is_string ($sum_key)) $output[$puffer][$sum_key] += $sub_array[$sum_key];
      }
      #count grouped keys
      if (!array_key_exists ($count_key, $output[$puffer])) $output[$puffer][$count_key] = 1;
      if (is_string ($count_key)) $output[$puffer][$count_key]++;
    }
  }
  return $output;
}
?>
muddmonkey@harveyMcoldotedu 17-Aug-2005 01:44
If you're doing numeric arrays etc. I found flip-flip to work much better than array_unique:

<?PHP
    function microtime_float(){ //timing
       list($usec, $sec) = explode(" ", microtime());
       return ((float)$usec + (float)$sec);
    }

    //make an arry and fill it up
    $final=array();
    for($i=0;$i<50000;$i++){
        $final[]=$i%13; //make sure there are some dupes
    }
    //try array unique
    $start1 = microtime_float();
    array_unique($final);
    $stop1=microtime_float();
    echo($stop1-$start1.'<br>');
    //try my flip-flip
    $start2=microtime_float();
    array_flip(array_flip($final));
    $stop2=microtime_float();
    echo($stop2-$start2);
?>

Running this with only ints in the array (as above) I get runtimes such as:
1.6195669174194 (using unique)
0.017037868499756 (using flip flip)
which is two orders of magnitude faster!

Appending a string:
($final[]='test'.$i%13;)
gives:
0.42909598350525 (using unique)
0.023258924484253 (using flip-flip)
Which is not AS great, but still 20x faster than unique.

In both cases the flip-flip seems to use less memory than the unique.

Granted the flip-flip doesn't work for all cases, but if you're doing simple stuff like this, the flip-flip will give you better run times.

~JF
Christoph Ziegenberg 17-Jun-2005 11:44
If the array key is a string it might be important to keep it although the value is the same (as I need it at the moment). So I wrote a function which also returns array elements which have the same value but different string keys.

<?php
function array_unique_numeric ($arr)
{
    $str = $int = array();
    foreach(array_keys($arr) as $key) {
        ${(is_int($key)?'int':'str')}[$key] = $arr[$key];
    }
    return array_merge($str, array_unique($int));
}

// typical array after an array_merge()...
$array = array("a" => "green", "b" => "brown", "c" => "blue", "red", "d" => "green", "yellow", "red");

print_r(array_unique($array));
// Array
// (
//     [a] => green
//     [b] => brown
//     [c] => blue
//     [0] => red
//     [1] => yellow
// )

print_r(array_unique_numeric($array));
// Array
// (
//     [a] => green
//     [b] => brown
//     [c] => blue
//     [d] => green
//     [0] => red
//     [1] => yellow
// )
?>
memandeemail at gmail dot com 15-Apr-2005 01:46
<?php
/**
 * Removes duplicate keys from an array
 *
 * @param array $array
 * @return array
 */
function array_unique_key($array) {
    $result = array();
    foreach (array_unique(array_keys($array)) as $tvalue) {
        $result[$tvalue] = $array[$tvalue];
    }
    return $result;
}
?>
Ric 05-Apr-2005 09:44
A very simple way of getting rid of duplicate entries and re-indexing with key starting at 0:

<?php
    $temp=array_unique($main);
    $main=array_values($temp);
?>
trigger at e-mail dot ru 03-Feb-2005 02:53
Just a simple implementation for JavaScript:

<?php
function array_unique(thearray)
{
    thearray.sort();
    //reset($thearray);
    newarray = new Array();
    for (n=0;n<thearray.length;n++)
    {
        unique=1;//by default
        for(nn=0;nn<newarray.length;nn++)
            if (thearray[n] == newarray[nn])
            {
                unique=0;//already exists
                break;
            }
        if(unique)//dont exists
            newarray.push(thearray[n]);
    }
    return newarray;
 }
?>
lucas.bickel AT purplehaze DOT ch 26-Oct-2004 08:39
I quite like the following code for making multidimensional arrays unique:

<?php
foreach ($arrAddressList AS $key => $arrAddress) {
    $arrAddressList[$key] = serialize($arrAddress);
}
$arrAddressList = array_unique($arrAdressList);
foreach ($arrAddressList AS $key => $strAddress) {
    $arrAddressList[$key] = unserialize($strAddress);
}
?>

This gets me a unique array while not minding wether the the original array contains arrays or just strings (or whatever...).
wernerlistas at terra dot com dot br 16-Jun-2004 08:50
Following the code copies of a little function I've wrote that actually works with multidimensional arrays.
It also resets the array indexes.

<?php
if ( !function_exists( "arrayUnique" ) ){
    function arrayUnique ( $rArray ){
        $rReturn = array ();
        while ( list( $key, $val ) = each ( $rArray ) ){
            if ( !in_array( $val, $rReturn ) )
            array_push( $rReturn, $val );
        }
        return $rReturn;
    }
}
?>
csaba at alum dot mit dot edu 09-Jun-2004 07:17
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

<?php
function array_unique2(&$aray) {
    $aHash = array();
    foreach ($aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
?>

It is also adaptable to multi dimensional arrays.  For example, if your array is a sequence of (multidimensional) points, then in place of @$aHash[$val]++ you could use @$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.

Csaba Gabor
patrikG at home dot net 11-Mar-2004 07:05
If you need to have the keys of the duplicates in an array returned, you may find this function useful:

<?php
function unique_events($array){
    //checks $array for duplicate values and returns an
        //array containing the keys of duplicates
    $count= array_intersect_assoc($array, array_flip( array_count_values($array)));
    foreach($array as $key=>$value){
        if (in_array($value,$count)){
            $return[$value][]=$key;
        }
    }
    return $return;
}
?>

Example:

Input:
Array
(
    [0] => 44
    [1] => 23
    [2] => 23
    [3] => 23
    [4] => 9
    [5] => 9
    [6] => 9
    [7] => 9
    [8] => 9
    [9] => 9
    [10] => 9
    [11] => 9
)

Function returns:
Array
(
    [23] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [9] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
            [5] => 9
            [6] => 10
            [7] => 11
        )

)
bitmore.co.kr 19-Feb-2004 03:53
//Modify
Object Unique

<?php
    class foo {
        var $_name;
        var $_age;
        function foo($name,$age=NULL)    { $this->_name = $name; $this->_age = $age; }
        //function get()        { return $this->_name; }
        //function set($name,$age=NULL)    { $this->_name = $name; $this->_age = $age; }
    }

    function DistinctOn ($obj, $item) {
        $out = array();
        $list = array();
        foreach ($obj as $key=>$so) {
            if (!in_array($so->$item, $list)) {
                echo "key = $key,so = $so,item = $item,IFlist = ";print_r($list);echo "<br>";
                $list[] = $so->$item;//�����迭
                $out[$key] = $so;
            }
            echo "Forlist = ";print_r($list);echo "<br>";
        }
        return $out;
    }

    $foo_obj[0] = new foo('tom',20);
    $foo_obj[1] = new foo('paul',66);
    $foo_obj[2] = new foo('tom',23);

    $item = '_name';
    $result = DistinctOn ($foo_obj, $item);

    while(list($k,$v) = each($result)) {
        print "K = ";print_r($k);
        print ",V = ";print_r($v);
        print "<br>";
    }
    //key = 0,so = Object,item = _name,IFlist = Array ( ) ,Forlist = Array ( [0] => tom )
    //key = 1,so = Object,item = _name,IFlist = Array ( [0] => tom ) ,Forlist = Array ( [0] => tom [1] => paul )
    //Forlist = Array ( [0] => tom [1] => paul )
    //K = 0,V = foo Object ( [_name] => tom [_age] => 20 )
    //K = 1,V = foo Object ( [_name] => paul [_age] => 66 )

    print "<br><br>";
    $item = '_age';
    $result = DistinctOn ($foo_obj, $item);
    while(list($k,$v) = each($result)) {
        print "K = ";print_r($k);
        print ",V = ";print_r($v);
        print "<br>";
    }

    //key = 0,so = Object,item = _age,IFlist = Array ( ) ,Forlist = Array ( [0] => 20 )
    //key = 1,so = Object,item = _age,IFlist = Array ( [0] => 20 ) ,Forlist = Array ( [0] => 20 [1] => 66 )
    //key = 2,so = Object,item = _age,IFlist = Array ( [0] => 20 [1] => 66 ) ,
    //    Forlist = Array ( [0] => 20 [1] => 66 [2] => 23 )
    //K = 0,V = foo Object ( [_name] => tom [_age] => 20 )
    //K = 1,V = foo Object ( [_name] => paul [_age] => 66 )
    //K = 2,V = foo Object ( [_name] => tom [_age] => 23 )
?>
kay_rules at yahoo dot com 24-May-2003 02:28
this function will return an array with unique value and proper key increment start from 0.

<?php
/*******************************/
function my_array_unique($somearray){
    $tmparr = array_unique($somearray);
    $i=0;
    foreach ($tmparr as $v) {
        $newarr[$i] = $v;
        $i++;
    }
    return $newarr;
}
/********************************/
?>

eg:

<?php
$foo_arr[0] ='aa'
$foo_arr[1] ='bb'
$foo_arr[2] ='cc'
$foo_arr[3] ='bb'
$foo_arr[4] ='aa'
$foo_arr[5] ='dd'
?>

normal array_unique will return:

<?php
$foo_arr[0] ='aa';
$foo_arr[1] ='bb';
$foo_arr[2] ='cc';
$foo_arr[3] ='';
$foo_arr[4] ='';
$foo_arr[5] ='dd'
?>

my_array_unique will return:

<?php
$foo_arr[0] ='aa';
$foo_arr[1] ='bb';
$foo_arr[2] ='cc';
$foo_arr[3] ='dd'
?>
martin at lucas-smith dot co dot uk 27-Jan-2003 05:12
To get a list of the duplicated values in an array, array_unique isn't much help. Instead, use array_filter in conjunction with a callback function, as below:

<?php
$checkKeysUniqueComparison = create_function('$value','if ($value > 1) return true;');
$result = array_keys (array_filter (array_count_values($array), $checkKeysUniqueComparison));
?>

These two lines therefore will create $result, an array of duplicated values in the array $array, once each. E.g. the array
$array = array ("a", "b", "a", "b", "x", "y", "z", "x");
gives the result
Array([0] => a [1] => b [2] => x)
deigo at swirve dot NOSPAM dot com 23-Sep-2002 10:04
Before I found the mysql distinct I had to make a nicer array from the keys/values that I got from array_unique so.

<?php
$groups=array_unique($groups);
$newgroup[0]=reset($groups);
for ($x=1;$x<sizeof($groups);$x++)
{
  $newgroup[$x]=next($groups);
}
?>
php at hp-site dot dk 29-Aug-2002 11:15
Try this:
array_flip(array_flip($array));

It gives the same result as the old array_unique()
29-Aug-2002 02:39
<?php
$truc = array("l810u00","l810u00","l810q00");
$machin = array_unique($truc);
for($i=0;$i < count($machin) ; $i++){
print $machin[$i]."
";
}
?>
result :
l810u00

This is not strange: $machin (as returned by array unique), contains "l810u00" either in key[0] or key[1] but not both (the key depends on the ersion of PHP), and "l810q00" in key[2].
The returned array has TWO elements so count($machin)==2.
The returned array has a hole in it, and you're not displaying its full content. You could verify it by using this display loop instead:
foreach($machine as $key=>$value){
print '[' . $key . '] => ' . $value . '
";
}
result:
[0] => l810q00
[2] => l810u00
(the first line may display [1] instead of [0] for PHP 4.0.1p3, but you'll get the same order of values and two lines, as expected). When calling array_values() on the result, you're building a new array with the same values in the same order, but with renumbered keys (without holes in numeric keys).
spunk at dasspunk dot NOSPAM dot com 14-Nov-2001 04:52
I needed a way of retaining the original array's keys in the new, unique array. I came up with this. It works for my purposes but may need refinement.

<?php
function my_array_unique($somearray)
{
    asort($somearray);
    reset($somearray);
    $currentarrayvar = current($somearray);
    foreach ($somearray as $key=>$var)
    {
        if (next($somearray) != $currentarrayvar)
        {
            $uniquearray[$key] = $currentarrayvar;
            $currentarrayvar = current($somearray);
        }
    }
    reset($uniquearray);
    return $uniquearray;
}
?>
az at top-webdesign dot de 10-Jul-2001 01:00
Attention!
If you use array_unique be aware of data-types! (I spent hours of debugging because of that ...).

For example, if you've got an array containing a '3' as number and another '3' as string it won't be eliminated by array_unique.

An Example where this can happen, without really thinking about it:

I've got an article-list with product-numbers where the third and fourth digit is the code for the producer. So I read in the file an process it line by line and put each producer-code into an array:
------------------------------
<?php
$i=0;
while($line = fgets($csv, 10000) {
// splitting the line, product_no is the first part:

$data = explode(";", $line);

// putting the producer_code into an array:

$producer_id[$i] = trim(substr($data[0], 2, 2));

// make a special exception:

if(trim(substr($data[0], 2, 2)) == 40) {
$producer_id[$j] = '30';
}

// in the above line if you leave the 30 without the ''
// array_unique won't work!

$i++;
}

$producer_ids = array_values(array_unique($producer_id));
?>
-------------------------------
Result is to have all producer-ID's in an array without dupes.
rein at velt dot net 21-Apr-2001 12:44
Following code copies unique values from MyArray to TempArray.
Then copies non-empty elements from TempArray to UniqueArray.

Not the most elegant solution, but it works.

<?php
$TempArray = array_unique($MyArray);
while (list($index,$data)=each($TempArray)) {
      if (isempty($data)) {
          $UniqueArray[$index]=$data;
      }
}
?>
jllamas at bal dot com dot mx 25-Sep-2000 09:25
It seems that array_unique creates an exact copy of the original array and then elimitates duplicate values. It does NOT change the "internal references" of the array. For example:

<?php
    $test_alfa = array();
    $test_alfa[0] = "aa";
    $test_alfa[1] = "aa";
    $test_alfa[2] = "aa";
    $test_alfa[3] = "bb";
    $test_alfa[4] = "aa";
    $test_alfa[5] = "bb";
    $test_alfa[6] = "cc";
    $test_alfa[7] = "bb";

    $test_beta= array_unique($test_alfa);
    $numValues = count($test_beta);
    for ($i = 0 ; $i <= 7 ; $i++)
       echo("test_beta[$i] = $test_beta[$i] <br>");
    echo ("Number of elements in test_beta = $numValues ");
?>
will give you the following output:

test_beta[0] =
test_beta[1] = aa
test_beta[2] =
test_beta[3] =
test_beta[4] =
test_beta[5] = bb
test_beta[6] = cc
test_beta[7] =
Number of elements in test_beta = 3

The point is that you won't get the output you'd expect if you think that the values of the non duplicate elements are located in the first three array locations.

<?php
    $numValues = count($test_beta);
    for ($i=0;$i<=$numValues; $i++)
       echo("test_beta[$i] = $test_beta[$i] <br>");
    echo ("Number of elements in test_beta = $numValues ");
?>

will give you:

test_beta[0] =
test_beta[1] = aa
test_beta[2] =
Number of elements in test_beta = 3

Hope that saves u some debugging time!
array_uintersect
array_unshift
Функции для работы с массивами


Добавляет один или несколько элементов в начало массива

array_unique
array_values
Функции для работы с массивами
PHP Manual

array_unshift

(PHP 4, PHP 5)

array_unshift — Добавляет один или несколько элементов в начало массива

Описание

int array_unshift ( array &$array , mixed $var [, mixed $... ] )

array_unshift() добавляет переданные в качестве аргументов элементы в начало массива array. Обратите внимание, что список элементов добавляется целиком, то есть порядок элементов сохраняется. Все числовые ключи будут изменены таким образом, что нумерация массива будет начинаться с нуля, в то время как строковые ключи останутся прежними.

Список параметров

array

Входной массив.

var

Добавляемая в начало переменная.

Возвращаемые значения

Возвращает новое количество элементов в array.

Примеры

Пример #1 Пример использования array_unshift()

<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>

Результат выполнения данного примера:

Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

Смотрите также

  • array_shift() - Извлекает первый элемент массива
  • array_push() - Добавляет один или несколько элеметов в конец массива
  • array_pop() - Извлекает последний элемент массива

User Contributed Notes

Anonymous 19-Nov-2011 09:44
Sahn's example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    return = array_reverse($arr, true);
}
?>
Rafael M. Salvioni 12-Jun-2008 09:52
This function inserts a element in any position of the Array, by reference.

NOTE: The array is converted for a numeric array.

<?php

/**
 * Function array_insert().
 *
 * Returns the new number of the elements in the array.
 *
 * @param array $array Array (by reference)
 * @param mixed $value New element
 * @param int $offset Position
 * @return int
 */
function array_insert(&$array, $value, $offset)
{
    if (is_array($array)) {
        $array  = array_values($array);
        $offset = intval($offset);
        if ($offset < 0 || $offset >= count($array)) {
            array_push($array, $value);
        } elseif ($offset == 0) {
            array_unshift($array, $value);
        } else {
            $temp  = array_slice($array, 0, $offset);
            array_push($temp, $value);
            $array = array_slice($array, $offset);
            $array = array_merge($temp, $array);
        }
    } else {
        $array = array($value);
    }
    return count($array);
}

?>
sergei at gmx dot net 03-Oct-2007 08:49
You can preserve keys and unshift an array with numerical indexes in a really simple way if you'll do the following:

<?php
$someArray=array(224=>'someword1', 228=>'someword2', 102=>'someword3', 544=>'someword3',95=>'someword4');

$someArray=array(100=>'Test Element 1 ',255=>'Test Element 2')+$someArray;
?>

now the array looks as follows:

array(
100=>'Test Element 1 ',
255=>'Test Element 2'
224=>'someword1',
228=>'someword2',
102=>'someword3',
544=>'someword3',
95=>'someword4'
);
amschroeder at gmail dot com 26-Mar-2007 09:13
This becomes a nice little problem if you index your arrays out of order (while manually sorting).  For example:

<?php
$recordMonths[3] = '8/%/2006';
$recordMonths[4] = '7/%/2004';
$recordMonths[0] = '3/%/2007';
$recordMonths[1] = '2/%/2007';
$recordMonths[5] = '12/%/2000';
$recordMonths[6] = '11/%/2000';
$recordMonths[7] = '10/%/2000';
$recordMonths[2] = '1/%/2007';

for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
array_unshift($recordMonths,'%');
for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
?>

Produces:

singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007

It reindexes them based on the order they were created.  It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index.  Just my opinion...
John Brooking 02-Jun-2006 06:54
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the "side effect" of renumbering:

<?php
   array_unshift( $myArray, array_shift( $myArray ));
?>
php at electricsurfer dot com 26-Feb-2004 06:20
even simpler unshifting of a reference !
<?php
/**
 * @return int
 * @param $array array
 * @param $value mixed
 * @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
 */
function array_unshift_ref(&$array, &$value)
{
   $return = array_unshift($array,'');
   $array[0] =& $value;
   return $return;
}
?>
lagroue 09-Nov-2003 04:46
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :

<?php
function array_unshift1 (& $ioArray, $iValueWrappedInAnArray) {
    $lNewArray = false;
    foreach (array_keys ($ioArray) as $lKey)
        $lNewArray[$lKey+1] = & $ioArray[$lKey];
    $ioArray = array (& $iValueWrappedInAnArray[0]);
    if ($lNewArray)
        foreach (array_keys ($lNewArray) as $lKey)
             $ioArray[] = & $lNewArray[$lKey];
    return count($ioArray);
}

// before last PHP (now generates a deprecation warning)
array_unshift ($a, &$v);
// since last PHP (caution, there is a wrapping array !!)
array_unshift1 ($a, array (&$v));
?>
chris dot NoThxSpam dot given at hp dot com 23-Jul-2003 12:17
If you need to change the name of a key without changing its position in the array this function may be useful.

<?php
function array_key_change($Old, $New, $In, $NewVal=NULL) {
        $Temp = array();
        while(isset($Temp[$Old]) == false) {
                list($k, $v) = each($In);
                $Temp[$k] = $v;
                unset($In[$k]);
        }
        if($NewVal == NULL) {
                $NewVal = $Temp[$Old];
        }
        unset($Temp[$Old]);
        $Temp = array_reverse($Temp);
        $In = array_merge(array($New=>$NewVal), $In);
        while(list($k,$v) = each($Temp)) {
                $In = array_merge(array($k=>$v), $In);
        }
        return($In);
}
?>
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz 30-Jul-2002 07:00
array_merge() will also reindex (see array_merge() manual entry), but the '+' operator won't, so...

<?php
$arrayone=array("newkey"=>"newvalue") + $arrayone;
?>

does the job.
TimHyde at C21Technology dot com 18-Jul-2002 05:04
A simpler way to implement an array_unshift with key=>value pairs (i.e. similar to the example using array_reverse above) is to use array_merge.  i.e.

<?php
$arrayone=array_merge(array("newkey"=>"newvalue"),$arrayone);
?>

Obviously you need to take care when adding numeric or duplicate keys.
robert dot wills at fuzzbrain dot uklinux dot net 07-Feb-2002 06:02
Actually this problem with the keys getting reindexed only happens when the keys are numerical:

<?php

$a = array("f"=>"five", "s" =>"six", "t" =>
        "twenty");

print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}

array_unshift($a, "zero");
print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}
?>

Array
(
    [f] => five
    [s] => six
    [t] => twenty
)

k: f v: five
k: s v: six
k: t v: twenty
Array
(
    [0] => zero
    [f] => five
    [s] => six
    [t] => twenty
)

k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
sahn at hmc dot edu 27-Jul-2001 12:21
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    $arr = array_reverse($arr, true);
    return count($arr);
}
?>
matt at synergie dot net 18-Sep-2000 10:20
The behaviour of unshift nearly caught me out.
Not only is the item added at the start of the list but the list is re-indexed too.

<?php

$a = array(5=>"five", 6 =>"six", 20 => "twenty");

while(list($key, $value) = each($a))
    echo "k: $key v: $value<BR>\n";

echo "<BR>\n";
array_unshift($a, "zero");

while(list($key, $value) = each($a))
    echo "k: $key v: $value<BR>\n";

?>

k: 5 v: five
k: 6 v: six
k: 20 v: twenty

k: 0 v: zero
k: 1 v: five
k: 2 v: six
k: 3 v: twenty
array_unique
array_values
Функции для работы с массивами


Выбирает все значения массива

array_unshift
array_walk_recursive
Функции для работы с массивами
PHP Manual

array_values

(PHP 4, PHP 5)

array_values — Выбирает все значения массива

Описание

array array_values ( array $input )

array_values() возвращает массив cо всеми элементами массива input. Она также заново индексирует возвращаемый массив числовыми индексами.

Список параметров

input

Массив.

Возвращаемые значения

Возвращает индексированный массив значений.

Примеры

Пример #1 Пример использования array_values()

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

Результат выполнения данного примера:

Array
(
    [0] => XL
    [1] => gold
)

Смотрите также

  • array_keys() - Возвращает все или некоторое подмножество ключей массива

User Contributed Notes

kapilgopinath at gmail dot com 09-Mar-2012 06:57
extract all values from a multi dimesnsional array or a nexted json object
function array_keys_multi($array,&$vals)
{
    foreach ($array as $key => $value) {

        if (is_array($value)) {

            array_keys_multi($value,$vals);

        }else{

            $vals[] = $value;
        }
    }

    return $vals;
}
Sheldon Hearn 23-Jan-2012 09:14
Note that the $input argument is not reindexed. The return value is.
a dot ross at amdev dot eu 30-May-2011 12:21
<?php
/**
 * Flattens an array, or returns FALSE on fail.
 */
function array_flatten($array) {
  if (!is_array($array)) {
    return FALSE;
  }
  $result = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $result = array_merge($result, array_flatten($value));
    }
    else {
      $result[$key] = $value;
    }
  }
  return $result;
}
?>
abimaelrc 10-May-2011 05:39
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
/**
 * Get all values from specific key in a multidimensional array
 *
 * @param $key string
 * @param $arr array
 * @return null|string|array
 */
function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}

$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        )
    ),
    'vegetable' => array(
        'carrot' => 'carrot2',
    ),
    'fruits' => 'fruits',
);

var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive('apple', $arr)); // null
var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
var_dump(array_value_recursive('pear', $arr)); // null
?>
aowie1 at gmail dot com 19-Jan-2011 12:23
I needed a function that recursively went into each level of the array to order (only the indexed) arrays... and NOT flatten the whole thing.

Solution:
<?php
function array_values_recursive($arr){
        $arr = array_values($arr);
        foreach($arr as $key => $val)
            if(array_values($val) === $val)
                $arr[$key] = array_values_recursive($val);

        return $arr;
}
?>
geo dot artemenko at gmail dot com 04-May-2010 12:37
same array_flatten function, compressed and preserving keys.

function array_flatten($a,$f=array()){
  if(!$a||!is_array($a))return '';
  foreach($a as $k=>$v){
    if(is_array($v))$f=array_flatten($v,$f);
    else $f[$k]=$v;
  }
  return $f;
}
Carsten Milkau 01-Nov-2009 04:46
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus "preserving keys" may have different interpretations. Ivan's function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.

<?php
/*
 * Flattening a multi-dimensional array into a
 * single-dimensional one. The resulting keys are a
 * string-separated list of the original keys:
 *
 * a[x][y][z] becomes a[implode(sep, array(x,y,z))]
 */

function array_flatten_sep($sep, $array) {
  $result = array();
  $stack = array();
  array_push($stack, array("", $array));

  while (count($stack) > 0) {
    list($prefix, $array) = array_pop($stack);

    foreach ($array as $key => $value) {
      $new_key = $prefix . strval($key);

      if (is_array($value))
        array_push($stack, array($new_key . $sep, $value));
      else
        $result[$new_key] = $value
    }
  }

  return $result;
}

/*
 * Flattening a multi-dimensional array into an
 * n-dimensional one. The last n keys of each element are
 * preserved. If this results in ambiguities, results are
 * undefined.
 *
 * a[x_1][x_2]...[x_m]  becomes  a[x_{m-n+1}]...[x_m]
 */
function array_flatten_n($array, $n) {
  $result = array();
  $stack = array();
  array_push($stack, array(array(), $array));

  while (count($stack) > 0) {
    list($prefix, $array) = array_pop($stack);

    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $new_prefix = array_values($prefix);
        array_push($new_prefix, $key);
        if (count($new_prefix) >= n)
          array_shift($new_prefix);

        array_push($stack, array($new_prefix, $value));
      } else {
        $array = $result;
        foreach ($prefix as $pkey) {
           if (!is_array($array[$pkey]))
             $array[$pkey] = array();
           $array = $array[$pkey];
        }
        $array[$key] = $value;
      }
    }
  }

  return $result;
}
?>
karl dot rixon at gmail dot com 18-Sep-2009 02:57
A modification of wellandpower at hotmail.com's function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.

<?php

function array_values_recursive($array) {
    $temp = array();
    foreach ($array as $key => $value) {
        if (is_numeric($key)) {
            $temp[] = is_array($value) ? array_values_recursive($value) : $value;
        } else {
            $temp[$key] = is_array($value) ? array_values_recursive($value) : $value;
        }
    }
    return $temp;
}

?>
id_ivan at yahoo dot com 08-Mar-2009 03:36
i missed one array value for mistakenly putting the recursive function outside the loop. so here is the corrected function:

<?php
    /* ---------------------
    * @function  array_flatten
    * @param     array
    * @since     0.1
    * @return    array
    * @notes     flatten associative multi dimension array recursive
    * @update    18:31 3/8/2009
    * @author    Rivanoor Bren <id_ivan(at)yahoo.com>
    ---------------------- */
    function array_flatten($array, $preserve = FALSE, $r = array()){
        foreach($array as $key => $value){
            if (is_array($value)){
                foreach($value as $k => $v){
                    if (is_array($v)) { $tmp = $v; unset($value[$k]); }
                }
                if ($preserve) $r[$key] = $value;
                else $r[] = $value;
            }
          // this is correct
          $r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
        }
        // wrong spot:
        // $r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
        return $r;
    }
?>
id_ivan at yahoo dot com 07-Mar-2009 07:29
I finally found a way to solve my problem with multidimension array and though to share it here. This function flatten multi dimension (associative/index) array recursively while maintaining the key with its value. You can see the example for a better explanation.

<?php
    /* ---------------------
    * @function  array_flatten
    * @param     array
    * @since     0.1
    * @return    array
    * @notes     flatten associative multi dimension array recursive
    * @update    22:02 3/7/2009
    * @author    Rivanoor Bren <id_ivan(at)yahoo.com>
    ---------------------- */
    function array_flatten($array, $preserve = FALSE, $r = array()){
        foreach($array as $key => $value){
            if (is_array($value)){
                foreach($value as $k => $v){
                    if (is_array($v)) { $tmp = $v; unset($value[$k]); }
                }
                if ($preserve) $r[$key] = $value;
                else $r[] = $value;
            }
        }
        $r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
        return $r;
    }

    print_r($tmp);
/* ---
Array
(
    [home] => Array
        (
            [id] => 1
            [pid] => 0
            [link] => home
            [subcat] =>
        )

    [works] => Array
        (
            [id] => 2
            [pid] => 0
            [link] => works
            [subcat] => Array
                (
                    [viz] => Array
                        (
                            [id] => 4
                            [pid] => 2
                            [link] => viz
                            [subcat] =>
                        )

                    [script] => Array
                        (
                            [id] => 5
                            [pid] => 2
                            [link] => script
                            [subcat] => Array
                                (
                                    [arch] => Array
                                        (
                                            [id] => 6
                                            [pid] => 5
                                            [link] => arch
                                            [subcat] =>
                                        )

                                )

                        )

                )

        )

    [blog] => Array
        (
            [id] => 3
            [pid] => 0
            [link] => blog
            [subcat] =>
        )

)

--- */

    print_r(array_flatten($tmp, 1));

/* ---
Array
(
    [home] => Array
        (
            [id] => 1
            [pid] => 0
            [link] => home
            [subcat] =>
        )

    [works] => Array
        (
            [id] => 2
            [pid] => 0
            [link] => works
        )

    [blog] => Array
        (
            [id] => 3
            [pid] => 0
            [link] => blog
            [subcat] =>
        )

    [viz] => Array
        (
            [id] => 4
            [pid] => 2
            [link] => viz
            [subcat] =>
        )

    [script] => Array
        (
            [id] => 5
            [pid] => 2
            [link] => script
        )

    [arch] => Array
        (
            [id] => 6
            [pid] => 5
            [link] => arch
            [subcat] =>
        )

)
--- */
?>
farum21 at hotmail dot com 03-Nov-2008 01:54
Spent a few hours today figuring out a more elegant way to flatten an array:

<?php

$aNonFlat = array(
    1,
    2,
    array(
        3,
        4,
        5,
        array(
            6,
            7
        ),
        8,
        9,
    ),
    10,
    11
);

$objTmp = (object) array('aFlat' => array());

array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);

var_dump($objTmp->aFlat);

/*
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
  [10]=>
  int(11)
}
*/

?>
Anonymous 07-Oct-2008 06:44
<?php
$array=array( 'value1'=>'value',
            'array1'=> array( 'subItem1'=>'subItem1',
                         'subItem2'=>'subItem2' ),
            'array2'=> array( 'subItem1'=>'subItem1' ));

$newArray=array();
array_flatten($array,$newArray);
print_r( $newArray );

//Output
//Array
//(
//    [value1] => value
//    [array1|subItem1] => subItem1
//    [array1|subItem2] => subItem2
//    [array2|subItem1] => subItem1
//)

// recursively reduces deep arrays to single-dimensional arrays
function array_flatten($array, &$newArray = Array() ,$prefix='',$delimiter='|') {
  foreach ($array as $key => $child) {
    if (is_array($child)) {
      $newPrefix = $prefix.$key.$delimiter;
      $newArray =& array_flatten($child, $newArray ,$newPrefix, $delimiter);
    } else {
      $newArray[$prefix.$key] = $child;
    }
  }
  return $newArray;
}
?>
chrysb at gmail dot com 24-Sep-2008 12:34
If you are looking for a way to count the total number of times a specific value appears in array, use this function:

<?php
function array_value_count ($match, $array)
{
    $count = 0;

    foreach ($array as $key => $value)
    {
        if ($value == $match)
        {
            $count++;
        }
    }

    return $count;
}
?>

This should really be a native function of PHP.
madhamster 12-Jun-2008 04:18
Good function, if you want to acces associative array element by position:

<?php

$array = array('fruit'=>'apple', 'juice'=>'orange', 'color'=>'lime');

$array = array_values($array);

echo $array[2];

?>
rene dot zak at post dot cz 24-Apr-2008 01:05
<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => ' ',
    'fruit4' => ' ',
    'fruit5' => 'apple');

    for ($i = 0; $i <  count($array); $i++) {
    $key=key($array);
    $val=$array[$key];
    if ($val<> ' ') {
       echo $key ." = ".  $val ." <br> ";
       }
     next($array);
    }

/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>
EA 01-Feb-2008 03:36
<?php
/*
  array array_use_keys ( array $array_data , array $array_keys)
*/
function array_use_keys(&$array_data, &$array_keys)
// pre: $array_data != array(NULL)
// post: read only rows from $array_data having values from $array_keys for keys
//       effective result: array{$array_data[$array_key[0]] .. $array_data[$array_key[n]]}
   {
      $resultarray = array();

      foreach($array_keys as $key) // $key is the value of a element in $array_keys which is going to be used as a key
         array_push($resultarray, $array_data[$key]); // note: array_push indexes with integers

      return($resultarray);
   }
?>

I only found the array_keys, yet it uses string, so I figured since I couldn't find a solution to make one of my own.
Hopefully this could make it into the next PHP in a improved array_keys;

PS
  There are no sane errorchecks, so beware.
bluej100 at gmail dot com 07-Sep-2007 10:10
Most of the array_flatten functions don't allow preservation of keys. Mine allows preserve, don't preserve, and preserve only strings (default).

<?
// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
  foreach ($array as $key => $child) {
    if (is_array($child)) {
      $newArray =& array_flatten($child, $preserve_keys, $newArray);
    } elseif ($preserve_keys + is_string($key) > 1) {
      $newArray[$key] = $child;
    } else {
      $newArray[] = $child;
    }
  }
  return $newArray;
}

// Tests

$array = Array(
  'A' => Array(
    1 => 'foo',
    2 => Array(
      'a' => 'bar'
    )
  ),
  'B' => 'baz'
);

echo 'var_dump($array);'."\n";
var_dump($array);
echo 'var_dump(array_flatten($array, 0));'."\n";
var_dump(array_flatten($array, 0));
echo 'var_dump(array_flatten($array, 1));'."\n";
var_dump(array_flatten($array, 1));
echo 'var_dump(array_flatten($array, 2));'."\n";
var_dump(array_flatten($array, 2));
?>
deceze at gmail dot YesThatsGoogleMail dot com 03-Sep-2007 12:31
Please note that 'wellandpower at hotmail.com's recursive merge doesn't work. Here's the fixed version:

<?php

function array_values_recursive($array) {
   $flat = array();

   foreach ($array as $value) {
           if (is_array($value)) $flat = array_merge($flat, array_values_recursive($value));
           else $flat[] = $value;
   }
   return $flat;
}

?>
warmo_at_o2_dot_pl 21-Mar-2007 10:42
@Yassin Ezbakhe <yassin88 at gmail dot com>
When we have to flatten multidimensional array of strings or numbers this method could be much faster.
Inconvenience of this method is, that its speed depends on size of strings/numbers, which array contains - bigger strings, lower efficiency.
Conclusion: Use this method for small amount of data in arrays (less than 500B per element in my case) which have many dimensions, in other case, use Yassin Ezbakhe method.

<?php

function md_implode($array, $glue = '')
{
    if (is_array ($array))
    {
        $output = '';
        foreach ($array as $v)
        {
            $output .= md_implode($v, $glue);
        }
        return $output;
    }
    else
    {
        return $array.$glue;
    }
}

function md_array_flatten($md_array)
{
    $flat_array = explode ('#|#',md_implode($md_array,'#|#')); // "#|#" is a sample delimiter
    array_pop($flat_array); // to remove last empty element
    return $flat_array;
}

//Usage:
$flat_array = md_array_flatten($some_md_array)

?>
ahigerd at stratitec dot com 24-Jan-2007 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
wellandpower at hotmail.com 29-Aug-2006 05:56
The function here flatterns an entire array and was not the behaviour I expected from a function of this name.

I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

In order to do this, you will want this function:

function array_values_recursive($array) {
   $temp = array();

   foreach ($array as $value) {
           if(is_array($value)) { $temp[] = array_values_recursive($value); }
           else { $temp[] = $value; }
   }
   return $temp;
}

Hopefully this will assist.
wizglins at gmx dot ch 13-Apr-2006 12:21
In case you want to replace all keys in multiarrays by integers starting at 0, the following function might help.

<?php

function numerieren($array)
{
$array_v = array_values($array);
$count_v = count($array_v);

for ($i=0; $i<$count_v; $i++)
  if (is_array($array_v[$i]))
    $array_v[$i] = numerieren($array_v[$i]);
return $array_v;
}

?>
Yassin Ezbakhe <yassin88 at gmail dot com> 31-Aug-2005 04:28
<?php
/**********************************************
 *
 *   PURPOSE: Flatten a deep multidimensional array into a list of its
 *   scalar values
 *
 *   array array_values_recursive (array array)
 *
 *   WARNING: Array keys will be lost
 *
 *********************************************/

function array_values_recursive($array)
{
    $arrayValues = array();

    foreach ($array as $value)
    {
        if (is_scalar($value) OR is_resource($value))
        {
             $arrayValues[] = $value;
        }
        elseif (is_array($value))
        {
             $arrayValues = array_merge($arrayValues, array_values_recursive($value));
        }
    }

    return $arrayValues;
}
?>

This function is an improved and faster version of the one posted by <27-Apr-2004 09:47>
kars at kde dot nl 24-May-2005 03:08
Also, objects in the array that were added by reference are handled correctly as well:

class Foo {
        var $n;

        function Foo ($n) {
                $this->n = $n;
        }
}

$a = new Foo(1);
$b = new Foo(2);
$c = new Foo(3);
$l = array(&$a, &$b, &$c); // add by reference
$m = array_values($l);

$a->n = 5;

echo $m[0]->n;

This prints "5" as you would expect.
27-Apr-2004 06:47
<?php
/**
   flatten an arbitrarily deep multidimensional array
   into a list of its scalar values
   (may be inefficient for large structures)
   (will infinite recurse on self-referential structures)
   (could be extended to handle objects)
*/
function array_values_recursive($ary)
{
   $lst = array();
   foreach( array_keys($ary) as $k ){
      $v = $ary[$k];
      if (is_scalar($v)) {
         $lst[] = $v;
      } elseif (is_array($v)) {
         $lst = array_merge( $lst,
            array_values_recursive($v)
         );
      }
   }
   return $lst;
}
?>

code till dawn!  -mark meves!
cyberphant0m AT earthlink DOT net 27-Feb-2004 09:24
That may be true, however I doubt that anyone should have that big of an array. If they do then they probably are doing some intense computing in which case, they may want to opt for the power of C++.
nopy at users dot sourceforge dot net 24-Oct-2003 03:36
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

For example, if your PHP momory_limits is 8MB,
 and says there's a BIG array $bigArray which allocate 5MB of memory.

Doing this will cause PHP exceeds the momory limits:

<?php
  $bigArray = array_values( $bigArray );
?>

It's because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.
03-Nov-2002 07:48
also useful to use for list(), if the array for input is the result of a function that only returns associative arrays:

list($var1, $var2, $var3) = array_values(myfunc("only returns assoc arrays"));
mailseppel at gmx dot de 04-Oct-2002 04:10
Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:

<?php
$row = mysql_fetch_array($db_result, $db_link);
?>

Hope I haven't misunderstood anything here.. :)
carl at thep.lu.se 29-Jan-2002 03:59
Indeed you can, and that's what's so great about it. I have, for instance, a function that returns the results of a database query as an array. I want to keep the order that the entries were returned in, but at the same time I want to be able to access them _either_ by the position _or_ by some other index (such as some sort of ID in the database, gotten from elsewhere). In this case, I can make the function return an array from id to [array of values], and by a simple call to array_values() this is transformed into an array indexed from 0 to count()-1. Useful.
richard at phpguru dot org 19-Dec-2001 12:56
If you have a numerically indexed array with some keys missing, ie 1, 2, 4, 5 and you want to reindex it so it's 1,2,3,4 *without changing the positions of the values* (ie sort()) then you can use this function to do it.
array_unshift
array_walk_recursive
Функции для работы с массивами


Рекурсивно применяет пользовательскую функцию к каждому элементу массива

array_values
array_walk
Функции для работы с массивами
PHP Manual

array_walk_recursive

(PHP 5)

array_walk_recursive — Рекурсивно применяет пользовательскую функцию к каждому элементу массива

Описание

bool array_walk_recursive ( array &$input , callable $funcname [, mixed $userdata = NULL ] )

Применяет пользовательскую функцию funcname к каждому элементу массива input. Эта функция обрабатывает каждый элемент многомерного массива.

Список параметров

input

Входной массив.

funcname

Обычно, funcname принимает два параметра. Первым параметром идет значение элемента массива input, а вторым - его ключ.

Замечание:

Если требуется, чтобы функция funcname изменила значения в массиве, определите первый параметр funcname как ссылку. Тогда все изменения будут применены к элементам массива.

userdata

Если указан необязательный параметр userdata, то он будет передан третьим параметром функции funcname.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования array_walk_recursive()

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

Результат выполнения данного примера:

a holds apple
b holds banana
sour holds lemon

Обратите внимание, что ключ 'sweet' никогда не отображается. Любой ключ, содержащий значение типа array, не будет передаваться в функцию.

Смотрите также

  • array_walk() - Применяет пользовательскую функцию к каждому элементу массива
  • информация о типе callback

User Contributed Notes

qfox at ya dot ru 25-Mar-2012 02:11
array_flatten example powered by array_walk_recursive

function array_flatten($nested, $preserve_keys = false) {
    $flat = array();
    $collector = $preserve_keys ? function ($v, $k) use (&$flat) {
        $flat[$k] = $v;
    } : function ($v) use (&$flat) {
        $flat[] = $v;
    };
    array_walk_recursive($paths, $nested);
    return $flat;
}
cyranix at cyranix dot com 28-Oct-2011 07:45
I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution.

<?php

    /**
     * Sets key/value pairs at any depth on an array.
     * @param $data an array of key/value pairs to be added/modified
     * @param $array the array to operate on
     */
    function setNodes($data, &$array)
    {
        $separator = '.'; // set this to any string that won't occur in your keys
        foreach ($data as $name => $value) {
            if (strpos($name, $separator) === false) {
                // If the array doesn't contain a special separator character, just set the key/value pair.
                // If $value is an array, you will of course set nested key/value pairs just fine.
                $array[$name] = $value;
            } else {
                // In this case we're trying to target a specific nested node without overwriting any other siblings/ancestors.
                // The node or its ancestors may not exist yet.
                $keys = explode($separator, $name);
                // Set the root of the tree.
                $opt_tree =& $array;
                // Start traversing the tree using the specified keys.
                while ($key = array_shift($keys)) {
                    // If there are more keys after the current one...
                    if ($keys) {
                        if (!isset($opt_tree[$key]) || !is_array($opt_tree[$key])) {
                            // Create this node if it doesn't already exist.
                            $opt_tree[$key] = array();
                        }
                        // Redefine the "root" of the tree to this node (assign by reference) then process the next key.
                        $opt_tree =& $opt_tree[$key];
                    } else {
                        // This is the last key to check, so assign the value.
                        $opt_tree[$key] = $value;
                    }
                }
            }
        }
    }

?>

Sample usage:

<?php

$x = array();
setNodes(array('foo' => 'bar', 'baz' => array('quux' => 42, 'hup' => 101)), $x);
print_r($x); // $x has the same structure as the first argument
setNodes(array('jif.snee' => 'hello world', 'baz.quux.wek' => 5), $x);
print_r($x); // added $x['jif']['snee'] and modified $x['baz']['quux'] to be array('wek' => 5)

?>
ghoffman at salientdigital dot com 13-Oct-2011 10:29
If you are wanting to change the values of an existing multi-dimensional array, as it says above in the note, you need to specify the first argument as a reference. All that means is, be sure to precede the $item variable with an ampersand (&) as in the good_example below.

Unfortunately the PHP example given doesn't do this. It actually took me a while to figure out why my function wasn't changing the original array, even though I was passing by reference.

Here's the tip: Don't return any value from the function! Just change the value of $item that you passed in by reference. This is rather counter-intuitive since the vast majority of functions return a value.

<?php
// array_walk_recursive fails to change your array unless you pass by reference.
// Don't return values from your filter function, even though it's quite logical at a glance!
function bad_example($item,$key){
   if($key=='test'){
       return 'PHP Rocks';  // Don't do it
   }else{
      return $item;  // Don't do this either
   }
}

// array_walk_recursive pass-by-reference example
function good_example(&$item,$key){
   if($key=='test'){
        $item='PHP Rocks'; // Do This!
   }
}

$arr = array('a'=>'1','b'=>'2','test'=>'Replace This');

array_walk_recursive($arr,'bad_example');
var_dump($arr);
/**
 * no errors, but prints...
 * array('a'=>'1','b'=>'2','test'=>'Replace This');
 */

array_walk_recursive($arr,'good_example');
var_dump($arr);
/**
 * prints...
 * array('a'=>'1','b'=>'2','test'=>'PHP Rocks');
 */

?>

Returning a value from your function does work if you pass by reference and modify $item before you return, but you will eat up memory very, very fast if you try it, even on an example as small as the one here.

One other silly thing you might try first is something like this:

<?php
// Resist the urge to do this, it doesn't work.
$filtered = array_walk_recursive($unfiltered,'filter_function');
?>

Of course, $filtered is just TRUE afterwards, not the filtered results you were wanting. Oh, it ran your function recursively alright, but changed all the values in the local function scope only and returns a boolean as the documentation states.
rob at yurkowski dot net 26-Oct-2010 11:16
If you don't really particularly care about the keys of an array, you can capture all values quite simply:

<?php

$sample = array('dog' => 'woof', 'cat' => array('angry' => 'hiss', 'happy' => 'purr'), 'aardvark' => 'kssksskss');
$output = array();

// Push all $val onto $output.
array_walk_recursive($sample, create_function('$val, $key, $obj', 'array_push($obj, $val);'), &output);

// Printing
echo nl2br(print_r($output, true));

/*
* Array
* (
*  [0] => woof
*  [1] => hiss
*  [2] => purr
*  [3] => kssksskss
* )
*/
?>

[EDIT BY danbrown AT php DOT net: In a note added by 'FaustoFilho' on 17-MAY-2011, the following information was appended to this note.

[If you intend to use this] "function to extract the last key value of an array, don't forget to insert a currency sign ($) signal before '$output' at 7th line.

This value must be a variable, and if you forgot to assign this signal, your code won't work, displaying an error like this:

Parse error: syntax error, unexpected ')', expecting T_PAAMAYIM_NEKUDOTAYIM in /path/to/script.php on line 7."]
bradbeattie at gmail dot com 27-Aug-2010 11:18
The description says "If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference." This isn't necessarily helpful as the function you're calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so.

<?php
    function trim_by_reference(&$string) {
        $string = trim($string);
    }
?>

The downside to this approach is that you need to create a wrapper function for each function you might want to call. Instead, we can use PHP 5.3's inline function syntax to create a new version of array_walk_recursive.

<?php
    /**
     * This function acts exactly like array_walk_recursive, except that it pretends that the function
     * its calling replaces the value with its result.
     *
     * @param $array The first value of the array will be passed into $function as the primary argument
     * @param $function The function to be called on each element in the array, recursively
     * @param $parameters An optional array of the additional parameters to be appeneded to the function
     *
     * Example usage to alter $array to get the second, third and fourth character from each value
     *     array_walk_recursive_referential($array, "substr", array("1","3"));
     */
    function array_walk_recursive_referential(&$array, $function, $parameters = array()) {
        $reference_function = function(&$value, $key, $userdata) {
            $parameters = array_merge(array($value), $userdata[1]);
            $value = call_user_func_array($userdata[0], $parameters);
        };
        array_walk_recursive($array, $reference_function, array($function, $parameters));
    }
?>

The advantage here is that we only explicitly define one wrapper function instead of potentially dozens.
devel at starosta dot org 12-Oct-2008 05:41
Nice system to make DB tree using function array_walk_recursive:

<?php
function _CategoriesTree(&$item, $key)
{
global $objDB;

  if ($key=="childs")
  {
    $res = $objDB->getAssoc('SELECT category_id, name,category_parent_id, category_id AS childs  FROM categories WHERE category_parent_id = '.$item.' ORDER BY orderid');
    if(!empty($res))
    {
      // walk inside subcategories
      $item = $res;
    }
    else
    {
      // equvalent => no childs
      $item = -1;
    }
  }
}

$categories = $objDB->getAssoc('SELECT category_id, name,category_parent_id, category_id AS childs  FROM categories WHERE category_parent_id = 0 ORDER BY orderid');  // fetchPairs -> value is the index
array_walk_recursive($categories, 'treeFunc',$objDB);

// test
print_r($categories);
?>
martin dot velek at gmail dot com 28-Sep-2008 02:01
If you will know that a tree in DB is not huge you can use array_walk_recursive to create tree structure e.g. in array.

let's assume following table:
NAME        PARENT
a                  null
b                  null
c                  null
a1               a
a2               a
b1               b
b11             b1
b111           b11

<?php
require_once 'Zend/Db/Adapter/Pdo/Sqlite.php';

function treeFunc(&$item, $key, $dbConn)
{
    $res = $dbConn->fetchPairs('SELECT name FROM tree where parent = ?',$key);
    if(!empty($res))
         $item = $res;
}

$arr = $dbConn->fetchPairs('SELECT name FROM tree where parent is null');  // fetchPairs -> value is the index

$valid = true;
while($valid)
{
       $oldCount  = count($arr,COUNT_RECURSIVE);
       array_walk_recursive($arr, 'treeFunc',$dbConn);
       $newCount = count($arr,COUNT_RECURSIVE);
       if ($oldCount == $newCount)  // if there is no change, exit...
                   $valid = false;
}
print_r($arr);
?>

--------------------------------------------------
Array
(
    [a] => Array
        (
            [a1] =>
            [a2] =>
        )

    [b] => Array
        (
            [b1] => Array
                (
                    [b11] => Array
                        (
                            [b111] =>
                        )

                )

        )

    [c] =>
)
amoffat at amoffat dot com 04-Jun-2008 05:15
<?
function my_array_map() {
    $args = func_get_args();
    $arr = array_shift($args);

    foreach ($args as $fn) {
        $nfn = create_function('&$v, $k, $fn', '$v = $fn($v);');
        array_walk_recursive($arr, $nfn, $fn);
    }
    return $arr;
}
?>

takes an array as the first argument, and functions as the other arguments.  it applies those functions recursively to the array
JW 14-Mar-2008 05:59
This function has a serious bug, which is still not fixed as of the PHP 5.2.5 release. After you call it, it can accidentally modify your original array. Save yourself hours of frustration by reading on.

The bug is here: http://bugs.php.net/bug.php?id=42850, and it looks like it will be fixed for 5.3.

If the array that you walk contains other array elements, they will be turned into references. This will happen even if the callback function doesn't take its first argument by reference, and doesn't do anything to the values.

For example, try this:
<?php
$data = array ('key1' => 'val1', 'key2' => array('key3' => 'val3'));
function foo($item, $key){}
var_dump($data);
?>

The original array has no references. Now try this:
<?php
array_walk_recursive($data,'foo');
var_dump($data);
?>

Now key2 is a reference, not just an array. So if you do this:
<?php
function test($item){$item['key2'] = array();}
test($data);
var_dump($data);
?>

you will see that test modifies $data, even though it shouldn't.

One workaround is to immediately make a deep copy of the array after calling array_walk_recursive, like this:
<?php
function array_duplicate($input) {
  if (!is_array($input)) return $input;
  $output = array();
  foreach ($input as $key => $value) {
    $output[$key] = array_duplicate($value);
  }
  return $output;
}
array_walk_recursive($data,'foo');
$data = array_duplicate($data);
var_dump($data);
?>

After doing that, the references are gone.
wileur at gmail dot com 06-Mar-2007 05:59
A simple way to use callback functions that are defined in a class is to simply pass the class instance and function names as values in an array:
<?php
class testClass {
    function callbackFunction($value, $key) {
        echo "$key: $value<br />\n";
    }
    function printArray($foo) {
        array_walk_recursive($foo, array($this, 'callbackFunction'));
    }
}
?>
adam dott pub att adamswick dott com 09-Nov-2006 06:08
Thanks to all of you in the prior posts.

I don't like the fact that the current version of array_walk_recursive() doesn't track all array keys.  This version will do that, as well as tracking array depth on multi-dimensional arrays.

- - - - - - -

Class Array_walk_recursive3 {

    private $depth = -1;
    private $userdata, $funcname;
    public $status;
    public $input;

    public function __construct($input, $funcname, $userdata = "") {
        $this->input = $input;
        $this->funcname = $funcname;
        $this->userdata = $userdata;
        $this->status = $this->array_walk_recursive($this->input);
    }

    private function test_print(&$value, &$key)
    {
        echo str_repeat("  ", $this->depth)."$key holds ";
        if (!is_array($value)) {
            echo $value;

            if (trim($value) == "banana") {
                $value = "cherry";
                $key = "c";
            }
        }
        echo "\n";

    }

    private function array_walk_recursive(&$input) {
        $funcname = array(&$this, $this->funcname);
       if (!is_callable($funcname)) {

           return false;
       }

       if (!is_array($input)) {
           return false;
       }

        $this->depth++;

       foreach (array_keys($input) AS $keyIdx => $key) {
            $saved_value = $input[$key];
            $saved_key = $key;
            call_user_func_array($funcname, array(&$input[$saved_key], &$key));

            if ($input[$saved_key] !== $saved_value || $saved_key !== $key) {
                $saved_value = $input[$saved_key];

                unset($input[$saved_key]);
                $input[$key] = $saved_value;
            }
           if (is_array($input[$key])) {
                if (!$this->array_walk_recursive($input[$key], $funcname)) return false;
                $this->depth--;
           }
       }
       return true;
    }

}

$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

$fruitObj = new Array_walk_recursive3($fruits, 'test_print');
echo $fruitObj->status;
$newFruitArr = $fruitObj->input;
print_r($fruits);
print_r($newFruitArr);
ik at paulkaspers dot nl 15-Oct-2006 01:46
To egingell at sisna dot com:

There is a small bug in your function, the following line should be changed:
From: if ($value != $saved_value || $saved_key != $key) {
Into: if ($value !== $saved_value || $saved_key !== $key) {

It's a nice function, because I was searching for something to change the keys of a multiple dimension array.
gieterke at gmail dot com 29-Mar-2006 04:59
I think there are a lot of people who want/have to work object oriented.
this is an Object oriented version

the code is written in PHP5
<?php
    //auto overload classes, so you don't have to put in all the includes
    function __autoload($class_name) {
        require_once $class_name . '.php';
    }

    echo "TESTING: arraywalker<br>";
    $anObject = new ClassName();

    //array_walk_recursive($anObject->getFruits(), 'test_print'); => doesn't work
    array_walk_recursive($anObject->getFruits(), array(&$anObject, 'test_print'));

    echo"<br><br>";
        //if you just want to give the array and not hte function name that handles the array
    $anObject->arrWalker($anObject->getFruits());
?>

<?php
//Class description---------------------------------------------
class ClassName {
    //Class variables
    private $sweet = array();
    private $fruits = array();

    //Constructor
    public function __construct(){
        $this->sweet = array('a' => 'apple', 'b' => 'banana');
        $this->fruits = array('sweet' => $this->sweet, 'sour' => 'lemon');
    }

    //public methods
    public function getFruits(){
        return $this->fruits;
    }

    public function test_print($item, $key){
        echo "$key holds $item\n<br>";
    }

    public function arrWalker($arr){
        array_walk_recursive($arr, array(&$this, 'test_print'));

    }
}
?>

the code above gives following input:
TESTING: arraywalker
a holds apple
b holds banana
sour holds lemon

a holds apple
b holds banana
sour holds lemon
egingell at sisna dot com 18-Mar-2006 01:53
Slightly modified version of array_walk_recursive function by "omega13a at sbcglobal dot net"

$function also modifies the keys in addition to the values.

Usefull if you want to trim() the keys and values of an array.

The $key in $funcname would also have to be passed by referrence.

Named 'array_walk_recursive2' since it is not the same as the PHP5 version, you can rename it to 'array_walk_recursive' if you are running PHP4 and have no reason to upgrade.

<?
function funcname(&$value, &$key, $userdata = "") {
    // Do stuff to $value and $key
}

function array_walk_recursive2(&$input, $funcname, $userdata = "") {
    if (!is_callable($funcname)) {
        return false;
    }

    if (!is_array($input)) {
        return false;
    }

    foreach ($input AS $key => $value) {
        if (is_array($input[$key])) {
            array_walk_recursive2($input[$key], $funcname, $userdata);
        } else {
            $saved_value = $value;
            $saved_key = $key;
            if (!empty($userdata)) {
                $funcname($value, $key, $userdata);
            } else {
                $funcname($value, $key);
            }

            if ($value != $saved_value || $saved_key != $key) {
                unset($input[$saved_key]);
                $input[$key] = $value;
            }
        }
    }
    return true;
}
?>
gabrielu at hotmail dot com 21-Feb-2006 01:13
I decided to add to the previous PHP 4 compatible version of array_walk_recursive() so that it would work within a class and as a standalone function.  Both instances are handled by the following function which I modified from omega13a at sbcglobal dot net.

The following example is for usage within a class.  To use as a standalone function take it out of the class and rename it.  (Example: array_walk_recursive_2)

<?php
class A_Class {

function array_walk_recursive(&$input, $funcname, $userdata = '') {
  if(!function_exists('array_walk_recursive')) {
    if(!is_callable($funcname))
      return false;

    if(!is_array($input))
      return false;

    foreach($input as $key=>$value) {
      if(is_array($input[$key])) {
        if(isset($this)) {
          eval('$this->' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
        } else {
          if(@get_class($this))
            eval(get_class() . '::' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
          else
            eval(__FUNCTION__ . '($input[$key], $funcname, $userdata);');
        }
      } else {
        $saved_value = $value;

        if(is_array($funcname)) {
          $f = '';
          for($a=0; $a<count($funcname); $a++)
            if(is_object($funcname[$a])) {
              $f .= get_class($funcname[$a]);
            } else {
              if($a > 0)
                $f .= '::';
              $f .= $funcname[$a];
            }
          $f .= '($value, $key' . (!empty($userdata) ? ', $userdata' : '') . ');';
          eval($f);
        } else {
          if(!empty($userdata))
            $funcname($value, $key, $userdata);
          else
            $funcname($value, $key);
        }

        if($value != $saved_value)
          $input[$key] = $value;
      }
    }
    return true;
  } else {
    array_walk_recursive($input, $funcname, $userdata);
  }
}

function kv_addslashes(&$v, $k) {
  $v = addslashes($v);
}
}
?>

Usage:
<?php
$arr = array(
  'a' => '"Hello World"',
  'b' => "'Hello World'",
  'c' => "Hello 'Worl\"d",
  'd' => array(
    'A' => 'H"e"l"l"o" "W"o"r"l"d'
    )
  );

$class = new A_Class();
$class->array_walk_recursive($arr, array(&$class, 'kv_addslashes'));
print_r($arr);
?>
omega13a at sbcglobal dot net 21-Dec-2005 04:21
This is a peice of code I wrote that appears to create this function for PHP 4.

<?php
if (!function_exists('array_walk_recursive'))
{
    function array_walk_recursive(&$input, $funcname, $userdata = "")
    {
        if (!is_callable($funcname))
        {
            return false;
        }

        if (!is_array($input))
        {
            return false;
        }

        foreach ($input AS $key => $value)
        {
            if (is_array($input[$key]))
            {
                array_walk_recursive($input[$key], $funcname, $userdata);
            }
            else
            {
                $saved_value = $value;
                if (!empty($userdata))
                {
                    $funcname($value, $key, $userdata);
                }
                else
                {
                    $funcname($value, $key);
                }

                if ($value != $saved_value)
                {
                    $input[$key] = $value;
                }
            }
        }
        return true;
    }
}
?>

Please note it is a conditionaly set function and will have to be put before any call to it.

If there is anything wrong with it, please email me.
cory at lavacube dot com 06-Dec-2005 02:09
A simple way to implement array_walk_recursive() in PHP 4 is to use to do the following...

<?php

// first, lets define our function
    function test_array_walkr( &$item, $key )
    {
        // do what you want to do here - in this example we will
        // check to see if $item is an array. If it is, we will
        // check to see if the key '.hide' exists. If this exists,
        // we will set the entire array to NULL;
        if( is_array($item) && array_key_exists('.hide', $item) )
        {
            $item = NULL;
        }

        // this is the code that causes the recursive effect
        // we do this after, to allow for any changes to $item
        // to be included in the next recursive call...
        if( is_array($item) )
        {
            array_walk($item, __FUNCTION__);
        }
    }

// next, let's define our array:
$test = array(
                'one'    => array('one->one', 'one->two', 'one->three'),
                'two'    => array('.hide'=>true, 'two->one', 'two->two', 'two->three'),
                'three'    => array('three->one', 'three->two', 'three->three')
            );

// lets run the test. ;-)
    array_walk($test, 'test_array_walkr');

// ... and get the results
    print_r($test);

?>

This example will yeild:
Array
(
    [one] => Array
        (
            [0] => one->one
            [1] => one->two
            [2] => one->three
        )
    [two] =>
    [three] => Array
        (
            [0] => three->one
            [1] => three->two
            [2] => three->three
        )
)

Hope this helps someone. :-)
aidan at php dot net 21-Feb-2005 11:10
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
hannes (at) tismer.com 14-Dec-2004 11:08
I wondered about an array_mergedown function working with PHP4, using an array_walk_recursive-like function which just merges any number of arrays of any dimension to a one dimension array containing every key=>value part of all arrays:

<?php
function array_mergedown() {
    global $outarray;
    $outarray = array();
    function array_walk_recphp4(&$val,$key) {
        global $outarray;
        if (is_array($val)) array_walk($val,'array_walk_recphp4');
        else {
            $outarray[$key] = $val;
        }
    }
    $params = func_get_args();
    foreach ($params as $subarr) {
        array_walk_recphp4($subarr, '');
    }
    return $outarray;
}
?>

For testing:

<?php
$arr1[]["foo1"] = "bar1";
$arr2["foo2"] = "bar2";
$arr2[12] = "bar3";
$arr2[10]["foo4"] = "bar4";
$arr2[]["foo4"][0]["foo5"] = "bar5";
$arr3 = "nono";

print_r(array_mergedown($arr1, $arr2, $arr3));
?>

returns:
Array ( [foo1] => bar1 [foo2] => bar2 [12] => bar3 [foo4] => bar4 [foo5] => bar5 )

I hope this helped someone :)
array_values
array_walk
Функции для работы с массивами


Применяет пользовательскую функцию к каждому элементу массива

array_walk_recursive
array
Функции для работы с массивами
PHP Manual

array_walk

(PHP 4, PHP 5)

array_walk — Применяет пользовательскую функцию к каждому элементу массива

Описание

bool array_walk ( array &$array , callable $funcname [, mixed $userdata = NULL ] )

Применяет пользовательскую функцию funcname к каждому элементу массива array.

array_walk() не подвержена влиянию внутреннего указателя массива array. array_walk() обойдёт все элементы массива независимо от позиции указателя.

Список параметров

array

Входной массив.

funcname

Обычно функция funcname принимает два параметра. В качестве первого параметра идет значение элемента массива array, а ключ - в качестве второго.

Замечание:

Если требуется, чтобы функция funcname изменила значения в массиве, определите первый параметр funcname как ссылку. Тогда все изменения будут применены к элементам оригинального массива.

Замечание:

Множество встроенных функций (например, strtolower()) выводят предупреждение, если им передано больше параметров, чем они ожидают, или которые не могут непосредственно использоваться в funcname.

Потенциально изменены могут быть только значения массива array; структура самого массива не может быть изменена, то есть нельзя добавить, удалить или поменять порядок элементов. Если callback-функция не соответствует этому требованию, поведение данной функции станет неопределённым и непредсказуемым.

userdata

Если указан необязательный параметр userdata, он будет передан в качестве третьего параметра в callback-функцию funcname.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Ошибки

Если функция funcname требует больше параметров, чем передано на самом деле, каждый раз, когда array_walk() будет вызывать funcname, будет генерироваться ошибка уровня E_WARNING. Эти предупреждения могут быть подавлены добавлением оператора управления ошибками PHP @ в вызов array_walk(), или использованием error_reporting().

Примеры

Пример #1 Пример использования array_walk()

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "До ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... и после:\n";

array_walk($fruits, 'test_print');
?>

Результат выполнения данного примера:

До ...:
d. lemon
a. orange
b. banana
c. apple
... и после:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

Смотрите также

  • array_walk_recursive() - Рекурсивно применяет пользовательскую функцию к каждому элементу массива
  • iterator_apply() - Вызывает функцию для каждого элемента в итераторе
  • create_function() - Создаёт анонимную (лямбда) функцию
  • list() - Присваивает переменным из списка значения подобно массиву
  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров
  • array_map() - Применяет callback-функцию ко всем элементам указанных массивов
  • информация о типе callback
  • foreach

User Contributed Notes

helloworld at gmail dot com 21-Mar-2012 10:53
To retrieve the userData parameter outside the function, you have to pass it by reference inside an array.
<?php
$customData = array();
$myArray = array('apple', 'orange', 'banana');
array_walk($myArray, 'myFunction', array(&$customData));

function myFunction(&$item, $index, $data)
{
    $data[0][$index] = strlen($item);
    // ...
}

print_r($customData);
?>
Output :
Array ( [0] => 5 [1] => 6 [2] => 6 )
manuscle at gmail dot com 06-Dec-2011 07:16
example with closures, checking and deleting value in array:

<?php
$array = array('foo' => 'bar', 'baz' => 'bat');

array_walk($array, function($val,$key) use(&$array){
    if ($val == 'bar') {
        unset($array[$key]);
    }
});

var_dump($array);
alex_stanhope at hotmail dot com 26-Oct-2011 01:16
I wanted to walk an array and reverse map it into a second array.  I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

<?php
$output = array();
array_walk($input, 'gmapmark_reverse', $output);

function gmapmark_reverse(&$item, $index, &$target) {
    $target[$item['form_key']] = $index;
}
?>

In my debugger I can see that $target is progressively updated, but when array_walk returns, $output is empty.  If however I use a (deprecated) call-by-reference:

<?php
array_walk($input, 'gmapmark_reverse', &$output);
?>

$output is returned correctly.  Unfortunately there's not an easy way to suppress the warnings:

<?php
@array_walk($input, 'gmapmark_reverse', &$output);
?>

doesn't silence them.  I've designed a workaround using a static array:

<?php
$reverse = array();
array_walk($input, 'gmapmark_reverse');
// call function one last time to get target array out, because parameters don't work
$reverse = gmapmark_reverse($reverse);

function gmapmark_reverse(&$item, $index = 0) {
  static $target;
  if (!$target) {
    $target = array();
  }
  if (isset($item['form_key'])) {
    $target[$item['form_key']] = $index;
  }
  return($target);
}
?>
tufanbarisyildirim at gmail dot com 05-Oct-2011 06:15
Filter an array by using key.

<?php
    $product_1 = 'test';
    $product_2 = 'test 2';

    function array_key_filter($array,$callback = 'trim')
    {
        $filtered = array();
        array_walk($array,function ($degeri,$degisken_adi) use (&$filtered,$callback)
        {
            if($callback($degisken_adi))
            {
                $filtered[$degisken_adi] =  $degeri;
            }
        });

        return $filtered;
    }

    #using

    $degiskenler = array_key_filter(get_defined_vars(),function($key)
    {
        return strpos($key,'product_') === 0;
    });

    print_r($degiskenler);
?>
output:

Array
(
    [product_1] => test
    [product_2] => test 2
)
Maxim 11-Jul-2011 12:23
Note that using array_walk with intval is inappropriate.
There are many examples on internet that suggest to use following code to safely escape $_POST arrays of integers:
<?php
array_walk($_POST['something'],'intval'); // does nothing in PHP 5.3.3
?>
It works in _some_ older PHP versions (5.2), but is against specifications. Since intval() does not modify it's arguments, but returns modified result, the code above has no effect on the array and will leave security hole in your website.

You can use following instead:
<?php
$_POST['something'] = array_map(intval,$_POST['something']);
?>
@jfredys 22-Mar-2011 05:07
I was looking for trimming all the elements in an array, I found this as the simplest solution:

<?php
array_walk($ids, create_function('&$val', '$val = trim($val);'));
?>
http://alex.moutonking.com/wordpress 15-Feb-2011 10:49
For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

<?php
$names = array("D\'Artagnan", "Aramis", "Portos");
array_walk($names, function(&$n) {
  $n = stripslashes($n);
});
?>

The trap with array_walk being it doesn't return the array, instead it's modified by reference.
op_adept at yahoo dot co dot uk 02-Dec-2010 03:20
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

<?php

function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){
    array_walk( $arr , "prefix", array($inner_glue, $prefix) );
    return implode($outer_glue, $arr);
}

function prefix(&$value, $key, array $additional){
    $inner_glue = $additional[0];
    $prefix = isset($additional[1])? $additional[1] : false;
    if($prefix === false) $prefix = $key;

    $value = $prefix.$inner_glue.$value;
}

//Example 1:
$order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC");
echo array_implode_prefix(",", $order_by, " ");
//Output: 3 ASC,2 DESC,7 ASC

//Example 2:
$columns = array("product_id", "category_id", "name", "description");
$table = "product";

echo array_implode_prefix(", ", $columns, ".", $table);
//Output:product.product_id, product.category_id, product.name, product.description

//Example 3 (function prefix) won't really be used on its own
$pre= "vacation";
$value = "lalaland";
prefix($value, $pre, array("."));
echo $value;

//Output: vacation.lalaland

?>
AskApache 30-Oct-2010 12:27
Here's a handy function that illustrates using an array_walk that uses a create_function as the callback which in turn uses another array_walk with another create_function that outputs the global variables pretty-print style.

Note that by using $g=array() as the first arg for array_walk it isn't necessary to declare the array beforehand.

Other notes:  ob_start, (print), and array_walk all return true on success which is how the if processing works.

Using <?php !!$array; ?> returns true only if sizeof array is greater than 0, just a shortcut for <?php if(sizeof($array)>0);?> ... more in the php manual section on booleans.

The output is meant to be displayed inline on a page so the htmlspecialchars is called on the output.  The output is buffered by ob_start and is then output by echoing the return of ob_get_clean(), which returns the buffer and cleans the buffer.

DEBUG would need to be a defined constant for this to execute, personally I like to
<?php
if($_SERVER['REMOTE_ADDR']=='MYSTATICIPADDRESS') askapache_global_debug();
//or
if($_SERVER['REMOTE_ADDR']=='MYSTATICIPADDRESS') define('DEBUG',TRUE);
?>

<?php

function askapache_global_debug()
{
array_walk(
 $g=array('_GET','_POST','_COOKIE','_SESSION','_ENV','_SERVER'),
   create_function('$n','global $$n;
    if(
      !!$$n
      && ob_start()
      && (print "( $"."$n )\n")
      && array_walk($$n,
       create_function(\'&$v,$k\', \'echo "[$k] => $v\n";\'))
     )
    echo "<pre>".htmlspecialchars(ob_get_clean())."</pre>";'
   )
);
}
if(DEBUG) askapache_global_debug();

?>
matthew at codenaked dot org 02-Sep-2010 11:24
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the "glue" string as the optional userdata parameter. The following example is used to zip an array of email headers:

<?php

/**
 * Zip together the keys and values of an array using the provided glue
 *
 * The values of the array are replaced with the new computed value
 *
 * @param array $data
 * @param string $glue
 */
function zip(&$data, $glue=': ')
{
    if(!is_array($data)) {
        throw new InvalidArgumentException('First parameter must be an array');
    }

    array_walk($data, function(&$value, $key, $joinUsing) {
        $value = $key . $joinUsing . $value;
    }, $glue);
}

$myName = 'Matthew Purdon';
$myEmail = 'matthew@example.com';
$from = "$myName <$myEmail>";

$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Return-path'] = "<$myEmail>";
$headers['X-Mailer'] = "PHP" . phpversion() . "";
$headers['Content-Type'] = 'text/plain; charset="UTF-8"';

zip($headers);

$headers = implode("\n", $headers);
$headers .= "\n";

echo $headers;

/*
From: Matthew Purdon <matthew@example.com>
Reply-To: Matthew Purdon <matthew@example.com>
Return-path: <matthew@example.com>
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset="UTF-8"
*/
?>
arekandrei at yandex dot ru 03-Jan-2010 07:30
You can use lambda function as a second parameter:

<?php
array_walk($myArray, function(&$value, $key){
    // if you want to change array values then "&" before the $value is mandatory.
});
?>

Example (multiply positive values by two):

<?php
$myArray = array(1, 2, 3, 4, 5);

array_walk($myArray, function(&$value, $index){
    if ($value > 0) $value *= 2;
});
?>
rustamabd at gmail dot com 13-Dec-2009 06:32
Don't forget about the array_map() function, it may be easier to use!

Here's how to lower-case all elements in an array:

<?php
    $arr = array_map('strtolower', $arr);
?>
Zigbigidorlu 06-Oct-2009 10:45
I tried this function to create safe SQL arrays when I'm creating query strings from keywords, but I found it to be too bulky for my purposes.  So, instead I created this function:

<?php

 //Create a SQL safe array
 function mysql_safe_array($array)
 {
    $array = array();
    foreach($array as $item)
    {
        $safe = mysql_real_escape_string($item);
        array_push($array,$safe);
        unset($safe);
    }
    return $array;
 }

 //Example usage
 $keywords = explode(" ",$_GET['keywords']);

 $keywords = mysql_safe_array($keywords);

 $query_s = implode("%' AND `field` LIKE '%",$keywords);
 $query = "`description` LIKE '%$query_s%'";
 $query = stripslashes(implode(" ",$query));
?>
erelsgl at gmail dot com 04-Mar-2009 03:40
If you want to unset elements from the callback function, maybe what you really need is array_filter.
jab_creations_-at_-yahoo_-dot-_com 26-Nov-2008 04:08
Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function...

<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");

print_r($fruits);
echo '<br />';

function name_base($key)
{
 $name2 = str_replace(" ", "_", $key);
 $name3 = str_replace("&", "and", $name2);
 $name4 = strtolower($name3);
 echo $name4.'<br />';
 return $name4;
}
echo '<br />';

$test = array_map('name_base', $fruits);
$fruits_fixed = $test;
echo '<br />';
print_r($fruits_fixed);
?>
peterzuzek AT gmail DOT com 16-Nov-2008 09:04
I had some problems using this function - it didn't want to apply PHP-defined functions. So I decided to write my own - here it is. I had to use some generic-programming skills, didn't really checked the speed (I think it could be slow)... I believe it could be much better, but I don't know, how - well, I guess multiple array support and recursion would be nice. So?

Prototype:
bool arrayWalk(array &$arry, callback $callback, mixed $params=false)

<?php

    function arrayWalk(&$arry, $callback, $params=false) {
        $P=array(""); // parameters
        $a=""; // arguement string :)

        if($params !== false) { // add parameters
            if(is_array($params)) { // multiple additional parameters
                foreach($params as $par)
                    { $P[]=$par; }
            }
            else // just one additional
                { $P[]=$params; }
        }

        for( // create the arguement string
            $i=0; isset($P[$i]); ++$i
        )
            { $a.='$'.chr($i + 97).', '; } // random argument names

        $a=substr($a, 0, -2); // to get rid of the last comma and two spaces

        $func=create_function($a, 'return '.$callback.'('.$a.');'); // the generic function

        if(is_callable($func)) {
            for( // cycle through array
                $i=0; isset($arry[$i]); ++$i
            ) {
                $P[0]=$arry[$i]; // first element must be the first argument - array value
                $arry[$i] = call_user_func_array($func, $P); // assign the new value obtained by the generic function
            }
        }
        else
            { return false; } // failure - function not callable

        return true; // success!
    } // arrayWalk()

?>

One big problem I've noticed so far - for example, if you wanted to use str_replace on the array, you'd fail - simply because of the arguement order of str_replace, where the string modified is the third arguement, not the first as arrayWalk requires.

So, still some work left...
diyism 30-Oct-2008 11:18
When i pass the third parameter by reference in php5.2.5,
happened this: Warning: Call-time pass-by-reference has been deprecated - argument passed by value...

And to set allow_call_time_pass_reference to true in php.ini won't work, according to http://bugs.php.net/bug.php?id=19699   thus to work around:

<?php
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_") {$arr_rtn[0]["_".$v[\'ID\']]=$v; unset($arr_rtn[0][$k]);}'), array(&$arrChnOut));
?>
diyism 22-Oct-2008 04:04
Although the manual warned you not to unset element, but sometimes thus is very useful and work as charm:

<?php
$arrChnOut=array(0=>array('ID' => '13',
                          'ChannelName' => 'Computers'
                         ),
                 1=>array('ID' => '17',
                          'ChannelName' => 'Computers'
                         ),
                 2=>array('ID' => '18',
                          'ChannelName' => 'Computers'
                         ),
                );
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_"){$arr_rtn["_".$v[\'ID\']]=$v;unset($arr_rtn[$k]);}'), &$arrChnOut);
var_export($arrChnOut);
?>
example at user dot com 06-Sep-2008 08:10
On array_walk and create_function used within a class scope - Anonymous functions are out of scope.  So, if you want to access $this within the anonymous function, you'd have to pass it through the third parameter...

<?php

// example copies all values into $this where key is the same as property name

array_walk($array, create_function('$v,$k,&$that', 'if (property_exists($that,$k)) {$that->$k = $v;}'), $this);

// or, switch it around and array_walk the object

array_walk($this, create_function('&$v,$k,$array','if (array_key_exists($k,$array)) {$v = $array[$k];}'), $array);

?>
harmor 09-May-2008 12:23
I just wanted a function to trim all the array elements.  Here is a non-recursive version:

<?php
$data = array('       a',' b','    c        d   ');

function _trim(&$value)
{
    $value = trim($value);
}

function array_trim($arr)
{
    array_walk($arr,"_trim");
    return $arr;
}

$arr = array_trim($data);

echo '<pre>';
var_dump($arr);
echo '</pre>';

$single = implode(' ',$arr);

echo '<pre>';
var_dump($single);
echo '</pre>';
?>

Output:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(10) "c        d"
}

string(14) "a b c        d"
mike >> mike AT debitage.com 06-Mar-2008 12:01
<?php
   /**
    *    class.ArrayTool.php lets you search an array based on key => value pairs
    *
    *   @version 1.0
    *   @ 1-11-2008
    *   @author Mike Volmar
    *
    *    Object for converting between array key and value
    *
    */

class ArrayTool {

    var $mydata = array();
    var $flag = 0;
    var $results;

    function ArrayTool(){

    }

    function tellAll(){
        print_r($this->mydata);
    }

    function setArray($data){
        $this->mydata = $data;
    }

    function getKey($input){
        foreach($this->mydata as $key => $value){
            if(($this->flag == 0)&&($input == $value)){
                $this->results = $key;
                $this->flag = 1;
            }
        }
        $this->flag = 0;
        return $this->results;
    }

    function getValue($input){
        foreach($this->mydata as $key => $value){
            if(($this->flag == 0)&&($input == $key)){
                $this->results = $value;
                $this->flag = 1;
            }
        }
        $this->flag = 0;
        return $this->results;
    }

}

?>
jerk at yoosic dot de 21-Dec-2006 08:05
if you want to modify every value of an multidimensional array use this function used here:

<?php

$array = array (1=>1, 2=> 2, 3 => array(1=>11, 2=>12, 3=>13));
$text = "test";

function modarr(&$array, $text) {
        foreach ($array as $key => $arr) {
                if(is_array($arr)) $res[$key] = modarr(&$arr,$text);
                // modification function here
                else $res[$key] = $arr.$text;
                }
        return $res;
}

$erg = modarr($array, $text);

print_r($erg);

?>

result will be_

<?php
Array ( [1] => 1test [2] => 2test [3] => Array ( [1] => 11test [2] => 12test [3] => 13test ) )
?>
nihaopaul at nihaopaul dot com 06-May-2006 03:59
no sure if this should go under array-walk but it does what i need, it searches a multidimensionial array by using an array to walk it, it either returns a value or an array.

<?php
function walker($walk, $array) {
    if (count($walk) >0) {
        foreach($array as $key => $value) {
            if ($key == $walk[0]) {
                if (is_array($value)) {
                    unset($walk[0]);
                    return walker(array_values($walk), $value);
                } else {
                    if (isset($value)) {
                        if (count($walk) == 1) {
                            return $value;
                        } else {
                            return 0;
                        }
                    } else {
                        return 0;
                    }
                }
            }
        }
        return 0;
    } else {
        return $array;
    }
}
?>
ludvig dot ericson at gmail dot com 21-Nov-2005 06:09
In response to 'ibolmo', this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

<?php
function string_walk(&$string, $funcname, $userdata = null) {
    for($i = 0; $i < strlen($string); $i++) {
        # NOTE: PHP's dereference sucks, we have to do this.
        $hack = $string{$i};
        call_user_func($funcname, &$hack, $i, $userdata);
        $string{$i} = $hack;
    }
}

function yourFunc($value, $position) {
    echo $value . ' ';
}

function yourOtherFunc(&$value, $position) {
    $value = str_rot13($value);
}

# NOTE: We now need this ugly $x = hack.
string_walk($x = 'interesting', 'yourFunc');
// Ouput: i n t e r e s t i n g

string_walk($x = 'interesting', 'yourOtherFunc');
echo $x;
// Output: vagrerfgvat
?>

Also note that calling str_rot13() directly on $x would be much faster ;-) just a sample.
ibolmo 17-Nov-2005 07:53
If anyone is interested to implement the array_walk functionality to a string. I've made this handy function. Note that this can be easily extended for any type of purpose. I've used this to convert from a string of bytes to a hex string then back from hex to a byte string.
<?php
function string_walk($string,$funcname)
{
    for($i=0;$i<strlen($string);$i++) {
        call_user_func($funcname,$string{$i});
    }
}

function yourFunc($val)
{
    echo $val.' ';
}

string_walk('interesting','yourFunc');
//ouput: i n t e r e s t i n g
?>
thomas dot hebinck at digionline dot de 31-Oct-2005 06:07
This is a short way to concatenate a string to each element of an array:

$arr=array(1,2,3,4,5,6,7,8,9,0);
$str=' test'; // must not include ' or " ...

array_walk($arr,create_function('&$elem','$elem .= "' . $str . '";'));

var_export($arr);

The output is:
array ( 0 => '1 test', 1 => '2 test', 2 => '3 test', 3 => '4 test', 4 => '5 test', 5 => '6 test', 6 => '7 test', 7 => '8 test', 8 => '9 test', 9 => '0 test', )
Andrzej Martynowicz at gmail dot com 18-Sep-2005 06:03
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

<?php
function enumerate( &$item1, $key, &$startNum ) {
   $item1 = $startNum++ ." $item1";
}

$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', $num );

print_r( $fruits );

echo '$num is: '. $num ."\n";
?>

This outputs:

Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 1

Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter..

<?php
$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', &$num ); // reference here

print_r( $fruits );

echo '$num is: '. $num ."\n";
echo "we've got ". ($num - 1) ." fruits in the basket!";
?>

This outputs:
Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 5
we've got 4 fruits in the basket!

Now $num has changed so we are able to count the items (without calling count() unnecessarily).

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.
webmaster at tmproductionz dot com 18-Jul-2005 12:54
to the note right before this one.  that will only trim leading and trailing white space. if you want to trim white space inside the string (ie 'hello     world' to 'hello world') you should use this:

$val = preg_replace ( "/\s\s+/" , " " , $val ) ;

this will also trim leading and trailing white space.
el_porno at web dot de 27-May-2005 03:03
You want to get rid of the whitespaces users add in your form fields...?
Simply use...:

class SomeVeryImportantClass
{
...
    public function mungeFormData(&$data)
    {
        array_walk($data, array($this, 'munge'));
    }

    private function munge(&$value, &$key)
    {
        if(is_array($value))
        {
            $this->mungeFormData($value);
        }
        else
        {
            $value = trim($value);
        }
    }
...
}

so...
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc
caliban at darklock dot com 23-May-2005 10:33
> I believe this relies on the deprecated runtime
> pass-by-reference mechanism

The array() keyword is a language construct, not a function, so I don't think this is applicable.
Enlightened One 07-Apr-2005 11:17
Beware that "array ($this, method)" construct. If you're wanting to alter members of the "$this" object inside "method" you should construct the callback like this:

  $callback[] = &$this;
  $callback[] = method;
  array_walk ($input, $callback);

Creating your callback using the array() method as suggested by "appletalk" results in a copy of $this being passed to method, not the original object, therefor any changes made to the object by method will be lost when array_walk() returns. While you could construct the callback with "array(&$this, method)", I believe this relies on the deprecated runtime pass-by-reference mechanism which may be removed in future releases of PHP. Better to not create a dependence on that feature now than having to track it down and fix it in the future.
Hayley Watson 16-Jan-2005 06:27
As well as being able to pass the array the callback will be working on by reference, one can pass the optional userdata parameters by reference also:
<?php

function surprise($x,$key,$xs)
{
    //$key is unused here.
    $x.='!';
    array_push($xs,$x);
}

$array1 = array('this','that','the other');
$array2 = array();

array_walk($array1,'surprise',&$array2);

print_r($array1);
print_r($array2);
?>
Of course, that precise example would be better handled by array_map, but the principle is there.
memandeemail at gmail dot com 11-Nov-2004 05:24
If you are using array_walk on a class, dont will work

so ... try this on your own class:

class your_own_class {
    /**
    * @return void
    * @param array $input
    * @param string $funcname
    * @desc A little workaround, do the same thing.
    */
    function array_walk($input, $funcname) {
        foreach ($input as $key => $value) $this->$funcname($value, $key);
    }
}
04-Nov-2004 11:22
If array_walk_recursive() is not present and you want to apply htmlentities() on each array element you can use this:

<?php
function array_htmlentities(&$elem)
{
  if (!is_array($elem))
  {
    $elem=htmlentities($elem);
  }
  else
  {
    foreach ($elem as $key=>$value)
      $elem[$key]=array_htmlentities($value);
  }
  return $elem;
} // array_htmlentities()
?>

If you want to output an array with print_r() and you have html in it this function is very helpful.
lgaga dot dont dot spam at muszaki dot info 16-Oct-2004 07:31
Behaviour like array_walk_recursive() can be achieved in php <=5 by a callback function to array_walk() similar to this:

function walkcallback(&$val,$key) {
    if (is_array($val)) array_walk($val,'walkcallback',$new);
    else {
        // do what you want with $val and $key recursively
    }
}
bisqwit at iki dot fi 03-Sep-2004 04:54
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.
paul at heliosville dot com 03-Sep-2004 12:13
one rather important note that was lost in the Great PHP Doc Note Purge of '04 is that you can call methods using array_walk(). Let's assume that we have a class named 'Search', in which there is a method called 'convertKeywords'. Here's how you would call that convertKeywords method from inside the class:

    array_walk($keywords, array($this, 'convertKeywords'));

Notice that, instead of giving a string as the second argument, you give an array with two items: the variable that holds the class (in this case, $this), and the method to call. Here's what it would look like if you were to call convertKeywords from an already-instantiated class:

    $search = new Search;
    array_walk($keywords, array($search, 'convertKeywords'));
Eierkoek 03-Sep-2004 06:46
normaly the $_GET array will add slashes to the array values. To remove all slashes in this array, i created the folowing code

  set_magic_quotes_runtime (0);
  function StripAllSlashes (&$ArrayGET, $Value)
  {
    if (is_array ($ArrayGET)) array_walk ($ArrayGET, "StripAllSlashes");
    else $ArrayGET = stripslashes ($ArrayGET);
  }
  if (isset ($_GET) && get_magic_quotes_gpc ()) array_walk ($_GET, "StripAllSlashes");

I hope this code was usefull,

Eierkoek
array_walk_recursive
array
Функции для работы с массивами


Создает массив

array_walk
arsort
Функции для работы с массивами
PHP Manual

array

(PHP 4, PHP 5)

array — Создает массив

Описание

array array ([ mixed $... ] )

Создает массив. Подробнее о массивах читайте в разделе "Массивы".

Список параметров

...

Синтаксис "индекс => значения", разделённые запятыми, определяет индексы и их значения. Индекс может быть строкой или целым числом. Если индекс опущен, будет автоматически сгенерирован числовой индекс, начиная с 0. Если индекс - число, следующим сгенерированным индексом будет число, равное максимальному числовому индексу + 1. Обратите внимание, что если определены два одинаковых индекса, последующий перезапишет предыдущий.

Наличие висячей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.

Возвращаемые значения

Возвращает массив параметров. Параметрам может быть назначен индекс с помощью оператора =>. Подробнее о массивах читайте в разделе "Массивы".

Примеры

Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.

Пример #1 Пример использования array()

<?php
$fruits = array (
    "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);
?>

Пример #2 Автоматическая индексация с помощью array()

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

Результат выполнения данного примера:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Обратите внимание, что индекс '3' определён дважды, и содержит последнее значение 13. Индекс 4 определён после индекса 8, и следующий сгенерированный индекс (значение 19) - 9, начиная с максимального индекса 8.

Этот пример создаёт массив, нумерация которого начинаяется с 1.

Пример #3 array(), нумерация которого начинаяется с 1

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

Результат выполнения данного примера:

Array
(
    [1] => January
    [2] => February
    [3] => March
)

Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.

Пример #4 Доступ к массиву внутри двойных кавычек

<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>

Примечания

Замечание:

array() является языковой конструкцией, используемой для представления литеральных массивов, и не является обычной функцией.

Смотрите также

  • array_pad() - Дополнить размер массива определенным значением до заданной величины
  • list() - Присваивает переменным из списка значения подобно массиву
  • count() - Подсчитывает количество элементов массива или что-то в объекте
  • range() - Создает массив, содержащий диапазон элементов
  • foreach
  • Тип массив

User Contributed Notes

qeremy 07-Mar-2012 02:50
Some tricky functions;

<?php
function is_array_assoc($arr) {
    if (is_array($arr)) {
        foreach ($arr as $k => $v) {
            if (is_string($k) || (is_int($k) && $k < 0)) {
                return 1;
            }
        }
        return 0;
    }
    return -1;
}

function is_array_multi($arr) {
    return is_array($arr)
        ? (count($arr) != count($arr, COUNT_RECURSIVE) ? 1 : 0)
        : -1;
}

$arr[] = array("foo", "bar", 1.09);
$arr[] = array("red", "yellow", 1 => "foo");
$arr[] = array("red", "yellow", -1 => "foo");
$arr[] = array("x" => array("red", "yellow"), "y" => array("one", "two"));
$arr[] = array();
$arr[] = "s";

foreach ($arr as $a) {
    echo is_array_assoc($a) ."\n";
}
echo "\n";
foreach ($arr as $a) {
    echo is_array_multi($a) ."\n";
}
?>

0
0
1
1
0
-1

0
0
0
1
0
-1

<?php
function array_count($arr) {
    $r = 0;
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r++;
        }
    }
    return $r;
}

function array_count_all($arr, $r = 0) {
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r = array_count_all($v, $r);
            $r++;
        }
    }
    return $r;
}

$a = array("foo", "bar", 1.09, array(1,2,3), array("a" => "aaa"));
echo array_count($a); // 2

$a = array(
    "foo", "bar", 1.09,
    "x" => array(1,2,3),
    array("a" => "aaa", "b" => array(), "c" => array(""), "d" => array("")),
    "e" => array(""),
    "z" => array(""),
    "q" => array("", array()),
    "w" => array("lorem", 1 => "impsum", 18, "dolor", array("last as 11th array"))
);
echo array_count_all($a); // 11
?>
r0h4rd at gmail dot com 06-Feb-2011 02:59
"Quick and dirty" class to get an offset of multidimensional array by given path (sorry, that without comments).

<?php

    class ArrayAsPathException extends Exception {}

    class ArrayAsPath {
        protected
            $data = array(),
            $separator = '.';

        public function __construct (array $data = array()) {
            $this->data = $data;
        }

        public function set ($value, $path = null) {
            if (!isset($path)) {
                $this->data = $value;
            }

            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            $code = '';
            $pices = '[\''.$pathtoken.'\']';
            while ($pathtoken !== false) {
                if (($pathtoken = strtok($separator)) !== false) {
                    $code .= 'if (!isset($this->data'.$pices.')) $this->data'.$pices.' = array(); ';
                    $pices .= '[\''.$pathtoken.'\']';
                } else {
                    $code .= 'return $this->data'.$pices.' = $value;';
                }
            }

            return eval($code);
        }

        public function get ($path = '', $default = null) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    if (isset($default)) {
                        return $default;
                    }

                    throw new ArrayAsPathException ('Can\'t find "'.$pathtoken.'" in "'.$path.'"');
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return $result ? $result : $default;
        }

        public function has ($path) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    return false;
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return true;
        }

        public function setSepatator ($separator) {
            $this->separator = $separator;
        }

        public function getSeparator ($separator) {
            return $this->separator;
        }
    }

?>

Code:
<?php

    $params = new ArrayAsPath;
    $params->set(array(
        'foo' => array(
            'bar' => array(
                'item' => 'Value'
            )
        )
    ));

    try {
        $params->set('test', 'foo.bar.far.new');
        printf(
            'Array:<pre>%s</pre>
            foo.bar.item:<pre>%s</pre>
            foo.bar.far:<pre>%s</pre>
            foo.bar.far.new<pre>%s</pre>',
            var_export($params->get(), true),
            var_export($params->get('foo.bar.item'), true),
            var_export($params->get('foo.bar.far'), true),
            var_export($params->get('foo.bar.far.new'), true)
        );
    } catch (ArrayAsPathException $e) {
        echo 'Oops! It seems that something is wrong. '.$e->getMessage();
    }

?>

Will display:
Array:
array (
  'foo' =>
  array (
    'bar' =>
    array (
      'item' => 'Value',
      'far' =>
      array (
        'new' => 'test',
      ),
    ),
  ),
)

foo.bar.item:
'Value'

foo.bar.far:
array (
  'new' => 'test',
)

foo.bar.far.new:
'test'
contact at dot REMOVETHIS dot erikmaas dot com 21-Dec-2010 01:17
A array_peek function as no excists yet:
<?php
function array_peek($array) {
    return $array[(count($array)-1)];
}
?>
eugene at ultimatecms dot co dot za 03-Mar-2010 06:29
This is a useful way to get foreign key variables from a specific sql table.
This function can be used to include all relevant data from all relating tables:

<?php
function get_string_between($string, $start, $end){
         $string = " ".$string;
         $ini = strpos($string,$start);
         if($ini == 0)
                return $tbl;
         $ini += strlen($start);
         $len = strpos($string,$end,$ini) - $ini;
         return substr($string,$ini,$len);
}

function get_foreign_keys($tbl) {
        $query = query_getrow("SHOW CREATE TABLE ".mysql_escape_string($tbl));

        $dat = explode('CONSTRAINT',$query[1]);
        foreach($dat as $d => $a) {
                if(strpos($a,"FOREIGN KEY"))
                $data['keys'][] = array($tbl,get_string_between($a,"` FOREIGN KEY (`","`) REFERENCES"));
        }

        foreach($dat as $d => $a) {
                if(strpos($a,"REFERENCE"))
                $data['references'][] = explode('` (`',get_string_between($a,"REFERENCES `","`) ON"));
        }
        return $data;
}

//Example code:

        $data = get_foreign_keys('task_table');
        echo '<pre>';
        print_r($data);
        echo '</pre>';

?>

// $query[1] outputs:

CREATE TABLE `task_table` (
  `task_id` int(64) NOT NULL auto_increment,
  `ticket_id` int(64) NOT NULL,
  `task_type` varchar(64) NOT NULL,
  `comment` text,
  `assigned_to` int(11) default NULL,
  `dependant` int(64) default NULL,
  `resolved` int(1) default NULL,
  PRIMARY KEY  (`task_id`),
  KEY `ticket_id` (`ticket_id`,`dependant`),
  KEY `assigned_to` (`assigned_to`),
  KEY `task_dependant` (`dependant`),
  CONSTRAINT `task_table_ibfk_1` FOREIGN KEY (`ticket_id`) REFERENCES `tickets_table` (`ticket_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_2` FOREIGN KEY (`assigned_to`) REFERENCES `contact_table` (`contact_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_3` FOREIGN KEY (`dependant`) REFERENCES `task_table` (`task_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

// $data outputs:
Array (
    [keys] => Array
        (
            [0] => Array
                (
                    [0] => task_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => task_table
                    [1] => assigned_to
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => dependant
                )
        )

    [references] => Array
        (
            [0] => Array
                (
                    [0] => tickets_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => contact_table
                    [1] => contact_id
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => task_id
                )
        )
)
mail at leonardomartinez dot com 10-Oct-2009 01:39
<?php
function array_two_key_swap( $multidimensional_array ) {

    /*
        Writen by: Leonardo Martinez

        Created: 10-10-2009
        Modified: 10-15-2009

        This function takes a two dimensional array[x][y], swaps the first
        key with the second key so the values can be referenced using array[y][x].

        Example:
                    samplearray['directiory'][0] = "myicons";
                    samplearray['directiory'][1] = "myicons";
                    samplearray['directiory'][2] = "myiconsold";
                    samplearray['directiory'][3] = "myiconsold";

                    samplearray['filename'][0] = "hat.png";
                    samplearray['filename'][1] = "dog.png";
                    samplearray['filename'][2] = "mice.png";
                    samplearray['filename'][3] = "rat.png";

        The above array converts to:

                    newarray[0]['filename']     = "hat.png"
                    newarray[0]['directiory']     = "myicons"
                    newarray[1]['filename']     = "dog.png"
                    newarray[1]['directiory']     = "myicons"
                    newarray[2]['filename']     = "mice.png"
                    newarray[2]['directiory']     = "myiconsold"
                    newarray[3]['filename']     = "rat.png"
                    newarray[3]['directiory']     = "myiconsold"

    */

    $keys = array_keys( $multidimensional_array );

    $array_swaped = array();

    foreach($multidimensional_array[$keys[0]] as $key_counter => $value1) {

        $temp_array = array();

        foreach($keys as $key) {
            $temp_array[$key] = $multidimensional_array[$key][$key_counter];
        }

        $array_swaped[] = $temp_array;
    }

    return $array_swaped;
}
?>
kamil at navikam dot pl 03-Jun-2009 03:42
Easy function to unarray an array :-)
It will make $array['something'] => $something.
Usefull for making code more clear.

example of use:
<?
function unarray($row) {
    foreach($row as $key => $value) {
        global $$key;
        $$key = $value;
    }
}

$sql = mysql_query("SELECT * FROM `pracownicy`");
while ($row = mysql_fetch_assoc($sql)) {
    unarray($row);
    echo $idpracownika.'<br>'; //instead of $row['idpracownika']
}
?>
Marcel dot Glacki at stud dot fh-swf dot de 27-Apr-2009 03:49
I encountered the following but didn't see it documented/reported anywhere so I'll just mentioned it here.

As written in the manual:
"When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1".

This generated index has always the largest integer used as a key so far. So adding $a[5] = 'foo'; after an $a[10] = 'bar'; will not force the next generated index to be 6 but to be 11 as 10 was the highest index encountered until here.

Anyway, the following can happen:
<?php
$max_int = 2147483647; // Max value for integer on a 32-bit system
$arr = array();

$arr[1] = 'foo'; // New generated index will be 2
$arr[ $max_int ] = 'bar'; // Caution: Next generated index will be -2147483648 due to the integer overflow!
$arr[0] = 'bar'; // The highest value should be 2147483648 but due to the i-overflow it is -2147483648 so current index 0 is larger. The new generated index therefore is 1!
$arr[]  = 'failure'; // Warning: Cannot add element to the array as the next element is already occupied.
?>
alwynlobo at gmail dot com 03-Mar-2009 11:03
Here's an example on how to create a multi-dimensional array...(without using ArrayObject)

<?php
$characters = array(array(array(
                array ( name=>"name 1",
                        occupation=>"Developer",
                        age=>30,
                        specialty=>"Java" ),
                array ( name=>"name 2",
                        occupation=>"Programmer",
                        age=>24,
                        specialty=>"C++" ),
                array ( name=>"name 3",
                        occupation=>"Designer",
                        age=>63,
                        specialty=>"Javascript" )))
);

print $characters[0][0][2][occupation];
?>
jonberglund at gmail dot com 07-Jul-2008 09:25
The following function (similar to one above) will render an array as a series of HTML select options (i.e. "<option>...</option>"). The problem with the one before is that there was no way to handle <optgroup>, so this function solves that issue.

function arrayToSelect($option, $selected = '', $optgroup = NULL)
{
    $returnStatement = '';

    if ($selected == '') {
        $returnStatement .= '<option value="" selected="selected">Select one...</option>';
    }

    if (isset($optgroup)) {
        foreach ($optgroup as $optgroupKey => $optgroupValue) {
            $returnStatement .= '<optgroup label="' . $optgroupValue . '">';

            foreach ($option[$optgroupKey] as $optionKey => $optionValue) {
                if ($optionKey == $selected) {
                    $returnStatement .= '<option selected="selected" value="' . $optionKey . '">' . $optionValue . '</option>';
                } else {
                    $returnStatement .= '<option value="' . $optionKey . '">' . $optionValue . '</option>';
                }
            }

            $returnStatement .= '</optgroup>';
        }
    } else {
        foreach ($option as $key => $value) {
            if ($key == $selected) {
                $returnStatement .= '<option selected="selected" value="' . $key . '">' . $value . '</option>';
            } else {
                $returnStatement .= '<option value="' . $key . '">' . $value . '</option>';
            }
        }
    }

    return $returnStatement;
}

 So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an <optgroup> label. So, with this function, if only a single array is passed to the function (i.e. "arrayToSelect($stateList)") then it will simply spit out a bunch of "<option>" elements. On the other hand, if two arrays are passed to it, the second array becomes a "key" for translating the first array.

Here's a further example:

$countryList = array(
    'CA'        => 'Canada',
    'US'        => 'United States');

$stateList['CA'] = array(
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'MB'        => 'Manitoba',
    'NB'        => 'New Brunswick',
    'NL'        => 'Newfoundland/Labrador',
    'NS'        => 'Nova Scotia',
    'NT'        => 'Northwest Territories',
    'NU'        => 'Nunavut',
    'ON'        => 'Ontario',
    'PE'        => 'Prince Edward Island',
    'QC'        => 'Quebec',
    'SK'        => 'Saskatchewan',
    'YT'        => 'Yukon');

$stateList['US'] = array(
    'AL'        => 'Alabama',
    'AK'        => 'Alaska',
    'AZ'        => 'Arizona',
    'AR'        => 'Arkansas',
    'CA'        => 'California',
    'CO'        => 'Colorado',
    'CT'        => 'Connecticut',
    'DE'        => 'Delaware',
    'DC'        => 'District of Columbia',
    'FL'        => 'Florida',
    'GA'        => 'Georgia',
    'HI'        => 'Hawaii',
    'ID'        => 'Idaho',
    'IL'        => 'Illinois',
    'IN'        => 'Indiana',
    'IA'        => 'Iowa',
    'KS'        => 'Kansas',
    'KY'        => 'Kentucky',
    'LA'        => 'Louisiana',
    'ME'        => 'Maine',
    'MD'        => 'Maryland',
    'MA'        => 'Massachusetts',
    'MI'        => 'Michigan',
    'MN'        => 'Minnesota',
    'MS'        => 'Mississippi',
    'MO'        => 'Missouri',
    'MT'        => 'Montana',
    'NE'        => 'Nebraska',
    'NV'        => 'Nevada',
    'NH'        => 'New Hampshire',
    'NJ'        => 'New Jersey',
    'NM'        => 'New Mexico',
    'NY'        => 'New York',
    'NC'        => 'North Carolina',
    'ND'        => 'North Dakota',
    'OH'        => 'Ohio',
    'OK'        => 'Oklahoma',
    'OR'        => 'Oregon',
    'PA'        => 'Pennsylvania',
    'RI'        => 'Rhode Island',
    'SC'        => 'South Carolina',
    'SD'        => 'South Dakota',
    'TN'        => 'Tennessee',
    'TX'        => 'Texas',
    'UT'        => 'Utah',
    'VT'        => 'Vermont',
    'VA'        => 'Virginia',
    'WA'        => 'Washington',
    'WV'        => 'West Virginia',
    'WI'        => 'Wisconsin',
    'WY'        => 'Wyoming');

...

<select name="state" id="state"><?php echo arrayToSelect($stateList,'',$countryList) ?></select>
<select name="country" id="country"><?php echo arrayToSelect($countryList,'US') ?></select>
sebasg37 at gmail dot com 12-Feb-2008 11:32
Recursive function similar to print_r for describing anidated arrays in html <ol>. Maybe it's useful for someone.

<?php
function describeAnidatedArray($array)
{
    $buf = '';
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $buf .= '<ol>' . describeAnidatedArray($value) . '</ol>';
        }
        else
            $buf .= "<li>$value</li>";
    }
    return $buf;
}

// Example:
$array = array("a", "b", "c", array("1", "2", array("A", "B")), array("3", "4"), "d");

echo describeAnidatedArray($array);
?>

output:

# a
# b
# c

   1. 1
   2. 2
         1. A
         2. B

   1. 3
   2. 4

# d
jon hohle 16-Nov-2007 05:12
Here are shorter versions of sam barrow's functions. From a PHP perspective these are O(1) (without getting into what's going on in the interpreter), instead of O(n).

<?php
function randomKey(array $array)
{
    return randomElement(array_keys($array));
}

function randomElement(array $array)
{
    if (count($array) === 0)
    {
        trigger_error('Array is empty.',  E_USER_WARNING);
        return null;
    }

    $rand = mt_rand(0, count($array) - 1);
    $array_keys = array_keys($array);

    return $array[$array_keys[$rand]];
}
?>
sam barrow 13-Nov-2007 10:46
check out these functions - retrieves a random element or key of an array (numeric or string indexes, doesn't matter).

function randomKey(array $array)
    {
        global $mod, $plg, $sec ;

        $rand = rand(0, count($array) - 1) ;

        $counter = 0 ;
        foreach (array_keys($array) as $key)
            {
                if ($counter++ == $rand)
                    {
                        return $key ;
                    }
            }

        trigger_error('Array is empty.', E_USER_WARNING) ;
    }

function randomElement(array $array)
    {
        global $mod, $plg, $sec ;

        $rand = rand(0, count($array) - 1) ;

        $counter = 0 ;
        foreach ($array as $value)
            {
                if ($counter++ == $rand)
                    {
                        return $value ;
                    }
            }

        trigger_error('Array is empty.', E_USER_WARNING) ;
    }
Mike Mackintosh 29-Oct-2007 09:38
If you need to add an object as an array key, for example an object from Simple XML Parser, you can use the following.

File.XML
<?xml version="1.0" encoding="UTF-8"?>
<Settings type="General">
  <Setting name="SettingName">This This This</Setting>
</Settings>

The script:
<?php
$raw = $xml =  new SimpleXMLElement('File.XML');
foreach($raw->Setting as $A => $B)
{
    // Set Array From XML
    $Setting[(string) $B['name']] = (string)  $B[0];
}
?>
By telling the key to read the object as a string, it will let you set it.

Hope this helps someone out!
Sam Yong - hellclanner [at] live dot com 27-Oct-2007 05:39
I wanted to put a large range of numbers into an array but it seems to me that the array function don't have that kind of ability for me to put in a range of numbers without having to list down every single number.

Here's my solution:
<?php

function arr_range($r1,$r2){

// the end range is smaller than the start range
// switch around
if($r2 < $r1){
$t = $r1;
$r1 = $r2;
$r2 = $t;
unset($t);
}

$return_val = array();
$i = 0;

// for each value of the range
// add the value into the temparory array
for($i = $r1;$i<=$r2;$i++){
$return_val[] = $i;
}

// return the values in array form
return $return_val;
}

// example usages
$values = arr_range(100,6000);
$values = arr_range(1996,2010);
$values = arr_range(50,25); // it works
$values = arr_range(-64,1024);

?>
Christian W. 17-Aug-2007 02:27
If you already created an associative array you can add a new element by:

<?php
$arr = array("foo" => 1);
print_r($arr);

$arr["bar"] = 2;
print_r($arr);
?>

Output:
Array
(
    [foo] => 1
)
Array
(
    [foo] => 1
    [bar] => 2
)
admin at baungenjar dot com 14-May-2007 06:11
I wrote the code below to load values from a query, than save them to two variables, code and text. It is used to replace values using str_replace.

The tricky part(for me) was building the two variables from a query.

//grab available classes - table of id numbers and //corresponding titles
$class_values = mysql_query($sql_classes);

// grab avaialable book conditions
$condition_values = mysql_query($sql_conditions);

// build conversion tables
// one for class one for coinditoion

    $condcode = array();
    $condtext = array();
    $classcode = array();
    $classtext = array();
        $i=0;

  while ($row=mysql_fetch_row($condition_values)){
        //echo $row[0]." ".$row[1];
    $condcode[$i] =$row[0];
    $condtext[$i] =$row[1];
        $i++;
  }
    $i=0;
  while ($row=mysql_fetch_row($class_values)){
        //echo $row[0]." ".$row[1];
    $classcode[$i] = $row[0];
    $classtext[$i] = $row[1];
        ++$i;
  }

// there is no output, but now four arrays exist .
//there are four becuase theycame from two tables
// now i call

//example:
echo str_replace($classcode,$classtext,1);

//would output
Algebra

//
webmaster at phpemailformprocessor dot com 06-Aug-2006 09:48
When using an array to create a list of keys and values for a select box generator which will consist of states I found using "NULL" as an index and ""(empty value) as a value to be useful:

<?php

$states = array(
    0    => 'Select a State',
    NULL => '',
    1    => 'AL - Alabama',
    2    => 'AK - Alaska',
    # And so on ...
);

$select = '<select name="state" id="state" size="1">'."\r\n";

foreach($states as $key => $value){
    $select .= "\t".'<option value="'.$key.'">' . $value.'</option>'."\r\n";
}

$select .= '</select>';

echo $select;

?>

 This will print out:

<select name="state" id="state" size="1">
    <option value="0">Select a State</option>
    <option value=""></option>
    <option value="1">AL - Alabama</option>
    <option value="2">AK - Alaska</option>
    # And so on ...

</select>

Now a user has a blank value to select if they later decide to not provide their address in the form. The first two options will return TRUE when checked against the php function - EMPTY() after the form is submitted when processing the form
Craig at frostycoolslug dot com 25-Jul-2006 04:39
Just a helpful note, when creating arrays, avoid doing:

<?php
  $var[key] = "value";
?>

PHP will look for a constant called 'key' before it will treat it as a string, thus slowing down execution (I've seen files with thousands of these and PHP taking over a second to execute).

Always concider switching on E_NOTICE before releasing any PHP, it'll help avoid making simple mistakes.
jupiter at nospam dot com 02-Jun-2006 03:33
<?php

// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
  if ($asc == 1) {  // use first subarrays for new keys of arrays
    $multiarraykeys = array_reverse($multiarray, true);
  } else {  // use the last array keys
    $multiarraykeys = $multiarray;  // use last subarray keys
  }  // end array reordering
  $newarraykeys = array();  // establish array
  foreach ($multiarraykeys as $arrayvalue) {  // build new array keys
    if (is_array($arrayvalue)) {  // is subarray an array
      $newarraykeys = array_keys($arrayvalue) + $newarraykeys;
    }  // if count(prevsubarray)>count(currentarray), extras survive
  }  // end key building loop
  foreach ($multiarray as $newsubarraykey => $arrayvalue) {
    if (is_array($arrayvalue)) {  // multiarray element is an array
      $i = 0;  // start counter for subarray key
      foreach ($arrayvalue as $subarrayvalue) {  // access subarray
        $newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
        $i++;  // increase counter
      }  // end subarray loop
    } else {  // multiarray element is a value
      foreach ($newarraykeys as $newarraykey) {  // new subarray keys
        $newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
      }  // end loop for array variables
    }  // end conditional
  }  // end new multiarray building loop
  return $newmultiarray;
}

// will change
$old = array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new = array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
  'f'=>array('a'=>1,'b'=>3,'d'=>5));

// note: if $asc parameter isn't default, last subarray keys used

?>

The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
bill at carneyco dot com 02-Feb-2006 08:42
I wanted to be able to control the flow of data in a loop instead of just building tables with it or having to write 500 select statements for single line items. This is what I came up with thanks to the help of my PHP brother in FL. Hope someone else gets some use out it.
<?

//set array variable
$results = array();

//talk to the db
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());

//count the rows and fields
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);

//start the loop
for ( $i = 0; $i < $totalRows; ++$i ) {

//make it 2 dim in case you change your order
  $results[$i] = mysql_fetch_array($result);

//call data at will controlling the loop with the array
echo $results[your_row_id]['your_field_name']; }

//print the entire array to see what lives where
print_r($results);  ?>
php 07-Jan-2006 03:30
This function converts chunks of a string in an array:

function array_str($str, $len) {
  $newstr = '';
  for($i = 0; $i < strlen($str); $i++) {
    $newstr .= substr($str, $i, $len);
  }
  return $newstr;
}

use it as:

$str = "abcdefghilmn";
echo "<table width=\"100%\">\n";
foreach(array_str($str, 4) as $chunk) {
  echo "<tr><td>".$chunk."</td></tr>\n";
}
echo "</table>";

this prints:

------
abcd
------
efgh
------
ilmn
------

It don't use regular expressions. Please add this function to php :)
James 24-Nov-2005 01:04
re: m.izydorski 29-May-2005 07:17

The reason the code snippet below is "very slow" is because the backtick (`) is a shell call delimiter, not a string delimiter. Every element of the array would be executed as a shell call and the result stored as array elements.

<?
// Very slow:
$my_array = array(`sign`, `cat01`, `cat02`, ... , `cat40`,`terra01`, `terra02`, ... , `terra50`);
?>

See the backtick operator page for more information:
http://uk2.php.net/manual/en/language.operators.execution.php
matthiasDELETETHIS at ansorgs dot de 31-May-2005 02:52
How to use array() to create an array of references rather than of copies? (Especially needed when dealing with objects.) I played around somewhat and found a solution: place & before the parameters of array() that shall be references. My PHP version is 4.3.10.

Demonstration:

<?php
$ref1 = 'unchanged';
$ref2 = & $ref1;

$array_of_copies = array($ref1, $ref2);
print_r($array_of_copies); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_copies[0] = 'changed'; // $ref1 = 'changed'; is not equivalent, as it was _copied_ to the array
print_r($array_of_copies); // prints: Array ( [0] => changed [1] => unchanged )

$array_of_refs = array(& $ref1, & $ref2); // the difference: place & before arguments
print_r($array_of_refs); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_refs[0] = 'changed'; // $ref1 = 'changed'; is equivalent as $array_of_refs[0] references $ref1
print_r($array_of_refs, true); // prints: Array ( [0] => changed [1] => changed )
?>
m dot izydorski at anti_spa_m dot rubikon dot pl 29-May-2005 12:17
Ad. rdude's comment

Additionally, there is a performance loss while one are using ` marks instead ' when creating an array:

<?
//Very slow:
$my_array = array(`sign`, `cat01`, `cat02`, ... , `cat40`,`terra01`, `terra02`, ... , `terra50`);

//Much faster:
$my_array = array('sign', 'cat01', 'cat02', ... , 'cat40', 'terra01', 'terra02', ... , 'terra50');
?>

There is no reason to use ` marks (as I know), but this is a default question mark used in query output in phpMyAdmin. If you copy-paste phpMyAdmin query display, you can encounter serious performance problem.
aissatya at yahoo dot com 16-May-2005 01:48
<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
<?php
$fruits = array (
   "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
   "numbers" => array(1, 2, 3, 4, 5, 6),
   "holes"  => array("first", 5 => "second", "third")
);
?>
brian at blueeye dot us 21-Apr-2005 05:34
If you need, for some reason, to create variable Multi-Dimensional Arrays, here's a quick function that will allow you to have any number of sub elements without knowing how many elements there will be ahead of time. Note that this will overwrite an existing array value of the same path.

<?php
// set_element(array path, mixed value)
function set_element(&$path, $data) {
    return ($key = array_pop($path)) ? set_element($path, array($key=>$data)) : $data;
}
?>

For example:

<?php
echo "<pre>";
$path = array('base', 'category', 'subcategory', 'item');
$array = set_element($path, 'item_value');
print_r($array);
echo "</pre>";
?>

Will display:
Array
(
    [base] => Array
        (
            [category] => Array
                (
                    [subcategory] => Array
                        (
                            [item] => item_value
                        )
                )
        )
)
mortoray at ecircle-ag dot com 18-Feb-2005 05:35
Be careful if you need to use mixed types with a key of 0 in an array, as several distinct forms end up being the same key:

$a = array();
$a[null] = 1;
$a[0] = 2;
$a['0'] = 3;
$a["0"] = 4;
$a[false] = 5;
$a[0.0] = 6;
$a[''] = 7;
$a[] = 8;

print_r( $a );

This will print out only 3 values: 6, 7, 8.
rdude at fuzzelish dot com 17-Feb-2005 01:35
If you are creating an array with a large number of static items, you will find serious performance differences between using the array() function and the $array[] construct. For example:
<?
 // Slower method
 $my_array = array(1, 2, 3, � 500);

 // Faster method
 $my_array[] = 1;
 $my_array[] = 2;
 $my_array[] = 3;
 �
 $my_array[] = 500;
?>
michael dot bommarito at gmail dot com 15-Jan-2005 07:14
Just in case anyone else was looking for some help writing an LU decomposition function, here's a simple example.

N.B. All arrays are assumed to begin with index 1, not 0.  This is not hard to change, but make sure you specify array(1=>...), not just array(...).

Furthermore, this function is optimized to only consider variable elements of the matrices.  As $L will be a lower triangular matrix, there is no need to compute the elements of either the diagonal or the upper triangle; likewise with $U.

This function also does not check to verify that the input matrix is non-singular.

/*
 * LU Decomposition
 * @param $A initial matrix (1...m x 1...n)
 * @param $L lower triangular matrix, passed by reference
 * @param $U upper triangular matrix, passed by reference
*/
function LUDecompose($A, &$L, &$U) {
    $m = sizeof($A);
    $n = sizeof($A[1]);

    for ( $i = 1; $i <= $m; $i++ ) {
        $U[$i][$i] = $A[$i][$i];

        for ( $j = $i + 1; $j <= $m; $j++ ) {
            $L[$j][$i] = $A[$j][$i] / $U[$i][$i];
            $U[$i][$j] = $A[$i][$j];
        }
        for ( $j = $i + 1; $j <= $m; $j++ ) {
            for ( $k = $i + 1; $k <= $m; $k++ ) {
                $A[$j][$k] = $A[$j][$k] - ($L[$j][$i] * $U[$i][$k]);
            }
        }
    }

    return;
}
phpm at nreynolds dot me dot uk 11-Jan-2005 08:24
This helper function creates a multi-dimensional array. For example, creating a three dimensional array measuring 10x20x30: <?php $my_array = multi_dim(10, 20, 30); ?>

<?php

function multi_dim()
{
    $fill_value = null;

    for ($arg_index = func_num_args() - 1; $arg_index >= 0; $arg_index--) {
        $dim_size = func_get_arg($arg_index);
        $fill_value = array_fill(0, $dim_size, $fill_value);
    }

    return $fill_value;
}

?>
stephen[AT]brooksie-net[DOT]co[DOT]uk 17-Dec-2004 04:57
I think I may have found a simpler, slightly more logical route to solving the previous problem. I came across this solution when retreving data from MySql which in most cases was for individual bits of data, but also needed to reference a set of sub data from a second table.

<?php

// -------------------------------------------------------
// Function: db_get_data()
// Desc: Build array of data from mysql table and sub table(s)
// PreCondition: None
// Returns: Array of rows / sub rows from db,
// -------------------------------------------------------

function db_get_data()
{
    $ar_sub = array();

    /* [ .... code for connecting and querying DB .... ] */

    // Retireve from first table
    $row = mysql_fetch_row($result);

    // Get first two fields
    $ar_details['item0'] = $row ['field0'];
    $ar_details['item1'] = $row ['field1'];

    // Using result from query on sub table
    // for each sub row, 'push' data on sub array
    while($row_sub = mysql_fetch_array($result_sub))
    {
        array_push($ar_sub, $row_sub['sub_field']);
    }

    // Add sub array as element of parent array
    $ar_details['item3'] = $ar_sub;

    return $ar_details;
}

// -------------------------------------------------------
// Retrieving array data
// -------------------------------------------------------

// Call function
$arr_details = db_get_data()

// Output Data
echo $ar_details['item1'];
echo $ar_details['item2'];

// For each record in sub array....
for($i=0; $i<count($ar_details['item3']); $i++)
{
    echo $ar_details['item3'][$i];
}

?>

For extra sub tables the process can be repeated by adding more sub arrays, and each sub array can hold as much data as you like. Therefore allowing you to build an ever expanding tree as required. If you have the option I would recommend using nested classes though :)
baZz 16-Oct-2003 03:27
Chek this out!!!. Suppose that you want to create an array like the following:
<?php
  $arr1 = (
    0 => array ("customer"=>"Client 1","Item a"),
    1 => array ("customer"=>"Client 2","Item b")
  );
?>
Seems prety easy, but what if you want to generate it dinamically woops!!!.  Imagine that you have a file with thousands of lines and each line is a purchase order from diferent clients:
<?php
/*function to add elements*/
function addArray(&$array, $id, $var)
{
    $tempArray = array( $var => $id);
    $array = array_merge ($array, $tempArray);
}
/*The same as above but the element is an array*/
function addArrayArr(&$array, $var, &$array1)
{
    $tempArray = array($var => $array1);
    $array = array_merge ($array, $tempArray);
}
/*labels of our array or heders of the file*/
$keyarr = array("customer","item");
/*info that may you read from a file line 1 and 2*/
$valarr0 = array("Client 1","Item a");
$valarr1 = array("Client 2","Item b");

$numofrows = 2;/*In our case is just two lines*/
$tmpArray = array();
for($i = 0; $i < $numofrows; $i++){
  $tmp = "valarr$i";
  $tmpvar = ${$tmp};/*Using var of vars tricky tricky*/
  foreach( $keyarr as $key=>$value){
    addArray($tmparr,$tmpvar[$key],$value);
  }
  addArrayArr($finalarr,$i,$tmparr);
} /*voila all it's perfectly ordered on finalarr*/

/*Here we just print the info but you can insert it into a database*/
echo "Customer: ".$finalarr[0]["customer"]."<br>";
echo "Item: ".$finalarr[0]["item"]."<br>";
echo "Customer: ".$finalarr[1]["customer"]."<br>";
echo "Item: ".$finalarr[1]["item"]."<br>";
?>

The lines above should print something like:
Customer: Client 1
Item: Item a
Customer: Client 2
Item: Item b
I hope someone find this useful.
TCross1 at hotmail dot com 03-Sep-2003 12:38
here is the sort of "textbook" way to output the contents of an array which avoids using foreach() and allows you to index & iterate through the array as you see fit:

<?php

$arrayName = array("apples", "bananas", "oranges", "pears");
$arrayLength = count($arrayName);

for ($i = 0; $i < $arrayLength; $i++){
    echo "arrayName at[" . $i . "] is: [" .$arrayName[$i] . "]<br>\n";
}

?>

enjoy!

-tim
darthjarkon at hotmail dot com 09-Jul-2003 11:09
I found a slightly better way to create large 2d arrays:

<?php
// this will simply output a 2d array-- it isn't very robust but it
//suits my needs here
function display_all($array){
    echo "<table><tr>";
    foreach($array as $spot){
    echo "<td align='center' width= '20'>";
    foreach($spot as $spotdeux){
    echo "<br>".$spotdeux;
    }
    }
    echo "</tr> </table>";
}
//this actually creates the array and puts the value 0 in all
// locations.  the $xax and $yax can be upped or
//downed to create a larger or smaller array
function creater_array(){
    $ar=Array();
    $xax=5;
    $yax=5;
    $i=1;
    for ($y=0; $y<$yax; $y++)
    {
    array_push($ar,array());
    for ($x=0; $x<$xax; $x++)
    {
    array_push($ar[$y],"0");
    }
    }
return $ar;
}

$b = creater_array();
display_all($b);
?>
10-May-2003 03:53
Similarly to a comment by stlawson at sbcglobal dot net on this page:
http://www.php.net/basic-syntax.instruction-separation

It is usually advisable to define your arrays like this:
$array = array(
     'foo',
     'bar',
);

Note the comma after the last element - this is perfectly legal. Moreover,
it's best to add that last comma so that when you add new elements to the
array, you don't have to worry about adding a comma after what used to be
the last element.

<?php
$array = array(
     'foo',
     'bar',
     'baz',
);
?>
marcel at labor-club dot de 24-Feb-2003 07:58
i tried to find a way to create BIG multidimensional-arrays. but the notes below only show the usage of it, or the creation of small arrays like $matrix=array('birne', 'apfel', 'beere');

for an online game, i use a big array (50x80) elements.
it's no fun, to write the declaration of it in the ordinary way.

here's my solution, to create an 2d-array, filled for example with raising numbers.

<?php
$matrix=array();
$sx=30;
$sy=40;
$i=1;
for ($y=0; $y<$sy; $y++)
{
    array_push($matrix,array());
    for ($x=0; $x<$sx; $x++)
    {
        array_push($matrix[$y],array());
        $matrix[$x][$y]=$i;
        $i++;
    }
}
?>

if there is a better way, plz send an email. i always want to learn more php!
grubby_d at yahoo dot com 06-Dec-2002 10:58
About NULL as an array index.

An interesting thing with arrays is that you can use NULL as an index. I am trying it out with drop down list which will be used to update a database. Its not that good of an idea but it made me find the solution. For the database example you want to use the index "NULL" with quotes.

Say you have table person which has a foreign key reference to companies. BUT you want to allow the user to not specify a company as well. So you have determined that the database reference allows NULLs.

So you make a SELECT control with the lookup values as:

<OPTION value=(comp_id)>comp_name</OPTION>

using a while loop to print out the values.

Then you want the option to select NONE of the options. If you use something like -1 or 0 to represent this "blank" option you have to handle that in your php. Instead add this to your array: myarray("NULL") = "-none-" and you will get a field like this:

<OPTION value=NULL>-none-</OPTION>

Now every value from your SELECT control will be valid for the database and wont cause a foreign key references violation. it doesnt guarantee the data is coming from your trusty SELECT box so you still may want to check anyway.

Some interesting things about using the real NULL value as an array index:

<?php
$myarray = array(1, 2, 3);

echo count($myarray) . "<BR>";  // 3
$myarray[NULL] = "the null value";
echo count($myarray) . "<BR>";  // 4

if (array_key_exists(NULL, $myarray)
{ echo "this code will never be reached";}
?>

This will return FALSE and will generate this warning:

Warning: Wrong datatype for first argument in call to array_key_exists
MadLogic at Paradise dot net dot nz 31-Oct-2002 02:39
Heres a simple yet intelligent way of setting an array, grabbing the values from the array using a loop.

<?php
$ary = array("1"=>'One','Two',"3"=>'Three');
$a = '0'; $b = count($ary);
while ($a <= $b) {
  $pr = $ary[$a];
  print "$pr<br>";
  $a++;
}
?>
mads at __nospam__westermann dot dk 23-Oct-2002 07:39
In PHP 4.2.3 (and maybe earlier versions) arrays with numeric indexes may be initialized to start at a specific index and then automatically increment the index. This will save you having to write the index in front of every element for arrays that are not zero-based.

The code:

<?php
                  $a = array
        (
            21    => 1,
            2,
            3,
        );
    print '<pre>';
    print_r($a);
    print '</pre>';
?>

will print:

<?php
Array
(
    [21] => 1
    [22] => 2
    [23] => 3
)
?>
John 18-Jul-2002 11:48
Be careful not to create an array on top of an already existing variable:

<?php
$name = "John";
$name['last'] = "Doe";
?>

$name becomes "Dohn" since 'last' evaluates to the 0th position of $name.
Same is true for multi-arrays.
Markus dot Elfring at web dot de 30-May-2002 03:04
It seems to me that the use of brackets with multidimensional arrays is not described here.

But the following examples work:

<?php
$value = $point['x']['y'];
$message[1][2][3] = 'Greetings';
?>
jay at ezlasvegas dot net 20-Apr-2002 04:21
If you want to create an array of a set size and you have PHP4, use
array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish
to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS,
$INITIAL_VALUE);

Jay Walker
Las Vegas Hotel Associate
http://www.ezlasvegas.net
jjm152 at hotmail dot com 10-Mar-2002 06:22
The easiest way to "list" the values of either a normal 1 list array or a multi dimensional array is to use a foreach() clause.

Example for 1 dim array:

<?php
   $arr = array( 1, 2, 3, 4, 5 );
   foreach ( $arr as $val ) {
       echo "Value: $Val\n";
      }
?>

For multi dim array:

<?php
     $arr = array( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four, 5 => 'five');
      foreach ( $arr as $key => $value ) {
       echo "Key: $key, Value: $value\n";
      }
?>

This is quite possibly the easiest way i've found to iterate through an array.
tobiasquinteiro at ig dot com dot br 29-Jan-2002 12:25
<?
        // This is a small script that shows how to use an multiple array
        for($x = 0;$x < 10;$x++){
                for($y = 0;$y < 10;$y++){
                        $mat[$x][$y] = "$x,$y";
                }
        }

        for($x = 0;$x < count($mat);$x++){
                for($y = 0;$y < count($mat[$x]);$y++){
                        echo    "mat[$x][$y]: " .
                                $mat[$x][$y] . " ";
                }
                echo "\n";
        }
?>
deepak_pradhan at yahoo dot com 15-Sep-2001 05:16
I have seen that most of the time we get confused with Mult-Dimensional arrays.
I found print_r to be very helpful here.

Say the defined array is:
$a = array(1,2,array("A","B"));

print_r ($a);
Should give result like this:
Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => A [1] => B ) )
We can see here that:
$a is an array, $a[0]=1, $a[1]=2 and $a[2]=array it self with two elements.

thx
dp
joshua dot e at usa dot net 24-May-2001 11:12
Here's a cool tip for working with associative arrays-
Here's what I was trying to accomplish:

I wanted to hit a DB, and load the results into an associative array, since I only had key/value pairs returned. I loaded them into an array, because I wanted to manipulate the data further after the DB select, but I didn't want to hit the DB more than necessary.

Here's how I did it:

<?php
//assume db connectivity
//load it all into the associative array
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}
//now we expand it
while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}
?>

I found this to be super efficient, and extremely cool.
slicky at newshelix dot com 20-Mar-2001 01:57
Notice that you can also add arrays to other arrays with the $array[] "operator" while the dimension doesn't matter.

Here's an example:
$x[w][x] = $y[y][z];
this will give you a 4dimensional assosiative array.
$x[][] = $y[][];
this will give you a 4dimensional non assosiative array.

So let me come to the point. This get interessting for shortening things up. For instance:

<?php
        foreach ($lines as $line){
            if(!trim($line)) continue;
            $tds[] = explode("$delimiter",$line);
        }
?>
jasonr at argia dot net 27-Nov-2000 05:01
Arrays are never removed from memory, however there is an internal pointer that always points to the "next" array item. After you interate through an array, this will need to be reset back to the first element if you want to access it in a loop again.
see the Reset function at
http://www.php.net/manual/function.reset.php if you are confused.
rubein at earthlink dot net 26-Sep-2000 11:07
Multidimensional arrays are actually single-dimensional arrays nested inside other single-dimensional arrays.

$array[0] refers to element 0 of $array
$array[0][2] refers to element 2 of element 0 of $array.

If an array was initialized like this:

$array[0] = "foo";
$array[1][0] = "bar";
$array[1][1] = "baz";
$array[1][2] = "bam";

then:
is_array($array) = TRUE
is_array($array[0]) = FALSE
is_array($array[1]) = TRUE
count($array) = 2 (elements 0 and 1)
count($array[1] = 3 (elements 0 thru 2)

This can be really useful if you want to return a list of arrays that were stored in a file or something:

$array[0] = unserialize($somedata);
$array[1] = unserialize($someotherdata);

if $somedata["foo"] = 42 before it was serialized previously, you'd now have this:
$array[0]["foo"] = 42
php-manual at improbable dot org 02-Apr-2000 03:17
If you want to create an array of a set size and you have PHP4, use array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS, $INITIAL_VALUE);
baghera at mindspring dot com 12-Oct-1999 02:54
Every array has an "internal pointer". When you create an array, the internal pointer is automatically set to point at the first member. You can print the current location of the pointer:

$bob= current($myarrayname);
echo "$bob";

You can advance the pointer to the next spot using next($myarrayname).

To see a particular member of an array, set a $variable= $myarrayname[2] where "2" is the number of the member you want to use.

When assigning members to an array, the members are numbered beginning with 0, rather than 1.
array_walk
arsort
Функции для работы с массивами


Сортирует массив в обратном порядке, сохраняя ключи

array
asort
Функции для работы с массивами
PHP Manual

arsort

(PHP 4, PHP 5)

arsort — Сортирует массив в обратном порядке, сохраняя ключи

Описание

bool arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Эта функция сортирует массив в обратном порядке таким образом, что сохраняются отношения между ключами и значениями.

Она полезна, в основном, при сортировке ассоциативных массивов, когда важно сохранить отношение ключ => значение.

Список параметров

array

Входной массив.

sort_flags

Вы можете изменить поведение сортировки, используя дополнительный параметр sort_flags, подробнее см. sort().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования arsort()

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Результат выполнения данного примера:

a = orange
d = lemon
b = banana
c = apple

Названия фруктов были отсортированы в обратном порядке и ключи, ассоциированные с элементами, были сохранены.

Смотрите также

  • asort() - Сортирует массив, сохраняя ключи
  • Сравнение функций сортировки массивов

User Contributed Notes

sebas2day 07-May-2012 02:52
If you are dealing with a multidimensional array you want to sort, then this might be helpfull:

<?php
function array_sort($arr){
    if(empty($arr)) return $arr;
    foreach($arr as $k => $a){
        if(!is_array($a)){
            arsort($arr); // could be any kind of sort
            return $arr;
        }else{
            $arr[$k] = array_sort($a);
        }
    }
    return $arr;
}
?>
FatBat 13-Oct-2011 01:40
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
jordancdarwin at googlemail dot com 15-Dec-2007 02:21
A lot of people seem to trip up on this and ask me questions as to debugging. Bear in mind that this returns boolean, and does not return an array of affected items.

$array = array("One"=>1, "Three" => 3,"Two" =>2);
print_r(asort($array));

If successful, will return 1, and error if there is a string used. Useful to note so then people stop asking me :D
Scott Woods 02-Feb-2005 08:21
Note about "morgan at anomalyinc dot com"'s comment:

As of PHP4, you can just use array_multisort() to sort parallel or multi-dimensional arrays.
rodders_plonker at yahoo dot com 21-Aug-2000 06:43
I was having trouble with the arsort() function on an older version of PHP which was returning an error along the lines of 'wrong perameter count for function arsort' when I tried to use a flag for numeric sorting (2/SORT_NUMERIC).
I figured, as I only wanted to sort integers, I could pad numbers from the left to a specific length with 0's (using the lpad function provided by improv@magma.ca in the notes at http://www.php.net/manual/ref.strings.php).
A string sort then correctly sorts numerically (i.e. {30,2,10,21} becomes {030,021,010,002} not {30,21,2,10}) when echoing the number an (int)$string_name hides the leading 0's.

Made my day :).

Rodders.
morgan at anomalyinc dot com 24-Nov-1999 07:30
If you need to sort a multi-demension array, for example, an array such as

$TeamInfo[$TeamID]["WinRecord"]
$TeamInfo[$TeamID]["LossRecord"]
$TeamInfo[$TeamID]["TieRecord"]
$TeamInfo[$TeamID]["GoalDiff"]
$TeamInfo[$TeamID]["TeamPoints"]

and you have say, 100 teams here, and want to sort by "TeamPoints":

first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id... ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that's clear, but mail me if it isn't...
-mo
array
asort
Функции для работы с массивами


Сортирует массив, сохраняя ключи

arsort
compact
Функции для работы с массивами
PHP Manual

asort

(PHP 4, PHP 5)

asort — Сортирует массив, сохраняя ключи

Описание

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Эта функция сортирует массив таким образом, что сохраняются отношения между ключами и значениями. Она полезна, в основном, при сортировке ассоциативных массивов, когда важно сохранить отношение ключ => значение.

Список параметров

array

Входной массив.

sort_flags

Вы можете изменить поведение сортировки, используя дополнительный параметр sort_flags, подробнее см. sort().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования asort()

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Результат выполнения данного примера:

c = apple
b = banana
d = lemon
a = orange

Названия фруктов были отсортированы в алфавитном порядке и ключи, ассоциированные с элементами, были сохранены.

Смотрите также

  • arsort() - Сортирует массив в обратном порядке, сохраняя ключи
  • Сравнение функций сортировки массивов

User Contributed Notes

nick ([AT]) nickyost ([DOT]) com 15-Sep-2011 03:32
This function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution.

Hope it helps!
Anon 06-May-2011 05:37
Case insensitive sort in one line:

<?php

array_multisort(array_map('strtolower', $array), $array);

?>
rick at toewsweb dot net 28-Apr-2011 04:40
On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com):

What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order:

Ex:
<?php
$kvpairs = array('noun' => 'thought', 'animal' => 'fish', 'abstract' => 'thought', 'food' => 'fish', 'verb' => 'fish');
print "before:\n";
print_r($kvpairs);

// Essentially, one line of code is all that's needed for the sort:
array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs);

print "after:\n";
print_r($kvpairs);
?>

before:
Array
(
    [noun] => thought
    [animal] => fish
    [abstract] => thought
    [food] => fish
    [verb] => fish
)
after:
Array
(
    [animal] => fish
    [food] => fish
    [verb] => fish
    [abstract] => thought
    [noun] => thought
)

Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it.
ebade at yahoo dot com 09-Jul-2009 01:30
<?php
// Sort an associative array while case insensitive
// Might be useful to someone else
//
// Example:
// $arr = $res1 = array(
//              [a] => Trans Union
//              [b] => TRACE
//              [c] => TeleMatch
//              [d] => test);
//
// asort($res1);
// $res2 = asorti($arr);
//
// ASORT RESULT
// $res1 = array(
//              [b] => TRACE
//              [c] => TeleMatch
//              [a] => Trans Union
//              [d] => test);
//
// DESIRED RESULT
// $res2 = array(
//              [c] => TeleMatch
//              [d] => test
//              [b] => TRACE
//              [a] => Trans Union);

function asorti($arr) {
   $arr2 = $arr;
   foreach($arr2 as $key => $val) {
      $arr2[$key] = strtolower($val);
   }

   asort($arr2);
   foreach($arr2 as $key => $val) {
      $arr2[$key] = $arr[$key];
   }

   return $arr2;
}
?>
Eran 21-Apr-2009 05:15
i made this sample multi dimensional array sort to someone who needed to read lines from a text file instead of using sql - order by statement.

the idea is to take the key and sort(order) the specific column and then order the entire of the array as the selected column asort returned.

<?php
/**
 *
 * This sample is reading text data
 * and perform a sort to a 2 dimensional array
 * just like a normal sql do to "order by asc"
 *
 */

$foo = array();

/*
# SORT_REGULAR - compare items normally (don't change types)
# SORT_NUMERIC - compare items numerically
# SORT_STRING - compare items as strings
*/
$sort_by = SORT_REGULAR;

/*
# 0 - order by name column
# 1 - order by age column
# 2 - order by rank column
# 3 - order by color column
*/
$order_by = 1;

// source file
$line_of_text[1] = 'a1name|f2age|h3rank|jcolor';
$line_of_text[2] = 'b1name|d2age|i3rank|k4color';
$line_of_text[0] = 'c1name|e2age|g3rank|l4color';

// make array
for ($x=0; $x<=2; $x++)
{
    $line = explode('|',$line_of_text[$x]);

    // save it by coulmns otherwise it will saved like rows
    for ($i=0; $i<=3; $i++) {
          $foo[$i][$x] = $line[$i];
    }
}

// get the key order
$a = $foo[$order_by];

// sort
asort($a, $sort_by);

// start print
echo "<table cellpudding=0 cellspacing=0 border=1>\n";
        echo "<tr>\n";
          echo "<td>key</td>\n";
          echo "<td>name</td>\n";
          echo "<td>age</td>\n";
          echo "<td>rank</td>\n";
          echo "<td>color</td>\n";
        echo "</tr>\n";

// print by key order
foreach ($a as $k => $v) {
    echo "<tr>\n";
      echo "<td>$k</td>\n";
      // you can print here a for loop (0 to num of columns[=3])
      echo "<td>".$foo[0][$k]."</td>\n";
      echo "<td>".$foo[1][$k]."</td>\n";
      echo "<td>".$foo[2][$k]."</td>\n";
      echo "<td>".$foo[3][$k]."</td>\n";
    echo "</tr>\n";
}
echo "</table>\n";
?>
Cai Black 05-Mar-2009 11:20
I could not find a built-in to handle this specific case.  I hope that someone else finds it useful as well.

<?php
// array_sort_numerically_indexed_values
//
// (PHP 4, PHP 5)
//
// array_sort_numerically_indexed_values - Sort the numerically indexed values of an array.
//
//
// Description:
//
//   bool array_sort_numerically_indexed_values ( array &$array )
//
//   This function sorts the only values of the array that are numerically indexed.  This is mainly useful when sorting values that were returned from a datasource where value ordering is not specified, is not configurable, or is unknown.
//
//
// Parameters:
//
//   array
//     The input array.
//
// Return Values:
//
//   Returns TRUE on success or FALSE on failure (see below for more information).
//
//
// Notes:
//
//   The input array MUST contain an element 'count' with an integer value representing the number of numerically indexed array elements.
//
//
// Examples:
//
//   Example #1 array_sort_numerically_indexed_values example
//
//     <?php
//     // An array wherein the numerically indexed elements ($pets[0] through $pets[3]) are unordered.
//     $pets=array(
//       0 => 'Biscuit',
//       1 => 'Alley',
//       2 => 'Doogie',
//       3 => 'Conan',
//       'Conan' => array(
//         0 => 'cat',
//         1 => 'male'
//       ),
//       'Biscuit' => array(
//         0 => 'cat',
//         1 => 'female'
//       ),
//       'Doogie' => array(
//         0 => 'dog',
//         1 => 'male'
//       ),
//       'Alley' => array(
//         0 => 'dog',
//         1 => 'female'
//       ),
//       'count' => 4
//     );
//
//     array_sort_numerically_indexed_values($pets);
//
//     print_r($pets);
//     ?>
//
//     The above example will output:
//
//       Array
//         (
//           [0] => Alley
//           [1] => Biscuit
//           [2] => Conan
//           [3] => Doogie
//           [Conan] => Array
//             (
//               [0] => cat
//               [1] => male
//             )
//           [Biscuit] => Array
//             (
//               [0] => cat
//               [1] => female
//             )
//           [Doogie] => Array
//             (
//               [0] => dog
//               [1] => male
//             )
//           [Alley] => Array
//             (
//               [0] => dog
//               [1] => female
//             )
//           [count] => 4
//         )
//
//     The numerically index array elements were sorted alphabetically.
//
// Credits:
//   Cai Black < caiblack [at] hotmail [dot] com >
//

function array_sort_numerically_indexed_values(&$myArray) {
    if(isset($myArray['count'])) {
        $sort_again=true;
        if( $sort_again && ($myArray['count'] > 1) ) {
            $sort_previous_value='';
            for($i=0; $i<$myArray['count']; $i++) {
                $sort_again=false;
                // if not the first item then
                if($i > 0) {
                    // if current index value is less than previous value then
                    if($myArray[$i] < $myArray[$i-1]) {
                        // set swap to current index value
                        $sort_swap=$myArray[$i];
                        // set current index to previous index value
                        $myArray[$i]=$myArray[$i-1];
                        // set previous index to swap value
                        $myArray[$i-1]=$sort_swap;
                        // set $sort_again to true
                        $sort_again=true;
                    } // end if
                } // end if
                // set $sort_previous_value to current index value
                $sort_previous_value=$myArray[$i];
            } // end for
        } // end if
        return true;
    } else {
        return false;
    } // end if
} // end function array_sort_numerically_indexed_values
?>
ThA-B 11-Oct-2008 05:11
mzvarik at gmail dot com!
Your post at 16-Jan-2008 12:46 saved my life, so I request it not to be deleted, but put somewhere in more visible place.
I got situation, where server is not (and will not be) configured properly and latvian language can not be recognized neither in setlocale or sort functions.
Latvian is also known as ISO-8859-13, lv_LV, lv, lv_LV.ISO-8859-13, cp1257, windows-1257, etc. And because non of them worked with setlocale() and sort() under win32/php5.2.1 environment, i used your functions MySort() and myStrCmp() with slight change:
$cz_chars = 'Aa Āā Bb Cc Čč Dd Ee Ēē Ff Gg Ģģ Hh Ii Īī Jj Kk Ķķ Ll Ļļ Mm Nn Ņņ Oo Pp Rr Ss Šš Tt Uu Ūū Vv Zz Žž';
voila!
Thank You very very much!
bakatamas at freemail dot hu 15-Feb-2008 02:34
Dear mike at clear-link dot com!

I needed a case insensitive version of your function. It is still not perfect as I have to do something with country specific characters (öüóőúéáűíÖÜÓŐÚÉÁŰÍ)

function akisort(&$array,$valrev=false,$keyrev=false)
    {
    if ($valrev)
        {
        arsort($array);
        }
        else
        {
        asort($array);
        };
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num)
        {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        $tmp2 = array();
        foreach($tmp as $key => $value)
            {
            $tmp2[] = $key;
            $number = $value;
            };
        natcasesort($tmp2);
        reset($tmp2);
        print_r($tmp2);
        unset($tmp);
        foreach($tmp2 as $key => $value)
            {
            $tmp[$value] = $number;
            };
        if($keyrev)
            {
            $tmp = array_reverse($tmp, true);
            };
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        };
};
mike at clear-link dot com 31-Jan-2008 03:56
Small typo in the aksort function I just submitted. Here's the entire thing again, with the correction noted:

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
  $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        // Fixed from previous post: $i = $num;
    }
}
?>
mike at clear-link dot com 31-Jan-2008 03:23
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $num;
    }
}

// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);

// Standard asort
asort($tmp);
print_r($tmp);

// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);

// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);

// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);

// Results
Array
(
    [pe] => 1
    [ca] => 1
    [ce] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [ca] => 1
    [ce] => 1
    [pe] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [cb] => 2
    [pa] => 2
    [ca] => 1
    [ce] => 1
    [pe] => 1
)
Array
(
    [pa] => 2
    [cb] => 2
    [pe] => 1
    [ce] => 1
    [ca] => 1
)
mzvarik at gmail dot com 16-Jan-2008 09:29
I noticed that my function mentioned earlier is very misleading - somebody please delete that note!

This is how you sort:
<?php
setlocale (LC_ALL, 'czech');
$array = array("a", "č", "c");
usort ($array, 'strcoll');
print_r($array);
?>
przemekkus [at] interia [dot] pl 02-Nov-2007 06:34
Function written by a dot brandon at chello dot nl has an error  - wrong variable name. It should be:

if($rev) arsort($named_hash,$flags=0) ;

instead of

if($reverse) arsort($named_hash,$flags=0) ;
greenie2600 at yahoo dot com 09-Aug-2007 12:22
The function offered by richard at happymango dot me dot uk does not handle numeric indices properly. smileaf's suggested fix did not work for me. Use with caution.
a dot brandon at chello dot nl 25-Jun-2007 07:18
I use this for quasi-SQL orderby. Loosely based on smileaf. Any good for you nerds?

<?

function named_records_sort($named_recs, $order_by, $rev=false, $flags=0)
{// Create 1-dimensional named array with just
 // sortfield (in stead of record) values
    $named_hash = array();
     foreach($named_recs as $key=>$fields)
             $named_hash["$key"] = $fields[$order_by];

 // Order 1-dimensional array,
 // maintaining key-value relations
    if($reverse) arsort($named_hash,$flags=0) ;
    else asort($named_hash, $flags=0);

 // Create copy of named records array
 // in order of sortarray
    $sorted_records = array();
    foreach($named_hash as $key=>$val)
           $sorted_records["$key"]= $named_recs[$key];

return $sorted_records;} // named_recs_sort()

function show_sorted_records($named_recs, $order_by, $rev=false, $flags=0)
{$sorted_records=named_records_sort($named_recs, $order_by, $rev, $flags);
foreach($sorted_records as $name=>$fields)
  {echo "<b>$name</b>   ";
   foreach($fields as $field=>$val)
          echo "$field = $val "; echo "<br>";}
} // show_sorted_records()

$girl_friends=array();
$girl_friends["Anna"]=
array("born"=>'1989-08-22',"cupsize"=>'B-',"IQ"=>105, "daddy"=>'rich');
$girl_friends["Zoe"]
=array("born"=>'1978-03-11',"cupsize"=>'C#',"IQ"=>130, "daddy"=>'poor');
$girl_friends["Lilly"]
=array("born"=>'1985-06-16',"cupsize"=>'DD',"IQ"=>90, "daddy"=>'nasty');

$order_by="cupsize"; echo "And the winners are: <br>";
show_sorted_records($girl_friends, $order_by, true);

?>
gunnar at taljaren dot se 14-Jun-2007 01:00
for ($i=0;$i<5;$i++)
   $values[] = $i;
asort($values);

works, but
for ($i=0;$i<5;$i++)
   $values[$i] =$i;
asort($values);
doesn't!
nilesh dot gamit at gmail dot com 25-Apr-2007 03:50
function to sort 2d array: recordSort(); It is really helpful as most PHP sort functions provides facility for sorting 1d array & multi dimensional array sorting is not handy. Normally this function will help u.. if u r displaying some records n u want sorting by clicking on some column. basically same is achieved by direct SQL changes like ORDER BY ASC/DESC. But in case, if your records are not actual records, this function will help. i.e. some table has following fields in DB.
name, email, telephone and are_you_married; are_you_married is either 0 / 1. now u r displaying N for 1 and Y for 0; and you want sorting on are_you_married on display. then ORDER BY ASC/DESC. will not work. So, try this…

<?php
    function recordSort($records, $field, $reverse, $defaultSortField = 0)
    {
            $uniqueSortId = 0;
            $hash = array(); $sortedRecords = array(); $tempArr = array(); $indexedArray = array(); $recordArray = array();

            foreach($records as $record) {
                $uniqueSortId++;
                $recordStr = implode("|", $record)."|".$uniqueSortId;
                $recordArray[] = explode("|", $recordStr);
            }

            $primarySortIndex = count($record);
            $records = $recordArray;

             foreach($records as $record) {
                $hash[$record[$primarySortIndex]] = $record[$field];
             }
            uasort($hash, "strnatcasecmp");
            if($reverse)
            $hash = array_reverse($hash, true);

            $valueCount = array_count_values($hash);

            foreach($hash as $primaryKey => $value) {
                $indexedArray[] = $primaryKey;
            }

            $i = 0;
            foreach($hash as $primaryKey => $value) {
                $i++;
                if($valueCount[$value] > 1) {
                    foreach($records as $record)  {
                        if($primaryKey == $record[$primarySortIndex]) {
                            $tempArr[$record[$defaultSortField]."__".$i] = $record;
                            break;
                        }
                    }

                    $index = array_search($primaryKey, $indexedArray);

                    if( ($i == count($records)) || ($value != $hash[$indexedArray[$index+1]]) )  {
                        uksort($tempArr, "strnatcasecmp");

                        if($reverse)
                        $tempArr = array_reverse($tempArr);

                        foreach($tempArr as $newRecs) {
                            $sortedRecords [] = $newRecs;
                        }

                        $tempArr = array();
                    }
                }
                else {
                    foreach($records as $record)  {
                       if($primaryKey == $record[$primarySortIndex])  {
                                $sortedRecords[] = $record;
                                break;
                        }
                    }
                }
            }
            return $sortedRecords;
    }

    $array[0][0] = 'nilesh';   // sort_index = 0
    $array[0][1] = 'yogesh'; // sort_index = 1
    $array[0][2] = 'aakash'; // sort_index = 2
    $array[0][3] = '100';      // sort_index = 3
    $array[0][4] = 'nilesh';   // sort_index = 4
    $array[0][5] = 'Nil100';  // sort_index = 5
    $array[0][6] = 'Y';         // sort_index = 6

    $array[1][0] = 'Nil100';
    $array[1][1] = '1001';
    $array[1][2] = 'nilesh';
    $array[1][3] = 'nilesh';
    $array[1][4] = 'nilesh';
    $array[1][5] = 'yogesh';
    $array[1][6] = 'Nil100';

    $array[2][0] = 'Nil100';
    $array[2][1] = 'Y';
    $array[2][2] = '100';
    $array[2][3] = '10nilesh';
    $array[2][4] = 'aakash';
    $array[2][5] = '_aakash';
    $array[2][6] = 'aakash_';

    echo "array before sorting..."
    print_r($array);

    /* $sortedList = recordSort(2d_array, sort_index, reverse, second_level_sort_index_if_duplicates_found_default_is_0 = '0'); */
    $sortedList = recordSort($array, 4, 0, 5);

    echo "array after sorting..."
    print_r($sortedList);
?>
smileaf at smileaf dot org 24-Jan-2007 06:34
Ok I was mistaken, after re-reading the previous post the ".$key" is important. What caused the sorting issue for me wasn't that at all. But rather something else.
doing an: asort($records, $flags); before returning fixes the sorting problems.
The sorting problem I was refearing to causes a character based sorting done on numeric data.
so instead of:
1
2
3
...
10
12
20
It was returned back as
1
10
12
2
20
3
...
basically what I was trying to fix in the first place.
smileaf at smileaf dot org 24-Jan-2007 04:59
This revised version removes the ".$key" from the hash as I wasn't sure why it was there and caused sorting problems for me.
And allows the use of the array flags in both ksort and krsort.
<?
function record_sort($records, $field, $reverse=false, $flags=0)
{
    $hash = array();

    foreach($records as $key => $record)
    {
        $hash[$record[$field]] = $record;
    }

    ($reverse)? krsort($hash, $flags) : ksort($hash, $flags);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}
?>
richard at happymango dot me dot uk 23-Nov-2006 03:52
This is a fixed version of the same function I posted below. Now it will handle duplicate entries in the sorted field. EG: If there were two records that had the name Heathrow it would still work.

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $key => $record)
    {
        $hash[$record[$field].$key] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

?>
richard at happymango dot me dot uk 22-Nov-2006 03:35
This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending.

It is usefull for sorting query results from a database by a particular field after the query has been returned

This function can be quite greedy. It recreates the array as a hash to use ksort() then back again

By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $record)
    {
        $hash[$record[$field]] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

// Example below

$airports = array
(
    array( "code" => "LHR", "name" => "Heathrow" ),
    array( "code" => "LGW", "name" => "Gatwick" ),
);

printf("Before: <pre>%s</pre>", print_r($airports, true));

$airports = record_sort($airports, "name");

printf("After: <pre>%s</pre>", print_r($airports, true));

?>

Example Outputs:

Before: Array
(
    [0] => Array ( [code] => LHR, [name] => Heathrow )
    [1] => Array ( [code] => LGW, [name] => Gatwick )
)

After: Array
(
    [0] => Array ( [code] => LGW, [name] => Gatwick )
    [1] => Array ( [code] => LHR, [name] => Heathrow )
)
php at web-in-time dot com 05-Sep-2006 02:47
acecream's function works fine, especially with the spectre extension.

nevertheless sometimes the index values have to be kept. To achieve this, just replace:

$sorted_arr[] = $array[$arr_key];

with:

$sorted_arr[$arr_key] = $array[$arr_key];
rojaro 23-Jun-2004 07:38
Advanced sort array by second index function, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).
Only the first two arguments are required.

<?php

function sabsi ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) {
  if(is_array($array) && count($array)>0) {
    foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
    if(!$natsort) ($order=='asc')? asort($temp) : arsort($temp);
    else {
      ($case_sensitive)? natsort($temp) : natcasesort($temp);
      if($order!='asc') $temp=array_reverse($temp,TRUE);
    }
    foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
    return $sorted;
  }
  return $array;
}

?>
csaba at alum dot mit dot edu 23-Jun-2004 04:47
If you have a pair of arrays which have a one to one association (examples: spouses, first to last name, SSN to name), when you sort one, you might wish to sort the other in the same way to maintain the correlation.  This example illustrates a way:

<?php
$aMen = array('Fred', 'Bob', 'Tim', 'John', 'Bill');
$aPartner = array('Sue', 'Mary', 'Ann', 'Cathy', 'Nancy');
asort($aMen);                   // aMen now sorted; numeric keys out of order
$aWomen = array_keys($aMen);    // create a new array for result
foreach ($aWomen as $idx => &$name) $name=$aPartner[$name];
                                // aWomen now has the sorted partners
$aMen = array_merge($aMen);     // put the numeric keys in order
?>

Csaba Gabor
KOmaSHOOTER at gmx dot de 20-May-2003 05:52
here another version from acecream multisorting for arrays :)

<?php
function array_sort_multi2($array, $key,$key2)

{
  for ($i = 0; $i < sizeof($array); $i++) {
       if(! empty($array[$i][$key][$key2])){
       $sort_values[$i] = $array[$i][$key][$key2];
       }else{
       $sort_values[$i] = $array[$i];
       }
  }
  asort ($sort_values);
  reset ($sort_values);
  while (list ($arr_keys, $arr_values) = each ($sort_values)) {
         $sorted_arr[] = $array[$arr_keys];
  }
  return $sorted_arr;
}
?>
spectre at hellfish dot NOSPAM dot org 28-Apr-2003 09:54
that works nicely, tho it breaks the result-array up if one or more of arrays indexes are deleted before sorting. this one should fix it up:

change:
for ($i = 0; $i < sizeof($array); $i++) {

to:
foreach ($array as $i => $k) {
acecream 22-Apr-2003 04:02
my version of sorting multi dimensional array

<?php
function array_sort($array, $key)
{
   for ($i = 0; $i < sizeof($array); $i++) {
        $sort_values[$i] = $array[$i][$key];
   }
   asort ($sort_values);
   reset ($sort_values);
   while (list ($arr_key, $arr_val) = each ($sort_values)) {
          $sorted_arr[] = $array[$arr_key];
   }
   return $sorted_arr;
}
?>
mbevan at marginsoftware dot com 03-Dec-2002 01:25
Nevermind... use my last note as a quick tip: if you wish to keep the keys, use asort() and arsort() in place of sort() and rsort().
31-Jul-2002 06:48
Sorry, my last post had a typo:
// unnecessary backslashes break create_function, oops.
  if ( is_string($var) ) $var = "\'$var\'";
//it should be:
  if ( is_string($var) ) $var = "'$var'";

-- FIXED and TESTED -- :)

Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "'$var'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
phzzzt .a.t. acm .d.o.t. org 31-Jul-2002 06:32
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "\'$var\'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
salchicha at cable dot net dot co 03-Apr-2002 01:23
Here's one I whipped up to allow you to sort an array of a specific class by a member or function:

<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
   $tarr = array();
   $rarr = array();
   for($i = 0; $i < count($arr); $i++) {
      $element = $arr[$i];
      $tarr[] = strtolower($element->{$var});
   }

   reset($tarr);
   asort($tarr);
   $karr = array_keys($tarr);
   for($i = 0; $i < count($tarr); $i++) {
      $rarr[] = $arr[intval($karr[$i])];
   }

   return $rarr;
}
?>

It works very well. For example, I have a Room class with members title, isActive(), date, etc. I can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and it'll work.
rcwang at cmu dot edu 02-Mar-2002 05:42
Here's my version of sorting multi-dimensional array by 2nd index.
Feel free to change the code to suit your needs.

<?php
function aSortBySecondIndex($multiArray, $secondIndex) {
    while (list($firstIndex, ) = each($multiArray))
        $indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
    asort($indexMap);
    while (list($firstIndex, ) = each($indexMap))
        if (is_numeric($firstIndex))
            $sortedArray[] = $multiArray[$firstIndex];
        else $sortedArray[$firstIndex] = $multiArray[$firstIndex];
    return $sortedArray;
}
?>
markus at runout dot at 29-Nov-2001 12:37
for sorting CASEINSENSITIVE try
natcasesort()

there's little difference to sort,
but maybe that doesn't matter for you.
freeman at generalresources dot com 04-May-2001 04:51
The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.
sweetland at whoadammit dot com 15-Aug-2000 12:02
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
 ** comesafter ($s1, $s2)
 **
 ** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
 **/

function comesafter ($s1, $s2) {
        /**
         ** We don't want to overstep the bounds of one of the strings and segfault,
         ** so let's see which one is shorter.
         **/

        $order = 1;

        if (strlen ($s1) > strlen ($s2)) {
                $temp = $s1;
                $s1 = $s2;
                $s2 = $temp;
                $order = 0;
        }

        for ($index = 0; $index < strlen ($s1); $index++) {
                /**
                 ** $s1 comes after $s2
                 **/

                if ($s1[$index] > $s2[$index]) return ($order);

                /**
                 ** $s1 comes before $s2
                 **/

                if ($s1[$index] < $s2[$index]) return (1 - $order);
        }

        /**
         ** Special case in which $s1 is a substring of $s2
         **/

        return ($order);
}

/**
 ** asortbyindex ($sortarray, $index)
 **
 ** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
 ** of the Ith member of both the group and user arrays is a string identifier. In the
 ** case of a user array this is the username; with the group array it is the group name.
 ** asortby
 **/

function asortbyindex ($sortarray, $index) {
        $lastindex = count ($sortarray) - 1;
        for ($subindex = 0; $subindex < $lastindex; $subindex++) {
                $lastiteration = $lastindex - $subindex;
                for ($iteration = 0; $iteration < $lastiteration;    $iteration++) {
                        $nextchar = 0;
                        if (comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
                                $temp = $sortarray[$iteration];
                                $sortarray[$iteration] = $sortarray[$iteration + 1];
                                $sortarray[$iteration + 1] = $temp;
                        }
                }
        }
        return ($sortarray);
}
?>

It's a bit long with all the comments, but I hope it helps.
bwuhlman at tallships dot ca 02-Aug-2000 03:01
Well, actually, asort has *two* annoying features.

It works perfectly well sorting hashes (or associative arrays, as you might have it), but doggedly refuses to sort regular arrays maintaining index assocation. Kind've makes sense, but the docs don't explicitly say you can't do it.

Urgggh.
jacko at kring dot co dot uk 24-Feb-2000 11:26
asort has one anoying feature, it ignores any default or implicit order in the data.  i.e. if two elements of an array contain "banana" then it is not garanteed that the first will still be the first after the sort.
This makes the Burrows-Wheeler block sort a bit of a pain to impliment, with a trailing string having to be appended to all strings before sorting, and removed after sorting. To maintain the so called "banana" order.
arsort
compact
Функции для работы с массивами


Создает массив, содержащий названия переменных и их значения

asort
count
Функции для работы с массивами
PHP Manual

compact

(PHP 4, PHP 5)

compact — Создает массив, содержащий названия переменных и их значения

Описание

array compact ( mixed $varname [, mixed $... ] )

Создает массив, содержащий переменные и их значения.

Для каждого из переданного параметров, функция compact() ищет переменную с указанным именем в текущей таблице символов и добавляет их в выводимый массив так, что имя переменной становится ключом, а содержимое переменной становится значением этого ключа. Короче говоря, она обратна функции extract().

Любые неустановленные строки будут просто пропущены.

Список параметров

varname

compact() принимает неограниченное количество параметров. Любой из параметров может быть либо строкой, содержащей название переменной, либо массивом названий переменных. Массив может содержать вложенные массивы названий переменных; функция compact() обрабатывает их рекурсивно.

Возвращаемые значения

Возвращает массив со всеми переменными, добавленными в него.

Примеры

Пример #1 Пример использования compact()

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?>

Результат выполнения данного примера:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

Примечания

Замечание: Замечания по работе функции compact

Так как переменные переменных не могут быть использованы с суперглобальными массивами внутри функций, суперглобальные массивы не могут быть переданы в compact().

Смотрите также

  • extract() - Импортирует переменные из массива в текущую таблицу символов

User Contributed Notes

piedone at pyrocenter dot hu 15-Apr-2011 06:00
A quick way of compacting all local variables:

<?php
$localVariables = compact(array_keys(get_defined_vars()));
?>

This is useful if you want to return all local variables from a function/method or you want to pass all local variables to one. A valid example would be to use this with application hooks/events (if you want the called hook to be able to modify everything in the caller), but otherwise use with care (as methods should be used through their declared interface).
Robc 19-Jan-2011 03:16
The description says that compact is the opposite of extract() but it is important to understand that it does not completely reverse extract().  In particluar compact() does not unset() the argument variables given to it (and that extract() may have created).  If you want the individual variables to be unset after they are combined into an array then you have to do that yourself.
tatarynowicz at gmail dot com 10-Jan-2011 03:17
Please note that compact() will _not_ issue a warning if the specified variable name is undefined.
Anonymous 06-Apr-2009 03:41
Compact does not work with references, but there is a short way to resolve this:

<?php
//$foo=array();
foreach( array('apple','banana') as $v) $foo[$v] = &$v;
?>
packard_bell_nec at hotmail dot com 31-Jan-2008 09:46
You can check whether a variable is defined by using array_key_exists()!
First, you may ask that no reserved array (would be called $LOCALS) is predefined in function scope (contrast to reserved array $GLOBALS in global scope. To solve it, you can use compact().
Then, you may ask that why property_exists() cannot be used. This is because no reserved function is predefined to create OBJECT containing variables and their values, and no reserved function is predefined to import variables into the current symbol table from an OBJECT. In addition, property_exists() breaks the naming convention of reserved function.
Finally, I show how to check whether a variable is defined by using array_key_exists():
<?php
function too(){
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
$foo = null;
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
}
too();
?>
The output will be:
0<br/>
1<br/>
M Spreij 24-May-2007 06:10
Can also handy for debugging, to quickly show a bunch of variables and their values:

<?php
print_r(compact(explode(' ', 'count acw cols coldepth')));
?>

gives

Array
(
    [count] => 70
    [acw] => 9
    [cols] => 7
    [coldepth] => 10
)
mijllirg at wearethedotin dot com 17-Nov-2005 11:38
You might could think of it as ${$var}.  So, if you variable is not accessible with the ${$var} it will not working with this function.  Examples being inside of function or class where you variable is not present.

<?php
$foo = 'bar';

function blah()
{
    // this will no work since the $foo is not in scope
    $somthin = compact('foo'); // you get empty array
}
?>

PS: Sorry for my poor english...
hericklr at gmail dot com 13-Jun-2005 08:43
The compact function doesn't work inside the classes or functions.
I think its escope is local...
Above it is a code to help about it.
Comments & Suggestions are welcome.
PS: Sorry for my poor english...

<?php

    function x_compact()
    {    if(func_num_args()==0)
        {    return false; }
        $m=array();

        function attach($val)
        {    global $m;
            if((!is_numeric($val)) && array_key_exists($val,$GLOBALS))
            {    $m[$val]=$GLOBALS[$val];}
        }

        function sub($par)
        {    global $m;
            if(is_array($par))
            {    foreach($par as $cel)
                {    if(is_array($cel))
                    {    sub($cel); }
                    else
                    {    attach($cel); }
                }
            }
            else
            {    attach($par); }
            return $m;
        }

        for($i=0;$i<func_num_args();$i++)
        {    $arg=func_get_arg($i);
            sub($arg);
        }

        return sub($arg);
    }
?>
pillepop2003 at yahoo dot de 22-Nov-2004 12:26
Use the following piece of code if you want to insert a value into an array at a path that is extracted from a string.

Example:
You have a syntax like 'a|b|c|d' which represents the array structure, and you want to insert a value X into the array at the position $array['a']['b']['c']['d'] = X.

<?
    function array_path_insert(&$array, $path, $value)
    {
        $path_el = split('\|', $path);

        $arr_ref =& $array;

        for($i = 0; $i < sizeof($path_el); $i++)
        {
            $arr_ref =& $arr_ref[$path_el[$i]];
        }

        $arr_ref = $value;
    }

    $array['a']['b']['f'] = 4;
    $path  = 'a|b|d|e';
    $value = 'hallo';

    array_path_insert($array, $path, $value);

    /* var_dump($array) returns:

    array(1) {
      ["a"]=>
      &array(1) {
        ["b"]=>
        &array(2) {
          ["f"]=>
          int(4)
          ["d"]=>
          &array(1) {
            ["e"]=>
            string(5) "hallo"
          }
        }
      }
    */

?>

Rock on
Philipp
asort
count
Функции для работы с массивами


Подсчитывает количество элементов массива или что-то в объекте

compact
current
Функции для работы с массивами
PHP Manual

count

(PHP 4, PHP 5)

count — Подсчитывает количество элементов массива или что-то в объекте

Описание

int count ( mixed $var [, int $mode = COUNT_NORMAL ] )

Подсчитывает количество элементов массива или что-то в объекте.

Для объектов, если у вас включена поддержка SPL, вы можете перехватить count(), реализуя интерфейс Countable. Этот интерфейс имеет ровно один метод, Countable::count(), который возвращает значение функции count().

Пожалуйста, смотрите раздел "Массивы" в этом руководстве для более детального представления о реализации и использовании массивов в PHP.

Список параметров

var

Массив или объект.

mode

Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов. count() не обнаруживает бесконечную рекурсию.

Возвращаемые значения

Возвращает количество элементов в var. Если var не является массивом или объектом, реализующим интерфейс Countable, будет возвращена 1. За одним исключением: если var - NULL, то будет возвращён 0.

Предостережение

count() может возвратить 0 для переменных, которые не установлены, но также может возвратить 0 для переменных, которые инициализированы пустым массивом. Используйте функцию isset() для того, чтобы протестировать, установлена ли переменная.

Список изменений

Версия | Описание
4.2.0 | Добавлен необязательный параметр mode.

Примеры

Пример #1 Пример использования count()

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$result = count($b);
// $result == 3

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?>

Пример #2 Пример рекурсивного использования count()

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// рекурсивный count
echo count($food, COUNT_RECURSIVE); // выводит 8

// обычный count
echo count($food); // выводит 2

?>

Смотрите также

  • is_array() - Определяет, является ли переменная массивом
  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • strlen() - Возвращает длину строки

User Contributed Notes

MilesPrower- at hotmail dot com 26-May-2012 03:02
Count only values that are not empty:

<?php

function countreal($arr){
$arrsize = sizeof($arr);
foreach($arr as $k => $v){
if(empty($v)){$arrsize = $arrsize - 1;}
}
return $arrsize;}

?>
carlos56_dal at hotmail dot com 13-Apr-2012 07:40
When use an huge array, it's recommended to set a variable with the size of the array, p.g.

<?php

$array_size = count($your_array);
for($i = 0; $i < $array_size; $i++)
{
  // Process array data
}
?>
It's quicker than:
<?php
for($i = 0; $i < sizeof($your_array); $i++)
{
  // Process array data
}
?>
In the first example, run the sizeof function once, however in the second example run n times the sizeof function
nicolas dot grekas+php at gmail dot com 10-Sep-2011 11:29
As of PHP 5.2.6, count() DOES detect infinite recursion.
It triggers a warning when its argument is a recursive array.
mike dot mackintosh at angrystatic dot com 08-Sep-2011 10:31
If you try to do a sizeof or count with an object, it will always return 1 if the object is not null.

You need to type cast the object as an array for it to count correctly.

ex:

<?php
$obj->foo = 'fu';
$obj->bar = $fooBar();

echo count($obj); //returns 1

echo count( (array) $obj); // returns 2
?>
gothamxi 07-Mar-2011 10:48
simple random value from array.

<?php
$topic=array(
    "UFOs",
    "Barack Obama",
    "China",
    "Christianity",
    "Communism",
    "World War II",
    "Global Warming",
    "Vegetarianism",
            );

echo ("What do you think about ".$topic[ rand( 1,count($topic) ) ]."? ");

?>

output-->
What do you think about Global Warming? , etc
pro at developergatsby dot com 15-Jan-2011 02:37
Complexity of count function.

I just tested the complexity of count().
It looks O(1).

Here is the result.

<< counting array with 1 element>>
total time : 0.021ms
start -> end : 100 %

<< counting array with 100000 elements>>
total time : 0.015ms
start -> end : 100 %

Here is the testing code.
mini_bench_to is a function.
<?php

$arr = array();
$arr[] = "1";

$t['start'] = microtime(true);
$size = count($arr);
$t['end'] = microtime(true);
$str_result_bench = mini_bench_to($t);
echo $str_result_bench; // string return

$arr = array();
for($index = 0; $index < 100000; $index++) {
    $arr[] = $index;
}
$t['start'] = microtime(true);
$size = count($arr);
$t['end'] = microtime(true);
$str_result_bench=mini_bench_to($t);
echo $str_result_bench; // string return

?>

<?php
function mini_bench_to($arg_t, $arg_ra=false) {
    $tttime=round((end($arg_t)-$arg_t['start'])*1000,4);
    if ($arg_ra) $ar_aff['total_time']=$tttime;
    else $aff="total time : ".$tttime."ms\n";
    $prv_cle='start';
    $prv_val=$arg_t['start'];

    foreach ($arg_t as $cle=>$val)
    {
        if($cle!='start')
        {
            $prcnt_t=round(((round(($val-$prv_val)*1000,4)/$tttime)*100),1);
            if ($arg_ra) $ar_aff[$prv_cle.' -> '.$cle]=$prcnt_t;
            $aff.=$prv_cle.' -> '.$cle.' : '.$prcnt_t." %\n";
            $prv_val=$val;
            $prv_cle=$cle;
        }
    }
    if ($arg_ra) return $ar_aff;
    return $aff;
}
?>
marc at example dot com 23-Sep-2010 12:10
Just found use for this function...
Can count an array of items where a certain condition is met.
Feel free to improve it.

function countWhere($input = 1, $operator = '==', $where = 1)
{
    $input = is_array($input) ? $input : (array)$input;
    $operator = !in_array($operator, array('<','>','<=', '>=','==', '!=')) ? '==' : $operator;

    $i = 0;

    foreach($input as $current)
    {
        $match = null;
        eval('$match = (bool)("'.$current.'"'.$operator.'"'.$where.'");');

        $i = $match ? $i+1 : $i;
    }

    return $i;
}

USAGE:
echo countWhere(array('PZ','AB','CD','EF','GH'), '!=', 'GH');

OUTPUT:
4
marc at gutt dot it 07-Jun-2010 11:10
There was a change in a PHP5 version. Now an empty string returns 1:
<?php
echo count(''); // returns 1
echo count(array()); // returns 0
?>

This wasn't in PHP4 and some older PHP5 versions.
D X 03-Mar-2010 06:42
To know how much properties an object has, I do it like this:
count((array) $object)
... because count($object) gives me allways 1
ravenswd at gmail dot com 04-Aug-2009 12:37
The code snippet posted by legobuff at hotmail dot com on 02-Feb-2000 contains an error. This is the code that was posted:

<?php
// To find the index of the last element in the array:
end($yourArray);
$index = key($yourArray);
?>

However, this will fail if the indices have been stored out of sequence. What you actually want is max(array_keys($yourArray)), as indicated below:

<?php
$yourArray = array(1=>'a', 7=>'b', 5=>'c');

print count($yourArray); // prints 3

end($yourArray);
print key($yourArray); // prints 5

print max(array_keys($yourArray)); // prints 7
?>
jezdec at email dot cz 19-Apr-2009 04:42
Hi there,
there is a simple script with example for counting rows and columns of a two-dimensional array.

<?php
$data = array(
    "apples" =>
        array("red", "yellow", "pineapples"),
    "bananas" =>
        array("small", "medium", "big"),
    "vegs" =>
        array("potatoes", "carrots", "onions")
);

$rows = count($data,0);
$cols = (count($data,1)/count($data,0))-1;
print "There are {$rows} rows and {$cols} columns in the table!";
?>
ceo at l-i-e dot com 17-Dec-2008 12:22
count('') returns the very un-intuitive value of 1...
michael.debyl at gmail dot comz0r 16-Jul-2008 03:45
There doesn't seem to be a succinct method already noted on this page for counting multidimensional array end nodes (Items in multidimensional arrays), so I thought this function might help somebody.

Nice and simple :)

<?php
function rcount ($array) {
  $count = 0;
  if (is_array($array)) {
    foreach($array as $id=>$sub) {
    if (!is_array($sub)) { $count++; }
     else { $count = ($count + rcount($sub)); }
    }
    return $count;
  }
  return FALSE;
}
?>
analpaper{gmail} 03-Jul-2008 07:37
I found useful this little function that detects if a array is multidimensional or not.

<?php
function array_is2D($array) {
  return is_array($array) ? count($array)===count($array, COUNT_RECURSIVE) : -1;
}
?>

---
live2code
Anonymous 11-Jan-2008 01:20
Here is an iterative soloution of danny's count_recursive function which might be more efficient due to the missing recursion

<?php
/**
 * counts elements of an multidimensional array
 *
 * @param array $array Input Array
 * @param int $limit dimensions that shall be considered (-1 means no limit )
 * @return int counted elements
 */
function multicount ($array, $limit = -1)
{
   $cnt = 0;
   $limit = $limit > 0 ? (int) $limit : -1;
   $arrs[] = $array;
   for ($i=0; isset($arrs[$i]) && is_array($arrs[$i]); ++$i)
   {
      foreach ($arrs[$i] as $value)
      {
         if (!is_array($value) ) ++$cnt;
         elseif( $limit==-1 || $limit>1 )
         {
            if( $limit>1 ) --$limit;
            $arrs[] = $value;
         }
      }
   }
   return $cnt;
}
?>
atoi_monte at hotmail dot com 28-Jun-2007 02:10
Please note: While SPL is compiled into PHP by default starting with PHP 5, the Countable interface is not available until 5.1
danny at dannymendel dot com 13-Jun-2007 01:14
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.

// $limit is set to the number of recursions
<?php
function count_recursive ($array, $limit)
{
    foreach ($array as $id => $_array)
    {
        if (is_array ($_array) && $limit > 0) $count += count_recursive ($_array, $limit - 1); else $count += 1;
    }
    return $count;
}
?>
yarolan at mail dot ru 26-Apr-2007 04:56
NEVER USE IN CYCLES!

<?php
//size of $arr ~ 2000 elements

//wrong variant (Time exec ~ 19 sec)
for($i=0;$i<count($arr);$i++)
{
   //...
}

//right variant(Time exec ~ 0.2 sec)
$arr_size=count($arr);
for($i=0;$i<$arr_size;$i++)
{
   //...
}
?>

it was discovered experimentally.
Colin 03-Feb-2007 07:24
<?php
// countValuesRecursive
// The goal of this function is to count non-false values of a multidimenional array
// This is useful in making a quick determination if a form sent any values
// If no values were sent I can simply return to the blank form rather than continuing to the validation of each input
// There are two limitations of the principle:
// 1. If you WANT to send FALSE, 0, '', or NULL as form values this function will not count those, thus not doing what's expected
// 2. This would create an endless loop on a form that has no required fields such as one where users can choose to recieve optional  email subscriptions but where choosing none is also valid
function countValuesRecursive($array, $count = 0) {

    // Cycle through the array
    foreach ($array as $value) {

        // Check if the value is an array
        if (is_array($value)) {

            // Cycle through deeper level
            $count = countValuesRecursive($value, $count);
            }
        else {

            // Check if the value is TRUE
            if ($value) {
                $count++;
                }
            }
        }

    // Return the count
    return $count;
    }
?>
alexandr at vladykin dot pp dot ru 08-Nov-2006 04:28
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).

<?php
  function getArrCount ($arr, $depth=1) {
      if (!is_array($arr) || !$depth) return 0;

     $res=count($arr);

      foreach ($arr as $in_ar)
         $res+=getArrCount($in_ar, $depth-1);

      return $res;
  }
?>
anil dot iitk at gmail dot com 26-Jan-2006 12:32
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
             'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo "<br>".count($food, COUNT_RECURSIVE); // output 8

function average($a){
  return array_sum($a)/count($a) ;
}
$b = array(1,2,3,4,5,6,7,8,9);
echo "Average of array:".average($b);

?>
Scorch at netpix dot com 20-Dec-2005 05:59
Be careful of recasting your variables, especially with database array returns:

<?php
$res = mysql_query("select * from blah") // a query that returns an empty set
$row = mysql_fetch_array($res); // get's 0 since there's no return
echo count($row); // echos 1 - since $row is not an array
echo $row[0]; // echos "", but casts $row as an array?
echo count($row); // echos 0 now
?>
Tom 30-Nov-2005 04:57
You can find an average from an array using this and array_sum.
<?php
//array average( array input )
function average($input) {
return array_sum($input) / count($input);
}
?>

You can also do a method of form validation that involves putting all errors into an array and letting count() do the key part.
<?php
if(isset($_POST['submit'])) {
$errors = array();
if(empty($_POST['message'])) $errors[] = "Empty message field";
if(!preg_match('/[a-z0-9.]@[a-z0-9].[a-z]/i', $_POST['email']) {
$errors[] = "Bad email address";
  }
if(count($errors) == 0) {
//process form...
  }
}
?>
Fred D 18-Oct-2005 09:16
The trim_text function was helpful, but it did not take account of the possibility of having nothing to trim which can sometimes happen if you are using this function in a loop through data. I've added a count function to deal with that possibility

<?php
function trim_text_elipse($text, $count){
//Create variable
$trimmed="";

//Remove double white space
$text = str_replace("  ", " ", $text);

//Turn the text into an array
$string = explode(" ", $text);

//Check to see how many words there are
$wordTotal = count($string);
    //Check to see if there are more words than the $count variable
    if($wordTotal > $count){
        //Loop through adding words until the $count variable is reached
        for ( $wordCounter = 0; $wordCounter <= $count; $wordCounter++ ){
            $trimmed .= $string[$wordCounter];
                //Check to and add space or finish with elipse
                if ( $wordCounter < $count ){ $trimmed .= " "; }
                else { $trimmed .= " &#8230;"; }
                }
    }else{
    //Set value returned to the existing value
    $trimmed =$text;
    }
//Trim off any white space
$trimmed = trim($trimmed);
return $trimmed;
}

?>
david _at_ webgroup _dot_ org 12-Feb-2005 04:30
While michael at htmlland dot net's code works, I believe it is better to use:
$extension=substr($file,strrpos($file,".")+1);

This doesn't incur the overhead of array handling.  I haven't tested it for time functions, but it should work just as well and SHOULD be faster.
freefaler at gmail dot com 19-Nov-2004 05:01
If you want to count only elements in the second level of 2D arrays.A close to mind note, useful for multidimentional arrays:

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
             'veggie' => array('carrot', 'collard','pea'));

// recursive count
echo count($food,COUNT_RECURSIVE);  // output 8

// normal count
echo count($food);                  // output 2

// all the fruits and veggies
echo (count($food,COUNT_RECURSIVE)-count($food,0)); //output 6
?>
moazzam at ummah dot org 14-Oct-2004 04:59
This is an obvious note, but I am writing it any way so other, who did may not have observed this, can take advantage of it too.

When running loops with count conditions, the code runs faster if you first assign the count() value to a variable and use that (instead of using count() directly in a loop condition.

To explain my point better, here is an example:

<?php

for ($i=0; $i<10000; $i++) {
    $arr[] = $i;
}

$time11 = microtime_float();
$bf = "";
for ($i=0; $i<count($arr); $i++) {
    $bf .= $arr[$i]."\n";
}
$time12 = microtime_float();
$time1 = $time12 - $time11;

print "First: ".$time1."\n";

$time21 = microtime_float();
$l = count($arr);
for ($i=0; $i<$l; $i++) {
    $bf .= $arr[$i]."\n";
}
$time22 = microtime_float();
$time2 = $time22 - $time21;

print "Second: ".$time2."\n";

?>

The output from the code above is (when run many times):

First: 0.13001585006714
Second: 0.099159002304077

First: 0.12128901481628
Second: 0.079941987991333

First: 0.18690299987793
Second: 0.13346600532532

As you can see, the second method (which doesnt use count() directly in the loop) is faster than the first method (which uses count() directly in the loop).

BTW:  I copied the microtime_float() function from one of the comments in the microtime() section. It just returns time with microseconds as float. Check comments in microtime() for more info.
michael at htmlland dot net 04-Jun-2004 10:30
I have found on upload scripts or on file manipulation scripts that people can trick a classic file type filter:
example:

<?php
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[1];
if($extention == "jpg"){ echo"Not correct"; exit; }
?>

This returns the filename extention as jpg not wav.

One way to change this is to use count() :
example:

<?php
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[count($bits) - 1];
if($extention == "jpg"){ echo "Not correct"; exit; }
?>

This returns the filename extention as wav not jpg.
rolandfoxx at yahoo dot com 30-Mar-2004 04:13
As an addition, any of the array manipulation functions can likewise get count to once again return 0:

<?php
$a = array();
print(count($a)); // prints 0
$a[0] = "foo";
array_shift($a);
print(count($a)); //prints 0
$a[0] = "bar";
array_splice($a, 0, 1);
print(count($a)); //prints 0
?>
admin at lft-muenchen dot de 12-Mar-2003 04:18
Note:

<?php
print (strlen($a)); // will print 0
$a="";
print (strlen($a)); // will print 1
$a=null;
print (strlen($a)); // will print 1
$a=array();
print (strlen($a)); // will print 0
?>

you can only get an array back to size 0 by using the array() command, not by just setting it to "" or null.
simon at invalid dot com 20-Aug-2002 12:40
Reminder for using count():

<?php
$ary = array(null, "a", "b", null);
echo count($ary);    // count: 4

$ary[10] = "c";
echo count($ary);    // count: 5

$ary[15] = null;
echo count($ary);    // count: 6
?>

=> NULL is seen as an element in count()

Count 2D array:

<?php
$a2Dary = array(array("a", "b") , array(), "v");

echo count($a2Dary);        // count: 3
echo count($a2Dary[0]);    //count 2
echo count($a2Dary[1]);    // count: 0
echo count($a2Dary[2]);    // count: 1
?>

Hope can help you
webmaster at NOSPAMtrafficg dot com 26-Apr-2002 03:48
Counting a multi-dimentional array

test array

<?php
$settings[0][0]  = 128;
$settings[0][1]  = 256;
$settings[0][2]  = 384;
$settings[0][3]  = 512;
$settings[0][4]  = 1024;
$settings[0][5]  = 2048;

$settings[1][0]  = 1024;
$settings[1][1]  = 2048;
$settings[1][2]  = 3072;
$settings[1][3]  = 4096;

count($settings) // returns 2
count($settings[0]) // returns 6
count($settings[1]) // returns 4
?>
kanareykin at denison dot edu 26-Mar-2001 01:13
Here's how to count non-empty elements
in an array of any dimension. Hope
it will be useful for somebody.

<?php
// recursively count all non-empty elements
// in array of any dimension or mixed - i.e.
// array('1' => 2, '2' => array('1' => 3, '2' => 4))
function count_all($arg)
{
    // skip if argument is empty
    if ($arg)    {
        // not an array, return 1 (base case)
        if(!is_array($arg))
            return 1;
        // else call recursively for all elements $arg
        foreach($arg as $key => $val)
            $count += count_all($val);

        return $count;
    }
}
?>
martin at complinet dot com 30-Nov-2000 04:31
The count function does not ignore null values in an array. To achieve this use this function.

<?php
function xcount($array) {
        while (list($key, $value) = each($array)) {
                if ($value) {
                        $count++;
                }
        }
return $count;
}
?>
jmcastagnetto at php dot net 04-Sep-2000 12:30
If you want to disambiguate if a variable contains an array w/ only one element, just us is_array() or gettype()
legobuff at hotmail dot com 02-Feb-2000 10:43
This is taken from sganer@expio.co.nz comments on the sizeof() function:
If some elements in your array are not set, then sizeof() and count() will not return the index of the last element, but will return the number of set elements. To find the index of the last element in the array:

end($yourArray);
$index = key($yourArray);

... Where $yourArray is the array you want to find the last index ($index) of.
compact
current
Функции для работы с массивами


Возвращает текущий элемент массива

count
each
Функции для работы с массивами
PHP Manual

current

(PHP 4, PHP 5)

current — Возвращает текущий элемент массива

Описание

mixed current ( array &$array )

У каждого массива имеется внутренний указатель на его "текущий" элемент, который инициализирован первым элементом, добавленным в массив.

Список параметров

array

Массив.

Возвращаемые значения

Функция current() просто возвращает значение элемента массива, на который указывает его внутренний указатель. Она не перемещает указатель куда бы то ни было. Если внутренний указатель находится за пределами списка элементов или массив пуст, current() возвращает FALSE.

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Пример использования current() и дружественных функций

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport);    // $mode = 'foot';
$mode = end($transport);     // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>

Примечания

Замечание: Вы не сможете отличить конец массива от boolean элемента FALSE. Для корректного обхода массива, который может содержать FALSE элементы, смотрите функцию each().

Смотрите также

  • end() - Устанавливает внутренний указатель массива на его последний элемент
  • key() - Выбирает ключ из массива
  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • prev() - Передвигает внутренний указатель массива на одну позицию назад
  • reset() - Устанавливает внутренний указатель массива на его первый элемент
  • next() - Передвигает внутренний указатель массива на одну позицию вперёд

User Contributed Notes

michael at squiloople dot com 10-Jan-2012 07:44
current() also works on objects:

<?php

  echo current((object) array('one', 'two')); // Outputs: one

?>
marc dot hanisch at nospam dot ateam dot de 19-May-2010 06:37
current() works with functions returning an array, too.
This is helpfull to get the first element of the returned array.

Note that current() with functions always returns the first element, because there is no variable the array was assigned to (and therefore no pointer).

Example:

<?php
//get the first element of the returned array
$element = current(get_my_arrays());
?>

In addition, current() with functions will not behave as assumed if your function returns an array reference and modifies the arrays pointer, of course!
aefxx 15-May-2008 08:39
A simple copy function that not only copies the given array but ensures the copy's pointer is set to the exact same position:

<?php
function array_copy(&array)
{
    $key = key($array);
    $copy = $array;

    while (($copy_key = key($copy)) !== NULL) {
        if ($copy_key == $key) break;
        next($copy);
    }

    return $copy;
}
?>

That's all ... bye.
gregory at gregory dot net 27-Feb-2008 09:07
It took me a while to figure this out, but there is a more consistent way to figure out whether you really went past the end of the array, than using each().

You see, each() gets the value BEFORE advancing the pointer, and next() gets the value AFTER advancing the pointer. When you are implementing the Iterator interface, therefore, it's a real pain in the behind to use each().

And thus, I give you the solution:
To see if you've blown past the end of the array, use key($array) and see if it returns NULL. If it does, you're past the end of the array -- keys can't be null in arrays.

Nifty, huh? Here's how I implemented the Iterator interface in one of my classes:

<?php

/**
 * DbRow file
 * @package PalDb
 */

/**
 * This class lets you use Db rows and object-relational mapping functionality.
 */

class DbRow implements Iterator
{
    /**
     * The DbResult object that gave us this row through fetchDbRows
     * @var DbResult
     */
    protected $result;

    /**
     * The fields of the row
     * @var $fields
     */
    protected $fields;

    /**
     * Constructor
     *
     * @param PDOStatement $stmt
     *  The PDO statement object that this result uses
     * @param DbResult $result
     *  The result that produced this row through fetchDbRows
     */
    function __construct($result)
    {
        $this->result = $result;
    }

    /**
     * Get the DbResult object that gave us this row through fetchDbRows
     * @return DbResult
     *
     * @return unknown
     */
    function getResult()
    {
        return $this->result;
    }

    function __set(
        $name,
        $value)
    {
        $this->fields[$name] = $value;
    }

    function __get(
        $name)
    {
        if (isset($this->fields[$name]))
            return $this->fields[$name];
        else
            return null;
    }

    /**
     * Iterator implementation - rewind
     */
    function rewind()
    {
        $this->beyondLastField = false;
        return reset($this->fields);
    }

    function valid()
    {
        return !$this->beyondLastField;
    }

    function current()
    {
        return current($this->fields);
    }

    function key()
    {
        return key($this->fields);
    }

    function next()
    {
        $next = next($this->fields);
        $key = key($this->fields);
        if (isset($key)) {
            return $next[1];
        } else {
            $this->beyondLastField = true;
            return false; // doesn't matter what we return here, see valid()
        }
    }

    private $beyondLastField = false;
};

Hope this helps someone.
vaclav dot sir at gmail dot com 13-Aug-2007 09:23
To that "note": You won't be able to distinguish the end of an array from a boolean FALSE element, BUT you can distinguish the end from a NULL value of the key() function.

Example:
<?php
if (key($array) === null) {
    echo "You are in the end of the array.";
} else {
    echo "Current element: " . current($array);
}
?>
marnaq 17-Aug-2006 05:20
To make this function return a reference to the element instead, use:

<?php
function &current_by_ref(&$arr) {
    return $arr[key($arr)];
}
?>
mdeng at kabenresearch dot com 23-Apr-2004 11:04
For large array(my sample was 80000+ elements), if you want to traverse the array in sequence, using array index $a[$i] could be very inefficient(very slow). I had to switch to use current($a).
vitalib at 012 dot net dot il 02-Dec-2003 02:10
Note that by copying an array its internal pointer is lost:

<?php
$myarray = array(0=>'a', 1=>'b', 2=>'c');
next($myarray);
print_r(current($myarray));
echo '<br>';
$a = $myarray;
print_r(current($a));
?>

Would output 'b' and then 'a' since the internal pointer wasn't copied. You can cope with that problem using references instead, like that:

<?php
$a =& $myarray;
?>
tipman 08-May-2003 04:07
if you got a array with number as index you get the last index with this:

eg:
$array[0] = "foo";
$array[1] = "foo2";

$lastKey = sizeof($array) - 1;

only a little help :)
retestro_REMOVE at SPAM_esperanto dot org dot il 01-Mar-2003 06:31
The docs do not specify this, but adding to the array using the brackets syntax:
     <?php $my_array[] = $new_value; ?>
will not advance the internal pointer of the array. therefore, you cannot use current() to get the last value added or key() to get the key of the most recently added element.

You should do an end($my_array) to advance the internal pointer to the end ( as stated in one of the notes on end() ), then

    <?php
     $last_key = key($my_array);  // will return the key
     $last_value = current($my_array);  // will return the value
    ?>

If you have no need in the key, $last_value = end($my_array) will also do the job.

- Sergey.
count
each
Функции для работы с массивами


Возвращает текущую пару ключ/значение из массива и смещает его указатель

current
end
Функции для работы с массивами
PHP Manual

each

(PHP 4, PHP 5)

each — Возвращает текущую пару ключ/значение из массива и смещает его указатель

Описание

array each ( array &$array )

Возвращает текущую пару ключ/значение из массива и смещает его указатель.

После выполнения each(), указатель массива перемещается к следующему его элементу, пока не будет достигнут конец массива. Для повторного обхода массива при помощи each необходимо использовать функцию reset().

Список параметров

array

Входной массив.

Возвращаемые значения

Возвращает текущую пару ключ/значение из массива array. Данная пара возвращается в массива из четырех элементов, с ключами 0, 1, key и value. Элементы 0 и key содержат имя ключа элемента массива, а 1 и value содержат его данные.

Если внутренний указатель массива указывает за его пределы, each() возвратит FALSE.

Примеры

Пример #1 Примеры использования each()

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar теперь содержит следующие пары ключ/значение:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar теперь содержит следующие пары ключ/значение:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() обычно используется совместно с list() для обхода массива, как в этом примере:

Пример #2 Обход массива функцией each()

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

Результат выполнения данного примера:

a => apple
b => banana
c => cranberry

Предостережение

Поскольку добавление элемента в массив сбрасывает указатель, вышеприведённый пример может привести бесконечному циклу, если мы будем присваивать $fruit другие значения внутри цикла.

Внимание

Функция each() также принимает и объекты, но может возратить неожиданные результаты, поэтому итерировать свойства объекта с помощью each() не рекомендуется.

Смотрите также

  • key() - Выбирает ключ из массива
  • list() - Присваивает переменным из списка значения подобно массиву
  • current() - Возвращает текущий элемент массива
  • reset() - Устанавливает внутренний указатель массива на его первый элемент
  • next() - Передвигает внутренний указатель массива на одну позицию вперёд
  • prev() - Передвигает внутренний указатель массива на одну позицию назад
  • foreach
  • Итерация объектов

User Contributed Notes

gaviel 18-Mar-2011 03:53
Ok Here's one for iterating multidimensional array .. using foreach

    <?php
        $members = array(
                            "member1" => array (
                                                "First Name" => "Robert",
                                                "Last Name" => "Burton",
                                                "Age" => "20"
                                                ),
                            "member2" => array (
                                                "First Name" => "Cheska",
                                                "Last Name" => "Vladesk",
                                                "Age" => "21"
                                                ),
                            "member3" => array (
                                                "First Name" => "Gino",
                                                "Last Name" => "Marley",
                                                "Age" => "19"
                                                ),
                            "member4" => array (
                                                "First Name" => "Jake",
                                                "Last Name" => "White",
                                                "Age" => "16"
                                                ),
                            );
        $dataSetCount = count($members);
        echo "<h1>There are $dataSetCount members</h1>";

        $i = 0;
        foreach ($members as $each_members) {
            $i++;
            echo "<h2>Member $i</h2>";
                foreach ($each_members as $position => $details) {
                    echo "<b>$position</b>" . ": " . $details . "<br />";
                }
            }
    ?>
massimo dot modica at tin dot it 03-Feb-2010 02:36
If you forget to reset the array before each(), the same code may give different results with different php versions.

<?php

$a = array(1,2,3);

foreach ($a AS $k => $v) $a[$k] = 2*$v;

while(list($k2, $v2) = each($a)) { echo($v2."\n"); }

?>

In PHP 5.2.0:

2
4
6

In PHP 5.2.6:

4
6
php at omit dot ianco dot co dot uk 13-Apr-2008 06:10
I wanted to be able to add to an array while looping through it. foreach does not allow this because it is using a secret copy of the array. each makes this possible (tested on PHP 4).
<?php
$shopping_list = array('oysters', 'caviare');
reset ($shopping_list);
while (list($key, $value) = each ($shopping_list)) {
    if ($value == 'oysters') $shopping_list[] = 'champagne';
    elseif ($value == 'champagne') $shopping_list[] = 'ice';
}
print_r($shopping_list);
// Array ( [0] => oysters [1] => caviare [2] => champagne [3] => ice )
?>
wolfeym38 at yahoo dot com 11-Jun-2007 11:28
Regarding speed of foreach vs while(list) =each
I wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways,

<?php
function getDiff($start, $end) {
    $s = explode(' ', $start);
    $stot = $s[1] + $s[0];
    $e = explode(' ', $end);
    $etot = $e[1] + $e[0];
    return $etot - $stot;
}

$lim=10000000;
$arr = array();
for ($i=0; $i<$lim; $i++) {
    $arr[$i] = $i/2;
}

$start = microtime();
foreach ($arr as $key=>$val);

$end = microtime();
echo "time for foreach = " . getDiff($start, $end) . ".\n";

reset($arr);
$start = microtime();
while (list($key, $val) = each($arr));
$end = microtime();
echo "time list each = " . getDiff($start, $end) . ".\n";
?>

here are some of my results: with 1,000,000
time for foreach = 0.0244591236115.
time list each = 0.158002853394.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0245339870453.
time list each = 0.154260158539.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0269000530243.
time list each = 0.157305955887.

then with 10,000,000:
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 1.96586894989.
time list each = 14.1371650696.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.02504014969.
time list each = 13.7696218491.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.0246758461.
time list each = 13.8425710201.

by the way, these results are with php 5.2 i believe, and a linux machine with 3gb of ram and 2.8ghz dual core pentium
michael k (name der redaktion bekannt.) 10-May-2007 12:36
If you want to iterate over a two-dimensional, sparse array, and want to  first display every first element, then every second and so on, you can use this code:

 $fruits = array ( "fruits"  => array ( "a" => "orange",
                                      "b" => "banana",
                                      "c" => "apple"
                                    ),
                 "numbers" => array ( 1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      6
                                    ),
                 "holes"   => array (      "first",
                                      5 => "second",
                                           "third",
                                     10 => "fourth",
                                    )
               );

$done = False;
while ($done == False) {
       $done = True;

       // Important: &$val has to be a reference (use the &),
       // if you don't, the internal counter of $val will be
       // re-initialized each time and you loop over the first elements
       // for eternity.

       foreach($fruits as $key => &$val) {

               if (list($inner_key, $inner_val) = each(&$val)) {
                       $done = False;
                       echo "$key : : $inner_key => $inner_val  <br>  \n";
               }

       }
}

NOTE: this is just a quick hack, if you know a better way, post it!
sjoerd-php at linuxonly dot nl 31-Mar-2006 06:04
Use foreach instead of while, list and each. Foreach is:
- easier to read
- faster
- not influenced by the array pointer, so it does not need reset().

It works like this:
<?php
$arr = array('foo', 'bar');
foreach ($arr as $value) {
    echo "The value is $value.";
}

$arr = array('key' => 'value', 'foo' => 'bar');
foreach ($arr as $key => $value) {
    echo "Key: $key, value: $value";
}
?>
matthew at mhalls dot net 04-Dec-2005 03:58
To panania at 3ringwebs dot com:

If you know for certain that you are only receiving one row, the while becomes redundant. To shorten your code:

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
list($key, $val) = mysql_fetch_row($RecordsetSelect);
echo "$key => $val\n";
mysql_free_result($RecordsetSelect);

With only one row being returned this is more elegant a solution, but just being nit-picky in essence. It also shows another quick way of using list.
amby2 at izh dot com 24-Nov-2005 09:55
I've found a compact way to cycle through an associative array using for statement (not while, as it has been done in the most of examples below):

<?php

for (reset($array); list($key) = each($array);) {
  echo $key;
  echo $array[$key];
}

?>

or

<?php

for (reset($array); list($key, $value) = each($array);) {
  echo $key;
  echo $value;
  echo $array[$key];
}

?>

You hardly forget to add reset($array) code line using such construction.
Sopinon 23-Jul-2005 05:17
If you want to display the hole structure (tree) of your array, then you can use this recursive solution.

<?PHP
$tree= "";
array_tree($your_array);
echo $tree;

// Recursive Function
function array_tree($array, $index=0){
    global $tree;
    $space="";
    for ($i=0;$i<$index;$i++){
        $space .= "     ";
    }
    if(gettype($array)=="array"){
        $index++;
        while (list ($x, $tmp) = each ($array)){
            $tree .= $space."$x => $tmp\n";
            array_tree($tmp, $index);
        }
    }
}
?>
james at gogo dot co dot nz 02-Nov-2004 07:29
It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.

<?php
  $x = array(1,2,3);

  print_r(each($x));
  echo "\n";

  $y =& $x;
  print_r(each($y));
  echo "\n";

  $z =& $y;
  print_r(each($z));
  echo "\n";
?>
panania at 3ringwebs dot com 31-Dec-2003 05:51
The last method for record sets is great if you don't know the number of rows returned from a query, but if you do there's an easier way...

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
$row_Recordset1 = mysql_fetch_assoc($RecordsetSelect);
while (list($key, $val) = each($row_Recordset1)) {
    echo "$key => $val\n";
}
mysql_free_result($RecordsetSelect);

Here we know that only 1 record will be returned because of the WHERE criteria. (Of course this is dependent on you own DB schema.)
wodzuY2k at anronet dot pl 04-Aug-2002 12:41
This function will help you dump any variable into XML structure.

        //dump var into simple XML structure
        function var_dump_xml($tagname,$variable,$level=0)
         {
            for($i=0;$i<$level;$i++) $marg.=' ';
            if (eregi('^[0-9].*$',$tagname)) $tagname='tag_'.$tagname; //XML tag cannot start with [0-9] character
            if (is_array($variable))
             {
                echo $marg."<$tagname>\n";
                while (list ($key, $val) = each ($variable))  var_dump_xml($key,$val,$level+1);
                echo $marg."</$tagname>\n";
             }
            elseif (strlen($variable)>0)
             {
                 echo $marg."<$tagname>".htmlspecialchars($variable)."</$tagname>\n";
             };
         };

        /*
        example:

        $myVar = array("name"=>"Joe", "age"=>"26", "children"=>array("Ann","Michael"));
        var_dump_xml("myVarTag",$myVar);
        */
Gillis at dancrea dot com 26-May-2002 10:13
I wrote a short and pretty simple script to search through associative arrays for some value in the values, heres a simplifyed example of it:

<?php

$foo['bob'] = "bob is ugly";
$foo['bill'] = "bill is rich";
$foo['barbie'] = "barbie is cute";
$search = "rich";

echo "searching the array foo for $search:<br>";
reset ($foo);
while (list ($key, $val) = each ($foo)) {
if (preg_match ("/$search/i", $val)) {
    print "A match was found in $key.<br />";
} else {
    print "A match was not found in $key.<br />";
}
}

?>

will output:
Searching the array foo for rich:
A match was not found in bob
A match was found in bill
A match was not found in barbie
wodzuY2k at anronet dot pl 08-May-2002 09:40
Yet another useful example of how to make globals out of the config file.

config file:
[section1]
 value=foo

PHP result :
variable: $section1_value=foo;

function servicesConfig_makeGlobals()
 {
    global $servicesConfig;
    $servicesConfig = parse_ini_file("servicesConfig.conf", TRUE);
    reset($servicesConfig);
    while (list ($section, $section_val) = each ($servicesConfig))
     {
         reset($servicesConfig[$section]);
        while (list ($key, $val) = each ($servicesConfig[$section]))
         {
            $GLOBALS[$section.'_'.$key]=$val;
         };
     };
 };
13-Feb-2002 04:10
I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one.

It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values).

while (list ($x, $tmp) = each ($array)) {
   while (list ($y, $val) = each ($tmp)) {
      echo "$x, $y, $val";
   }
}

The answer for each (x,y) pair can thus be (providng, of course those values where in your array beforehand):

1, 1, 2
2, 2, 0
3, 1, 1
5, 2, 2
5, 1, 2

Note that only the (x,y) pairs with a corresponding value is shown.

Hang in there
Jon Egil Strand
NTNU
tk at turtle-entertainment dot de 29-Jan-2001 11:33
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
kris at angelanthony dot com 25-Oct-2000 01:03
Remember to use "reset()" if you iterate over an array with "each()" more than once!  Example:

while(list($key,$value) = each($array)){
 // code here
}

NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block.  You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.
phpmanual at devin dot com 14-Jul-2000 05:26
Note further that each() performs a shallow copy
of the value side of an (assoc) array; if you need to iterate on deep structures, something like:

<?php

reset($A); while (list($k,) = each($A)) {
    $elem = &$A[$k];
    /* ... */
}

?>

Is needed.  Copy construction would be handy to have here.
ellenzhg at hotmail dot com 30-Mar-2000 12:06
<?php
//each.php

$foo = array( "Robert" => "Bob", "Seppo" => "Sepi" );
$bar = each( $foo );
$k = implode(array_keys($bar),",");
$v = implode(array_values($bar),",");
echo $k ."<br>";
echo $v;
?>

output:
1,value,0,key
Bob,Bob,Robert,Robert
Above example only be interpretered by PHP4.
pyxl at dont_spam_on_me dot jerrell dot com 16-Feb-2000 03:41
Ok, for you folks who are learning this, here's something that should help your comprehension of each(), because I bashed my brains for a while on this one.

The first example indicates that each() spits out a 4-cell 1 dimensional array.  This is all fine and dandy until you get to the second example, where that seems to be thrown out the window, because though each() is still spitting out 4 array elements, the list() being used is set up to only accept 2 values, as it's being executed with only wo variables in it!

For some folks, this might not be a problem, but I couldn't understand the mismatch - why was it done, and where did the array go that each() generated??  Well, upon executing that code, it turns out that the first two array elements of the 4 element array that each() creates are assigned to those two variables, and the last two array element values are just thrown away - they're totally ignored.  It's how PHP is written.

Now, why do that?  Well, the example was definitely written more to show folks how to use each() to make life much easier when dealing with a particular operations array in PHP that a lot of people work with, but it also has the side effect (which hopefully my little explaination has made more palatable) of demonstrating how each() can act when being used with other functions that don't necessarily want all of each()'s input.
current
end
Функции для работы с массивами


Устанавливает внутренний указатель массива на его последний элемент

each
extract
Функции для работы с массивами
PHP Manual

end

(PHP 4, PHP 5)

end — Устанавливает внутренний указатель массива на его последний элемент

Описание

mixed end ( array &$array )

end() устанавливает внутренний указатель array на последний элемент и возвращает его значение.

Список параметров

array

Массив. Этот массив передается по ссылке, потому что он модифицируется данной функцией. Это означает что вы должны передать его как реальную переменную, а не как функцию, возвращающую массив, так как по ссылке можно передавать только реальные переменные.

Возвращаемые значения

Возвращает значение последнего элемента или FALSE для пустого массива.

Примеры

Пример #1 Пример использования end()

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

Смотрите также

  • current() - Возвращает текущий элемент массива
  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • prev() - Передвигает внутренний указатель массива на одну позицию назад
  • reset() - Устанавливает внутренний указатель массива на его первый элемент
  • next() - Передвигает внутренний указатель массива на одну позицию вперёд

User Contributed Notes

jorge at REMOVETHIS-2upmedia dot com 01-Mar-2012 01:20
If all you want is the last item of the array without affecting the internal array pointer just do the following:

<?php

function endc( $array ) { return end( $array ); }

$items = array( 'one', 'two', 'three' );
$lastItem = endc( $items ); // three
$current = current( $items ); // one
?>

This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
Tim C 16-Dec-2010 07:41
An easy (and correct) way to get the last key:
$lastkey = array_pop(array_keys($arr));
franz at develophp dot org 01-Dec-2010 03:06
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

    <?php
    $a = array();
    $a[1] = 1;
    $a[0] = 0;
    echo end($a);
    ?>

This will print "0".
laurence at crazypillstudios dot com 07-Jun-2010 02:12
this is a function to move items in an array up or down in the array. it is done by breaking the array into two separate arrays and then have a loop creates the final array adding the item we want to move when the counter is equal to the new position we established the array key, position and direction were passed via a query string

<?php
//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
    //count the original number of rows
    $count = count($array);
    //set the integer we will use to place the moved item
    if($dir=="up"){
        if($pos==1){
            //if the item is already first and we try moving it up
            //we send it to the end of the array
            $change = $count;
        }else{
            //anywhere else it just moves back one closer to the start of the array
            $change = $pos-1;
        }
    }
    //do the same for the down button
    if($dir=="dn"){
        if($pos==$count){
            $change = 1;
        }else{
            $change = $pos+1;
        }
    }
    //copy the element that you wish to move
    $move = $array[$keytomove];
    //delete the original from the main array
    unset($array[$keytomove]);
    //create an array of the names of the values we
    //are not moving
    $preint = 1;
    foreach($array as $c){
        $notmoved["{$preint}"] = $c['name'];
    $preint++;
    }
    //loop through all the elements
    $int = 1;
    while($int<=$count){
        //dynamically change the key of the unmoved item as we increment the counter
        $notmovedkey = $notmoved["$int"];
        //when the counter is equal to the position we want
        //to place the moved entry we pump it into a new array
        if($int==$change){
            $neworder["{$keytomove}"] = $move;
        }
        //add all the other array items if the position number is not met and
        //resume adding them once the moved item is written
        if($contkey!=""){
            $neworder["{$notmovedkey}"] = $array["{$notmovedkey}"];
        }
    $int++;
    }

    return($neworder);
}
?>

This is not too elegant but it works.
Sam Yong - hellclanner at live dot com 23-Aug-2009 05:05
Take note that end() does not recursively set your multiple dimension arrays' pointer to the end.

Take a look at the following:
<?php

// create the array for testing
$a = array();
$i = 0;
while($i++ < 3){
$a[] = array(dechex(crc32(mt_rand())),dechex(crc32('lol'.mt_rand())));
}

// show the array tree
echo '<pre>';var_dump($a);

// set the pointer of $a to the end
end($a);

// get the current element of $a
var_dump(current($a));
// get the current element of the current element of $a
var_dump(current(current($a)));

?>

You will notice that you probably get something like this:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "764d8d20"
    [1]=>
    string(8) "85ee186d"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "c8c72466"
    [1]=>
    string(8) "a0fdccb2"
  }
  [2]=>
  array(2) {
    [0]=>
    string(8) "3463a31b"
    [1]=>
    string(8) "589f6b63"
  }
}

array(2) {
  [0]=>
  string(8) "3463a31b"
  [1]=>
  string(8) "589f6b63"
}

string(8) "3463a31b"

The array elements' pointer are still at the first one as current. So do take note.
admin at nabito dot net 06-Aug-2008 12:04
This is simple way how to get file extension.

<?php
$filename = 'somefile.jpg';
echo end(explode(".", $filename)); // return jpg string

$filename = 'the_another_file.html';
echo end(explode(".", $filename)); // return html string
?>
jasper at jtey dot com 11-Jul-2006 12:48
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:

<?php
// Returns the key at the end of the array
function endKey($array){
 end($array);
 return key($array);
}
?>

Usage example:
<?php
$a = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($a); // will output "three"
?>
ken at expitrans dot com 27-Oct-2005 09:02
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:

<?php

echo ">> ".end(array_keys(array('x' => 'y')))."\n";

?>

which will return "Fatal error: Only variables can be passed by reference" in version <= 5.0.4 but not in 5.0.5.

If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:

<?php

$x = array_keys(array('x' => 'y'));
echo ">> ".end($x)."\n";

?>
28-Aug-2002 06:34
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:

<?php
function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}

function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}
?>
28-Aug-2002 06:17
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array:

<?php
function array_add(&$array, $value) {
$array[] = $value; // add an element
end($array); // important!
return key($array);
}
?>
each
extract
Функции для работы с массивами


Импортирует переменные из массива в текущую таблицу символов

end
in_array
Функции для работы с массивами
PHP Manual

extract

(PHP 4, PHP 5)

extract — Импортирует переменные из массива в текущую таблицу символов

Описание

int extract ( array &$var_array [, int $extract_type = EXTR_OVERWRITE [, string $prefix = NULL ]] )

Импортирует переменные из массива в текущую таблицу символов.

Каждый ключ проверяется на предмет корректного имени переменной. Также проверяются совпадения с существующими переменными в символьной таблице.

Список параметров

var_array

Ассоциативный массив. Эта функция рассматривает ключи массива в качестве имен переменных, а их значения - в качестве значений этих переменных. Для каждой пары ключ/значение будет создана переменная в текущей таблице символов, в соответствии с параметрами extract_type и prefix.

Вы должны использовать ассоциативный массив, использование числовых массивов не приведёт ни к каким результатам, если вы не используете EXTR_PREFIX_ALL или EXTR_PREFIX_INVALID.

extract_type

Параметр extract_type определяет способ трактования неправильных/числовых ключей и коллизий. Он может принимать следующие значения:

EXTR_OVERWRITE
Если переменная с таким именем существует, она будет перезаписана.
EXTR_SKIP
Если переменная с таким именем существует, ее текущее значение не будет перезаписано.
EXTR_PREFIX_SAME
Если переменная с таким именем существует, к её имени будет добавлен префикс, определённый параметром prefix.
EXTR_PREFIX_ALL
Добавить префикс prefix ко всем именам переменных.
EXTR_PREFIX_INVALID
Добавить префикс prefix только к некорректным/числовым именам переменных.
EXTR_IF_EXISTS
Перезаписать только переменные, уже имеющиеся в текущей таблице символов, в противном случае не делать ничего. Данная возможность полезна для определения списка приемлемых переменных и для извлечения только тех переменных, которые вы уже определили из массивов типа $_REQUEST, например.
EXTR_PREFIX_IF_EXISTS
Создать только префикс-версии переменных, если версия данной переменной без префикса уже существует в текущей символьной таблице.
EXTR_REFS
Извлечь переменные как ссылки. Это означает, что значения таких переменных будут всё ещё ссылаться на значения массива var_array. Вы можете использовать этот флаг отдельно или комбинировать его с другими значениями extract_type с помощью побитового 'или'.

Если extract_type не указан, он трактуется как EXTR_OVERWRITE.

prefix

Обратите внимание, что prefix имеет значение, только если extract_type установлен в EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID или EXTR_PREFIX_IF_EXISTS. Если в результате добавления префикса, не будет получено допустимое имя для переменной, она не будет импортирована в текущую символьную таблицу.

Возвращаемые значения

Возвращает количество переменных, успешно импортированных в текущую таблицу символов.

Список изменений

Версия | Описание
4.3.0 | Добавлена константа EXTR_REFS.
4.2.0 | Добавлены константы EXTR_IF_EXISTS и EXTR_PREFIX_IF_EXISTS.
4.0.5 | Эта функция теперь возвращает количество извлеченных переменных. Добавлена константа EXTR_PREFIX_INVALID. Константа EXTR_PREFIX_ALL также включает числовые переменные.

Примеры

Пример #1 Пример использования extract()

Функцию extract() также можно использовать для импорта в текущую таблицу символов переменных, содержащихся в ассоциативном массиве, возвращённом функцией wddx_deserialize().

<?php

/* Предположим, что $var_array - это массив, полученный в результате
   wddx_deserialize */

$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?>

Результат выполнения данного примера:

blue, large, sphere, medium

Переменная $size не была перезаписана, потому что мы определили EXTR_PREFIX_SAME, в результате чего была создана переменная $wddx_size. Если был бы определён флаг EXTR_SKIP, тогда переменная $wddx_size не была бы создана. EXTR_OVERWRITE была бы причиной того, что переменной $size было бы присвоено значение "medium", и EXTR_PREFIX_ALL была бы причиной того, что были бы также созданы новые переменные $wddx_color, $wddx_size и $wddx_shape.

Примечания

Внимание

Не используйте функцию extract() на непроверенных данных, таких как пользовательский ввод ($_GET, $_FILES и т.п.). Если вы сделаете это, например, для того, что бы временно запустить старый код, использующий register_globals, используйте соответствующий флаг extract_type для того, что бы не перезаписать уже установленные переменные, такой как EXTR_SKIP и удостоверьтесь, что вы извлекаете содержимое в том же порядке, что указан в директиве variables_order в php.ini.

Замечание:

Если у вас включена директива register_globals и вы используете extract() с массивом $_FILES и параметром EXTR_SKIP, вы можете быть удивлены результатами.

Внимание

Это нерекомендуемая практика и документирована здесь только для полноты картины. Использование register_globals считается устаревшим и вызов extract() на непроверенных данных, таких как $_FILES, как уже было сказано выше, потенциальный риск безопасности. Если вы столкнулись с данным случаем, это означает что вы используете как минимум две плохие практики кодирования.

<?php

/* Предположим, что $testfile это имя input загрузки файла
   и что директива register_globals включена. */

var_dump($testfile);
extract($_FILES, EXTR_SKIP);
var_dump($testfile);
var_dump($testfile['tmp_name']);

?>
Вы можете ожидать что-нибудь вроде следующего:
string(14) "/tmp/phpgCCPX8"
array(5) {
  ["name"]=>
  string(10) "somefile.txt"
  ["type"]=>
  string(24) "application/octet-stream"
  ["tmp_name"]=>
  string(14) "/tmp/phpgCCPX8"
  ["error"]=>
  int(0)
  ["size"]=>
  int(4208)
}
string(14) "/tmp/phpgCCPX8"
Однако, вместо этого вы увидите что-нибудь вроде этого:
string(14) "/tmp/phpgCCPX8"
string(14) "/tmp/phpgCCPX8"
string(1) "/"

Это происходит потому, что так как включена директива register_globals, переменная $testfile уже существует в глобальной области видимости в момент вызова extract(). А так как указан параметр EXTR_SKIP, $testfile не будет перезаписана содержимым массива $_FILES, поэтому $testfile останется строкой. Так как к строкам можно обращаться с помощью синтаксиса массивов и нечисловая строка tmp_name интерпретируется как 0, PHP воспринимает $testfile['tmp_name'] как $testfile[0].

Смотрите также

  • compact() - Создает массив, содержащий названия переменных и их значения
  • list() - Присваивает переменным из списка значения подобно массиву

User Contributed Notes

Robc 01-Nov-2011 06:30
When extracting from a row after a database query using for example:

$row = mysql_fetch_array($result, MYSQL_ASSOC)
extract($row);

I find that the resultant variables may not match the variable type in the database.  In particular I have found integers in the database may gettype() to string on the extracted variable.
darylblake at gmail dot com 12-Apr-2011 05:07
Warning: in larger php web applications this is not a good choice. Use of this function will not help maintainability of your code.

please read php warnings about using this on untrusted data:

<?php
$sql=query("SELECT * FROM contact WHERE contact_id='$invoicedata_clientcontact'");
        if ($tmp=fetch_array($sql))
        {
            extract($tmp);
        }
?>

it will create variables that may overwrite other variables and can cause strange behaviour, advise against using this function if at all possible.
Justin Heesemann 15-Jul-2010 07:32
This function shows odd behavior when used in class methods and an array key called "this" is being extracted:

<?php
class a {
        protected $foo;
        function b ($r) {
                extract($r);
                var_dump($this);
                //properties still can be acccessed:
                $this->foo = "bling";
                echo $this->foo,"\n";
                // next line would stop the script from compiling
                //$this = "this will raise a fatal error";

        }
}

$a = new a();
$a->b(array("this" => "that"));
?>

prints:
string(4) "that"
bling
Rodrigo 15-Jun-2010 09:41
Here's a way to use extract in $_FILES arrays without using register_gloabals on.

I started to use extract a few weeks ago, and my codes hasn't been so clean since then. The use of the arrays $_POST and $_GET is ok, but one missed doublequote causes a lot of trouble.

Besides I teach PHP in a school, and this function has made my examples easier.

<?php
if(isset($_FILES["file"])){
    extract($_FILES);
    extract($file);
    echo $name."<br>";
    echo $tmp_name."<br>";
    echo $size."<br>";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form action="" method="post" enctype="multipart/form-data" name="form1">
  <p>
    <input type="file" name="file">
</p>
  <p>
    <input type="submit" name="Submit" value="Enviar">
</p>
</form>
</body>
</html>

Hope this can help anyone.
auto493097 at hushmail dot com 23-Feb-2010 10:07
I use XDebug with NetbeansIDE to for analyzing and developing PHP Code. When debugging an extract statement no new variables appeared in the variable's list. Although all variables created by extract could be examined by explicit watch items and single variables appeared as soon as an PHP script makes use of them I am not sure weather it is a wrong configuration, a feature or a bug in XDebug.
danbettles at yahoo dot co dot uk 24-Aug-2009 04:04
When using EXTR_PREFIX_ALL - and probably all the other EXTR_PREFIX_* constants - and a numerically-indexed array, extract() will add an underscore ("_") between the prefix and the index.

<?php

extract(array('foo', 'bar'), EXTR_PREFIX_ALL, 'var');

print_r(get_defined_vars());  // Reveals $var_0 = 'foo' and $var_1 = 'bar'
?>
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 07:15
In the meantime, I'm using this:

// extract alternative
# extracts variables where new value is above the threshold or if old value is on or below the threshold (or var is not defined)
# an associative array is obviously the sane thing to pass
#
# I am absolutely certain someone will find obvious problems or errors with this
# I haven't even tried to compare other values than 0 so if you need to do that and surely finds obvious flaws,
# please mail me, I'd really like to know.
# benjaminATwebbutvecklarnaDOTse

// usage example:
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM site_preset WHERE ID = $site_id")));
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM category_preset WHERE ID = $category_id")));

function thrextract($arr,$thr = 0){
    foreach($arr as $key => $var){
        global $$key;
        if($var > $thr or $$key <= $thr) $$key = $var;
    }
}
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 06:19
Re: anon at anon dot org, about extract() and null values

Personally I've found use extracting multiple resultsets from db where the latter would overwrite the previous when a variable is not null ( and optionally if its not >0 )

It would be useful if $extract_type was extended on top of these two:

EXTR_OVERWRITE
EXTR_SKIP

with something like this:

EXTR_OVERWRITE_NULL
 - If there is a collision, overwrite the existing variable if it is null

EXTR_OVERWRITE_0
 - Same thing but == 0 or null

EXTR_SKIP_NULL
 - If there is a collision, skip the new variable if the existing is not null

EXTR_SKIP_0
 - Same thing but == 0 or null

Those ought to cover a few good cases that aren't covered now.
Hayley Watson 13-Mar-2008 03:18
Dan O'Donnell's suggestion needs a third requirement to work as described:

c) No other variables are defined - especially variables that contain potentially sensitive information.

Without that condition the difference between extract() and assigning variables by hand (and the resulting security implications) should be obvious.

The only valid security step there is (b) - but you should be doing that anyway.
Dan O'Donnell 21-Apr-2007 12:25
Following up on ktwombley at gmail dot com's post:

Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure

a) your define acceptable input variables beforehand (i.e. as empty variables)
b) Sanitise any user input to avoid unacceptable variable content.

If you do these two things, then I'm not sure I see the difference between extract($_REQUEST,EXTR_IF_EXISTS); and assigning each of the variables by hand.

I'm not talking here about the idea of storing the variables in a database, just the immediately necessary steps to allow you to use extract on REQUEST arrays with relative safety.
Dutchdavey 13-Mar-2007 12:26
I would draw your attention to the user note at the very end of this page regarding PREFIXES. The user points out that php adds a '_' to your prefixes.
ktwombley at gmail dot com 31-Aug-2006 10:05
It's really easy to open gaping security holes using extract() on $_REQUEST, $_GET, etc. You have to be really sure of what you're doing, and use the proper flags on extract() to avoid clobbering important variables.

For instance, the submission by kake26 at gmail dot com will not only perfectly emulate register globals (that's bad), but it'll store it in a database and recall the same variables every time the script runs (essentially allowing an attacker to attack your script every time it runs via one attack). Oops!

To fix it, you'd have to get creative with flags. Maybe you could use EXTR_PREFIX_ALL instead of EXTR_OVERWRITE, for example. Of course, you should also sanitize the form elements to ensure there's no php code in them, and also to make sure any very important variables aren't in the form data. (like the classic $is_admin = true attack)
nicolas zeh 16-Mar-2006 09:24
This function provides exactly the same functionality as extract except that a parameter was added defining the extract target.
This function can be used if your PHP installation does not support the required Flags or more important if you would like to extract arrays to another destination as to $GLOBALS, i.e. other arrays or objects.
The only difference to extract is that extract_to moves the array pointer of $arr to the end as $arr is passed by reference to support the EXTR_REFS flag.

<?php
    if( !defined('EXTR_PREFIX_ALL') ) define('EXTR_PREFIX_ALL', 3);
    if( !defined('EXTR_PREFIX_INVALID') ) define('EXTR_PREFIX_INVALID', 4);
    if( !defined('EXTR_IF_EXISTS') ) define('EXTR_IF_EXISTS', 5);
    if( !defined('EXTR_PREFIX_IF_EXISTS') ) define('EXTR_PREFIX_IF_EXISTS', 6);
    if( !defined('EXTR_REFS') ) define('EXTR_REFS', 256);

    function extract_to( &$arr, &$to, $type=EXTR_OVERWRITE, $prefix=false ){

        if( !is_array( $arr ) ) return trigger_error("extract_to(): First argument should be an array", E_USER_WARNING );

        if( is_array( $to ) ) $t=0;
        else if( is_object( $to ) ) $t=1;
        else return trigger_error("extract_to(): Second argument should be an array or object", E_USER_WARNING );

        if( $type==EXTR_PREFIX_SAME || $type==EXTR_PREFIX_ALL || $type==EXTR_PREFIX_INVALID || $type==EXTR_PREFIX_IF_EXISTS )
            if( $prefix===false ) return trigger_error("extract_to(): Prefix expected to be specified", E_USER_WARNING );
            else $prefix .= '_';

        $i=0;
        foreach( $arr as $key=>$val ){

            $nkey = $key;
            $isset = $t==1 ? isset( $to[$key] ) : isset( $to->$key );

            if( ( $type==EXTR_SKIP && $isset )
                || ( $type==EXTR_IF_EXISTS && !$isset ) )
                    continue;

            else if( ( $type==EXTR_PREFIX_SAME && $isset )
                || ( $type==EXTR_PREFIX_ALL )
                || ( $type==EXTR_PREFIX_INVALID && !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $key ) ) )
                    $nkey = $prefix.$key;

            else if( $type==EXTR_PREFIX_IF_EXISTS )
                if( $isset ) $nkey = $prefix.$key;
                else continue;

            if( !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $nkey ) ) continue;

            if( $t==1 )
                if( $type & EXTR_REFS ) $to->$nkey = &$arr[$key];
                else $to->$nkey = $val;
            else
                if( $type & EXTR_REFS ) $to[$nkey] = &$arr[$key];
                else $to[$nkey] = $val;

            $i++;
        }

        return $i;
    }

    // e.g.:
    extract_to( $myarray, $myobject, EXTR_IF_EXISTS );
?>
owk dot ch199_ph at gadz dot org 08-Mar-2006 04:21
And if you want with PHP 5 an easy way to extract $V by reference, try this :
<?php
    foreach ($V as $k => &$v) {
        $$k =& $v;
    }
?>
It can be used to create special kind of "free args" functions that let you choose when you call them the way you send variables, and which ones. They are moreover very fast to call thanks to references :
<?php
    function free_args (&$V) {
        foreach ($V as $k => &$v) {
            $$k =& $v;
        }
        unset ($k);  unset ($v);  unset ($V);

        // be careful that if you need to extract $k, $v or $V variables you should find other names for them in the lines above (ie. $__k, $__v and $__V)
    }

    $huge_text = '...';

    $a = array ('arg1' => 'val1', 'arg2' => &$huge_text); // in this call, only $arg2 will be a true reference in the function
    free_args ($a);
?>
Be warned that you can't write : "<?php free_args (array ('arg1' => 'val1')); ?>" because the array can't be referenced by the function, as it's not yet created when the function starts.
moslehi<atsign>gmail<d0t>c0m 20-Jan-2006 01:32
Experimentally I found that calling extract() also shows the number of keys if the key is set and is not numeric ! Maybe there was a better definition than mine  . Please have a look to this scripts :

<?PHP
$var["i"] = "a";
$var["j"] = "b";
$var["k"] = 1;
echo extract($var); // returns 3
?>

<?PHP
$var2["i"] = "a";
$var2[2] = "b";
$var2[] = 1;
echo extract($var2); // returns 1
?>

(Arash Moslehi)
Csaba at alum dot mit dot edu 27-Nov-2005 11:41
Sometimes you may want to extract only a named subset of the key/value pairs in an array.  This keeps things more orderly and could prevent an unrelated variable from getting clobbered from an errant key.  For example,

$things = 'unsaid';
$REQUEST = array(He=>This, said=>1, my=>is, info=>2, had=>a,
                 very=>3, important=>test, things=>4);
$aVarToExtract = array(my, important, info);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));

will extract
$my = 'is';
$important = 'test';
$info = 2;

but will leave certain
$things = 'unsaid'

Csaba Gabor from Vienna
NB.  Of course the composite request coming in from a web page is in $_REQUEST.
anon at anon dot org 30-May-2005 12:02
A warning about extract() and null values.

This might be an actual Zend2 Engine bug, but it's bad programming practice, so I'm sharing it here instead.

I often work in envrionments where E_STRICT (which would prevent errors like this) isn't on, and I don't have access to change it. I also use a very simple template class that in a nutshell works like this:

$t = new Template('somefile.php');
$t->title = $title;
$t->body = $body;
$t->display();

display() more or less looks like this:

function display(){
    extract(get_object_vars($this),EXTR_REFS);
    ob_start(); include $this->templateFileName;
    return ob_get_clean();
}

If any of the assigned values are null (let's say that in this case $title wasn't initialized above) it causes the engine to do all sorts of incredibly whacky stuff like certifiably lose track of variables in an incredibly inconsistent way. I traced the problem down to the fact that it's using the EXTR_REFS flag. I assume that in PHP's internal variable storage or reference counting mechanism, that trying to extract null references makes it lose track or count of something or rather.

In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn't contain null keys or values!
kake26 at gmail dot com 30-Apr-2005 08:59
The following is a neat use for extract to store and manipulate large amounts of form data from. I basically loop through the $_POST and implode it seperating the key and value pairs by a space. Then store it in a db, the reversing function basically explodes the string to a array. Then converts the indexed array to a associative array then uses extract to seal the deal and make it easily available within a program. My main reason for sharing these are the fact I make some big web applications that store allot of forum data in a DB and these functions make it very easy to quickly and easily store and recall the data. I've contributed it because I spent many hours creating this code and recall going "I wish someone had previously submitted it to the page notes". Would have saved me allot of time and agony and I'm sure I'm not the only person that could really benefit from it, so I decided to share.

<?php
$stack = array();
foreach ($_POST as $key => $value) {
array_push($stack, $key, $value);
}
// store it
$block = implode(" ",$stack); // yeilds a space delimited string
// insert query to store string in DB here, like the one below
$query = "INSERT INTO `sometable` VALUES('".$seluser."','".addslashes($block)."');";
$result = mysql_query($query) or die("Query failed for block insert: " . mysql_error());
// note $seluser in my case is a user ID associated with that block
// in one of my web apps
?>

The nice thing is with the above we can quickly create a string of key and value pairs from the data the script got. Without really caring what their names are. You know how if register globals are on you say $someformvar rather than $_POST["someformvar"]; , basically the code below reads this previous created block returns it to that state. Sort of like presistant register globals.

<?php
// insert query to grab the previously stored string here
$query = "SELECT * FROM `sometable` WHERE `blockid` = '".addslashes($bid)."';";
$result = mysql_query($query) or die("Query failed read: " . mysql_error());
$sql = mysql_fetch_array($result, MYSQL_ASSOC);
$array = eplode(" ",$sql["data"]);
for ($i = 0; $i < sizeof($array); $i+=2) {
$myassoc[$array[$i]] = isset($array[$i+1])?$array[$i+1]:NULL;
}
extract($myassoc, EXTR_OVERWRITE);
// now you're key and value pairs from $_POST have been restored
// instead of $_POST
?>
pg dot perfection at gmail dot com 14-Mar-2005 02:33
Here is a little example of how an extraction method should look like when it needs to work recursive (work on nested_arrays too)...

Note that this is only an example, it can be done more easily, and more advanced too.

<?php
/**
 * A nested version of the extract () function.
 *
 * @param    array    $array        The array which to extract the variables from
 * @param    int        $type        The type to use to overwrite (follows the same as extract () on PHP 5.0.3
 * @param    string    $prefix        The prefix to be used for a variable when necessary
 */
function extract_nested (&$array, $type = EXTR_OVERWRITE, $prefix = '')
{
    /**
     *  Is the array really an array?
     */
    if (!is_array ($array))
    {
        return trigger_error ('extract_nested (): First argument should be an array', E_USER_WARNING);
    }

    /**
     *  If the prefix is set, check if the prefix matches an acceptable regex pattern
     * (the one used for variables)
     */
    if (!empty ($prefix) && !preg_match ('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $prefix))
    {
        return trigger_error ('extract_nested (): Third argument should start with a letter or an underscore', E_USER_WARNING);
    }

    /**
     * Check if a prefix is necessary. If so and it is empty return an error.
     */
    if (($type == EXTR_PREFIX_SAME || $type == EXTR_PREFIX_ALL || $type == EXTR_PREFIX_IF_EXISTS) && empty ($prefix))
    {
        return trigger_error ('extract_nested (): Prefix expected to be specified', E_USER_WARNING);
    }

    /**
     * Make sure the prefix is oke
     */
    $prefix = $prefix . '_';

    /**
     *  Loop thru the array
     */
    foreach ($array as $key => $val)
    {
        /**
         *  If the key isn't an array extract it as we need to do
         */
        if (!is_array ($array[$key]))
        {
            switch ($type)
            {
                default:
                case EXTR_OVERWRITE:
                    $GLOBALS[$key] = $val;
                break;
                case EXTR_SKIP:
                    $GLOBALS[$key] = isset ($GLOBALS[$key]) ? $GLOBALS[$key] : $val;
                break;
                case EXTR_PREFIX_SAME:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_ALL:
                    $GLOBALS[$prefix . $key] = $val;
                break;
                case EXTR_PREFIX_INVALID:
                    if (!preg_match ('#^[a-zA-Z_\x7f-\xff]$#', $key{0}))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                break;
                case EXTR_REFS:
                    $GLOBALS[$key] =& $array[$key];
                break;
            }
        }
        /**
         *  The key is an array... use the function on that index
         */
        else
        {
            extract_nested ($array[$key], $type, $prefix);
        }
    }
}
?>
Michael Newton 02-Mar-2005 05:23
They say "If the result is not a valid variable name, it is not imported into the symbol table."

What they should say is that if _any_ of the results have invalid names, _none_ of the variables get extracted.

Under 4.3.10 on Windows 2000, I was pulling some mySQL records, but needed to convert two fields into IP addresses:
<?
extract(mysql_fetch_assoc(mysql_query('SELECT * FROM foo')));
extract(mysql_fetch_assoc(mysql_query('SELECT INET_NTOA(bar) AS bar, INET_NTOA(baz) FROM foo')));
?>

I had forgotten the second AS modifier in the SQL query.  Because it couldn't extract a variable called INET_NTOA(baz) into the symbol table, it didn't do either of them.

(BTW I don't normally stack functions up like that!  Just to make a short example!)
21-Feb-2005 07:31
To make this perfectly clear (hopefully), an underscore is always added when the string is prefixed.
extract(array("color" => "blue"),EXTR_PREFIX_ALL,'');// note: prefix is empty
is the same as
$color='_blue';
Aaron Stone 17-Nov-2004 10:44
If you are working porting an older application, and taking the advice above, extracting only _SERVER, _SESSING, _COOKIE, _POST, _GET, you have forgotten to extract _FILES. Putting _FILES last and using EXTR_SKIP doesn't work because the name of the file upload box is already set as a variable containing only the temporary name of the uploaded file from one of the earlier extracts (I haven't tested to see which one specifically, however). A workaround is to put _FILES last and use EXTR_OVERWRITE. This allows extract to replace that temp-name-only variable with the full array of file upload information.
Adam Monsen <adamm at wazamatta dot com> 02-Oct-2004 05:03
As shown in the example, if your 'prefix' is used, a single underscore is added to the name of the extracted variable. Meaning, a prefix of 'p' becomes a prefix of 'p_', so 'blarg' prefixed would be 'p_blarg'.

If you're not sure what variables you've created through extraction, you can call get_defined_vars() to see all defined variables in the current scope.
end
in_array
Функции для работы с массивами


Проверяет, присутствует ли в массиве значение

extract
key
Функции для работы с массивами
PHP Manual

in_array

(PHP 4, PHP 5)

in_array — Проверяет, присутствует ли в массиве значение

Описание

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Ищет в haystack значение needle. Если strict не установлен, то при поиске будет использовано нестрогое сравнение.

Список параметров

needle

Искомое значение.

Замечание:

Если needle - строка, сравнение будет произведено с учетом регистра.

haystack

Массив.

strict

Если третий параметр strict установлен в TRUE тогда функция in_array() также проверит соответствие типов параметра needle и соответствующего значения массива haystack.

Возвращаемые значения

Возвращает TRUE, если needle был найден в массиве, и FALSE в обратном случае.

Список изменений

Версия | Описание
4.2.0 | needle теперь может быть массивом.

Примеры

Пример #1 Пример использования in_array()

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Нашел Irix";
}
if (in_array("mac", $os)) {
    echo "Нашел mac";
}
?>

Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:

Нашел Irix

Пример #2 Пример использования in_array() с параметром strict

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' найдено со строгой проверкой\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 найдено со строгой проверкой\n";
}
?>

Результат выполнения данного примера:

1.13 найдено со строгой проверкой

Пример #3 Пример использования in_array() с массивом в качестве параметра needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' найдено\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' найдено\n";
}

if (in_array('o', $a)) {
    echo "'o' найдено\n";
}
?>

Результат выполнения данного примера:

  'ph' найдено
  'o' найдено

Смотрите также

  • array_search() - Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • array_key_exists() - Проверяет, присутствует ли в массиве указанный ключ или индекс

User Contributed Notes

janis dot janovskis at gmail dot com 28-Feb-2012 11:03
Since sometimes in_array returns strange results - see notes above.
I was able to find value in array by this quite a simple function;
<?php
/**
* $find <mixed> value to find
* $array<array> array to search in
*/

function _value_in_array($array, $find){
 $exists = FALSE;
 if(!is_array($array)){
   return;
}
foreach ($array as $key => $value) {
  if($find == $value){
       $exists = TRUE;
  }
}
  return $exists;
}

// Note
// You can't use wildcards and it does not check variable type
?>
rajeevroy15 at gmail dot com dot com 30-Nov-2011 04:51
is_array function checks only array only and giving incorrect result with multi-dimensional arrays.

Here is a custom function which will give the solution to check Array or Object and Checking of multi-dimensional arrays and objects as well.

<?php

function in_object($val, $obj){

    if($val == ""){
        trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
        return false;
    }
    if(!is_object($obj)){
        $obj = (object)$obj;
    }

    foreach($obj as $key => $value){
        if(!is_object($value) && !is_array($value)){
            if($value == $val){
                return true;
            }
        }else{
            return in_object($val, $value);
        }
    }
    return false;
}
?>
Usage  :
<?php

$array = array("a", "b", "c"=>array("x", "y"=>array("p", "q"=>"r")));

if(in_object("r", $arrX)){
    echo "r is there ";
}else{
    echo "Its not there ";
}
?>
beingmrkenny at gmail dot com 27-Oct-2011 03:35
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
chris at axxis dot gr 26-Sep-2011 07:49
It's funny how PHP has an in_array method, but not an in_object one. Here is a simple function which will check if a value can be found within an object.

<?php
  // in_object method
  // to check if a value in an object exists.
  function in_object($value,$object) {
    if (is_object($object)) {
      foreach($object as $key => $item) {
        if ($value==$item) return $key;
      }
    }
    return false;
  }
?>

This is very useful if an object has been created dynamically (especially from external code, which you don't control, as in an application-plugin, CMS, etc), and you don't know the object's properties.
The above function will return the property, so you will be able to use it in your code later on.

Here is a very good basic example of how useful this function is!

<?php
  class My_Class {
    function __construct($key, $value) {
      $this->$key = $value;
      // As you can see, this is a dynamic class, its properties and values can be unknown...
    }
  }

  function in_object($value,$object) {
    if (is_object($object)) {
      foreach($object as $key => $item) {
        if ($value==$item) return $key;
      }
    }
    return false;
  }

  function manipulate_property($value,$object) {
    if ($property = in_object($value,$object)) {
      // value found. I can now use this property.
      // I can simply echo'it (makes no sense, as I could instead simply echo "value")
      echo "<br />I found the property holding this value: ".$object->$property;
      // or (here comes the good part)
      // change the property
      $object->$property = "This is a changed value!";
      echo "<br />I changed the value to: ".$object->$property;
      // or return it for use in my program flow
      return $property;
    } else {
      echo "Value NOT FOUND!<br />";
      return false;
    }
  }

  // imagine if some function creates the class conditionally...
  if ( 1 == 1) {
    $class = new My_Class("property","Unchanged Value");
  } else {
    $class = new My_Class("property","Some Other Value");
  }

  // now let's check if the value we want exists, and if yes, let's have some fun with it...
  $property = manipulate_property("Unchanged Value",$class);
  if ($property) {
    $my_variable = $class->$property;
    echo "<br />This is my variable now:".$my_variable;
  } else $my_variable = $some_other_variable;
?>

Just run it to see for yourself!
Lea Hayes 04-Aug-2011 05:40
Determine whether an object field matches needle.

Usage Example:
---------------

<?php
$arr = array( new stdClass(), new stdClass() );
$arr[0]->colour = 'red';
$arr[1]->colour = 'green';
$arr[1]->state  = 'enabled';

if (in_array_field('red', 'colour', $arr))
   echo 'Item exists with colour red.';
if (in_array_field('magenta', 'colour', $arr))
   echo 'Item exists with colour magenta.';
if (in_array_field('enabled', 'state', $arr))
   echo 'Item exists with enabled state.';
?>

Output:
--------
Item exists with colour red.
Item exists with enabled state.

<?php
function in_array_field($needle, $needle_field, $haystack, $strict = false) {
    if ($strict) {
        foreach ($haystack as $item)
            if (isset($item->$needle_field) && $item->$needle_field === $needle)
                return true;
    }
    else {
        foreach ($haystack as $item)
            if (isset($item->$needle_field) && $item->$needle_field == $needle)
                return true;
    }
    return false;
}
?>
Ray dot Paseur at Gmail dot com 01-Aug-2011 09:20
Be VERY careful about testing for strings in arrays that might also contain integers.  In this snippet, the range() function turns the numeric values into integers, and loose data typing finds a match with zero.

Outputs:
PHP in_array() FOUND @#%?!!
@#%?!! == 0 AT POSITION 26 BECAUSE OF LOOSE TYPE

<?php // RAY_temp_in_array.php
error_reporting(E_ALL);
echo "<pre>";

// THE ALLOWABLE SELECTIONS
$alpha = range('A','Z');
$alpha = array_merge($alpha, range('0', '9'));

// LOOK FOR A BOGUS SELECTION
$str = '@#%?!!';
if (in_array($str, $alpha))
{
    echo "PHP in_array() FOUND $str ";
}
else
{
    echo "$str IS NOT IN ARRAY";
}

// SEARCH THE ARRAY FOR THE KEY OF THE STRING
$key = array_search($str, $alpha);
echo "<br/>$str == $alpha[$key] AT POSITION $key";

if ($str == 0) echo " BECAUSE OF LOOSE TYPE";
?>
Anonymous 18-Jun-2011 12:16
known issue
when checking a string vs a integer

$testarray = array(0,1,2,3,4);

in_array("bla", $a) returns true
in_array("bla6", $a) returns true
in_array("6bla", $a) returns false

"bla" as a integer value returns the number zero
"bla6" as a integer value returns the number zero
 "6bla" returns the number six as its the only vaild part of that

if you checking for unknown types eg string vs integer
then you would need the strict value to be true.
Sascha Luedi 28-Feb-2011 09:33
strange behaviour of in_array:

If you have an array like:
<?php
$a = array(0,1,2,3,4,5);
in_array("bla", $a) returns true
in_array("bla6", $a) returns true
in_array("6bla", $a) returns false
?>

If you have an array like (without 0):
<?php
$a = array(1,2,3,4,5);
in_array("bla", $a) returns false
in_array("6bla", $a) returns false
in_array("5bla", $a) returns true
?>

so better use strict arg!
Joris Meijer 15-Feb-2011 05:31
A good option if your array contains objects and you wish to recursively search it (eg. with in_arrayr), is to use json_encode and json_decode first:

<?php

$array = json_decode(json_encode($array_with_objects), true);

?>

In my opinion this is more elegant than a recursive in_array function which converts the objects into arrays while searching for a key and/or value.
user at NOSPAM at fullservicead dot com 02-Feb-2011 08:52
After reading all other notes about performance,
I made a little test.

fill an array in a loop with random characters,
shuffle it
search on it using 4 methods.

I tried to have haystack as array and string; hence the strstr.

I tried it on 9, 99, 999, 9999 elements and the results
remain in the same order:

9999 elements

Function :  execution time in miliseconds.

strstr : 1.2994079589844
fast_in_array : 1.0655579566956
isset : 0.99128198623657 //Winner, used from another note here.
in_array : 2.9410798549652

One last detail, I moved my functions around in the script to make sure there was no memory caching, reiteration op or whatever, it's all the same. in_array is the slowest and the use of isset($array[$NEEDLE]) the fastest.

I hope it saves somebody else the trouble.
bosdilooda at gmail dot com 21-Jan-2011 12:07
There should be a big red warning sign here because this function behaves in mysterious ways...

let haystack be an array of integers:

$arr = array(1,2,3,4,5);

let $needle be a string of "2foobar"

then

in_array($needle,$arr)

will return true because string ("2foobar") evaluates to integer (2).
Sabrina 28-Nov-2010 01:29
Here's another way to get around the case-sensitive issue with in_array:

<?php
function in_arrayi($needle, $haystack)
{
    for($h = 0 ; $h < count($haystack) ; $h++)
    {
        $haystack[$h] = strtolower($haystack[$h]);
    }
    return in_array(strtolower($needle),$haystack);
}
?>

This is good for parsing URI's or preventing SQL injection.
ctulek at gmail dot com 30-Aug-2010 11:07
If you have an array like:
$arr = array(0,1,2,3,4,5);

in_array(NULL, $arr) returns true because you have 0 in your array. That is, in_array does not use === for equal check.
Willian Gustavo Veiga 16-Jun-2010 07:41
I wrote a function that search for a property value of an object in an array of objects:

<?php
function property_value_in_array($array, $property, $value) {
    $flag = false;

    foreach($array as $object) {
        if(!is_object($object) || !property_exists($object, $property)) {
            return false;
        }

        if($object->$property == $value) {
            $flag = true;
        }
    }

    return $flag;
}

$obj1 = new StdClass();
$obj2 = new StdClass();
$obj3 = new StdClass();

$obj1->name = 'Object 1';
$obj1->age = 12;

$obj2->name = 'Object 2';
$obj2->age = 13;

$obj3->name = 'Object 3';
$obj3->age = 14;

/* It returns true because there is the "14" value in the "age" property of an object within the array. */
echo property_value_in_array(array($obj1, $obj2, $obj3), 'age', 14);
?>
Svinto 22-May-2010 11:53
in_array() will always return true if a value in the haystack is of type bool(true).
This always hold except when the needle is of type bool(false).

Code:
<?php
$haystack = array(true);
$needle = "anything except bool(false)";
$result = in_array($needle, $haystack);
var_dump($result); #Will always be true
?>

Solution:
run in_array() with strict set to true.
<?php
in_array($needle, $haystack, true);
?>

Tested on PHP 5.2.6
bogdan AT bogdanconstantinescu DOT com 21-Apr-2010 08:01
If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time

<?php

    function in_multiarray($elem, $array)
    {
        $top = sizeof($array) - 1;
        $bottom = 0;
        while($bottom <= $top)
        {
            if($array[$bottom] == $elem)
                return true;
            else
                if(is_array($array[$bottom]))
                    if(in_multiarray($elem, ($array[$bottom])))
                        return true;

            $bottom++;
        }
        return false;
    }
?>
jv at vip dot ie 13-Feb-2010 04:46
If you're working with very large 2 dimensional arrays (eg 20,000+ elements) it's much faster to do this...

<?php
$needle = 'test for this';

$flipped_haystack = array_flip($haystack);

if ( isset($flipped_haystack[$needle]) )
{
  print "Yes it's there!";
}
?>

I had a script that went from 30+ seconds down to 2 seconds (when hunting through a 50,000 element array 50,000 times).

Remember to only flip it once at the beginning of your code though!
natan dot volkovich at gmail dot com 30-Nov-2009 02:10
If you're trying to find out whether or not at least a single value of an array matches a value in your haystack then use "array_intersect" instead of "in_array".

<?php
$needle = array(1,2);
$haystack = array(0,1,2);

echo "in_array: ".(int)in_array($needle, $haystack); // returns 0
echo "array_intersect: ".(int)array_intersect((array)$needle, $haystack); // returns 1
?>
vladimir at vingrad dot ru 14-Nov-2009 03:14
This function has Problem with UTF-8. To solve this Problem use:

in_array( mb_strtolower($tag, "UTF-8"), $arr)
thomas dot sahlin at gmail dot com 05-Oct-2009 12:53
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow = array('apple', 'banana', 'orange');

if (in_array('banana', $slow))
    print('Found it!');

$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset($fast['banana']))
    print('Found it!');

?>
me at bubjavier dot com 14-Sep-2009 04:15
in case your haystack is undefined or not set:

<?php

$fruitExists = in_array('mango', (array) $_SESSION["fruits"]);

?>

will return false if the haystack is not an array.
robin at robinnixon dot com 25-Jul-2009 12:38
This function is five times faster than in_array(). It uses a binary search and should be able to be used as a direct replacement:

<?php
function fast_in_array($elem, $array)
{
   $top = sizeof($array) -1;
   $bot = 0;

   while($top >= $bot)
   {
      $p = floor(($top + $bot) / 2);
      if ($array[$p] < $elem) $bot = $p + 1;
      elseif ($array[$p] > $elem) $top = $p - 1;
      else return TRUE;
   }

   return FALSE;
}
?>
john at dwarven dot co dot uk 01-Jul-2009 04:34
I just struggled for a while with this, although it may be obvious to others.

If you have an array with mixed type content such as:

<?php

 $ary = array (
   1,
   "John",
   0,
   "Foo",
   "Bar"
 );

?>

be sure to use the strict checking when searching for a string in the array, or it will match on the 0 int in that array and give a true for all values of needle that are strings strings.

<?php

var_dump( in_array( 2, $ary ) );

// outputs FALSE

var_dump( in_array( 'Not in there', $ary ) );

// outputs TRUE

var_dump( in_array( 'Not in there', $ary, TRUE ) );

// outputs FALSE

?>
MarkAndrewSlade at gmail dot com 17-Apr-2009 10:46
This function will generate a PHP_NOTICE if you are looking for data of type A in an array containing data of type B if casting A to B would generate a PHP_NOTICE.  This may not be obvious.  For example:

<?php

$o = new stdClass;
$a = array(1, 2, $o);
in_array(5, $a);

?>

The output here is:

Notice: Object of class stdClass could not be converted to int in /some/script.php on line 5
Thingmand 09-Mar-2009 11:58
A little function to use an array of needles:

<?php
function array_in_array($needles, $haystack) {

    foreach ($needles as $needle) {

        if ( in_array($needle, $haystack) ) {
            return true;
        }
    }

    return false;
}
?>
brouwer dot p at gmail dot com 08-Mar-2009 02:55
If made a in_array function that checks if the specified key matches. It works recursivly so it doesn't matter how deep your input array is.
<?php
  function myInArray($array, $value, $key){
    //loop through the array
    foreach ($array as $val) {
      //if $val is an array cal myInArray again with $val as array input
      if(is_array($val)){
        if(myInArray($val,$value,$key))
          return true;
      }
      //else check if the given key has $value as value
      else{
        if($array[$key]==$value)
          return true;
      }
    }
    return false;
  }
?>
Kelvin J 28-Feb-2009 05:04
For a case-insensitive in_array(), you can use array_map() to avoid a foreach statement, e.g.:

<?php
    function in_arrayi($needle, $haystack) {
        return in_array(strtolower($needle), array_map('strtolower', $haystack));
    }
?>
selmand [at] gmail.com 13-Feb-2009 04:38
Removes same text with in_array in a string.

<?

$hizmet="aeg,akai,aeg,arcelik,aeg,arcelik,klima,kombi";

// alots of same stings

$x=explode(",",$hizmet);

$t= array();
$k=0;
for($i=0;$i<sizeof($x);$i++){ // this for remove its
    //echo $x[$i]."\n";
    if(!in_array($x[$i],$t))
    {
        $t[$k]=$x[$i];
        $k++;
    }

}

for($i=0;$i<sizeof($t);$i++){ // rebuilding $hizmet strings.

    echo $t[$i].",";

}

?>
soxred93 at gmail dot com 28-Jan-2009 01:37
Here's a simple little function I wrote that is a case insensitive version of in_array():

<?php
    function in_arrayi( $needle, $haystack ) {
        $found = false;
        foreach( $haystack as $value ) {
            if( strtolower( $value ) == strtolower( $needle ) ) {
                $found = true;
            }
        }
        return $found;
    }
?>
jordigirones at gmail dot com 21-Jan-2009 07:54
function similar to in_array but implements LIKE '<string>%'

<?php
   function in_array_like($referencia,$array){
      foreach($array as $ref){
        if (strstr($referencia,$ref)){
          return true;
        }
      }
      return false;
    }
?>
rhill at xenu-directory dot net 17-Jan-2009 01:05
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle = array(
    'fruit'=>'banana', 'vegetable'=>'carrot'
    );

$haystack = array(
    array('vegetable'=>'carrot', 'fruit'=>'banana'),
    array('fruit'=>'apple', 'vegetable'=>'celery')
    );

echo in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
james dot ellis at gmail dot com 29-Oct-2008 09:17
Be aware of oddities when dealing with 0 (zero) values in an array...

This script:
<?php
$array = array('testing',0,'name');
var_dump($array);
//this will return true
var_dump(in_array('foo', $array));
//this will return false
var_dump(in_array('foo', $array, TRUE));
?>

It seems in non strict mode, the 0 value in the array is evaluating to boolean FALSE and in_array returns TRUE. Use strict mode to work around this peculiarity.
This only seems to occur when there is an integer 0 in the array. A string '0' will return FALSE for the first test above (at least in 5.2.6).
james dot randell at hotmail dot co dot uk 16-Sep-2008 02:54
Small method i built for my Array module, after looking through the manual I wanted a small compact way of making a wildcard search through an arrays values, and returning only those that it found.

<?php

    /**
     * Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
     *
     * @param    string        $string        Needle to find
     * @param    array        $array        Haystack to look through
     * @result    array                    Returns the elements that the $string was found in
     */
    function find ($string, $array = array ())
    {
        foreach ($array as $key => $value) {
            unset ($array[$key]);
            if (strpos($value, $string) !== false) {
                $array[$key] = $value;
            }
        }
        return $array;
    }
?>
alishahnovin at hotmail dot com 02-Sep-2008 12:43
Here's a function that does an in_array, but takes wildcards in the needle, and also can be case sensitive/insensitive...

A few points:
-It doesn't use foreach, but for, which is quicker
-I didn't use regex to search with a wildcard for the reason that the needle could be unpredictable if it's user-input, and rather than having to escape metacharacters, I decided it would be easier to do a plain text comparison.
-Needles with wildcards can come in many forms such as:

Str*ng
S*r*ng*
*rng
*i*n*

so a split is being done on that string, and each part is then compared with the current item. If the first part is not found, the comparison is done, and we move on. If it IS found, we move on to the next part of the needle, while chopping off the initial part of the haystack string. This is to ensure that each comparison of a needle part is looking at the next part of the haystack string.

For example:

needle: "Bo*bo"
haystack[0] = "Bob is lazy"

On the first pass, when searching "Bo", we then modify the haystack[0] to be: "b is lazy" so that "bo" is compared with that. Otherwise, we'd be comparing "bo" with "Bob is lazy", and returning true incorrectly.

I haven't fully tested the function, so let me know if you spot any bugs, or have any questions.

<?php

function in_wildarray($needle, $haystack, $case_sensitive=true) {
    $is_wild = (strpos($needle,"*")===true)? true : false;
    $needles = ($is_wild)? explode("*", $needle) : array();
    $needle = ($case_sensitive)? $needle : strtolower($needle);
    for($i=0;$i<count($haystack);$i++) {
        $haystack_str = ($case_sensitive)? haystack[$i] : strtolower($haystack[$i]);
        if ($is_wild) {
            $found = false;
            for($x=0;$x<count($needles);$x++) {
                $needle_part = trim($needles[x]);
                $needle_index = strpos($haystack_str, $needle_part);
                if ($needle_index===false) {
                    $found = false;
                    break; //break out of the loop, because string part is not found in the haystack string
                } else {
                    $found = true;
                    //chop off the start of the string to the needle_index
                    //so we can be sure that the found items are in the correct order
                    //and we are avoiding the potential of finding duplicate characters
                    $haystack_str = substr($haystack_str, 0, $needle_index);
                }
            }
            if ($found) { return true; }
        } elseif (!$is_wild && $haystack_str == $needle) {
            return true;
        }
    }
    return false;
}

?>

As the code is right now, when there are wild cards, it will treat the initial segment as though it's preceded with a wild card. In other words, the first segment will be searched, not simply at the beginning of the string, but anywhere. Because it's a simple fix, I'll leave it to others. :)
crashrox at gmail dot com 21-Jul-2008 08:34
Recursive in array using SPL

<?php
function in_array_recursive($needle, $haystack) {

    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));

    foreach($it AS $element) {
        if($element == $needle) {
            return true;
        }
    }

    return false;
}
?>
Martijn Wieringa 19-May-2008 02:20
When using numbers as needle, it gets tricky:

Note this behaviour (3rd statement):

in_array(0, array(42)) = FALSE
in_array(0, array('42')) = FALSE
in_array(0, array('Foo')) = TRUE
in_array('0', array('Foo')) = FALSE
sick949 at hotmail dot com 05-Mar-2008 03:43
A first idea for a function that checks if a text is in a specific column of an array.
It does not use in_array function because it doesn't check via columns.
Its a test, could be much better. Do not use it without test.

<?php

function in_array_column($text, $column, $array)
{
    if (!empty($array) && is_array($array))
    {
        for ($i=0; $i < count($array); $i++)
        {
            if ($array[$i][$column]==$text || strcmp($array[$i][$column],$text)==0) return true;
        }
    }
    return false;
}

?>
guitar king 29-Jan-2008 11:52
In PHP 4, the first argument seems not allowed to be an object. In PHP 5, also objects are allowed as $needle.
f d0t fesser att gmx d0t net 16-Oct-2007 03:20
In case you have to check for unknown or dynamic variables in an array, you can use the following simple work-around to avoid misleading checks against empty and zero values (and only these "values"!):

<?php
  in_array($value, $my_array, empty($value) && $value !== '0');
?>

The function empty() is the right choice as it turns to true for all 0, null and ''.
The '0' value (where empty() returns true as well) has to be excluded manually (as this is handled by in_array correctly!).

Examples:
<?php
  $val = 0;
  $res = in_array($val, array('2007'));
?>

leads incorrectly to true where

<?php
  $val = 0;
  $res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

leads correctly to false (strict check!) while

<?php
  $val = 2007;
  $res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

still correctly finds the '2007' ($res === true) because it ignores strict checking for that value.
info at b1g dot de 02-Aug-2007 10:44
Be careful with checking for "zero" in arrays when you are not in strict mode.
in_array(0, array()) == true
in_array(0, array(), true) == false
Quaquaversal 20-May-2007 08:48
A simple function to type less when wanting to check if any one of many values is in a single array.

<?php
function array_in_array($needle, $haystack) {
    //Make sure $needle is an array for foreach
    if(!is_array($needle)) $needle = array($needle);
    //For each value in $needle, return TRUE if in $haystack
    foreach($needle as $pin)
        if(in_array($pin, $haystack)) return TRUE;
    //Return FALSE if none of the values from $needle are found in $haystack
    return FALSE;
}
?>
Bodo Graumann 16-Mar-2007 10:43
Be careful!

in_array(null, $some_array)
seems to differ between versions

with 5.1.2 it is false
but with 5.2.1 it's true!
musik at krapplack dot de 04-Jun-2006 05:52
I needed a version of in_array() that supports wildcards in the haystack. Here it is:

<?php
function my_inArray($needle, $haystack) {
    # this function allows wildcards in the array to be searched
    foreach ($haystack as $value) {
        if (true === fnmatch($value, $needle)) {
            return true;
        }
    }
    return false;
}

$haystack = array('*krapplack.de');
$needle = 'www.krapplack.de';

echo my_inArray($needle, $haystack); # outputs "true"
?>

Unfortunately, fnmatch() is not available on Windows or other non-POSIX compliant systems.

Cheers,
Thomas
rick at fawo dot nl 08-Apr-2006 08:23
Here's another deep_in_array function, but this one has a case-insensitive option :)
<?
function deep_in_array($value, $array, $case_insensitive = false){
    foreach($array as $item){
        if(is_array($item)) $ret = deep_in_array($value, $item, $case_insensitive);
        else $ret = ($case_insensitive) ? strtolower($item)==$value : $item==$value;
        if($ret)return $ret;
    }
    return false;
}
?>
sandrejev at gmail dot com 22-Feb-2006 07:11
Sorry, that deep_in_array() was a bit broken.

<?php
function deep_in_array($value, $array) {
    foreach($array as $item) {
        if(!is_array($item)) {
            if ($item == $value) return true;
            else continue;
        }

        if(in_array($value, $item)) return true;
        else if(deep_in_array($value, $item)) return true;
    }
    return false;
}
?>
kitchin 05-Feb-2006 06:52
Here's a gotcha, and another reason to always use strict with this function.

$x= array('this');
$test= in_array(0, $x);
var_dump($test); // true

$x= array(0);
$test= in_array('that', $x);
var_dump($test); // true

$x= array('0');
$test= in_array('that', $x);
var_dump($test); // false

It's hard to think of a reason to use this function *without* strict.

This is important for validating user input from a set of allowed values, such as from a <select> tag.
13-Jan-2006 09:44
in_arrayr -- Checks if the value is in an array recursively

Description
bool in_array (mixed needle, array haystack)

<?php
function in_arrayr($needle, $haystack) {
        foreach ($haystack as $v) {
                if ($needle == $v) return true;
                elseif (is_array($v)) return in_arrayr($needle, $v);
        }
        return false;
}
// i think it works
?>
adrian foeder 08-Nov-2005 01:21
hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:

<?php
function rec_in_array($needle, $haystack, $alsokeys=false)
    {
        if(!is_array($haystack)) return false;
        if(in_array($needle, $haystack) || ($alsokeys && in_array($needle, array_keys($haystack)) )) return true;
        else {
            foreach($haystack AS $element) {
                $ret = rec_in_array($needle, $element, $alsokeys);
            }
        }

        return $ret;
    }
?>
tacone at gmx dot net 03-Aug-2005 07:05
Beware of type conversion!

This snippet will unset every 0 key element form the array, when cycling an array which contains at least one _num value.
This is because php tries to convert every element of $forbidden_elements to integer when encountering a numeric index into array.
So $array[0] it's considered equal to (int)'_num'.

<?php
$forbidden_elements=array('_num');
    foreach ($array as $key=>$value){
        if (in_array($key,$forbidden_elements)){
                unset ($array[$key]);
            }
}
?>

The following example works, anway you can use strict comparison as well.

<?php
$forbidden_elements=array('_num');
    foreach ($array as $key=>$value){
        if (in_array($key,$forbidden_elements) && is_string($key)){
                unset ($array[$key]);
            }
}
?>
Aragorn5551 at gmx dot de 11-Jun-2005 05:26
If you have a multidimensional array filled only with Boolean values like me, you need to use 'strict', otherwise in_array() will return an unexpected result.

Example:

<?php
$error_arr = array('error_one' => FALSE, 'error_two' => FALSE, array('error_three' => FALSE, 'error_four' => FALSE));

if (in_array (TRUE, $error_arr)) {
   echo 'An error occurred';
}
else {
   echo 'No error occurred';
}
?>

This will return 'An error occurred' although theres no TRUE value inside the array in any dimension. With 'strict' the function will return the correct result 'No error occurred'.

Hope this helps somebody, cause it took me some time to figure this out.
gordon at kanazawa-gu dot ac dot jp 07-Jan-2003 05:05
case-insensitive version of in_array:

<?php
function is_in_array($str, $array) {
  return preg_grep('/^' . preg_quote($str, '/') . '$/i', $array);
}
?>
pingjuNOSPAM at stud dot NOSPAM dot ntnu dot no 25-Nov-2002 06:56
if the needle is only a part of an element in the haystack, FALSE will be returned, though the difference maybe only a special char like line feeding (\n or \r).
tom at orbittechservices dot com 09-Aug-2002 07:17
I searched the general mailing list and found that in PHP versions before 4.2.0 needle was not allowed to be an array.

Here's how I solved it to check if a value is in_array to avoid duplicates;

<?php
$myArray = array(array('p', 'h'), array('p', 'r'));

$newValue = "q";
$newInsert = array('p','q');

$itBeInThere = 0;
foreach ($myArray as $currentValue) {
  if (in_array ($newValue, $currentValue)) {
    $itBeInThere = 1;
  }
if ($itBeInThere != 1) {
  array_unshift ($myArray, $newInsert);
}
?>
one at groobo dot com 07-May-2002 03:14
Sometimes, you might want to search values in array, that does not exist. In this case php will display nasty warning:
Wrong datatype for second argument in call to in_array() .

In this case, add a simple statement before the in_array function:

<?php
if (sizeof($arr_to_searchin) == 0 || !in_array($value, $arr_to_searchin)) { /*...*/ }
?>

In this case, the 1st statement will return true, omitting the 2nd one.
jon at gaarsmand dot dk 09-Apr-2002 08:53
If you want to search a multiple array for a value - you can use this function - which looks up the value in any of the arrays dimensions (like in_array() does in the first dimension).
Note that the speed is growing proportional with the size of the array - why in_array is best if you can determine where to look for the value.

Copy & paste this into your code...

<?php
function in_multi_array($needle, $haystack)
{
    $in_multi_array = false;
    if(in_array($needle, $haystack))
    {
        $in_multi_array = true;
    }
    else
    {
        for($i = 0; $i < sizeof($haystack); $i++)
        {
            if(is_array($haystack[$i]))
            {
                if(in_multi_array($needle, $haystack[$i]))
                {
                    $in_multi_array = true;
                    break;
                }
            }
        }
    }
    return $in_multi_array;
}
?>
extract
key
Функции для работы с массивами


Выбирает ключ из массива

in_array
krsort
Функции для работы с массивами
PHP Manual

key

(PHP 4, PHP 5)

key — Выбирает ключ из массива

Описание

mixed key ( array &$array )

key() возвращает индекс текущего элемента массива.

Список параметров

array

Массив.

Возвращаемые значения

Функция key() просто возвращает ключ того элемента массива, на который в данный момент указывает внутренний указатель массива. Он не сдвигает указатель ни в каком направлении. Если внутренний указатель указывает вне границ массива или массив пуст, key() возвратит NULL.

Примеры

Пример #1 Пример использования key()

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// этот цикл выведет все ключи ассоциативного массива,
// значения которых равны "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

Результат выполнения данного примера:

fruit1<br />
fruit4<br />
fruit5<br />

Смотрите также

  • current() - Возвращает текущий элемент массива
  • next() - Передвигает внутренний указатель массива на одну позицию вперёд

User Contributed Notes

HellFireAE at gmail dot com 16-Mar-2012 11:37
I've used this as a way of getting $_GET's from the URL. It's actually quite cool, I don't know if this is a hack or what but I like it.

<?php
  switch(strToLower(key($_GET))){
    case "register":
      $page->set("{PAGE_TITLE}", "Register");
      break;
    default:
      $page->set("{PAGE_TITLE}", "Play");
      break;
  }
?>

So if you put "?register" it outputs the page title to "Register" and if it isn't that, then it's "Play".

Hope this helps people.
goker.cebeci 23-Feb-2012 07:41
object usage:

<?php

$object = new stdClass();
$object->child->key = 'value';

echo key((array) $object->child);
// key

?>
FatBat 17-Oct-2011 12:20
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
FokeyJoe 10-Mar-2011 06:10
Just to illustrate the behaviour of the internal pointer when you add items. Adding to an array does not affect the internal pointer.

<?php
$a = array();
var_dump(key($a));  // null
$a[] = "jump";
var_dump(key($a));  // 0
$a[] = "lazy";
var_dump(key($a));  // 0
end($a);
var_dump(key($a));  // 1
$a[] = "fox";
var_dump(key($a));  // 1
?>
Dallas at ekkysoftware dot com 04-Mar-2010 09:32
I had a problem when there are nulls in your data, such as:-

<?php
$row = array(  'first'=>'number', 'second'=>'letter', 'third'=>null, 'forth'=>'word');

while($value = current($row)){
    echo "\"".key($row)."\"";
    next($row);
}
?>

The problem is that current() returns the value 'null', but it isn't the end of the list. To get the correct results I used:-

<?php
foreach($row as $value){
    echo "\"".key($row)."\"";
    next($row);
}
?>
jamon at clearsightdesign dot com 18-Aug-2009 10:24
I wrote a simple, yet powerful function for finding a key in an array relative to another key. This is very useful for finding the next key in an associative array if you know the current key, or any other arbitrary key relative to the current key.

This function does not use a foreach loop. I have not tested it for speed compared to a foreach loop. I would assume it's faster since it uses PHP's built in functions, but I could be wrong. I'd appreciate feedback on this.

- Jamon Holmgren

<?php
    // array_key_relative - Returns a key in an associative array relative to another key without using foreach. Very useful for finding previous key or finding next key in array, etc
    // - Written by Jamon Holmgren (www.jamonholmgren.com). Last revised 8/18/2009. Free for any use.
    // function array_key_relative(array $array, string $current_key, int $offset)
    function array_key_relative($array, $current_key, $offset = 1) {
        // create key map
        $keys = array_keys($array);
        // find current key
        $current_key_index = array_search($current_key, $keys);
        // return desired offset, if in array, or false if not
        if(isset($keys[$current_key_index + $offset])) {
            return $keys[$current_key_index + $offset];
        }
        return false;
    }
?>

Usage example:

<?php
    $test_array = array(
        "apple" => "Red, shiny fruit",
        "orange" => "Orange, dull, juicy fruit",
        "pear" => "Usually green and odd-shaped fruit",
        "banana" => "Long yellow fruit that monkeys like to eat",
        "cantelope" => "Larger than a grapefruit",
        "grapefruit" => "Kind of sour"
    );

    echo array_key_relative($test_array, "apple", 2); // outputs "pear"
    echo array_key_relative($test_array, "orange", -1); // outputs "apple" */

    $next_key = array_key_relative($test_array, "banana", 1); // Get the key after banana (cantelope)
    echo $test_array[$next_key]; // outputs "Larger than a grapefruit"
?>
michael 09-Dec-2008 11:19
Here is an improved version of the KeyName function below. It is simpler and faster, especially on large arrays as it runs in O(1) instead of O(n).

<?php
function KeyName(array $a, $pos) {
    $temp = array_slice($a, $pos, 1, true);
    return key($temp);
}
?>

Also, KeyName($a, -1) will return the last key, etc.
Twey 15-Mar-2008 12:25
As of PHP5, objects are passed by reference by default.
egingell at sisna dot com 02-Dec-2007 03:12
What's the point of lines 14 and 25? $array is destroyed when the function returns. If you want this to work as written, change line 2 to this: (pass $array by reference instead of by value)
<?
function add_key ($value, &$array) // returns the key of the value added or existing already within the array
?>

>    danny at dannymendel dot com
>    12-Apr-2006 09:41
>    An auto incremental key value function, returning the key value:
>
> 1    <?
> 2    function add_key ($value, $array) // returns the key of the value added or existing already within the array
> 3    {
> 4        if (is_array ($array))
> 5        {
> 6            if (!in_array ($value, $array))
> 7            {
> 8                ksort ($array);
> 9
>10                end ($array);
>11
>12                $key = key ($array) + 1;
>13
>14                $array[$key] = $value;
>15            }
>16            else
>17            {
>18                $key = array_search ($value, $array);
>19            }
>20        }
>21        else
>22        {
>23            $key = 1;
>24
>25            $array[$key] = $value;
>26        }
>27        return $key;
>28    }
>29    ?>
yarco dot w at gmail dot com 13-Sep-2007 01:45
Re: br_joris[at]hotmail[doth]com

Do you really mean you want 2 keys point to 1 value?
What you've written seems you want 1 key point to 2 values.

But if you really want 2 keys point to 1 value, you could do the following:

<?php
$buf['key1'] = 'abc';
$buf['key2'] = & $buf['key1'];
?>
danny at dannymendel dot com 12-Apr-2006 08:41
An auto incremental key value function, returning the key value:

<?
function add_key ($value, $array) // returns the key of the value added or existing already within the array
{
    if (is_array ($array))
    {
        if (!in_array ($value, $array))
        {
            ksort ($array);

            end ($array);

            $key = key ($array) + 1;

            $array[$key] = $value;
        }
        else
        {
            $key = array_search ($value, $array);
        }
    }
    else
    {
        $key = 1;

        $array[$key] = $value;
    }
    return $key;
}
?>
php_notes at ionws dot com 10-Oct-2005 04:17
Note that key($array) returns NULL if $array's internal pointer goes past the end of the array.  For example, the following code:

<?php
$arr = array(
    'one' => '1',
    'two' => '2',
    'three' => '3',
    'four' => '4',
    'five' => '5');

for ($i = 0; $i < 10; $i++) {
    var_dump(key($arr));
    next($arr);
}
?>

results in:
string(3) "one"
string(3) "two"
string(5) "three"
string(4) "four"
string(4) "five"
NULL
NULL
NULL
NULL
NULL
Danniel@t h e - police (d'0't) com 22-May-2005 01:55
To get the key name by position from Array:
<?php
$myArray['name1']=3;
$myArray['name2']=2;
$myArray['name3']=1;

echo($myArray[1]);   /* return NULL */
/* isset($myArray[1]) return false;   */
/* is_null($myArray[1]) return true;  */

function KeyName($myArray,$pos) {
   // $pos--;
   /* uncomment the above line if you */
   /* prefer position to start from 1 */

   if ( ($pos < 0) || ( $pos >= count($myArray) ) )
         return "NULL";  // set this any way you like

   reset($myArray);
   for($i = 0;$i < $pos; $i++) next($myArray);

   return key($myArray);
}

echo KeyName($myArray,1);  // result: name2
echo KeyName($myArray,2);  // result: name3
echo KeyName($myArray,3);  // result: "NULL"
?>

You can get any existing "key name" from array that is located at position $pos gived as second parameter. If no element is defined at given position the function will return the string "NULL".
Danniel@t h e - police (d'0't) com 22-May-2005 01:55
To get the key name by position from Array:
<?php
$myArray['name1']=3;
$myArray['name2']=2;
$myArray['name3']=1;

echo($myArray[1]);   /* return NULL */
/* isset($myArray[1]) return false;   */
/* is_null($myArray[1]) return true;  */

function KeyName($myArray,$pos) {
   // $pos--;
   /* uncomment the above line if you */
   /* prefer position to start from 1 */

   if ( ($pos < 0) || ( $pos >= count($myArray) ) )
         return "NULL";  // set this any way you like

   reset($myArray);
   for($i = 0;$i < $pos; $i++) next($myArray);

   return key($myArray);
}

echo KeyName($myArray,1);  // result: name2
echo KeyName($myArray,2);  // result: name3
echo KeyName($myArray,3);  // result: "NULL"
?>

You can get any existing "key name" from array that is located at position $pos gived as second parameter. If no element is defined at given position the function will return the string "NULL".
happy dot machine at skynet dot be 06-May-2003 11:20
<?php
$tab = array();
$tab[0] = 'php';
$tab[1] = '.';
$tab[2] = 'net';

// you will not enter the while
// $key = 0, while will consider $key as false
reset($tab);
while ($key = key($tab) ) {
echo $tab[$key];
next($tab);
}

// this will
reset($tab);
while (!is_null($key = key($tab) ) ) {
echo $tab[$key];
next($tab);
}

// when key() can't return a 'key', it return NULL
echo var_dump($key);
?>
kajetan at kajetan dot nu 04-Jul-2002 01:20
I'm writing a forum and use an array to hold all the smiles. The keys in the array are the characters to write to get a smiley, and the data is the filename, like this
$Smiles[':-)'] = 'smile.gif'

To output all the smileys in a table with 3 columns, I wrote this code:

<?php
$the_end = false;

$s = reset($Smiles);
$k = key($Smiles);

while(!$the_end){
    echo '<tr>';
    for($i=0; $i<3; $i++){
        echo '<td>';
        if($the_end) echo '&nbsp;';
        else{
        echo $k.'< br><img src="'. $s .'">';
          $s = next($Smiles);
        if ($s==false) $the_end=true;
        else
            $k = key($Smiles);
        }
        echo "</td>\n";
    }
    echo "</tr>\n";
}
?>

I had to write a space in the < br> tag in the code above, because the board did a line brake otherwise.
mkeller at gmx dot de 11-Oct-2001 12:46
In the case key() does not give you back the key(myarray) but "0", try this:
(Try this example without the line containing "end($myarray)" and you see my reason for this post...)

<?php
for($i = 0; $i <= 10; $i++) {
        $myarray[] = 'content '.$i;
        end($myarray);
        echo ('<br>key()='.key($myarray).' , content='.$myarray[$i]);
    }
?>
php at snr-graphics dot com 23-Mar-2001 11:50
A Method of Multi-Dimensionalizing an Associative Array (This idea was designed with Graphics (image filenames in mind):

(A quick overview):
While working on a rather large web application, I found that I needed a way to obtain "all" the details on images used by the application, these images (by filename) were stored in the configuration file, in the form of associative arrays.

The following represents an example of how I tool those and converted them into multi-dimensional associative arrays.

<?php
do {
  $size = getImageSize($path.$myarray[key($myarray)]);
  if ($size[2] == '1') { $size[2] = 'gif'; }
  else if ($size[2] == '2') { $size[2] = 'jpg'; }
  else if ($size[2] == '3') { $size[2] = 'png'; }
  else if ($size[2] == '4') { $size[2] = 'swf'; }
  else { $size[2] = 'UNKNOWN'; }
$myarray[key($myarray)] = Array($myarray[Key($myarray)],$size[0],$size[1],$size[2],$size[3]);
} while (next($myarray));
?>

The end result is an multi-dim. associative array which contains the values:

<?php
$myarray["this"][0] = # filename.gif
$myarray["this"][1] = # width
$myarray["this"][2] = # height
$myarray["this"][3] = # type (converted to the file extension.)
$myarray["this"][4] = # height=x width=x
?>

This may not be all that impressive to some, but it turned out to be very useful for me, so I thought I'd share, in addition, I think it gives a "very" good example of "a use" for the Key() function.

Frankly, I was quite happy to discover this function, I can't count the number of times I "needed to use the key as a value".

I hope you find this code useful.
in_array
krsort
Функции для работы с массивами


Сортирует массив по ключам в обратном порядке

key
ksort
Функции для работы с массивами
PHP Manual

krsort

(PHP 4, PHP 5)

krsort — Сортирует массив по ключам в обратном порядке

Описание

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Сортирует массив по ключам в обратном порядке, сохраняя отношения между ключами и значениями. Эта функция полезна, в основном, для работы с ассоциативными массивами.

Список параметров

array

Входной массив.

sort_flags

Вы можете изменить поведение сортировки, используя дополнительный параметр sort_flags, подробнее см. sort().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования krsort()

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Результат выполнения данного примера:

d = lemon
c = apple
b = banana
a = orange

Смотрите также

  • arsort() - Сортирует массив в обратном порядке, сохраняя ключи
  • ksort() - Сортирует массив по ключам
  • Сравнение функций сортировки массивов

User Contributed Notes

07-Aug-2005 06:37
To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
    $keys = array_keys($array);
    natsort($keys);

    foreach ($keys as $k)
    {
        $new_array[$k] = $array[$k];
    }

    $new_array = array_reverse($new_array, true);

    return $new_array;
}
?>
peter at pmkmedia dot com 07-Nov-2003 01:51
Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // � Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}
lolo at phpheaven dot net 28-Nov-2000 12:33
If you want to emulate the krsort function for an older version of php, you can use this piece of code:

function KeyComp($a, $b)
{
  return -(strcmp($a,$b));
}

function krsort($MyArray)
{
  uksort($MyArray, "KeyComp");
}

Maybe obvious and useless, but who knows...
key
ksort
Функции для работы с массивами


Сортирует массив по ключам

krsort
list
Функции для работы с массивами
PHP Manual

ksort

(PHP 4, PHP 5)

ksort — Сортирует массив по ключам

Описание

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Сортирует массив по ключам, сохраняя отношения между ключами и значениями. Эта функция полезна, в основном, для работы с ассоциативными массивами.

Список параметров

array

Входной массив.

sort_flags

Вы можете изменить поведение сортировки, используя дополнительный параметр sort_flags, подробнее смотри функцию sort().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ksort()

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Результат выполнения данного примера:

a = orange
b = banana
c = apple
d = lemon

Смотрите также

  • asort() - Сортирует массив, сохраняя ключи
  • Сравнение функций сортировки массивов

User Contributed Notes

Haprog 15-Aug-2011 05:50
Here is a function to recursively sort multidimentional arrays by key:

<?php
function deep_ksort(&$arr) {
    ksort($arr);
    foreach ($arr as &$a) {
        if (is_array($a) && !empty($a)) {
            deep_ksort($a);
        }
    }
}
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2011 08:48
Note that ksort will NOT help you much if numeric and string keys are mixed together.
<?php
$t = array(
  "a"=>"A",
  0=>"A",
  "b"=>"A",
  1=>"A"
);
var_dump($t);
ksort($t);
var_dump($t);
?>

produces (on PHP 5.3.6-4 with Suhosin-Patch) :

array(4) {
  ["a"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["b"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

array(4) {
  ["b"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["a"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

note that the second array should be sorted by keys, but is even more messed up than the first one!
DavidG 17-Jun-2010 06:47
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:

<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));

var_dump($people);

$sortArray = array();

foreach($people as $person){
    foreach($person as $key=>$value){
        if(!isset($sortArray[$key])){
            $sortArray[$key] = array();
        }
        $sortArray[$key][] = $value;
    }
}

$orderby = "name"; //change this to whatever key you want from the array

array_multisort($sortArray[$orderby],SORT_DESC,$people);

var_dump($people);
?>

Output from first var_dump:

[0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }
}

Output from 2nd var_dump:

array(3) {
  [0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }

There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
serpro at gmail dot com 13-Mar-2009 02:02
Here is a function to sort an array by the key of his sub-array.

<?php

function sksort(&$array, $subkey="id", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

?>

Example
<?php
$info = array("peter" => array("age" => 21,
                                           "gender" => "male"
                                           ),
                   "john"  => array("age" => 19,
                                           "gender" => "male"
                                           ),
                   "mary" => array("age" => 20,
                                           "gender" => "female"
                                          )
                  );

sksort($info, "age");
var_dump($info);

sksort($info, "age", true);
var_dump($ifno);
?>

This will be the output of the example:

/*DESCENDING SORT*/
array(3) {
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
}

/*ASCENDING SORT*/
array(3) {
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
}
maik dot riechert at animey dot net 12-Aug-2008 11:32
Be careful when using ksort for mixed type keys!!

$a = array(
    'first' => true,
    0       => 'sally',
);

$b = array(
    0       => 'sally',
    'first' => true,
);

ksort($a);
ksort($b);
var_dump($a);
var_dump($b);

Output is:
array(
    0 => 'sally',
    'first' => true,
)

array(
    'first' => true,
    0 => 'sally',
)

If you want same results for both arrays, use:

ksort($a, SORT_STRING);

The reason for that lays in the compare mechanism which would normally just typecast 'first' to an integer or 0 to a string when comparing it to each other. So you have to use SORT_STRING, otherwise you would lose information when 'first' is converted to int.
05-Nov-2006 05:26
Why not just use built-in PHP functions? You can do an in-place natural sort by keys with:

uksort($array, 'strnatcasecmp');
richard dot quadling at bandvulc dot co dot uk 24-Oct-2005 01:10
Just to complete the comments made by ssb45.

If the supplied array is an empty array, the value returned is NOT an array.

All that is required is to pre-initialize the result.

function natksort(&$aToBeSorted)
    {
    $aResult = array();
    $aKeys = array_keys($aToBeSorted);
    natcasesort($aKeys);
    foreach ($aKeys as $sKey)
        {
        $aResult[$sKey] = $aToBeSorted[$sKey];
        }
    $aToBeSorted = $aResult;
    return True;
    }
ssb45 at cornell dot edu 30-Jun-2005 04:58
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is.  While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched.  Thus, you must use this syntax:

$array = natksort($array);

If you want to use the more natural syntax:

$status = natksort($array);

Then use this modified version:

function natksort(&$array) {
    $keys = array_keys($array);
    natcasesort($keys);

    foreach ($keys as $k) {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
    return true;
}
justin at booleangate dot org 18-Jan-2005 01:04
Here's a handy function for natural order sorting on keys.

function natksort($array) {
  // Like ksort but uses natural sort instead
  $keys = array_keys($array);
  natsort($keys);

  foreach ($keys as $k)
    $new_array[$k] = $array[$k];

  return $new_array;
}
yaroukh at email dot cz 06-May-2004 08:08
I believe documentation should mention which of array-functions do reset the internal pointer; this one does so ...
pedromartinez at alquimiapaginas dot com 28-Nov-2003 07:58
A list of directories can be listed sorted by date (newer first) with this script. This is usefull if the directories contain (for example) pictures and you want the newer to appear first.

$maindir = "." ;
$mydir = opendir($maindir) ;

// SORT
$directorios = array();
while (false !== ($fn = readdir($mydir)))
{
    if (is_dir($fn) && $fn != "." && $fn != "..")
    {
        $directory = getcwd()."/$fn";
        $key = date("Y\-m\-d\-His ", filectime($directory));
        $directorios[$key] = $directory;
    }
}

ksort($directorios);
$cronosdir = array();
$cronosdir = array_reverse($directorios);

while (list($key, $directory) = each($cronosdir)) {
    echo "$key = $directory<bR>";
}

Pedro
09-Mar-2002 07:09
here 2 functions to ksort/uksort an array and all its member arrays

function tksort(&$array)
  {
  ksort($array);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      tksort($array[$k]);
      }
    }
  }

function utksort(&$array, $function)
  {
  uksort($array, $function);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      utksort($array[$k], $function);
      }
    }
  }
delvach at mail dot com 06-Nov-2001 01:29
A real quick way to do a case-insensitive sort of an array keyed by strings:

uksort($myArray, "strnatcasecmp");
sbarnum at mac dot com 19-Oct-2001 03:54
ksort on an array with negative integers as keys yields some odd results.  Not sure if this is a bad idea (negative key values) or what.
krsort
list
Функции для работы с массивами


Присваивает переменным из списка значения подобно массиву

ksort
natcasesort
Функции для работы с массивами
PHP Manual

list

(PHP 4, PHP 5)

list — Присваивает переменным из списка значения подобно массиву

Описание

array list ( mixed $varname [, mixed $... ] )

Подобно array(), это не функция, а языковая конструкция. list() используется для того, чтобы присвоить списку переменных значения за одну операцию.

Список параметров

varname

Переменная.

Возвращаемые значения

Возвращает присвоенный массив.

Примеры

Пример #1 Примеры использования list()

<?php

$info = array('кофе', 'коричневый', 'кофеин');

// Составить список всех переменных
list($drink, $color, $power) = $info;
echo "$drink - $color, а $power делает его особенным.\n";

// Составить список только некоторых из них
list($drink, , $power) = $info;
echo "В $drink есть $power.\n";

// Или только третья
list( , , $power) = $info;
echo "Мне нужен $power!\n";

// list() не работает со строками
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Пример #2 Пример использования list()

<table>
 <tr>
  <th>Имя работника</th>
  <th>Зарплата</th>
 </tr>

<?php

$result = mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    echo " <tr>\n" .
          "  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          "  <td>$salary</td>\n" .
          " </tr>\n";
}

?>

</table>

Пример #3 Использование list() с индексами массивов

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>
int(1)
int(2)
int(3)

Пример #4 Использование list() с индексами массива

<?php

$info = array('кофе', 'коричневый', 'кофеин');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Выведет (сравните порядок исходных элементов с порядком, в в котором они были перезаписаны list()):

array(3) {
  [2]=>
  string(12) "кофеин"
  [1]=>
  string(20) "коричневый"
  [0]=>
  string(8) "кофе"
}

Примечания

Внимание

list() присваивает значения начиная с крайнего правого параметра. Если вы используете простые переменные, можете не беспокоиться об этом. Но если вы используете индексные массивы, вы можете ожидать, что в результате выполнения функции list() вы получите тот же порядок элементов, что и в исходном массиве: слева направо; однако это не так. Они будут присвоены в обратном порядке.

Внимание

Изменение массива во время выполнения функции list() (например, использование list($a, $b) = $b) приводит к непредсказуемому поведению.

Замечание:

list() работает только с массивами, индексами которых являются числа и нумерация которых начинается с 0.

Смотрите также

  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • array() - Создает массив
  • extract() - Импортирует переменные из массива в текущую таблицу символов

User Contributed Notes

dan dot lugg at gmail dot com 14-Jan-2012 05:43
Although the warning claims of undefined behaviour, it's reasonably straightforward what happens.

<?php
    $a = array(1, 2, 3);
    list($a, $b, $c) = $a;
    var_dump($a, $b, $c);
    // int(1)
    // int(2)
    // int(3)
?>

Since list() works from right to left on the target variables, $a is replaced last, thus keeping the remaining array element values around long enough to populate $b and $c.

<?php
    $a = array(1, 2, 3);
    list($c, $b, $a) = $a;
    var_dump($a, $b, $c);
    // int(3)
    // NULL
    // NULL
?>

$a is populated first (remember, right to left) with the value 3 from itself. Since $a is no longer an array, list() is forced to substitute NULL values for $b and $c.

This appears to be perfectly sensible, though there may be edge cases and other strange behaviour I'm unaware of.
Ultimater at gmail dot com 08-May-2011 03:37
Note that list(...) isn't limited to scalar variables.
It can even create an associative array:

<?php
$html=<<<EOT
<table>
<tr class="row-odd">
<td><span class="username">Foo</span></td>
<td><span class="userid">30185</span></td>
</tr><tr class="row-even">
<td><span class="username">Bar</span></td>
<td><span class="userid">3093</span></td>
</tr>
</table>
EOT;

interface RegExps
{
    const PROFILE_CONTENT='/<tr[^>]*>.*?<span class="username">(.*?)<\/span>[
        ]?.*?<span class="userid">(.*?)<\/span>.*?<\/tr>/msi';
}

preg_match_all(RegExps::PROFILE_CONTENT,$html, $matches,PREG_SET_ORDER);
$profiles=array();
foreach($matches as $match)
{
    $profile=array();
    list(,$profile['username'],$profile['userid'])=$match;
    //$profile=array_reverse($profile);
    $profiles[]=$profile;
}
echo '<pre>'.print_r($profiles,true).'</pre>';
?>

Just be careful, as the manual warns us, regarding the right-most parameter being handled first.
If this becomes a problem, I'd suggest using array_reverse as shown in my code.
boukeversteegh at gmail dot com 06-Apr-2011 12:49
If your array is shorter than the number of arguments in list(), you will get an "undefined index" notice.

You can solve it by making sure the array is long enough:

<?php
   $array = Array( "one", "two" );

   # This will give a Notice: undefined index [2]:
   list( $one, $two, $three ) = $array;

   # This won't:
   list( $one, $two, $three ) = $array + Array( null, null, null );

   # If you know count($array) will be at least 1, you could skip the first index:
   list( $one, $two, $three ) = $array + Array( 1 => null, null );

   # You could of course also use other default values:
   list( $one, $two, $three ) = $array + Array( "one", "two", "three" );
?>
lili at nikha dot org 04-Apr-2011 04:02
Keep it simple!
For associative arrays, my replacement for list() is this:
<?php
foreach ($associative_array as $key => $value) { $$key = $value; }
?>

Example:
<?php
$petnames = array();
$petnames['dog'] = 'Paul';
$petnames['cat'] = 'Lili';

foreach ($petnames as $name => $value) { $$name = $value; }

echo 'my pets are '.$dog.' and '.$cat;
?>

Will give you:
my pets are Paul and Lili
develop at dieploegers dot de 31-Mar-2010 03:37
Remember, that list starts from index 0. You can skip an index if you just leave the column blank like this:

<?php
list(,$a,$b,$c) = array(1,2,3,4);
?>

You CAN'T (at least not in 5.3.1, what I have tested) set the column to null:

<?php
list(null,$a,$b,$c) = array(1,2,3,4);
?>

This will fail.
Anonymous 12-Mar-2010 09:29
Quick little function that is similar to list but for objects.

<?php
    function listObj() {
        $stack = debug_backtrace();
        if (isset($stack[0]['args'])) {
            $i = 0;
            $args = $stack[0]['args'];
            foreach ($args[0] as $key => $value)
                $args[++$i] = $value;
        }
    }

    class obj {public $var = "test"; public $vars = "test2"; function obj() {}}
    listObj(new obj, &$var, &$var2);
    echo $var, $var2;
?>
claude dot pache at gmail dot com 13-May-2009 03:26
A simple way to swap variables (correction of a note of mario dot mueller dot work at gmail dot com below):
<?php
list($var1, $var2) = array($var2, $var1); // swaps the values of $var1 and $var2
?>
Note that this is not equivalent to:
<?php
$var2 = $var1; $var1 = $var2; // $var1 and $var2 get both the old value of $var1
?>
as one could fear. Indeed, the array is constructed with the values of $var1 and $var2 (and not with the variables $var1 and $var2 themselves) before the assignment is carried out.

Similarly, it is possible to bypass the problem pointed by sasha in the previous note by providing an expression rather than a variable on the right-hand side of the assignment operator:
<?php
$var = array ("test" ,"blah");
list ($a,$var) = $var + array();
echo $a ; // prints "test", not "b"
echo $var ; // prints "blah"
?>
tristan in oregon 08-Apr-2008 07:44
Here's yet another way to make a list()-like construct for associative arrays. This one has the advantage that it doesn't depend on the order of the keys, it only extracts the keys that you specify, and only extracts them into the current scope instead of the global scope (which you can still do, but at least here you have the option).

<?php
    $arr  = array("foo" => 1, "bar" => 2, "baz" => 3);
    $keys = array("baz");

//  $foo = 10;
    $bar = 20;
    $baz = 30;

    extract(array_intersect_key($arr, $keys));

    var_dump($foo);
    var_dump($bar);
    var_dump($baz);
?>

Should print
NULL
int(20)
int(3)

If your version of PHP doesn't have array_intersect_key() yet (below 5.1 I think), it's easy to write a limited feature replacement for this purpose.

<?php
function my_array_intersect_key ($assoc, $keys)
{
    $intersection = array();
    foreach ($assoc as $key => $val)
        if (in_array($key, $keys))
            $intersection[$key] = $val;

    return $intersection;
}
?>
kevin at vanzonneveld dot net 06-Feb-2008 07:12
Another way to do it associative (if your array isn't numeric), is to just use array_values like this:

<?php
$os = array();
$os["main"] = "Linux";
$os["distro"] = "Ubuntu";
$os["version"] = "7.10";

list($main, $distro, $version) = array_values($os);
?>
danieljames3 at g mail 19-Jan-2008 05:51
With regard to the note written by ergalvan at bitam dot com:

You must take note that list() assigns variables starting from the rightmost one (as stated in the warning). That makes $record having the value "value4" and then $var1, $var2 and $var3 take their values from the "new" $record variable.

It's clear that the behavior stated in the warning wasn't followed by version 5.0.4 (and perhaps previous versions?)

----------

I'm still seeing this behavior in PHP 5.2.5.  Hopefully someone can comment on why it's been changed.
Hayley Watson 04-Nov-2007 12:36
In the code by tenz699 at hotmail dot com, the list() construct is taking values from the result of the each() function, not from the associative array; the example is therefore spurious.

each() returns an array of four elements, indexed in the order 1, 'value', 0, 'key'. As noted in the documentation, the associative keys are ignored, and the numerically-indexed values are assigned in key order.

<?php
$array = array('foo'=>'bar');
$t = each($array);
print_r($t);
list($a,$b,$c,$d) = $t;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>

Output:
Array
(
    [1] => bar
    [value] => bar
    [0] => foo
    [key] => foo
)
string(3) "foo"
string(3) "bar"
NULL
NULL
tenz699 at hotmail dot com 18-Sep-2007 10:50
PhP manual's NOTE says: list() only works on numerical arrays and assumes the numerical indices start at 0.

I'm finding it do works for associative arrays too,as below:

<?
$tenzin = array ("1" => "one", "2" => "two","3"=>"three");
while(list($keys,$values) = each($tenzin))
echo($keys." ".$values."<br>");
?>

gives O/P
1 one
2 two
3 three

tsarma
mick at wireframe dot com 08-Aug-2007 12:08
It's worth noting that, as expected, list() does not have to have as many variables (and/or empty skips) as there are elements in the array. PHP will disregard all elements that there are no variables for. So:

<?php
$Array_Letters = array('A', 'B', 'C', 'D', 'E', 'F');

list($Letter_1, $Letter_2) = $Array_Letters;

echo $Letter_1 . $Letter_2;
?>

Will output: AB

Mick
tobylewis at logogriph dot com 08-May-2007 03:55
The list construct assigns elements from a numbered array starting from element zero.  It does not assign elements from associative arrays.  So

$arr = array();
$arr[1] = 'x';
list($a, $b) = $arr;
var_dump($a); //outputs NULL because there is no element [0]
var_dump($b); //outputs 'x'

and

$arr = array('red'=>'stop','green'=>'go');
list($a, $b) = $arr;
var_dump($a); //outputs NULL
var_dump($b); //outputs NULL

If there are not enough elements in the array for the variables in the list the excess variables are assigned NULL.

If there are more elements in the array than variables in the list, the extra array elements are ignored without error.

Also the warning above about order of assignment is confusing until you get used to php arrays.  The order in which array elements are stored is the order in which elements are assigned to the array.  So even in a numbered array if you assign $may_arr[2] before you assign $my_array[0] then element [2] will be in the array before [0].  This becomes apparent when using commands like, push, shift or foreach which work with the stored order of the elements.  So the warning only applies when the variables in the list are themselves array elements which have not already been assigned to their array.
ergalvan at bitam dot com 04-May-2006 11:29
With regard to the note written by dolan at teamsapient dot com:

You must take note that list() assigns variables starting from the rightmost one (as stated in the warning). That makes $record having the value "value4" and then $var1, $var2 and $var3 take their values from the "new" $record variable.

It's clear that the behavior stated in the warning wasn't followed by version 5.0.4 (and perhaps previous versions?)
dolan at teamsapient dot com 06-Apr-2006 11:08
I noticed w/ version 5.1.2, the behavior of list() has changed (this occurred at some point between version 5.0.4 and 5.1.2).  When re-using a variable name in list() that list() is being assigned to, instead of the values being assigned all at once, the reused variable gets overwritten before all the values are read.

Here's an example:
** disclaimer: obviously this is sloppy code, but I want to point out the behavior change (in case anyone else comes across similar code) **

<?
$data = array();
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");

foreach($data as $record)
{
    list($var1, $var2, $var3, $record) = $record;
    echo "var 1: $var1, var 2: $var2, var 3: $var3, record: $record\\n";
}
?>

OUTPUT on version 5.0.4:
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4

OUTPUT on version 5.1.2:
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
mzizka at hotmail dot com 02-Jan-2006 08:49
Elements on the left-hand side that don't have a corresponding element on the right-hand side will be set to NULL. For example,

<?php
$y = 0;
list($x, $y) = array("x");
var_dump($x);
var_dump($y);
?>

Results in:

string(1) "x"
NULL
Nearsighted 25-Jul-2005 07:34
list, coupled with while, makes for a handy way to populate arrays.

while (list($repcnt[], $replnk[], $date[]) = mysql_fetch_row($seek0))
{
// insert what you want to do here.
}

PHP will automatically assign numerical values for the array because of the [] signs after the variable.

From here, you can access their row values by array numbers.

eg.

for ($i=0;$i<$rowcount;$i++)
{
echo "The title number $repcnt[$i] was written on $date[$i].";
}
webmaster at miningstocks dot com 31-May-2005 11:05
One way to use the list function with non-numerical keys is to use the array_values() function

<?php
$array = array ("value1" => "one", "value2" => "two");
list ($value1, $value2) = array_values($array);
?>
mortoray at ecircle-ag dot com 16-Feb-2005 01:29
There is no way to do reference assignment using the list function, therefore list assignment is will always be a copy assignment (which is of course not always what you want).

By example, and showing the workaround (which is to just not use list):

    function &pass_refs( &$a ) {
        return array( &$a );
    }

    $a = 1;
    list( $b ) = pass_refs( $a ); //*
    $a = 2;
    print( "$b" ); //prints 1

    $ret = pass_refs( $a );
    $b =& $ret[0];
    $a = 3;
    print( "$b" ); //prints 3

*This is where some syntax like the following would be desired:
   list( &$b ) = pass_refs( $a );
or maybe:
   list( $b ) =& pass_refs( $a );
jennevdmeer at zonnet dot nl 21-Oct-2004 08:29
This is a function simulair to that of 'list' it lists an array with the 'key' as variable name and then those variables contain the value of the key in the array.
This is a bit easier then list in my opinion since you dont have to list up all variable names and it just names them as the key.

<?php
 function lista($a) {
  foreach ($a as $k => $v) {
   $s = "global \$".$k;
   eval($s.";");
   $s = "\$".$k ." = \"". $v."\"";
   eval($s.";");
  }
 }
?>
HW 14-Aug-2004 01:08
The list() construct can be used within other list() constructs (so that it can be used to extract the elements of multidimensional arrays):
<?php
$matrix = array(array(1,2),
                array(3,4));

list(list($tl,$tr),list($bl,$br)) = $matrix;

echo "$tl $tr $bl $br";
?>
Outputs "1 2 3 4".
jeronimo at DELETE_THIS dot transartmedia dot com 28-Jan-2004 07:28
If you want to swap values between variables without using an intermediary, try using the list() and array() language constructs. For instance:

<?

// Initial values.
$biggest = 1;
$smallest = 10;

// Instead of using a temporary variable...
$temp = $biggest;
$biggest = $smallest;
$smallest = $temp;

// ...Just swap the values.
list($biggest, $smallest) = array($smallest, $biggest);

?>

This works with any number of variables; you're not limited to just two.
Cheers,
Jeronimo
rubein at earthlink dot net 28-Dec-2000 05:15
Note: If you have an array full of arrays, you can't use list() in conjunction to foreach() when traversing said array, e.g.

$someArray = array(
  array(1, "one"),
  array(2, "two"),
  array(3, "three")
);

foreach($somearray as list($num, $text)) { ... }

This, however will work

foreach($somearray as $subarray) {
  list($num, $text) = $subarray;
  ...
}
ksort
natcasesort
Функции для работы с массивами


РЎРѕСЂС‚РёСЂСѓРµС‚ РјР°СЃСЃРёРІ, РёСЃРїРѕР»СЊР·СѓСЏ Р°Р»РіРѕСЂРёС‚Рј "natural order" Р±РµР· СѓС‡РµС‚Р° СЂРµРіРёСЃС‚СЂР° СЃРёРјРІРѕР»РѕРІ

list
natsort
Р¤СѓРЅРєС†РёРё РґР»СЏ СЂР°Р±РѕС‚С‹ СЃ РјР°СЃСЃРёРІР°РјРё
PHP Manual

natcasesort

(PHP 4, PHP 5)

natcasesort — РЎРѕСЂС‚РёСЂСѓРµС‚ РјР°СЃСЃРёРІ, РёСЃРїРѕР»СЊР·СѓСЏ Р°Р»РіРѕСЂРёС‚Рј "natural order" Р±РµР· СѓС‡РµС‚Р° СЂРµРіРёСЃС‚СЂР° СЃРёРјРІРѕР»РѕРІ

РћРїРёСЃР°РЅРёРµ

bool natcasesort ( array &$array )

natcasesort() - СЌС‚Рѕ СЂРµРіРёСЃС‚СЂРѕРЅРµР·Р°РІРёСЃРёРјС‹Р№ Р°РЅР°Р»РѕРі natsort().

РС‚Р° С„СѓРЅРєС†РёСЏ СЂРµР°Р»РёР·СѓРµС‚ Р°Р»РіРѕСЂРёС‚Рј СЃРѕСЂС‚РёСЂРѕРІРєРё, РїСЂРё РєРѕС‚РѕСЂРѕРј РїРѕСЂСЏРґРѕРє Р±СѓРєРІРµРЅРЅРѕ-С†РёС„СЂРѕРІС‹С… СЃС‚СЂРѕРє Р±СѓРґРµС‚ РїСЂРёРІС‹С‡РЅС‹Рј РґР»СЏ С‡РµР»РѕРІРµРєР°. РўР°РєРѕР№ Р°Р»РіРѕСЂРёС‚Рј РЅР°Р·С‹РІР°РµС‚СЃСЏ "natural ordering".

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

array

Р’С…РѕРґРЅРѕР№ РјР°СЃСЃРёРІ.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ TRUE РІ СЃР»СѓС‡Р°Рµ СѓСЃРїРµС€РЅРѕРіРѕ Р·Р°РІРµСЂС€РµРЅРёСЏ РёР»Рё FALSE РІ СЃР»СѓС‡Р°Рµ РІРѕР·РЅРёРєРЅРѕРІРµРЅРёСЏ РѕС€РёР±РєРё.

РџСЂРёРјРµСЂС‹

РџСЂРёРјРµСЂ #1 РџСЂРёРјРµСЂ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёСЏ natcasesort()

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "РћР±С‹С‡РЅР°СЏ СЃРѕСЂС‚РёСЂРѕРІРєР°\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order СЃРѕСЂС‚РёСЂРѕРІРєР° (Р±РµР· СѓС‡РµС‚Р° СЂРµРіРёСЃС‚СЂР°)\n";
print_r($array2);
?>

Р РµР·СѓР»СЊС‚Р°С‚ РІС‹РїРѕР»РЅРµРЅРёСЏ РґР°РЅРЅРѕРіРѕ РїСЂРёРјРµСЂР°:

РћР±С‹С‡РЅР°СЏ СЃРѕСЂС‚РёСЂРѕРІРєР°
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Natural order СЃРѕСЂС‚РёСЂРѕРІРєР° (Р±РµР· СѓС‡РµС‚Р° СЂРµРіРёСЃС‚СЂР°)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

РџРѕРґСЂРѕР±РЅРµРµ СЃРјРѕС‚СЂРё СЃС‚Р°С‚СЊСЋ Martin Pool » Natural Order String Comparison.

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • natsort() - РЎРѕСЂС‚РёСЂСѓРµС‚ РјР°СЃСЃРёРІ, РёСЃРїРѕР»СЊР·СѓСЏ Р°Р»РіРѕСЂРёС‚Рј "natural order"
  • РЎСЂР°РІРЅРµРЅРёРµ С„СѓРЅРєС†РёР№ СЃРѕСЂС‚РёСЂРѕРІРєРё РјР°СЃСЃРёРІРѕРІ
  • strnatcmp() - РЎСЂР°РІРЅРµРЅРёРµ СЃС‚СЂРѕРє СЃ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёРµРј Р°Р»РіРѕСЂРёС‚РјР° "natural order"
  • strnatcasecmp() - РЎСЂР°РІРЅРµРЅРёРµ СЃС‚СЂРѕРє Р±РµР· СѓС‡РµС‚Р° СЂРµРіРёСЃС‚СЂР° СЃ РёСЃРїРѕР»СЊР·РѕРІР°РЅРёРµРј Р°Р»РіРѕСЂРёС‚РјР° "natural order"

User Contributed Notes

w-dot-rosenbach-at-netskill-de 14-Dec-2010 09:45
Sorting UTF-8 by arbitrary order:

<?php
mb_internal_encoding("UTF-8");

class utf_8_german
{
  // everything else is sorted at the end
  static $order = '0123456789AaГ„Г¤BbCcDdEeFfGgHhIiJjKkLlMm
NnOoГ–Г¶PpQqRrSsГџTtUuГњГјVvWwXxYyZz';
  static $char2order;

  static function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }

    // lazy init mapping
    if (empty(self::$char2order))
    {
      $order = 1;
      $len = mb_strlen(self::$order);
      for ($order=0; $order<$len; ++$order)
      {
        self::$char2order[mb_substr(self::$order, $order, 1)] = $order;
      }
    }

    $len_a = mb_strlen($a);
    $len_b = mb_strlen($b);
    $max=min($len_a, $len_b);
    for($i=0; $i<$max; ++$i)
    {
      $char_a= mb_substr($a, $i, 1);
      $char_b= mb_substr($b, $i, 1);

      if ($char_a == $char_b) continue;
      $order_a = (isset(self::$char2order[$char_a])) ? self::$char2order[$char_a] : 9999;
      $order_b = (isset(self::$char2order[$char_b])) ? self::$char2order[$char_b] : 9999;

      return ($order_a < $order_b) ? -1 : 1;
    }
    return ($len_a < $len_b) ? -1 : 1;
  }
}

// usage example:

$t = array(
  'Birnen', 'Birne', 'Г„pfel', 'Apfel',
);

uasort($t, 'utf_8_german::cmp');
echo '$t: <pre>'.htmlspecialchars(print_r($t,true),null,'UTF-8').'</pre>';
?>
shawn at shawnwilkerson dot com 05-May-2009 10:03
I kept getting varied results using natcasesort and sort on mixed arrays -- per the descriptions.

Sometimes simple is better:

A little snippet of code:

<?php                        if($responders->num_rows) {
                            $i=0;
                            while($row= $responders->fetch_assoc()) {
                                $user=getUserName($row['responderID']);
                                $r[$i]= array("sortname"=>strtolower($user),"userName"=>$user, "userID"=>$row['responderID'], "responderID"=>$row['idresponders']);
                                $i++;
                            }
                            sort($r);
                            print_r($r);
                        }

?>

I simply created a lower cased sort field at the front of the result set and then sort by it -- which provides the expected result and leaves the actual needed fields unchanged.

For the curious:  all user information is kept completed in another database (and table) from the content database due to security reasons.  The getUser functions we have written allow us to pull only what is legally allowed without exposing anything else.

This is why a left join or something wasn't used and we have to build a pseudo result array here from both databases.
claude at schlesser dot lu 07-Jan-2009 12:41
Here a function that will natural sort an array by keys with keys that contain special characters.

<?php
function natksort($array)
{
    $original_keys_arr = array();
    $original_values_arr = array();
    $clean_keys_arr = array();

    $i = 0;
    foreach ($array AS $key => $value)
    {
        $original_keys_arr[$i] = $key;
        $original_values_arr[$i] = $value;
        $clean_keys_arr[$i] = strtr($key, "Г„Г–ГњГ¤Г¶ГјГ‰Г€ГЂГ‹Г«Г©ГЁГ Г§", "AOUaouEEAEeeeac");
        $i++;
    }

    natcasesort($clean_keys_arr);

    $result_arr = array();

    foreach ($clean_keys_arr AS $key => $value)
    {
        $original_key = $original_keys_arr[$key];
        $original_value = $original_values_arr[$key];
        $result_arr[$original_key] = $original_value;
    }

    return $result_arr;
}
?>

Hope it will be useful to somebody :)
Kim 02-Dec-2008 07:45
If your array already is sorted ASC or DESC, then natcasesort, ksort and sort (I only tested those) will invert the sorting order.
This is most troublesome since its impossible to force a sorting order. I had to use array_multisort instead and lose the natrual sorting.

Natcasesort expects a single dimension array, so if your value is an array then it will report a "Array to string conversion" notice per key/value set.
php at method5 dot de 06-Nov-2003 10:56
hi all,
this is my first post at php.net first of all thank you for this huge site :)

ok i found it usefull to post this for others. in the german language we have words like 'д ц ь' its called "umlaute" and it was a problem to me to "naturally" sort an huge array correctly so i coded this small block to get me helped, if anyone has an better idea please post and let us know as i am not a real crack :)

1. change each "umlaut" (дцьЯ) into its "nearest" equivalent
2. natcasesorting it naturally
3. re-assiging the correct sorted array with the original-words again while keeping track of the KEY...

example-array:
$aSupplier = array(3 => "MAN",2 => "Atlas",16 => "Chevrolet",17 => "Chrysler",19 => "Citroen",24 => "DAF",25 => "Daihatsu",27 => "Daewoo",28 => "Demag",30 => "Dodge",36 => "Schierling",208 => "HIAB",38 => "Hьffermann",39 => "Gergen",40 => "Kubato",41 => "Faun",43 => "Kleindienst",44 => "Swing",45 => "Neuhaus",46 => "Unimog",47 => "Meiller",48 => "Pfau-Johnston",49 => "Geesink",50 => "Schцrling",51 => "Demag-Witting",53 => "Helmers",54 => "Ellermann",55 => "Jacobsen",56 => "Biki",57 => "Hansa",58 => "Kramer",59 => "Schmitz",60 => "Toro",61 => "Iseki",62 => "Haller",63 => "Kuka",64 => "Brock",65 => "Ambross",66 => "Sobernheimer",67 => "Pietsch",68 => "Kьpper",69 => "Weisser",71 => "Wackenhut");

foreach ( $aSupplier as $key => $value )
{
    $aSupplier2[$key] = strtr($aSupplier[$key], "ДЦЬдцьЯ", "AOUaous");
}

natcasesort($aSupplier2);

foreach ( $aSupplier2 as $key => $value )
{
  if ( $aSupplier2[$key] != "" )
    $aSupplier3[$key] = $aSupplier[$key];
}

echo "<pre>";
print_r($aSupplier3);
echo "</pre>";

greetz
tim
vbAlexDOSMan at Yahoo dot com 12-Sep-2003 01:21
Ulli at Stemmeler dot net:  I remade your function -- it's a little more compact now -- Enjoy...

function ignorecasesort(&$array) {

  /*Make each element it's lowercase self plus itself*/
  /*(e.g. "MyWebSite" would become "mywebsiteMyWebSite"*/
  for ($i = 0; $i < sizeof($array); $array[$i] = strtolower($array[$i]).$array[$i], $i++);

  /*Sort it -- only the lowercase versions will be used*/
  sort($array);

  /*Take each array element, cut it in half, and add the latter half to a new array*/
  /*(e.g. "mywebsiteMyWebSite" would become "MyWebSite")*/
  for ($i = 0; $i < sizeof($array); $i++) {
    $this = $array[$i];
    $array[$i] = substr($this, (strlen($this)/2), strlen($this));
  }
}
dslicer at maine dot rr dot com 02-Jun-2003 06:41
Something that should probably be documented is the fact that both natsort and natcasesort maintain the key-value associations of the array. If you natsort a numerically indexed array, a for loop will not produce the sorted order; a foreach loop, however, will produce the sorted order, but the indices won't be in numeric order. If you want natsort and natcasesort to break the key-value associations, just use array_values on the sorted array, like so:

natcasesort($arr);
$arr = array_values($arr);
tmiller25 at hotmail dot com 25-Apr-2002 07:55
add this loop to the function above if you want items which have the same first characters to be listed in a way that the shorter string comes first.
--------------------
  /* short before longer (e.g. 'abc' should come before 'abcd') */
  for($i=count($array)-1;$i>0;$i--) {
    $str_a = $array[$i  ];
    $str_b = $array[$i-1];
    $cmp_a = strtolower(substr($str_a,0,strlen($str_a)));
    $cmp_b = strtolower(substr($str_b,0,strlen($str_a)));
    if ($cmp_a==$cmp_b && strlen($str_a)<strlen($str_b)) {
      $array[$i]=$str_b; $array[$i-1]=$str_a; $i+=2;
    }
  }
--------------------
Ulli at Stemmeler dot net 05-Apr-2002 08:01
natcasesort didn't work first time I needed something like this.
Not on my local server, not on my server on the web.
I needed an array sorted ignoring upper and lower cases. In the end lower case array-members stayed at the end of the array.

I replaced it with this function:
---------
function ignorecasesort(&$array) {
$separator="|<>|";
for($i=0;$i<sizeof($array);$i++) { $array[$i]=strtolower($array[$i]).$separator.$array[$i]; }
sort($array);
for($i=0;$i<sizeof($array);$i++) { $this=$array[$i]; $this=explode($separator,$this); $array[$i]=$this[1]; }
}
---------
list
natsort
Р¤СѓРЅРєС†РёРё РґР»СЏ СЂР°Р±РѕС‚С‹ СЃ РјР°СЃСЃРёРІР°РјРё


Сортирует массив, используя алгоритм "natural order"

natcasesort
next
Функции для работы с массивами
PHP Manual

natsort

(PHP 4, PHP 5)

natsort — Сортирует массив, используя алгоритм "natural order"

Описание

bool natsort ( array &$array )

Эта функция реализует алгоритм сортировки, при котором порядок буквенно-цифровых строк будет привычным для человека. Такой алгоритм называется "natural ordering". Отличие алгоритма "natural ordering" от обычных алгоритмов сортировки, применяемых, например, функцией sort() можно увидеть в примере ниже.

Список параметров

array

Входной массив.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
5.2.10 | В строках, отбитых нулями спереди, (например, '00005') теперь данная отбивка игнорируется.

Примеры

Пример #1 Простой пример использования natsort()

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Обычная сортировка\n";
print_r($array1);

natsort($array2);
echo "\nСортировка natural order\n";
print_r($array2);
?>

Результат выполнения данного примера:

Обычная сортировка
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Сортировка natural order
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Подробнее смотри статью Martin Pool » Natural Order String Comparison.

Пример #2 Примеры использования различных трюков с natsort()

<?php
echo "Отрицательные числа\n";
$negative = array('-5','3','-2','0','-1000','9','1');
print_r($negative);
natsort($negative);
print_r($negative);

echo "Отбивка нулями\n";
$zeros = array('09', '8', '10', '009', '011', '0');
print_r($zeros);
natsort($zeros);
print_r($zeros);

echo "Другие символы\n";
$images_oops = array('image_1.jpg','image_12.jpg', 'image_21.jpg', 'image_4.jpg');
print_r($images_oops);
natsort($images_oops);
print_r($images_oops);

echo "Сортировка по ключу\n";
$smoothie = array('orange' => 1, 'apple' => 1, 'yogurt' => 4, 'banana' => 4);
print_r($smoothie);
uksort( $smoothie, 'strnatcmp');
print_r($smoothie);
?>

Результат выполнения данного примера:

Отрицательные числа
Array
(
    [0] => -5
    [1] => 3
    [2] => -2
    [3] => 0
    [4] => -1000
    [5] => 9
    [6] => 1
)
Array
(
    [2] => -2
    [0] => -5
    [4] => -1000
    [3] => 0
    [6] => 1
    [1] => 3
    [5] => 9
)

Отбивка нулями
Array
(
    [0] => 09
    [1] => 8
    [2] => 10
    [3] => 009
    [4] => 011
    [5] => 0
)
Array
(
    [5] => 0
    [1] => 8
    [3] => 009
    [0] => 09
    [2] => 10
    [4] => 011
)

Другие символы
Array
(
    [0] => image_1.jpg
    [1] => image_12.jpg
    [2] => image_21.jpg
    [3] => image_4.jpg
)
Array
(
    [0] => image_1.jpg
    [3] => image_4.jpg
    [1] => image_12.jpg
    [2] => image_21.jpg
)

Сортировка по ключу
Array
(
    [orange] => 1
    [apple]  => 1
    [yogurt] => 4
    [banana] => 4
)
Array
(
    [apple]  => 1
    [banana] => 4
    [orange] => 1
    [yogurt] => 4
)

Смотрите также

  • natcasesort() - Сортирует массив, используя алгоритм "natural order" без учета регистра символов
  • Сравнение функций сортировки массивов
  • strnatcmp() - Сравнение строк с использованием алгоритма "natural order"
  • strnatcasecmp() - Сравнение строк без учета регистра с использованием алгоритма "natural order"

User Contributed Notes

RuneImp at gmail dot com 13-Jan-2012 08:17
A natural key sorting function that won't loose data. Using an array_flip technique might be faster but can loose data if the initial values are not all unique.

<?php
/**
 * keyNatSort does a natural sort via key on the supplied array.
 *
 * @param   $array      The array to natural sort via key.
 * @param   $saveMemory If true will delete values from the original array as it builds the sorted array.
 * @return  Sorted array on success. Boolean false if sort failed or null if the object was not an array.
 */
function keyNatSort($array, $saveMemory=false)
{
    if(is_array($array))
    {
        $keys = array_keys($array);
        if(natsort($keys))
        {
            $result = array();
            foreach($keys as $key)
            {
                $result[$key] = $array[$key];
                if($saveMemory)
                    unset($array[$key]);
            }

        }
        else
            $result = false;
    }
    else
        $result = null;

    return $result;
}
?>
jonathan_2097 at hotmail dot com 16-Nov-2011 10:33
natsort by key
<?php
function knatsort($array)
{
    return array_flip(natsort(array_flip($array));
}
?>
Johan GENNESSON (php at genjo dot fr) 24-Nov-2010 07:18
Be careful of the new behaviour in 5.2.10 version.
See the following sample:

<?php

$array = array('1 bis', '10 ter', '0 PHP', '0', '01', '01 Ver', '0 ', '1 ', '1');

natsort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>

5.2.6-1 will output:
Array
(
    [3] => 0
    [6] => 0
    [2] => 0 OP
    [4] => 01
    [5] => 01 Ver
    [8] => 1
    [7] => 1
    [0] => 1 bis
    [1] => 10 ter
)

5.2.10 will output:
Array
(
    [6] => 0
    [3] => 0
    [8] => 1
    [4] => 01
    [7] => 1
    [5] => 01 Ver
    [0] => 1 bis
    [1] => 10 ter
    [2] => 0 OP
)

Greetings
the_A at gmx dot at 03-Feb-2010 07:55
Another approach to a natsord2d-function:
Imagine having an array like:
Array
(
    [subarray1] => Array
        (
            [1] => foo
            [2] => bar
        )
    [subarray2] => Array
        (
            [1] => 12
            [2] => 2
        )
)
and you want to natsort it (=all the sub-arrays) by the values of sub-array2

<?php
    function natsort2d_custom (&$array, $sortby) {
        natsort($array[$sortby]);    //First natsort the specified sub-array $sortby
        $sorted_array = array();    //Create a temporary array
        $sorted_array[$sortby] = $array[$sortby];     //Add the sorted sub-array to the temporary array with teh same key

        foreach($array AS $key1=>$value1) {     //Walking through the rest of $array, ...
            if($key1 != $sortby) {     //...leaving out [$sortby]
                $sorted_array[$key1] = array();     //Create sub-array $key1

                foreach ($array[$sortby] AS $key2=>$value2) {     //Walk trough $array[$sortby] (which is now already natsorted) key by key
                    $sorted_array[$key1][$key2] = $array[$key1][$key2];
                    // Put keys (and values) of array[$key1] in the same order as array[$sort] and stuff it into $sorted_array with the same key
                }
            }
        }
        $array = $sorted_array;
        reset($array);
    }
?>
After sorting the array this way, it would be:
Array
(
    [subarray1] => Array
        (
           [2] => bar
           [1] => foo

        )
    [subarray2] => Array
        (
            [2] => 2
            [1] => 12
        )
)

This works, of course, with an unlimited amount of sub-arrays, provided none of the sub-arrays has a sub-array itself (non-recoursive)
Christoph 25-Nov-2009 10:45
Note:

The natsort function will sort depending on the operating system, but not depending on either Linux or Windows-based systems

There's a difference when sorting an array which is generated from the filesystem:
Array(
    [0] => ./system/kernel/js/01_ui.core.js
    [1] => ./system/kernel/js/00_jquery-1.3.2.js
    [2] => ./system/kernel/js/02_my.desktop.js
)

natsort($array) will result in two different ways:

Case 1: (Debian)
Array(
    [1] => ./system/kernel/js/00_jquery-1.3.2.js
    [0] => ./system/kernel/js/01_ui.core.js
    [2] => ./system/kernel/js/02_my.desktop.js
)

Case 2: (Debian Kernel, but Ubuntu shadowed php-Version)
Array(
    [0] => ./system/kernel/js/01_ui.core.js
    [2] => ./system/kernel/js/02_my.desktop.js
    [1] => ./system/kernel/js/00_jquery-1.3.2.js
)

...so make sure you've named the files beginning with 01, then it works fine.
kirik-san at users.sourceforge.net 29-Oct-2009 07:51
Just a reverse sorting function for "natural order" algorithm:
<?php
function natrsort(&$array)
{
    natsort($array);
    $array = array_reverse($array);
}

$arr = array("img12.png", "img2.png", "img1.png", "img10.png");
natrsort($arr);
print_r($arr);
?>
ale152 16-Mar-2009 02:00
Note: negatives number.
<?php
$a = array(-5,-2,3,9);
natsort($a);
print_r($a);
?>
Will output:
Array ( [1] => -2 [0] => -5 [2] => 3 [3] => 9 )
AJenbo 15-Jan-2009 01:33
natsort might not act like you would expect with zero padding, heres a quick sample.

<?php
$array = array('09', '8', '10', '009', '011');
natsort($array);
?>
/*
Array
(
    [3] => 009
    [4] => 011
    [0] => 09
    [1] => 8
    [2] => 10
)
*/
wyvern at greywyvern dot com 17-Dec-2008 10:53
There's no need to include your own API code to natsort an associative array by key.  PHP's in-built functions (other than natsort) can do the job just fine:

<?php
  uksort($myArray, "strnatcmp");
?>
awizemann at gmail dot com 30-Aug-2007 12:34
natsort() will not work correctly if you use underscores in file names (if your array is for sorting files).

Example:

$images = array('image_1.jpg','image_12.jpg');

Will not produce the same as:

$images = array('image1.jpg','image12.jpg');
lacent at gmail dot com 16-Jan-2007 09:42
there is another rnatsort function lower on the page, but it didn't work in the context i needed it in.

reasoning for this:
sorting naturally via the keys of an array, but needing to reverse the order.

    function rnatsort ( &$array = array() )
    {
        $keys    = array_keys($array);
        natsort($keys);
        $total    = count($keys) - 1;
        $temp1    = array();
        $temp2     = array();

        // assigning original keys to an array with a backwards set of keys, to use in krsort();
        foreach ( $keys as $key )
        {
            $temp1[$total] = $key;
            --$total;
        }

        ksort($temp1);

        // setting the new array, with the order from the krsort() and the values of original array.
        foreach ( $temp1 as $key )
        {
            $temp2[$key] = $array[$key];
        }

        $array = $temp2;
    }
@gmail bereikme 01-Sep-2006 08:06
Here's a handy function to sort an array on 1 or more columns using natural sort:
<?php
// Example: $records = columnSort($records, array('name', 'asc', 'addres', 'desc', 'city', 'asc'));

$globalMultisortVar = array();
function columnSort($recs, $cols) {
    global $globalMultisortVar;
    $globalMultisortVar = $cols;
    usort($recs, 'multiStrnatcmp');
    return($recs);
}

function multiStrnatcmp($a, $b) {
    global $globalMultisortVar;
    $cols = $globalMultisortVar;
    $i = 0;
    $result = 0;
    while ($result == 0 && $i < count($cols)) {
        $result = ($cols[$i + 1] == 'desc' ? strnatcmp($b[$cols[$i]], $a[$cols[$i]]) : $result = strnatcmp($a[$cols[$i]], $b[$cols[$i]]));
        $i+=2;
    }
    return $result;
}

?>

Greetings,

  - John
12-Mar-2006 07:44
The last comment should have been posted in doc about (r)sort( ). Indeed, and unfortunately, ORDER BY *does not* perform natural ordering. So, sometimes we *must* do a SQL request followed by natsort( ).
h3 22-Feb-2006 08:59
This function can be very usefull, but in some cases, like if you want to sort a MySQL query result, it's important to keep in mind that MySQL as built'in sorting functions which are way faster than resorting the result using a complex php algorythm, especially with large arrays.

ex; 'SELECT * FROM `table` ORDER BY columnName ASC, columnName2 DESC'
lil at thedreamersmaze dot spam-me-not dot org 31-Jan-2006 08:38
There's one little thing missing in this useful bit of code posted by mbirth at webwriters dot de:

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
   reset($value);
   $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
   $aryOut[$key] = $aryInput[$key];
// --------^^^^ add this if you want your keys preserved!
  }
  $aryInput = $aryOut;
}

?>
natcasesort.too 05-Aug-2005 03:17
I got caught out through naive use of this feature - attempting to sort a list of image filenames from a digital camera, where the filenames are leading zero padded (e.g. DSCF0120.jpg) , will not sort correctly.
Maybe the example could be modified to exhibit this behaviour
(e.g. set array to -img0120.jpg','IMG0.png', 'img0012.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png)
If the example hadn't used images I would have coded it correctly first time around!
mroach at mroach dot com 27-Jun-2005 09:08
Here's an expansion of the natsort2d function that mbirth wrote. This one allows you to specify the key for sorting.

<?php
function natsort2d( &$arrIn, $index = null )
{

    $arrTemp = array();
    $arrOut = array();

    foreach ( $arrIn as $key=>$value ) {

        reset($value);
        $arrTemp[$key] = is_null($index)
                            ? current($value)
                            : $value[$index];
    }

    natsort($arrTemp);

    foreach ( $arrTemp as $key=>$value ) {
        $arrOut[$key] = $arrIn[$key];
    }

    $arrIn = $arrOut;

}

?>
phpnet at moritz-abraham dot de 02-Sep-2004 02:09
additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this:
<?
$array['test0'] = array('main' =>  'a', 'sub' => 'a');
$array['test2'] = array('main' =>  'a', 'sub' => 'b');
$array['test3'] = array('main' =>  'b', 'sub' => 'c');
$array['test1'] = array('main' =>  'a', 'sub' => 'c');
$array['test4'] = array('main' =>  'b', 'sub' => 'a');
$array['test5'] = array('main' =>  'b', 'sub' => 'b');
?>
or
<?
$array[0] = array('main' =>  1, 'sub' => 1);
$array[2] = array('main' =>  1, 'sub' => 2);
$array[3] = array('main' =>  2, 'sub' => 3);
$array[1] = array('main' =>  1, 'sub' => 3);
$array[4] = array('main' =>  2, 'sub' => 1);
$array[5] = array('main' =>  2, 'sub' => 2);
?>
on one or more columns.

the code
<? $array = array_natsort_list($array,'main','sub'); ?>
will result in $array being sortet like this:
test0,test2,test1,test4,test5,test3
or
0,2,1,4,5,3.

you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached.

to me it was very usefull for sorting a menu having submenus and even sub-submenus.

i hope it might help you too.

here is the function:
<?
function array_natsort_list($array) {
    // for all arguments without the first starting at end of list
    for ($i=func_num_args();$i>1;$i--) {
        // get column to sort by
        $sort_by = func_get_arg($i-1);
        // clear arrays
        $new_array = array();
        $temporary_array = array();
        // walk through original array
        foreach($array as $original_key => $original_value) {
            // and save only values
            $temporary_array[] = $original_value[$sort_by];
        }
        // sort array on values
        natsort($temporary_array);
        // delete double values
        $temporary_array = array_unique($temporary_array);
        // walk through temporary array
        foreach($temporary_array as $temporary_value) {
            // walk through original array
            foreach($array as $original_key => $original_value) {
                // and search for entries having the right value
                if($temporary_value == $original_value[$sort_by]) {
                    // save in new array
                    $new_array[$original_key] = $original_value;
                }
            }
        }
        // update original array
        $array = $new_array;
    }
    return $array;
}
?>
xlab AT adaptiveNOSPAMarts DOT net 15-Jan-2004 12:51
Under limited testing, natsort() appears to work well for IP addresses. For my needs, it is far less code than the ip2long()/long2ip() conversion I was using before.
mbirth at webwriters dot de 09-Jan-2004 12:31
For those who want to natsort a 2d-array on the first element of each sub-array, the following few lines should do the job.

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
    reset($value);
    $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
    $aryOut[] = $aryInput[$key];
  }
  $aryInput = $aryOut;
}

?>
rasmus at flajm dot com 14-Dec-2003 09:30
To make a reverse function, you can simply:

function rnatsort(&$a){
    natsort($a);
    $a = array_reverse($a, true);
}
justin at redwiredesign dot com 22-Aug-2003 10:10
One of the things I've needed to do lately is apply natural sorting to a complex array, e.g.:

Array
(
    [0] => Array
        (
            [ID] = 4
            [name] = Fred
        )

    [1] => Array
        (
            [ID] = 6
            [name] = Bob
        )
)

where I want to sort the parent array by the child's name. I couldn't see a way of doing this using array_walk, so I've written a simple function to do it. Hopefully someone will find this useful:

/**
 * @return Returns the array sorted as required
 * @param $aryData Array containing data to sort
 * @param $strIndex Name of column to use as an index
 * @param $strSortBy Column to sort the array by
 * @param $strSortType String containing either asc or desc [default to asc]
 * @desc Naturally sorts an array using by the column $strSortBy
 */
function array_natsort($aryData, $strIndex, $strSortBy, $strSortType=false)
{
    //    if the parameters are invalid
    if (!is_array($aryData) || !$strIndex || !$strSortBy)
        //    return the array
        return $aryData;

    //    create our temporary arrays
    $arySort = $aryResult = array();

    //    loop through the array
    foreach ($aryData as $aryRow)
        //    set up the value in the array
        $arySort[$aryRow[$strIndex]] = $aryRow[$strSortBy];

    //    apply the natural sort
    natsort($arySort);

    //    if the sort type is descending
    if ($strSortType=="desc")
        //    reverse the array
        arsort($arySort);

    //    loop through the sorted and original data
    foreach ($arySort as $arySortKey => $arySorted)
        foreach ($aryData as $aryOriginal)
            //    if the key matches
            if ($aryOriginal[$strIndex]==$arySortKey)
                //    add it to the output array
                array_push($aryResult, $aryOriginal);

    //    return the return
    return $aryResult;
}
flash at minet dot net 12-Aug-2003 10:27
About the reverse natsort.. Maybe simpler to do :

function strrnatcmp ($a, $b) {
    return strnatcmp ($b, $a);
}
dslicer at maine dot rr dot com 02-Jun-2003 06:41
Something that should probably be documented is the fact that both natsort and natcasesort maintain the key-value associations of the array. If you natsort a numerically indexed array, a for loop will not produce the sorted order; a foreach loop, however, will produce the sorted order, but the indices won't be in numeric order. If you want natsort and natcasesort to break the key-value associations, just use array_values on the sorted array, like so:

natsort($arr);
$arr = array_values($arr);
anonymous at coward dot net 31-May-2003 01:46
Reverse Natsort:

  function rnatsort($a, $b) {
    return -1 * strnatcmp($a, $b);
  }

  usort($arr, "rnatsort");
natcasesort
next
Функции для работы с массивами


Передвигает внутренний указатель массива на одну позицию вперёд

natsort
pos
Функции для работы с массивами
PHP Manual

next

(PHP 4, PHP 5)

next — Передвигает внутренний указатель массива на одну позицию вперёд

Описание

mixed next ( array &$array )

next() ведёт себя подобно current(), но с одним отличием. Перед тем, как возвратить значение элемента массива, эта функция передвигает его внутренний указатель на одну позицию вперёд. Другими словами, она возвращает следующий элемент массива и сдвигает его внутренний указатель на одну позицию.

Список параметров

array

Массив array модифицируется данной функцией.

Возвращаемые значения

Возвращает значение элемента массива, находящегося на позиции, следующей за позицией внутренний указателя или FALSE, если достигнут конец массива.

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Пример использования next() и друзей

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Примечания

Замечание: Вы не сможете отличить конец массива от boolean элемента FALSE. Для корректного обхода массива, который может содержать FALSE элементы, смотрите функцию each().

Смотрите также

  • current() - Возвращает текущий элемент массива
  • end() - Устанавливает внутренний указатель массива на его последний элемент
  • prev() - Передвигает внутренний указатель массива на одну позицию назад
  • reset() - Устанавливает внутренний указатель массива на его первый элемент
  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель

User Contributed Notes

double at dumpit dot de 08-Dec-2009 01:19
PHP: 5.2.10-2ubuntu6.3 (default apt-get installation on actual, see Date, jaunty 9.10 Ubuntu Distro - G33kWoRDs)

Have a look at your array pointer if you copy an array - the pointer will be copied, too.

For example if you got this construct:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    $array2 = $array;
    next($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

But if you copy the array after you've setted the pointer, the pointer will be copied, too:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = $array;
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 1
?>

What's more is, that foreach not resetting the pointer after walk through:
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array();
    foreach($array AS $key => $value){
        echo $key;
        $array2[$key] = $value;
    }
    echo var_dump(key($array));
    echo key($array2);

    // will output for foreach:
    // 0 1 2 3 4 5 6 7
    // and for the keys
    // NULL
    // 0
?>

The php-functions seems to reset the pointer on the given position after walk through (i don't know the internal handling - there could be used a copy of the array, too):
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array_values($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

There are a lot Methods like array_merge($array) that will neither reset the pointer of $array nor copy the pointer to $array2. Have a look on this.
I Hope this was a little helpfull.
ThinkMedical at Gmail dot com 02-Sep-2008 03:27
regarding references with foreach, you can use them directly. Obviating various posts which provide many lines of 'work arounds'.

$array = array(1,2,3,4,5);

foreach($array as &$value)

or use $key

foreach($array as $key => $value)
{
    $array[$key] = '...';
}
adityabhai [at] gmail com [Aditya Bhatt] 09-May-2008 05:14
<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

    public function getPrev () {

      self::setCurrent($this->curr);
      return prev($this->all);

    }

  }
?>

Demo Example:

<?php
   $steps = new Steps();
   $steps->add('1');
   $steps->add('2');
   $steps->add('3');
   $steps->add('4');
   $steps->add('5');
   $steps->add('6');
   $steps->setCurrent('4');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
   $steps->setCurrent('2');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
?>
darkside at i dot ua 11-Dec-2007 03:36
This class implements simple operations with array

<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

  }
?>

usage example:

<?php
   $steps = new Steps();
   $steps->add('one');
   $steps->add('two');
   $steps->add('three');
   $steps->setCurrent('one');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   $steps->setCurrent('two');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
?>
gg2005 at gmail dot com 06-Feb-2007 01:32
Don't confuse next with continue!

If you're a Perl developer starting with PHP, you might try to use "next" inside a loop to skip to the next iteration...

i.e.,

foreach ($things as $thing) {
  if (something I don't like about $thing) {
   next;
  }
  blah....
}

The php compiler will take next... but it's not going to work.

Do this instead:
foreach ($things as $thing) {
  if (something I don't like about $thing) {
   continue;
  }
  blah....
}
GPatmore 12-Oct-2006 12:14
If your using a foreach loop, unless you for a reference, PHP will make a copy of the array to use it the loop.

So, when I need to take a different action for the last element in the array I use the following:

<?php
$ary  = explode(',','a,b,c,d,e,f,g');
foreach($ary as $a){
    print 'letter ' . $a;
    if(next($ary)){
        print '<br>';
    }else{
        print '<br>dun!';
    }
}
?>

Output:

letter a
letter b
letter c
letter d
letter e
letter f
letter g
dun!

NOTE::
PHP5 has added an ability to reference the variable in a foreach like:

<?php
foreach($ary as &$a){}
?>

this will probably cause undesired results when using the method above.

also if the array is changed in any way as to cause the length of the original array to become different then the copy, it will not work.
Consider the following example:

<?php
$ary  = explode(',','a,b,c,d,e,f,g');
foreach($ary as $a){
    print 'letter ' . $a;
    if(next($ary)){
        unset($ary[count($ary) - 1]);
        print '<br>';
    }else{
        print '<br>dun!';
    }
}
?>

output:

letter a
letter b
letter c
letter d
dun!letter e
dun!letter f
dun!letter g
dun!
tom at nono dot be 26-Jul-2006 04:19
I see some questions like "how can I know if an array has a next value without changing its internal pointer" and some pretty complicated responses that DO work mind you and in some cases you'll need them...

But suppose you just need a different action within a foreach loop when reaching the final item:
(it won't be usefull in every situation, but in most it will)

$numOfItems = count($someArray);
$counter = 0;
foreach ($someArray as $key => value){
    $counter += 1;
    if ($counter <> $numOfItems){
        //here all next items exist
   } else {
        //final item
   }
}
Sigmar 30-May-2006 03:02
And if you want to know if there are any array elements in array before given key, you can use this function:

function any_array_keys_before($keyname, &$array) {
    if (!is_array($array)) {
        return false;
    }
    if (empty($keyname)) {
        return false;
    }
    $set = false;
    $count = 0;
    foreach ($array as $key => $value) {
        if ($set === false && $key != $keyname) {
            $count ++;
        } else if ($key == $keyname) {
            $set = true;
        }
    }
    return $count > 0 ? true : false;
}
Sigmar 30-May-2006 02:52
If you want to check, if there are some more elements in array after given key, you can use the following function:

function more_array_keys($keyname, &$array) {
    if (!is_array($array)) {
        return false;
    }
    if (empty($keyname)) {
        return false;
    }
    $set = false;
    $count = 0;
    foreach ($array as $key => $value) {
        if ($set === true) {
            $count++;
        }
        if ($key == $keyname) {
            $set = true;
        }
    }
    return $count > 0 ? true : false;
}
tino at infeon dot com 13-May-2006 08:48
this may be handy and i didnt know where else to post it.. i need a simple function to cycle through an array i eventually made it into a class so i could have multiple cycles.. if you like it or find it usefull please email me and let me know

class Cycle
{
    var $position;
    var $dataArray;
    var $dataArrayCount;

    function Cycle()
    {
        $this->dataArray = func_get_args();
        $this->dataArrayCount = count($this->dataArray);
    }

    function Display()
    {
        $this->position = (!isset($this->position) || $this->position >= ($this->dataArrayCount - 1)) ? 0 : $this->position += 1;
        return $this->dataArray[$this->position];
    }

}

$bgColor = new Cycle('#000000', '#FFFFFF', '#FF0000');

echo $bgcolor->Display();
//returns #000000
echo $bgcolor->Display();
//returns #FFFFFF
echo $bgcolor->Display();
//returns #FF0000
echo $bgcolor->Display();
//returns #000000
brentimus 28-Apr-2005 10:10
Papipo's function below is usefull in concept but does not work.

"Since you do not pass the array by reference, its pointer is only moved inside the function."

This is true, but the array you are manipulating in your has_next() function will have it's pointer set to the first element, not the same position as the original array. What you want to do is pass the array to the has_next() function via reference. While in the has_next() function, make a copy of the array to work on. Find out the current pointer position of the original array and set the pointer on the working copy of the array to the same element. Then you may test to see if the array has a "next" element.

Try the followig insetad:

<?php
function has_next(&$array)
{
    $A_work=$array;  //$A_work is a copy of $array but with its internal pointer set to the first element.
    $PTR=current($array);
    array_set_pointer($A_work, $PTR);

    if(is_array($A_work))
    {
        if(next($A_work)===false)
            return false;
        else
            return true;
    }
    else
        return false;
}

function array_set_pointer(&$array, $value)
{
    reset($array);
    while($val=current($array))
    {
        if($val==$value)
            break;

        next($array);
    }
}
?>
papipo's gmail account 13-Oct-2004 01:47
I need to know if an array has more items, but without moving array's internail pointer. Thats is, a has_next() function:

<?php
function has_next($array) {
    if (is_array($array)) {
        if (next($array) === false) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

$array = array('fruit', 'melon');
if (has_next($array)) {
    echo next($array);
}

// prints 'melon'
?>

Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
lukasz at karapuda dot com 18-Aug-2004 10:06
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($arr, $key)
{
   $keys = array_keys($arr);
   $keyIndexes = array_flip($keys);

   $return = array();
   if (isset($keys[$keyIndexes[$key]-1])) {
       $return[] = $keys[$keyIndexes[$key]-1];
   }
   else {
       $return[] = $keys[sizeof($keys)-1];
   }

   if (isset($keys[$keyIndexes[$key]+1])) {
       $return[] = $keys[$keyIndexes[$key]+1];
   }
   else {
       $return[] = $keys[0];
   }

   return $return;
}
?>
court shrock 20-May-2004 04:36
This code returns neighbors of the specified key.  The result will be empty if it doesn't have any neighbors.  My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array.  Feel free to point out stupidities :)

<?php

function array_neighbor($arr, $key)
{
    krsort($arr);
    $keys = array_keys($arr);
    $keyIndexes = array_flip($keys);

    $return = array();
    if (isset($keys[$keyIndexes[$key]-1]))
        $return[] = $keys[$keyIndexes[$key]-1];
    if (isset($keys[$keyIndexes[$key]+1]))
        $return[] = $keys[$keyIndexes[$key]+1];

    return $return;
}

?>
bm at ANTISPAM dot solidwave dot com 16-Apr-2004 09:49
Take care when replacing code using reset()/next() with code using foreach as foreach does not update the array's internal pointer.  This means you cannot, say, use next() to skip an element in foreach loop, or use current() within a function to get a reference to the current element.  You probably have code depending on this internal pointer and replacing it will be more work than you anticipated.

See http://www.php.net/foreach
natsort
pos
Функции для работы с массивами


Псевдоним current

next
prev
Функции для работы с массивами
PHP Manual

pos

(PHP 4, PHP 5)

pos — Псевдоним current()

Описание

Эта функция является псевдонимом: current()

User Contributed Notes

There are no user contributed notes for this page.
next
prev
Функции для работы с массивами


Передвигает внутренний указатель массива на одну позицию назад

pos
range
Функции для работы с массивами
PHP Manual

prev

(PHP 4, PHP 5)

prev — Передвигает внутренний указатель массива на одну позицию назад

Описание

mixed prev ( array &$array )

Передвигает внутренний указатель массива на одну позицию назад.

prev() ведёт себя подобно next(), за исключением того, что она передвигает внутренний указатель массива на одну позицию назад, а не вперёд.

Список параметров

array

Входной массив.

Возвращаемые значения

Возвращает значение массива, на которое ранее указывал внутренний указатель массива, или FALSE если больше элементов нет.

Примеры

Пример #1 Пример использования prev() и друзей

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Примечания

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Замечание: Вы не сможете различить начало массива от boolean элемента FALSE. Для корректного обхода массива, который может содержать элементы FALSE, смотрите функцию each().

Смотрите также

  • current() - Возвращает текущий элемент массива
  • end() - Устанавливает внутренний указатель массива на его последний элемент
  • next() - Передвигает внутренний указатель массива на одну позицию вперёд
  • reset() - Устанавливает внутренний указатель массива на его первый элемент
  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель

User Contributed Notes

soapergem at gmail dot com 29-May-2009 12:06
Here's a slight revision to xmlich02's backwards iteration example. The problem with his/her example is that it will halt if any of the array elements are boolean false, while this version will not.

<?php

end($ar);
while ( !is_null($key = key($ar)) ) {
    $val = current($ar);
    echo "{$key} => {$val}\n";
    prev($ar);
}

?>
xmlich02 at stud dot fit dot vutbr dot cz 29-Sep-2007 12:19
// example of backward iteration

$ar = array ( 'a', 'b', 'c', 'd', 'e', 'f') ;

print_r($ar);

end($ar);
while($val = current($ar)) {
  echo $val.' ';
  prev($ar);
}
pos
range
Функции для работы с массивами


Создает массив, содержащий диапазон элементов

prev
reset
Функции для работы с массивами
PHP Manual

range

(PHP 4, PHP 5)

range — Создает массив, содержащий диапазон элементов

Описание

array range ( mixed $start , mixed $limit [, number $step = 1 ] )

Создает массив, содержащий диапазон элементов.

Список параметров

start

Первое значение последовательности.

limit

Конечное значение, которым заканчивается последовательность.

step

Если указан параметр step, то он будет использоваться как инкремент между элементами последовательности. step должен быть положительным числом. Если step не указан, он принимает значение по умолчанию 1.

Возвращаемые значения

Возвращает массив элементов от start до limit, включительно.

Список изменений

Версия | Описание
5.0.0 | Добавлен необязательный параметр step.
4.1.0 to 4.3.2 | В PHP версий с 4.1.0 по 4.3.2, range() рассматривала числовые строки именно как строки, а не числа. Вместо них использовалась последовательность знаков. Например, "4242" трактовалось как "4".
4.1.0 | До появления PHP 4.1.0, range() создавала только массивы, содержащие диапазон чисел в порядке возрастания. Поддержка диапазонов знаков и убывающих диапазонов была добавлена в версии 4.1.0. Диапазон знаков можно задать только при помощи строки из одного знака. Если длина такой строки будет более одного знака, будет использован только первый знак.

Примеры

Пример #1 Примеры использования range()

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
    echo $number;
}

// Параметр step был добавлен в 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
    echo $number;
}

// Использование последовательности знаков было добавлено в версии 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
    echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
    echo $letter;
}
?>

Смотрите также

  • shuffle() - Перемешивает массив
  • array_fill() - Заполняет массив значениями
  • foreach

User Contributed Notes

me at phpscott dot com 23-May-2012 05:37
So, I needed a quick and dirty way to create a dropdown select for hours, minutes and seconds using 2 digit formatting, and to create those arrays of data, I combined range with array merge..

<?php
$prepend = array('00','01','02','03','04','05','06','07','08','09');
$hours     = array_merge($prepend,range(10, 23));
$minutes     = array_merge($prepend,range(10, 59));
$seconds     = $minutes;
?>

Super simple.
dries at volta dot be 09-Feb-2012 11:30
Ever wanted to generate an array with a range of column names for use in Excel file related parsing?
I've wrote a function that starts at the A column and adds column names up until the column you specified.

<?php

/**
 * This function creates an array with column names up until the column
 * you specified.
*/
function createColumnsArray($end_column, $first_letters = '')
{
  $columns = array();
  $length = strlen($end_column);
  $letters = range('A', 'Z');

  // Iterate over 26 letters.
  foreach ($letters as $letter) {
      // Paste the $first_letters before the next.
      $column = $first_letters . $letter;

      // Add the column to the final array.
      $columns[] = $column;

      // If it was the end column that was added, return the columns.
      if ($column == $end_column)
          return $columns;
  }

  // Add the column children.
  foreach ($columns as $column) {
      // Don't itterate if the $end_column was already set in a previous itteration.
      // Stop iterating if you've reached the maximum character length.
      if (!in_array($end_column, $columns) && strlen($column) < $length) {
          $new_columns = createColumnsArray($end_column, $column);
          // Merge the new columns which were created with the final columns array.
          $columns = array_merge($columns, $new_columns);
      }
  }

  return $columns;
}

?>

Usage:

<?php

// Return an array with all column names from A until and with BI.
createColumnsArray('BI');

?>
Aram Kocharyan 27-Feb-2011 07:58
Here's a function to generate ranges from strings:

<?php

/*  Creates an array of integers based on a given range string of format "int - int"
    Eg. range_str('2 - 5'); */
function range_str($str) {
    preg_match('#(\\d+)\\s*-\\s*(\\d+)#', $str, $matches);
    if ( count($matches) == 3 ) {
        return range($matches[1], $matches[2]);
    }
    return FALSE;
}

// Test
$array = range_str(' 2 - 4 ');
print_r($array);

?>

This outputs:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)
jay at NOspam dot myd3 dot com 29-Apr-2009 05:54
This is a modified version of thomas' range_string() function. It's simpler, cleaner, and more robust, but it lacks the advanced features his function had, hopefully it will be of assitance to someone.

Examples:

    input: "1, 2, 3, 4, 5, 6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1 - -6" --> output: 1, 2, 3, 4, 5, 6
    input: "0 - 0" --> output: 0
    input: "1, 4-6, 2" --> output: 1, 2, 4, 5, 6
    input: "6,3-1" --> output: 1, 2, 3, 6

<?php

define('RANGE_ARRAY_SORT', 1);
define('RANGE_ARRAY', 2);
define('RANGE_STRING_SORT', 3);
define('RANGE_STRING', 4);

function range_string($range_str, $output_type = RANGE_ARRAY_SORT)
{
    // Remove spaces and nother non-essential characters
    $find[]    = "/[^\d,\-]/";
    $replace[] = "";

    // Remove duplicate hyphens
    $find[]    = "/\-+/";
    $replace[] = "-";

    // Remove duplicate commas
    $find[]    = "/\,+/";
    $replace[] = ",";

    $range_str = preg_replace($find, $replace, $range_str);

    // Remove any commas or hypens from the end of the string
    $range_str = trim($range_str,",-");

    $range_out = array();
    $ranges    = explode(",", $range_str);

    foreach($ranges as $range)
    {

        if(is_numeric($range) || strlen($range) == 1)
        {
            // Just a number; add it to the list.
            $range_out[] = (int) $range;
        }
        else if(is_string($range))
        {

            // Is probably a range of values.
           $range_exp = preg_split("/(\D)/",$range,-1,PREG_SPLIT_DELIM_CAPTURE);

            $start = $range_exp[0];
            $end   = $range_exp[2];

            if($start > $end)
            {
                for($i = $start; $i >= $end; $i -= 1)
                {
                    $range_out[] = (int) $i;
                }
            }
            else
            {
                for($i = $start; $i <= $end; $i += 1)
                {
                    $range_out[] = (int) $i;
                }
            }

        }
    }

    switch ($output_type) {
        case RANGE_ARRAY_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_ARRAY:
            return $range_out;
            break;

        case RANGE_STRING_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_STRING:

        default:
            return implode(", ", $range_out);
            break;
    }
}

// Sample Usage:
$range = range_string("6, 3-1");

?>
thomas+php1 at tgohome dot com 30-Sep-2008 08:44
Range as a string. Items are separated with a comma; which can be in any of the following formats:

"1, 2, 3, 4, 5, 6" - output: 1, 2, 3, 4, 5, 6
"1 - 6"  - output: 1, 2, 3, 4, 5, 6
"1 -%2 6" - output: 1, 3, 5 (last number will not be counted unless it evenly fits in)
"1 - -6" - output: 1, 0, -1, -2, -3, -4, -5, -6
"0 - 0" - output: 0
"1, 2, 3, [LAST_NUM] - 6" - output: 1, 2, 3, 3, 4, 5, 6 (note repeated 3)
"1, 2, 3, [LAST_NUM+1] - 6" - output: 1, 2, 3, 4, 5, 6 (no repeated 3)
"1, 2, 3, [LAST_NUM+-1] - 6" - output: 1, 2, 3, 2, 3, 4, 5, 6

<?php

define('RANGE_ARRAY', 1);
define('RANGE_STRING', 2);

function range_string($range_str, $output_type = RANGE_ARRAY)
{
    $range_out = array();
    $ranges = explode(",", $range_str);

    $last_num = 0;

    foreach($ranges as $range)
    {
        $step = 1;
        $range = trim($range);

        if(is_numeric($range))
        {
            // Just a number; add it to the list.
            $range_out[] = $range;
            $last_num = $range;
        }
        else if(is_string($range))
        {
            // Figure out if it is just a character.
            if(strlen($range) == 1)
            {
                $range_out[] = (string)$range;
                $last_num = 0;
            }
            else
            {
                // Is probably a range of values.
                $range_exp = explode(" ", $range);

                if(substr($range_exp[1], 0, 1) == '-' && !is_numeric(substr($range_exp[1], 0, 1)))
                {
                    // Jumping range?
                    $jump = str_split($range_exp[1], 1);

                    if(count($jump) > 0)
                    {
                        if($jump[1] == '%')
                        {
                            $step = substr($range_exp[1], 2);
                        }
                    }
                    else
                    {
                        // Normal range.
                        $step = 1;
                    }
                }
                else
                {
                    $step = 1;
                }

                if($range_exp[0] == '[LAST_NUM]')
                {
                    $start = $last_num;
                }
                else
                {
                    $exp = explode("+", $range_exp[0]);

                    if($exp[0] == '[LAST_NUM')
                    {
                        $start = $last_num + trim($exp[1], ']');
                    }
                    else
                    {
                        $start = $range_exp[0];
                    }
                }

                $end = $range_exp[2];

                if($start > $end)
                {
                    for($i = $start; $i >= $end; $i -= $step)
                    {
                        $range_out[] = $i;
                    }

                    $last_num = $i;
                }
                else
                {
                    for($i = $start; $i <= $end; $i += $step)
                    {
                        $range_out[] = $i;
                    }

                    $last_num = $i;
                }

                // echo $step . ", ";
            }
        }
    }

    if($output_type == RANGE_ARRAY)
    {
        return $range_out;
    }
    else
    {
        return implode(", ", $range_out);
    }
}

echo range_string("1, 2, 3, [LAST_NUM+1] - 6", RANGE_STRING);

?>
ThinkMedical at Gmail dot com 26-Aug-2008 05:11
foreach(range()) whilst efficiant in other languages, such as python, it is not (compared to a for) in php*.

php is a C-inspired language and thus for is entirely in-keeping with the lanuage aethetic to use it

<?php
//efficiant
for($i = $start; $i < $end; $i+=$step)
{
        //do something with array
}

//inefficiant
foreach(range($start, $end, $step) as $i)
{
        //do something with array
}
?>

That the officiant documentation doesnt mention the for loop is strange.

Note however, that in PHP5 foreach is faster than for when iterating without incrementing a variable.

* My tests using microtime and 100 000 iterations consistently (~10 times) show that for is 4x faster than foreach(range()).
captvanhalen at gmail dot com 27-Mar-2008 10:33
Here is a home rolled range() function that uses the step feature for those unfortunate souls who cannot use PHP5:

<?php
function my_range( $start, $end, $step = 1) {

    $range = array();

    foreach (range( $start, $end ) as $index) {

        if (! (($index - $start) % $step) ) {
            $range[] = $index;
        }
    }

    return $range;
}
?>
chris at laflash dot org 09-May-2007 04:47
Quick HTML menus with minimum and maximum sets of years:

<?php
    /*
    ** Quick HTML menus with minimum and maximum sets of years.
    ** @author Chris Charlton <chris@laflash.org>
    ** @license FREE!
    */

    // Years range setup
    $year_built_min = 1900;
    $year_built_max = date("Y");
?>
<select id="yearBuiltMin" size="1">
    <?php // Generate minimum years

        foreach (range($year_built_min, $year_built_max) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>

<select id="yearBuiltMax" size="1">
      <?php // Generate max years

        foreach (range($year_built_max, $year_built_min) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>
m0sh3 at hotmail dot com 01-Mar-2007 05:46
Here's how i use it to check if array is associative or not:

<?php

if (array_keys($arr)===range(0, sizeof($arr)-1)) {
// not associative array

} else {
// associative array

}

?>
manuel at levante dot de 07-Nov-2006 05:25
<?php
function srange ($s) {
  preg_match_all("/([0-9]{1,2})-?([0-9]{0,2}) ?,?;?/", $s, $a);
  $n = array ();
  foreach ($a[1] as $k => $v) {
    $n  = array_merge ($n, range ($v, (empty($a[2][$k])?$v:$a[2][$k])));
  }
  return ($n);
}

$s = '1-4 6-7 9-10';
print_r(srange($s));
?>

Return:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 6
    [5] => 7
    [6] => 9
    [7] => 10
)
subscription101 at hotmail dot com 08-Jan-2006 06:36
A much simpler way of creating a range of even numbers is by starting with an even number:

<?php

    range(2, 10, 2);

?>
emory underscore smith at hotmail 20-Aug-2005 07:53
since its not stated explicitly above, thought id point out that you arent limited to using integers.

however, be careful when doing so, as you might not get the range you expect!

to illustrate:

<?php
$am = range(500,1600,10);
$fm = range(88.1,107.9,.2);
print_r($am);
print_r($fm);
?>

print_r($am) yields the expected result:

Array
(
    [0] => 500
    [1] => 510
    [2] => 520
    ...
    [109] => 1590
    [110] => 1600
)

print_r($fm), however, falls a bit (1%) short:

Array
(
    [0] => 88.1
    [1] => 88.3
    [2] => 88.5
    ...
    [97] => 107.5
    [98] => 107.7
)

so, if you want to use a non-integral step size params for numeric ranges, be sure to account for fp representation accuracy and error accumulation; a step size of something like pi or 1/10 could spell disaster for a large range. if in doubt, use integral steps and divide ... something like <?php range(88.1,108,.2) ?> might work to recover 107.9, but would not be scalable like, say <?php array_map(create_function('$x','return $x/10;'),range(881,1079,2)) ?>.

-emory
derek at php dot net 08-May-2005 06:13
This should emulate range() a little better.
<?php
function range_wroar($low, $high, $step = 1) {
    $arr = array();
    $step = (abs($step)>0)?abs($step):1;
    $sign = ($low<=$high)?1:-1;
    if(is_numeric($low) && is_numeric($high)) {
        //numeric sequence
        for ($i = (float)$low; $i*$sign <= $high*$sign; $i += $step*$sign)
            $arr[] = $i;
    }    else    {
        //character sequence
        if (is_numeric($low))
            return $this->range($low, 0, $step);
        if (is_numeric($high))
            return $this->range(0, $high, $step);
        $low = ord($low);
        $high = ord($high);
        for ($i = $low; $i*$sign <= $high*$sign; $i += $step*$sign) {

            $arr[] = chr($i);
        }
    }
    return $arr;
}
?>
j dot gizmo at aon dot at 23-Sep-2004 04:23
i figured i'd add some more functionality to the myRange() functions below.
now you can, besides giving a $step parameter,
1. count backwards
2. count with letters
3. give whatever parameter you want, there's nothing (i know of) that will cause an endless loop (try a negative $step for the previous function....)

<?php
function myRange($num1, $num2, $step=1)
{
    if (is_numeric($num1) && is_numeric($num2))
    {
        //we have a numeric range
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get the direction
        for($i = (float)$num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = $i;
        }
    }
    else
    {
        //we have a character range
        $num1=ord((string)$num1); //convert to ascii value
        $num2=ord((string)$num2);
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get direction
        for($i = $num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = chr($i);
        }
    }
    return $temp;
}

print_r(myRange( 1, 3, 0.5 )); //you can use fractional steps
print_r(myRange( "a", "k", 3 )); //or count letters
print_r(myRange( "5", "9" )); //numbers are detected even if hidden in strtings
print_r(myRange( "!", "%", 1/pi() )); //or mess around with senseless parameters

?>
donwilson at gmail dot com 31-Aug-2004 09:38
To speed your MyRange() function, I have created a much nicer function with less code to sift through to include the step parameter.

<?php
    // range() limitation for PHP <5.0.0
    function myRange($num1, $num2, $step=1)
    {
        for($i = $num1; $i <= $num2; $i += $step)
        {
            $temp[] = $i;
        }

        return $temp;
    }
?>

For whatever reason my comment was deleted..?
Forrester at tfcustomized dot com 17-May-2004 07:57
Since users of < PHP 5.0.0 don't have the option of the step parameter, I've created a little function to account for it:

@USAGE: (int low, int high [, int step])

function myRange($low,$high,$step=1)
{
$ranArray = range($low,$high);
$step--;
$keys = count($ranArray);
    for($i=0;$i<$keys;$i++)
    {
    $retArray[] = $ranArray[$i];
    $i = $i + $step;
    }
return $retArray;
}

// Example usage:
print_r(myRange(1,11,2));
// Returns the array:
// [0] => 1
// [1] => 3
// [2] => 5
// [3] => 7
// [4] => 9
// [5] => 11
prev
reset
Функции для работы с массивами


Устанавливает внутренний указатель массива на его первый элемент

range
rsort
Функции для работы с массивами
PHP Manual

reset

(PHP 4, PHP 5)

reset — Устанавливает внутренний указатель массива на его первый элемент

Описание

mixed reset ( array &$array )

reset() перемещает внутренний указатель array к его первому элементу и возвращает значение первого элемента массива.

Список параметров

array

Входной массив.

Возвращаемые значения

Возвращает значение первого элемента массива, или FALSE, если массив пуст.

Примеры

Пример #1 Пример использования reset()

<?php

$array = array('первый шаг', 'второй шаг', 'третий шаг', 'четвертый шаг');

// по умолчанию указатель указывает на первый элемент
echo current($array) . "<br />\n"; // "первый шаг"

// пропускаем два шага
next($array);
next($array);
echo current($array) . "<br />\n"; // "третий шаг"

// сбрасываем указатель, тем самым возвращаемся к первому шагу
reset($array);
echo current($array) . "<br />\n"; // "первый шаг"

?>

Смотрите также

  • current() - Возвращает текущий элемент массива
  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • end() - Устанавливает внутренний указатель массива на его последний элемент
  • next() - Передвигает внутренний указатель массива на одну позицию вперёд
  • prev() - Передвигает внутренний указатель массива на одну позицию назад

User Contributed Notes

milo at mdlwebsolutions dot com 03-Apr-2012 10:22
GOTCHA: If your first element is false, you don't know whether it was empty or not.

<?php

$a = array();
$b = array(false, true, true);
var_dump(reset($a) === reset($b)); //bool(true)

?>

So don't count on a false return being an empty array.
kendsnyder at gmail dot com 08-Feb-2010 08:12
Don't use `reset()` to get the first value of an associative array. It works great for true arrays but works unexpectedly on Iterator objects. http://bugs.php.net/bug.php?id=38478
steffen schomberg 17-Jul-2007 05:32
The following method resets every array contained in a multi-dimensional array recursively. It takes the multi-dimensional array as parameter.

function Array_Dimensional_Reset(&$arrRef) {
    foreach ($arrRef as $key=>$val) {
        if (is_array($val)) {
            $this->Array_Dimensional_Reset($val);
            reset($arrRef[$key]);
        }
    }
}
m dot lebkowski+php at gmail dot com 03-Aug-2006 01:58
Colin, there`s a better (IMO) way to solve your problem.
<?
  // ...
  foreach($a as $k => &$d){}   // notice the "&"
  // ...
?>
It`s a new feature in PHP5 to use references in foreach loop. This way PHP isn`t making a copy of the array, so the internal pointer won`t be reset.
Colin 06-Jun-2006 08:11
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason.  The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.

The following code demonstrates the resetting of a subarray:

<?
$a = array(
    'a' => array(
        'A', 'B', 'C', 'D',
    ),
    'b' => array(
        'AA', 'BB', 'CC', 'DD',
    ),
);

// Set the pointer of $a to 'b' and the pointer of 'b' to 'CC'
reset($a);
next($a);
next($a['b']);
next($a['b']);
next($a['b']);

var_dump(key($a['b']));
foreach($a as $k => $d)
{
}
var_dump(key($a['b']));
?>

The result of the two var dumps are 3 and 0, respectively.  Clearly the internal pointer of $a['b'] was reset by doing the foreach loop over $a.

Each time the foreach loop iterated over the 'a' and 'b' keys of $a it made a copy of $a['a'] and $a['b'] into $d which resetted the internal pointers of $a['a'] and $a['b'] despite making no obvious changes.

The solution is instead to iterate over the keys of $a.

<?
foreach(array_keys($a) as $k)
{
}
?>

and using $a[$k] (or creating an alias of $a[$k] as $d and dealing with the consequences of using aliases).

For the curious, I was implementing the Iterator interface on a dummy object and calling a global object to do the actual iteration (also to cope with PHP's lack of C-style pointers which when doing a $a = $b on objects would cause the data in $a to be inconsistent with the data in $b when modified).  Being that I had many dummy objects representing different data sets I chose to store each data set as a subarray contained within the global object.  To make this work each dummy object has to store a key (which can freely be duplicated without problems) that it passes to the global object when rewind, key, current, next, and valid were called on the dummy object.

Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings.  Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.

So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.

Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
27-Feb-2006 01:20
I wrote a nice function, which rotates values of array. Very useful for table rows where you have to rotate colors

<?php
function rotate(&$array) {
    $item = current($array);
    if (!next($array)) reset($array);
    return $item;
}
?>
Alexandre Koriakine 18-Nov-2005 02:09
Also it's good to reset this way the multidimentional arrays:

reset($voo2['moder']);
while (list($key, $value) = each ($voo2['moder'])) {

reset($voo2['moder'][$key]);
while (list($key1, $value1) = each ($voo2['moder'][$key])) {
#do what u want
}

}
s_p_a_mcatcher at hotmail dot com 01-Dec-2004 10:30
Be aware that when using reset() to clear an element and key from an array, if auto-incrementing, the new array keys will not reset a key previously set:

$temparray[] = "0";
$temparray[] = "1";
$temparray[] = "2";
unset($temparray[2]);
$temparray[] = "2";
$temparray[] = "3";

print_r($temparray);

The above will return:
Array
(
    [0] => 0
    [1] => 1
    [3] => 2
    [4] => 3
)

When attempting something like this, its better to use array_pop().

hope it helped
leaetherstrip at inbox dot NOSPAMru 17-Oct-2004 06:54
Note that reset() will not affect sub-arrays of multidimensional array.

For example,

<?php
    $arr = array(
        1 => array(2,3,4,5,6),
        2 => array(6,7,8,9,10)
    );

    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }

    reset($arr);

    // Do the same again
    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }
?>

will print

IN $arr[1]
$arr[1][0] = 2
$arr[1][1] = 3
$arr[1][2] = 4
$arr[1][3] = 5
$arr[1][4] = 6
IN $arr[2]
$arr[2][0] = 6
$arr[2][1] = 7
$arr[2][2] = 8
$arr[2][3] = 9
$arr[2][4] = 10
IN $arr[1]
IN $arr[2]
kevin at oceania dot net 18-Jul-2003 06:54
Here is a simple example on how to combine 2 arrays. Here we use array_combine() to create list of months and there respective month number. The same result could just as easily be achieved with array('1'=>'January') etc.

<?php

  // make it or break it
  error_reporting(E_ALL);

  // create and array of keys
  $keys = range(1,12);

  // create an array of months
  $months = array(
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
);

  // combine the arrays
  $combined_array = array_combine($keys, $months);

  // echo out the results
  foreach($combined_array as $k=>$v){ echo $k.' -> '.$v.'<br />'; }

?>
jules 12-Jun-2003 12:29
Be aware that if you give an empty array to reset(), what you'll get back is a boolean. consider...

      $myarray = array();
      $ret = reset($myarray);
      echo 'reset has type '. gettype($ret) .' and val * '. $ret;
      if( $ret )
      {
        echo '*. But it evaluates true';
      }
      else
      {
        echo '*. It evaluates false';
      }
      if( is_null($ret) )
      {
        echo ', and appears null';
      }
      {
        echo ', and appears not null';
      }

      echo '.';

<output>
reset has type boolean and val * *. It evaluates false, and appears not null.
</output>

<bleaugh/>
kk at shonline dot de 30-Jul-1998 05:22
When used on a scalar or unset value, reset() spews warning messages. This is often a problem when accessing arrays generated from HTML form input data: these are scalar or unset if the user didn't enter sufficient information.

You can silence these error messages by prefixing an @ (at sign) to reset(), but it is better style to protect your reset() and the following array traversal with an if (isset()). Example code:

<?php
if (isset($form_array)) {
  reset($form_array);
  while (list($k, $v) = each($form_array) {
    do_something($k, $v);
  }
}
?>
range
rsort
Функции для работы с массивами


Сортирует массив в обратном порядке

reset
shuffle
Функции для работы с массивами
PHP Manual

rsort

(PHP 4, PHP 5)

rsort — Сортирует массив в обратном порядке

Описание

bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Эта функция сортирует массив в обратном порядке (от большего к меньшему).

Список параметров

array

Входной массив.

sort_flags

Вы можете изменить поведение сортировки, используя дополнительный параметр sort_flags, подробнее смотрите функцию sort().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования rsort()

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Результат выполнения данного примера:

0 = orange
1 = lemon
2 = banana
3 = apple

Названия фруктов были отсортированы по алфавиту в обратном порядке.

Примечания

Замечание: Эта функция присваивает новые ключи элементам массива. Она удалит все существующие ключи, а не просто переупорядочит их.

Смотрите также

  • arsort() - Сортирует массив в обратном порядке, сохраняя ключи
  • krsort() - Сортирует массив по ключам в обратном порядке
  • Сравнение функций сортировки массивов

User Contributed Notes

Alex M 27-Jun-2005 07:39
A cleaner (I think) way to sort a list of files into reversed order based on their modification date.

<?php
   $path = $_SERVER[DOCUMENT_ROOT]."/files/";
   $dh = @opendir($path);

   while (false !== ($file=readdir($dh)))
   {
      if (substr($file,0,1)!=".")
         $files[]=array(filemtime($path.$file),$file);   #2-D array
   }
   closedir($dh);

   if ($files)
   {
      rsort($files); #sorts by filemtime

      #done! Show the files sorted by modification date
      foreach ($files as $file)
         echo "$file[0] $file[1]<br>\n";  #file[0]=Unix timestamp; file[1]=filename
   }
?>
pshirkey at boosthardware dot com 14-Jan-2005 01:06
I needed a function that would sort a list of files into reversed order based on their modification date.

Here's what I came up with:

function display_content($dir,$ext){

    $f = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($folder = readdir($dh)) !== false) {
                if (preg_match("/\s*$ext$/", $folder)) {
                    $fullpath = "$dir/$folder";
                    $mtime = filemtime ($fullpath);

                    $ff = array($mtime => $fullpath);
                    $f = array_merge($f, $ff);

            }
                }

            rsort($f, SORT_NUMERIC);

            while (list($key, $val) = each($f)) {
                $fcontents = file($val, "r");
                while (list($key, $val) = each($fcontents))
                    echo "$val\n";
            }

        }
    }

        closedir($dh);
}

Call it like so:

display_content("folder","extension");
ray at non-aol dot com 02-Nov-2004 07:49
Like sort(), rsort() assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.  This means that it will destroy associative keys.

$animals = array("dog"=>"large",  "cat"=>"medium",  "mouse"=>"small");
print_r($animals);
//Array ( [dog] => large [cat] => medium [mouse] => small )

rsort($animals);
print_r($animals);
//Array ( [0] => small [1] => medium [2] => large )

Use KSORT() or KRSORT() to preserve associative keys.
rnk-php at kleckner dot net 17-Jun-2003 12:37
Apparently rsort does not put arrays with one value back to zero.  If you have an array like: $tmp = array(9 => 'asdf') and then rsort it, $tmp[0] is empty and $tmp[9] stays as is.
slevy1 at pipeline dot com 12-Jun-2001 11:15
I thought rsort was working successfully or on a multi-dimensional array of strings that had first been sorted with usort(). But, I noticed today that the array  was only partially in descending order.  I tried array_reverse on it and that seems to have solved things.
reset
shuffle
Функции для работы с массивами


Перемешивает массив

rsort
sizeof
Функции для работы с массивами
PHP Manual

shuffle

(PHP 4, PHP 5)

shuffle — Перемешивает массив

Описание

bool shuffle ( array &$array )

Эта функция перемешивает элементы массива в случайном порядке.

Список параметров

array

Массив.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования shuffle()

<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?>

Список изменений

Версия | Описание
4.2.0 | Генератор случайных чисел инициализируется автоматически.

Примечания

Замечание: Эта функция присваивает новые ключи элементам массива. Она удалит все существующие ключи, а не просто переупорядочит их.

Смотрите также

  • Сравнение функций сортировки массивов

User Contributed Notes

tim at leethost dot com 26-Sep-2011 06:15
This is a great SEO function for web developers.  It shuffles the array, but does it identically each time. SEOshuffle guarantees shuffled yet consistent order.

<?php
/* $seed variable is optional */
function SEOshuffle(&$items, $seed=false) {
  $original = md5(serialize($items));
  mt_srand(crc32(($seed) ? $seed : $items[0]));
  for ($i = count($items) - 1; $i > 0; $i--){
    $j = @mt_rand(0, $i);
    list($items[$i], $items[$j]) = array($items[$j], $items[$i]);
  }
  if ($original == md5(serialize($items))) {
    list($items[count($items) - 1], $items[0]) = array($items[0], $items[count($items) - 1]);
  }
}
?>
timtrinidad at gmail dot com 08-Aug-2011 12:38
It appears that the suhosin extensions >= 0.9.26 that have the suhosin.mt_srand.ignore and suhosin.srand.ignore settings set to "Off" do not affect shuffle().

In other words, the only way I was able to get pseudo-random and predictable results through shuffle() was to disable the extension.
Donald 14-Jun-2011 08:25
Very simple shuffle function preserving key with value

<?php
function shuffle_assoc( $array )
{
   $keys = array_keys( $array );
   shuffle( $keys );
   return array_merge( array_flip( $keys ) , $array );
}
?>
Eric Anderson 29-Mar-2011 09:33
Copy and paste this script and refresh the page to see the shuffling effect.

<?php
    /**
    * Shuffles and displays cards in a deck
    * @author:     Eric Anderson
    * @filename:   deckofcards.php
    */

    // Create an array of face values
    // and an array of card values
    // then merge them together
    $cards = array_merge(array("J", "Q", "K", "A"), range(2,10)); // 13 cards

    // Shuffle the cards
    shuffle($cards);

    // Create an multidimentional array to hold the 4 suits
    $suits = array(
        'Heart' => array(),
        'Spade' => array(),
        'Diamond' => array(),
        'Club' => array()
        );

    // Add cards to their respective suits
    for($i = 0; $i < count($suits); $i++)
    {
        for($j = 0; $j < count($cards); $j++)
        {
            $suits['Heart'][$j] = $cards[$j]."<span style=color:#FF0000;>&hearts;</span>";
            $suits['Spade'][$j] = $cards[$j]."&spades;";
            $suits['Diamond'][$j] = $cards[$j]."<span style=color:#FF0000;>&diams;</span>";
            $suits['Club'][$j] = $cards[$j]."&clubs;";
        }
    }

    // Create a deck
    $deck = array();

    // Merge the suits into the empty deck array
    $deck = array_merge($deck, $suits);

    // Display the deck to the screen
    echo "<p><b>Deck of cards:</b></p>";
    foreach($deck as $k1 => $v1)
    {
        // Display suit name
        echo "<p>&emsp;$k1's<br />&emsp;{<br />&emsp;&emsp;";
        $acc = 0;

        // Display card value
        foreach($v1 as $k2 => $v2)
        {
            echo "$v2&nbsp";
            $acc++;

            if ($acc == 4)
            {
                echo "<br />&emsp;&emsp;";
                $acc = 0;
            }
        }
        echo "<br />&emsp;}</p>";
    }
?>
andjones at gmail dot com 26-Aug-2010 09:35
Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

<?php

function shuffle_assoc($list) {
  if (!is_array($list)) return $list;

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key)
    $random[$key] = $list[$key];

  return $random;
}

?>
ezakto at ezakto dot com 24-Jul-2010 11:13
This is a replica of shuffle() but preserving keys (associative and non-associative)

bool kshuffle  (  array &$array  )

<?php

function kshuffle(&$array) {
    if(!is_array($array) || empty($array)) {
        return false;
    }
    $tmp = array();
    foreach($array as $key => $value) {
        $tmp[] = array('k' => $key, 'v' => $value);
    }
    shuffle($tmp);
    $array = array();
    foreach($tmp as $entry) {
        $array[$entry['k']] = $entry['v'];
    }
    return true;
}

$array = array('first' => 0, 'second' => 1, 'third' => 2);
kshuffle($array);
print_r($array); // [second] => 1 [first] => 0 [third] => 2

$array = array('first', 'second', 'third');
kshuffle($array);
print_r($array); // [1] => second [2] => third [0] => first

?>
m0gr14 at gmail dot com 04-Jul-2010 10:39
This function shuffles an associative array recursive.

<?php

/**
* Shuffles an associative array recursive
* @author Mogria <m0gr14@gmail.com>
* @param array $array
* @return array
*
*/

function rec_assoc_shuffle($array)
{
  $ary_keys = array_keys($array);
  $ary_values = array_values($array);
  shuffle($ary_values);
  foreach($ary_keys as $key => $value) {
    if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) {
      $ary_values[$key] = rec_assoc_shuffle($ary_values[$key]);
    }
    $new[$value] = $ary_values[$key];
  }
  return $new;
}

?>

Example of use:
<?php
$array =
    Array(
        1,
        Array(
            1,
            2,
            3,
            4,
            Array(
                1,
                2,
                3,
                4,
                5
            )
        ),
        2,
        3,
        Array(
            0,
            1,
                Array(
                    1,
                    2,
                    3,
                    4,
                        Array(
                            1,
                            6,
                            5,
                            2,
                            1,
                            3
                        )
                )
        ),
        4,
        5,
        6,
        7
    );
$array = rec_assoc_shuffle($array);
echo '<pre>';
print_r($array);
echo '</pre>';

/*
Returns:
Array
(
    [0] => 6
    [1] => 5
    [2] => Array
        (
            [0] => 1
            [1] => 3
            [2] => Array
                (
                    [0] => 3
                    [1] => 1
                    [2] => 2
                    [3] => 4
                    [4] => 5
                )

            [3] => 2
            [4] => 4
        )

    [3] => 3
    [4] => Array
        (
            [0] => Array
                (
                    [0] => 3
                    [1] => 1
                    [2] => 4
                    [3] => Array
                        (
                            [0] => 5
                            [1] => 1
                            [2] => 3
                            [3] => 6
                            [4] => 1
                            [5] => 2
                        )

                    [4] => 2
                )

            [1] => 1
            [2] => 0
        )

    [5] => 2
    [6] => 1
    [7] => 4
    [8] => 7
)

*/

?>
rick at suggestive dot com 24-Mar-2010 02:19
Many people in SEO need to supply an array and shuffle the results and need the same result each time that page is generated. This is my implementation with a working example:

<?php
function seoShuffle(&$items,$string) {
    mt_srand(strlen($string));
    for ($i = count($items) - 1; $i > 0; $i--){
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}

$items = array('one','two','three','four','five','six');
$string = 'whatever';

echo '<pre>';
print_r($items);
echo '</pre>';

seoShuffle($items,$string);

echo '<pre>';
print_r($items);
echo '</pre>';
?>
tyler at CompLangs dot com 01-Jan-2010 06:59
Here is a quick function I wrote that generates a random password and uses shuffle() to easily shuffle the order.

<?php
public function randPass($upper = 3, $lower = 3, $numeric = 3, $other = 2) {
    //we need these vars to create a password string
    $passOrder = Array();
    $passWord = '';

    //generate the contents of the password
    for ($i = 0; $i < $upper; $i++) {
        $passOrder[] = chr(rand(65, 90));
    }
    for ($i = 0; $i < $lower; $i++) {
        $passOrder[] = chr(rand(97, 122));
    }
    for ($i = 0; $i < $numeric; $i++) {
        $passOrder[] = chr(rand(48, 57));
    }
    for ($i = 0; $i < $other; $i++) {
        $passOrder[] = chr(rand(33, 47));
    }

    //randomize the order of characters
    shuffle($passOrder);

    //concatenate into a string
    foreach ($passOrder as $char) {
        $passWord .= $char;
    }

    //we're done
    return $passWord;
}
?>
ahmad at ahmadnassri dot com 18-Nov-2009 08:58
shuffle for associative arrays, preserves key=>value pairs.
(Based on (Vladimir Kornea of typetango.com)'s function)

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }
?>

*note: as of PHP 5.2.10, array_rand's resulting array of keys is no longer shuffled, so we use array_keys + shuffle.
Anonymous 28-Aug-2009 09:18
I needed a simple function two shuffle a two dimensional array. Please note the second level arrays must be indexed using integers, for example $myarray[0]["Name"] and not $myarray["One"]["Name"]. Here is the function:

<?php
function twodshuffle($array)
{
    // Get array length
    $count = count($array);
    // Create a range of indicies
    $indi = range(0,$count-1);
    // Randomize indicies array
    shuffle($indi);
    // Initialize new array
    $newarray = array($count);
    // Holds current index
    $i = 0;
    // Shuffle multidimensional array
    foreach ($indi as $index)
    {
        $newarray[$i] = $array[$index];
        $i++;
    }
    return $newarray;
}
?>

Please note it only works on two dimensional arrays. Here is an example:

<?php
$myarray = array("Google" => array("Name" => "Google", "URL" => "www.google.com", "Usage" => "Googling"), "Yahoo" => array("Name" => "Yahoo", "URL" => "www.yahoo.com", "Usage" => "Yahooing?"), "Ask" => array("Name" => "Ask", "URL" => "www.ask.com", "Usage" => "Asking Jeeves"));

print_r(twodshuffle($myarray));

/* And the result is:
Array ( [0] => Array ( [Name] => Ask [URL] => www.ask.com [Usage] => Asking Jeeves ) [1] => Array ( [Name] => Google [URL] => www.google.com [Usage] => Googling ) [2] => Array ( [Name] => Yahoo [URL] => www.yahoo.com [Usage] => Yahooing? ) )
*/
?>

Hope you find it useful!
John Galt 21-Jul-2009 09:08
I wrote these functions just for the heck of it, but I managed to get them to work even though I'm a PHP amateur. They're just two functions for a deck of 52 cards. newDeck() creates a deck and deal() creates hands for the deck.

<?php
 // Two basic playing card functions
 // newDeck([$numJokers]) - returns array of 52 cards plus (if supplied) $numJokers jokers
 // deal($deck[, $numHands[, $numCards]]) - returns two compact()ed variables--the new $deck and $hand arrays

 function newDeck($numJokers = 0)
 {
  // Returns $deck: array of 52 standard deck of 4-suit cards plus $numJokers jokers, shuffled (key starts at zero)
  // in format of e.g. $deck[4] = "A &spades;" = ace of spades (fifth card)
  $suitCards = array("J", "Q", "K", "A");
  $suitCards = array_merge($suitCards, range(2, 10));
  $hearts = array();
  $spades = array();
  $diamonds = array();
  $clubs = array();
  foreach($suitCards as $card)
  {
   $hearts[] = "<span style=\"color: #FF0000;\">" . $card . " &hearts;" . "</span>";
   $spades[] = "<span style=\"color: #000000;\">" . $card . " &spades;" . "</span>";
   $diamonds[] = "<span style=\"color: #FF0000;\">" . $card . " &diams;" . "</span>";
   $clubs[] = "<span style=\"color: #000000;\">" . $card . " &clubs;" . "</span>";
  }
  $jokers = array();
  for($i = 0; $i < $numJokers; $i++)
   $jokers[] = "<span style=\"color: #8467D7;\">JOKER</span>";
  $deck = array_merge($hearts, $spades, $clubs, $diamonds, $jokers);
  shuffle($deck);
  return $deck;
 }

 function deal($deck, $numHands = 1, $numCards = 7)
 {
  // Returns $hand: two-dimensional array, first key being player ID and second being card number (both starting from zero)
  // e.g. $hand[2][4] = "6 &hearts;" = six of hearts (third hand, fifth card)
  // To return, use extract, e.g. extract(deal($deck, 2, 13)); (also returns $deck)
  $hand = array();
  for($i = 0; $i < $numHands; $i++)
  {
   for($j = 0; $j < $numCards; $j++)
   {
    $hand[$i][$j] = next($deck);
    if($i == 0 && $j == 0)
     $hand[0][0] = prev($deck);
   }
  }
  $deck = array_splice($deck, ($numHands * $numCards));
  return compact("hand", "deck");
 }

 $deck = newDeck();
 extract(deal($deck, 3, 7));

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <!-- Just an example of test output to demonstrate capability. -->
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Basic Playing Card Functions</title>
 </head>

 <body>
  <h1>Deck</h1>
  <pre>
<?php
 print_r($deck);
?>
  </pre>
  <hr />
  <h1>Hands</h1>
  <pre>
<?php
 print_r($hand);
?>
  </pre>
 </body>
</html>
mateusz dot charytoniuk at gmail dot com 20-Jun-2009 12:19
If you want to keep array shuffled in one particular way for every user visiting your site, you can use:

<?php
srand($user['id']);
shuffle($some_array);
?>
aalaap at gmail dot com 08-Jun-2009 05:12
I've been wondering why shuffle() doesn't provide the shuffled array as a return value instead of a bool. I mean, what could possibly go wrong in shuffling elements from an array?

So I use something like this:

<?php
function array_shuffle($array) {
    if (shuffle($array)) {
        return $array;
    } else {
        return FALSE;
    }
}
?>
sivaji2009 at gmail dot com 17-May-2009 02:07
Here i wrote a custom shuffle function which preserves the array index and distributes the array element randomly.

<?php

/*
 * return an array whose elements are shuffled in random order.
 */
function custom_shuffle($my_array = array()) {
  $copy = array();
  while (count($my_array)) {
    // takes a rand array elements by its key
    $element = array_rand($my_array);
    // assign the array and its value to an another array
    $copy[$element] = $my_array[$element];
    //delete the element from source array
    unset($my_array[$element]);
  }
  return $copy;
}

$array = array(
  'a' => 'apple',
  'b' => 'ball',
  'c' => 'cat',
  'd' => 'dog',
  'e' => 'egg',
  'f' => 'fan',
  'g' => 'gun'
);

print_r(custom_shuffle($array));

Array
(
    [c] => cat
    [e] => egg
    [f] => fan
    [a] => apple
    [b] => ball
    [g] => gun
    [d] => dog
)

?>
dirk dot avery a t gmail 30-Apr-2009 08:58
Building on examples by m227 and pineappleclock, here is a function that returns all permutations of each set in the power set of an array of strings (instead of a string).  Thanks for the great examples!

<?php

/*
 Use: $arr = power_perms($in);

 Example:
  $in = array("A","B","C");
  $power_perms = power_perms($in);

 Returns:
  Array
  (
    [0] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

    [1] => Array
        (
            [0] => A
            [1] => C
            [2] => B
        )

    [2] => Array
        (
            [0] => B
            [1] => A
            [2] => C
        )

    [3] => Array
        (
            [0] => B
            [1] => C
            [2] => A
        )

    [4] => Array
        (
            [0] => C
            [1] => A
            [2] => B
        )

    [5] => Array
        (
            [0] => C
            [1] => B
            [2] => A
        )

    [6] => Array
        (
            [0] => A
            [1] => B
        )

    [7] => Array
        (
            [0] => B
            [1] => A
        )

    [8] => Array
        (
            [0] => B
            [1] => C
        )

    [9] => Array
        (
            [0] => C
            [1] => B
        )

    [10] => Array
        (
            [0] => A
            [1] => C
        )

    [11] => Array
        (
            [0] => C
            [1] => A
        )

    [12] => Array
        (
            [0] => A
        )

    [13] => Array
        (
            [0] => B
        )

    [14] => Array
        (
            [0] => C
        )

  )

*/

function power_perms($arr) {

    $power_set = power_set($arr);
    $result = array();
    foreach($power_set as $set) {
        $perms = perms($set);
        $result = array_merge($result,$perms);
    }
    return $result;
}

function power_set($in,$minLength = 1) {

   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }

   //usort($return,"cmp");  //can sort here by length
   return $return;
}

function factorial($int){
   if($int < 2) {
       return 1;
   }

   for($f = 2; $int-1 > 1; $f *= $int--);

   return $f;
}

function perm($arr, $nth = null) {

    if ($nth === null) {
        return perms($arr);
    }

    $result = array();
    $length = count($arr);

    while ($length--) {
        $f = factorial($length);
        $p = floor($nth / $f);
        $result[] = $arr[$p];
        array_delete_by_key($arr, $p);
        $nth -= $p * $f;
    }

    $result = array_merge($result,$arr);
    return $result;
}

function perms($arr) {
    $p = array();
    for ($i=0; $i < factorial(count($arr)); $i++) {
        $p[] = perm($arr, $i);
    }
    return $p;
}

function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {

    unset($array[$delete_key]);

    if(!$use_old_keys) {
        $array = array_values($array);
    }

    return TRUE;
}
?>
john 18-Feb-2009 09:21
To shuffle keeping the keys intact, I've used the following:

<?PHP

$shuff=array("a","b","c","d","e","f","g",
                   "h","i","j","k","l");
uasort( $shuff, 'scmp' );
print_r($shuff);

function scmp( $a, $b ) {
     return rand(-1,1);
}

?>

Example output:
Array
(
    [7] => h
    [6] => g
    [2] => c
    [0] => a
    [5] => f
    [4] => e
    [10] => k
    [3] => d
    [8] => i
    [11] => l
    [1] => b
    [9] => j
)

Array
(
    [6] => g
    [0] => a
    [2] => c
    [10] => k
    [8] => i
    [5] => f
    [1] => b
    [4] => e
    [9] => j
    [3] => d
    [7] => h
    [11] => l
)

Works for me...
pineappleclock at gmail dot com 22-Jan-2009 10:06
If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm:

<?php
/**
* Returns the power set of a one dimensional array,
* a 2-D array.
* array(a,b,c) ->
* array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c))
*/
function powerSet($in,$minLength = 1) {
   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }
   return $return;
}
?>
csaba at alum dot mit dot edu 03-Jan-2009 08:01
The following function, NKnext(), generates combinations sequentially.  NKnext's output is a string of 0s and 1s where a "1" at position k represents the kth item being selected.  For example, "1001000" represents the 0th and 3rd items being chosen from among 7.  Feed NKnext() such a string to generate the next one in the sequence.  Note that the sequence is a Gray Code where all adjacent element pairs (including the first and last) differ by a minimal amount (ie. a 0-1 swap), so that one could easily make it circular (Hamiltonian).

<?php
$n = 7;
$k = 3;
enumNK ($n, $k);            // show all possibilities

function enumNK ($n, $k) {
  // Iteratively generate all strings of $k "1"s and $n-$k "0"s
  // so that adjacent strings have exactly one 0-1 swap.
  // Final string is a BRR of the original (right barrel rotation)
  print                     // print the initial string
    $str = str_repeat("1", $k) . str_repeat("0", $n-$k);
  while ($str= NKnext($str)) print "<br> $str"; }

function swap ($str, $pos1, $pos2) {
  // Return $str with characters at $pos1 and $pos2 swapped
  $chr = $str[$pos1];
  $str[$pos1] = $str[$pos2];
  $str[$pos2] = $chr;
  return $str; }

function mod($num, $base) {    // Mathematician's modulus
  // compare with http://php.net/fmod
  return ($num - $base*floor($num/$base)); }

function NKnext ($str, $pos=0, $dir=1) {
  // Assumes there were initially $k=substr_count($str, "1") contiguous 1s
  //   starting at ($dir==1=>leftmost; $dir==1=>rightmost) position $pos
  //   to be barrel rotated in the direction $dir (1=>right, -1=>left)
  //   while going through all possibilities of [$n=strlen($str), $k]
  // Returns the resultant next string in the iteration
  //   by finding the position of the next swap ($pos and $pos2)
  NKswap ($str, $pos, $dir, substr_count ($str, "1"), strlen($str), $pos2);
  if ($pos==$pos2) return ""; return swap($str, $pos, $pos2); }

function NKswap ($str, &$pos, $dir, $k, $n, &$pos2) {
  // Under the assumptions for NKnext, returns the two
  //   positions ($pos, $pos2) that are to be swapped.
  // $pos2 is set to $pos if $str is final (ie. no more swaps)
  if (!$k || $k==$n) return $pos2 = $pos;          // all 0s or all 1s

  $ch1 = ($str[$pos]!="0");      // Is char of interest (fixed char) a "1"?
  $sub = substr($str, 0, $pos) . substr($str, $pos + 1);  // Rest of string

  // Position of next char of interest
  $np = mod($pos - ($dir==1) + $ch1 * $dir * ($k-1), $n-1);

  NKswap($sub, $np, $ch1 ? -$dir : $dir, $k---$ch1, $n-1, $pos2);
  if ($np==$pos2)                 // If substring is done
    return ($pos2 = mod($pos + $ch1 * $dir * ($k - !$k), $n));

  if ($pos2>=$pos) ++$pos2;     // Adjustment for 'char of interest' posn
  $pos = $np + ($np>=$pos); }   // Return the "normal" swap position
?>

BR = Barrel rotation
BRR/BRL = Barrel rotation to the right/left by 1

The basic algorithm is recursive, with a fixed "1" position identified ($pos=0, below), all sub-possibilities are iterated, then it is replaced with a 0, and then all those sub-possibilities are iterated.
[5, 3] example with leftmost 1 fixed: 11100 -> 10101 -> 10110 -> 11010 -> 10011 -> 11001
[5, 3] continued with leftmost char swap: 11001 -> 01101
[5, 3] continued with leftmost 0 fixed: 01101 -> 00111 -> 01011 -> 01110

When $dir is 1 in the above functions, it represents a net BRR, and $pos represents the starting position of the leftmost 1.
When $dir is -1 in the above functions, it represents a net BRL, and $pos represents the starting position of the rightmost 1.
$pos is essentially used to determine when all the swaps are done.  For example, in rotating 1110 (with $dir=1 and $pos=0) we go through the following: 1101 (and not 0111!), 1011, 0111

Happy New Year,
Csaba Gabor from Vienna
tony at brokerbin dot com 11-Nov-2008 07:26
Here is IMO the simplest and extremely fast way to shuffle an associative array AND keep the key=>value relationship.  However, it ONLY works if there are NO NUMERIC keys AT ALL.  Look into array_merge for the reason why.

<?php

$unshuffled = array('one'=>1,'two'=>2,'three'=>3);

$shuffled = array_merge( array_flip(array_rand($unshuffled,count($unshuffled))),$unshuffled );

?>

peace
Antonio Ognio 06-May-2008 09:42
Another shuffle() implementation that preserves keys, does not use extra memory and perhaps is a bit easier to grasp.

<?php
if (function_exists('shuffle_with_keys')===false) {
  function shuffle_with_keys(&$array) {
    /* Auxiliary array to hold the new order */
    $aux = array();
    /* We work with an array of the keys */
    $keys = array_keys($array);
    /* We shuffle the keys */
    shuffle($keys);
    /* We iterate thru' the new order of the keys */
    foreach($keys as $key) {
      /* We insert the key, value pair in its new order */
      $aux[$key] = $array[$key];
      /* We remove the element from the old array to save memory */
      unset($array[$key]);
    }
    /* The auxiliary array with the new order overwrites the old variable */
    $array = $aux;
  }
}
?>
rich at home dot nl 23-Jan-2008 09:17
Function that does the same as shuffle(), but preserves key=>values.
(Based on (Vladimir Kornea of typetango.com)'s function)

<?php
  function shuffle_assoc(&$array) {
    if (count($array)>1) { //$keys needs to be an array, no need to shuffle 1 item anyway
      $keys = array_rand($array, count($array));

      foreach($keys as $key)
        $new[$key] = $array[$key];

      $array = $new;
    }
    return true; //because it's a wannabe shuffle(), which returns true
  }

  $test = array(1=>'one','two'=>'2',3=>'3');
  print_r($test);
  shuffle_assoc($test);
  print_r($test);

?>

Array
(
    [1] => one
    [two] => 2
    [3] => 3
)
Array
(
    [two] => 2
    [1] => one
    [3] => 3
)
carrox at mail dot ru 23-Dec-2007 02:15
Very fast way to shuffle associative array and keep key=>value

<?php

  $tmp=array("one"=>1,"two"=>2,"three"=>3,"four"=>4);
  $new=array();
  $c=count($tmp);

  $k=array_keys($tmp);
  $v=array_values($tmp);

   while($c>0) {
     $i=array_rand($k);
     $new[$k[$i]]=$v[$i];
     unset($k[$i]); #exlude selected number from list
     $c--;
   }

   print_r($tmp);
   print_r($new);

?>

Result:

Array
(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
)
Array
(
    [two] => 2
    [three] => 3
    [four] => 4
    [one] => 1
)

And thats all, folks!
downforme at gmx dot at 06-Nov-2007 10:08
my approach to bring some chaos to associative arrays
<?php
define ("SHUFFLEBOTH", 0);
define ("SHUFFLEVALUES", 1);
define ("SHUFFLEKEYS", 2);
function shuffle_assoc(&$array, $mode=SHUFFLEBOTH) {
    $keys = array_keys($array);
    $values = array_values($array);
    if (($mode==SHUFFLEBOTH) || ($mode==SHUFFLEVALUES)) shuffle($values);
    if (($mode==SHUFFLEBOTH) || ($mode==SHUFFLEKEYS)) shuffle($keys);
    $array = array_combine($keys, $values);
}
?>
hauser dot j at gmail dot com 14-Feb-2007 02:19
Permutation using recursion

<?php
function perm($n)
{
    if($n <= 1) return 1;
    else return $n * perm($n-1);
}
?>

Usage example:
<?php $result = perm(8); ?>

$result will be 40320
m227 at tlen dot pl 13-Oct-2006 03:22
here come my three pennies about permutations. I did function below to work with word anagrams, it works flawlessly, however may be seen as a slow one.

<?php
/** (c) on LGPL license 2006.10 michal@glebowski.pl */
function fact($int){
   if($int<2)return 1;
   for($f=2;$int-1>1;$f*=$int--);
   return $f;
}

/** @return string string $s with $n-th character cut */
function del($s, $n) {
    return substr($s, 0, $n).substr($s, $n+1);
}
/**
 * @param $s string word to permute
 * @param $n int n-th permutation
 * @return string n-th permutation (out of strlen(string)!)
 */
function perm($s, $n = null) {

    if ($n === null) return perms($s);

    $r = '';
    $l = strlen($s);
    while ($l--) {
        $f = fact($l);
        $p = floor($n/$f);
        $r.= $s{$p};
        $s = del($s, $p);
        $n-= $p*$f;
    }
    $r.=$s;
    return $r;
}
/** @return array array of all permutations */
function perms($s) {
    $p = array();
    for ($i=0;$i<fact(strlen($s));$i++)    $p[] = perm($s, $i);
    return $p;
}
?>
07-Jun-2006 02:53
Posted below is code that you would expect to work

<?php

$keys = shuffle(array_keys($arr));

foreach ($keys as $key) {

  $arr_elem = $arr[$key];
  // do what you want with the array element

}

?>

This in fact does not work because shuffle returns a boolean true or false. More accurate code using this method would be:

<?php

$keys = array_keys($arr);
shuffle($keys);

foreach ($keys as $key) {

  $arr_elem = $arr[$key];
  // do what you want with the array element

}

?>
alejandro dot garza at itesm dot mx 10-Mar-2006 08:47
This is taken from an O'Reilly Book and modified slightly to return all possible permutations of a 1D array:

<?php

# Modified from http://linuxalpha1.eicn.ch/OReilly_books/books/webprog/pcook/ch04_26.htm
# Takes a non-associatuve 1D (vector) array of items
#  and returns an array of arrays with each possible permutation
function array_2D_permute($items, $perms = array( )) {
static $permuted_array;
    if (empty($items)) {
        $permuted_array[]=$perms;
        #print_r($new);
      #print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             array_2D_permute($newitems, $newperms);
         }
         return $permuted_array;
    }
}

$arr=array("Architecture","Mexico","Periodicals","Test");
$result=array_2D_permute($arr);
print_r($result);
?>
bill at SWScripts dot com 22-Sep-2005 09:45
Just a quick note to let people know that shuffle() will work on multidimensional associative arrays provided that the first key is already numeric.

So this array can be shuffled without losing any of the secondary keys or their values:

$array[0]['color'], $array[0]['size'], $array[0]['fabric']
. . .
$array[50]['color'], $array[50]['size'], $array[50]['fabric']

I recently ran up against needing to randomize this array and tried shuffle even though it's not really for associative arrays.

Hope it helps somebody out there.
Markus of CodeWallah.Com 30-Aug-2005 10:55
Here's a pretty little function to shuffle an associative array, taking a bit different approach from the earlier entries.

<?PHP
function ass_array_shuffle ($array) {
    while (count($array) > 0) {
        $val = array_rand($array);
        $new_arr[$val] = $array[$val];
        unset($array[$val]);
    }
    return $new_arr;
}
?>

In the function above, the original array is randomly scavenged upon until nothing is left of it. This removes the need for any temporary variables, or indeed for any superfluous tossing around of stuff.
skissane at iips dot mq dot edu dot au 06-Jun-2005 03:11
note that in PHP 5.0.4 (and assumably earlier versions as well), shuffle internally calls rand(), not mt_rand().

This was important because I was trying to use a fixed seed to get repeatable results, by calling mt_srand(). But of course that doesn't work, since shuffle uses rand() not mt_rand(). The solution is either to use srand() for seeding, or to write your own version of shuffle() using mt_rand(). (See examples which others have contributed; or, just have a look at ext/standard/array.c) mt_rand on many platforms gives better results than the builtin library anyway...

N.B. Obviously, the way the shuffle function is implemented may change without notice in future versions, including e.g. changing to use mt_rand instead.
monte at ohrt dot com 21-Mar-2005 02:10
[EDIT by danbrown AT php DOT net: As pointed out on 25 July, 2008, by "Anonymous", this implementation may have some errors or inconsistencies that may cause this function not to achieve the desired result.  "Anonymous" provided the following link for more information: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle]

This is an attempt to get the Fisher Yates shuffle right, and as optimized as possible. The array items are stepped through from last to first, each being swapped with another between itself and the beginning of the array (N-1 shuffles required.) Using list() to swap array vars instead of a tmp var proved to be slightly slower. Testing for $i = $j decreases performance as the array size increases, so it was left out (elements are always swapped.)

<?php
function fisherYatesShuffle(&$items)
{
   for ($i = count($items) - 1; $i > 0; $i--)
   {
      $j = @mt_rand(0, $i);
      $tmp = $items[$i];
      $items[$i] = $items[$j];
      $items[$j] = $tmp;
   }
}
?>
Bjorn AT smokingmedia DOT com 23-Sep-2004 05:02
To shuffle an associated array and remain the association between keys and values, use this function:

<?php

$test_array = array("first" => 1,"second" => 2,"third" => 3,"fourth" => 4);

function shuffle_assoc($input_array){

   foreach($input_array as $key => $value){
      $temp_array[$value][key] = $key;
      }

   shuffle($input_array);

   foreach($input_array as $key => $value){
      $return_array[$temp_array[$value][key]] = $value;
      }

   return $return_array;
   }

echo "<pre>";
print_r(shuffle_assoc($test_array));
echo "</pre><hr />";

// this will output something like this:
/*
Array
(
    [fourth] => 4
    [second] => 2
    [third] => 3
    [first] => 1
)

*/
?>
Justin Knoll 15-Apr-2004 05:24
This code is very appealing in its simplicity and speed, but it's not a random shuffle:

<?php
function randomcmp($a, $b)
{
  return mt_rand(-1, 1);
}

function swapshuffle(&$array)
{
  srand((double) microtime() * 10000000);
  uksort($array, "randomcmp");
}
?>

This is because uksort calls the C function zend_qsort and this quicksorts the array using the provided comparision function. The pairs of indices selected are biased by the nature of the quicksort algorithm.

One effect is that an element in the middle of the array is heavily biased toward being "shuffled" to the middle. Elements on the edges are biased towards the edges; they're likely to switch edges, but unlikely to end up in the middle.
injunjoel 11-Mar-2004 07:27
Be aware that when shuffling an associative array your associative keys will be lost! example below:
<?php
echo "before shuffle\n";
$numbers = array('first'=>1,'second'=>2,'third'=>3,'fourth'=>4);
foreach($numbers as $key=>$value){
    echo "$key => $value\n";
}
echo "\nafter shuffle\n";
srand((float)microtime() * 1000000);
shuffle($numbers);

foreach($numbers as $key=>$value){
    echo "$key => $value\n";
}

?>
--output--
before shuffle
first => 1
second => 2
third => 3
fourth => 4

after shuffle
0 => 4
1 => 1
2 => 3
3 => 2
rsort
sizeof
Функции для работы с массивами


Псевдоним count

shuffle
sort
Функции для работы с массивами
PHP Manual

sizeof

(PHP 4, PHP 5)

sizeof — Псевдоним count()

Описание

Эта функция является псевдонимом: count().

User Contributed Notes

Emil Mohamed 22-Dec-2008 01:04
Here are real test for below statements:
Source:
<?php
$arr = array();
$num = 1000000;
echo "Populating test array with $num elements ... ";
for($i=0; $i<$num; $i++) {
    $arr[$i] = microtime(true) . mt_rand();
}
echo "Populated.\n\n";

echo "Start testing FOREAH ... \n";
$start_time = microtime(true);
foreach ($arr as $i=>$elem) {
    $res = isset($arr[$i]);
}
echo "FOREACH result: " . (microtime(true) - $start_time) . "\n\n";

echo "Start testing regular FOR ... \n";
$start_time = microtime(true);
for ($i=0; $i<sizeof($arr); $i++) {
    $res = isset($arr[$i]);
}
echo "Regular for result: " . (microtime(true) - $start_time) . "\n\n";

echo "Starting test for pre-computed size array FOR ... \n";
$start_time = microtime(true);
$sizeof_arr = sizeof($arr);
for ($i=0; $i<$sizeof_arr; $i++) {
    $res = isset($arr[$i]);
}
echo "pre-computed size of array FOR: " . (microtime(true) - $start_time);
?>

Output:
emil@neon:~$ php test-loops-performance.php
Populating test array with 1000000 elements ... Populated.

Start testing FOREAH ...
FOREACH result: 0.500122070312

Start testing regular FOR ...
Regular for result: 0.886044979095

Starting test for pre-computed size array FOR ...
pre-computed size of array FOR: 0.454435825348
umopdn [at] msn [dawt] com 23-Sep-2008 02:38
a) Always try and use PHP's internal routines to iterate through objects of various types (arrays in most examples below).

Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.

(This is why foreach () will run faster than manual interation)

b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.

c) I agree with PixEye's remarks on sizeof().  In PHP it is just an alias for the true function count().  It has other meanings logically in other languages rather than the number of elements in an object.  This should be avoided as it may confuse developers transitioning to PHP from other languages.
PixEye 23-Sep-2008 09:09
I am quite surprised about previous posts. Here are my advices:

1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).

2/ prefer the powerful forEach() function to iterate over arrays.
kaisellgren at gmail dot com 07-Sep-2008 08:54
In addition to previous posts, there is a better and cleaner way to loop through an array using this function.

<?php

for ($a = 0,$b = sizeof($array);$a < $b;$a++)
 echo $array[$a];

?>
rrf5000 at psu dot edu 17-Apr-2008 07:54
To explain previous comments:  the reason that the FOR loop runs faster on LARGE arrays if you set its size to an array first (using count() or sizeof() ) is pretty simple.  It's because if you use

<?php
for ($i = 0; $i < sizeof($huge_array); $i++)
{
  code
}
?>

every time the FOR loop checks its condition (is $i less than sizeof($huge_array) ), it must run the sizeof() function on $huge_array again.  This is what causes the extra processing time, which can become significant on larger arrays.

As a side note, this has been thoroughly commented on both correctly and incorrectly in the User Contributed Notes for the count() function.  Users Jaik, Wulfson, and Anonymous have summed this particular matter up pretty well in their posts http://www.php.net/manual/en/function.count.php#78741 , http://www.php.net/manual/en/function.count.php#78931 , and http://www.php.net/manual/en/function.count.php#79238 .
Andreas dot Schuhmacher87 at googlemail dot com 13-Apr-2008 11:02
also you can use for like this (no count() needed)
<?php
    for($i = 0, $item = ''; false != ($item = $some_array[$i]); $i++) {
        print $item; //index $i of $some_array
        //code
    }
?>
communiti.ch 10-Apr-2008 06:55
If your array is "huge"

It is reccomended to set a variable first for this case:

THIS->

$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}

IS QUICKER THEN->

for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}
svanegmond at tinyplanet dot ca 13-Mar-2008 11:12
For people who use this kind of idiom:

for ($i=0; $i<sizeof($array); $i++) {
   ...
}

At least in PHP4, you will notice a large performance improvement if you switch to:

$max = sizeof($array);
for ($i=0; $i<$max; $i++) {
   ...
}

I had an array with a few thousand items in it, each of them a map with 5 key-value pairs, and just for'ing through the array took a second of CPU on a decent machine.
shuffle
sort
Функции для работы с массивами


Сортирует массив

sizeof
uasort
Функции для работы с массивами
PHP Manual

sort

(PHP 4, PHP 5)

sort — Сортирует массив

Описание

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Эта функция сортирует массив. После завершения работы функции элементы массива будут расположены в порядке возрастания.

Список параметров

array

Входной массив.

sort_flags

Дополнительный второй параметр sort_flags можно использовать для изменения поведения сортировки, используя следующие значения:

Флаги сортировки:

  • SORT_REGULAR - обычное сравнение элементов (без изменения типов)
  • SORT_NUMERIC - числовое сравнение элементов
  • SORT_STRING - строковое сравнение элементов
  • SORT_LOCALE_STRING - строковое сравнение элементов в зависимости от текущей локали. strings, based on the current locale. Добавлено в версиях PHP 4.4.0 и 5.0.2, используется локаль, которая может быть изменена с помощью функции setlocale().
  • SORT_NATURAL - сравнение элементов как строк, используя естественное упорядочение, аналогичное упорядочению в функции natsort(). Добавлено в PHP 5.4.0.
  • SORT_FLAG_CASE - может быть объединен (побитовое ИЛИ) с константами SORT_STRING или SORT_NATURAL для сортировки строк без учета регистра. Добавлено в PHP 5.4.0.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования sort()

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Результат выполнения данного примера:

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

Фрукты отсортированы в алфавитном порядке.

Пример #2 Пример использования sort() с регистронезависимым естественным упорядочением

<?php

$fruits = array(
    "Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Результат выполнения данного примера:

fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

The fruits have been sorted like natcasesort().

Примечания

Замечание: Эта функция присваивает новые ключи элементам массива. Она удалит все существующие ключи, а не просто переупорядочит их.

Замечание: Как и большинство функций сортировки в PHP, sort() использует реализацию алгоритма » быстрой сортировки.

Внимание

Будьте осторожны при сортировке массивов, содержащих элементы разных типов, так как в этом случае результат работы функции sort() может быть непредсказуемым.

Смотрите также

  • asort() - Сортирует массив, сохраняя ключи
  • Сравнение функций сортировки массивов

User Contributed Notes

holdoffhunger at gmail dot com 02-Jan-2012 05:02
I wanted a function that would efficiently let me sort a string array by the length of each entry.  Below is a neat trick in logic that allows me to manipulate the sort function.  (1) Get the length of the string, (2) Str_pad the length with 0's, so that it is a definite length, (3) Append that number to the beginning of the string, (4) Then do rsort or sort normally.  Below is an rsort implementation...

<?php

    // Released Under Affero General Public License, Version 3 (AGPL3)
    // Author: holdoffhunger@gmail.com

    $array_of_data = array(        "hello",
                    "php",
                    "is",
                    "awesome",
                    "1",
                    "1234",
                    "12",
                    "9");

    print("<pre>");
    print_r($array_of_data);

    /*  Output Here Is:
            Array
        (
            [0] => hello
            [1] => php
            [2] => is
            [3] => awesome
            [4] => 1
            [5] => 1234
            [6] => 12
            [7] => 9
        )
    */

    $number_of_entries = count($array_of_data);

    for($i = 0; $i < $number_of_entries; $i++)
    {
        $current_entry = $array_of_data[$i];
        $current_entry_length = strlen($current_entry);
        $appendable_entry_length = str_pad($current_entry_length, 10, "0", STR_PAD_LEFT);
        $array_of_data[$i] = $appendable_entry_length . " /|\/|\/|\ " . $array_of_data[$i];
    }

    rsort($array_of_data);

    for($i = 0; $i < $number_of_entries; $i++)
    {
        $current_entry = $array_of_data[$i];
        $current_entry_explosion = explode(" /|\/|\/|\ ", $current_entry);
        $array_of_data[$i] = $current_entry_explosion[1];
    }

    print_r($array_of_data);
    print("</pre>");

    /*  Sorted Output Here Is:
        Array
        (
            [0] => awesome
            [1] => hello
            [2] => 1234
            [3] => php
            [4] => is
            [5] => 12
            [6] => 9
            [7] => 1
        )
    */

?>
Walter Tross 16-Dec-2011 02:38
unless you specify the second argument, "regular" comparisons will be used. I quote from the page on comparison operators:
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically."
What this means is that "10" < "1a", and "1a" < "2", but "10" > "2". In other words, regular PHP string comparisons are not transitive.
This implies that the output of sort() can in rare cases depend on the order of the input array:
<?php
function echo_sorted($a)
{
   echo "{$a[0]} {$a[1]} {$a[2]}";
   sort($a);
   echo " => {$a[0]} {$a[1]} {$a[2]}\n";
}
// on PHP 5.2.6:
echo_sorted(array( "10", "1a", "2")); // => 10 1a 2
echo_sorted(array( "10", "2", "1a")); // => 1a 2 10
echo_sorted(array( "1a", "10", "2")); // => 2 10 1a
echo_sorted(array( "1a", "2", "10")); // => 1a 2 10
echo_sorted(array( "2", "10", "1a")); // => 2 10 1a
echo_sorted(array( "2", "1a", "10")); // => 10 1a 2
?>
ajanata at gmail dot com 20-Oct-2011 09:13
This took me longer than it should have to figure out, but if you want the behavior of sort($array, SORT_STRING) (that is, re-indexing the array unlike natcasesort) in a case-insensitive manner, it is a simple matter of doing usort($array, strcasecmp).
holdoffhunger at gmail dot com 18-Jul-2011 09:14
I have discovered an interesting trick with the sort function.  Many coders are using it to sort options for a user, because a computer will only need sorted data in limited cases.  However, every coder wants their sorted data to be usable.  It's very common to find any sorted data online, and to find options, "Sort by Date," "Sort Alphabetically," etc., etc., whether you're looking at an online catalogue or some bulletin board.

The trick is to use a combination of html commenting and str_pad's to do definitive "sort by" functions.  Let me demonstrate with an example: consider two arrays, Sorted_By_Date and Sorted_By_Name.  You want every element to be "<option value=something>Option Name</option", so that you can do a simple foreach statement that prints every option value.  But, sorting these arrays will technically sort just sort whatever you put into "value".  So, here's a neat trick.  Make every entry "<!-- Sort_Value --><option value=something>Option Name</option."  That way, when you sort, it'll have to sort technically by whatever is the Sort_Value.

The greatness of this trick is that you can make as many "sort this data by X" fields as you want!  Just create multiple arrays, each with the same option values and names, but with a different value put in "Sort_Value", which could be a date, a name, a price, etc..  With numbers, you may need to use the str_pad function, to push all of the zeros out to the left, for a proper sort.  For instance, in my code, that looks like...

<?php

                $number_of_versions_sort_value = str_pad($number_of_versions, 20, "0", STR_PAD_LEFT);

?>
alex dot hristov dot 88 at gmail dot com 16-Jun-2011 07:26
As some people have mentioned before sorting a multidimentional array can be a bit tricky. it took me quite a while to get it going but it works as a charm:

<?php
//$order has to be either asc or desc
 function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
        if(is_array($array) && count($array)>0) {
            foreach(array_keys($array) as $key)
            $temp[$key]=$array[$key][$index];
            if(!$natsort) {
                if ($order=='asc')
                    asort($temp);
                else
                    arsort($temp);
            }
            else
            {
                if ($case_sensitive===true)
                    natsort($temp);
                else
                    natcasesort($temp);
            if($order!='asc')
                $temp=array_reverse($temp,TRUE);
            }
            foreach(array_keys($temp) as $key)
                if (is_numeric($key))
                    $sorted[]=$array[$key];
                else
                    $sorted[$key]=$array[$key];
            return $sorted;
        }
    return $sorted;
}
?>
markrose at markrose dot ca 01-Jun-2011 11:54
I've yet to come across a fast way to merge sorted arrays by a user value. Merging the arrays and using PHP's usort isn't efficient, as it doesn't take advantage of the existing sorting. So I wrote my own merge sorted arrays by user value function. The limit parameter can be used be used to limit the number of results (there is no point sorting more results than needed). This sort is stable: values will be taken preferentially from the first, then second, etc., array inside $merge_arrays.

Note that this function will fail if a user value is boolean false. It could be adapted to hold the best value inside an array at some performance penalty. It could also be adapted to comparing strings case-insensitively.

To give you some idea of the performance, my machine will sort out the first 1000 values of 10 sorted arrays of 1000 values each in under 40 ms, using an integer sort field. Not fast by C standards, but a vast improvement over usort'ing 10,000 values.

<?php
function merge_sorted_arrays_by_field ($merge_arrays, $sort_field, $sort_desc = false, $limit = 0)
{
    $array_count = count($merge_arrays);

    // fast special cases...
    switch ($array_count)
    {
        case 0: return array();
        case 1: return $limit ? array_slice(reset($merge_arrays), 0, $limit) : reset($merge_arrays);
    }

    if ($limit === 0)
        $limit = PHP_INT_MAX;

    // rekey merge_arrays array 0->N
    $merge_arrays = array_values($merge_arrays);

    $best_array = false;
    $best_value = false;

    $results = array();

    // move sort order logic outside the inner loop to speed things up
    if ($sort_desc)
    {
        for ($i = 0; $i < $limit; ++$i)
        {
            for ($j = 0; $j < $array_count; ++$j)
            {
                // if the array $merge_arrays[$j] is empty, skip to next
                if (false === ($current_value = current($merge_arrays[$j])))
                    continue;

                // if we don't have a value for this round, or if the current value is bigger...
                if ($best_value === false || $current_value[$sort_field] > $best_value[$sort_field])
                {
                    $best_array = $j;
                    $best_value = $current_value;
                }
            }

            // all arrays empty?
            if ($best_value === false)
                break;

            $results[] = $best_value;
            $best_value = false;
            next($merge_arrays[$best_array]);
        }
    }
    else
    {
        for ($i = 0; $i < $limit; ++$i)
        {
            for ($j = 0; $j < $array_count; ++$j)
            {
                if (false === ($current_value = current($merge_arrays[$j])))
                    continue;

                // if we don't have a value for this round, or if the current value is smaller...
                if ($best_value === false || $current_value[$sort_field] < $best_value[$sort_field])
                {
                    $best_array = $j;
                    $best_value = $current_value;
                }
            }

            // all arrays empty?
            if ($best_value === false)
                break;

            $results[] = $best_value;
            $best_value = false;
            next($merge_arrays[$best_array]);
        }
    }

    return $results;
}
?>
cmarshall at gmx dot de 17-May-2011 03:10
I read up on various problems re: sort() and German Umlaut chars and my head was soon spinning - bug in sort() or not, solution via locale or not, etc. ... (a total newbie here).

The obvious solution for me was quick and dirty: transform the Umlaut chars (present as HTML codes in my case) to their normal equivalent ('ä' = 'ae', 'ö' = 'oe', 'ü' = 'ue', 'ß' = 'ss' etc.), sort the array, then transform back. However there are cases in which a 'Mueller' is really that and does NOT need to be transformed into 'Müller' afterwards. Hence I for example replace the Umlaut itself with it's normal equivalent plus a char not used in the string otherwise (e.g. '_') so that the transfer back to Umlaut would only take place on certain combinations.

Of course any other char instead of '_' can be used as additional char (influencing the sort result). I know that my solution is rough at the edges and may cause other sort problems but it was sufficient for my purpose.

The array '$dat' in this example was filled with German town names (I actually worked with a multiple array ('$dat[][]') but stripped the code down to this as it's easier to understand):

<?php
// START Pre-sorting (Umlaut -> normal letters)
$max = count($dat);
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('&szlig;','ss_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Auml;','Ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&auml;','ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Ouml;','Oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&ouml;','oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Uuml;','Ue_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&uuml;','ue_',$dat[$totcnt]);
}
// END Pre-sorting (Umlaut -> normal letters)

// START Sorting //
function compare_towns($a, $b)
{
return strnatcmp($a, $b);
}
usort($dat, 'compare_towns');
// END Sorting //

// START Post-sorting (normal letters -> Umlaut)
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('ss_','&szlig;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ae_','&Auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ae_','&auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Oe_','&Ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('oe_','&ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ue_','&Uuml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ue_','&uuml;',$dat[$totcnt]);
}
// END Post-sorting (normal letters -> Umlaut)
?>
anaz114119 at gmail dot com 24-Dec-2010 02:34
sort from textfile by coloumn
example name||date||time||comments
if you want to sort by date
$column = 2
<?php
function array_sort($array,$column){
 $column = $column-1;
 foreach($array as $line){
 $bits = explode("||",$line);
 $bits ="$bits[$column]**$line";
 $array1[]=$bits;
}
 asort($array1);
 foreach($array1 as $line){
 $bit = explode("**",$line);
 $bit ="$bit[1]";
 $array2[]=$bit;
}
 return$array2;
}
?>
poulou_0 at hotmail dot com 21-Dec-2010 12:59
if you are not interested in high or low case sort

<?php
//where
$sortable_array[$k] = $v2;
//put
$sortable_array[$k] = strtolower($v2);

//and where
$sortable_array[$k] = $v;
//put
$sortable_array[$k] = strtolower($v);
?>
phpdotnet at m4tt dot co dot uk 16-Aug-2010 07:03
Simple function to sort an array by a specific key. Maintains index association.

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

/*
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
*/

?>
eriewave at hotmail dot com 29-Mar-2010 01:16
If you need to sort an array containing some equivalent values and you want the equivalents to end up next to each other in the overall order (similar to a MySQL's ORDER BY output), rather than breaking the function, do this:

<?php

sort($array, ksort($array))

?>

-When the sort() function finds two equivalents, it will sort them arbitrarily by their key #'s as a second parameter.

-Dirk
Dollar Hauler Admin 11-Mar-2010 10:10
I could never find a way to sort multidimensional arrays with 5+ keys while maintaining the data structure, but here it is:

(you can add an infinite number of keys, but it has to be added manually :\ )

<?php

$array[0]['name']  = 'Chris';
$array[0]['phone'] = '3971095';
$array[0]['year']  = '1978';
$array[0]['address'] = 'Street 1';

$array[1]['name']  = 'Breanne';
$array[1]['phone'] = '3766350';
$array[1]['year']  = '1990';
$array[1]['address'] = 'Street 2';

$array[2]['name']  = 'Dusty';
$array[2]['phone'] = '1541120';
$array[2]['year']  = '1982';
$array[2]['address'] = 'Street 3';

function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){
    // sort by ?
    foreach ($array as $pos =>  $val)
        $tmp_array[$pos] = $val[$sort_by];
    asort($tmp_array);

    // display however you want
    foreach ($tmp_array as $pos =>  $val){
        $return_array[$pos][$sort_by] = $array[$pos][$sort_by];
        $return_array[$pos][$key1] = $array[$pos][$key1];
        if (isset($key2)){
            $return_array[$pos][$key2] = $array[$pos][$key2];
            }
        if (isset($key3)){
            $return_array[$pos][$key3] = $array[$pos][$key3];
            }
        if (isset($key4)){
            $return_array[$pos][$key4] = $array[$pos][$key4];
            }
        if (isset($key5)){
            $return_array[$pos][$key5] = $array[$pos][$key5];
            }
        if (isset($key6)){
            $return_array[$pos][$key6] = $array[$pos][$key6];
            }
        }
    return $return_array;
    }

//usage (only enter the keys you want sorted):

$sorted = multisort($array,'year','name','phone','address');
print_r($sorted);

//output:
Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) )
Brecht Cloetens 23-Nov-2009 03:57
<?php

/**
 * function: array_columns
 * author: Brecht Cloetens
 * params: $a = array() // original array
 *         $c = int() // number of columns
 */
function array_columns(&$a, $c=2)
{
    $m = ceil(count($a)/$c);
    $j = 0;
    for($i=0; $i<$m; $i++) {
        for($k=0; $k<$c; $k++) {
            $key = $i+($m*$k);
            settype($key,'integer');
            if(array_key_exists($key,$a)) {
                $b[$j] = $a[$key];
                $j++;
            }
        }
    }
    $a = $b;
}

$arr = range('a','z');
array_columns($arr,4);
print_r($arr);

?>

Example:
array(1,2,3,4,5) will be converted to array(1,4,2,5,3);

This can be easy if you want to display an array into a specified number of columns.

<table>
    <tr>
        <td>$arr[0] => 1</td>
        <td>$arr[1] => 4</td>
    </tr>
    <tr>
        <td>$arr[2] => 2</td>
        <td>$arr[3] => 5</td>
    </tr>
    <tr>
        <td>$arr[4] => 3</td>
        <td></td>
    </tr>
</table>
Anonymous 17-Nov-2009 06:10
[EDIT BY danbrown AT php DOT net: The code provided by this anonymous author contains bugfixes for and additions to code originally donated by "toenie" on 07-NOV-09.  The original author included the following note: "If you want to sort while using an 2 dimensional array, you can use this script I just wrote for myself. I thought it could be helpful for other people too."]

I also added the ability to sort in ascending and descending order.

$order = "ASC" will sort the array in ascending order
$order = "DESC" will sort the array in descending order

Here is the code:

<?php
    function order_array_num ($array, $key, $order = "ASC")
    {
        $tmp = array();
        foreach($array as $akey => $array2)
        {
            $tmp[$akey] = $array2[$key];
        }

        if($order == "DESC")
        {arsort($tmp , SORT_NUMERIC );}
        else
        {asort($tmp , SORT_NUMERIC );}

        $tmp2 = array();
        foreach($tmp as $key => $value)
        {
            $tmp2[$key] = $array[$key];
        }

        return $tmp2;
    }
?>
petr dot biza at gmail dot com 11-Sep-2009 06:29
Here is a function to sort an array by the key of his sub-array with keep key in top level.

<?php
function sksort(&$array, $subkey="id", $sort_descending=false, $keep_keys_in_sub = false) {
    $temp_array = $array;

    foreach ($temp_array as $key => &$value) {

      $sort = array();
      foreach ($value as $index => $val) {
          $sort[$index] = $val[$subkey];
      }

      asort($sort);

      $keys = array_keys($sort);
      $newValue = array();
      foreach ($keys as $index) {
        if($keep_keys_in_sub)
            $newValue[$index] = $value[$index];
          else
            $newValue[] = $value[$index];
      }

      if($sort_descending)
        $value = array_reverse($newValue, $keep_keys_in_sub);
      else
        $value = $newValue;
    }

    $array = $temp_array;
  }
?>
phpnet at theindy dot net 27-Aug-2009 10:45
In response to the msort function I find that the array_multisort function is a lot faster.

-John
danm68 at gmail dot com 25-Aug-2009 09:59
sort() used with strings doesn't sort just alphabetically. It sorts all upper-case strings alphabetically first and then sorts lower-case strings alphabetically second.
Just in case anyone was as confused as I was and I've never seen this mentioned anywhere.
otobrglez at gmail dot com 18-Feb-2009 12:45
This will select number of unique keys from array and order them in original order.

<?php
/*
$rows - array of records
$st - number of keys that you want to have

By Oto Brglez.

*/

$pom_k = array();
for($i=0; $i<$st;){
    $pom = array_rand($rows,1);
    if(!in_array($pom,$pom_k)){
        $pom_k[] = $pom;
        $i++;
    };
};
sort($pom_k,SORT_NUMERIC);

?>
stepmuel at ee dot ethz dot ch 09-Dec-2008 08:14
A little shorter way to sort an array of objects; with a callback function.

<?php
function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}

function getIndex($obj) {
    return $obj->getPosition();
}

objSort($objArray,'getIndex');
?>
jalil at measat dot org 15-Nov-2008 01:48
this is an implementation of the complement of
Matthew Hood's objectSort (http://my.php.net/manual/en/function.sort.php#75036), which i found very convenient for sorting objects.

this does the reverse, it sorts according to the key
selected for the object but in reverse order.
and having both sort methods allows consistency and convenience for sorting objects, if speed isn't your major concern.

the only change ( apart form data being reworded as object )  is the use of < instead of > in the original.
you could of couse incorporate all in one routine, but why
complicate matters.

<?php
    function objectRSort(&$object, $key)
    {
        for ($i = count($object) - 1; $i >= 0; $i--)
        {
          $swapped = false;
          for ($j = 0; $j < $i; $j++)
          {
               if ($object[$j]->$key < $object[$j + 1]->$key)
               {
                    $tmp = $object[$j];
                    $object[$j] = $object[$j + 1];
                    $object[$j + 1] = $tmp;
                    $swapped = true;
               }
          }
          if (!$swapped) return;
        }
    }
?>
lucazd at gmail dot com 26-Sep-2008 01:04
Please, think twice before creating (and posting) your homemade solution for ordering an array by a field.

PHP already has a solution for this; usort, which is about x40 faster than any other solution.

If creating a callback for each case hurts, you can do something like this:

<?php
/**
 * @author Lucas Dománico
 */
class util {
    static private $sortfield = null;
    static private $sortorder = 1;
    static private function sort_callback(&$a, &$b) {
        if($a[self::$sortfield] == $b[self::$sortfield]) return 0;
        return ($a[self::$sortfield] < $b[self::$sortfield])? -self::$sortorder : self::$sortorder;
    }
    static function sort(&$v, $field, $asc=true) {
        self::$sortfield = $field;
        self::$sortorder = $asc? 1 : -1;
        usort($v, array('util', 'sort_callback'));
    }
}

# Usage:
for($i=0; $i<1000 ;$i++) {
  $v[] = array('score'=>rand(1,10000));
}
util::sort($v, 'score');

?>
www at designdetector dot com 09-Sep-2008 07:43
To sort an array of multiple text fields alphabetically you have to make the text lowercase before sorting the array. Otherwise PHP puts acronyms before words. You can see this in my example code. Simply store the original text field at the end of the array line and call it later from there. You can safely ignore the lowercase version which is added to the start of the array line.

<?php
echo '<pre>ORIGINAL DATA:
<br />';

$data = array(
'Saturn|7|8|9|0||',
'Hello|0|1|2|3||',
'SFX|5|3|2|4||',
'HP|9|0|5|6||'
);

print_r($data);

sort($data);
reset($data);

echo '<br />RAW SORT:
<br />';

print_r($data);

for ($c = 0; $c < count($data); $c++) {
    list ($letter,$g1,$g2,$g3,$g4,$end) = explode ('|', $data[$c]);
    $lowercase = strtolower($letter);
    $data2[$c] = array($lowercase,$g1,$g2,$g3,$g4,$letter);
}

sort($data2);
reset($data2);

echo '<br />LOWERCASE SORT:
<br />';

print_r($data2);

echo '</pre>';
?>
matpatnik at hotmail dot com 23-Jan-2008 03:46
This function will sort entity letters eg:&eacute;

I hope that help someone

function sort_entity($array) {
    $total = count($array);
    for ($i=0;$i<$total;$i++) {
        if ($array[$i]{0} == '&') {
            $array[$i] = $array[$i]{1}.$array[$i];
        } else {
            $array[$i] = $array[$i]{0}.$array[$i];
        }
    }
    sort($array);

    for ($i=0;$i<$total;$i++) {
        $array[$i] = substr($array[$i],1);
    }

    return $array;
}
jasons at work dot com 07-Jan-2008 12:25
Update to the msort code posted by: alishahnovin

I had a problem with the msort function not being case sensitive. All capital letters A-Z would list in order then all lowercase letters would follow.

the line:
if ($item[$id]<$array[$lowest_id][$id]) {

was changed to:
if (strtolower($item[$id]) < strtolower($array[$lowest_id][$id])) {

<?php
function msort($array, $id="id", $sort_ascending=true) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id])) {
                                    if ($array[$lowest_id][$id]) {
                    if (strtolower($item[$id]) < strtolower($array[$lowest_id][$id])) {
                        $lowest_id = $index;
                    }
                    }
                                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
                if ($sort_ascending) {
            return $temp_array;
                } else {
                    return array_reverse($temp_array);
                }
    }
?>
david wh thomas at gm at 1l dot c0m 02-Sep-2007 06:02
Here's a variation on the above function to sort arrays with more than one key by an arbitrary key's value.

This function allows sorting of an array of objects too

<?php
    /**
     * Sorts an array of objects by the value of one of the object properties or array keys
     *
     * @param array $array
     * @param key value $id
     * @param boolean $sort_ascending
     * @param boolean $is_object_array
     * @return array
     */
 function vsort($array, $id="id", $sort_ascending=true, $is_object_array = false) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            if($is_object_array){
                foreach ($array as $item) {
                    if (isset($item->$id)) {
                                        if ($array[$lowest_id]->$id) {
                        if ($item->$id<$array[$lowest_id]->$id) {
                            $lowest_id = $index;
                        }
                        }
                                    }
                    $index++;
                }
            }else{
                foreach ($array as $item) {
                    if (isset($item[$id])) {
                        if ($array[$lowest_id][$id]) {
                        if ($item[$id]<$array[$lowest_id][$id]) {
                            $lowest_id = $index;
                        }
                        }
                                    }
                    $index++;
                }
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
                if ($sort_ascending) {
            return $temp_array;
                } else {
                    return array_reverse($temp_array);
                }
    }

?>

Sample Usage:

<?php
$nodes = vsort($nodes,'term_data_weight', false, true);
print '<pre>'.print_r($nodes,1).'</pre>';
?>
quirk at qns dot se 22-Jul-2007 05:42
Hi, this is my version of sorting an array by field.

From browsing previous versions it pretty much resembles bluej's version. It's way much faster than the versions where the sorting is made "manually" rather than with native php functions, and I wrote it after trying one of those that kept timing out my scripts if I had 10000 posts.

This one preserves numerical keys as well. So if you want to re-index the array after using it with numerical keys just use the array_values on the result. However there are cases where the key actually means something even if it's a number (id etc) so I didn't want to take it for granted that it should be reindexed.

Cheers
Q

<?php
        function sortArrayByField
        (
            $original,
            $field,
            $descending = false
        )
        {
            $sortArr = array();

            foreach ( $original as $key => $value )
            {
                $sortArr[ $key ] = $value[ $field ];
            }

            if ( $descending )
            {
                arsort( $sortArr );
            }
            else
            {
                asort( $sortArr );
            }

            $resultArr = array();
            foreach ( $sortArr as $key => $value )
            {
                $resultArr[ $key ] = $original[ $key ];
            }

            return $resultArr;
        }
?>
alishahnovin at hotmail dot com 19-Jul-2007 04:16
Someone asked me if the msort I posted below can do a sort by descending... (as it sorts by ascending...smallest to greatest).

It's a simple fix with an extra param, and then an array_reverse...but for the lazy, here you are:

<?php
function msort($array, $id="id", $sort_ascending=true) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id])) {
                                    if ($array[$lowest_id][$id]) {
                    if ($item[$id]<$array[$lowest_id][$id]) {
                        $lowest_id = $index;
                    }
                    }
                                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
                if ($sort_ascending) {
            return $temp_array;
                } else {
                    return array_reverse($temp_array);
                }
    }
?>

<?php

//oh no, this is not in the ordered by id!!
$data[] = array("item"=>"item 1", "id"=>1);
$data[] = array("item"=>"item 3", "id"=>3);
$data[] = array("item"=>"item 2", "id"=>2);

var_dump(  msort($data, "id", false)  ); //just msort it...greatest to smallest

var_dump(  msort($data, "id")  ); //just msort it...smallest to greatest

/* outputs

array
  0 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1

array
  0 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3

*/

?>
bluej100@gmail 10-Jul-2007 03:03
The sort2d I posted before did nothing by default--that'll teach me to copy-and-paste without thinking. Its sort function has to be associative. I've changed the default to asort. natcasesort does actually work, though.

// $sort used as variable function--can be natcasesort, for example
// WARNING: $sort must be associative
function sort2d( &$arrIn, $index = null, $sort = 'asort') {
  // pseudo-secure--never allow user input into $sort
  if (strpos($sort, 'sort') === false) {$sort = 'asort';}
  $arrTemp = Array();
  $arrOut = Array();

  foreach ( $arrIn as $key=>$value ) {
    $arrTemp[$key] = is_null($index) ? reset($value) : $value[$index];
  }

  $sort($arrTemp);

  foreach ( $arrTemp as $key=>$value ) {
    $arrOut[$key] = $arrIn[$key];
  }

  $arrIn = $arrOut;
}

Also, uasort is probably actually the better solution for most 2d sorting, unless you're sorting by a dozen different indexes.
NBS Studio 04-Jul-2007 01:14
This is my way of sorting files into date modified date order. It worked for me!

$dir='topics';
$ext='php5';
$files=scandir($dir);
foreach($files as $fs){
    if(($fs!='.')&&($fs!='..')){
        $fs1.='¬'.filemtime($dir.'/'.$fs).'#'.$fs;
    }
}
$fs2=split('[¬]',$fs1);
arsort($fs2);
foreach($fs2 as $fs3){
    if(eregi($ext,$fs3)){
        $fs4.='¬'.$fs3;
    }
}
$fs5=split('[#]',$fs4);
foreach($fs5 as $fs6){
    if(eregi($ext,$fs6)){
        $fs7.='¬'.$fs6;
    }
}
$fs8=split('[¬]',$fs7);
foreach($fs8 as $fs9){
    $file_list.=$fs9.'
</br>';
}

print $file_list;
sinan at sinaneldem dot com 23-Jun-2007 08:29
here is little script which will merge arrays, remove duplicates and sort it by alphabetical order:

<?php

$array1 = array('apple', 'banana','pear');
$array2 = array('grape', 'pear','orange');

function array_unique_merge_sort($array1, $array2){
$array = array_unique(array_merge($array1, $array2));
sort($array);
foreach ($array as $key => $value) {
    $new[$key] = $value;
}
return $new;
}

print_r (array_unique_merge_sort($array1, $array2));

?>

this will print out:

Array ( [0] => apple [1] => banana [2] => grape [3] => orange [4] => pear )
bluej100@gmail 07-Jun-2007 03:05
One more solution for multidimensional sort: variable functions.

<?php
// $sort used as variable function--can be natcasesort, for example
  function sort2d( &$arrIn, $index = null, $sort = 'sort') {
    // pseudo-secure--never allow user input into $sort
    if (strpos($sort, 'sort') === false) {$sort = 'sort';}
    $arrTemp = Array();
    $arrOut = Array();

    foreach ( $arrIn as $key=>$value ) {
      reset($value);
      $arrTemp[$key] = is_null($index) ? current($value) : $value[$index];
    }

    $sort($arrTemp);

    foreach ( $arrTemp as $key=>$value ) {
      $arrOut[$key] = $arrIn[$key];
    }

    $arrIn = $arrOut;
  }
?>

It appears to me that there are only two algorithms being proposed here (several times each):

1) copy into temp, pass temp to sort function, re-order by temp
2) implement search function in PHP

I'm curious whether anyone's implementation of (2) can beat (1) for speed. Someone have a fast PHP mergesort they can benchmark against this one? Obviously, the fact that the (1) solutions use at least two, possibly three times the memory is a drawback, but I expect that for most of us, speed is significantly more important than memory. Maybe I'll check it myself when I have a minute.
alishahnovin at hotmail dot com 28-May-2007 10:29
Here's my fixed up msort array. What it does is goes through a multidimensional array, and sorts it by the desired key (defaulting to 'id').

So, for example, if you have an array like:

array[0]['value'] = "statement 2"
array[0]['id'] = "2"
array[1]['value'] = "statement 3"
array[1]['id'] = "3"
array[2]['value'] = "statement 1"
array[2]['id'] = "1"

it would rearrange and return the array to be like:

array[0]['value'] = "statement 1"
array[0]['id'] = "1"
array[1]['value'] = "statement 2"
array[1]['id'] = "2"
array[2]['value'] = "statement 3"
array[2]['id'] = "3"

The 'id' index can start at any point, and any array item missing the id index will be added to the end.

<?php
function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id]) && $array[$lowest_id][$id]) {
                    if ($item[$id]<$array[$lowest_id][$id]) {
                        $lowest_id = $index;
                    }
                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
        return $temp_array;
    }
?>

Ex:

<?php

//oh no, this is not in the ordered by id!!
$data[] = array("item"=>"item 4");
$data[] = array("item"=>"item 1", "id"=>1);
$data[] = array("item"=>"item 3", "id"=>3);
$data[] = array("item"=>"item 2", "id"=>2);

var_dump(  msort($data)  ); //just msort it!

/* outputs

array
  0 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  3 =>
    array
      'item' => 'item 4' (length=6)

*/

?>
alishahnovin at hotmail dot com 25-May-2007 04:11
I had a multidimensional array, which needed to be sorted by one of the keys. This is what I came up with...

<?php
function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if ($item[$id]<$array[$lowest_id][$id]) {
                    $lowest_id = $index;
                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
        return $temp_array;
    }
?>

Ex:

<?php

//oh no, this is not in the ordered by id!!
$data[] = array("item"=>"item 4", "id"=>4);
$data[] = array("item"=>"item 1", "id"=>1);
$data[] = array("item"=>"item 3", "id"=>3);
$data[] = array("item"=>"item 2", "id"=>2);

var_dump(  msort($data)  ); //just msort it!

/* outputs

array
  0 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  3 =>
    array
      'item' => 'item 4' (length=6)
      'id' => 4

*/

?>
(Qube#php@Efnet) 14-May-2007 03:38
How to use an anonymous array to sort any associative array by an arbitrary key (or nested key):

$order = -1; # -1 = Ascending. Use 1 for descending.
$sortby = "['key1']['subkey']";
$mysort = create_function('$a,$b', "\$a1=\$a$sortby;\$b1=\$b$sortby; if (\$a1==\$b1) return 0; else return (\$a1<\$b1) ? $order : 0- $
order;");
uasort($assocarray, $mysort);

You can use this in a recursive function if necessary (which is why I developed it).
Matthew Hood 09-May-2007 07:27
The bubble sort below will sort an array of objects based on any one of the values contained in them.

usage: objectSort($details, 'percent');

function objectSort(&$data, $key)
{
    for ($i = count($data) - 1; $i >= 0; $i--)
    {
      $swapped = false;
      for ($j = 0; $j < $i; $j++)
      {
           if ($data[$j]->$key > $data[$j + 1]->$key)
           {
                $tmp = $data[$j];
                $data[$j] = $data[$j + 1];
                $data[$j + 1] = $tmp;
                $swapped = true;
           }
      }
      if (!$swapped) return;
    }
}
y5 at yellow5 dot us 15-Mar-2007 06:52
An improvement on the very nice code submitted by alex [at] vkpb [dot] com. This will preserve the keys if the array is numeric:

function SortDataSet($aArray, $sField, $bDescending = false)
{
    $bIsNumeric = IsNumeric($aArray);
    $aKeys = array_keys($aArray);
    $nSize = sizeof($aArray);

    for ($nIndex = 0; $nIndex < $nSize - 1; $nIndex++)
    {
        $nMinIndex = $nIndex;
        $objMinValue = $aArray[$aKeys[$nIndex]][$sField];
        $sKey = $aKeys[$nIndex];

        for ($nSortIndex = $nIndex + 1; $nSortIndex < $nSize; ++$nSortIndex)
        {
            if ($aArray[$aKeys[$nSortIndex]][$sField] < $objMinValue)
            {
                $nMinIndex = $nSortIndex;
                $sKey = $aKeys[$nSortIndex];
                $objMinValue = $aArray[$aKeys[$nSortIndex]][$sField];
            }
        }

        $aKeys[$nMinIndex] = $aKeys[$nIndex];
        $aKeys[$nIndex] = $sKey;
    }

    $aReturn = array();
    for($nSortIndex = 0; $nSortIndex < $nSize; ++$nSortIndex)
    {
        $nIndex = $bDescending ? $nSize - $nSortIndex - 1: $nSortIndex;
        $aReturn[$aKeys[$nIndex]] = $aArray[$aKeys[$nIndex]];
    }

    return $bIsNumeric ? array_values($aReturn) : $aReturn;
}

function IsNumeric($aArray)
{
    $aKeys = array_keys($aArray);
    for ($nIndex = 0; $nIndex < sizeof($aKeys); $nIndex++)
    {
        if (!is_int($aKeys[$nIndex]) || ($aKeys[$nIndex] != $nIndex))
        {
            return false;
        }
    }

    return true;
}
joris at mangrove dot nl 01-Feb-2007 05:40
Commenting on note http://www.php.net/manual/en/function.sort.php#62311 :

Sorting an array of objects will not always yield the results you desire.

As pointed out correctly in the note above, sort() sorts the array by value of the first member variable. However, you can not always assume the order of your member variables! You must take into account your class hierarchy!

By default, PHP places the inherited member variables on top, meaning your first member variable is NOT the first variable in your class definition!
However, if you use code analyzers or a compile cache, things can be very different. E.g., in eAccelerator, the inherited member variables are at the end, meaning you get different sort results with caching on or off.

Conclusion:
Never use sort on arrays with values of a type other than scalar or array.
alex [at] vkpb [dot] com 26-Jan-2007 03:36
Sorting of an array by a method of inserts.

<?

       function sortByField($multArray,$sortField,$desc=true){
            $tmpKey='';
            $ResArray=array();

            $maIndex=array_keys($multArray);
            $maSize=count($multArray)-1;

            for($i=0; $i < $maSize ; $i++) {

               $minElement=$i;
               $tempMin=$multArray[$maIndex[$i]][$sortField];
               $tmpKey=$maIndex[$i];

                for($j=$i+1; $j <= $maSize; $j++)
                  if($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
                     $minElement=$j;
                     $tmpKey=$maIndex[$j];
                     $tempMin=$multArray[$maIndex[$j]][$sortField];

                  }
                  $maIndex[$minElement]=$maIndex[$i];
                  $maIndex[$i]=$tmpKey;
            }

           if($desc)
               for($j=0;$j<=$maSize;$j++)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
           else
              for($j=$maSize;$j>=0;$j--)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];

           return $ResArray;
       }

// make array
$array['aaa']=array("name"=>"vasia","order"=>1);
$array['bbb']=array("name"=>"petia","order"=>2);
$array['ccc']=array("name"=>"kolia","order"=>3);
$array['ddd']=array("name"=>"zenia","order"=>4);

// set sort
$SortOrder=0; // desc by default , 1- asc

var_dump(sortByField($array,'order',$SortOrder));

array
  'ddd' =>
    array
      'name' => 'zenia' (length=5)
      'order' => 4
  'aaa' =>
    array
      'name' => 'vasia' (length=5)
      'order' => 1
  'bbb' =>
    array
      'name' => 'petia' (length=5)
      'order' => 2
  'ccc' =>
    array
      'name' => 'kolia' (length=5)
      'order' => 3

?>
crudo at pinknet dot cz 28-Nov-2006 05:54
Simple way, how to sort an array without loosing keys:

<?php

$sizes = $bad = $good = array("d" => "dddd", "a" => "aaaa", "c" => "cccc", "e" => "eeee", "b" => "bbbb");

// original
print_r($sizes);

/*
Array
(
    [d] => dddd
    [a] => aaaa
    [c] => cccc
    [e] => eeee
    [b] => bbbb
)
*/

// bad way
sort($bad);
print_r($bad);

/*
Array
(
    [0] => aaaa
    [1] => bbbb
    [2] => cccc
    [3] => dddd
    [4] => eeee
)
*/

// good way
$good=array_flip($good);
ksort($good);
$good=array_flip($good);

print_r($good);

/*
Array
(
    [a] => aaaa
    [b] => bbbb
    [c] => cccc
    [d] => dddd
    [e] => eeee
)
*/

?>
eran dot liberty at gmail dot com 15-Nov-2006 07:24
/**
 * Will sort an array by the value of the applied lambda function to each element
 * without loosing the keys!
 * @param unknown_type $arr
 * @param unknown_type $func of the form mixvar func(your object)
 */
function sortByFunc(&$arr, $func) {
        $tmpArr = array();
        foreach ($arr as $k => &$e) {
            $tmpArr[] = array('f' => $func($e), 'k' => $k, 'e' =>&$e);
        }
        sort($tmpArr);
        $arr = array();
        foreach($tmpArr as &$fke) {
            $arr[$fke['k']] = &$fke['e'];
        }
}

example:
$arr = array(
    1 => array('name' => 'eran', 'age' => 30),
    2 => array('name' => 'naama', 'age' => 29),
    3 => array('name' => 'a', 'age' => 11),
    4 => array('name' => 'b', 'age' => 51),
    5 => array('name' => 'z', 'age' => 5),
);
foreach($arr as $key => $val) {
    echo "<br> $key => (" . $val['name'] . " ," . $val['age'] . ")";
}
sortByFunc($arr,create_function('$element','return $element["age"];'));
echo "<br> now sorted:";
foreach($arr as $key => $val) {
    echo "<br> $key => (" . $val['name'] . " ," . $val['age'] . ")";
}
output:
1 => (eran ,30)
2 => (naama ,29)
3 => (a ,11)
4 => (b ,51)
5 => (z ,5)
now sorted:
5 => (z ,5)
3 => (a ,11)
2 => (naama ,29)
1 => (eran ,30)
4 => (b ,51)
memzap at gmail dot com 21-Jul-2006 10:31
Here is how you would open a file, and put each line into an array. This sorts by the first field $title field.  The next thing I would like to figure out is how to do this same sort but with the ability to skip the first word of the title. Like if the title has an "a" or "the" it would skip that portion of the sort.

$currentfile = "file.txt";
$fp = fopen( $currentfile, "r" ) or die("Couldn't open $currentfile");
while ( ! feof( $fp ) ) {
    $line[] = fgets( $fp, 1024 );

    foreach ( $line as $newarray ) {
}
    $newline[] = trim($newarray);
    sort($newline);
    list($title1, $titleurl1, $rating1) = split ('\|',
$newline[0]);
    list($title2, $titleurl2, $rating2) = split ('\|',
$newline[1]);
    list($title3, $titleurl3, $rating3) = split ('\|',
$newline[2]);
    list($title4, $titleurl4, $rating4) = split ('\|',
$newline[3]);
g8z at yahoo dot com 14-Jul-2006 04:28
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

For example:

$a = array();

$a []= array(
    'name'         => 'Sam',
    'age'         => 23,
    'hire_date'    => '2004-01-01'
);
$a []= array(
    'name'        => 'Sam',
    'age'        => 44,
    'hire_date'    => '2003-03-23'
);
$a []= array(
    'name'        => 'Jenny',
    'age'        => 20,
    'hire_date' => '2000-12-31'
);
$a []= array(
    'name'        => 'Samantha',
    'age'        => 50,
    'hire_date' => '2000-12-14'
);

$sticky_fields = array( 'name' );
print_r( stickysort( $a, 'age', DESC_NUM, $sticky_fields ) );

OUTPUT:

Array
(
    [0] => Array
        (
            [name] => Sam
            [age] => 44
            [hire_date] => 2003-03-23
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 23
            [hire_date] => 2004-01-01
        )
    [2] => Array
        (
            [name] => Jenny
            [age] => 20
            [hire_date] => 2000-12-31
        )
    [3] => Array
        (
            [name] => Samantha
            [age] => 50
            [hire_date] => 2000-12-14
        )
)

Here's why this is the correct output - the "name" field is sticky, so it cannot change its sort order. Thus, the "age" field is only sorted as a sub-sort within records where "name" is identical. Thus, the "Sam" records are reversed, because 44 > 23, but Samantha remains at the bottom, even though her age is 50. This is a way of achieving "sub-sorts" and "sub-sub-sorts" (and so on) within records of identical data for specific fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
g8z at yahoo dot com 10-Jul-2006 08:58
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
g8z at yahoo dot com 10-Jul-2006 08:57
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
Emiliyan at ServicesBG dot Com 28-Mar-2006 07:41
#This is a function that will sort an array...
function sort_by($array,  $keyname = null, $sortby) {
   $myarray = $inarray = array();
   # First store the keyvalues in a seperate array
    foreach ($array as $i => $befree) {
        $myarray[$i] = $array[$i][$keyname];
    }
   # Sort the new array by
    switch ($sortby) {
    case 'asc':
    # Sort an array and maintain index association...
    asort($myarray);
    break;
    case 'arsort':
    # Sort an array in reverse order and maintain index association
    arsort($myarray);
    break;
    case 'natcasesor':
    # Sort an array using a case insensitive "natural order" algorithm
    natcasesort($myarray);
    break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key=> $befree) {
       $inarray[$key] = $array[$key];
    }
    return $inarray;
}
sort_by(); example...
$info = sort_by($myarray, 'name', $use = 'asc');
print_r($info);
ludvig dot ericson at gmail dot com 25-Feb-2006 09:48
A tip for those who like "raul at jimi dot com dot mx" need to preserve keys after changing stuff in the middle of an array:
array_values.

Example:
<?php
$array = array(1, 2, 5, 9, 3);
unset($array[3]); // Remove index 3, which is 9.
$array = array_values($array);
?>

Hint: array_values can be fine for removing keys and reindex them by number instead, too (applies to functions like posix_pwgetuid which returns an associative array, unlike C and others, call array_values on it, and it'll be the same format IIRC.)
jesper at snt dot utwente dot nl 24-Feb-2006 01:26
If you sort an array of objects, the first variable in the object will be used for sorting:

<?php
class foo
{
  var $value; //First variable: Used for sorting
  var $id;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i < 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on value
sort($bar);
print_r($bar);
?>

Compare the piece of code above with the following:

<?php
class foo
{
  var $id; //First variable: Used for sorting
  var $value;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i = 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on id
sort($bar);
print_r($bar);
?>

As you can see the location of declaration of the variables matter!
If you want to sort on both or on a combination of variables, use ksort()
jerome a-t+ yamafoto d*o*t com 22-Feb-2006 09:39
when sorting an array, beware of variable type from elements you put in this array

Example:

$a = 2; // $a is an integer
$b = 'item';
$arr = array($a, $b);
sort($arr);

print_r($arr);

this will output:
$arr[0] = 'item';
$arr[1] = 2;

$a = '2'; // $a is a string
$b = 'item';
$arr = array($a, $b);
sort($arr);

print_r($arr);

this will output:
$arr[0] = '2';
$arr[1] = 'item'

to avoid this problem use:

sort($arr, SORT_STRING)
nm at thenoodleman dot com 30-Jan-2006 05:18
Faster, more effective function:

array_sort (array, ['asc'/'desc'])

Second parameter specifies whether to order ascending or descending. Default is ascending.

function array_sort($array, $type='asc'){
    $result=array();
    foreach($array as $var => $val){
        $set=false;
        foreach($result as $var2 => $val2){
            if($set==false){
                if($val>$val2 && $type=='desc' || $val<$val2 && $type=='asc'){
                    $temp=array();
                    foreach($result as $var3 => $val3){
                        if($var3==$var2) $set=true;
                        if($set){
                            $temp[$var3]=$val3;
                            unset($result[$var3]);
                        }
                    }
                    $result[$var]=$val;
                    foreach($temp as $var3 => $val3){
                        $result[$var3]=$val3;
                    }
                }
            }
        }
        if(!$set){
            $result[$var]=$val;
        }
    }
    return $result;
}

Works for ordering by integers or strings, no need to specify which.

Example:

$array=array('a' => 50, 'b' => 25, 'c' => 75);
print_r(array_sort($array));

Returns:
Array
(
[b] => 25
[a] => 50
[c] => 75
)
james at miicro dot net 24-Jan-2006 10:26
Further to john dot dutcher at highmark dot com's comments - padding the name could cause a problem if you get abnormally long names, it might be better to rebuild the array thus:

Array (
[0] => Array ( [sortname_01] => Dutcher [sortname_02] => F [sortname_03] => John [name] => Dutcher, John F )
[1] => Array ( [sortname_01] => Dutch [sortname_02] => A [sortname_03] => Roger [name] => Dutch, Roger A )
[2] => Array ( [sortname_01] => Dut [sortname_02] => H [sortname_03] => Maurice [name] => Dut, Maurice H )
[3] => Array ( [sortname_01] => Dut [sortname_02] => S [sortname_03] => Mildred [name] => Dut, Mildred S )
)

which should give:

Array (
[0] => Array ( [sortname_01] => Dut [sortname_02] => H [sortname_03] => Maurice [name] => Dut, Maurice H )
[1] => Array ( [sortname_01] => Dut [sortname_02] => S [sortname_03] => Mildred [name] => Dut, Mildred S )
[2] => Array ( [sortname_01] => Dutch [sortname_02] => A [sortname_03] => Roger [name] => Dutch, Roger A )
[3] => Array ( [sortname_01] => Dutcher [sortname_02] => F [sortname_03] => John [name] => Dutcher, John F )
)
john dot dutcher at highmark dot com 11-Jan-2006 04:58
Regarding the array sorting of names by 'whatever' ....

That post addresses a nearly identical issue with sorting that I also have.

I just wanted to inquire though.........wouldn't the building of the 'sortname'  value require that the last name and first name be padded to their full size as they are placed into the
'sortname' field in order to get proper sorting/alignment ?

Otherwise would one have .......

    dutcherjohnf                   (Dutcher, John F)
    dutchrogera                   (Dutch, Roger A)
    dutmauriceh                   (Dut, Maurice H)

Instead of:

    dut           maurice         h
    dutch         roger          a
    dutcher      john            f

John D.
raul at jimi dot com dot mx 01-Dec-2005 09:50
I had an array like this:
$arr=array (1,4,3,6,5);

which returns this:
$arr[0]=1
$arr[1]=4
$arr[2]=3
$arr[3]=6
$arr[4]=5

But lets say i remove [2] which is number 3, i get:

$arr[0]=1
$arr[1]=4
$arr[3]=6
$arr[4]=5

And i want to reindex without doing a sort because i dont want to lose the order of the numbers (like a pop in a stack but in the middle of the list), i do this:

$arr=array_chunk($arr,count($arr));
$arr=$arr[0];

the result is:

$arr[0]=1
$arr[1]=4
$arr[2]=6
$arr[3]=5

This can be applied mostly for tree sorting, when you only have the id and the parent values of the node, and you want to have N levels.
phillip dot metzger at gmail dot com 09-Nov-2005 09:36
For a case insensitive sort use this array_multisort().

<?php
$array_var = Array("Cheery", "zap", "Banana", "apple", "Zing");

array_multisort((strtolower($array_var)), SORT_ASC, SORT_STRING, $array_var);
?>

Result order:
apple
Banana
Cheery
zap
Zing
james at miicro dot net 19-Jul-2005 02:49
It's useful to know that if you're using this function on a multidimensional array, php will sort the first key, then the second and so on. This is similar to being able to use SQL to order by field1, field2 etc.

So:

Array (
[0] => Array ( [category] => work [name] => Smith )
[1] => Array ( [category] => play [name] => Johnson )
[2] => Array ( [category] => work [name] => Berger )
)

will become:

Array (
[0] => Array ( [category] => play [name] => Johnson )
[1] => Array ( [category] => work [name] => Berger )
[2] => Array ( [category] => work [name] => Smith )
)

Hope it helps someone.
whatever at toposphere dot com 02-Jul-2005 01:12
The usort solution below still has problems when sorting strings of different lengths, just like the other flavors of sort that I've tried.

Here's a solution that I came up with -- it's kinda ugly, and it might not be practical for large arrays, but it's works great for me.

I'm getting some people's names out of mySQL and placing them in an array like this: "$lastname, $firstname $middlename". Because some people don't have middle names, "sort" screws up the alphabetization. So what I've done is this:

$index = 0;
while ($rows = mysql_fetch_array($sqlResult)) {
    extract($rows);
    $my_array[$index]['sortname'] = strtolower(preg_replace("/[^a-zA-Z]/", "", "$lastname$firstname$middlename"));
    $my_array[$index]['name'] = trim("$lastname, $firstname $middlename");
    $index++;
}
sort($my_array); // now in perfect alpha order

My "hack" is in the fourth line -- I take the entire name, last name first, and use preg_replace() to take out all non-letter characters, and then used strtolower() to make it all lowercase to ensure all letters would be treated equally by PHP. This goes into the ['sortname'] key within the array.

(The ['sortname'] value has to come before ['name'], or else the array will be sorted by ['name'] instead.)

This gives me:

Array
(
   [0] => Array ( [sortname] => shmojoe [name] => Shmo, Joe )
   [1] => Array ( [sortname] => shmojoem [name] => Shmo, Joe M )
)
... and so on

So the array gets sorted by ['sortname'], which never needs to be displayed, and the associated ['name'] can be displayed in perfect alphabetical order, whether there is one name, two names or three. And because ['sortname'] is letters only, it works great for hyphenated last names or ones with apostrophes, like Smith-Jones or O'Donnell.

I feel that the dual preg_replace() and strtolower() may not be the best theoretical solution, and I don't know how it would run on a really large array, but as I said, it's a great solution for my little site.
dwatson at planandgrow dot com 18-Mar-2005 05:55
Here is a recursive use of sort for multi-dim arrays:

<?php

/*Mulsort function recursively sorts a  multi-dimensional, numeric array in place,
regardless of how many dimensions it has.  The array can be ragged -- not a matrix.
*/

function mulsort(&$a)
{
    sort($a);
    $c = count($a);
    for($i = 0; $i < $c; $i++)
        if (is_array($a[$i]))
            mulsort($a[$i]);
}

//The following array is just used to demo the mulsort function.
$array_demo = array ( array ( array (333,1,9,8,7,6,5), array (array(1, 'x', 22), 99, 88 ), -10 ),
        array ( array (11, 12, 'a', 'b', 'c'), array (8, 1, 2,-5) ) );

echo "Array before sorting:<br /><pre>";
var_dump($array_demo);
echo "</pre></ br></ br>";

mulsort($array_demo);

echo "Array after sorting:<br /><pre>";
var_dump($array_demo);
echo "</pre>";

?>
timc at hlyw dot com 17-Feb-2005 04:04
I dig the multi_sort function(s) from above.  But, they don't work for hash arrays.  I added a keys variable to keep track of the key value as the array gets sorted.  Feed back welcome.

<?php
function array_qsort (&$array, $column=0, $order=SORT_ASC, $first=0, $last= -2)
{
  // $array  - the array to be sorted
  // $column - index (column) on which to sort
  //          can be a string if using an associative array
  // $order  - SORT_ASC (default) for ascending or SORT_DESC for descending
  // $first  - start index (row) for partial array sort
  // $last  - stop  index (row) for partial array sort
  // $keys  - array of key values for hash array sort

  $keys = array_keys($array);
  if($last == -2) $last = count($array) - 1;
  if($last > $first) {
   $alpha = $first;
   $omega = $last;
   $key_alpha = $keys[$alpha];
   $key_omega = $keys[$omega];
   $guess = $array[$key_alpha][$column];
   while($omega >= $alpha) {
     if($order == SORT_ASC) {
       while($array[$key_alpha][$column] < $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] > $guess) {$omega--; $key_omega = $keys[$omega]; }
     } else {
       while($array[$key_alpha][$column] > $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] < $guess) {$omega--; $key_omega = $keys[$omega]; }
     }
     if($alpha > $omega) break;
     $temporary = $array[$key_alpha];
     $array[$key_alpha] = $array[$key_omega]; $alpha++;
     $key_alpha = $keys[$alpha];
     $array[$key_omega] = $temporary; $omega--;
     $key_omega = $keys[$omega];
   }
   array_qsort ($array, $column, $order, $first, $omega);
   array_qsort ($array, $column, $order, $alpha, $last);
  }
}
?>
anthony at ectrolinux dot com 08-Sep-2004 04:39
In a brief addition to the previous poster's message, the ascending sorting order used by PHP directly corresponds to ISO-8859-1 (ASCII). Therefore the character \48 (numeral 0) would be placed before the character \82 (R), which would be placed before the character \110 (n), and so forth.
teunkloosterman at hotmail dot com 30-Aug-2004 01:14
Just to show how it sorts:

<?php
$array = Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "!", "@", "#", "\\\$", "%", "^", "&", "*", "(", ")", "_", "-", "=", "+", "\\\\", "|", ",", "<", ".", ">", "?", "'", "\\\"", "`", "~");
sort($array);
echo implode("", $array);
?>

returns:

 !"#$%&'()*+,-.0123456789<=>?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ
\^_`abcdefghijklmnopqrstuvwxyz|~

note: the result begins with a space
Gerhard Conradi 10-Mar-2004 12:49
Hi @all,

to my previous author: thanks, thanks, thanks! Works great and saved me lot of time. I added an extension for ascending/descending order. Here are the changes:

// first i defined two constants for asc and desc
// you can skip that, but then you have to change the switch command at the end of the function
define("ORDER_ASC", "asc");
define("ORDER_DESC", "desc");

function mu_sort($array, $key_sort, $asc_desc) { // start function

// check input parameters
if (func_num_args()<2 || func_num_args()>3) die("Wrong number of parameters for the call of mu_sort()");

   $array = func_get_arg(0);
   $key_sort = func_get_arg(1);
   if (func_num_args()==3)
      $asc_desc = func_get_arg(2);
   else
      $asc_desc = ORDER_ASC;

   $key_sorta = explode(",", $key_sort);
   .... // from here it's exactly the same

   ... // until here
      } // end loop #2
   } // end loop #1

   // sort
   // if you don't want to use the constants defined at the top, change here to whatever you're using
   switch($asc_desc) {
      case ORDER_DESC:
         rsort($output); break;
      default:
         sort($output);
   }

   // return sorted array
   return $output;
} // end function

Now you can call the function like this:
mu_sort($array, $key_sort, ORDER_DESC);
or even:
mu_sort($array, $key_sort); // This will sort the array by default ascending

Have fun...
matias at arenasoftware dot com 23-Mar-2003 05:36
Lets say you have the following array:
$array1 = Array(third => "Some text 3", second => "Some text 2", first => "Some text 1", fourth => "Some text 4" );
and you want to sort it by first,second,third, fourth.
Very easy! Just create a second array:
$array2 = Array(first => "", second => "", third => "", fourth => "");
and do:
$result = array_merge($array2,$array1);

now $result = Array(first => "Some text 1",second => "Some text 2",third => "Some text 3",fourth => "Some text 4");

This is very usefull when you want to print data out of a database table for example, but you would like to give it a custom order.
arjan321 at hotmail dot com 31-Jan-2003 12:23
Ik you want to sort case insensitive, use the natcasesort()
shailu_agrawal at yahoo dot no_spam dot com 13-Nov-2002 06:05
if 2nd parameter is "SORT_REGULAR" it will compare characters by ASCII values.
For ex: if unsorted values are:  B , a , A
with SORT_REGULAR sorted result will be: A , B , a
and with SORT_STRING sorted result will be: a , A , B
whit at transpect dot com 25-Oct-2002 02:06
fmmarzoa's qsort_multiarray gets the last record with the removal of a "-1" from the 3rd line of the function definition. Here's a routine using it that takes a tab-delimited table with the column names in the first row, and displays it from an arbitrary column on the left to the last on the right with option to sort by any one column:

<?php
//tab-delimited ASCII file to sort - no more than one linefeed at end
$infile="members.txt";
//first column on left to display - count from 0
$firstcol="1";

function qsort_multiarray($array, $num = 0, $order = "ASC", $left = 0, $right = -1) {
        if($right == -1) {
                $right = count($array);
        }
        $links = $left;
        $rechts = $right;
        $mitte = $array[($left + $right) / 2][$num];
        if($rechts > $links) {
                do {
                        if($order == "ASC") {
                                while($array[$links][$num]<$mitte) $links++;
                                while($array[$rechts][$num]>$mitte) $rechts--;
                        } else {
                                while($array[$links][$num]>$mitte) $links++;
                                while($array[$rechts][$num]<$mitte) $rechts--;
                        }
                        if($links <= $rechts) {
                                $tmp = $array[$links];
                                $array[$links++] = $array[$rechts];
                                $array[$rechts--] = $tmp;
                        }
                } while($links <= $rechts);
                if ($left < $rechts) $array = qsort_multiarray($array,$num,$order,$left, $rechts);
                if ($links < $right) $array = qsort_multiarray($array,$num,$order,$links,$right);
        }
        return $array;
}

$mem=file("$infile");
$line=explode("\t","$mem[0]");
$cnt=count($line);
echo "<html><head><title>$infile</title></head><body>";
echo "<table border=\"1\"><tr>";
for ($i=$firstcol;$i<$cnt;$i++) {
        echo "<td><a href=\"$PHP_SELF?col=$i\">$line[$i]</a></td>";
}
echo "</tr>";
$cnt=count($mem);
for ($i=$firstcol;$i<$cnt;$i++) {
        $line=explode("\t","$mem[$i]");
        $cnt2=count($line);
        for ($j=$firstcol;$j<$cnt2;$j++) {
                $mem2[$i][$j]=$line[$j];
        }
}
if(!isset($col)) $col=$firstcol;
$mem2=qsort_multiarray($mem2,$col);
for ($i=0;$i<$cnt;$i++) {
        echo "<tr>";
        for ($j=$firstcol;$j<$cnt2;$j++) {
                $show=$mem2[$i][$j];
                echo "<td>$show</td>";
        }
        echo "</tr>";
}
echo "</table></body></html>";
?>
14-Mar-2002 02:09
If you want to sort an array according to your locale do the following:
(de_DE as example)

setlocale("LC_ALL","de_DE");
usort($arraytobesorted, 'strcoll');

--ed: In PHP 4.4 and PHP 5.0 you can do:
setlocale("LC_ALL", "de_DE");
sort($arraytobesorted, SORT_LOCALE_STRNG);
RunMaster at gmx dot de 29-Aug-2001 10:11
Note that sort() is void, so an assignment like

$foo_array = sort( $foo_array );

wont work. In result you cannot combine sort() for use with other array-related functions just like array_unique() or array_values(). None of the following statements works:

sort( array_unique( $foo_array ) );
// returns empty string

$foo_array = array_unique( sort( $foo_array) );
// returns parameter failure

The only way to combine those functions is to apply sort() in a single line statement.

So please dont waste your time with hours of debugging like me before I found out, its void... ;-)
phpdotnetNO_SPAM at electronic-strategy dot com 05-Jul-2001 09:34
/*
Small function to Alphabetically sort Multidimensional arrays by index values of an n dimension array.

I have only tested this for sorting an array of up to 6 dimensions by a value within the second dimension. This code is very rough and works for my purposes, but has not been tested beyond my needs.

Although a little clunky and not a mathematical type algorithm, it get's the job done. It theoretically overcomes many of the problems I have seen with multidimensional arrays in that it is possible to specify within the function, not by reference :-(, which index you wish to sort by, no matter how many dimensions down.

call function by assigning it to a new / existing array:

$row_array = multidimsort($row_array);
*/

function multidimsort($array_in) {
     $multiarray = array();
    $array_out = array();
    $loopvalue = 0;

    /* -1 as traversal of array starts from 0, count() starts from 1 */
    $multicount = count($array_in) - 1;

    /* add the indexes you wish to sort array by to a new array in this case index is two levels down, but shouldn't make a difference if it goes further indexes down. (Not tested!) */
    for($i = 0; $i <= $multicount; $i++) {
        array_push($multiarray, $array_in[$i][2]);
        //array_push($multiarray, $array_in[$i][2][4]);
        //array_push($multiarray, $array_in[$i][1][3][7]);
    }

    /* alphabetically sort the new array (Ascending in this case) can chage sort to whatever type you like. Even apply user-defined sort. */
    asort($multiarray);

    /* reset internal pointer to beginning of array after above sort */
    reset($multiarray);

    /* traverse new array of index values and add the corresponding element of the input array to the correct position in the output array */
    while (list ($key, $val) = each ($multiarray)) {

        $array_out[$loopvalue] = $array_in[$key];

        $loopvalue++;
    }

    /* return the output array which is all nicely sorted by the index you wanted! */
    return $array_out;
}
Richard dot C dot Mitchell at Boeing dot com 23-Apr-2001 09:59
The usort function can be used to sort multi-dimension arrays, also.

To do a case-insensitive sort on the 7th column of a two-dimensional array:
usort($listing, create_function('$a,$b','return strcasecmp($a[7],$b[7]);'));

When using associative arrays:
usort($listing, create_function('$a,$b','return strcasecmp($a["name"],$b["name"]);'));

Case-sensitive, descending (just change '$a,$b' to '$b,$a'):
usort($listing, create_function('$b,$a','return strcmp($a["name"],$b["name"]);'));

A two-dimensional array of numbers (7th column, ascending):
usort($listing, create_function('$a,$b','return $a[7]==$b[7]?0:($a[7]<$b[7]?-1:1);'));
peek at mailandnews dot com 07-Apr-2001 04:06
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:

usort($listing, 'strcasecmp');

This didn't work (why not?), but you can do a proper case insensitive sort like this:

usort($listing, create_function('$a,$b','return strcasecmp($a,$b);'));
ultrafunkula at mad dot scientist dot com 30-Mar-2000 10:08
What you really want is asort(). The neat thing about PHP arrays is that even though they have a traditional numerical index, they are not defined by it. What I mean by this is if you define an array $data[], then $data[2] does not necessarily exist between $data[1] and $data[3].
So if you asort() by the artist name and then use each() to recover the array elements in the order they exist(rather than an incremental loop which ties you to their arbitrary numerical key), you can sort your data by any dimension of your array. Try this out:
$data[0][1]='Title 2';
$data[0][2]='Title 1';
$data[0][0]='Title 3';
$data[1][1]='Barney';
$data[1][0]='Charlie';
$data[1][2]='Al';
$data[2][2]='Sing the song of Al';
$data[2][1]='Jam with Barney';
$data[2][0]='Charlie Rocks';

while (list($key) = each($data[1])) {
print $data[0][$key].",".$data[1][$key].",".$data[2][$key]."<p>";
}

asort($data[1]);

while (list($key) = each($data[1])) {
print $data[0][$key].",".$data[1][$key].",".$data[2][$key]."<p>";
}

The interesting part is that the first, UNSORTED array doesn't come out in numerical order, because it wasn't put in that way.  If you asort($data[2]) you'll sort by lyrics, and so on. Just make sure you remember to each() by the same dimension as you asort().
misillet at tin dot it 17-Mar-2000 10:58
Note that using sort() it seems to sort by ASCII code, because "AC" is before "Ab" in the result array
sizeof
uasort
Функции для работы с массивами


Сортирует массив, используя пользовательскую функцию для сравнения элементов с сохранением ключей

sort
uksort
Функции для работы с массивами
PHP Manual

uasort

(PHP 4, PHP 5)

uasort — Сортирует массив, используя пользовательскую функцию для сравнения элементов с сохранением ключей

Описание

bool uasort ( array &$array , callable $cmp_function )

Эта функция сортирует массив таким образом, что его индексы сохраняют отношения с элементами, с которыми ранее были ассоциированы, с помощью callback-функции, предоставленной пользователем.

Это обычно используется при сортировке ассоциативных массивов, в которых важен актуальный порядок элементов.

Список параметров

array

Входной массив.

cmp_function

Смотрите функции usort() и uksort() для примеров callback-функций сортировки, предоставленных пользователем.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Простой пример использования uasort()

<?php
// Функция сравнения
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Сортируемый массив
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// Сортируем и выводим получившийся массив
uasort($array, 'cmp');
print_r($array);
?>

Результат выполнения данного примера:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

Смотрите также

  • usort() - Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов
  • Сравнение функций сортировки массивов

User Contributed Notes

Said Dashuk 11-Oct-2011 10:33
My simple and effective solution for sort multi-dimensional array by any key:

<?php
function sort_by_key ($arr,$key) {
    global $key2sort;
    $key2sort = $key;
    uasort($arr, 'sbk');
    return ($arr);
}
function sbk ($a, $b) {global $key2sort; return (strcasecmp ($a[$key2sort],$b[$key2sort]));}
?>
clem at fragment dot at 31-Aug-2011 04:57
for a simple case insensitive compare you can use this (php >= 5.3):

<?php
$greetings = array('howdy', 'Hey', 'aloha he');

uasort($a, function($a, $b){ return strcasecmp($a, $b); });

//$a == array('aloha he', 'howdy', 'Hey');
?>
englishman at bigmir dot net 02-Jul-2011 04:44
In case you need to sort an associative array by one of its keys, this function might be useful:

<?php
function sortByOneKey(array $array, $key, $asc = true) {
    $result = array();

    $values = array();
    foreach ($array as $id => $value) {
        $values[$id] = isset($value[$key]) ? $value[$key] : '';
    }

    if ($asc) {
        asort($values);
    }
    else {
        arsort($values);
    }

    foreach ($values as $key => $value) {
        $result[$key] = $array[$key];
    }

    return $result;
}

?>

Consider the following example:

<?php

$users = array(
    1 => array('name' => 'John', 'age' => 35),
    2 => array('name' => 'Alice', 'age' => 23),
    3 => array('name' => 'Bob', 'age' => 26)
);

$sortedByNameAsc = sortByOneKey($users, 'name');
$sortedByNameDesc = sortByOneKey($users, 'name', false);

echo "Sorted by Name in ascending order: ";
echo "<pre>" . print_r($sortedByNameAsc, true) . "</pre>";
echo "<br /><br />Sorted by Name in descending order: ";
echo "<pre>" . print_r($sortedByNameDesc, true) . "</pre>";

?>

The output will be the following:

Sorted by Name in ascending order:
Array
(
    [2] => Array
        (
            [name] => Alice
            [age] => 23
        )

    [3] => Array
        (
            [name] => Bob
            [age] => 26
        )

    [1] => Array
        (
            [name] => John
            [age] => 35
        )

)

Sorted by Name in descending order:
Array
(
    [1] => Array
        (
            [name] => John
            [age] => 35
        )

    [3] => Array
        (
            [name] => Bob
            [age] => 26
        )

    [2] => Array
        (
            [name] => Alice
            [age] => 23
        )

)
yannick dot battail at gmail dot com 17-Nov-2010 06:37
An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits = array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort ( $fruits , function ($a, $b) {
            return strnatcmp($a,$b); // or other function/code
        }
    );
print_r($fruits);
?>
returns
Array
(
    [3] => Orange6
    [0] => Orange9
    [2] => Orange10
    [1] => Orange11
    [4] => Orange15
)
magikMaker 19-Oct-2010 02:48
a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection, 'my_sort_function');

// Object Oriented
uasort($collection, array($this, 'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));

?>
Yves 08-Oct-2010 12:20
Took me some time to figure that out:
the user function must return an *integer*, if you return a float, you may not get the expected result.

<?php
  $a = ('a' => 0.9, 'b' => 0.7, 'c' => 0.8);

  function sorting($a, $b) { return $a - $b; }

  // The function above will not =work, you have to

  function sorting($a, $b)
  {
   $d = $a = $b;
    return $d < 0 ? -1 : ($d > 0 ? 1 : 0);
  }
?>
phire_sk 05-Oct-2010 02:19
I tried using some of the previous built multisorts, but they weren't working as expected.

So, I made my own Class, and it seems to work wonderfully.

Here is the code:

<?php
/************************************
*    Allows sorting multi-dimensional
*    arrays by a specific key and in
*    asc or desc order
**/
class multiSort
{
    var $key;    //key in your array

    //runs the sort, and returns sorted array
    function run ($myarray, $key_to_sort, $type_of_sort = '')
    {
        $this->key = $key_to_sort;

        if ($type_of_sort == 'desc')
            uasort($myarray, array($this, 'myreverse_compare'));
        else
            uasort($myarray, array($this, 'mycompare'));

        return $myarray;
    }

    //for ascending order
    function mycompare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] < $y[$this->key] )
            return -1;
        else
            return 1;
    }

    //for descending order
    function myreverse_compare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] > $y[$this->key] )
            return -1;
        else
            return 1;
    }
}
?>
stephan dot hoyer at netresearch dot de 22-Jul-2010 05:17
To sort string containing Umlauts you can use this callback function:

<?php
    function sortWUmlauts($s1, $s2)
    {
        $search = array('Ä','Ö','Ü','ß');
        $replace = array('A','O','U','s');
        return strcmp(
           str_ireplace($search, $replace, $s1),
           str_ireplace($search, $replace, $s2)
           );
    }
?>

simply call:

<?php uasort($array, 'sortWUmlauts'); ?>
paul at webtop-designs dot com 30-Nov-2009 01:40
Just expanding on php arobase kochira period com's method:

If you are looking to sort a multi-D array by a specific column and have entries in both upper and lower case, simply drop the entries to lowercase before doing the strcmp.

<?php
$dirs = array(
  array('name' => 'First Folder', 'path' => 'sompath'),
  array('name' => 'second folder', 'path' => 'sompath2'),
  array('name' => 'Third Folder', 'path' => 'sompath3')
);

function so($a, $b) {
    return (strcmp (strtolower($a['name']), strtolower($b['name'])));
}
?>
Alt_F4 09-Oct-2009 08:34
I couldn't work out a way to specify what element to sort by using the existing php functions - maybe I didn't look hard enough?? So i wrote my own multidimensional array sorting class.

<?php

$stock = array(array("id" => 1,"item" => "hat",
                 "number" => 5,    "price" => 15),
                array("id" => 5,"item" => "shoes",
                 "number" => 1,    "price" => 50),
                array("id" => 3,"item" => "tie",
                 "number" => 2,    "price" => 30));

$sort = new multiSort();

//will sort the array by id in ascending order
print_r ($sort->sortArray($stock,'id','rcmp'));

//will sort the array by id in descending order
print_r ($sort->sortArray($stock,'id','cmp'));

//can also be used like so (specifying the index of the array)
print_r ($sort->sortArray($stock,'0','rcmp'));

//////////////////////////////////////////////////////

class multiSort {

    function sortArray($array,$parameter,$_function) { return $this->_uasort($array,$_function,$parameter); }

    function cmp ($a, $b, $p) { return (strcmp ($a[$p],$b[$p]));}

    function rcmp ($a, $b, $p) { return -1 * (strcmp ($a[$p],$b[$p]));}

    function _uasort($array,$func,$param) {
        for($i=0;$i<sizeof($array);$i++) {
            $tmp = $i;
            for($j=1;$j<sizeof($array);$j++) {
                $result = $this->$func($array[$tmp],$array[$j],$param);
                if($result == -1) {
                    $array = $this->arraySwap($array,$tmp,$j);
                    $tmp = $j;
                }
            }
        }
        return $array;
    }

    function arrayswap($arr, $src, $dst) {
        $tmp = $arr[$dst];
        $arr[$dst] = $arr[$src];
        $arr[$src] = $tmp;
        return $arr;
    }
}
//////////////////////////////////////////////////////////
?>

hope someone finds this useful.
php arobase kochira period com 08-Jun-2008 04:13
Difference between uasort() and usort(), the missing example ...

<?php
  $arr = array ( 10 => array('id' => 'dix',  'aa' => '1010'),
                100 => array('id' => 'cent', 'aa' => '100100'),
                  2 => array('id' => 'deux', 'aa' => '22'),
                  7 => array('id' => 'sept', 'aa' => '77'));

  // id sorting
  function so ($a, $b) { return (strcmp ($a['id'],$b['id']));    }
?>

*** uasort($arr, 'so') output:

<?php Array (
    [100] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [2] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [10] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [7] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>

*** usort($arr, 'so') output:

<?php Array (
    [0] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [1] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [2] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [3] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>
joeseed86 at gmail dot com 04-Jan-2007 09:54
Using uasort to alphabetically sort nested objects:

In this example, a "collection" object contains an array of "dataItem" objects which consist of a string name, a string attribute x and an arbitrary integer y.

This code allows you to sort the dataset by any of the dataItem attributes, or the order in which they were originally added to the set.

I'm using PHP 4.23 at work at the moment for legacy reasons, so I wrote the example following that object model.

<?php
class dataItem
{
    var $name;
    var $x;

    //Constructor
    function dataItem($name,$x,$y)
    {
        $this->name = $name;
        $this->x = $x;
        $this->y = $y;
    }
}

class collection
{
    var $dataSet = array();

    //Creates a new data item and adds it to our array
    function add($name,$x,$y)
    {
        $this->dataSet[] = new dataItem($name,$x,$y);
    }

    //The wrapper sort function
    function sortDataSet($s)
    {
        //Sort by the given parameter
        switch($s)
        {
            case "name":
                //Note use of array to reference member method of this object in callback
                uasort($this->dataSet,array($this,"cmpName"));
                break;

            case "x":
                uasort($this->dataSet,array($this,"cmpX"));
                break;

            case "y":
                uasort($this->dataSet,array($this,"cmpY"));
                break;

            case "added":
            default:
                //Re-sort array by original keys
                ksort($this->dataSet);
        }
    }

    //Callback function for sorting by name
    //$a and $b are dataItem objects
    function cmpName($a,$b)
    {
        //Use sort() for simple alphabetical comparison
        //Convert to lowercase to ensure consistent behaviour
        $sortable = array(strtolower($a->name),strtolower($b->name));
        $sorted = $sortable;
        sort($sorted);

        //If the names have switched position, return -1. Otherwise, return 1.
        return ($sorted[0] == $sortable[0]) ? -1 : 1;
    }

    //Callback function for sorting by x
    //$a and $b are dataItem objects
    function cmpX($a,$b)
    {
        //Use sort() for simple alphabetical comparison
        //Convert to lowercase to ensure consistent behaviour
        $sortable = array(strtolower($a->x),strtolower($b->x));
        $sorted = $sortable;
        sort($sorted);

        //If the names have switched position, return -1. Otherwise, return 1.
        return ($sorted[0] == $sortable[0]) ? -1 : 1;
    }

    //Callback function for sorting by y
    //$a and $b are dataItem objects
    function cmpY($a,$b)
    {
        //If $a's y attribute >= $b's y attribute, return 1. Otherwise, return -1.
        return ($a->y >= $b->y) ? 1 : -1;
    }

}

//Create a collection object
$myCollection = new collection();

//Add a few "records"
$myCollection->add("pancake","egg",7);
$myCollection->add("France","Paris",2);
$myCollection->add("Naked Gun","Leslie Nielsen",1);
$myCollection->add("OSX","huge icons",33);
$myCollection->add("telephone","keypad",-3);

//Test the output

//Sort by name:
$myCollection->sortDataSet("name");
print_r($myCollection->dataSet);

//Sort by x
$myCollection->sortDataSet("x");
print_r($myCollection->dataSet);

//Sort by y
$myCollection->sortDataSet("y");
print_r($myCollection->dataSet);

//Sort by order added
$myCollection->sortDataSet("added");
print_r($myCollection->dataSet);

?>

Will give this output (Anotated and re-formatted for ease of reading):

Sorted by name:
France         Paris            2
Naked Gun      Leslie Nielsen   1
OSX            huge icons       33
pancake        egg              7
telephone      keypad          -3

Sorted by x:
pancake        egg              7
OSX            huge icons       33
telephone      keypad          -3
Naked Gun      Leslie Nielsen   1
France         Paris            2

Sorted by y:
telephone      keypad          -3
Naked Gun      Leslie Nielsen   1
France         Paris            2
pancake        egg              7
OSX            huge icons       33

Sorted as added:
pancake        egg              7
France         Paris            2
Naked Gun      Leslie Nielsen   1
OSX            huge icons       33
telephone      keypad          -3

This is obviously a trivial case, but it can be very useful for larger data structures.
rlynch at lynchmarks dot com 16-May-2005 05:36
A subtle bug, corrected...

<?php
function masort(&$data, $sortby)
{
   static $sort_funcs = array();

   if (empty($sort_funcs[$sortby])) {
       $code = "\$c=0;";
       foreach (split(',', $sortby) as $key) {
         $array = array_pop($data);
         array_push($data, $array);
         if(is_numeric($array[$key]))
           $code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) ) return \$c;";
         else
           $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
       }
       $code .= 'return $c;';
       $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
   } else {
       $sort_func = $sort_funcs[$sortby];
   }
   $sort_func = $sort_funcs[$sortby];
   uasort($data, $sort_func);
}
?>

Note that

$code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) ) return \$c;";

Has had the "return \$c" added.  Ultimately what the method is trying to accomplish is to build a chain of sort-order precedence.  But this requires each evaluation to short-circuit out with a return.  It was missing.

Peace
lucas dot karisny at linuxmail dot org 12-Feb-2005 06:09
The following is a modification of the dholme/messju masort func using david's float code with automatic data type detection.  As long as the value isn't a string numeral (I.E. "1", '13.4') this should sort strings and numbers without having to explicity set which they are.

<?php
function masort(&$data, $sortby)
{
   static $sort_funcs = array();

   if (empty($sort_funcs[$sortby])) {
       $code = "\$c=0;";
       foreach (split(',', $sortby) as $key) {
         $array = array_pop($data);
         array_push($data, $array);
         if(is_numeric($array[$key]))
           $code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) );";
         else
           $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
       }
       $code .= 'return $c;';
       $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
   } else {
       $sort_func = $sort_funcs[$sortby];
   }
   $sort_func = $sort_funcs[$sortby];
   uasort($data, $sort_func);
}
?>
siefer at sym dot net 04-Oct-2004 02:24
Hello naholyr at yahoo dot fr!

should it be

$cmp = create_function('$a, $b', "return $cmp_val;");

?

this works with my arrays ;-)

regards, Christopher
marek at lewczuk dot com 27-May-2004 04:01
Below another array sorting function - you can use many keys, whether order type is ascendant or descendant, if values of given key should be treat as string or numeric, if array keys should be preserved. This function is locale-safe - it means that string sorting will be based on setLocale settings. You should be aware that I did not make comprehensive tests, so be careful...

// my locales
SetLocale(LC_COLLATE,"pl_PL.UTF-8");
SetLocale(LC_CTYPE, "pl_PL.UTF-8");

function Array_Sort ($array, $arguments = Array(), $keys = true) {

  // comparing function code
  $code = "";

  // foreach sorting argument (array key)
  foreach ($arguments as $argument) {

    // order field
    $field = substr($argument, 2, strlen($argument));

    // sort type ("s" -> string, "n" -> numeric)
    $type = $argument[0];

    // sort order ("+" -> "ASC", "-" -> "DESC")
    $order = $argument[1];

    // add "if" statement, which checks if this argument
       should be used
    $code .= "if (!Is_Numeric(\$result) || \$result == 0) ";

    // if "numeric" sort type
    if (strtolower($type) == "n") $code .= $order == "-" ? "\$result = (\$a['{$field}'] > \$b['{$field}'] ? -1 : (\$a['{$field}'] < \$b['{$field}'] ? 1 : 0));" : "\$result = (\$a['{$field}'] > \$b['{$field}'] ? 1 : (\$a['{$field}'] < \$b['{$field}'] ? -1 : 0));";

    // if "string" sort type
    else $code .= $order == "-" ? "\$result = strcoll(\$a['{$field}'], \$b['{$field}']) * -1;" : "\$result = strcoll(\$a['{$field}'], \$b['{$field}']);";
  }

  // return result
  $code .= "return \$result;";

  // create comparing function
  $compare = create_function('$a, $b', $code);

  // sort array and preserve keys
  if ($keys) uasort($array, $compare);

  // sort array, but not preserve keys
  else usort($array, $compare);

  // return array
  return $array;
}

Example array:
$array['sdsd'] = array("dir" => 1, "name" => "sas", "olek" => "sdsd");
$array['sds2'] = array("dir" => 2, "name" => "&#347;as", "olek" => "t");

Example - preserve keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")));

Array
(
    [sds2] => Array
        (
            [dir] => 1
            [name] => &#347;as
            [olek] => t
        )

    [sdsd] => Array
        (
            [dir] => 1
            [name] => sas
            [olek] => sdsd
        )

)

Example - without preserving keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")), false);

Array
(
    [0] => Array
        (
            [dir] => 1
            [name] => &#347;as
            [olek] => t
        )

    [1] => Array
        (
            [dir] => 1
            [name] => sas
            [olek] => sdsd
        )

)

Enyoj
david [__at__] castlelaing.com 10-May-2004 09:28
WARNING:-Regarding remmy.cjb.net (22-Oct-2003 05:57) mutisort() function:

Sorting by floating point numbers doesn't work in the current function. Use the modified version below if you want to sort by a floating point column.

<?php
// Based on the other notes given before.
// Sorts an array (you know the kind) by key
// and by the comparison operator you prefer.

// Note that instead of most important criteron first, it's
// least important criterion first.

// The default sort order is ascending, and the default sort
// type is strnatcmp.

// function multisort($array[, $key, $order, $type]...)
function multisort($array)
{
   for($i = 1; $i < func_num_args(); $i += 3)
   {
       $key = func_get_arg($i);
       if (is_string($key)) $key = '"'.$key.'"';

       $order = true;
       if($i + 1 < func_num_args())
           $order = func_get_arg($i + 1);

       $type = 0;
       if($i + 2 < func_num_args())
           $type = func_get_arg($i + 2);

       switch($type)
       {
           case 1: // Case insensitive natural.
               $t = 'strcasecmp($a[' . $key . '], $b[' . $key . '])';
               break;
           case 2: // Numeric.
               $t = '($a[' . $key . '] == $b[' . $key . ']) ? 0:(($a[' . $key . '] < $b[' . $key . ']) ? -1 : 1)';
               break;
           case 3: // Case sensitive string.
               $t = 'strcmp($a[' . $key . '], $b[' . $key . '])';
               break;
           case 4: // Case insensitive string.
               $t = 'strcasecmp($a[' . $key . '], $b[' . $key . '])';
               break;
           default: // Case sensitive natural.
               $t = 'strnatcmp($a[' . $key . '], $b[' . $key . '])';
               break;
       }
       echo $t;
       usort($array, create_function('$a, $b', '; return ' . ($order ? '' : '-') . '(' . $t . ');'));
   }
   return $array;
}
?>
dn dot php at gmx dot de 23-Nov-2003 04:34
regarding remmy.cjb.net (22-Oct-2003 05:57) note:
The "multisort" function is not working. Try the following example.
( I hope this and your note will be deleted soon.)
..- Denis

<?php
$a = array(
    array('c1' => 1, 'c2' => 1, 'c3' => 1, 'c4' => 1),
    array('c1' => 1, 'c2' => 1, 'c3' => 1, 'c4' => 2),
    array('c1' => 1, 'c2' => 1, 'c3' => 2, 'c4' => 1),
    array('c1' => 1, 'c2' => 1, 'c3' => 2, 'c4' => 2)
);

echo('<pre>');
print_r(multisort($a, "'c4'", true, 2,"'c3'", true, 2,"'c2'", true, 2,"'c1'", true, 2));
echo('</pre>');
?>
remmy.cjb.net 21-Oct-2003 11:57
Hope this helps!

- Remmy

<?php

// Based on the other notes given before.
// Sorts an array (you know the kind) by key
// and by the comparison operator you prefer.

// Note that instead of most important criteron first, it's
// least important criterion first.

// The default sort order is ascending, and the default sort
// type is strnatcmp.

// function multisort($array[, $key, $order, $type]...)
function multisort($array)
{
    for($i = 1; $i < func_num_args(); $i += 3)
    {
        $key = func_get_arg($i);

        $order = true;
        if($i + 1 < func_num_args())
            $order = func_get_arg($i + 1);

        $type = 0;
        if($i + 2 < func_num_args())
            $type = func_get_arg($i + 2);

        switch($type)
        {
            case 1: // Case insensitive natural.
                $t = 'strcasenatcmp($a[' . $key . '], $b[' . $key . '])';
                break;
            case 2: // Numeric.
                $t = '$a[' . $key . '] - $b[' . $key . ']';
                break;
            case 3: // Case sensitive string.
                $t = 'strcmp($a[' . $key . '], $b[' . $key . '])';
                break;
            case 4: // Case insensitive string.
                $t = 'strcasecmp($a[' . $key . '], $b[' . $key . '])';
                break;
            default: // Case sensitive natural.
                $t = 'strnatcmp($a[' . $key . '], $b[' . $key . '])';
                break;
        }

        uasort($array, create_function('$a, $b', 'return ' . ($order ? '' : '-') . '(' . $t . ');'));
    }

    return $array;
}

$a = array(
    array('id' => 1, 'name' => 'apple'),
    array('id' => 2, 'name' => 'orange'),
    array('id' => 8, 'name' => 'banana'),
    array('id' => 8, 'name' => 'grapefruit'),
    array('id' => 9, 'name' => 'smoke'),
    array('id' => 1, 'name' => 'screen')
);

// This works like MYSQL 'ORDER BY id DESC, name ASC'
// Note the quoting of string literal keys.
echo('<pre>');
print_r(multisort($a, "'name'", true, 0, "'id'", false, 2));
echo('</pre>');

?>
cablehead 16-Sep-2003 09:08
dholmes we turned your masort function into a smarty plugin:

http://www.phpinsider.com/smarty-forum/viewtopic.php?t=1079

messju contributed the following performance improvements.

function masort(&$data, $sortby)
{
    static $sort_funcs = array();

    if (empty($sort_funcs[$sortby])) {
        $code = "\$c=0;";
        foreach (split(',', $sortby) as $key) {
            $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
        }
        $code .= 'return $c;';
        $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
    } else {
        $sort_func = $sort_funcs[$sortby];
    }
    $sort_func = $sort_funcs[$sortby];
    uasort($data, $sort_func);
}

thank you for the cool function!
php at eden2 dot com 17-Jul-2003 04:36
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?

After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:

"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"

and getting back:

"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"

(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
naholyr at yahoo dot fr 10-Jan-2003 09:35
You can sort a multidimensionnal array by any of its key with this function:

function multi_sort($array, $key)
{
  $cmp_val="((\$a['$key']>\$b['$key'])?1:
    ((\$a['$key']==\$b['$key'])?0:-1))";
  $cmp=create_function('$a, $b', "return $body;");
  uasort($array, $cmp);
  return $array;
}

example:
$myarray = array(
  array("name"=>"kernighan", "language"=>"c"),
  array("name"=>"lerdorf", "language"=>"php"),
  array("name"=>"Stroustrup", "language"=>"c++"),
  array("name"=>"Gosling", "language"=>"java")
);

multi_sort($myarray, "name") returns:
name=Gosling    language=java
name=Kernighan    language=c
name=Lerdorf    language=php
name=Stroustrup    language=c++
dholmes at jccc d0t net 09-Oct-2002 02:27
Here is a little sort function that actually uses a dynamic callback for usort to do it's thing.

It assumes your data is in the form of:
    $data = array(
            array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'),
            array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'),
            array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'),
            array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob'));

Now, you want to sort on one or more cols, don't you?

masort($data, 'LAST,FIRST');
or
masort($data,array('FIRST','ID'));

Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me.

function masort(&$data, $sortby){
    if(is_array($sortby)){
        $sortby = join(',',$sortby);
    }

    uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\');
        foreach($skeys as $key){
            if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){
                return($c);
            }
        }
        return($c); '));
}
Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array".  If anyone has a better way, please suggest.  Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on.
stilgar_cpsNOSPAM at zipmail dot NOSPAMcom dot br 05-Sep-2001 02:30
Use example:

$array[0]['Fator1']=7;
$array[0]['Fator2']="Name";
$array[1]['Fator1']=5;
$array[1]['Fator2']="Name";
$array[2]['Fator1']=7;
$array[2]['Fator2']="NameDiferente";
.....

We want to order by Fator1, then Fator2, then:

function Compare($ar1, $ar2)
{
   if ($ar1['Fator1']<$ar2['Fator1'])
      return -1;
   else if ($ar1['Fator1']>$ar2['Fator1'])
      return 1;
   if ($ar1['Fator2']<$ar2['Fator2'])
      return -1;
   else if ($ar1['Fator2']>$ar2['Fator2'])
      return 1;
   return 0;
}

To sort now, we use:

uasort($array, 'Compare');
sort
uksort
Функции для работы с массивами


Сортирует массив по ключам, используя пользовательскую функцию для сравнения ключей

uasort
usort
Функции для работы с массивами
PHP Manual

uksort

(PHP 4, PHP 5)

uksort — Сортирует массив по ключам, используя пользовательскую функцию для сравнения ключей

Описание

bool uksort ( array &$array , callable $cmp_function )

uksort() отсортирует массив, используя для сравнения его ключей функцию, предоставленную пользователем. Используйте эту функцию, если массив должен быть отсортирован по какому-нибудь необычному признаку.

Список параметров

array

Входной массив.

cmp_function

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования uksort()

<?php
function cmp($a, $b)
{
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

Результат выполнения данного примера:

an apple: 3
a banana: 4
the Earth: 2
John: 1

Смотрите также

  • usort() - Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов
  • Сравнение функций сортировки массивов

User Contributed Notes

mdsky at web dot de 23-May-2010 11:26
Case insensitive without own function:

uksort($array, "strnatcasecmp");
contacto at hardcode dot com dot ar 29-Jul-2009 06:56
need a case insensitive sort by key function? i did and couldn find it, so:

<?php
function insensitive_uksort($a,$b) {
    return strtolower($a)<strtolower($b);
}
uksort($arr, "insensitive_uksort");
?>
brian dot short at gmail dot com 07-Jul-2009 07:58
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last.

<?php
function cmp($a, $b)
{
   $a = preg_replace('@^(a|an|the) @', '', $a);
   $b = preg_replace('@^(a|an|the) @', '', $b);

   //special code for grades
   if (strpos( $a, "+") !== false || strpos( $b, "+") !== false  ||
       strpos( $a, "-") !== false || strpos( $b, "-") !== false ){

        $substrA = substr($a, 0, 1);
        $substrB = substr($b, 0, 1);

        $modifierA = (strlen($a) == 2) ? substr($a, 1, 1) : "";
        $modifierB = (strlen($b) == 2) ? substr($b, 1, 1) : "";

        if ($substrA == $substrB){
            //figure out plusses and minuses.
            if ($modifierA == "+"){
                return -1;
            } else if ($modifierB == "+"){
                return 1;
            }

            if ($modifierA == "-"){
                return 1;
            } else if ($modifierB == '-'){
                return -1;
            }
        } else {
            return strcasecmp($a, $b);
        }

    }
   return strcasecmp($a, $b);
}

$grades = array(
                 "C+" => 13    ,
                "C" => 10     ,
                "D+" => 8     ,
                "B+" => 7     ,
                "C-" => 6     ,
                "A-" => 5     ,
                "F" => 5      ,
                "B" => 4      ,
                "B-" => 4     ,
                "D" => 3      ,
                "D-" => 3     ,
                "A+" => 1
    );

uksort($grades, "cmp");
?>

result:  Array
(
    [A+] => 1
    [A-] => 5
    [B+] => 7
    [B] => 4
    [B-] => 4
    [C+] => 13
    [C] => 10
    [C-] => 6
    [D+] => 8
    [D] => 3
    [D-] => 3
    [F] => 5
)
fgallan at gmail dot com 02-Aug-2007 09:22
muti-array special sort funciton:

<?php
/// mycmp functions ///
function mycmp_asc($a, $b) {
    global $_CMP_FORMULA;
    static $_CMP_FORMULA_VA, $_CMP_FORMULA_VB;
    if (!$_CMP_FORMULA_VA) {
        $_CMP_FORMULA_VA = '$va = ' . str_replace('{}', '$a', $_CMP_FORMULA) . ';';
    }
    if (!$_CMP_FORMULA_VB) {
        $_CMP_FORMULA_VB = '$vb = ' . str_replace('{}', '$b', $_CMP_FORMULA) . ';';
    }
    eval($_CMP_FORMULA_VA);
    eval($_CMP_FORMULA_VB);
    if ($va == $vb) return 0;
    else return ($va < $vb ? -1 : 1);
}
function mycmp_desc($a, $b) {
    global $_CMP_FORMULA;
    static $_CMP_FORMULA_VA, $_CMP_FORMULA_VB;
    if (!$_CMP_FORMULA_VA) {
        $_CMP_FORMULA_VA = '$va = ' . str_replace('{}', '$a', $_CMP_FORMULA) . ';';
    }
    if (!$_CMP_FORMULA_VB) {
        $_CMP_FORMULA_VB = '$vb = ' . str_replace('{}', '$b', $_CMP_FORMULA) . ';';
    }
    eval($_CMP_FORMULA_VA);
    eval($_CMP_FORMULA_VB);
    if ($va == $vb) return 0;
    else return ($va > $vb ? -1 : 1);
}

/// run sort ///
$r = array(
    array(
        'name' => 'name1',
        'numbers' => array(1,3,5,7,9),
    ),
    array(
        'name' => 'name2',
        'numbers' => array(5,6,7,8,9),
    ),
    array(
        'name' => 'name3',
        'numbers' => array(1,2,3,4,5),
    ),
);
global $_CMP_FORMULA;
$_CMP_FORMULA = 'array_sum({}["numbers"])';
usort($r, "mycmp_desc");
echo '<pre>'; print_r($r); echo '</pre>';
?>

print:
Array
(
    [0] => Array
        (
            [name] => name2
            [numbers] => Array
                (
                    [0] => 5
                    [1] => 6
                    [2] => 7
                    [3] => 8
                    [4] => 9
                )

        )

    [1] => Array
        (
            [name] => name1
            [numbers] => Array
                (
                    [0] => 1
                    [1] => 3
                    [2] => 5
                    [3] => 7
                    [4] => 9
                )

        )

    [2] => Array
        (
            [name] => name3
            [numbers] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => 4
                    [4] => 5
                )

        )

)
aleczapka at gmx dot net 14-Nov-2006 12:13
Since, so many people reused array_sorter class, I decided to put here some updated version with fixes.

<?php
//
// $Id: array_sorter.inc.php 82 2005-11-17 17:14:39Z aleczapka $
//

/**
* Handles multidimentional array sorting by a key (not recursive).
*
* @author Oliwier Ptak <aleczapka@gmail.com>
*/
class array_sorter
{
    var $skey = false;
    var $sarray = false;
    var $sasc = true;
    var $sas_object = false;

    /**
    * Constructor
    *
    * @access public
    * @param mixed $array array to sort
    * @param string $key array key to sort by
    * @param boolean $asc sort order (ascending or descending)
    */
    function array_sorter(&$array, $key, $asc=true, $as_object=false) // {{{
    {
        $this->sarray = $array;
        $this->skey = $key;
        $this->sasc = $asc;
        $this->sas_object = $as_object;
    } // }}}

    function debug()  // {{{
    {
        echo "skey: ".$this->skey."<br>";
        echo "sasc: ".$this->sasc."<br>";
    } // }}}

    /**
    * Sort method
    *
    * @access public
    * @param boolean $remap if true reindex the array to reset indexes
    */
    function sortit($remap=true)  // {{{
    {
        if (!is_array($this->sarray) || !array_key_exists($this->skey, @$this->sarray[0]))
            return $this->sarray;

        //$this->debug();

        uksort($this->sarray, array($this, "_as_cmp"));
        if ($remap)
        {
            $tmp = array();
            while (list($id, $data) = each($this->sarray))
                $tmp[] = $data;
            return $tmp;
        }
        return $this->sarray;
    } // }}}

    /**
    * Custom sort function
    *
    * @access private
    * @param mixed $a an array entry
    * @param mixed $b an array entry
    */
    function _as_cmp($a, $b)  // {{{
    {
        //since uksort will pass here only indexes get real values from our array
        if (!is_array($a) && !is_array($b))
        {
            //sort objects
            if ($this->sas_object)
            {
                $obj_a = $this->sarray[$a];
                $obj_b = $this->sarray[$b];

                $str = "\$a = \$obj_a->$this->skey;";
                $str .= "\$b = \$obj_b->$this->skey;";
                eval($str);
            }
            else
            {
                $a = $this->sarray[$a][$this->skey];
                $b = $this->sarray[$b][$this->skey];
            }
        }

        //if string - use string comparision
        if (!ctype_digit($a) && !ctype_digit($b) &&
            !is_int($a) && !is_int($b))
        {
            if ($this->sasc)
                return strcasecmp($a, $b);
            else
                return strcasecmp($b, $a);
        }
        else
        {
            if ($a == $b)
                return 0;

            if ($this->sasc)
                return ($a > $b) ? 1 : -1;
            else
                return ($a > $b) ? -1 : 1;
        }
    }  // }}}

}//end of class

?>
joelith at cyberone dot com dot au 12-Sep-2006 10:13
You can use this function to sort an array of days into order. We grabbed some data from a database which comes out as array('Monday'=>34, 'Sunday'=>45... etc but the day is not in order. So use this:

<?php
function cmp($a, $b){
    $days = array('Tuesday'=>0, 'Wednesday'=>1, 'Thursday'=>2, 'Friday'=>3, 'Saturday'=>4, 'Sunday'=>5, 'Monday'=>6);
    // company logic dictates a week begins on a Tuesday.
    if ($days[$a]<$days[$b]){
        return -1;
    }else{
        return 1;
    }
}
?>
skippy at zuavra dot net 28-Nov-2005 03:57
As silly as it may seem, you may sometimes need a comparison function which leaves the array in the same order. It's not as trivial as returning 0 (zero) all the time, since for some reason it doesn't actually leave the values alone.

Here's a simpler and faster version of the code presented by Ignatius Reilly in an earlier note, which can be used to infer original position based on the original array:

function cmp($a, $b) {
  if ($a == $b) return 0;
  global $target_array_here;
  static $keys;
  if (!$keys) $keys = array_keys($target_array_here);
  $x = array_search($a, $keys);
  $y = array_search($b, $keys);
  return ($x < $y ? -1 : 1);
}
Toni Soler 28-Sep-2005 01:51
Added "sort_type" to the previous class (ascendent/descendent options)

<?php
class t_object_sorter
{
    var $object_array;
    var $sort_by;

    function _comp($a,$b)
    {
        $key=$this->sort_by;
        if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
        return ($this->object_array[$a]->$key < $this->object_array[$b]->$key) ? -1 : 1;
    }

    function _comp_desc($a,$b)
    {
        $key=$this->sort_by;
        if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
        return ($this->object_array[$a]->$key > $this->object_array[$b]->$key) ? -1 : 1;
    }

    function sort(&$object_array, $sort_by, $sort_type = "ASC")
    {
        $this->object_array = $object_array;
        $this->sort_by      = $sort_by;
        if ($sort_type == "DESC")
        {
            uksort($object_array, array($this, "_comp_desc"));
        }
        else
        {
            uksort($object_array, array($this, "_comp"));
        }
    }
}
?>
Commanace at gmail dot com 27-Aug-2005 09:38
I've written a small class that will sort arrays of objects by a certain attribute:

<?php
class t_object_sorter
{
    protected $object_array;
    protected $sort_by;

    private function _comp($a,$b)
    {
        $key=$this->sort_by;
        debug($this->object_array[$a],__FILE__,__LINE__);
        if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
        return ($this->object_array[$a]->$key < $this->object_array[$b]->$key) ? -1 : 1;
    }

    public function sort(&$object_array, $sort_by)
    {
        $this->object_array = $object_array;
        $this->sort_by      = $sort_by;
        uksort($object_array, array($this, "_comp"));
    }
}
?>

It is used like that:

<?php
$sorter = new t_object_sorter;
$sorter->sort($menu->item, 'position');
?>

This call will sort all "item"-objects of the object "menu" by their attribute "position".

I hope this is helpfull.
Jimomighty 19-Mar-2005 07:30
...

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return ($a < $b) ? -1 : 1;
}

function uksort_tree ( &$array )
{
    // [PHP5] foreach ( $array as &$value )
    foreach ( $array as $key => $value )
    {
       if ( is_array ( $value ) )
       {
            // [PHP5] uksort_tree ( $value );
           uksort_tree ( $array[$key] );
       }
    }

    uksort( $array, "cmp" );
}

uksort_tree( $myEntryArray );

...
aleczapka at gmx dot net 22-Dec-2004 04:35
One remark regarding array_sorter class.
It won't work correctly with eg. dates from mysql like 20041206105350, cause you can't convert such number into integer. To fix it remove intval() from the code. If the variable is a number it will work without converting this to int anyways. Here is the fix.

<?php
....
if ($a == $b)
    return 0;
if ($this->sasc)
    return ($a > $b) ? 1 : -1;
else
    return ($a > $b) ? -1 : 1;
...
?>
jg at delegation dot ca 17-Dec-2004 07:41
To sort dates with uksort:

function datediff($a, $b) {

$a = date('U',$a);
$b = date('U',$b);

if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;

return $r;
}
aleczapka at gmx dot net 06-Dec-2004 04:27
Here is a small and very fast object to handle sorting of multidimentional arrays by a key.
<?php
/**
* Handles multidimentional array sorting by a key (not recursive)
*
* @author Oliwier Ptak <aleczapka at gmx dot net>
*/
class array_sorter
{
    var $skey = false;
    var $sarray = false;
    var $sasc = true;

    /**
    * Constructor
    *
    * @access public
    * @param mixed $array array to sort
    * @param string $key array key to sort by
    * @param boolean $asc sort order (ascending or descending)
    */
    function array_sorter(&$array, $key, $asc=true)
    {
        $this->sarray = $array;
        $this->skey = $key;
        $this->sasc = $asc;
    }

    /**
    * Sort method
    *
    * @access public
    * @param boolean $remap if true reindex the array to rewrite indexes
    */
    function sortit($remap=true)
    {
        $array = &$this->sarray;
        uksort($array, array($this, "_as_cmp"));
        if ($remap)
        {
            $tmp = array();
            while (list($id, $data) = each($array))
                $tmp[] = $data;
            return $tmp;
        }
        return $array;
    }

    /**
    * Custom sort function
    *
    * @access private
    * @param mixed $a an array entry
    * @param mixed $b an array entry
    */
    function _as_cmp($a, $b)
    {
        //since uksort will pass here only indexes get real values from our array
        if (!is_array($a) && !is_array($b))
        {
            $a = $this->sarray[$a][$this->skey];
            $b = $this->sarray[$b][$this->skey];
        }

        //if string - use string comparision
        if (!ctype_digit($a) && !ctype_digit($b))
        {
            if ($this->sasc)
                return strcasecmp($a, $b);
            else
                return strcasecmp($b, $a);
        }
        else
        {
            if (intval($a) == intval($b))
                return 0;

            if ($this->sasc)
                return (intval($a) > intval($b)) ? -1 : 1;
            else
                return (intval($a) > intval($b)) ? 1 : -1;
        }
    }

}//end of class
?>

Sample $input_array:

Array
(
    [0] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

Example of usage:
<?php
    function multi_sort(&$array, $key, $asc=true)
    {
        $sorter = new array_sorter($array, $key, $asc);
        return $sorter->sortit();
    }
    //sort by parent_id in descending order
    $my_array = multi_sort($input_array, "parent_id", false);
?>

The result array will be:
Array
(

    [0] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )
fabriceb at gmx dot net 08-Jul-2004 06:26
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of objects to store records that have an 1 to n relationship. E.g. a class "family" has family members stored as an array of objects. Each of those objects prepresents a record in a database related to the family (by it's familyId).

To identify members, I'm using their memberId as the key of the array e.g. $family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions _objSort and sortMembers which will sort the "members" array by key using it's properties (for space reasons I didn't include the methods used to open the records):
<?php
class familyMember
{
    var $memberId;
    var $familyId;
    var $firstName;
    var $age;
    var $hairColor;
// ...
}

class family
{
    var $familyId;
    var $name;
    var $members = array(); // array of familyMember objects
    var $sortFields = array();
    var $sortDirections = array();
    // ...
    function _objSort(&$a, &$b, $i = 0)
    {
        $field        = $this->sortFields[$i];
        $direction    = $this->sortDirections[$i];

        $diff = strnatcmp($this->details[$a]->$field, $this->details[$b]->$field) * $direction;
        if ($diff == 0 && isset($this->sortFields[++$i]))
        {
            $diff = $this->_objSort($a, $b, $i);
        }

        return $diff;
    }

    function sortMembers($sortFields)
    {
        $i = 0;
        foreach ($sortFields as $field => $direction)
        {
            $this->sortFields[$i] = $field;
            $direction == "DESC" ? $this->sortDirections[$i] = -1 : $this->sortDirections[$i] = 1;
            $i++;
        }

        uksort($this->details, array($this, "_objSort"));

        $this->sortFields = array();
        $this->sortDirections = array();
    }
}
// open a family
$familyId = 5;
$family = new family($familyId);
$family->open(); // this will also fetch all members

// sort members by 3 fields
$family->sortMembers(array("firstName" => "ASC", "age" => "DESC", "hairColor" => "ASC"));
// output all family members
foreach ($family->members as $member)
{
    echo $member->firstName." - ".$member->age." - ".$member->hairColor."<br />";
}
?>

Note that this might not be the fastest thing on earth and it hasn't been tested very much yet but I hope it's useful for someone.
webmaster at kik-it at N0SP4M dot com 09-Feb-2004 10:03
The code below allows you to sort an array_A following array_B keys order, original keys and values remain associated.

<?

//main function
Function SortArrayAKeysLikeArrayBKeys(&$TheArrayToSort){
   uksort($TheArrayToSort,"SortArrayAKeysLikeArrayBKeys_cmp");
}

//the custom compare function
Function SortArrayAKeysLikeArrayBKeys_cmp($a,$b){
  global $TheArrayOrder;
  $PosA=KeyPosInArray($a,$TheArrayOrder);
  $PosB=KeyPosInArray($b,$TheArrayOrder);
  if ($PosA==$PosB){return 0;}else{return ($PosA > $PosB ? 1 : -1);}
}

//where is my key in my array
Function KeyPosInArray($Key,$Array){
   $i=0;
   $Pos=99999999;
   if($Array){
      foreach($Array as $K => $V){
         $i++;
         if($K==$Key){
            $Pos=$i;
            break;
         }
      }
   }
   return $Pos;
}

//the array you want to sort
$AnyArrayToSort['age']='19';
$AnyArrayToSort['ville']='rennes';
$AnyArrayToSort['website']='kik-it.com';
$AnyArrayToSort['region']='bretagne';
$AnyArrayToSort['code_postal']='35200';
$AnyArrayToSort['Nom']='Fred';

//the array with the correct keys/values order
$TheArrayOrder['Nom']='Whatever';
$TheArrayOrder['age']='Anything';
$TheArrayOrder['region']='What u want';
$TheArrayOrder['ville']='Something';
$TheArrayOrder['code_postal']='Nothing';

//before sort
print_r($AnyArrayToSort);
echo "<br>";
//we sort
SortArrayAKeysLikeArrayBKeys($AnyArrayToSort);
echo "<br>";
//after sort
print_r($AnyArrayToSort);
?>

Will print :

Array ( [age] => 19 [ville] => rennes [website] => kik-it.com [region] => bretagne [code_postal] => 35200 [Nom] => Fred )

Array ( [Nom] => Fred [age] => 19 [region] => bretagne [ville] => rennes [code_postal] => 35200 [website] => kik-it.com )

The keys not listed in the $TheArrayOrder will appear at the end of your sorted array (only if Key Pos < 99999999 ;o)
guss at typo dot co dot il 07-Dec-2003 12:18
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case, using recursion to compare strings has a huge performance impact while a simple loop would suffice and be faster and more simple.
Recursion is only good if it simplifies your code or your understanding of the concept. the previous example does neither, especially as it does a lot of repetitive things in each iteration, such as asigning the character order constant, rebuilding it into an array and such

For example, the string comparison could be written as such :
function str_compare($a,$b) {
    $order="aA��bBcC&#269;&#268;..."; // longer normally & without that html entities
    $default = strlen($a) - strlen($b);
    $minlen = strlen($a) < strlen($b) ? strlen($a) : strlen($b);
    for ($i = 0; $i < $minlen; $i++) {
        $pos_a=strpos($order,$a[$i]);
        $pos_b=strpos($order,$b[$i]);
        if ($pos_a != $pos_b)
            return $pos_a - $pos_b;
    }
    return $default;
}

Which is much simpler and faster.
Note that the above function will break for characters that are not listed in $order. it should be failry trivial to fix it.
ignatius dot reilly at free dot fr 13-Nov-2003 10:59
To use a more complicated comparison function, one can use a callback to a method of an object instance.
For example the following will take an array $arr whose keys are the same as those of $reference, and reorder $arr so that the keys appear in the same order as in $reference.

class kcmp {
    var $reference ;
    function kcmp( $reference ) {
       $this->reference = $reference ;
    }
    function kcompare( $a, $b ) {
       $keys = array_keys( $this->reference ) ;
       $position_a = array_search( $a, $keys ) ;
       $position_b = array_search( $b, $keys ) ;
       return  $position_a < $position_b ? -1 : 1 ;
    }
}

$reference = array(
    "k2" => "a2",
    "k3" => "a3",
    "k1" => "a1"
) ;
$arr = array(
    "k1" => "b1",
    "k2" => "b2",
    "k3" => "b3"
) ;
print_r( $arr ) ;
uksort( $arr, array( new kcmp( $reference ), "kcompare" ) ) ;
print_r( $arr ) ;
pachollini at stones dot com 03-Mar-2003 04:47
I tried to write my own function for sorting with special Czech characters, which php normally compares wrong way. The function is recoursive, it compares the first characters of the strings and when they're the same, the function calls itself with parameters without the first character. My php often crashed by calling this function. After some time if found the problem: it crashed after 10th recoursive call. I think it's a bug in php, and I've made this workaround:

function str_compare($a,$b,$level=0)
    {
    $maxlevel=9;
    if($GLOBALS["STR_COMPARE"] && is_array($a))
        {
        $a=$a[$GLOBALS["STR_COMPARE"]];
        $b=$b[$GLOBALS["STR_COMPARE"]];
        }
    $result=0;
    if($a==$b) return 0;
    elseif($a=="") return ($b=="") ? 0 : 1;
    elseif ($b=="") return -1;
    else
        {
        $order="aA��bBcC&#269;&#268;..."; // longer normally & without that html entities
        for($i=0;$i<strlen($order);$i++) $codes[]=ord($order[$i]);
        $char_a=$a[0];$char_b=$b[0];
        $pos_a=array_search(ord($a),$codes); $pos_b=array_search(ord($b),$codes);
        //echo"$char_a - $pos_a<br>";
        if($pos_a===false || $pos_b===false)
            {
            if($char_a==$char_b)
                {
                if ($level<=$maxlevel) $result=str_compare (substr($a,1),substr($b,1),$level+1);
                else $a<$b ? $result=-1 : $result=1;
                }
            else ($char_a<$char_b) ? $result=-1 : $result=1;
            }
        else
            {
            if($pos_a==$pos_b)
                {
                if ($level<=$maxlevel) $result=str_compare(substr($a,1), substr($b,1),$level+1);
                else $a<$b ? $result=-1 : $result=1;
                }
            else ($pos_a<$pos_b) ? $result=-1 : $result=1;
            }
        return $result;
        }
    }
kumar at chicagomodular (dot) com 29-Jan-2003 09:12
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
--necessary info from http://www.php.net/manual/en/function.usort.php if you didn't see it already
uasort
usort
Функции для работы с массивами


Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов

uksort
Классы/Объекты
Функции для работы с массивами
PHP Manual

usort

(PHP 4, PHP 5)

usort — Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов

Описание

bool usort ( array &$array , callable $cmp_function )

Эта функция сортирует элементы массива, используя для сравнения значений callback-функцию, предоставленную пользователем. Используйте эту функцию, если вам нужно отсортировать массив по какому-нибудь необычному признаку.

Замечание:

Если два элемента исходного массива равны, их порядок относительно друг друга в отсортированном массиве неопределён.

Замечание: Эта функция присваивает новые ключи элементам массива. Она удалит все существующие ключи, а не просто переупорядочит их.

Список параметров

array

Входной массив.

cmp_function

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
4.1.0 | Представлен новый алгоритм сортировки. Функция cmp_function не сохраняет исходный порядок одинаковых элементов.

Примеры

Пример #1 Пример использования usort()

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

Результат выполнения данного примера:

0: 1
1: 2
2: 3
3: 5
4: 6

Замечание:

Очевидно, что для этого тривиального случая более подходит функция sort().

Пример #2 Пример использования функции usort() с многомерными массивами

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

При сортировке многомерного массива переменные $a и $b содержат ссылки на первые два индекса массива.

Результат выполнения данного примера:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Пример #3 Пример использования usort() с методом класса

<?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* Это статическая функция сравнения: */
    static function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

usort($a, array("TestObj", "cmp_obj"));

foreach ($a as $item) {
    echo $item->name . "\n";
}
?>

Результат выполнения данного примера:

b
c
d

Пример #4 Пример использования функции usort() с применением анонимной функции для сортировки многомерного массива

<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));

foreach ($array as $item) {
    echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>

Результат выполнения данного примера:

y, a
x, b
z, c

Смотрите также

  • uasort() - Сортирует массив, используя пользовательскую функцию для сравнения элементов с сохранением ключей
  • Сравнение функций сортировки массивов

User Contributed Notes

zuallauz at gmail dot com 29-Mar-2012 09:56
When trying to do some custom sorting with objects and an anonymous function it wasn't entirely clear how this usort function works. I think it probably uses a quicksort in the background. Basically it actually moves the $b variable up or down in respect to the $a variable. It does NOT move the $a variable inside the callback function. This is key to getting your logic right in the comparisons.

If you return -1 that moves the $b variable down the array, return 1 moves $b up the array and return 0 keeps $b in the same place.

To test I cut down my code to sorting a simple array from highest priority to lowest.

<?php
$priorities = array(5, 8, 3, 7, 3);

usort($priorities, function($a, $b)
{
    if ($a == $b)
    {
        echo "a ($a) is same priority as b ($b), keeping the same\n";
        return 0;
    }
    else if ($a > $b)
    {
        echo "a ($a) is higher priority than b ($b), moving b down array\n";
        return -1;
    }
    else {
        echo "b ($b) is higher priority than a ($a), moving b up array\n";
        return 1;
    }
});

echo "Sorted priorities:\n";
var_dump($priorities);
?>

Output:

b (8) is higher priority than a (3), moving b up array
b (5) is higher priority than a (3), moving b up array
b (7) is higher priority than a (3), moving b up array
a (3) is same priority as b (3), keeping the same
a (8) is higher priority than b (3), moving b down array
b (8) is higher priority than a (7), moving b up array
b (8) is higher priority than a (5), moving b up array
b (8) is higher priority than a (3), moving b up array
a (5) is higher priority than b (3), moving b down array
a (7) is higher priority than b (5), moving b down array

Sorted priorities:
array(5) {
  [0]=> int(8)
  [1]=> int(7)
  [2]=> int(5)
  [3]=> int(3)
  [4]=> int(3)
}
andi_mclean at ntlworld dot com 04-Feb-2012 03:58
I needed a sort method that would sort strings but take note of any numbers and would compare them as number. I also want to ignore any non alphanumerical characters.

Eg.
Slot 1 Example
Slot 10 Example
Slot 2 Example

Should infact be
Slot 1 Example
Slot 2 Example
Slot 10 Example

<?php
function sort_with_numbers($a , $b) {
    $a = explode(' ',$a);
    $b = explode(' ',$b);
    $size = min(count($a), count($b));
    for($index =0; $index < $size; ++$index) {
        $a1 = ereg_replace("[^A-Za-z0-9]", "",$a[$index]);
        $b1 = ereg_replace("[^A-Za-z0-9]", "",$b[$index]);
        $equal = 0;
        if (is_numeric($a1) && is_numeric($b1)) {
            $equal = $a1 - $b1;
        } else {
            $equal = strcasecmp($a1,$b1);
        }
        if ($equal < 0) {
            return -1;
        }
        if ($equal > 0) {
            return 1;
        }
    }
    return count($a) - count($b);
}
?>
Quicker 05-Jan-2012 01:53
This one may approve multisort performance dramatically.

I had a 100K-row-array with assoc keys and sub arrays, several MBs. Using usort hammered my dev box cpu for several minutes until I killed it.
My own assoc-version of [someone else's code] did the same. Following Array-Indexing and sorting solution only took very few secs:

<?php
define('funcname',0);
define('indexfieldinfuncparamspos',1);
define('funcparams',2);
function array_index($dataarr,$field2funcarr){
  $indexarr=array();
  foreach($dataarr as $key=>$valarr) {
    $currentindex='';
    foreach($field2funcarr as $fieldid=>$funcarr) if(is_array($funcarr)) {
      $funcarr[funcparams][$funcarr[indexfieldinfuncparamspos]]= $valarr[$fieldid];
      $currentindex.= call_user_func_array($funcarr[funcname],$funcarr[funcparams]).'_';
    } else $currentindex.= $valarr[$fieldid].'_';
    $indexarr[$currentindex]=$key;
  }
  return $indexarr;
}
function array_sortbyindex(&$dataarr,$indexarr,$issortindexbykey=true){
  // assumes complete index!: each item of indexarr must correlate a key of dataarr
  $resultarr=array();
  if($issortindexbykey) ksort($indexarr);
  foreach($indexarr as $datakey) $resultarr[$datakey]= $dataarr[$datakey];
  return $resultarr;
}

$dataarr=array(
'Franz'=>array('letters'=>5,'wordtype'=>'name'),
'goes'=>array('letters'=>4,'wordtype'=>'verb'),
'to'=>array('letters'=>2,'wordtype'=>'prep'),
'China'=>array('letters'=>5,'wordtype'=>'noun'));

// just build an index for interest (empty string for wordtype as no modification required):
print_r(array_index($dataarr, array('letters'=>array('str_pad',0,array('',7,'0',STR_PAD_LEFT)), 'wordtype'=>'')));

// build index and sort - all in one go:
print_r(array_sortbyindex($dataarr, array_index($dataarr, array('letters'=>array('str_pad',0, array('',7,'0',STR_PAD_LEFT)), 'wordtype'=>''))));
?>

first print_r returns:
Array
(
    [0000005_name_] => Franz
    [0000004_verb_] => goes
    [0000002_prep_] => to
    [0000005_noun_] => China
)

second print_r returns:
Array
(
    [to] => Array
        (
            [letters] => 2
            [wordtype] => prep
        )

    [goes] => Array
        (
            [letters] => 4
            [wordtype] => verb
        )

    [Franz] => Array
        (
            [letters] => 5
            [wordtype] => name
        )

    [China] => Array
        (
            [letters] => 5
            [wordtype] => noun
        )

)

Major Benefits:
- extremly fast
- each sort field can apply an own modifier. Ideally you can use out-of-the-box functions, which reduces effort for programming callbacks
- you could use the index eg. for sorted data output without physically sorting the data
admin at gosenz dot com 04-Dec-2011 08:58
sort multi-dimentional arrays in class with usort

<?php
class ArraySort
{
    private $arr = array();

    public function __construct($arr)
    {
        $this->arr = $arr;
    }

    public function doSort()
    {
        $cmp = function($a, $b)
        {
            //Do Some Comparation
        }
        if(is_array($this->arr))
        {
            usort($this->arr, $cmp);
        }
        return $this->arr;
    }
}
?>
Gok6tm 13-Sep-2011 06:09
this is a new multisort function for sorting on multiple subfield like it will be in sql : 'ORDER BY field1, field2'
number of sort field is undefined
<?php

$array[] = array('soc' => 3, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>5);
$array[] = array('soc' => 1, 'code'=>2);
$array[] = array('soc' => 3, 'code'=>2);

//usage
print_r(multiSort($array, 'soc', 'code'));

function multiSort() {
    //get args of the function
    $args = func_get_args();
    $c = count($args);
    if ($c < 2) {
        return false;
    }
    //get the array to sort
    $array = array_splice($args, 0, 1);
    $array = $array[0];
    //sort with an anoymous function using args
    usort($array, function($a, $b) use($args) {

        $i = 0;
        $c = count($args);
        $cmp = 0;
        while($cmp == 0 && $i < $c)
        {
            $cmp = strcmp($a[ $args[ $i ] ], $b[ $args[ $i ] ]);
            $i++;
        }

        return $cmp;

    });

    return $array;

}
?>

output:
Array
(
    [0] => Array
        (
            [soc] => 1
            [code] => 1
        )

    [1] => Array
        (
            [soc] => 1
            [code] => 1
        )

    [2] => Array
        (
            [soc] => 1
            [code] => 2
        )

    [3] => Array
        (
            [soc] => 2
            [code] => 1
        )

    [4] => Array
        (
            [soc] => 2
            [code] => 5
        )

    [5] => Array
        (
            [soc] => 3
            [code] => 1
        )

    [6] => Array
        (
            [soc] => 3
            [code] => 2
        )

)
neculitairinel at yahoo dot com 19-Aug-2011 06:12
Here is another date sort, in case you have hours and minutes in the dates.

<?php
function DateSort($a,$b,$d="-") {
    if ($a == $b) {
        return 0;
    } else {
        $a = strtotime($a);
        $b = strtotime($b);
        if($a<$b) {
            return -1;
        } else {
            return 1;
        }
    }
}
?>
Lea Hayes 12-Jul-2011 05:55
<?php
/**
 * Sort array of objects by field.
 *
 * @param array $objects Array of objects to sort.
 * @param string $on Name of field.
 * @param string $order (ASC|DESC)
 */
function sort_on_field(&$objects, $on, $order = 'ASC') {
    $comparer = ($order === 'DESC')
        ? "return -strcmp(\$a->{$on},\$b->{$on});"
        : "return strcmp(\$a->{$on},\$b->{$on});";
    usort($objects, create_function('$a,$b', $comparer));
}
?>
bcsj 28-Jun-2011 11:12
Sorting a multidimensional array by a subkey seem to be one of the bigger challenges when using usort. At least if one want the key to be dynamic. For anyone interested this code seemed to work rather well for me:

<?php

usort($array,array(new cmp($key), "cmp__"));

class cmp {
    var $key;
    function __construct($key) {
        $this->key = $key;
    }

    function cmp__($a,$b) {
        $key = $this->key;
        if ($a[$key] == $b[$key]) return 0;
        return (($a[$key] > $b[$key]) ? 1 : -1);
    }
}

?>
masonswolf+ignorethispart at gmail dot com 13-Jun-2011 10:42
[The second version of a function I wrote], just a little cleaner to use, since the usort call is now folded into the custom 'usortByArrayKey' function.

Seems like this is a popular problem - sorting an array of arrays by the keys of sub-arrays, so I'll go ahead and throw in an approach I haven't seen anyone mention yet. It only works since PHP 5.3 because that's when anonymous functions got added to the language.

<?php
function usortByArrayKey(&$array, $key, $asc=SORT_ASC) {
    $sort_flags = array(SORT_ASC, SORT_DESC);
    if(!in_array($asc, $sort_flags)) throw new InvalidArgumentException('sort flag only accepts SORT_ASC or SORT_DESC');
    $cmp = function(array $a, array $b) use ($key, $asc, $sort_flags) {
        if(!is_array($key)) { //just one key and sort direction
            if(!isset($a[$key]) || !isset($b[$key])) {
                throw new Exception('attempting to sort on non-existent keys');
            }
            if($a[$key] == $b[$key]) return 0;
            return ($asc==SORT_ASC xor $a[$key] < $b[$key]) ? 1 : -1;
        } else { //using multiple keys for sort and sub-sort
            foreach($key as $sub_key => $sub_asc) {
                //array can come as 'sort_key'=>SORT_ASC|SORT_DESC or just 'sort_key', so need to detect which
                if(!in_array($sub_asc, $sort_flags)) { $sub_key = $sub_asc; $sub_asc = $asc; }
                //just like above, except 'continue' in place of return 0
                if(!isset($a[$sub_key]) || !isset($b[$sub_key])) {
                    throw new Exception('attempting to sort on non-existent keys');
                }
                if($a[$sub_key] == $b[$sub_key]) continue;
                return ($sub_asc==SORT_ASC xor $a[$sub_key] < $b[$sub_key]) ? 1 : -1;
            }
            return 0;
        }
    };
    usort($array, $cmp);
};
?>

Examples:
1) Sort a multi-dimensional array by a single key, from least to greatest:
    usortByArrayKey($resultset, 'order_id');

2) Sort a multi-dimensional array by a single key, from greatest to least:
    usortByArrayKey($resultset, 'purchase_amount', SORT_DESC);

3) Sort a multi-dimensional array first by one key, but then by a different key when the first one is equal, both from least to greatest:
    usortByArrayKey($resultset, array('product_id', 'price'));

4) Sort a multi-dimensional array by two different keys from least to greatest, and then a third from greatest to least if the first two keys map to the equal values:
    usortByArrayKey($resultset, array('product_id', 'customer_id', 'date'=>SORT_DESC));

5) Sort a multi-dimensional array by multiple keys, all from greatest to least:
    usortByArrayKey($resultset, array('product_id', 'price'), SORT_DESC);

One word of caution, since SORT_ASC and SORT_DESC have actual int values of 4 and 3, respectively, if you need to sort a multi-dimensional array by keys 3 or 4, and you're using an array to pass in your keys, you MUST specify your sort flags (e.g. array(3 => SORT_ASC,...)) to prevent unexpected behavior, instead of relying on the function's second parameter as your default sort flag.
cuonghuyto at gmail dot com 02-Mar-2011 02:42
Some contribution towards a specification of usort()

------
- If you don't provide the callback function, an error would be raised: "usort(): Invalid comparison function."
- If your callback function doesn't return anything, or returns any value other than -1 or +1 (e.g. 0, 2, -2), then usort() would treat your sorting purpose as if there is no comparison operator provided, and it would actually change your list into an undefined order
------
markfiend at gmail dot com 21-Feb-2011 02:22
To sort a multidimensional array (such as is returned from database query) by the values in $array[foo][$key]

e.g.
<?php
/** Potential pitfall if there is already a key of '__________'
 *  in the subarrays. Not likely I hope!
 * -------------------------------------------------------------
 */
function array_sort_by_subval(&$array, $key) {
    foreach($array as &$v) {
        $v['__________'] = $v[$key];
    }
    usort($array, 'sort_by_underscores');
    foreach($array as &$v) {
        unset($v['__________']);
    }
}

function sort_by_underscores($a, $b) {
    if($a['__________'] == $b['__________']) return 0;
    if($a['__________'] < $b['__________']) return -1;
    return 1;
}

$n = array(array('a' => 0, 'b' => 7, 'c' => 2),
           array('a' => 4, 'b' => 1, 'c' => 3),
           array('a' => 7, 'b' => 3, 'c' => 1));

array_sort_by_subval($n, 'b');
?>
The array $n will now be:
array(array('a' => 4, 'b' => 1, 'c' => 3),
      array('a' => 7, 'b' => 3, 'c' => 1),
      array('a' => 0, 'b' => 7, 'c' => 2))
cmanley_nl 24-Jan-2011 11:55
I had to sort a result set by host. I made this comparator function to use in usort calls.
Sorts by host segment so that a.example.org comes after b.example.com, etc.

<?php
function hostcmp($a, $b) {
    $a = strtolower($a);
    $b = strtolower($b);
    if ($a == $b) {
        return 0;
    }
    $parts_a = array_reverse(explode('.', $a));
    $parts_b = array_reverse(explode('.', $b));
    $max = max(count($parts_a), count($parts_b));
    for ($i=0; $i < $max; $i++) {
        if (($i < count($parts_a)) && ($i < count($parts_b))) {
            if ($c = strcmp($parts_a[$i],$parts_b[$i])) {
                return $c;
            }
        }
        else {
            // Return numeric cmp on array sizes. PHP doesn't have a <=> operator, so emulate it.
            //return count($parts_a) <=> count($parts_b);
            return count($parts_a) == count($parts_b) ? 0 : (count($parts_a) < count($parts_b) ? -1 : 1);
        }
    }
    return 0;
}
?>
fmaz008 at gmail dot com 29-Sep-2010 02:23
This comment is just to help backward compatibility.

I needed to have a foreach loop using reference just before using the usort function on the same array that was used in the foreach.

Like this:
<?php
public function sortByTitle()
{
        if(empty($this->_arrSubCat))
            return false;

        foreach($this->_arrSubCat as &$cat)
            $cat->sortByTitle();

        usort($this->_arrSubCat, 'strcasecmp');
}
?>

I had this strange bug where the last object of the $this->_arrSubCat array before the sort was alway replaced/overwrited with his string value.

On my machine (PHP 5.3), I had no problem, but when I placed the code on another server, my code crashed with a fatal error (Because I was using a string as an object later in the code)

The solution I found is really simple, and avoid the array to have a reference declared in memory while running the sort function. Just add an unset($cat):

<?php
public function sortByTitle()
{
        if(empty($this->_arrSubCat))
            return false;

        foreach($this->_arrSubCat as &$cat)
            $cat->sortByTitle();

        unset($cat); //No more problem because of the foreach &cat reference.
        usort($this->_arrSubCat, 'strcasecmp');
}
?>

It took me an hour an a half to locate the bug, hope it will save someone some time !
phil at lavin dot me dot uk 01-Aug-2010 11:06
strcmp (or strcasecmp) can be used as a callback function for usort. It will cast your comparison values to string. Thus, you can implement a __toString() method into your classes and use usort without creating a callback function:

<?php
class Foo {
   private $a;
   private $b;

   public function __construct($a, $b) {
      $this->a = $a;
      $this->b = $b;
   }

   public function __toString() {
      return (string)$this->a;
   }
}

$foo = array(new Foo('t', 'b'), new Foo('a', 'c'), new Foo('g', 'd'));

print_r($foo);

usort($foo, 'strcasecmp');

print_r($foo);
?>
xaguilars at gmail dot com 06-May-2010 04:03
I'd like to share with the community my function for sorting an array of arrays or objects containing associative data. This could be used, for example, with a MySQL result.

<?php
function sort_by($field, &$arr, $sorting=SORT_ASC, $case_insensitive=true){
    if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
        if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
        else $strcmp_fn = "strnatcmp";

        if($sorting==SORT_ASC){
            $fn = create_function('$a,$b', '
                if(is_object($a) && is_object($b)){
                    return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
                }else if(is_array($a) && is_array($b)){
                    return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
                }else return 0;
            ');
        }else{
            $fn = create_function('$a,$b', '
                if(is_object($a) && is_object($b)){
                    return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
                }else if(is_array($a) && is_array($b)){
                    return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
                }else return 0;
            ');
        }
        usort($arr, $fn);
        return true;
    }else{
        return false;
    }
}
?>
Alex Rath 17-Apr-2010 11:35
This is the perfect Place for anonymous Functions, here an Example:

<?php

  $array = array(3, 2, 5, 6, 1);

  usort($array, function($func_a, $func_b) {
    if($func_a == $func_b) return 0;
    return ($func_a < $func_b) ? -1 : 1;
  });

  foreach ($array as $key => $value) echo "$key: $value\n";

?>
nicolas dot demarque at gmail dot com 10-Apr-2010 11:37
Another way to compare object is to have a compare static function in the class with reccursion ability and have globals or static variables who save the state of comparison, and the order.

It could be a good idea to have a variable with comparison functions name (with the sorting : numeric, alphanumeric, inverse).

<?php
interface Comparable{static function compare($a, $b);}
class myObj implements Comparable{
        var $var1; var $var2; var $var3;
        function __construct($v1, $v2, $v3){
                $this->var1=$v1; $this->var2=$v2; $this->var3=$v3;
        }
        public function __toString() {
                return "v1 ".$this->var1." v2 ".$this->var2." v3 ".$this->var3;
        }
        static function compare($a, $b){
                $sort=$GLOBALS['sorts'][$GLOBALS['sort']];
                echo "$sort\n";
                if($a->$sort == $b->$sort){
                        if($GLOBALS['sorts'][$GLOBALS['sort']+1]){
                                $GLOBALS['sort']++;
                                $res=  call_user_func(array('myObj', 'compare'), $a, $b);
                                $GLOBALS['sort']=0; return $res;
                        }
                        $GLOBALS['sort']=0; return 0;
                }
                $GLOBALS['sort']=0;
                if($a->$sort > $b->$sort)
                        return 1;
                return -1;
        }
}

$objects = array(new myObj("1", "2", "3"), new myObj("2", "2", "2"), new myObj("1", "3", "4"));

/* Tests */
$sorts=Array('var1', 'var2', 'var3'); $sort = 0; usort($objects, array('myObj', 'compare')); echo ("var1 var2 var3\n"); foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var3', 'var1'); $sort = 0; usort($objects, array('myObj', 'compare')); echo ("\nvar2 var3 var1\n"); foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var1', 'var3'); $sort = 0; usort($objects, array('myObj', 'compare')); echo ("\nvar2 var1 var3\n"); foreach($objects as $o)echo $o."\n";

?>
Paul Geraghty foofoonet at the G Mall 27-Nov-2009 11:42
For anyone else sorting mixed RSS feeds in date order, here's an example of the perhaps not so obvious way of calling a method from the same class using usort():

<?php
class MyAggregator {

  static function cmp_pubdate( $a, $b ) {
    $a_t = strtotime( $a['pubdate'] ) ;
    $b_t = strtotime( $b['pubdate'] ) ;

    if( $a_t == $b_t ) return 0 ;
    return ($a_t > $b_t ) ? -1 : 1;
  }

// assemble arrays for display in date order
  function all_documents(){
    $all_data  = array_merge (
    $this->upcoming(), $this->past() ) ;

// Use within its own class using the $this syntax so:
    usort( $all_data, array( $this , "cmp_pubdate" ) ) ;

  return $all_data ;
  }
}
?>

As previously said, use as a static function in other parts of your code:

<?php usort ( $a, array( "MyAggregator", "cmp_pubdate" ) ) ; ?>
Rogier 16-Nov-2009 03:50
<?php
// I have seen many examples of sorting, almost all of which
// are too specific and require one implementation per property
// on which to sort.
// So I decided to use Reflection, implementing a more generic approach that in fact turned out
// to resemble an approach I used in the early days of .NET...

// Intentionally, I did not do any checking on existing
// items. This is just to keep simplicity and to
// demonstrate the sorting functionality.

// A more real-life appraoach would require e.g. a collection that is based
// on implementing the Iterator, ArrayAccess and Countable interfaces.

// Take note that this implementation is specific for PHP5+ only
// This code was tested on PHP 5.0.4

class SortableItem
{
    static public $sortProperty;

    static function USortAsc($a, $b)
    {
        /*@var $_pd ReflectionProperty*/
        $_pd = self::$sortProperty;
        if ($_pd !== null)
        {
            if ($_pd->getValue($a) === $_pd->getValue($b))
                return 0;
            else
                return (($_pd->getValue($a) < $_pd->getValue($b))?-1:1);
        }
        return 0;
    }

    static function USortDesc($a, $b)
    {
        return -(self::USortAsc($a,$b));
    }

}
class Item extends SortableItem
{
    public $name;
    public $index;
    public $description;

    function __construct($nam,$idx,$desc)
    {
        $this->name = $nam;
        $this->index = $idx;
        $this->description = $desc;
    }
    function __toString()
    {
        return "$this->index; $this->name; $this->description\n";
    }
}
class ItemCollection
{
    protected $_array = array();
    protected $_itemDescriptor;

    function __construct()
    {
        $this->_itemDescriptor = new ReflectionClass('Item');
    }

    function Add(Item $item)
    {
        $this->_array[] = $item;
    }

    function Sort($property, $asc=true)
    {
        // this is where sorting logic takes place
        $_pd = $this->_itemDescriptor->getProperty($property);
        if ($_pd == null)
        {
            user_error('Property '.$property.' does not exist in class '.$this->_itemDescriptor->getName(), E_WARNING);
            return;
        }
        // set sortDescriptor
        Item::$sortProperty = $_pd;
        // and apply sorting
        usort($this->_array, array('Item', ($asc?'USortAsc':'USortDesc')));
    }

    function getItems(){return $this->_array;}
}

//testing it....
$utime = microtime(true);
$coll = new ItemCollection();
$coll->Add( new Item('apple',0,'a sour fruit') );
$coll->Add( new Item('pear',54,'delicious pears') );
$coll->Add( new Item('mango',245,'bread and butter') );

echo PHP_EOL,'sort by index, asc',PHP_EOL;
$coll->Sort('index',true);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}

echo PHP_EOL,'sort by index, desc',PHP_EOL;
$coll->Sort('index',false);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}

echo PHP_EOL,'sort by name, asc',PHP_EOL;
$coll->Sort('name',true);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}

echo PHP_EOL,'sort by name, desc',PHP_EOL;
$coll->Sort('name',false);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}
$utime = microtime(true)-$utime;
echo PHP_EOL,' sorting all took ',round(1000*$utime,2),' ms';
?>
Will Shaver 27-Aug-2009 02:31
An even better implementation of osort [than my original, posted on 24-AUG-09 (since deleted)], allowing for multiple properties and directions.  With php 5.3.0 sorting by properties of an object becomes MUCH simpler.  Note that this uses anonymous functions / closures. Might find reviewing the php docs on that useful.  Look below for examples for previous version of php.

<?php
function osort(&$array, $props)
{
    if(!is_array($props))
        $props = array($props => true);

    usort($array, function($a, $b) use ($props) {
        foreach($props as $prop => $ascending)
        {
            if($a->$prop != $b->$prop)
            {
                if($ascending)
                    return $a->$prop > $b->$prop ? 1 : -1;
                else
                    return $b->$prop > $a->$prop ? 1 : -1;
            }
        }
        return -1; //if all props equal
    });
}
?>

Usage:

<?php
osort($items, array("Color" => true, "Size" => false));
//or
osort($items, "Color");
?>
maarten at xel dot nl 17-Jul-2009 08:45
If you ever have to sort a collection of objects on something like a string (name) present in every object, but want to keep the array of objects intact you might find this useful:

<?php
function naturalSortObjectArray($objectArray) {
        function naturalSortByName($a, $b) {
            return strnatcmp($a->name, $b->name);
        }
        usort($objectArray, "naturalSortByName");
        return $objectArray;
}
?>
majkl578 at gmail dot com 25-Jun-2009 05:25
As of PHP 5.3 it is possible to use anonymous functions:

<?php
$arrayToSort = array(2,6,1,9,3);

/* As of PHP 5.3 */
usort($arrayToSort, function($a, $b) {
    return $a > $b ? 1 : -1;
});

var_dump($arrayToSort);

/* Returns:
array
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 6
  4 => int 9
*/
?>
phpguy at lifetoward dot com 11-Jun-2009 05:54
I recommend that you take special note of the fact that an INTEGER value must be returned from a sorting callback function. So, let's say you want to sort arrays by a quotient of two of their elements and to do so you write something like:
<?php
function sorter($a, $b)
{ return $a['num']/$a['denom'] - $b['num']/$b['denom']; }
?>

You may not get the result you want because probably $x['num']/$x['denom'] has absolute value less than 1 and you'll get a lot of "same value" effective results from the comparator function as integer rounding occurs.

To solve this just boost up the quotients to be big integers, then subtract them:

<?php
function sorter($a, $b)
{ return 1000*$a['num']/$a['denom'] - 1000*$b['num']/$b['denom']; }
?>
huskyr at gmail dot com 28-May-2009 06:04
Remember that functions inside of functions will become part of the global scope too. So, something like:

<?php
    function foo($array) {
        function compare($a,$b) {
            return $a < $b;
        }
        usort($array, "compare");
        return $array;
    }

    function bar($array) {
        function compare($a,$b) {
            return $a > $b;
        }
        usort($array, "compare");
        return $array;
    }

    foo($something);
    bar($something_else);
?>

Will result in a fatal error because you're redeclaring 'compare'. This could be a little strange, e.g. for JavaScript programmers who expect functions in functions to become private outside of the parent scope.
gmail.com - nmcquay 31-Mar-2009 12:25
I wrote a wrapper for usort that lets you use something similar to an SQL ORDER BY clause. It can sort arrays of associative arrays and arrays of objects and I think it would work with some hybrid case.

Example of how the function works:

<?php
$testAry = array(
  array('a' => 1, 'b' => 2, 'c' => 3),
  array('a' => 2, 'b' => 1, 'c' => 3),
  array('a' => 3, 'b' => 2, 'c' => 1),
  array('a' => 1, 'b' => 3, 'c' => 2),
  array('a' => 2, 'b' => 3, 'c' => 1),
  array('a' => 3, 'b' => 1, 'c' => 2)
);

Utility::orderBy($testAry, 'a ASC, b DESC');

//Result:
$testAry = array(
  array('a' => 1, 'b' => 3, 'c' => 2),
  array('a' => 1, 'b' => 2, 'c' => 3),
  array('a' => 2, 'b' => 3, 'c' => 1),
  array('a' => 2, 'b' => 1, 'c' => 3),
  array('a' => 3, 'b' => 2, 'c' => 1),
  array('a' => 3, 'b' => 1, 'c' => 2)
);
?>

To sort an array of objects you would do something like:
Utility::orderBy($objectAry, 'getCreationDate() DESC, getSubOrder() ASC');

This would sort an array of objects that have methods getCreationDate() and getSubOrder().

Here is the function:

<?php
class Utility {
    /*
    * @param array $ary the array we want to sort
    * @param string $clause a string specifying how to sort the array similar to SQL ORDER BY clause
    * @param bool $ascending that default sorts fall back to when no direction is specified
    * @return null
    */
    public static function orderBy(&$ary, $clause, $ascending = true) {
        $clause = str_ireplace('order by', '', $clause);
        $clause = preg_replace('/\s+/', ' ', $clause);
        $keys = explode(',', $clause);
        $dirMap = array('desc' => 1, 'asc' => -1);
        $def = $ascending ? -1 : 1;

        $keyAry = array();
        $dirAry = array();
        foreach($keys as $key) {
            $key = explode(' ', trim($key));
            $keyAry[] = trim($key[0]);
            if(isset($key[1])) {
                $dir = strtolower(trim($key[1]));
                $dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def;
            } else {
                $dirAry[] = $def;
            }
        }

        $fnBody = '';
        for($i = count($keyAry) - 1; $i >= 0; $i--) {
            $k = $keyAry[$i];
            $t = $dirAry[$i];
            $f = -1 * $t;
            $aStr = '$a[\''.$k.'\']';
            $bStr = '$b[\''.$k.'\']';
            if(strpos($k, '(') !== false) {
                $aStr = '$a->'.$k;
                $bStr = '$b->'.$k;
            }

            if($fnBody == '') {
                $fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n";
                $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
            } else {
                $fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody;
                $fnBody .= "}\n";
                $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
            }
        }

        if($fnBody) {
            $sortFn = create_function('$a,$b', $fnBody);
            usort($ary, $sortFn);
        }
    }
}
?>
luke dot semerau at gmail dot com 28-Mar-2009 12:25
If you need to use usort with a key in the calling method, I wrote this as a utility:
<?php

function usort_comparison($obj, $method, $key) {
    $usorter = &new Usort($obj, $method, $key);
    return array($usorter, "sort");
}

class Usort {
    function __construct($obj, $method, $key) {
        $this->obj = $obj;
        $this->method = $method;
        $this->key = $key;
    }
    function sort($a, $b) {
        return call_user_func_array(array($this->obj, $this->method), array($a, $b, $this->key));
    }
}

?>

<?php

require_once("util/usort.php");

class Foo {
    $items = array(FooBar(13), FooBar(2));
    public function sorter() {
        usort($this-items, usort_comparison("Foo", "_cmp", "item"));
    }

    public static function _cmp($a, $b, $key) {
         return strcasecmp($a->$key, $b->$key);
    }

}

class FooBar {
    public $item;
    function __construct($val) {
        $this->item = $val;
    }
}

?>

~ simple example... but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z)
fig dot miguel at gmail dot com 12-Feb-2009 04:29
I often need to order arrays by one dimension, therefore, I implemented a generic function, called "g_arr_dimsort":

<?php
function arr_dimsort_cmp($a,$b)
/*
 *      Compare function used when sorting arrays.
 */
{
  global $G_ARR_STYPE, $G_ARR_SDIM;

  /* -- Sort numbers? */

  if ($G_ARR_STYPE == 'NUMBER') {

      if ((float)$a[$G_ARR_SDIM] == (float)$b[$G_ARR_SDIM]) return 0;

      return (floatval($a[$G_ARR_SDIM]) > floatval($b[$G_ARR_SDIM])) ? 1: -1;
  }
  /* -- Sort strings? */

  if ($G_ARR_STYPE == 'STRING') return strcmp($a[$G_ARR_SDIM],$b[$G_ARR_SDIM]);

  /* -- First time: get the right data type */

  $G_ARR_STYPE = is_string($a[$G_ARR_SDIM])? 'STRING' : 'NUMBER';

  return arr_dimsort_cmp($a,$b);
}

function g_arr_dimsort(&$arr,$dim,$type = '',$keepkey = false)
/*
 *      Sort an array by a given dimension
 */
{
  global $G_ARR_SDIM, $G_ARR_STYPE;

  $G_ARR_SDIM = $dim; $G_ARR_STYPE = $type;

  if ($keepkey) uasort(&$arr,'arr_dimsort_cmp');
  else
      usort(&$arr,'arr_dimsort_cmp');
}

/* -- Testing it: */

$arr[] = array('Fruit' => 'Orange','Stock' => 10, 'Price'=> 10.2);
$arr[] = array('Fruit' => 'Lemon' ,'Stock' => 100,'Price'=> 5.36);
$arr[] = array('Fruit' => 'Apple' ,'Stock' => 20,'Price'=> 11.1);

echo "Sort by Fruit\n"; g_arr_dimsort(&$arr,'Fruit'); print_r($arr);
echo "Sort by Stock\n"; g_arr_dimsort(&$arr,'Stock','NUMBER'); print_r($arr);
echo "Sort by Fruit and keep keys\n"; g_arr_dimsort(&$arr,'Fruit','',true); print_r($arr);
echo "Sort by Price\n"; g_arr_dimsort(&$arr,'Price'); print_r($arr);

?>
Anonymous 12-Jan-2009 03:14
To sort reliably on more than one "column" in database-style arrays, handle this within your cmp function where the first field to be sorted returns 0:

<?php

function cmp($a, $b){

 if($a[field_1] == $b[field_1]){

  if($a[field_2] == $b[field_2]){

   return 0;

  }

  elseif($a[field_2] > $b[field_2]){

   return -1;

  }

  elseif($a[field_2] < $b[field_2]){

   return 1;

  }

 }

 elseif($a[field_1] > $b[field_1]){

  return -1;

 }

 elseif($a[field_1] < $b[field_1]){

  return 1;

 }

}

?>

Sorting by doing multiple passes does not seem to be reliable.
jalil at measat dot org 28-Dec-2008 05:37
<?php
/*---------------------------------------------------------
* my own home made easy object sort, which
* i cannot find anywhere on the net
* at all, tut. i can find only complicated ones,
* which brings me a headache.
*
* You can enhance it to return all sorts of error
* conditions if you wish,
* i need nothing but a false return upon failure to sort,
* so that is the only error i have here
*
* Example usage:
*
* INPUT                 -       $objects_array
// an array of objects for sorting

* PARAMETERS    -       property
// the property of the object to be sorted

* OUTPUT                -       $engine
// an engine object created by new,
// with your arrays of objects sorted according to your
// selected property
//( the sorting is done upon sort object creation )
*
* Code Examples
*
* $engine = new objSorter($objects_array);
// sorts on FIRST property -  default

* $engine = new objSorter($objects_array,'property');
// sort on ANY specific property
*--------------------------------------------------------*/

class objSorter
{
var $property;
var $sorted;

    function ObjSorter($objects_array,$property=null)
        {
            $sample    = $objects_array[0];
            $vars    = get_object_vars($sample);

        if (isset($property))
            {
            if (isset($sample->$property))
// make sure requested property is correct for the object
                {
                $this->property = $property;
                usort($objects_array, array($this,'_compare'));
                }
            else
                {
                $this->sorted    = false;
                return;
                }
            }
        else
            {
                list($property,$var)     = each($sample);
                $this->property         = $property;
                usort($objects_array, array($this,'_compare'));
            }

        $this->sorted    = ($objects_array);
        }

    function _compare($apple, $orange)
        {
        $property    = $this->property;
        if ($apple->$property == $orange->$property) return 0;
        return ($apple->$property < $orange->$property) ? -1 : 1;
        }
} // end class
?>

USAGE EXAMPLE
DUMP ORIGINAL
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )

SORTED by age

<?php
$objects                = new ObjSorter($objects_array,'age');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
?>

user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )

SORTED by richness

<?php
$objects                = new ObjSorter($objects_array,'richness');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
?>

user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )

Simulated wrong property request ( dumb property )

<?php
$objects                = new ObjSorter($objects_array,'dumb property');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
else echo 'DUMB ERROR';
?>

DUMB ERROR
drorasta 22-Jun-2008 10:16
Here's how you can usort() a multidimensional array (like in example #2 above) within a class:

<?php usort($myArray, array("className", "cmp")); ?>
Ariz Jacinto 13-May-2008 10:50
Here's how to use usort() within a class using a static function as a callback (using the example above):

<?php

class MyObj {
    var $name;

    function SampleObj($name){
        $this->name = $name;

        usort($this->name, array(&$this, "compareValues"));

    }

    static function compareValues($a, $b){
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

?>
Anonymous 14-Mar-2008 04:37
From the docs the user defined function looks as it could be arbitrary. This is not the case.
I needed a comparison that would send arbitrary values at the end of the array. Say '0' means invalid for example.
So here is a sample function.

<?php
function array_cmp($a, $b) {
  if( $a == 0 ) {
    return 99;
  } elseif( $a >  $b ) {
    return 1;
  } elseif( $a == $b ) {
    return 0;
  } elseif( $a <  $b ) {
    return -1;
  }
}

usort($test_array, "array_cmp");
print '<pre>'; print_r( $test_array ); print '</pre>';

$test_array = array(
   'a' => 8 ,
   'b' => 0 ,
   'c' => 1 ,
   'd' => 0 ,
   'e' => 3
 );

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 8
    [3] => 0
    [4] => 3
)
?>

This is beacause comparisons aren't applied to all possible pairs. So when the '0' is tested as $b strange things can occur...

This is solved simply adding an
  } elseif( $b == 0) {
    return -99;
  }
statement.

Carefull of the pitfalls. If you alter the ordering in strange ways without knowledge in the underlying algorithm one could even trigger infinite loops. (if your testing for $a and $b for the same value give inconsistent results. )
Sid_M 05-Nov-2007 05:54
The sample function for having the sort function be a class method has a comment identifying the sorting function as static, however the function does not have the static keyword. In PHP 5 (at least as configured on my server), usort will fail, identifying the method as non-static. Preceding the function keyword with the static keyword fixed the problem.
15-Mar-2007 05:12
A simple way of having reversed sort order from usort() function without using array_reverse() is to change "greater than" to "lesser that" sign (or vice versa) in the compare function.
Tim 13-Nov-2006 03:43
If you want to sort an array of strings by the length of its values, you can write a better cmp-function than manually comparing string lengths with if-statements. Unfortunately, I see this bad technique in other people's code. I prefer using this:

<?php
function length_cmp( $a, $b ) {
    return strlen($a)-strlen($b) ;
}
?>

This function sorts the array in ascending order. If you want to sort descending, simply swap $a and $b either in the parameters or in the subtraction.

-Tim
svenxy AT nospam gmx net 16-Oct-2006 01:58
This will sort subnets correctly:

<?php

$zones =
array('192.168.11',
'192.169.12',
'192.168.13',
'192.167.14',
'192.168.15',
'122.168.16',
'192.168.17'
);

function sort_subnets ($a, $b) {
    $a_arr = explode('.', $a);
    $b_arr = explode('.', $b);
    foreach (range(0,3) as $i) {
        if ( $a_arr[$i] < $b_arr[$i] ) {
            return -1;
        }
        elseif ( $a_arr[$i] > $b_arr[$i] ) {
            return 1;
        }
    }
    return -1;
}

usort($zones, 'sort_subnets');
print '<pre>';
print_r($zones);
print '</pre>';

?>
stephen in koto 05-Apr-2006 10:28
For using usort inside a method in an object, where the callback sort method is in the same object, this works:

<?php usort($arr_to_sort, array($this, "sort_terms_by_criteria")); ?>

If you wish to keep elements in their original or reverse order if they are the same length, just don't return zero for items that compare the same. Return a 1 or -1, as appropriate.
sydney at totoche dot org 16-Jan-2006 01:44
Instead of doing  :

<?php $strc = strcmp( strtolower($a[$f]), strtolower($b[$f]) ); ?>

you could do this :

<?php $strc = strcasecmp( $a[$f], $b[$f] ); ?>

which is more efficient and is does case insensitive comparison according to the current locale.
sean at NOSPAM dot orwd dot com 23-Sep-2005 02:46
In order to get a proper text sorting I have changed the arfsort() function submitted by jonathan(at)inetz(dot)com.

The one line I have changed is:

<?php
$strc = strcmp( $a[$f], $b[$f] );
?>

to

<?php
$strc = strcmp( strtolower($a[$f]), strtolower($b[$f]) );
?>

It can now sort correctly for alphabetization.  Capital letters where getting in the way.

Sean
Tim 22-Sep-2005 07:25
A couple examples here advocate the use of 'create_function' for sorting, which is tempting to use because of the limitations of usort. But beware this method -- the function created will NOT be freed at the end of the sorting routine, which creates a memory leak. For this reason, this method should probably never be used.

If you need multi-key or other complex sorting, the fundamental problem is passing in parameters into the comparison routine. I suggest creating a global variable (_array_key_multisort_parameters or something long), and controlling the comparison routine in that way.
rpmPUBLI at iespana dot es 03-Sep-2005 12:48
(I've browsed the docummented notes and I haven't found this note, so there I go):

Please note that, when sorting associative arrays (i.e. non-numeric indexes), these will be lost and replaced by a regular numeric index starting at 0.
reinhard at ess dot co dot at 08-Aug-2005 06:34
maybe someone can use this.
with that compare-function you can get this order:

string1, string2, ..., string10, string11, ...string22...

else the functions make something like

string10,string11,...string1,string20....
or
string1,string10,string11,string2,string20...

it's not the best solution, but works for my purpose...

<?php
function cmp($a,$b){
   list($a)=explode(".",$a);
   list($b)=explode(".",$b);
   $s=0;
   for($i=0;$i<=strlen($a);++$i){
      if(is_numeric($a[$i])&&is_numeric($b[$i])){
         $n=1;
         $anum=$bnum=0;
         while((is_numeric($a[$i])||is_numeric($b[$i]))&&
                    (strlen($a)>=$i||strlen($b)>=$i)){
            if(is_numeric($a[$i])&&$i<=strlen($a)) $anum=$a[$i]+$anum*$n;
            if(is_numeric($b[$i])&&$i<=strlen($b)) $bnum=$b[$i]+$bnum*$n;
            $n*=10;
            ++$i;
         }
         if($n>1) --$i;
         if($anum!=$bnum) return $anum<$bnum?-1:1;
      }elseif($a[$i]!=$b[$i]) return $a[$i]<$b[$i]?-1:1;
   }
}
?>

use it like this:

<?php
usort($array,"cmp");
?>
Jeremy Swinborne 20-Jul-2005 01:56
When I query a DB I usually put my record set inside of a multi-dimentional array.  I finally wrote a program that will allow you to sort your record set by column after you put it in an array.

<?php
$test = array();
$test[0]['name'] = 'jeremy';
$test[0]['email'] = 'lala@example.com';
$test[0]['phone'] = '123-123-1234';
$test[0]['trick'] = 'mezopia';

$test[1]['name'] = 'Amanda';
$test[1]['email'] = 'hot@example.com';
$test[1]['phone'] = '123-123-1235';
$test[1]['trick'] = 'youarecool';

$test[2]['name'] = 'john';
$test[2]['email'] = 'wowee@example.com';
$test[2]['phone'] = '123-123-3333';
$test[2]['trick'] = 'goneinanhour';

print_r(columnSort($test, 'name'));

function columnSort($unsorted, $column) {
    $sorted = $unsorted;
    for ($i=0; $i < sizeof($sorted)-1; $i++) {
      for ($j=0; $j<sizeof($sorted)-1-$i; $j++)
        if ($sorted[$j][$column] > $sorted[$j+1][$column]) {
          $tmp = $sorted[$j];
          $sorted[$j] = $sorted[$j+1];
          $sorted[$j+1] = $tmp;
      }
    }
    return $sorted;
}
?>
dmhouse at gmail dot com 19-Jul-2005 02:09
The easiest way to compare two integers is just to take the second away from the first. For example, say you wanted to sort by an integer property of an object. Your comparison function would look like this:

<?php
function compare_counts($a, $b) {
  return $a->count - $b->count;
}
?>

This works because you don't necessarily have to return -1, 0 or 1, the manual states any integer less than, equal to or greater than 0 is OK.
steve at tracorp dot com 12-Apr-2005 04:57
When sorting a large multi-dimensional array, I ran into an issue where the array was not being sorted either ascending or descending, even when it started in sorted order.  It turns out that the above note about the callback function returning an integer is true.  My comparison function was just a subtraction between two floating point numbers, and the result being a float produced very unpredictable results.
guenther dot stadler at gmx dot net 30-Mar-2005 02:25
Just something i stumbled about right now:
If the array consists of just one elemtent, the user-function is not called at all.

Although this surely makes sense, think of it if you want to use your order-function for adding extra data to your arrays...
ulrichUNDERSCOREalexis at yahoo dot com 04-Mar-2005 07:03
Please note that:
- the HTML entities should be replaced by their accented counterparts;
- the $patterns arrays have been split for display convenience.

<?php

/* returns the collated string (with no accent or with the matching string
 * replacement) in lower case according to that language rule.
 * The aim is to alphabetically sort lists of strings with characters from
 * other languages but using collation rules of that given language
 * (ISO 639-1 code).
 * Latin-derived alphabets are supported (currently English, French and
 * German)
 * rules source: http://en.wikipedia.org/wiki/Latin_alphabet
 */
function collatedLower($string, $lang=null) {
   switch ($lang) {
       case 'de':
           // German
        $patterns = array(
        "/&aacute;|&agrave;|&acirc;|&atilde;|&aring;|
&Aacute;|&Agrave;|&Acirc;|&Atilde;|&Aring;/",
        "/&auml;|&aelig;|&Auml;|&AElig;/",
        "/&ccedil;|&Ccedil;/",
        "/&eacute;|&egrave;|&ecirc;|&euml;|
&Eacute;|&Egrave;|&Ecirc;|&Euml;/",
        "/&igrave;|&iacute;|&icirc;|&iuml;|
&Igrave;|&Iacute;|&Icirc;|&Iuml;/",
        "/&ntilde;|&Ntilde;/",
        "/&ograve;|&oacute;|&ocirc;|&otilde;|&oslash;|
&Ograve;|&Oacute;|&Ocirc;|&Otilde;|&Oslash;/",
        "/&ouml;|&oelig;|&Ouml;|&OElig;/",
        "/&szlig;/",
        "/&ugrave;|&uacute;|&ucirc;|
&Ugrave;|&Uacute;|&Ucirc;/",
        "/&uuml;|&Uuml;/",
        "/&yacute;|&yuml;|&Yacute;/");
           $replace = array('a', 'ae', 'c', 'e', 'i', 'n', 'o', 'oe', 'ss', 'u', 'ue', 'y');
           break;
       default:
           // 'en' (English), 'fr' (French)
           $patterns = array(
        "/&aacute;|&agrave;|&acirc;|&atilde;|&auml;|&aring;|
&Aacute;|&Agrave;|&Acirc;|&Atilde;|&Auml;|&Aring;/",
        "/&aelig;|&AElig;/",
        "/&ccedil;|&Ccedil;/",
        "/&eacute;|&egrave;|&ecirc;|&euml;|
&Eacute;|&Egrave;|&Ecirc;|&Euml;/",
        "/&igrave;|&iacute;|&icirc;|&iuml;|
&Igrave;|&Iacute;|&Icirc;|&Iuml;/",
        "/&ntilde;|&Ntilde;/",
        "/&ograve;|&oacute;|&ocirc;|&otilde;|&ouml;|&oslash;|
&Ograve;|&Oacute;|&Ocirc;|&Otilde;|&Ouml;|&Oslash;/",
        "/&oelig;|&OElig;/",
        "/&szlig;/",
        "/&ugrave;|&uacute;|&ucirc;|&uuml;|
&Ugrave;|&Uacute;|&Ucirc;|&Uuml;/",
        "/&yacute;|&yuml;|&Yacute;/");
           $replace = array('a', 'ae', 'c', 'e', 'i', 'n', 'o', 'oe', 'ss', 'u', 'y');
           break;
       }
   return preg_replace($patterns,$replace,$string);
}

// English
function compareAccents_en($a, $b) {
   return compareAccents($a, $b, 'en');
}

// French
function compareAccents_fr($a, $b) {
   return compareAccents($a, $b, 'fr');
}

// German
function compareAccents_de($a, $b) {
   return compareAccents($a, $b, 'de');
}

/*
 * comparison function to group together accented letters with
 * their lower-case non-accented counterparts
 * the $lang parameter enables sorting rules for that language
 * (ISO 639-1 code)
 */
function compareAccents($a, $b, $lang=null) {
   $anew = strtolower(collatedLower($a,$lang));
   $bnew = strtolower(collatedLower($b,$lang));
   if ($anew < $bnew) return -1;
   if ($anew > $bnew) return 1;
   return 0;
}

// usage:
usort($myList,'compareAccents_fr');

// to be compared to:
setlocale(LC_COLLATE,'fr');
usort($myList, 'strcoll');

?>
Raveler at telenet dot be 20-May-2004 10:02
The array_alternate_multisort function written by robert below doesn't work. There are several bugs in the code and it doesn't work when sorting by multiple keys because the order of the first key isn't taken into account when sorting by the second key and so on. Also, because robert uses strcasecmp the algorithm doesn't work properly with floats or other variable types. Here's the improved version:

<?php
    function SortArray() {
        $arguments = func_get_args();
        $array = $arguments[0];
        $code = '';
        for ($c = 1; $c < count($arguments); $c += 2) {
            if (in_array($arguments[$c + 1], array("ASC", "DESC"))) {
                $code .= 'if ($a["'.$arguments[$c].'"] != $b["'.$arguments[$c].'"]) {';
                if ($arguments[$c + 1] == "ASC") {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? -1 : 1); }';
                }
                else {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? 1 : -1); }';
                }
            }
        }
        $code .= 'return 0;';
        $compare = create_function('$a,$b', $code);
        usort($array, $compare);
        return $array;
    }
?>
todor at todor dot net 08-Mar-2004 04:39
To sort multidimentional arrays .... by one key.

<?php
function multi_sort($tab,$key){
    $compare = create_function('$a,$b','if ($a["'.$key.'"] == $b["'.$key.'"]) {return 0;}else {return ($a["'.$key.'"] > $b["'.$key.'"]) ? -1 : 1;}');
    usort($tab,$compare) ;
    return $tab ;
}
?>
arjini at mac dot com 26-Jan-2004 10:05
<?php
/*
This is a class I built to sort parent/child relationships of array elements.
I post this here, because thanks to usort, you can also assign an explicit order
to the elements.

I first built this to sort categories and subcategories.

My database has four fields. category_id, parent_id, category_name, category_position

$rows is an associative array from the database with my categories.
*/
$rows = array( 0=>array('category_id'=>1,'parent_id' =>3,'category_name' =>'Second Child','category_position'=>2),
                    1=>array('category_id' =>2,'parent_id' =>0,'category_name' =>'Second Parent','category_position'=>2),
                    2=>array('category_id' =>3,'parent_id' =>0,'category_name' =>'First Parent','category_position'=>1),
                    3=>array('category_id' =>4,'parent_id' =>0,'category_name' =>'Third Parent','category_position'=>3),
                    4=>array('category_id' =>5,'parent_id' =>3,'category_name' =>'First Child','category_position'=>1),
                    5=>array('category_id' =>6,'parent_id' =>5,'category_name'=>'Second Sub-Child','category_position'=>2),
                    6=>array('category_id' =>7,'parent_id' =>5,'category_name' =>'First Sub-Child','category_position'=>1)
                    );

$ordered = chain('category_id', 'parent_id', 'category_position', $rows);

foreach($ordered as $item)
{
    echo str_repeat('------', $item['indent']).$item['category_name'].'<br>';
}

/*

Output

First Parent
------First Child
------------First Sub-Child
------------Second Sub-Child
------Second Child
Second Parent
Third Parent

You can have it only return a certain "branch" if you specify a root_id.
Aditionally, you can keep it by going to deep by specifying max-level.

Hope someone finds this useful, I sure would have liked to see this here a week ago.

Ah yes... and the code that runs it.
*/

function chain($primary_field, $parent_field, $sort_field, $rows, $root_id=0, $maxlevel=25)
{
    $c = new chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel);
    return $c->chain_table;
}

class chain
{
    var $table;
    var $rows;
    var $chain_table;
    var $primary_field;
    var $parent_field;
    var $sort_field;

    function chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel)
    {
        $this->rows = $rows;
        $this->primary_field = $primary_field;
        $this->parent_field = $parent_field;
        $this->sort_field = $sort_field;
        $this->buildChain($root_id,$maxlevel);
    }

    function buildChain($rootcatid,$maxlevel)
    {
        foreach($this->rows as $row)
        {
            $this->table[$row[$this->parent_field]][ $row[$this->primary_field]] = $row;
        }
        $this->makeBranch($rootcatid,0,$maxlevel);
    }

    function makeBranch($parent_id,$level,$maxlevel)
    {
        $rows=$this->table[$parent_id];
        foreach($rows as $key=>$value)
        {
            $rows[$key]['key'] = $this->sort_field;
        }

        usort($rows,'chainCMP');
        foreach($rows as $item)
        {
            $item['indent'] = $level;
            $this->chain_table[] = $item;
            if((isset($this->table[$item[$this->primary_field]])) && (($maxlevel>$level+1) || ($maxlevel==0)))
            {
                $this->makeBranch($item[$this->primary_field], $level+1, $maxlevel);
            }
        }
    }
}

function chainCMP($a,$b)
{
    if($a[$a['key']] == $b[$b['key']])
    {
        return 0;
    }
    return($a[$a['key']]<$b[$b['key']])?-1:1;
}

?>
sreid at sea-to-sky dot net 07-Jan-2004 08:22
As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal.

Sometimes you really do need a stable sort. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field. In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below. It is a merge sort, which is guaranteed O(n*log(n)) complexity, which means it stays reasonably fast even when you use larger lists (unlike bubblesort and insertion sort, which are O(n^2)).

<?php
function mergesort(&$array, $cmp_function = 'strcmp') {
    // Arrays of size < 2 require no action.
    if (count($array) < 2) return;
    // Split the array in half
    $halfway = count($array) / 2;
    $array1 = array_slice($array, 0, $halfway);
    $array2 = array_slice($array, $halfway);
    // Recurse to sort the two halves
    mergesort($array1, $cmp_function);
    mergesort($array2, $cmp_function);
    // If all of $array1 is <= all of $array2, just append them.
    if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
        $array = array_merge($array1, $array2);
        return;
    }
    // Merge the two sorted arrays into a single sorted array
    $array = array();
    $ptr1 = $ptr2 = 0;
    while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
        if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
            $array[] = $array1[$ptr1++];
        }
        else {
            $array[] = $array2[$ptr2++];
        }
    }
    // Merge the remainder
    while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
    while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
    return;
}
?>
webmaster at zeroweb dot org 20-Dec-2003 03:05
Needed a quick, fairly uncluttered way of sorting an array of objects by a certain object attribute, so here's what I came up with. Uses one global array and usort(). Also accepts an optional sort direction argument (CSORT_ASC = sort ascending, CSORT_DESC = sort descending). Use it like this:

(assuming $myarray is your array, "index" is the attribute you want to sort by, and you want to sort in descending order)

      csort($myarray, "index", CSORT_DESC);

Hope this is of use to someone. Probably a better way to pull this off, but this works alright.

<?php
define("CSORT_ASC",     1);
define("CSORT_DESC",     -1);

function csort_cmp(&$a, &$b)
{
    global $csort_cmp;

    if ($a->$csort_cmp['key'] > $b->$csort_cmp['key'])
        return $csort_cmp['direction'];

    if ($a->$csort_cmp['key'] < $b->$csort_cmp['key'])
        return -1 * $csort_cmp['direction'];

    return 0;
}

function csort(&$a, $k, $sort_direction=CSORT_ASC)
{
    global $csort_cmp;

    $csort_cmp = array(
        'key'           => $k,
        'direction'     => $sort_direction
    );

    usort($a, "csort_cmp");

    unset($csort_cmp);
}
?>
kristen at ccshoreline dot org 22-Nov-2003 12:39
I have a class with a bunch of functions that work with an SQL database. I am working with calendar dates that occur more than once (like once a week for 2 months), so I have to generate the date in php after the SQL. But I wanted to sort the events based on the date, so I tried using usort, but was unable to get it to work, because it didn't think that my sorting function was defined (even though it was in the same class). I have a separate class to store the data, that has a variable called Start which is a PHP date object.

So here is how I got it to work. First I created a temporary function, that returned the value of a string comparison of the timestamps for the dates. Then I used that temporary function for the usort. Enjoy.

<?php
$tempfunction = create_function('$event1,$event2',
        'return strcmp($event1->Start[0],$event2->Start[0]);');
usort($data,$tempfunction);
?>
skrebbel at operamail dot com 27-Mar-2003 01:59
here's another recursive multisort, however a clean and fast one that is class-based (but works as well outside classes) and does not uglify your global namespace at all. note that strnatcmp is used, but one could use something else of course.

btw, for arrays in which the rows/columns are 'swapped', use array_multisort().

<?php
class Banana {
    var $aData;//the array we want to sort.
    var $aSortkeys;//the order in which we want the array to be sorted.
    function _sortcmp($a, $b, $i=0) {
        $r = strnatcmp($a[$this->aSortkeys[$i]],$b[$this->aSortkeys[$i]]);
        if($r==0) {
            $i++;
            if ($this->aSortkeys[$i]) $r = $this->_sortcmp($a, $b, $i+1);
        }
        return $r;
    }
    function sort() {
        if(count($this->aSortkeys)) {
            usort($this->aData,array($this,"_sortcmp"));
        }
    }
}
$B = new Banana;
$B->aData = array(
    array("name" => "hank", "headsize" => "big", "age" => 32),
    array("name" => "frank", "headsize" => "huge", "age" => 36)
);
$B->aSortkeys = array("age","name");
$B->sort();

?>
sorry for the ugly indenting, but i couldn't get it any better in this note adder thing.
steveNO_SPAM at AXE_MEcontentwatch dot com 31-Dec-2002 02:11
The sort functions do nothing if identical keys exist.  Of course, you shouldn't have identical keys anyway, but this just might save someone else the oodles of time it took me to figure out while using multi-dimentional arrays:

<?php
class myArticleList {
// ... //
  function &getList () {

    // works
        $a = array (
                   "articleList1" => array ( "2", "3" ),
                   "articleList2" => array ( "3" , "4")
                 );
    usort( $a, array( $this, "compareByTitle") );

    // doesn't work
        $b = array (
                   "articleList" => array ( "2", "3" ),
                   "articleList" => array ( "3" , "4")
                 );
    usort( $b, array( $this, "compareByTitle") );
  }

  function compareByTitle( $a, $b ) {
  // ... //
  }
}
?>
mharrodine AT blue yonder DOT co-uk 11-Dec-2002 04:46
I like to define my arrays to look like tables in a database or spreadsheet as follows (it looks tidy is the only reason!):

Row(s)  Column(s) ------------->
   |        $array[0] = array("1", "2","3");
   |        $array[1] = array("1", "2","3");
   \/       $array[2] = array("1", "2","3");

This "array of arrays" seems to behave differently to normal associative or multi-dimension arrays when sorting but using franky's routine....

<?php
function cmp ($a, $b)
{
global $w_o;
if ($a[$w_o] == $b[$w_o]) return 0;
return ($a[$w_o] < $b[$w_o]) ? -1 : 1;
}
?>

...you simply specify the column you want to sort by defining $w_o and call "usort($my_array,"cmp");". This might seem obvious to some people but wasn't to me and I hope this helps others in the same situation. Thanks....
jfren484 AT hotmail DOT com 24-Oct-2002 04:37
If you've used ADO before, you may have used the Sort property on a recordset.  It's very powerful - you can add a nice ORDER BY clause after getting the recordset from the database.  It's especially helpful if you want to show a list on a web page and make the column headings links that cause the list to resort on that column.

I wanted to do the same thing with mysql recordsets, but it looks like you have to have the ORDER BY in your query.  I re-worked the example from johan_land at yahoo dot com above for sorting multidimensional arrays.  When I get a mysql recordset, I create an array with all of the records like this:

<?php
$aaRows[]    = array();
if (mysql_num_rows($rsRows) > 0)
    while ($aRow = mysql_fetch_array($rsRows, MYSQL_ASSOC))
        $aaRows[]    = $aRow;
?>

At this point $aaRows is an array of arrays - it's a numeric-indexed array containing records from the recordset, which themselves are associative arrays.  The following code takes the array of records as the first parameter, and an array of fields to sort - each field is an associative array, where 'name' is the db field name, and 'dir' is the direction to sort.  If dir is 'DESC' (case-insensitive), it will sort descending.  Any other value (including not setting one) will cause it to sort ascending.

<?php
function sortRows(&$a_aaRows, $a_aaSortCriteria)
{
    GLOBAL    $g_aaSortArray;

    function compare($a_aRow1, $a_aRow2, $a_lField = 0)
    {
        GLOBAL    $g_aaSortArray;

        $lCompareVal    = 0;

        if ($a_lField < count($g_aaSortArray))
        {
            $sSortFieldName    = $g_aaSortArray[$a_lField]['name'];
            $sSortFieldDir    = $g_aaSortArray[$a_lField]['dir'];

            $vValue1    = eval('return $a_aRow1[' . $sSortFieldName . '];');
            $vValue2    = eval('return $a_aRow2[' . $sSortFieldName . '];');

            if ($vValue1 == $vValue2)
                $lCompareVal    = compare($a_aRow1, $a_aRow2, $a_lField + 1);
            else
            {
                $lCompareVal    =    $vValue1 > $vValue2 ? 1 : -1;
                if (strtolower(substr($sSortFieldDir, 0, 4)) == 'desc')
                    $lCompareVal    = -$lCompareVal;
            }
        }

        return $lCompareVal;
    }

    $g_aaSortArray    = $a_aaSortCriteria;
    usort($a_aaRows, 'compare');
}
?>

When I call it it looks something like this:

<?php
sortRows($aaRows, array(array('name' => 'STATE', 'dir' => 'ASC'), array('name' => 'CITY', 'dir' => 'DESC')));
?>
mkr at binarywerks dot dk 20-Sep-2002 09:29
If you want to sort an array according to another array acting as a priority list, you can use this function.

<?php
function listcmp($a, $b)
{
  global $order;

  foreach($order as $key => $value)
    {
      if($a==$value)
        {
          return 0;
          break;
        }

      if($b==$value)
        {
          return 1;
          break;
        }
    }
}

$order[0] = "first";
$order[1] = "second";
$order[2] = "third";

$array[0] = "second";
$array[1] = "first";
$array[2] = "third";
$array[3] = "fourth";
$array[4] = "second";
$array[5] = "first";
$array[6] = "second";

usort($array, "listcmp");

print_r($array);
?>
simen at NO_SPAM_AT_ALLbleed dot no 06-Aug-2002 01:16
To sort a list of objects either ascending (a) or descending (d) using key use the function below for comparison.

<?php
function property_sort($oa, $ob) {
    global $sort_key;
    global $sort_dir;

    $a = strtolower($oa->$sort_key);
    $b = strtolower($ob->$sort_key);

    if ($a == $b) {
        return 0;
    } else if (($a > $b && $sort_dir == "a") || ($a < $b && $sort_dir == "d")) {
        return 1;
    } else {
        return -1;
    }
}
?>
prozac at iguanasoft dot com 15-Jul-2002 05:55
Here is a simple example of converting a timestamp date("U") into a date. This sorts by that day and then by string value alphabetically.

I hope it saves someone some time... Happy PHP'in!

<?php
//data to sort
$shared[0]["page_id"] = "2025731470";
$shared[1]["page_id"] = "2025731450";
$shared[2]["page_id"] = "1025731456";
$shared[3]["page_id"] = "1025731460";
$shared[0]["username"] = "larry";
$shared[1]["username"] = "alvin";
$shared[2]["username"] = "garth";
$shared[3]["username"] = "harvy";

//function to convert timestamp to date
function convert_timestamp($timestamp){
    $limit=date("U");
    $limiting=$timestamp-$limit;
    return date ("Ymd", mktime (0,0,$limiting));
}
//comparison function
function cmp ($a, $b) {
    $l=convert_timestamp($a["page_id"]);
    $k=convert_timestamp($b["page_id"]);
    if($k==$l){
        return strcmp($a["username"], $b["username"]);
    }else{
        return strcmp($k, $l);
    }
}

//sort array
usort($shared, "cmp");

//display sorted info
while (list ($key, $value) = each ($shared)) {
    echo "\$shared[$key]: ";
    echo $value["page_id"];
    echo " username: ";
    echo $value["username"];
    echo "<break_tag>";
}
?>

This will output:
$shared[0]: 2025731450   username: alvin
$shared[1]: 2025731470   username: larry
$shared[2]: 1025731456   username: garth
$shared[3]: 1025731460   username: harvy
alex at netflex dot nl 02-Jul-2002 04:10
This function will sort on more then one values, test and have fun

<pre>
<?php

  $array[0]['name'] = "a";
  $array[0]['id'] = 3;

  $array[1]['name'] = "a";
  $array[1]['id'] = 2;

  $array[2]['name'] = "a";
  $array[2]['id'] = 5;

  $array[3]['name'] = "b";
  $array[3]['id'] = 8;

  $array[4]['name'] = "b";
  $array[4]['id'] = 1;

  $array[5]['name'] = "b";
  $array[5]['id'] = 0;

  $array[6]['name'] = "c";
  $array[6]['id'] = 5;

  $array[7]['name'] = "c";
  $array[7]['id'] = 7;

  $array[8]['name'] = "c";
  $array[8]['id'] = 3;

  print_r($array);

  $sort_array[0]['name'] = "name";
  $sort_array[0]['sort'] = "ASC";
  $sort_array[0]['case'] = TRUE;

  $sort_array[1]['name'] = "id";
  $sort_array[1]['case'] = FALSE;

  sortx($array, $sort_array);

  print_r($array);

  function sortx(&$array, $sort = array()) {
    $function = '';
    while (list($key) = each($sort)) {
      if (isset($sort[$key]['case'])&&($sort[$key]['case'] == TRUE)) {
        $function .= 'if (strtolower($a["' . $sort[$key]['name'] . '"])<>strtolower($b["' . $sort[$key]['name'] . '"])) { return (strtolower($a["' . $sort[$key]['name'] . '"]) ';
      } else {
        $function .= 'if ($a["' . $sort[$key]['name'] . '"]<>$b["' . $sort[$key]['name'] . '"]) { return ($a["' . $sort[$key]['name'] . '"] ';
      }
      if (isset($sort[$key]['sort'])&&($sort[$key]['sort'] == "DESC")) {
        $function .= '<';
      } else {
        $function .= '>';
      }
      if (isset($sort[$key]['case'])&&($sort[$key]['case'] == TRUE)) {
        $function .= ' strtolower($b["' . $sort[$key]['name'] . '"])) ? 1 : -1; } else';
      } else {
        $function .= ' $b["' . $sort[$key]['name'] . '"]) ? 1 : -1; } else';
      }
    }
    $function .= ' { return 0; }';
    usort($array, create_function('$a, $b', $function));
  }

?>
</pre>
graham at irwin dot org 15-Jan-2002 08:28
Example 3 above does not work with 4.0.4pl1, unless you write the uasort line as follows:
uasort($a, array ($a[0], "cmp_obj"));

(I assume any instance of the object: a[0] or a[1] or a[2] would work as well)

It does not work at all with associative arrays of objects.
xnoguer at rezebra dot com 25-Sep-2001 11:48
just for debugging purposes, usort does not complain if its argument function is not defined, i.e.:

<?php usort($my_array,"non existant function"); ?>

will not do anything...
josh at wintelcom dot net 24-Aug-2001 06:58
This lets you sort an associative multi-dimensional array by multiple key/field names.  Much similiar to the SQL clause ORDER BY.  Enjoy.

<?php
function cmp ($a, $b) {

    // Populate this array with your values...
    // Below is the SQL equivalent of
    // select * from blah ORDER BY date desc, type asc, name asc

    $vals = array(
        'date' => 'd',
        'type' => 'a',
        'name' => 'a'
    );

    while(list($key, $val) = each($vals)) {

        if($val == "d") {
            if ($a["$key"] > $b["$key"]) {
                return -1;
            }
            if ($a["$key"] < $b["$key"]) {
                return 1;
            }
        }

        if($val == "a") {
            if ($a["$key"] < $b["$key"]) {
                return -1;
            }
            if($a["$key"] > $b["$key"]) {
                return 1;
            }
        }

    }

}
?>
franky at iname dot com 17-Jul-2001 03:08
For sort multi-array by specific index

<?php
function cmp ($a, $b)
{
 global $w_o;
 if ($a[$w_o] == $b[$w_o]) return 0;
 return ($a[$w_o] < $b[$w_o]) ? -1 : 1;
}
# the index is the second element of
# each row

$w_o =1;
usort($my_arry_info,"cmp");
?>
johan_land at yahoo dot com 29-Jun-2001 05:23
These functions will sort an array by more than one element. The elements to sort by is specified in $sortArr. If you eg. want to sort by $destArr[]["sortBy2"][0] you add '["sortBy2"][0]' to $sortArr. Use it as much as you want!! If you modify it, please let me know...

<?php
//The functions
function compare($a, $b) {
    return cmpRec(0, $a, $b);
}

function cmpRec($i, $a, $b) {
    global $sortArr;
    if($i == sizeof($sortArr)) {
        return 0;
    }
    $avalue = '$avalue = $a'.$sortArr[$i].';';
    $bvalue = '$bvalue = $b'.$sortArr[$i].';';
    eval($avalue);
    eval($bvalue);
        if($avalue == $bvalue) {
        return cmpRec($i+1, $a, $b);
    } else {
        return ($avalue > $bvalue) ? (1) : (-1);
    }
}

//For testing the functions
$destArr = array( array( "sortBy1" => 2, "sortBy2" => array( "Fish", "eat seafood" )), array( "sortBy1" => 1, "sortBy2" => array( "Lions", "eat everything" )), array( "sortBy1" => 1, "sortBy2" => array( "Bird", "eat birdfood" )) );
$sortArr = array( '["sortBy1"]', '["sortBy2"][0]' );
print_r($destArr);
usort($destArr, "compare");
reset($destArr);
print_r($destArr);
?>
bo at erichsen dot com 20-Mar-2001 05:16
when using usort to refer to a function inside a class i have succesfully used:

<?php usort($myarray,array($this,"cmp")); ?>
derek at luddite dot net 18-Sep-2000 11:35
Needed a date sort and I didn't know if one was available so I wrote one. Maybe it'll help someone:

<?php
function DateSort($a,$b,$d="-") {
    if ($a == $b) {
        return 0;
    } else {  //Convert into dates and compare
        list($am,$ad,$ay)=split($d,$a);
        list($bm,$bd,$by)=split($d,$b);
        if (mktime(0,0,0,$am,$ad,$ay) < mktime(0,0,0,$bm,$bd,$by)) {
            return -1;
        } else {
            return 1;
        }
    }
}
?>

$d is the delimeter
uksort
Классы/Объекты
Функции для работы с массивами


Функции работы с Классами/Объектами

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
  • Классы/Объекты
    • __autoload — Attempt to load undefined class
    • call_user_method_array — Вызывает метод объекта с массивом параметров [устаревшее]
    • call_user_method — Вызывает метод указанного объекта [устаревшее]
    • class_alias — Создает псевдоним для указанного класса
    • class_exists — Проверяет, был ли объявлен класс
    • get_called_class — Имя класса, полученное с помощью позднего статического связывания
    • get_class_methods — Возвращает массив имен методов класса
    • get_class_vars — Возвращает объявленные по умолчанию свойства класса
    • get_class — Возвращает имя класса, к которому принадлежит объект
    • get_declared_classes — Возвращает массив с именами объявленных классов
    • get_declared_interfaces — Возвращает массив всех объявленных интерфейсов
    • get_declared_traits — Returns an array of all declared traits
    • get_object_vars — Возвращает свойства указанного объекта
    • get_parent_class — Возвращает имя родительского класса для объекта или класса
    • interface_exists — Проверяет, определен ли интерфейс
    • is_a — Проверяет, принадлежит ли объект к данному классу или содержит данный класс в числе своих предков
    • is_subclass_of — Проверяет, содержит ли объект в своем дереве предков указанный класс
    • method_exists — Проверяет, существует ли метод в данном классе
    • property_exists — Проверяет, содержит ли объект или класс указанный атрибут
    • trait_exists — Checks if the trait exists

User Contributed Notes

There are no user contributed notes for this page.
usort
Введение
Расширения, относящиеся к переменным и типам


Введение

Эти функции позволяют получить информацию о классах и экземплярах объектов. Вы можете получить имя класса, которому принадлежит объект, равно как и все его свойства и методы. Используя эти функции, вы сможете установить не только принадлежность объекта к конкретному классу, но и определить порядок наследования (к примеру, какой класс наследует класс данного объекта).

User Contributed Notes

There are no user contributed notes for this page.
Классы/Объекты
Установка и настройка
Классы/Объекты


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Классы/Объекты


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
Классы/Объекты


Примеры

В приведённом ниже примере, мы сначала определим базовый класс и класс его наследующий. Базовый класс описывает овощ: съедобен ли и какого внешне цвета. Дочерний класс Spinach добавляет метод приготовления овоща и проверки -- был ли он уже приготовлен.

Пример #1 classes.inc

<?php

// базовый класс с основными свойствами и методами
class Vegetable {

    var $edible;
    var $color;

    function Vegetable($edible, $color="green")
    {
        $this->edible = $edible;
        $this->color = $color;
    }

    function is_edible()
    {
        return $this->edible;
    }

    function what_color()
    {
        return $this->color;
    }

} // конец класса Vegetable

// расширяет базовый класс
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach()
    {
        $this->Vegetable(true, "green");
    }

    function cook_it()
    {
        $this->cooked = true;
    }

    function is_cooked()
    {
        return $this->cooked;
    }

} // конец класса Spinach

?>

Теперь мы создадим по объекту каждого класса и распечатаем информацию о них, включая порядок их наследования. Также мы объявим несколько функций-утилит, главным образом для удобного вывода результатов.

Пример #2 test_script.php

<pre>
<?php

include "classes.inc";

// функции-утилиты

function print_vars($obj)
{
    $arr = get_object_vars($obj);
    while (list($prop, $val) = each($arr))
        echo "\t$prop = $val\n";
}

function print_methods($obj)
{
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method)
        echo "\tfunction $method()\n";
}

function class_parentage($obj, $class)
{
    if (is_subclass_of($GLOBALS[$obj], $class)) {
        echo "Object $obj belongs to class " . get_class($$obj);
        echo " a subclass of $class\n";
    } else {
        echo "Object $obj does not belong to a subclass of $class\n";
    }
}

// создание экземпляров объектов

$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();

// распечатка информации об объектах
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";

// показать свойства объекта класса Spinach
echo "\nveggie: Properties\n";
print_vars($veggie);

// и методы объекта базового класса Vegetable
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

Важно заметить, что в приведенном выше примере объект $leafy -- экземпляр класса Spinach, который наследует класс Vegetable, вследствие чего последняя часть скрипта выведет:

       [...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Классы/Объекты
Классы/Объекты


Классы/Объекты
PHP Manual

Классы/Объекты

Содержание

  • __autoload — Attempt to load undefined class
  • call_user_method_array — Вызывает метод объекта с массивом параметров [устаревшее]
  • call_user_method — Вызывает метод указанного объекта [устаревшее]
  • class_alias — Создает псевдоним для указанного класса
  • class_exists — Проверяет, был ли объявлен класс
  • get_called_class — Имя класса, полученное с помощью позднего статического связывания
  • get_class_methods — Возвращает массив имен методов класса
  • get_class_vars — Возвращает объявленные по умолчанию свойства класса
  • get_class — Возвращает имя класса, к которому принадлежит объект
  • get_declared_classes — Возвращает массив с именами объявленных классов
  • get_declared_interfaces — Возвращает массив всех объявленных интерфейсов
  • get_declared_traits — Returns an array of all declared traits
  • get_object_vars — Возвращает свойства указанного объекта
  • get_parent_class — Возвращает имя родительского класса для объекта или класса
  • interface_exists — Проверяет, определен ли интерфейс
  • is_a — Проверяет, принадлежит ли объект к данному классу или содержит данный класс в числе своих предков
  • is_subclass_of — Проверяет, содержит ли объект в своем дереве предков указанный класс
  • method_exists — Проверяет, существует ли метод в данном классе
  • property_exists — Проверяет, содержит ли объект или класс указанный атрибут
  • trait_exists — Checks if the trait exists

User Contributed Notes

Skydev 05-Jan-2011 11:40
A small function that allows finding all references to the object. Written in 3 minutes and may be buggy (for ex pass object as reference in some places?)

<?php
function find_ref_obj($object, $obj, $path) {
    if (in_array($obj,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$obj;
    $r = array();
    foreach ((array)$obj as $k => $v) {
        if ($v === $object)
            $r[] = $path . "->$k";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_ref_arr($object, $arr, $path) {
    if (in_array($arr,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$arr;
    $r = array();
    foreach ($arr as $k => $v) {
        if ($v === $object)
            $r[] = $path . "['$k']";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_references($object) {
    $r = array();
    $GLOBALS['__REF_CHECKED']=array();
    foreach ($GLOBALS as $n => $v)
    if ($n!='__REF_CHECKED')
    if ($n!='GLOBALS') {
        if ($v === $object)
            $r[]=$n;
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    unset($GLOBALS['__REF_CHECKED']);
    return $r;
}

function find_refs($object) {
    return implode(', ',find_references($object));
}
?>
Dennis 01-Jul-2010 04:04
We have an array with many objects in a style like

<?php

$step = new StepModel(1); // if the StepModel id is "1"
$demand = $step->getDemand(); // returns DemandModel
$step2 = $demand->getCustomer(); // returns StepModel
$demand2 = $step2->getDemand(); // returns DemandModel

// [ ... ]

?>

$step and $step2 can be the same objects. So we have an recursive array. Now we need to know if $step == $step2 or $step === $step2. In other words: We need to know the php internal resource ids.

Because there is no function in php api, we made the following function.

Be careful: In our case, all objects have as first attribute ["id":protected]. If your objects are different from this, you need to edit $pattern.

Warning: function is very slow and should only be called if it's necessary for debugging reasons:

<?php

/**
 * returns resource- and object-ids of all objects in an array
 *
 * @param array $array
 * @return array
 */
function getObjectInformation(Array $array)
{
    // start output-buffering
    ob_start();

    // create an var_dump of $array
    var_dump($array);

    // save the dump in var $dump
    $dump = ob_get_contents();

    // clean the output-buffer
    ob_end_clean();

    // delete white-spaces
    $dump = str_replace(' ', '', $dump);

    // define the regex-pattern
    // in our case, all objects look like this:
    //
    // object(ClassName)#1(1){
    // ["id":protected]=>
    // string(1)"1"
    $pattern  = '/object\(([a-zA-Z0-9]+)\)#([0-9]+)\([0-9]+\){\\n';
    $pattern .= '\["id":protected\]=>\\n';
    $pattern .= 'string\([0-9]+\)"([v]?[0-9]+)"/im';

    // search for all matches
    preg_match_all($pattern, $dump, $regs);

    // sort all mathes by class name, object id and then resource id
    array_multisort($regs[1], SORT_ASC, SORT_STRING,
                    $regs[3], SORT_ASC, SORT_NUMERIC,
                    $regs[2], SORT_ASC, SORT_NUMERIC);

    // cache the last match
    $lastMatch = array();

    // the return value
    $return = array();

    // loop through the matches
    for ($i = 0; $i < sizeof($regs[0]); $i ++) {

        // check if the current match was not visited before
        if (0 == sizeof($lastMatch) ||
            $regs[1][$i] != $lastMatch[1] ||
            $regs[2][$i] != $lastMatch[2] ||
            $regs[3][$i] != $lastMatch[3]) {

            // save the match in return value
            array_push($return, array($regs[1][$i],
                                      $regs[2][$i],
                                      $regs[3][$i]));
        }

        // save match in last match cache
        $lastMatch[1] = $regs[1][$i];
        $lastMatch[2] = $regs[2][$i];
        $lastMatch[3] = $regs[3][$i];
    }

    // return all matches
    return $return;
}

?>

I know, it's not that elegant but I hope it's useful for a few people.
zerotwo at bk dot ru 19-Feb-2008 10:50
Sorry for my bad language.

Main class that ad’s other classes from includes

main.php :

define(EXT, '.php');

$config = array(
  'path' => array (
    'data' => 'data/',
    'inc' => 'inc/',
    'lang' => 'lng/',
    'dl' => 'dl/',
  ),
 ...
);

class general {
  private $cfg;
  public $call = array();

  function __construct($configs) {
    global ${"$configs"};
    $this->cfg = $configs;
  }

  function _include($filename) {
    foreach($this->cfg[path] as $dir) {
      if(file_exists($dir.$filename.EXT)) {
        include($dir.$filename.EXT);
        if(class_exists($filename)) {
          $this->call[$filename] = new $filename();
        }
        return true;
      }
    }
  ...
}

$main = new general();

// call profiler->start()

$main->call[profiler]->start();

profiler.php :

class profiler {
// simple profiler
  private $time_start;

  private function get_time() {
    list($usec, $sec) = explode(' ', microtime());
    return ((float)$usec + (float)$sec);
  }

  function start() {
    $this->time_start = $this->get_time();
  }
  function finish() {
    return ($this->get_time() - $this->time_start);
  }
}

index.php :

require('main.php');
...
$main->call[profiler]->finish();

You can edit $config to add path to other directories, and do $main->_include(‘CLASS) and it will include a script and if class named ‘CLASS exist it will create a new class in call[].
You can easily access class $main->call[‘CLASS]

Thank you for reading.
ahigerd at timeips dot com 20-Dec-2007 07:02
To access an object member with an illegal character in the name, use this syntax:

$obj->{'illegal-property:name()'}

This is particularly relevant with the dynamically-generated classes used by, for instance, database objects and the SoapClient class.
pascal dot poncet at netconsult dot com 13-Oct-2005 07:21
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
ia [AT] zoznam [DOT] sk 02-Aug-2005 10:55
as for zabmilenko's solution:
wouldn't it be better to create it this way?

<?php
// The base class for all db classes
class DB {
 protected $connectId;
}

// Class for MySQL, which extends base class
class MySQL extends DB {
 function connect () {
  $this->connectId = mysql_connect (...);
 }
}

// Class for PostgreSQL, which extends base class
class pgSQL extends DB {
 function connect () {
  $this->connectId = pg_connect (...);
 }
}

// and then call constructor like this:
$dbName = "MySQL";
$db = new $dbName ( ... );
// ... which creates an object of class MySQL
?>
zabmilenko at hotmail dot com 27-Jun-2005 12:08
((PHP5))

I wanted to dynamically choose an extender for a class.  This took awhile of playing with it but I came up with a solution.  Note that I can't verify how safe it is, but it appears to work for me.  Perhaps someone else can shed light on the details:

<?php

class A { var $value = "Class A\n"; }
class B { var $value = "Class B\n"; }

// Uncomment which extender you want.  You can use variables as well.
// define('__EXTENDER__', 'A');
   define('__EXTENDER__', 'B');

// Use eval to create a wrapper class.
eval('class EXTENDER extends '. __EXTENDER__ . ' { }');

class C extends EXTENDER
{
  function __construct()
  {
     echo $this->value;
  }
}

$t = new C;

?>

Outputs:   Class B

Practical application:  I have a database abstraction system that has individual classes for mysql, pgsql, et al.  I want to be able to create a global db class that extends one of the individual db classes depending on the application configuration.

I know that there are probably much better ways of doing this but I haven't reached that level when it comes to classes.
cjones 03-Mar-2005 01:27
If anyone is interested in looking for a way to dynamically load existing objects into a class, here is what I found very useful.

//---------------------------------------------------------
// Dynamically load External Objects into a class

  function objRef ( &$obj ) {
    eval("\$this->obj_".get_class($obj)." = \$obj;");
  }
//---------------------------------------------------------
// Reference by using: $this->obj_[object Name]->[var|f{}]

Example:

class date {  function date ( ) { $this->date = "March 3rd"; } }
class time {  function time ( ) { $this->time = "12:30pm"; } }

class show {
    function objRef ( &$obj ){
        eval("\$this->obj_".get_class($obj)." = \$obj;");
    }
   function test ( $var ){
       echo "$var".$this->obj_date->date." @ ".$this->obj_time->time;
   }
}

$date = new date;
$time = new time;
$show = new show;
    $show->objRef($date);
    $show->objRef($time);
    $show->test("Time Now => ");

// Output: Time Now => March 3rd @ 12:30pm

I found the prefix 'obj_' before the class name useful because it helped me to automatically identify external object references when scanning through my scripts. You can omit this if you want. Hope this helps someone.
http://sc.tri-bit.com/ StoneCypher 02-Mar-2005 10:25
to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There's a much easier solution to getting a class' name for working with a factory function.  Let's assume you're doing something like this:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {
      case 'stuff'      : return new Stuff($instancedata);
      case 'otherstuff' : return new Otherstuff($instancedata);
    }

  }

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {

      case 'stuff'      : return array('typeis'=>'stuff',      'instance'=>new Stuff($instancedata));
      case 'otherstuff' : return array('typeis'=>'otherstuff', 'instance'=>new Otherstuff($instancedata));

    }

  }

?>

Nice 'n simple.  It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior.  If you move to PHP5, the static keyword solves your problem cleanly.
covertka at muohio dot edu 02-Jan-2005 05:27
To pillepop2003 at yahoo dot de:

I have the same issue.  I have a base class that manages database tasks for a number of child classes.  One of the functions in the base class is a find() method that returns instances of the child classes.  Since find() is usually called as a static method, it needs to know the name of the child class.  As you've found, this appears to be impossible to get in an easy fashion.

The only way I've found to get the child class name is to use the debug_traceback() function.  This requires me to have a find() method in every child class, but it does work.

Here's an example:

<?php
  require_once("Application.php");

  class parentClass {
    function find() {
      $className = NULL;
      foreach (debug_backtrace() as $bt) {
        if ($bt['function'] == __FUNCTION__) {
          $className = $bt['class'];
        }
      }

      // here should be some code to find the proper id, let's assume it was id 1
      $id = 1;
      return new $className($id);
    }
  }

  class foo extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  class bar extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  $a = foo::find();
  printf("Type for \$a: %s<br/>\n", get_class($a));
  $b = bar::find();
  printf("Type for \$b: %s<br/>\n", get_class($b));
?>
iparanoid at gmx dot de 04-Aug-2004 11:17
To pillepop2003 at yahoo dot de:

It seems to me if there really is no nice way to get the class name in an un-instanciated class, there is a workaround in PHP5 though using static/class variables.

Example:

<?php

class myFoo
{
    static $__ClassName = __CLASS__;

    static function getClassName()
    {
        return myFoo::$__ClassName;
    }
};

class myFooExtended extends myFoo
{
    function __construct()
    {
        myFooExtended::$__ClassName = __CLASS__;
    };
};

?>

However, you'll need to have at least instanciated an object of the class myFooExtended before calling getClassName or introduce some other initialization (the class variable will need to be set at some point to __CLASS__ in the sub-class).
greg at doutromundo dot com 05-Jul-2004 07:58
As programmers, you're probably more organized than me, but, I do try and maintain some order in my classes and codes and separate them in "packages" as in java.
This helped me keep them organized but caused havok when trying to use them, so what I did was to create a class that handles the loading of classes (which I instanciate in all pages) along with my error handling class all bundled up. This way, I can load my classes with a command similar to
$baseClass->loadClass("package","className"[,"constructor"]);

the function responsible for this has some checking to see if they are loaded and stuff like that...

function loadClass($packageName,$className,$constructor=""){
  // if you dont have a constructor declare any function inside
  // the class
  if ($constructor==""){
    $constructor=$className;
  }
  if(!is_callable(array($className,$constructor))){
    if (defined("CLASS_DIR")){
      $pkg = CLASS_DIR.$packageName."/";
        if (is_dir($pkg)){
          // we have a directory with the package name
          $cls = $pkg.$className.".class.php";
          if(is_file($cls)){
            // we have a file
            include_once($cls);
          }else{
            die("Class <b>$className</b> could not be found in package <b>$packageName</b> , please check your instalation");
          }
        }else{
          die("Package <b>$packageName</b> could not be found, please check your instalation");
        }
      }
    }
}

Just remember to define CLASS_DIR as the physical path for the directories where you packages are...

Hope this comes in handy...

Here's an example of a diretory strucutre...
/var/www/classes/   <- this would be CLASS_DIR
in there I have:
package1/
     name.class.php
     name2.class.php
....

The loadClass would look like: loadClass("package1","name");

Cute and easy
ettinger at consultant dot com 18-Jun-2004 04:59
Re: Looking for an uninstantiated class

# Loads data from a table into a class object
class LFPDataFactory extends LFPObject {
        var $object;
        var $class;
        var $table;
        function LFPDataFactory($args) {
                $this->unpackArgs($args); // assigns locals from $args
                if (in_array(strtolower($this->class), get_declared_classes())) {
                        $this->object = new $this->class;
                        // assemble the columns in the table...
                        // select their values and put them in our new object...
                } else { trigger_error("Class ".$this->class." not found", E_USER_ERROR); }
        }
}
$r = new LFPDataFactory("class=LFPLayout,table=layout");
$new_obj = $r->object; // this is a LFPLayout object.
print_r($new_obj);

This class looks to see if the class exists, then instantiates it -- a declared class is not the same as an instantiated class. As long as LFPLayout exists somewhere in the scripts, get_declared_classes() will find it. Remember strtolower on compare, however.

Why would I do this? Because I have my class layouts the same as their respective tables; the factory then selects the data (making sure that the variables match) and plugs in the data. (I've left out the actual code to do the selection/insertion).
HOC 28-May-2004 09:40
to pillepop2003

Why do u want to know the classname of an non-existant object?

The only possible explanation for this question seems to me u want to know the class before u instantiate the object. Well, this is of no use since u always instantiate a class of ur choice.

When the class is instantiated into an object u can find the class of the object by means of get_class(). This is all u need. In case of inheritance u can use get_class($this) to get the class of the instantiated object. Now u can differentiate according to which class the object belongs to.

e.g.:

<?php
class A{
   function A(){
      $class_of_this = get_class($this);
      echo 'Object is an instance of class '.$class_of_this.' which is the ';
      if(strcmp($class_of_this,'A')==0)
         echo 'parent-class';
      else if(strcmp($class_of_this,'B')==0)
         echo 'child-class';
      echo ".\n";
   }
}

class B extends A{
   function B(){
      $this->A();
   }
}

$object1 = new A();
$object2 = new B();
?>

When u run this code-snippet the output will be:

Object is an instance of class A which is the parent-class.
Object is an instance of class B which is the child-class.
ar at 5mm de 28-Aug-2003 07:59
I missed some kind of function to dynamicly override or extend an Object:

-----------------------------------------
function &extendObj(&$obj, $code) {
    static $num = 0;

    $classname = get_class($obj);
    $newclass = $classname.$num;

    eval('class '.$newclass.' extends '.$classname.' { '.$code.' }');

    $newobj = new $newclass();

    $vars = get_class_vars($classname);
    foreach($vars AS $key=>$value) {
        $newobj->$key = &$obj->$key;
    }

    return $newobj;
}
-----------------------------------------

This creates a new class which extends the old one by the given code parameter, instanciates it and copy all vars from the old obj to the new one.

-----------------------------------------
class testA {
    var $prop = 'a';

    function funcA($val) {
        $this->prop = $val;
    }

    function value() {
        return $this->prop;
    }
}

$obj = new testA();

$newobj = &extendObj(&$obj, 'function addX() { $this->prop .= "x"; }');

$newobj->funcA('abc');
$newobj->addX();
echo $newobj->value();
-----------------------------------------

Results in 'abcx'. You can use the function multiple times and also with class variables. Be carefull, even if $newobj is just a copy of $obj, $obj->value() will return 'abcx', too, because of the & operator: $newobj->$key = &$obj->$key;
zidsu at hotmail dot com 08-Jul-2003 05:24
FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:

class Some_class {
  var $value = 3;
  function add_value ($input_param) {
    return include ("path/some_file.php");
  }
}

And your included file:

$input_param += $this->value;
return $input_param;

Then your function call will be:

$instance = new Some_class ();
$instance->add_value (3);

And this will return
6
hopefully :P

Keep in mind though, that the scope in the included file will be identical to the scope the function 'add_value' has.
And if you want to return the outcome, you should also have a return statement made in your include as well.
asommer*at*as-media.com 20-Sep-2002 02:52
Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

class a {

..function ha ( ) {
....if ( $some_expr ) {
......$this = new b;
......return $this->ha ( );
....}
....return $something;
..}

}

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change... but it opens a few possibilities in flexible scripting!!
einhverfr at not-this-host dot hotmail dot com 14-Sep-2002 12:35
You may find it helpful in complex projects to have namespaces for your classes, and arrange these in a hierarchical manner.   A simple way to do this is to use the filesystem to order your hierarchies and then define a function like this:

function use_namespace($namespace){

require_once("namespaces/$namespace.obj.php");

}

(lack of indentation due to HTML UI for this page)
This requires that all your object libraries end in .obj.php (which I use) but you can modfy it to suit your needs.  To call it you could, for exmaple call:

use_namespace("example");
or if foo is part of example you can call:
use_namespace("example/foo");
justin at quadmyre dot com 19-Aug-2002 09:38
If you want to be able to call an instance of a class from within another class, all you need to do is store a reference to the external class as a property of the local class (can use the constructor to pass this to the class), then call the external method like this:

$this->classref->memberfunction($vars);

or if the double '->' is too freaky for you, how about:

$ref=&$this->classref;
$ref->memberfunction($vars);

This is handy if you write something like a general SQL class that you want member functions in other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.

Justin

Example:

<?php

class class1 {
    function test($var) {
        $result = $var + 2;
        return $result;
    }
}

class class2{
    var $ref_to_class=''; # to be pointer to other class

    function class1(&$ref){ #constructor
        $this->ref_to_class=$ref; #save ref to other class as property of this class
    }

    function test2($var){
        $val = $this->ref_to_class->test($var); #call other class using ref
        return $val;
    }
}

$obj1=new class1;
# obj1 is instantiated.
$obj2=new class2($obj1);
# pass ref to obj1 when instantiating obj2

$var=5;
$result=obj2->test2($var);
# call method in obj2, which calls method in obj1
echo ($result);

?>
gateschris at yahoo dot com 08-Mar-2001 01:59
[Editor's note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the "Classes and Objects" page of the manual and comments/editor's notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

<?php
class foo {
 function foo () { }
 function a () { }
}

class bar extends foo {
 function bar () { }
 function a () { }
}

lala = new Bar();
?>
------------------
how do we find programmatically if member a now belongs to class Bar or Foo.
Примеры
__autoload
Классы/Объекты
PHP Manual


Attempt to load undefined class

Классы/Объекты
call_user_method_array
Классы/Объекты
PHP Manual

__autoload

(Информация о версии неизвестна, возможно, только в SVN)

__autoload — Attempt to load undefined class

Описание

void __autoload ( string $class )

You can define this function to enable classes autoloading.

Список параметров

class

Name of the class to load

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • spl_autoload_register() - Register given function as __autoload() implementation

User Contributed Notes

carloagonzales at gmail dot com 04-Apr-2012 01:42
__autoload magic function can also be used inside a class and have the class handle the inclusion of class files.

/********
index.php
********/
<?php

class foobar {
    public function executeMe(){
        function __autoload($classname){
            include $classname . '.php';
        }
    }
}

$foo = new foobar();

$foo->executeMe();
some::foobar2(); //will output "hello! I'm static!"

$bar = new some();
$bar->foobar(); //will output "hello! I'm public!"
?>

/********
some.php
********/

<?php
class some {

    public function foobar (){
        echo "hello! I'm public!";
    }

    static function foobar2 (){
        echo "hello! I'm static!";
    }
}
?>
qeremy 08-Mar-2012 03:01
Even I have never been using this function, just a simple example in order to explain it;

./myClass.php
<?php
class myClass {
    public function __construct() {
        echo "myClass init'ed successfuly!!!";
    }
}
?>

./index.php
<?php
// we've writen this code where we need
function __autoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}

// we've called a class ***
$obj = new myClass();
?>

*** At this line, our "./myClass.php" will be included! This is the magic that we're wondering... And you get this result "myClass init'ed successfuly!!!".

So, if you call a class that named as myClass then a file will be included myClass.php if it exists (if not you get an include error normally). If you call Foo, Foo.php will be included, and so on...

And you don't need some code like this anymore;

<?php
include_once("./myClass.php");
include_once("./myFoo.php");
include_once("./myBar.php");

$obj = new myClass();
$foo = new Foo();
$bar = new Bar();
?>

Your class files will be included "automatically" when you call (init) them without these functions: "include, include_once, require, require_once".
Классы/Объекты
call_user_method_array
Классы/Объекты


Вызывает метод объекта с массивом параметров [устаревшее]

__autoload
call_user_method
Классы/Объекты
PHP Manual

call_user_method_array

(PHP 4 >= 4.0.5, PHP 5)

call_user_method_array — Вызывает метод объекта с массивом параметров [устаревшее]

Описание

mixed call_user_method_array ( string $method_name , object &$obj , array $params )
Внимание

Функция call_user_method_array() устарела с выходом 4.1.0.

Список параметров

method_name

Имя вызываемого метода.

obj

Объект (object), содержащий вызываемый метод method_name.

params

Массив параметров.

Примеры

Пример #1 Альтернатива call_user_method_array()

<?php
call_user_func_array(array($obj, $method_name), $params);
call_user_func_array(array(&$obj, $method_name), $params); // PHP 4
?>

Смотрите также

  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров
  • call_user_func() - Вызывает пользовательскую функцию, указанную в первом параметре

User Contributed Notes

wloche at hotmail dot com 15-Jul-2010 01:33
You don't have to write a new function, <?php call_user_func_array(array($obj, $method_name), $params); ?> works pretty fine! (to my mind, 'eval' fucntion should be avoided almost all the time)
brudinie at googlemail dot com 25-Mar-2009 07:23
<?php

/**
 * @param string $func - method name
 * @param object $obj - object to call method on
 * @param boolean|array $params - array of parameters
 */
function call_object_method_array($func, $obj, $params=false){
    if (!method_exists($obj,$func)){
        // object doesn't have function, return null
        return (null);
    }
    // no params so just return function
    if (!$params){
        return ($obj->$func());
    }
    // build eval string to execute function with parameters
    $pstr='';
    $p=0;
    foreach ($params as $param){
        $pstr.=$p>0 ? ', ' : '';
        $pstr.='$params['.$p.']';
        $p++;
    }
    $evalstr='$retval=$obj->'.$func.'('.$pstr.');';
    $evalok=eval($evalstr);
    // if eval worked ok, return value returned by function
    if ($evalok){
        return ($retval);
    } else {
        return (null);
    }
    return (null);
}

?>
leonwinter at gmail dot com 02-Oct-2006 04:45
If you this function will be deleted in future php releases you can use this function:

<?
       function _call_user_method_array($name, $obj, $params) {
           // get params
           $txt = "";
           foreach($params as $nr => $el) {
               $txt.='$params['.$nr."], ";
           }
           $txt = substr($txt, 0, strlen($txt)-2);
           // run it
           return eval('return call_user_method($name, $obj, '.$txt.');');
       }
?>

Hope this helps somebody.
__autoload
call_user_method
Классы/Объекты


Вызывает метод указанного объекта [устаревшее]

call_user_method_array
class_alias
Классы/Объекты
PHP Manual

call_user_method

(PHP 4, PHP 5)

call_user_method — Вызывает метод указанного объекта [устаревшее]

Описание

mixed call_user_method ( string $method_name , object &$obj [, mixed $parameter [, mixed $... ]] )
Внимание

Функция call_user_method_array() устарела с выходом 4.1.0.

Список параметров

method_name

Имя вызываемого метода.

obj

Объект (object), содержащий вызываемый метод method_name.

parameter ...

Необязательные параметры.

Примеры

Пример #1 Альтернатива call_user_method()

<?php
call_user_func(array($obj, $method_name), $parameter /* , ... */);
call_user_func(array(&$obj, $method_name), $parameter /* , ... */); // PHP 4
?>

Смотрите также

  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров
  • call_user_func() - Вызывает пользовательскую функцию, указанную в первом параметре

User Contributed Notes

david dot jarchovsky at gmail dot com 17-Dec-2008 04:48
It's possible to use this function in case of calling static methods too.

<?php
class example {
    public static function b(){
        $self = self;
        call_user_method('c',$self);
    }

    public static function c(){
        echo "B\n";
    }
};

example::b();
?>
Chris 24-Jun-2008 07:26
From what i've observed, call_user_func() does everything this funciton does and a little more.  I made a pretty good example call_user_func()'s usage with object instances and figured it might be useful here:

<?php

    /**

        This is a demonstration of 2 neat features of PHP

        *    passing array arguments in as a big array, and using += to assign defaults to missing values
                This would allow for function calls that more closely mimick thoes made in javascript using JSON, with enough work, it could be almost identical using associative arrays
        *    function callbacks within a class to global instances of other classes
                This allows you pass a function callback to an object early on, and hold off its execution until later in the program (say during page outputing after everything has been setup)

    **/

    class Runner {

        public $id;

        public function __construct($id) {
            $this->id = $id;
            echo "constructing " . __CLASS__ . " with id of $id<br />\n";
        }

        public function run($distance = null, $measurement = 'km') {
            if ($distance) {
                echo 'I ran ' . $distance . ' ' . $measurement . '.';
            } else {
                echo 'I ran.';
            }
            echo "({$this->id})<br />\n";
        }
    }

    class Speaker {

        public $id;

        public function __construct($id = 0) {
            $this->id = $id;
            echo "constructing " . __CLASS__ . " with id of $id<br />\n";
        }

        public function speak($statement = 'hello world') {
            echo $statement . "({$this->id})<br />\n";
        }
    }

    class Test {
        protected $runCallback = null;
        protected $speakCallback = null;
        protected $statement;
        protected $distance;

        public function __construct(array $params = array()) {
            echo "constructing " . __CLASS__ . "<br />\n";
            $params += array('speakCallback' => array('Speaker', 'speak'), 'runCallback' => array('Runner', 'run'), 'statement' => 'Hello from ' . __CLASS__ . ' class!', 'distance' => 10);
            foreach($params as $k => $v) {
                $this->$k = $v;
            }
        }

        public function getInstance() {
            return new self(current(func_get_args()));
        }

        public function callRunner() {
            if (is_callable($this->runCallback))
                return call_user_func($this->runCallback, $this->distance);
            else
                throw new Exception("runCallback is not callable\n" . var_export($this->runCallback, true) . "\n");
        }
        public function callSpeaker() {
            if (is_callable($this->speakCallback))
                return call_user_func($this->speakCallback, $this->statement);
            else
                throw new Exception("speakCallback is not callable\n" . var_export($this->speakCallback, true) . "\n");
        }
    }

    $r = new Runner(1);
    $s = new Speaker(2);

    // Note that we're using $s instead of 'Speaker'
    call_user_func(array($s, 'speak'), 'Hello from global!');

    // try out from global with call_user_func_array() to pass args as an array
    call_user_func_array(array($r, 'run'), array(5, 'mi'));

    $Test = new Test(array('runCallback' => array($r, 'run'), 'speakCallback' => array($s, 'speak')));
    $Test->callRunner();
    $Test->callSpeaker();

    $Test = call_user_func(array('Test', 'getInstance'), array('runCallback' => array($r, 'run'), 'distance' => 15));
    // should work as expected
    $Test->callRunner();
    // should throw an error for trying to use this during a static call to Speaker::speak() because of the default
    $Test->callSpeaker();

?>

Hope that's helpful.
ravichandran_11 at yahoo dot co dot in 10-Mar-2008 04:32
<?php
class abc{
   function func($argument)  {
       $argument="It works";
   }
}
$obj=new abc;
$argument_to_be_changed="No it doesn't work";
call_user_method("func", $obj, &$argument_to_be_changed);
echo "Result : ".$argument_to_be_changed;
?>

This code is working. But will through some warning message which you can hide by configuring php.ini
j dot h at h-elektro dot de 05-Feb-2007 12:11
It does not work to use Pointers as Arguments:

<?php
class abc{
   function func(&$argument)  {
       $argument="It works";
   }
}

$obj=new abc;
$argument_to_be_changed="No it doesnt";
call_user_method("func", $obj, $argument_to_be_changed);

echo "Result".$argument_to_be_changed;
?>

The result is: "No it doesnt".

Regards
der Jan
paulo at emd dot com dot br 18-Sep-2000 05:12
This function is very similar to this:

<?php
$method="Print";
$object->$method($param1,$param2);
?>

Note the extra $ after the ->
jmcastagnetto at php dot net 21-Aug-2000 05:04
You can pass a variable number of parameters to a function, use a definition like:

function mymethod ($v1, $v2, $v3="", $v4="")

and then you can pass 2, 3 or 4 parameters. This is explained in the "Functions" section of the manual.

See also the PHP4 functions: func_num_args(), func_get_arg(), and func_get_args(), and examples therein
call_user_method_array
class_alias
Классы/Объекты


Создает псевдоним для указанного класса

call_user_method
class_exists
Классы/Объекты
PHP Manual

class_alias

(PHP 5 >= 5.3.0)

class_alias — Создает псевдоним для указанного класса

Описание

bool class_alias ([ string $original [, string $alias ]] )

Создает псевдоним alias для класса original. Новый класс с псевдонимом будет точно таким же, как и оригинальный класс.

Список параметров

original

Оригинальный класс.

alias

Имя псевдонима для класса.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования class_alias()

<?php

class foo { }

class_alias('foo', 'bar');

$a = new foo;
$b = new bar;

// объекты одинаковы
var_dump($a == $b, $a === $b);
var_dump($a instanceof $b);

// классы одинаковы
var_dump($a instanceof foo);
var_dump($a instanceof bar);

var_dump($b instanceof foo);
var_dump($b instanceof bar);

?>

Результат выполнения данного примера:

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Смотрите также

  • get_parent_class() - Возвращает имя родительского класса для объекта или класса
  • is_subclass_of() - Проверяет, содержит ли объект в своем дереве предков указанный класс

User Contributed Notes

adam at adamhahn dot com 06-Sep-2011 12:13
Something to note,

If the $original class has not yet been defined or loaded, the auto loader will be invoked in order to try and load it.

If the class for which you are trying to create an alias does not exist, or can not be loaded with the auto loader, you will generate a PHP Warning.
programmer-comfreek at hotmail dot com 15-Aug-2011 09:38
If you defined the class 'original' in a namespace, you will have to specify the namespace(s), too:
<?php
namespace ns1\ns2\ns3;

class A {}

class_alias('ns1\ns2\ns3\A', 'B');
/* or if you want B to exist in ns1\ns2\ns3 */
class_alias('ns1\ns2\ns3\A', 'ns1\ns2\ns3\B');
?>
nicolas dot grekas+php at gmail dot com 31-Dec-2010 01:09
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

BUT when derivation creates a new class name - that means, you can then instantiate a new kind of objects - aliasing is just what it says: a synonym, so objects instantiated with the aliased name are of the exact same kind of objects instantiated with the non-aliased name.

See this code for example:
<?php
class A {};
class B1 extends A {};
class_alias('A', 'B2');

$b1 = new B1; echo get_class($b1); // prints B1
$b2 = new B2; echo get_class($b2); // prints A !
?>
nicolas dot grekas+php at gmail dot com 30-Dec-2010 02:41
class_alias also works for interfaces!

<?php
interface foo {}
class_alias('foo', 'bar');
echo interface_exists('bar') ? 'yes!' : 'no'; // prints yes!
?>
paul [dot] kotets [at] gmail [dot] com 03-Sep-2009 03:43
This function will appear in PHP 5.3 (at least I can use it with PHP 5.3, build Aug 7 2009 08:21:14)
For older versions of PHP I wrote the next function:

<?php
if (!function_exists('class_alias')) {
    function class_alias($original, $alias) {
        eval('abstract class ' . $alias . ' extends ' . $original . ' {}');
    }
}
?>

Keyword 'abstract' is used for classes, which defines abstract methods.
This function is used in autoload purposes (when I extend classes), so abstract keyword doesn't broke anything for me.
call_user_method
class_exists
Классы/Объекты


Проверяет, был ли объявлен класс

class_alias
get_called_class
Классы/Объекты
PHP Manual

class_exists

(PHP 4, PHP 5)

class_exists — Проверяет, был ли объявлен класс

Описание

bool class_exists ( string $class_name [, bool $autoload = true ] )

Эта функция проверяет, был ли объявлен указанный класс или нет.

Список параметров

class_name

Имя класса. Воспринимается без учета регистра.

autoload

Вызывать ли по умолчанию __autoload.

Возвращаемые значения

Возвращает TRUE, если класс class_name объявлен, иначе FALSE.

Список изменений

Версия | Описание
5.0.2 | Больше не возвращает TRUE для объявленных интерфейсов. Используйте для этого interface_exists().
5.0.0 | Добавлен параметр autoload.

Примеры

Пример #1 Пример использования class_exists()

<?php
// Проверяем существование класса перед его использованием
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Пример #2 Пример использования параметра autoload

<?php
function __autoload($class)
{
    include($class . '.php');

    // Проверяем необходимость подключения указанного класса
    if (!class_exists($class, false)) {
        trigger_error("Unable to load class: $class", E_USER_WARNING);
    }
}

if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Смотрите также

  • function_exists() - Возвращает TRUE, если указанная функция определена
  • interface_exists() - Проверяет, определен ли интерфейс
  • get_declared_classes() - Возвращает массив с именами объявленных классов

User Contributed Notes

toocoolone at gmail dot com 14-Feb-2012 06:47
I'm running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn't exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
/**
 * Assuming I have my own custom exception handler (MyException) let's
 * try to see if a file exists.
 */
try {
    if( ! file_exists( 'myfile.php' ) ) {
        throw new MyException('Doh!');
    }
    include( 'myfile.php' );
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
 * The above code either includes myfile.php or throws the new MyException
 * as expected. No problem right? The same should be true of class_exists(),
 * right? So then...
 */
$classname = 'NonExistentClass';
try {
    if( ! class_exists( $classname ) ) {
        throw new MyException('Double Doh!');
    }
    $var = new $classname();
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
* Should throw a new instance of MyException. But instead I get an
* uncaught LogicException blah blah blah for the default Exception
* class AND MyException. I only catch MyException so we've got on
* uncaught resulting in the dreaded LogicException error.
*/
?>

By registering an additional autoload handler function that did nothing, I was able to stop throwing the extra Exception and only throw my own.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
spl_autoload_register( 'myAutoLoad' ); // Add these two and no worries...
function myAutoLoad() {}
/**
 * By registering the additional custom autoload function that does nothing
 * class_exists() returns only boolean and does NOT throw an uncaught Exception
 */
?>

Found this buried in some search results. I don't remember the page URL but if it would have been here it might have saved me some time!
Anonymous 07-Mar-2011 10:21
It might not be obvious to some, but whenever you reference a namespace in a string, each backslash must be escaped with another backslash because of how PHP handles strings.

<?php
class_exists('\\Zend_Registry'); // return true
?>
myb at mikebevz dot com 23-Sep-2010 06:50
I've got a problem, which I can't solve.
Let's assume that class Zend_Registry exists in global namespace.

---
namespace myNs;

class SomeClass {
   public function MyFunc() {
      class_exists('Zend_Registry'); // return false
      class_exists('\Zend_Registry'); // return false
      class_exists('::Zend_Registry'); // return false
   }
}
---

How would I check for a class, which exists outside of myNs?
Klaus 28-Apr-2010 04:21
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.
azrael dot com at gmail dot com 11-Dec-2008 04:14
If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

Use instead
<?php
in_array($class_name, get_declared_classes());
?>
Anonymous 29-Nov-2008 10:27
If you planned to use utf-8 in classes or variables names, remember that locale has to be properly set firstly, e.g.
<?php
locale (LC_ALL, 'ru_RU.UTF-8');
?>
or it turn into errors.
Radek @ cz 05-May-2008 06:43
If you want to combat many class includes effectively, define your own autoloader function and spl_autoload_register() that autoloader.
richard at richard-sumilang dot com 27-Mar-2008 12:56
[ >= PHP 5.3]

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

echo (class_exists("com::richardsumilang::common::MyClass")) ? "Yes" : "No";
Frayja 01-Jun-2006 01:42
Like someone else pointed out class_exists() is case-INsensitive.

Using in_array() which is case-sensitive, the following function is a case-sensitive version of class_exists().

<?php
function class_exists_sensitive( $classname )
{
   return ( class_exists( $classname ) && in_array( $classname, get_declared_classes() ) );
}
?>
06-Apr-2004 05:04
Just a note that at least PHP 4.3.1 seems to crash under some situations if you call class_exists($foo) where $foo is an array (that is, the calling code is incorrect but the error recovery is far from perfect).
anonymous at somewhere dot tld 17-Jul-2003 12:20
If you have a directory of classes you want to create. (Modules in my instance)... you can do it like that

<?php
if (is_dir($this->MODULE_PATH) && $dh = opendir($this->MODULE_PATH)) {
   while (($file = readdir($dh)) !== false) {
      if (preg_match("/(Mod[a-zA-Z0-9]+).php/", $file, $matches)>0) {
         // include and create the class
         require_once($this->MODULE_PATH."/".$file);
         $modules[] = new $matches[1]();
      }
   }
} else {
   exit;
}
?>

//---
Here the rule is that all modules are on the form
ModModulename.php and that the class has the same name as the file.
The $modules array has all the classes initialized after this code
class_alias
get_called_class
Классы/Объекты


Имя класса, полученное с помощью позднего статического связывания

class_exists
get_class_methods
Классы/Объекты
PHP Manual

get_called_class

(PHP 5 >= 5.3.0)

get_called_class — Имя класса, полученное с помощью позднего статического связывания

Описание

string get_called_class ( void )

Возвращает имя класса, из которого был вызван статический метод.

Возвращаемые значения

Возвращает имя класса. Возвращает FALSE, если было вызвано вне класса.

Примеры

Пример #1 Пример использования get_called_class()

<?php

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::test();
bar::test();

?>

Результат выполнения данного примера:

string(3) "foo"
string(3) "bar"

Смотрите также

  • get_parent_class() - Возвращает имя родительского класса для объекта или класса
  • get_class() - Возвращает имя класса, к которому принадлежит объект
  • is_subclass_of() - Проверяет, содержит ли объект в своем дереве предков указанный класс

User Contributed Notes

dsaa at dubli dot com 09-Feb-2012 06:22
The workarounds to use get_called_class in PHP versions previous to 5.3 didn't quite work for me when the class name in my call was contained in a variable, so I did a couple of modifications to the workarounds proposed.
<?php
/**
* workaround until update to PHP 5.3 takes place
* (Don't make more than one call in the same line, or it will break!!!).
*/
if (!function_exists('get_called_class')):
function get_called_class()
{
    $bt = debug_backtrace();
    $l = count($bt) - 1;
    $matches = array();
    while(empty($matches) && $l > -1){
        $lines = file($bt[$l]['file']);
        $callerLine = $lines[$bt[$l]['line']-1];
        preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
        $callerLine,
        $matches);
    }
    if (!isset($matches[1])) $matches[1]=NULL; //for notices
    if ($matches[1] == 'self') {
        $line = $bt[$l]['line']-1;
        while ($line > 0 && strpos($lines[$line], 'class') === false) {
            $line--;
        }
        preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
    }
    return $matches[1];
}
endif;
?>
maxim at inbox dot ru 26-Dec-2011 07:54
get_called_class
i was need to get call function from __costruct and found that php 5.3 returns correct, but no one of there functins neither.
So i fix it:
<?php if (!function_exists('get_called_class')):

  function get_called_class()
  {
    $bt = debug_backtrace();
    $lines = file($bt[1]['file']);

    preg_match('/([a-zA-Z0-9\_]+)::'.$bt[1]['function'].'/',
               $lines[$bt[1]['line']-1],
               $matches);

if(empty($matches[1])){
    $pp= serialize( $bt[1]["object"]);
    $nx=strpos($pp,'"')+1;
    $nx=substr($pp,$nx,strpos($pp,'"'));
    if (!empty($nx))
    {
    echo   " RETURING....: (".  $nx  . ")<br>";
    return $nx;
    }
}
echo   " RETURING....: (" . $matches[1]  . ")<br>";
    return $matches[1];
}
endif;
?>
uebele 06-Apr-2011 09:14
SEE: http://php.net/manual/en/language.oop5.late-static-bindings.php

I think it is worth mentioning on this page, that many uses of the value returned by get_called_function() could be handled with the new use of the old keyword static, as in
<?php
static::$foo;
?>

versus
<?php
$that=get_called_class();
$that::$foo;
?>

I had been using $that:: as my conventional replacement for self:: until my googling landed me the url above.  I have replaced all uses of $that with static with success both as
<?php
static::$foo; //and...
new static();
?>

Since static:: is listed with the limitation: "Another difference is that static:: can only refer to static properties." one may still need to use a $that:: to call static functions; though I have not yet needed this semantic.
webmaster at easy-coding dot de 12-Mar-2010 08:03
if you cannot avoid that carriage return characters will be used as windows linebreaks, you should set

<?php ini_set("auto_detect_line_endings", 1); ?>

otherwise the solutions posted here will fail.
Abhi Beckert 28-Oct-2009 08:41
Beware that this does not behave as expected if your method is not declared as static! For example:

<?php

class foo {
  static public function test() {
    var_dump(get_called_class());
  }

  public function testTwo() {
    var_dump(get_called_class());
  }
}

class bar extends foo {
}

class abc {
  function test() {
    foo::test();
    bar::test();
  }

  function testTwo() {
    foo::testTwo();
    bar::testTwo();
  }
}

echo "basic\n";
foo::test();
bar::test();

echo "basic without static declaration\n";
foo::testTwo();
bar::testTwo();

echo "in a class\n";
$abc = new abc();
$abc->test();

echo "in a class without static declaration\n";
$abc->testTwo();

?>

The result is:

basic
string 'foo'
string 'bar'

basic without static declaration
string 'foo'
string 'bar'

in a class
string 'foo'
string 'bar'

in a class without static declaration
string 'abc'
string 'abc'
mucahitkahveci at yahoo dot com 03-Sep-2009 07:21
Addition to tom at r dot je:
It is fine but does not work for method calls like:

<?php
class Car
{
    static function getClass()
    {
        echo get_called_class();
    }
}
$method='getClass';
Car::$method(); //prints nothing
?>

So I developed to meet also this issue, and add one extra line not to cause notice errors:

<?php
if(!function_exists('get_called_class')) {
function get_called_class() {
    $matches=array();
    $bt = debug_backtrace();
    $l = 0;
    do {
        $l++;
        if(isset($bt[$l]['class']) AND !empty($bt[$l]['class'])) {
            return $bt[$l]['class'];
        }
        $lines = file($bt[$l]['file']);
        $callerLine = $lines[$bt[$l]['line']-1];
        preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
                   $callerLine,
                   $matches);
        if (!isset($matches[1])) $matches[1]=NULL; //for notices
        if ($matches[1] == 'self') {
               $line = $bt[$l]['line']-1;
               while ($line > 0 && strpos($lines[$line], 'class') === false) {
                   $line--;
               }
               preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
       }
    }
    while ($matches[1] == 'parent'  && $matches[1]);
    return $matches[1];
}
}
?>
tom at r dot je 11-Aug-2009 09:18
I've further extended spidgorny at gmail dot com's 5.2 get_called_class() solution to also account for self:: calls. It works backwards up the file to find the class definition.

<?php
if(!function_exists('get_called_class')) {
function get_called_class() {
    $bt = debug_backtrace();
    $l = 0;
    do {
        $l++;
        $lines = file($bt[$l]['file']);
        $callerLine = $lines[$bt[$l]['line']-1];
        preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
                   $callerLine,
                   $matches);

       if ($matches[1] == 'self') {
               $line = $bt[$l]['line']-1;
               while ($line > 0 && strpos($lines[$line], 'class') === false) {
                   $line--;
               }
               preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
       }
    }
    while ($matches[1] == 'parent'  && $matches[1]);
    return $matches[1];
  }
}

?>

Not pretty but works until servers can be upgraded.
php at itronic dot at 07-Aug-2009 06:53
If you call a static getInstance() function to create a instance of a class from another class, this function have to be static, if it is not static the original name of the caller class and not of the current class get returned.

example:

<?php

class a {
  function getXName() {
     return x::getClassName();
  }
  function getXStaticName() {
     return x::getStaticClassName();
  }

}

class b extends a {
}

class x {
  public function getClassName() {
    return get_called_class();
  }
  public static function getStaticClassName() {
    return get_called_class();
  }
}

$a = new a();

$b = new b();

echo $a->getXName(); // will return "a"
echo $b->getXName(); // will return "b"

echo $a->getXStaticName(); // will return "x"
echo $b->getXStaticName(); // will return "x"

?>
steve at visual77 dot com 29-Jul-2009 04:21
I've furthered enhanced the attempts to fix get_called_class() for PHP 5.2 Using a class and some static properties, we can keep track of how many times it has already processed the current line, so multiple calls on the same line will still function properly.

<?php

if(!function_exists('get_called_class')) {
    class class_tools {
        static $i = 0;
        static $fl = null;

        static function get_called() {
            $bt = debug_backtrace();

            if(self::$fl == $bt[2]['file'].$bt[2]['line']) {
                self::$i++;
            } else {
                self::$i = 0;
                self::$fl = $bt[2]['file'].$bt[2]['line'];
            }

            $lines = file($bt[2]['file']);

            preg_match_all('/([a-zA-Z0-9\_]+)::'.$bt[2]['function'].'/',
                $lines[$bt[2]['line']-1],
                $matches);

            return $matches[1][self::$i];
        }
    }

    function get_called_class() {
        return class_tools::get_called_class();
    }
}

?>
aashley at php dot net 26-Jul-2009 11:06
Small change to spidgorny at gmail dot com's example so that it works with static calls as well.

Change:
} while ($matches[1] == 'parent' && $matches[1]);

to:
} while( in_array($matches[1], array('parent', 'self')) && $matches[1]);
spidgorny at gmail dot com 14-Jul-2009 02:32
My modification to the get_called_class() simulation function, which takes care of the parent:: calls. It goes further into the backtrace to find the first non "parent" call. This way we pop-up to the original caller class. I'm not sure if this is the default behavior of the original PHP 5.3 function.
<?php
// http://us.php.net/manual/en/function.get-called-class.php#89478
if (!function_exists('get_called_class')):

  function get_called_class() {
    $bt = debug_backtrace();
    //debug($bt);
    $l = 0;
    do {
        $l++;
        $lines = file($bt[$l]['file']);
        $callerLine = $lines[$bt[$l]['line']-1];
        //debug($callerLine);
        preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
                   $callerLine,
                   $matches);
    } while ($matches[1] == 'parent' && $matches[1]);
    return $matches[1];
  }

endif;
?>
progman at centrum dot sk 10-Mar-2009 12:49
Simplified version:

<?php if (!function_exists('get_called_class')):

  function get_called_class()
  {
    $bt = debug_backtrace();
    $lines = file($bt[1]['file']);
    preg_match('/([a-zA-Z0-9\_]+)::'.$bt[1]['function'].'/',
               $lines[$bt[1]['line']-1],
               $matches);
    return $matches[1];
  }

endif; ?>

When you use this function in singleton, mind there can by only one getInstance() call per line:

<?php

  abstract class Singleton  {  ... }
  class MySingleton1 extends Singleton { ... }
  class MySingleton2 extends Singleton  { ... }

  // this will work:
  $s1 = MySingleton1::getInstance();
  $s2 = MySingleton2::getInstance();

  // here will be problem:
  $s1 = MySingleton1::getInstance(); $s2 = MySingleton2::getInstance();

?>
a dot cudbard-bell at sussex dot ac dot uk 21-Feb-2009 10:03
Here's a simple way of getting the inheritance tree of a class, no matter which class the function was actually defined in. Will work as a static function method too.

<?php
class A {
    public function get_class_tree(){
        $cur_class = get_called_class();
        do {
            echo $cur_class;
        }
        while($cur_class = get_parent_class($cur_class));
    }
}

class B {

}

class C {

}

$foo = new C();
$foo->get_class_tree();

?>

CBA
danbettles at yahoo dot co dot uk 08-Oct-2008 12:00
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
class_exists
get_class_methods
Классы/Объекты


Возвращает массив имен методов класса

get_called_class
get_class_vars
Классы/Объекты
PHP Manual

get_class_methods

(PHP 4, PHP 5)

get_class_methods — Возвращает массив имен методов класса

Описание

array get_class_methods ( mixed $class_name )

Возвращает массив имен методов класса.

Список параметров

class_name

The class name or an object instance

Возвращаемые значения

Возвращает массив имен методов, объявленных в классе class_name. В случае ошибки будет возвращен NULL.

Список изменений

Версия | Описание
5.0.0 | Начиная с PHP 5, эта функция возвращает имена методов именно так, как они были объявлены (с учетом регистра). В PHP 4 они возвращались в нижнем регистре.
4.0.6 | Добавлена возможность указания самого объекта.

Примеры

Пример #1 Пример использования get_class_methods()

<?php

class myclass {
    // конструктор
    function myclass()
    {
        return(true);
    }

    // метод 1
    function myfunc1()
    {
        return(true);
    }

    // метод 2
    function myfunc2()
    {
        return(true);
    }
}

$class_methods = get_class_methods('myclass');
// или
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

Результат выполнения данного примера:

myclass
myfunc1
myfunc2

Смотрите также

  • get_class() - Возвращает имя класса, к которому принадлежит объект
  • get_class_vars() - Возвращает объявленные по умолчанию свойства класса
  • get_object_vars() - Возвращает свойства указанного объекта

User Contributed Notes

mnkras at gmail dot com 15-May-2011 09:00
I use this function for an api, so it excludes some functions from the list.

<?php
    public function getApiList() {
        $cmethods = get_class_methods(__CLASS__);
        $exclude = array('generateAuth', 'authenticateRequest', 'getApiList');
        $methods = array();
        foreach($cmethods as $value){
            if(!in_array($value, $exclude)) {
                $methods[] = $value;
            }
        }
        return $methods;
    }
?>
fschmengler at sgh-it dot eu 08-Jan-2010 04:40
It should be noted that the returned methods are dependant on the current scope. See this example:

<?php
class C
{
    private function privateMethod()
    {

    }
    public function publicMethod()
    {

    }
    public function __construct()
    {
        echo '$this:';
        var_dump(get_class_methods($this));
        echo 'C (inside class):';
        var_dump(get_class_methods('C'));
    }
}
$c = new C;
echo '$c:';
var_dump(get_class_methods($c));
echo 'C (outside class):';
var_dump(get_class_methods('C'));
?>

Output:

$this:
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

C (inside class):
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

$c:
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)

C (outside class):
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)
James Laver 14-Dec-2007 07:39
I have a situation with a superclass using get_class_methods() on a child and it's returning protected methods of the parent.

I thought people should be aware of this since it's forcing me to go use the reflection system instead.
php at stock-consulting dot com 06-Feb-2007 02:40
Note that this function will answer both class AND instance methods ("class methods" are called "static" in PHP). Sort of a little "trap" for people who have in-depth experience with the OO terminology :-)
BoD 15-Mar-2006 07:09
!Concerning PHP5 Only!

If you want to get all methods/functions from a class you can do this with the get_class_methods function.
<?php
    $arrMethodNames = get_class_methods ( $ClassNameOrObject);
?>
However the drawback on this function in PHP5 is that you will NOT receive protected and private methods of a class/object if you are calling the method from another class/object context.

If you want to receive all methods of a given Class in another Class you should use the PHP5 Reflection API. The following source allows to retrieve all methods from a derived class in its (abstract) Base Class.

In the example you need to call the base constructor from the derived classes constructor in order to let the base class know the name of the derived class. Use the "__CLASS__" definition for passing the classname of current class to its base class.

<?php

    // Base Class - Abstract
    abstract class A {

        // Array of ReflectionMethod Objects
        // is being set upon instanciation
        // derived Classes don't need to know about this array
        private $arrMethods;

        // Constructor which MUST be called from derived Class Constructor
        protected function __construct ( $strDerivedClassName ) {
            $oRefl = new ReflectionClass ( $strDerivedClassName );
            if ( is_object($oRefl) ) {
                $this->arrMethods = $oRefl->getMethods();
            }
        }

        // Some abstract function
        abstract protected function D ();

        // Some private function
        private function E() {
        }

        // method to print all class/object methods
        // must be callable from derived classes
        // can be protected if only for internal class use
        public function PrintAllMethods () {
            foreach ( $this->arrMethods as $curReflectionMethod ) {
                echo $curReflectionMethod->getName()."<br>";
            }
        }
    }

    // Derived Class
    class B extends A {

        // Constructor for this class
        // MUST call Base Constructor
        public function __construct () {
            // Call Base Constructor
            parent::__construct(__CLASS__);
        }

        // Some public function
        public function A () {
        }

        // some protected function
        protected function B () {
        }

        // some private function
        private function C() {
        }

        // some abstract method from base class implemented
        protected function D () {
        }
    }

    // Create new B Object
    $b = new B();
    // Print all Methods of this Object/Class
    $b->PrintAllMethods();
?>

In this example output will be:

__construct
A
B
C
D
E
PrintAllMethods

As you can see these are all methods from class B and also all methods from Class A respectivly in order of their declaration. Note that only one method "__construct" and only one method "D" are being shown. This is due to overloading (__construct) and implementing (D) in PHP.

In this example any further method-handling methods should be implemented in the base class as these will be available in derived classes as well. Just make sure that you use the right access specifiers for these additional methods ( private, protected, public )

BoD
jazepstein at greenash dot net dot au 16-Oct-2005 06:37
In PHP4, this function converts its return values to lowercase; but in PHP5, it leaves the return values in their original case. This can cause serious problems when trying to write code that dynamically calls a class method, and that works in both PHP4 and PHP5. This code snippet shows one way of achieving compatibility with both versions:

<?php
// Example variables - these would be dynamic in a real application.
$className = 'SomeClass';
$methodName= 'someMethod';
$args = array('arg1', 'arg2');

// Use array_map() and strtolower() to make all values returned by get_class_methods() lowercase. PHP4 does this anyway - now it will happen regardless of the PHP version being used.
$classMethods = array_map(strtolower, get_class_methods($className));

// in_array() can only handle being given an array.
if (!$classMethods) {
  $classMethods = array();
}

if (in_array(strtolower($methodName), $classMethods)) {
  // call some method
  return call_user_func_array(array($className, $methodName), $args);
}
?>
Oli Filth 11-Apr-2005 08:21
As an extension to onesimus's code below for finding inherited methods, in PHP 5 you can use the Reflection API to find which of these are overriden.

e.g.

<?php
function get_overriden_methods($class)
{
    $rClass = new ReflectionClass($class);
    $array = NULL;

    foreach ($rClass->getMethods() as $rMethod)
    {
        try
        {
            // attempt to find method in parent class
            new ReflectionMethod($rClass->getParentClass()->getName(),
                                $rMethod->getName());
            // check whether method is explicitly defined in this class
            if ($rMethod->getDeclaringClass()->getName()
                == $rClass->getName())
            {
                // if so, then it is overriden, so add to array
                $array[] .=  $rMethod->getName();
            }
        }
        catch (exception $e)
        {    /* was not in parent class! */    }
    }

    return $array;
}
?>
kabatak 20-Feb-2005 05:11
In PHP4, if you need to get_class_methods in their original case. You can use this simple function I created.

// Note: this function assumes that you only have 1 class in 1 file

$file = "path/to/myclass.php"

function file_get_class_methods ($file)
{
    $arr = file($file);
    foreach ($arr as $line)
    {
        if (ereg ('function ([_A-Za-z0-9]+)', $line, $regs))
            $arr_methods[] = $regs[1];
    }
    return $arr_methods;
}
epowell at removethis dot visi dot com 11-Oct-2004 08:47
I've figured out how to get around my issue described below, using the Reflection API.

<?
/* Pass the name of the class, not a declared handler */
function get_public_methods($className) {
    /* Init the return array */
    $returnArray = array();

    /* Iterate through each method in the class */
    foreach (get_class_methods($className) as $method) {

        /* Get a reflection object for the class method */
        $reflect = new ReflectionMethod($className, $method);

        /* For private, use isPrivate().  For protected, use isProtected() */
        /* See the Reflection API documentation for more definitions */
        if($reflect->isPublic()) {
            /* The method is one we're looking for, push it onto the return array */
            array_push($returnArray,$method);
        }
    }

    /* return the array to the caller */
    return $returnArray;
}
?>
onesimus at cox dot net 19-Jun-2004 02:32
This function will return only the methods for the object you indicate. It will strip out the inherited methods.

function get_this_class_methods($class){
    $array1 = get_class_methods($class);
    if($parent_class = get_parent_class($class)){
        $array2 = get_class_methods($parent_class);
        $array3 = array_diff($array1, $array2);
    }else{
        $array3 = $array1;
    }
    return($array3);
}
gk at proliberty dot com 01-Jun-2003 04:16
It is important to note that get_class_methods($class) returns not only methods defined by $class but also the inherited methods.

There does not appear to be any PHP function to determine which methods are inherited and which are defined explicitly by a class.
aldo at cerca dot com 21-Apr-2002 10:18
If you use "get_class_methods" to check if a Method is in a Class remember that the function return lowered name of class methods:

class classPippo
{
        function DummyFunct()
        {
                // Do nothing...
        }
}

$aClassMethods = get_class_methods(classPippo);

$sMethodName = 'DummyFunct';

// This not work...

        if (in_array($sMethodName, $aClassMethods))
        classPippo::DummyFunct();

// This work...

        if (in_array(strtolower($sMethodName), $aClassMethods))
        classPippo::DummyFunct();
matt at zevi dot net 21-Mar-2002 04:46
Win32 only:

It's probably worth noting here that you can't get the methods of an object created by the built-in 'COM' class. ie - this won't work:

$word = new COM('Word.Application');
$methods = get_class_methods(get_class($word));
print_r($methods);

Matt
get_called_class
get_class_vars
Классы/Объекты


Возвращает объявленные по умолчанию свойства класса

get_class_methods
get_class
Классы/Объекты
PHP Manual

get_class_vars

(PHP 4, PHP 5)

get_class_vars — Возвращает объявленные по умолчанию свойства класса

Описание

array get_class_vars ( string $class_name )

Возвращает объявленные по умолчанию свойства указанного класса.

Список параметров

class_name

Имя класса

Возвращаемые значения

Возвращает ассоциативный массив объявленных свойств класса, видимых из текущей области видимости, с их значением по умолчанию. Получившиеся элементы массива имеют форму varname => value. В случае ошибки возвращается FALSE.

Список изменений

Версия | Описание
5.0.3 | В зависимости от области видимости, get_class_vars() вернет только те свойства, доступ к которым может быть получен из текущей области видимости.
5.0.2 | Вызов get_class_vars() не вернет все свойства в качестве массива, в отличие от предыдущего поведения, где protected и private свойства имели префикс с нулевым байтом.
5.0.1 | Вызов get_class_vars() покажет все свойства, как при конвертировании объекта в класс.
До версии 4.2.0 | Неинициализированные переменные класса не будут возвращены функцией get_class_vars()

Примеры

Пример #1 Пример использования get_class_vars()

<?php

class myclass {

    var $var1; // переменная не имеет начального значения...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4; // PHP 5

    // конструктор
    function myclass() {
        // change some properties
        $this->var1 = "foo";
        $this->var2 = "bar";
        return true;
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

Результат выполнения данного примера:

// До PHP 4.2.0
var2 : xyz
var3 : 100

// Начиная с PHP 4.2.0
var1 :
var2 : xyz
var3 : 100

Пример #2 get_class_vars() и поведение области видимости

<?php
function format($array)
{
    return implode('|', array_keys($array)) . "\r\n";
}

class TestCase
{
    public $a    = 1;
    protected $b = 2;
    private $c   = 3;

    public static function expose()
    {
        echo format(get_class_vars(__CLASS__));
    }
}

TestCase::expose();
echo format(get_class_vars('TestCase'));
?>

Результат выполнения данного примера:

// 5.0.0
a| * b| TestCase c
a| * b| TestCase c

// 5.0.1 - 5.0.2
a|b|c
a|b|c

// 5.0.3 +
a|b|c
a

Смотрите также

  • get_class_methods() - Возвращает массив имен методов класса
  • get_object_vars() - Возвращает свойства указанного объекта

User Contributed Notes

Mattias Ahlbck 14-Feb-2012 09:39
get_class_vars_assoc()
- Returns an associative array with name of (parent) class(es) as key(s) and corresponding class vars as sub-arrays. My boilerplate for some crude O/R mapping.

Note: vars re-defined in sub-classes are ignored.

<?php

class GrandClass {
    public $grandVar;
    public $in_grand_and_parent;
    public $in_grand_and_child;

    public static function load() {
        print_r(self::get_class_vars_assoc());
    }

    protected static function get_class_vars_assoc() {
        $called = get_called_class();
        //echo "called: $called \n";
        $classVars[$called] = array_keys(get_class_vars($called));

        $parent = get_parent_class($called);
        while ( $parent !== FALSE ) {
            //echo "parent: $parent \n";
            $classVars[$parent] = array_keys(get_class_vars($parent));
            $classVars[$called] = array_diff($classVars[$called],
                                             $classVars[$parent]);
            if ( isset($prevParentVars) ) {
                $prevParentVars = array_diff($prevParentVars,
                                             $classVars[$parent]);
            }

            $prevParentVars = &$classVars[$parent];
            $parent = get_parent_class($parent);
        }

        return $classVars;
    }
}

class ParentClass extends GrandClass {
    public $in_grand_and_parent;
    public $parentVar;
    public $in_parent_and_child;
}

class ChildClass extends ParentClass {
    public $in_grand_and_child;
    public $in_parent_and_child;
    public $childVar;
}

ChildClass::load();

?>

Array
(
    [ChildClass] => Array
        (
            [2] => childVar
        )

    [ParentClass] => Array
        (
            [1] => parentVar
            [2] => in_parent_and_child
        )

    [GrandClass] => Array
        (
            [0] => grandVar
            [1] => in_grand_and_parent
            [2] => in_grand_and_child
        )

)
ciantic 30-Jan-2012 10:06
I propse following for getting Public members, always:
<?PHP
if (!function_exists("get_public_class_vars")) {
    function get_public_class_vars($class) {
        return get_class_vars($class);
    }
}
if (!function_exists("get_public_object_vars")) {
    function get_public_object_vars($object) {
        return get_object_vars($object);
    }
}
?>

This is to mitigate the problem and a feature that get_object_vars($this) returns private members. Running it simply outside the scope will get the public.

Iterating public members only and their defaults are enormously useful in e.g. in serialization classes such as options where each public member is an serializable that is saved and loaded.
pBakhuis at Gmail dot com 07-Oct-2011 03:08
If you need the variables before the class is included this function does not seem to work.
Use a reflection class to get around this.
http://www.php.net/reflectionclass
ken at verango dot com 04-Oct-2010 04:50
All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array.  For serialization I recommend:

<?php
$cName = get_class($this);
$varTemplate= get_class_vars($cName)
foreach ($varTemplate as $name => $defaultVal) {
  $vars[$name] = $this->$name; // gets actual val.
}
?>

No scan the $vars and create serialization string how you wish.

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.
ianitsky at gmail dot com 10-Nov-2009 11:53
If you need get the child protected/private vars ignoring the parent vars, use like this:

<?php
class childClass extends parentClass {
    private $login;
    private $password;

    public function __set($key, $val) {
        if ($key == 'password')
            $this->$key = md5($val);
        else
            $this->$key = $val;
    }
}
class parentClass {
    public $name;
    public $email;

    function __construct() {
        $reflection = new ReflectionClass($this);
        $vars = array_keys($reflection->getdefaultProperties());
        $reflection = new ReflectionClass(__CLASS__);
        $parent_vars = array_keys($reflection->getdefaultProperties());

        $my_child_vars = array();
        foreach ($vars as $key) {
            if (!in_array($key, $parent_vars)) {
                $my_child_vars[] = $key;
            }
        }

        print_r($my_child_vars);
    }
}

$child_class = new childClass();
?>
harmor 20-Dec-2008 03:53
So I wanted to get a list of the public parameters in a child class using a static function pre-5.3.0 (< 5.3.0).  In 5.3.0+ you would use the new 'static' like you would 'self' to get the late binding.

<?php
class childClass extends parentClass
{
    public $id;
    public $name;

    public static function getFields()
    {
        return self::_getFields(__CLASS__);
    }

}
abstract class parentClass
{
    public $idInParent;
    public $nameInParent;

    abstract public static function getFields();

    final protected static function _getFields($className)
    {
        $rtn = array();
        foreach (array_keys(get_class_vars($className)) as $var) {
            $rtn[] = $var;
        }
        return $rtn;
    }

}

var_dump(childClass::getFields());
?>

Results:
array(4) {
  [0]=>
  string(2) "id"
  [1]=>
  string(4) "name"
  [2]=>
  string(10) "idInParent"
  [3]=>
  string(12) "nameInParent"
}
artktec at art-k-tec dot com 16-Nov-2007 09:18
There seems to be be a function to get constants missing , i.e. get_class_constants() ... so here is a simple function for you all. Hopefully Zend will include this in the next round as a native php call, without using reflection.

<?php
   function GetClassConstants($sClassName) {
      $oClass = new ReflectionClass($sClassName);
      return $oClass->getConstants());
   }
?>
phpnet at stccorp dot net 15-Jun-2007 05:18
This is one of the best php functions. Look at what you can do

class Object
{
   var $updtFields;//keep track of affected values
   function Object($record="") {
       if (is_array($record))
       {
          $this->updtFields = array();
          foreach(array_keys(get_class_vars(get_class($this))) as $k)
          if (isset($record[$k]))
         {
          $this->$k = $record[$k];
          $this->updtFields[] = $k;
         }
      }
   }//end of arrayToObject

   function toDebug($nl='<br>')
   {
       foreach(array_keys(get_class_vars(get_class($this))) as $k)
       echo "$k = [" . $this->$k . "]{$nl}";
    }//end of toDebug
}

Now you can do really cool things. If you have a form like
<form action="" method="post">
  <input type="text" name="name" />
  <input type="text" name="phone" />
  <input type="submit" />
</form>

and you define your class like this
class Person extends Object{
  var $name; //same same as in the form
  var $phone;
}

when you submmit the form, you can get the data like

$person = new Person($_POST);

//everything in just one line,cool!! Also if you use pear db or adodb when you get data from the database you can do the same thing except use the $row that you get from the database. Remember to ask the result is associative mode.

This is my core Object for everthing I do and it works great.
bernd at tiggerswelt dot net 29-Jan-2007 02:52
If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

Example:

<?PHP

  class Foo {
    const Bar = "error";

    public $Foo = self::Bar;
  }

  print_r(get_class_vars("Foo"));

?>

... but using "Foo::Bar" instead "self::Bar" will work ;)
gizmobits at hotmail dot com 03-Mar-2006 07:48
I wanted a simple ToString() function that was automatic and class independent.  I wanted to dump it into any of several classes and get values quickly.  I wanted to leave it there so I could customize it for each class, so an outside function wasn't suitable.  I came up with this and thought it might be useful.  Have fun!

<?php
  function ToString () {
    $s = "";
    $s .= "<table>\n";
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    foreach (get_class_vars(get_class($this)) as $name => $value) {
      $s .= "<tr><td>$name:</td><td>" . $this->$name . "</td></tr>\n";
    }
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    $s .= "</table>\n";
    return $s;
  }

?>
php dot net at sharpdreams dot com 25-Oct-2005 06:25
Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

<?php
class Foo {
   public $x;
   protected $y;
   private $z;
   public function __sleep() {
      return( get_class_vars( __CLASS__ ) );
   }
}
?>

works fine (returns x, y, & z). However, given the same class as above,

<?php
print_r( get_class_vars( "Foo" ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).
alan_k at php dot net 21-Jan-2005 07:23
in PHP5 to get all the vars (including private etc.) use:

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();
rec at NOSPAM dot instantmassacre dot com 23-Jan-2003 04:23
If you want to retrieve the class vars from within the class itself, use $this.

<?php
class Foo {

    var $a;
    var $b;
    var $c;
    var $d;
    var $e;

    function GetClassVars()
    {
        return array_keys(get_class_vars(get_class($this))); // $this
    }

}

$Foo = new Foo;

$class_vars = $Foo->GetClassVars();

foreach ($class_vars as $cvar)
{
    echo $cvar . "<br />\n";
}
?>

Produces, after PHP 4.2.0, the following:

a
b
c
d
e
get_class_methods
get_class
Классы/Объекты


Возвращает имя класса, к которому принадлежит объект

get_class_vars
get_declared_classes
Классы/Объекты
PHP Manual

get_class

(PHP 4, PHP 5)

get_class — Возвращает имя класса, к которому принадлежит объект

Описание

string get_class ([ object $object = NULL ] )

Возвращает имя класса, экземпляром которого является объект object.

Список параметров

object

Тестируемый объект. Внутри класса этот параметр может быть опущен.

Возвращаемые значения

Возвращает имя класса, к которому принадлежит экземпляр object. Возвращает FALSE, если object не является объектом.

Если параметр object опущен внутри класса, будет возвращено имя этого класса.

Ошибки

Если get_class() будет вызвана с чем-то другим, не являющимся объектом, будет вызвана ошибка уровня E_WARNING.

Список изменений

Версия | Описание
Начиная с версии 5.3.0 | NULL стал значением по умолчанию для параметра object, поэтому передача NULL в object теперь имеет тот же самый эффект, как и отсутствие какой-либо передачи вообще.
Начиная с версии 5.0.0 | Имя класса теперь возвращается в оригинальной записи.
Начиная с версии 5.0.0 | Параметр object стал необязателен при вызове из метода объекта.

Примеры

Пример #1 Использование get_class()

<?php

class foo {
    function name()
    {
        echo "My name is " , get_class($this) , "\n";
    }
}

// создание объекта
$bar = new foo();

// внешний вызов
echo "Its name is " , get_class($bar) , "\n";

// внутренний вызов
$bar->name();

?>

Результат выполнения данного примера:

Its name is foo
My name is foo

Пример #2 Использование get_class() в родительском классе

<?php

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this));
        var_dump(get_class());
    }
}

class foo extends bar {
}

new foo;

?>

Результат выполнения данного примера:

string(3) "foo"
string(3) "bar"

Смотрите также

  • get_called_class() - Имя класса, полученное с помощью позднего статического связывания
  • get_parent_class() - Возвращает имя родительского класса для объекта или класса
  • gettype() - Возвращает тип переменной
  • is_subclass_of() - Проверяет, содержит ли объект в своем дереве предков указанный класс

User Contributed Notes

macnimble at gmail dot com 17-Mar-2012 07:24
Need a quick way to parse the name of a class when it's namespaced? Try this:

<?php
namespace Engine;
function parse_classname ($name)
{
  return array(
    'namespace' => array_slice(explode('\\', $name), 0, -1),
    'classname' => join('', array_slice(explode('\\', $name), -1)),
  );
}
final class Kernel
{
  final public function __construct ()
  {
    echo '<pre>', print_r(parse_classname(__CLASS__),1), '</pre>';
    // Or this for a one-line method to get just the classname:
    // echo join('', array_slice(explode('\\', __CLASS__), -1));
  }
}
new Kernel();
?>

Outputs:
Array
(
    [namespace] => Array
        (
            [0] => Engine
        )

    [classname] => Kernel
)
mail dot temc at gmail dot com 06-Dec-2011 02:51
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here's a good example that should fix that for ever:

<?php

class Foo {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

class Bar extends Foo {

}

class Quux extends Bar {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

$foo = new Foo();
$bar = new Bar();
$quux = new Quux();

echo "\n--doMethod--\n";

$foo->doMethod();
$bar->doMethod();
$quux->doMethod();

echo "\n--doGetClassThis--\n";

$foo->doGetClassThis();
$bar->doGetClassThis();
$quux->doGetClassThis();

echo "\n--doGetClass--\n";

$foo->doGetClass();
$bar->doGetClass();
$quux->doGetClass();

?>

OUTPUT:

--doMethod--
Foo::doMethod
Foo::doMethod
Quux::doMethod

--doGetClassThis--
Foo::doThat
Bar::doThat
Quux::doThat

--doGetClass--
Foo::doThat
Foo::doThat
Quux::doThat
ozana at omdesign dot cz 28-Nov-2011 07:53
Simplest way how to gets Class without namespace

<?php
namespace a\b\c\d\e\f;

class Foo {

  public function __toString() {
    $class = explode('\\', __CLASS__);
    return end($class);
  }
}

echo new Foo(); // prints Foo
?>
Michael Richey 31-Oct-2011 12:01
Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it's not available.  Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

<?php
abstract class Singleton {
    protected static $m_pInstance;
    final public static function getInstance(){
        $class = static::getClass();
        if(!isset(static::$m_pInstance[$class])) {
            static::$m_pInstance[$class] = new $class;
        }
        return static::$m_pInstance[$class];
    }
    final public static function getClass(){
        return get_called_class();
    }
}

// I don't remember where I found this, but this is to allow php < 5.3 to use this method.
if (!function_exists('get_called_class')) {
    function get_called_class($bt = false, $l = 1) {
        if (!$bt)
            $bt = debug_backtrace();
        if (!isset($bt[$l]))
            throw new Exception("Cannot find called class -> stack level too deep.");
        if (!isset($bt[$l]['type'])) {
            throw new Exception('type not set');
        }
        else
            switch ($bt[$l]['type']) {
                case '::':
                    $lines = file($bt[$l]['file']);
                    $i = 0;
                    $callerLine = '';
                    do {
                        $i++;
                        $callerLine = $lines[$bt[$l]['line'] - $i] . $callerLine;
                    } while (stripos($callerLine, $bt[$l]['function']) === false);
                    preg_match('/([a-zA-Z0-9\_]+)::' . $bt[$l]['function'] . '/', $callerLine, $matches);
                    if (!isset($matches[1])) {
                        // must be an edge case.
                        throw new Exception("Could not find caller class: originating method call is obscured.");
                    }
                    switch ($matches[1]) {
                        case 'self':
                        case 'parent':
                            return get_called_class($bt, $l + 1);
                        default:
                            return $matches[1];
                    }
                // won't get here.
                case '->': switch ($bt[$l]['function']) {
                        case '__get':
                            // edge case -> get class of calling object
                            if (!is_object($bt[$l]['object']))
                                throw new Exception("Edge case fail. __get called on non object.");
                            return get_class($bt[$l]['object']);
                        default: return $bt[$l]['class'];
                    }

                default: throw new Exception("Unknown backtrace method type");
            }
    }
}

class B extends Singleton {
}

class C extends Singleton {
}

$b = B::getInstance();
echo 'class: '.get_class($b);

echo '<br />';

$c = C::getInstance();
echo echo 'class: '.get_class($c);
?>
This returns:
class: b
class: c
me at nwhiting dot com 06-Dec-2010 08:14
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
 * Returns the name of a class using get_class with the namespaces stripped.
 * This will not work inside a class scope as get_class() a workaround for
 * that is using get_class_name(get_class());
 *
 * @param  object|string  $object  Object or Class Name to retrieve name

 * @return  string  Name of class with namespaces stripped
 */
function get_class_name($object = null)
{
    if (!is_object($object) && !is_string($object)) {
        return false;
    }

    $class = explode('\\', (is_string($object) ? $object : get_class($object)));
    return $class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class TestClass {

    public function test()
    {
       return get_class_name(get_class());
    }
}

class GetClassNameTest extends \PHPUnit_Framework_TestCase
{
    public function testGetClassName()
    {
        $class  = new TestClass();
        $std  = new \stdClass();
        $this->assertEquals('TestClass', get_class_name($class));
        $this->assertEquals('stdClass', get_class_name($std));
        $this->assertEquals('Test', get_class_name('Test'));
        $this->assertFalse(get_class_name(null));
        $this->assertFalse(get_class_name(array()));
        $this->assertEquals('TestClass', $class->test());
    }
}
?>
Aaron 18-Jun-2010 11:14
This can sometimes be used in place of get_called_class(). I used this function in a parent class to get the name of the class that extends it.
ovidiu.bute [at] gmail.com 05-Apr-2010 10:23
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

namespace Shop;

<?php
class Foo
{
  public function __construct()
  {
     echo "Foo";
  }
}

//Different file

include('inc/Shop.class.php');

$test = new Shop\Foo();
echo get_class($test);//returns Shop\Foo
?>
Tom Brown 17-Sep-2009 11:02
As of 5.3.0 this function seems to have started throwing an E_WARNING error if you pass it a non-object. Supress that with "@" if you are actually checking and handling the false return code.
Lanselot 11-Feb-2009 02:09
Beware if you're omitting the parameter on inherited classes.
It'll return the class name of the method where it's called.

<?php
class A {
    function foo() {
      return get_class();
    }
}
class B extends A {
   function bar() {
      return get_class();
   }
}
$instance = new B();
echo $instance->bar(); //Prints 'B';
echo $instance->foo(); //Prints 'A';
?>
danbettles at yahoo dot co dot uk 08-Oct-2008 11:56
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function.  When called in a static method, this function returns the name of the class the call was made against.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
Maik 04-Oct-2008 08:36
The code just worked fine with PHP 5.3.
Thanks to you it could be rebuild to work with earlier versions of PHP 5.

I just changed the 'static' to 'self' and die() to an Exception.

<?php
// This one extends Singleton with proper class name
class someSingleton extends Singleton {
    public static function getInstance() {
        parent::$__CLASS__ = __CLASS__;
        parent::getInstance();
    }
}
// This one does the logic
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance = null;

    protected function __construct() {}
    abstract protected function init();

    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        $class = self::getClass();

        if (self::$instance === null) {
            self::$instance = new $class();
            self::$instance->init();
        }

        return self::$instance;
    }

    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = self::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class)
            throw new Exception("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");

        return $implementing_class;
    }
}
?>
Edward 21-Aug-2008 03:26
The code in my previous comment was not completely correct. I think this one is.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;

    protected function __construct() {
    }

    abstract protected function init();

    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        static $instance;

        $class = self::getClass();

        if ($instance === null) {
            $instance = new $class();
            $instance->init();
        }

        return $instance;
    }

    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = static::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return $implementing_class;
    }
}
?>
Edward 20-Aug-2008 05:42
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance;

    protected function __construct() {
        static::$instance = $this;
        $this->init();
    }

    abstract protected function init();

    protected function getInstance() {
        $class = static::getClass();

        if (static::$instance===null) {
            static::$instance = new $class;
        }

        return static::$instance;
    }

    private static function getClass() {
        if (static::$__CLASS__ == __CLASS__) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return static::$__CLASS__;
    }
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
    protected static $__CLASS__ = __CLASS__; // Provide this in each singleton class.

    protected function someFunction() {
        $instance = static::getInstance();
        // ...
    }
}
?>

Hope this helps you save some time :)
James 22-Jun-2008 02:46
To get round this problem, another option is a factory to create singletons.

<?php
class Factory {
  private static $instances = array();
  public static function getInstance($class_name) {
    if(!array_key_exists($class_name, self::$instances)) {
      self::$instances[$class_name] = new $class_name();
    }
    return self::$instances[$class_name];
  }
}
?>

I guess you could modify this to create singletons from some, and prototypes for the rest.

There's probably some good way to stop people instantiating objects directly. Perhaps by using the backtrace in the constructor of the class to ensure that it was indeed the Factory that created the object.
Anonymous 29-Apr-2008 09:59
I jumped the gun. The following code also working for statics called inside other classes.

<?php
        for( $i=0 ; $i < count($bt) ; $i++)
        {
            if($bt[$i]['function'] == 'getInstance')
            {
                $class = $bt[$i]['class'];

            } else {
                break;
            }
        }
?>
dave dot zap at gmail dot com 29-Apr-2008 09:13
Take care using the backtrace method to find the calling class of a static method, you should step backward through the array and find a match for your getInstance() function. In backtrace the class name you want is not always the last item in the array.

I will not post the whole singleton class here, but have made the following modification to Frederik Krautwald's method (found below)

<?php
$bt = debug_backtrace();
// this method is count($bt)-1) by Frederik will fall over when calling getInstance from within an include file.
//$class = $bt[count($bt) - 1]['class'];

for( $i=count($bt)-1 ; $i > 0 ; $i--)
{
    if($bt[$i]['function'] == 'getInstance')
    {
        $class = $bt[$i]['class'];
        break;
    }
}
?>
Anonymous 12-Apr-2008 02:01
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not 'know' the name of the calling subclass', so I use a backtrace to determine it. I don't like hacks like this, but as long as PHP doesn't have an alternative, this is what has to be done:

public function table_name() {
        $result = null;
        if (isset($this)) { // object context
            $result = get_class($this);
        }
        else { // class context
            $result = get_class();
            $trace = debug_backtrace();
            foreach ($trace as &$frame) {
                if (!isset($frame['class'])) {
                    break;
                }
                if ($frame['class'] != $result) {
                    if (!is_subclass_of($frame['class'], $result)) {
                        break;
                    }
                    $result = $frame['class'];
                }
            }
        }
        return $result;
    }
frederic dot sureau at gmail dot com 29-Feb-2008 11:01
@ hek :

The problem is that the method getInstance() in a Singleton must be static, so we cannot use $this because it doesn't exists :(
andregs at NOSPAM dot gmail dot NOSPAM dot com 21-Feb-2008 01:17
After reading the previous comments, this is the best I've done to get the final class name of a subclass:

<?php

class Singleton
{
   private static $_instances = array();
   protected final function __construct(){}

   /**
    * @param string $classname
    * @return Singleton
    */
   protected static function getInstance()
   {
      $classname = func_get_arg(0);
      if (! isset(self::$_instances[$classname]))
      {
         self::$_instances[$classname] = new $classname();
      }
      return self::$_instances[$classname];
   }

}

class Child extends Singleton
{
   /**
    * @return Child
    */
   public static function getInstance()
   {
      return parent::getInstance(get_class());
   }
}

?>

Subclasses must override "getInstance" and cannot override "__construct".
hek at theeks dot net 10-Jan-2008 12:51
I may be missing something, but in all the laments wishing for some sort of get_real_class() function to return the final class name of of a derived class (a.k.a. subclass), my testing suggests that the existing get_class() function can do this just fine, at least when an object of the derived class has been instantiated.

Consider:

<?php

class BaseClass {
  function whoAmI() {
    return get_class($this);
  }
}

class DerivedClass extends BaseClass {}

$baseInstance = new BaseClass();
$derivedInstance = new DerivedClass();

echo $baseInstance->whoAmI(); // returns "BaseClass"
echo $derivedInstance->whoAmI(); // returns "DerivedClass"
echo BaseClass::whoAmI(); // returns an empty string
echo DerivedClass::whoAmI(); // returns an empty string

?>

In my opinion, the final two calls in my example should actually throw runtime errors, but apparently they don't.

Now consider:

<?php

class BaseClass {
  function whoAmI() {
    return get_class(/* $this */);
  }
}

class DerivedClass extends BaseClass {}

$baseInstance = new BaseClass();
$derivedInstance = new DerivedClass();

echo $baseInstance->whoAmI(); // returns "BaseClass"
echo $derivedInstance->whoAmI(); // returns "BaseClass"
echo BaseClass::whoAmI(); // returns "BaseClass"
echo DerivedClass::whoAmI(); // returns "BaseClass"

?>

So you can see, if you need to know the final class name of an *object* constructed from a subclass there's no problem, though if what you're after is the final class name of a derived class *for which you have no instance handy* then what I've demonstrated here isn't going to help you with that -- though it's hard for me to imagine you could write code like DerivedClass::whoAmI() and seriously care about the value you get back, since this line of code itself shows that you know the final class name of the derived class already to begin with!  But people are clever, so maybe there is some case where my simple view on this breaks down.  Anyway, happy trails.  I hope this helps someone someday.
dodgie74 at NOSPAM dot yahoo dot NOSPAM dot co dot uk 09-Sep-2007 05:40
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        //here, we want "self" to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
        return $this->m_instanceName . ' - ' . self::classDisplayName();
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

In the above example, assuming runtime binding (where the keyword "self" refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance - Derived Class

However, assuming compile-time binding (where the keyword "self" refers to the class in which the method is defined), which is how php works, the output would be:

My Instance - Base Class

The oddity here is that "$this" is bound at runtime to the actual class of the object (obviously) but "self" is bound at compile-time, which seems counter-intuitive to me. "self" is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which "self" ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to "self" being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the "self" keyword for static methods:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        $realClass = get_class($this);
        return $this->m_instanceName . ' - ' . call_user_func(array($realClass, 'classDisplayName'));
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

Output:
My Instance - Derived Class

I realise that some people might respond "why don't use just just the class name with ' Class' appended instead of the classDisplayName() method", which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.
bramus at bram dot us 20-Aug-2007 08:40
@ Frederik :

<?
$class = $bt[count($bt) - 1]['class'];
?>

should be

<?
$class = $bt[count($bt) - 2]['class'];
?>

;-)
Frederik Krautwald 25-Jun-2007 08:13
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
    protected static $_instances = array();

    protected function __construct() {}

    protected static function getInstance() {
        $bt = debug_backtrace();
        $class = $bt[count($bt) - 1]['class'];
        if (!isset(self::$_instances[$class])) {
            self::$_instances[$class] = new $class();
        }
        return self::$_instances[$class];
    }
}
class A extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class B extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class C extends A {
    public static function getInstance() {
        return parent::getInstance();
    }
}

$a = A::getInstance();
$b = B::getInstance();
$c = C::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
echo "\$c is a " . get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.
mightye at gmail dot com 23-Jun-2007 06:20
To: Bryan

In this model it is still workable if your singleton variable is actually an array.  Consider:
<?php
abstract class Singleton {
    protected final static $instances = array();

    protected __construct(){}

    protected function getInstance() {
        $class = get_real_class(); // imaginary function returning the final class name, not the class the code executes from
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
class A extends Singleton {
}
class B extends Singleton {
}

$a = A::getInstance();
$b = B::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
?>
This would output:
$a is a A
$b is a B

The only alternative as described elsewhere is to make getInstance() protected abstract, accept the class name as an argument, and extend this call with a public final method for every sub-class which uses get_class() in its local object scope and passes it to the superclass.

Or else create a singleton factory like this:
<?php
final class SingletonFactory {
    protected static $instances = array();

    protected getInstance($class) {
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
?>
The downside to this of course to this latter model is that the class itself doesn't get to decide if it is a singleton, the calling code gets to decide this instead, and a class that really wants or *needs* to be a singleton has no way to enforce this, not even by making its constructor protected.

Basically these design patterns, and various other meta manipulations (things which operate on the nature of the object, not on the data the object holds) could benefit greatly from knowing exactly what the final type of this object is, and not having native access to this information obligates work-arounds.
Bryan 19-Jun-2007 08:07
janci's Singleton example is all well and good, until you create another class "Bar" which also extends Singleton.

<?php
$single_foo = Foo::getInstance();
$single_bar = Bar::getInstance();
?>

$single_bar will now be an instance of Foo! This is because there is only one copy of the static variable $__instance in the Singleton class. Here is a better Singleton class:

<?php
abstract class Singleton {
    static $_instances = array();

    //Prevent singletons from being instantiated other than via getInstance();
    protected function __construct() {}
    protected function __clone() {}

    static function getInstance($class_name) {
        if(!isset(self::$_instances[$class_name])) {
            self::$_instances[$class_name] = new $class_name();
        }
        return self::$_instances[$class_name];
    }
}?>

Unfortunately, you are still required to define Foo as janci does. I would love to see an example where the only thing you add to the class is "extends Singleton" and you're done, but that seems to be impossible.
janci 30-Apr-2007 12:00
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern.

There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    public static function getInstance()
    {
        if (self::$__instance == false)
        {
            // This acctually is not what we want, $class will always be 'Singleton' :(
            $class = get_class();
            self::$__instance = new $class();
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // ...
}

$single_foo = Foo::getInstance();
?>
This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11

The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    protected static function getInstance($class)
    {
        if (self::$__instance == false)
        {
            if (class_exists($class))
            {
                self::$__instance = new $class();
            }
            else
            {
                throw new Exception('Cannot instantiate undefined class [' . $class . ']', 1);
            }
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // You have to overload the getInstance method in each extended class:
    public static function getInstance()
    {
        return parent::getInstance(get_class());
    }
}

$single_foo = Foo::getInstance();
?>

This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;)
yicheng zero-four at gmail dot com 27-Apr-2007 12:29
To matsgefvert dot se and Marc,

I'm sorry but I'm still having a very difficult time understanding why you would want this behavior.  I understand that you are generating some code for some persistent layer for database access.

In your code example, Marc, you say that you would like the SomeTable::read() to return "SomeTable" when called from your client.  Yet, at this point you *know* what the class name is.  Even assuming you are generating this code automatically, you can simply generate your SomeTable class as such.

<?php

class PersistedObject {
  //...
  public static function read($table, $key){
    // do some databasey stuff
    // with $table which is the table name
    return $table;
  }
}

class SomeTable extends PersistedObject {
  //...
  // make a copy in the child class
  public static function read($key){
    $table = get_class();
    return parent::read($table, $key);
  }
}

// this will now return "SomeTable"
$someTableObject = SomeTable::read(1234);

?>

I'm still failing to see how this would provide but a convenience for very rare & specific issues, at the cost of non-OOP behavior by allowing static methods to bind to objects instead of classes.

One of the most common uses for get_class() is for debugging lines, for example:

<?php

class PersistedObject {
  //...
  public static function transaction($params){
    // do some stuff
    if ($error_occurred){
      echo "Error : WTFBBQ happened in " . get_class() . "::" . __FUNCTION__ . ".  Time to get some coffee!";
  }
}

class SomeTable extends PersistedObject {
  //...
}

SomeTable::transaction( $someParams );
?>

Now, when an error occurs inside the call to SomeTable::transaction(), we get incorrect error output.
Kerry Kobashi 14-Apr-2007 11:58
It should be noted that class names are represented in lowercase under PHP 4.x.

class MyClass {
   function MyClass() {
   }
   function ShowClass() {
      echo get_class($this);
   }
}

$p = new MyClass();
$p->ShowClass();

Displays:

myclass

If you serialize $p, you will also see that the class name is lower case as well:

$p = new MyClass();
echo serialize($p);

Displays:

O:7:"myclass":1:{s:3:"val";i:100;}

In my case, this is an important point for mapping class names to database table names (and vice versa).
Marc W. 13-Apr-2007 09:40
The previous comment (from matsgefvert dot se) is 100% correct. To further elaborate on the persistence layers example suggested, consider the case where you are dynamically creating inherited objects. For example:
<?php

class PersistedObject {
//...
public static function read($key){
//You will need the table name here to actually read
// from the persistence medium
echo get_class();
}

class SomeTable extends PersistedObject {
//...
}

/*
Somewhere else in our code we would like to call the read method
*/

$someTableObject = SomeTable::read(1234);

?>
Remember that the SomeTable class would be generated on the fly, probably by some DB schema. The problem is that you would actually like the above example to output "SomeTable", but unfortunately, it will output "PersistedObject".
spam at matsgefvert dot se 24-Feb-2007 01:37
I disagree with the notion that the authors of the previous posts are unfamiliar with OOP. Without the ability to know from general (parent) objects what kind of classes we're operating on, it makes things rather difficult, especially in building frameworks that rely heavily on class types (e.g. persistence layers).

The proposed BooBoof::getclass() and CooCoof::getclass() scheme will not work in some particular scenarios since static calls aren't virtual, which means a parent class will always call its own getclass() function instead of the one needed to find out the class name.

The only solution I've found is to pass along a string containing the class name we're working on to the generalized functions. It is however an ugly solution, certainly less than ideal and goes against what OOP and reflection is all about, IMHO.
yicheng zero-four at gmail dot com 18-Jan-2007 12:22
This a response to luke at liveoakinteractive dot com and davidc at php dot net.  Static methods and variables, by definition, are bound to class types not object instances.  You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious.  Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).

Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it.  The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class.  The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass().  So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?"  The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior.  CooCoof::getclass() will have the expected behavior.
makc dot the dot great at gmail dot com 17-Dec-2006 09:29
Check it out:

<?php

class A {
 function s () { return "A::s"; }
 function s1 () { return $this->s(); }
}

class B extends A {
 function s () { return "B::s"; }
}

$a = new A(); echo $a->s1();
echo "<br>";
$b = new B(); echo $b->s1();
echo "<br>";

class C {
 static function s () { return "C::s"; }
 static function s1 () { return self::s(); }
}

class D extends C {
 static function s () { return "D::s"; }
}

echo C::s1();
echo "<br>";
echo D::s1();
echo "<br>";

?>

Output:
A::s
B::s
C::s
C::s

Seems like static function always belong to its class.
luke at liveoakinteractive dot com 06-Dec-2006 07:03
This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.

Observe the following:
<?php
class BooBoof {
  public static function getclass() {
    return __CLASS__;
  }

  public function retrieve_class() {
    return get_class($this);
  }
}

class CooCoof extends BooBoof {
}

echo CooCoof::getclass();
// outputs BooBoof

$coocoof = new CooCoof;
echo $coocoof->retrieve_class();
// outputs CooCoof
?>

__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.
benjaminhill at gmail dot com 27-Apr-2006 10:47
More funkyness:

class Parent {
   function displayTableName() {
      echo get_class($this);
      echo get_class();
   }
}

class Child {
   function __construct() {
      $this->displayTableName();
   }
}

Will return
- Child
- Parent

So when they say "the object isn't required in PHP5" - they don't really mean it.
brjann at NOSPAMATALLgmail dot com 16-Nov-2005 12:39
This behavior is unexpected, but good to be aware of

class parentclass {
    public function getClass(){
        echo get_class($this); //using "$this"
    }
}
class child extends parentclass {
}

$obj = new child();
$obj->getClass(); //outputs "child"

class parentclass {
    public function getClass(){
        echo get_class(); //note, no "$this"
    }
}
class child extends parentclass {
}

$obj = new child();
$obj->getClass(); //outputs "parentclass"
davidc at php dot net 13-Oct-2005 10:25
As of php5, you cannot use get_class($this); in a public static function. You would have to do something like this:

<?php

class BooBoof {
    public static function getclass()
    {
        return __CLASS__;
    }
}

$c = BooBoof::getclass();
print $c;
?>

To get the class since you cannot use
<?php
public static function getclass()
{
    return get_class($this);
}
?>

Rather simple and straightforward but that might help some people that are searching for it..
wired at evd dot ru 25-Sep-2005 02:25
There is one unexpected bahaviour (for me as least):

<?php

  class parent
  {
    ...

    public function getInstance ($id)
    {
      ...

      print get_class() . "\n" . __CLASS__;

      ...
    }
  }

  class child extends parent
  {
    ...
  }

  child::getInstance(...);
?>

This code will produce:

  parent
  parent

So I can't make "new $className(...)" in getInstance(). The only option is to do a fabric.
kunxin at creaion dot com 25-Jul-2005 05:30
I just migrated from PHP 4 to PHP 5 and noticed that in PHP 5.03 that a lot of code dependent on get_class() and its variants stop working.

It turns out that get_class() and its variants are now case-sensitive.
refrozen dot com 05-Jul-2005 03:01
philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns
MagicalTux at FF.ST 02-Feb-2004 04:11
Note that the constant __CLASS__ is different from get_class($this) :
<?
  class test {
    function whoami() {
      echo "Hello, I'm whoami 1 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
    }
  }
  class test2 extends test {
    function whoami2() {
      echo "Hello, I'm whoami 2 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
      parent::whoami(); // call parent whoami() function
    }
  }
  $test=new test;
  $test->whoami();
  $test2=new test2;
  $test2->whoami();
  $test2->whoami2();
?>

The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.
Dan 29-Jan-2003 10:00
This function does return the class name in lowercase, but that does not seem to make any difference. The code below, although very sloppy, works fine in all of the following configurations.

PHP 4.2.2 on Windows NT5 with Apache 1.3.24
PHP 4.2.1 in Zend Development Environment on box above
PHP 4.2.3 on Linux RedHat 7.3 with Apache 1.3.27

class TeSt {
   var $a;
   var $b = "Fred";

   // Notice the case difference in the constructor name

   function Test() {
      $classname = get_class($this); // $classname = "test"
      $this->ra = get_class_vars($classname);
   }
}
// Next line also works with Test(), TEST(), or test()
$obj = new TeSt();
print_r($obj->ra);

Result :
   Array
   (
       [a] =>
       [b] => Fred
   )
oliver DOT pliquett @mediagear DOT de 13-Aug-2002 08:07
This function can become _VERY_ helpful if you want to return a new object of the same type. See this example:

<?php
class Foo{
    var $name;

    function Foo( $parameter ){
        $this->name = $parameter;
    }

    function whoami() {
        echo "I'm a " . get_class( $this ) ."\n";
    }

    function getNew() {
        $className = get_class( $this );

        // here it happens:
        return new $className ( "world" ) ;
    }
}
class Bar extends Foo {

    function Bar( $name ){
        $this->Foo( $name );
    }

    function welcome() {
        echo "Hello, " . $this->name .  "! \n";
    }
}

// We generate a Bar object:
$myBar = new Bar( "Oliver" );
$myBar->welcome();

//now let's instanciate a new Bar object.
//note: this method is inherited from Foo by Bar!

$baba = $myBar->getNew();

$baba->welcome();
$baba->whoami();

/* Output:
Hello, Oliver!
Hello, world!
I'm a bar
*/
?>
philip at cornado dot com 20-Jun-2002 12:15
As of PHP 4.3.0 the constant __CLASS__ exists and contains the class name.
get_class_vars
get_declared_classes
Классы/Объекты


Возвращает массив с именами объявленных классов

get_class
get_declared_interfaces
Классы/Объекты
PHP Manual

get_declared_classes

(PHP 4, PHP 5)

get_declared_classes — Возвращает массив с именами объявленных классов

Описание

array get_declared_classes ( void )

Возвращает объявленные классы.

Возвращаемые значения

Возвращает массив имен объявленных классов текущего скрипта.

Замечание:

Учтите также, что в зависимости от расширений, собранных или загруженных в PHP, может варьироваться число дополнительных классов. Это означает, что вы не сможете использовать собственные классы с данными именами. Список предопределенных классов находится в разделе дополнения "Предопределенные Классы".

Примеры

Пример #1 Пример использования get_declared_classes()

<?php
print_r(get_declared_classes());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

Смотрите также

  • class_exists() - Проверяет, был ли объявлен класс
  • get_declared_interfaces() - Возвращает массив всех объявленных интерфейсов
  • get_defined_functions() - Возвращает массив всех определённых функций

User Contributed Notes

dcahh at gmx de 29-Feb-2008 09:23
This function considers only classes and subclasses. Not subsubclasses.

In fact I have code that provides an abstract class and then classes using this abstract class. Further I have subclasses to my concrete classes - which is why my subclasses are not listed within the returned array.
dexen + goofy _ pl 25-Sep-2007 11:32
Summary:
 * in PHP 5.1 class names have case preserved
 * contrary, in PHP 4.4 class names are downcased, withe exception of a few build-in ones

The get_declared_classes() funcition returns the list of names with case preserved, as of PHP 5.1 series (prolly 5.0 too, but i have no way to test it right now). Since PHP generally is caseless in regard to names of classes, this may come at a surprise. Also, this could potentially break older code asssuming downcased list.

Take extra care when  checking for existence of a class. Following example is, potentially, error prone: <?php in_array( $className, $classget_declared_classes() ) ?>

A sure-fire (while slower) way would be to iterate over the array and normalize case to, say, lower:

<?php
$exists = FALSE;
$className = strtolower( $className );
foreach ( get_declared_classes() as $c ) {
    if ( $className === strtolower( $c ) ) {
        $exists = TRUE;
        break;
    }
}?>

Optimization of the above snippet is left as a simple excercise to the reader ;)
-- dexen deVries
matt at mattsoft dot net 21-Dec-2005 02:58
classes can't be unloaded. probably not very practical to implement that in a future version. I wouldn't go out of my way to do it if I were zend. you're better off finding a workaround. it's better programming technique to find a way around having to do that anyway.

http://www.zend.com/zend/week/week223.php#Heading10
22-Mar-2005 09:16
Regarding note of 3-21:

<?php

class myclass {}

$class = 'myclass';
$instance = new $class();

?>

This function could also be used to determine the names of classes defined in a particular file by calling it before and after include. It's hardly a pointless function.
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 07:41
The array returned by this function will be in the order the classes were defined / included / required and this order does not appear to change.

For example:

<?PHP

//define classone
class classone { }

//define classtwo
class classtwo { }

//This will show X classes (built-ins, extensions etc) with
//classone and classtwo as the last two elements

print_r(get_declared_classes());

//define classthree
class classthree { }

//...and four
class classfour { }

//Shows the same result as before with class three and four appended
print_r(get_declared_classes());

?>

Output:

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
 )

and...

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
   [12] => classthree
   [13] => classfour
)
Jazeps Basko 07-Feb-2004 11:52
In PHP5, you don't get declared interfaces by calling this function!!!
To get interfaces you should use get_declared_interfaces(). However, to check if an interface is already defined, you should use class_exists()! This is strange, but PHP team does not think so.
smokey 20-Mar-2003 03:06
you cannot remove them. they are "defined", which happens when the class is being loaded from the parser. you just deleted an instance of a class.
Leigh Purdie 23-Jan-2003 01:01
Note that classes remain in the declared list, even when their associated object is undef'd.

eg:
    $object = new MyClass;
    print_r(get_declared_classes());

    undef($object);
    print_r(get_declared_classes());

- the two print_r's will return the same data.
Not sure how to remove a class from the declared list.
get_class
get_declared_interfaces
Классы/Объекты


Возвращает массив всех объявленных интерфейсов

get_declared_classes
get_declared_traits
Классы/Объекты
PHP Manual

get_declared_interfaces

(PHP 5)

get_declared_interfaces — Возвращает массив всех объявленных интерфейсов

Описание

array get_declared_interfaces ( void )

Возвращает объявленные интерфейсы.

Возвращаемые значения

Возвращает массив имен всех объявленных интерфейсов в текущем скрипте.

Примеры

Пример #1 Пример использования get_declared_interfaces()

<?php
print_r(get_declared_interfaces());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

Смотрите также

  • interface_exists() - Проверяет, определен ли интерфейс
  • get_declared_classes() - Возвращает массив с именами объявленных классов
  • class_implements() - Return the interfaces which are implemented by the given class

User Contributed Notes

There are no user contributed notes for this page.
get_declared_classes
get_declared_traits
Классы/Объекты


Returns an array of all declared traits

get_declared_interfaces
get_object_vars
Классы/Объекты
PHP Manual

get_declared_traits

(Информация о версии неизвестна, возможно, только в SVN)

get_declared_traits — Returns an array of all declared traits

Описание

array get_declared_traits ( void )

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Returns an array with names of all declared traits in values. Returns NULL in case of a failure.

Смотрите также

  • class_uses() - Return the traits used by the given class

User Contributed Notes

There are no user contributed notes for this page.
get_declared_interfaces
get_object_vars
Классы/Объекты


Возвращает свойства указанного объекта

get_declared_traits
get_parent_class
Классы/Объекты
PHP Manual

get_object_vars

(PHP 4, PHP 5)

get_object_vars — Возвращает свойства указанного объекта

Описание

array get_object_vars ( object $object )

Возвращает видимые нестатические свойства указанного объекта object в соответствии с областью видимости.

Список параметров

object

Экземпляр объекта

Возвращаемые значения

Возвращает ассоциативный массив нестатических свойств объекта object, доступных в данной области видимости. Если свойству не было присвоено значение, оно будет возвращено со значением NULL.

Список изменений

Версия | Описание
5.3.0 | Функция теперь возвращает NULL, если object не является объектом.
до версии 5.3.0 | Если object не являлся объектом, get_object_vars() возвращала FALSE
prior to 4.2.0 | В случае если свойству объекта object не было присвоено значения, оно не возвращалось в массиве

Примеры

Пример #1 Пример использования get_object_vars()

<?php

class foo {
    private $a;
    public $b = 1;
    public $c;
    private $d;
    static $e;

    public function test() {
        var_dump(get_object_vars($this));
    }
}

$test = new foo;
var_dump(get_object_vars($test));

$test->test();

?>

Результат выполнения данного примера:

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}
array(4) {
  ["a"]=>
  NULL
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
  ["d"]=>
  NULL
}

Смотрите также

  • get_class_methods() - Возвращает массив имен методов класса
  • get_class_vars() - Возвращает объявленные по умолчанию свойства класса

User Contributed Notes

Fabien Haddadi 30-May-2012 09:42
It seems like there's no function that determines all the *static* variables of a class.

I've come out with this one as I needed it in a project:

<?php
function get_class_static_vars($object) {
     return array_diff(get_class_vars(get_class($object)), get_object_vars($object));
}
?>

It relies on an interesting property: the fact that get_object_vars only returns the non-static variables of an object.
Dionisiy 20-Apr-2012 06:21
Note that before PHP 5.3.9 numeric object variables of unserialized object are not public, and get_object_vars() won't return them:
https://bugs.php.net/bug.php?id=61774
elminster2031 at hotmail dot com 07-Jul-2010 12:30
Also note that this is recursive. For example:

<?php
class Sarah{

    private $Father;
    private $Mother;

    public function __construct(){
        $this->Father    =    NULL; //I don't know Sarah's Father
        $this->Mother    =    NULL; //I don't know Sarah's Mother
    }
}
class John_Connor{

    private $Father;
    private $Mother;

    public function __construct(){
        $this->Father    =    $this; //John went back in time and fathered himself
        $this->Mother    =    new Sarah(); //Sarah was his mom and his mate ewww
    }

    public function showParents(){
        return get_object_vars($this);
    }
}

$John    =    new John_Connor();
var_dump($John->showParents());
?>

You will see this outputs:

array(2) {
  ["Father"]=>
  object(John_Connor)#1 (2) {
    ["Father":"John_Connor":private]=>
    object(John_Connor)#1 (2) {
      ["Father":"John_Connor":private]=>
      *RECURSION*
      ["Mother":"John_Connor":private]=>
      object(Sarah)#2 (2) {
        ["Father":"Sarah":private]=>
        NULL
        ["Mother":"Sarah":private]=>
        NULL
      }
    }
    ["Mother":"John_Connor":private]=>
    object(Sarah)#2 (2) {
      ["Father":"Sarah":private]=>
      NULL
      ["Mother":"Sarah":private]=>
      NULL
    }
  }
  ["Mother"]=>
  object(Sarah)#2 (2) {
    ["Father":"Sarah":private]=>
    NULL
    ["Mother":"Sarah":private]=>
    NULL
  }
}
joelhy 12-Jun-2010 05:56
Here is a function for getting only public properties even if you are in the class:
<?php
function my_get_object_vars($obj) {
    $ref = new ReflectionObject($obj);
    $pros = $ref->getProperties(ReflectionProperty::IS_PUBLIC);
    $result = array();
    foreach ($pros as $pro) {
        false && $pro = new ReflectionProperty();
        $result[$pro->getName()] = $pro->getValue($obj);
    }

    return $result;
}
?>
benny at nospam dot com 26-Dec-2009 01:31
Be aware of the fact that this is scope-sensitive. If you're calling this from an objects own method, then private and protected vars will be outputted as well. Call it from outside the object and the result will most likely be what you want to archive.
rarioj at gmail dot com 08-Sep-2009 09:57
General purpose functions to convert an array (multidimensional) to object, and vice versa:

<?php

// From object to array.
function toArray($data) {
    if (is_object($data)) $data = get_object_vars($data);
    return is_array($data) ? array_map(__FUNCTION__, $data) : $data;
}

// From array to object.
function toObject($data) {
    return is_array($data) ? (object) array_map(__FUNCTION__, $data) : $data;
}

?>
huzursuz at mailinator dot com 02-Feb-2009 08:44
better version of conv_obj, based on XML... this converts XML to an array... use it by

<?php
$result = xmlobj2arr(simplexml_load_string($xmlContent));

function xmlobj2arr($Data) {
       if (is_object($Data)) {
               foreach (get_object_vars($Data) as $key => $val) {
                       $ret[$key] = xmlobj2arr($val);
               }
               return $ret;
       } elseif (is_array($Data)) {
               foreach ($Data as $key => $val) {
                       $ret[$key] = xmlobj2arr($val);
               }
               return $ret;
       } else {
               return $Data;
       }
}
?>
jon at websandbox dot net 05-Jul-2008 09:00
If you're using the SPL ArrayObject class (or similar, or the ArrayAccess interface), you may have noticed that it's difficult to loop through an object's properties.

get_object_vars does not return the properties of an ArrayObject.  The only workaround I can see is to use get_class_vars.

<?php
$obj = new ArrayObject();
$obj->foo = "bar";
$obj[] = "1";
$obj[] = "2";
foreach($obj as $key => $value) {
 // will iterate over the array, iterating over "1" and "2", but ignoring $obj->foo
}

var_dump($obj); // dumps the array values, ignores $obj->foo

$a = get_object_vars($obj); // returns an empty array

class Fart extends ArrayObject {
    public $foo = "bar";
}

$obj = new Fart();
$a = get_object_vars($obj); // return an empty array
$a = get_class_vars(get_class($obj)); // returns array("foo"=>"bar"), Yay!

/* The above works with subclasses as well */
class Toot extends Fart {
    public $weeble = "wobble";
}

$a = get_class_vars(get_class($obj));
// returns array("weeble" => "wobble", "foo"=>"bar"), Yay again!

?>

So, to iterate over the properties of an ArrayObject, and not the array values:

<?php

$obj = new Toot(); // which is a subclass of ArrayObject
$props = get_class_vars(get_class($obj));
foreach($props as $prop => $defaultValue) {
  $value = $obj->$prop; // now you have the property name and  its value
}

?>
pardini at gmail dot com 08-May-2008 04:38
get_object_vars() has confusing behaviour when called as get_object_vars($this) or similar: since a method inside a class definition can access private vars, apparently so can get_object_vars(), so it returns private vars as well.

A simple workaround is to define a method that in itself calls get_object_vars, like:

<?php
function getPublicObjectVars($obj) {
  return get_object_vars($obj);
}

class Smth {
  private $notShown = 1;
  public $shown = 2;

  function test() {
    $vars = get_object_vars($this); // includes 'notShown'
    $vars = getPublicObjectVars($this); // only 'shown'
  }

}
?>
Jaymon (php at marcyes dot com) 06-Jan-2008 11:16
This method returns all the public, private, and protected vars of a given object. There are some other solutions presented in the comments but they didn't seem to preserve arrays, etc..

Hope it can help someone...

<?php
function parseObject($obj, $values=true){

    $obj_dump  = print_r($obj, 1);
    $ret_list = array();
    $ret_map = array();
    $ret_name = '';
    $dump_lines = preg_split('/[\r\n]+/',$obj_dump);
    $ARR_NAME = 'arr_name';
    $ARR_LIST = 'arr_list';
    $arr_index = -1;

    // get the object type...
    $matches = array();
    preg_match('/^\s*(\S+)\s+\bObject\b/i',$obj_dump,$matches);
    if(isset($matches[1])){ $ret_name = $matches[1]; }//if

    foreach($dump_lines as &$line){

      $matches = array();

      //load up var and values...
      if(preg_match('/^\s*\[\s*(\S+)\s*\]\s+=>\s+(.*)$/', $line, $matches)){

        if(mb_stripos($matches[2],'array') !== false){

          $arr_map = array();
          $arr_map[$ARR_NAME] = $matches[1];
          $arr_map[$ARR_LIST] = array();
          $arr_list[++$arr_index] = $arr_map;

        }else{

          // save normal variables and arrays differently...
          if($arr_index >= 0){
            $arr_list[$arr_index][$ARR_LIST][$matches[1]] = $matches[2];
          }else{
            $ret_list[$matches[1]] = $matches[2];
          }//if/else

        }//if/else

      }else{

        // save the current array to the return list...
        if(mb_stripos($line,')') !== false){

          if($arr_index >= 0){

            $arr_map = array_pop($arr_list);

            // if there is more than one array then this array belongs to the earlier array...
            if($arr_index > 0){
              $arr_list[($arr_index-1)][$ARR_LIST][$arr_map[$ARR_NAME]] = $arr_map[$ARR_LIST];
            }else{
              $ret_list[$arr_map[$ARR_NAME]] = $arr_map[$ARR_LIST];
            }//if/else

            $arr_index--;

          }//if

        }//if

      }//if/else

    }//foreach

    $ret_map['name'] = $ret_name;
    $ret_map['variables'] = $ret_list;
    return $ret_map;

  }//method
?>
biga888 AT gmail 19-Nov-2007 12:48
Just thought I would pass this on.

Working with PHP 5.2.4

In Windows this works by reading the vars from the passed in object and copying them to the vars of the current object.

    public function copyMe(User $user) {
        $varArray = get_object_vars($this);
        $copyVarArray = get_object_vars($user);
        foreach ($varArray as $key=>$value) {
            $this->$key = $copyVarArray[$key];
        }
    }

This did not work in Linux, I had to add another function to return the array of vars. Calling get_array_vars on the passed in object would return an empty array.

        public function copyMe(User $user) {
        $varArray = $this->getArray();
        $copyVarArray = $user->getArray();
        foreach ($varArray as $key=>$value) {
            $this->$key = $copyVarArray[$key];
        }
    }

    public function getArray() {
        return get_object_vars($this);
    }
Hayley Watson 07-Oct-2007 04:31
Progressively simplifying the method of the previous post.

The first part of the simplification came when it was realised that everything being passed to it was being checked twice to see if it was an array or an object - once before the function is called, and once after the function had begin.
The latter pair of tests are retained so that they do not need to be made explicitly in other part of the program before calling the function in the first place.
<?php
function conv_obj($Data){
    if(is_object($Data)){
        foreach(get_object_vars($Data) as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }elseif(is_array($Data)){
        foreach($Data as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }else{
        return $Data;
    }
}
?>

Reversing the tests to get the simplest case out of the way first.
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)){
        foreach(get_object_vars($Data) as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }else{
        foreach($Data as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }
}
?>

The only difference between the two loops is in what they are iterating over.
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)){
        $vars = get_object_vars($Data);
        foreach($vars as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }else{
        $vars = $Data;
        foreach($vars as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }
}
?>

Moving the common tail of the if statement's two branches:
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)){
        $vars = get_object_vars($Data);
    }else{
        $vars = $Data;
    }

    foreach($vars as $key=>$val){
            $ret[$key]=conv_obj($val);
    }
    return $ret;
}
?>

A lot of the time $vars===$Data, and when it doesn't we don't need $Data any more anyway, so we re-use the $Data variable instead of bringing in a new $vars variable, and then we can drop the do-nothing else branch:
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)) $Data = get_object_vars($Data);

    foreach($Data as $key=>$val){
            $ret[$key]=conv_obj($val);
    }
    return $ret;
}
?>

A case for using array_map():
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)) $Data = get_object_vars($Data);

    $ret = array_map('conv_obj', $Data);
    return $ret;
}
?>

And finally the return variable is otherwise unused:
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)) $Data = get_object_vars($Data);

    return array_map('conv_obj', $Data);
}
?>
firemouth at gmail dot com 10-Sep-2007 06:48
This is a slight modification of the previous poster's function.  We ran into a problem using this function when we had a JS array nested inside a JS hash.

Something like this...

myHash = new Hash();
myHash[address] = new Array();

When we threw that at this function, it found the first hash as an object, and then using the previous poster's function, it did not consider the array as an "object."  Instead it gave us a std_object type and we were unable to make any use of it.

The modification we made was adding a check for is_array inside both the is_object and is_array checks when you call the function.  This checks for an array inside either an object or a nested array.

function conv_obj($Data){
    if(is_object($Data)){

        foreach(get_object_vars($Data) as $key=>$val){
            if(is_object($val) || is_array($val)){
                $ret[$key]=conv_obj($val);
            }else{
                $ret[$key]=$val;
            }
        }
        return $ret;
    }elseif(is_array($Data)){
        foreach($Data as $key=>$val){
            if(is_object($val) || is_array($val)){
                $ret[$key]=conv_obj($val);
            }else{
                $ret[$key]=$val;
            }
        }
        return $ret;
    }else{
        return $Data;
    }
}
C.H. 15-Aug-2007 06:03
function conv_obj($Data){
     if(is_object($Data)){
         foreach(get_object_vars($Data) as $key=>$val){
             if(is_object($val)){
                 $ret[$key]=conv_obj($val);
             }else{
                 $ret[$key]=$val;
             }
         }
         return $ret;
     }elseif(is_array($Data)){
         foreach($Data as $key=>$val){
             if(is_object($val)){
                 $ret[$key]=conv_obj($val);
             }else{
                 $ret[$key]=$val;
             }
         }
         return $ret;
     }else{
         return $Data;
     }
 }

Very simple function to convert any Subobject to an array.
Created it while working with Soap.
For me as an beginner with PHP, very useful :o)
thinice at gmail dot com 13-Aug-2007 10:46
To add to my previous comment - the error message should have meant same structure.

As my implementation called for cross-class comparison.
thinice at gmail dot com 25-Jul-2007 02:21
If you're looking to compare to like objects this is a way you can do it:
<?
function objCompare($oA, $oB) {
    $oVarsA=get_object_vars($oA);
    $oVarsB=get_object_vars($oB);
    if(($aKeys=array_keys($oVarsA)) !== array_keys($oVarsB)) {
        $GLOBALS[err]=ERR(__CLASS__,__FUNCTION__,__FILE__,'',"Supplied objects are not of same class.");
        return false;
    } else {
        foreach($aKeys as $sKey) {
            if($oVarsA[$sKey] !== $oVarsB[$sKey]) {
                $retAr[]=$sKey;
            }
        }
        return $retAr;
    }
}

$o=new Audit;
$o->_load(1);
$aDifferences=objCompare($o->oOldVersion, $o->oNewVersion);

echo "Between the compared objects, the variables below differ from eachother:<br/>";
print_r($aDifferences);
echo "<br/><br/><h2>For an automated output:</h2>";
foreach($aDifferences as $sVar) {
    echo "OLD VERSION of var ".$sVar.":<br/>".$o->oOldVersion->{$sVar}."<br/><br/>";
    echo "NEW VERSION of var ".$sVar.":<br/>".$o->oNewVersion->{$sVar}."<br/>";
    echo "<hr>";
}
?>
Maikel 23-May-2007 11:13
To follow the code of d11wtq (enquiries AT chriscorbyn.co.uk). I did this function to inspect all properties(public, private, protected) of object.

<?php
header("content-type: text/plain");

// Classes to test!
class OtherClass
{
    private $privateVarOtherClass = 11;
}

class MyClass extends OtherClass
{
    protected $protectedVar = "some";
    public $publicVar = "nk";
    private $privateVar = "algo";
    var $oldStyle;
}

// Dangerous function
function get_properties($obj, $values=false)
{
    $obj_dump  = print_r($obj, 1);
    $matches =  array();
    preg_match_all('/^\s+\[(\w+).*\] => (\w*)/m', $obj_dump, $matches);
    if ($values)
    {
        $output = array();
        foreach ($matches[1] as $key => $property)
        {
            $output[$property] = $matches[2][$key];
        }
        return $output;
    }
    else
    {
        return $matches[1];
    }
}

$instance = new MyClass();

echo "Properties\n";
print_r(get_properties($instance));

echo "Properties and values\n";
print_r(get_properties($instance, true));

?>

Note: remember that static properties are not visible to the object. By that not supported to them
thiago dot henrique dot mata at gmail dot com 21-Feb-2007 11:23
<?php
# How to make a function change the private attributes
# from some object without use serialize functions or
# lose the control of the changes.

/**
 * Parent Class to allow the change of privates attributes
 * Look the abstract function __setAttribute.
 *
 * @author Renan de Lima ( renandelima@gmail.com )
 * @author Thiago Mata ( thiago.henrique.mata@gmail.com )
 * @date 2007-02-21
 */
abstract class father
{
    /**
     * Receive the Aray and try to change the attribute value
     *
     * @param array $arrNewValues
     */
    public function __fromDatabase( $arrNewValues )
    {
        $arrToSet = array_intersect_key( $arrNewValues, get_object_vars( $this ) );
        foreach( $arrToSet as $strAttribute => $mixValue )
        {
            $this->__setAttribute( $strAttribute , $mixValue );
        }
    }

    /**
     * Required method to control the attributes of class
     * @param string $strAttribute
     * @param unknown $mixValue
     */
    abstract protected function __setAttribute( $strAttribute, $mixValue );

}

/**
 * Just a example of a child class using the functionality
 *
 * Note: if you don't wanna to allow the change of some attribute
 * by this method you can just make more complex the __setAttribute function.
 *
 * @author Renan de Lima ( renandelima@gmail.com )
 * @author Thiago Mata ( thiago.henrique.mata@gmail.com )
 * @date 2007-02-21
 */
class son extends father
{

    private $atr = 9;

    /**
     * This is the most simple implementation of the method.
     * This way it's allowed to the parent class change any attribute
     * @param string $strAttribute
     * @param unknown $mixValue
     */
    protected function __setAttribute( $strAttribute, $mixValue )
    {
        $this->{ $strAttribute } = $mixValue;
    }

}

$objSon = new son();
$objSon->__fromDatabase( array( 'atr' => 55 ) );
var_dump( $objSon );
?>
ananda dot putra at gmail dot com 01-Mar-2006 03:49
Hi all, I just wrote a function which dumps all the object propreties and its associations recursively into an array. Here it is..
<?php
function object_to_array($obj) {
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        foreach ($_arr as $key => $val) {
                $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
                $arr[$key] = $val;
        }
        return $arr;
}
?>

Example:
You have an object like this:
fruitsbasket Object
(
    [Fruits] => Array
        (
            [0] => fruits Object
                (
                    [_name] => Mango
                    [_color] => Green
                    [_weight] => 10
                )

            [1] => fruits Object
                (
                    [_name] => Apple
                    [_color] => Red
                    [_weight] => 15
                )

            [2] => fruits Object
                (
                    [_name] => Grape
                    [_color] => Purple
                    [_weight] => 5
                )

        )

    [total_weight] => 30
)

just do:
<?php
$the_array = object_to_array($the_object);
print_r($the_array);
?>

it will produce an array:
Array
(
    [Fruits] => Array
        (
            [0] => Array
                (
                    [_name] => Mango
                    [_color] => Green
                    [_weight] => 10
                )

            [1] => Array
                (
                    [_name] => Apple
                    [_color] => Red
                    [_weight] => 15
                )

            [2] => Array
                (
                    [_name] => Grape
                    [_color] => Purple
                    [_weight] => 5
                )

        )

    [total_weight] => 30
)

I wish function like this could be usefull for you all. :)
support at sascha minus diebel dot de 23-Dec-2005 02:55
Note that get_object_vars() returns the variables of the object not the class. You need to know if your class is extended from a parent class.
d11wtq (enquiries AT chriscorbyn.co.uk) 17-Nov-2005 03:40
Since there's no apparent means of obtaining all the *private* properties in an object I wrote a little function to do it.  Built in support would be much more efficient since mine uses a preg_  search to do this....

<?php

function get_private_properties($obj, $inside=false)
{
    $obj_dump  = print_r($obj, 1);
    preg_match_all('/^\s+\[(\w+):private\]/m', $obj_dump, $matches);
    if ($inside)
    {
        $output = array();
        foreach ($matches[1] as $property)
        {
            $output[$property] = $obj->$property;
            return $output;
        }
    }
    else return $matches[1];
}

?>

So if you run it with the optional second paramter missing you'll just get an array of the variable names that are private inside the class.  This is the only option if you are not inside the actual object and the object has no private properties inherited.

If you run it with the second parameter set to true you will get an associative array with the properties and their corresponding values.  I'd only advise to do that for singletons since you may get errors if there are any private properites in parents/children.
pascal dot poncet at netconsult dot com 13-Oct-2005 07:20
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
Marc 23-Aug-2005 06:08
If you want to access all properties (private, protected, public) of a class and his base class(es) from outside the object you can take a look in the code below.
You can even reffrence them.

Example:
<?php

// Dummy class to act as parent class.
class Dummy
{
    private        $d1 = 1;
    protected    $d2 = 2;
    public        $d3 = 3;
}

// The class to test on.
class Test extends Dummy
{
    private        $t1 = 11;
    protected    $t2 = 12;
    public        $t3 = 13;
}

// Instance of the test class.
$test =& new Test();

// The propertynames of the test class and his parent.
$nameD1 = "\0Dummy\0d1";    // class Dummy, private      $d1
$nameD2 = "\0*\0d2";        // class Dummy, protected $d2
$nameD3 = "d3";            // class Dummy, public    $d3

$nameT1 = "\0Test\0t1";        // class Test,  private      $t1
$nameT2 = "\0*\0t2";        // class Test,  protected $t2
$nameT3 = "t3";            // class Test,  public    $t3

// Printing all members (private, protected, public) of test class and parent.
// These are the values at construction.
print("Original object:\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Create new values to use as reffrence.
$varD1 = 31;
$varD2 = 32;
$varD3 = 33;

$varT1 = 41;
$varT2 = 42;
$varT3 = 43;

// Reffrence these to the class properties.
$test->$nameD1 =& $varD1;
$test->$nameD2 =& $varD2;
$test->$nameD3 =& $varD3;

$test->$nameT1 =& $varT1;
$test->$nameT2 =& $varT2;
$test->$nameT3 =& $varT3;

// Printing all members (private, protected, public) of test class and parent.
// The values have changed by assigning reffrence to them.
print("Object Changed by reffrence (1):\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Change the original values.
// This will change the class properties.
$varD1 = 61;
$varD1 = 62;
$varD1 = 63;

$varT1 = 71;
$varT1 = 72;
$varT1 = 73;

// Printing all members (private, protected, public) of test class and parent.
// The values have changed because the variables $varXX have been changed.
print("Object Changed by reffrence (2):\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Printing the object using print_r() shows the changes
// have been done on the object.
print("Object Changed (print_r):\n");
print_r($test);
print("\n");

// If you dont now the class propertynames you can get these by casting the
// object to an array. The array keys are the names
$prop = array_keys((array) $test);
print("Getting all class propertynames (print_r)\n");
print_r($prop);

//Result
/*

Original object:
    $d1 = 1
    $d2 = 2
    $d3 = 3
    $t1 = 11
    $t2 = 12
    $t3 = 13

Object Changed by reffrence (1):
    $d1 = 31
    $d2 = 32
    $d3 = 33
    $t1 = 41
    $t2 = 42
    $t3 = 43

Object Changed by reffrence (2):
    $d1 = 63
    $d2 = 32
    $d3 = 33
    $t1 = 73
    $t2 = 42
    $t3 = 43

Object Changed (print_r):
Test Object
(
    [t1:private] => 73
    [t2:protected] => 42
    [t3] => 43
    [d1:private] => 63
    [d2:protected] => 32
    [d3] => 33
)

Getting all class propertynames (print_r)
Array
(
    [0] => Test

*/

?>
stachnik at gmail dot com 02-Aug-2005 09:00
In PHP5 to get an array with all properties (even the private ones) all you have to do is write a public method that returns an array for your class:

public function getArray()
{
  return get_object_vars($this);
}

and then

$myBeautifulArray = $myBeautifulObject->getArray ();

Have BEAUTIFUL day :)
fmmarzoa at librexpresion dot org 01-Nov-2004 11:53
You can still cast the object to an array to get all its members and see its visibility. Example:

<?php

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing array cast:\n";

$Arr = (array)$Obj;
print_r ( $Arr );

?>

This will returns:

Using get_object_vars:
Array
(
    [skin] => 1
)

Using array cast:
Array
(
    [skin] => 1
    [ * meat] => 2
    [ Potatoe roots] => 3
)

As you can see, you can obtain the visibility for each member from this cast. That which seems to be spaces into array keys are '\0' characters, so the general rule to parse keys seems to be:

Public members: member_name
Protected memebers: \0*\0member_name
Private members: \0Class_name\0member_name

I've wroten a obj2array function that creates entries without visibility for each key, so you can handle them into the array as it were within the object:

<?php

function obj2array ( &$Instance ) {
    $clone = (array) $Instance;
    $rtn = array ();
    $rtn['___SOURCE_KEYS_'] = $clone;

    while ( list ($key, $value) = each ($clone) ) {
        $aux = explode ("\0", $key);
        $newkey = $aux[count($aux)-1];
        $rtn[$newkey] = &$rtn['___SOURCE_KEYS_'][$key];
    }

    return $rtn;
}

?>

I've created also a <i>bless</i> function that works similar to Perl's bless, so you can further recast the array converting it in an object of an specific class:

<?php

function bless ( &$Instance, $Class ) {
    if ( ! (is_array ($Instance) ) ) {
        return NULL;
    }

    // First get source keys if available
    if ( isset ($Instance['___SOURCE_KEYS_'])) {
        $Instance = $Instance['___SOURCE_KEYS_'];
    }

    // Get serialization data from array
    $serdata = serialize ( $Instance );

    list ($array_params, $array_elems) = explode ('{', $serdata, 2);
    list ($array_tag, $array_count) = explode (':', $array_params, 3 );
    $serdata = "O:".strlen ($Class).":\"$Class\":$array_count:{".$array_elems;

    $Instance = unserialize ( $serdata );
    return $Instance;
}
?>

With these ones you can do things like:

<?php

define("SFCMS_DIR", dirname(__FILE__)."/..");
require_once (SFCMS_DIR."/Misc/bless.php");

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }

    function PrintAll () {
        echo "skin = ".$this->skin."\n";
        echo "meat = ".$this->meat."\n";
        echo "roots = ".$this->roots."\n";
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing obj2array func:\n";

$Arr = obj2array($Obj);
print_r ( $Arr );

echo "\n\nSetting all members to 0.\n";
$Arr['skin']=0;
$Arr['meat']=0;
$Arr['roots']=0;

echo "Converting the array into an instance of the original class.\n";
bless ( $Arr, Potatoe );

if ( is_object ($Arr) ) {
    echo "\$Arr is now an object.\n";
    if ( $Arr instanceof Potatoe ) {
        echo "\$Arr is an instance of Potatoe class.\n";
    }
}

$Arr->PrintAll();

?>
27-Oct-2004 08:02
actually, it's not entirely true that php5 will only return public members....php5 will return any variable IT HAS ACCESS TO

In other words, if you do a get_class_variables($this) inside a class, you'll get everything - public, private, the whole shebang...really annoying since you can't check to see what's private/public without using reflection
manicdepressive AT mindless DOT com 05-Mar-2004 07:57
more strange, strange behaviour:

if you are trying to deep-copy an object with get_object_vars(), strange behaviour can accidentally clobber your original object properties.  please read very, very carefully:

get_object_vars() may either return references to *or* deep copies of the object's properties *depending on whether that property has been set with the -> operator*.   (this behaviour probably varies per php platform and os so please confirm for yourself.)

furthermore, consider
  $properties = get_object_vars($obj);
normally, unset()ting a reference does not affect the original, i.e. $ref = NULL; is not the same as unset($ref); per the references documentation.  However, if you have this strange references version and you unset() an array element of $properties, it will *SET THE OBJECT PROPERTY TO NULL*, which is not how references normally work.

even stranger behaviour comes into effect that i can only express with an example.  please test this with your version and OS and proceed very carefully:
-->
<?php
echo "<pre>\n";

class Lump
{
   var $size = 'average';

   function & copy()
   {  // return a deep copy
      $copy = new Lump();
      $properties = get_object_vars($this);
      foreach( array_keys( $properties ) as $property ){
         $copy->$property = $properties[$property];  // deep, right?
      }
      return $copy;
   }

}

$lump = new Lump();

$lump->size = 'huge';  // <--- this line changes everything
// comment above line out, and see the difference
// also, try substituting another property for 'size'

$properties = get_object_vars($lump);
$properties['size'] = 'small'; // this behavior varies

echo "after changing the properties array:\n";
var_dump( $lump );
// it's either big or small (never huge) depending on
// whether you commented-out the indicated line

//------------- let's try using our copy() method

$original_lump = new Lump();
$original_lump->size = 'huge'; // this line changes the behaviour
$other_lump =& $original_lump->copy();
unset( $other_lump->size );
echo "after unsetting in copy:\n";
var_dump( $original_lump ); // i'm afraid so -- original value clobbered !

echo "</pre>\n";
?>
code till dawn,
   mark meves
christopher AT NOSPAM AT idealab DOT com 30-Dec-2003 03:12
Hmmm.  A bit embarassing...

It turns out the best way to get references to all of your objects member variables is NOT with the functions I provided before, or with get_object_vars.

Just cast the object to array.

$a=(array)$obj;

# The two following statements are now equivalent and identical
$a["member"]=3;
$obj->member=3;

A very powerful tool, for inspectors and what not.
christopher AT NOSPAM AT idealab DOT com 23-Dec-2003 12:49
Please note that you cannot affect the object via the array values...in other words, the returned array does not contain references to the values within the object, but copies.

If you are making an object inspector or editor, this is not good enough.  So I made the following methods:

METHODS:

function &getVar($obj, $name)
{
        $expr="\$prop=&\$obj->$name;";
        eval($expr);
        return $prop;
}

function &getObjectVars($obj)
{
        $result=array();
        $vars=get_object_vars($obj);
        foreach ($vars as $var => $value)
        {
                $result[$var]=&getVar(&$obj, $var);
        }
        return $result;
}

[NOTE:  You must pass in a reference to an object, not an object.  Sorry if this  offends PHP'ers, but the distinction of pass-by-value and copy-on-assignment drives me batty (compared to Python, Java, Smalltalk), so I make all my functions pass by value, and force myself to pass in a reference to keep track of what is happening under the hood.]

EXAMPLE:

class Bob
{
        function Bob()
        {
                $this->thing=13;
                $this->other="whatever";
        }

        var $thing;
        var $other;
}

$obj=&new Bob();

# NOTE:  Passing in a reference!
$props=getObjectVars(&$obj);
$props["thing"]=-11;

var_dump($obj);

RESULTS:

object(bob)(2) {
  ["thing"]=>
  &int(-11)
  ["other"]=>
  &string(8) "whatever"
}
jordi at laigu dot net 06-Nov-2003 05:21
In case your object contains again OBJECTS or ARRAYS:

function makeAssoc($res) {
  if (is_object($res)) $res = get_object_vars($res);
  while (list($key, $value) = each($res)) {
    if (is_object($value) || is_array($value)) {
      $res[$key] = makeAssoc($value);
    }
  }
  return $res;
}

Thanks to mark at dreamzpace dot com
markus at emedia-solutions-wolf dot de 06-Mar-2003 12:01
Hi,

I figured out that in prior version to 4.2 the returned array only contains attributes directly in this class, excluding the derived ones from parentclasses.
info at phpken dot de 21-Nov-2002 06:34
hello,

this example will look like all values of vars was set in your class. write a method like the name: dumpClass and then fill in follow code:

$vars = get_object_vars($this);

echo "<b>class vars</b>";

foreach( $vars as $name => $value ) {
    echo "<li>".$name." : ".$value;
}

look at: get_object_vars($this);

andreas v.l
mark at dreamzpace dot com 13-Sep-2002 10:44
In case your object contains again objects (and so on), this function might be useful:

function makeAssoc($res) {
  $res = get_object_vars($res);
  while (list($key, $value) = each($res)) {
    if (is_object($value)) {
      $res[$key] = makeAssoc($value);
    }
  }
  return $res;
}
nick_eby at bonzidev dot com 09-Jul-2002 12:13
Furthermore, variables not declared in the class but set on a given object, will be returned by get_object_vars().

Example, ver. 4.2.1:
<?
class MyTest {
        var $classVar1 = 'Class Var 1';
        var $classVar2;
        var $classVar3;

        function MyTest()
        {
                $this->classVar2 = 'class var 2';
        }
}

$test = new MyTest();
// This var isn't declared in the class
$test->newObjVar = 'foobar';

echo "<pre>";
print_r(get_object_vars($test));
echo "</pre>";
?>

The output is:
Array
(

    [classVar1] => Class Var 1
    [classVar2] => class var 2
    [classVar3] =>
    [newObjVar] => foobar
)

Prior to version 4.2, classVar3 would not be output as it was never assigned a value.
michael at tapinternet dot com 13-Jun-2002 03:32
It seems that get_object_vars will now return properties of an object even if they have no value  - meaning only defined by var $foo in the class declaration.  This is noted behaviour in 4.2.1 which is different from previous versions and hitherto undocumented on this page.
florian at XCLUDETHISgsf dot de 29-Jan-2002 10:02
There is a strange behaviour, not sure whether it is a bug:

if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
     foreach($array_of_objectvars as $key => $val) {
     echo(" $key => $val<br>");
     }
?>
I get only _ONE_ line with the $key = first variable name of the object and $val = the values of _ALL_ variables of the object including the first separated by a space.

NOW:
if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
     foreach($array_of_objectvars as $key => $val) {
     echo(" $key => $val<br>");
     }
     echo($data_array_of_objects[0]->objectvar1."<br>");
     echo($data_array_of_objects[0]->objectvar2."<br>");
?>

I get a list of $key = $ val as expected, before the other echos' are printed.
It seems to me that get_object_vars works differently when you access a variable in those objects explicitly (as in the echos)
get_declared_traits
get_parent_class
Классы/Объекты


Возвращает имя родительского класса для объекта или класса

get_object_vars
interface_exists
Классы/Объекты
PHP Manual

get_parent_class

(PHP 4, PHP 5)

get_parent_class — Возвращает имя родительского класса для объекта или класса

Описание

string get_parent_class ([ mixed $object ] )

Возвращает имя родительского класса для объекта или класса.

Список параметров

object

Тестируемый объект или имя класса

Возвращаемые значения

Возвращает имя родительского класса, если object является объектом или именем класса.

Замечание:

Если объект не имеет родителя, или переданного класса с таким именем не существует, то будет возвращено FALSE.

Если функция вызвана без параметров вне объекта, эта функция возвращает FALSE.

Список изменений

Версия | Описание
До версии 5.1.0 | Если функция была вызвана без параметров внутри объекта, то будет возвращено NULL вместе с предупреждением.
С версии 5.0.0 | Параметр object стал необязательным, если вызов происходит внутри метода данного объекта.
С версии 4.0.5 | Если object - строка, возвращает имя родительского класса указанного класса.

Примеры

Пример #1 Пример использования get_parent_class()

<?php

class dad {
    function dad()
    {
    // реализация какой-нибудь логики
    }
}

class child extends dad {
    function child()
    {
        echo "I'm " , get_parent_class($this) , "'s son\n";
    }
}

class child2 extends dad {
    function child2()
    {
        echo "I'm " , get_parent_class('child2') , "'s son too\n";
    }
}

$foo = new child();
$bar = new child2();

?>

Результат выполнения данного примера:

I'm dad's son
I'm dad's son too

Смотрите также

  • get_class() - Возвращает имя класса, к которому принадлежит объект
  • is_subclass_of() - Проверяет, содержит ли объект в своем дереве предков указанный класс

User Contributed Notes

falundir at gmail dot com 13-Apr-2012 10:27
You can use this function to find common parent of multiple objects or classes.

<?php
/**
 * Returns name of the first (in class hierarchy) common parent class of all provided objects or classes.
 * Returns FALSE when common class is not found.
 *
 * @param mixed $objects Array that can contain objects or class names.
 * @return mixed
 */
function get_first_common_parent($objects) {
    $common_ancestors = null;
    foreach($objects as $object) {
        if (is_object($object)) {
            $class_name = get_class($object);
        } else {
            $class_name = $object;
        }

        $parent_class_names = array();
        $parent_class_name = $class_name;
        do {
            $parent_class_names[] = $parent_class_name;
        } while($parent_class_name = get_parent_class($parent_class_name));

        if ($common_ancestors === null) {
            $common_ancestors = $parent_class_names;
        } else {
            $common_ancestors = array_intersect($common_ancestors, $parent_class_names);
        }
    }

    return reset($common_ancestors);
}
?>

Example:

<?php
class A {
}

    class B extends A {
    }

        class D extends B {
        }

        class E extends B {
        }

    class C extends A {
    }

        class F extends C {
        }

            class G extends F {
            }

class H {
}

//returns "A"
get_first_common_parent(array('G', 'E'));

//returns "F"
get_first_common_parent(array(new G(), 'F'));

//returns false (no common parent)
get_first_common_parent(array('C', 'H'));

//returns false (non-existent class provided)
get_first_common_parent(array(new B(), 'X'));
?>
Michael Torp Kaalund 07-Jun-2011 05:45
I have been playing with parent and child class, and I used this function to determine that which one was calling an function. I for an example it if you only want your parent class to be able to make an function call:
here is my example (by the way this example was inspired by another example fund on php.net):
<?php

class Parents {
    public static $status; //This is the status
    protected static $idCount;
    protected $id;

    function __construct() {
        $this->id = ++self::$idCount;
        self::$status = "tmp";
    }

    public function run($task) {
        if(get_parent_class($this) == "") {
            echo 'Command issued: '.$task.'<br>';
            self::$status = $task;
        }
    }

    public function __tostring() {
        return "(".__class__.")id=".$this->id." status=".self::$status."<br>";
    }
}

class Child extends Parents {
    function __construct() {
        parent::__construct();
        self::$status = "tmp";
        echo "Child construct<br>";
    }

    public function __tostring() {
        return "(".__class__.")id=".$this->id." status=".self::$status."<br>";
    }
}

$parent = new Parents();
echo $parent;
$child = new Child();
echo $child;
echo get_parent_class('Child')."<br>";
$parent->run("mtk");
echo $parent;
echo $child;
$child->run("mtk1");
echo $parent;
echo $child;
?>

which will produces somethink like:
(Parents)id=1 status=tmp
Child construct
(Child)id=2 status=tmp
Parents
Command issued: mtk
(Parents)id=1 status=mtk
(Child)id=2 status=mtk
(Parents)id=1 status=mtk
(Child)id=2 status=mtk

hopes it helps some one :D
levu 20-Apr-2011 08:36
I wrote a simple function doing the reverse thing: get the children:

<?php
function get_child($instance, $classname) {
    $class = $classname;
    $t = get_class($instance);
    while (($p = get_parent_class($t)) !== false) {
        if ($p == $class) {
            return $t;
        }
        $t = $p;
    }
    return false;
}

abstract class A {
    function someFunction() {
        return get_child($this, __CLASS__);
    }
}

class B extends A {

}

class C extends B {

}

$c = new C();
echo $c->someFunction(); //displays B

?>
michael at getsprink dot -- com 09-Apr-2009 12:28
This little snippet to get the inheritance tree might be useful to someone.

<?php

header("Content-Type: text/plain;");

class Top {
  public function getParents($class=null, $plist=array()) {
    $class = $class ? $class : $this;
    $parent = get_parent_class($class);
    if($parent) {
      $plist[] = $parent;
      /*Do not use $this. Use 'self' here instead, or you
       * will get an infinite loop. */
      $plist = self::getParents($parent, $plist);
    }
    return $plist;
  }
}

class Middle extends Top {

}

class Bottom extends Middle {

}

$o = new Bottom();
print_r($o->getParents());

?>
ssb45 at cornell dot edu 14-May-2008 08:32
"'If called without parameter outside object' What on earth does that mean?"

There are two places this could be called:
1. From within a member function of an object.  In this case, it may be called with no parameters and will return the parent class of the object owning the member function.  (If the parameter is included, then it will return the parent class of the specified class as normal.)

2. From outside an object (i.e., global or function scope).  In this case, PHP doesn't know what class you're talking about if you don't include a parameter, so it returns FALSE.  (But, of course, it works if you specify the class with the parameter.)
marcus at synchromedia dot co dot uk 16-Apr-2008 09:08
"If called without parameter outside object" What on earth does that mean?

What I can tell you, and that is not documented, is that if the object in question does not have an explicitly declared parent class, it does return boolean false. It doesn't for example return 'stdClass' on the basis that all objects are derived from that.
birkholz at web dot de 06-Oct-2005 05:01
tim at correctclick dot com wrote:
<quote>
A slightly more cryptic but faster get_ancestors function:

<?php
function get_ancestors ($class) {

     for ($classes[] = $class; $class = get_parent_class ($class); $classes[] = $class);
     return $classes;

}
?>
(The second part of the for is implicitly testing for $class != "").  Recursion is considerably slower than looping, so you probably want to use this function.

Hope someone finds it useful.
</quote>

I would prefer this version, because it will create no duplicates:
<?php
function get_ancestors ($class) {
    $classes = array($class);
    while($class = get_parent_class($class)) { $classes[] = $class; }
    return $classes;
}

Greets, Dennis
?>
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 07:52
PHP (4 at least, dunno about 5) stores classnames in lower case, so:

<?PHP

class Foo
{
}

class Bar extends Foo
{
}

echo get_parent_class('Bar');

echo "\n";

echo get_parent_class('bar');

?>

will output:

foo
foo
radu dot rendec at ines dot ro 07-Apr-2004 06:44
If the argument obj is a string and the class is not defined, then the function returns FALSE.

If the argument obj is an object created from a class with no ancestors (or a string representing a class with no ancestors), then the function returns FALSE.
tim at correctclick dot com 05-Apr-2003 07:48
A slightly more cryptic but faster get_ancestors function:

function get_ancestors ($class) {

      for ($classes[] = $class; $class = get_parent_class ($class); $classes[] = $class);
      return $classes;

}

(The second part of the for is implicitly testing for $class != "").  Recursion is considerably slower than looping, so you probably want to use this function.

Hope someone finds it useful.
eric dot brison at anakeen dot com 28-Jan-2002 04:14
To return all ancestors class of an object

function get_ancestors_class($classname) {
  $father = get_parent_class($classname);

  if ($father != "") {

    $ancestors = get_ancestors_class($father);
    $ancestors[] = $father;
  }
  return $ancestors;
}

example :
-----------
Class C  {

}

Class B extends C {

}

Class A extends B {

}
print_r (get_ancestors_class("a"));
print_r (get_ancestors_class("b"));

example result :
---------------
Array
(
    [0] => c
    [1] => b
)
Array
(
    [0] => c
)
get_object_vars
interface_exists
Классы/Объекты


Проверяет, определен ли интерфейс

get_parent_class
is_a
Классы/Объекты
PHP Manual

interface_exists

(PHP 5 >= 5.0.2)

interface_exists — Проверяет, определен ли интерфейс

Описание

bool interface_exists ( string $interface_name [, bool $autoload = true ] )

Проверяет, определен ли указанный интерфейс.

Список параметров

interface_name

Имя интерфейса

autoload

Определяет, использовать ли по умолчанию __autoload или нет

Возвращаемые значения

Возвращает TRUE, если интерфейс, заданный именем interface_name был определен, FALSE в остальных случаях.

Примеры

Пример #1 Пример использования interface_exists()

<?php
// Проверяем существование интерфейса перед его использованием
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Методы
    }
}

?>

Смотрите также

  • get_declared_interfaces() - Возвращает массив всех объявленных интерфейсов
  • class_implements() - Return the interfaces which are implemented by the given class
  • class_exists() - Проверяет, был ли объявлен класс

User Contributed Notes

nils dot rocine at gmail dot com 26-Oct-2011 06:35
A little note on namespaces that may be obvious to some, but was not obvious to me.

Although you can make the below statement when the statement is in the same namespace as the interface/class declaration MyInterface...
<?php
$foo instanceof MyInterface
?>

Making use of the interface_exists, or class_exists functions, you must enter the full namespaced interface name like so (even if the function call is from the same namespace.)
<?php
interface_exists(__NAMESPACE__ . '\MyInterface', false);
?>
andrey at php dot net 24-Oct-2004 04:40
As far as I remember interface_exists() was added in 5.0.2 . In 5.0.0 and 5.0.1 class_exists() used to return TRUE when asked for a existing interface. Starting 5.0.2 class_exists() doesn't do that anymore.
get_parent_class
is_a
Классы/Объекты


Проверяет, принадлежит ли объект к данному классу или содержит данный класс в числе своих предков

interface_exists
is_subclass_of
Классы/Объекты
PHP Manual

is_a

(PHP 4 >= 4.2.0, PHP 5)

is_a — Проверяет, принадлежит ли объект к данному классу или содержит данный класс в числе своих предков

Описание

bool is_a ( object $object , string $class_name [, bool $allow_string = FALSE ] )

Проверяет, принадлежит ли объект object к данному классу или содержит данный класс в числе своих предков

Список параметров

object

Проверяемый объект

class_name

Имя класса

allow_string

Если параметр установлен в false, то не допускается имя класса в виде строки в качестве параметра object. Это также предотвращает вызов автозагрузчика, если класс не существует.

Возвращаемые значения

Возвращает TRUE, если объект принадлежит данному классу или имеет данный класс в числе своих предков, иначе возвращается FALSE.

Список изменений

Версия | Описание
5.3.9 | Добавлен параметр allow_string
5.3.0 | Данная функция больше не считается устаревшей, а значит, не будет выводить предупреждения E_STRICT.
5.0.0 | Эта функция была помечена устаревшей в пользу оператора instanceof. Вызов данной функции вызовет предупреждение уровня E_STRICT.

Примеры

Пример #1 Пример использования is_a()

<?php
// объявление класса
class WidgetFactory
{
  var $oink = 'moo';
}

// создание нового объекта
$WF = new WidgetFactory();

if (is_a($WF, 'WidgetFactory')) {
  echo "да, \$WF все еще WidgetFactory\n";
}
?>

Пример #2 Использование оператора instanceof в PHP 5

<?php
if ($WF instanceof WidgetFactory) {
    echo 'Да, $WF - WidgetFactory';
}
?>

Смотрите также

  • get_class() - Возвращает имя класса, к которому принадлежит объект
  • get_parent_class() - Возвращает имя родительского класса для объекта или класса
  • is_subclass_of() - Проверяет, содержит ли объект в своем дереве предков указанный класс

User Contributed Notes

eitan at mosenkis dot net 12-Jan-2012 01:09
As of PHP 5.3.9, is_a() seems to return false when passed a string for the first argument. Instead, use is_subclass_of() and, if necessary for your purposes, also check if the two arguments are equal, since is_subclass_of('foo', 'foo') will return false, while is_a('foo', 'foo') used to return true.
Aron Budinszky 07-Sep-2011 04:21
Be careful! Starting in PHP 5.3.7 the behavior of is_a() has changed slightly: when calling is_a() with a first argument that is not an object, __autoload() is triggered!

In practice, this means that calling is_a('23', 'User'); will trigger __autoload() on "23". Previously, the above statement simply returned 'false'.

More info can be found here:
https://bugs.php.net/bug.php?id=55475

Whether this change is considered a bug and whether it will be reverted or kept in future versions is yet to be determined, but nevertheless it is how it is, for now...
p dot scheit at zweipol dot net 16-Jan-2007 01:44
At least in PHP 5.1.6 this works as well with Interfaces.

<?php
interface test {
  public function A();
}

class TestImplementor implements test {
  public function A () {
    print "A";
  }
}

$testImpl = new TestImplementor();

var_dump(is_a($testImpl,'test'));
?>

will return true
martin dunisch 13-Feb-2006 12:02
Workaround for older PHP-Versions:

function is_a($anObject, $aClass) {
   return get_class($anObject) == strtolower($aClass)
     or is_subclass_of($anObject, $aClass);
}
dead dot screamer at seznam dot cz 06-Feb-2006 11:44
Why I test if class `A` inherit class `B` or implements interface `C` before I create class `A`?

<?
//That isn't work:

//1. function is_A()
if(is_A('A','B'))$a=new A;
if(is_A('A','C'))$a=new A;

//2. operator instanceOf
if(A instanceOf B)$a=new A;
if(A instanceOf C)$a=new A;
?>
zabmilenko at hotmail dot com 07-Oct-2005 05:18
Lazy Instantiation using is_a() and php5

<?php

class ObjectA
{
    public function print_line($text)
    {
        print $text . "\n";
    }
}

class ObjectB
{
    public function ObjectA()
    {
        static $objecta;

        if (!is_a($objecta, 'ObjectA'))
        {
            $objecta = new ObjectA;
        }

        return $objecta;
    }
}

$obj = new ObjectB;
$obj->ObjectA()->print_line('testing, 1 2 3');

?>

In the above example, ObjectA is not instantiated until needed by ObjectB.  Then ObjectB can continually use it's creation as needed without reinstantiating it.

There are other ways, but I like this one :-)
cesoid at yahoo dot com 05-Oct-2005 07:01
is_a returns TRUE for instances of children of the class.

For example:

class Animal
{}

class Dog extends Animal
{}

$test = new Dog();

In this example is_a($test, "Animal") would evaluate to TRUE as well as is_a($test, "Dog").

This seemed intuitive to me, but did not seem to be documented.
interface_exists
is_subclass_of
Классы/Объекты


Проверяет, содержит ли объект в своем дереве предков указанный класс

is_a
method_exists
Классы/Объекты
PHP Manual

is_subclass_of

(PHP 4, PHP 5)

is_subclass_of — Проверяет, содержит ли объект в своем дереве предков указанный класс

Описание

bool is_subclass_of ( mixed $object , string $class_name [, bool $allow_string = TRUE ] )

Проверяет, содержит ли объект object в своем дереве предков класс class_name .

Список параметров

object

Имя класса или экземпляр объекта

class_name

Имя класса

allow_string

Если параметр установлен в false, то не допускается имя класса в виде строки в качестве параметра object. Это также предотвращает вызов автозагрузчика, если класс не существует.

Возвращаемые значения

Эта функция возвращает TRUE, если объект object принадлежит к классу, наследующему от class_name, иначе она возвращает FALSE.

Список изменений

Версия | Описание
5.3.9 | Добавлен параметр allow_string
5.0.3 | Вы также можете передать параметр object в виде строки (имени класса)

Примеры

Пример #1 Пример использования is_subclass_of()

<?php
// объявляем класс
class WidgetFactory
{
  var $oink = 'moo';
}

// объявляем наследника
class WidgetFactory_Child extends WidgetFactory
{
  var $oink = 'oink';
}

// создаем новый объект
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();

if (is_subclass_of($WFC, 'WidgetFactory')) {
  echo "да, \$WFC наследует WidgetFactory\n";
} else {
  echo "нет, \$WFC не наследует WidgetFactory\n";
}

if (is_subclass_of($WF, 'WidgetFactory')) {
  echo "да, \$WF наследует WidgetFactory\n";
} else {
  echo "нет, \$WF не наследует WidgetFactory\n";
}

// применимо только с версии PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
  echo "да, WidgetFactory_Child наследует WidgetFactory\n";
} else {
  echo "нет, WidgetFactory_Child не наследует WidgetFactory\n";
}
?>

Результат выполнения данного примера:

да, $WFC наследует WidgetFactory
нет, $WF не наследует WidgetFactory
да, WidgetFactory_Child наследует WidgetFactory

Примечания

Замечание:

Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс еще не известен.

Смотрите также

  • get_class() - Возвращает имя класса, к которому принадлежит объект
  • get_parent_class() - Возвращает имя родительского класса для объекта или класса
  • is_a() - Проверяет, принадлежит ли объект к данному классу или содержит данный класс в числе своих предков
  • class_parents() - Return the parent classes of the given class

User Contributed Notes

nicholas at aquarionics dot com 17-Mar-2009 01:02
This might be useful to someone, so:

If you're using Autoload, you should be aware that this will attempt to autoload $classname if it isn't already loaded. I discovered this when I had something using is_subclass_of inside an error thrown by autoload, which then recursed until it ran out of memory.
Damien Bezborodov 16-Mar-2009 04:55
If you need something similar to is_subclass_of() to determine if a class implements an interface before instantiating it, use reflection:

<?php

interface A_Interface {}
class A implements A_Interface {}

$reflectionA = new ReflectionClass('A');
var_dump(
    $reflectionA->implementsInterface('A_Interface')
);

?>
bool(true)
kostyl_kostyl gav-gav mail point ru 07-Mar-2009 03:08
<?php
interface I {
}
class A implements I {
}
class B extends A  {
}
if (is_subclass_of('A', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'A')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
?>

result:
bad <- you must to describe intermediate class B to be good
good
good
jm 30-Sep-2008 08:02
It would appear that is_subclass_of is case insensitive unlike get_class in php5.
i.e.

<?php
class fooBar {}
class bar extends fooBar {}

assert(get_class(new fooBar()) == "fooBar");
assert(is_subclass_of(new bar(), "foobar") == true);
?>

i run across this while migrating some code from php4 to php5 and the code would only half-the-time break.
Ondra Zizka 13-Oct-2006 05:31
For PHP4:

<?php
/** Returns whether specified class is subclass of the other class. */
function is_subclass($sClass, $sExpectedParentClass){
    do if( $sExpectedParentClass === $sClass ) return true;
    while( false != ($sClass = get_parent_class($sClass)) );
    return false;
}
// Test:
class A {} class B extends A {} class C extends B {} echo (int) is_subclass('C', 'A');
?>
gunniboyh at web dot de 20-May-2006 06:16
is_subclass_of() works also with classes between the class of obj and the superclass.

example:
<?php
class A {};
class B extends A {};
class C extends B {};

$foo=new C();
echo ((is_subclass_of($foo,'A')) ? 'true' : 'false');
?>

echoes 'true' .
01-Oct-2005 06:32
this function does not check interfaces, unlike instanceof operator.
youcantryreachingme at REMOVEME dot hotmail dot com 21-Mar-2005 06:15
A bug report at http://pear.php.net/bugs/bug.php?id=2975 indicates that the "is_subclass_of" function can return the error message:

Warning: Unknown class passed as parameter

in the event that the class represented by the second argument hasn't yet been instantiated.
is_a
method_exists
Классы/Объекты


Проверяет, существует ли метод в данном классе

is_subclass_of
property_exists
Классы/Объекты
PHP Manual

method_exists

(PHP 4, PHP 5)

method_exists — Проверяет, существует ли метод в данном классе

Описание

bool method_exists ( mixed $object , string $method_name )

Проверяет, существует ли метод класса, в указанном объекте object.

Список параметров

object

Экземпляр объекта или имя класса

method_name

Имя метода

Возвращаемые значения

Возвращает TRUE, если метод method_name определен для указанного объекта object, иначе возвращает FALSE.

Примечания

Замечание:

Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс еще не известен.

Примеры

Пример #1 Пример использования method_exists()

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>

Результат выполнения данного примера:

bool(true)

Пример #2 Пример статического использования method_exists()

<?php
var_dump(method_exists('Directory','read'));
?>

Результат выполнения данного примера:

bool(true)

Смотрите также

  • function_exists() - Возвращает TRUE, если указанная функция определена
  • is_callable() - Проверяет, может ли значение переменной быть вызвано в качестве функции
  • class_exists() - Проверяет, был ли объявлен класс

User Contributed Notes

Niels 11-May-2011 12:45
Just to mention it: both method_exists() and is_callable() return true for inherited methods:

<?php
class ParentClass {

   function doParent() { }
}

class ChildClass extends ParentClass { }

$p = new ParentClass();
$c = new ChildClass();

// all return true
var_dump(method_exists($p, 'doParent'));
var_dump(method_exists($c, 'doParent'));

var_dump(is_callable(array($p, 'doParent')));
var_dump(is_callable(array($c, 'doParent')));
?>
mail at bartrail dot de 25-Apr-2011 10:06
Using method_exists inside an object's __call() method can be very usefull if you want to avoid to get a fatal error because of a limit in function nesting or if you are calling methods that dont exist but need to continue in your application:

<?php
class Something
{

    /**
     * Call a method dynamically
     *
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        if(method_exists($this, $method)) {
          return call_user_func_array(array($this, $method), $args);
        }else{
          throw new Exception(sprintf('The required method "%s" does not exist for %s', $method, get_class($this)));
        }
    }

}
?>
phoenix at todofixthis dot com 21-Dec-2010 09:13
As noted [elsewhere] method_exists() does not care about the existence of __call(), whereas is_callable() does:

<?php
class Test {
  public function explicit(  ) {
      // ...
  }

  public function __call( $meth, $args ) {
      // ...
  }
}

$Tester = new Test();

var_export(method_exists($Tester, 'anything')); // false
var_export(is_callable(array($Tester, 'anything'))); // true
?>
buggedcom 18-Aug-2010 11:02
Be warned that the class must exist before calling method exists from an eval statement otherwise you will get a Signal Bus error.
uramihsayibok, gmail, com 06-Aug-2010 10:09
It wasn't spelled out but could be inferred: method_exists() also works on interfaces.

<?php

var_dump(method_exists("Iterator", "current"));
// bool(true)

?>
Anonymous 08-May-2010 05:20
If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__

<?php

class A{
  __construct($method){
      return method_exists(__CLASS__,$method);
  }

  private function foo(){

  }
}

$test = new A('foo');
//should return true

?>

You might also use the method describe below with <?php in_array() ?> trick but I consider this one here easier and more readable and well, the way it is intended toi be done ;)
admin ( at ) djokodonev dot com 16-Oct-2009 04:30
Hi,

Here is a useful function that  you can use to check classes methods access e.g whether it is public, private or static or both..

here it goes:

<?php
// Example class
class myClass {

    private $private1;

    static $static1;

    public $public1;

    public function publ() {

    }

    private function priv() {

    }

    private static function privstatic() {

    }

    public static function publstatic() {

    }

    static function mytest() {

    }
}

// The function uses the reflection class that is built into PHP!!!
// The purpose is to determine the type of a certain method that exi
function is_class_method($type="public", $method, $class) {
   // $type = mb_strtolower($type);
    $refl = new ReflectionMethod($class, $method);
    switch($type) {
        case "static":
        return $refl->isStatic();
        break;
        case "public":
        return $refl->isPublic();
        break;
        case "private":
        return $refl->isPrivate();
        break;
    }
}
var_dump(is_class_method("static", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "publstatic", "myClass")); // False the methos is public and also static not private
 // you get the idea.. I hope this helps someone..
?>
florin from syneto net 07-Oct-2009 07:34
This function is case-insensitive (as is PHP) and here is the proof:
<?php
class A {
    public function FUNC() { echo '*****'; }
}

$a = new A();
$a->func(); // *****
var_dump(method_exists($a, 'func')); // bool(true)
?>
jp at function dot fi 30-Apr-2006 02:29
As mentioned before, is_callable and method_exists report all methods callable even if they are private/protected and thus actually not callable. So instead of those functions you may use following work-around which reports methods as supposed to.

<?php
class Foo1 {
  public function bar() {
    echo "I'm private Foo1::bar()";
  }
}

class Foo2 {
  private function bar() {
    echo "I'm public Foo2::bar()";
  }
}

$f1=new Foo1;
$f2=new Foo2;

if(is_callable(array($f1,"bar"))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(is_callable(array($f2,"bar"))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f1))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f2))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}

?>

output
Foo1::bar() is callable (correct)
Foo2::bar() is callable (incorrect)
Foo1::bar() is callable (correct)
Foo2::bar() isn't callable (correct)

?>
seufert at gmail dot com 26-Apr-2006 06:27
Just a note that the behaviour of this function changed between version 5.0.x and 5.1.x when using static member functions

Using this code:
<?php
class a {
    static function test() {return "A";}
}
if(method_exists('a','test'))
    print call_user_func(array('a','test'));
else
    print "Nothing";
?>
PHP 5.1.x returns "A"
PHP 5.0.x returns "Nothing"

Im not sure of a workaround for PHP 5.0.x yet.
spam at majiclab dot com 31-Jan-2006 08:33
Both method_exists() and is_callable() return private and protected functions, which, as mentioned below, causes problems for PHP5/OO programming.  You can use get_class_methods() with either an $instance of a class or the 'ClassName' to get only public functions.
daniel at softel dot jp 09-Jan-2006 07:34
Note that in PHP5, method_exists() will sucessfully find *private* methods. This has some OO/data-hiding ramifications.
jpgiot at nospam ifrance.com 06-May-2004 07:42
a little difference :

to find a method of an object (instance of a class)

<?php
if (method_exists($myinstance,'themethod'))
    echo 'ok';
?>

to find a method of a class (using the class name, not the instance of the class!)

<?php
if (is_callable(array('theclassname','themethod')))
    echo 'ok';
?>
Thomas@ThBeckmann 31-Jan-2003 01:47
Though, as Bejamin noted, it's not possible to use the class name in method_exists within the class definition, get_class_methods delivers the method names for a given class name even inside the class. Thus another workaround for the mentioned problem is to use in_array(<method_name>, get_class_methods(<class_name>))
benjamin_ansbach at web dot de 27-Dec-2002 12:49
if you want to check for a method "inside" of a class use:

method_exists($this, 'function_name')

i was a bit confused 'cause i thought i'm only able to check for a method when i got an object like $object_name = new class_name() with:

method_exists($object_name, 'method_name')

small example for those who didn't understood what i mean ( maybe caused by bad english :) ):

<?php

class a {

    function a() {

        if(method_exists($this, 'test'))
            echo 'a::test() exists!';
        else
            echo 'a::test() doesn\'t exists';

    }

    function test() {

        return true;

    }

}

$b = new a();

?>

the output will be: a::test() exists!

maybe this will help someone
j dot metzger at steptown dot com 16-Jan-2002 03:42
call_user_method uses the same mechanism as a normal method call. So you can get the returned values as well in this way.

$pagetext=call_user_method($method,$object_call);

All information is then in $pagetext.
is_subclass_of
property_exists
Классы/Объекты


Проверяет, содержит ли объект или класс указанный атрибут

method_exists
trait_exists
Классы/Объекты
PHP Manual

property_exists

(PHP 5 >= 5.1.0)

property_exists — Проверяет, содержит ли объект или класс указанный атрибут

Описание

bool property_exists ( mixed $class , string $property )

Функция проверяет, существует ли атрибут property в указанном классе.

Замечание:

В противоположность isset(), property_exists() возвращает TRUE даже если свойство имеет значение NULL.

Список параметров

class

Имя класса или объекта класса для проверки

property

Имя свойства

Возвращаемые значения

Возвращает TRUE, если свойство существует, FALSE - если оно не существует или NULL в случае ошибки.

Примечания

Замечание:

Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс еще не известен.

Замечание:

Функция property_exists() не определяет магически доступные свойства с помощью метода __get.

Список изменений

Версия | Описание
5.3.0 | Эта функция проверяет существование свойства вне зависимости от его доступности.

Примеры

Пример #1 Пример использования property_exists()

<?php

class myClass {
    public $mine;
    private $xpto;
    static protected $test;

    static function test() {
        var_dump(property_exists('myClass', 'xpto')); //true
    }
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //true, начиная с версии PHP 5.3.0
var_dump(property_exists('myClass', 'bar'));    //false
var_dump(property_exists('myClass', 'test'));   //true, начиная с версии PHP 5.3.0
myClass::test();

?>

Смотрите также

  • method_exists() - Проверяет, существует ли метод в данном классе

User Contributed Notes

foddex at foddex dot net 22-Dec-2010 01:56
Note that before PHP 5.3.3, this function fails for private properties in base classes (which is fixed in 5.3.3)

<?php
class Base {
        private $var = 1;

        public function test() {
                var_dump( property_exists( $this, 'var' ) );
        }
}

class Derived extends Base {
}

$b = new Base();
$b->test();
$d = new Derived();
$d->test();
?>

Executing this code with PHP 5.0 <= x < 5.3 this script echoes (incorrect result):
bool(true)
bool(false)

Executing this code with PHP 5.3 this script echoes (correct result):
bool(true)
bool(true)
webmaster at thedigitalorchard dot ca 24-Apr-2010 09:56
According to my tests, isset() is 4 times faster than property_exists(), so use a combination of these functions in your programming for best performance.

For example:

<?php

$fld = 'somevar';

if (isset($this->$fld) || property_exists($this, $fld)) {

}

?>

If your programming routinely checks a larger number of property names that are expected to exist, whereas a smaller number may not, then using isset(), as above, will result in faster execution of the programming.
peter at nonumber dot nl 27-Aug-2008 02:48
The above PHP4 function did not work for me. This does:

<?php
if ( !function_exists( 'property_exists' ) ) {
    function property_exists( $class, $property ) {
        if ( is_object( $class ) ) {
            $vars = get_object_vars( $class );
        } else {
            $vars = get_class_vars( $class );
        }
        return array_key_exists( $property, $vars );
    }
}
?>
rayro at gmx dot de 11-Nov-2007 04:49
To check the existance of a property from outside the scope (even if it's not accessible) try/consider the following:

<?php
function property_exists_safe($class, $prop)
{
  $r = property_exists($class, $prop);
  if (!$r) {
    $x = new ReflectionClass($class);
    $r = $x->hasProperty($prop);
  }
  return $r;
}

class myClass {
    public $mine;
    private $xpto;

    static function test1() {
        // true, it can be accessed from here
        var_dump(property_exists('myClass', 'xpto'));
    }

    static function test2() {
        // true, it can be accessed from everywhere!
        var_dump(property_exists_safe('myClass', 'xpto'));
    }
}

var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //false, isn't public
myClass::test1();
echo("\n");
var_dump(property_exists_safe('myClass', 'mine')); //true
var_dump(property_exists_safe(new myClass, 'mine')); //true
var_dump(property_exists_safe('myClass', 'xpto')); //true
myClass::test2(); //true
?>

bool(true)
bool(true)
bool(false)
bool(true)

bool(true)
bool(true)
bool(true)
bool(true)
caist at caist dot com 14-Oct-2007 06:19
A niet way to copy properties from one object to another avoiding stuff like:

$obj2 -> prop1 = $obj1 -> prop1;
$obj2 -> prop2 = $obj1 -> prop2;
$obj2 -> prop3 = $obj1 -> prop3;

...is this loop through all properties:

// copies all property values from obj1 to obj2
foreach ($obj1 as $prop_name => $prop_value)
{
    if (property_exists(get_class($obj2), $prop_name))
                 $obj2 -> {$prop_name} = $prop_value;
}
K 13-Jul-2007 01:11
to ssettl2 at google's mail >

1) Use self:: in static methods : http://php.net/language.oop5.static

2) Under the description title of this page : "This function checks if the given property exists in the specified class (and if it is ACCESSIBLE FROM THE CURRENT SCOPE)."

This is normal behaviour in PHP5.

Regards
Alan71 07-Aug-2006 10:57
This function is case-sensitive, so :

<?php
class Test {
   public $property;

   public foo() { echo($property); }
}

property_exists('Test', 'property');   // will return true
property_exists('Test', 'Property');   // will return false
?>

(under PHP5.1.2)
jcaplan at bogus dot amazon dot com 08-Jun-2006 02:35
The documentation leaves out the important case of new properties you add to objects at run time.  In fact, property_exists will return true if you ask it about such properties.

<?
class Y {}
$y = new Y;

echo isset( $y->prop ) ? "yes\n" : "no\n"; // no;
echo property_exists( 'Y', 'prop' ) ? "yes\n" : "no\n"; // no
echo property_exists( $y, 'prop' ) ? "yes\n" : "no\n"; // no

$y->prop = null;

echo isset( $y->prop ) ? "yes\n" : "no\n"; // no;
echo property_exists( 'Y', 'prop' ) ? "yes\n" : "no\n"; // no
echo property_exists( $y, 'prop' ) ? "yes\n" : "no\n"; // yes
?>
Pete W 01-Jun-2006 11:52
In a similar vein to the previous note, To check in PHP4 if an object has a property, even if the property is null:

<?php

if(array_key_exists('propertyName',get_object_vars($myObj)))
{
  // ..the property has been defined
}
?>
timshel 14-Nov-2005 04:20
I haven't tested this with the exact function semantics of 5.1, but this code should implement this function in php < 5.1:

<?php
if (!function_exists('property_exists')) {
  function property_exists($class, $property) {
    if (is_object($class))
      $class = get_class($class);

    return array_key_exists($property, get_class_vars($class));
  }
}
?>
method_exists
trait_exists
Классы/Объекты


Checks if the trait exists

property_exists
Classkit
Классы/Объекты
PHP Manual

trait_exists

(Информация о версии неизвестна, возможно, только в SVN)

trait_exists — Checks if the trait exists

Описание

bool trait_exists ( string $traitname [, bool $autoload ] )

Список параметров

traitname

Name of the trait to check

autoload

Whether to autoload if not already loaded.

Возвращаемые значения

Returns TRUE if trait exists, FALSE if not, NULL in case of an error.

User Contributed Notes

There are no user contributed notes for this page.
property_exists
Classkit
Классы/Объекты


Classkit

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • classkit
    • classkit_import — Импортирует определения методов нового класса из файла
    • classkit_method_add — Динамически добавляет новый метод в заданный класс
    • classkit_method_copy — Копирует метод из одного класса в другой
    • classkit_method_redefine — Динамически меняет код заданного метода
    • classkit_method_remove — Динамически удаляет заданный метод
    • classkit_method_rename — Динамически меняет имя заданного метода

User Contributed Notes

There are no user contributed notes for this page.
trait_exists
Введение
Расширения, относящиеся к переменным и типам


Введение

Эти функции позволяют динамически управлять классами PHP во время выполнения.

Замечание:

Этот модуль был заменен модулем runkit, который не ограничивается управлением классами, а умеет управлять так же и функциями.

User Contributed Notes

There are no user contributed notes for this page.
Classkit
Установка и настройка
Classkit


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Classkit


Установка

Это расширение не поддерживается и считается умершим. Однако, его исходный код все еще доступен в PECL SVN вот здесь: » http://svn.php.net/viewvc/pecl/classkit.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

CLASSKIT_ACC_PRIVATE (int)
Помечает метод, как private
CLASSKIT_ACC_PROTECTED (int)
Помечает метод, как protected
CLASSKIT_ACC_PUBLIC (int)
Помечает метод, как public

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
classkit
Classkit


Classkit
PHP Manual

classkit

Содержание

  • classkit_import — Импортирует определения методов нового класса из файла
  • classkit_method_add — Динамически добавляет новый метод в заданный класс
  • classkit_method_copy — Копирует метод из одного класса в другой
  • classkit_method_redefine — Динамически меняет код заданного метода
  • classkit_method_remove — Динамически удаляет заданный метод
  • classkit_method_rename — Динамически меняет имя заданного метода

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
classkit_import
Classkit
PHP Manual


Импортирует определения методов нового класса из файла

classkit
classkit_method_add
classkit
PHP Manual

classkit_import

(PECL classkit >= 0.3)

classkit_import — Импортирует определения методов нового класса из файла

Описание

array classkit_import ( string $filename )

Замечание: Эта функция не может быть использована для влияния на работающие в данный момент (или цепные) методы.

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

filename

Имя файла с определениями методов класса

Возвращаемые значения

Ассоциативный массив импортированных методов

Примеры

Пример #1 Пример использования classkit_import()

<?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// требуется newclass.php (см. выше)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// вывод оригинала
echo $e->foo();

// импорт замещающего метода
classkit_import('newclass.php');

// вывод импортированного метода
echo $e->foo();

?>

Результат выполнения данного примера:

foo!
bar!

Смотрите также

  • classkit_method_add() - Динамически добавляет новый метод в заданный класс
  • classkit_method_copy() - Копирует метод из одного класса в другой

User Contributed Notes

There are no user contributed notes for this page.
classkit
classkit_method_add
classkit


Динамически добавляет новый метод в заданный класс

classkit_import
classkit_method_copy
classkit
PHP Manual

classkit_method_add

(PECL classkit >= 0.1)

classkit_method_add — Динамически добавляет новый метод в заданный класс

Описание

bool classkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_ACC_PUBLIC ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

classname

Класс, в который этот метод будет добавлен

methodname

Имя добавляемого метода

args

Список аргументов для созданного метода с разделителем ","

code

Код, который будет выполняться во время вызова methodname

flags

Тип создаваемого метода, может быть CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED или CLASSKIT_ACC_PRIVATE

Замечание:

Этот параметр используется только в PHP начиная с 5 версии, поскольку в предыдущих версиях все методы были общедоступными.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования classkit_method_add()

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// создается объект Example
$e = new Example();

// Добавляется новый общедоступный метод
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// сложение 12 + 4
echo $e->add(12, 4);
?>

Результат выполнения данного примера:

16

Смотрите также

  • classkit_method_copy() - Копирует метод из одного класса в другой
  • classkit_method_redefine() - Динамически меняет код заданного метода
  • classkit_method_remove() - Динамически удаляет заданный метод
  • classkit_method_rename() - Динамически меняет имя заданного метода
  • create_function() - Создаёт анонимную (лямбда) функцию

User Contributed Notes

Lester 03-Apr-2008 09:54
If you creates methods by using classkit_method_add(), they are not visible in get_class_methods().

class A
{
       public function foo()
       {
            return "foo!\n";
       }
}

classkit_method_redefine('A','bar','','return "bar !\n";',CLASSKIT_ACC_PUBLIC);

print_r(get_class_methods('A'));
// writes only "foo"
classkit_import
classkit_method_copy
classkit


Копирует метод из одного класса в другой

classkit_method_add
classkit_method_redefine
classkit
PHP Manual

classkit_method_copy

(PECL classkit >= 0.2)

classkit_method_copy — Копирует метод из одного класса в другой

Описание

bool classkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

dClass

Класс, в который необходимо скопировать метод

dMethod

Имя нового метода

sClass

Исходный класс, содержащий копируемый метод

sMethod

Имя копируемого метода из исходного класса. Если этот параметр не указан, предполагается значение dMethod.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования classkit_method_copy()

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // изначально без методов
}

// копируется метод example() из класса Foo в класс Bar, с новым именем baz()
classkit_method_copy('Bar', 'baz', 'Foo', 'example');

// вывод скопированной функции
echo Bar::baz();
?>

Результат выполнения данного примера:

foo!

Смотрите также

  • classkit_method_add() - Динамически добавляет новый метод в заданный класс
  • classkit_method_redefine() - Динамически меняет код заданного метода
  • classkit_method_remove() - Динамически удаляет заданный метод
  • classkit_method_rename() - Динамически меняет имя заданного метода

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_add
classkit_method_redefine
classkit


Динамически меняет код заданного метода

classkit_method_copy
classkit_method_remove
classkit
PHP Manual

classkit_method_redefine

(PECL classkit >= 0.1)

classkit_method_redefine — Динамически меняет код заданного метода

Описание

bool classkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_ACC_PUBLIC ] )

Замечание: Эта функция не может быть использована для влияния на работающие в данный момент (или цепные) методы.

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

classname

Класс, в котором необходимо переопределить метод

methodname

Имя переопределяемого метода

args

Список аргументов переопределяемого метода с разделителем ","

code

Новый код, который будет выполняться во время вызова methodname

flags

Переопределяемый метод может быть CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED или CLASSKIT_ACC_PRIVATE

Замечание:

Этот параметр используется только в PHP начиная с 5 версии, поскольку в предыдущих версиях все методы были общедоступными.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования classkit_method_redefine()

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// создается объект Example
$e = new Example();

// вывод Example::foo() (до переопределения)
echo "Before: " . $e->foo();

// Переопределение метода 'foo'
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// вывод Example::foo() (после переопределения)
echo "After: " . $e->foo();
?>

Результат выполнения данного примера:

Before: foo!
After: bar!

Смотрите также

  • classkit_method_add() - Динамически добавляет новый метод в заданный класс
  • classkit_method_copy() - Копирует метод из одного класса в другой
  • classkit_method_remove() - Динамически удаляет заданный метод
  • classkit_method_rename() - Динамически меняет имя заданного метода

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_copy
classkit_method_remove
classkit


Динамически удаляет заданный метод

classkit_method_redefine
classkit_method_rename
classkit
PHP Manual

classkit_method_remove

(PECL classkit >= 0.1)

classkit_method_remove — Динамически удаляет заданный метод

Описание

bool classkit_method_remove ( string $classname , string $methodname )

Замечание: Эта функция не может быть использована для влияния на работающие в данный момент (или цепные) методы.

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

classname

Класс, в котором необходимо удалить метод

methodname

Имя удаляемого метода

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования classkit_method_remove()

<?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Удаление метода 'foo'
classkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

Результат выполнения данного примера:

bar

Смотрите также

  • classkit_method_add() - Динамически добавляет новый метод в заданный класс
  • classkit_method_copy() - Копирует метод из одного класса в другой
  • classkit_method_redefine() - Динамически меняет код заданного метода
  • classkit_method_rename() - Динамически меняет имя заданного метода

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_redefine
classkit_method_rename
classkit


Динамически меняет имя заданного метода

classkit_method_remove
Ctype
classkit
PHP Manual

classkit_method_rename

(PECL classkit >= 0.1)

classkit_method_rename — Динамически меняет имя заданного метода

Описание

bool classkit_method_rename ( string $classname , string $methodname , string $newname )

Замечание: Эта функция не может быть использована для влияния на работающие в данный момент (или цепные) методы.

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

classname

Класс, в котором необходимо переименовать метод

methodname

Имя переименовываемого метода

newname

Новое имя метода после переименования

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования classkit_method_rename()

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Переименование метода 'foo' в 'bar'
classkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// вывод переименованной функции
echo Example::bar();
?>

Результат выполнения данного примера:

foo!

Смотрите также

  • classkit_method_add() - Динамически добавляет новый метод в заданный класс
  • classkit_method_copy() - Копирует метод из одного класса в другой
  • classkit_method_redefine() - Динамически меняет код заданного метода
  • classkit_method_remove() - Динамически удаляет заданный метод

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_remove
Ctype
classkit


Функции определения типа символов

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Ctype
    • ctype_alnum — Проверяет на наличие буквенно-цифровых символов
    • ctype_alpha — Проверяет на наличие буквенных символов
    • ctype_cntrl — Проверяет на наличие управляющих символов
    • ctype_digit — Проверяет на наличие цифровых символов в строке
    • ctype_graph — Проверяет наличие всех печатных символов, кроме пробела
    • ctype_lower — Проверяет наличие символов в нижнем регистре
    • ctype_print — Проверяет на наличие печатных символов
    • ctype_punct — Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами
    • ctype_space — Проверяет наличие пробельных символов
    • ctype_upper — Проверяет на наличие символов в верхнем регистре
    • ctype_xdigit — Проверяет наличие шестнадцатиричных цифр

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_rename
Введение
Расширения, относящиеся к переменным и типам


Введение

Функции, представленные этим расширением, позволяют проверить принадлежность символа или строки определенному классу символов, принимая во внимание текущие региональные установки (см. также функцию setlocale()).

Будучи вызванными с целочисленным аргументом, эти функции полностью аналогичны своим эквивалентам в языке C (из ctype.h). Это означает, что если вы передаёте целое значение менее 256, функции проверяют соответствует ли это значение ASCII указанному классу символов (цифры находятся в диапазоне 0x30-0x39). Если число находится в пределах от -128 до -1 включительно, то к его значению будет прибавлено 256 и сравнение будет проводиться с использованием результата сложения.

Если аргументом выступает строка, то функции будут проверять каждый символ в этой строке и вернут TRUE только если каждый символ удовлетворяет требуемому условию. При вызове с пустой строкой в качестве аргумента, функции всегда возвращают TRUE в PHP < 5.1 и FALSE после 5.1.

При передаче данных других типов (кроме целого или строки) функции сразу же возвращают FALSE.

Следует обратить внимание на то, что данные функции работают значительно быстрее, чем регулярные выражения и даже эквивалентиные "str_*" и "is_*" функции. Это происходит потому, что ctype использует родную библиотеку C и поэтому выполняется значительно быстрее.

User Contributed Notes

There are no user contributed notes for this page.
Ctype
Установка и настройка
Ctype


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Ctype


Требования

Стандартная библиотека C всегда доступна, поэтому дополнительных требования нет.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Начиная с PHP 4.2.0 эти функции включены по умолчанию. В предыдущих версиях вы должны сконфигурировать и откомпилировать PHP с --enable-ctype . Запретить поддержку ctype можно с помощью --disable-ctype .

Версия PHP для Windows имеет встроенную поддержку данного расширения. Это означает, что для использования данных функций не требуется загрузка никаких дополнительных расширений.

Замечание: Встроенная поддержка ctype доступна с PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Ctype
Ctype


Ctype
PHP Manual

Ctype

Содержание

  • ctype_alnum — Проверяет на наличие буквенно-цифровых символов
  • ctype_alpha — Проверяет на наличие буквенных символов
  • ctype_cntrl — Проверяет на наличие управляющих символов
  • ctype_digit — Проверяет на наличие цифровых символов в строке
  • ctype_graph — Проверяет наличие всех печатных символов, кроме пробела
  • ctype_lower — Проверяет наличие символов в нижнем регистре
  • ctype_print — Проверяет на наличие печатных символов
  • ctype_punct — Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами
  • ctype_space — Проверяет наличие пробельных символов
  • ctype_upper — Проверяет на наличие символов в верхнем регистре
  • ctype_xdigit — Проверяет наличие шестнадцатиричных цифр

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
ctype_alnum
Ctype
PHP Manual


Проверяет на наличие буквенно-цифровых символов

Ctype
ctype_alpha
Ctype
PHP Manual

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5)

ctype_alnum — Проверяет на наличие буквенно-цифровых символов

Описание

bool ctype_alnum ( string $text )

Проверяет, все ли символы в переданной строке text являются буквенно-цифровыми. В стандартной локали C буквами являются только [A-Za-z].

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text является буквой или цифрой, иначе возвращается FALSE.

Примеры

Пример #1 Пример использования ctype_alnum() (с использованием локали по умолчанию)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "Строка $testcase состоит только из букв и цифр.\n";
    } else {
        echo "Строка $testcase не состоит только из букв и цифр.\n";
    }
}
?>

Результат выполнения данного примера:

Строка AbCd1zyZ9 состоит только из букв и цифр.
Строка foo!#$bar не состоит только из букв и цифр.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_alpha() - Проверяет на наличие буквенных символов
  • ctype_digit() - Проверяет на наличие цифровых символов в строке
  • setlocale() - Устанавливает настройки локали

User Contributed Notes

Rory 07-Dec-2009 04:42
Just for the record, Gentoo doesn't include this function by default. You'll have to recompile PHP with the "ctype" USE flag.
Josip Rodin 12-Aug-2009 09:13
There doesn't actually seem to be a performance loss compared to using regexes. For example:

<?php
$sUser = 'my_username01';

$time_start1 = microtime(true);
$aValid = array('-', '_');
$ret1 = ctype_alnum(str_replace($aValid, '', $sUser));
$time_end1 = microtime(true);
$time1 = $time_end1 - $time_start1;
printf("Checked it with ctype_alnum and got %d in %.10f seconds\n", print_r($ret1, true), $time1);

$time_start2 = microtime(true);
$ret2 = preg_match('/^[\w-]+$/', $sUser);
$time_end2 = microtime(true);
$time2 = $time_end2 - $time_start2;
printf("Checked it with preg_match  and got %d in %.10f seconds\n", print_r($ret2, true), $time2);

?>

This returns:

% time php ctype_alnum.php
Checked it with ctype_alnum and got 1 in 0.0000379086 seconds
Checked it with preg_match  and got 1 in 0.0001120567 seconds
php ctype_alnum.php  0,01s user 0,01s system 84% cpu 0,024 total
% time php ctype_alnum.php
Checked it with ctype_alnum and got 1 in 0.0000400543 seconds
Checked it with preg_match  and got 1 in 0.0001108646 seconds
php ctype_alnum.php  0,00s user 0,02s system 98% cpu 0,024 total
% time php ctype_alnum.php
Checked it with ctype_alnum and got 1 in 0.0000391006 seconds
Checked it with preg_match  and got 1 in 0.0001142025 seconds
php ctype_alnum.php  0,02s user 0,01s system 98% cpu 0,024 total

ctype_alnum() seems to be consistently faster. I'm guessing that the preg engine initialization induces a bit of overhead.
thinice at gmail dot com 22-Jul-2009 02:46
ctype_alnum() is a godsend for quick and easy username/data filtering when used in conjunction with str_replace().

Let's say your usernames have dash(-) and underscore(_) allowable and alphanumeric digits as well.

Instead of a regex you can trade a bit of performance for simplicity:

<?php
$sUser = 'my_username01';
$aValid = array('-', '_');

if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
    echo 'Your username is not properly formatted.';
}
?>
Ctype
ctype_alpha
Ctype


Проверяет на наличие буквенных символов

ctype_alnum
ctype_cntrl
Ctype
PHP Manual

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5)

ctype_alpha — Проверяет на наличие буквенных символов

Описание

bool ctype_alpha ( string $text )

Проверяет, все ли символы в переданной строке text являются буквенными. В стандартной локали C буквами являются только [A-Za-z] и ctype_alpha() эквивалентна (ctype_upper($text) || ctype_lower($text)), если $text состоит всего из одного символа, но в других языках есть буквы, которые не считаются ни верхним, ни нижним регистром.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text является буквой из текущей локали, FALSE в противном случае.

Примеры

Пример #1 Пример использования ctype_alpha() (с использованием локали по умолчанию)

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
    if (ctype_alpha($testcase)) {
        echo "Строка $testcase состоит только из букв.\n";
    } else {
        echo "Строка $testcase состоит не только из букв.\n";
    }
}
?>

Результат выполнения данного примера:

Строка KjgWZC состоит только из букв.
Строка arf12 состоит не только из букв.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_upper() - Проверяет на наличие символов в верхнем регистре
  • ctype_lower() - Проверяет наличие символов в нижнем регистре
  • setlocale() - Устанавливает настройки локали

User Contributed Notes

Tyrunur 27-May-2009 02:12
It works if you set the locale correctly:

<?php

setLocale(LC_CTYPE, 'FR_fr.UTF-8');

?>

with this change you will get "yes" "yes"
jerome at yazo dot net 14-Mar-2009 08:18
worth noticing? It seems that the ctype_alpha family of functions won't handle UTF-8 string (php 5.2.6)

<?php

$texte = 'jérôme';
setLocale(LC_CTYPE, 'FR_fr');
echo 'Pure ascii ? ', (ctype_alpha($texte) ) ? 'yes' : 'no';
echo '<br />';
$texte = iconv( "UTF-8", "ISO-8859-1", $texte) ;
echo  'Letters only ? ' , (ctype_alpha($texte) ) ? 'yes' : 'no';

?>

ouputs :

Pure ascii ? no
Letters only ? yes
ctype_alnum
ctype_cntrl
Ctype


Проверяет на наличие управляющих символов

ctype_alpha
ctype_digit
Ctype
PHP Manual

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5)

ctype_cntrl — Проверяет на наличие управляющих символов

Описание

bool ctype_cntrl ( string $text )

Проверяет, все ли символы в переданной строке text являются управляющими символами. Управляющими символами, к примеру, являются перевод строки, символ табуляции, escape.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text является управляющим символом из текущей локали, FALSE в противном случае.

Примеры

Пример #1 Пример использования ctype_cntrl()

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
    if (ctype_cntrl($testcase)) {
        echo "Строка '$name' состоит только из управляющих символов.\n";
    } else {
        echo "Строка '$name' не состоит только из управляющих символов.\n";
    }
}
?>

Результат выполнения данного примера:

Строка 'string1' состоит только из управляющих символов.
Строка 'string2' не состоит только из управляющих символов.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_print() - Проверяет на наличие печатных символов

User Contributed Notes

There are no user contributed notes for this page.
ctype_alpha
ctype_digit
Ctype


Проверяет на наличие цифровых символов в строке

ctype_cntrl
ctype_graph
Ctype
PHP Manual

ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit — Проверяет на наличие цифровых символов в строке

Описание

bool ctype_digit ( string $text )

Проверяет, являются ли все символы в строке text цифровыми.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE если каждый символ строки text является десятичной цифрой, либо FALSE в противном случае.

Список изменений

Версия | Описание
5.1.0 | До версии PHP 5.1.0 эта функция возвращала TRUE, если в качестве text передавалась пустая строка.

Примеры

Пример #1 Пример использования ctype_digit()

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "Строка $testcase состоит только из цифр.\n";
    } else {
        echo "Строка $testcase не состоит только из цифр.\n";
    }
}
?>

Результат выполнения данного примера:

Строка 1820.20 не состоит только из цифр.
Строка 10002 состоит только из цифр.
Строка wsl!12 не состоит только из цифр.

Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 это символ * )

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

Примечания

Замечание:

Для извлечения пользы из работы этой функции ей необходимо передавать строку (string), поэтому, если ей, к примеру, будет передан integer, то она может не возвратить ожидаемый результат. Однако, необходимо учитывать, что HTML-формы передают числовые строки, а не целые числа. Подробнее читайте в разделе "Типы" данного руководства.

Смотрите также

  • ctype_alnum() - Проверяет на наличие буквенно-цифровых символов
  • ctype_xdigit() - Проверяет наличие шестнадцатиричных цифр
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_string() - Проверяет, является ли переменная строкой

User Contributed Notes

info at directwebsolutions dot nl 19-May-2012 09:16
All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: "123").
3. ctype_digit() excepts all numbers to be strings (like: "123") and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

My function only accepts numbers regardless whether they are in string or in integer format.
<?php
    /**
     * Check input for existing only of digits (numbers)
     * @author Tim Boormans <info@directwebsolutions.nl>
     * @param $digit
     * @return bool
     */
    function is_digit($digit) {
        if(is_int($digit)) {
            return true;
        } elseif(is_string($digit)) {
            return ctype_digit($digit);
        } else {
            // booleans, floats and others
            return false;
        }
    }
?>
Skippy 25-Oct-2011 01:44
If you need to check for integers instead of just digits you can supply your own function such as this:

<?php
function ctype_int($text)
{
    return preg_match('/^-?[0-9]+$/', (string)$text) ? true : false;
}
?>
portalpress dot org at gmail dot com 22-May-2011 08:24
To my surprise after one million iterations:

It took 0.5646638 seconds to false if(('abc'*1 . '')==='abc')
It took 0.5725240 seconds to true if(('123'*1 . '')==='123')
It took 0.3741021 seconds to false if((('abc'*1) . '')==='abc')
It took 0.4357590 seconds to true if((('123'*1) . '')==='123')
It took 0.3529291 seconds to false ctype_digit('abc')
It took 0.3391420 seconds to true ctype_digit('123')

The function ctype_digit() is faster then an inline if().
But this test also shows the value of ((first*1) . second).
mdsky at web dot de 21-May-2010 12:44
is_numeric gives true by f. ex. 1e3 or 0xf5 too. So it's not the same as ctype_digit, which just gives true when only values from 0 to 9 are entered.
John Saman 05-Feb-2010 05:38
Using is_numeric function is quite faster than ctype_digit.

is_numeric took 0.237 Seconds for one million runs. while ctype_digit took 0.470 Seconds.
strrev xc tod noxeh ta ellij 14-Dec-2009 08:41
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII '0'-'9') and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)
walter 09-Dec-2009 02:18
I was looking at whether this would save time on the numerous input validations I make in legions of scripts.  Typically I use a function numbers_only() which simply does a preg_replace() to remove non-digits from a string.

To test for a possible speedup, I created a new function which only performed the preg_replace() once a type_digit() check had failed.

The results for 1 million interations showed that using ctype_digit() beforehand caused approximately 1/3rd additional latency on strings that were going to be preg_replace()'d anyway (ie: strings that did not contain only digits).  It caused an over 100% speedup over that (latency inclusive) time for input strings that were pure numbers.  The speedup was around 2/3 of the original blind preg_replace().

The lesson for me is that it's only worth trying to optimise away preg_replace() using ctype_digit() or similar if you know with some certainty that the vast majority of your inputs will lean one way or the other.

Having said that, ctype_digit() seems to be cosnistently 30% faster than preg_match().  But adding the additional PHP option as a requirement for your codebase may not justify the optimisation.

Let's face it: PHP aint exactly assembler, even if it is much faster than ruby :)
Chris 02-Aug-2009 12:17
Remove all non-printable characters from a string:
<?php
$str = implode('', array_filter(str_split($str, 1), 'ctype_print'));
?>
Peter de Pijd 18-Jul-2009 03:53
Note that an empty string is also false:
ctype_digit("") // false
a_p_leeming at hotmail dot com 24-May-2009 06:17
Also note that

<?php ctype_digit("-1");   //false ?>
raul dot 3k at gmail dot com 09-Apr-2009 08:21
The ctype_digit can be used in a simple form to validate a field:
<?php
$field = $_POST["field"];
if(!ctype_digit($field)){
  echo "It's not a digit";
}
?>

Note:
Digits is 0-9
Anonymous 19-Nov-2008 01:56
Indeed, ctype_digit only functions correctly on strings. Cast your vars to string before you test them. Also, be wary and only use ctype_digit if you're sure your var contains either a string or int, as boolean true for ex will convert to int 1.

To be truly safe, you need to check the type of the var first. Here's a wrapper function that improves upon ctype_digit's broken implementation:

<?php

// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
    return (is_string($str) || is_int($str) || is_float($str)) &&
        ctype_digit((string)$str);
}

?>

If, like me, you're not willing to take a chance on ctype_digit having other problems, use this version:

<?php

// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
    return (is_string($str) || is_int($str) || is_float($str)) &&
        preg_match('/^\d+\z/', $str);
}

?>
minterior at gmail dot com 10-Sep-2007 07:43
I use ctype_digit() function as a part of this IMEI validation function.

<?php

/**
 * Check the IMEI of a mobile phone
 * @param $imei IMEI to validate
 */
function is_IMEI_valid($imei){
    if(!ctype_digit($imei)) return false;
    $len = strlen($imei);
    if($len != 15) return false;

    for($ii=1, $sum=0 ; $ii < $len ; $ii++){
        if($ii % 2 == 0) $prod = 2;
        else $prod = 1;
        $num = $prod * $imei[$ii-1];
        if($num > 9){
          $numstr = strval($num);
          $sum += $numstr[0] + $numstr[1];
        }else $sum += $num;
    }

    $sumlast = intval(10*(($sum/10)-floor($sum/10))); //The last digit of $sum
    $dif = (10-$sumlast);
    $diflast = intval(10*(($dif/10)-floor($dif/10))); //The last digit of $dif
    $CD = intval($imei[$len-1]); //check digit

    if($diflast == $CD) return true;

    return false;
}
?>
ctype_cntrl
ctype_graph
Ctype


Проверяет наличие всех печатных символов, кроме пробела

ctype_digit
ctype_lower
Ctype
PHP Manual

ctype_graph

(PHP 4 >= 4.0.4, PHP 5)

ctype_graph — Проверяет наличие всех печатных символов, кроме пробела

Описание

bool ctype_graph ( string $text )

Проверяет, все ли символы в переданной строке text являются видимыми при печати.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text печатный и фактически создает видимый вывод (без пробельных символов), FALSE в противном случае.

Примеры

Пример #1 Пример использования ctype_graph()

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_graph($testcase)) {
        echo "Строка '$name' состоит только из (видимых) печатных символов.\n";
    } else {
        echo "Строка '$name' не состоит только из (видимых) печатных символов.\n";
    }
}
?>

Результат выполнения данного примера:

Строка 'string1' не состоит только из (видимых) печатных символов.
Строка 'string2' состоит только из (видимых) печатных символов.
Строка 'string3' состоит только из (видимых) печатных символов.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_alnum() - Проверяет на наличие буквенно-цифровых символов
  • ctype_print() - Проверяет на наличие печатных символов
  • ctype_punct() - Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами

User Contributed Notes

There are no user contributed notes for this page.
ctype_digit
ctype_lower
Ctype


Проверяет наличие символов в нижнем регистре

ctype_graph
ctype_print
Ctype
PHP Manual

ctype_lower

(PHP 4 >= 4.0.4, PHP 5)

ctype_lower — Проверяет наличие символов в нижнем регистре

Описание

bool ctype_lower ( string $text )

Проверяет, все ли символы в переданной строке text являются буквами в нижнем регистре.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text является буквой в нижнем регистре в текущей локали.

Примеры

Пример #1 Пример использования ctype_lower() (с использованием локали по умолчанию)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
    if (ctype_lower($testcase)) {
        echo "Строка $testcase состоит только из букв в нижнем регистре.\n";
    } else {
        echo "Строка $testcase не состоит только из букв в нижнем регистре.\n";
    }
}
?>

Результат выполнения данного примера:

Строка aac123 не состоит только из букв в нижнем регистре.
Строка qiutoas состоит только из букв в нижнем регистре.
Строка QASsdks не состоит только из букв в нижнем регистре.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_alpha() - Проверяет на наличие буквенных символов
  • ctype_upper() - Проверяет на наличие символов в верхнем регистре
  • setlocale() - Устанавливает настройки локали

User Contributed Notes

There are no user contributed notes for this page.
ctype_graph
ctype_print
Ctype


Проверяет на наличие печатных символов

ctype_lower
ctype_punct
Ctype
PHP Manual

ctype_print

(PHP 4 >= 4.0.4, PHP 5)

ctype_print — Проверяет на наличие печатных символов

Описание

bool ctype_print ( string $text )

Проверяет, все ли символы в переданной строке text являются печатными.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text фактически создает вывод (включая пустой). Возвращает FALSE, если text содержит управляющие символы, или символы, которые вообще не имеют никакого вывода или функции управления.

Примеры

Пример #1 Пример использования ctype_print()

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_print($testcase)) {
        echo "Строка '$name' состоит только из печатных символов.\n";
    } else {
        echo "Строка '$name' не состоит только из печатных символов.\n";
    }
}
?>

Результат выполнения данного примера:

Строка 'string1' не состоит только из печатных символов.
Строка 'string2' состоит только из печатных символов.
Строка 'string3' состоит только из печатных символов.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_cntrl() - Проверяет на наличие управляющих символов
  • ctype_graph() - Проверяет наличие всех печатных символов, кроме пробела
  • ctype_punct() - Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами

User Contributed Notes

flatline at greyhat dot nl 03-Mar-2004 04:58
It seems that this function does not recognize characters such as '�', '�', '�', '�' as printable.

Depends on your locale settings, in the default "C" locale they are
indeed not printable as it is 7bit ASCII based. (hartmut)
ctype_lower
ctype_punct
Ctype


Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами

ctype_print
ctype_space
Ctype
PHP Manual

ctype_punct

(PHP 4 >= 4.0.4, PHP 5)

ctype_punct — Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами

Описание

bool ctype_punct ( string $text )

Проверяет, все ли символы в переданной строке text являются знаками пунктуации.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text является печатным, но не является ни буквой, ни цифрой, ни пустым символом, иначе будет возвращено FALSE.

Примеры

Пример #1 Пример использования ctype_punct()

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
    if (ctype_punct($testcase)) {
        echo "Строка $testcase состоит только из знаков пунктуации.\n";
    } else {
        echo "Строка $testcase не состоит только из знаков пунктуации.\n";
    }
}
?>

Результат выполнения данного примера:

Строка ABasdk!@!$# не состоит только из знаков пунктуации.
Строка !@ # $ не состоит только из знаков пунктуации.
Строка *&$() состоит только из знаков пунктуации.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_cntrl() - Проверяет на наличие управляющих символов
  • ctype_graph() - Проверяет наличие всех печатных символов, кроме пробела

User Contributed Notes

There are no user contributed notes for this page.
ctype_print
ctype_space
Ctype


Проверяет наличие пробельных символов

ctype_punct
ctype_upper
Ctype
PHP Manual

ctype_space

(PHP 4 >= 4.0.4, PHP 5)

ctype_space — Проверяет наличие пробельных символов

Описание

bool ctype_space ( string $text )

Проверяет, все ли символы в переданной строке text являются пробельными.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text создает какой-нибудь из пробельных символов, FALSE в противном случае. Кроме пробела, сюда также относятся символы табуляции, вертикальной табуляции, перевода строки, возврата каретки и перевода страницы.

Примеры

Пример #1 Пример использования ctype_space()

<?php
$strings = array('string1' => "\n\r\t", 'string2' => "\narf12", 'string3' => '\n\r\t');
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "Строка '$name' состоит только из пробельных символов.\n";
    } else {
        echo "Строка '$name' не состоит только из пробельных символов.\n";
    }
}
?>

Результат выполнения данного примера:

Строка 'string1' состоит только из пробельных символов.
Строка 'string2' не состоит только из пробельных символов.
Строка 'string3' не состоит только из пробельных символов.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_cntrl() - Проверяет на наличие управляющих символов
  • ctype_graph() - Проверяет наличие всех печатных символов, кроме пробела
  • ctype_punct() - Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами

User Contributed Notes

gardnerjohng at hotmail dot com 14-Sep-2009 09:00
A function I wrote last night was fairly flexible in terms of detecting whitespace, and even took into account the pesky non-breaking spaces / zero-width spaces further up the Unicode alphabet.

The benefit here was being able to isolate and identify specific Unicode indices based on their subrange.

<?php
    //    Returns TRUE if the ASCII value of $string matches a registered whitespace character.
    //    *    This includes non-breaking spaces, zero-width spaces, and any unicode values below 32.
    //    *    $string: Character to identify. If string extends past one character, the value
    //        is truncated and only the initial character is examined.
    function is_whitespace($string){
        //    Return FALSE if passed an empty string.
        if($string == "") return FALSE;

        $char    =    ord($string);

        //    Control Characters
        if($char < 33)                        return TRUE;
        if($char > 8191 && $char < 8208)    return TRUE;
        if($char > 8231 && $char < 8240)    return TRUE;

        //    Additional Characters
        switch($char){
            case 160:    // Non-Breaking Space
            case 8287:    // Medium Mathematical Space
                return TRUE;
                break;
        }
        return FALSE;
    }
?>
per dot zut at gmail dot com 22-Jul-2008 12:48
The contradiction bellow brutaly forced me to do some testing.

ctype_space(""), as well as ctype_space(NULL), returns false
ctype_space(), returns NULL, with a warning

(PHP Version 4.4.8)
abozzay at yahoo dot com 07-May-2008 02:53
PHP Version 5.2.3-1ubuntu6
ctype_space("") returns false
Anonymous 17-Oct-2007 08:46
ctype_space("") i.e. the empty string, returns true
ctype_punct
ctype_upper
Ctype


Проверяет на наличие символов в верхнем регистре

ctype_space
ctype_xdigit
Ctype
PHP Manual

ctype_upper

(PHP 4 >= 4.0.4, PHP 5)

ctype_upper — Проверяет на наличие символов в верхнем регистре

Описание

bool ctype_upper ( string $text )

Проверяет, все ли символы в переданной строке text являются буквами в верхнем регистре.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE, если каждый символ в строке text является буквой в верхнем регистре в текущей локали.

Примеры

Пример #1 Пример использования ctype_upper() (с использованием локали по умолчанию)

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
    if (ctype_upper($testcase)) {
        echo "Строка $testcase состоит только из букв в верхнем регистре.\n";
    } else {
        echo "Строка $testcase не состоит только из букв в верхнем регистре.\n";
    }
}
?>

Результат выполнения данного примера:

Строка AKLWC139 не состоит только из букв в верхнем регистре.
Строка LMNSDO состоит только из букв в верхнем регистре.
Строка akwSKWsm не состоит только из букв в верхнем регистре.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_alpha() - Проверяет на наличие буквенных символов
  • ctype_lower() - Проверяет наличие символов в нижнем регистре
  • setlocale() - Устанавливает настройки локали

User Contributed Notes

There are no user contributed notes for this page.
ctype_space
ctype_xdigit
Ctype


Проверяет наличие шестнадцатиричных цифр

ctype_upper
Filter
Ctype
PHP Manual

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5)

ctype_xdigit — Проверяет наличие шестнадцатиричных цифр

Описание

bool ctype_xdigit ( string $text )

Проверяет, являются ли все символы в строке text шестнадцатиричными 'цифрами'.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

Возвращает TRUE если каждый символ строки text является шестнадцатиричной 'цифрой', то есть десятичной цифрой либо символом из диапазона [A-Fa-f], в обратном случае возвращает FALSE.

Примеры

Пример #1 Пример использования ctype_xdigit()

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "Строка $testcase состоит из шестнадцатиричных цифр.\n";
    } else {
        echo "Строка $testcase состоит не только из шестнадцатиричных цифр.\n";
    }
}
?>

Результат выполнения данного примера:

Строка AB10BC99 состоит из шестнадцатиричных цифр.
Строка AR1012 состоит не только из шестнадцатиричных цифр.
Строка ab12bc99 состоит из шестнадцатиричных цифр.

Примечания

Замечание:

Если передан integer в диапазоне между -128 и 255 включительно, то он будет обработан как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Смотрите также

  • ctype_digit() - Проверяет на наличие цифровых символов в строке

User Contributed Notes

tom at hgmail dot com 14-Jan-2006 12:36
This function shows its usefulness on a web site where a user is asked to entered a hexidecimal color code for a color. To prevent breaking W3C standard and having them enter in "neon-green" or the wrong type of code like 355511235.

In conjunction with strlen()  you could create a function like this:

function check_valid_colorhex($colorCode) {
    // If user accidentally passed along the # sign, strip it off
    $colorCode = ltrim($colorCode, '#');

    if (
          ctype_xdigit($colorCode) &&
          (strlen($colorCode) == 6 || strlen($colorCode) == 3))
               return true;

    else return false;
}
ctype_upper
Filter
Ctype


Фильтрация данных

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Types of filters
    • Фильтры валидации данных
    • Очищающие фильтры
    • Остальные фильтры
    • Флаги, используемые в фильтрах
  • Предопределенные константы
  • Примеры
    • Валидация
    • Нормализация значения (Sanitizing)
  • Фильтрация данных
    • filter_has_var — Проверяет существование переменной указанного типа
    • filter_id — Возвращает идентификатор, принадлежащий именованному фильтру
    • filter_input_array — Принимает несколько переменных извне PHP и, при необходимости, фильтрует их
    • filter_input — Принимает переменную извне PHP и, при необходимости, фильтрует ее
    • filter_list — Возвращает список всех поддерживаемых фильтров
    • filter_var_array — Принимает несколько переменных и, при необходимости, фильтрует их
    • filter_var — Фильтрует переменную с помощью определенного фильтра

User Contributed Notes

There are no user contributed notes for this page.
ctype_xdigit
Введение
Расширения, относящиеся к переменным и типам


Введение

Фильтры данного расширения позволяют выполнить валидацию данных и обезопасить их от возможных вредоносных конструкций. Это особенно полезно, если содержимое получено из неизвестных или ненадежных источников, таких, как пользовательский ввод. Например, такие данные можно получить из HTML-форм.

Существует два основных типа фильтрации: проверка и очистка.

Проверка используется для определения соответствия данных определённым критериям. Например, применение FILTER_VALIDATE_EMAIL позволяет проверить, являются ли введённые данные адресом email, однако, сами данные при этом останутся нетронутыми.

Очистка используется для для извлечения из данных нежелательных конструкций. Например, применение FILTER_SANITIZE_EMAIL удалит все символы, которые не должен содержать email-адрес. То есть, проверки данных не происходит.

Кроме того, можно использовать различные флаги, как для проверки, так и для очистки, для более тонкой настройки согласно вашим нуждам. Например, передача флага FILTER_FLAG_PATH_REQUIRED при фильтрации URL установит необходимым условием наличие пути в ссылке (например, /foo в http://example.org/foo).

User Contributed Notes

There are no user contributed notes for this page.
Filter
Установка и настройка
Filter


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Filter


Установка

Начиная с версии PHP 5.2.0 расширение filter включено по умолчанию. До этой версии использовалось экспериментальное PECL-расширение, однако, оно больше не обновляется и поэтому не рекомендуется к использованию.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

Параметры конфигурации Filter
Имя | По умолчанию | Меняемо | Список изменений
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL в filter <= 0.9.4. Доступна с PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL в filter <= 0.9.4. Доступна с PHP 5.2.0.
Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.

Краткое разъяснение конфигурационных директив.

filter.default string

Фильтрует все $_GET, $_POST, $_COOKIE, $_REQUEST и $_SERVER данные этим фильтром. Исходные данные могут быть получены с помощью filter_input().

Принимает имя указанного фильтра как значение по умолчанию. Имена фильтров можно найти в списке существующих фильтров.

Замечание:

Будьте внимательны с флагами по умолчанию для фильтров по умолчанию. Следует явно устанавливать их в то значение, которое вам необходимо. Например, для установки фильтра по умолчанию, который будет работать точь-в-точь аналогично функции htmlspecialchars(), вам необходимо установить флаги по умолчанию в 0 так, как показано ниже.

Пример #1 Настройка фильтра по умолчанию для работы аналогично функции htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

filter.default_flags integer

Флаги по умолчанию, которые применяются, когда установлен фильтр по умолчанию. По умолчанию установлено в значение FILTER_FLAG_NO_ENCODE_QUOTES для сохранения обратной совместимости. Смотрите списке существующих флагов для ознакомления со списком всех имен флагов.

User Contributed Notes

warbaby67 at gmail dot com 14-Dec-2010 10:04
filter.default sets the default FILTER by name.
filter.default_flags sets default FLAGS for the default filter.

The values for filter.default should be a string "name" of a valid FILTER:

"int"      FILTER_VALIDATE_INT
"boolean"  FILTER_VALIDATE_BOOLEAN

The irony of the entire list I typed being blocked by the SPAM filter is not lost on me.  Perhaps I'm not the first.
Установка
Типы ресурсов
Установка и настройка


Типы ресурсов

Данное расширение не определяет никакие типы ресурсов.

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Types of filters
Установка и настройка


Types of filters

Содержание

  • Фильтры валидации данных
  • Очищающие фильтры
  • Остальные фильтры
  • Флаги, используемые в фильтрах

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Фильтры валидации данных
Filter


Фильтры валидации данных

Список фильтров валидации данных
ID | Имя | Параметры | Флаги | Описание
FILTER_VALIDATE_BOOLEAN | "boolean" |  | FILTER_NULL_ON_FAILURE | Возвращает TRUE для значений "1", "true", "on" и "yes". Иначе возвращает FALSE. Если установлен флаг FILTER_NULL_ON_FAILURE, то FALSE возвращается только для значений "0", "false", "off", "no" и "", а NULL будет возвращен для всех небулевых значений.
FILTER_VALIDATE_EMAIL | "validate_email" |  |  | Проверяет, что значение является корректным e-mail.
FILTER_VALIDATE_FLOAT | "float" | decimal | FILTER_FLAG_ALLOW_THOUSAND | Проверяет, что значение является корректным числом с плавающей точкой.
FILTER_VALIDATE_INT | "int" | min_range, max_range | FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX | Проверяет, что значение является корректным целым числом, и, при необходимости, входит в определенный диапазон.
FILTER_VALIDATE_IP | "validate_ip" |  | FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE | Проверяет, что значение является корректным IP-адресом, при необходимости только для протоколов IPv4 или IPv6, а также отсутствие вхождения в частные или зарезервированные диапазоны.
FILTER_VALIDATE_REGEXP | "validate_regexp" | regexp |  | Проверяет значение на соответствие regexp, Perl-совместимому регулярному выражению.
FILTER_VALIDATE_URL | "validate_url" |  | FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED | Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

Замечание:

Числа +0 и -0 не пройдут проверку на целые числа, но пройдут ее на числа с плавающей точкой.

User Contributed Notes

bee kay two at em ee dot com 06-May-2012 04:45
Notably missing is a way to validate text entry as printable,
printable multiline,
or printable and safe (tag free)

FILTER_VALIDATE_TEXT, which validates no special characters
perhaps with FILTER_FLAG_ALLOW_NEWLINE
and FILTER_FLAG_NOTAG to disallow tag starters
Tom 09-Apr-2012 10:08
Be aware!

In contrary to what the docs say (at least in PHP 5.3.1), this line:

$value = filter_var(FALSE, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

Will return NULL - not false. In other words: a boolean FALSE is not considered a valid boolean value by this function.

Also:

$value = filter_var("", FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

Will also return NULL - no matter what the docs say. So (string) FALSE is not considered a valid boolean input either.

Thus be aware the that correct usage/workaround for this filter is:

if (!is_bool($value)) {
    $value= filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}

For those of you who feel this is counterintuitive, note that there is an issue filed for this in the bug-tracker.
So you might want to follow the discussion there or vote for issue #49510.
Levi Morrison 26-Oct-2011 12:10
It's important to note that in PHP, false==null is true.  This means when you are using the FILTER_VALIDATE_BOOLEAN, you must use '===' and '!==' to check to see if something is/isn't null.

<?php
$false = filter_var('0', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

if ($false==null) {
    //will execute
}

if ($false===null) {
    //will not execute
}
?>
Griff 01-Sep-2011 04:28
<< FILTER_VALIDATE_EMAIL allows incomplete e-mail addresses to be validated, for examle john@gmail will validate as a proper e-mail address >>

"Plain" hostnames with no dots are valid in email addresses -
for example, "me@localhost".
php at sethsyberg dot com 07-Apr-2011 01:00
When validating floats, you must use the Identical/Not identical operators for proper validation of zeros:

This will not work as expected:
<?php
$x = 0;
if (!filter_var($x, FILTER_VALIDATE_FLOAT)) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>

This will work as expected:
<?php
$x = 0;
if (filter_var($x, FILTER_VALIDATE_FLOAT)!== false) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>
chastell at chastell dot net 15-Mar-2011 07:54
example@example is a perfectly valid email address – I use chastell@localhost and chastell@devielle (my computer’s name) email addresses all the time and they get delivered just fine.
eleljrk at gmail dot com 19-Feb-2011 07:23
For PHP 5.3.1 FILTER_VALIDATE_EMAIL does validate incomplete email addresses such as: example@example

Otherwise it's really good because FILTER_VALIDATE_EMAIL validates the standards of the local part very well.

This is a valid email address:
"this is a valid email@[]{}and it should be"@example.com
And FILTER_VALIDATE_EMAIL validate it.

But this isn't a valid email address:
"this is a valid email@[]{}and it should be"@example
However, FILTER_VALIDATE_EMAIL does validate it.
php dot net at piskvor dot org 11-Feb-2011 08:57
FILTER_VALIDATE_EMAIL is discarding valid e-mail addresses containing IDN. Since there are real, live IDNs on the Internet, that means the filtered output is too strict, leading to false negatives.

Punycode-encoded IDN addresses pass the filter correctly; so before checking for validity, it is necessary to convert the e-mail address to punycode.
Clifton 05-Jan-2011 08:00
FILTER_VALIDATE_EMAIL does NOT allow incomplete e-mail addresses to be validated as mentioned by Tomas.

Using the following code:

<?php
$email = "clifton@example"; //Note the .com missing
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
bool(false)

While the following code:

<?php
$email = "clifton@example.com"; //Note the .com added
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
clifton@example.com
string(16) "clifton@example.com"

This feature is only available for PHP Versions (PHP 5 >= 5.2.0) according to documentation. So make sure your version is correct.

Cheers,
Clifton
tomas dot chlouba at gmail dot com 18-Dec-2010 08:42
FILTER_VALIDATE_EMAIL allows incomplete e-mail addresses to be validated, for examle john@gmail will validate as a proper e-mail address.
pravila at alumni dot calpoly dot edu 21-Mar-2010 08:53
Take caution when using the FILTER_VALIDATE_BOOLEAN filter as it seems to have different behaviors when used in the filter_var() vs. the filter_input() functions.

To demonstrate, let's parse some arguments from a GET request (notice how arg2 is NOT set):

example.com/script.php?arg1=yes&arg3=no

<?php
// filtering by variable
$var1 = filter_var($_GET["arg1"], FILTER_VALIDATE_BOOLEAN);
$var2 = filter_var($_GET["arg2"], FILTER_VALIDATE_BOOLEAN);
$var3 = filter_var($_GET["arg3"], FILTER_VALIDATE_BOOLEAN);

// filtering by input
$input1 = filter_input(INPUT_GET, "arg1", FILTER_VALIDATE_BOOLEAN);
$input2 = filter_input(INPUT_GET, "arg2", FILTER_VALIDATE_BOOLEAN);
$input3 = filter_input(INPUT_GET, "arg3", FILTER_VALIDATE_BOOLEAN);

// as expected...
var_dump($var1);      // bool(true)
var_dump($var2);      // bool(false)
var_dump($var3);      // bool(false)

// NULL is not an expected return...
var_dump($input1);    // bool(true)
var_dump($input2);    // NULL
var_dump($input3);    // bool(false)
?>

As per the documentation, the return is limited to true XOR false unless the FILTER_NULL_ON_FAILURE flag is set, but it seems as if this flag is set automatically with the filter_input() function.

(Note: same behavior for filter_var_array() vs. filter_input_array())
Types of filters
Очищающие фильтры
Types of filters


Очищающие фильтры

Список очищающих фильтров
ID | Имя | Параметры | Флаги | Описание
FILTER_SANITIZE_EMAIL | "email" |  |  | Удаляет все символы, кроме букв, цифр и !#$%&'*+-/=?^_`{|}~@.[].
FILTER_SANITIZE_ENCODED | "encoded" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH | Кодирует строку в формат URL, при необходимости удаляет или кодирует специальные символы.
FILTER_SANITIZE_MAGIC_QUOTES | "magic_quotes" |  |  | Применяется функция addslashes().
FILTER_SANITIZE_NUMBER_FLOAT | "number_float" |  | FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC | Удаляет все символы, кроме цифр, +- и, при необходимости, .,eE.
FILTER_SANITIZE_NUMBER_INT | "number_int" |  |  | Удаляет все символы, кроме цифр и знаков плюса и минуса.
FILTER_SANITIZE_SPECIAL_CHARS | "special_chars" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_HIGH | Экранирует HTML-символы '"<>& и символы с ASCII-кодом, меньшим 32, при необходимости удаляет или кодирует остальные специальные символы.
FILTER_SANITIZE_FULL_SPECIAL_CHARS | "full_special_chars" |  | FILTER_FLAG_NO_ENCODE_QUOTES, | Эквивалентно вызову htmlspecialchars() с установленным параметром ENT_QUOTES. Кодирование кавычек может быть отключено с помощью установки флага FILTER_FLAG_NO_ENCODE_QUOTES. Аналогично htmlspecialchars(), этот фильтр принимает во внимание default_charset и, если будет обнаружена некорректная последовательность байт для данной кодировки, то вся строка будет признана негодной и и результатом будет строка нулевой длины. При использовании этого фильтра в качестве фильтра по умолчанию, ознакомьтесь с предупреждением ниже об установке флагов по умолчанию в 0.
FILTER_SANITIZE_STRING | "string" |  | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Удаляет тэги, при необходимости удаляет или кодирует специальные символы.
FILTER_SANITIZE_STRIPPED | "stripped" |  |  | Псевдоним фильтра "string".
FILTER_SANITIZE_URL | "url" |  |  | Удаляет все символы, кроме букв, цифр и $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.
FILTER_UNSAFE_RAW | "unsafe_raw" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Бездействует, при необходимости удаляет или кодирует специальные символы.

Внимание

При использовании одного из этих фильтров в качестве фильтра по умолчанию либо через ваш ini-файл, либо через конфигурацию веб-сервера, флаги по умолчанию установлены в значение FILTER_FLAG_NO_ENCODE_QUOTES. Вам необходимо явно придать параметру filter.default_flags значение 0 для наличия пустых кавычек по умолчанию. К примеру:

Пример #1 Настройка фильтра по умолчанию для работы аналогично функции htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

User Contributed Notes

scamber256 at hotmail dot de 06-Aug-2011 02:37
Just a hint I tested,

You can obtain all the chars <32 (so newline and c.return), by using not operator > !FILTER_FLAG_STRIP_LOW as the last argument.

Example:
filter_input(INPUT_GET,'test',FILTER_SANITIZE_STRING,!FILTER_FLAG_STRIP_LOW);

The filter keeps working as before removing anything else as before apart from FILTER_FLAG_STRIP_LOW.
Just filter those "bad" chars <32 manually you don't want.
Dmitry Snytkine 11-Apr-2011 04:17
Beware that FILTER_FLAG_STRIP_LOW strips NEWLINE and TAG and CARRIAGE RETURN chars. If you have a form that accepts user input in plaintext format, all the submitted text will lose all the line breaks, making it appear all on one line. This basically renders this filter useless for parsing user-submitted text, even in plain text.
marcus at synchromedia dot co dot uk 27-Nov-2009 01:07
It's not entirely clear what the LOW and HIGH ranges are. LOW is characters below 32, HIGH is those above 127, i.e. outside the ASCII range.

<?php
$a = "\tcafé\n";
//This will remove the tab and the line break
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
//This will remove the é.
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
?>
Фильтры валидации данных
Остальные фильтры
Types of filters


Остальные фильтры

Список различных фильтров
ID | Имя | Параметры | Флаги | Описание
FILTER_CALLBACK | "callback" | Функция или метод типа callable |  | Вызывается пользовательская функция для фильтрации данных.

User Contributed Notes

There are no user contributed notes for this page.
Очищающие фильтры
Флаги, используемые в фильтрах
Types of filters


Флаги, используемые в фильтрах

Список используемых флагов в фильтрах
ID | Используется совместно с фильтром | Описание
FILTER_FLAG_STRIP_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Удаляет символы, код которых <32.
FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Удаляет символы, код которых >127.
FILTER_FLAG_ALLOW_FRACTION | FILTER_SANITIZE_NUMBER_FLOAT | Разрешает наличие точки (.) в качестве десятичного разделителя в числах.
FILTER_FLAG_ALLOW_THOUSAND | FILTER_SANITIZE_NUMBER_FLOAT, FILTER_VALIDATE_FLOAT | Разрешает наличие запятой (,) в качестве разделителя тысяч в числах.
FILTER_FLAG_ALLOW_SCIENTIFIC | FILTER_SANITIZE_NUMBER_FLOAT | Разрешает наличие e и E для научных нотаций чисел.
FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_SANITIZE_STRING | При установке этого флага одиночные (') и двойные (") кавычки кодироваться не будут.
FILTER_FLAG_ENCODE_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Кодирует все символы, код которых <32.
FILTER_FLAG_ENCODE_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Кодирует все символы, код которых >127.
FILTER_FLAG_ENCODE_AMP | FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Кодирует амперсанд (&).
FILTER_NULL_ON_FAILURE | FILTER_VALIDATE_BOOLEAN | Возвращает NULL для неопознанных булевых значений.
FILTER_FLAG_ALLOW_OCTAL | FILTER_VALIDATE_INT | Трактует ввод, начинающийся с нуля (0) как восьмеричное число. Для этого последующие числа должны быть в диапазоне 0-7.
FILTER_FLAG_ALLOW_HEX | FILTER_VALIDATE_INT | Трактует ввод, начинающийся с 0x или 0X как шестнадцатеричное число. Для этого последующие символы должны быть в диапазоне a-fA-F0-9.
FILTER_FLAG_IPV4 | FILTER_VALIDATE_IP | Разрешает формат IPv4 для IP-адреса.
FILTER_FLAG_IPV6 | FILTER_VALIDATE_IP | Разрешает формат IPv6 для IP-адреса.
FILTER_FLAG_NO_PRIV_RANGE | FILTER_VALIDATE_IP | Запрещает успешное прохождение проверки для следующих частных IPv4-диапазонов: 10.0.0.0/8, 172.16.0.0/12 и 192.168.0.0/16. Запрещает успешное прохождение проверки для IPv6-адресов, начинающихся с FD или FC.
FILTER_FLAG_NO_RES_RANGE | FILTER_VALIDATE_IP | Запрещает успешное прохождение проверки для следующих зарезервированных IPv4-диапазонов: 0.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24 и 224.0.0.0/4. Данный флаг не применяется к IPv6-адресам.
FILTER_FLAG_PATH_REQUIRED | FILTER_VALIDATE_URL | Включает содержание пути в URL в качестве необходимого условия.
FILTER_FLAG_QUERY_REQUIRED | FILTER_VALIDATE_URL | Включает содержание строки запроса (query string) в URL в качестве необходимого условия.

User Contributed Notes

bohwaz 06-Feb-2012 12:52
Please note that FILTER_FLAG_HOST_REQUIRED and FILTER_FLAG_SCHEME_REQUIRED have disappeared. They were previously mentioned in the constants page but it seems that host and scheme are now required by default for the validate_url filter.
php dot net at ewood dot users dot cementhorizon dot com 19-Oct-2010 04:42
In order to filter on loopback addresses try this :

<?php
function FILTER_FLAG_NO_LOOPBACK_RANGE($value) {
    // Fails validation for the following loopback IPv4 range: 127.0.0.0/8
    // This flag does not apply to IPv6 addresses
    return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? $value :
        (((ip2long($value) & 0xff000000) == 0x7f000000) ? FALSE : $value);
}

$var = filter_var('127.0.0.1', FILTER_CALLBACK, array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns FALSE

$var = filter_var('74.125.19.103', FILTER_CALLBACK, array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns '74.125.19.103'

// To filter Private IP ranges and Loopback ranges
$var = filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)
    && filter_var('127.0.0.1', FILTER_CALLBACK, array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns FALSE
?>

(If someone wants to write in handling for the IPv6 loopback interface at "::1" go for it.)

-Gene Wood
Остальные фильтры
Предопределенные константы
Types of filters


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

INPUT_POST (integer)
POST переменные.
INPUT_GET (integer)
GET переменные.
INPUT_COOKIE (integer)
COOKIE переменные.
INPUT_ENV (integer)
ENV переменные.
INPUT_SERVER (integer)
SERVER переменные.
INPUT_SESSION (integer)
SESSION переменные. (еще не реализовано)
INPUT_REQUEST (integer)
REQUEST переменные. (еще не реализовано)
FILTER_FLAG_NONE (integer)
Не использовать флаги.
FILTER_REQUIRE_SCALAR (integer)
Флаг используется для указания необходимости скалярного значения в качестве входного значения.
FILTER_REQUIRE_ARRAY (integer)
Требовать массив в качестве входного значения.
FILTER_FORCE_ARRAY (integer)
Всегда возвращать массив.
FILTER_NULL_ON_FAILURE (integer)
Использовать NULL вместо FALSE в случае ошибки.
FILTER_VALIDATE_INT (integer)
Идентификатор фильтра "int".
FILTER_VALIDATE_BOOLEAN (integer)
Идентификатор фильтра "boolean".
FILTER_VALIDATE_FLOAT (integer)
Идентификатор фильтра "float".
FILTER_VALIDATE_REGEXP (integer)
Идентификатор фильтра "validate_regexp".
FILTER_VALIDATE_URL (integer)
Идентификатор фильтра "validate_url".
FILTER_VALIDATE_EMAIL (integer)
Идентификатор фильтра "validate_email".
FILTER_VALIDATE_IP (integer)
Идентификатор фильтра "validate_ip".
FILTER_DEFAULT (integer)
Идентификатор фильтра по умолчанию ("string").
FILTER_UNSAFE_RAW (integer)
Идентификатор фильтра "unsafe_raw".
FILTER_SANITIZE_STRING (integer)
Идентификатор фильтра "string".
FILTER_SANITIZE_STRIPPED (integer)
Идентификатор фильтра "stripped".
FILTER_SANITIZE_ENCODED (integer)
Идентификатор фильтра "encoded".
FILTER_SANITIZE_SPECIAL_CHARS (integer)
Идентификатор фильтра "special_chars".
FILTER_SANITIZE_EMAIL (integer)
Идентификатор фильтра "email".
FILTER_SANITIZE_URL (integer)
Идентификатор фильтра "url".
FILTER_SANITIZE_NUMBER_INT (integer)
Идентификатор фильтра "number_int".
FILTER_SANITIZE_NUMBER_FLOAT (integer)
Идентификатор фильтра "number_float".
FILTER_SANITIZE_MAGIC_QUOTES (integer)
Идентификатор фильтра "magic_quotes".
FILTER_CALLBACK (integer)
Идентификатор фильтра "callback".
FILTER_FLAG_ALLOW_OCTAL (integer)
Разрешить восьмеричную запись (0[0-7]+) в фильтре "int".
FILTER_FLAG_ALLOW_HEX (integer)
Разрешить шестнадцатиричную запись (0x[0-9a-fA-F]+) в фильтре "int".
FILTER_FLAG_STRIP_LOW (integer)
Удалять символы с ASCII кодом, меньшим 32.
FILTER_FLAG_STRIP_HIGH (integer)
Удалять символы с ASCII кодом, большим 127.
FILTER_FLAG_ENCODE_LOW (integer)
Кодировать символы с ASCII кодом, меньшим 32.
FILTER_FLAG_ENCODE_HIGH (integer)
Кодировать символы с ASCII кодом, большим 127.
FILTER_FLAG_ENCODE_AMP (integer)
Кодировать &.
FILTER_FLAG_NO_ENCODE_QUOTES (integer)
Не кодировать ' и ".
FILTER_FLAG_EMPTY_STRING_NULL (integer)
(На данный момент не используется.)
FILTER_FLAG_ALLOW_FRACTION (integer)
Разрешить дробную часть в фильтре "number_float".
FILTER_FLAG_ALLOW_THOUSAND (integer)
Разрешить разделитель (,) между группами цифр по 3 в фильтре "number_float".
FILTER_FLAG_ALLOW_SCIENTIFIC (integer)
Разрешить научную запись (e, E) в фильтре "number_float".
FILTER_FLAG_PATH_REQUIRED (integer)
Требовать наличие составляющей "путь" в фильтре "validate_url".
FILTER_FLAG_QUERY_REQUIRED (integer)
Требовать наличие строки запроса в фильтре "validate_url".
FILTER_FLAG_IPV4 (integer)
Разрешить только IPv4 адреса в фильтре "validate_ip".
FILTER_FLAG_IPV6 (integer)
Разрешить только IPv6 адреса в фильтре "validate_ip".
FILTER_FLAG_NO_RES_RANGE (integer)
Запретить зарезервированные адреса в фильтре "validate_ip".
FILTER_FLAG_NO_PRIV_RANGE (integer)
Запретить частные адреса в фильтре "validate_ip".

User Contributed Notes

sixd at php dot net 23-Dec-2010 10:37
Rasmus added FILTER_SANITIZE_FULL_SPECIAL_CHARS to PHP 5.3.3.  See
http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3/
ext/filter/filter.c?r1=297245&r2=297244&pathrev=297245
His earlier commit to the PHP source code trunk commented that this "Added the full htmlspecialchars() functionality which includes utf-8 validation as a default filter."
Флаги, используемые в фильтрах
Примеры
Filter


Примеры

Содержание

  • Валидация
  • Нормализация значения (Sanitizing)

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Валидация
Filter


Валидация

Пример #1 Валидация e-mail адреса, используя функцию filter_var()

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "E-mail (email_a) указан верно.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "E-mail (email_b) указан верно.";
}
?>

Результат выполнения данного примера:

E-mail (email_a) указан верно.

Пример #2 Валидация IP адреса, используя функцию filter_var()

<?php
$ip_a = '127.0.0.1';
$ip_b = '42.42';

if (filter_var($ip_a, FILTER_VALIDATE_IP)) {
    echo "Адрес (ip_a) указан верно.";
}
if (filter_var($ip_b, FILTER_VALIDATE_IP)) {
    echo "Адрес (ip_b) указан верно.";
}
?>

Результат выполнения данного примера:

Адрес (ip_a) указан верно.

Пример #3 Дополнительные параметры функции filter_var()

<?php
$int_a = '1';
$int_b = '-1';
$int_c = '4';
$options = array(
    'options' => array(
                      'min_range' => 0,
                      'max_range' => 3,
                      )
);
if (filter_var($int_a, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Число (int_a) является верным (от 0 до 3).\n";
}
if (filter_var($int_b, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Число (int_b) является верным (от 0 до 3).\n";
}
if (filter_var($int_c, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Число (int_c) является верным (от 0 до 3).\n";
}

$options['options']['default'] = 1;
if (($int_c = filter_var($int_c, FILTER_VALIDATE_INT, $options)) !== FALSE) {
    echo "Число (int_c) является верным (от 0 и 3) и равно $int_c.";
}
?>

Результат выполнения данного примера:

Число (int_a) является верным (от 0 до 3).
Число (int_c) является верным (от 0 до 3).

User Contributed Notes

There are no user contributed notes for this page.
Примеры
Нормализация значения (Sanitizing)
Примеры


Нормализация значения (Sanitizing)

Пример #1 Нормализация и валидация e-mail адресов

<?php
$a = 'joe@example.org';
$b = 'bogus - at - example dot org';
$c = '(bogus@example.org)';

$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
    echo "Нормализованный e-mail (a) является верным.\n";
}

$sanitized_b = filter_var($b, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_b, FILTER_VALIDATE_EMAIL)) {
    echo "Нормализованный e-mail (b) является верным.";
} else {
    echo "Нормализованный e-mail (b) является неверным.\n";
}

$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL)) {
    echo "Нормализованный e-mail (c) является верным.\n";
    echo "До нормализации: $c\n";
    echo "После нормализации: $sanitized_c\n";
}
?>

Результат выполнения данного примера:

Нормализованный e-mail (a) является верным.
Нормализованный e-mail (b) является неверным.
Нормализованный e-mail (c) является верным.
До нормализации: (bogus@example.org)
После нормализации: bogus@example.org

Пример #2 Настройка фильтра по умолчанию

filter.default = full_special_chars
filter.default_flags = 0

User Contributed Notes

There are no user contributed notes for this page.
Валидация
Фильтрация данных
Примеры


Фильтрация данных

Содержание

  • filter_has_var — Проверяет существование переменной указанного типа
  • filter_id — Возвращает идентификатор, принадлежащий именованному фильтру
  • filter_input_array — Принимает несколько переменных извне PHP и, при необходимости, фильтрует их
  • filter_input — Принимает переменную извне PHP и, при необходимости, фильтрует ее
  • filter_list — Возвращает список всех поддерживаемых фильтров
  • filter_var_array — Принимает несколько переменных и, при необходимости, фильтрует их
  • filter_var — Фильтрует переменную с помощью определенного фильтра

User Contributed Notes

Anonymous 24-Dec-2008 09:08
--quoted from filter.txt in the source code

* As the input filter acts on input data before the magic quotes function
  mangles data, all access through the filter() function will not have any
  quotes or slashes added - it will be the pure data as send by the browser.
Jovan Suervo 26-Nov-2007 01:35
It seems that all FILTER_VALIDATE_URL is doing is calling parse_url(), which makes it effectively useless since parse_url() only fails on really malformed urls.

<?php
$url = 'http://...';

var_dump(filter_var($url, FILTER_VALIDATE_URL));
?>

Will display: string(10) "http://..."

None of the flags help either, so you're better off with regular expressions to validate a url.
fumble1 at web dot de 12-Aug-2007 10:54
I recommend you to use the FILTER_REQUIRE_SCALAR (or FILTER_REQUIRE_ARRAY) flags, since you can use array-brackets both to access string offsets and array-element -- however, not only this can lead to unexpected behaviour. Look at this example:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));
// further checks
?>

/script.php?src[0]=foobar will cause a warning. :-(
Hence my recommendation:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW));
// further checks
?>
Richard Davey rich at corephp dot co dot uk 13-Jun-2007 11:15
There is an undocumented filter flag for FILTER_VALIDATE_BOOLEAN. The documentation implies that it will return NULL if the value doesn't match the allowed true/false values. However this doesn't happen unless you give it the FILTER_NULL_ON_FAILURE flag like this:

<?php
$value = 'car';
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
?>

In the above $result will equal NULL. Without the extra flag it would equal FALSE, which isn't usually a desired result for this specific filter.
ckroll at rightmedia dot com 08-May-2007 08:02
Beware, the FILTER_SANITIZE_STRING flag functions much like strip_tags, so < will get filtered from input regardless of it's actually part of a tag.  We were getting unexepected results with a graphic library we wrote when trying to print < on a dynamic button.  The url came in something like ?string=%3C (<) but after filter ran it was empty.  To get around this, you could use FILTER_UNSAFE_RAW on that one param.
user 02-Feb-2007 12:15
Below is some code using filter API to restrict access to LAN by IPv4 private address range.

These notes may save someone else a little time:

filter_input_array() is useless for running multiple filters on the same key.
No way to chain or negate filters.

<?php

/* Merciful comment! */
function FILTER_NEGATE_HACK($_){ return (bool)!$_; }

function client_is_private_ipv4(){
  return (filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
            FILTER_NEGATE_HACK(filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE));
}

if (! client_is_private_ipv4())
  exit('This application is restricted to local network users');

?>
vojtech at x dot cz 21-Dec-2006 06:38
Also notice that filter functions are using only the original variable values passed to the script even if you change the value in super global variable ($_GET, $_POST, ...) later in the script.

<?php
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'something'
$_GET['var'] = 'changed';
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'changed'
?>

In fact, external data are duplicated in SAPI before the script is processed and filter functions don't use super globals anymore (as explained in Filter tutorial bellow, section 'How does it work?').
vojtech at x dot cz 21-Dec-2006 05:13
Just to note that "server and env support may not work in all sapi, for filter 0.11.0 or php 5.2.0" as mentioned in Filter tutorial bellow.

The workaround is obvious:
Instead of
<?php
$var = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_DEFAULT);
?>
use
<?php
$var = filter_var(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : NULL, FILTER_DEFAULT);
?>
Нормализация значения (Sanitizing)
filter_has_var
Filter


Проверяет существование переменной указанного типа

Фильтрация данных
filter_id
Фильтрация данных
PHP Manual

filter_has_var

(PHP 5 >= 5.2.0)

filter_has_var — Проверяет существование переменной указанного типа

Описание

bool filter_has_var ( int $type , string $variable_name )

Список параметров

type

Один из INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV.

variable_name

Имя проверяемой переменной.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

Anonymous 21-May-2009 02:28
To note: filter_has_var() is a bit faster than isset()
drm at melp dot nl 16-Jan-2009 01:54
Please note that the function does not check the live array, it actually checks the content received by php:

<?php
$_GET['test'] = 1;
echo filter_has_var(INPUT_GET, 'test') ? 'Yes' : 'No';
?>

would say "No", unless the parameter was actually in the querystring.

Also, if the input var is empty, it will say Yes.
Фильтрация данных
filter_id
Фильтрация данных


Возвращает идентификатор, принадлежащий именованному фильтру

filter_has_var
filter_input_array
Фильтрация данных
PHP Manual

filter_id

(PHP 5 >= 5.2.0)

filter_id — Возвращает идентификатор, принадлежащий именованному фильтру

Описание

int filter_id ( string $filtername )

Список параметров

filtername

Имя фильтра.

Возвращаемые значения

Идентификатор фильтра в случае успеха или FALSE, если фильтр не существует.

Смотрите также

  • filter_list() - Возвращает список всех поддерживаемых фильтров

User Contributed Notes

w0n4b3 at gmail dot com 23-Jun-2011 02:47
[To get a list of filters and their IDs:]

<?php
$filters = filter_list();
foreach($filters as $filter_name) {
    echo $filter_name .": ".filter_id($filter_name) ."<br>";
}
?>
Will result in:
boolean: 258
float: 259
validate_regexp: 272
validate_url: 273
validate_email: 274
validate_ip: 275
string: 513
stripped: 513
encoded: 514
special_chars: 515
unsafe_raw: 516
email: 517
url: 518
number_int: 519
number_float: 520
magic_quotes: 521
callback: 1024
filter_has_var
filter_input_array
Фильтрация данных


Принимает несколько переменных извне PHP и, при необходимости, фильтрует их

filter_id
filter_input
Фильтрация данных
PHP Manual

filter_input_array

(PHP 5 >= 5.2.0)

filter_input_array — Принимает несколько переменных извне PHP и, при необходимости, фильтрует их

Описание

mixed filter_input_array ( int $type [, mixed $definition ] )

Эта функция полезна для получения множества переменных без многократного вызова функции filter_input().

Список параметров

type

Один из INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER или INPUT_ENV.

definition

Массив, определяющий аргументы. Допустимый ключ - строка string, содержащая имя переменной, и допустимое значение - или тип filter, или массив array, при необходимости определяющий фильтр, флаги и параметры. Если значение является массивом, допустимыми ключами являются filter, который определяет (тип фильтра ), flags, который определяет любые флаги, применяемые к фильтру и options, который определяет любые параметры, применяемые к фильтру. См. пример ниже для лучшего понимания.

Этот параметр также может быть целым числом, содержащим предопределенную фильтровую константу. Затем все значения во входном массиве фильтруются этим фильтром.

Возвращаемые значения

Массив, содержащий значения запрошенных переменных в случае успеха, или FALSE в случае возникновения ошибки. Значение массива будет FALSE, если фильтрация завершилась неудачей, или NULL, если переменная не определена. Либо, если установлен флаг FILTER_NULL_ON_FAILURE, возвращается FALSE, если переменная не определена и NULL, если фильтрация завершилась неудачей.

Примеры

Пример #1 Пример использования filter_input_array()

<?php
error_reporting(E_ALL | E_STRICT);
/* данные, полученные методом POST
$_POST = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);
*/

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_REQUIRE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versions'     => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_ARRAY,
                           )

);

$myinputs = filter_input_array(INPUT_POST, $args);

var_dump($myinputs);
echo "\n";
?>

Результат выполнения данного примера:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Примечания

Замечание:

В массиве INPUT_SERVER нет ключа REQUEST_TIME, потому что он будет позднее в $_SERVER.

Смотрите также

  • filter_input() - Принимает переменную извне PHP и, при необходимости, фильтрует ее
  • filter_var_array() - Принимает несколько переменных и, при необходимости, фильтрует их
  • Types of filters

User Contributed Notes

Anonymous 22-Apr-2010 12:12
Beware: if none of the arguments is set, this function returns NULL, not an array of NULL values.

/* No POST vars set in request
$_POST = array();
*/

$args = array('some_post_var' => FILTER_VALIDATE_INT);
$myinputs = filter_input_array(INPUT_POST, $args);
var_dump($myinputs);

Expected Output: array(1) { ["some_post_var"]=> NULL }

Actual Output: NULL
ville at N0SPAM dot zydo dot com 13-Mar-2010 03:18
While filtering input arrays, be careful of what flags you set besides FILTER_REQUIRE_ARRAY. For example, setting the flags like so:

<?php
$filter = array(
'myInputArr' => array('filter' => FILTER_SANITIZE_STRING,
                      'flags' => array('FILTER_FLAG_STRIP_LOW', 'FILTER_REQUIRE_ARRAY'))
);

$form_inputs = filter_input_array(INPUT_POST, $filter);
?>

.. will result in a blank $form_inputs['myInputArr'] regardless of what $_POST['myInputArr'] contains.
kibblewhite at live dot com 26-Jan-2009 07:35
If you are trying to handling multiple form inputs with same name, then you must assign the `'flags'  => FILTER_REQUIRE_ARRAY` to the definitions entry.

Example, you have a html form as such:
<form>
 <input name="t1[]" value="Some string One" />
 <input name="t1[]" value="Another String Two" />
</form>

Your definitions array will look a little like this:
$args = array(
  't1'    => array(
      'name' => 't1',
      'filter' => FILTER_SANITIZE_STRING,
      'flags'  => FILTER_REQUIRE_ARRAY)
);
kdeloach at gmail dot com 12-Aug-2008 12:42
@iam4webwork

This is not specific to filter_input.  If you have an element in HTML called names[], it can be accessed by calling $_POST['names'].
Kevin 08-Jul-2008 06:37
Looks like filter_input_array isn't aware of changes to the input arrays that were made before calling filter_input_array. Instead, it always looks at the originally submitted input arrays.

So this will not work:

$_POST['my_float_field'] = str_replace(',','.',$_POST['my_float_field']);
$args = array('my_float_field',FILTER_VALIDATE_FLOAT);
$result = filter_input_array(INPUT_POST, $args);
phpnotes dot 20 dot zsh at spamgourmet dot com 10-Sep-2007 10:32
The above example will actually output "NULL" because of the undefined variable doesnotexist - see http://bugs.php.net/bug.php?id=42608.
Sinured 22-Aug-2007 10:10
extract() is a very convenient way of copying all those variables to the local scope. (see http://www.php.net/extract)
iam4webwork at NOSPAM dot hotmail dot com 08-Jun-2007 01:02
The above example raises other questions such as how one would validate an html array.  In the input form each input tag that refers to an html array would be named for example testarray[].  However, after the form is submitted, the syntax for validating the values is different from  the expected $_POST['testarray[]']. Instead one has to drop the braces and validate as follows, assuming that testarray[] is supposed to be an html array of numerical values:

Valid test:

echo '*';
echo filter_input(
INPUT_POST,
'testarray',
FILTER_VALIDATE_INT,
FILTER_REQUIRE_ARRAY
);
echo '*';

But the following is an invalid test that results in 2 consequtive asterisks only!

echo '*';
echo filter_input(INPUT_POST,
'testarray[]',
FILTER_VALIDATE_INT,
FILTER_REQUIRE_ARRAY
);
echo '*';

So, there is a naming inconsistency going on, as after the form is submitted, one has to forget about the original name of the submitted array by dropping its braces. Maybe when the PECL/Filter extension is reviewed again, the great ones might consider making the syntax a little more forgiving.
filter_id
filter_input
Фильтрация данных


Принимает переменную извне PHP и, при необходимости, фильтрует ее

filter_input_array
filter_list
Фильтрация данных
PHP Manual

filter_input

(PHP 5 >= 5.2.0)

filter_input — Принимает переменную извне PHP и, при необходимости, фильтрует ее

Описание

mixed filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Список параметров

type

Один из INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER или INPUT_ENV.

variable_name

Имя получаемой переменной.

filter

Идентификатор применяемого фильтра. См.список допустимых значений в Types of filters

options

Ассоциативный массив параметров либо логическое ИЛИ флагов. Если фильтр принимает параметры, флаги могут быть указаны в элементе массива "flags".

Возвращаемые значения

Значение запрашиваемой переменной в случае успеха, FALSE, если фильтрация завершилась неудачей, или NULL, если переменная variable_name не определена. Если установлен флаг FILTER_NULL_ON_FAILURE, функция возвращает FALSE, если переменная не определена и NULL, если фильтрация завершилась неудачей.

Примеры

Пример #1 Пример использования filter_input()

<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "Вы искали $search_html.\n";
echo "<a href='?search=$search_url'>Искать снова.</a>";
?>

Результатом выполнения данного примера будет что-то подобное:

Вы искали Me &#38; son.
<a href='?search=Me%20%26%20son'>Искать снова.</a>

Смотрите также

  • filter_var() - Фильтрует переменную с помощью определенного фильтра
  • filter_input_array() - Принимает несколько переменных извне PHP и, при необходимости, фильтрует их
  • filter_var_array() - Принимает несколько переменных и, при необходимости, фильтрует их
  • Types of filters

User Contributed Notes

chris at chlab dot ch 20-Mar-2012 09:46
To use a class method for a callback function, as usual, provide an array with an instance of the class and the method name.
Example:

<?php
class myValidator
{
  public function username($value)
  {
    // return username or boolean false
  }
}

$myValidator = new myValidator;
$options = array('options' => array($myValidator, 'username'));
$username = filter_input(INPUT_GET, 'username', FILTER_CALLBACK, $options);
var_dump($username);
?>
ss23 at ss23 dot geek dot nz 28-Jul-2010 11:37
Note that this function doesn't (or at least doesn't seem to) actually filter based on the current values of $_GET etc. Instead, it seems to filter based off the original values.
<?php
$_GET['search'] = 'foo'; // This has no effect on the filter_input

$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

If you need to set a default input value and filter that, use filter_var on your required input variable instead
travismowens at gmail dot com 28-Jul-2010 09:21
I wouldn't recommend people use this function to store their data in a database.  It's best not to encode data when storing it, it's better to store it raw and convert in upon the time of need.

One main reason for this is because if you have a short CHAR(16) field and the text contains encoded characters (quotes, ampersand) you can easily take a 12 character entry which obviously fits, but because of encoding it no longer fits.

Also, while not as common, if you need to use this data in another place, such as a non webpage (perhaps in a desktop app, or to a cell phone SMS or to a pager) the HTML encoded data will appear raw, and now you have to decode the data.

In summary, the best way to architect your system, is to store data as raw, and encode it only the moment you need to.  So this means in your PHP upon doing a SQL query, instead of merely doing an   echo $row['title']  you need to run htmlentities() on your echos, or better yet, an abstract function.
med dot k1987 at yahoo dot com 30-Jun-2010 07:48
Hello,
Does anybody know how to prevent FILTER_SANITIZE_SPECIAL_CHARS from converting the line breaks (\n) into (&#10;).
I'm developing a simple commenting system for my website and I found that the php filter converts \n to &#10; so when using nl2br() there are no line breaks.
help please.
thanks :)
Maksym Karazeev 03-Mar-2009 01:13
Just a tip.

Note how to setup default filter for filter_var_array

When I tried to use filter_var_array and didn't mentioned all array indexes in definition it filtered it with some filter and broke values so using this tip corrected everything

<?php
$def = array_map(create_function('', 'return array("filter"=>FILTER_UNSAFE_RAW);'), $input);
?>
Marques Johansson 02-Jan-2008 11:30
Despite the documentation for 'type', you can specify multiple types by doing:

$test = filter_input(INPUT_GET | INPUT_POST, 'test');

This was tested in 5.2.3.

When both are set it appears to return the value defined first by variables_order (php.ini).

This trick does not seem to work in filter_input_array though.  Neither function supports INPUT_REQUEST at the moment.
vid at phpcult dot com 10-Dec-2007 12:49
If you want to use the callback filter with filter_input, you need to do something like:

$args = array ('options' => 'mycallbackfunction');

$foobar = filter_input(INPUT_POST,'postedvariable',FILTER_CALLBACK,$args);
anthony dot parsons at manx dot net 23-Aug-2007 02:10
FastCGI seems to cause strange side-effects with unexpected null values when using INPUT_SERVER and INPUT_ENV with this function. You can use this code to see if it affects your server:
<?php
var_dump($_SERVER);
foreach ( array_keys($_SERVER) as $b ) {
    var_dump($b, filter_input(INPUT_SERVER, $b));
}
echo '<hr>';
var_dump($_ENV);
foreach ( array_keys($_ENV) as $b ) {
    var_dump($b, filter_input(INPUT_ENV, $b));
}
?>
If you want to be on the safe side, using the superglobal $_SERVER and $_ENV variables will always work. You can still use the filter_* functions for Get/Post/Cookie without a problem, which is the important part!
filter_input_array
filter_list
Фильтрация данных


Возвращает список всех поддерживаемых фильтров

filter_input
filter_var_array
Фильтрация данных
PHP Manual

filter_list

(PHP 5 >= 5.2.0)

filter_list — Возвращает список всех поддерживаемых фильтров

Описание

array filter_list ( void )

Возвращаемые значения

Возвращает массив имен всех поддерживаемых фильтров, пустой массив, если таких фильтров не существует. Идентификаторы (ID) фильтров не являются ключами этого массива, они могут быть получены с помощью функции filter_id() по имени фильтра.

Примеры

Пример #1 Пример использования filter_list()

<?php
print_r(filter_list());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [0] => int
    [1] => boolean
    [2] => float
    [3] => validate_regexp
    [4] => validate_url
    [5] => validate_email
    [6] => validate_ip
    [7] => string
    [8] => stripped
    [9] => encoded
    [10] => special_chars
    [11] => unsafe_raw
    [12] => email
    [13] => url
    [14] => number_int
    [15] => number_float
    [16] => magic_quotes
    [17] => callback
)

User Contributed Notes

vb dot jyoti at gmail dot com 13-Aug-2008 11:57
<?php
echo "<pre>";
print_r(filter_list());
echo "</pre>";
foreach (filter_list() as $key => $value)
{
echo "<br>".$key."=".$value.'='.filter_id($value);
}
?>

0=int=257
1=boolean=258
2=float=259
3=validate_regexp=272
4=validate_url=273
5=validate_email=274
6=validate_ip=275
7=string=513
8=stripped=513
9=encoded=514
10=special_chars=515
11=unsafe_raw=516
12=email=517
13=url=518
14=number_int=519
15=number_float=520
16=magic_quotes=521
17=callback=1024
filter_input
filter_var_array
Фильтрация данных


Принимает несколько переменных и, при необходимости, фильтрует их

filter_list
filter_var
Фильтрация данных
PHP Manual

filter_var_array

(PHP 5 >= 5.2.0)

filter_var_array — Принимает несколько переменных и, при необходимости, фильтрует их

Описание

mixed filter_var_array ( array $data [, mixed $definition ] )

Эта функция полезна для получения множества переменных без многократного вызова функции filter_var().

Список параметров

data

Массив со строковыми ключами, содержащий данные для фильтрации.

definition

Массив, определяющий параметры. Допустимый ключ - строка string, содержащая имя переменной и допустимое значение - или тип фильтра, или массив array, при необходимости определяющий фильтр, флаги и параметры. Если значение является массивом, допустимыми ключами являются filter, который определяет тип фильтра, flags, который определяет любые флаги, применяемые к фильтру, и options, который определяет любые параметры, применяемые к фильтру. См. пример ниже для лучшего понимания.

Этот параметр также может быть целым числом, содержащим предопределенную фильтровую константу. Затем все значения во входном массиве фильтруются этим фильтром.

Возвращаемые значения

Массив, содержащий значения запрошенных переменных в случае успеха, или FALSE в случае возникновения ошибки. Значение массива будет FALSE, если фильтрация завершилась неудачей, или NULL, если если переменная не определена.

Примеры

Пример #1 Пример использования filter_var_array()

<?php
error_reporting(E_ALL | E_STRICT);
$data = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_FORCE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versions'     => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_FORCE_ARRAY,
                           )

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo "\n";
?>

Результат выполнения данного примера:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Смотрите также

  • filter_input_array() - Принимает несколько переменных извне PHP и, при необходимости, фильтрует их
  • filter_var() - Фильтрует переменную с помощью определенного фильтра
  • filter_input() - Принимает переменную извне PHP и, при необходимости, фильтрует ее
  • Types of filters

User Contributed Notes

xavier 18-Aug-2010 01:37
When I run the script on my linux box (php 5.2.10) the output of "Example #1 A filter_var_array() example"
is actually:

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Notice that the values of "product_id" and "versions" are not arrays.  If you add the FILTER_FORCE_ARRAY flag to the "product_id" and "versions" filter arrays then the output returns as it is outlined in the example.
eguvenc at gmail dot com 06-Jun-2009 03:45
<?php
//an example of simply sanitize an array..

$data = array(
                '<b>bold</b>',
                '<script>javascript</script>',
                'P*}i@893746%%%p*.i.*}}|.dw<?php echo "echo works!!";?>');

$myinputs = filter_var_array($data,FILTER_SANITIZE_STRING);

var_dump($myinputs);

//OUTPUT:
//formarray(3) { [0]=> string(4) "bold" [1]=> string(10) "javascript" [2]=> string(26) "P*}i@893746%%%p*.i.*}}|.dw" }
?>
Veysel zer 08-Jun-2007 03:41
Numeric keys are not allowed in the definition array
filter_list
filter_var
Фильтрация данных


Фильтрует переменную с помощью определенного фильтра

filter_var_array
Управление функциями
Фильтрация данных
PHP Manual

filter_var

(PHP 5 >= 5.2.0)

filter_var — Фильтрует переменную с помощью определенного фильтра

Описание

mixed filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Список параметров

variable

Значение переменной для фильтрации.

filter

ID используемого фильтра. Список доступных фильтров доступен на странице "Types of filters".

options

Ассоциативный массив параметров либо логическая дизъюнкция (операция ИЛИ) флагов. Если фильтр принимает параметры, флаги могут быть указаны в элементе массива "flags". Для фильтра "callback" должен быть указан тип callable. Фильтр "callback" должен принимать один аргумент, значение для фильтрации, и возвращать значение после фильтрации.

<?php
// используйте этот формат для фильтров с дополнительными параметрами
$options = array(
    'options' => array(
        'default' => 3, // значение, возвращаемое, если фильтрация завершилась неудачей
        // другие параметры
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);
$var = filter_var('0755', FILTER_VALIDATE_INT, $options);

// для фильтра, который принимает только флаги, вы можете передать их непосредственно
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

// для фильтра, который принимает только флаги, вы так же можете передать их как массив
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
                  array('flags' => FILTER_NULL_ON_FAILURE));

// callback-фильтр валидации
function foo($value)
{
    // Ожидаемый формат: Фамилия, Имена
    if (strpos($value, ", ") === false) return false;
    list($surname, $givennames) = explode(", ", $value, 2);
    $empty = (empty($surname) || empty($givennames));
    $notstrings = (!is_string($surname) || !is_string($givennames));
    if ($empty || $notstrings) {
        return false;
    } else {
        return $value;
    }
}
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
?>

Возвращаемые значения

Возвращает отфильтрованные данные или FALSE, если фильтрация завершилась неудачей.

Примеры

Пример #1 Пример использования filter_var()

<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>

Результат выполнения данного примера:

string(15) "bob@example.com"
bool(false)

Смотрите также

  • filter_var_array() - Принимает несколько переменных и, при необходимости, фильтрует их
  • filter_input() - Принимает переменную извне PHP и, при необходимости, фильтрует ее
  • filter_input_array() - Принимает несколько переменных извне PHP и, при необходимости, фильтрует их
  • Types of filters
  • информация о типе callback

User Contributed Notes

Andi, info at pragmamx dot org 23-May-2012 06:07
And this is also a valid url

http://example.com/"><script>alert(document.cookie)</script>
keevitaja at gmail dot com 28-Jan-2012 08:05
please note FILTER_VALIDATE_URL passes following url

http://example.ee/sdsf"f
joelhy 06-Jul-2011 02:44
For those looking for private ip checking, there it is:
<?php
 function is_private_ip($ip)
{
     return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
?>
Luke America 04-Jun-2011 06:09
And ... if you also want to handle pre-encoded multi-byte international URL's, you can include the additional code here:

<?php

// convert multi-byte international url's by stripping multi-byte chars
$uri = urldecode($uri) . ' ';
$len = mb_strlen($uri);
if ($len !== strlen($uri))
{
        $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
        $uri = mb_decode_numericentity($uri, $convmap, 'UTF-8');
}
$uri = trim($uri);

// now, process pre-encoded MBI's
$regex = '#&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);#i';
$uri_test = preg_replace($regex, '$1', htmlentities($uri, ENT_QUOTES, 'UTF-8'));
if ($uri_test != '') {$uri = $uri_test;}

?>
php at maisqi dot com 27-May-2011 07:11
FILTER_VALIDATE_URL does not support internationalized domain name (IDN). Valid or not, no domain name with Unicode chars on it will pass validation.

We can circumvent this with a home grown solutions, but C code is C code, so I've gone for the code bellow, which builds on filter_var().

<?php
$res = filter_var ($uri, FILTER_VALIDATE_URL);
if ($res) return $res;
// Check if it has unicode chars.
$l = mb_strlen ($uri);
if ($l !== strlen ($uri)) {
    // Replace wide chars by “X”.
    $s = str_repeat (' ', $l);
    for ($i = 0; $i < $l; ++$i) {
        $ch = mb_substr ($uri, $i, 1);
        $s [$i] = strlen ($ch) > 1 ? 'X' : $ch;
    }
    // Re-check now.
    $res = filter_var ($s, FILTER_VALIDATE_URL);
    if ($res) {    $uri = $res; return 1;    }
}
?>

The logic is simple. A non-ascii char is more than one byte long. We replace every one of those chars by "X" and check again.

An alternative will be to punycode the URI before calling filter_var(), but PHP lacks native support for punycode. I think my approach is effective. Please e-mail me if you think otherwise or see room for improvement.
Arvid Bergelmir 11-Jan-2010 05:18
This function will return FALSE on failure but be careful validating boolean values:

Validation failed:
<?php filter_var('abc', FILTER_VALIDATE_BOOLEAN); // bool(false) ?>

Validation correct:
<?php filter_var('0', FILTER_VALIDATE_BOOLEAN); // bool(false) ?>
drtebi at yahoo 24-Nov-2009 11:55
Notice that filter_var with FILTER_VALIDATE_EMAIL does not work if you are trying to get a String from an XML document e.g. via xpath.

I often use XML files as configuration files and use a function that returns a string from the config file via xpath. While this worked fine before 5.2.11, it doesn't anymore (and shouldn't, since it's an XML Element, not a String).

To overcome this problem, $variable can be type-casted:

<?php
$variable = fancyXmlGetFunction('from');
filter_var((String) $variable, FILTER_VALIDATE_EMAIL);
?>
suit dot 2009 at rebell dot at 07-Aug-2009 03:11
If PHP >= 5.2 is not present, you can use the regular expression of the original PHP-c-file:

http://svn.php.net/viewvc/php/php-src/trunk/ext/filter/logical_filters.c

Instead of:
<?php filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)); ?>

Just use preg_match(); with a copy of the original regular expression (found in the void "php_filter_validate_email") in logical_filters.c

in fact, this expression (and the original filter-funktion) ignores RFC 5321 (Section 4.5.3.1. Size Limits and Minimums).
tedivm at tedivm dot com 22-Jun-2009 01:28
How to pass options and flags-

<?php
$options = array();
$options['options']['min_range'] = 1;
$options['options']['max_range'] = 10;
$options['flags'] = FILTER_FLAG_ALLOW_OCTAL;
filter_var(3, FILTER_VALIDATE_INT, $options);
?>
Meska 30-Apr-2009 12:08
Just a little filter to validate IP v4 & v6
This little script display result in function of the query
<?php
$ipv6="2a01:e35:aaa4:6860:a5e7:5ba9:965e:cc93";
$ipv4="82.237.3.3";
$fake = "3342423423";
$ipv4priv = "255.255.255.255";
$ipv6priv = "::1";
echo "<pre>";
echo $ipv4;
echo "<br />";
var_dump(filter_var($ipv4,FILTER_VALIDATE_IP));
echo "<br />";
echo $ipv6;
echo "<br />";
var_dump(filter_var($ipv6,FILTER_VALIDATE_IP));
echo "<br />";
echo $fake;
echo "<br />";
var_dump(filter_var($fake,FILTER_VALIDATE_IP));
echo "<br />";
echo $ipv4priv;
echo "<br/>";
echo "FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE";
echo "<br />";
var_dump(filter_var($ipv4priv,FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE));
echo "<br />";
echo $ipv4priv;
echo "<br/>";
echo "FILTER_FLAG_NO_PRIV_RANGE";
echo "<br />";
var_dump(filter_var($ipv4priv,FILTER_FLAG_NO_PRIV_RANGE));
echo "<br />";
echo $ipv6priv;
echo "<br/>";
echo "FILTER_FLAG_NO_PRIV_RANGE";
echo "<br />";
var_dump(filter_var($ipv6priv,FILTER_FLAG_NO_PRIV_RANGE));
echo "<br />";
echo $ipv6priv;
echo "<br />";
var_dump(filter_var($ipv6priv,FILTER_VALIDATE_IP));

echo "</pre>";

?>
jon dot bertsch at ucop dot edu 24-Mar-2009 07:49
Here's an actual example of the filter syntax with a flag since there doesn't appear to be a one liner for this anywhere:

'hours' => array('filter'=>FILTER_SANITIZE_NUMBER_FLOAT, 'flags' => FILTER_FLAG_ALLOW_FRACTION, 'options'=> '.')
dyer85 at gmail dot com 03-Nov-2008 02:00
Note that when using FILTER_VALIDATE_INT along with the FILTER_FLAG_ALLOW_HEX flag, the string "2f", for example, is not validated successfully, because you must use the "0x" prefix, otherwise, it treats the data as base 10.

The range options are also smart enough to recognize when the boundaries are exceeded in different bases.

Here's an example:

<?php

$foo = '256';
$bar = '0x100';
var_dump(validate_int($foo)); // false, too large
var_dump(validate_int($bar)); // false, too large

function validate_int($input)
{
  return filter_var(
    $input,
    FILTER_VALIDATE_INT,

    // We must pass an associative array
    // to include the range check options.
    array(
      'flags'   => FILTER_FLAG_ALLOW_HEX,
      'options' => array('min_range' => 1, 'max_range' => 0xff)
    )
  );
}

?>
visseraj at gmail dot com 28-Aug-2008 10:31
Here are the other possible flags that you can use:
http://us3.php.net/manual/hu/ref.filter.php
dale dot liszka at gmail dot com 09-Jul-2008 10:15
Here is how to use multiple flags (for those who learn better by example, like me):

<?php
echo "|asdf".chr(9).chr(128)."_123|";
echo "\n";
// "bitwise conjunction" means logic OR / bitwise |
echo filter_var("|asdf".chr(9).chr(128)."_123\n|" ,FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

/*
Results:
|asdf    �_123|
|asdf_123|
*/
?>
dale dot liszka at gmail dot com 09-Jul-2008 09:54
Using the FILTER_CALLBACK requires an array to be passed as the options:

<?php
function toDash($x){
   return str_replace("_","-",$x);
}

echo filter_var("asdf_123",FILTER_CALLBACK,array("options"=>"toDash"));
// returns 'asdf-123'
?>
John 26-Jul-2007 12:35
I managed to get this to work with PHP 5.1.6 on CentOS 5 with minor difficulty.

1) Download the PECL filter package
2) Extract the tarball
3) phpize the directory
4) ./configure
5) make
6) filter-0.11.0/logical_filters.c:25:31: error: ext/pcre/php_pcre.h: No such file or directory
7) find / -name php_pcre.h
8) Make sure php-devel is installed
9) Edit filter-0.11.0/logical_filters.c and replace "ext/pcre/php_pcre.h" with the absolute path of php_pcre.h
10) make
11) make install
12) add "extension=filter.so" to php.ini
13) Restart Apache
filter_var_array
Управление функциями
Фильтрация данных


Управление функциями

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Управление функциями
    • call_user_func_array — Вызывает пользовательскую функцию с массивом параметров
    • call_user_func — Вызывает пользовательскую функцию, указанную в первом параметре
    • create_function — Создаёт анонимную (лямбда) функцию
    • forward_static_call_array — Call a static method and pass the arguments as array
    • forward_static_call — Call a static method
    • func_get_arg — Возвращает элемент из списка аргументов
    • func_get_args — Возвращает массив, содержащий аргументы функции
    • func_num_args — Возвращает количество аргументов, переданных функции
    • function_exists — Возвращает TRUE, если указанная функция определена
    • get_defined_functions — Возвращает массив всех определённых функций
    • register_shutdown_function — Регистрирует функцию, которая выполнится по завершении работы скрипта
    • register_tick_function — Регистрирует функцию для выполнения при каждом тике
    • unregister_tick_function — Удаляет функцию из списка зарегистрированных для выполнения при каждом тике

User Contributed Notes

There are no user contributed notes for this page.
filter_var
Введение
Расширения, относящиеся к переменным и типам


Введение

Эти функции позволяют различными способами решать проблемы, возникающие при работе с функциями.

User Contributed Notes

There are no user contributed notes for this page.
Управление функциями
Установка и настройка
Управление функциями


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Управление функциями


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Управление функциями
Управление функциями


Управление функциями
PHP Manual

Управление функциями

Содержание

  • call_user_func_array — Вызывает пользовательскую функцию с массивом параметров
  • call_user_func — Вызывает пользовательскую функцию, указанную в первом параметре
  • create_function — Создаёт анонимную (лямбда) функцию
  • forward_static_call_array — Call a static method and pass the arguments as array
  • forward_static_call — Call a static method
  • func_get_arg — Возвращает элемент из списка аргументов
  • func_get_args — Возвращает массив, содержащий аргументы функции
  • func_num_args — Возвращает количество аргументов, переданных функции
  • function_exists — Возвращает TRUE, если указанная функция определена
  • get_defined_functions — Возвращает массив всех определённых функций
  • register_shutdown_function — Регистрирует функцию, которая выполнится по завершении работы скрипта
  • register_tick_function — Регистрирует функцию для выполнения при каждом тике
  • unregister_tick_function — Удаляет функцию из списка зарегистрированных для выполнения при каждом тике

User Contributed Notes

php dot spamguard at pulseforce dot com 27-Jan-2009 06:31
PHP is great in how it allows you to send a variable-length argument list to a function by using the func_* functions. However, unfortunately (and this has been brought up numerous time in PHP bug reports/feature requests), it doesn't support passing arguments by reference which would have greatly simplified processing multiple variables at once by simply doing: somefunction($a, $b, $c) and having them processed, without having to do any additional assignment.

However, I've discovered a way to leverage several features of PHP and created a very good example that shows how you can process multiple variables in one fell swoop!

The usage is (with my example function/class):
"list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);"

If PHP had ACTUALLY been capable of passing variables by reference when using variable-length argument lists, that could have been reduced to:
"TextEscape::escape_multi($a, $b, $c, $d, $e);"

It's extremely close though, both in simplicity and speed. Just be VERY sure to ALWAYS have the SAME NUMBER AND ORDER of arguments on both sides of that statement.

The use of a static class was just to make the code cleaner and easier to look at. This can be applied to any functions!

Now, onto the code, enjoy the sheer brilliance and enjoy modifying multiple variables at once in just ONE statement! ;-)

<?php

class TextEscape
{
    public static function escape_string($sString)
    {
        /* can be anything, using htmlspecialchars() in this example */
        return htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        foreach ($aVariables as $iKey => $sValue)
        {
            $aVariables[$iKey] = TextEscape::escape_string($sValue);
        }

        /* return the escaped values */
        return $aVariables;
    }
}

// Create test variables
$a = "A<bar";
$b = "B>bar";
$c = "C<bar";
$d = "D>bar";
$e = "E<bar";

// Variables Before:
// Array
// (
//    [0] => A<bar
//    [1] => B>bar
//    [2] => C<bar
//    [3] => D>bar
//    [4] => E<bar
// )
print_r(array($a, $b, $c, $d, $e));

// Process every variable at once,
// we're exploiting both how list() and
// variable-length argument lists work
// to make the usage this smooth! ;-)
list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);

// Variables After:
// Array
// (
//    [0] => A&lt;bar
//    [1] => B&gt;bar
//    [2] => C&lt;bar
//    [3] => D&gt;bar
//    [4] => E&lt;bar
// )
print_r(array($a, $b, $c, $d, $e));

?>

That's the CLEAN LOOKING version of the code, which illustrates exactly what is HAPPENING.

I also made a speedfreak edition of the function, but didn't want to post it as the main example since it's harder to read.

But it's faster, much faster! It passes by reference where it can and loops in a more efficient way.

Just replace the above function with this one, the outcome is the same but the speed is better:

<?php

class TextEscape
{
    public static function escape_string(&$sString) // CHANGED: we now pass by reference to the actual text processing function
    {
        /* can be anything, using htmlspecialchars() in this example */
        $sString = htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        for ($i=(count($aVariables)-1); $i>=0; $i--) // CHANGED: a more efficient for-loop is used instead of a foreach; and for anyone wondering about the counter declaration, this is a common optimization trick which makes it so that the size of the array only has to be checked ONCE, by initializing the counter to the index of the last element (which is size of array minus 1) and then iterating downwards until we reach 0 (the first element)
        {
            TextEscape::escape_string($aVariables[$i]); // CHANGED: this has been changed to modify the variable by reference instead
        }

        /* return the escaped values */
        return $aVariables;
    }
}

?>

Enjoy!
Michael T. McGrew 12-May-2005 09:56
An interesting way to use functions is by putting other things than PHP in them, i.e. HTML CSS. This can be useful if you will be using a format for many pages. Yes, the include function can be used also, but by defining them in functions can make them more portable in a way and keep you from having to make many include files. You could use include() when one will be putting big portions of PHP, HTML, and/or CSS and will be using them in many pages. Then you could use PHP, HTML, and/or CSS in a function when it is smaller portions of code and only want it to be on a few pages.

I have been using include() for HTML and CSS in my early days of PHP coding, but I will be using functions for that a lot more now.

<?php function a() {  ?>
<style type="text/css">
table {
border: 1px dashed black;
background: #95EAFE;
text-align:left;
width:610px;
}
.linkbar {
font-family:sans-serif;
line-height:40px;
top:1px;
text-align:center;
width:200px;
height:10px;
}
</style>
<?php }  ?>

Now doing:
<?php a(); ?>
will return all of the CSS just as if you had wrote it on the actual page, or used include() . The same thing goes for HTML code inside a function. The possibilities are endless...
michael dot bommarito at gmail dot com 30-Jan-2005 11:28
I've developed an easy-to-use hack using these functions to emulate overloaded functions.  It's especially handy for constructors and/or C++ style templating.

Here's a little example to get you going.  This does the trick for most circumstances, and if you need more intelligent parsing, it's not too hard to implement with regex or a more suitable classification scheme.

N.B. Note the lack of whitespace between variable types in case strings.

class Matrix {

...

function Matrix() {
  $args = func_get_args();
  $argmatch = implode(",", array_map('gettype', $args));

  switch( $argmatch ) {
    case 'integer,integer':
      //initialize m x n matrix
      break;

    case 'integer,integer,integer':
      //initialize m x n matrix with constant c
      break;

    case 'integer,integer,float':
      //initialize m x n matrix with constant c
      break;

    case 'array':
      //initialize from array (2D....)
      break;

    case 'array,integer':
      //intialize from array (1D packed with m rows)
      break;

    default:
      //(void) overload?
      //error handling?
      break;
  }
}

...

}
php-note-2003-june-18 at ryandesign dot com 18-Jun-2003 08:22
Xavier's example is rather complicated, and his task would be much more simply accomplished by using classes. Define a base class to do the basic functions open, dump, and close, and create extension classes to override whatever behavior.

class foo {
  function open() {
    // Default functionality for open()
  }
  function dump() {
    // Default functionality for dump()
  }
  function close() {
    // Default functionality for close()
  }
}

class bar extends foo {
  function open() {
    // Override functionality of open()
  }
  // dump() and close() remain as in class foo
}
xmontero at dsitelecom dot com 23-Aug-2002 02:49
You can do some kind of overloading functions in PHP using "function_exists".

Let's suppose you want a script to call plugins that are php files and you want the plugins to "override" behaviours that if not overriden are used by default.

You might for example write a "mySQL table viewer" which displays a table and it "opens a table", "dumps the header", "dumps row-by-row" and then "closes the table".

Let's suppose you want a plugin for "Stocks" which prints negative stocks in red, so you want to override the "dumping row-by-row" to do that behaviour. Instead you do not want to have all the "default behaviour" repeated in the plugin.

You may then do the following:

1) Define a default plugin (ex: "default.php"

2) Write all your functions in default.php to open, dump and close, but add them a suffix:

open_table_default()
dump_header_default()
dump_row_default()
close_table_default()

3) Call your functions with a wrapper: Insetad of this:
open_table() or open_table_default() write this:

plugincall("open_table");

4) Then write a function called plugincall which uses function_exists() to see if you call one or the other function:

function plugincall($desired_function_name)
{

if( function_exists( $desired_function_name))
{
    //Call the plugin
    //Note the $ before the name
    $desired_function_name()
}
else
{
  $desired_function_name = $desired_function_name . "_default";
  if( function_exists($desired_function_name))
  {
      //Call the default
      //Note the $ before the name
      $desired_function_name()
  }
  else
  {
      // Nor the plugin nor the default were defined
  }
}

So, now, if the require_once(plugin.php) contains a function called "open_table()", it will be used. Instaed, "open_table_default()" will be used.

It's not like overloading functions, but it is very useful to write scripts ampliable by other programmers: If they write a function, it is used, if not, the default is used.

See ya!
Xavier Montero.
Предопределенные константы
call_user_func_array
Управление функциями
PHP Manual


Вызывает пользовательскую функцию с массивом параметров

Управление функциями
call_user_func
Управление функциями
PHP Manual

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5)

call_user_func_array — Вызывает пользовательскую функцию с массивом параметров

Описание

mixed call_user_func_array ( callable $callback , array $param_arr )

Вызывает пользовательскую функцию callback, с параметрами из массива param_arr.

Список параметров

callback

Вызываемая функция типа callable.

param_arr

Передаваемые в функцию параметры, в виде индексированного массива.

Возвращаемые значения

Возвращает результат функции или FALSE в случае ошибки.

Список изменений

Версия | Описание
5.3.0 | Изменилась интерпретация объектно-ориентированных ключевых слов, таких как parent и self. Ранее, их вызов с помощью синтаксиса двойного двоеточия вызывал предупреждение уровня E_STRICT, так как они расценивались как статические вызовы.

Примеры

Пример #1 Использование call_user_func_array()

<?php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " got $arg and $arg2\n";
    }
}

// Вызываем функцию foobar() с 2 аргументами
call_user_func_array("foobar", array("one", "two"));

// Вызываем метод $foo->bar() с 2 аргументами
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>

Результатом выполнения данного примера будет что-то подобное:

foobar got one and two
foo::bar got three and four

Пример #2 Пример использования call_user_func_array() и имени из пространства имен

<?php

namespace Foobar;

class Foo {
    static public function test($name) {
        print "Hello {$name}!\n";
    }
}

// Начиная с версии PHP 5.3.0
call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'));

// Начиная с версии PHP 5.3.0
call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));

?>

Результатом выполнения данного примера будет что-то подобное:

Hello Hannes!
Hello Philip!

Пример #3 Использование lambda-функции

<?php

$func = function($arg1, $arg2) {
    return $arg1 * $arg2;
};

var_dump(call_user_func_array($func, array(2, 4))); /* Начиная с версии PHP 5.3.0 */

?>

Результат выполнения данного примера:

int(8)

Примечания

Замечание:

Переменные-ссылки в param_arr передаются в функцию по ссылке, вне зависимости от того, ожидает ли функция передачу соответствующего параметра по ссылке или нет. Эта форма "динамической" передачи по ссылке не выводит замечания об устаревшем поведении, но тем не менее считается устаревшей, и, скорее всего, будет удалена в следующей версии PHP. Далее, это не влияет на встроенные функции, у которых учитывается сигнатура функции. Передача по значению параметра функции, при ожидаемой передачи по ссылке, вызовет предупреждение и заставит call_user_func() вернуть FALSE (за исключением если переданное значение имеет количество ссылок (reference count) равное 1).

Замечание:

Callback-функции, зарегистрированные такими функциями как call_user_func() и call_user_func_array(), не будут вызваны при наличии не пойманного исключения, брошенного в предыдущей callback-функции.

Смотрите также

  • call_user_func() - Вызывает пользовательскую функцию, указанную в первом параметре
  • информация о типе callback
  • ReflectionFunction::invokeArgs() - Вызов функции с передачей аргументов
  • ReflectionMethod::invokeArgs() - Вызов метода с передачей аргументов массивом

User Contributed Notes

tracid2008 AT googlemail.com 22-Mar-2011 02:42
I think a better solution is to use ReflectionClass instead of call_user_func_array:

<?php
$rc = new ReflectionClass('SomeClass');
$class = $rc->newInstanceArgs(array('foo', 'bar'));

echo $class->doSomething();
?>
gaojingjing2008 at gmail dot com 14-Jan-2011 01:28
in PHP 5.2.* when pass string to $param_arr, there will not be warning, but in PHP 5.3, there was a warning
Brad Proctor 06-Nov-2010 09:07
This function is relatively slow (as of PHP 5.3.3) and if you are calling a method with a known number of parameters it is much faster to call it this way:

$class->{$method}($param1, $param2);

vs

call_user_func_array (array($class, $method), array($param1, $param2));

But if you don't know how many parameters...

The wrapper function below is slightly faster, but the problem now is that you are making two function calls.  One to the wrapper and one to the function.

However, If you are able to take this code out of the function and use it inline it is nearly twice as fast (in most cases) as calling call_user_func_array natively.

<?php
function wrap_call_user_func_array($c, $a, $p) {
    switch(count($p)) {
        case 0: $c->{$a}(); break;
        case 1: $c->{$a}($p[0]); break;
        case 2: $c->{$a}($p[0], $p[1]); break;
        case 3: $c->{$a}($p[0], $p[1], $p[2]); break;
        case 4: $c->{$a}($p[0], $p[1], $p[2], $p[3]); break;
        case 5: $c->{$a}($p[0], $p[1], $p[2], $p[3], $p[4]); break;
        default: call_user_func_array(array($c, $a), $p);  break;
    }
}
?>
orestes at orestescarracedo dot com 05-Nov-2010 01:24
It's not commented above:

This function behaves as call_user_func. To call a method of a class instace, instead of passing the function name as the first argument, pass an array like ($classInstance, 'methodName')

<?php
public class Person {
    private $name = null;
    private $pocketContents= null;

    protected function __construct() {
        $this->name = 'My creator was too lazy to name me';
    }
    public function getName() {
        return $this->name;
    }
    public function setName($name) {
        $this->name = $name;
    }
    public function getPocketContents() {
        return $this->$pocketContents;
    }
    public function setPocketContents() {
        $args = func_get_args();
        $this->$pocketContents = $args;
    }
}

$contents = array();
$contents[0] = 'random';
$contents['foo'] = 'bar';

$subobject = array();
$subobject['param'] = 'value';
$contents['subobject'] = $subobject;

call_user_func(($myInstance, 'setPocketContents'), $contents);
?>
hinom06 [at] hotmail.co.jp 14-Sep-2010 09:27
<?php

/*
Usage sample to apply any filter in a string.
*/

class Strings
{
    function Foo( $v, $allow = '' )
    {
        return strip_tags( $v, $allow );
    }

    // add an element at the beginning of an array
    // thanks for Vidal Rodríguez
    // http://www.php.net/manual/en/function.array-push.php#98299
    function ArrayRpush( $arr, $item )
    {
      return array_pad( $arr, -( count( $arr ) + 1 ), $item );
    }

}

Class Functions
{

    function Call( $f )
    {
        return call_user_func_array( $f[0], $f[1] );

        /* usage sample:
            //
            // calling function
            Functions::Call( 'strip_tags', array( '<br>foo<br>bar</b>', '<br><b>' ) );

            // calling object
            Functions::Call( array( 'Strings', 'StripTags' ), array( '<br>foo<br>bar</b>', '<br><b>' ) );
        */
    }

}

$form = array(
            'field' => array(
                            'value'         => '<b>foo bar</b><br><script>alert("1");</script>',
                            'pre-filter'    => array( array( 'Strings', 'Foo' ) , array( '<b><br>' ) ),
                            ),
            );

$v    = $form['field'];
$f    = $v['pre-filter'];
$f[1] = isset( $v['pre-filter'][1] ) ? Strings::ArrayRpush( $f[1], $v['value'] ) : $f[1] = array( $v['value'] );

echo Functions::Call( $f );

?>
Kris dot Craig at gmail dot com 16-Jun-2010 03:28
Many people have wondered how to effectively implement dispatch tables in PHP.  Here's my answer to that (if you'll forgive my creative flair):

<?php

/*
 * Using dispatch tables in PHP.
 *
 * --Kris Craig
 */

define( "YOUR_MOTHER",  1 );
define( "YOUR_FATHER",  2 );
define( "YOUR_BROTHER", 3 );
define( "YOUR_SISTER",  4 );

class MyFamily
{
    static $dispatch = array( YOUR_MOTHER => "Mom", YOUR_FATHER => "GetPrisonInmate", YOUR_BROTHER => "ReplaceName", YOUR_SISTER => "LazyGirl" );
    static $args = array( YOUR_MOTHER => array(), YOUR_FATHER => array( "55170-054", TRUE ), YOUR_BROTHER => array(), YOUR_SISTER => array() );

    function GetDispatch( $fromwhere )
    {
        return call_user_func_array( array( self, self::$dispatch[$fromwhere] ), self::$args[$fromwhere] );
    }

    function Mom()
    {
        return "Mommy loves you!";
    }

    function GetPrisonInmate( $PrisonerID, $GoodBehavior )
    {
        //Check prison records for his ID, then....

        if ( $GoodBehavior )
        {
            $parole = "APPROVED";
        }
        else
        {
            $parole = "DENIED";
        }

        return "Your father (#$PrisonerID) has $remaining years left in his sentence.  His most recent parole application has been:  $parole";
    }

    function ReplaceName()
    {
        return "Her name is Sally now.";
    }

    function LazyGirl()
    {
        print "Your sister needs to get out more....";

        //sleep( pow( 60, 2 ) * 18 );  //You can sleep later!

        die( "Nah, I'm too tired." );
    }
}

print "Status on family member: " . MyFamily::GetDispatch( YOUR_FATHER );

?>
noone at example dot com 21-Apr-2010 03:03
For those of you that have to consider performance: it takes about 3 times as long to call the function this way than via a straight statement, so whenever it is feasible to avoid this method it's a wise idea to do so.

Note that eval() is about 10 times slower than a straight statement to call a function with arguments, so this is definitely a better option than using eval() even if you only consider performance.
Guy Paddock 15-Apr-2010 02:14
It appears that it is safe to pass an associative array in for $param_arr. The parameters will still be passed in the order the elements appear in the array, not alphabetical key order.
kweejee at gmail dot com 22-Jan-2010 08:04
I recently had
<?php
  call_user_func_array('MyClass::myFunction', array(0, 10));
?>
working on my home server, but when I uploaded it to a host with a different version of PHP it stopped working and gave the error message "call_user_func_array() [function.call-user-func-array]: Unable to call MyClass::myFunction()" The solution I found was to use this instead:
<?php
  call_user_func_array(array('MyClass', 'myFunction'), array(0, 10));
?>
aj at ajbrown dot org 22-Dec-2009 07:30
Just a heads up, the second parameter MUST be an array if it's specified,  but that doesn't seem to be enforced until ~5.3.

I just pulled my hair out with an old installation of CakePHP because it was passing NULL instead of an empty array.
mrextreme at freemail dot hu 07-Dec-2009 08:34
If you are using PHP < 5.3 and want to call the parent class' __construct() with a variable parameter list, use this:

<?php
public function __construct()
{
    $vArgs = func_get_args(); // you can't just put func_get_args() into a function as a parameter
    call_user_func_array(array('parent', '__construct'), $vArgs);
}
?>
dmitry dot revenko at businessmedia dot ru 25-Sep-2009 05:28
Just hope this note helps someone (I killed the whole day on issue).

If you use something like this in PHP < 5.3:
<?php call_user_func_array(array($this, 'parent::func'), $args); ?>
Such a script will cause segmentation fault in your webserver.

In 5.3 you should write it:
<?php call_user_func_array('parent::func', $args); ?>
al dot james at NOSPAMGMAIL dot com 17-Jun-2009 03:19
If you want to use call_user_func_array to call an objects constructor, this works for me:

<?php
$obj = new $object_class();
call_user_func_array(array($obj, '__construct'), $args);
?>

(However it does depend on having a constructor where all arguments are optional, which may or may not be possible)

So this is a two part initiation, the object gets initiated with no arguments first (hence requiring options constructor params), and then __construct gets called again. Thus, you should not do anything in your constructor that triggers effects outside the class... it should just set the objects state.
Damin 13-Jun-2009 12:06
Those having the passing by reference issue can use this simple hack.
I´m really not sure WHY this works, but it does, and it does not make use of EVAL or other questionable functions.
<?php
    function executeHook($name, $type='hooks'){
        $args = func_get_args();
        array_shift($args);
        array_shift($args);
        //Rather stupid Hack for the call_user_func_array();
        $Args = array();
        foreach($args as $k => &$arg){
            $Args[$k] = &$arg;
        }
        //End Hack
        $hooks = &$this->$type;
        if(!isset($hooks[$name])) return false;
        $hook = $hooks[$name];
        call_user_func_array($hook, $Args);
    }
?>

All it´s doing is copying the args ($args) into a new array ($Args) by reference, which i would think would be identical to the original array in every way (that matters).

Note the code here is an example of usage. The actual hack is denoted by comments.
If someone knows a better alternative, by all means, i would love to see it.
Freek (at) Gruntjes.net 07-Apr-2009 01:53
I just noticed that when you use this function with parameters that need to be passed by reference it will not work.

<?php
function refFunc(&$var)
{
  $var .= 'bar';
}

$var = 'foo';
?>

call_user_func_array('refFunc', array($var));
echo $var;

will output 'foo' and not  'foobar'. Witch is logical since you are declaring a new variable with array($var) however not so obvious.
thiago dot henrique dot mata at gmail dot com 22-Jul-2008 02:17
<?php
Class Delegate
{
    private $arrInstances = array();

    protected function addObject( $oElement )
    {
        // add one element on the end of the stack  //
        $this->arrInstances[] = $oElement;
    }

    public function __call( $strMethod, $arrParams )
    {
        // for each element in instance //
        foreach( $this->arrInstances as $oElement )
        {
            // get the class of the element //
            $strClass = get_class( $oElement );
            // get all methods of the class  //
            $arrMethods = get_class_methods( $strClass );
            // case the method exists into this class  //
            if( in_array( $strMethod , $arrMethods ) )
            {
                // prepare caller //
                $arrCaller = Array( $strClass , $strMethod );
                // return the result of the method into the object  //
                return call_user_func_array( $arrCaller, $arrParams );
            }
        }
        // any object has the method //
        // throw a exception //
        throw new Exception( " Method " . $strMethod . " not exist in this class " . get_class( $this ) . "." );
    }
}

class Log
{
    public function sayHi()
    {
        print "hi!" . "<br/>\n";
    }

    public function sayMyName()
    {
        print "log" . "<br/>\n";
    }
}

class Other
{
    public function sayHello()
    {
        print "hello there!" . "<br/>\n";
    }

    public function sayMyName()
    {
        print "other" . "<br/>\n";
    }
}

class Example extends Delegate
{
    public function __construct()
    {
        $this->addObject( new Log() );
        $this->addObject( new Other() );
    }
}

$oExample = new Example();
$oExample->sayHi();
$oExample->sayHello();
$oExample->sayMyName();

/*
    hi!<br/>
    hello there!<br/>
    log<br/>
*/
?>
dnhuff at acm.org 07-Jun-2008 11:57
It appears that when PHP executes something like:

$a = array(1,2,3);
$b =& $a[1];

both $b and $a[1] are converted into references to a common value -- makes sense until you transfer that to a call_user_func:

call_user_func_array('foo', $a);

suddenly, inside foo, the second parameter is passed by reference!

And you can't call this wrong, only another subtly of references.

Note it appears that ksort($a) will remove the reference as well as put the elements in key order so you (probably) get what you expect. (see below on the use of a foreach ($a as &v).)
dnhuff at acm.org 07-Jun-2008 11:38
the order of argument correspondence from the array to the function formal parameters is by 'natural order' of the array and not explicit numerical key order.

So: $a[0] = 'arg 1'; $a[2] = 'arg 2'; $a[1] = 'arg 3';
    call_user_func_array('foo', $a);

delivers the args to foo in the order the keys were inserted! as in...
    foo($a[0], $a[2], $a[1]);

if you wanted something else, ksort the array first.
aeolianmeson at 8n54tvv dot blitzeclipse dot com 27-May-2008 08:48
There's a possibility that call_user_func_array(), call_user_func(), and Exception::getTrace() will cause a trace entry to not have the 'file' or 'line' elements.

Dustin Oprea
richard_harrison at rjharrison dot org 11-Apr-2007 02:31
If you are thinking of using call_user_func_array to instantiate an object (see comments below using Reflection) then since v5.1.3 you can use the Reflection::newInstanceArgs() method.

<?php

// arguments you wish to pass to constructor of new object
$args = array('a', 'b');

// class name of new object
$className = 'myCommand';

// make a reflection object
$reflectionObj = new ReflectionClass($className);

// use Reflection to create a new instance, using the $args
$command = $reflectionObj->newInstanceArgs($args);

// this is the same as: new myCommand('a', 'b');
?>
levi at alliancesoftware dot com dot au 08-Feb-2007 02:50
Regarding the comments below about calling parent constructors:

PHP5 with E_STRICT no longer allows calls as below:

<?php
// Causes an error with E_STRICT
call_user_func_array(array('parent', '__construct'), $args);
?>

It gives an error because you are trying to call a nonstatic function as if it was static. The correct syntax is

<?php
// Works fine
call_user_func_array(array($this, 'parent::__construct'), $args);
?>
15-May-2006 02:43
For those wishing to implement call-by-name functionality in PHP, such as implemented e.g. in DB apis, here's a quick-n-dirty version for PHP 5 and up
<?php
/**
 * Call a user function using named instead of positional parameters.
 * If some of the named parameters are not present in the original function, they
 * will be silently discarded.
 * Does no special processing for call-by-ref functions...
 * @param string $function name of function to be called
 * @param array $params array containing parameters to be passed to the function using their name (ie array key)
 */
function call_user_func_named($function, $params)
{
    // make sure we do not throw exception if function not found: raise error instead...
    // (oh boy, we do like php 4 better than 5, don't we...)
    if (!function_exists($function))
    {
        trigger_error('call to unexisting function '.$function, E_USER_ERROR);
        return NULL;
    }
    $reflect = new ReflectionFunction($function);
    $real_params = array();
    foreach ($reflect->getParameters() as $i => $param)
    {
        $pname = $param->getName();
        if ($param->isPassedByReference())
        {
            /// @todo shall we raise some warning?
        }
        if (array_key_exists($pname, $params))
        {
            $real_params[] = $params[$pname];
        }
        else if ($param->isDefaultValueAvailable()) {
            $real_params[] = $param->getDefaultValue();
        }
        else
        {
            // missing required parameter: mark an error and exit
            //return new Exception('call to '.$function.' missing parameter nr. '.$i+1);
            trigger_error(sprintf('call to %s missing parameter nr. %d', $function, $i+1), E_USER_ERROR);
            return NULL;
        }
    }
    return call_user_func_array($function, $real_params);
}
?>
eugene at artprime dot ru 23-Dec-2005 02:59
<?php
  return call_user_func_array(
    array(new ReflectionClass($className), 'newInstance'),
    $functionParameters
  );
?>

Look here: http://www.zend.com/zend/week/week182.php#Heading1
crocodile2u at yandex dot ru 20-Dec-2005 05:06
Here is another version of createObjArray() function written here earlier by taylor.

Believing that using 'eval()' is at least "dirty", I came to the following solution (with a help of panchous - at phpclub dot ru forums ). This solution utilizes the new Reflection API.

<?php
function & createObjArray($type, $args = array()) {
    $reflection = new ReflectionClass($type);
    $output     = call_user_func_array(array(&$reflection, 'newInstance'), $args);
    return $output;
}
?>
Egor 15-Nov-2005 09:35
Note that, despite the name, this does work on builtin functions (and object methods with the array(&$obj, $method) syntax), not just user-defined functions and methods.
rrant (at) gmail (dot) com 10-Nov-2005 03:50
Just an extra for the post of amer at o2 dot pl:

If you need to call the PARENT method:
call_user_func_array(array('parent', 'method'), $args);

With that, if you need to call a constructor and/or add some extra code to the instantiation process:

<?php
function __construct() {
    // Get the arguments
    $args = func_get_args();
    // Initialize parent with arguments
    call_user_func_array(array('parent', '__construct'), $args);
    // ... Your Code Here ...
}
?>

Note that your constructor pass all the arguments to the parent constructor and it doesn't matter how many arguments you pass.

This is pretty useful for constructors with a variable number of arguments.
taylor 02-Jun-2005 05:51
I came up with a better solution to the problem that I solve below with createObjArray that maintains parameter type:

<?php

function createObjArray($type,$args=array()) {
     $paramstr = '';
     for ($i = 0; $i < count($args); $i++) {
           $paramstr .= '$args['.$i.'],';
     }
     $paramstr = rtrim($paramstr,',');

     return eval("return new $type($paramstr);");
}

?>

Would be good to add error checking, but it works.
taylor 07-May-2005 03:04
<?php
    /**
     * Create an object of a specified type using an array as the parameters
     * to the constructor.  NOTE: does not maintain proper
     * types for the arguments.  They are all converted to strings.
     * @param $type Type type of object to create (class name)
     * @param $args The arguments to pass to the constructor
     */
    function createObjArray($type, $args=array()) {
        if ( !class_exists($type) ) {
            return NULL;
        }

        // build argument list; be sure to escape string delimeters
        $func = create_function('$str', 'return str_replace("\'","\\\'",$str);');
        $sargs = "'" . join( "','", array_map($func,$args) ). "'";

        // build & eval code; return result
        $seval = "return new $type($sargs);";
        return eval($seval);
    }
?>
amer at o2 dot pl 20-Jan-2005 02:44
PLS notice that "patripaq at hotmail dot com" 's code will be valid if B EXTENDS A...
<?php
class B extends A{
...
}
?>
there>>"What I wanted to do is create an object that can manage any number and any kind of parameters."

BUT IT IS NOT A POINT AT ALL

If you need to call just function with parameters:
call_user_func_array('Foo',$args);

If you need to call CLASS method (NOT object):
call_user_func_array(array('class', 'Foo'),$args);

If you need to call OBJECT method:
call_user_func_array(array(&$Object, 'Foo'),$args);

If you need to call method of object of object:
call_user_func_array(array(&$Object->Object, 'Foo'),$args);

If you need to call object method from within the very same object (NOT CLASS!):
call_user_func_array(array(&$this, 'Foo'),args);

The call_user_func_array ITSELF can manage any number and any kind of parameters. It can handle ANY FUNCTION too as it is defined and that maybe partipaq wanted to manage.

What You actually need is object composition not inheritance. Make an instance from arguments.
<?php
...
class B{
   function __construct() {
      $args = func_get_args(); // Get arguments
      $this->OBJ = new A($args);
      call_user_func_array(array(&$this->OBJ, 'A'), $args );
   }
}
?>
Then there can be any number and any type of created object B parameters
james at gogo dot co dot nz 21-Nov-2004 05:19
Be aware the call_user_func_array always returns by value, as demonstrated here...

<?php
    function &foo(&$a)
    {
      return $a;
    }

    $b = 2;
    $c =& call_user_func_array('foo', array(&$b));
    $c++;
    echo $b . ' ' . $c;
?>

outputs "2 3", rather than the expected "3 3".

Here is a function you can use in place of call_user_func_array which returns a reference to the result of the function call.

<?php
    function &ref_call_user_func_array($callable, $args)
    {
        if(is_scalar($callable))
        {
            // $callable is the name of a function
            $call = $callable;
        }
        else
        {
            if(is_object($callable[0]))
            {
                // $callable is an object and a method name
                $call = "\$callable[0]->{$callable[1]}";
            }
            else
            {
                // $callable is a class name and a static method
                $call = "{$callable[0]}::{$callable[1]}";
            }
        }

        // Note because the keys in $args might be strings
        // we do this in a slightly round about way.
        $argumentString = array();
        $argumentKeys = array_keys($args);
        foreach($argumentKeys as $argK)
        {
            $argumentString[] = "\$args[$argumentKeys[$argK]]";
        }
        $argumentString = implode($argumentString, ', ');
        // Note also that eval doesn't return references, so we
        // work around it in this way...
        eval("\$result =& {$call}({$argumentString});");
        return $result;
    }
?>
php at pjt33 dot f2g dot net 25-Oct-2004 05:31
Note that, although it doesn't say so here or in the linked page with information about the callback type, the changelog ( http://www.php.net/ChangeLog-4.php#4.0.5 ) states that call_user_func_array in PHP 4.0.4 won't take an array as the first argument. This was added in 4.0.5.
patripaq at hotmail dot com 06-Aug-2004 03:49
I just started using PHP 5.0 and, so far, I'm loving it !  However, I had a problem the other day and thought it would be a good idea to inform other programmers about the solution I found to get around it.  It concerns the new __constructor() function and the call_user_func_array() function.  What I wanted to do is create an object that can manage any number and any kind of parameters.  Here's the problematic code:

<?php
//--------------------------
class A {
  function __construct() {
    $args = func_get_args(); // Get arguments
    // Class initialization...
  }
  function A() {
    $args = func_get_args(); // Get arguments
    call_user_func_array( array(&$this, '__construct'), $args ); // Infinite loop to B::__construct()...
  }
}

class B {
  function __construct() {
    $args = func_get_args(); // Get arguments
    call_user_func_array( array(&$this, 'A'), $args ); // Initialize parent with arguments
    // Class initialization...
  }
}

$obj = new B( 'param1', 'param2' );
//--------------------------
?>

I suppose you can guess where the problem is located... In the A::A() function, the call to __construct() using call_user_func_array() is redirected to B::__construct() instead of A::__construct().  The only way I found to specify which constructor function I wanted to call was to stop using A::__construct() and use the old fashion constructor instead.  If anyone can find a better way, feel free to add comments.  Here's my solution.  Hope it helps anyone.

<?php
//--------------------------
class A {
  function A() {
    $args = func_get_args(); // Get arguments
    // Class initialization...
  }
}

class B {
  function __construct() {
    $args = func_get_args(); // Get arguments
    call_user_func_array( array(&$this, 'A'), $args ); // Initialize parent with arguments
    // Class initialization...
  }
}

$obj = new B( 'param1', 'param2' );
//--------------------------
?>
hong dot nguyen at k-edge dot com 02-Apr-2004 09:37
call_user_func_array can pass parameters as reference:

<?php
call_user_func_array(array(&$obj,$method),array(&$arg1,$arg2,$arg3))
?>

Use it as work-around for "Call-time pass-by-reference has been deprecated".
adamh at densi dot com 31-Jul-2003 11:58
call_user_func_array() is nifty for calling PHP functions which use variable argument length. For example:

<?php
$array = array(
 array("foo", "bar"),
 array("bat", "rat"),
);

$values = call_user_func_array("array_merge", $array);

var_dump($values);
?>

/* output:
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "bat"
  [3]=>
  string(3) "rat"
}
*/

The neat feature is that $array could have any number of arrays inside it.
gord at fig dot org 06-May-2003 04:30
If you need to call object and class methods in PHP < 4.0.4, the following code ought to do the trick:

<?php
if (!function_exists('call_user_func_array')) {
    function call_user_func_array($func, $args)
    {
        $argString = '';
        $comma = '';
        for ($i = 0; $i < count($args); $i ++) {
            $argString .= $comma . "\$args[$i]";
            $comma = ', ';
        }

        if (is_array($func)) {
            $obj =& $func[0];
            $meth = $func[1];
            if (is_string($func[0])) {
                eval("\$retval = $obj::\$meth($argString);");
            } else {
                eval("\$retval = \$obj->\$meth($argString);");
            }
        } else {
            eval("\$retval = \$func($argString);");
        }
        return $retval;
    }
}
?>
nutbar at innocent dot com 12-Mar-2003 12:29
This function, combined with some others, can allow you to make some really easy & generic function macros (since real macros don't exist in PHP yet).

<?php
function my_printf() {
   $args = func_get_args();
   return call_user_func_array('printf', $args);
}
?>

This allows you to use my_printf() just as if it were printf() itself.  Very useful since you don't have to worry about how many arguments any functions take.
NOSPAM dot dont dot remove at thekid dot de 22-Jun-2002 04:19
Unified constructors in PHP4:

<?php
  class Object {
    function Object() {
      $args= func_get_args();
      call_user_func_array(array(&$this, '__construct'), $args);
    }

    function __construct($args= NULL) {
      var_dump($args);
    }
  }

  class Exception extends Object {
    var
      $message;

    function __construct($message) {
      $this->message= $message;
      parent::__construct();
    }
  }

  class IOException extends Exception {
  }

  var_dump(
    error_reporting(),
    zend_version(),
    phpversion()
  );

  $c= new IOException('file not found');

  echo '===> Result: '; var_dump($c);
?>
Управление функциями
call_user_func
Управление функциями


Вызывает пользовательскую функцию, указанную в первом параметре

call_user_func_array
create_function
Управление функциями
PHP Manual

call_user_func

(PHP 4, PHP 5)

call_user_func — Вызывает пользовательскую функцию, указанную в первом параметре

Описание

mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )

Вызывает пользовательскую функцию, переданную в параметре callback.

Список параметров

callback

Вызываемая функция типа callable.

parameter

Ноль или более параметров, передаваемые в функцию.

Замечание:

Учтите, что параметры для call_user_func() не передаются по ссылке.

Пример #1 Пример использования call_user_func() с ссылками

<?php
error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

call_user_func_array('increment', array(&$a)); // Вместо этого можно использовать этот способ до PHP 5.3
echo $a."\n";
?>

Результат выполнения данного примера:

0
1

Возвращаемые значения

Возвращает результат функции, или FALSE в случае ошибки.

Список изменений

Версия | Описание
5.3.0 | Изменилась интерпретация объектно-ориентированных ключевых слов, таких как parent и self. Ранее, при их вызове с помощью синтаксиса двойного двоеточия вызывалась ошибка уровня E_STRICT, т.к. они интерпретировались как статические вызовы.

Примеры

Пример #2 Пример использования call_user_func()

<?php
function barber($type)
{
    echo "Вы хотели стрижку $type, без проблем\n";
}
call_user_func('barber', "под горшок");
call_user_func('barber', "наголо");
?>

Результат выполнения данного примера:

Вы хотели стрижку под горшок, без проблем
Вы хотели стрижку наголо, без проблем

Пример #3 Использование call_user_func() и пространства имен

<?php

namespace Foobar;

class Foo {
    static public function test() {
        print "Привет, мир!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::test'); // Начиная с версии PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // Начиная с версии PHP 5.3.0

?>

Результат выполнения данного примера:

Привет, мир!
Привет, мир!

Пример #4 Вызов метода класса из call_user_func()

<?php

class myclass {
    static function say_hello()
    {
        echo "Привет!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // Начиная с версии 5.2.3

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

?>

Результат выполнения данного примера:

Привет!
Привет!
Привет!

Пример #5 Использование лямбда-функции и call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* Начиная с версии PHP 5.3.0 */
?>

Результат выполнения данного примера:

[test]

Примечания

Замечание:

Callback-функции, зарегистрированные такими функциями как call_user_func() и call_user_func_array(), не будут вызваны при наличии не пойманного исключения, брошенного в предыдущей callback-функции.

Смотрите также

  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров
  • is_callable() - Проверяет, может ли значение переменной быть вызвано в качестве функции
  • информация о типе callback
  • ReflectionFunction::invoke() - Вызывает функцию
  • ReflectionMethod::invoke() - Вызов

User Contributed Notes

paul dot e dot s dot wormer at gmail dot com 10-Feb-2012 02:58
Example#1 (with Xamp, PHP v. 5.3.8, Windows 7) writes

Warning: Parameter 1 to increment() expected to be a reference, value given in C:\xampp\htdocs\call_user_func.php on line 9
0
1

--------
When argument of increment is by-value (remove & from &$var), warning is gone and output is
0
1
dexen dot devries at gmail dot com 04-Nov-2011 05:00
In PHP v5.2, you /can/ use call_user_func(array($this, 'parent::SOME_FUNCTION')).

If you don't have custom __autoload() function, you are good to go.

If you do have custom __autoload(), you need to make it `parent' aware. Something like:

<?php
function __autoload($classname) {
  if ($classname === 'parent')
    return;
  else
    //((load class definition))
}
?>

Rationale: PHP 5.2 surprisingly tries to autoload a class named `parent'. However, if you don't do anything in __autoload() for the `parent' class, it'll work just fine.
Gavin 23-Sep-2011 02:48
If using call_user_func() to pass resources (e.g. pipes created by proc_open), pass them using an array or object containing the resources, instead of "naked".

Bad: call_user_func($callback, $pipes[0], $pipes[1], $pipe[2]);

Good: Bad: call_user_func($callback, $pipes);

Passing the variables containing resource ids in the "bad" example above appears to work, but can cause troubles later when trying to close STDIN ($pipe[0] for example), and then read the output of the spawned child from $pipes[1].  The child process may or may not hang in read(), as reported by strace, even though the passed resources look valid, and the fclose on the stdin resource returns true.

Switching to the "good" example above solved the issue above for me.

Peace to you.
blakerenton09 at yahoo dot com 06-Jun-2011 04:45
call_user_func may also be used to call a closure or anonymous function that has been passed into a user-defined function.

<?php
function Benchmark()
{
    foreach(func_get_args() as $function)
    {
        $st = microtime(true);
        call_user_func($function);
        $et = microtime(true);
        echo sprintf("Time: %f", $et - $st) . '<br />';
    }
}

Benchmark(function()
{
    for ( $i = 0; $i <= 10000; $i++ )
    { }
},
function()
{
    $i = 0;
    while ( $i <= 10000 )
    {
        $i++;
    }
});
?>

Returns:
Time: 0.001652
Time: 0.001458
romainbessuges at gmail dot com 09-May-2011 05:50
I made a wrapper for call_user_func_array which is really simple and convenient. It takes advantage of the __invoke() magic method :

<?php
class Func {

    public static function fromFunction($name){
        return new Func($name);
    }

    public static function fromClassMethod($class, $name){
        return new Func(array($class, $name));
    }

    public static function fromObjectMethod($object, $name){
        return new Func(array($object, $name));
    }

    public $function;

    public function  __construct($function) {
        $this->function = $function;
    }

    public function __invoke(){
        return call_user_func_array($this->function, func_get_args());
    }
}
?>

Example :

<?php
$func = Func::fromObjectMethod($myArrayObject, "offsetGet");

echo $func(3);
?>
gskluzacek dot nospam at gmail dot com 11-Sep-2010 10:38
if you simply want to dynamically call a method on an object it is not necessary to use call_user_function but instead you can do the following:

<?php

$method_name = "AMethodName";

$obj = new ClassName();

$obj->{$method_name}();

?>

I've used the above so I know it works.

Regards,
-- Greg
moisadoru at gmail dot com 13-May-2010 08:49
Actually, when calling a static method of some class, the params are sent by reference:
<?php
class Foo {
    private $x = 0;
    public function getX(){
        return $this->x;
    }
    public function setX($val){
        $this->x = $val;
    }
}

class Bar {
    static function incStatic(Foo $f){
        $f->setX($f->getX()+1);
        global $foo;
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
    public function incNonStatic(Foo $f){
        $f->setX($f->getX()+1);
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
}

function inc(Foo $f){
    $f->setX($f->getX()+1);
    if($f === $foo) echo '<span style="color: blue">' . __FUNCTION__ . '() objects are equal</span><br />';
    else  echo '<span style="color: red">' . __FUNCTION__ . '() objects are not equal</span><br />';
}

$foo = new Foo;
$bar = new Bar;

call_user_func('inc', $foo);
call_user_func('Bar::incStatic', $foo);
call_user_func(array($bar, 'incNonStatic'), $foo);
?>

The results on PHP 5.2.6 (macosx 10.5):

inc() objects are not equal
Bar::incStatic() objects are equal
Bar::incNonStatic() objects are not equal

Hope it helps sombody.
Nitrogen 04-Oct-2009 04:08
A good use for call_user_func(); is for recursive functions.
If you're distributing code, you will often come across users who will rename functions and break the code..
Use this: call_user_func(__FUNCTION__, ... ); inside a function to call itself with whatever parameters you want.

<?php
// example, an extremely simplified factorial calculator..
// it's quite obvious when someone renames the function, it'll spit out an error because it wants to call itself.
function Factorial($i=1) {
  return($i==1?1:$i*Factorial($i-1));
}

// you can give this function whatever name you want, it'll always work, of course if you initially call it using the name you gave it.
function qwertyuiop($i=1) {
  return($i==1?1:$i*call_user_func(__FUNCTION__,$i-1));
}
?>

Just that I didn't see any reference to recursive functions when user_call_func(); really helps.
edgar dot klerks at gmail dot com 17-Mar-2009 07:18
An entirely OO solution to add dynamicly methods to classes, I used in a project:
<?php
class ProductPart {

        protected $data;
        protected $plugins = array();
        function __construct($data){

                $this->data = $data;

        }
        public function register(ProductPlugin $plugin){

                if(!in_array($plugin, $this->plugins)){

                        $this->plugins[$plugin->toString()] = $plugin;
                } else {
                        throw new Exception('Function allready defined');
                }
        }
        public function unregister(ProductPlugin $plugin){
                if(isset($this->plugins[$plugin->toString()])){
                        unset($this->plugins[$plugin->toString()]);
                } else {
                        throw new Exception('No such function');
                }

        }

        protected function __call($method, $args) {
              if(isset($this->plugins[$method])){
                array_unshift(&$args, $this->data);
                array_unshift(&$args, $this);
                return $this->plugins[$method]->run($args[0], $args[1], $args[2]);

              } else {
                throw new Exception('No such function');
              }
        }
} ?>

I simplified the class somewhat for clearity.

With this class, you can dynamicly add and remove classes by calling register or unregister. Register will store the object in an associative array by calling toString (as defined by ProductPlugin) and saving the method under the returned string in the array. (In this case the name of the method the class adds.)

When a method is called, which isn't standard in the object, _call will lookup the called method in the array. If found, __call run the method of the plugin with the provided arguments. I restricted the user provided argument to 1, because I want to force the user to use associative arrays.

Because I chose an array to store my classes, removing a function is quite simple. However the unregister function isn't optimal, I better pass a string instead of a plugin object. I didn't test it yet on performance.

The ProductPlugin class:

<?php

abstract class ProductPlugin {
        protected $name = null;
        abstract public function run($obj, $data, $args);
        public function __construct($data = null) {

                if($this->name === null){
                        throw new Exception('Name must be defined');
                }
                $this->init($data);
        }
        protected function init($data){

        }
        public function toString(){
                return $this->name;
        }
}

?>

And at last some demonstration code:

<?php
$bla = new ProductPart(array('HelloWorld' => 'Hello world'));
$hello = new helloPlugin();
$bla->register($hello);
$bla->HelloWorld();
$bla->unregister($hello);
$bla->HelloWorld();

?>
dead,screamer@seznam,cz 21-Dec-2008 08:50
<?php call_user_func()?> and <?php call_user_func_array()?> hide some errors (notices, warnings and maybe errors), even if is display_errors turned on and error_Reporting is set to E_ALL|E_STRICT
Maxdamantus 03-Nov-2007 10:26
Note that the parser can interpret variables in function syntax, which means you can pass all variables normally (eg: reference).

<?php
function myfunction($string, &$int){
    echo $string."\n";
    $int++;
}
$function_name = "myfunction";
$x = 1336;
$function_name("Hello World", $x);
echo $x;
?>
---
Hello World
1337
chris at NOSPAM dot panospheric dot com 22-Sep-2007 07:37
I am looking for a way to make dynamic method calls on objects. I may have overlooked other posts but here is the example anyway.

<?php

class MyClass1 {

   var $input1 = 4;
   var $input2 = 5;

   function MyClass1(){}

   function adding() {

   $var1 = $this->input1;
   $var2 = $this->input2;

   $result = $var1 + $var2;

   return $result;
   }

}

class MyClass2 {

   var $anotherObject;

   function MyClass2($anotherObject){

     $this->anotherObject = &$anotherObject;

   }

}

?>

Now we will call a method of object of object:

<?php

$myclass1Object =& New MyClass1();

$myclass2Object =& New MyClass2(&$myclass1Object);

$output =  $myclass2Object->anotherObject->adding();

echo $output; //outputs 9 if all is well

?>

Now we want to do it dynamically that works in PHP 4 and 5. There are two ways of doing this.

First Method using variable variables:

<?php

$objectName = 'myclass2Object';  //case sensitive.
$anotherObject = 'anotherObject';//case sensitive
$functionName = 'adding';

$output = $$objectName->{$anotherObject}->{$functionName}();

echo $output; //will output 9 as well

?>

Now the same using call_user_func():

<?php

$output = call_user_func(array(&$$objectName->{$anotherObject},$functionName));

echo $output; //outputs 9 as well

?>

If you have a method of an object of an object that requires parameters you can do this:

<?php

call_user_func(array(&$objectName->{$anotherObject},$functionName), $arg1, $arg2);

?>

I hope this might be helpful to someone.

Cheers.
Knightnet 07-Sep-2007 05:31
You don't need to use this function to call a variable class function. Instead you can do the following:

$this->{$fnname}();

The example works in PHP 5 from within the class. It is the {} that do the trick.

Regards,
Julian.
serge belychev 23-Aug-2007 07:08
For calling a class method from version 5.2.3 you can write

<?php
class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func('myclass::say_hello');
?>
lsblsb at gmx dot de 29-Jun-2007 04:55
referring to Mr.KTO (and Bug #24931):
[system: PHP 5.2.0-8] - _doesnt_ pass by reference, at least when using the old syntax with the '&'.

when you pass your object by reference using call_user_func, any changes made on that object within the called function wont effect your "original" object.

you should use mixed call_user_func_array ( callback $function, array $param_arr ) instead or eval() (slower).
Mr.KTO 14-Jun-2007 07:39
To send an object to your function by link, using call_user_func it's not enough (in php4) to define func(&$obj) { ... }

You need: call_user_func("callback", &$myobj)

(in php5 objects are sending by link as default)
jaimz at vertigolabs dot org 27-Oct-2006 10:40
replay to bkfake-php at yahoo dot com's comment:

that's not passing by referance, your explicitly setting the value of $testy's member variable, infact, if you take the & out of your outsidefunc() it still works...
bkfake-php at yahoo dot com 26-Oct-2006 10:18
I have found a case where the parameters ARE passed by reference

class test
{
    function test()
    {
        $this->passme = '';
        call_user_func('outsidefunc',$this);
        // $this->passme is now 'not empty'
        // with 5.1.2
        // not so with php 4.3.10...
    }
}

function outsidefunc(&$testy)
{
     $testy->passme = 'not empty';
}
$test = new test();
echo 'passme = '.$test->passme;
Typer85 at gmail dot com 12-Sep-2006 03:57
I would just like to say at first that I prefer variable function calls over the use of this function.

However I found that at some times, the use of this function is needed in situtations where variable function calls can not be used. And in those same situations, the use of this function is also better than using eval.

The situation I ran into is this:

I wanted to call object methods dynamically from within the object but with arguments given for possible parameters that the method I will call requires.

The parameters themselves are dynamic, meaning I have no prior knowledge of how many their are, their values, or if they even exist.

Also because object methods are dynamic, meaning I have no prior knowledge which object method will actually be called, I can not simply use variable function calls, call the method and pass any parameters.

So what I simply do is call the object method with an array of parameters, something that, to the best of my knowledge, can not be done with variable function calls, since variable function calls, even though they themeselves are dynamic, passing parameters to them is not.
watchout at no dot spam dot please 29-Aug-2006 06:05
> This particular case will not work. The user functions can only be successfully called (as the documentation alludes to), with static calls to class functions.

actually it *does* work on PHP 5.0.2 (tested), and should also work on PHP 4.3.x (untested). Also the documentation does not state that only calls to static class methods are possible, but it says clearly that calls to OBJECT (thats dynamic) methods are possible: http://cz.php.net/manual/en/language.pseudo-types.php (see under type callback)
rlansky at webroot dot com 14-Jul-2006 04:17
Based on the previous posts, it appears that using call_user_func can be serveral times slower than using variable substitution. I think these results are somewhat misleading.

I set up a similar test in which a static method of an object was called repeatedly in a loop. I got similar results to those seen; when calling the method using call_user_func the execution was twice that of calling the method directly. However, I then started adding some "meat" to the method in question. In my case, I found that what was constant was not the percentage change, but rather that there is a fixed cost to using call_user_func.

In my case, this fixed cost was 2 microseconds per call. When executing a method that performs no operations, this is a large percentage of the execution time for that method. However, when using this on a method that actually performs some work, the 2 microsecond cost is almost impossible to measure.

It seems to me that if you want to use call_user_func to call a very fast executing method, and you need to do this thousands of times, then you may want to reconsider. However, if you are using this to call methods that are not executed thousands of times, the small fixed cost of using php call_user_func is probably not an issue.
Maresa 13-Apr-2006 03:41
I tested the same code that insta at citiesunlimited dot com pasted on the following machines:

www1 machine:
OS:  FreeBSD 5.2.1-RELEASE
CPU: 2 x Intel(R) Xeon(TM) CPU 2.66GHz (2657.82-MHz 686-class CPU) with Hyperthreading
MEM: 1073217536 (1023 MB)
PHP 5.1.2 (cli)
PHP 4.4.1 (Web)

www2 machine:
OS:  Linux version 2.6.14-gentoo-r5 Gentoo 3.4.3-r1, ssp-3.4.3-0, pie-8.7.7)
CPU: 2 x Dual Core AMD Opteron(tm) Processor 265 stepping 02 1808.357 MHz
MEM: 2060388k total
PHP 5.1.2 (cli)
PHP Version 4.4.0-pl1-gentoo (web)

dev machine:
OS:  Linux version 2.6.15-gentoo-r1 Gentoo 3.3.5.20050130-r1, ssp-3.3.5.20050130-1, pie-8.7.7.1
CPU: Intel(R) Pentium(R) 4 CPU 2.00GHz stepping 04
MEM: 516384k total,
PHP 4.4.0-pl1-gentoo (cli)
PHP Version 4.4.0-pl1-gentoo (web)

The result are as follows:

www1 - CLI
Variable functions took 0.012186050415 seconds.
call_user_func took 0.0300550460815 seconds.
eval took 0.17235994339 seconds.

www1 - Web
Variable functions took 0.017616 seconds.
call_user_func took 0.034926 seconds.
eval took 0.149618 seconds

www2 - CLI
Variable functions took 0.0065491199493408 seconds.
call_user_func took 0.019452095031738 seconds.
eval took 0.10734891891479 seconds.

www2 - Web
Variable functions took 0.01565 seconds.
call_user_func took 0.02613 seconds.
eval took 0.132258 seconds.

dev - CLI
Variable functions took 0.025176 seconds.
call_user_func took 0.047402 seconds.
eval took 0.168196 seconds.

dev - Web
Variable functions took 0.025465 seconds.
call_user_func took 0.049713 seconds.
eval took 0.20154 seconds.

On www1 - CLI, eval is about 14 times slower than calling function by using variable.
On www1 - Web, eval is about 8.5 times slower (hmm interesting. Perhaps PHP4 is faster calculating eval than PHP5)

On www2 - CLI, eval is about 16 times slower than calling function by using variable.
On www2 - Web, eval is about 8.5 times slower (about same result as www1)

On dev - CLI, eval is about 6.6 times slower than calling function by using variable.
On dev - Web, eval is about 8 times slower (about same result as www1)

On the dev machine, CLI and web version of PHP is the same. and their speed difference between calling function using variable or eval does not differ that much compare to PHP5 VS PHP5
insta at citiesunlimited dot com 06-Feb-2006 12:15
I benchmarked the comparison in speed between variable functions, call_user_func, and eval.  My results are below:

Variable functions took 0.125958204269 seconds.
call_user_func took 0.485446929932 seconds.
eval took 2.78526711464 seconds.

This was run on a Compaq Proliant server, 180MHz Pentium Pro 256MB RAM.  Code is as follows:

<?php

function fa () { return 1; }
function fb () { return 1; }
function fc () { return 1; }

$calla = 'fa';
$callb = 'fb';
$callc = 'fc';

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += $calla();
    $x += $callb();
    $x += $callc();
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "Variable functions took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += call_user_func('fa', '');
    $x += call_user_func('fb', '');
    $x += call_user_func('fc', '');
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "call_user_func took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    eval( '$x += ' . $calla . '();' );
    eval( '$x += ' . $callb . '();' );
    eval( '$x += ' . $callc . '();' );
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "eval took " . (microtime( true ) - $time) . " seconds.<br />" );

?>
Marco 05-Oct-2005 01:42
>phil at gettcomm dot com
>22-May-2002 04:51
>if you need to get a reference back from a method, you can work around
>call_user_func()'s shortcomings like this:
>
Naaa! Having back a reference is a real problem, but it can be solved by mean of eval(), instead of using call_user_func:

<?php
  class Node {
    var $name;
    var $child;
    function Node ( $name ) { $this->name = $name; }
    function &getChild () { return $this->child; }
  }
  $p = new Node ( 'Father' );
  $c = new Node ( 'Child' );
  $p->child = &$c;

  eval ( "\\$cref = &\\$p->getChild ();" );
  $cref->name = 'Another Child';

  // Prints out 'Another Child'
  echo "****** After eval c = " . $c->name . "\\n\\n";

?>
php at REMOVEMEkennel17 dot co dot uk 09-Aug-2005 08:46
re comment by mw at lanfear dot com

I am using PHP 4.3.2 and that technique works fine here as well.
mw at lanfear dot com 26-Jul-2005 01:49
This function is actually quite useful for calling static methods on classes, which you CANNOT call as:

$v1 = 'MyClass';
$m1 = 'method';
$v1::$m1();           // syntax error -- not permitted.

The following, however, DOES work quite well, and is hopefully slightly faster than eval() ...

$ar = array($v1, $m1);

call_user_func($ar);    // works teh awes0me!!1!

[I am, however, presuming PHP5 here ...]
info at webseiteselberpflegen dot de 18-May-2005 01:00
It seems like call_user_func() can not be used to create Objects via the new Command.

The Following example dosen't work:

<?php
  include_once(class_".$type.".php");
  $object = new call_user_func ('bdv_'.$type);
?>

But this works:

<?php
    include_once(class_".$type.".php");
    $constr = 'bdv_'.$type;
    $object = new $constr();
?>
d at safetypub dot org 15-Mar-2005 08:43
callbacks, this par excellence, goes with set error handler, everywhere you'ren't sure of extensio de intensionibus (animis alii).

<?php

$checkMe = null;
$detail = array();
set_error_handler("imErrant");

array_shift($argv);
if ($argc == 1){
        call_user_func(strtolower($argv[0]));
} else if($argc == 2){
        call_user_func(strtolower($argv[0]), $argv[1]);
}
else
        call_user_func_array(strtolower($argv[0]),array_shift($argv));

if($checkMe)var_export($detail);

function imErrant($no, $str, $file, $line)
{
    global $checkMe, $detail;
    $checkMe = $no;
    $detail = array($str, $file, $line);
}
?>
24-Feb-2005 07:46
<?php
/*
    A very simple event handler dispose and change the latest one I did
*/

class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke = null )
    {
        if( $pDuke == null )
        {
            call_user_func( array( &$this, "OnEventHandler" ), $this, null );
            return;
        }

        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );

    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

//////////////////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "OnEventHandler", null );

$b ->OnEvent();
$b ->OnEvent( $pDuke );
?>
zxy at estec-jp dot com 24-Feb-2005 02:57
A simple event handler dispose released by useful callback in PHP 4.x

<?php
class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke )
    {
        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );
    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

///////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "SayHello", null );
$b ->OnEvent( $pDuke );
?>
bostjan dot skufca at domenca dot com 15-Dec-2004 12:33
This is the CORRECTED VERSION of previous note. After playing a while I realised that objects are not passed by reference implicitly, you have to do it on your own, so:

call_user_func(array($objectBar, 'methodFoo')); // case sensitive

first duplicates object $objectBar (internally) and only then calls it's methodFoo. This kind of use is discouraged as it may result in "unpredicted behaviour".

Correct version is here.
call_user_func(array(&$objectBar, 'methodFoo')); // case sensitive
(note the reference operator).

--- and the corrected note is here ---

I couldn't find any simple list of available callback variations, so I made one. It is tested on PHP 4.3.9 only.

If you need to call ordinary function:
call_user_func('funcFoo');

If you need to call CLASS method (NOT object):
call_user_func(array('classBar', 'methodFoo')); // case insensitive

If you need to call OBJECT method:
call_user_func(array(&$objectBar, 'methodFoo')); // case sensitive

If you need to call method of object of object:
call_user_func(array(&$objectBar->objectTor, 'methodFoo')); // case sensitive

If you need to call object method from within the very same object (NOT CLASS!):
call_user_func(array(&$this, 'methodFoo'));
07-Oct-2004 12:23
If you are trying to instantiate an object from a class whose name is dynamic, you WILL NOT be able to do this with call_user_func() and I do not suggest that you do it with eval(). The way to do it is actually much simpler than i thought. As far as i know this works in PHP 4 and 5:

<?PHP
class foo {
 var $boo;
    function foo( $someVal ) {
     $this->boo = $someVal;
    }
}

$ClassToUse = "foo";
$bar = new $ClassToUse('test');
echo $bar->boo;
?>
arjini at mac dot com 29-Mar-2004 05:04
Some of the wierder examples below confused me, and made me think that the following would work (but it does!).

<?php

class barber{
    function shop($one,$two,$three,$four='quartet'){
        echo $one.','.$two.','.$three.','.$four;
    }
}

$bsq = new barber;
call_user_func(array(&$bsq,'shop'),'one','two','three');

/* Output = one,two,three,quartet */

class bigBarber{
    var $quartet;
    function bigBarber(){
        $this->quartet = 'four';
    }
    function shop($one,$two,$three,$five='quintet'){
        echo $one.','.$two.','.$three.','.$this->quartet.','.$five;
    }
}

$bbsq = new bigBarber();
call_user_func(array(&$bbsq,'shop'),'one','two','three');

/* Output = one,two,three,four,quintet */

?>
Kris Koskelin 22-Jan-2004 03:21
I was trying to use this function to call a method of an already-instantiated object.  I needed to do this with the object itself, not simply call the class' method.

To accomplish this, I really avoided this particular function altogether like this:

<?php
if ( method_exists($my_obj, $action) ){
     return $my_obj->{$action}();
}
?>

I hope someone else finds this useful.  Note that doing this allows you to pass params to the function more-or-less in the same way you would to any other class method.
Michele.Manzato at verona.miz.it 29-Sep-2003 08:49
With overload()ed classes call_user_func_* calls real class methods only. If the method does not exist then PHP does not try with the "__call()" magic method (at least until PHP 4.3.3). See this:

<?php
class A
{
    function A() {}

    function __call($method, $args, &$ret) {
        echo "__call(): You called '{$method}()'<br>\n";
        return true;
    }

    function regular() {
        echo "You called 'regular()'<br>\n";
    }
};
overload("A");

$a = new A;

$a->regular();                          // Works, calls regular()
call_user_func(array(&$a, "regular"));  // Works, calls regular()

$a->hello();                            // Works, calls __call()
call_user_func(array(&$a, "hello"));    // Does NOT work!
?>
Carl 28-Jul-2003 11:53
I had a problem where I wanted to parameterize a callback. The end called was in an external class, but I needed to save some state for the callback that didn't make sense to keep in the original object, as it might change from call to call...

<?php
class foo
{
    function foo()
    {
        $str = "Hello There";

        $str2 = "Carl";

        $that =& new holder($str);

        call_user_func(array(&$that, 'callback'), $str2);
    }
}

class holder
{
    function holder($aParam)
    {
        $this->param = $aParam;
    }

    function callback($aStr)
    {
        echo "A=$this->param, B=$aStr\n";
    }
}
?>
matt at tasonline dot com 23-Nov-2002 12:24
On PHP 4.2.3 (not sure about older releases) you can send objects by reference by sending the reference from call_user_func()

<?php
function myFunction(@$obj)
{
   $obj->doThis('hello');
   return 0;
}

$myObj = new CObject();

call_user_func('myFunction', @$myObj);
?>
phil at gettcomm dot com 21-May-2002 07:51
if you need to get a reference back from a method, you can work around call_user_func()'s shortcomings like this:

<?php

$globalObj;

class tClass
{
    function &instance()
    {
        global $globalObj;
        if(!is_object($globalObj))
        {
            $globalObj = new tClass();
        }
        return $globalObj;
    }
}

$classname = "tClass";
# calling the function this way won't
# return a reference.
$test = &call_user_func(array($classname,"instance"));
# but if we call it again with the instance
# that we just got, it'll be the right
# one
$test = &$test->instance();
# so test is now a reference to $globalObj, just like it should be

# let's verify it:
$test->blah=1;

echo "<pre>";
print_r($test)."\n";
print_r($globalObj);
echo "</pre>";
# there, now it behaves just like you'd expect

?>
teleware at mind dot net 08-Apr-2002 01:34
I ran into some quirky behavior using call_user_func with an object.  The function parseAction() below lets me call any of my object's methods by passing the name of the method into a page (e.g. http://xyz.com/page.php?action=login).

<?php
class MyClass {

    function parseAction($actionKey)
    {
        global $METarget;

        if(method_exists($this,$actionKey))
        {
            call_user_func(array(&$this,$actionKey));
            return;
        }
        else
        {
            exit("Unknown action keyword: $actionKey");
        }
    }

    ...
    // other methods
    ...
}
?>

I found that my member variables weren't always being updated correctly.  The numberic values were preserved but the string variables retained their old value.  The solution was to put the reference operator '&' in front of the object's variable.  In this case it's $this because I'm calling it from within the object but this was also true when calling parseAction from an instanciated object e.g. call_user_func(array(&$myObject,$actionKey))
dougqh at hotmail dot com 07-Mar-2002 05:16
The previous note I posted had an error in the source code.  That has been corrected in this note.

Note, that returning by reference does not work properly when the function
is called using call_user_func.

This example illustrates the problem...

<?php
$globalVar = 0;

function &staticFunction()
{
   global $globalVar;

   return $globalVar;
}

$result =& call_user_func( "staticFunction" );

$result = 3;

print "result:" . $result . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";

$result2 =& staticFunction();

$result2 = 3;

print "result2: " . $result2 . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";
?>

The above code results in the following output ...
Note that $result is not a reference to $globalVar.

result:0
globalVar: 0
result2: 3
globalVar: 3

Also, the use of call_user_method is now deprecated in favor of passing
array( &$object, $method ) as the function to call_user_func.  This is
reported when error reporting is set to E_ALL in the latest versions of
PHP.
danyloco at yahoo dot com 17-Jul-2001 04:31
I was trying to call multiple functions within a class, and after a brain frying experience this is what came out... hope it helps:

<?php
class Foo {
 function hey1($id){echo "In hey1";}
 function hey2($id){echo "In hey2";}
 #... and so forth ...
 function runtest($id) {
   #the fun part :)
   for($i=1; $i<=2; $i++) {
     $fp = "hey".$i;
     $this->$fp($id);
}
}
}
?>

It worked like a charm :).
andreyhristov at yahoo dot com 22-Aug-2000 06:09
Let say we construct somehow the name of the function. In some cases we can use nested  'switch'  but the alternative is to to use for and parse a string to construct  the  function  name, after than  we also can construct and the parameter(s) for it. It  is like using of eval. I use it in  one of my projects to construct a name of nested array like $ar['1999'['july']['29']['19'], etc.

the problem is in that I'm parsing a string to construct the name. If I've {1:2:3}  the array name  will be $ar['1']['2']['3'] but if i've
{1:2:3:4:5} it will  be $ar['1']['2']['3']['4']['5'].

Eval is the only way (very hard because of characters escaping is needed)  to do it. So this function is of the type of EVAL().
USE IT wherever your script is  'self-modified';
call_user_func_array
create_function
Управление функциями


Создаёт анонимную (лямбда) функцию

call_user_func
forward_static_call_array
Управление функциями
PHP Manual

create_function

(PHP 4 >= 4.0.1, PHP 5)

create_function — Создаёт анонимную (лямбда) функцию

Описание

string create_function ( string $args , string $code )

Создаёт анонимную функцию из переданных параметров и возвращает её уникальное имя.

Список параметров

Обычно параметры передаются строкой в одинарных кавычках. Основанием для использования строк в одинарных кавычках является защита имён переменных от обработки, другими словами, если вы будете использовать двойные кавычки, то необходимо будет проэкранировать все имена переменных, вот так: \$avar.

args

Аргументы функции.

code

Код функции.

Возвращаемые значения

Возвращает уникальное имя функции в виде строки, или FALSE в случае ошибки.

Примеры

Пример #1 Создание анонимной функции с помощью create_function()

Вы можете использовать эту функцию (к примеру) для создания функций на основании информации, полученной во время выполнения программы:

<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "Новая анонимная функция: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// выводит
// Новая анонимная функция: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>

Или, возможно, чтобы иметь общий обработчик для применения набора операций к списку параметров:

Пример #2 Создание функции-обработчика с помощью create_function()

<?php
function process($var1, $var2, $farr)
{
    foreach ($farr as $f) {
        echo $f($var1, $var2) . "\n";
    }
}

// создаем кучу математических функций
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "тригонометрия: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "гипотенуза: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nИспользуем первый массив анонимных функций\n";
echo "параметры: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// теперь создаем кучу функций обработки строк
$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'и \"$b\"\n** для меня одинаковы! (смотря по первым 3 символам)";'),
    create_function('$a,$b', '; return "CRC: " . crc32($a) . ", ".crc32($b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
    );
echo "\nИспользование второго массива анонимных функций\n";
process("Варкалось. Хливкие шорьки пырялись по наве", "Варабей под кровлю, а сова на ловлю", $garr);
?>

Результат выполнения данного примера:

Используем первый массив анонимных функций
параметры: 2.3445, M_PI
тригонометрия: -1.6291725057799
гипотенуза: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a)/b = 0.27122299212594

Использование второго массива анонимных функций
** "Варабей под кровлю, а сова на ловлю" и "Варкалось. Хливкие шорьки пырялись по наве"
** для меня одинаковы! (смотря по первым 3 символам)
CRC: -1622439884, -458910041
similar(a,b) = 25(35.460992907801%)

Однако, вероятно, наиболее обоснованное использование лямбда (анонимных) функций - это создание функций-обработчиков, например, при использовании array_walk() или usort()

Пример #3 Использование анонимной функции как функции-обработчика

<?php
$av = array("о, ", "эх, ", "то ", "это ");
array_walk($av, create_function('&$v,$k', '$v = $v . "манго";'));
print_r($av);
?>

Результат выполнения данного примера:

Array
(
  [0] => о, манго
  [1] => эх, манго
  [2] => то манго
  [3] => это манго
)

Сортировка строк по их длине

<?php

$sv = array("мало", "много", "большая строка", "строка строка строка");
print_r($sv);

?>

Результат выполнения данного примера:

Array
(
  [0] => мало
  [1] => много
  [2] => большая строка
  [3] => строка строка строка
)

Теперь отсортируем их в обратном порядке:

<?php

usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);

?>

Результат выполнения данного примера:

Array
(
  [0] => строка строка строка
  [1] => большая строка
  [2] => много
  [3] => мало
)

Смотрите также

  • "Анонимные функции"

User Contributed Notes

Dave H 24-Mar-2011 06:47
The following function is very useful for creating an alias of a user function.
For built-in functions, it is less useful because default values are not available, so function aliases for built-in functions must have all parameters supplied, whether optional or not.

<?php
function create_function_alias($function_name, $alias_name)
{
    if(function_exists($alias_name))
        return false;
    $rf = new ReflectionFunction($function_name);
    $fproto = $alias_name.'(';
    $fcall = $function_name.'(';
    $need_comma = false;

    foreach($rf->getParameters() as $param)
    {
        if($need_comma)
        {
            $fproto .= ',';
            $fcall .= ',';
        }

        $fproto .= '$'.$param->getName();
        $fcall .= '$'.$param->getName();

        if($param->isOptional() && $param->isDefaultValueAvailable())
        {
            $val = $param->getDefaultValue();
            if(is_string($val))
                $val = "'$val'";
            $fproto .= ' = '.$val;
        }
        $need_comma = true;
    }
    $fproto .= ')';
    $fcall .= ')';

    $f = "function $fproto".PHP_EOL;
    $f .= '{return '.$fcall.';}';

    eval($f);
    return true;
}
?>
sezer 03-Jan-2011 01:25
This function creates lambda_xx function at global namespace (\) even if you are in a specific namespace.

Namespace aa;
create_function() > function is in still global space

So your function should also include all other functions and constants as aa\xxx() and there is no way to create in current namespace as of 5.3.3
phenno7 [a_t] yahoo dot com 15-Sep-2010 01:53
The function takes as arguments the tree array, the category id on which i want the retrieval, and the depth level for which i would like the subcategories ids returned.

this saves me a LOT of time on large adjacency list trees.

<?php
$ctg_tree = array(
'1'=>array('parent_id'=>0,
           'children'=>array(
          '2'=>array('parent_id'=>1,
                      'children'=>array(
                      '3'=>array('parent_id'=>2))),
           '4'=>array('parent_id'=>1,
                      'children'=>array(
                      '5'=>array('parent_id'=>4),
                      '6'=>array('parent_id'=>4))))));

function getSubCategories($ctg_tree, $id, $level = null) {

        $getBranchIds =
create_function(
'$tree, $ctg_id, $level = null, $arr = null,'.
' $push = false, $getBranchIds','
            if(!$arr) {
                $arr = array();
            }
            if(intval($level) && $push){
                $level--;
            }

            foreach($tree as $key=>$ctg) {
                if($push) {
                    $arr[] = $key;
                }
                if($ctg_id == $key) {
                    $start = true;
                    $push = true;
                }
if(count($ctg[\'children\']) && (intval($level) || $level === null)) {
$getBranchIds(
$ctg[\'children\'],$ctg_id,$level,&$arr,$push,$getBranchIds
);
                }
                if($start) return $arr;
            }

            return $arr;');

return $getBranchIds(
$ctg_tree, $id, $level, null, false, $getBranchIds
);
    }

print_r(getSubCategories($ctg_tree, 4, 1));
?>

Array
(
    [0] => 5
    [1] => 6
)

print_r(getSubCategories($ctg_tree, 1, 1));

Array
(
    [0] => 2
    [1] => 4
)

<?php
print_r(getSubCategories($ctg_tree, 1));
?>

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)
Its Will 01-Sep-2010 08:27
If you create a function that will only be used from an object context (i.e. you want a dynamic method that can then call methods from the original object, still maintaining access to the object's runtime values) then you can use the following functions I have created (ob_lambda_func and ob_lambda) to enable the dynamic function to easily call *public* methods on the object, in their runtime contexts:

<?php
/* the OB Lambda functions allow a lambda function to call a method from its callee's object */
if(!function_exists('ob_lambda_func')){
function ob_lambda_func($method, $args) {
   if((phpversion()+0)<5.1 || (substr(phpversion(),2)+0)<1.1)
       die("\nError: This script requires PHP v5.1.1+!\n");
   $bt=debug_backtrace();
   foreach($bt as $xsp) {
       if(isset($xsp['object'])) {
           if(!method_exists($xsp['object'], $method)) continue;
           return call_user_func_array(array($xsp['object'], $method), $args);
       }
   }
   if(!function_exists($method))
       die("\nOB: Internal Error! ($method)");
   return call_user_func_array($method, $args);
}}
if(!function_exists('ob_lambda')){
function ob_lambda($method) {
   return create_function('','$args=func_get_args(); return ob_lambda_func('.var_export($method, true).',$args);');
}}

/* Usage:
 *   For each callable method, store the results of ob_lambda('method_name')
 *   When a lambda function you call wants to access one of these methods,
 *    you need to pass it the result of ob_lambda for that method, the easiest
 *    way is to have one of the lambda functions arguments accept the result
 *       i.e.:  $myFunc=ob_lambda('myMethod');
 *              $lf1=create_function('$func', '$func( ... args ... )');
 *              $lf1($myFunc);
 *    because create_function prepends a \0 to the function name, it is difficult
 *    to pass the result of ob_lambda to the target function without using an argument
 */
/* here is an example -- lambda function Foo::test can call Foo::Bar and Foo::Baz, and these  */
class Foo {
    private $bar, $baz, $test;
    private $runtimeValue=0;
    function __construct() {
        $this->runtimeValue=rand();
        $this->bar=ob_lambda('Bar');
        $this->baz=ob_lambda('Baz');
        $this->test=create_function(
            '$bar, $baz',
            '$bar("Hello, World!"); $baz();'
        );
    }
    function Test() {
        $fn=$this->test;
        $fn($this->bar, $this->baz);
    }
    function Bar($a) {
        echo "$a: Bar ($this->runtimeValue)\n";
    }
    function Baz() {
        echo "and another! Baz ($this->runtimeValue)\n";
    }
}

$foo=new Foo();
// Foo::Bar("Testing Other Method"); <-- this causes fatal error
//  (using $this when not in object context)
$foo->Test();

?>

This snippet (with test) shows how the lambda function $foo->test can call Foo::Bar and Foo::Baz without an explicit reference to the original object. The methods are run from their object context, and so can access the runtime-modified variable $foo->runtimeValue, which is set to a random number on construction.
The function definition for $foo->test is the following:
function ($bar, $baz) {
    $bar("Hello, World!");
    $baz;
}
As you can see, it is clean and simple, with no obvious artifacts from the use of OB Lambda

The expected output should be:
Hello, World!: Bar (440048505)
and another! Baz (440048505)

Or any other random number in place of 440048505
Make sure, before you change your code, that your target server has PHP 5.1.1+, or these functions won't work and will return an error!
Hope this helps anyone as much as it has me! :)
julius _email _me _at grantzau _dot _com 16-Jul-2010 09:59
To avoid memory problems, when creating a dynamic function within loops, register it as a global variable, and check if it has already been set;

<?php
global $my_func;
if (!isset($my_func))
{
    $my_func = create_function($args, $code);
}

$my_func();
?>

That way you don't end up creating the same function twice (or a couple of million of times, as it happened to me...)
v dot churakov at i2d dot ru 20-Feb-2010 04:56
<?

function is_function( &$mixed )
{
    if ( is_object( $mixed ) ) {
        return ( $mixed instanceof Closure );
    } elseif( is_string( $mixed ) ) {
        return function_exists( $mixed );
    } else {
        return false;
    }
}

function myfunc(){}

$test = 123;
echo  is_function( $test ); //will return false

$test = 'isset';
echo  is_function( $test ); //will return false... it's not work with reserved :( ...

$test = 'myfunc';
echo  is_function( $test ); //will return true

$test = create_function( '', 'echo 123;' );
echo  is_function( $test ); //will return true

$test = function () { echo 123; };
echo  is_function( $test ); //will return true

?>
edgar at goodforall dot eu 02-Jul-2009 07:45
Just a little toy I thought up, I would like to share. Creates an anonymous function, which let you use a class  as a function.

In php 5.3 there is support for real functors  (trough __invoke):

<?php
function createFunctor($className){
        $content = "
                static \$class;
                if(!\$class){
                        \$class = new $className;
                }
                return \$class->run(\$args);
        ";
        $f = create_function('$args', $content);
        return $f;

}
class test {
        public function run($args){
                print $args;
        }
}
$test = createFunctor('test');
$test('hello world');
?>
Stefan Scheld 23-Sep-2008 07:48
Workaround is as follows:

<?php
class Foo {
    function setHandler($handlerName, $handlerCode) {
        $this->handlerFunctions[$handlerName] = create_function('&$self, $dataArr', $handlerCode);
// NOTE: $this not allowed here, using $self as replacement
    }

    function executeHandler($handlerName, $dataArr) {
        if($this->handlerFunctions[$handlerName]) {
                $this->handlerFunctions[$handlerName](&$this, $dataArr);
            }
     }

    function getConstantInfo($what) {
        return($what);
    }
}

$bla = new Foo;

$bla->setHandler("load", 'echo($self->getConstantInfo("name")."\n");');
$bla->executeHandler("load", array("foo" => "bar"));
?>
neo at nowhere dot com 28-Aug-2008 01:56
In response to kkaiser at revolution-records dot net's note, even tho PHP will allow you to use
<?
$myfunc = create_function('$this', $code);
?>
You can NOT use a reference to "$this" inside of the anonymous function, as PHP will complain that you are using a reference to "$this" in a non-object context.

Currently, I have not found a work-around for this...
Alan FUNG 07-Aug-2008 12:24
$f = create_function('','echo "function defined by create_function";');
$f();

result:
function defined by create_function

You may define no return in function body while you are using create_function.
Rene Saarsoo 06-Feb-2008 02:31
Here has been some discussion about the "memory leak" create_function() can create.

What create_function() actually does, is creating an ordinary function with name chr(0).lambda_n where n is some number:

<?php
$f = create_function('', 'return 1;');

function lambda_1() { return 2; }

$g = "lambda_1";
echo $g(); // outputs: 2

$h = chr(0)."lambda_1";
echo $h(); // outputs: 1
?>
colin dot mckinnon at gmail dot com 20-Aug-2007 05:51
In response to koyama at hoge dot org (14-Dec-2000):

This does NOT create a new method - try adding this at the end:

<?php
if (function_exists($h->lamda)) {
   print "Its a function\n";
} else {
   print "No it isnt";
}
?>

It creates a function which $h->lamda points to.

Under PHP4 you could simply add an argument $this which meant it *behaved* like a method (though it existed in global scope) but with PHP5, you can't have a variable named $this in a function (which is rather irksome).

(and methinks the ant-bot challenge is taking the mickey - min(three, four)?  !).
TSE-WebDesign 18-Aug-2007 09:55
Here's how to call a runtime-created function from another runtime-created function:
<?php
        $get_func = create_function('$func', 'return substr($func,1);');
        $get_value = create_function('$index','return pow($index,$index);');
        $another_func = create_function('$a', '$func="\x00"."'.$get_func($get_value).'";return $func($a);');
        echo $another_func(2); # result is 4
?>
kkaiser at revolution-records dot net 13-Apr-2007 01:10
In the process of migrating a PHP4 codebase to PHP5, I ran into a peculiar problem. In the library, every class was derived from a generic class called 'class_container'. 'class_container' contained an array called runtime_functions and a method called class_function that was as follows:

<?php
function class_function($name,$params,$code) {

  $this->runtime_functions[$name] = create_function($params,$code);

}
?>

In a subclass of class_container, there was a function that utilized class_function() to store some custom lambda functions that were self-referential:

<?php
function myfunc($name,$code) {

  $this->class_function($name,'$theobj','$this=&$theobj;'.$code);

}
?>

In PHP4, this worked just fine. The idea was to write blocks of code at the subclass level, such as "echo $this->id;", then simply $MYOBJ->myfunc("go","echo $this->id;"); and later call it like $MYOBJ->runtime_functions["go"]();

It essentially worked exactly like binding anonymous functions to objects in Javascript.

Note how the "$this" keyword had to be manually redefined for the $code block to work.

In PHP5, however, you can't redeclare $this without getting a fatal error, so the code had to be updated to:

<?php
function myfunc($name,$code) {

  $this->class_function($name,'$this',$code);

}
?>

Apparently create_function() allows you to set $this via a function argument, allowing you to bind anonymous functions to instantiated objects. Thought it might be useful to somebody.
a dot steenveld at id dot umcn dot nl 18-Jan-2007 06:18
It is possible to use this call to implement continuations but you need a small workaround for a nagging feature of create_function(). The result of this function does start with a null character which might result in loosing the name of your function altogether!. (See also bug report #40160)

Here is a bit of code to play with. The result should be 'f(2, 2) = 6'
<?php
/* continuations in php.
   vim:nu

   Code inspired by http://www.ps.uni-sb.de/~duchier/python/continuations.html
*/

function writeln($s) { echo "$s\n"; }

function lambda0 ($args, $code)
    { return substr(create_function ($args, $code), 1);
    }
function L ($l)
    { if (strncmp($l, 'lambda_', 7) === 0) return "\0$l";
      else return $l;
    }

function mul ($x, $y, $c) { $f = L($c); $f($x*$y); }
function add ($x, $y, $c) { $f = L($c); $f($x+$y); }
function mal ($x, $y, $c) { mul(2, $x, lambda0 ('$v', "add(\$v, $y, $c);")); }

function f($x, $y)
    { mal($x, $y, lambda0 ('$v', "writeln(\"f($x, $y) = \$v\");"));
    }

    f(2, 2);
?>
Dan D 23-Oct-2006 07:22
Beware when using anonymous functions in PHP as you would in languages like Python, Ruby, Lisp or Javascript.  As was stated previously, the allocated memory is never released; they are not objects in PHP -- they are just dynamically named global functions -- so they don't have scope and are not subject to garbage collection.

So, if you're developing anything remotely reusable (OO or otherwise), I would avoid them like the plague.  They're slow, inefficient and there's no telling if your implementation will end up in a large loop.  Mine ended up in an iteration over ~1 million records and quickly exhasted my 500MB-per-process limit.
Phlyst 06-Oct-2006 05:10
In reply to info at adaniels dot nl:

You may not be able to use __FUNCTION__ in a lambda (thanks for pointing it out; I was having that problem just now), but you can use $GLOBALS to work around it if you're assigning the function to a variable. I reimplemented array_walk_recursive() in PHP4 like this:

<?php
$array_walk_recursive = create_function('&$array, $callback',
    'foreach($array as $element) {
        if(is_array($element)) {
            $funky = $GLOBALS["array_walk_recursive"];
            $funky($element, $callback);
        }
        else {
            $callback($element);
        }
    }');
?>
Josh J 27-Sep-2006 12:45
In regards to the recursion issue by info at adaniels dot nl

Anon function recursion by referencing the function variable in the correct scope.
<?php
$fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func($GLOBALS["fn2"], ++$a);');
$fn2(1);
?>
info at adaniels dot nl 10-May-2006 03:42
Note that using __FUNCTION__ in a an anonymous function, will always result '__lambda_func'.

<?php
    $fn = create_function('', 'echo __FUNCTION__;');
    $fn();
    // Result: __lambda_func
    echo $fn;
    // Result: ºlambda_2 (the actual first character cannot be displayed)
?>

This means that a anonymous function can't be used recursively. The following code (recursively counting to 10) results in an error:
<?php
    $fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func(__FUNCTION__, $a++);');
    $fn2(1);
    // Warning: call_user_func(__lambda_func) [function.call-user-func]: First argument is expected to be a valid callback in T:/test/test.php(21) : runtime-created function on line 1
?>
josh at janrain dot com 03-Mar-2006 10:21
Beware! This is merely a convenience function that generates a unique name for a regular function. It is *not* a closure or even an anonymous function. It is just a regular function that gets named for you.
Joshua E Cook 19-Jan-2006 04:43
Functions created by create_function() cannot return a value by reference.  The function below creates a function that can.  The arguments are the same as create_function().  Note that these arguments are passed, unmodified, to eval(), so be sure that data passed in is sanitized.

<?php
/**
 * create_ref_function
 * Create an anonymous (lambda-style) function
 * which returns a reference
 * see http://php.net/create_function
 */
function
create_ref_function( $args, $code )
{
    static $n = 0;

    $functionName = sprintf('ref_lambda_%d',++$n);

    $declaration = sprintf('function &%s(%s) {%s}',$functionName,$args,$body);

    eval($declaration);

    return $functionName;
}
?>
boards at gmail dot com 31-Dec-2005 11:18
If you were checking to see if a function is made properly, this would be a better way of checking:

<?php
$fnc = @create_function('$arg1,$arg2,$arg3', 'return true;');
# make that function whatever you want
if (empty($fnc)) {
  die('Could not create function $fnc.');
}

# although, the follow will NOT work
if (empty(create_function('$arg', 'return $arg;'))) {
  die('Could not create anonymous function.');
}
# you would get an error regarding not being able to use a
# return value in writeable context (i.e. a return value is
# a const in C, and the function empty() doesn't use a
# const void* parameter
?>
david [at] davelee.com.au 13-Apr-2005 02:15
<?php
# dynamically create html helper functions which take the args
# $string_contents, $optional_hash_of_options
# and return the contents wrapped in a tag

$html_funcs = Array(
    'table',
    'tr',
    'th',
    'td',
    'div',
    'span',
    'pre',
    'strong',
    'em'
);
$args = '$html, $options=Array()';
$code = '
  $o = "";
  foreach ($options as $a => $b) {
    $o .= " $a=\"$b\"";
  }
  return "<$tag$o>$html</$tag>";
';
foreach ($html_funcs as $key => $tag) {
    ${$tag} = create_function($args, "\$tag = '$tag'; $code");
}

# usage example:

print $table(
  $tr($th('heading').$td('this is the cell content')),
  Array('style'=>'border: 1px solid silver;')
);
?>
endofyourself at yahoo dot com 07-Oct-2004 12:17
You really should avoid using this as well as you should avoid using eval(). Not only will there be a performance decrease but can it lead to obfuscation and bad coding habits. There is almost always an alternative solution to self modifying code.
MagicalTux at FF.ST 09-Mar-2004 10:25
neo at gothic-chat d0t de wrote :
Beware of memory-leaks, the garbage-collection seems to 'oversee' dynamically created functions!

Not really...

In fact, PHP can not "unassign" functions. So if you create a function, it won't be deleted until the end of the script, even if you unset the variable containing its name.

If you need to change a part of a function everytime you run a loop, think of a way to make a more general function or try using eval :) (functions are made to be re-used. If you need to run your own piece of code once, eval is much better).
neo at gothic-chat d0t de 20-Jan-2004 08:54
Beware of memory-leaks, the garbage-collection seems to 'oversee' dynamically created functions!

I used a function like this to replace special characters in links with their htmlentities:
<?php
$text = preg_replace_callback (
    "/(<(frame src|a href|form action)=\")([^\"]+)(\"[^>]*>)/i",
    create_function (
        '$matches',
        'return $matches[1] . htmlentities ($matches[3]) . $matches[4];'
    ),
    $text);
?>

After 1000 calls, the process used about 5MB more than before. In my situation this boosted up the memory-size of one PHP-process up to over 100MB!

In such cases, better store the function in a global variable.
nospam at fiderallalla dot de 08-Aug-2003 06:39
Sometimes it may be useful to create functions in a dynamic environment
(f. e. in a daemon-like php script).

Normally declaring a function must be done once, which results in the problem,
that in this special case modifying a function wouldn't have an effect until the script is reloaded.

Maybe this code snipplet is useful 4 u.

File: "functions.inc"

<?php
function test($str) {
    echo $str;
}
?>

Dynamic FunctionHandler:

<?php
$FileName = "functions.inc";
$FileHandle = fopen($FileName,"r");
$FileContent = fread($FileHandle,filesize($FileName));
fclose($FileHandle);

preg_match_all("#function\ ?([a-zA-Z0-9-_]*)\ ?\((.*?)\)\ ?\{(.*?)\}#mixse",$FileContent,$Matches);
if ( is_array($Matches) && isset($Matches[0]) && count($Matches[0]) > 0  ) {
     foreach ( $Matches[0] as $key=>$val ) {
        $$Matches[1][$key] = create_function($Matches[2][$key],$Matches[3][$key]);
    }
}
?>

The Test:
<?php echo $test("test"); ?>
.. will echo "test";

Hans Kuhlen
DB on music_ml at yahoo dot com dot ar 02-Apr-2003 04:58
[EDIT by danbrown AT php DOT net: Combined user-corrected post with previous (incorrect) post.]

You can't refer to a class variable from an anonymous function inside a class method using $this.  Anonymous functions don't inherit the method scope.  You'll have to do this:

<?php
class AnyClass {

 var $classVar = 'some regular expression pattern';

 function classMethod() {

   $_anonymFunc = create_function( '$arg1, $arg2', 'if ( eregi($arg2, $arg1) ) { return true; } else { return false; } ' );

   $willWork = $_anonymFunc('some string', $classVar);

 }

}
?>
listes at brissambre dot org 14-Aug-2002 10:22
[Editor's note: Only regular variables are serialized (scalars, arrays, objects), and as lambda functions are not stored as any of those types, it is not saved during session serialization.]

Warning, it seems that you can't store such lambda functions in Sessions, because only the function's name will be stored, not the function itself.
So don't save the function but only it's code and call create_function each time the script is called.
ben-php at bacarisse dot btinternet dot co dot uk 26-Jul-2001 01:33
A nice technique for building complex search patterns on lists, files or whatever is to build function combining functions like this:

<?php
function _not_($f) {
  return create_function('$x',
    "return !$f(\$x);");
}

function _and_($f, $g) {
  return create_function('$x',
    "return $f(\$x) && $g(\$x);");
}
?>

(similarly for _or_ and others...).  Once you've built your matching primitives you can then build more complex matches into your script.

Unfortunately, as explained in (closed) bug #10721, the function names returned by create_function have a null byte at the front and this causes a parse error.

You can fix the definition like this:

<?php
function _not_($f) {
  $f = substr($f, 1);
  return create_function('$x',
    "return !call_user_func(chr(0).'$f', \$x)");
}
?>

The expression that re-builds the function name avoid the null being literally in the parsed string.  If there is a better fix, please let me know.
x-empt[a_t]ispep.cx 05-Jul-2001 11:41
Create_function enables the ability to change the scope of functions.  You might have a class where it needs to define a GLOBAL function.  This is possible, like:

<?php
        class blah {
                function blah() {
                        $z=create_function('$arg1string','return "function-z-".$arg1string;');
                        $GLOBALS['z']=$z;
                }
        }
        $blah_object=new blah;

        $result=$GLOBALS['z']('Argument 1 String');
        echo $result;
?>

Making a function escape it's defined scope can be useful in many situations.
maxim at maxim dot cx 27-Apr-2001 03:26
for those who want to assign it's own name to a function consider this code:

<?php
$fname = 'hello';

$func = sprintf('
    function %s($v="") {
        Return "$v<BR>";
    }
',
$fname
);

eval($func);
echo $fname('Please print it.... please....');
?>

what it does is,
: Creats a function as a string;
: Replaces the function name with $fname value;
: Converts the string into a REAL php code with eval()
: Calls the function using the variable function as declared before ($fname);

Simple, isn't it?

Can work well as an abstraction layer for portability and/or compatibility purposes

Maxim Maletsky
maxim@maxim.cx // PHPBeginner.com
mrben at free dot fr 20-Feb-2001 08:33
Here is another tricky but usefull techynote, good for adding "plugin" to a existing class :

<?php

class Hoge {
    var $lamda;
    var $text;

    function set($lamda)
    {
        $this->lamda = $lamda;
    }

    function callLamda()
    {
        $func = $this->lamda;
        return $func($this);
    }

    function get()
    {
        return $this->text;
    }
}

$newfunc = create_function('&$class', 'echo $class->get();' );

$h = new Hoge;
$h->text = "Hi there !";
$h->set($newfunc);
$h->callLamda();

?>
koyama at hoge dot org 14-Dec-2000 04:22
How do you use function which is created by create_function() as class method?

<?php
class Hoge {
  var $lamda;
  function set($lamda) {
    $this->lamda = $lamda;
  }
  function callLamda() {
    $func = $this->lamda;
    return $func();
  }
}

$newfunc = create_function('', 'echo "hoge<br>\n";');

$h = new Hoge;
$h->set( $newfunc );
$h->callLamda();
?>

It works fine. :-)
call_user_func
forward_static_call_array
Управление функциями


Call a static method and pass the arguments as array

create_function
forward_static_call
Управление функциями
PHP Manual

forward_static_call_array

(PHP 5 >= 5.3.0)

forward_static_call_array — Call a static method and pass the arguments as array

Описание

mixed forward_static_call_array ( callable $function , array $parameters )

Calls a user defined function or method given by the function parameter. This function must be called within a method context, it can't be used outside a class. It uses the late static binding. All arguments of the forwarded method are passed as values, and as an array, similarly to call_user_func_array().

Список параметров

function

The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name.

parameter

One parameter, gathering all the method parameter in one array.

Замечание:

Note that the parameters for forward_static_call_array() are not passed by reference.

Возвращаемые значения

Returns the function result, or FALSE on error.

Примеры

Пример #1 forward_static_call_array() example

<?php

class A
{
    const NAME = 'A';
    public static function test() {
        $args = func_get_args();
        echo static::NAME, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NAME = 'B';

    public static function test() {
        echo self::NAME, "\n";
        forward_static_call_array(array('A', 'test'), array('more', 'args'));
        forward_static_call_array( 'test', array('other', 'args'));
    }
}

B::test('foo');

function test() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

Результат выполнения данного примера:

B
B more,args
C other,args

Смотрите также

  • forward_static_call() - Call a static method
  • call_user_func() - Вызывает пользовательскую функцию, указанную в первом параметре
  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров
  • is_callable() - Проверяет, может ли значение переменной быть вызвано в качестве функции
  • информация о типе callback

User Contributed Notes

strrev xc tod noxeh ta ellij 11-Nov-2009 06:07
If you replace forward_static_call_array() by call_user_func_array(); you will get the same result.
create_function
forward_static_call
Управление функциями


Call a static method

forward_static_call_array
func_get_arg
Управление функциями
PHP Manual

forward_static_call

(PHP 5 >= 5.3.0)

forward_static_call — Call a static method

Описание

mixed forward_static_call ( callable $function [, mixed $parameter [, mixed $... ]] )

Calls a user defined function or method given by the function parameter, with the following arguments. This function must be called within a method context, it can't be used outside a class. It uses the late static binding.

Список параметров

function

The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name.

parameter

Zero or more parameters to be passed to the function.

Возвращаемые значения

Returns the function result, or FALSE on error.

Примеры

Пример #1 forward_static_call() example

<?php

class A
{
    const NAME = 'A';
    public static function test() {
        $args = func_get_args();
        echo static::NAME, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NAME = 'B';

    public static function test() {
        echo self::NAME, "\n";
        forward_static_call(array('A', 'test'), 'more', 'args');
        forward_static_call( 'test', 'other', 'args');
    }
}

B::test('foo');

function test() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

Результат выполнения данного примера:

B
B more,args
C other,args

Смотрите также

  • forward_static_call_array() - Call a static method and pass the arguments as array
  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров
  • call_user_func() - Вызывает пользовательскую функцию, указанную в первом параметре
  • is_callable() - Проверяет, может ли значение переменной быть вызвано в качестве функции
  • информация о типе callback

User Contributed Notes

arthur dot techarts at gmail dot com 12-Jul-2011 07:39
Example to understand this function and difference with call_user_func:

<?php
class Beer {
    const NAME = 'Beer!';
    public static function printed(){
        echo 'static Beer:NAME = '. static::NAME . PHP_EOL;
    }
}

class Ale extends Beer {
    const NAME = 'Ale!';
    public static function printed(){
        forward_static_call(array('parent','printed'));
        call_user_func(array('parent','printed'));

        forward_static_call(array('Beer','printed'));
        call_user_func(array('Beer','printed'));
    }
}

Ale::printed();
echo '</pre>';
?>
forward_static_call_array
func_get_arg
Управление функциями


Возвращает элемент из списка аргументов

forward_static_call
func_get_args
Управление функциями
PHP Manual

func_get_arg

(PHP 4, PHP 5)

func_get_arg — Возвращает элемент из списка аргументов

Описание

mixed func_get_arg ( int $arg_num )

Возвращает указанный аргумент из списка аргументов пользовательской функции.

Эта функция может быть использована совместно с func_get_args() и func_num_args() для создания функций с переменным количеством аргументов.

Список параметров

arg_num

Номер аргумента. Аргументы функции считаются с нуля.

Возвращаемые значения

Возвращает указанный аргумент, или FALSE в случае ошибки.

Список изменений

Версия | Описание
5.3.0 | Эта функция теперь может быть использована в качестве параметра функции.
5.3.0 | Если эта функция вызвана в глобальной области видимости файла, подключенного с помощью include() или require() из функции вызывающего файла, то теперь будет сгенерировано предупреждение и возвращено значение FALSE.

Ошибки

Генерирует предупреждение при вызове вне определения функции, или если arg_num больше реально переданного количества аргументов.

Примеры

Пример #1 Пример использования func_get_arg()

<?php
function foo()
{
     $numargs = func_num_args();
     echo "Количество аргументов: $numargs<br />\n";
     if ($numargs >= 2) {
         echo "Второй аргумент: " . func_get_arg(1) . "<br />\n";
     }
}

foo (1, 2, 3);
?>

Пример #2 Использование func_get_arg() до и после PHP 5.3

test.php
<?php
function foo() {
    include './fga.inc';
}

foo('Первый аргумент', 'Второй аргумент');
?>

fga.php
<?php

$arg = func_get_arg(1);
var_export($arg);

?>

Вывод до PHP 5.3:

'Второй аргумент'

Вывод в PHP 5.3 и выше:

Warning: func_get_arg():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Пример #3 Пример передачи аргументов по ссылке и по значению с func_get_arg()

<?php
function byVal($arg) {
    echo 'Передан          : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'После изменения  : ', var_export(func_get_arg(0)), PHP_EOL;
}

function byRef(&$arg) {
    echo 'Передан          : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'После изменения  : ', var_export(func_get_arg(0)), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

Результат выполнения данного примера:

Передан : 'bar'
После изменения : 'bar'
Передан : 'bar'
После изменения : 'baz'

Примечания

Замечание:

Так как для определения параметров данной функции необходим контекст выполнения, она не может быть передана в качестве параметра в версиях PHP до 5.3.0. Если функцию все же необходимо передать, то нужно присвоить ее переменной, которую уже можно использовать при передаче.

Замечание:

Если аргументы были переданы по ссылке, то все изменения аргументов будут отражены на возвращаемых функцией значениях.

Замечание: Эта функция возвращает только копии переданных аргументов, и не возвращает значения по умолчанию (непереданных) аргументов.

Смотрите также

  • func_get_args() - Возвращает массив, содержащий аргументы функции
  • func_num_args() - Возвращает количество аргументов, переданных функции

User Contributed Notes

beta3designs [at] gmail [dot] com 06-Jul-2009 06:34
This functions seems so powerful... just when i saw it i thought about writing a fast average of n numbers function so here it is, it is very simple... example usage included.

<?php

//Calculate the average of the numbers given

function avg(){
    $sum = 0;
    for($i = 0; $i < func_num_args(); $i++){
        $sum += func_get_arg($i);
    }
    $avg = $sum / func_num_args();
    return $avg;
}

echo sprintf("%.2f",avg(2,1,2,1,3,4,5,1,3,6));
?>
wintermute 20-Sep-2007 11:11
Bishop: Your ternary example is flawed:

<?php
// using ternary operators
function pick($a,$b) { return (isset($a) ? $a : $b); }
$a = (pick($b,$c) ? pick($c,$d) : null);
?>

If $b is not null, it will evaluate pick($c, $d) and return $c if that is not null. If $b and $c are both null, it will not evaluate pick($c, $d) and will return null regardless of the value of $d. I'm not sure how you'd save this.

Another option would be to use an array:
<?PHP
function pick($array)
{
  foreach ($array as $element)
  {
    if ($element != null)
    {
      return($element)
    }
  }
  return(null);
}

$a = pick(array($b, $c, $d, $e))
?>

I don't know that there's any real difference between this and the variable-argument form, but some people might prefer it, so it's worth noting.
Aries-Belgium 11-Jan-2007 10:44
I was just thinking about a way to create a singleton where you only need to run the instance() function only one time with an argument. And I came up with this solution: (maybe it's useful for other users)

<?php
class Singleton {
      private $arg = "";

      private function __construct($arg) {
              $this->arg = $arg;
      }

      public static function instance() {
             static $_instance = null;
             if(func_num_args() == 0 && $_instance == null) {
                    $_instance = new Singleton(func_get_arg(0));
             }
      }
}

// first time
$singleton = Singleton::instance("foobar");

// later in your code (in other class and/or function)
$singleton = Singleton::instance();
?>
bishop 10-Dec-2004 09:58
Regarding a "deferment" operator for dvogel at ssc dot wisc dot edu, pick your poison:

<?php
// using ternary operators
function pick($a,$b) { return (isset($a) ? $a : $b); }
$a = (pick($b,$c) ? pick($c,$d) : null);
?>

<?php
// using varargs function
function pick($a) {
    $argc = func_num_args();
    for ($i = 0; $i < $argc; $i++) {
        $arg = func_get_arg($i);
        if (! is_null($arg)) {
            return $arg;
        }
    }

    return null;
}

$a = pick($b, $c, $d);
?>
mw atto lanfear dotto com 07-Dec-2004 02:56
func_get_arg() does not appear to be allowed to be used as a function argument itself within class constructors in PHP 5.0.2 (wonk-ay!!!):

<?php

class ABC
{
    function __construct()
    {
        foreach (func_get_args() as $name => $value)
        {
    echo <<<EOT
    <br/>
    $name : $value <br/>
    <br/>

EOT;
        }
    }
}

class DEF extends ABC
{
    function __construct()
    {
        parent::__construct(func_get_arg(0),
                                    func_get_arg(1),
                                    func_get_arg(2));
    }
}

$def = new DEF(123123, "asdfasdf", "blahblahblah");

?>

The above script generates:

Fatal error: func_get_arg(): Can't be used as a function parameter in c:\Inetpub\wwwroot\phpwasrc\chapter10\xxx.php on line 23

There are, however, no problems when passing these as parameters to regular functions.
dvogel at ssc dot wisc dot edu 21-Oct-2004 02:54
I've always wants a deferment or cascade operator so that I could use this expression:

  $a = $b ## $c ## $d;

and everything to the right of the assignment operator would evaluate to the left-most value that is not null. It is essentially a collapsed version of this:

<?php
  if ($b) {
    $a=$b;
  } else {
    if($c) {
      $a=$c;
    } else {
      if ($d) {
        $a = $d;
      } else {
        $a = null;
      }
    }
  }
?>
In leiu of this, I'm trying to make a function that takes a variable number of arguments and returns the first that is not null. I wan't to use this on some large-ish arrays, so I'd like to pass these by reference. However, call-time reference passing is disabled (and should be, imo) in newer versions of PHP. I'd like suggestions on how to pass both references and values to this function.

The only solution I can think of is setting variables to the reference of the array first. e.g.

$a = array( ... );
$b = 0;
$c = &a;
first_not_null($a, $b);

Does anyone know a better solution?
harald at triptop dot org 14-Sep-2004 03:09
func_get_arg is useful, if you know the exact order of the arguments, or if the order doesn't matter. i use this function (or func_get_args) for example to create own sprintf wrappers.

if you want to pass a variable number of arguments to a function it's in my opinion better, to submit it as a key/value array e.g.:

<?php
functioncall(array("param1" => "...",...));
?>

and 'extract' the array inside the function. you don't need to do tricks like type-checking for parameter-recognition, in this case.
anders at ingemann dot fakestuff dot de 03-Jun-2004 06:16
I actually think that there is need for such "do absolutely everything" functions. I use them mostly as tools for rapid prototyping.
And there is a method with which you may be able to pass several strings to a function: ereg();
Another use for such functions is to create little code snippets for other people out there. They won't have to edit the function any longer if they do not use a parameter. They just don't name it when calling the function.
This results in allrounder functions that are very robust in their use.Normally you just have a little code snippet (e.g. ip-blocking snippets). Through this type of programming you have whole functions.
26-May-2004 09:29
very clever unless you need to specify at least two parameters of the same type - which is which? Obviously, you may decide on some defaults, but then the whole thing gets ugly. What if you need a string ONLY if a boolean was also supplied? The type-checking becomes the main focus of your function, shit. For the sake of clean code you should specify a clean interface to your functions, and decide on what and where is passed as an argument. Yes, you can always code a do_absolutely_everything() function, but is there any sense?
anders at ingemann dot fakestuff dot de 29-Apr-2004 04:18
A pretty cool thing for user defined functions is only to submit the needed parameters. If you call a function that has three optional parameters you have to define the two first ones (even if they should stay like the defined standard in the function) before your are able to tell the function what the third important parameter is. Instead you might as well just find out by the pattern or the type of the submitted parameter which variable it should be assigned to.
like this:

<?php
function whatever()
{
    for($i=0;$i<func_num_args();$i++)
    {
        if(is_bool(func_get_arg($i))) $log_ip=func_get_arg($i);
        if(is_int(func_get_arg($i))) $limit=func_get_arg($i);
        if(is_string(func_get_arg($i))) $name=func_get_arg($i);
    }
}
?>

Now you can call the function with any parameter you want.
e.g.:

<?php whatever(3600); ?>

in that case $limit would be defined with 3600.

It doesn't matter if you do this:

<?php whatever(3600,false); ?>

or this:

<?php whatever(3600,"blaaah"); ?>

or this:

<?php whatever("blaaah",true,3600); ?>

You may also use ereg(). Through that you're able to use more than one parameter as a string.
hmm probably ereg() is the best solution...
never mind.
just check it out ;-)
mightye (at) mightye (dot) org 12-Mar-2004 09:45
func_get_arg() returns a *copy* of the argument, to my knowledge there is no way to retrieve references to a variable number of arguments.

I have a module system in my game at http://lotgd.net where I'd like to be able to pass a variable number of arguments to functions in a module, and pass them by reference if the module asks for it by reference, but you can't accept optional parameters as references, nor can you retrieve the reference on a variable number of arguments.  Looks like my modules will have to do with out the ability to accept parameters to their functions by reference.
forward_static_call
func_get_args
Управление функциями


Возвращает массив, содержащий аргументы функции

func_get_arg
func_num_args
Управление функциями
PHP Manual

func_get_args

(PHP 4, PHP 5)

func_get_args — Возвращает массив, содержащий аргументы функции

Описание

array func_get_args ( void )

Возвращает массив, содержащий аргументы функции.

Эта функция может быть использована совместно с func_num_args() и func_get_arg() для создания функций с переменным количеством аргументов.

Возвращаемые значения

Возвращает массив, в котором каждый элемент является копией соответствующего члена списка аргументов пользовательской функции.

Список изменений

Версия | Описание
5.3.0 | Эта функция теперь может быть использована в качестве параметра функции.
5.3.0 | Если эта функция вызвана в глобальной области видимости файла, подключенного с помощью include() или require() из функции вызывающего файла, то теперь будет сгенерировано предупреждение и возвращено значение FALSE.

Ошибки

Генерирует предупреждение при вызове вне определения функции.

Примеры

Пример #1 Пример использования func_get_args()

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Количество аргументов: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Второй аргумент: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Аргумент №$i: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
?>

Результат выполнения данного примера:

Количество аргументов: 3<br />
Второй аргумент: 2<br />
Аргумент №0: 1<br />
Аргумент №1: 2<br />
Аргумент №2: 3<br />

Пример #2 Использование func_get_args() до и после PHP 5.3

test.php
<?php
function foo() {
    include './fga.inc';
}

foo('Первый аргумент', 'Второй аргумент');
?>

fga.inc
<?php

$args = func_get_args();
var_export($args);

?>

Вывод до PHP 5.3:

array (
  0 => 'Первый аргумент',
  1 => 'Второй аргумент',
)

Вывод в PHP 5.3 и выше:

Warning: func_get_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Пример #3 Пример передачи аргументов по ссылке и по значению с func_get_args()

<?php
function byVal($arg) {
    echo 'Передан          : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'После изменения  : ', var_export(func_get_args()), PHP_EOL;
}

function byRef(&$arg) {
    echo 'Передан          : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'После изменения  : ', var_export(func_get_args()), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

Результат выполнения данного примера:

Передан : array (
0 => 'bar',
)
После изменения : array (
0 => 'bar',
)
Передан : array (
0 => 'bar',
)
После изменения : array (
0 => 'baz',
)

Примечания

Замечание:

Так как для определения параметров данной функции необходим контекст выполнения, она не может быть передана в качестве параметра в версиях PHP до 5.3.0. Если функцию все же необходимо передать, то нужно присвоить ее переменной, которую уже можно использовать при передаче.

Замечание:

Если аргументы были переданы по ссылке, то все изменения аргументов будут отражены на возвращаемых функцией значениях.

Замечание: Эта функция возвращает только копии переданных аргументов, и не возвращает значения по умолчанию (непереданных) аргументов.

Смотрите также

  • func_get_arg() - Возвращает элемент из списка аргументов
  • func_num_args() - Возвращает количество аргументов, переданных функции
  • ReflectionFunctionAbstract::getParameters() - Получает аргументы

User Contributed Notes

Pyetro Costa (PySafe) Brazil-SP 26-Apr-2012 06:17
In this example, we try to show how to assign the value of the arguments for the variables dynamically and why only works this way.
We will see how to work with get_class_vars () and func_get_args (). We can see that when assign to the class variables to an array that keys of this array are of type string,
for it the array keys are the names of variables, thus we could not use a numeric index to access elements of this array. To enable access to these elements we must first transform the array keys in numeric index keys, then we can work with the use of indexes.

<?
// Creates a Class
class foo {
  // Define varibles
  private $a='01', $b='02', $c='03';

  // Creates the constructor with a single required argument
  function __construct($a) {

    // Sets the argument value to variable
    $this->a=$a;

    // Count how many arguments were passed
    $nArgs = func_num_args();

    // Run if number of arguments is greater than one
    if($nArgs>1) {
      // Creates an array with the class variables
      $cVars = get_class_vars(__CLASS__);
      // The array keys are the name of class variables
      var_dump($cVars); // array(3) { ["a"]=> string(2) "01" ["b"]=> string(2) "02" ["c"]=> string(2) "03" }

      // Show value of array elements
      echo '<br> => '.$cVars[0]; // => null
      echo '<br> => '.$cVars[a]; // => 01

      // Show value of class variables by reference of $this
      echo '<br> => '.$this->{1}; // => null
      echo '<br> => '.$this->{b}; // => 02

      // Show value by reference $this with array $cVars
      echo '<br> => '.$this->$cVars[2]; // => Show a error: "Fatal error: Cannot access empty property in C:\..." Because this array element not exist
      echo '<br> => '.$this->$cVars['a']; // => null // Because "$cvars[a]" was set to a value and not a reference to class variable

      // Changes the array, the values given the keys and the keys change to numeric index
      $cVars = array_keys($cVars);

      // Now, the array elements are a reference to the class variable and can be accessed by an index
      echo '<br><br>';
      var_dump($cVars); // array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }

      // First prints the default value of the class variables and then the value assigned by the argument
      reset($cVars);
      for($i=1; $i<$nArgs; $i++) {
          $str .= '<br> Index:'.$i.',   key ['.current($cVars).'] => '.$this->$cVars[$i].',   Arg('.$i.') == '.func_get_arg($i);
          $this->$cVars[$i]=func_get_arg($i);
          $str .= '<br> Index:'.$i.',   key['.current($cVars).'] => '.$this->$cVars[$i].',   Arg('.$i.') == '.func_get_arg($i);
        next($cVars);
      }
      echo '<br>'.nl2br($str).'<br><br>';
    }
    print_r($this);
  }
}

new foo('alpha',12345,'charlie');
?>

Now we can see below the same content over briefly.

<?
class test {
  private $a='01', $b='02', $c='03';

  function __construct($a) {
    $this->a=$a;
    $nArgs = func_num_args();
    if($nArgs>1) {
      $cVars = get_class_vars(__CLASS__);
      $cVars = array_keys($cVars);

      for($i=1; $i<$nArgs; $i++)
        $this->$cVars[$i]=func_get_arg($i);

      echo $this->a.', '.$this->b.', '.$this->c;
    }
  }
}

$foo = new test('alpha',12345,'charlie');
?>
OpenTechnologist 30-Dec-2011 07:54
please note that optional parameters are not seen/passed by func_get_args(), as well as func_get_arg().

ex:

<?php
function testfunc($optional = 'this argument is optional..') {
    $args = func_get_args();
    var_dump($args);
    echo $optional;
}
?>

test case #1:
testfunc('argument no longer optional..');

result for #1:
array(1) {
    [0]=>  string(20) "argument no longer optional.."
}
argument no longer optional..

test case #2:
testfunc('argument no longer optional..','this is an extra argument');

result for #2:
array(2) {
    [0]=>  string(29) "argument no longer optional.."
    [1]=>  string(25) "this is an extra argument"
}
argument no longer optional..

test case #3: -- RESULTS IN AN EMPTY ARRAY
testfunc();

result for #3:
array(0) {
}
this argument is optional..
red 13-Oct-2011 01:16
I had to pass variable length arguments from one function to another. It seems the only way of doing this is to use call_user_func_array.

<?php

function query(/*query [, $arg1...$argN]*/){
    $query  = call_user_func_array('replaceAndClean', func_get_args());
    $result = mysql_query($query);
    return $result;
}

function replaceAndClean(/*query [, $arg1...$argN]*/){
   $args = func_get_args();
   if(count($args) == 1){
       return $args[0];
   }
   $query = array_shift($args);
   return vsprintf($query, array_map('mysql_real_escape_string', $args));
}

?>

Example:

<?php

// unsave call
query("SELECT FROM foo where bar='".$_POST['bar']."'");

// save call
query("SELECT FROM foo where bar='%d'", $_POST['bar']);

?>
pBakhuis at Gmail dot com 05-Oct-2011 05:30
Please note that you can't use this for recursive functions as you can't pass the parameters to the function again as then they'll be in the form of an array.
mulllhausen 05-Apr-2011 07:49
i use this structure a lot for debugging. i always place the call to 'debugfunc' at the start of any function which i want to debug. the square brackets in the echod output are useful to see if there is accidental whitespace within string variables passed to anyfunc. if anyone can suggest a better way of passing the names of the arguments to debugfunc i would appreciate it. as it is works fine, but its not very universal...

<?php
anyfunc('val1','val2','val3');

function anyfunc($arg1, $arg2, $arg3)
{
    debugfunc(__FUNCTION__, '$arg1, $arg2, $arg3', func_get_args());
    /*do useful non-debugging stuff*/
}
function debugfunc($name, $arg_names, $arg_vals)
{
    echo "begin function [$name]. ";
    $arg_names_array = explode(',', $arg_names);
    foreach($arg_names_array as $k => $v)
    {
        $v = trim($v);
        echo "$v: [$arg_vals[$k]] ";
    }
    echo "\n";
}

//output:
//begin function [anyfunc]. $arg1: [val1] $arg2: [val2] $arg3: [val3]
?>
mitko at edabg dot com 06-Apr-2009 03:48
<?php
/*
This example demonstrate how to use unknown variable arguments by reference.
func_get_args() don't return arguments by reference, but
debug_backtrace() "args" is by reference.
In PHP 5 this have no particular sense, because calling with arguments by reference
is depreciated and produce warning.
*/

class foo {

    var $bar = "default bar";

    function foo(/*variable arguments*/) {
// func_get_args returns copy of arguments
//        $args = func_get_args();
// debug_backtrace returns arguments by reference
        $stack = debug_backtrace();
        $args = array();
        if (isset($stack[0]["args"]))
            for($i=0; $i < count($stack[0]["args"]); $i++)
                $args[$i] = & $stack[0]["args"][$i];
        call_user_func_array(array(&$this, 'bar'), $args);
    }

    function bar($bar = NULL) {
        if (isset($bar))
            $this->bar = & $bar;
    }
}

$global_bar = "bar global";
$foo = & new foo();
echo "foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo "global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    default bar</br>
global_bar:  bar global</br>
*/

$foo = & new foo(&$global_bar);
echo "foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo "global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    bar global</br>
global_bar:  new bar</br>
*/

?>
marco @ vi-da 20-Mar-2009 01:01
sanitazes vars

<?php
function mysql_safe($q) {
    $x = array_shift(func_get_args());
    return vsprintf(preg_replace('/%([1-9]):(d|s)/','%$1$$2',$q), array_map('mysql_escape_string',$x));
}
?>

example

<?php
$query = mysql_safe("select * from somewhere where mood = %2:s and some_id = %1:d order by %3:s desc", $id, 'happy', $order);
?>
Oto Brglez 12-Mar-2009 06:18
How to create simple sum function that can sum N arguments. Like this:

<?php

function sum(){
    $s=0;
    foreach(func_get_args() as $a) $s+= is_numeric($a)?$a:0;
    return $s;
};

print sum(1,2,3,4,5,6); // will return 21
print sum(3,2,1); // will return 6
print sum(false,array(),5,5); // will return 10

?>
anderson at francotecnologia dot com 26-Aug-2008 11:25
How to create a polymorphic/"overloaded" function

<?php
function select()
{
    $t = '';
    $args = func_get_args();
    foreach ($args as &$a) {
        $t .= gettype($a) . '|';
        $a = mysql_real_escape_string($a);
    }
    if ($t != '') {
        $t = substr($t, 0, - 1);
    }
    $sql = '';
    switch ($t) {
        case 'integer':
            // search by ID
            $sql = "id = {$args[0]}";
            break;
        case 'string':
            // search by name
            $sql = "name LIKE '%{$args[0]}%'";
            break;
        case 'string|integer':
            // search by name AND status
            $sql = "name LIKE '%{$args[0]}%' AND status = {$args[1]}";
            break;
        case 'string|integer|integer':
            // search by name with limit
            $sql = "name LIKE '%{$args[0]}%' LIMIT {$args[1]},{$args[2]}";
            break;
        default:
            // :P
            $sql = '1 = 2';
    }
    return mysql_query('SELECT * FROM table WHERE ' . $sql);
}
$res = select(29); // by ID
$res = select('Anderson'); // by name
$res = select('Anderson', 1); // by name and status
$res = select('Anderson', 0, 5); // by name with limit
?>
kangaroo232002 at yahoo dot co dot uk 26-Aug-2008 02:25
Instead of having to define your arg list twice, and keeping to the good style of initialising your variables in the head of your class, you can use (PHP5):

<?php
class myclass {
     public $value = null;
    public $key = null;
    public $column = null;
    public $table = null;
    public function __construct() {
        $vars = get_class_vars();
        for($i=0; $i<func_num_args();$i++) {
            $this->${$vars[$i]}=func_get_arg($i);
        }
    }
}
?>

which should allow you to set variables while retaining their default values if they are not set (in this case, null), without having to mess around with functions to retain default values so is much neater (just don't change the order you declare your vars!)

<?php
//usage
$c = new myclass("value", "tablekey", "tablecol", "table");
echo $c->key;
//prints 'tablekey'
?>
Anonymous 28-Jan-2008 08:11
I use the following concept for quick "plugin" of multiple argument support.

<?php

function increment($n) {
  $p = func_get_args();
  if (count($p) > 1) {
    return array_map(__FUNCTION__, $p);
  }
  $n =& $p[0];

  return ++$n;
}

list($two, $three, $four) = increment(1,2,3);

?>
tristan dot colombo at laposte dot net 18-Oct-2007 01:03
In order to use the function 'func_get_args()' to instanciate differents type of objects, you must use the Reflection API.
By example, we have two different classes and we want to have an unique function (using an unfixed number of parameters) to create the objects. We create two classes 'a' and 'b' where constructors accept different numbers of arguments.
Class a (class/a.class.php):
<?php
  include_once 'a.class.php';

  class b extends a
  {
    private $param3;

    public function __construct($a, $b, $c)
    {
      $this->param1 = $a;
      $this->param2 = $b;
      $this->param3 = $c;
    }

    public function display()
    {
      echo $this->param1 . ', ' . $this->param2 . ' and ' . $this->param3 . '!<br />';
    }
  }
?>

Class b (class/b.class.php):
<?php

  class a
  {
    private $param1;
    private $param2;

    public function __construct($a, $b)
    {
      $this->param1 = $a;
      $this->param2 = $b;
    }

    public function display()
    {
      echo $this->param1 . ' and ' . $this->param2 . '<br />';
    }
  }
?>

Main program :
<?php

  function classFactory()
  {
    // Retrieve arguments list
    $_args = func_get_args();
    // Delete the first argument which is the class name
    $_className = array_shift($_args);

    // Include the requested class
    include_once 'class/' . $_className . '.class.php';

    // Create Reflection object
    // See : http://www.php.net/manual/en/language.oop5.reflection.php
    $_reflection = new ReflectionClass($_className);

    // Use the Reflection API
    return $_reflection->newInstanceArgs($_args);
  }

  $a = classFactory('a', 'hello', 'world');
  $b = classFactory('b', 'that\'s', 'all', 'folks');

  $a->display();
  $b->display();

?>
Sinured 20-Aug-2007 05:38
It may seem obvious, but if you want your variadic function to at least require one parameter, you can do this instead of checking func_num_args() == 0, which I've seen often:

<?php
function variadic($dummy) {
    $args = func_get_args();
    foreach ($args as $arg) {
        echo "$arg<br />\n";
    }
}
?>

func_get_args() fetches ALL passed parameters, not only those that weren't copied to a local variable.
ario [a] mail [dot] utexas [dot] edu 07-May-2007 02:50
"Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable."

This means that the following code generates an error:

<?php

function foo($list)
{
  echo implode(', ', $list);
}

function foo2()
{
  foo(func_get_args());
}

foo2(1, 2, 3);

?>

However, you can easily get around this by doing the following:

<?php

function foo($list)
{
  echo implode(', ', $list);
}

function foo2()
{
  foo($args = func_get_args());
}

foo2(1, 2, 3);

?>

This captures the context from foo2(), making this legal.  You get the expected output:

"1, 2, 3"
jmcguire81 [at] gmail.com 21-Mar-2007 02:13
Here is another variation on accepting a variable number of arguments. This allows for a variable number of arguments to be passed to a Class constructor, as well as a customized class version to be used dynamically. Syntax in code is:

<?php
$mail = Generator("MailClassName", $db_ref);

function Generator() {

   $numargs = func_num_args();

   $classname = func_get_arg(0);
   $argstring='';
   if ($numargs > 1) {
      $arg_list = func_get_args();

      for ($x=1; $x<$numargs; $x++) {
         $argstring .= '$arg_list['.$x.']';
         if ($x != $numargs-1) $argstring .= ',';
      }
   }

   if (class_exists("Custom{$classname}")) {
      $classname = "Custom{$classname}";
      if ($argstring) return eval("return new $classname($argstring);");
      return new $classname;
   }

   if ($argstring) return eval("return new $classname($argstring);");
   return new $classname;
}
?>

Hope this is of use to someone.
rafagd at gmail dot com 13-Feb-2007 08:53
Sometimes, you may need to dynamic set and get of args...

This function merge array args, so you can dynamic set some args by sending an array arg.

<?php
  function dynamicArgs(/*$arg1, $arg2...$argN*/) {
    $args = func_get_args(); $num  = func_num_args();
    for ($i = 1; $i < $num; $i++) {
      $args[0] = array_merge((array) $args[0], (array) $args[$i]);
    }
    return $args[0];
  }

  var_dump(dynamicArgs('a',array('b','c'),'d',1);
?>

This should output like:

array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  int(1)
}
bew 31-Mar-2006 07:55
A more concise way of expressing my idea from the previous post (I'd forgotten about array_slice()):

<?php
function func_get_default_args($a) {
    $args = array_slice(func_get_args(), 1);
    return array_merge($args, array_slice($a, sizeof($args)));
}

function foo($a = 1, $b = 2, $c = 3) {
    print_r(func_get_default_args(func_get_args(), $a, $b, $c));
}

// prints: Array ( [0] => a [1] => b [2] => 3 )
foo('a', 'b');
?>
Nathan Ostgard 06-Dec-2005 10:14
If you're using PHP5, the variable number of argument functions all return the objects by reference - and not a copy of the object, as this leads you to believe.
T.M. 04-Nov-2004 07:24
Simple function to calculate average value using dynamic arguments:
<?php
function average(){
    return array_sum(func_get_args())/func_num_args();
}
print average(10, 15, 20, 25); // 17.5
?>
volte6 at drunkduck dot com 30-Sep-2004 02:54
For those who have a use for a C style enum() function:

<?php
//*******************************************
// void enum();
// enumerates constants for unique values guarenteed.
function enum()
{
  $i=0;
  $ARG_ARR = func_get_args();
  if (is_array($ARG_ARR))
  {
    foreach ($ARG_ARR as $CONSTANT)
    {
      define ($CONSTANT, ++$i);
    }
  }
}

// USAGE:
enum(ERR_USER_EXISTS, ERR_OLD_POST);

// etc. etc.
//*******************************************
?>

this can be used for error codes etc.
I deliberately skipped the 0 (zero) define, which could be useful for error checking.
mark at manngo dot net 23-Mar-2003 11:13
You can also fake named arguments using eval:

<?php
function test()
{   foreach (func_get_args() as $k=>$arg) eval ("\$$arg;");
    echo "$a plus $b gives ".($a+$b);
}

test("a=3","b=4");
?>
daveNO at ovumSPAMdesign dot com 17-Sep-2001 11:29
<?php
// How to simulate named parameters in PHP.
// By Dave Benjamin <dave@ovumdesign.com>

// Turns the array returned by func_get_args() into an array of name/value
// pairs that can be processed by extract().
function varargs($args) {
    $count = count($args);
    for ($i = 0; $i < $count; $i += 2) {
        $result[$args[$i]] = $args[$i + 1];
    }

    return $result;
}

// Example
function test(&$ref1, &$ref2) {
    // Default arguments go here.
    $foo = "oof";

    // Do some magic.
    extract(varargs(func_get_args()));

    echo nl2br("\n\$var1 = $var1");
    echo nl2br("\n\$var2 = $var2");
    echo nl2br("\n\$foo = $foo\n\n");

    // Modify some variables that were passed by reference.
    // Note that func_get_args() doesn't pass references, so they
    // need to be explicitly declared in the function definition.
    $ref1 = 42;
    $ref2 = 84;
}

$a = 5;
$b = 6;

echo nl2br("Before calling test(): \$a = $a\n");
echo nl2br("Before calling test(): \$b = $b\n");

// Try removing the 'foo, "bar"' from the following line.
test($a, $b, var1, "abc", var2, "def", foo, "bar");

echo nl2br("After calling test(): \$a = $a\n");
echo nl2br("After calling test(): \$b = $b\n");
?>
04-Jun-2001 07:44
You can pass a variable number of arguments to a function whilst keeping references intact by using an array. The disadvantage of course, is that the called function needs to be aware that it's arguments are in an array.

<?php
// Prints "hello mutated world"
function mutator($args=null) {
$n=count($args);
while($i<$n) $args[$i++] = "mutated";
}
$a = "hello";
$b = "strange";
$c = "world";
mutator(array($a, &$b, $c));
echo "$a $b $c";
?>
func_get_arg
func_num_args
Управление функциями


Возвращает количество аргументов, переданных функции

func_get_args
function_exists
Управление функциями
PHP Manual

func_num_args

(PHP 4, PHP 5)

func_num_args — Возвращает количество аргументов, переданных функции

Описание

int func_num_args ( void )

Возвращает количество аргументов, переданных функции.

Эта функция также может быть использована совместно с func_get_arg() и func_get_args() для создания функций с переменным количеством аргументов.

Возвращаемые значения

Возвращает количество аргументов, переданных текущей пользовательской функции.

Список изменений

Версия | Описание
5.3.0 | Эта функция теперь может быть использована в качестве параметра функции.
5.3.0 | Если эта функция вызвана в глобальной области видимости файла, подключенного с помощью include() или require() из функции вызывающего файла, то теперь будет сгенерировано предупреждение и возвращено значение -1.

Ошибки

Генерирует предупреждение при вызове вне определения функции.

Примеры

Пример #1 Пример использования func_num_args()

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Количество аргументов: $numargs\n";
}

foo(1, 2, 3);
?>

Результат выполнения данного примера:

Количество аргументов: 3

Пример #2 Использование func_num_args() до и после PHP 5.3

test.php
<?php
function foo() {
    include './fna.php';
}

foo('Первый аргумент', 'Второй аргумент');
?>

fna.php
<?php

$num_args = func_num_args();
var_export($num_args);

?>

Вывод до PHP 5.3:

2

Вывод в PHP 5.3 и выше будет содержать что-то типа следующего:

Warning: func_num_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fna.php on line 3
-1

Примечания

Замечание:

Так как для определения параметров данной функции необходим контекст выполнения, она не может быть передана в качестве параметра в версиях PHP до 5.3.0. Если функцию все же необходимо передать, то нужно присвоить ее переменной, которую уже можно использовать при передаче.

Смотрите также

  • func_get_arg() - Возвращает элемент из списка аргументов
  • func_get_args() - Возвращает массив, содержащий аргументы функции
  • ReflectionFunctionAbstract::getNumberOfParameters() - Получает количество аргументов

User Contributed Notes

luisguillermo dot quevedovelez at gmail dot com 13-Mar-2012 07:32
I had defined a function function_name(){ ...} as a drupal callback.
I try to get how many params where passed

I got a Error and my Site falls down

I've replaced func_get_args() instead func_num_args() and my Site was restored.

I conclude you can not use  func_num_args() in callbacks.

Hope it helps.
Dennis Robinson from basnetworks dot net 29-Jun-2009 09:29
This function comes in handy, and I believe is the only solution, when you have an optional parameter that can take any type of data.

For example:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
    if ($data !== null)
    {
        // Do something with $data
        // If you call my_function('something'), this WILL NOT be reached
        // If you call my_function('something', null), this WILL NOT be reached
    }
}

?>

The problem with the above function is that you will never be able to use null as the value for $data.  To fix this, use func_num_args() like so:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
    if (func_num_args() >= 2)
    {
        // Do something with $data
        // If you call my_function('something'), this WILL NOT be reached
        // If you call my_function('something', null), this WILL be reached
    }
}

?>

This solution works because func_num_args() reports exactly how many arguments were passed when the function was called.  It does not take into account when default argument values are used.
padron at aaargh dot com dot br 19-Jan-2007 11:18
func_num_args(), func_get_args() and func_get_arg() can be very useful to emulate overloading in PHP.

Suppose you have a class to add a user in a system, and that you want to allow 2 ways of doing it. The first way would be passing an array with all the user info in it, and the second way would be passing each user attribute as a single argument.

<?php

class Test {

    function insertUser() {

        // gets the number of parameters
        $numArgs = func_num_args();

        // make decisions based on the arguments number
        if ($numArgs == 1) {
            // if it's only one argument, we suppose that it is an array with user info

            // gets the first argument
            $user = func_get_arg(0);

            // checks if it really is an array
            if (is_array($user)) {

                // here you should check if the array contains all necessary fields

                // adds the user
                echo "User added.<br/>";
                echo "ID: " . $user["id"] . "<br/>";
                echo "NAME: " . $user["name"] . "<br/>";
                echo "EMAIL: " . $user["email"] . "<br/>";

            } else {

                // generates an error if argument is not an array
                echo "Argument is not an array: " . $user . ".<br/>";

            }

        } else if ($numArgs == 3) {
            // if the function receives 3 arguments, we assume that they
            // are 'id', 'name' and 'email' respectively

            // inserts the user into the system
            echo "User added.<br/>";
            echo "ID: " . func_get_arg(0) . "<br/>";
            echo "NAME: " . func_get_arg(1) . "<br/>";
            echo "EMAIL: " . func_get_arg(2) . "<br/>";

        } else {

            // if the number of arguments is different from 1 and 3
            // an error will be generated

            echo "Wrong argument number.<br/>";
            echo "Arguments received: " . func_num_args();

        }
    }

}

// creates an Test object
$objTest = new Teste();

// inserts an user passing an array with all his info
$objTest->insertUser(array("id" => 1, "name" => "George W. Bush", "email" => "jackass@whitehouse.gov"));

echo "<br/>";

// inserts an user providing each attribute as a single argument
$objTest->insertUser(2, "Vicente Fox", "iloveusa@disney.com");

echo "<br/>";

// this will generate an error, because only 2 arguments were passed
$objTest->insertUser(3, "Tony Blair");

?>
neelam_ab2003 at yahoo dot co dot in 11-May-2006 12:40
Just adding a note to JARED's Note.

func_num_args() works if and only if called from within a function definition BECAUSE it calculates the number of arguments sent while function calling. That is why it gives

'1' in helloWorld("HelloWorld!") and '2' in helloWorld("HelloWorld!", "HowdyWorld!") - There is nothing to do with DEFAULT args.

If you call the same function as helloWorld(); "No args passed"

It will give a warning for wrong function call ("Warning: Missing argument 1 for helloWorld()") and the result of func_num_args() will be '0'.
friz at godshell dot com 16-Mar-2006 11:24
This function comes in extremely handy in OO Classes.  My focus is currently PHP 4, but this technique probably works just as well in PHP 5.

<?php
Class foo {
   // constructor, other methods, etc

   function somedata($somedata = '') {
      if (func_num_args() > 0) {
         $this->somedata = $somedata;
      }

      return $this->somedata;
   }
}
?>

This allows for a default value to be set, while not requiring the parameter.  (Yes, I'm aware that it only warns when you do, but I think this is a little cleaner)
jared at ws-db dot com 06-Sep-2005 09:46
Just a note for anyone wondering. This function doesn't include params that have a default value, unless you pass one in to overwrite the default param value. Not sure if that makes sense, so here's an example:

<?php
function helloWorld($ArgA, $ArgB="HelloWorld!") {
  return func_num_args();
}

// The following will return 1
$Returns1 = helloWorld("HelloWorld!");

// The following will return 2
$Returns2 = helloWorld("HelloWorld!", "HowdyWorld!");
?>
andy at arakka dot co dot th 11-May-2005 07:16
func_num_args() can be used in conjunction with named arguments, also. For example:

<?php
function DebugShow( $label, $value ) {
  echo "# " . $label ;
  if ( func_num_args() > 1 ) echo " = " . $value ;
  echo "<br>";
}
?>
ashley at dcs dot warwick dot ac dot uk 17-Apr-2002 04:40
If you want to pass the parameters on intact to another function, use func_get_args and call_user_func_array (careful - this one is only available in recent PHP versions).  For example:

<?php
/* Print an HTML tag.  This accepts a variable number of arguments:
   the first should be the name of the tag, followed by pairs of
   arguments that describe keys and values.  The values are printed
   with surrounding double quote characters.  */
function printTag() {
  $numArgs = func_num_args();
  if ($numArgs < 1) die("printTag given no arguments");

  echo "<" . func_get_arg(0);
  for ($i = 1; $i < $numArgs; $i+=2) {
    echo " " . func_get_arg($i);
    if ($i+1 < $numArgs)
      echo "=\"" . func_get_arg($i+1) . "\"";
  }
  echo ">";

}

/* Print an HTML tag with a newline on the end */
function printTagNL() {
  $args = func_get_args();
  call_user_func_array("printTag", $args);
  echo "\n";
}

printTagNL("input", "type", "hidden", "name", "SORTORDER", "value", $columnNo);
?>
thalis at NOSPAMcs dot pitt dot edu 29-Mar-2002 12:05
The idea of func_get_args() is to construct functions of variable number of parameters like

<?php
function var_param_func(){
    if(func_num_args()==0){
        //do one thing
    }
    if(func_num_args()==1)
        //do another thing
        //get the args with func_get_args()
    }
}
?>
func_get_args
function_exists
Управление функциями


Возвращает TRUE, если указанная функция определена

func_num_args
get_defined_functions
Управление функциями
PHP Manual

function_exists

(PHP 4, PHP 5)

function_exists — Возвращает TRUE, если указанная функция определена

Описание

bool function_exists ( string $function_name )

Проверяет, есть ли в списке определённых функций, как встроенных, так и пользовательских, функция function_name.

Список параметров

function_name

Имя функции, строка.

Возвращаемые значения

Возвращает TRUE, если function_name существует и является функцией, иначе возвращается FALSE.

Замечание:

Эта функция возвращает FALSE для языковых конструкций, таких как include_once() или echo().

Примеры

Пример #1 Пример использования function_exists()

<?php
if (function_exists('imap_open')) {
    echo "IMAP функции доступны.<br />\n";
} else {
    echo "IMAP функции недоступны.<br />\n";
}
?>

Примечания

Замечание:

Обратите внимание, что название функции может присутствовать, даже если саму функцию невозможно использовать из-за настроек конфигурации или опций компиляции (например, как для функций image).

Смотрите также

  • method_exists() - Проверяет, существует ли метод в данном классе
  • is_callable() - Проверяет, может ли значение переменной быть вызвано в качестве функции
  • get_defined_functions() - Возвращает массив всех определённых функций
  • class_exists() - Проверяет, был ли объявлен класс
  • extension_loaded() - Определение, загружено ли расширение

User Contributed Notes

admin at gk-root dot com 22-Mar-2012 02:51
// If you want to chack if the function is enabled or disable in php.ini you can use this function:

<?php
function func_enabled($func) {
    $disabled = explode(',', ini_get('disable_functions'));
    foreach ($disabled as $disableFunction) {
        $is_disabled[] = trim($disableFunction);
    }
    if (in_array($func,$is_disabled)) {
        $it_is_disabled["m"] = $func.'() has been disabled for security reasons in php.ini';
        $it_is_disabled["s"] = 0;
    } else {
        $it_is_disabled["m"] = $func.'() is allow to use';
        $it_is_disabled["s"] = 1;
    }
    return $it_is_disabled;
}
?>

// An example of how to use:

<?php
$if_is_disabled = func_enabled('exec'); // return Arrey
echo $if_is_disabled["m"]; // return text value
echo '<br/>';
echo $if_is_disabled["s"]; // return 1 or 0
?>
Michael dot Bond at mail dot wvu dot edu 20-Sep-2011 10:07
a more complete function_exists that checks for the following:

functions (php and user defined)
class methods
 * as strings in the sense of "class::method" or "class->method"
 * passing a class name or object, as well as the method
language constructs (echo, print, etc ..)

<?php
function functionExists($param1,$param2=null) {

    $langConstructs = array("die",
                            "echo", "empty", "exit", "eval",
                            "include", "include_once", "isset",
                            "list",
                            "print",
                            "require", "require_once",
                            "unset"
                            );

    // 2 params provided, assume class
    if (!is_null($param2)) {
        return(method_exists($param1,$param2));
    }

    // Ignore everything that isn't a string, from this point on
    if (!is_string($param1)) {
        return(FALSE);
    }

    // check if function exists
    if (function_exists($param1) === TRUE) {
        return(TRUE);
    }

    // Check to see if it is an object being passed as a string.
    // if so, assume object
    $items = explode("::",$param1);
    if (count($items) == 2) {
        return(method_exists($items[0],$items[1]));
    }

    $items = explode("->",$param1);
    if (count($items) == 2) {
        return(method_exists($items[0],$items[1]));
    }

    // check to see if it is a language construct
    if (in_array($param1,$langConstructs)) {
        return(TRUE);
    }

    return(FALSE);
}
?>
tinelbarb at yahoo dot com 31-Aug-2010 12:36
I had a problem with VARIANT set of functions, which are not implemented in some custom compilations of php (like LAMP), so I had to define my own "VARIANT" functions.
Like the users in this page have noticed ( eddiec, for example ), the code
<?php
if ( !function_exists('SOME_FUNCTION')) {
    function SOME_FUNCTION () {
        //my run
    }
} ?>
will not work, since the PHP first parse the script for defined functions/classes (the IF statement will not stop it to find the declaration) and then it runs the script.

So, I noticed the good observation of [neelam_ab2003] and the solution is to create a test function which include the declaration of the custom function. And that's working!
Here is an example for "variant_xor" PHP function:
<?php
function DEFINE_variant_xor () {
    function variant_xor($a=0, $b=0) {
        return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
    }
}

if ( !function_exists(' variant_xor')) {
    DEFINE_variant_xor () ;
    //which will pass back to the script the declaration of my function
}
?>

Of course, when clone PHP functions, always make sure that your functions works entirely like the original ones with the type of arguments you need :-)
zach at bygeekz dot com 20-Sep-2008 06:20
to php at fluidthoughts dot com

you aren't comparing against false, that if compares against true, so it's going to return that, as false != true
true being 1, True, (bool)True, etc.
false being 0, False, Null, etc
<?php

$foo=null;
if ($foo) { echo 'yay'; } //does not echo yay, because null is not True

$foo=false;
if ($foo) { echo 'yay'; } //does not echo yay, because false is not True

$foo=null;
if (!$foo) { echo 'yay'; } //echoes yay!

$foo=false;
if (!$foo) { echo 'yay'; } //echoes yay!

?>

This..
<?php
    if (!function_exists('')) {
                echo "empty string function doesnt exist as compared as negative\n";
        }

        if (!function_exists(NULL)) {
                echo "NULL function doesnt exist as compared as negative\n";
        }
?>
Works.

Alternatively, to enter upon existance..

Use your code. Since they dont exist, it wont enter..
php at fluidthoughts dot com 19-Mar-2008 10:18
function_exists returns false on NULL and empty string:

<?php
        if (function_exists('')) {
                echo "empty string function exists\n";
        }

        if (function_exists(NULL)) {
                echo "NULL function exists\n";
        }
?>

Neither of the echo statements happen when I run this.
jeremiah at jkjonesco dot com 01-Oct-2007 11:56
If you are trying to use this for testing a "function" within a class, then you need to use method_exists().  A "function" within an object is a method, not a function.
webmaster at mamo-net dot de 22-Sep-2007 05:43
If you use suhosin.executor.func.blacklist instead of disabled_functions in your php.ini, function_exists will return true for a disabled function. I used this to have the same beahviour with suhosin.executor.func.blacklist and disabled_functions:

<?php
function suhosin_function_exists($func) {
    if (extension_loaded('suhosin')) {
        $suhosin = @ini_get("suhosin.executor.func.blacklist");
        if (empty($suhosin) == false) {
            $suhosin = explode(',', $suhosin);
            $suhosin = array_map('trim', $suhosin);
            $suhosin = array_map('strtolower', $suhosin);
            return (function_exists($func) == true && array_search($func, $suhosin) === false);
        }
    }
    return function_exists($func);
}
?>
White-Gandalf 13-Sep-2007 07:26
I stumbled over the same problem as "eddiec" (users not able or not willing to use "_once"-suffixes).

A possible alternative explanation for the behavior:

If a file is included, it is possibly parsed every include-time.(?)
While parsing, every function in global scope is tried to register. THIS gets wrong, when multiple times included, and it produces an error.

If functions are defined within block scopes, their registration seems to be delayed until execution of such a block. Thus, not the function "function_exists" functions wrong, but simply the philosophy of the interpreter produces such results.

Thus, the same effect can be achieved by simply putting block braces around the contents of an include_once file:

if (function_exists('function_in_question')) return;
{
    function function_in_question(...)
    {
        ...
    }
    ...other stuff
}

...which is equivalent to...

if (!function_exists('function_in_question'))
{
    function function_in_question(...)
    {
        ...
    }
    ...other stuff
}
dieter at edarta dot be 16-Feb-2007 03:09
to brooklynphil at hotmail dot com:

Your post is misleading, namely the 3rd and last speedtest you describe is an unfair comparison:

<?php
is_callable('test','test');
?>

The value of the 2nd parameter $syntax_only is 'test' and this evaluates to boolean true. In other words, this is exactly the same as calling the function like this:

<?php
is_callable('test',true);
?>

Of course this will be faster because is_callable only does a very basic syntaxcheck. From the documentation: 'It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback.'

If you omit this erroneous 3rd test, then according to your examples function_exists is 2 to 4 times faster.

I hope you can see that loop-testing functions is not so simple. :)

rtfm
eddiec at stararcher dot com 09-Feb-2007 09:58
Note that function_exists will return TRUE in the following situation, presumably because the function "testfunc" was defined when the script was PARSED/ITERPRETED, before the function_exists call was made at RUNTIME:

<?php
if (function_exists('testfunc')) return;
function testfunc() { }
?>

So, this construction is not useful for preventing testfunc from being multiply defined if the script is muliply included or required.

However, the following construction DOES work to prevent multiple defines of testfunc:

<?php
if (!function_exists('testfunc')) {
  function testfunc() { }
}
?>

CONTRAST this with similar uses of defined() which is completely runtime evaluated.  These both work:

<?php
if (defined('testfunc_defined')) return;
define('testfunc_defined', 1);
function testfunc() { }
?>

AND...

<?php
if (!defined('testfunc_defined')) {
define('testfunc_defined', 1);
function testfunc() { }
}
brooklynphil at hotmail dot com 30-Jan-2007 11:02
to bob at thethirdshift dot net
regarding is_callable vs function_exists.

using your code
is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0443360805511 seconds
Did 10000 function_exists in 0.0111110210419 seconds

then we replace
is_callable(array('test','test'));
with
$callarray = array('test','test'); // place this outside for-loop
is_callable($callarray);

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0314660072327 seconds
Did 10000 function_exists in 0.0120670795441 seconds

then we replace
is_callable(array('test','test'));
with
is_callable('test','test');

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.00991606712341 seconds
Did 10000 function_exists in 0.0113790035248 seconds

I hope you can see that loop-testing functions is not so simple. :)
Dan 17-Jul-2006 08:49
I would like to comment on the following post:

A note of caution: function_exists() appears to be case-insensitive (at least as of PHP 4.3.8).  e.g.:

<?php
   function MyCasedFunction() {
       return true;
   }

   // Will return true, even though casing is "wrong"
   if (function_exists("mYcAsEdFuNcTiOn"))
       echo "I see it!";
?>

I believe that function calls itself are case insensitve, so this function is returning a valid truth. PHP doesn't care about cases.
andi at splitbrain dot org 07-Jul-2006 03:48
function_exists will return false for functions disabled with the disable_functions ini directive. However those functions are still declared so trying to define them yourself will fail.

<?php
if(!function_exists('readfile')){
  function readfile($file){
    $handle=@fopen($cache,"r");
    echo @fread($handle,filesize($file));
    @fclose($handle);
  }
}
?>

The above will issue a "Cannot redeclare readfile()" fatal error if readfile was disabled with disable_functions.
neelam_ab2003 at yahoo dot co dot in 11-May-2006 12:06
<?php
/*PHP doesn't Support nested functions. I have tried following in PHP_VERSION - 5.1.2*/

function A(){}

function B(){
    function C(){
        function D(){}
    }
}

IsFunctionExist('A');
IsFunctionExist('B');
IsFunctionExist('C');
IsFunctionExist('D');

function IsFunctionExist($funcName){
    echo function_exists($funcName)?" $funcName exist <br>":" $funcName doesn't exist <br>";
}
?>

/*O U T P U T
A exist
B exist
C doesn't exist
D doesn't exist
*/
chaumo 16-Jul-2005 05:46
to avoid direct calls this can be better than function_exists
in the parent file:
<?php
define("IN_MODULE",true);
?>
and in the target file:
<?php
if(!defined("IN_MODULE")) die("Can't access the file directly");
?>
fili at fili dot nl 08-Jun-2005 09:24
To prevent direct calls to included files i use the following technique.

In the main file create an empty function with a random name. Like so:

<?php
function hjudejdjiwe() { return true; }
?>

Then check for the existence of this function within your include:

<?php
if (!function_exists('hjudejdjiwe')) { die('!'); }
?>

Simple but effective.
bob at thethirdshift dot net 23-Jun-2004 09:55
I, too, was wondering whether is_callable or function exists is faster when checking class methods.  So, I setup the following test:

<?php
function doTimes($start, $end)
  {
    $start_time = explode (" ", $start);
    $start_time = $start_time[1] + $start_time[0];
    $end_time = explode (" ", $end);
    $end_time = $end_time[1] + $end_time[0];
    $time = $end_time - $start_time;
    return $time;
  }

class test
  {
      function test()
      {
          return true;
      }
  }

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(function_exists('test::test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists     = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>function_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 function_exists in ".$timeExists." seconds";
?>

This gives the output :

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0640790462494 seconds
Did 10000 function_exists in 0.0304429531097 seconds

So the fact that function_exists is twice as fast is slightly over shadowed by the fact that it doesn't work on class methods, at least not as far as I can tell.
ckrack at i-z dot de 09-Mar-2004 12:22
i was wondering whether is_callable or function exists is faster when checking class methods.

is_callable(array('foo', 'bar'));
function_exists('foo::bar');

my results when doing each operation 10000 times with a simple test class were the following:

is_callable: 0.28671383857727 seconds
function_exists: 0.14569997787476 seconds

(following tests have proved this to be true).

thus you can see, function_exists is twice as fast as is_callable.
breadman 29-Jul-2003 05:17
Functions within a function are better off as anonymous returns from create_function(), unless you want to be able to call it elsewhere.

However, I have used this in skinning:  I use alert_box() to display certain errors, like a faulty SQL query.  This simply calls display_alert(), which is defined in my skin scripts.  However, alert_box() is sometimes called before I know which skin to load, so it has its own functionality which it uses if function_exists('display_alert') returns false.
dshearin at excite dot com 08-Jul-2003 03:15
This can be used to conditionally define a user function. In this sense, it can act as a sort of inline include_once().

For example, suppose you have a function A that calls function B. B is only used inside function A and is never called from anywhere else in the script. It's logical (and perfectly legal in PHP) to define B inside of A's definition, like so:

<?php
function A($inputArray)
{
   if (!function_exists('B'))
   {
      function B($item)
      {
           // Do something with $item
         // and return result
          return $result;
      }
   }
   foreach ($inputArray as $nextItem) $outputArray[] = B($nextItem);
   return $outputArray;
}
?>

Without the function_exists test, you would get a fatal error the second time you called A, as PHP would think you were trying to redefine B (not legal in PHP). The placement of the test is also important. Since the if block is executed sequentially, like any other block of code, it must come before any call to the function defined within.
func_num_args
get_defined_functions
Управление функциями


Возвращает массив всех определённых функций

function_exists
register_shutdown_function
Управление функциями
PHP Manual

get_defined_functions

(PHP 4 >= 4.0.4, PHP 5)

get_defined_functions — Возвращает массив всех определённых функций

Описание

array get_defined_functions ( void )

Возвращает массив всех определённых функций.

Возвращаемые значения

Эта функция возвращает многомерный массив, содержащий список всех определённых функций, встроенных и пользовательских. Встроенные функции перечислены в элементе массива $arr["internal"], а определенные пользователем - в элементе $arr["user"] (см. пример ниже).

Примеры

Пример #1 Пример использования get_defined_functions()

<?php
function myrow($id, $data)
{
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => myrow
        )

)

Смотрите также

  • function_exists() - Возвращает TRUE, если указанная функция определена
  • get_defined_vars() - Возвращает массив всех определенных переменных
  • get_defined_constants() - Возвращает ассоциативный массив с именами и значениями всех предопределенных констант
  • get_declared_classes() - Возвращает массив с именами объявленных классов

User Contributed Notes

Nguyet.Duc 30-Jul-2011 01:22
get_defined_functions() just returns a list of function names without function arguments. Here is the code to list user-defined function names plus arguments:

<?php
    $content = file_get_contents('example.php');
    preg_match_all("/(function )(\S*\(\S*\))/", $content, $matches);
    foreach($matches[2] as $match) {
        $function[] = "// " . trim($match) . "<br />\n";
    }
    natcasesort($function);
    $functionlist .= "/* Functions in this file */<br />\n";
    $functionlist .= "/**************************/<br />\n\n";
    $functionlist .= implode('', $function);
    echo $functionlist;
?>

Output:

/* Functions in this file */
/**************************/
// add_data($data)
// add_files($list)
// archive($name)
// bzip_file($name)
rob at webdimension dot co dot uk 01-Apr-2011 08:48
A quick way of using this function:

<?php
// ALL USER DEFINED FUNCTIONS
$arr = get_defined_functions();
foreach ($arr['user'] as $key => $value){
echo $value.'<br />';
}
// ALL USER DEFINED FUNCTIONS

// ALL INTERNAL FUNCTIONS
$arr = get_defined_functions();
foreach ($arr['internal'] as $key => $value){
echo $value.'<br />';
}
// ALL INTERNAL FUNCTIONS
?>
gmdebby at gmail dot com 14-Jan-2011 01:28
Note : get_defined_functions return lowercase names on Windows 7 with WampServer 2.1
ChaosKaizer 10-Jul-2008 07:13
for user defined function

<?php
/**
 * @param string $function_name The user function name, as a string.
 * @return Returns TRUE if function_name  exists and is a function, FALSE otherwise.
 */
function user_func_exists($function_name = 'do_action') {

    $func = get_defined_functions();

    $user_func = array_flip($func['user']);

    unset($func);

    return ( isset($user_func[$function_name]) );
}
?>
strrev xc.noxeh@ellij 04-Jun-2008 05:31
Please note that functions created with create_function() are not returned.
(However that might change in a later version)
spudinski at gmail dot com 01-Apr-2008 06:13
To search for a function.
<html>
<head>
<title>List of all Internal functions</title>
<style type="text/css">
body {
    background-color: #FFFFFF;
    color: #222222;
    font-size: 11px;
    font-family: arial, tahoma;
}
table {
    color: #222222;
    font-size: 11px;
    font-family: arial, tahoma;
}
tr.found {
    background-color: #66EE00;
    font-weight: bold;
}
a:link {
    color: #222222;
}
a:visited {
    color: #CCCCCC;
}
a:active {
    color: #444444;
}
a:hover {
    text-decoration: underline;
}
</style>
</head>
<body>
<p>
    <form method="GET">
    Search: <input type="text" name="search"><br>
    <input type="submit">
    </form>
</p>
<?php
    if (!empty($_GET['search'])) {
        echo '<p>' . '<a href="#' . $_GET['search'] . '">' .
        'Goto ' . $_GET['search'] . '</a>' .
        '<script type="text/javascript">
            window.onload = function() {
                document.location += "#' . $_GET['search'] . '";
                return true;
            }
        </script>
        </p>';
    }
?>
<p>
    <table>
<?php
    $country = 'us';
    $functions = get_defined_functions();
    $functions = $functions['internal'];
    $num = 0;
    foreach($functions as $function) {
        $num++;
        echo '<tr ' . (($_GET['search'] == $function) ? 'class="found"' : '') . '><td>' .
        number_format($num) . '</td><td>' . '<a name="' . $function . '" href="http://' . $country . '.php.net/' .
        $function . '">' . $function . '</a>' . '</td></tr>';
    }
?>
    </table>
</p>
</body>
</html>
berchentreff at berchentreff dot de 31-Mar-2006 05:46
look at here, list all the defined function on your php-Version and give as well formatted output width links onto the php-manual:

<html><head>
<style type="text/css"><!--
li{font-family:Verdana,Arail,sans-serif;width:500px;margin-top:7px;}
a{padding:4px;}
a.a1{font-size:12px;background-color:#CCCCCC;color:#663300;}
a.a1:hover{background-color:#663300;color:#CCCCCC;}
a.a1:visited{background-color:#fff;color:#999;}
a.a1:visited:hover{background-color:#fff;color:#999;}
a.a0{font-size:12px;background-color:#CCCCFF;color:#663399;}
a.a0:hover{background-color:#663399;color:#CCCCFF;}
a.a0:visited{background-color:#ffC;color:#999;}
a.a0:visited:hover{background-color:#ffC;color:#999;}
--></style>
</head><body style="background-color:#999;">
<?php
$arr = get_defined_functions();

foreach($arr as $zeile){
sort($zeile);$s=0;
foreach($zeile as $bzeile){
$s=($s)?0:1;
echo "<li><a class='a".$s."'  href='http://de.php.net/".$bzeile."'>".$bzeile."</a></li>";}
}
?>
</body>
</html>
kaneccc at seznam dot cz 27-Mar-2003 04:30
I've written simple XML-RPC server which automatically registers all defined functions starting with "RPC_" prefix and found, that with PHP 2.4.3 on Win32 and Linux platforms function names are in lowercase so the xmlrpc_server_call_method() is case sensitive which is correct with XML, but not with PHP and get_functions_defined()

I also suggest changing the function to have flags/options to return internal, user or both functions only and starting with prefix such as:

<?php
// constants
define( 'xxx_INTERNAL', 0x1 );
define( 'xxx_USER', 0x2 );
define( 'xxx_BOTH', 0x3 );

// declaration
array get_functions_defined( int options, string prefix );
?>

with both arguments optional.

Johnnie
mIHATESPAMduskis at bates dot edu 21-Nov-2002 02:47
At least with PHP 4.2.3 on a GNU/Linux/Apache platform, get_defined_functions() returns user-defined functions as all-lower case strings regardless of how the functions are capitalized when they are defined.

Threw me for a loop.
peten at spam dot me dot not dot frontiernet dot net 02-Jun-2002 10:28
Here's a useful trick with the get_defined_functions function - show all available functions with a link to the documentation (you can even change the mirror it goes to):

<?php
  // the php mirror
  $php_host = "http://us2.php.net/";

  // the number of cols in our table
  $num_cols = 3;

  $ar = get_defined_functions();
  $int_funct = $ar[internal];
  sort($int_funct);
  $count = count($int_funct);
?>
<html>
 <head>
  <title>
   Available PHP Functions
  </title>
 </head>
 <body>
  <p>
   <?php print $count; ?> functions
    available on
    <?php
      print $_SERVER[SERVER_NAME];
     ?>
   (<a href="<?php print $php_host;?>"
    target="phpwin">php</a>
    version
    <?php print phpversion(); ?>)
  </p>
  <table align="center" border="2">
   <tr>
<?php
  for($i=0;$i<$count;$i++) {
    $doc = $php_host
     . "manual/en/function."
     . strtr($int_funct[$i], "_", "-")
     . ".php";
    print "    <td><a href=\"" . $doc
     . "\" target=\"phpwin\">"
     . $int_funct[$i]
     . "</a></td>\n";
    if(($i > 1)
     && (($i+$num_cols)%$num_cols==($num_cols-1)))
      print "   </tr>\n   <tr>\n";
    }
  for($i=($num_cols-($count%$num_cols));$i>0;$i--)
    print "    <td>&nbsp;</td>\n";
?>
  </table>
 </body>
</html>
function_exists
register_shutdown_function
Управление функциями


Регистрирует функцию, которая выполнится по завершении работы скрипта

get_defined_functions
register_tick_function
Управление функциями
PHP Manual

register_shutdown_function

(PHP 4, PHP 5)

register_shutdown_function — Регистрирует функцию, которая выполнится по завершении работы скрипта

Описание

void register_shutdown_function ( callable $callback [, mixed $parameter [, mixed $... ]] )

Регистрирует функцию callback, которая выполнится после завершения работы скрипта или при вызове функции exit().

Возможна регистрация нескольких подобных функций с помощью register_shutdown_function(), при этом функции будут выполняться в том порядке, в каком они были зарегистрированы. Если вы вызовете exit() в одной из зарегистрированных завершающих функций, процесс будет полностью остановлен и последующие завершающие функции не будут вызваны.

Список параметров

callback

Регистрируемая завершающая функция.

Завершающие функции вызываются в течение запроса. Это значит, что из них можно посылать данные на вывод и получать доступ к буферизации вывода.

parameter

Разрешается передавать параметры в завершающую функцию, указав их как дополнительные параметры.

...

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Если передано название несуществующей завершающей функции, то генерируется ошибка уровня E_WARNING.

Список изменений

Версия | Описание
4.1.0 | Зарегистрированные завершающие функции теперь вызываются в течение запроса. В ранних версиях, выполнявшихся в Apache, зарегистрированные завершающие функции вызывались после того, как запрос был полностью завершен (включая отсылку всех буферов вывода), так что было невозможно послать вывод в браузер с помощью echo() или print(), или получить содержимое буферов вывода из ob_get_contents(). Заголовки также уже были посланы к этому моменту.

Примеры

Пример #1 Пример использования register_shutdown_function()

<?php
function shutdown()
{
    // Это наша завершающая функция,
    // здесь мы можем выполнить кое-какую работу
    // перед тем как скрипт полностью завершится.

    echo 'Скрипт успешно завершился', PHP_EOL;
}

register_shutdown_function('shutdown');
?>

Примечания

Замечание:

На некоторых веб-серверах рабочая директория скрипта может измениться внутри завершающей функции, например, Apache.

Смотрите также

  • auto_append_file
  • exit() - Выводит сообщение и прекращает выполнение текущего скрипта
  • Раздел "Обработка соединений"

User Contributed Notes

alexyam at live dot com 08-Apr-2012 03:50
When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()

For example, under nginx and php-fpm 5.3+, this will make browsers wait 10 seconds to show output:

<?php
    echo "You have to wait 10 seconds to see this.<br>";
    register_shutdown_function('shutdown');
    exit;
    function shutdown(){
        sleep(10);
        echo "Because exit() doesn't terminate php-fpm calls immediately.<br>";
    }
?>

This doesn't:

<?php
    echo "You can see this from the browser immediately.<br>";
    fastcgi_finish_request();
    sleep(10);
    echo "You can't see this form the browser.";
?>
david dot schueler at tel-billig dot de 11-Nov-2010 04:51
I had a problem when forking a child process and accessing the variables by using the "global" keyword in the shutdown function.
So i used another way for getting the variables to the shutdown function: I passed them by reference.

Example:
<?php
function shutdown_function (&$test) {
    echo __FUNCTION__.'(): $test = '.$test."\n";
}

$test = 1;
register_shutdown_function('shutdown_function', &$test);
echo '$test = '.$test."\n";

// do some stuff and change the variable values
$test = 2;

// now the shutdown function gets called
exit(0);
?>

Maybe tis helps someone. (I'm using PHP 5.2.11)
emanueledelgrande ad email dot it 19-Sep-2010 07:53
A lot of useful services may be delegated to this useful trigger.
It is very effective because it is executed at the end of the script but before any object destruction, so all instantiations are still alive.

Here's a simple shutdown events manager class which allows to manage either functions or static/dynamic methods, with an indefinite number of arguments without using any reflection, availing on a internal handling through func_get_args() and call_user_func_array() specific functions:

<?php
// managing the shutdown callback events:
class shutdownScheduler {
    private $callbacks; // array to store user callbacks

    public function __construct() {
        $this->callbacks = array();
        register_shutdown_function(array($this, 'callRegisteredShutdown'));
    }
    public function registerShutdownEvent() {
        $callback = func_get_args();

        if (empty($callback)) {
            trigger_error('No callback passed to '.__FUNCTION__.' method', E_USER_ERROR);
            return false;
        }
        if (!is_callable($callback[0])) {
            trigger_error('Invalid callback passed to the '.__FUNCTION__.' method', E_USER_ERROR);
            return false;
        }
        $this->callbacks[] = $callback;
        return true;
    }
    public function callRegisteredShutdown() {
        foreach ($this->callbacks as $arguments) {
            $callback = array_shift($arguments);
            call_user_func_array($callback, $arguments);
        }
    }
    // test methods:
    public function dynamicTest() {
        echo '_REQUEST array is '.count($_REQUEST).' elements long.<br />';
    }
    public static function staticTest() {
        echo '_SERVER array is '.count($_SERVER).' elements long.<br />';
    }
}
?>

A simple application:

<?php
// a generic function
function say($a = 'a generic greeting', $b = '') {
    echo "Saying {$a} {$b}<br />";
}

$scheduler = new shutdownScheduler();

// schedule a global scope function:
$scheduler->registerShutdownEvent('say', 'hello!');

// try to schedule a dyamic method:
$scheduler->registerShutdownEvent(array($scheduler, 'dynamicTest'));
// try with a static call:
$scheduler->registerShutdownEvent('scheduler::staticTest');

?>

It is easy to guess how to extend this example in a more complex context in which user defined functions and methods should be handled according to the priority depending on specific variables.

Hope it may help somebody.
Happy coding!
clover at fromru dot com 01-Jun-2010 02:17
If you register function that needs to be running last (for example, close database connection) - just register another shutdown function from shutdown function:
<?php
function test1(){
  register_shutdown_function('test_last');
}

function test2(){/*...*/}
function test3(){/*...*/}
function test_last(){/*...*/}

register_shutdown_function('test1');
register_shutdown_function('test2');
register_shutdown_function('test3');
?>

the script will call functions in correct order: test1, test2, test3, test_last
sander @ unity-x 12-May-2010 03:42
simple method to disconnect the client and continue processing:

<?php
function endOutput($endMessage){
    ignore_user_abort(true);
    set_time_limit(0);
    header("Connection: close");
    header("Content-Length: ".strlen($endMessage));
    echo $endMessage;
    echo str_repeat("\r\n", 10); // just to be sure
    flush();
}

// Must be called before any output
endOutput("thank you for visiting, have a nice day');

sleep(100);
mail("you@yourmail.com", "ping", "i'm here");
?>
jawsper at aximax dot nl 20-Apr-2010 05:21
Something found out during testing:

the ini auto_append_file will be included BEFORE the registered function(s) will be called.
Anonymous 30-Mar-2010 09:41
Note that in the various solutions presented here, a call to ob_start() at the begining of a script and a flush at the end will defeat any optimisation attempt to return large files in chunks (custom code or readfile). i.e. don't use ob_start if you are going to return large files you will simply bust the memory limit.
ravenswd at gmail dot com 21-Dec-2009 01:43
You may get the idea to call debug_backtrace or debug_print_backtrace from inside a shutdown function, to trace where a fatal error occurred. Unfortunately, these functions will not work inside a shutdown function.
Ant P. 02-Oct-2009 12:13
As of PHP 5.3.0, the last note about unpredictable working directory also applies to FastCGI, when previously it didn't.
Anonymous 17-Sep-2009 05:29
Note that if the handler function is private static it will never be called! It must be public!
michaeln at associationsplus dawt see eh 28-Aug-2009 02:52
This may seem obvious to many people, but don't register an object's __destruct() function as a shutdown function! In many instances, it will then call the destructor twice, most likely on an already destroyed object! For example, you might get this error:

PHP Warning:  mysqli::close() [<a href='function.mysqli-close'>function.mysqli-close</a>]: Couldn't fetch mysqli in /path/to/file.php

I saw docey's comment from 2006 in this very page where they do just that, and this more often than not cause problems!

It would be wise to look out for old code where someone has done that very thing then too!
Filip Dalge 16-Aug-2009 08:35
The following function register_close_function should reproduce the former php behavior of closing the connection before executing the shutdown handler, based on the code posted by sts at mail dot xubion dot hu. It does not work on any machine.

<?php
function register_close_function($func) {
  register_close_function::$func = $func;
  register_shutdown_function(array("register_close_function", "close"));
  ob_start();
}
class register_close_function {
  // just a container
  static $func;
  function close() {
    header("Connection: close");
    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush();
    flush();
    call_user_func(register_close_function::$func);
  }
}
?>
pgl at yoyo dot org 02-Aug-2009 02:25
You definitely need to be careful about using relative paths in after the shutdown function has been called, but the current working directory doesn't (necessarily) get changed to the web server's ServerRoot - I've tested on two different servers and they both have their CWD changed to '/' (which isn't the ServerRoot).

This demonstrates the behaviour:

<?php
function echocwd() { echo 'cwd: ', getcwd(), "\n"; }

register_shutdown_function('echocwd');
echocwd() and exit;
?>

Outputs:

cwd: /path/to/my/site/docroot/test
cwd: /

NB: CLI scripts are unaffected, and keep their CWD as the directory the script was called from.
Bob 30-Jun-2009 10:21
A note about error management.
If you like to use the boolean 'or' operator for error detection, like this:
<?php
register_shutdown_function('my_shutdown_function') or
    throw new Exception("Could not register shutdown function");
?>
it won't work.
This function always returns void which == false, so the exception will *always* be thrown.
Error reporting is integrated into the function.
cFreed at orange dot fr 14-Mar-2009 09:36
May be obvious for most people, but I spent time to clearly understand something which is only INDIRECTLY mentioned by the manual, so I hope this useful for someones.

Pay attention to the function prototype: the $function argument is a callback one (follow the link for more information).
This means that you must write this argument differently depending on the $function context:
. function-name, as a string, when it is a built-in or user-defined function
. array(class-name, method-name), when it is an object method
kwmccabe 12-Nov-2008 10:37
Registered class methods may be public or static (not just static as claimed elsewhere).
<?php
class TEST {
    function TEST() {
        echo __METHOD__ . "<br/>\n";
        register_shutdown_function(array($this, "shutdown_static"), "inside");
        register_shutdown_function(array($this, "shutdown_public"), "inside");
    }
    public function shutdown_public( $param ) {
        echo __METHOD__ . ":param = $param <br/>\n";
    }
    static function shutdown_static( $param ) {
        echo __METHOD__ . ":param = $param <br/>\n";
    }
}

$test = new TEST();
register_shutdown_function(array("TEST","shutdown_static"), "outside");
register_shutdown_function(array($test,"shutdown_public"), "outside");
die("DYING BUT NOT DEAD<br/>\n");
echo "NOTE: shutdown methods called after exit() and even die() <br/>\n";
?>

Output:
TEST::TEST
DYING BUT NOT DEAD
TEST::shutdown_static:param = inside
TEST::shutdown_public:param = inside
TEST::shutdown_static:param = outside
TEST::shutdown_public:param = outside
SonOfTron 05-Oct-2008 06:24
You can achieve similar results by using auto_append_file in the php.ini or .htaccess file:
(php.ini)
auto_append_file = /my-auto-append-file.php
(.htaccess)
php_value auto_append_file /my-auto-append-file.php
RLK 14-Sep-2008 02:26
Contrary to the the note that "headers are always sent" and some of the comments below - You CAN use header() inside of a shutdown function as you would anywhere else; when headers_sent() is false. You can do custom fatal handling this way:

<?php
ini_set('display_errors',0);
register_shutdown_function('shutdown');

$obj = new stdClass();
$obj->method();

function shutdown()
{
  if(!is_null($e = error_get_last()))
  {
    header('content-type: text/plain');
    print "this is not html:\n\n". print_r($e,true);
  }
}
?>
boutell round-about boutell dhot com 29-Nov-2007 05:37
According to tests shown in this comment on the PHP5 deconstructor page:

http://us3.php.net/manual/en/language.oop5.decon.php#76710

Functions registered with register_shutdown_function are called before deconstructors, at least as of PHP 5.2.1. This contradicts an earlier commenter who claims that objects cannot be utilized in functions called from register_shutdown_function. This is good news for those who want to use register_shutdown_function to work around the (fairly nasty) problems with using objects in a session write handler.
dcez at land dot ru 13-Sep-2007 09:57
This simple function (i gues)  is for measuring page generation time in microseconds, using earlier mentioned register_shutdown_function...

Here is an example:

<?php
set_time_limit(0);

function check_time($time_str, $end = false){

    global $start; //Need some global variable where we will ceep our start time

    list($msec, $sec) = explode(' ', $time_str);
    $result = bcadd($msec, $sec, 10);

    if(!$end){

        $start = $result;
        register_shutdown_function('check_time', microtime(), 'true'); //Function registrates itself only with some parametrs now

    }elseif($end){

        $end = $result;
        echo '<br />Page was generated in '.bcsub($end, $start, 10).' seconds...<br />';

    }

}

check_time(microtime()); //Caling our function once!

//Doing some job which we will measure...

$fd = fopen('users.txt', 'r');
while(!feof($fd)){
    $buffer .= fread($fd, 1024);
}
fclose($fd);

?>

As you see may be its large, but you dont have to call "check_time" function twice, in the start and at the end of the script, as many users usually do...
Fuzika 13-Aug-2007 05:27
Sinured's example of how to use a static method did not work for me.
But this did:

<?php
register_shutdown_function(array('theClass','theStaticMethod'));
?>

Hope this helps someone.

[EDIT by danbrown AT php DOT net: This example did not work for the author of this note because it is written for PHP 5.  The author was using PHP 4.]
Sinured 10-Aug-2007 06:26
You can use a static method of a class as a shutdown function without passing an instance. I think that doesn't make too much sense, however it's possible.

<?php
register_shutdown_function('someClass::someMethod');
?>

If this method is *NOT* static, then PHP will complain about an invalid callback instead of just emitting an E_STRICT error.
buraks78 at gmail dot com 01-Jul-2007 05:51
Read the post regarding the change of working directory to ServerRoot carefully. This means that require_once "path/to/script" (or similar constructs) with relative paths will not work in shutdown functions.
Ldkronos 25-Jan-2007 09:55
It's already been discussed on the zlib page ( http://www.php.net/zlib ), but hasn't been mention here...

When zlib compression is enabled, register_shutdown_function doesn't work properly. Anything output from your shutdown function will not be readable by the browser. Firefox just ignores it. IE6 will show you a blank page.

The workaround that worked for me is to add the following to the top of the script.
ini_set('zlib.output_compression', 0);
docey 06-Nov-2006 12:17
if you want to make use of php5 __construct and _destruct functionality this functions is your rescue.

so say you have a class called 'fiveclass', you need some code like this:

<?php
class fiveclass
{

  function fiveclass()
  {
   return $this->__construct(); // forward php4 to __construct
  }

  function __construct()
  {
    // register __destruct method as shutdown function
    register_shutdown_function(array(&$this, "__destruct"));

   return true;
  }

  function __destruct()
  {
    // finish what where doing;
    close_db();
    flush_output();
    write_cache_away();

   return true;
  }

}

$obj = new fiveclass();
?>

now you have the same functionality. __destruct is automaticly called at the end of your script.
morphling at quick dot cz 30-Apr-2006 03:14
There is a note "Shutdown function is called during the script shutdown so headers are always already sent.", but my php 5.1 seems to act differently.
Example:
<?php
class Test {

    private $running;

    public function main() {
        $this->running = true;
        ob_start();
        error_reporting(E_ALL);
        register_shutdown_function(array($this, "clean_exit"));
        echo "Hello";
        // triggers E_ERROR
        $fatal->error();

        $this->running = false;
    }

    public function clean_exit() {
        if ($this->running) {
            header("Location: error.php");
        }
    }
}
$t = new Test();
$t->main();
?>
This example redirects you on error.php, this could be a simple way to handle E_ERROR.
michael at onlinecity dot dk 20-Apr-2006 01:07
Note that under Windows 2003/IIS6 and PHP5 5.1.2 ISAPI the register_shutdown_function executes under IUSR_, regardless of what user the script executes under.
This means that even if you use Application Pools and NETWORK SERVICE as user, shutdown functions will run under the default IIS user.
dweingart at pobox dot com 13-Mar-2006 08:53
I have discovered a change in behavior from PHP 5.0.4 to PHP 5.1.2 when using a shutdown function in conjunction with an output buffering callback.

In PHP 5.0.4 (and earlier versions I believe) the shutdown function is called after the output buffering callback.

In PHP 5.1.2 (not sure when the change occurred) the shutdown function is called before the output buffering callback.

Test code:
<?php
function ob_callback($buf) {
    $buf .= '<li>' . __FUNCTION__ .'</li>';
    return $buf;
}

function shutdown_func() {
    echo '<li>' . __FUNCTION__ .'</li>';
}

ob_start('ob_callback');
register_shutdown_function('shutdown_func');
echo '<ol>';
?>

PHP 5.0.4:

1. ob_callback
2. shutdown_func

PHP 5.1.2:

1. shutdown_func
2. ob_callback
me at thomaskeller dot biz 11-Mar-2006 02:27
Well, it might be obvious, but one should remember that one cannot send any HTTP header in the shutdown callback.

Something like

<?php

function redirect()
{
     header("Location: myuri.php");
}

register_shutdown_function("redirect");

// do something useful here

?>

doesn't work and PHP sends out the popular "headers already sent" warning.

I tried to set a redirection target somewhere in the script, but wanted to make sure that it was only set/executed at the very end of the script, since my custom redirect function also cleaned any output buffers at that point. Well, no luck here =)
kenneth dot kalmer at gmail dot com 27-Jan-2006 09:26
I performed two tests on the register_shutdown_function() to see under what conditions it was called, and if a can call a static method from a class. Here are the results:

<?php
/**
 * Tests the shutdown function being able to call a static methods
 */
class Shutdown
{
    public static function Method ($mixed = 0)
    {
        // we need absolute
        $ap = dirname (__FILE__);
        $mixed = time () . " - $mixed\n";
        file_put_contents ("$ap/shutdown.log", $mixed, FILE_APPEND);
    }
}
// 3. Throw an exception
register_shutdown_function (array ('Shutdown', 'Method'), 'throw');
throw new Exception ('bla bla');

// 2. Use the exit command
//register_shutdown_function (array ('Shutdown', 'Method'), 'exit');
//exit ('exiting here...')

// 1. Exit normally
//register_shutdown_function (array ('Shutdown', 'Method'));
?>

To test simply leave one of the three test lines uncommented and execute. Executing bottom-up yielded:

1138382480 - 0
1138382503 - exit
1138382564 - throw

HTH
sezer yalcin 26-Dec-2005 09:11
re:codeslinger at compsalot dot com

fork() is actually creating 2 processes from one. So there is no surprise register_shutdown_function will be executed per each process.

I think you have reported this as a bug and now in php 5.1.0 when you exit from child process, it does not execute it. Well, what are you going to do if you have something to register for forked process?

I hope php will be more stable near soon!

codeslinger at compsalot dot com
03-Feb-2005 09:22
Here is a nice little surprise to keep in mind...

If you register a shutdown function for your main program.  And then you fork() a child.

Guess What?
When the child exits it will run the code that was intended for the main program.  This can be a really bad thing  ;-)

Happily there is a simple work-around.  All you need to do is to create a global variable such as:

$IamaChild = [TRUE | FALSE];

and have your shutdown function check the value...
http://livejournal.com/~sinde1/ 02-Dec-2005 04:49
If you want to do something with files in function, that registered in register_shutdown_function(), use ABSOLUTE paths to files instead of relative. Because when script processing is complete current working directory chages to ServerRoot (see httpd.conf)
Niels Ganser <php dot comment at depoll dot de> 22-Sep-2005 07:58
Just a quick note: from 5.0.5 on objects will be unloaded _before_ your shutdown function is called which means you can't use previously initiated objects (such as mysqli).

See bug 33772 for more information.
codeslinger at compsalot dot com 03-Feb-2005 09:22
Here is a nice little surprise to keep in mind...

If you register a shutdown function for your main program.  And then you fork() a child.

Guess What?
When the child exits it will run the code that was intended for the main program.  This can be a really bad thing  ;-)

Happily there is a simple work-around.  All you need to do is to create a global variable such as:

$IamaChild = [TRUE | FALSE];

and have your shutdown function check the value...
php at kevin dot offwhite dot net 28-May-2004 02:14
Various commenters have described how this function doesn't work for time-consuming background processing, because the webpage doesn't close the connection.  The workaround using output buffering and header('Connection: close'); seems to work, but the solution I prefer is to put the background processing in a separate script which gets included as a transparent gif.

<?php

  //logger.php -- does the time-consuming log_it() function

  function log_it()
  {
    sleep(12); //simulate long processing
    error_log('log_it() completed');
  }

  error_reporting(0);
  register_shutdown_function('log_it');
  header('Cache-Control: no-cache');
  header('Content-type: image/gif');

  //the size of the unencoded transparent gif
  header('Content-length: 85');

  //1x1 pixel transparent gif
  print base64_decode('R0lGODlhAQABALMAAAAAAIAAAACAA'.
                       'ICAAAAAgIAAgACAgMDAwICAgP8AAA'.
                       'D/AP//AAAA//8A/wD//wBiZCH5BAE'.
                       'AAA8ALAAAAAABAAEAAAQC8EUAOw==');

  flush();
  exit;

?>

@-----------Page you want to add background processing to ---------@
<html>
<body>
<h1>Hello World</h1>

<!-- Call logger.php to do background processing -->
<img src="logger.php" width="1" height="1" border="0" alt="" />

</body>
</html>
@------------------------------------------------------------------@

The only caveat is, of course, if the user has images turned off then the script won't be called.  Tested successfully with IE6, Firefox 0.8, and Opera 7.11
astrolox at lawyersonline dot co dot uk 18-Mar-2004 11:57
When using the register_shutdown_function command in php 4. The registered functions are called in the order that you register them.

This is important to note if you are doing database work using classes that register shutdown functions for themselves.

You must register the shutdown_functions in the order that you want things to shutdown. ( ie the database needs to shutdown last )

Example of what will not work but what you might expect to work :

<?php
class database {

        function database() {
                echo "connect to sql server -- (database :: constructor)<br>\n";
                register_shutdown_function( array( &$this, "phpshutdown" ) );
                $this->connected = 1;
        }

        function do_sql( $sql ) {
                if ( $this->connected == 1 ) {
                        echo "performing sql -- (database :: do_sql)<br>\n";
                } else {
                        echo " ERROR -- CAN NOT PERFORM SQL -- NOT CONNECTED TO SERVER -- (database :: do_sql)<br>\n";
                }
        }

        function phpshutdown() {
                echo "close connection to sql server -- <b>(database :: shutdown)</b><br>\n";
                $this->connected = 0;
        }
}

class table {

        function table( &$database, $name ) {
                $this->database =& $database;
                $this->name = $name;
                echo "read table data using database class -- name=$this->name -- (table :: constructor)<br>\n";
                register_shutdown_function( array( &$this, "phpshutdown" ) );
                $this->database->do_sql( "read table data" );
        }

        function phpshutdown() {
                echo "save changes to database -- name=$this->name -- <b>(table :: shutdown)</b><br>\n";
                $this->database->do_sql( "save table data" );
        }
}

$db =& new database();

$shoppingcard =& new table( &$db, "cart " );
?>

Output of the above example is :-

connect to sql server -- (database :: constructor)
read table data using database class -- name=cart -- (table :: constructor)
performing sql -- (database :: do_sql)
close connection to sql server -- (database :: shutdown)
save changes to database -- name=cart -- (table :: shutdown)
ERROR -- CAN NOT PERFORM SQL -- NOT CONNECTED TO SERVER -- (database :: do_sql)
Jim Smith 15-Mar-2004 04:17
I was trying to figure out how to pass parameters to the register_shutdown_function() since you cannot register a function with parameters and passing through globals is not appropriate. E.g. what I was trying to do was  <? register_shutdown_function("anotherfunction('parameter')") ?>
Turns out, the trick is to use create_function() to create a "function" that calls the desired function with static parameters.

<?php
$funtext="mail('u@ho.com','mail test','sent after shutdown');";
register_shutdown_function(create_function('',$funtext));
?>

Here's another example showing in-line logging and a post-execution version:

Before: in-process logging

<?php
function logit($message) {
   $oF=fopen('TEST.log', 'a');
   fwrite($oF,"$message\n");
   fclose($oF);
   sleep(5);  // so you can see the delay
}
print "loging";
logit("traditional execution");
print "logged";
exit;
?>
After:

<?php
function logit($message) {
   $forlater=create_function('',"loglater('$message');");
   register_shutdown_function($forlater);
}
function loglater($message) {
   $oF=fopen('TEST.log', 'a');
   fwrite($oF,"$message\n");
   fclose($oF);
   sleep(5);  // so you can see the delay
}
print "loging";
logit("delayed execution");
print "logged";
exit;
?>

In the 'before' example, the file is written (and the delay occurs) before the "logged" appears. In the 'after' example, the file is written after execution terminates.

Maybe it would be nice to add a parameter to the register_shutdown_function that does this automatically?
sts at mail dot xubion dot hu 15-Mar-2004 02:56
If you need the old (<4.1) behavior of register_shutdown_function you can achieve the same with "Connection: close" and "Content-Length: xxxx" headers if you know the exact size of the sent data (which can be easily caught with output buffering).
An example:
<?php
header("Connection: close");
ob_start();
phpinfo();
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(13);
error_log("do something in the background");
?>

The same will work with registered functions.
According to http spec, browsers should close the connection when they got the amount of data specified in Content-Length header. At least it works fine for me in IE6 and Opera7.
James Wyse (James [at] tastyspoon.com) 12-Feb-2004 08:49
Just a note to say that if your function uses paths relative to the script you are running (ie. for reading files, "../dir/" etc) then your function may not work correctly when registered as a shutdown function. I'm not sure where the 'working dir' IS when running a shutdown function but I find it best to use absolute paths ("/home/www/dir/").
www dot php dot net at spam dot monnard dot org 01-Dec-2003 10:26
Response to => vbwebprofi at gmx dot de 22-Nov-2003 03:12

You have to do a changement on the object to see the difference between = and =&

Here is your code modified to see the difference.
The modification of the code are essentially the var $Value_changed and the function change().
I have tested it under RedHat 9 with PHP 4.2.2

--8<--- cls_TEST.php --------------------------------------------->8--
<?php
class TEST {
    var $Value;
    var $Value_changed;

    // Constructor

    function TEST($in_Value = 0){
        // Register destructor
        register_shutdown_function(array(&$this, '_TEST'));

        $this->Value = $in_Value;
        $this->Value_changed = $in_Value;
        $this->_Log('TEST');
    }

    // Destructor
    function _TEST() {
        $this->_Log('_TEST');
    }

    // Private function
    function _Log($in_Msg) {
        $oF = fopen('/tmp/TEST.log', 'a');
        fwrite($oF, sprintf("%s : %-5s = %d ; %d\n",
                            date('Y-m-d H:i:s', time()),
                            $in_Msg,
                            $this->Value,
                            $this->Value_changed));
        fclose($oF);
    }

    // Function change()
    function change() {
        $this->Value_changed++;
        $this->_Log('change');
    }
}
?>
--8<--- test_TEST.php -------------------------------------------->8--
<?php
    // include class TEST
    include_once('cls_TEST.php');

    echo "New...<br>\n";
    $o1 =  new TEST(1);
    $o2 =& new TEST(2);
    # Strange declaration :
    $o3 &= new TEST(3);

    echo "Sleep...<br>\n";
    sleep(5);

    echo "Change...<br>\n";
    $o1->change();
    $o2->change();
    # The following line doesn't work !
    #$o3->change();

    echo "Sleep...<br>\n";
    sleep(5);

    echo "End.";
?>
--8<-------------------------------------------------------------->8--

It should produce a content like this in the file, specified in the _Log function :

2003-12-02 04:22:55 : TEST  = 1 ; 1
2003-12-02 04:22:55 : TEST  = 2 ; 2
2003-12-02 04:22:55 : TEST  = 3 ; 3
2003-12-02 04:23:01 : change = 1 ; 2
2003-12-02 04:23:01 : change = 2 ; 3
2003-12-02 04:23:06 : _TEST = 1 ; 1
2003-12-02 04:23:06 : _TEST = 2 ; 3
2003-12-02 04:23:06 : _TEST = 3 ; 3
gabe at websaviour dot com 21-Nov-2003 12:09
It should be noted that register_shutdown_function() does not guarantee that the connection will be closed before executing the function.  In particular on Apache 1.3.27 w/ PHP 4.3.0 on OS X as well as Apache 1.3.22 w/ PHP 4.1.2 on Red Hat I have discovered that Apache does not close the connection until after the registered shutdown function has completed execution.  I am not sure what the circumstances that cause this are, but there is a bug at http://bugs.php.net/bug.php?id=20447

This is important, because as far as I can tell, the documented functionality of register_shutdown_function() is the *ONLY* way to achieve anything resembling asynchronous processing with PHP in a web server environment.  In my mind this is a severe limitation, because if you have some processing intensive task that needs to be done and you want to do it in PHP, there is no way to have it occur without an accompanying wait in a browser window.  Sure you can use ignore_user_abort() to ensure that processing doesn't get cancelled by an impatient user (or impatient browser for that matter), but usability is still compromised.
phpmanual at NO_SPHAMnetebb dot com 15-Nov-2003 08:31
Given this code:

<?php
class CallbackClass {
    function CallbackFunction() {
        // refers to $this
    }

    function StaticFunction() {
        // doesn't refer to $this
    }
}

function NonClassFunction() {
}
?>

there appear to be 3 ways to set a callback function in PHP (using register_shutdown_function() as an example):

1: register_shutdown_function('NonClassFunction');

2: register_shutdown_function(array('CallbackClass', 'StaticFunction'));

3: $o =& new CallbackClass();
   register_shutdown_function(array($o, 'CallbackFunction'));

The following may also prove useful:

<?php
class CallbackClass {
    function CallbackClass() {
        register_shutdown_function(array(&$this, 'CallbackFunction')); // the & is important
    }

    function CallbackFunction() {
        // refers to $this
    }
}
?>
jules at sitepointAASASZZ dot com 01-Jul-2003 12:41
If your script exceeds the maximum execution time, and terminates thusly:

Fatal error: Maximum execution time of 20 seconds exceeded in - on line 12

The registered shutdown functions will still be executed.

I figured it was important that this be made clear!
php at spandex dot deleteme dot nildram dot co dot uk 28-Apr-2003 01:43
I've had immense trouble getting any of the examples of emulated destructors to work.  They always seemed to have a copy of the object just after initialisation.  Many people mention that the register_shutdown_function will take a copy of the object rather than a reference... and this can be cured with an ampersand.  If you look in the PEAR docs for the way they emulate destructors you'll find that you also need one before the "new" statement when you create an instance of your object.  There's an editors note above that mentions this too... but I thought I'd collect it all here in one example that really works.  Honest... I'm using it (PHP 4.3.1):

<?php
class Object {
    var $somevar = "foo";

    function Object() {
        $somevar = "bar";
        register_shutdown_function(array(&$this, 'MyDestructor'));
    }

    function MyDestructor() {
        # Do useful destructor stuff here...
    }
}

# Now create the object as follows and then 'MyDestructor'
# will be called on shutdown and will be able to operate on
# the object as it ended up... not as it started!
$my_object =& new Object;
?>
kwazy at php dot net 29-Jan-2003 07:53
One more note to add about register_shutdown_function and objects.

It is possible to self-register the object from the constructor, but even using the syntax:
register_shutdown_function(array(&$this,'shutdown'))

will only result in the function being called with the object in the "just initialized" state, any changes made to the object after construction will not be there when the script actually exits.

But if you use:

<?php
$obj = new object();
register_shutdown_function(array(&$obj,'shutdown'));
?>

the object method 'shutdown' will be called with the current state of the object intact.

[Editor's note: The explanation for this behavior is really simple.
"$obj = new object()" creates a copy of the object which you can refer with $this in the object's constructor.
To solve this "problem" you should use "$obj = &new object()" which assign the reference to the current object.]
23-Oct-2002 09:35
When using CLI ( and perhaps command line without CLI - I didn't test it) the shutdown function doesn't get called if the process gets a SIGINT or SIGTERM. only the natural exit of PHP calls the shutdown function.
To overcome the problem compile the command line interpreter with --enable-pcntl and add this code:

<?php
function sigint()
{
    exit;
}
pcntl_signal(SIGINT, 'sigint');
pcntl_signal(SIGTERM, 'sigint');
?>

This way when the process recieves one of those signals, it quits normaly, and the shutdown function gets called.
Note: using the pcntl function in web server envoirment is considered problematic, so if you are writing a script that runs both from the command line and from the server, you should put some conditional code around that block that identifies wheater this is a command line envoirment or not.
adam at saki dot com dot au 20-Aug-2002 03:38
When using objects the syntax register_shutdown_function(array($object, 'function')) will take a copy of the object at the time of the call.  This means you cannot do this in the constructor and have it correctly destruct objects.  The alternative is to use register_shutdown_function(array(&$object, 'function')) where the ampersand passes the reference and not the copy.  This appears to work fine.
enygma at phpdeveloper dot org 16-Jul-2002 03:37
I figured I'd share this since I got it working on my box.... this lets you run the "bye" function if the page ends normally or they stop it.

<?php
set_time_limit("0");
function bye(){
    //this is run when the page ends
    if(connection_aborted()){
        //this just means that the user hit the stop button or something
    }
}
register_shutdown_function('bye');
$count=100000000000000;
for($i=0; $i<$count; $i++){
    #sit here and loop for a bit so we can have time to hit Stop...
    echo " \n";
}
echo "end";
?>

I figured it might be useful to someone out there trying to run a function when the page ends (or is stopped).
priebe at mi-corporation dot com 14-Mar-2002 08:25
Note that register_shutdown_function() does not work under Apache on Windows platforms.  Your shutdown function will be called, but the connection will not close until the processing is complete.  Zend tells me that this is due to a difference between Apache for *nix and Apache for Windows.

I'm seeing similar behavior under IIS (using php4isapi).
get_defined_functions
register_tick_function
Управление функциями


Регистрирует функцию для выполнения при каждом тике

register_shutdown_function
unregister_tick_function
Управление функциями
PHP Manual

register_tick_function

(PHP 4 >= 4.0.3, PHP 5)

register_tick_function — Регистрирует функцию для выполнения при каждом тике

Описание

bool register_tick_function ( callable $function [, mixed $arg [, mixed $... ]] )

Регистрирует функцию function, которая должна вызываться при каждом тике.

Список параметров

function

Строка с именем функции, или массив, состоящий из объекта и метода.

arg

...

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования register_tick_function()

<?php
declare(ticks=1);

// using a function as the callback
register_tick_function('my_function', true);

// using an object->method
$object = new my_class();
register_tick_function(array(&$object, 'my_method'), true);
?>

Список изменений

Версия | Описание
5.3.0 | Тики теперь поддерживаются и на потоковых модулях веб-серверов.

Примечания

Внимание

Не используйте register_tick_function() на потоковых модулях веб-серверов с PHP 5.2 и ниже.

Смотрите также

  • declare
  • unregister_tick_function() - Удаляет функцию из списка зарегистрированных для выполнения при каждом тике

User Contributed Notes

rob dot eyre at gmail dot com 22-Jul-2011 05:19
It looks like register_tick_function() can accept an anonymous function, but unregister_tick_function() cannot
Jeremy 21-Jun-2007 11:03
I tried the following on an IIS 6/PHP 5 machine:

<?php

    set_time_limit(0);

    function profiler($return = false)
    {
        static $m = 0;
        if($return) return $m . " bytes";
        if(($mem = memory_get_usage()) > $m) $m = $mem;
    }

    register_tick_function('profiler');
    declare(ticks = 1);

    $numbers = array();
    for($i=0; $i<1000000; $i++)
    {
        print($i . "<br />");
    }

    print(profiler(true));

?>

...and got the following errors:

1) PHP has encountered an Unhandled Exception Code -1073741674 at 0435EC5A
2) PHP has encountered an Access Violation at 02727891
3) PHP has encountered an Access Violation at 02727879
4) PHP has encountered an Access Violation at 00000000

So far the code hasn't crashed the web server, but like the warning says, "register_tick_function() should not be used with threaded web server modules. Ticks are not working in ZTS mode and may crash your web server."

Strangely enough, the code does execute successfully every once in a while.
register_shutdown_function
unregister_tick_function
Управление функциями


Удаляет функцию из списка зарегистрированных для выполнения при каждом тике

register_tick_function
Object Aggregation
Управление функциями
PHP Manual

unregister_tick_function

(PHP 4 >= 4.0.3, PHP 5)

unregister_tick_function — Удаляет функцию из списка зарегистрированных для выполнения при каждом тике

Описание

void unregister_tick_function ( string $function_name )

Удаляет function_name из списка функций, зарегистрированных для выполнения при каждом тике (см. tick).

Список параметров

function_name

Название функции, строка.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • register_tick_function() - Регистрирует функцию для выполнения при каждом тике

User Contributed Notes

rob dot eyre at gmail dot com 22-Jul-2011 05:22
Note that unregister_tick_function() can also accept a callback in the form of an array (either static, like array($className, $methodName) or instance, like array(&$this, $methodName)).

It cannot accept an anonymous function, however.
register_tick_function
Object Aggregation
Управление функциями


Object Aggregation/Composition [PHP 4]

  • Введение
  • Примеры
    • Object Aggregation examples
    • Примеры
  • Object Aggregation Функции
    • aggregate_info — Gets aggregation information for a given object
    • aggregate_methods_by_list — Selective dynamic class methods aggregation to an object
    • aggregate_methods_by_regexp — Selective class methods aggregation to an object using a regular expression
    • aggregate_methods — Dynamic class and object aggregation of methods
    • aggregate_properties_by_list — Selective dynamic class properties aggregation to an object
    • aggregate_properties_by_regexp — Selective class properties aggregation to an object using a regular expression
    • aggregate_properties — Dynamic aggregation of class properties to an object
    • aggregate — Dynamic class and object aggregation of methods and properties
    • aggregation_info — Псевдоним aggregate_info
    • deaggregate — Removes the aggregated methods and properties from an object

User Contributed Notes

There are no user contributed notes for this page.
unregister_tick_function
Введение
Расширения, относящиеся к переменным и типам


Введение

Внимание

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и любую другую относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierarchies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.

User Contributed Notes

There are no user contributed notes for this page.
Object Aggregation
Примеры
Object Aggregation


Примеры

Содержание

  • Object Aggregation examples
  • Примеры

User Contributed Notes

There are no user contributed notes for this page.
Введение
Object Aggregation examples
Object Aggregation


Object Aggregation examples

An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:

Пример #1 Class association

<?php
class MyDateTime {

  function MyDateTime()
  {
      // empty constructor
  }

  function now()
  {
      return date("Y-m-d H:i:s");
  }
}

class Report {
  var $_dt;
  // more properties ...

  function Report()
  {
      $this->_dt = new MyDateTime();
      // initialization code ...
  }

  function generateReport()
  {
      $dateTime = $this->_dt->now();
      // more code ...
  }

  // more methods ...
}

$rep = new Report();
?>
We can also associate instances at runtime by passing a reference in a constructor (or any other method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

Пример #2 Object association

<?php
class MyDateTime {
  // same as previous example
}

class MyDateTimePlus {
  var $_format;

  function MyDateTimePlus($format="Y-m-d H:i:s")
  {
      $this->_format = $format;
  }

  function now()
  {
      return date($this->_format);
  }
}

class Report {
  var $_dt;    // we'll keep the reference to MyDateTime here
  // more properties ...

  function Report()
  {
      // do some initialization
  }

  function setMyDateTime(&$dt)
  {
      $this->_dt =& $dt;
  }

  function generateReport()
  {
      $dateTime = $this->_dt->now();
      // more code ...
  }

  // more methods ...
}

$rep = new Report();
$dt = new MyDateTime();
$dtp = new MyDateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep->setMyDateTime($dt);
echo $rep->generateReport();

// later on in the code ...

// generate report with fancy date
$rep->setMyDateTime($dtp);
$output = $rep->generateReport();
// save $output in database
// ... etc ...
?>

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.

User Contributed Notes

There are no user contributed notes for this page.
Примеры
Примеры
Примеры


Примеры
PHP Manual

Примеры

We define 3 classes, each implementing a different storage method:

Пример #1 storage_classes.inc

<?php
class FileStorage {
   var $data;

   function FileStorage($data)
   {
       $this->data = $data;
   }

   function write($name)
   {
       $fp = fopen(name, "w");
       fwrite($fp, $this->data);
       fclose($data);
   }
}

class WDDXStorage {
   var $data;
   var $version = "1.0";
   var $_id; // "private" variable

   function WDDXStorage($data)
   {
       $this->data = $data;
       $this->_id = $this->_genID();
   }

   function store()
   {
       if ($this->_id) {
           $pid = wddx_packet_start($this->_id);
           wddx_add_vars($pid, "this->data");
           $packet = wddx_packet_end($pid);
       } else {
           $packet = wddx_serialize_value($this->data);
       }
       $dbh = dba_open("varstore", "w", "gdbm");
       dba_insert(md5(uniqid("", true)), $packet, $dbh);
       dba_close($dbh);
   }

   // a private method
   function _genID()
   {
       return md5(uniqid(rand(), true));
   }
}

class DBStorage {
   var $data;
   var $dbtype = "mysql";

   function DBStorage($data)
   {
       $this->data = $data;
   }

   function save()
   {
       $dbh = mysql_connect();
       mysql_select_db("storage", $dbh);
       $serdata = serialize($this->data);
       mysql_query("insert into vars ('$serdata',now())", $dbh);
       mysql_close($dbh);
   }
}

?>

We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

Пример #2 test_aggregation.php

<?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr)
{
   foreach ($arr as $k => $v)
       $out[] = "\t$k => $v";
   return implode("\n", $out);
}

function object_info($obj)
{
   $out[] = "Class: " . get_class($obj);
   foreach (get_object_vars($obj) as $var=>$val) {
       if (is_array($val)) {
           $out[] = "property: $var (array)\n" . p_arr($val);
       } else {
           $out[] = "property: $var = $val";
       }
   }
   foreach (get_class_methods($obj) as $method) {
       $out[] = "method: $method";
   }
   return implode("\n", $out);
}

$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo object_info($fs) . "\n";
echo "\n\$ws object\n";
echo object_info($ws) . "\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

?>

We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The process of aggregation is cumulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

User Contributed Notes

There are no user contributed notes for this page.
Object Aggregation examples
Object Aggregation Функции
Примеры
PHP Manual


Object Aggregation Функции

Содержание

  • aggregate_info — Gets aggregation information for a given object
  • aggregate_methods_by_list — Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp — Selective class methods aggregation to an object using a regular expression
  • aggregate_methods — Dynamic class and object aggregation of methods
  • aggregate_properties_by_list — Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp — Selective class properties aggregation to an object using a regular expression
  • aggregate_properties — Dynamic aggregation of class properties to an object
  • aggregate — Dynamic class and object aggregation of methods and properties
  • aggregation_info — Псевдоним aggregate_info
  • deaggregate — Removes the aggregated methods and properties from an object

User Contributed Notes

kencomer at NOSPAM dot kencomer dot com 20-Sep-2005 09:04
For PHP5 applications, the all of the "aggregate" function family is now in runkit.

  http://php.net/manual/en/ref.runkit.php
Jeb. 17-Jan-2003 02:18
It is worth noting that class association does not work, even in PHP 4.3.0 - this ability is experimental. I'm assuming it was added in for the sake of forwards-compatibilty. Use object association instead for now.

Until it is implemented, you will receieve a parse error when attempting to use it.

Related bug report: http://bugs.php.net/bug.php?id=20531

Just to prevent people posting about "why it doesn't work??", etc etc etc.
Greg Beaver firstname at chiaraquartet dot net 04-Jan-2003 03:54
If you need to serialize an object for sessions or other purposes, and want to save aggregation state, extend it from a base class such as this one, and use $this->agg/$this->unagg instead of aggregate/deaggregate

<?php
class base
{
    var $_aggregates = array();

    function agg($agg)
    {
        aggregate($this,$agg);
        $this->_aggregates[$agg] = 1;
    }

    function unagg($agg = false)
    {
        if ($agg)
        {
             deaggregate($this,$agg);
             unset($this->_aggregates[$agg]);
        } else
        {
             deaggregate($this);
            $this->_aggregates = array();
        }
    }
}
?>
Примеры
aggregate_info
Object Aggregation


Gets aggregation information for a given object

Object Aggregation Функции
aggregate_methods_by_list
Object Aggregation Функции
PHP Manual

aggregate_info

(PHP 4 >= 4.3.0)

aggregate_info — Gets aggregation information for a given object

Описание

array aggregate_info ( object $object )

Gets the aggregation information for the given object.

Список параметров

object

Возвращаемые значения

Returns the aggregation information as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.

Примеры

Пример #1 Using aggregate_info()

<?php

class Slicer {
    var $vegetable;

    function Slicer($vegetable)
    {
        $this->vegetable = $vegetable;
    }

    function slice_it($num_cuts)
    {
        echo "Doing some simple slicing\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some slicing
        }
    }
}

class Dicer {
    var $vegetable;
    var $rotation_angle = 90;   // degrees

    function Dicer($vegetable)
    {
        $this->vegetable = $vegetable;
    }

    function dice_it($num_cuts)
    {
        echo "Cutting in one direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some cutting
        }
        $this->rotate($this->rotation_angle);
        echo "Cutting in a second direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some more cutting
        }
    }

    function rotate($deg)
    {
        echo "Now rotating {$this->vegetable} {$deg} degrees\n";
    }

    function _secret_super_dicing($num_cuts)
    {
        // so secret we cannot show you ;-)
    }
}

$obj = new Slicer('onion');
aggregate($obj, 'Dicer');
print_r(aggregate_info($obj));
?>

Результат выполнения данного примера:

Array
(
    [dicer] => Array
        (
            [methods] => Array
                (
                    [0] => dice_it
                    [1] => rotate
                )

            [properties] => Array
                (
                    [0] => rotation_angle
                )

        )

)
As you can see, all properties and methods of the Dicer class have been aggregated into our new object, with the exception of the class constructor and the method _secret_super_dicing()

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

There are no user contributed notes for this page.
Object Aggregation Функции
aggregate_methods_by_list
Object Aggregation Функции


Selective dynamic class methods aggregation to an object

aggregate_info
aggregate_methods_by_regexp
Object Aggregation Функции
PHP Manual

aggregate_methods_by_list

(PHP 4 >= 4.2.0)

aggregate_methods_by_list — Selective dynamic class methods aggregation to an object

Описание

void aggregate_methods_by_list ( object $object , string $class_name , array $methods_list [, bool $exclude = false ] )

Aggregates methods from a class to an existing object using a list of method names.

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Список параметров

object

class_name

methods_list

exclude

The optional parameter exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

There are no user contributed notes for this page.
aggregate_info
aggregate_methods_by_regexp
Object Aggregation Функции


Selective class methods aggregation to an object using a regular expression

aggregate_methods_by_list
aggregate_methods
Object Aggregation Функции
PHP Manual

aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp — Selective class methods aggregation to an object using a regular expression

Описание

void aggregate_methods_by_regexp ( object $object , string $class_name , string $regexp [, bool $exclude = false ] )

Aggregates methods from a class to an existing object using a regular expression to match method names.

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Список параметров

object

class_name

regexp

exclude

The optional parameter exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

There are no user contributed notes for this page.
aggregate_methods_by_list
aggregate_methods
Object Aggregation Функции


Dynamic class and object aggregation of methods

aggregate_methods_by_regexp
aggregate_properties_by_list
Object Aggregation Функции
PHP Manual

aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods — Dynamic class and object aggregation of methods

Описание

void aggregate_methods ( object $object , string $class_name )

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

Список параметров

object

class_name

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

Rodolfo 12-Sep-2005 03:27
Just a note: aggregate_methods doesn't aggregate those methods already defined in the class, including those methods inherited from a parent class.

Here's an example:

- If class B inherits from class A and aggregates methods from class C:

<?php

class A {
          function foo() {
                echo 'from class A';
          }
}

class B extends A {
    function B() {
         aggregate_methods($this,'C');
    }
}

class C {
          function foo() {
                echo 'from class C';
          }
}

$myclass = new B();
$myclass->foo();
// This will print 'from class A'

?>
a at antialize dot dk 21-Mar-2005 03:12
You can use this to dynamicily add methods to a class

class foo {
  function addMethod(  $code ) {
    $cname = uniqid("class");
    eval( "class ${cname} { ${code} }" );
    aggregate_methods( $this , $cname );
  }

  function bar() {
    $this->addMethod( "function baz() { echo 'sha'; }" );
  }
}

$bang = new foo();
$bang->bar();
$bang->baz();
aggregate_methods_by_regexp
aggregate_properties_by_list
Object Aggregation Функции


Selective dynamic class properties aggregation to an object

aggregate_methods
aggregate_properties_by_regexp
Object Aggregation Функции
PHP Manual

aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list — Selective dynamic class properties aggregation to an object

Описание

void aggregate_properties_by_list ( object $object , string $class_name , array $properties_list [, bool $exclude = false ] )

Aggregates properties from a class to an existing object using a list of property names.

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Список параметров

object

class_name

properties_list

exclude

The optional parameter exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • aggregate_info() - Gets aggregation information for a given object
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

There are no user contributed notes for this page.
aggregate_methods
aggregate_properties_by_regexp
Object Aggregation Функции


Selective class properties aggregation to an object using a regular expression

aggregate_properties_by_list
aggregate_properties
Object Aggregation Функции
PHP Manual

aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp — Selective class properties aggregation to an object using a regular expression

Описание

void aggregate_properties_by_regexp ( object $object , string $class_name , string $regexp [, bool $exclude = false ] )

Aggregates properties from a class to an existing object using a regular expression to match their names.

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Список параметров

object

class_name

regexp

exclude

The optional parameter exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_info() - Gets aggregation information for a given object
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

There are no user contributed notes for this page.
aggregate_properties_by_list
aggregate_properties
Object Aggregation Функции


Dynamic aggregation of class properties to an object

aggregate_properties_by_regexp
aggregate
Object Aggregation Функции
PHP Manual

aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties — Dynamic aggregation of class properties to an object

Описание

void aggregate_properties ( object $object , string $class_name )

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

Список параметров

object

class_name

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties()
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

There are no user contributed notes for this page.
aggregate_properties_by_regexp
aggregate
Object Aggregation Функции


Dynamic class and object aggregation of methods and properties

aggregate_properties
aggregation_info
Object Aggregation Функции
PHP Manual

aggregate

(PHP 4 >= 4.2.0)

aggregate — Dynamic class and object aggregation of methods and properties

Описание

void aggregate ( object $object , string $class_name )

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

Список параметров

object

class_name

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

User Contributed Notes

mail at bealers dot com 20-Nov-2008 10:14
I had to fix someone else's php4 code to work under php5 that was b0rked due to aggregate not working, here's how I did it.

<?php

class shell { }

$classes = array("foo", "bar", "baz");

function php5aggregate($holdingClass, $className)
{
  // use php5 reflection to suss out the method names for the given class
  // http://uk.php.net/manual/en/language.oop5.reflection.php
  $reflect = new ReflectionClass($className);
  foreach ($reflect->getMethods() as $method)
  {
    // copy the method to $holdingClass
    // http://www.php.net/manual/en/function.runkit-method-copy.php
    runkit_method_copy($holdingClass, $method->getName(), $className);
  }
}

if (version_compare(PHP_VERSION, '5.0.0') === 1)
{
  /**
  * aggregate() does not exist in php5, so use our custom function
  * note, our custom aggregate function takes the holding class *name*
  * which is instantiated afterwards, this is different to how the php4 function works
  */
  foreach($classes as $value)
  {
    php5aggregate("shell",$value);
  }

  $shell = new shell;
}
else
{
  // php4
  $shell = new shell;
  foreach($classes as $value)
  {
    aggregate($shell,$value);
  }
}

?>
kencomer at NOSPAM dot kencomer dot com 11-Sep-2005 09:22
For PHP5 applications, the aggregate functionality available through classkit has been incorporated into and replaced by runkit. Per the classkit page of the PHP manual:

"Note:  This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well."

  http://php.net/manual/en/ref.runkit.php

Per the runkit page:

" This package is meant as a feature added replacement for the classkit package. When compiled with the --enable-runkit=classkit  option to ./configure, it will export classkit compatible function definitions and constants."
Matt Barry 28-Mar-2005 12:02
A note for those who may be implementing projects in PHP4 using aggregate(); these functions do not exist in PHP5.  For similar functionality, you can try using the Classkit extension:

http://us2.php.net/manual/en/ref.classkit.php
gmail pfayolle 07-Jan-2005 12:16
Note that even if this can be used to emulate multiple inheritance to some extent, an object in PHP can only be subclass of the class used in the class declaration and no other.

<?php

class A {}
class B {}

class C extends A
{
  function C()
  {
    aggregate($this, 'B'); // emulate multiple inheritance
  }
}

$c = new C;
echo (int)is_subclass_of($c, 'B');

/*
Output: 0
*/

?>
hewei at ied dot org dot cn 02-Mar-2003 03:34
YES you can use aggregation functions to simulate multiple inheritence.

function foo()
{
    aggregate($this, "bar");
    bar::bar();
}
aggregate_properties
aggregation_info
Object Aggregation Функции


Псевдоним aggregate_info

aggregate
deaggregate
Object Aggregation Функции
PHP Manual

aggregation_info

(PHP 4 >= 4.2.0 and < 4.3.0)

aggregation_info — Псевдоним aggregate_info()

Описание

Эта функция является псевдонимом: aggregate_info().

User Contributed Notes

There are no user contributed notes for this page.
aggregate
deaggregate
Object Aggregation Функции


Removes the aggregated methods and properties from an object

aggregation_info
Quickhash
Object Aggregation Функции
PHP Manual

deaggregate

(PHP 4 >= 4.2.0)

deaggregate — Removes the aggregated methods and properties from an object

Описание

void deaggregate ( object $object [, string $class_name ] )

Removes the methods and properties from classes that were aggregated to an object.

Список параметров

object

class_name

If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate()

User Contributed Notes

There are no user contributed notes for this page.
aggregation_info
Quickhash
Object Aggregation Функции


Quickhash

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
  • Предопределенные константы
  • Примеры
  • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntSet::add — This method adds a new entry to the set
    • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
    • QuickHashIntSet::delete — This method deletes an entry from the set
    • QuickHashIntSet::exists — This method checks whether a key is part of the set
    • QuickHashIntSet::getSize — Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
    • QuickHashIntSet::loadFromString — This factory method creates a set from a string
    • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString — This method returns a serialized version of the set
  • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashIntHash::add — This method adds a new entry to the hash
    • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
    • QuickHashIntHash::delete — This method deletes am entry from the hash
    • QuickHashIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize — Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashStringIntHash::add — This method adds a new entry to the hash
    • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
    • QuickHashStringIntHash::delete — This method deletes am entry from the hash
    • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashIntStringHash — The QuickHashIntStringHash class
    • QuickHashIntStringHash::add — This method adds a new entry to the hash
    • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
    • QuickHashIntStringHash::delete — This method deletes am entry from the hash
    • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.
deaggregate
Введение
Расширения, относящиеся к переменным и типам


Введение

The quickhash extension contains a set of specific strongly-typed classes to deal with specific set and hash implementations.

User Contributed Notes

There are no user contributed notes for this page.
Quickhash
Установка и настройка
Quickhash


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Quickhash


Требования

This extension requires no additional libraries.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pecl.php.net/package/quickhash

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Примеры
Quickhash


Примеры

Пример #1 Quickhash Example

<?php
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
$set->add( 1 );
$set->add( 3 );

var_dump( $set->exists( 3 ) );
var_dump( $set->exists( 4 ) );

$set->saveToFile( "/tmp/test-set.set" );

$newSet = QuickHashIntSet::loadFromFile(
    "/tmp/test-set.set"
);

var_dump( $newSet->exists( 3 ) );
var_dump( $newSet->exists( 4 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(false)
bool(true)
bool(false)

Пример #2 Quickhash ArrayAccess Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding and updating hash entries.
$hash[3] = 145926;
$hash[3] = 1415926;
$hash[2] = 72;

// Checking if keys exist
var_dump( isset( $hash[3] ) );

// Removing hash entries
unset( $hash[2] );

// Retrieving the value stored for a hash
echo $hash[3], "\n";
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
1415926

Пример #3 Quickhash Iterator Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding hash entries.
$hash[1] = 145926;
$hash[2] = 1415926;
$hash[3] = 72;
$hash[4] = 712314;
$hash[5] = -4234;

foreach( $hash as $key => $value )
{
    echo $key, ' => ', $value, "\n";
}
?>

Результатом выполнения данного примера будет что-то подобное:

5 => -4234
4 => 712314
1 => 145926
2 => 1415926
3 => 72

Пример #4 Quickhash String Values Example

<?php
$hash = new QuickHashIntStringHash( 64 );

// Adding hash entries.
$hash[1] = "one million four hundred fifteen thousand nine hundred twenty six";
$hash->add( 2, "one more" );1415926;

foreach( $hash as $key => $value )
{
    echo $key, ' => ', $value, "\n";
}
?>

Результатом выполнения данного примера будет что-то подобное:

1 => one million four hundred fifteen thousand nine hundred twenty six
2 => one more

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
QuickHashIntSet
Quickhash


The QuickHashIntSet class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

This class wraps around a set containing integer numbers.

Sets can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Обзор классов

QuickHashIntSet {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public bool add ( int $key )
public __construct ( int $size [, int $options ] )
public bool delete ( int $key )
public bool exists ( int $key )
publicint getSize ( void )
public static QuickHashIntSet loadFromFile ( string $filename [, int $size [, int $options ]] )
public static QuickHashIntSet loadFromString ( string $contents [, int $size [, int $options ]] )
public void saveToFile ( string $filename )
public string saveToString ( void )
}

Предопределенные константы

QuickHashIntSet::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntSet::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntSet::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntSet::HASHER_JENKINS2

Selects a variant hashing algorithm.

Содержание

  • QuickHashIntSet::add — This method adds a new entry to the set
  • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
  • QuickHashIntSet::delete — This method deletes an entry from the set
  • QuickHashIntSet::exists — This method checks whether a key is part of the set
  • QuickHashIntSet::getSize — Returns the number of elements in the set
  • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
  • QuickHashIntSet::loadFromString — This factory method creates a set from a string
  • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
  • QuickHashIntSet::saveToString — This method returns a serialized version of the set

User Contributed Notes

There are no user contributed notes for this page.
Примеры
QuickHashIntSet::add
Quickhash


This method adds a new entry to the set

QuickHashIntSet
QuickHashIntSet::__construct
QuickHashIntSet
PHP Manual

QuickHashIntSet::add

(PECL quickhash >= Unknown)

QuickHashIntSet::add — This method adds a new entry to the set

Описание

public bool QuickHashIntSet::add ( int $key )

This method adds a new entry to the set, and returns whether the entry was added. Entries are by default always added unless QuickHashIntSet::CHECK_FOR_DUPES has been passed when the set was created.

Список параметров

key

The key of the entry to add.

Возвращаемые значения

TRUE when the entry was added, and FALSE if the entry was not added.

Примеры

Пример #1 QuickHashIntSet::add() example

<?php
echo "without dupe checking\n";
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

echo "\nwith dupe checking\n";
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

without dupe checking
bool(false)
bool(true)
bool(true)
bool(true)

with dupe checking
bool(false)
bool(true)
bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet
QuickHashIntSet::__construct
QuickHashIntSet


Creates a new QuickHashIntSet object

QuickHashIntSet::add
QuickHashIntSet::delete
QuickHashIntSet
PHP Manual

QuickHashIntSet::__construct

(PECL quickhash >= Unknown)

QuickHashIntSet::__construct — Creates a new QuickHashIntSet object

Описание

public QuickHashIntSet::__construct ( int $size [, int $options ] )

This constructor creates a new QuickHashIntSet. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Список параметров

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The options that you can pass in are: QuickHashIntSet::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the set; QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntSet::HASHER_NO_HASH, QuickHashIntSet::HASHER_JENKINS1 or QuickHashIntSet::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Возвращаемые значения

Returns a new QuickHashIntSet object.

Примеры

Пример #1 QuickHashIntSet::__construct() example

<?php
var_dump( new QuickHashIntSet( 1024 ) );
var_dump( new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntSet(
        1024,
        QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC | QuickHashIntSet::HASHER_JENKINS2
    )
);
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::add
QuickHashIntSet::delete
QuickHashIntSet


This method deletes an entry from the set

QuickHashIntSet::__construct
QuickHashIntSet::exists
QuickHashIntSet
PHP Manual

QuickHashIntSet::delete

(PECL quickhash >= Unknown)

QuickHashIntSet::delete — This method deletes an entry from the set

Описание

public bool QuickHashIntSet::delete ( int $key )

This method deletes an entry from the set, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the set itself is freed.

Список параметров

key

The key of the entry to delete.

Возвращаемые значения

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Примеры

Пример #1 QuickHashIntSet::delete() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->delete( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->delete( 4 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::__construct
QuickHashIntSet::exists
QuickHashIntSet


This method checks whether a key is part of the set

QuickHashIntSet::delete
QuickHashIntSet::getSize
QuickHashIntSet
PHP Manual

QuickHashIntSet::exists

(PECL quickhash >= Unknown)

QuickHashIntSet::exists — This method checks whether a key is part of the set

Описание

public bool QuickHashIntSet::exists ( int $key )

This method checks whether an entry with the provided key exists in the set.

Список параметров

key

The key of the entry to check for whether it exists in the set.

Возвращаемые значения

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Примеры

Пример #1 QuickHashIntSet::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating set: ", microtime( true ), "\n";
$set = new QuickHashIntSet( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $set->add( $key );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $set->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

Результатом выполнения данного примера будет что-то подобное:

Creating set: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::delete
QuickHashIntSet::getSize
QuickHashIntSet


Returns the number of elements in the set

QuickHashIntSet::exists
QuickHashIntSet::loadFromFile
QuickHashIntSet
PHP Manual

QuickHashIntSet::getSize

(PECL quickhash >= Unknown)

QuickHashIntSet::getSize — Returns the number of elements in the set

Описание

publicint QuickHashIntSet::getSize ( void )

Returns the number of elements in the set.

Список параметров

key

The key of the entry to add.

Возвращаемые значения

The number of elements in the set.

Примеры

Пример #1 QuickHashIntSet::getSize() example

<?php
$set = new QuickHashIntSet( 8 );
var_dump( $set->add( 2 ) );
var_dump( $set->add( 3 ) );
var_dump( $set->getSize() );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::exists
QuickHashIntSet::loadFromFile
QuickHashIntSet


This factory method creates a set from a file

QuickHashIntSet::getSize
QuickHashIntSet::loadFromString
QuickHashIntSet
PHP Manual

QuickHashIntSet::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromFile — This factory method creates a set from a file

Описание

public static QuickHashIntSet QuickHashIntSet::loadFromFile ( string $filename [, int $size [, int $options ]] )

This factory method creates a new set from a definition file on disk. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

Список параметров

filename

The filename of the file to read the set from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two with a maximum limit of 4194304.

Возвращаемые значения

Returns a new QuickHashIntSet.

Примеры

Пример #1 QuickHashIntSet::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.set";
$set = QuickHashIntSet::loadFromFile(
    $file,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $set->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Результатом выполнения данного примера будет что-то подобное:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::getSize
QuickHashIntSet::loadFromString
QuickHashIntSet


This factory method creates a set from a string

QuickHashIntSet::loadFromFile
QuickHashIntSet::saveToFile
QuickHashIntSet
PHP Manual

QuickHashIntSet::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromString — This factory method creates a set from a string

Описание

public static QuickHashIntSet QuickHashIntSet::loadFromString ( string $contents [, int $size [, int $options ]] )

This factory method creates a new set from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

Список параметров

contents

The string containing a serialized format of the set.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two automatically limited from 64 to 4194304.

Возвращаемые значения

Returns a new QuickHashIntSet.

Примеры

Пример #1 QuickHashIntSet::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.set" );
$set = QuickHashIntSet::loadFromString(
    $contents,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $set->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Результатом выполнения данного примера будет что-то подобное:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::loadFromFile
QuickHashIntSet::saveToFile
QuickHashIntSet


This method stores an in-memory set to disk

QuickHashIntSet::loadFromString
QuickHashIntSet::saveToString
QuickHashIntSet
PHP Manual

QuickHashIntSet::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToFile — This method stores an in-memory set to disk

Описание

public void QuickHashIntSet::saveToFile ( string $filename )

This method stores an existing set to a file on disk, in the same format that loadFromFile() can read.

Список параметров

filename

The filename of the file to store the hash in.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 QuickHashIntSet::saveToFile() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

$set->saveToFile( '/tmp/test.set' );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::loadFromString
QuickHashIntSet::saveToString
QuickHashIntSet


This method returns a serialized version of the set

QuickHashIntSet::saveToFile
QuickHashIntHash
QuickHashIntSet
PHP Manual

QuickHashIntSet::saveToString

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToString — This method returns a serialized version of the set

Описание

public string QuickHashIntSet::saveToString ( void )

This method returns a serialized version of the set in the same format that loadFromString() can read.

Возвращаемые значения

This method returns a string containing a serialized format of the set. Each element is stored as a four byte value in the Endianness that the current system uses.

Примеры

Пример #1 QuickHashIntSet::saveToString() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

var_dump( $set->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::saveToFile
QuickHashIntHash
QuickHashIntSet


The QuickHashIntHash class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

This class wraps around a hash containing integer numbers, where the values are also integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Обзор классов

QuickHashIntHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public bool add ( int $key [, int $value ] )
public __construct ( int $size [, int $options ] )
public bool delete ( int $key )
public bool exists ( int $key )
public int get ( int $key )
public int getSize ( void )
public static QuickHashIntHash loadFromFile ( string $filename [, int $options ] )
public static QuickHashIntHash loadFromString ( string $contents [, int $options ] )
public void saveToFile ( string $filename )
public string saveToString ( void )
public bool set ( int $key , int $value )
public bool update ( int $key , int $value )
}

Предопределенные константы

QuickHashIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Содержание

  • QuickHashIntHash::add — This method adds a new entry to the hash
  • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
  • QuickHashIntHash::delete — This method deletes am entry from the hash
  • QuickHashIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntHash::getSize — Returns the number of elements in the hash
  • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntSet::saveToString
QuickHashIntHash::add
Quickhash


This method adds a new entry to the hash

QuickHashIntHash
QuickHashIntHash::__construct
QuickHashIntHash
PHP Manual

QuickHashIntHash::add

(PECL quickhash >= Unknown)

QuickHashIntHash::add — This method adds a new entry to the hash

Описание

public bool QuickHashIntHash::add ( int $key [, int $value ] )

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

Список параметров

key

The key of the entry to add.

value

The optional value of the entry to add. If no value is specified, 1 will be used.

Возвращаемые значения

TRUE when the entry was added, and FALSE if the entry was not added.

Примеры

Пример #1 QuickHashIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 22 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 78 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 9 ) );

echo "\ndefault value\n";
var_dump( $hash->add( 5 ) );
var_dump( $hash->get( 5 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

default value
bool(true)
int(1)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash
QuickHashIntHash::__construct
QuickHashIntHash


Creates a new QuickHashIntHash object

QuickHashIntHash::add
QuickHashIntHash::delete
QuickHashIntHash
PHP Manual

QuickHashIntHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntHash::__construct — Creates a new QuickHashIntHash object

Описание

public QuickHashIntHash::__construct ( int $size [, int $options ] )

This constructor creates a new QuickHashIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Список параметров

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntHash::HASHER_NO_HASH, QuickHashIntHash::HASHER_JENKINS1 or QuickHashIntHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Возвращаемые значения

Returns a new QuickHashIntHash object.

Примеры

Пример #1 QuickHashIntHash::__construct() example

<?php
var_dump( new QuickHashIntHash( 1024 ) );
var_dump( new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntHash(
        1024,
        QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntHash::HASHER_JENKINS2
    )
);
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::add
QuickHashIntHash::delete
QuickHashIntHash


This method deletes am entry from the hash

QuickHashIntHash::__construct
QuickHashIntHash::exists
QuickHashIntHash
PHP Manual

QuickHashIntHash::delete

(PECL quickhash >= Unknown)

QuickHashIntHash::delete — This method deletes am entry from the hash

Описание

public bool QuickHashIntHash::delete ( int $key )

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Список параметров

key

The key of the entry to delete.

Возвращаемые значения

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Примеры

Пример #1 QuickHashIntHash::delete() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 5 ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::__construct
QuickHashIntHash::exists
QuickHashIntHash


This method checks whether a key is part of the hash

QuickHashIntHash::delete
QuickHashIntHash::get
QuickHashIntHash
PHP Manual

QuickHashIntHash::exists

(PECL quickhash >= Unknown)

QuickHashIntHash::exists — This method checks whether a key is part of the hash

Описание

public bool QuickHashIntHash::exists ( int $key )

This method checks whether an entry with the provided key exists in the hash.

Список параметров

key

The key of the entry to check for whether it exists in the hash.

Возвращаемые значения

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Примеры

Пример #1 QuickHashIntHash::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating hash: ", microtime( true ), "\n";
$hash = new QuickHashIntHash( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $hash->add( $key, 56 );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $hash->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

Результатом выполнения данного примера будет что-то подобное:

Creating hash: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::delete
QuickHashIntHash::get
QuickHashIntHash


This method retrieves a value from the hash by its key

QuickHashIntHash::exists
QuickHashIntHash::getSize
QuickHashIntHash
PHP Manual

QuickHashIntHash::get

(PECL quickhash >= Unknown)

QuickHashIntHash::get — This method retrieves a value from the hash by its key

Описание

public int QuickHashIntHash::get ( int $key )

This method retrieves a value from the hash by its key.

Список параметров

key

The key of the entry to add.

Возвращаемые значения

The value if the key exists, or NULL if the key wasn't part of the hash.

Примеры

Пример #1 QuickHashIntHash::get() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2 ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
bool(true)
int(1)
bool(true)
int(5)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::exists
QuickHashIntHash::getSize
QuickHashIntHash


Returns the number of elements in the hash

QuickHashIntHash::get
QuickHashIntHash::loadFromFile
QuickHashIntHash
PHP Manual

QuickHashIntHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntHash::getSize — Returns the number of elements in the hash

Описание

public int QuickHashIntHash::getSize ( void )

Returns the number of elements in the hash.

Список параметров

key

The key of the entry to add.

Возвращаемые значения

The number of elements in the hash.

Примеры

Пример #1 QuickHashIntHash::getSize() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->add( 2 ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::get
QuickHashIntHash::loadFromFile
QuickHashIntHash


This factory method creates a hash from a file

QuickHashIntHash::getSize
QuickHashIntHash::loadFromString
QuickHashIntHash
PHP Manual

QuickHashIntHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromFile — This factory method creates a hash from a file

Описание

public static QuickHashIntHash QuickHashIntHash::loadFromFile ( string $filename [, int $options ] )

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x11\0', the number of elements as a 32 bit signed integer in system Endianness, followed by 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each hash element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key. An example could be:

Пример #1 QuickHash IntHash file format

00000000  51 48 11 00 02 00 00 00  01 00 00 00 01 00 00 00  |QH..............|
00000010  03 00 00 00 09 00 00 00                           |........|
00000018

Пример #2 QuickHash IntHash file format

header signature ('QH'; key type: 1; value type: 1; filler: \0x00)
00000000  51 48 11 00

number of elements:
00000004  02 00 00 00

data string:
00000000  01 00 00 00 01 00 00 00  03 00 00 00 09 00 00 00

key/value 1 (key = 1, value = 1)
01 00 00 00  01 00 00 00

key/value 2 (key = 3, value = 9)
03 00 00 00  09 00 00 00

Список параметров

filename

The filename of the file to read the hash from.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Возвращаемые значения

Returns a new QuickHashIntHash.

Примеры

Пример #3 QuickHashIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash";
$hash = QuickHashIntHash::loadFromFile(
    $file,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Результатом выполнения данного примера будет что-то подобное:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::getSize
QuickHashIntHash::loadFromString
QuickHashIntHash


This factory method creates a hash from a string

QuickHashIntHash::loadFromFile
QuickHashIntHash::saveToFile
QuickHashIntHash
PHP Manual

QuickHashIntHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromString — This factory method creates a hash from a string

Описание

public static QuickHashIntHash QuickHashIntHash::loadFromString ( string $contents [, int $options ] )

This factory method creates a new hash from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key.

Список параметров

contents

The string containing a serialized format of the hash.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Возвращаемые значения

Returns a new QuickHashIntHash.

Примеры

Пример #1 QuickHashIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntHash::loadFromString(
    $contents,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Результатом выполнения данного примера будет что-то подобное:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::loadFromFile
QuickHashIntHash::saveToFile
QuickHashIntHash


This method stores an in-memory hash to disk

QuickHashIntHash::loadFromString
QuickHashIntHash::saveToString
QuickHashIntHash
PHP Manual

QuickHashIntHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk

Описание

public void QuickHashIntHash::saveToFile ( string $filename )

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Список параметров

filename

The filename of the file to store the hash in.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 QuickHashIntHash::saveToFile() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 43 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 52 ) );

$hash->saveToFile( '/tmp/test.hash' );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::loadFromString
QuickHashIntHash::saveToString
QuickHashIntHash


This method returns a serialized version of the hash

QuickHashIntHash::saveToFile
QuickHashIntHash::set
QuickHashIntHash
PHP Manual

QuickHashIntHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToString — This method returns a serialized version of the hash

Описание

public string QuickHashIntHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Возвращаемые значения

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

Примеры

Пример #1 QuickHashIntHash::saveToString() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 34 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 55 ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::saveToFile
QuickHashIntHash::set
QuickHashIntHash


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntHash::saveToString
QuickHashIntHash::update
QuickHashIntHash
PHP Manual

QuickHashIntHash::set

(PECL quickhash >= Unknown)

QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Описание

public bool QuickHashIntHash::set ( int $key , int $value )

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Список параметров

key

The key of the entry to add or update.

value

The new value to set the entry with.

Возвращаемые значения

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Примеры

Пример #1 QuickHashIntHash::set() example

<?php
$hash = new QuickHashIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, 16091 ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, 29906 ) );
var_dump( $hash->get( 46692 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::saveToString
QuickHashIntHash::update
QuickHashIntHash


This method updates an entry in the hash with a new value

QuickHashIntHash::set
QuickHashStringIntHash
QuickHashIntHash
PHP Manual

QuickHashIntHash::update

(PECL quickhash >= Unknown)

QuickHashIntHash::update — This method updates an entry in the hash with a new value

Описание

public bool QuickHashIntHash::update ( int $key , int $value )

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Список параметров

key

The key of the entry to add.

value

The new value to update the entry with.

Возвращаемые значения

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Примеры

Пример #1 QuickHashIntHash::update() example

<?php
$hash = new QuickHashIntHash( 1024 );

var_dump( $hash->add( 141421, 173205 ) );
var_dump( $hash->update( 141421, 223606 ) );
var_dump( $hash->get( 141421 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(true)
int(223606)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::set
QuickHashStringIntHash
QuickHashIntHash


The QuickHashStringIntHash class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

This class wraps around a hash containing strings, where the values are integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Обзор классов

QuickHashStringIntHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
/* Methods */
public bool add ( string $key , int $value )
public __construct ( int $size [, int $options = 0 ] )
public bool delete ( string $key )
public bool exists ( string $key )
public mixed get ( string $key )
public int getSize ( void )
public static QuickHashStringIntHash loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )
public static QuickHashStringIntHash loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )
public void saveToFile ( string $filename )
public string saveToString ( void )
public int set ( string $key , int $value )
public bool update ( string $key , int $value )
}

Предопределенные константы

QuickHashStringIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

Содержание

  • QuickHashStringIntHash::add — This method adds a new entry to the hash
  • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
  • QuickHashStringIntHash::delete — This method deletes am entry from the hash
  • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
  • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntHash::update
QuickHashStringIntHash::add
Quickhash


This method adds a new entry to the hash

QuickHashStringIntHash
QuickHashStringIntHash::__construct
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::add

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::add — This method adds a new entry to the hash

Описание

public bool QuickHashStringIntHash::add ( string $key , int $value )

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashStringIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

Список параметров

key

The key of the entry to add.

value

The value of the entry to add.

Возвращаемые значения

TRUE when the entry was added, and FALSE if the entry was not added.

Примеры

Пример #1 QuickHashStringIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 22 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 78 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 9 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

without dupe checking
object(QuickHashStringIntHash)#1 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
object(QuickHashStringIntHash)#2 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash
QuickHashStringIntHash::__construct
QuickHashStringIntHash


Creates a new QuickHashStringIntHash object

QuickHashStringIntHash::add
QuickHashStringIntHash::delete
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::__construct

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object

Описание

public QuickHashStringIntHash::__construct ( int $size [, int $options = 0 ] )

This constructor creates a new QuickHashStringIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Список параметров

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashStringIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash and QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager.

Возвращаемые значения

Returns a new QuickHashStringIntHash object.

Примеры

Пример #1 QuickHashStringIntHash::__construct() example

<?php
var_dump( new QuickHashStringIntHash( 1024 ) );
var_dump( new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES ) );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::add
QuickHashStringIntHash::delete
QuickHashStringIntHash


This method deletes am entry from the hash

QuickHashStringIntHash::__construct
QuickHashStringIntHash::exists
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::delete

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::delete — This method deletes am entry from the hash

Описание

public bool QuickHashStringIntHash::delete ( string $key )

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Список параметров

key

The key of the entry to delete.

Возвращаемые значения

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Примеры

Пример #1 QuickHashStringIntHash::delete() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->add( 'four', 5 ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
bool(true)
int(5)
bool(true)
bool(false)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::__construct
QuickHashStringIntHash::exists
QuickHashStringIntHash


This method checks whether a key is part of the hash

QuickHashStringIntHash::delete
QuickHashStringIntHash::get
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::exists

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::exists — This method checks whether a key is part of the hash

Описание

public bool QuickHashStringIntHash::exists ( string $key )

This method checks whether an entry with the provided key exists in the hash.

Список параметров

key

The key of the entry to check for whether it exists in the hash.

Возвращаемые значения

Returns TRUE when the entry was found, or FALSE when the entry is not found.

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::delete
QuickHashStringIntHash::get
QuickHashStringIntHash


This method retrieves a value from the hash by its key

QuickHashStringIntHash::exists
QuickHashStringIntHash::getSize
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::get

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::get — This method retrieves a value from the hash by its key

Описание

public mixed QuickHashStringIntHash::get ( string $key )

This method retrieves a value from the hash by its key.

Список параметров

key

The key of the entry to add.

Возвращаемые значения

The value if the key exists, or NULL if the key wasn't part of the hash.

Примеры

Пример #1 QuickHashStringIntHash::get() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->get( "one" ) );

var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->get( "two" ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::exists
QuickHashStringIntHash::getSize
QuickHashStringIntHash


Returns the number of elements in the hash

QuickHashStringIntHash::get
QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::getSize

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::getSize — Returns the number of elements in the hash

Описание

public int QuickHashStringIntHash::getSize ( void )

Returns the number of elements in the hash.

Список параметров

key

The key of the entry to add.

Возвращаемые значения

The number of elements in the hash.

Примеры

Пример #1 QuickHashStringIntHash::getSize() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->add( "three", 5 ) );
var_dump( $hash->getSize() );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::get
QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash


This factory method creates a hash from a file

QuickHashStringIntHash::getSize
QuickHashStringIntHash::loadFromString
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::loadFromFile

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file

Описание

public static QuickHashStringIntHash QuickHashStringIntHash::loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x21\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. The follows another signed 32 bit integer containing the number of bucket lists. After the header and the strings, the elements follow. They are ordered by bucket list so that the keys don't have to be hashed in order to restore the hash. For each bucket list, the following information is stored (all as 32 bit integers): the bucket list index, the number of elements in that list, and then in pairs of two unsigned 32 bit integers the elements, where the first one is the index into the string list containing the keys, and the second one the value. An example could be:

Пример #1 QuickHash StringIntHash file format

00000000  51 48 21 00 02 00 00 00  09 00 00 00 40 00 00 00  |QH!.........@...|
00000010  4f 4e 45 00 4e 49 4e 45  00 07 00 00 00 01 00 00  |ONE.NINE........|
00000020  00 00 00 00 00 01 00 00  00 2f 00 00 00 01 00 00  |........./......|
00000030  00 04 00 00 00 03 00 00  00                       |.........|
00000039

Пример #2 QuickHash IntHash file format

header signature ('QH'; key type: 2; value type: 1; filler: \0x00)
00000000  51 48 21 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

number of hash bucket lists (this is configured for hashes as argument to the
constructor normally, 64 in this case):
0000000C  40 00 00 00

string values:
00000010  4f 4e 45 00 4e 49 4e 45  00

bucket lists:
  bucket list 1 (with key 7, and 1 element):
    header:
    07 00 00 00 01 00 00 00
    elements (key index: 0 ('ONE'), value = 0):
    00 00 00 00 01 00 00 00
  bucket list 2 (with key 0x2f, and 1 element):
    header:
    2f 00 00 00 01 00 00 00
    elements (key index: 4 ('NINE'), value = 3):
    04 00 00 00 03 00 00 00

Список параметров

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is read from the file format (unlike the QuickHashIntHash and QuickHashIntStringHash classes, where it is automatically calculated from the number of entries in the hash.)

Возвращаемые значения

Returns a new QuickHashStringIntHash.

Примеры

Пример #3 QuickHashStringIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash.string";
$hash = QuickHashStringIntHash::loadFromFile(
    $file,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    $i = 48712 + $key * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

Результатом выполнения данного примера будет что-то подобное:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::getSize
QuickHashStringIntHash::loadFromString
QuickHashStringIntHash


This factory method creates a hash from a string

QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash::saveToFile
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::loadFromString

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string

Описание

public static QuickHashStringIntHash QuickHashStringIntHash::loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

Список параметров

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Возвращаемые значения

Returns a new QuickHashStringIntHash.

Примеры

Пример #1 QuickHashStringIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash.string" );
$hash = QuickHashStringIntHash::loadFromString(
    $contents,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    $i = 48712 + $key * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

Результатом выполнения данного примера будет что-то подобное:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash::saveToFile
QuickHashStringIntHash


This method stores an in-memory hash to disk

QuickHashStringIntHash::loadFromString
QuickHashStringIntHash::saveToString
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::saveToFile

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk

Описание

public void QuickHashStringIntHash::saveToFile ( string $filename )

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Список параметров

filename

The filename of the file to store the hash in.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 QuickHashStringIntHash::saveToFile() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

$hash->saveToFile( '/tmp/test.hash.string' );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::loadFromString
QuickHashStringIntHash::saveToString
QuickHashStringIntHash


This method returns a serialized version of the hash

QuickHashStringIntHash::saveToFile
QuickHashStringIntHash::set
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::saveToString

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash

Описание

public string QuickHashStringIntHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Возвращаемые значения

This method returns a serialized format of an existing hash, in the same format that loadFromString() can read.

Примеры

Пример #1 QuickHashStringIntHash::saveToString() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::saveToFile
QuickHashStringIntHash::set
QuickHashStringIntHash


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashStringIntHash::saveToString
QuickHashStringIntHash::update
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::set

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Описание

public int QuickHashStringIntHash::set ( string $key , int $value )

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Список параметров

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Возвращаемые значения

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Примеры

Пример #1 QuickHashStringIntHash::set() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 16091 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );

echo "Set->Update\n";
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 29906 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
?>

Результатом выполнения данного примера будет что-то подобное:

Set->Add
bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::saveToString
QuickHashStringIntHash::update
QuickHashStringIntHash


This method updates an entry in the hash with a new value

QuickHashStringIntHash::set
QuickHashIntStringHash
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::update

(Информация о версии неизвестна, возможно, только в SVN)

QuickHashStringIntHash::update — This method updates an entry in the hash with a new value

Описание

public bool QuickHashStringIntHash::update ( string $key , int $value )

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Список параметров

key

The key of the entry to add.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

Возвращаемые значения

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Примеры

Пример #1 QuickHashStringIntHash::update() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

$hash->add( 'six', 314159265 );
$hash->add( "a lot", 314159265 );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";

var_dump( $hash->update( 'a lot', 314159266 ) );
var_dump( $hash->update( "a lot plus one", 314159999 ) );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";
?>

Результатом выполнения данного примера будет что-то подобное:

314159265
314159265
bool(true)
bool(false)
314159265
314159266

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::set
QuickHashIntStringHash
QuickHashStringIntHash


The QuickHashIntStringHash class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

This class wraps around a hash containing integer numbers, where the values are strings. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Обзор классов

QuickHashIntStringHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public bool add ( int $key , string $value )
public __construct ( int $size [, int $options = 0 ] )
public bool delete ( int $key )
public bool exists ( int $key )
public mixed get ( int $key )
public int getSize ( void )
public static QuickHashIntStringHash loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )
public static QuickHashIntStringHash loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )
public void saveToFile ( string $filename )
public string saveToString ( void )
public int set ( int $key , string $value )
public bool update ( int $key , string $value )
}

Предопределенные константы

QuickHashIntStringHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntStringHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntStringHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntStringHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Содержание

  • QuickHashIntStringHash::add — This method adds a new entry to the hash
  • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
  • QuickHashIntStringHash::delete — This method deletes am entry from the hash
  • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
  • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.
QuickHashStringIntHash::update
QuickHashIntStringHash::add
Quickhash


This method adds a new entry to the hash

QuickHashIntStringHash
QuickHashIntStringHash::__construct
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::add

(PECL quickhash >= Unknown)

QuickHashIntStringHash::add — This method adds a new entry to the hash

Описание

public bool QuickHashIntStringHash::add ( int $key , string $value )

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntStringHash::CHECK_FOR_DUPES has been passed when the hash was created.

Список параметров

key

The key of the entry to add.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Возвращаемые значения

TRUE when the entry was added, and FALSE if the entry was not added.

Примеры

Пример #1 QuickHashIntStringHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twenty two" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twelve" ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "seventy eight" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "nine" ) );
?>

Результатом выполнения данного примера будет что-то подобное:

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(10) "twenty two"
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(13) "seventy eight"
bool(false)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash
QuickHashIntStringHash::__construct
QuickHashIntStringHash


Creates a new QuickHashIntStringHash object

QuickHashIntStringHash::add
QuickHashIntStringHash::delete
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object

Описание

public QuickHashIntStringHash::__construct ( int $size [, int $options = 0 ] )

This constructor creates a new QuickHashIntStringHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Список параметров

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntStringHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntStringHash::HASHER_NO_HASH, QuickHashIntStringHash::HASHER_JENKINS1 or QuickHashIntStringHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Возвращаемые значения

Returns a new QuickHashIntStringHash object.

Примеры

Пример #1 QuickHashIntStringHash::__construct() example

<?php
var_dump( new QuickHashIntStringHash( 1024 ) );
var_dump( new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntStringHash(
        1024,
        QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntStringHash::HASHER_JENKINS2
    )
);
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::add
QuickHashIntStringHash::delete
QuickHashIntStringHash


This method deletes am entry from the hash

QuickHashIntStringHash::__construct
QuickHashIntStringHash::exists
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::delete

(PECL quickhash >= Unknown)

QuickHashIntStringHash::delete — This method deletes am entry from the hash

Описание

public bool QuickHashIntStringHash::delete ( int $key )

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Список параметров

key

The key of the entry to delete.

Возвращаемые значения

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Примеры

Пример #1 QuickHashIntStringHash::delete() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "five" ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::__construct
QuickHashIntStringHash::exists
QuickHashIntStringHash


This method checks whether a key is part of the hash

QuickHashIntStringHash::delete
QuickHashIntStringHash::get
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::exists

(PECL quickhash >= Unknown)

QuickHashIntStringHash::exists — This method checks whether a key is part of the hash

Описание

public bool QuickHashIntStringHash::exists ( int $key )

This method checks whether an entry with the provided key exists in the hash.

Список параметров

key

The key of the entry to check for whether it exists in the hash.

Возвращаемые значения

Returns TRUE when the entry was found, or FALSE when the entry is not found.

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::delete
QuickHashIntStringHash::get
QuickHashIntStringHash


This method retrieves a value from the hash by its key

QuickHashIntStringHash::exists
QuickHashIntStringHash::getSize
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::get

(PECL quickhash >= Unknown)

QuickHashIntStringHash::get — This method retrieves a value from the hash by its key

Описание

public mixed QuickHashIntStringHash::get ( int $key )

This method retrieves a value from the hash by its key.

Список параметров

key

The key of the entry to add.

Возвращаемые значения

The value if the key exists, or NULL if the key wasn't part of the hash.

Примеры

Пример #1 QuickHashIntStringHash::get() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(false)
bool(true)
string(3) "two"
bool(true)
string(1) "5"

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::exists
QuickHashIntStringHash::getSize
QuickHashIntStringHash


Returns the number of elements in the hash

QuickHashIntStringHash::get
QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntStringHash::getSize — Returns the number of elements in the hash

Описание

public int QuickHashIntStringHash::getSize ( void )

Returns the number of elements in the hash.

Возвращаемые значения

The number of elements in the hash.

Примеры

Пример #1 QuickHashIntStringHash::getSize() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::get
QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash


This factory method creates a hash from a file

QuickHashIntStringHash::getSize
QuickHashIntStringHash::loadFromString
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file

Описание

public static QuickHashIntStringHash QuickHashIntStringHash::loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x12\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. After the header and the strings, the elements follow in pairs of two unsigned 32 bit integers where the first one is the key, and the second one the index in the the element data string. An example could be:

Пример #1 QuickHash IntString file format

00000000  51 48 12 00 02 00 00 00  09 00 00 00 4f 4e 45 00  |QH..........ONE.|
00000010  4e 49 4e 45 00 01 00 00  00 00 00 00 00 03 00 00  |NINE............|
00000020  00 04 00 00 00                                    |.....|
00000025

Пример #2 QuickHash IntString file format

header signature ('QH'; key type: 1; value type: 2; filler: \0x00)
00000000  51 48 12 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

string values:
0000000C  4f 4e 45 00 4e 49 4e 45  00

data string:
00000015  01 00 00 00 00 00 00 00  03 00 00 00 04 00 00 00

key/value 1 (key = 1, string index = 0 ("ONE")):
01 00 00 00  00 00 00 00

key/value 2 (key = 3, string index = 4 ("NINE")):
03 00 00 00  04 00 00 00

Список параметров

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Возвращаемые значения

Returns a new QuickHashIntStringHash.

Примеры

Пример #3 QuickHashIntStringHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.string.hash";
$hash = QuickHashIntStringHash::loadFromFile(
    $file,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Результатом выполнения данного примера будет что-то подобное:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::getSize
QuickHashIntStringHash::loadFromString
QuickHashIntStringHash


This factory method creates a hash from a string

QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash::saveToFile
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string

Описание

public static QuickHashIntStringHash QuickHashIntStringHash::loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

Список параметров

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Возвращаемые значения

Returns a new QuickHashIntStringHash.

Примеры

Пример #1 QuickHashIntStringHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntStringHash::loadFromString(
    $contents,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Результатом выполнения данного примера будет что-то подобное:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash::saveToFile
QuickHashIntStringHash


This method stores an in-memory hash to disk

QuickHashIntStringHash::loadFromString
QuickHashIntStringHash::saveToString
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk

Описание

public void QuickHashIntStringHash::saveToFile ( string $filename )

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Список параметров

filename

The filename of the file to store the hash in.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 QuickHashIntStringHash::saveToFile() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fourty three" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fifty two" ) );

$hash->saveToFile( '/tmp/test.string.hash' );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::loadFromString
QuickHashIntStringHash::saveToString
QuickHashIntStringHash


This method returns a serialized version of the hash

QuickHashIntStringHash::saveToFile
QuickHashIntStringHash::set
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash

Описание

public string QuickHashIntStringHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Возвращаемые значения

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

Примеры

Пример #1 QuickHashIntStringHash::saveToString() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "thirty four" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 5, "fifty five" ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::saveToFile
QuickHashIntStringHash::set
QuickHashIntStringHash


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntStringHash::saveToString
QuickHashIntStringHash::update
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::set

(PECL quickhash >= Unknown)

QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Описание

public int QuickHashIntStringHash::set ( int $key , string $value )

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Список параметров

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Возвращаемые значения

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Примеры

Пример #1 QuickHashIntStringHash::set() example

<?php
$hash = new QuickHashIntStringHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, "sixteen thousand ninety one" ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, "twenty nine thousand nine hundred six" ) );
var_dump( $hash->get( 46692 ) );
?>

Результатом выполнения данного примера будет что-то подобное:

Set->Add
bool(false)
int(2)
string(27) "sixteen thousand ninety one"
Set->Update
int(1)
string(37) "twenty nine thousand nine hundred six"

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::saveToString
QuickHashIntStringHash::update
QuickHashIntStringHash


This method updates an entry in the hash with a new value

QuickHashIntStringHash::set
Reflection
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::update

(PECL quickhash >= Unknown)

QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

Описание

public bool QuickHashIntStringHash::update ( int $key , string $value )

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Список параметров

key

The key of the entry to add.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

Возвращаемые значения

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Примеры

Пример #1 QuickHashIntStringHash::update() example

<?php
$hash->add( 161803398, "--" );
$hash->add( 314159265, "a lot" );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";

var_dump( $hash->update( 314159265, "a lot plus one" ) );
var_dump( $hash->update( 314159999, "a lot plus one" ) );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";
?>

Результатом выполнения данного примера будет что-то подобное:

--
a lot
bool(true)
bool(false)
--
a lot plus one

User Contributed Notes

There are no user contributed notes for this page.
QuickHashIntStringHash::set
Reflection
QuickHashIntStringHash


Reflection

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
  • Расширение
  • Reflection — Класс Reflection
    • Reflection::export — Экспортирует Reflection
    • Reflection::getModifierNames — Получение имен модификаторов
  • ReflectionClass — Класс ReflectionClass
    • ReflectionClass::__construct — Создаёт объект класса ReflectionClass
    • ReflectionClass::export — Экспортирует класс
    • ReflectionClass::getConstant — Возвращает определенную константу
    • ReflectionClass::getConstants — Возвращает константы
    • ReflectionClass::getConstructor — Возвращает конструктор
    • ReflectionClass::getDefaultProperties — Возвращает свойства по умолчанию
    • ReflectionClass::getDocComment — Возвращает doc-блоки комментариев
    • ReflectionClass::getEndLine — Возвращает номер последней строки
    • ReflectionClass::getExtension — Возвращает информацию о расширении
    • ReflectionClass::getExtensionName — Возвращает имя расширения
    • ReflectionClass::getFileName — Возвращает имя файла, в котором объявлен класс
    • ReflectionClass::getInterfaceNames — Возвращает имена интерфейсов
    • ReflectionClass::getInterfaces — Возвращает интерфейсы
    • ReflectionClass::getMethod — Возвращает объект класса ReflectionMethod
    • ReflectionClass::getMethods — Возвращает список методов
    • ReflectionClass::getModifiers — Возвращает информацию о модификаторах класса
    • ReflectionClass::getName — Возвращает имя класса
    • ReflectionClass::getNamespaceName — Возвращает название пространства имён
    • ReflectionClass::getParentClass — Возвращает родительский класс
    • ReflectionClass::getProperties — Возвращает свойства
    • ReflectionClass::getProperty — Возвращает свойство
    • ReflectionClass::getShortName — Возвращает короткое имя
    • ReflectionClass::getStartLine — Возвращает номер начальной строки
    • ReflectionClass::getStaticProperties — Возвращает static свойства
    • ReflectionClass::getStaticPropertyValue — Возвращает значение static свойства
    • ReflectionClass::getTraitAliases — Возвращает массив trait-псевдонимов
    • ReflectionClass::getTraitNames — Возвращает массив trait-имён, задействованных в этом классе
    • ReflectionClass::getTraits — Возвращает массив traits, задействованных в этом классе
    • ReflectionClass::hasConstant — Проверяет, задана ли константа
    • ReflectionClass::hasMethod — Проверяет, задан ли метод
    • ReflectionClass::hasProperty — Проверяет, задано ли свойство
    • ReflectionClass::implementsInterface — Проверяет, реализуется ли интерфейс
    • ReflectionClass::inNamespace — Проверяет, определён ли класс в пространстве имён
    • ReflectionClass::isAbstract — Проверяет, является ли класс абстрактным
    • ReflectionClass::isCloneable — Проверяет, можно ли клонировать этот класс
    • ReflectionClass::isFinal — Проверяет, является ли класс окончательным (final)
    • ReflectionClass::isInstance — Проверяет, принадлежит ли объект классу
    • ReflectionClass::isInstantiable — Проверяет, можно ли создать экземпляр класса
    • ReflectionClass::isInterface — Проверяет, является ли класс интерфейсом
    • ReflectionClass::isInternal — Проверяет, является ли класс встроенным
    • ReflectionClass::isIterateable — Проверяет, является ли класс итерируемым
    • ReflectionClass::isSubclassOf — Проверяет, является ли класс подклассом
    • ReflectionClass::isTrait — Проверяет, является ли класс trait
    • ReflectionClass::isUserDefined — Проверяет, является ли класс пользовательским
    • ReflectionClass::newInstance — Создаёт экземпляр класса с переданными аргументами
    • ReflectionClass::newInstanceArgs — Создаёт экземпляр класса с переданными параметрами
    • ReflectionClass::newInstanceWithoutConstructor — Создаёт новый экземпляр класса без вызова конструктора
    • ReflectionClass::setStaticPropertyValue — Устанавливает значение static-свойства
    • ReflectionClass::__toString — Возвращает строковое представление объекта класса ReflectionClass
  • ReflectionZendExtension — Класс ReflectionZendExtension
    • ReflectionZendExtension::__clone — Копирующий конструктор
    • ReflectionZendExtension::__construct — Конструктор
    • ReflectionZendExtension::export — Экспорт
    • ReflectionZendExtension::getAuthor — Получение автора
    • ReflectionZendExtension::getCopyright — Получение строки авторских прав
    • ReflectionZendExtension::getName — Получение строки имени
    • ReflectionZendExtension::getURL — Получение URL
    • ReflectionZendExtension::getVersion — Получение номера версии
    • ReflectionZendExtension::__toString — Преобразование в строку
  • ReflectionExtension — Класс ReflectionExtension
    • ReflectionExtension::__clone — Клонирует объект
    • ReflectionExtension::__construct — Создаёт объект класса ReflectionExtension
    • ReflectionExtension::export — Экспортирует модуль
    • ReflectionExtension::getClasses — Возвращает классы
    • ReflectionExtension::getClassNames — Получение имен классов
    • ReflectionExtension::getConstants — Получение констант
    • ReflectionExtension::getDependencies — Получение зависимостей
    • ReflectionExtension::getFunctions — Получение функций расширения
    • ReflectionExtension::getINIEntries — Получение ini-настроек расширения
    • ReflectionExtension::getName — Получение имени расширения
    • ReflectionExtension::getVersion — Получение версии расширения
    • ReflectionExtension::info — Вывод информации о расширении
    • ReflectionExtension::isPersistent — Определяет, является ли расширение постоянным
    • ReflectionExtension::isTemporary — Определяет, является ли расширение временным
    • ReflectionExtension::__toString — Преобразование в строку
  • ReflectionFunction — Класс ReflectionFunction
    • ReflectionFunction::__construct — Конструктор класса ReflectionFunction
    • ReflectionFunction::export — Экспорт функции
    • ReflectionFunction::getClosure — Возвращает динамически созданное замыкание для функции
    • ReflectionFunction::invoke — Вызывает функцию
    • ReflectionFunction::invokeArgs — Вызов функции с передачей аргументов
    • ReflectionFunction::isDisabled — Проверяет, что функция отключена
    • ReflectionFunction::__toString — Представление в виде строки
  • ReflectionFunctionAbstract — Класс ReflectionFunctionAbstract
    • ReflectionFunctionAbstract::__clone — Копирующий конструктор
    • ReflectionFunctionAbstract::getClosureThis — Возвращает указатель this замыкания
    • ReflectionFunctionAbstract::getDocComment — Получает документируемый комментарий
    • ReflectionFunctionAbstract::getEndLine — Получает номер строки завершения описания функции
    • ReflectionFunctionAbstract::getExtension — Получает информацию о расширении
    • ReflectionFunctionAbstract::getExtensionName — Получение имени расширения
    • ReflectionFunctionAbstract::getFileName — Получает имя файла
    • ReflectionFunctionAbstract::getName — Получает имя функции
    • ReflectionFunctionAbstract::getNamespaceName — Получение имени пространства имен
    • ReflectionFunctionAbstract::getNumberOfParameters — Получает количество аргументов
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Получает количество обязательных аргументов
    • ReflectionFunctionAbstract::getParameters — Получает аргументы
    • ReflectionFunctionAbstract::getShortName — Получает короткое имя функции
    • ReflectionFunctionAbstract::getStartLine — Получает начальный номер строки
    • ReflectionFunctionAbstract::getStaticVariables — Получает статические переменные
    • ReflectionFunctionAbstract::inNamespace — Проверяет, находится ли функция в пространстве имен
    • ReflectionFunctionAbstract::isClosure — Проверяет, является ли функция замыканием
    • ReflectionFunctionAbstract::isDeprecated — Проверяет, является ли функция устаревшей
    • ReflectionFunctionAbstract::isInternal — Проверяет, является ли функция внутренней
    • ReflectionFunctionAbstract::isUserDefined — Проверяет, является ли функция определенной пользователем
    • ReflectionFunctionAbstract::returnsReference — Проверяет, что функция возвращает ссылку
    • ReflectionFunctionAbstract::__toString — Преобразование в строку
  • ReflectionMethod — Класс ReflectionMethod
    • ReflectionMethod::__construct — Конструктор класса ReflectionMethod
    • ReflectionMethod::export — Экспорт отраженного метода
    • ReflectionMethod::getClosure — Возвращает динамически созданное замыкание для метода
    • ReflectionMethod::getDeclaringClass — Получает класс, объявляющий отображенный метод
    • ReflectionMethod::getModifiers — Получает модификаторы метода
    • ReflectionMethod::getPrototype — Получает прототип метода (если такой есть)
    • ReflectionMethod::invoke — Вызов
    • ReflectionMethod::invokeArgs — Вызов метода с передачей аргументов массивом
    • ReflectionMethod::isAbstract — Проверяет, является ли метод абстрактным
    • ReflectionMethod::isConstructor — Проверяет, является ли метод конструктором
    • ReflectionMethod::isDestructor — Проверяет, является ли метод деструктором
    • ReflectionMethod::isFinal — Проверяет, может ли метод иметь наследников (final)
    • ReflectionMethod::isPrivate — Проверяет, является ли метод частным (private)
    • ReflectionMethod::isProtected — Проверяет, является ли метод защищенным (protected)
    • ReflectionMethod::isPublic — Проверяет, является ли метод общедоступным (public)
    • ReflectionMethod::isStatic — Проверяет, является ли метод статическим
    • ReflectionMethod::setAccessible — Делает метод доступным
    • ReflectionMethod::__toString — Возвращает строковое представление объекта Reflection method
  • ReflectionObject — Класс ReflectionObject
    • ReflectionObject::__construct — Конструктор класса ReflectionObject
    • ReflectionObject::export — Экспорт
  • ReflectionParameter — Класс ReflectionParameter
    • ReflectionParameter::allowsNull — Проверяет, допустимо ли значение null для аргумента
    • ReflectionParameter::canBePassedByValue — Проверяет, можно ли передать этот аргумент по значению
    • ReflectionParameter::__clone — Копирующий конструктор
    • ReflectionParameter::__construct — Конструктор класса
    • ReflectionParameter::export — Экспорт
    • ReflectionParameter::getClass — Получение класса
    • ReflectionParameter::getDeclaringClass — Получение объявляющего класса
    • ReflectionParameter::getDeclaringFunction — Получение объявляющей функции
    • ReflectionParameter::getDefaultValue — Получение значения по умолчанию аргумента
    • ReflectionParameter::getName — Получение имени аргумента
    • ReflectionParameter::getPosition — Получение позиции аргумента
    • ReflectionParameter::isArray — Проверяет, ожидает ли аргумент массив в качестве значения
    • ReflectionParameter::isDefaultValueAvailable — Проверяет доступно ли значение по умолчанию аргумента
    • ReflectionParameter::isOptional — Проверка, является ли аргумент необязательным
    • ReflectionParameter::isPassedByReference — Проверяет, что аргумент передан по ссылке
    • ReflectionParameter::__toString — Преобразование в строку
  • ReflectionProperty — Класс ReflectionProperty
    • ReflectionProperty::__clone — Копирующий конструктор
    • ReflectionProperty::__construct — Конструктор класса ReflectionProperty
    • ReflectionProperty::export — Экспорт
    • ReflectionProperty::getDeclaringClass — Получение объявляющего класса
    • ReflectionProperty::getDocComment — Получение документируемого комментария
    • ReflectionProperty::getModifiers — Получение модификаторов
    • ReflectionProperty::getName — Получение имени свойства
    • ReflectionProperty::getValue — Получение значения
    • ReflectionProperty::isDefault — Проверяет, является ли значение свойством по умолчанию
    • ReflectionProperty::isPrivate — Проверяет, является ли свойство частным (private)
    • ReflectionProperty::isProtected — Проверяет, является ли свойство защищенным (protected)
    • ReflectionProperty::isPublic — Проверяет, является ли свойство общедоступным (public)
    • ReflectionProperty::isStatic — Проверка, является ли свойство статическим
    • ReflectionProperty::setAccessible — Задание доступности свойства
    • ReflectionProperty::setValue — Задание значения свойству
    • ReflectionProperty::__toString — Преобразование в строку
  • Reflector — Интерфейс Reflector
    • Reflector::export — Экспорт
    • Reflector::__toString — Представление в виде строки
  • ReflectionException — Класс ReflectionException

User Contributed Notes

Anonymous 26-Aug-2010 09:19
Here is a code snippet for some of us who are just beginning with reflection. I have a simple class below with two properties and two methods. We will use reflection classes to populate the properties dynamically and then print them:

<?php

class A
{
    public $one = '';
    public $two = '';

    //Constructor
    public function __construct()
    {
        //Constructor
    }

    //print variable one
    public function echoOne()
    {
        echo $this->one."\n";
    }

    //print variable two
    public function echoTwo()
    {
        echo $this->two."\n";
    }
}

//Instantiate the object
$a = new A();

//Instantiate the reflection object
$reflector = new ReflectionClass('A');

//Now get all the properties from class A in to $properties array
$properties = $reflector->getProperties();

$i =1;
//Now go through the $properties array and populate each property
foreach($properties as $property)
{
    //Populating properties
    $a->{$property->getName()}=$i;
    //Invoking the method to print what was populated
    $a->{"echo".ucfirst($property->getName())}()."\n";

    $i++;
}

?>
QuickHashIntStringHash::update
Введение
Расширения, относящиеся к переменным и типам


Введение

PHP 5 включает в себя полноценный Reflection API, который предоставляет возможность проводить реверс-инжиниринг реверс-инжиниринг классов, интерфейсов, функций, методов и модулей. Кроме того, Reflection API позволяет получать doc-блоки комментариев функций, классов и методов.

Обратите внимание, что определённая часть внутреннего API не содержит кода, который необходим для работы модуля Reflection. Например, внутренний PHP-класс может не иметь reflection-данных для своих свойств. Однако это известные ошибки и впоследствии такие классы будут исправлены.

User Contributed Notes

There are no user contributed notes for this page.
Reflection
Установка и настройка
Reflection


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Reflection


Предопределенные константы

Каждый класс описывает свои собственные константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
Reflection


Примеры

В документации по Reflection вы сможете встретить множество примеров, чаще всего в описании конструкторов классов.

Пример #1 Пример использования Reflection из shell (Терминала)

$ php --rf strlen
$ php --rc finfo
$ php --re json
$ php --ri dom

Результатом выполнения данного примера будет что-то подобное:

Function [ <internal:Core> function strlen ] {

  - Parameters [1] {
    Parameter #0 [ <required> $str ]
  }
}

Class [ <internal:fileinfo> class finfo ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [4] {
    Method [ <internal:fileinfo, ctor> public method finfo ] {

      - Parameters [2] {
        Parameter #0 [ <optional> $options ]
        Parameter #1 [ <optional> $arg ]
      }
    }

    Method [ <internal:fileinfo> public method set_flags ] {

      - Parameters [1] {
        Parameter #0 [ <required> $options ]
      }
    }

    Method [ <internal:fileinfo> public method file ] {

      - Parameters [3] {
        Parameter #0 [ <required> $filename ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }

    Method [ <internal:fileinfo> public method buffer ] {

      - Parameters [3] {
        Parameter #0 [ <required> $string ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }
  }
}

Extension [ <persistent> extension #23 json version 1.2.1 ] {

  - Constants [10] {
    Constant [ integer JSON_HEX_TAG ] { 1 }
    Constant [ integer JSON_HEX_AMP ] { 2 }
    Constant [ integer JSON_HEX_APOS ] { 4 }
    Constant [ integer JSON_HEX_QUOT ] { 8 }
    Constant [ integer JSON_FORCE_OBJECT ] { 16 }
    Constant [ integer JSON_ERROR_NONE ] { 0 }
    Constant [ integer JSON_ERROR_DEPTH ] { 1 }
    Constant [ integer JSON_ERROR_STATE_MISMATCH ] { 2 }
    Constant [ integer JSON_ERROR_CTRL_CHAR ] { 3 }
    Constant [ integer JSON_ERROR_SYNTAX ] { 4 }
  }

  - Functions {
    Function [ <internal:json> function json_encode ] {

      - Parameters [2] {
        Parameter #0 [ <required> $value ]
        Parameter #1 [ <optional> $options ]
      }
    }
    Function [ <internal:json> function json_decode ] {

      - Parameters [3] {
        Parameter #0 [ <required> $json ]
        Parameter #1 [ <optional> $assoc ]
        Parameter #2 [ <optional> $depth ]
      }
    }
    Function [ <internal:json> function json_last_error ] {

      - Parameters [0] {
      }
    }
  }
}

dom

DOM/XML => enabled
DOM/XML API Version => 20031129
libxml Version => 2.7.3
HTML Support => enabled
XPath Support => enabled
XPointer Support => enabled
Schema Support => enabled
RelaxNG Support => enabled

User Contributed Notes

spectrum at bigmir dot net 28-Dec-2010 02:11
Simple table generation using Reflection:

<?php

class A
{
    public    $name = 'Vasiliy';
    public    $text = 'Once upon a time';
}

class B
{
    public    $name = 'Had bought a cat';
    public    $text = 'named Valentine';
}

class grid
{
    public function build(  $dataSource, $headers, $fields  )
    {
        $result = '<table border="1">';
        $result .= $this -> make_head( $headers );

        foreach ($dataSource as $source):
            $class_name = get_class($source);
            if ( $class_name != FALSE ):
                $reflector = new ReflectionClass($source);
                echo 'Class "'. $class_name .'" found.<br />';
                $result .= $this -> make_row( $reflector, $fields, $source );
            endif;
        endforeach;

        $result .= '</table>';
        return $result;
    }

    private function make_head( $headers )
    {
        $result = '<tr>';
        foreach ( $headers as $header):
            $result .= "<th>$header</th>";
        endforeach;
        $result .= '</tr>';
        return $result;
    }

    private function make_row( $reflector, $fields, $source )
    {
        $result = '<tr>';
        foreach ( $fields as $field ):
            if ( $reflector -> hasProperty($field) ):
                $property = $reflector -> getProperty($field);
                $result .= '<td>'. $property -> getValue($source) .'</td>';
            endif;
        endforeach;
        $result .= '</tr>';
        return $result;
    }
}

$A = new A;
$B = new B;
$C = 'Test';

$dataSource = array( $A, $B, $C );
$headers = array( 'H1', 'H2' );
$fields = array( 'name', 'text' );

$grid = new grid;
$table = $grid -> build( $dataSource, $headers, $fields );
echo $table;

?>
Kovin 18-May-2009 02:00
If you want to use method closures and don't have PHP 5.3, perhaps you find useful the following function
<?php
    function get_method_closure($object,$method_name){
        if(method_exists(get_class($object),$method_name)){
            $func            = create_function( '',
                            '
                                $args            = func_get_args();
                                static $object    = NULL;

                                /*
                                * Check if this function is being called to set the static $object, which
                                * containts scope information to invoke the method
                                */
                                if(is_null($object) && count($args) && get_class($args[0])=="'.get_class($object).'"){
                                    $object = $args[0];
                                    return;
                                }

                                if(!is_null($object)){
                                    return call_user_func_array(array($object,"'.$method_name.'"),$args);
                                }else{
                                    return FALSE;
                                }'
                            );

            //Initialize static $object
            $func($object);

            //Return closure
            return $func;
        }else{
            return false;
        }
    }
?>
Here is how you would use it:
<?php
class foo{
    public function bar($foo){
        return strtolower($foo);
    }
}

$foo = new foo();
$f = get_method_closure($foo,'bar');
echo $f("BAR");//Prints 'bar'
?>
Предопределенные константы
Расширение
Reflection


Расширение

Если вам нужна специализированная версия встроенного класса (который, например, сможет генерировать цветной HTML при экспорте, будет иметь легкодоступные свойства вместо методов или же какие-нибудь вспомогательные методы), то можете просто взять и расширить его.

Пример #1 Расширение встроенных классов

<?php
/**
 * Мой Reflection_Method класс
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = array();

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this->visibility = Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Демо-класс #1
 *
 */
class T {
    protected function x() {}
}

/**
 * Демо-класс #2
 *
 */
class U extends T {
    function x() {}
}

// Выведем информацию о методе
var_dump(new My_Reflection_Method('U', 'x'));
?>

Результатом выполнения данного примера будет что-то подобное:

object(My_Reflection_Method)#1 (3) {
  ["visibility"]=>
  array(1) {
    [0]=>
    string(6) "public"
  }
  ["name"]=>
  string(1) "x"
  ["class"]=>
  string(1) "U"
}
Предостережение

Когда вы переопределяете конструктор, обязательно не забудьте вызвать родительский конструктор до любого добавленного вами кода. Если так не делать, то вы можете получить сообщение об ошибке вида: Fatal error: Internal error: Failed to retrieve the reflection object

User Contributed Notes

khelaz at gmail dot com 28-Apr-2011 11:12
Extending class ReflectionFunction to get source code of function

<?php
class Custom_Reflection_Function extends ReflectionFunction {

    public function getSource() {
        if( !file_exists( $this->getFileName() ) ) return false;

        $start_offset = ( $this->getStartLine() - 1 );
        $end_offset   = ( $this->getEndLine() - $this->getStartLine() ) + 1;

        return join( '', array_slice( file( $this->getFileName() ), $start_offset, $end_offset ) );
    }
}
?>
Примеры
Reflection
Reflection


Класс Reflection

(PHP 5)

Введение

Класс Reflection.

Обзор классов

Reflection {
/* Методы */
public static string export ( Reflector $reflector [, bool $return = false ] )
public static array getModifierNames ( int $modifiers )
}

Содержание

  • Reflection::export — Экспортирует Reflection
  • Reflection::getModifierNames — Получение имен модификаторов

User Contributed Notes

apmithani at yahoo dot com 26-Aug-2010 09:05
Here is a code snippet for some of us who are just beginning with reflection. I have a simple class below with two properties and two methods. We will use reflection classes to populate the properties dynamically and then print them:

<?php

class A
{
    public $one = '';
    public $two = '';

    //Constructor
    public function __construct()
    {
        //Constructor
    }

    //print variable one
    public function echoOne()
    {
        echo $this->one."\n";
    }

    //print variable two
    public function echoTwo()
    {
        echo $this->two."\n";
    }
}

//Instantiate the object
$a = new A();

//Instantiate the reflection object
$reflector = new ReflectionClass('A');

//Now get all the properties from class A in to $properties array
$properties = $reflector->getProperties();

$i =1;
//Now go through the $properties array and populate each property
foreach($properties as $property)
{
    //Populating properties
    $a->{$property->getName()}=$i;
    //Invoking the method to print what was populated
    $a->{"echo".ucfirst($property->getName())}()."\n";

    $i++;
}

?>
Расширение
Reflection::export
Reflection


Экспортирует Reflection

Reflection
Reflection::getModifierNames
Reflection
PHP Manual

Reflection::export

(PHP 5)

Reflection::export — Экспортирует Reflection

Описание

public static string Reflection::export ( Reflector $reflector [, bool $return = false ] )

Экспортирует Reflection.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

reflector

Экспортируемый объект Reflection.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Если параметр return установлен в TRUE, тогда экспортируемый объект будет возвращен как string, иначе будет возвращен NULL.

Смотрите также

  • Reflection::getModifierNames() - Получение имен модификаторов

User Contributed Notes

There are no user contributed notes for this page.
Reflection
Reflection::getModifierNames
Reflection


Получение имен модификаторов

Reflection::export
ReflectionClass
Reflection
PHP Manual

Reflection::getModifierNames

(PHP 5)

Reflection::getModifierNames — Получение имен модификаторов

Описание

public static array Reflection::getModifierNames ( int $modifiers )

Получает имена модификаторов.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

modifiers

Числовые значения модификаторов, имена которых требуется получить.

Возвращаемые значения

Массив имен модификаторов.

Смотрите также

  • Reflection::export() - Экспортирует Reflection

User Contributed Notes

There are no user contributed notes for this page.
Reflection::export
ReflectionClass
Reflection


Класс ReflectionClass

(PHP 5)

Введение

Класс ReflectionClass сообщает информацию о классе.

Обзор классов

ReflectionClass implements Reflector {
/* Константы */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* Свойства */
public $name ;
/* Методы */
__construct ( mixed $argument )
public static string export ( mixed $argument [, bool $return = false ] )
public mixed getConstant ( string $name )
public array getConstants ( void )
public object getConstructor ( void )
public array getDefaultProperties ( void )
public string getDocComment ( void )
public int getEndLine ( void )
public ReflectionExtension getExtension ( void )
public string getExtensionName ( void )
public string getFileName ( void )
public array getInterfaceNames ( void )
public array getInterfaces ( void )
public ReflectionMethod getMethod ( string $name )
public array getMethods ([ string $filter ] )
public int getModifiers ( void )
public string getName ( void )
public string getNamespaceName ( void )
public object getParentClass ( void )
public array getProperties ([ int $filter ] )
public ReflectionProperty getProperty ( string $name )
public string getShortName ( void )
public int getStartLine ( void )
public array getStaticProperties ( void )
public mixed getStaticPropertyValue ( string $name [, string $default ] )
public array getTraitAliases ( void )
public array getTraitNames ( void )
public array getTraits ( void )
public bool hasConstant ( string $name )
public bool hasMethod ( string $name )
public bool hasProperty ( string $name )
public bool implementsInterface ( string $interface )
public bool inNamespace ( void )
public bool isAbstract ( void )
public bool isCloneable ( void )
public bool isFinal ( void )
public bool isInstance ( object $object )
public bool isInstantiable ( void )
public bool isInterface ( void )
public bool isInternal ( void )
public bool isIterateable ( void )
public bool isSubclassOf ( string $class )
public bool isTrait ( void )
public bool isUserDefined ( void )
public object newInstance ( mixed $args [, mixed $... ] )
public object newInstanceArgs ([ array $args ] )
public object newInstanceWithoutConstructor ( void )
public void setStaticPropertyValue ( string $name , string $value )
public string __toString ( void )
}

Свойства

name

Имя класса. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

Предопределенные константы

Модификаторы ReflectionClass

ReflectionClass::IS_IMPLICIT_ABSTRACT

Указывает, что класс является абстрактным, потому что он содержит абстрактные методы.

ReflectionClass::IS_EXPLICIT_ABSTRACT

Указывает, что класс является абстрактным, потому что так указано при его описании.

ReflectionClass::IS_FINAL

Указывает, что класс является окончательным (final) class.

Содержание

  • ReflectionClass::__construct — Создаёт объект класса ReflectionClass
  • ReflectionClass::export — Экспортирует класс
  • ReflectionClass::getConstant — Возвращает определенную константу
  • ReflectionClass::getConstants — Возвращает константы
  • ReflectionClass::getConstructor — Возвращает конструктор
  • ReflectionClass::getDefaultProperties — Возвращает свойства по умолчанию
  • ReflectionClass::getDocComment — Возвращает doc-блоки комментариев
  • ReflectionClass::getEndLine — Возвращает номер последней строки
  • ReflectionClass::getExtension — Возвращает информацию о расширении
  • ReflectionClass::getExtensionName — Возвращает имя расширения
  • ReflectionClass::getFileName — Возвращает имя файла, в котором объявлен класс
  • ReflectionClass::getInterfaceNames — Возвращает имена интерфейсов
  • ReflectionClass::getInterfaces — Возвращает интерфейсы
  • ReflectionClass::getMethod — Возвращает объект класса ReflectionMethod
  • ReflectionClass::getMethods — Возвращает список методов
  • ReflectionClass::getModifiers — Возвращает информацию о модификаторах класса
  • ReflectionClass::getName — Возвращает имя класса
  • ReflectionClass::getNamespaceName — Возвращает название пространства имён
  • ReflectionClass::getParentClass — Возвращает родительский класс
  • ReflectionClass::getProperties — Возвращает свойства
  • ReflectionClass::getProperty — Возвращает свойство
  • ReflectionClass::getShortName — Возвращает короткое имя
  • ReflectionClass::getStartLine — Возвращает номер начальной строки
  • ReflectionClass::getStaticProperties — Возвращает static свойства
  • ReflectionClass::getStaticPropertyValue — Возвращает значение static свойства
  • ReflectionClass::getTraitAliases — Возвращает массив trait-псевдонимов
  • ReflectionClass::getTraitNames — Возвращает массив trait-имён, задействованных в этом классе
  • ReflectionClass::getTraits — Возвращает массив traits, задействованных в этом классе
  • ReflectionClass::hasConstant — Проверяет, задана ли константа
  • ReflectionClass::hasMethod — Проверяет, задан ли метод
  • ReflectionClass::hasProperty — Проверяет, задано ли свойство
  • ReflectionClass::implementsInterface — Проверяет, реализуется ли интерфейс
  • ReflectionClass::inNamespace — Проверяет, определён ли класс в пространстве имён
  • ReflectionClass::isAbstract — Проверяет, является ли класс абстрактным
  • ReflectionClass::isCloneable — Проверяет, можно ли клонировать этот класс
  • ReflectionClass::isFinal — Проверяет, является ли класс окончательным (final)
  • ReflectionClass::isInstance — Проверяет, принадлежит ли объект классу
  • ReflectionClass::isInstantiable — Проверяет, можно ли создать экземпляр класса
  • ReflectionClass::isInterface — Проверяет, является ли класс интерфейсом
  • ReflectionClass::isInternal — Проверяет, является ли класс встроенным
  • ReflectionClass::isIterateable — Проверяет, является ли класс итерируемым
  • ReflectionClass::isSubclassOf — Проверяет, является ли класс подклассом
  • ReflectionClass::isTrait — Проверяет, является ли класс trait
  • ReflectionClass::isUserDefined — Проверяет, является ли класс пользовательским
  • ReflectionClass::newInstance — Создаёт экземпляр класса с переданными аргументами
  • ReflectionClass::newInstanceArgs — Создаёт экземпляр класса с переданными параметрами
  • ReflectionClass::newInstanceWithoutConstructor — Создаёт новый экземпляр класса без вызова конструктора
  • ReflectionClass::setStaticPropertyValue — Устанавливает значение static-свойства
  • ReflectionClass::__toString — Возвращает строковое представление объекта класса ReflectionClass

User Contributed Notes

Anonymous 11-Nov-2011 09:58
Unserialized reflection class cause error.

<?php
/**
 * abc
 */
class a{}

$ref = new ReflectionClass('a');
$ref = unserialize(serialize($ref));
var_dump($ref);
var_dump($ref->getDocComment());

// object(ReflectionClass)#2 (1) {
//   ["name"]=>
//   string(1) "a"
// }
// PHP Fatal error:  ReflectionClass::getDocComment(): Internal error: Failed to retrieve the reflection object
?>
thecelavi at gmail dot com 30-Nov-2009 04:07
Right:

<?php
use AppCore as Core;
$oReflectionClass = new ReflectionClass('App\Core\Singleton');
?>

Wrong:

<?php
use AppCore as Core;
$oReflectionClass = new ReflectionClass('\App\Core\Singleton');
?>
danbettles at yahoo dot co dot uk 29-Mar-2009 02:48
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.

So instead of:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('Core\Singleton');
?>

You would type:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('App\Core\Singleton');
?>
Reflection::getModifierNames
ReflectionClass::__construct
Reflection


Создаёт объект класса ReflectionClass

ReflectionClass
ReflectionClass::export
ReflectionClass
PHP Manual

ReflectionClass::__construct

(PHP 5)

ReflectionClass::__construct — Создаёт объект класса ReflectionClass

Описание

ReflectionClass::__construct ( mixed $argument )

Создаёт новый объект класса ReflectionClass.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

argument

В качестве аргумента может принимать строку (string), содержащую имя исследуемого класса, либо объект (object).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Простой пример использования ReflectionClass

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

Результатом выполнения данного примера будет что-то подобное:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

Смотрите также

  • ReflectionObject::__construct() - Конструктор класса ReflectionObject
  • Конструкторы

User Contributed Notes

gafisher at griasolutions dot com 30-Jan-2012 01:23
Running the following code on Windows Vista (I know, I know), PHP 5.3.9, the ReflectionClass constructor actually throws a ReflectionException when the desired class cannot be instantiated:

<?php
    try {
        $ReflectedClass = new ReflectionClass('NonExist');
    } catch (LogicException $Exception) {
        die('Not gonna make it in here...');
    } catch (ReflectionException $Exception) {
        die('Your class does not exist!');
    }
?>
cspray at gmail dot com 12-Jun-2011 07:14
Useful to know that if you pass a string into the construct and the class cannot be instantiated for some reason a SPL LogicException will be thrown.

This code was ran on a Mac OS X 10.6.7, AMP, PHP 5.3+

<?php

    //  index.php
    try {
        $ReflectedClass = new ReflectionClass('NonExist');
    } catch (LogicException $logicDuh) {
        print_r($logicDuh);
    }

?>

Will return a deeply nested array full of useful information about the error.
ivo at jansch dot nl 24-Jan-2010 04:16
It's very useful to know that you can also use the ReflectionClass to inspect interfaces, even thouth Interfaces are not classes. Example:

<?php

  interface Edible
  {
    public function eat();
  }

  $refl = new ReflectionClass("Edible");
  $methods = $refl->getMethods();
?>

[Edit by danbrown AT php DOT net - Contains a bugfix by (dbl AT bnet DOT com) on 18-AUG-2010 with the following message: "underline had to be removed for it to work ( new Reflection_Class -> new ReflectionClass )"]
ReflectionClass
ReflectionClass::export
ReflectionClass


Экспортирует класс

ReflectionClass::__construct
ReflectionClass::getConstant
ReflectionClass
PHP Manual

ReflectionClass::export

(PHP 5)

ReflectionClass::export — Экспортирует класс

Описание

public static string ReflectionClass::export ( mixed $argument [, bool $return = false ] )

Экспортирует reflected (отражённый) класс.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

argument

Экспортируемый объект Reflection.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Если параметр return установлен в TRUE, тогда экспортируемый объект будет возвращен как string, иначе будет возвращен NULL.

Смотрите также

  • ReflectionClass::getName() - Возвращает имя класса

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::__construct
ReflectionClass::getConstant
ReflectionClass


Возвращает определенную константу

ReflectionClass::export
ReflectionClass::getConstants
ReflectionClass
PHP Manual

ReflectionClass::getConstant

(PHP 5)

ReflectionClass::getConstant — Возвращает определенную константу

Описание

public mixed ReflectionClass::getConstant ( string $name )

Возвращает определенную константу.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

name

Имя константы.

Возвращаемые значения

Значение константы.

Смотрите также

  • ReflectionClass::getConstants() - Возвращает константы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::export
ReflectionClass::getConstants
ReflectionClass


Возвращает константы

ReflectionClass::getConstant
ReflectionClass::getConstructor
ReflectionClass
PHP Manual

ReflectionClass::getConstants

(PHP 5)

ReflectionClass::getConstants — Возвращает константы

Описание

public array ReflectionClass::getConstants ( void )

Возвращает определённые в классе константы.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив (array) констант. Имя константы - ключ, значение константы - значение.

Смотрите также

  • ReflectionClass::getConstant() - Возвращает определенную константу

User Contributed Notes

djhob1972 at yahoo dot com dot au 16-Dec-2009 05:42
I was trying to determine how to get a var_dump of constants that are within an interface.  Thats right, not using any classes but the interface itself.

Along my travels I found it quite interesting that the ReflectionClass along with a direct call to the interface will also dump its constants.  Perfect!!!!

This was using PHP 5.3.1 and my example as below:-

1st File:

constants.php

<?php
<?php>

interface MyConstants
{
    // --------------------------
    // Programmatic Level
    // --------------------------
    const DEBUG_MODE_ACTIVE       = FALSE;
    const PHP_VERSION_REQUIREMENT = "5.1.2";
}
?>

=======
Second file:
=======

test.php

<?php>
include_once ("constants.php");

$oClass = new ReflectionClass ('MyConstants');
$array = $oClass->getConstants ();
var_dump ($array);
unset ($oClass);
?>

what you would get from the command line:-

?:\???\htdocs\????>php test.php
array(2) {
  ["DEBUG_MODE_ACTIVE"]=> bool(false)
  ["PHP_VERSION_REQUIREMENT"]=> string(5) "5.1.2"

But as you can see this can work quite well to your advantage in many ways so I truely hope this helps someone else with a similar headache in the future to come!

Enjoy!
ReflectionClass::getConstant
ReflectionClass::getConstructor
ReflectionClass


Возвращает конструктор

ReflectionClass::getConstants
ReflectionClass::getDefaultProperties
ReflectionClass
PHP Manual

ReflectionClass::getConstructor

(PHP 5)

ReflectionClass::getConstructor — Возвращает конструктор

Описание

public object ReflectionClass::getConstructor ( void )

Возвращает конструктор класса.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект класса ReflectionMethod.

Смотрите также

  • ReflectionClass::getName() - Возвращает имя класса

User Contributed Notes

jochem at drecomm dot nl 13-May-2011 08:13
Old constructors also count as contructor:

<?php

class SomeClass {

    function SomeClass($some_arg) {
    }

}

$refl = new ReflectionClass('SomeClass');

var_dump($refl->isInstantiable()); // bool(true)

echo $refl->getConstructor();

/* OUTPUT:
Method [ <user, ctor> public method SomeClass ] {
  @@ /var/www/vhosts/api.example.com/httpdocs/testRefl.php 5 - 6

  - Parameters [1] {
    Parameter #0 [ <required> $some_arg ]
  }
}
*/

?>

Some more behavior:

<?php

class SomeClass {

   function funcA($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('SomeClass');

var_dump($refl->isInstantiable()); // bool(true)

var_dump($refl->getConstructor()); // NULL

/* --------------- */

class AnotherClass {

   private function __construct() {
   }

   function funcB($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('AnotherClass');

var_dump($refl->isInstantiable()); // bool(false)

echo $refl->getConstructor();
/*
Method [ <user, ctor> private method __construct ] {
  @@ /testRefl.php 22 - 23
}
*/

?>

Tested on PHP 5.2.4
Rob McVey 16-Jul-2010 07:47
Just posting some example code for anyone wanting to mess around with this stuff:

<?php

class Say
{
    private $what_to_say;
    public function __construct($no_default, $word = "Hello World", $options = array('a', 'b'))
    {
        $this->what_to_say = $word;
    }

    public function speak()
    {
        echo $this->what_to_say;
    }
}

$class = new ReflectionClass('Say');

$constructor = $class->getConstructor();

echo $constructor;

/*     OUTPUTS:

Method [ <user, ctor> public method __construct ] {
  @@ /reflect.php 6 - 9

  - Parameters [3] {
    Parameter #0 [ <required> $no_default ]
    Parameter #1 [ <optional> $word = 'Hello World' ]
    Parameter #2 [ <optional> $options = Array ]
  }
}

*/

$parameters = $constructor->getParameters();

var_export($parameters);

/*    OUTPUT:

array (
  0 =>
  ReflectionParameter::__set_state(array(
     'name' => 'no_default',
  )),
  1 =>
  ReflectionParameter::__set_state(array(
     'name' => 'word',
  )),
  2 =>
  ReflectionParameter::__set_state(array(
     'name' => 'options',
  )),
)

*/

$nl = "\n";
echo "$nl\tParameters$nl";
foreach($parameters as $param)
{
    echo "****** $" . $param->name . " ******$nl";
    echo "Nullable:\t\t" . $param->allowsNull() . $nl
         ."Default Value:\t\t";
    echo ($param->isDefaultValueAvailable()) ? $param->getDefaultValue() : "None";
    echo $nl ."Is Array:\t\t";
    echo ($param->isArray()) ? "Yes" : "No";
    echo $nl . "Optional:\t\t";
    echo ($param->isOptional()) ? "Yes" : "No";
    echo $nl;
}

/*    OUTPUT:

    Parameters
****** $no_default ******
Nullable:        1
Default Value:    None
Is Array:        No
Optional:        No
****** $word ******
Nullable:        1
Default Value:    Hello World
Is Array:        No
Optional:        Yes
****** $options ******
Nullable:        1
Default Value:    Array
Is Array:        No
Optional:        Yes

*/

?>

To clarify the possibly confusing behavior of ReflectionParemeter::isArray(), it will return true if the parameter has type hinting:

<?php
...
public function __construct($no_default, $word = "Hello World", array $options = array('a', 'b'))
...
?>

Calling isArray() will now return true for the $options parameter
ReflectionClass::getConstants
ReflectionClass::getDefaultProperties
ReflectionClass


Возвращает свойства по умолчанию

ReflectionClass::getConstructor
ReflectionClass::getDocComment
ReflectionClass
PHP Manual

ReflectionClass::getDefaultProperties

(PHP 5)

ReflectionClass::getDefaultProperties — Возвращает свойства по умолчанию

Описание

public array ReflectionClass::getDefaultProperties ( void )

Возвращает свойства класса по умолчанию (включая наследованные свойства).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Ассоциативный массив (array) свойств по умолчанию, ключами которого являются имена свойств, а значениями -- соответствующие значения по умолчанию или же NULL, если этому свойству не было задано значение по умолчанию. Функция не различает static (статические) и non static (не статические) свойства, а также не предоставляет информацию о модификаторах видимости при выводе.

Примеры

Пример #1 Пример использования ReflectionClass::getDefaultProperties()

<?php
class Bar {
    protected $inheritedProperty = 'наследованное свойство по умолчанию';
}

class Foo extends Bar {
    public $property = 'свойство по умолчанию';
    private $privateProperty = 'закрытое свойство по умолчанию';
    public static $staticProperty = 'статическое свойство';
    public $defaultlessProperty;
}

$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

Результат выполнения данного примера:

array(5) {
   ["staticProperty"]=>
   string(14) "статическое свойство"
   ["property"]=>
   string(15) "свойство по умолчанию"
   ["privateProperty"]=>
   string(22) "закрытое свойство по умолчанию"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "наследованное свойство по умолчанию"
}

Смотрите также

  • ReflectionClass::getProperties() - Возвращает свойства
  • ReflectionClass::getStaticProperties() - Возвращает static свойства
  • ReflectionClass::getProperty() - Возвращает свойство

User Contributed Notes

runaurufu AT gmail.com 04-Aug-2011 01:02
Worth noting that it will not return private parameters of parent class...
so it works exactly as get_class_vars or get_object_vars
captainjester at hotmail dot com 20-Jan-2010 03:20
This will return all properties in a class and any parent classes.  The array will have keys set to the property names and empty values.
ReflectionClass::getConstructor
ReflectionClass::getDocComment
ReflectionClass


Возвращает doc-блоки комментариев

ReflectionClass::getDefaultProperties
ReflectionClass::getEndLine
ReflectionClass
PHP Manual

ReflectionClass::getDocComment

(PHP 5 >= 5.1.0)

ReflectionClass::getDocComment — Возвращает doc-блоки комментариев

Описание

public string ReflectionClass::getDocComment ( void )

Возвращает doc-блоки комментариев класса.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

doc-блок комментариев, если он существует, в противном случае FALSE

Примеры

Пример #1 Пример использования ReflectionClass::getDocComment()

<?php
/**
* Тестовый класс
*
* @param  foo bar
* @return baz
*/
class TestClass { }

$rc = new ReflectionClass('TestClass');
var_dump($rc->getDocComment())
?>

Результат выполнения данного примера:

string(55) "/**
* Тестовый класс
*
* @param  foo bar
* @return baz
*/"

Смотрите также

  • ReflectionClass::getName() - Возвращает имя класса

User Contributed Notes

uramihsayibok, gmail, com 15-Sep-2010 09:50
According to what I can find in the PHP (5.3.2) source code, getDocComment will return the doc comment as the parser found it.
The doc comment (T_DOC_COMMENT) must begin with a /** - that's two asterisks, not one. The comment continues until the first */. A normal multi-line comment /*...*/ (T_COMMENT) does not count as a doc comment.

The doc comment itself includes those five characters, so <?php substr($doccomment, 3, -2) ?> will get you what's inside. A call to trim() after is recommended.
leosouza at hotmail dot com 26-Feb-2010 10:10
The code getDocComment() is not as effective as it seems, a method with a well-crafted regular expression, can solve some problems that this method does not address, for example: Some comments that begin with "/ *" will not be returned in a file too extensive.

The method below shows how you can use a regular expression to get better results.

This code snippet captures the comments in a file. "Php" and replaces it with an empty string, ie "cut" the comments of a class:

<?php
    public function getComments() {

        $expr = "/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/";

        $filename = $this->fileDir; //file directory
        $file = fopen($filename, "r");
        $length = filesize($filename);
        $comments = fread($file, $length);

        preg_match_all($expr, $comments, $matchs); //capture the comments

        foreach($matchs[0] as $id => $variable){
            $comments = str_replace($variable,'',$comments); // replace the scores of empty
        }
        fclose($file);
        $file = fopen($filename, "w");
        $file = fwrite($file, $comments);
    }
?>
joe dot scylla at gmail dot com 14-Oct-2009 08:23
If you're using a bytecode cache like eAccelerator this method will return FALSE even if there is a properly formatted Docblock. It looks like the information required by this method gets stripped out by the bytecode cache.
ReflectionClass::getDefaultProperties
ReflectionClass::getEndLine
ReflectionClass


Возвращает номер последней строки

ReflectionClass::getDocComment
ReflectionClass::getExtension
ReflectionClass
PHP Manual

ReflectionClass::getEndLine

(PHP 5)

ReflectionClass::getEndLine — Возвращает номер последней строки

Описание

public int ReflectionClass::getEndLine ( void )

Возвращает номер последней строки определения пользовательского класса.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Номер последней строки определения пользовательского класса или FALSE, если номер неизвестен.

Примеры

Пример #1 Пример использования ReflectionClass::getEndLine()

<?php
// Тестовый класс
class TestClass { }

$rc = new ReflectionClass('TestClass');

echo $rc->getEndLine();
?>

Результат выполнения данного примера:

3

Смотрите также

  • ReflectionClass::getStartLine() - Возвращает номер начальной строки

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getDocComment
ReflectionClass::getExtension
ReflectionClass


Возвращает информацию о расширении

ReflectionClass::getEndLine
ReflectionClass::getExtensionName
ReflectionClass
PHP Manual

ReflectionClass::getExtension

(PHP 5)

ReflectionClass::getExtension — Возвращает информацию о расширении

Описание

public ReflectionExtension ReflectionClass::getExtension ( void )

Возвращает объект расширения класса ReflectionExtension.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект класса ReflectionExtension.

Смотрите также

  • ReflectionClass::getExtensionName() - Возвращает имя расширения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getEndLine
ReflectionClass::getExtensionName
ReflectionClass


Возвращает имя расширения

ReflectionClass::getExtension
ReflectionClass::getFileName
ReflectionClass
PHP Manual

ReflectionClass::getExtensionName

(PHP 5)

ReflectionClass::getExtensionName — Возвращает имя расширения

Описание

public string ReflectionClass::getExtensionName ( void )

Возвращает имя расширения.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя расширения.

Смотрите также

  • ReflectionClass::getExtension() - Возвращает информацию о расширении

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getExtension
ReflectionClass::getFileName
ReflectionClass


Возвращает имя файла, в котором объявлен класс

ReflectionClass::getExtensionName
ReflectionClass::getInterfaceNames
ReflectionClass
PHP Manual

ReflectionClass::getFileName

(PHP 5)

ReflectionClass::getFileName — Возвращает имя файла, в котором объявлен класс

Описание

public string ReflectionClass::getFileName ( void )

Возвращает имя файла, в котором объявлен класс.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает имя файла, в котором объявлен класс. Если класс объявлен в ядре PHP или в расширении PHP, возвращает FALSE.

Смотрите также

  • ReflectionClass::getExtensionName() - Возвращает имя расширения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getExtensionName
ReflectionClass::getInterfaceNames
ReflectionClass


Возвращает имена интерфейсов

ReflectionClass::getFileName
ReflectionClass::getInterfaces
ReflectionClass
PHP Manual

ReflectionClass::getInterfaceNames

(PHP 5 >= 5.2.0)

ReflectionClass::getInterfaceNames — Возвращает имена интерфейсов

Описание

public array ReflectionClass::getInterfaceNames ( void )

Возвращает имена интерфейсов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив имен интерфейсов.

Примеры

Пример #1 Пример использования ReflectionClass::getInterfaceNames()

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaceNames());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [0] => Foo
    [1] => Bar
)

Смотрите также

  • ReflectionClass::getInterfaces() - Возвращает интерфейсы

User Contributed Notes

pinpin 27-Mar-2011 04:11
It seems the interface names are actually listed in a defined order:
- "extends" takes precedence over "implements" (i.e. first will be interfaces from (implemented in) the parent class (if any), then interfaces implemented in the class itself)
- when multiple interfaces are implemented at one time/level, it can be:
+ from an "implements" : they're listed in the defined order
+ from an "extends" (a class extends another class which implements multiple interfaces; or an interface extends multiple interfaces) : they're listed in REVERSE order

<?php
interface Foo {}
interface Bar {}
interface Other {}
interface Foobar extends Foo, Bar {}
interface Barfoo extends Bar, Foo {}

class Test1 implements Foo, Bar {}
class Test2 implements Bar, Foo {}

class Test3 extends Test1 {}
class Test4 extends Test2 {}

class Test5 extends Test1 implements Other {}

class Test6 implements Foobar, Other {}
class TestO implements Other {}
class Test7 extends TestO implements Barfoo {}

$r=new ReflectionClass('Test1');
print_r($r->getInterfaceNames()); // Foo, Bar

$r=new ReflectionClass('Test2');
print_r($r->getInterfaceNames()); // Bar, Foo

$r=new ReflectionClass('Test3');
print_r($r->getInterfaceNames()); // Bar, Foo

$r=new ReflectionClass('Test4');
print_r($r->getInterfaceNames()); // Foo, Bar

$r=new ReflectionClass('Test5');
print_r($r->getInterfaceNames()); // Bar, Foo, Other

$r=new ReflectionClass('Test6');
print_r($r->getInterfaceNames()); // Foobar, Bar, Foo, Other

$r=new ReflectionClass('Test7');
print_r($r->getInterfaceNames()); // Other, Barfoo, Foo, Bar
?>
ReflectionClass::getFileName
ReflectionClass::getInterfaces
ReflectionClass


Возвращает интерфейсы

ReflectionClass::getInterfaceNames
ReflectionClass::getMethod
ReflectionClass
PHP Manual

ReflectionClass::getInterfaces

(PHP 5)

ReflectionClass::getInterfaces — Возвращает интерфейсы

Описание

public array ReflectionClass::getInterfaces ( void )

Возвращает интерфейсы.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Ассоциативный массив (array) интерфейсов, в котором ключами являются имена интерфейсов, а значениями -- объекты ReflectionClass.

Примеры

Пример #1 Пример использования ReflectionClass::getInterfaces()

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaces());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [Foo] => ReflectionClass Object
        (
            [name] => Foo
        )

    [Bar] => ReflectionClass Object
        (
            [name] => Bar
        )

)

Смотрите также

  • ReflectionClass::getInterfaceNames() - Возвращает имена интерфейсов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getInterfaceNames
ReflectionClass::getMethod
ReflectionClass


Возвращает объект класса ReflectionMethod

ReflectionClass::getInterfaces
ReflectionClass::getMethods
ReflectionClass
PHP Manual

ReflectionClass::getMethod

(PHP 5)

ReflectionClass::getMethod — Возвращает объект класса ReflectionMethod

Описание

public ReflectionMethod ReflectionClass::getMethod ( string $name )

Возвращает объект класса ReflectionMethod, содержащий информацию о методе.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

name

Исследуемый метод.

Возвращаемые значения

Объект класса ReflectionMethod.

Смотрите также

  • ReflectionClass::getMethod()

User Contributed Notes

Christopher Turner 23-Mar-2011 07:04
If the method doesn't exist within the class that the ReflectionClass is reflecting an Exception is thrown.
Jarrod Nettles 22-Dec-2010 12:58
If you ever need to get the type hint of a parameter in a method use this.

<?php

//Target our class
$reflector = new ReflectionClass('MyClass');

//Get the parameters of a method
$parameters = $reflector->getMethod('FireCannon')->getParameters();

//Loop through each parameter and get the type
foreach($parameters as $param)
{
     //Before you call getClass() that class must be defined!
     echo $param->getClass()->name;
}

?>
ReflectionClass::getInterfaces
ReflectionClass::getMethods
ReflectionClass


Возвращает список методов

ReflectionClass::getMethod
ReflectionClass::getModifiers
ReflectionClass
PHP Manual

ReflectionClass::getMethods

(PHP 5)

ReflectionClass::getMethods — Возвращает список методов

Описание

public array ReflectionClass::getMethods ([ string $filter ] )

Возвращает список методов.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

filter

Любая комбинация из следующих констант: ReflectionMethod::IS_STATIC,
ReflectionMethod::IS_PUBLIC,
ReflectionMethod::IS_PROTECTED,
ReflectionMethod::IS_PRIVATE,
ReflectionMethod::IS_ABSTRACT,
ReflectionMethod::IS_FINAL.

Возвращаемые значения

Массив (array) методов.

Смотрите также

  • ReflectionClass::getMethod() - Возвращает объект класса ReflectionMethod

User Contributed Notes

erik at dubbelboer dot com 28-Mar-2012 05:21
The $filter uses an OR to filter the methods.

So php ReflectionMethod::IS_STATIC | ReflectionMethod::IS_PUBLIC will return all methods which are static or public methods, NOT only the methods which are both static and private.
deminy at deminy dot net 22-Jun-2011 09:24
Method ReflectionClass::getMethods doesn't work constantly across different versions of PHP. For following code piece

<?php
class Dummy implements Iterator
{
    public function current () {}
    public function next () {}
    public function key () {}
    public function valid () {}
    public function rewind () {}
}

$reflection = new ReflectionClass('Dummy');
$aMethods = $reflection->getMethods();
echo '# of methods: ', count($aMethods), "\n";
?>

, it outputs "# of methods: 10" on PHP 5.2.14 and PHP 5.2.17, including all methods defined in the class itself and in the interface no matter if a method has been implemented or overridden; however, it returns "# of methods: 5" on PHP 5.3.5. Based on some other tests did by my colleagues, I assume it also returns "# of methods: 5" on PHP 5.2.10 and PHP 5.3.6.
calibhaan at gmail dot com 11-May-2010 09:57
This method return an array of ReflectionMethod;
For example:

<?php
$reflection = new ReflectionClass('Test');
$aMethods = $reflection->getMethods();
var_dump($aMethods);
?>

Display:
array(2) {
 [0]=> &object(ReflectionMethod)#7 (2) {
  ["name"]=> string(11) "__construct"
  ["class"]=> string(9) "Test" }
 [1]=> &object(ReflectionMethod)#8 (2) {
  ["name"]=> string(3) "run"
  ["class"]=> string(9) "Test" }
}
ReflectionClass::getMethod
ReflectionClass::getModifiers
ReflectionClass


Возвращает информацию о модификаторах класса

ReflectionClass::getMethods
ReflectionClass::getName
ReflectionClass
PHP Manual

ReflectionClass::getModifiers

(PHP 5)

ReflectionClass::getModifiers — Возвращает информацию о модификаторах класса

Описание

public int ReflectionClass::getModifiers ( void )

Возвращает битовую маску модификаторов для данного метода.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает битовую маску из констант модификаторов.

Смотрите также

  • ReflectionClass::getProperties() - Возвращает свойства

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getMethods
ReflectionClass::getName
ReflectionClass


Возвращает имя класса

ReflectionClass::getModifiers
ReflectionClass::getNamespaceName
ReflectionClass
PHP Manual

ReflectionClass::getName

(PHP 5)

ReflectionClass::getName — Возвращает имя класса

Описание

public string ReflectionClass::getName ( void )

Возвращает имя класса.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя класса.

Примеры

Пример #1 Пример использования ReflectionClass::getName()

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Результат выполнения данного примера:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Смотрите также

  • ReflectionClass::getNamespaceName() - Возвращает название пространства имён

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getModifiers
ReflectionClass::getNamespaceName
ReflectionClass


Возвращает название пространства имён

ReflectionClass::getName
ReflectionClass::getParentClass
ReflectionClass
PHP Manual

ReflectionClass::getNamespaceName

(PHP 5 >= 5.3.0)

ReflectionClass::getNamespaceName — Возвращает название пространства имён

Описание

public string ReflectionClass::getNamespaceName ( void )

Возвращает название пространства имён.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Название пространства имён.

Примеры

Пример #1 Пример использования ReflectionClass::getNamespaceName()

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Результат выполнения данного примера:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Смотрите также

  • ReflectionClass::getParentClass() - Возвращает родительский класс
  • namespaces

User Contributed Notes

francois 14-Aug-2011 04:08
If the object does not belong to a namespace, an empty string is returned
ReflectionClass::getName
ReflectionClass::getParentClass
ReflectionClass


Возвращает родительский класс

ReflectionClass::getNamespaceName
ReflectionClass::getProperties
ReflectionClass
PHP Manual

ReflectionClass::getParentClass

(PHP 5)

ReflectionClass::getParentClass — Возвращает родительский класс

Описание

public object ReflectionClass::getParentClass ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект класса ReflectionClass.

Смотрите также

  • ReflectionClass::__construct() - Создаёт объект класса ReflectionClass

User Contributed Notes

havelangep at hotmail dot com 16-Dec-2010 01:26
Here is a "replacement" for is_a that will additionally look both into the extended classes and in the implemented interfaces

<?php
/**
     * Check if a class extends or implements a specific class/interface
     * @param string $search The class or interface name to look for
     * @param string $className The class name of the object to compare to
     * @return bool
     */
    function IsExtendsOrImplements( $search, $className ) {
        $class = new ReflectionClass( $className );
        if( false === $class ) {
            return false;
        }
        do {
            $name = $class->getName();
            if( $search == $name ) {
                return true;
            }
            $interfaces = $class->getInterfaceNames();
            if( is_array( $interfaces ) && in_array( $search, $interfaces )) {
                return true;
            }
            $class = $class->getParentClass();
        } while( false !== $class );
        return false;
    }
?>
jochem at drecomm dot nl 18-Nov-2010 04:34
When you want to find all parents (parent, parent of parent, parent of parent's parent and so on) try:

<?php
$class = new ReflectionClass('whatever');

$parents = array();

while ($parent = $class->getParentClass()) {
    $parents[] = $parent->getName();
}

echo "Parents: " . implode(", ", $parents);
?>

ReflectionClass::getParentClass() can return a ReflectionClass object of the parent class or false if no parent.

(PHP Version 5.1.6)
meecrob at k42b3 dot com 20-Jun-2008 03:47
When your class extends a parent class you maybe want the name
of them. Using getParentClass() is maybe a bit confusing. When
you want the name as string try the following.

<?php
$class = new ReflectionClass('whatever');

$parent = (array) $class->getParentClass();

if(array_key_exists('name', $parent))
{
    # name of the parent class
    $parent = parent['name'];
}
else
{
    # no parent class avaible
    $parent = false;
}
?>

When you turn getParentClass() to an array it will result either
array(0 => false) when no parent class exist or
array('name' => 'name of the parent class'). Tested on PHP 5.2.4
ReflectionClass::getNamespaceName
ReflectionClass::getProperties
ReflectionClass


Возвращает свойства

ReflectionClass::getParentClass
ReflectionClass::getProperty
ReflectionClass
PHP Manual

ReflectionClass::getProperties

(PHP 5)

ReflectionClass::getProperties — Возвращает свойства

Описание

public array ReflectionClass::getProperties ([ int $filter ] )

Возвращает reflected (отражённые) свойства.

Список параметров

filter

Опциональный фильтр, позволяющий возвращать только желаемые типы свойств. Он настраивается с помощью констант ReflectionProperty, по умолчанию позволяет возвращать свойства всех типов.

Возвращаемые значения

Массив объектов класса ReflectionProperty.

Примеры

Пример #1 Пример фильтрации с помощью ReflectionClass::getProperties()

В этом примере демонстрируется использование параметра filter, который в данном случае не пропускает private (закрытые) свойства.

<?php
class Foo {
    public    $foo  = 1;
    protected $bar  = 2;
    private   $baz  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
    print $prop->getName() . "\n";
}

var_dump($props);

?>

Результатом выполнения данного примера будет что-то подобное:

foo
bar
array(2) {
  [0]=>
  object(ReflectionProperty)#3 (2) {
    ["name"]=>
    string(3) "foo"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionProperty)#4 (2) {
    ["name"]=>
    string(3) "bar"
    ["class"]=>
    string(3) "Foo"
  }
}

Смотрите также

  • ReflectionClass::getProperty() - Возвращает свойство
  • ReflectionProperty
  • константы ReflectionProperty

User Contributed Notes

Yzmir Ramirez 16-Oct-2010 08:53
Looks like you can access public, protected, private variables by casting the object to an array (useful for Unit Testing).  However casting to an array still won't allow you access to protected and private static variables.

In PHP 5.3.0+ use ReflectionProperty::setAccessable(true);

<?php

echo "PHP Version: ".phpversion()."\n";

class Foo {
    public    $foo  = 'public';
    protected $bar  = 'protected';
    private   $baz  = 'private';

    public static    $sfoo  = 'public static';
    protected static $sbar  = 'protected static';
    private static   $sbaz  = 'private static';

    const COO = 'const';

}

$obj = new Foo;

$arr = (array)$obj;

print_r($arr);

echo "Accessing Public Static: ".Foo::$sfoo."\n";
// echo Foo::$sbar."\n"; // Fatal error: Cannot access protected property Foo::$sbar
// echo Foo::$sbaz."\n"; // Fatal error: Cannot access private property Foo::$sbaz
echo "Accessing Constant: ".Foo::COO."\n";
?>

PHP Version: 5.2.12
Array
(
    [foo] => public
    [*bar] => protected
    [Foobaz] => private
)
Accessing Public Static: public static
Accessing Constant: const

PHP Version: 5.1.6
Array
(
    [foo] => public
    [*bar] => protected
    [Foobaz] => private
)
Accessing Public Static: public static
Accessing Constant: const
Jeff Hunter 09-Oct-2009 05:30
It appears the filter parameter accepts a long value that is one of ReflectionProperty::IS_STATIC, ReflectionProperty::IS_PUBLIC, ReflectionProperty::IS_PROTECTED, or ReflectionProperty::IS_PRIVATE as a way to limit the returned properties.  Flags may be combined by adding them together.

Example:

<?php
class Foo {
  public $alpha = 1;
  protected $beta = 2;
  private $gamma = 3;

  public function listProperties() {
    $reflect = new ReflectionObject($this);
    foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PROTECTED) as $prop) {
      print $prop->getName() . "\n";
    }
  }
}

$foo = new Foo();
$foo->listProperties();
?>

will output:

  alpha
  beta
mcurtis 28-Jan-2009 02:41
It should be noted that the 'filter' parameter in the getProperties(filter) method is expected to be of type long.  Not sure why, but it doesn't function as a way of passing in a string to fetch a subset of properties by string match.
muratyaman at gmail dot com 22-Jan-2009 07:47
Some may find this useful.

<?php
/**
 * Recursive function to get an associative array of class properties by property name => ReflectionProperty() object
 * including inherited ones from extended classes
 * @param string $className Class name
 * @param string $types Any combination of <b>public, private, protected, static</b>
 * @return array
 */
function getClassProperties($className, $types='public'){
    $ref = new ReflectionClass($className);
    $props = $ref->getProperties();
    $props_arr = array();
    foreach($props as $prop){
        $f = $prop->getName();

        if($prop->isPublic() and (stripos($types, 'public') === FALSE)) continue;
        if($prop->isPrivate() and (stripos($types, 'private') === FALSE)) continue;
        if($prop->isProtected() and (stripos($types, 'protected') === FALSE)) continue;
        if($prop->isStatic() and (stripos($types, 'static') === FALSE)) continue;

        $props_arr[$f] = $prop;
    }
    if($parentClass = $ref->getParentClass()){
        $parent_props_arr = getClassProperties($parentClass->getName());//RECURSION
        if(count($parent_props_arr) > 0)
            $props_arr = array_merge($parent_props_arr, $props_arr);
    }
    return $props_arr;
}

//USAGE

class A{
  public $a1;

    function abc(){
        //do something
    }
}

class AA extends A{
    public $a2;

    function edf(){
        //do something
    }
}

class AAA extends AA{
  //may not have extra properties, but may have extra methods
    function ghi(){
        //ok
    }
}

//$ref = new ReflectionClass('AAA'); $props = $ref->getProperties();//This will get no properties!
$props_arr = getClassProperties('AAA', 'public');//Use this
var_dump($props_arr);
/*
OUTPUT on PHP5.2.6:
array
  'a1' =>
    object(ReflectionProperty)[4]
      public 'name' => string 'a1' (length=2)
      public 'class' => string 'AAA' (length=3)
  'a2' =>
    object(ReflectionProperty)[3]
      public 'name' => string 'a2' (length=2)
      public 'class' => string 'AAA' (length=3)

*/

?>
david dot thalmann at gmail dot com 05-Jan-2009 08:19
With PHP 5.3 protected or private properties are easy to access with setAccessible(). However, it's sometimes needed (e.g. Unit Tests) and here is a workaround for getValue():

<?php

$class = new ReflectionClass('SomeClass');
$props = $class->getProperties();
// $propsStatic = $class->getStaticProperties();

$myPrivatePropertyValue = $props['aPrivateProperty'];

?>

Note that it wont work if you access the property directly with getProperty().
ReflectionClass::getParentClass
ReflectionClass::getProperty
ReflectionClass


Возвращает свойство

ReflectionClass::getProperties
ReflectionClass::getShortName
ReflectionClass
PHP Manual

ReflectionClass::getProperty

(PHP 5)

ReflectionClass::getProperty — Возвращает свойство

Описание

public ReflectionProperty ReflectionClass::getProperty ( string $name )

Возвращает свойство.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

name

Имя свойства.

Возвращаемые значения

Объект класса ReflectionProperty.

Смотрите также

  • ReflectionClass::getProperties() - Возвращает свойства

User Contributed Notes

eric at naeseth dot com 02-Aug-2011 03:38
If the class doesn't have a property with the given name, a ReflectionException will be raised.
ReflectionClass::getProperties
ReflectionClass::getShortName
ReflectionClass


Возвращает короткое имя

ReflectionClass::getProperty
ReflectionClass::getStartLine
ReflectionClass
PHP Manual

ReflectionClass::getShortName

(PHP 5 >= 5.3.0)

ReflectionClass::getShortName — Возвращает короткое имя

Описание

public string ReflectionClass::getShortName ( void )

Возвращает короткое имя класса, ту часть, которая не относится к названию пространства имён.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Короткое имя класса.

Примеры

Пример #1 Пример использования ReflectionClass::getShortName()

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Результат выполнения данного примера:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Смотрите также

  • ReflectionClass::getName() - Возвращает имя класса

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getProperty
ReflectionClass::getStartLine
ReflectionClass


Возвращает номер начальной строки

ReflectionClass::getShortName
ReflectionClass::getStaticProperties
ReflectionClass
PHP Manual

ReflectionClass::getStartLine

(PHP 5)

ReflectionClass::getStartLine — Возвращает номер начальной строки

Описание

public int ReflectionClass::getStartLine ( void )

Возвращает номер начальной строки.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Номер начальной строки в виде целого числа (integer).

Смотрите также

  • ReflectionClass::getEndLine() - Возвращает номер последней строки

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getShortName
ReflectionClass::getStaticProperties
ReflectionClass


Возвращает static свойства

ReflectionClass::getStartLine
ReflectionClass::getStaticPropertyValue
ReflectionClass
PHP Manual

ReflectionClass::getStaticProperties

(PHP 5)

ReflectionClass::getStaticProperties — Возвращает static свойства

Описание

public array ReflectionClass::getStaticProperties ( void )

Возвращает static (статические) свойства.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив (array) static свойств.

Смотрите также

  • ReflectionClass::getStaticPropertyValue() - Возвращает значение static свойства
  • ReflectionClass::setStaticPropertyValue() - Устанавливает значение static-свойства

User Contributed Notes

jlennox @ google mail 08-May-2010 10:03
I had the need to recursive merge the results from a subclass with all of it's parents, and this was the resulting code:

<?php
function GetStaticPropertiesRecursive($class) {
    $currentClass = $class;
    $joinedProperties = array();
    do {
        $reflection = new ReflectionClass($class);
        $staticProperties = $reflection->getStaticProperties();
        foreach ($staticProperties as $name => $value) {
            if (is_array($value)) {
                if (isset($joinedProperties[$name]))
                    $joinedProperties[$name] = array_merge($value, $joinedProperties[$name]);
                else
                    $joinedProperties[$name] = $value;
            } else {
                if (isset($joinedProperties[$name]))
                    $joinedProperties[$name][] = $value;
                else
                    $joinedProperties[$name] = array($value);
            }
        }
    } while ($class = get_parent_class($class));
    return $joinedProperties;
}

Using this function:
class base {
    public static $Test = array("foo1", "foo2");
}
class sub extends base {
    public static $Test = "sub";
}

print_r(GetStaticPropertiesRecursive("sub"));
?>

That outputs:
Array
(
    [Test] => Array
        (
            [0] => foo1
            [1] => foo2
            [2] => sub
        )

)

The merge follows the rules of array_merge on duplicate keys.
ReflectionClass::getStartLine
ReflectionClass::getStaticPropertyValue
ReflectionClass


Возвращает значение static свойства

ReflectionClass::getStaticProperties
ReflectionClass::getTraitAliases
ReflectionClass
PHP Manual

ReflectionClass::getStaticPropertyValue

(PHP 5 >= 5.1.0)

ReflectionClass::getStaticPropertyValue — Возвращает значение static свойства

Описание

public mixed ReflectionClass::getStaticPropertyValue ( string $name [, string $default ] )

Возвращает значение static (статического) свойства.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

name

default

Возвращаемые значения

Смотрите также

  • ReflectionClass::getStaticProperties() - Возвращает static свойства
  • ReflectionClass::setStaticPropertyValue() - Устанавливает значение static-свойства

User Contributed Notes

Antares 16-Aug-2011 07:11
It seems this method has a security level different from the getStaticProperties method.

If you make two classes A and B looking like

<?php
class A{
        protected static $static_var='foo';

        public function getStatic(){
           $class=new ReflectionClass($this);
           return $class->getStaticPropertyValue('static_var');
        }

        public function getStatic2(){
            $class=new ReflectionClass($this);
            $staticProps=$class->getStaticProperties();
            return $staticProps['static_var'];
        }

        public function __construct(){
              echo $this->getStatic2();
              echo $this->getStatic();
        }
}

class B extends A{
        protected static $static_var='foo2';

}
?>

Then the output will be an exception for the getStatic() call, when the getStatic2() will correctly return 'foo2';
Mauro Gabriel Titimoli 21-Jan-2010 12:05
If you want to change a static property of a variable class...

PHP 5.2
<?php
$reflection = new ReflectionClass($className);
$staticPropertyReference = & $reflection->getStaticPropertyValue($staticPropertyName);

$staticPropertyReference = 'new value';
?>

PHP 5.3
<?php
$className::$$classProperty
?>
ReflectionClass::getStaticProperties
ReflectionClass::getTraitAliases
ReflectionClass


Возвращает массив trait-псевдонимов

ReflectionClass::getStaticPropertyValue
ReflectionClass::getTraitNames
ReflectionClass
PHP Manual

ReflectionClass::getTraitAliases

(PHP >= 5.4.0)

ReflectionClass::getTraitAliases — Возвращает массив trait-псевдонимов

Описание

public array ReflectionClass::getTraitAliases ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает ассоциативный массив, ключами которого являются новые имена методов, а в значениями -- оригинальные имена методов (в формате "TraitName::original"). В случае возникновения ошибки возвращает NULL.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getStaticPropertyValue
ReflectionClass::getTraitNames
ReflectionClass


Возвращает массив trait-имён, задействованных в этом классе

ReflectionClass::getTraitAliases
ReflectionClass::getTraits
ReflectionClass
PHP Manual

ReflectionClass::getTraitNames

(PHP >= 5.4.0)

ReflectionClass::getTraitNames — Возвращает массив trait-имён, задействованных в этом классе

Описание

public array ReflectionClass::getTraitNames ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает массив, значениями которого являются trait-имена. В случае возникновения ошибки возвращает NULL.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getTraitAliases
ReflectionClass::getTraits
ReflectionClass


Возвращает массив traits, задействованных в этом классе

ReflectionClass::getTraitNames
ReflectionClass::hasConstant
ReflectionClass
PHP Manual

ReflectionClass::getTraits

(PHP >= 5.4.0)

ReflectionClass::getTraits — Возвращает массив traits, задействованных в этом классе

Описание

public array ReflectionClass::getTraits ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает ассоциативный массив, ключами которого являются имена traits, а значениями -- экземпляры класса ReflectionClass для каждого trait. В случае возникновения ошибки возвращает NULL.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getTraitNames
ReflectionClass::hasConstant
ReflectionClass


Проверяет, задана ли константа

ReflectionClass::getTraits
ReflectionClass::hasMethod
ReflectionClass
PHP Manual

ReflectionClass::hasConstant

(PHP 5 >= 5.1.0)

ReflectionClass::hasConstant — Проверяет, задана ли константа

Описание

public bool ReflectionClass::hasConstant ( string $name )

Проверяет, задана ли в классе указанная константа или нет.

Список параметров

name

Имя проверяемой константы.

Возвращаемые значения

TRUE если константа задана, в противном случае FALSE.

Примеры

Пример #1 Пример использования ReflectionClass::hasConstant()

<?php
class Foo {
    const c1 = 1;
}

$class = new ReflectionClass("Foo");

var_dump($class->hasConstant("c1"));
var_dump($class->hasConstant("c2"));
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(false)

Смотрите также

  • ReflectionClass::hasMethod() - Проверяет, задан ли метод
  • ReflectionClass::hasProperty() - Проверяет, задано ли свойство

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::getTraits
ReflectionClass::hasMethod
ReflectionClass


Проверяет, задан ли метод

ReflectionClass::hasConstant
ReflectionClass::hasProperty
ReflectionClass
PHP Manual

ReflectionClass::hasMethod

(PHP 5 >= 5.1.0)

ReflectionClass::hasMethod — Проверяет, задан ли метод

Описание

public bool ReflectionClass::hasMethod ( string $name )

Проверяет, задан ли в классе указанный метод или нет.

Список параметров

name

Имя проверяемого метода.

Возвращаемые значения

TRUE если метод задан, в противном случае FALSE

Примеры

Пример #1 Пример использования ReflectionClass::hasMethod()

<?php
Class C {
    public function publicFoo() {
        return true;
    }

    protected function protectedFoo() {
        return true;
    }

    private function privateFoo() {
        return true;
    }

    static function staticFoo() {
        return true;
    }
}

$rc = new ReflectionClass("C");

var_dump($rc->hasMethod('publicFoo'));

var_dump($rc->hasMethod('protectedFoo'));

var_dump($rc->hasMethod('privateFoo'));

var_dump($rc->hasMethod('staticFoo'));

// C не имеет метода bar
var_dump($rc->hasMethod('bar'));

// Имена методов регистронезависимые
var_dump($rc->hasMethod('PUBLICfOO'));
?>

Результат выполнения данного примера:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)

Смотрите также

  • ReflectionClass::hasConstant() - Проверяет, задана ли константа
  • ReflectionClass::hasProperty() - Проверяет, задано ли свойство

User Contributed Notes

michaelgranados at gmail dot com 19-May-2012 02:47
A way to check if you can call an method over a class:

<?php
function is_public_method(
        /* string */$className,
        /* string */$method
){
    $classInstance = new ReflectionClass($className);
    if ($classInstance->hasMethod($method)) {
        return false;
    }
    $methodInstance = $instance->getMethod($method);
    return $methodInstance->isPublic();
}
?>
phoenix at todofixthis dot com 28-Oct-2010 09:47
Parent methods (regardless of visibility) are also available to a ReflectionObject.  E.g.,

<?php
class ParentObject {
  public function parentPublic(  ) {
  }

  private function parentPrivate(  ) {
  }
}

class ChildObject extends ParentObject {
}

$Instance = new ChildObject();
$Reflector = new ReflectionObject($Instance);

var_dump($Reflector->hasMethod('parentPublic'));  // true
var_dump($Reflector->hasMethod('parentPrivate')); // true
?>
hanguofeng at gmail dot com 20-Oct-2010 09:09
note that even if private method will also be 'has'.
ReflectionClass::hasConstant
ReflectionClass::hasProperty
ReflectionClass


Проверяет, задано ли свойство

ReflectionClass::hasMethod
ReflectionClass::implementsInterface
ReflectionClass
PHP Manual

ReflectionClass::hasProperty

(PHP 5 >= 5.1.0)

ReflectionClass::hasProperty — Проверяет, задано ли свойство

Описание

public bool ReflectionClass::hasProperty ( string $name )

Проверяет, задано ли в классе указанное свойство или нет.

Список параметров

name

Имя проверяемого свойства.

Возвращаемые значения

TRUE если свойство задано, в противном случае FALSE

Примеры

Пример #1 Пример использования ReflectionClass::hasProperty()

<?php
class Foo {
    public    $p1;
    protected $p2;
    private   $p3;

}

$obj = new ReflectionObject(new Foo());

var_dump($obj->hasProperty("p1"));
var_dump($obj->hasProperty("p2"));
var_dump($obj->hasProperty("p3"));
var_dump($obj->hasProperty("p4"));
?>

Результатом выполнения данного примера будет что-то подобное:

bool(true)
bool(true)
bool(true)
bool(false)

Смотрите также

  • ReflectionClass::hasConstant() - Проверяет, задана ли константа
  • ReflectionClass::hasMethod() - Проверяет, задан ли метод

User Contributed Notes

rwilczek at web-appz dot de 13-Oct-2009 05:40
Note, that this method does not guarantee, that you can get a property with ReflectionClass::getProperty().

ReflectionClass::hasProperty() considers the parent classes (ignoring however, that a private property is not inherited), while ReflectionClass::getProperty() and ReflectionClass::getProperties() don't care about inheritance.

(Tested with PHP 5.3.0)

<?php
class Foo
{
    private $x;
}

class Bar extends Foo
{
    //
}

$foo = new ReflectionClass('Foo');
$bar = new ReflectionClass('Bar');

var_dump($foo->hasProperty('x'); // bool(true)
var_dump($bar->hasProperty('x'); // bool(true)

var_dump(get_class($foo->getProperty('x'))); //string(18) "ReflectionProperty"
try {
    $bar->getProperty('x');
} catch (ReflectionException $e) {
    echo $e->getMessage(); // Property x does not exist
}
?>
ReflectionClass::hasMethod
ReflectionClass::implementsInterface
ReflectionClass


Проверяет, реализуется ли интерфейс

ReflectionClass::hasProperty
ReflectionClass::inNamespace
ReflectionClass
PHP Manual

ReflectionClass::implementsInterface

(PHP 5)

ReflectionClass::implementsInterface — Проверяет, реализуется ли интерфейс

Описание

public bool ReflectionClass::implementsInterface ( string $interface )

Проверяет, реализует ли класс указанный интерфейс или нет.

Список параметров

interface

Имя интерфейса.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • ReflectionClass::isInterface() - Проверяет, является ли класс интерфейсом
  • ReflectionClass::isSubclassOf() - Проверяет, является ли класс подклассом
  • interface_exists() - Проверяет, определен ли интерфейс
  • Интерфейсы объектов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::hasProperty
ReflectionClass::inNamespace
ReflectionClass


Проверяет, определён ли класс в пространстве имён

ReflectionClass::implementsInterface
ReflectionClass::isAbstract
ReflectionClass
PHP Manual

ReflectionClass::inNamespace

(PHP 5 >= 5.3.0)

ReflectionClass::inNamespace — Проверяет, определён ли класс в пространстве имён

Описание

public bool ReflectionClass::inNamespace ( void )

Проверяет, определён ли класс в пространстве имён.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ReflectionClass::inNamespace()

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Результат выполнения данного примера:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Смотрите также

  • ReflectionClass::getNamespaceName() - Возвращает название пространства имён
  • PHP Namespaces

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::implementsInterface
ReflectionClass::isAbstract
ReflectionClass


Проверяет, является ли класс абстрактным

ReflectionClass::inNamespace
ReflectionClass::isCloneable
ReflectionClass
PHP Manual

ReflectionClass::isAbstract

(PHP 5)

ReflectionClass::isAbstract — Проверяет, является ли класс абстрактным

Описание

public bool ReflectionClass::isAbstract ( void )

Проверяет, является ли класс абстрактным.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ReflectionClass::isAbstract()

<?php
class          TestClass { }
abstract class TestAbstractClass { }

$testClass     = new ReflectionClass('TestClass');
$abstractClass = new ReflectionClass('TestAbstractClass');

var_dump($testClass->isAbstract());
var_dump($abstractClass->isAbstract());
?>

Результат выполнения данного примера:

bool(false)
bool(true)

Смотрите также

  • ReflectionClass::isInterface() - Проверяет, является ли класс интерфейсом
  • Абстрактные классы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::inNamespace
ReflectionClass::isCloneable
ReflectionClass


Проверяет, можно ли клонировать этот класс

ReflectionClass::isAbstract
ReflectionClass::isFinal
ReflectionClass
PHP Manual

ReflectionClass::isCloneable

(PHP >= 5.4.0)

ReflectionClass::isCloneable — Проверяет, можно ли клонировать этот класс

Описание

public bool ReflectionClass::isCloneable ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE, если класс можно клонировать, в противном случае FALSE.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isAbstract
ReflectionClass::isFinal
ReflectionClass


Проверяет, является ли класс окончательным (final)

ReflectionClass::isCloneable
ReflectionClass::isInstance
ReflectionClass
PHP Manual

ReflectionClass::isFinal

(PHP 5)

ReflectionClass::isFinal — Проверяет, является ли класс окончательным (final)

Описание

public bool ReflectionClass::isFinal ( void )

Проверяет, является ли класс окончательным (final).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ReflectionClass::isAbstract()

<?php
class       TestClass { }
final class TestFinalClass { }

$normalClass = new ReflectionClass('TestClass');
$finalClass  = new ReflectionClass('TestFinalClass');

var_dump($normalClass->isFinal());
var_dump($finalClass->isFinal());

?>

Результат выполнения данного примера:

bool(false)
bool(true)

Смотрите также

  • ReflectionClass::isAbstract() - Проверяет, является ли класс абстрактным
  • Ключевое слово "final"

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isCloneable
ReflectionClass::isInstance
ReflectionClass


Проверяет, принадлежит ли объект классу

ReflectionClass::isFinal
ReflectionClass::isInstantiable
ReflectionClass
PHP Manual

ReflectionClass::isInstance

(PHP 5)

ReflectionClass::isInstance — Проверяет, принадлежит ли объект классу

Описание

public bool ReflectionClass::isInstance ( object $object )

Проверяет, является ли объект экземпляром класса.

Список параметров

object

Проверяемый объект.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ReflectionClass::isInstance() и его аналогов

<?php
// Пример использования
$class = new ReflectionClass('Foo');

if ($class->isInstance($arg)) {
    echo "Yes";
}

// Аналогично этому
if ($arg instanceof Foo) {
    echo "Yes";
}

// Аналогично этому
if (is_a($arg, 'Foo')) {
    echo "Yes";
}
?>

Результатом выполнения данного примера будет что-то подобное:

Yes
Yes
Yes

Смотрите также

  • ReflectionClass::isInterface() - Проверяет, является ли класс интерфейсом
  • Операторы проверки типа (instanceof)
  • Интерфейсы объектов
  • is_a() - Проверяет, принадлежит ли объект к данному классу или содержит данный класс в числе своих предков

User Contributed Notes

Peter Kruithof 12-Jul-2010 06:21
This function has a flaw in PHP versions < 5.3.* (my tested version was 5.3.2), in which class inheritance is not handled properly. The following test case renders true in 5.3.2, but false on 5.2.9:

<?php
class A {
}

class B extends A {
    public function foo(A $a) {
    }
}

$b = new B();

$class = new ReflectionClass('B');
$method = $class->getMethod('foo');
$parameters = $method->getParameters();
$param = $parameters[0];
$class = $param->getClass();

var_dump($class->isInstance($b));
?>

If you're running a PHP version lower than 5.3, my suggestion is to use the following fix:

<?php
[...]

$param = $parameters[0];
$class = $param->getClass();
$classname = $class->getName();

var_dump($b instanceof $classname);
?>
ReflectionClass::isFinal
ReflectionClass::isInstantiable
ReflectionClass


Проверяет, можно ли создать экземпляр класса

ReflectionClass::isInstance
ReflectionClass::isInterface
ReflectionClass
PHP Manual

ReflectionClass::isInstantiable

(PHP 5)

ReflectionClass::isInstantiable — Проверяет, можно ли создать экземпляр класса

Описание

public bool ReflectionClass::isInstantiable ( void )

Проверяет, можно ли создать экземпляр класса.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ReflectionClass::isInstantiable()

<?php
class C { }

interface iface {
    function f1();
}

class ifaceImpl implements iface {
    function f1() {}
}

abstract class abstractClass {
    function f1() { }
    abstract function f2();
}

class D extends abstractClass {
    function f2() { }
}

class privateConstructor {
    private function __construct() { }
}

$classes = array(
    "C",
    "iface",
    "ifaceImpl",
    "abstractClass",
    "D",
    "privateConstructor",
);

foreach($classes  as $class ) {
    $reflectionClass = new ReflectionClass($class);
    echo "Можно ли создать экземпляр класса $class?  ";
    var_dump($reflectionClass->IsInstantiable());
}

?>

Результат выполнения данного примера:

Можно ли создать экземпляр класса C?  bool(true)
Можно ли создать экземпляр класса iface?  bool(false)
Можно ли создать экземпляр класса ifaceImpl?  bool(true)
Можно ли создать экземпляр класса abstractClass?  bool(false)
Можно ли создать экземпляр класса D?  bool(true)
Можно ли создать экземпляр класса privateConstructor?  bool(false)

Смотрите также

  • ReflectionClass::isInstance() - Проверяет, принадлежит ли объект классу

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isInstance
ReflectionClass::isInterface
ReflectionClass


Проверяет, является ли класс интерфейсом

ReflectionClass::isInstantiable
ReflectionClass::isInternal
ReflectionClass
PHP Manual

ReflectionClass::isInterface

(PHP 5)

ReflectionClass::isInterface — Проверяет, является ли класс интерфейсом

Описание

public bool ReflectionClass::isInterface ( void )

Проверяет, является ли класс интерфейсом или нет.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • ReflectionClass::isInstance() - Проверяет, принадлежит ли объект классу

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isInstantiable
ReflectionClass::isInternal
ReflectionClass


Проверяет, является ли класс встроенным

ReflectionClass::isInterface
ReflectionClass::isIterateable
ReflectionClass
PHP Manual

ReflectionClass::isInternal

(PHP 5)

ReflectionClass::isInternal — Проверяет, является ли класс встроенным

Описание

public bool ReflectionClass::isInternal ( void )

Проверяет, является ли класс встроенным, а не пользовательским.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • ReflectionClass::isUserDefined() - Проверяет, является ли класс пользовательским

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isInterface
ReflectionClass::isIterateable
ReflectionClass


Проверяет, является ли класс итерируемым

ReflectionClass::isInternal
ReflectionClass::isSubclassOf
ReflectionClass
PHP Manual

ReflectionClass::isIterateable

(PHP 5)

ReflectionClass::isIterateable — Проверяет, является ли класс итерируемым

Описание

public bool ReflectionClass::isIterateable ( void )

Проверяет, является ли класс итерируемым (iterateable) или нет.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ReflectionClass::isIterateable()

<?php

class IteratorClass implements Iterator {
    public function __construct() { }
    public function key() { }
    public function current() { }
    function next() { }
    function valid() { }
    function rewind() { }
}
class DerivedClass extends IteratorClass { }
class NonIterator { }

function dump_iterateable($class) {
    $reflection = new ReflectionClass($class);
    var_dump($reflection->isIterateable());
}

$classes = array("ArrayObject", "IteratorClass", "DerivedClass", "NonIterator");

foreach ($classes as $class) {
    echo "Является ли класс $class итерируемым? ";
    dump_iterateable($class);
}
?>

Результат выполнения данного примера:

Является ли класс ArrayObject итерируемым? bool(true)
Является ли класс IteratorClass итерируемым? bool(true)
Является ли класс DerivedClass итерируемым? bool(true)
Является ли класс NonIterator итерируемым? bool(false)

Смотрите также

  • ReflectionClass::__construct() - Создаёт объект класса ReflectionClass

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isInternal
ReflectionClass::isSubclassOf
ReflectionClass


Проверяет, является ли класс подклассом

ReflectionClass::isIterateable
ReflectionClass::isTrait
ReflectionClass
PHP Manual

ReflectionClass::isSubclassOf

(PHP 5)

ReflectionClass::isSubclassOf — Проверяет, является ли класс подклассом

Описание

public bool ReflectionClass::isSubclassOf ( string $class )

Проверяет, является ли класс подклассом указанного класса или реализует ли указанный интерфейс.

Список параметров

class

Имя класса, по которому будет вестись проверка.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • ReflectionClass::isInterface() - Проверяет, является ли класс интерфейсом
  • ReflectionClass::implementsInterface() - Проверяет, реализуется ли интерфейс
  • is_subclass_of() - Проверяет, содержит ли объект в своем дереве предков указанный класс
  • get_parent_class() - Возвращает имя родительского класса для объекта или класса

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isIterateable
ReflectionClass::isTrait
ReflectionClass


Проверяет, является ли класс trait

ReflectionClass::isSubclassOf
ReflectionClass::isUserDefined
ReflectionClass
PHP Manual

ReflectionClass::isTrait

(PHP >= 5.4.0)

ReflectionClass::isTrait — Проверяет, является ли класс trait

Описание

public bool ReflectionClass::isTrait ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE, если класс является trait, в противном случае FALSE. В случае возникновения ошибки возвращает NULL.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isSubclassOf
ReflectionClass::isUserDefined
ReflectionClass


Проверяет, является ли класс пользовательским

ReflectionClass::isTrait
ReflectionClass::newInstance
ReflectionClass
PHP Manual

ReflectionClass::isUserDefined

(PHP 5)

ReflectionClass::isUserDefined — Проверяет, является ли класс пользовательским

Описание

public bool ReflectionClass::isUserDefined ( void )

Проверяет, является ли класс пользовательским, а не встроенным.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • ReflectionClass::isInternal() - Проверяет, является ли класс встроенным

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isTrait
ReflectionClass::newInstance
ReflectionClass


Создаёт экземпляр класса с переданными аргументами

ReflectionClass::isUserDefined
ReflectionClass::newInstanceArgs
ReflectionClass
PHP Manual

ReflectionClass::newInstance

(PHP 5)

ReflectionClass::newInstance — Создаёт экземпляр класса с переданными аргументами

Описание

public object ReflectionClass::newInstance ( mixed $args [, mixed $... ] )

Создаёт новый экземпляр класса. Принятые аргументы передаются в конструктор класса.

Список параметров

args

Принимает произвольное число аргументов, подобно функции call_user_func(), которые затем передаются в конструктор класса.

Возвращаемые значения

Ошибки

Если конструктор не является public (общедоступным), то это приведёт к выбросу исключения ReflectionException.

Если конструктор отсутствует, а параметр args имеет один и более аргументов, то это приведёт к выбросу исключения ReflectionException.

Смотрите также

  • ReflectionClass::newInstanceArgs() - Создаёт экземпляр класса с переданными параметрами
  • ReflectionClass::newInstanceWithoutConstructor() - Создаёт новый экземпляр класса без вызова конструктора

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::isUserDefined
ReflectionClass::newInstanceArgs
ReflectionClass


Создаёт экземпляр класса с переданными параметрами

ReflectionClass::newInstance
ReflectionClass::newInstanceWithoutConstructor
ReflectionClass
PHP Manual

ReflectionClass::newInstanceArgs

(PHP 5 >= 5.1.3)

ReflectionClass::newInstanceArgs — Создаёт экземпляр класса с переданными параметрами

Описание

public object ReflectionClass::newInstanceArgs ([ array $args ] )

Создаёт новый экземпляр класса. Принятые аргументы передаются в конструктор класса.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

args

Массив (array) аргументов, который затем передаётся в конструктор класса.

Возвращаемые значения

Возвращает новый экземпляр класса.

Ошибки

Если конструктор не является public (общедоступным), то это приведёт к генерации исключения ReflectionException.

Если конструктор отсутствует, а параметр args имеет один и более аргументов, то это приведёт к генерации исключения ReflectionException.

Смотрите также

  • ReflectionClass::newInstance() - Создаёт экземпляр класса с переданными аргументами
  • ReflectionClass::newInstanceWithoutConstructor() - Создаёт новый экземпляр класса без вызова конструктора

User Contributed Notes

foxbunny 11-Dec-2010 07:23
It should be noted that the the values in the array are mapped to constructor arguments positionally, rather than by name, so using an associative array will not make any difference.
talk at stephensugden dot com 30-Oct-2010 03:17
This is the way I dynamically instantiate objects in my lightweight IoC container

<?php

class SimpleContainer {

  // ...

  // Creates an instance of an object with the provided array of arguments
  protected function instantiate($name, $args=array()){
    if(empty($args))
      return new $name();
    else {
      $ref = new ReflectionClass($name);
      return $ref->newInstanceArgs($args);
    }
  }
  // ...
}
?>

I explicitly do NOT handle the case where a user passes constructor arguments for a constructor-less class, as I this SHOULD fail.
sausage at tehsausage dot com 21-Aug-2010 04:14
Annoyingly, this will throw an exception for classes with no constructor even if you pass an empty array for the arguments. For generic programming you should avoid this function and use call_user_func_array with newInstance.
sarfraznawaz2005 at gmail dot com 14-Dec-2009 11:31
I use reflection class and also detect whether arguments are passed by reference or passed by value
and then initiate/call the method successfully with those arguments:

<?php
    if (count($args) > 1)
    {
        if (method_exists($class_name,  '__construct') === false)
        {
            exit("Constructor for the class <strong>$class_name</strong> does not exist, you should not pass arguments to the constructor of this class!");
        }

        $refMethod = new ReflectionMethod($class_name,  '__construct');
        $params = $refMethod->getParameters();

        $re_args = array();

        foreach($params as $key => $param)
        {
            if ($param->isPassedByReference())
            {
                $re_args[$key] = &$args[$key];
            }
            else
            {
                $re_args[$key] = $args[$key];
            }
        }

        $refClass = new ReflectionClass($class_name);
        $class_instance = $refClass->newInstanceArgs((array) $re_args);
    }
?>
kevinpeno at gmail dot com 16-Sep-2009 08:11
I misunderstood this function to be a sort of setter of Reflection::newInstance() arguments in an array form rather than a creator of new instances itself.

This function is equivilant to call_user_func_array() while Reflection::newInstance() is equivilant to call_user_func()
richardcook at gmail dot com 12-Apr-2009 02:39
the newInstanceArgs function cannot call a class' constructor if it has references in its arguments, so be careful what you pass into it:

<?php
class Foo {
    function __construct (&$arr) {
        $this->arr = &$arr;
    }
    function createInstance () {
        $reflectionClass = new ReflectionClass("Bar");

        return $reflectionClass->newInstanceArgs(array($this, $this->arr));
    }
    function mod($key, $val) {
        $this->arr[$key] = $val;
    }
}

class Bar {
    function __construct (&$foo, &$arr) {
        $this->foo = &$foo;
        $this->arr = &$arr;
    }
    function mod($key, $val) {
        $this->arr[$key] = $val;
    }
}

$arr = array();

$foo = new Foo($arr);

$arr["x"] = 1;

$foo->mod("y", 2);

$bar = $foo->createInstance();

$bar->mod("z", 3);

echo "<pre>";
print_r($arr);
print_r($foo);
print_r($bar);
echo "</pre>";

/*
Output:
Warning: Invocation of Bar's constructor failed in [code path] on line 31

Fatal error: Call to a member function mod() on a non-object in [code path] on line 58
*/
?>
gromit at mailinator dot com 29-Jul-2008 01:37
Be aware that calling the method newInstanceArgs with an empty array will still call the constructor with no arguments. If the class has no constructor then it will generate an exception.

You need to check if a constructor exists before calling this method or use try and catch to act on the exception.
ReflectionClass::newInstance
ReflectionClass::newInstanceWithoutConstructor
ReflectionClass


Создаёт новый экземпляр класса без вызова конструктора

ReflectionClass::newInstanceArgs
ReflectionClass::setStaticPropertyValue
ReflectionClass
PHP Manual

ReflectionClass::newInstanceWithoutConstructor

(PHP >= 5.4.0)

ReflectionClass::newInstanceWithoutConstructor — Создаёт новый экземпляр класса без вызова конструктора

Описание

public object ReflectionClass::newInstanceWithoutConstructor ( void )

Создаёт новый экземпляр класса без вызова конструктора.

Список параметров

Возвращаемые значения

Ошибки

Если класс является встроенным, и его экземпляр не может быть создан без вызова конструктора, то это приведёт к генерации исключения ReflectionException.

Смотрите также

  • ReflectionClass::newInstance() - Создаёт экземпляр класса с переданными аргументами
  • ReflectionClass::newInstanceArgs() - Создаёт экземпляр класса с переданными параметрами

User Contributed Notes

me [ata] thomas-lauria.de 28-Apr-2012 06:51
This new Feature enables Annotation based Dependency Injection:
<?php

//dependency to inject
class dep {}

class a {
  /**
   * @inject
   * @var dep
   */
  protected $foo;
}

class b extends a {
  /**
   * @inject
   * @var dep
   */
  protected $bar;

  public function __construct() {
    echo "CONSTRUCTOR CALLED\n";
  }
}

$ref = new ReflectionClass('b');
$inst = $ref->newInstanceWithoutConstructor();

$list = $ref->getProperties();
foreach($list as $prop){
  /* @var $prop ReflectionProperty */
  $prop->getDocComment(); //grep for @inject and the @vars class name
  $prop->setAccessible(true);
  $prop->setValue($inst, new dep());
}
if($const = $ref->getConstructor()) {
  $constName = $const->getName();
  $inst->{$constName}(); //use call_user_func_array($function, $param_arr); for arguments
}

print_r($inst);
print_r($inst->foo); //property still not accessable

The Output:

CONSTRUCTOR CALLED
b Object
(
    [bar:protected] => dep Object
        (
        )

    [foo:protected] => dep Object
        (
        )

)
PHP Fatal error:  Cannot access protected property b::$foo in diTest.php on line 42
oliver at ananit dot de 24-Nov-2011 03:57
If this method is not available in your version of PHP you can use a trick to create an instance without calling the constructor.
Use reflection to get the properties and default values of the class, and create a fake "serialized" string.

<?php
function createInstanceWithoutConstructor($class){
    $reflector = new ReflectionClass($class);
    $properties = $reflector->getProperties();
    $defaults = $reflector->getDefaultProperties();

    $serealized = "O:" . strlen($class) . ":\"$class\":".count($properties) .':{';
    foreach ($properties as $property){
        $name = $property->getName();
        if($property->isProtected()){
                $name = chr(0) . '*' .chr(0) .$name;
            } elseif($property->isPrivate()){
                $name = chr(0)  . $class.  chr(0).$name;
            }
            $serealized .= serialize($name);
            if(array_key_exists($property->getName(),$defaults) ){
                $serealized .= serialize($defaults[$property->getName()]);
            } else {
                $serealized .= serialize(null);
            }
        }
    $serealized .="}";
    return unserialize($serealized);
}
?>

Example:

<?php
class foo
{
    public $a = 10;
    protected $b = 2;
    private $c = "default";
    protected $d;
    public function __construct(){
        $this->a = null;
        $this->b = null;
        $this->c = "constructed";
        $this->d = 42;
    }
}

var_dump(createInstanceWithoutConstructor('foo'));
?>

Output:
object(foo)#6 (4) {
  ["a"]=>
  int(10)
  ["b":protected]=>
  int(2)
  ["c":"foo":private]=>
  string(7) "default"
  ["d":protected]=>
  NULL
}

I hope this can help someone.
Oliver Anan
alejosimon at gmail 06-Sep-2011 06:41
A good first use for this new method.

It implements a transparent parser constructor argument to achieve 99% reusable component.

<?php

use ReflectionClass ;

trait TSingleton
{
    /**
    *    Constructor.
    */
    protected function __construct() {}

    /**
    *    Drop clone singleton objects.
    */
    protected function __clone() {}

    /**
    *    Gets only one instance.
    *
    *    @params Optional multiple values as arguments for the constructor.
    *    @return Object instance from called class.
    */
    public static function getInstance()
    {
        static $instance = null ;

        if ( ! $instance )
        {
            $ref  = new ReflectionClass( get_called_class() ) ;
            $ctor = $ref->getConstructor() ;

            // Thanks PHP 5.4
            $self = $ref->newInstanceWithoutConstructor() ;

            // The magic.
            $ctor->setAccessible( true ) ;
            $instance = $ctor->invokeArgs( $self, func_get_args() ) ;
        }

        return $instance ;
    }
}

?>
ReflectionClass::newInstanceArgs
ReflectionClass::setStaticPropertyValue
ReflectionClass


Устанавливает значение static-свойства

ReflectionClass::newInstanceWithoutConstructor
ReflectionClass::__toString
ReflectionClass
PHP Manual

ReflectionClass::setStaticPropertyValue

(PHP 5 >= 5.1.0)

ReflectionClass::setStaticPropertyValue — Устанавливает значение static-свойства

Описание

public void ReflectionClass::setStaticPropertyValue ( string $name , string $value )

Устанавливает значение статического (static) свойства.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

name

Имя свойства.

value

Новое значение.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • ReflectionClass::getStaticPropertyValue() - Возвращает значение static свойства

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::newInstanceWithoutConstructor
ReflectionClass::__toString
ReflectionClass


Возвращает строковое представление объекта класса ReflectionClass

ReflectionClass::setStaticPropertyValue
ReflectionZendExtension
ReflectionClass
PHP Manual

ReflectionClass::__toString

(PHP 5)

ReflectionClass::__toString — Возвращает строковое представление объекта класса ReflectionClass

Описание

public string ReflectionClass::__toString ( void )

Возвращает строковое представление объекта класса ReflectionClass.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Строковое представление экземпляра класса ReflectionClass.

Примеры

Пример #1 Пример использования ReflectionClass::__toString()

<?php
$reflectionClass = new ReflectionClass('Exception');
echo $reflectionClass->__toString();
?>

Результат выполнения данного примера:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

Смотрите также

  • ReflectionClass::export() - Экспортирует класс
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::setStaticPropertyValue
ReflectionZendExtension
ReflectionClass


Класс ReflectionZendExtension

(PHP >= 5.4.0)

Введение

Обзор классов

ReflectionZendExtension implements Reflector {
/* Свойства */
public $name ;
/* Методы */
final private void __clone ( void )
__construct ( string $name )
public static string export ( string $name [, string $return ] )
public string getAuthor ( void )
public string getCopyright ( void )
public string getName ( void )
public string getURL ( void )
public string getVersion ( void )
public string __toString ( void )
}

Свойства

name

Имя модуля. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

Содержание

  • ReflectionZendExtension::__clone — Копирующий конструктор
  • ReflectionZendExtension::__construct — Конструктор
  • ReflectionZendExtension::export — Экспорт
  • ReflectionZendExtension::getAuthor — Получение автора
  • ReflectionZendExtension::getCopyright — Получение строки авторских прав
  • ReflectionZendExtension::getName — Получение строки имени
  • ReflectionZendExtension::getURL — Получение URL
  • ReflectionZendExtension::getVersion — Получение номера версии
  • ReflectionZendExtension::__toString — Преобразование в строку

User Contributed Notes

There are no user contributed notes for this page.
ReflectionClass::__toString
ReflectionZendExtension::__clone
Reflection


Копирующий конструктор

ReflectionZendExtension
ReflectionZendExtension::__construct
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::__clone

(PHP >= 5.4.0)

ReflectionZendExtension::__clone — Копирующий конструктор

Описание

final private void ReflectionZendExtension::__clone ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension
ReflectionZendExtension::__construct
ReflectionZendExtension


Конструктор

ReflectionZendExtension::__clone
ReflectionZendExtension::export
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::__construct

(PHP >= 5.4.0)

ReflectionZendExtension::__construct — Конструктор

Описание

ReflectionZendExtension::__construct ( string $name )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

name

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::__clone
ReflectionZendExtension::export
ReflectionZendExtension


Экспорт

ReflectionZendExtension::__construct
ReflectionZendExtension::getAuthor
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::export

(PHP >= 5.4.0)

ReflectionZendExtension::export — Экспорт

Описание

public static string ReflectionZendExtension::export ( string $name [, string $return ] )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

name

return

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::__construct
ReflectionZendExtension::getAuthor
ReflectionZendExtension


Получение автора

ReflectionZendExtension::export
ReflectionZendExtension::getCopyright
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getAuthor

(PHP >= 5.4.0)

ReflectionZendExtension::getAuthor — Получение автора

Описание

public string ReflectionZendExtension::getAuthor ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::export
ReflectionZendExtension::getCopyright
ReflectionZendExtension


Получение строки авторских прав

ReflectionZendExtension::getAuthor
ReflectionZendExtension::getName
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getCopyright

(PHP >= 5.4.0)

ReflectionZendExtension::getCopyright — Получение строки авторских прав

Описание

public string ReflectionZendExtension::getCopyright ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::getAuthor
ReflectionZendExtension::getName
ReflectionZendExtension


Получение строки имени

ReflectionZendExtension::getCopyright
ReflectionZendExtension::getURL
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getName

(PHP >= 5.4.0)

ReflectionZendExtension::getName — Получение строки имени

Описание

public string ReflectionZendExtension::getName ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::getCopyright
ReflectionZendExtension::getURL
ReflectionZendExtension


Получение URL

ReflectionZendExtension::getName
ReflectionZendExtension::getVersion
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getURL

(PHP >= 5.4.0)

ReflectionZendExtension::getURL — Получение URL

Описание

public string ReflectionZendExtension::getURL ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::getName
ReflectionZendExtension::getVersion
ReflectionZendExtension


Получение номера версии

ReflectionZendExtension::getURL
ReflectionZendExtension::__toString
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getVersion

(PHP >= 5.4.0)

ReflectionZendExtension::getVersion — Получение номера версии

Описание

public string ReflectionZendExtension::getVersion ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::getURL
ReflectionZendExtension::__toString
ReflectionZendExtension


Преобразование в строку

ReflectionZendExtension::getVersion
ReflectionExtension
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::__toString

(PHP >= 5.4.0)

ReflectionZendExtension::__toString — Преобразование в строку

Описание

public string ReflectionZendExtension::__toString ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::getVersion
ReflectionExtension
ReflectionZendExtension


Класс ReflectionExtension

(PHP 5)

Введение

Класс ReflectionExtension сообщает информацию о модулях.

Обзор классов

ReflectionExtension implements Reflector {
/* Свойства */
public $name ;
/* Методы */
final private void __clone ( void )
__construct ( string $name )
public static string export ( string $name [, string $return = false ] )
public array getClasses ( void )
public array getClassNames ( void )
public array getConstants ( void )
public array getDependencies ( void )
public array getFunctions ( void )
public array getINIEntries ( void )
public string getName ( void )
public string getVersion ( void )
public void info ( void )
public void isPersistent ( void )
public void isTemporary ( void )
public string __toString ( void )
}

Свойства

name

Имя модуля. Значение свойсвтва совпадает с тем, что возвращает метод ReflectionExtension::getName()

Содержание

  • ReflectionExtension::__clone — Клонирует объект
  • ReflectionExtension::__construct — Создаёт объект класса ReflectionExtension
  • ReflectionExtension::export — Экспортирует модуль
  • ReflectionExtension::getClasses — Возвращает классы
  • ReflectionExtension::getClassNames — Получение имен классов
  • ReflectionExtension::getConstants — Получение констант
  • ReflectionExtension::getDependencies — Получение зависимостей
  • ReflectionExtension::getFunctions — Получение функций расширения
  • ReflectionExtension::getINIEntries — Получение ini-настроек расширения
  • ReflectionExtension::getName — Получение имени расширения
  • ReflectionExtension::getVersion — Получение версии расширения
  • ReflectionExtension::info — Вывод информации о расширении
  • ReflectionExtension::isPersistent — Определяет, является ли расширение постоянным
  • ReflectionExtension::isTemporary — Определяет, является ли расширение временным
  • ReflectionExtension::__toString — Преобразование в строку

User Contributed Notes

There are no user contributed notes for this page.
ReflectionZendExtension::__toString
ReflectionExtension::__clone
Reflection


Клонирует объект

ReflectionExtension
ReflectionExtension::__construct
ReflectionExtension
PHP Manual

ReflectionExtension::__clone

(PHP 5)

ReflectionExtension::__clone — Клонирует объект

Описание

final private void ReflectionExtension::__clone ( void )

clone-метод предотвращает клонирование объекта. Reflection-объекты не могут быть клонированы.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Метод ничего не возвращает, в случае вызова возникает фатальная ошибка.

Смотрите также

  • ReflectionExtension::__construct() - Создаёт объект класса ReflectionExtension
  • Клонирование объектов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension
ReflectionExtension::__construct
ReflectionExtension


Создаёт объект класса ReflectionExtension

ReflectionExtension::__clone
ReflectionExtension::export
ReflectionExtension
PHP Manual

ReflectionExtension::__construct

(PHP 5)

ReflectionExtension::__construct — Создаёт объект класса ReflectionExtension

Описание

ReflectionExtension::__construct ( string $name )

Создаёт объект (object) класса ReflectionExtension.

Список параметров

name

Имя модуля.

Возвращаемые значения

Объект (object) класса ReflectionExtension.

Примеры

Пример #1 Пример использования ReflectionExtension

<?php
$ext = new ReflectionExtension('Reflection');

printf('Модуль: %s (версия: %s)', $ext->getName(), $ext->getVersion());
?>

Результатом выполнения данного примера будет что-то подобное:

Модуль: Reflection (версия: $Revision: 316929 $)

Смотрите также

  • ReflectionExtension::info() - Вывод информации о расширении
  • Конструкторы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::__clone
ReflectionExtension::export
ReflectionExtension


Экспортирует модуль

ReflectionExtension::__construct
ReflectionExtension::getClasses
ReflectionExtension
PHP Manual

ReflectionExtension::export

(PHP 5)

ReflectionExtension::export — Экспортирует модуль

Описание

public static string ReflectionExtension::export ( string $name [, string $return = false ] )

Экспортирует отражённый модуль. Формат вывода этой функции такой же как и при CLI-параметре --re [extension].

Список параметров

name

Экспортируемый объект Reflection.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Если параметр return установлен в TRUE, тогда экспортируемый объект будет возвращен как string, иначе будет возвращен NULL.

Смотрите также

  • ReflectionExtension::info() - Вывод информации о расширении

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::__construct
ReflectionExtension::getClasses
ReflectionExtension


Возвращает классы

ReflectionExtension::export
ReflectionExtension::getClassNames
ReflectionExtension
PHP Manual

ReflectionExtension::getClasses

(PHP 5)

ReflectionExtension::getClasses — Возвращает классы

Описание

public array ReflectionExtension::getClasses ( void )

Возвращает список классов модуля.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив объектов класса ReflectionClass, по одному на каждый класс модуля. Если не задано ни одного класса, то возвращается пустой массив.

Примеры

Пример #1 Пример использования ReflectionExtension::getClasses()

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClasses());
?>

Результатом выполнения данного примера будет что-то подобное:

array(1) {
  ["XMLWriter"]=>
  &object(ReflectionClass)#2 (1) {
    ["name"]=>
    string(9) "XMLWriter"
  }
}

Смотрите также

  • ReflectionExtension::getClassNames() - Получение имен классов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::export
ReflectionExtension::getClassNames
ReflectionExtension


Получение имен классов

ReflectionExtension::getClasses
ReflectionExtension::getConstants
ReflectionExtension
PHP Manual

ReflectionExtension::getClassNames

(PHP 5)

ReflectionExtension::getClassNames — Получение имен классов

Описание

public array ReflectionExtension::getClassNames ( void )

Получает список имен классов, как они определены в расширении.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив array имен классов, определенных в расширении. Если никаких классов не определено, будет возвращен пустой массив.

Примеры

Пример #1 Пример использования ReflectionExtension::getClassNames()

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClassNames());
?>

Результатом выполнения данного примера будет что-то подобное:

array(1) {
  [0]=>
  string(9) "XMLWriter"
}

Смотрите также

  • ReflectionExtension::getClasses() - Возвращает классы
  • ReflectionExtension::getName() - Получение имени расширения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getClasses
ReflectionExtension::getConstants
ReflectionExtension


Получение констант

ReflectionExtension::getClassNames
ReflectionExtension::getDependencies
ReflectionExtension
PHP Manual

ReflectionExtension::getConstants

(PHP 5)

ReflectionExtension::getConstants — Получение констант

Описание

public array ReflectionExtension::getConstants ( void )

Получает определенные в расширении константы.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Ассоциативный массив с именами констант в качестве ключей.

Примеры

Пример #1 Пример использования ReflectionExtension::getConstants()

<?php
$ext = new ReflectionExtension('DOM');

print_r($ext->getConstants());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [XML_ELEMENT_NODE] => 1
    [XML_ATTRIBUTE_NODE] => 2
    [XML_TEXT_NODE] => 3
    [XML_CDATA_SECTION_NODE] => 4
    [XML_ENTITY_REF_NODE] => 5
    [XML_ENTITY_NODE] => 6
    [XML_PI_NODE] => 7
    [XML_COMMENT_NODE] => 8
    [XML_DOCUMENT_NODE] => 9
    [XML_DOCUMENT_TYPE_NODE] => 10
    [XML_DOCUMENT_FRAG_NODE] => 11
    [XML_NOTATION_NODE] => 12
    [XML_HTML_DOCUMENT_NODE] => 13
    [XML_DTD_NODE] => 14
    [XML_ELEMENT_DECL_NODE] => 15
    [XML_ATTRIBUTE_DECL_NODE] => 16
    [XML_ENTITY_DECL_NODE] => 17
    [XML_NAMESPACE_DECL_NODE] => 18
    [XML_LOCAL_NAMESPACE] => 18
    [XML_ATTRIBUTE_CDATA] => 1
    [XML_ATTRIBUTE_ID] => 2
    [XML_ATTRIBUTE_IDREF] => 3
    [XML_ATTRIBUTE_IDREFS] => 4
    [XML_ATTRIBUTE_ENTITY] => 6
    [XML_ATTRIBUTE_NMTOKEN] => 7
    [XML_ATTRIBUTE_NMTOKENS] => 8
    [XML_ATTRIBUTE_ENUMERATION] => 9
    [XML_ATTRIBUTE_NOTATION] => 10
    [DOM_PHP_ERR] => 0
    [DOM_INDEX_SIZE_ERR] => 1
    [DOMSTRING_SIZE_ERR] => 2
    [DOM_HIERARCHY_REQUEST_ERR] => 3
    [DOM_WRONG_DOCUMENT_ERR] => 4
    [DOM_INVALID_CHARACTER_ERR] => 5
    [DOM_NO_DATA_ALLOWED_ERR] => 6
    [DOM_NO_MODIFICATION_ALLOWED_ERR] => 7
    [DOM_NOT_FOUND_ERR] => 8
    [DOM_NOT_SUPPORTED_ERR] => 9
    [DOM_INUSE_ATTRIBUTE_ERR] => 10
    [DOM_INVALID_STATE_ERR] => 11
    [DOM_SYNTAX_ERR] => 12
    [DOM_INVALID_MODIFICATION_ERR] => 13
    [DOM_NAMESPACE_ERR] => 14
    [DOM_INVALID_ACCESS_ERR] => 15
    [DOM_VALIDATION_ERR] => 16
)

Смотрите также

  • ReflectionExtension::getINIEntries() - Получение ini-настроек расширения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getClassNames
ReflectionExtension::getDependencies
ReflectionExtension


Получение зависимостей

ReflectionExtension::getConstants
ReflectionExtension::getFunctions
ReflectionExtension
PHP Manual

ReflectionExtension::getDependencies

(PHP 5)

ReflectionExtension::getDependencies — Получение зависимостей

Описание

public array ReflectionExtension::getDependencies ( void )

Получает список требуемых и конфликтующих зависимостей.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Ассоциативный массив array, ключами которого являются зависимости, а значениями следующие записи: Required, Optional или Conflicts.

Примеры

Пример #1 Пример использования ReflectionExtension::getDependencies()

<?php
$dom = new ReflectionExtension('dom');

print_r($dom->getDependencies());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [libxml] => Required
    [domxml] => Conflicts
)

Смотрите также

  • ReflectionClass::getVersion()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getConstants
ReflectionExtension::getFunctions
ReflectionExtension


Получение функций расширения

ReflectionExtension::getDependencies
ReflectionExtension::getINIEntries
ReflectionExtension
PHP Manual

ReflectionExtension::getFunctions

(PHP 5)

ReflectionExtension::getFunctions — Получение функций расширения

Описание

public array ReflectionExtension::getFunctions ( void )

Получает список определенных в расширении функций.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Ассоциативный массив объектов ReflectionFunction, в котором ключами являются названия определенных в расширении функций. Если функций в расширении не определено, будет возвращен пустой массив.

Примеры

Пример #1 Пример использования ReflectionExtension::getFunctions()

<?php
$dom = new ReflectionExtension('SimpleXML');

print_r($dom->getFunctions());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [simplexml_load_file] => ReflectionFunction Object
        (
            [name] => simplexml_load_file
        )

    [simplexml_load_string] => ReflectionFunction Object
        (
            [name] => simplexml_load_string
        )

    [simplexml_import_dom] => ReflectionFunction Object
        (
            [name] => simplexml_import_dom
        )

)

Смотрите также

  • ReflectionExtension::getClasses() - Возвращает классы
  • get_extension_funcs() - Возвращает массив имен функций модуля

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getDependencies
ReflectionExtension::getINIEntries
ReflectionExtension


Получение ini-настроек расширения

ReflectionExtension::getFunctions
ReflectionExtension::getName
ReflectionExtension
PHP Manual

ReflectionExtension::getINIEntries

(PHP 5)

ReflectionExtension::getINIEntries — Получение ini-настроек расширения

Описание

public array ReflectionExtension::getINIEntries ( void )

Получает ini-настройки расширения.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Ассоциативный массив array, в котором ключи - имена ini-настроек, а значения - соответствующие значения настроек.

Примеры

Пример #1 Пример использования ReflectionExtension::getINIEntries()

<?php
$ext = new ReflectionExtension('mysql');

print_r($ext->getINIEntries());
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [mysql.allow_persistent] => 1
    [mysql.max_persistent] => -1
    [mysql.max_links] => -1
    [mysql.default_host] =>
    [mysql.default_user] =>
    [mysql.default_password] =>
    [mysql.default_port] =>
    [mysql.default_socket] =>
    [mysql.connect_timeout] => 60
    [mysql.trace_mode] =>
    [mysql.allow_local_infile] => 1
    [mysql.cache_size] => 2000
)

Смотрите также

  • ReflectionExtension::getConstants() - Получение констант

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getFunctions
ReflectionExtension::getName
ReflectionExtension


Получение имени расширения

ReflectionExtension::getINIEntries
ReflectionExtension::getVersion
ReflectionExtension
PHP Manual

ReflectionExtension::getName

(PHP 5)

ReflectionExtension::getName — Получение имени расширения

Описание

public string ReflectionExtension::getName ( void )

Получает имя расширения.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя расширения.

Примеры

Пример #1 Пример использования ReflectionExtension::getName()

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getName());
?>

Результатом выполнения данного примера будет что-то подобное:

string(6) "mysqli"

Смотрите также

  • ReflectionExtension::getClassNames() - Получение имен классов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getINIEntries
ReflectionExtension::getVersion
ReflectionExtension


Получение версии расширения

ReflectionExtension::getName
ReflectionExtension::info
ReflectionExtension
PHP Manual

ReflectionExtension::getVersion

(PHP 5)

ReflectionExtension::getVersion — Получение версии расширения

Описание

public string ReflectionExtension::getVersion ( void )

Получает версию расширения.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Версия расширения.

Примеры

Пример #1 Пример использования ReflectionExtension::getVersion()

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getVersion());
?>

Результатом выполнения данного примера будет что-то подобное:

string(3) "0.1"

Смотрите также

  • ReflectionExtension::info() - Вывод информации о расширении

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getName
ReflectionExtension::info
ReflectionExtension


Вывод информации о расширении

ReflectionExtension::getVersion
ReflectionExtension::isPersistent
ReflectionExtension
PHP Manual

ReflectionExtension::info

(PHP 5)

ReflectionExtension::info — Вывод информации о расширении

Описание

public void ReflectionExtension::info ( void )

Выводит отрывок"phpinfo()", касающийся заданного расширения.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Информация о расширении.

Примеры

Пример #1 Пример использования ReflectionExtension::info()

<?php
$ext = new ReflectionExtension('mysqli');
$ext->info();
?>

Результатом выполнения данного примера будет что-то подобное:

mysqli

MysqlI Support => enabled
Client API library version => mysqlnd 5.0.5-dev - 081106 - $Revision: 315808 $
Active Persistent Links => 0
Inactive Persistent Links => 0
Active Links => 0
Persistent cache => enabled
put_hits => 0
put_misses => 0
get_hits => 0
get_misses => 0
size => 2000
free_items => 2000
references => 2

Directive => Local Value => Master Value
mysqli.max_links => Unlimited => Unlimited
mysqli.max_persistent => Unlimited => Unlimited
mysqli.allow_persistent => On => On
mysqli.default_host => no value => no value
mysqli.default_user => no value => no value
mysqli.default_pw => no value => no value
mysqli.default_port => 3306 => 3306
mysqli.default_socket => no value => no value
mysqli.reconnect => Off => Off
mysqli.allow_local_infile => On => On
mysqli.cache_size => 2000 => 2000

Смотрите также

  • ReflectionExtension::getName() - Получение имени расширения
  • phpinfo() - Outputs information about PHP's configuration

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::getVersion
ReflectionExtension::isPersistent
ReflectionExtension


Определяет, является ли расширение постоянным

ReflectionExtension::info
ReflectionExtension::isTemporary
ReflectionExtension
PHP Manual

ReflectionExtension::isPersistent

(PHP >= 5.4.0)

ReflectionExtension::isPersistent — Определяет, является ли расширение постоянным

Описание

public void ReflectionExtension::isPersistent ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE для расширений, загруженных посредствомextension, FALSE в противном случае.

Смотрите также

  • ReflectionExtension::isTemporary() - Определяет, является ли расширение временным

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::info
ReflectionExtension::isTemporary
ReflectionExtension


Определяет, является ли расширение временным

ReflectionExtension::isPersistent
ReflectionExtension::__toString
ReflectionExtension
PHP Manual

ReflectionExtension::isTemporary

(PHP >= 5.4.0)

ReflectionExtension::isTemporary — Определяет, является ли расширение временным

Описание

public void ReflectionExtension::isTemporary ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE для расширений, загруженных функцией dl(), FALSE в противном случае.

Смотрите также

  • ReflectionExtension::isPersistent() - Определяет, является ли расширение постоянным

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::isPersistent
ReflectionExtension::__toString
ReflectionExtension


Преобразование в строку

ReflectionExtension::isTemporary
ReflectionFunction
ReflectionExtension
PHP Manual

ReflectionExtension::__toString

(PHP 5)

ReflectionExtension::__toString — Преобразование в строку

Описание

public string ReflectionExtension::__toString ( void )

Выполняет экспорт расширения и возвращает его в виде строки string. Это то же самое, что и вызов ReflectionExtension::export() с аргументом return равным TRUE.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает экспортированное расширение в виде строки тем же образом, что и ReflectionExtension::export().

Смотрите также

  • ReflectionExtension::__construct() - Создаёт объект класса ReflectionExtension
  • ReflectionExtension::export() - Экспортирует модуль
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionExtension::isTemporary
ReflectionFunction
ReflectionExtension


Класс ReflectionFunction

(PHP 5)

Введение

Класс ReflectionFunction сообщает информацию о функциях.

Обзор классов

ReflectionFunction extends ReflectionFunctionAbstract implements Reflector {
/* Константы */
const integer IS_DEPRECATED = 262144 ;
/* Свойства */
public $name ;
/* Методы */
public __construct ( mixed $name )
public static string export ( string $name [, string $return ] )
public Closure getClosure ( void )
public mixed invoke ([ mixed $parameter [, mixed $... ]] )
public mixed invokeArgs ( array $args )
public bool isDisabled ( void )
public string __toString ( void )
/* Наследуемые методы */
final private void ReflectionFunctionAbstract::__clone ( void )
public object ReflectionFunctionAbstract::getClosureThis ( void )
public string ReflectionFunctionAbstract::getDocComment ( void )
public int ReflectionFunctionAbstract::getEndLine ( void )
public ReflectionExtension ReflectionFunctionAbstract::getExtension ( void )
public string ReflectionFunctionAbstract::getExtensionName ( void )
public string ReflectionFunctionAbstract::getFileName ( void )
public string ReflectionFunctionAbstract::getName ( void )
public string ReflectionFunctionAbstract::getNamespaceName ( void )
public int ReflectionFunctionAbstract::getNumberOfParameters ( void )
public int ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void )
public array ReflectionFunctionAbstract::getParameters ( void )
public string ReflectionFunctionAbstract::getShortName ( void )
public int ReflectionFunctionAbstract::getStartLine ( void )
public array ReflectionFunctionAbstract::getStaticVariables ( void )
public bool ReflectionFunctionAbstract::inNamespace ( void )
public bool ReflectionFunctionAbstract::isClosure ( void )
public bool ReflectionFunctionAbstract::isDeprecated ( void )
public bool ReflectionFunctionAbstract::isInternal ( void )
public bool ReflectionFunctionAbstract::isUserDefined ( void )
public bool ReflectionFunctionAbstract::returnsReference ( void )
abstract public void ReflectionFunctionAbstract::__toString ( void )
}

Свойства

name

Имя функции. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

Предопределенные константы

Модификаторы ReflectionFunction

ReflectionFunction::IS_DEPRECATED

Указывает на то, что функция устарела (deprecated).

Содержание

  • ReflectionFunction::__construct — Конструктор класса ReflectionFunction
  • ReflectionFunction::export — Экспорт функции
  • ReflectionFunction::getClosure — Возвращает динамически созданное замыкание для функции
  • ReflectionFunction::invoke — Вызывает функцию
  • ReflectionFunction::invokeArgs — Вызов функции с передачей аргументов
  • ReflectionFunction::isDisabled — Проверяет, что функция отключена
  • ReflectionFunction::__toString — Представление в виде строки

User Contributed Notes

Lorenz R.S. 12-Aug-2011 01:24
Here is a concise example of ReflectionFunction usage for Parameter Reflection / introspection (e.g. to automatically generate API descriptions)

<?php
$properties = $reflector->getProperties();
$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
    //invokes ■ReflectionParameter::__toString
    print $param;
}
?>

prints:

Parameter #0 [ <required> $regex ]
Parameter #1 [ <required> $replace ]
Parameter #2 [ <required> $subject ]
Parameter #3 [ <optional> $limit ]
Parameter #4 [ <optional> &$count ]
uramihsayibok, gmail, com 24-Oct-2010 03:00
ReflectionFunction will not work on class methods - instance or static. That is,

<?php

class A {
    function B() {}
    static function C() {}
}

new ReflectionFunction("A::B"); // throws "does not exist" ReflectionException
new ReflectionFunction("A::C"); // ditto

?>

The array syntax for method callbacks does not work either but throws a warning instead (__construct wants a string, not an array).
Since I don't know ahead of time whether something is a function or a class method, I have this:

<?php

function ReflectionFunctionFactory($callback) {
    if (is_array($callback)) {
        // must be a class method
        list($class, $method) = $callback;
        return new ReflectionMethod($class, $method);
    }

    // class::method syntax
    if (is_string($callback) && strpos($callback, "::") !== false) {
        list($class, $method) = explode("::", $callback);
        return new ReflectionMethod($class, $method);
    }

    // objects as functions (PHP 5.3+)
    if (version_compare(PHP_VERSION, "5.3.0", ">=") && method_exists($callback, "__invoke")) {
        return new ReflectionMethod($callback, "__invoke");
    }

    // assume it's a function
    return new ReflectionFunction($callback);
}

?>
ReflectionExtension::__toString
ReflectionFunction::__construct
Reflection


Конструктор класса ReflectionFunction

ReflectionFunction
ReflectionFunction::export
ReflectionFunction
PHP Manual

ReflectionFunction::__construct

(PHP 5)

ReflectionFunction::__construct — Конструктор класса ReflectionFunction

Описание

public ReflectionFunction::__construct ( mixed $name )

Создает объект класса ReflectionFunction.

Список параметров

name

Имя reflection-функции или замыкания.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Объект класса ReflectionException, если аргумент name не содержит допустимой функции.

Список изменений

Версия | Описание
5.3.0 | name теперь может быть замыканием.

Примеры

Пример #1 Пример использования ReflectionFunction::__construct()

<?php
/**
 * Простой счетчик
 *
 * @return    int
 */
function counter1()
{
    static $c = 0;
    return ++$c;
}

/**
 * Другой счетчик
 *
 * @return    int
 */
$counter2 = function()
{
    static $d = 0;
    return ++$d;

};

function dumpReflectionFunction($func)
{
    // Вывод основной информации
    printf(
        "\n\n===> %s функция '%s'\n".
        "     объявлена в %s\n".
        "     строки с %d по %d\n",
        $func->isInternal() ? 'internal' : 'user-defined',
        $func->getName(),
        $func->getFileName(),
        $func->getStartLine(),
        $func->getEndline()
    );

    // Печать документации
    printf("---> Документация:\n %s\n", var_export($func->getDocComment(), 1));

    // Вывод статических переменных
    if ($statics = $func->getStaticVariables())
    {
        printf("---> Статические переменные: %s\n", var_export($statics, 1));
    }
}

// Создание объекта класса ReflectionFunction
dumpReflectionFunction(new ReflectionFunction('counter1'));
dumpReflectionFunction(new ReflectionFunction($counter2));
?>

Результатом выполнения данного примера будет что-то подобное:

===> user-defined функция 'counter1'
     объявлена в Z:\reflectcounter.php
     строки с 7 по 11
---> Документация:
 '/**
 * Простой счетчик
 *
 * @return    int
 */'
---> Статические переменные: array (
  'c' => 0,
)

===> user-defined функция '{closure}'
     объявлена в Z:\reflectcounter.php
     строки с 18 по 23
---> Документация:
 '/**
 * Другой счетчик
 *
 * @return    int
 */'
---> Статические переменные: array (
  'd' => 0,
)

Смотрите также

  • ReflectionMethod::__construct() - Конструктор класса ReflectionMethod
  • Конструкторы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunction
ReflectionFunction::export
ReflectionFunction


Экспорт функции

ReflectionFunction::__construct
ReflectionFunction::getClosure
ReflectionFunction
PHP Manual

ReflectionFunction::export

(PHP 5)

ReflectionFunction::export — Экспорт функции

Описание

public static string ReflectionFunction::export ( string $name [, string $return ] )

Экспортирует отображение функцию.

Список параметров

name

Экспортируемый объект Reflection.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Если параметр return установлен в TRUE, тогда экспортируемый объект будет возвращен как string, иначе будет возвращен NULL.

Смотрите также

  • ReflectionFunction::invoke() - Вызывает функцию

User Contributed Notes

hytest at gmail dot com 22-Nov-2011 08:04
Example:

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo ReflectionFunction::export('title',true);

?>

Output:

Function [ <user> function title ] {
  @@ /path/to/file.php 2 - 5

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}
ReflectionFunction::__construct
ReflectionFunction::getClosure
ReflectionFunction


Возвращает динамически созданное замыкание для функции

ReflectionFunction::export
ReflectionFunction::invoke
ReflectionFunction
PHP Manual

ReflectionFunction::getClosure

(Информация о версии неизвестна, возможно, только в SVN)

ReflectionFunction::getClosure — Возвращает динамически созданное замыкание для функции

Описание

public Closure ReflectionFunction::getClosure ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает Closure. Возвращает NULL в случае ошибки.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunction::export
ReflectionFunction::invoke
ReflectionFunction


Вызывает функцию

ReflectionFunction::getClosure
ReflectionFunction::invokeArgs
ReflectionFunction
PHP Manual

ReflectionFunction::invoke

(PHP 5)

ReflectionFunction::invoke — Вызывает функцию

Описание

public mixed ReflectionFunction::invoke ([ mixed $parameter [, mixed $... ]] )

Вызывает отображенную функцию.

Список параметров

args

Передаваемые функции аргументы. Может содержать переменное число аргументов функциям, схожим с call_user_func().

Возвращаемые значения

Возвращает результат выполнения вызванной функции.

Примеры

Пример #1 Пример использования ReflectionFunction::invoke()

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invoke('Dr', 'Phil');
?>

Результат выполнения данного примера:

Dr. Phil

Примечания

Замечание:

Если функция имеет аргументы, которые должны быть ссылками, то они должны быть ссылками и в переданном спике аргументов.

Смотрите также

  • ReflectionFunction::export() - Экспорт функции
  • __invoke()
  • call_user_func() - Вызывает пользовательскую функцию, указанную в первом параметре

User Contributed Notes

spark at limao dot com dot br 10-Jun-2011 10:55
I know Reflections classes have a lot of power, but sometimes all we need is to store a annonymus function or even create a simple callback somewhere.

so here it is, the Callback class:
<?php
    class Callback{
        private $name = false;

        public function Callback($obj,$call=false){
            $name = array($obj);
            if($call) $name[] = $call;

            $this->name = $name;
        }
        public function invoke($params=array()){
            return call_user_func_array($this->name,$params);
        }
    }
?>

Usage:
<?php
    function sayName(){
        return "goku";
    }

    $myVar = new Callback("sayName");

    echo "Hi, I am ".$myVar->invoke()."!";

    //also works with methods: new Callback($obj,"method");
?>
ReflectionFunction::getClosure
ReflectionFunction::invokeArgs
ReflectionFunction


Вызов функции с передачей аргументов

ReflectionFunction::invoke
ReflectionFunction::isDisabled
ReflectionFunction
PHP Manual

ReflectionFunction::invokeArgs

(PHP 5 >= 5.1.0)

ReflectionFunction::invokeArgs — Вызов функции с передачей аргументов

Описание

public mixed ReflectionFunction::invokeArgs ( array $args )

Вызывает функцию и передает ей аргументы в виде массива.

Список параметров

args

Передаваемые функции аргументы в виде массива. Поведение функции схоже с call_user_func_array().

Возвращаемые значения

Возвращает результат выполнения вызванной функции.

Примеры

Пример #1 Пример использования ReflectionFunction::invokeArgs()

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invokeArgs(array('Dr', 'Phil'));
?>

Результат выполнения данного примера:

Dr. Phil

Пример #2 Пример использования ReflectionFunction::invokeArgs() со ссылками на аргументы

<?php
function get_false_conditions(array $conditions, array &$false_conditions)
{
    foreach ($conditions as $condition) {
        if (!$condition) {
            $false_conditions[] = $condition;
        }
    }
}

$function_ref     = new ReflectionFunction('get_false_conditions');

$conditions       = array(true, false, -1, 0, 1);
$false_conditions = array();

$function_ref->invokeArgs(array($conditions, &$false_conditions));

var_dump($false_conditions);
?>

Результат выполнения данного примера:

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

Примечания

Замечание:

Если функция имеет аргументы, которые должны быть ссылками, то они должны быть ссылками и в переданном спике аргументов.

Смотрите также

  • ReflectionFunction::invoke() - Вызывает функцию
  • ReflectionFunctionAbstract::getNumberOfParameters() - Получает количество аргументов
  • __invoke()
  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров

User Contributed Notes

Andrea Giammarchi 16-Feb-2008 06:41
I encountered a weird problem with ReflectionFunction, described in ticket 44139 of PHP Bugs.

If for some reason you need to call with invoke, or invokeArgs, a function like array_unshift (that accepts internally the array by reference) you could use this code to avoid the generated warning or fatal error.

<?php
function unshift(){
    $ref        = new ReflectionFunction('array_unshift');
    $arguments    = func_get_args();
    return        $ref->invokeArgs(array_merge(array(&$this->arr), $arguments));
}
?>

I don't know about performances (you can create an array manually too, starting from array(&$this->something) and adding arguments). However, it seems to work correctly without problems, at least until the send by reference will be usable with one single value ...
ReflectionFunction::invoke
ReflectionFunction::isDisabled
ReflectionFunction


Проверяет, что функция отключена

ReflectionFunction::invokeArgs
ReflectionFunction::__toString
ReflectionFunction
PHP Manual

ReflectionFunction::isDisabled

(PHP 5)

ReflectionFunction::isDisabled — Проверяет, что функция отключена

Описание

public bool ReflectionFunction::isDisabled ( void )

Проверяет, отключена ли функция, с помощью директивы disable_functions.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если функция отключена, FALSE противном случае.

Смотрите также

  • ReflectionFunctionAbstract::isUserDefined() - Проверяет, является ли функция определенной пользователем
  • Директива disable_functions

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunction::invokeArgs
ReflectionFunction::__toString
ReflectionFunction


Представление в виде строки

ReflectionFunction::isDisabled
ReflectionFunctionAbstract
ReflectionFunction
PHP Manual

ReflectionFunction::__toString

(PHP 5)

ReflectionFunction::__toString — Представление в виде строки

Описание

public string ReflectionFunction::__toString ( void )

Представление в виде строки.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Результат выполнения схож с выводом ReflectionFunction::export().

Примеры

Пример #1 Пример использования ReflectionFunction::__toString()

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo new ReflectionFunction('title');
?>

Результатом выполнения данного примера будет что-то подобное:

Function [ <user> function person ] {
  @@ Command line code 1 - 1

  - Parameters [2] {
    Parameter #0 [ <required> $prefix ]
    Parameter #1 [ <required> $name ]
  }
}

Смотрите также

  • ReflectionFunction::export() - Экспорт функции
  • ReflectionClass::clone()
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunction::isDisabled
ReflectionFunctionAbstract
ReflectionFunction


Класс ReflectionFunctionAbstract

(PHP 5)

Введение

Является родительским классом для ReflectionFunction, более подробную информацию смотрите в описании этого дочернего класса.

Обзор классов

ReflectionFunctionAbstract implements Reflector {
/* Свойства */
public $name ;
/* Методы */
final private void __clone ( void )
public object getClosureThis ( void )
public string getDocComment ( void )
public int getEndLine ( void )
public ReflectionExtension getExtension ( void )
public string getExtensionName ( void )
public string getFileName ( void )
public string getName ( void )
public string getNamespaceName ( void )
public int getNumberOfParameters ( void )
public int getNumberOfRequiredParameters ( void )
public array getParameters ( void )
public string getShortName ( void )
public int getStartLine ( void )
public array getStaticVariables ( void )
public bool inNamespace ( void )
public bool isClosure ( void )
public bool isDeprecated ( void )
public bool isInternal ( void )
public bool isUserDefined ( void )
public bool returnsReference ( void )
abstract public void __toString ( void )
}

Свойства

name

Имя функции. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

Содержание

  • ReflectionFunctionAbstract::__clone — Копирующий конструктор
  • ReflectionFunctionAbstract::getClosureThis — Возвращает указатель this замыкания
  • ReflectionFunctionAbstract::getDocComment — Получает документируемый комментарий
  • ReflectionFunctionAbstract::getEndLine — Получает номер строки завершения описания функции
  • ReflectionFunctionAbstract::getExtension — Получает информацию о расширении
  • ReflectionFunctionAbstract::getExtensionName — Получение имени расширения
  • ReflectionFunctionAbstract::getFileName — Получает имя файла
  • ReflectionFunctionAbstract::getName — Получает имя функции
  • ReflectionFunctionAbstract::getNamespaceName — Получение имени пространства имен
  • ReflectionFunctionAbstract::getNumberOfParameters — Получает количество аргументов
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Получает количество обязательных аргументов
  • ReflectionFunctionAbstract::getParameters — Получает аргументы
  • ReflectionFunctionAbstract::getShortName — Получает короткое имя функции
  • ReflectionFunctionAbstract::getStartLine — Получает начальный номер строки
  • ReflectionFunctionAbstract::getStaticVariables — Получает статические переменные
  • ReflectionFunctionAbstract::inNamespace — Проверяет, находится ли функция в пространстве имен
  • ReflectionFunctionAbstract::isClosure — Проверяет, является ли функция замыканием
  • ReflectionFunctionAbstract::isDeprecated — Проверяет, является ли функция устаревшей
  • ReflectionFunctionAbstract::isInternal — Проверяет, является ли функция внутренней
  • ReflectionFunctionAbstract::isUserDefined — Проверяет, является ли функция определенной пользователем
  • ReflectionFunctionAbstract::returnsReference — Проверяет, что функция возвращает ссылку
  • ReflectionFunctionAbstract::__toString — Преобразование в строку

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunction::__toString
ReflectionFunctionAbstract::__clone
Reflection


Копирующий конструктор

ReflectionFunctionAbstract
ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::__clone

(PHP 5)

ReflectionFunctionAbstract::__clone — Копирующий конструктор

Описание

final private void ReflectionFunctionAbstract::__clone ( void )

Копирует функцию.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Смотрите также

  • Копирование объектов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract
ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract


Возвращает указатель this замыкания

ReflectionFunctionAbstract::__clone
ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getClosureThis

(Информация о версии неизвестна, возможно, только в SVN)

ReflectionFunctionAbstract::getClosureThis — Возвращает указатель this замыкания

Описание

public object ReflectionFunctionAbstract::getClosureThis ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает указатель $this. Возвращает NULL в случае ошибки.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::__clone
ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract


Получает документируемый комментарий

ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getDocComment

(PHP 5 >= 5.1.0)

ReflectionFunctionAbstract::getDocComment — Получает документируемый комментарий

Описание

public string ReflectionFunctionAbstract::getDocComment ( void )

Получает документируемый комментарий из описания функции.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Комментарий, если он есть, FALSE в противном случае.

Смотрите также

  • ReflectionFunctionAbstract::getStartLine() - Получает начальный номер строки

User Contributed Notes

jens dot kohl+php at gmail dot com 26-Mar-2012 11:19
Beware when you try to use the getDocComment() methods with eAccelerator turned on. eAccelerator »optimizes« your code in a way that it removes any comments from your source. So at runtime you're not able to get any comments and therefor getDocComments return false.
bruno at vault7 dot com 12-Nov-2009 11:09
In order to retrieve a comment with this method, the comment must be imediately before the class, function or method, start with /** and end with */
ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract


Получает номер строки завершения описания функции

ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getEndLine

(PHP 5)

ReflectionFunctionAbstract::getEndLine — Получает номер строки завершения описания функции

Описание

public int ReflectionFunctionAbstract::getEndLine ( void )

Получает номер строки завершения описания функции.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Номер последней строки описания определенной пользователем функции либо FALSE, если он неизвестен.

Смотрите также

  • ReflectionFunctionAbstract::getStartLine() - Получает начальный номер строки

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract


Получает информацию о расширении

ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getExtension

(PHP 5)

ReflectionFunctionAbstract::getExtension — Получает информацию о расширении

Описание

public ReflectionExtension ReflectionFunctionAbstract::getExtension ( void )

Получение информации о расширении, в состав которого входит функция.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Информация о расширении в виде объекта ReflectionExtension.

Смотрите также

  • ReflectionFunctionAbstract::getExtensionName() - Получение имени расширения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract


Получение имени расширения

ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getExtensionName

(PHP 5)

ReflectionFunctionAbstract::getExtensionName — Получение имени расширения

Описание

public string ReflectionFunctionAbstract::getExtensionName ( void )

Получение имени расширения.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя расширения.

Смотрите также

  • ReflectionFunctionAbstract::getExtension() - Получает информацию о расширении

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract


Получает имя файла

ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getFileName

(PHP 5)

ReflectionFunctionAbstract::getFileName — Получает имя файла

Описание

public string ReflectionFunctionAbstract::getFileName ( void )

Получает имя файла из определенной пользователем функции.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя файла.

Смотрите также

  • ReflectionFunctionAbstract::getNamespaceName() - Получение имени пространства имен

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract


Получает имя функции

ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getName

(PHP 5)

ReflectionFunctionAbstract::getName — Получает имя функции

Описание

public string ReflectionFunctionAbstract::getName ( void )

Получение имени функции.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя функции.

Смотрите также

  • ReflectionFunctionAbstract::getExtensionName() - Получение имени расширения
  • ReflectionFunctionAbstract::isUserDefined() - Проверяет, является ли функция определенной пользователем

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract


Получение имени пространства имен

ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getNamespaceName

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::getNamespaceName — Получение имени пространства имен

Описание

public string ReflectionFunctionAbstract::getNamespaceName ( void )

Получение имени пространства имен, в котором определен класс.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя пространства имен.

Смотрите также

  • ReflectionFunctionAbstract::getFileName() - Получает имя файла
  • пространства имен

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract


Получает количество аргументов

ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getNumberOfParameters

(PHP 5 >= 5.0.3)

ReflectionFunctionAbstract::getNumberOfParameters — Получает количество аргументов

Описание

public int ReflectionFunctionAbstract::getNumberOfParameters ( void )

Получение количества аргументов в определении функции как обязательных, так и опциональных.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Число аргументов.

Смотрите также

  • ReflectionFunctionAbstract::getNumberOfRequiredParameters() - Получает количество обязательных аргументов
  • func_num_args() - Возвращает количество аргументов, переданных функции

User Contributed Notes

Robert Pitt ( LitePHP ) 11-Apr-2010 03:42
Working on a new MVC Application Framework i use this method to check how many arguments are required before calling the sub method!

Example

<?php
        $this->method_args_count = $this->CReflection
            ->getMethod($Route->getMethod())
            ->getNumberOfParameters();
        //Maybe be 5 but if uri is /controller/method/single_param/ we only of 1
        $this->params = $Route->getParams(); //0 in some cases

        if($this->method_args_count > count($this->params))
        {
            $this->difference = ($this->method_args_count - count($this->params));
            for($i=0;$i<=$this->difference;$i++)
            {
                $this->params[] = false;
            }
        }

        //Call the method with correct amount of params
        // but as false for params that have not been passed!
        call_user_func_array(array(new $this->obj,$Route->getMethod()),$this->params);
?>
ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract


Получает количество обязательных аргументов

ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getNumberOfRequiredParameters

(PHP 5 >= 5.0.3)

ReflectionFunctionAbstract::getNumberOfRequiredParameters — Получает количество обязательных аргументов

Описание

public int ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void )

Получение числа обязательных аргументов в определении функции.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Число обязательных аргументов.

Смотрите также

  • ReflectionFunctionAbstract::getNumberOfParameters() - Получает количество аргументов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract


Получает аргументы

ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getParameters

(PHP 5)

ReflectionFunctionAbstract::getParameters — Получает аргументы

Описание

public array ReflectionFunctionAbstract::getParameters ( void )

Получение аргументов в виде массива объектов ReflectionParameter.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Аргументы, представленные объектами ReflectionParameter.

Смотрите также

  • ReflectionFunctionAbstract::getNumberOfParameters() - Получает количество аргументов
  • func_get_args() - Возвращает массив, содержащий аргументы функции

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract


Получает короткое имя функции

ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getShortName

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::getShortName — Получает короткое имя функции

Описание

public string ReflectionFunctionAbstract::getShortName ( void )

Получение короткого имени функции (без указания пространства имен).

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Короткое имя функции.

Смотрите также

  • ReflectionFunctionAbstract::getNamespaceName() - Получение имени пространства имен
  • пространства имен

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract


Получает начальный номер строки

ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getStartLine

(PHP 5)

ReflectionFunctionAbstract::getStartLine — Получает начальный номер строки

Описание

public int ReflectionFunctionAbstract::getStartLine ( void )

Получение номера строки начала описания функции.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Стартовый номер строки.

Смотрите также

  • ReflectionFunctionAbstract::getEndLine() - Получает номер строки завершения описания функции

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract


Получает статические переменные

ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getStaticVariables

(PHP 5)

ReflectionFunctionAbstract::getStaticVariables — Получает статические переменные

Описание

public array ReflectionFunctionAbstract::getStaticVariables ( void )

Получение статических переменных.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив array статических переменных.

Смотрите также

  • ReflectionFunctionAbstract::getParameters() - Получает аргументы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract


Проверяет, находится ли функция в пространстве имен

ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::inNamespace

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::inNamespace — Проверяет, находится ли функция в пространстве имен

Описание

public bool ReflectionFunctionAbstract::inNamespace ( void )

Проверяет, что функция определена в пространстве имен.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если функция определена в пространстве имен, FALSE в противном случае.

Смотрите также

  • ReflectionFunctionAbstract::getNamespaceName() - Получение имени пространства имен
  • пространства имен

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract


Проверяет, является ли функция замыканием

ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isClosure

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::isClosure — Проверяет, является ли функция замыканием

Описание

public bool ReflectionFunctionAbstract::isClosure ( void )

Проверка, является ли функция замыканием.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если функция является замыканием, FALSE в противном случае.

Смотрите также

  • ReflectionFunctionAbstract::()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract


Проверяет, является ли функция устаревшей

ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isDeprecated

(PHP 5)

ReflectionFunctionAbstract::isDeprecated — Проверяет, является ли функция устаревшей

Описание

public bool ReflectionFunctionAbstract::isDeprecated ( void )

Проверяет, является ли функция устаревшей.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если функция устарела, FALSE в противном случае.

Примеры

Пример #1 Пример использования ReflectionFunctionAbstract::isDeprecated()

<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>

Результат выполнения данного примера:

bool(true)

Смотрите также

  • ReflectionFunctionAbstract::getDocComment() - Получает документируемый комментарий

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract


Проверяет, является ли функция внутренней

ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isInternal

(PHP 5)

ReflectionFunctionAbstract::isInternal — Проверяет, является ли функция внутренней

Описание

public bool ReflectionFunctionAbstract::isInternal ( void )

Проверяет, является ли функция внутренней, то есть не определенной пользователем.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если функция внутренняя, FALSE в противном случае.

Смотрите также

  • ReflectionFunctionAbstract::isUserDefined() - Проверяет, является ли функция определенной пользователем

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract


Проверяет, является ли функция определенной пользователем

ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract::returnsReference
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isUserDefined

(PHP 5)

ReflectionFunctionAbstract::isUserDefined — Проверяет, является ли функция определенной пользователем

Описание

public bool ReflectionFunctionAbstract::isUserDefined ( void )

Проверяет, является ли функция определенной пользователем, то есть это не внутренняя функция.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если функция определена пользователем, false; в противном случае.

Смотрите также

  • ReflectionFunctionAbstract::isInternal() - Проверяет, является ли функция внутренней

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract::returnsReference
ReflectionFunctionAbstract


Проверяет, что функция возвращает ссылку

ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract::__toString
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::returnsReference

(PHP 5)

ReflectionFunctionAbstract::returnsReference — Проверяет, что функция возвращает ссылку

Описание

public bool ReflectionFunctionAbstract::returnsReference ( void )

Проверяет, что функция возвращает ссылку.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если функция возвращает ссылку, FALSE в противном случае.

Смотрите также

  • ReflectionFunctionAbstract::isClosure() - Проверяет, является ли функция замыканием

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract::__toString
ReflectionFunctionAbstract


Преобразование в строку

ReflectionFunctionAbstract::returnsReference
ReflectionMethod
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::__toString

(PHP 5)

ReflectionFunctionAbstract::__toString — Преобразование в строку

Описание

abstract public void ReflectionFunctionAbstract::__toString ( void )

Представление в виде строки.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Строка.

Смотрите также

  • ReflectionClass::clone()
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionFunctionAbstract::returnsReference
ReflectionMethod
ReflectionFunctionAbstract


Класс ReflectionMethod

(PHP 5)

Введение

Класс ReflectionMethod сообщает информацию о методах.

Обзор классов

ReflectionMethod extends ReflectionFunctionAbstract implements Reflector {
/* Константы */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
const integer IS_ABSTRACT = 2 ;
const integer IS_FINAL = 4 ;
/* Свойства */
public $name ;
public $class ;
/* Методы */
public __construct ( mixed $class , string $name )
public static string export ( string $class , string $name [, bool $return = false ] )
public Closure getClosure ( string $object )
public ReflectionClass getDeclaringClass ( void )
public int getModifiers ( void )
public ReflectionMethod getPrototype ( void )
public mixed invoke ( object $object [, mixed $parameter [, mixed $... ]] )
public mixed invokeArgs ( object $object , array $args )
public bool isAbstract ( void )
public bool isConstructor ( void )
public bool isDestructor ( void )
public bool isFinal ( void )
public bool isPrivate ( void )
public bool isProtected ( void )
public bool isPublic ( void )
public bool isStatic ( void )
public void setAccessible ( bool $accessible )
public string __toString ( void )
/* Наследуемые методы */
final private void ReflectionFunctionAbstract::__clone ( void )
public object ReflectionFunctionAbstract::getClosureThis ( void )
public string ReflectionFunctionAbstract::getDocComment ( void )
public int ReflectionFunctionAbstract::getEndLine ( void )
public ReflectionExtension ReflectionFunctionAbstract::getExtension ( void )
public string ReflectionFunctionAbstract::getExtensionName ( void )
public string ReflectionFunctionAbstract::getFileName ( void )
public string ReflectionFunctionAbstract::getName ( void )
public string ReflectionFunctionAbstract::getNamespaceName ( void )
public int ReflectionFunctionAbstract::getNumberOfParameters ( void )
public int ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void )
public array ReflectionFunctionAbstract::getParameters ( void )
public string ReflectionFunctionAbstract::getShortName ( void )
public int ReflectionFunctionAbstract::getStartLine ( void )
public array ReflectionFunctionAbstract::getStaticVariables ( void )
public bool ReflectionFunctionAbstract::inNamespace ( void )
public bool ReflectionFunctionAbstract::isClosure ( void )
public bool ReflectionFunctionAbstract::isDeprecated ( void )
public bool ReflectionFunctionAbstract::isInternal ( void )
public bool ReflectionFunctionAbstract::isUserDefined ( void )
public bool ReflectionFunctionAbstract::returnsReference ( void )
abstract public void ReflectionFunctionAbstract::__toString ( void )
}

Свойства

name

Имя метода

class

Имя класса

Предопределенные константы

Модификаторы ReflectionMethod

ReflectionMethod::IS_STATIC

Указывает на то, что это статический метод.

ReflectionMethod::IS_PUBLIC

Указывает на то, что это публичный метод.

ReflectionMethod::IS_PROTECTED

Указывает на то, что это защищённый метод.

ReflectionMethod::IS_PRIVATE

Указывает на то, что это приватный метод.

ReflectionMethod::IS_ABSTRACT

Указывает на то, что это абстрактный метод.

ReflectionMethod::IS_FINAL

Указывает на то, что это финализированный метод.

Содержание

  • ReflectionMethod::__construct — Конструктор класса ReflectionMethod
  • ReflectionMethod::export — Экспорт отраженного метода
  • ReflectionMethod::getClosure — Возвращает динамически созданное замыкание для метода
  • ReflectionMethod::getDeclaringClass — Получает класс, объявляющий отображенный метод
  • ReflectionMethod::getModifiers — Получает модификаторы метода
  • ReflectionMethod::getPrototype — Получает прототип метода (если такой есть)
  • ReflectionMethod::invoke — Вызов
  • ReflectionMethod::invokeArgs — Вызов метода с передачей аргументов массивом
  • ReflectionMethod::isAbstract — Проверяет, является ли метод абстрактным
  • ReflectionMethod::isConstructor — Проверяет, является ли метод конструктором
  • ReflectionMethod::isDestructor — Проверяет, является ли метод деструктором
  • ReflectionMethod::isFinal — Проверяет, может ли метод иметь наследников (final)
  • ReflectionMethod::isPrivate — Проверяет, является ли метод частным (private)
  • ReflectionMethod::isProtected — Проверяет, является ли метод защищенным (protected)
  • ReflectionMethod::isPublic — Проверяет, является ли метод общедоступным (public)
  • ReflectionMethod::isStatic — Проверяет, является ли метод статическим
  • ReflectionMethod::setAccessible — Делает метод доступным
  • ReflectionMethod::__toString — Возвращает строковое представление объекта Reflection method

User Contributed Notes

webseiten dot designer at googlemail dot com 02-Apr-2011 11:53
Note that the public member $class contains the name of the class in which the method has been defined:

<?php
class A {public function __construct() {}}
class B extends A {}

$method = new ReflectionMethod('B', '__construct');
echo $method->class; // prints 'A'
?>
no dot prob at gmx dot net 02-Jun-2006 01:09
I have written a function which returns the value of a given DocComment tag.

Full example:

<?php

header('Content-Type: text/plain');

class Example
{
    /**
     * This is my DocComment!
     *
     * @DocTag: prints Hello World!
     */
    public function myMethod()
    {
        echo 'Hello World!';
    }
}

function getDocComment($str, $tag = '')
{
    if (empty($tag))
    {
        return $str;
    }

    $matches = array();
    preg_match("/".$tag.":(.*)(\\r\\n|\\r|\\n)/U", $str, $matches);

    if (isset($matches[1]))
    {
        return trim($matches[1]);
    }

    return '';
}

$method = new ReflectionMethod('Example', 'myMethod');

// will return Hello World!
echo getDocComment($method->getDocComment(), '@DocTag');

?>

Maybe you can add this functionality to the getDocComment methods of the reflection classes.
ReflectionFunctionAbstract::__toString
ReflectionMethod::__construct
Reflection


Конструктор класса ReflectionMethod

ReflectionMethod
ReflectionMethod::export
ReflectionMethod
PHP Manual

ReflectionMethod::__construct

(PHP 5)

ReflectionMethod::__construct — Конструктор класса ReflectionMethod

Описание

public ReflectionMethod::__construct ( mixed $class , string $name )

Создает новый объект класса ReflectionMethod.

Список параметров

class

Имя класса или объекта (экземпляра класса), содержащего метод.

name

Имя метода.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Исключение ReflectionException вызывается, если заданный метод не существует.

Примеры

Пример #1 Пример использования ReflectionMethod::__construct()

<?php
class Counter
{
    private static $c = 0;

    /**
     * Счетчик
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function increment()
    {
        return ++self::$c;
    }
}

// Создание экземпляра класса ReflectionMethod
$method = new ReflectionMethod('Counter', 'increment');

// Вывод основной информации
printf(
    "===> %s%s%s%s%s%s%s метод '%s' (%s)\n" .
    "     объявлен в %s\n" .
    "     строки с %d по %d\n" .
    "     имеет модификаторы %d[%s]\n",
        $method->isInternal() ? 'внутренний' : 'определенный пользователем',
        $method->isAbstract() ? ' abstract' : '',
        $method->isFinal() ? ' final' : '',
        $method->isPublic() ? ' public' : '',
        $method->isPrivate() ? ' private' : '',
        $method->isProtected() ? ' protected' : '',
        $method->isStatic() ? ' static' : '',
        $method->getName(),
        $method->isConstructor() ? 'конструктор' : 'обычный метод',
        $method->getFileName(),
        $method->getStartLine(),
        $method->getEndline(),
        $method->getModifiers(),
        implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// Вывод документируемого комментария
printf("---> Комментарий:\n %s\n", var_export($method->getDocComment(), 1));

// Вывод статических переменных, если есть
if ($statics= $method->getStaticVariables()) {
    printf("---> Статические переменные: %s\n", var_export($statics, 1));
}

// Вызов метода
printf("---> Результат вызова метода: ");
var_dump($method->invoke(NULL));
?>

Результатом выполнения данного примера будет что-то подобное:

===> определенный пользователем final public static метод 'increment' (обычный метод)
     объявлен в /Users/philip/cvs/phpdoc/test.php
     строки с 14 по 17
     имеет модификаторы 261[final public static]
---> Комментарий:
 '/**
     * Счетчик
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */'
---> Результат вызова метода: int(1)

Смотрите также

  • ReflectionMethod::export() - Экспорт отраженного метода
  • Конструкторы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod
ReflectionMethod::export
ReflectionMethod


Экспорт отраженного метода

ReflectionMethod::__construct
ReflectionMethod::getClosure
ReflectionMethod
PHP Manual

ReflectionMethod::export

(PHP 5)

ReflectionMethod::export — Экспорт отраженного метода

Описание

public static string ReflectionMethod::export ( string $class , string $name [, bool $return = false ] )

Экспортирует ReflectionMethod.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

class

Имя класса.

name

Имя метода.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Если параметр return установлен в TRUE, тогда экспортируемый объект будет возвращен как string, иначе будет возвращен NULL.

Смотрите также

  • ReflectionMethod::__construct() - Конструктор класса ReflectionMethod
  • ReflectionMethod::__toString() - Возвращает строковое представление объекта Reflection method

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::__construct
ReflectionMethod::getClosure
ReflectionMethod


Возвращает динамически созданное замыкание для метода

ReflectionMethod::export
ReflectionMethod::getDeclaringClass
ReflectionMethod
PHP Manual

ReflectionMethod::getClosure

(PHP >= 5.4.0)

ReflectionMethod::getClosure — Возвращает динамически созданное замыкание для метода

Описание

public Closure ReflectionMethod::getClosure ( string $object )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

object

Запрещен для статических методов, обязателен для остальных.

Возвращаемые значения

Возвращает замыкание Closure. Возвращает NULL в случае ошибки.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::export
ReflectionMethod::getDeclaringClass
ReflectionMethod


Получает класс, объявляющий отображенный метод

ReflectionMethod::getClosure
ReflectionMethod::getModifiers
ReflectionMethod
PHP Manual

ReflectionMethod::getDeclaringClass

(PHP 5)

ReflectionMethod::getDeclaringClass — Получает класс, объявляющий отображенный метод

Описание

public ReflectionClass ReflectionMethod::getDeclaringClass ( void )

Получает класс, объявляющий отображенный метод.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект ReflectionClass класса, частью которого является отображенный метод.

Примеры

Пример #1 Пример использования ReflectionMethod::getDeclaringClass()

<?php
class HelloWorld {

    protected function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
var_dump($reflectionMethod->getDeclaringClass());
?>

Результат выполнения данного примера:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(10) "HelloWorld"
}

Смотрите также

  • ReflectionMethod::isAbstract() - Проверяет, является ли метод абстрактным

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::getClosure
ReflectionMethod::getModifiers
ReflectionMethod


Получает модификаторы метода

ReflectionMethod::getDeclaringClass
ReflectionMethod::getPrototype
ReflectionMethod
PHP Manual

ReflectionMethod::getModifiers

(PHP 5)

ReflectionMethod::getModifiers — Получает модификаторы метода

Описание

public int ReflectionMethod::getModifiers ( void )

Возвращает битовое поле модификаторов доступа для метода.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Числовое представление модификаторов. Модификаторы перечислены ниже. Описания и значения этих модификаторов приведены в списке предопределенных констант.

Примеры

Пример #1 Пример использования ReflectionMethod::getModifiers()

<?php
class Testing
{
    final public static function foo()
    {
        return;
    }
    public function bar()
    {
        return;
    }
}

$foo = new ReflectionMethod('Testing', 'foo');

echo "Модификаторы метода foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Testing', 'bar');

echo "Модификаторы метода bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));
?>

Результатом выполнения данного примера будет что-то подобное:

Модификаторы метода foo():
261
final public static
Модификаторы метода bar():
65792
public

Смотрите также

  • Reflection::getModifierNames() - Получение имен модификаторов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::getDeclaringClass
ReflectionMethod::getPrototype
ReflectionMethod


Получает прототип метода (если такой есть)

ReflectionMethod::getModifiers
ReflectionMethod::invoke
ReflectionMethod
PHP Manual

ReflectionMethod::getPrototype

(PHP 5)

ReflectionMethod::getPrototype — Получает прототип метода (если такой есть)

Описание

public ReflectionMethod ReflectionMethod::getPrototype ( void )

Получает прототип метода.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект ReflectionMethod прототипа метода.

Ошибки

Исключение ReflectionException вызывается, если у метода нет прототипа.

Примеры

Пример #1 Пример использования ReflectionMethod::getPrototype()

<?php
class Hello {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}
class HelloWorld extends Hello {

    public function sayHelloTo($name) {
        return 'Hello world: ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
var_dump($reflectionMethod->getPrototype());
?>

Результат выполнения данного примера:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(10) "sayHelloTo"
  ["class"]=>
  string(5) "Hello"
}

Смотрите также

  • ReflectionMethod::getModifiers() - Получает модификаторы метода

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::getModifiers
ReflectionMethod::invoke
ReflectionMethod


Вызов

ReflectionMethod::getPrototype
ReflectionMethod::invokeArgs
ReflectionMethod
PHP Manual

ReflectionMethod::invoke

(PHP 5)

ReflectionMethod::invoke — Вызов

Описание

public mixed ReflectionMethod::invoke ( object $object [, mixed $parameter [, mixed $... ]] )

Вызывает отображенный метод.

Список параметров

object

Объект, метод которого требуется вызвать. Для статических методов передается null.

parameter

Ноль или более аргументов, передаваемых методу. Допускается передавать переменное число аргументов.

Возвращаемые значения

Возвращает результат выполнения метода.

Ошибки

Вызывает исключение ReflectionException, если в объекте object нет определения метода.

Вызывает исключение ReflectionException, если вызвать метод на исполнение не удалось.

Примеры

Пример #1 Пример использования ReflectionMethod::invoke()

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invoke(new HelloWorld(), 'Mike');
?>

Результат выполнения данного примера:

Hello Mike

Примечания

Замечание:

Если функция имеет аргументы, которые должны быть ссылками, то они должны быть ссылками и в переданном спике аргументов.

Смотрите также

  • ReflectionMethod::invokeArgs() - Вызов метода с передачей аргументов массивом
  • __invoke()
  • call_user_func() - Вызывает пользовательскую функцию, указанную в первом параметре

User Contributed Notes

templargrey at wp dot pl 21-Jul-2011 01:12
Seems that Reflection doesn`t resolve late static bindings - var_dump will show "string 'a' (length=1)".

<?php
class ParentClass { protected static $a = 'a'; static public function init() { return static::$a; } }
class ChildClass extends ParentClass { protected static $a = 'b'; }

$r = new ReflectionClass('ChildClass');
var_dump($r->getMethod('init')->invoke(null));
?>
rojaro at gmail dot com 10-Feb-2011 01:56
Note: If you want to invoke protected or private methods, you'll first have to make them accessible using the setAccessible() method (see http://php.net/reflectionmethod.setaccessible ).
ReflectionMethod::getPrototype
ReflectionMethod::invokeArgs
ReflectionMethod


Вызов метода с передачей аргументов массивом

ReflectionMethod::invoke
ReflectionMethod::isAbstract
ReflectionMethod
PHP Manual

ReflectionMethod::invokeArgs

(PHP 5 >= 5.1.0)

ReflectionMethod::invokeArgs — Вызов метода с передачей аргументов массивом

Описание

public mixed ReflectionMethod::invokeArgs ( object $object , array $args )

Вызывает отображенный метод и передает ему аргументы в виде массива.

Список параметров

object

Объект, метод которого вызывается. Если метод статический, можно передать null.

args

Массив array, содержащий аргументы функции.

Возвращаемые значения

Возвращает результат выполнения метода.

Ошибки

Вызывает исключение ReflectionException, если в объекте object нет определения этого метода.

Вызывает исключение ReflectionException, если вызвать метод на исполнение не удалось.

Примеры

Пример #1 Пример использования ReflectionMethod::invokeArgs()

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invokeArgs(new HelloWorld(), array('Mike'));
?>

Результат выполнения данного примера:

Hello Mike

Примечания

Замечание:

Если функция имеет аргументы, которые должны быть ссылками, то они должны быть ссылками и в переданном спике аргументов.

Смотрите также

  • ReflectionMethod::invoke() - Вызов
  • __invoke()
  • call_user_func_array() - Вызывает пользовательскую функцию с массивом параметров

User Contributed Notes

cweiske at cweiske dot de 25-Mar-2011 07:34
Passing arguments by reference works:
<?php $rm->invokeArgs($object, array(&$foo, $bar)); ?>
agent_harris at secure-mail dot biz 13-Feb-2011 07:12
There is a simple workaround for the reference passing problem:
Since the reflection api has to handle all parameters in a generic way it has no chance to guess if you wish to pass data per value or reference.

But it seems that you can also decide to pass a reference from where you call the function or method (not just only by the ampersand prefix in its declaration).

So just do the following; which worked for me:

<?php
//...
$method->invoke($object, $inputValue, &$outputValue);
?>

Since this will only be necessary with arrays and primitive data types it should be acceptable in most cases to know in advance if you need to pass per reference. But it is probably although necessary to keep the ampersand always in the declaration (because of the at least two layers between the actual function and your invoke call).

If this is the expected behavior it will maybe make sense to mention it in the documentation for invoke and invokeArgs.
serg dot smertin at gmail dot com 21-Sep-2010 06:51
We can do black magic, which is useful in templating block calls:

<?php
     $object->__named('methodNameHere', array('arg3' => 'three', 'arg1' => 'one'));

     ...

      /**
       * Pass method arguments by name
       *
       * @param string $method
       * @param array $args
       * @return mixed
       */
      public function __named($method, array $args = array())
      {
        $reflection = new ReflectionMethod($this, $method);

        $pass = array();
        foreach($reflection->getParameters() as $param)
        {
          /* @var $param ReflectionParameter */
          if(isset($args[$param->getName()]))
          {
            $pass[] = $args[$param->getName()];
          }
          else
          {
            $pass[] = $param->getDefaultValue();
          }
        }

        return $reflection->invokeArgs($this, $pass);
      }
?>
addiks at gmx dot de 20-May-2010 08:14
it seems that ReflectionMethod::invodeArgs() dont like reference-arguments in the method to call:

<?php

class Test{
  function foo(&$arg){
    $arg++;
  }
}

$test = new Test();

$class = new ReflectionClass("Test");
$method = $class->getMethod("foo");

$bar = 9;

$method->invokeArgs($test, array($bar));
?>

RESULT: "Invocation of method Test::foo() failed"
ReflectionMethod::invoke
ReflectionMethod::isAbstract
ReflectionMethod


Проверяет, является ли метод абстрактным

ReflectionMethod::invokeArgs
ReflectionMethod::isConstructor
ReflectionMethod
PHP Manual

ReflectionMethod::isAbstract

(PHP 5)

ReflectionMethod::isAbstract — Проверяет, является ли метод абстрактным

Описание

public bool ReflectionMethod::isAbstract ( void )

Проверяет, является ли метод абстрактным.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если метод абстрактный, FALSE в противном случае.

Смотрите также

  • ReflectionMethod::getDeclaringClass() - Получает класс, объявляющий отображенный метод

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::invokeArgs
ReflectionMethod::isConstructor
ReflectionMethod


Проверяет, является ли метод конструктором

ReflectionMethod::isAbstract
ReflectionMethod::isDestructor
ReflectionMethod
PHP Manual

ReflectionMethod::isConstructor

(PHP 5)

ReflectionMethod::isConstructor — Проверяет, является ли метод конструктором

Описание

public bool ReflectionMethod::isConstructor ( void )

Проверяет, является ли метод конструктором.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если метод является конструктором, FALSE в противном случае.

Смотрите также

  • ReflectionMethod::__construct() - Конструктор класса ReflectionMethod
  • ReflectionMethod::isAbstract() - Проверяет, является ли метод абстрактным
  • ReflectionMethod::isDestructor() - Проверяет, является ли метод деструктором

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::isAbstract
ReflectionMethod::isDestructor
ReflectionMethod


Проверяет, является ли метод деструктором

ReflectionMethod::isConstructor
ReflectionMethod::isFinal
ReflectionMethod
PHP Manual

ReflectionMethod::isDestructor

(PHP 5)

ReflectionMethod::isDestructor — Проверяет, является ли метод деструктором

Описание

public bool ReflectionMethod::isDestructor ( void )

Проверяет, является ли метод деструктором.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если метод является деструктором, FALSE в противном случае.

Смотрите также

  • ReflectionMethod::isConstructor() - Проверяет, является ли метод конструктором

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::isConstructor
ReflectionMethod::isFinal
ReflectionMethod


Проверяет, может ли метод иметь наследников (final)

ReflectionMethod::isDestructor
ReflectionMethod::isPrivate
ReflectionMethod
PHP Manual

ReflectionMethod::isFinal

(PHP 5)

ReflectionMethod::isFinal — Проверяет, может ли метод иметь наследников (final)

Описание

public bool ReflectionMethod::isFinal ( void )

Проверяет, может ли метод иметь потомков (final).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если создать наследника метода нельзя, FALSE в противном случае.

Смотрите также

  • ReflectionMethod::isStatic() - Проверяет, является ли метод статическим

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::isDestructor
ReflectionMethod::isPrivate
ReflectionMethod


Проверяет, является ли метод частным (private)

ReflectionMethod::isFinal
ReflectionMethod::isProtected
ReflectionMethod
PHP Manual

ReflectionMethod::isPrivate

(PHP 5)

ReflectionMethod::isPrivate — Проверяет, является ли метод частным (private)

Описание

public bool ReflectionMethod::isPrivate ( void )

Проверяет, является ли метод частным (private).

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если метод частный (private), FALSE в противном случае.

Смотрите также

  • ReflectionMethod::isPublic() - Проверяет, является ли метод общедоступным (public)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::isFinal
ReflectionMethod::isProtected
ReflectionMethod


Проверяет, является ли метод защищенным (protected)

ReflectionMethod::isPrivate
ReflectionMethod::isPublic
ReflectionMethod
PHP Manual

ReflectionMethod::isProtected

(PHP 5)

ReflectionMethod::isProtected — Проверяет, является ли метод защищенным (protected)

Описание

public bool ReflectionMethod::isProtected ( void )

Проверяет, является ли метод защищенным (protected).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если метод защищенный (protected), FALSE в противном случае.

Смотрите также

  • ReflectionMethod::isPrivate() - Проверяет, является ли метод частным (private)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::isPrivate
ReflectionMethod::isPublic
ReflectionMethod


Проверяет, является ли метод общедоступным (public)

ReflectionMethod::isProtected
ReflectionMethod::isStatic
ReflectionMethod
PHP Manual

ReflectionMethod::isPublic

(PHP 5)

ReflectionMethod::isPublic — Проверяет, является ли метод общедоступным (public)

Описание

public bool ReflectionMethod::isPublic ( void )

Проверяет, является ли метод общедоступным (public).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если метод общедоступный (public), FALSE в противном случае.

Смотрите также

  • ReflectionMethod::isPrivate() - Проверяет, является ли метод частным (private)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::isProtected
ReflectionMethod::isStatic
ReflectionMethod


Проверяет, является ли метод статическим

ReflectionMethod::isPublic
ReflectionMethod::setAccessible
ReflectionMethod
PHP Manual

ReflectionMethod::isStatic

(PHP 5)

ReflectionMethod::isStatic — Проверяет, является ли метод статическим

Описание

public bool ReflectionMethod::isStatic ( void )

Проверяет, является ли метод статическим.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если метод статический, FALSE в противном случае.

Смотрите также

  • ReflectionMethod::isFinal() - Проверяет, может ли метод иметь наследников (final)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::isPublic
ReflectionMethod::setAccessible
ReflectionMethod


Делает метод доступным

ReflectionMethod::isStatic
ReflectionMethod::__toString
ReflectionMethod
PHP Manual

ReflectionMethod::setAccessible

(PHP 5 >= 5.3.2)

ReflectionMethod::setAccessible — Делает метод доступным

Описание

public void ReflectionMethod::setAccessible ( bool $accessible )

Делает метод доступным. Например, позволяет вызывать защищенные и частные методы.

Список параметров

accessible

TRUE, чтобы сделать метод доступным, или FALSE.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • ReflectionMethod::isPrivate() - Проверяет, является ли метод частным (private)
  • ReflectionMethod::isProtected() - Проверяет, является ли метод защищенным (protected)

User Contributed Notes

dave1010 at gmail dot com 11-May-2011 03:21
This is handy for accessing private methods but remember that things are normally private for a reason! Unit Testing is one (debatable) use case for this.

Example:
<?php
class Foo {
  private function myPrivateMethod() {
    return 7;
  }
}

$method = new ReflectionMethod('Foo', 'myPrivateMethod');
$method->setAccessible(true);

echo $method->invoke(new Foo);
// echos "7"
?>

This works nicely with PHPUnit: http://php.net/manual/en/reflectionmethod.setaccessible.php
ReflectionMethod::isStatic
ReflectionMethod::__toString
ReflectionMethod


Возвращает строковое представление объекта Reflection method

ReflectionMethod::setAccessible
ReflectionObject
ReflectionMethod
PHP Manual

ReflectionMethod::__toString

(PHP 5)

ReflectionMethod::__toString — Возвращает строковое представление объекта Reflection method

Описание

public string ReflectionMethod::__toString ( void )

Возвращает строковое представление объекта Reflection method.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Строковое представление объекта ReflectionMethod.

Примеры

Пример #1 Пример использования ReflectionMethod::__toString()

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
echo $reflectionMethod;
?>

Результат выполнения данного примера:

Method [ <user> public method sayHelloTo ] {
  @@ /var/www/examples/reflection.php 16 - 18

  - Parameters [1] {
    Parameter #0 [ <required> $name ]
  }
}

Смотрите также

  • ReflectionMethod::export() - Экспорт отраженного метода
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionMethod::setAccessible
ReflectionObject
ReflectionMethod


Класс ReflectionObject

(PHP 5)

Введение

Класс ReflectionObject сообщает информацию об объектах (object).

Обзор классов

ReflectionObject extends ReflectionClass implements Reflector {
/* Константы */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* Свойства */
/* Методы */
public __construct ( object $argument )
public static string export ( string $argument [, bool $return ] )
/* Наследуемые методы */
ReflectionClass::__construct ( mixed $argument )
public static string ReflectionClass::export ( mixed $argument [, bool $return = false ] )
public mixed ReflectionClass::getConstant ( string $name )
public array ReflectionClass::getConstants ( void )
public object ReflectionClass::getConstructor ( void )
public array ReflectionClass::getDefaultProperties ( void )
public string ReflectionClass::getDocComment ( void )
public int ReflectionClass::getEndLine ( void )
public ReflectionExtension ReflectionClass::getExtension ( void )
public string ReflectionClass::getExtensionName ( void )
public string ReflectionClass::getFileName ( void )
public array ReflectionClass::getInterfaceNames ( void )
public array ReflectionClass::getInterfaces ( void )
public ReflectionMethod ReflectionClass::getMethod ( string $name )
public array ReflectionClass::getMethods ([ string $filter ] )
public int ReflectionClass::getModifiers ( void )
public string ReflectionClass::getName ( void )
public string ReflectionClass::getNamespaceName ( void )
public object ReflectionClass::getParentClass ( void )
public array ReflectionClass::getProperties ([ int $filter ] )
public ReflectionProperty ReflectionClass::getProperty ( string $name )
public string ReflectionClass::getShortName ( void )
public int ReflectionClass::getStartLine ( void )
public array ReflectionClass::getStaticProperties ( void )
public mixed ReflectionClass::getStaticPropertyValue ( string $name [, string $default ] )
public array ReflectionClass::getTraitAliases ( void )
public array ReflectionClass::getTraitNames ( void )
public array ReflectionClass::getTraits ( void )
public bool ReflectionClass::hasConstant ( string $name )
public bool ReflectionClass::hasMethod ( string $name )
public bool ReflectionClass::hasProperty ( string $name )
public bool ReflectionClass::implementsInterface ( string $interface )
public bool ReflectionClass::inNamespace ( void )
public bool ReflectionClass::isAbstract ( void )
public bool ReflectionClass::isCloneable ( void )
public bool ReflectionClass::isFinal ( void )
public bool ReflectionClass::isInstance ( object $object )
public bool ReflectionClass::isInstantiable ( void )
public bool ReflectionClass::isInterface ( void )
public bool ReflectionClass::isInternal ( void )
public bool ReflectionClass::isIterateable ( void )
public bool ReflectionClass::isSubclassOf ( string $class )
public bool ReflectionClass::isTrait ( void )
public bool ReflectionClass::isUserDefined ( void )
public object ReflectionClass::newInstance ( mixed $args [, mixed $... ] )
public object ReflectionClass::newInstanceArgs ([ array $args ] )
public object ReflectionClass::newInstanceWithoutConstructor ( void )
public void ReflectionClass::setStaticPropertyValue ( string $name , string $value )
public string ReflectionClass::__toString ( void )
}

Свойства

name

Имя класса объекта. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

Содержание

  • ReflectionObject::__construct — Конструктор класса ReflectionObject
  • ReflectionObject::export — Экспорт

User Contributed Notes

marcel dot nolte at noltecomputer dot de 02-Sep-2009 02:42
To simply enlist all methods and properties of an object simply write:

<?php ReflectionObject::export($yourObject); ?>

,which will cause an var_export-like output.
ReflectionMethod::__toString
ReflectionObject::__construct
Reflection


Конструктор класса ReflectionObject

ReflectionObject
ReflectionObject::export
ReflectionObject
PHP Manual

ReflectionObject::__construct

(PHP 5)

ReflectionObject::__construct — Конструктор класса ReflectionObject

Описание

public ReflectionObject::__construct ( object $argument )

Создает новый объект класса ReflectionObject.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

argument

Объект инстанцирования.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • ReflectionObject::export() - Экспорт
  • Конструкторы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionObject
ReflectionObject::export
ReflectionObject


Экспорт

ReflectionObject::__construct
ReflectionParameter
ReflectionObject
PHP Manual

ReflectionObject::export

(PHP 5)

ReflectionObject::export — Экспорт

Описание

public static string ReflectionObject::export ( string $argument [, bool $return ] )

Экспортирует отображение.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

argument

Экспортируемый объект Reflection.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Если параметр return установлен в TRUE, тогда экспортируемый объект будет возвращен как string, иначе будет возвращен NULL.

Смотрите также

  • ReflectionObject::__construct() - Конструктор класса ReflectionObject

User Contributed Notes

There are no user contributed notes for this page.
ReflectionObject::__construct
ReflectionParameter
ReflectionObject


Класс ReflectionParameter

(PHP 5)

Введение

Класс ReflectionParameter сообщает информацию об аргументах методов и функций.

Чтобы иметь возможность исследовать аргументы функции, сначала создайте представителя класса ReflectionFunction либо ReflectionMethod и затем используйте его метод ReflectionFunctionAbstract::getParameters() для получения массива аргументов.

Обзор классов

ReflectionParameter implements Reflector {
/* Свойства */
public $name ;
/* Методы */
public bool allowsNull ( void )
public bool canBePassedByValue ( void )
final private void __clone ( void )
public __construct ( string $function , string $parameter )
public static string export ( string $function , string $parameter [, bool $return ] )
public ReflectionClass getClass ( void )
public ReflectionClass getDeclaringClass ( void )
public ReflectionFunction getDeclaringFunction ( void )
public mixed getDefaultValue ( void )
public string getName ( void )
public int getPosition ( void )
public bool isArray ( void )
public bool isDefaultValueAvailable ( void )
public bool isOptional ( void )
public bool isPassedByReference ( void )
public string __toString ( void )
}

Свойства

name

Имя аргумента. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

Содержание

  • ReflectionParameter::allowsNull — Проверяет, допустимо ли значение null для аргумента
  • ReflectionParameter::canBePassedByValue — Проверяет, можно ли передать этот аргумент по значению
  • ReflectionParameter::__clone — Копирующий конструктор
  • ReflectionParameter::__construct — Конструктор класса
  • ReflectionParameter::export — Экспорт
  • ReflectionParameter::getClass — Получение класса
  • ReflectionParameter::getDeclaringClass — Получение объявляющего класса
  • ReflectionParameter::getDeclaringFunction — Получение объявляющей функции
  • ReflectionParameter::getDefaultValue — Получение значения по умолчанию аргумента
  • ReflectionParameter::getName — Получение имени аргумента
  • ReflectionParameter::getPosition — Получение позиции аргумента
  • ReflectionParameter::isArray — Проверяет, ожидает ли аргумент массив в качестве значения
  • ReflectionParameter::isDefaultValueAvailable — Проверяет доступно ли значение по умолчанию аргумента
  • ReflectionParameter::isOptional — Проверка, является ли аргумент необязательным
  • ReflectionParameter::isPassedByReference — Проверяет, что аргумент передан по ссылке
  • ReflectionParameter::__toString — Преобразование в строку

User Contributed Notes

fgm at riff dot org 11-May-2008 12:44
The note about the signature of the ReflectionParameter constructor is actually incomplete, at least in 5.2.5: it is possible to use an integer for the second parameter, and the constructor will use it to return the n-th parameter.

This allows you to obtain proper ReflectionParameter objects even when documenting code from extensions which (strangely enough) define several parameters with the same name. The string-based constructor always returns the first parameter with the matching name, whereas the integer-based constructor correctly returns the n-th parameter.

So, in short, this works:
<?php
// supposing the extension defined something like:
// Some_Class::someMethod($a, $x, $y, $x, $y)
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 4);
// returns the last parameter, whereas
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 'y');
// always returns the first $y at position 2
?>
killgecNOFSPAM at gmail dot com 25-Jul-2007 05:53
Signature of constructor of ReflectionParameter correctly is:

public function __construct(array/string $function, string $name);

where $function is either a name of a global function, or a class/method name pair.
massimo at mmware dot it 18-Jul-2007 08:58
I found these limitations using class ReflectionParameter from ReflectionFunction with INTERNAL FUNCTIONS (eg print_r, str_replace, ... ) :

1. parameter names don't match with manual: (try example 19.35 with arg "call_user_func" )
2. some functions (eg PCRE function, preg_match etc) have EMPTY parameter names
3. calling getDefaultValue on Parameters will result in Exception "Cannot determine default value for internal functions"
ReflectionObject::export
ReflectionParameter::allowsNull
Reflection


Проверяет, допустимо ли значение null для аргумента

ReflectionParameter
ReflectionParameter::canBePassedByValue
ReflectionParameter
PHP Manual

ReflectionParameter::allowsNull

(PHP 5)

ReflectionParameter::allowsNull — Проверяет, допустимо ли значение null для аргумента

Описание

public bool ReflectionParameter::allowsNull ( void )

Проверяет, допустимо ли значение NULL для аргумента.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если NULL допускается, FALSE в противном случае.

Смотрите также

  • ReflectionParameter::isOptional() - Проверка, является ли аргумент необязательным

User Contributed Notes

jeroen at asystance dot nl 10-Aug-2010 02:56
It seems this always returns true for user-defined functions. Consider
function f1 ( $var1 = null, $var2, $var3 = false ) {}
ReflectionMethod reports these all as nullable (and only the 3rd as optional - weird)
ReflectionParameter
ReflectionParameter::canBePassedByValue
ReflectionParameter


Проверяет, можно ли передать этот аргумент по значению

ReflectionParameter::allowsNull
ReflectionParameter::__clone
ReflectionParameter
PHP Manual

ReflectionParameter::canBePassedByValue

(PHP >= 5.4.0)

ReflectionParameter::canBePassedByValue — Проверяет, можно ли передать этот аргумент по значению

Описание

public bool ReflectionParameter::canBePassedByValue ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE, если передача аргумента по значению возможна, FALSE, если нет. Возвращает NULL в случае ошибки.

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::allowsNull
ReflectionParameter::__clone
ReflectionParameter


Копирующий конструктор

ReflectionParameter::canBePassedByValue
ReflectionParameter::__construct
ReflectionParameter
PHP Manual

ReflectionParameter::__clone

(PHP 5)

ReflectionParameter::__clone — Копирующий конструктор

Описание

final private void ReflectionParameter::__clone ( void )

Копирующий конструктор.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Смотрите также

  • ReflectionParameter::toString()
  • Копирование объектов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::canBePassedByValue
ReflectionParameter::__construct
ReflectionParameter


Конструктор класса

ReflectionParameter::__clone
ReflectionParameter::export
ReflectionParameter
PHP Manual

ReflectionParameter::__construct

(PHP 5)

ReflectionParameter::__construct — Конструктор класса

Описание

public ReflectionParameter::__construct ( string $function , string $parameter )

Конструктор класса ReflectionParameter.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

function

Функция, аргумент которой требуется отобразить.

parameter

Аргумент.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Использования класса ReflectionParameter

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

$reflect = new ReflectionFunction('foo');

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Аргумент #%d: %s {\n".
        "   Класс: %s\n".
        "   Допускает значения NULL: %s\n".
        "   Передается по ссылке: %s\n".
        "   Необязательный?: %s\n".
        "}\n",
        $i, // $param->getPosition() can be used from PHP 5.2.3
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'да' : 'нет'
    );
}
?>

Результатом выполнения данного примера будет что-то подобное:

Function [ <user> function foo ] {
  @@ /Users/philip/cvs/phpdoc/a 2 - 2

  - Parameters [3] {
    Parameter #0 [ <required> $a ]
    Parameter #1 [ <required> $b ]
    Parameter #2 [ <required> $c ]
  }
}
-- Аргумент #0: a {
   Класс: NULL
   Допускает значения NULL: true
   Передается по ссылке: false
   Необязательный?: нет
}
-- Аргумент #1: b {
   Класс: NULL
   Допускает значения NULL: true
   Передается по ссылке: false
   Необязательный?: нет
}
-- Аргумент #2: c {
   Класс: NULL
   Допускает значения NULL: true
   Передается по ссылке: false
   Необязательный?: нет
}

Смотрите также

  • ReflectionFunction::__construct() - Конструктор класса ReflectionFunction
  • ReflectionMethod::__construct() - Конструктор класса ReflectionMethod
  • Конструкторы

User Contributed Notes

tracid2008 t gmail o com 06-Dec-2011 03:31
You also can use a class instead of a function name. Just use an array like that
<?php
$reflect = new ReflectionParameter(array('className', 'methodName'), 'property');
?>
ReflectionParameter::__clone
ReflectionParameter::export
ReflectionParameter


Экспорт

ReflectionParameter::__construct
ReflectionParameter::getClass
ReflectionParameter
PHP Manual

ReflectionParameter::export

(PHP 5)

ReflectionParameter::export — Экспорт

Описание

public static string ReflectionParameter::export ( string $function , string $parameter [, bool $return ] )

Экспорт.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

function

Имя функции.

parameter

Имя аргумента.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Экспорт отображения.

Смотрите также

  • ReflectionParameter::toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::__construct
ReflectionParameter::getClass
ReflectionParameter


Получение класса

ReflectionParameter::export
ReflectionParameter::getDeclaringClass
ReflectionParameter
PHP Manual

ReflectionParameter::getClass

(PHP 5)

ReflectionParameter::getClass — Получение класса

Описание

public ReflectionClass ReflectionParameter::getClass ( void )

Получает класс.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект класса ReflectionClass.

Смотрите также

  • ReflectionParameter::getDeclaringClass() - Получение объявляющего класса

User Contributed Notes

tom at r dot je 11-May-2012 09:15
ReflectionParameter::getClass() will cause a fatal error (and trigger __autoload) if the class required by the parameter is not defined.

Sometimes it's useful to only know the class name without needing the class to be loaded.

Here's a simple function that will retrieve only the class name without requiring the class to exist:

<?php
function getClassName(ReflectionParameter $param) {
    preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
    return isset($matches[1]) ? $matches[1] : null;
}
?>
infernaz at gmail dot com 31-Jan-2011 12:09
The method returns ReflectionClass object of parameter type class or NULL if none.

<?php

class A {
    function b(B $c, array $d, $e) {
    }
}
class B {
}

$refl = new ReflectionClass('A');
$par = $refl->getMethod('b')->getParameters();

var_dump($par[0]->getClass()->getName());  // outputs B
var_dump($par[1]->getClass());  // note that array type outputs NULL
var_dump($par[2]->getClass());  // outputs NULL

?>
ReflectionParameter::export
ReflectionParameter::getDeclaringClass
ReflectionParameter


Получение объявляющего класса

ReflectionParameter::getClass
ReflectionParameter::getDeclaringFunction
ReflectionParameter
PHP Manual

ReflectionParameter::getDeclaringClass

(PHP 5)

ReflectionParameter::getDeclaringClass — Получение объявляющего класса

Описание

public ReflectionClass ReflectionParameter::getDeclaringClass ( void )

Получает объявляющий класс.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект класса ReflectionClass.

Смотрите также

  • ReflectionParameter::getClass() - Получение класса

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::getClass
ReflectionParameter::getDeclaringFunction
ReflectionParameter


Получение объявляющей функции

ReflectionParameter::getDeclaringClass
ReflectionParameter::getDefaultValue
ReflectionParameter
PHP Manual

ReflectionParameter::getDeclaringFunction

(PHP 5 >= 5.2.3)

ReflectionParameter::getDeclaringFunction — Получение объявляющей функции

Описание

public ReflectionFunction ReflectionParameter::getDeclaringFunction ( void )

Получает функцию, в которой аргумент объявлен.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект класса ReflectionFunction.

Смотрите также

  • ReflectionParameter::getDeclaringClass() - Получение объявляющего класса

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::getDeclaringClass
ReflectionParameter::getDefaultValue
ReflectionParameter


Получение значения по умолчанию аргумента

ReflectionParameter::getDeclaringFunction
ReflectionParameter::getName
ReflectionParameter
PHP Manual

ReflectionParameter::getDefaultValue

(PHP 5 >= 5.0.3)

ReflectionParameter::getDefaultValue — Получение значения по умолчанию аргумента

Описание

public mixed ReflectionParameter::getDefaultValue ( void )

Получает значение по умолчанию аргумента определенной пользователем функции или метода. Если аргумент не является необязательным, будет выброшено исключение ReflectionException.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Значение по умолчанию аргумента.

Примеры

Пример #1 Получение

<?php
function foo($test, $bar = 'baz')
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValue() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

Результат выполнения данного примера:

Name: test

Name: bar
Default value: baz

Примечания

Замечание:

В виду особенностей реализации, невозможно получить значение по умолчанию для встроенных функций или методов встроенных классов. Попытки это сделать приведут к выбросу исключения ReflectionException.

Смотрите также

  • ReflectionParameter::isOptional() - Проверка, является ли аргумент необязательным
  • ReflectionParameter::isPassedByReference() - Проверяет, что аргумент передан по ссылке

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::getDeclaringFunction
ReflectionParameter::getName
ReflectionParameter


Получение имени аргумента

ReflectionParameter::getDefaultValue
ReflectionParameter::getPosition
ReflectionParameter
PHP Manual

ReflectionParameter::getName

(PHP 5)

ReflectionParameter::getName — Получение имени аргумента

Описание

public string ReflectionParameter::getName ( void )

Получает имя аргумента.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя отображенного аргумента.

Смотрите также

  • ReflectionParameter::getValue()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::getDefaultValue
ReflectionParameter::getPosition
ReflectionParameter


Получение позиции аргумента

ReflectionParameter::getName
ReflectionParameter::isArray
ReflectionParameter
PHP Manual

ReflectionParameter::getPosition

(PHP 5 >= 5.2.3)

ReflectionParameter::getPosition — Получение позиции аргумента

Описание

public int ReflectionParameter::getPosition ( void )

Получает позицию аргумента в списке аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Позиция аргумента, слева направо, первый аргумент стоит на позиции #0.

Смотрите также

  • ReflectionParameter::getName() - Получение имени аргумента

User Contributed Notes

micah at raincross-tech dot com 05-Dec-2010 07:26
Note that the ReflectionFunctionAbstract::getParameters() method will return the parameters in the correct order.
ReflectionParameter::getName
ReflectionParameter::isArray
ReflectionParameter


Проверяет, ожидает ли аргумент массив в качестве значения

ReflectionParameter::getPosition
ReflectionParameter::isDefaultValueAvailable
ReflectionParameter
PHP Manual

ReflectionParameter::isArray

(PHP 5 >= 5.1.0)

ReflectionParameter::isArray — Проверяет, ожидает ли аргумент массив в качестве значения

Описание

public bool ReflectionParameter::isArray ( void )

Проверяет, ожидает ли аргумент массив в качестве значения.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если в качестве значения ожидается массив array, FALSE в противном случае.

Смотрите также

  • ReflectionParameter::isOptional() - Проверка, является ли аргумент необязательным

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::getPosition
ReflectionParameter::isDefaultValueAvailable
ReflectionParameter


Проверяет доступно ли значение по умолчанию аргумента

ReflectionParameter::isArray
ReflectionParameter::isOptional
ReflectionParameter
PHP Manual

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3)

ReflectionParameter::isDefaultValueAvailable — Проверяет доступно ли значение по умолчанию аргумента

Описание

public bool ReflectionParameter::isDefaultValueAvailable ( void )

Проверяет доступно ли значение по умолчанию аргумента.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если доступно значение по умолчанию, FALSE в противном случае.

Смотрите также

  • ReflectionParameter::getDefaultValue() - Получение значения по умолчанию аргумента
  • ReflectionParameter::getName() - Получение имени аргумента

User Contributed Notes

php at marcyes dot com 02-Aug-2011 05:37
A quick gotcha that I wasn't aware of, suppose you have a function definition like this:

<?php
function foo(array $bar = array('baz' => ''),$che){}
?>

And you want to check if $bar has a default value:

<?php
$rfunc = new ReflectionFunction('foo');
$rparams = $rfunc->getParams();

echo $rparams[0]->isDefaultValueAvailable() ? 'TRUE' : 'FALSE';
?>

That will echo 'FALSE' because $che has no default value so $bar becomes required and the Reflection interface no long sees $bar's default value of array('baz' => '').

The solution is to give $che a default value also:

<?php
function foo(array $bar = array('baz' => ''),$che = null){}
?>

And then $bar's default value will be visible again.

While I understand why it does this, I still wish there was a way to get the default value without resorting to giving all params after it a default value also.
ReflectionParameter::isArray
ReflectionParameter::isOptional
ReflectionParameter


Проверка, является ли аргумент необязательным

ReflectionParameter::isDefaultValueAvailable
ReflectionParameter::isPassedByReference
ReflectionParameter
PHP Manual

ReflectionParameter::isOptional

(PHP 5 >= 5.0.3)

ReflectionParameter::isOptional — Проверка, является ли аргумент необязательным

Описание

public bool ReflectionParameter::isOptional ( void )

Проверяет, является ли аргумент необязательным.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если аргумент необязательный, FALSE в противном случае.

Смотрите также

  • ReflectionParameter::getName() - Получение имени аргумента

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::isDefaultValueAvailable
ReflectionParameter::isPassedByReference
ReflectionParameter


Проверяет, что аргумент передан по ссылке

ReflectionParameter::isOptional
ReflectionParameter::__toString
ReflectionParameter
PHP Manual

ReflectionParameter::isPassedByReference

(PHP 5)

ReflectionParameter::isPassedByReference — Проверяет, что аргумент передан по ссылке

Описание

public bool ReflectionParameter::isPassedByReference ( void )

Проверяет, что аргумент передан по ссылке.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если аргумент передан по ссылке, FALSE в противном случае.

Смотрите также

  • ReflectionParameter::getName() - Получение имени аргумента

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::isOptional
ReflectionParameter::__toString
ReflectionParameter


Преобразование в строку

ReflectionParameter::isPassedByReference
ReflectionProperty
ReflectionParameter
PHP Manual

ReflectionParameter::__toString

(PHP 5)

ReflectionParameter::__toString — Преобразование в строку

Описание

public string ReflectionParameter::__toString ( void )

Представление в виде строки.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Смотрите также

  • ReflectionParameter::export() - Экспорт
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionParameter::isPassedByReference
ReflectionProperty
ReflectionParameter


Класс ReflectionProperty

(PHP 5)

Введение

Класс ReflectionProperty сообщает информацию о свойствах класса.

Обзор классов

ReflectionProperty implements Reflector {
/* Константы */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
/* Свойства */
public $name ;
public $class ;
/* Методы */
final private void __clone ( void )
__construct ( mixed $class , string $name )
public static string export ( mixed $class , string $name [, bool $return ] )
public ReflectionClass getDeclaringClass ( void )
public string getDocComment ( void )
public int getModifiers ( void )
public string getName ( void )
public mixed getValue ( object $object )
public bool isDefault ( void )
public bool isPrivate ( void )
public bool isProtected ( void )
public bool isPublic ( void )
public bool isStatic ( void )
public void setAccessible ( bool $accessible )
public void setValue ( object $object , mixed $value )
public string __toString ( void )
}

Свойства

name

Имя свойства. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

class

Имя класса, в котором данное свойство описано. Доступно только для чтения и выбрасывает исключение ReflectionException при попытке записи.

Предопределенные константы

Модификаторы ReflectionProperty

ReflectionProperty::IS_STATIC

Указывает, что свойство является статическим (static).

ReflectionProperty::IS_PUBLIC

Указывает, что свойство является общедоступным (public) properties.

ReflectionProperty::IS_PROTECTED

Указывает, что свойство является защищенным (protected).

ReflectionProperty::IS_PRIVATE

Указывает, что свойство является закрытым (private).

Содержание

  • ReflectionProperty::__clone — Копирующий конструктор
  • ReflectionProperty::__construct — Конструктор класса ReflectionProperty
  • ReflectionProperty::export — Экспорт
  • ReflectionProperty::getDeclaringClass — Получение объявляющего класса
  • ReflectionProperty::getDocComment — Получение документируемого комментария
  • ReflectionProperty::getModifiers — Получение модификаторов
  • ReflectionProperty::getName — Получение имени свойства
  • ReflectionProperty::getValue — Получение значения
  • ReflectionProperty::isDefault — Проверяет, является ли значение свойством по умолчанию
  • ReflectionProperty::isPrivate — Проверяет, является ли свойство частным (private)
  • ReflectionProperty::isProtected — Проверяет, является ли свойство защищенным (protected)
  • ReflectionProperty::isPublic — Проверяет, является ли свойство общедоступным (public)
  • ReflectionProperty::isStatic — Проверка, является ли свойство статическим
  • ReflectionProperty::setAccessible — Задание доступности свойства
  • ReflectionProperty::setValue — Задание значения свойству
  • ReflectionProperty::__toString — Преобразование в строку

User Contributed Notes

james at digitaledgeit dot com dot au 29-Aug-2010 08:30
Please ignore my previous note. I didn't fully understand what the previous notes were referring to as "runtime". I now see they were referring to a slightly different question.

Apologies!
james at digitaledgeit dot com dot au 29-Aug-2010 08:22
You CAN reflect an object at runtime:

<?php

class Abc {

    private $_abc = 123;

    public function __construct($abc) {
        $this->_abc = $abc;
    }

}

$obj = new Abc('def');

$refl = new \ReflectionObject($obj);
$prop = $refl->getProperty('_abc');
$prop->setAccessible(true);
echo $prop->getValue($obj);

?>

This outputs 'def', the value of _abc set at runtime.
rasmus at mindplay dot dk 30-Jul-2010 05:06
I think a more accurate explanation is this:

The Reflection classes are designed to reflect upon the source code of an application, not on any runtime information.

I think you misunderstand the ReflectionProperty constructor in your example above. The fact that it accepts an object as argument is just a convenience feature - you are actually inspecting the class of that object, not the object itself, so it's basically equivalent to:

<?php

// works fine
$Reflection = new ReflectionProperty(get_class($a), 'a');

// throws exception
$Reflection = new ReflectionProperty(get_class($a), 'foo');

?>

Getting the class of the object you're passing in is implied, since inspecting a defined property is the purpose of this class.

In your example, $a->foo is a dynamic member - it is not defined as a member of class, so there is no defining class reference, line number, default value, etc. - which means, there is nothing to reflect upon.

Clearly this very useful library could use some real documentation...
CodeDuck at gmx dot net 08-Feb-2006 08:07
Beware, the Reflection reflects only the information right after compile time based on the definitions, not based on runtime objects. Might be obvious, wasn't for me, until the app throws the exception at my head.

Example:

<?php

class A {
    public $a = null;

    function set() {
      $this->foo = 'bar';
    }
}

$a = new A;
$a->set();

// works fine
$Reflection = new ReflectionProperty($a, 'a');

// throws exception
$Reflection = new ReflectionProperty($a, 'foo');

?>
ReflectionParameter::__toString
ReflectionProperty::__clone
Reflection


Копирующий конструктор

ReflectionProperty
ReflectionProperty::__construct
ReflectionProperty
PHP Manual

ReflectionProperty::__clone

(PHP 5)

ReflectionProperty::__clone — Копирующий конструктор

Описание

final private void ReflectionProperty::__clone ( void )

Копирующий конструктор.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Смотрите также

  • ReflectionProperty::export() - Экспорт
  • Копирование обьектов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty
ReflectionProperty::__construct
ReflectionProperty


Конструктор класса ReflectionProperty

ReflectionProperty::__clone
ReflectionProperty::export
ReflectionProperty
PHP Manual

ReflectionProperty::__construct

(PHP 5)

ReflectionProperty::__construct — Конструктор класса ReflectionProperty

Описание

ReflectionProperty::__construct ( mixed $class , string $name )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

class

Имя класса, содержащего свойство.

name

Имя свойства, которое требуется отобразить.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Попытка получить или задать значение защищенного или частного свойства приведет к выбросу исключения.

Примеры

Пример #1 Пример использования ReflectionProperty::__construct()

<?php
class String
{
    public $length  = 5;
}

// Создание нового объекта класса ReflectionProperty
$prop = new ReflectionProperty('String', 'length');

// Вывод основной информации об объекте
printf(
    "===> %s%s%s%s свойство '%s' (которое %s)\n" .
    "     имеющее модификаторы %s\n",
        $prop->isPublic() ? ' общедоступное' : '',
        $prop->isPrivate() ? ' частное' : '',
        $prop->isProtected() ? ' защищенное' : '',
        $prop->isStatic() ? ' статическое' : '',
        $prop->getName(),
        $prop->isDefault() ? 'объявлено во время компиляции' : 'создано во время выполнения',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// создание строки
$obj= new String();

// получение текущего значения
printf("---> Значение: ");
var_dump($prop->getValue($obj));

// Изменение значения
$prop->setValue($obj, 10);
printf("---> Установка значения 10, новое значение: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

Результатом выполнения данного примера будет что-то подобное:

===> общедоступное свойство 'length' (которое объявлено во время компиляции)
     имеющее модификаторы array (
  0 => 'public',
)
---> Значение: int(5)
---> Установка значения 10, новое значение: int(10)
object(String)#2 (1) {
  ["length"]=>
  int(10)
}

Пример #2 Получение значений защищенных и частных свойств, используя класс ReflectionProperty

<?php

class Foo {
    public $x = 1;
    protected $y = 2;
    private $z = 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

?>

Результатом выполнения данного примера будет что-то подобное:

int(2)
int(3)

Смотрите также

  • ReflectionProperty::getName() - Получение имени свойства
  • Конструкторы

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::__clone
ReflectionProperty::export
ReflectionProperty


Экспорт

ReflectionProperty::__construct
ReflectionProperty::getDeclaringClass
ReflectionProperty
PHP Manual

ReflectionProperty::export

(PHP 5)

ReflectionProperty::export — Экспорт

Описание

public static string ReflectionProperty::export ( mixed $class , string $name [, bool $return ] )

Экспортирует отображение.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

argument

Экспортируемый объект Reflection.

name

Имя свойства.

return

Установка в TRUE вернет экспортируемое значение, в отличие от поведения, где этот параметр опущен. Установка в FALSE (по умолчанию) сделает противоположное.

Возвращаемые значения

Смотрите также

  • ReflectionProperty::toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::__construct
ReflectionProperty::getDeclaringClass
ReflectionProperty


Получение объявляющего класса

ReflectionProperty::export
ReflectionProperty::getDocComment
ReflectionProperty
PHP Manual

ReflectionProperty::getDeclaringClass

(PHP 5)

ReflectionProperty::getDeclaringClass — Получение объявляющего класса

Описание

public ReflectionClass ReflectionProperty::getDeclaringClass ( void )

Получение объявляющего класса.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Объект класса ReflectionClass.

Смотрите также

  • ReflectionProperty::getName() - Получение имени свойства

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::export
ReflectionProperty::getDocComment
ReflectionProperty


Получение документируемого комментария

ReflectionProperty::getDeclaringClass
ReflectionProperty::getModifiers
ReflectionProperty
PHP Manual

ReflectionProperty::getDocComment

(PHP 5 >= 5.1.0)

ReflectionProperty::getDocComment — Получение документируемого комментария

Описание

public string ReflectionProperty::getDocComment ( void )

Получает документируемый комментарий.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Комментарий.

Смотрите также

  • ReflectionProperty::export() - Экспорт

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::getDeclaringClass
ReflectionProperty::getModifiers
ReflectionProperty


Получение модификаторов

ReflectionProperty::getDocComment
ReflectionProperty::getName
ReflectionProperty
PHP Manual

ReflectionProperty::getModifiers

(PHP 5)

ReflectionProperty::getModifiers — Получение модификаторов

Описание

public int ReflectionProperty::getModifiers ( void )

Получает список модификаторов

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Числовое представление модификаторов.

Смотрите также

  • ReflectionProperty::isPrivate() - Проверяет, является ли свойство частным (private)
  • Reflection::getModifierNames() - Получение имен модификаторов

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::getDocComment
ReflectionProperty::getName
ReflectionProperty


Получение имени свойства

ReflectionProperty::getModifiers
ReflectionProperty::getValue
ReflectionProperty
PHP Manual

ReflectionProperty::getName

(PHP 5)

ReflectionProperty::getName — Получение имени свойства

Описание

public string ReflectionProperty::getName ( void )

Получает имя свойства.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Имя отображенного свойства.

Смотрите также

  • ReflectionProperty::getValue() - Получение значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::getModifiers
ReflectionProperty::getValue
ReflectionProperty


Получение значения

ReflectionProperty::getName
ReflectionProperty::isDefault
ReflectionProperty
PHP Manual

ReflectionProperty::getValue

(PHP 5)

ReflectionProperty::getValue — Получение значения

Описание

public mixed ReflectionProperty::getValue ( object $object )
public mixed ReflectionProperty::getValue ( void )

Получает значение свойства.

Список параметров

object

Если свойство не статическое, необходимо передать объект, из которого требуется это свойство получить. Если вам нужно получить свойство по умолчанию, не предоставляя объект, используйте функцию ReflectionClass::getDefaultProperties().

Возвращаемые значения

Текущее значение свойства.

Ошибки

Вызывает исключение ReflectionException, если свойство недоступно. Защищенные и частные свойства можно сделать доступными функцией ReflectionProperty::setAccessible().

Примеры

Пример #1 Пример использования ReflectionProperty::getValue()

<?php
class Foo {
    public static $staticProperty = 'foobar';

    public $property = 'barfoo';
    protected $privateProperty = 'foofoo';
}

$reflectionClass = new ReflectionClass('Foo');

var_dump($reflectionClass->getProperty('staticProperty')->getValue());
var_dump($reflectionClass->getProperty('property')->getValue(new Foo));

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
var_dump($reflectionProperty->getValue(new Foo));
?>

Результат выполнения данного примера:

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

Смотрите также

  • ReflectionProperty::setValue() - Задание значения свойству
  • ReflectionProperty::setAccessible() - Задание доступности свойства
  • ReflectionClass::getDefaultProperties() - Возвращает свойства по умолчанию
  • ReflectionClass::getStaticPropertyValue() - Возвращает значение static свойства

User Contributed Notes

sergiy dot sokolenko at gmail dot com 28-Jun-2010 03:48
To allow protected and private properties to be accessed, you should use
ReflectionProperty::setAccessible(bool $accessible):

<?php
/** Class Foo with protected and private members */
class Foo {
    protected $bar = 'barrr!';
    private $baz = 'bazzz!';
}

$reflFoo = new ReflectionClass('Foo');
$reflBar = $reflFoo->getProperty('bar');
$reflBaz = $reflFoo->getProperty('baz');

// Set private and protected members accessible for getValue/setValue
$reflBar->setAccessible(true);
$reflBaz->setAccessible(true);

$foo = new Foo();
echo $reflBar->getValue($foo); // will output "barrr!"
echo $reflBaz->getValue($foo); // will output "bazzz!"

// You can also setValue
$reflBar->setValue($foo, "new value");
echo $reflBar->getValue($foo); // will output "new value"
?>
tedivm at tedivm dot com 09-Jan-2010 09:33
Note this function does not return the value for everything, only public properties. Protected or private properties will result in a exception being thrown.
ReflectionProperty::getName
ReflectionProperty::isDefault
ReflectionProperty


Проверяет, является ли значение свойством по умолчанию

ReflectionProperty::getValue
ReflectionProperty::isPrivate
ReflectionProperty
PHP Manual

ReflectionProperty::isDefault

(PHP 5)

ReflectionProperty::isDefault — Проверяет, является ли значение свойством по умолчанию

Описание

public bool ReflectionProperty::isDefault ( void )

Проверяет, является ли значение свойством по умолчанию.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если свойство объявлено во время компиляции, либо FALSE, если оно было создано во время выполнения.

Смотрите также

  • ReflectionProperty::getValue() - Получение значения

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::getValue
ReflectionProperty::isPrivate
ReflectionProperty


Проверяет, является ли свойство частным (private)

ReflectionProperty::isDefault
ReflectionProperty::isProtected
ReflectionProperty
PHP Manual

ReflectionProperty::isPrivate

(PHP 5)

ReflectionProperty::isPrivate — Проверяет, является ли свойство частным (private)

Описание

public bool ReflectionProperty::isPrivate ( void )

Проверяет, является ли свойство частным (private).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если свойство частное, FALSE в противном случае.

Смотрите также

  • ReflectionProperty::isPublic() - Проверяет, является ли свойство общедоступным (public)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::isDefault
ReflectionProperty::isProtected
ReflectionProperty


Проверяет, является ли свойство защищенным (protected)

ReflectionProperty::isPrivate
ReflectionProperty::isPublic
ReflectionProperty
PHP Manual

ReflectionProperty::isProtected

(PHP 5)

ReflectionProperty::isProtected — Проверяет, является ли свойство защищенным (protected)

Описание

public bool ReflectionProperty::isProtected ( void )

Проверяет, является ли свойство защищенным (protected).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если свойство защищенное (protected), FALSE в противном случае.

Смотрите также

  • ReflectionProperty::isPrivate() - Проверяет, является ли свойство частным (private)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::isPrivate
ReflectionProperty::isPublic
ReflectionProperty


Проверяет, является ли свойство общедоступным (public)

ReflectionProperty::isProtected
ReflectionProperty::isStatic
ReflectionProperty
PHP Manual

ReflectionProperty::isPublic

(PHP 5)

ReflectionProperty::isPublic — Проверяет, является ли свойство общедоступным (public)

Описание

public bool ReflectionProperty::isPublic ( void )

Проверяет, является ли свойство общедоступным (public).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если свойство общедоступное, FALSE в противном случае.

Смотрите также

  • ReflectionProperty::isPrivate() - Проверяет, является ли свойство частным (private)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::isProtected
ReflectionProperty::isStatic
ReflectionProperty


Проверка, является ли свойство статическим

ReflectionProperty::isPublic
ReflectionProperty::setAccessible
ReflectionProperty
PHP Manual

ReflectionProperty::isStatic

(PHP 5)

ReflectionProperty::isStatic — Проверка, является ли свойство статическим

Описание

public bool ReflectionProperty::isStatic ( void )

Проверяет, является ли свойство статическим.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE, если свойство статическое, FALSE в противном случае.

Смотрите также

  • ReflectionProperty::isPrivate() - Проверяет, является ли свойство частным (private)

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::isPublic
ReflectionProperty::setAccessible
ReflectionProperty


Задание доступности свойства

ReflectionProperty::isStatic
ReflectionProperty::setValue
ReflectionProperty
PHP Manual

ReflectionProperty::setAccessible

(PHP 5 >= 5.3.0)

ReflectionProperty::setAccessible — Задание доступности свойства

Описание

public void ReflectionProperty::setAccessible ( bool $accessible )

Делает свойство доступным. Например, может сделать доступным защищенное и частное свойство.

Список параметров

accessible

TRUE делает свойство доступным, FALSE - закрывает доступ к свойству.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • ReflectionProperty::isPrivate() - Проверяет, является ли свойство частным (private)
  • ReflectionProperty::isProtected() - Проверяет, является ли свойство защищенным (protected)

User Contributed Notes

Yzmir Ramirez 15-Oct-2010 05:31
Have you tried:

<?php

echo "PHP Version: ".phpversion()."\n";

class Foo
{
    private   $bar  = "private";
    protected $bar2 = "protected";
    public    $bar3 = "public";
}

$obj = new Foo;

$arr = (array)$obj;

print_r($arr);
?>

Output:

PHP Version: 5.2.12
Array
(
    [Foobar] => private
    [*bar2] => protected
    [bar3] => public
)

PHP Version: 5.1.6
Array
(
    [Foobar] => private
    [*bar2] => protected
    [bar3] => public
)
Rob McVey 11-Jun-2010 10:11
If you are using < PHP 5.3 and need to get the private attributes and values, you can use this method:

This is what you are doing:

<?php
$obj_with_privates = new MyObject();
$class     = get_class($obj_with_privates);
$vars     = get_object_vars($obj_with_privates);
//will not show private attributes
print_r($vars);

$reflection = new ReflectionClass( $class );
$attributes = $reflection->getProperties();
//still no private access!
print_r($attributes);
?>

This is what you should do:

<?php
$obj_with_privates = new MyObject();

$class         = get_class( $obj_with_privates );
$reflection = new ReflectionClass( $class );
$abstract    = $reflection->getMethods( ReflectionMethod::IS_ABSTRACT );
$priv_attr  = $reflection->getProperties( ReflectionProperty::IS_PRIVATE );
$privates   = array();
$parent     = get_parent_class( $class );
$child         = $class;
$constructor = $reflection->getConstructor();

//If the class has abstract methods you need to implement them
$abstr_methods = "";
if(sizeof($abstr_methods))
{
    foreach($abstract as $method)
    {
        $mname = $method->name;
        $abstr_methods .= "public function $mname(){return false;}";
    }
}

//Convert private attributes to public attributes
if(sizeof($priv_attr))
{
    $parseable = unserialize(str_replace("\0$class\0", "\0*\0", serialize($obj)));
    foreach($priv_attr as $attribute)
    {
        $aname = $attribute->name;
        $privates[$aname] = $parseable->$aname;
    }
}

$temp_child_class = "temp" . str_replace("_", "", "$class");

//You can gain access to protected attributes by extending the target class
$class_def = "
class $temp_child_class extends $class{
    $constructor
    public function reflect_getmyvars(){
        return get_object_vars(\$this);
    }
    $abstr_methods
}
";

//place class definition in memory
eval($class_def);

//generate object from dynamic class
$tcobj =@ new $temp_child_class;
//call the method we added to the object (to access protected vars)
$vars = $tcobj->reflect_getmyvars();

$attribs = array_merge($vars, $privates);

//will now show private attributes
print_r($attribs);
?>
ReflectionProperty::isStatic
ReflectionProperty::setValue
ReflectionProperty


Задание значения свойству

ReflectionProperty::setAccessible
ReflectionProperty::__toString
ReflectionProperty
PHP Manual

ReflectionProperty::setValue

(PHP 5)

ReflectionProperty::setValue — Задание значения свойству

Описание

public void ReflectionProperty::setValue ( object $object , mixed $value )
public void ReflectionProperty::setValue ( mixed $value )

Задает (изменяет) значение свойства.

Список параметров

object

Если свойство нестатическое, необходимо передать объект, свойство в котором нужно изменить. Если свойство статическое, этот аргумент пропускается, и требуется задать только value.

value

Новое значение.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Вызывает исключение ReflectionException, если свойство недоступно. Можно делать защищенные и частные свойства доступными с помощью ReflectionProperty::setAccessible().

Примеры

Пример #1 Пример использования ReflectionProperty::setValue()

<?php
class Foo {
    public static $staticProperty;

    public $property;
    protected $privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

$reflectionClass->getProperty('staticProperty')->setValue('foo');
var_dump(Foo::$staticProperty);

$foo = new Foo;

$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

Результат выполнения данного примера:

string(3) "foo"
string(3) "bar"
string(6) "foobar"

Смотрите также

  • ReflectionProperty::getValue() - Получение значения
  • ReflectionProperty::setAccessible() - Задание доступности свойства
  • ReflectionClass::setStaticPropertyValue() - Устанавливает значение static-свойства

User Contributed Notes

me at ircmaxell dot om 22-Jun-2011 09:27
You can use ReflectionProperty::setValue to set the value on static properties as well as regular instance properties.  Simply pass null in place of the instance:

<?php
class Foo {
    protected static $bar = null;
    public static function sayBar() {
        echo self::$bar;
    }
}

$r = new ReflectionProperty('Foo', 'bar');
$r->setAccessible(true);
$r->setValue(null, 'foo');

Foo::sayBar(); // "foo"
?>
ReflectionProperty::setAccessible
ReflectionProperty::__toString
ReflectionProperty


Преобразование в строку

ReflectionProperty::setValue
Reflector
ReflectionProperty
PHP Manual

ReflectionProperty::__toString

(PHP 5)

ReflectionProperty::__toString — Преобразование в строку

Описание

public string ReflectionProperty::__toString ( void )

Представление в виде строки.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Смотрите также

  • ReflectionProperty::()
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::setValue
Reflector
ReflectionProperty


Интерфейс Reflector

(PHP 5)

Введение

Интерфейс Reflector реализуют все экспортируемые Reflection-классы.

Обзор классов

Reflector {
/* Методы */
abstract public static string export ( void )
abstract public string __toString ( void )
}

Содержание

  • Reflector::export — Экспорт
  • Reflector::__toString — Представление в виде строки

User Contributed Notes

There are no user contributed notes for this page.
ReflectionProperty::__toString
Reflector::export
Reflection


Экспорт

Reflector
Reflector::__toString
Reflector
PHP Manual

Reflector::export

(PHP 5)

Reflector::export — Экспорт

Описание

abstract public static string Reflector::export ( void )

Экспорт.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Смотрите также

  • Reflection::__toString()

User Contributed Notes

There are no user contributed notes for this page.
Reflector
Reflector::__toString
Reflector


Представление в виде строки

Reflector::export
ReflectionException
Reflector
PHP Manual

Reflector::__toString

(PHP 5)

Reflector::__toString — Представление в виде строки

Описание

abstract public string Reflector::__toString ( void )

Представление в виде строки.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Смотрите также

  • ReflectionProperty::export() - Экспорт
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.
Reflector::export
ReflectionException
Reflector


Класс ReflectionException

(PHP 5)

Введение

Класс ReflectionException.

Обзор классов

ReflectionException extends Exception {
/* Свойства */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Наследуемые методы */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.
Reflector::__toString
Функции для работы с переменными
Reflection


Функции для работы с переменными

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Функции для работы с переменными
    • debug_zval_dump — Выводит строковое представление внутреннего значения zend
    • doubleval — Псевдоним floatval
    • empty — Проверяет, пуста ли переменная
    • floatval — Возвращает значение переменной в виде числа с плавающей точкой
    • get_defined_vars — Возвращает массив всех определенных переменных
    • get_resource_type — Возвращает тип ресурса
    • gettype — Возвращает тип переменной
    • import_request_variables — Импортирует переменные GET/POST/Cookie в глобальную область видимости
    • intval — Возвращает целое значение переменной
    • is_array — Определяет, является ли переменная массивом
    • is_bool — Проверяет, является ли переменная булевой
    • is_callable — Проверяет, может ли значение переменной быть вызвано в качестве функции
    • is_double — Псевдоним is_float
    • is_float — Проверяет, является ли переменная числом с плавающей точкой
    • is_int — Проверяет, является ли переменная переменной целочисленного типа
    • is_integer — Псевдоним is_int
    • is_long — Псевдоним is_int
    • is_null — Проверяет, является ли значение переменной равным NULL
    • is_numeric — Проверяет, является ли переменная числом или строкой, содержащей число
    • is_object — Проверяет, является ли переменная объектом
    • is_real — Псевдоним is_float
    • is_resource — Проверяет, является ли переменная ресурсом
    • is_scalar — Проверяет, является ли переменная скалярным значением
    • is_string — Проверяет, является ли переменная строкой
    • isset — Определяет, была ли установлена переменная значением отличным от NULL
    • print_r — Выводит удобочитаемую информацию о переменной
    • serialize — Генерирует пригодное для хранения представление переменной
    • settype — Присваивает переменной новый тип
    • strval — Возвращает строковое значение переменной
    • unserialize — Создает PHP-значение из хранимого представления
    • unset — Удаляет переменную
    • var_dump — Выводит информацию о переменной
    • var_export — Выводит в браузер или возвращает интерпретируемое строковое представление переменной

User Contributed Notes

There are no user contributed notes for this page.
ReflectionException
Введение
Расширения, относящиеся к переменным и типам


Введение

Для более подробной информации о поведении и работе с переменными см. раздел "Переменные", секцию "Справочник языка" руководства.

User Contributed Notes

There are no user contributed notes for this page.
Функции для работы с переменными
Установка и настройка
Функции для работы с переменными


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Функции для работы с переменными


Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

Параметры конфигурации Variables
Имя | По умолчанию | Меняемо | Список изменений
unserialize_callback_func | NULL | PHP_INI_ALL | Доступна с PHP 4.2.0.
Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.

Краткое разъяснение конфигурационных директив.

unserialize_callback_func string

Если в процессе десериализации будет обнаружен неопределенный класс, то будет вызвана callback-функция unserialize(). Если указанная callback-функция не определена или не может определить отсутствующий класс, то будет выведено предупреждение.

См. также unserialize() и раздел автозагрузки объектов.

User Contributed Notes

There are no user contributed notes for this page.
Установка
Типы ресурсов
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Функции для работы с переменными
Функции для работы с переменными


Функции для работы с переменными
PHP Manual

Функции для работы с переменными

Содержание

  • debug_zval_dump — Выводит строковое представление внутреннего значения zend
  • doubleval — Псевдоним floatval
  • empty — Проверяет, пуста ли переменная
  • floatval — Возвращает значение переменной в виде числа с плавающей точкой
  • get_defined_vars — Возвращает массив всех определенных переменных
  • get_resource_type — Возвращает тип ресурса
  • gettype — Возвращает тип переменной
  • import_request_variables — Импортирует переменные GET/POST/Cookie в глобальную область видимости
  • intval — Возвращает целое значение переменной
  • is_array — Определяет, является ли переменная массивом
  • is_bool — Проверяет, является ли переменная булевой
  • is_callable — Проверяет, может ли значение переменной быть вызвано в качестве функции
  • is_double — Псевдоним is_float
  • is_float — Проверяет, является ли переменная числом с плавающей точкой
  • is_int — Проверяет, является ли переменная переменной целочисленного типа
  • is_integer — Псевдоним is_int
  • is_long — Псевдоним is_int
  • is_null — Проверяет, является ли значение переменной равным NULL
  • is_numeric — Проверяет, является ли переменная числом или строкой, содержащей число
  • is_object — Проверяет, является ли переменная объектом
  • is_real — Псевдоним is_float
  • is_resource — Проверяет, является ли переменная ресурсом
  • is_scalar — Проверяет, является ли переменная скалярным значением
  • is_string — Проверяет, является ли переменная строкой
  • isset — Определяет, была ли установлена переменная значением отличным от NULL
  • print_r — Выводит удобочитаемую информацию о переменной
  • serialize — Генерирует пригодное для хранения представление переменной
  • settype — Присваивает переменной новый тип
  • strval — Возвращает строковое значение переменной
  • unserialize — Создает PHP-значение из хранимого представления
  • unset — Удаляет переменную
  • var_dump — Выводит информацию о переменной
  • var_export — Выводит в браузер или возвращает интерпретируемое строковое представление переменной

User Contributed Notes

coding-kid at hotmail dot com 03-Apr-2010 08:13
A simple method to check what type input var is:

<code>
class filter{
    /*
     * @var: $types (array): holds all the supported datatypes, their number, and the callback that need to be made
     *                             to check if it's valid.
     */
    private $types = array('string'=> array('number'=> '1', 'callback'=> 'is_string'),
                            'int'=> array('number' => '2', 'callback' => 'is_int'),
                            'array'=> array('number' => '3', 'callback' => 'is_array'),
                            'object'=> array('number' => '4', 'callback' => 'is_object'),
                            'float'=> array('number' => '5', 'callback' => 'is_float'),
                            'bool'=> array('number' => '6', 'callback' => 'is_bool'),
                            'resource'=> array('number' => '7', 'callback' => 'is_resource'),
                            'null'=> array('number' => '8', 'callback' => 'is_null'));

    function __construct(){

    }
    /*
     * @desc: This method checks what type the input variable is
     *
     * @param: $var (mixed): The var that will be checked
     *
     * @param: $output_type (string): How the result will be returned
     *
     * @returns: string or int
     */
    function type($var, $output_type = 'numeric'){

        if(is_string($var)){
            $var_type = array("string", "1");
        } elseif(is_int($var)){
            $var_type = array("int", "2");
        } elseif(is_array($var)){
            $var_type = array("array", "3");
        } elseif(is_object($var)){
            $var_type = array("object", "4");
        } elseif(is_float($var)){
            $var_type = array("float", "5");
        } elseif(is_bool($var)){
            $var_type = array("bool", "6");
        } elseif(is_resource($var)){
            $var_type = array("resource", "7");
        } elseif(is_null($var)){
            $var_type = array("null", "8");
        }
        if($output_type == 'text'){
            return $var_type[0];
        } else{
            return $var_type[1];
        }
    }
}</code>
jfrasca at sheerdev dot com 31-Aug-2005 10:27
I needed a simple function that would reduce any kind of variable to a string or number while retaining some semblance of the data that was stored in the variable. This is what I came up with:

<?
function ReduceVar ($Value) {
    switch (gettype($Value)) {
        case "boolean":
        case "integer":
        case "double":
        case "string":
        case "NULL":
            return $Value;
        case "resource":
            return get_resource_type($Value);
        case "object":
            return ReduceVar(get_object_vars($Value));
        case "array":
            if (count($Value) <= 0)
                return NULL;
            else
                return ReduceVar(reset($Value));
        default:
            return NULL;
    }
}
?>
skelley at diff dot nl 22-Sep-2001 04:55
Sorry to say Mykolas, but your definition would not be correct.

isempty() evaluates to true for NULL, 0, "", false or 'not set' for any variable, object etc. that can be set to a value.

isset() evaluates to true if the variable, object etc. exists at all, whether it is 'empty' or not.

Example:
$foo = 0;
isset($foo); //will evaluate to true.
!empty($foo); //will evaluate to false.

unset($foo);
isset($foo); //will evaluate to false.
!empty($foo); //will evaluate to false.
Предопределенные константы
debug_zval_dump
Функции для работы с переменными
PHP Manual


Выводит строковое представление внутреннего значения zend

Функции для работы с переменными
doubleval
Функции для работы с переменными
PHP Manual

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5)

debug_zval_dump — Выводит строковое представление внутреннего значения zend

Описание

void debug_zval_dump ( mixed $variable )

Выводит строковое представление внутреннего значения zend.

Список параметров

variable

Обрабатываемая переменная.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования debug_zval_dump()

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump(&$var1);
?>

Результат выполнения данного примера:

&string(11) "Hello World" refcount(3)

Замечание: Предостережение по поводу refcount

Значение refcount, возвращаемое этой функцией, в некоторых случаях неочевидно. Например, разработчик может ожидать, что в приведенном выше примере значение refcount будет 2. Третья ссылка была создана в момент вызова debug_zval_dump().

Это поведение более сложно, когда переменная не передается в функцию debug_zval_dump() по ссылке. Для иллюстрации рассмотрим немного измененный вариант приведенного выше примера:

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump($var1); // в этот раз не передается по ссылке
?>

Результат выполнения данного примера:

string(11) "Hello World" refcount(1)

Почему refcount(1)? Потому что копия $var1 создается при вызове функции.

Эта функция становится еще более сбивающей с толку, когда передается переменная со значением refcount, равным 1 (копированием по значению):

<?php
$var1 = 'Hello World';

debug_zval_dump($var1);
?>

Результат выполнения данного примера:

string(11) "Hello World" refcount(2)

Значение refcount, равное 2, в данном случае совсем непонятно. Особенно учитывая приведенные выше примеры. Так в чем же дело?

Когда переменная имеет единственную ссылку (как было с переменной $var1, перед тем, как ее передали в качестве аргумента в функцию debug_zval_dump()), процессор PHP оптимизирует метод, которым она передается в функцию. Внутренне, PHP рассматривает $var1 как ссылку (таким образом refcount увеличивается для области видимости функции), при условии, что если в переданную ссылку придется производить запись, то будет создана ее копия, но только в момент записи. Такое поведение известно как "copy on write."

Таким образом, если debug_zval_dump() приходится писать в свой единственный параметр (а она не делает этого), то будет создана копия. До этого момента параметр остается ссылкой, приводя к увеличению refcount до 2 в области видимости вызова функции.

Смотрите также

  • var_dump() - Выводит информацию о переменной
  • debug_backtrace() - Выводит стек вызовов функций в массив
  • "Ссылки. Разъяснения"
  • "» Ссылки. Разъяснения (от Derick Rethans)"

User Contributed Notes

AmberBlackthorn 23-Oct-2010 05:35
The add of "Call-time pass-by-reference" as E_DEPRECATED makes it impossible to get the real refcount without getting an error, since <?php error_reporting(E_ALL ^ E_DEPRECATED); ?> and even <?php @debug_zval_dump(&$foo); ?> doesn't change anything.
Функции для работы с переменными
doubleval
Функции для работы с переменными


Псевдоним floatval

debug_zval_dump
empty
Функции для работы с переменными
PHP Manual

doubleval

(PHP 4, PHP 5)

doubleval — Псевдоним floatval()

Описание

Эта функция является псевдонимом: floatval().

Список изменений

Версия | Описание
4.2.0 | doubleval() стала псевдонимом функции floatval(). До этого времени существовала только функция doubleval().

User Contributed Notes

Anonymous 14-Sep-2010 03:30
We can convert the value to normal decimal value...
<?php
 $mynumstr = "100,000,000.75";
 $mynum = doubleval(str_replace(",","",$mynumstr));
 echo "Normal Value:".number_format($mynumstr);
?>
debug_zval_dump
empty
Функции для работы с переменными


Проверяет, пуста ли переменная

doubleval
floatval
Функции для работы с переменными
PHP Manual

empty

(PHP 4, PHP 5)

empty — Проверяет, пуста ли переменная

Описание

bool empty ( mixed $var )

Проверяет, пуста ли переменная.

Список параметров

var

Проверяемая переменная

Замечание:

empty() проверяет только переменные, и попытка проверить что-то еще вызовет ошибку синтаксиса. Другими словами, следующий код не будет работать: empty(trim($name)).

empty() является противоположностью (boolean) var, за исключением того, что в случае неопределенной переменной не будет сгенерировано предупреждения.

Возвращаемые значения

Возвращает FALSE, если var содержит непустое и ненулевое значение.

Следующие значения воспринимаются как пустые:

  • "" (пустая строка)
  • 0 (целое число)
  • 0.0 (дробное число)
  • "0" (строка)
  • NULL
  • FALSE
  • array() (пустой массив)
  • var $var; (переменная объявлена, но не имеет значения в классе)

Список изменений

Версия | Описание
5.4.0 | Проверка нечислового индекса строки возвращает TRUE.
5.0.0 | Объекты без свойств более не считаются пустыми.

Примеры

Пример #1 Простое сравнение empty() и isset().

<?php
$var = 0;

// Принимает значение true, потому что $var пусто
if (empty($var)) {
    echo '$var или 0, или пусто, или вообще не определена';
}

// Принимает значение true, потому что $var определена
if (isset($var)) {
    echo '$var определена, даже если она пустая';
}
?>

Пример #2 empty() и строковые индексы

В PHP 5.4 был изменен способ обработки строковых индексов в empty().

<?php
$expected_array_got_string = 'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));
?>

Результат выполнения данного примера в PHP 5.3:

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

Результат выполнения данного примера в PHP 5.4:

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

При использовании функции empty() на недоступных (необъявленных) свойствах объекта будет вызван встроенный метод объекта __isset(), если он определен.

Смотрите также

  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • __isset()
  • unset() - Удаляет переменную
  • array_key_exists() - Проверяет, присутствует ли в массиве указанный ключ или индекс
  • count() - Подсчитывает количество элементов массива или что-то в объекте
  • strlen() - Возвращает длину строки
  • Таблица сравнения типов

User Contributed Notes

martin dot aarhof at gmail dot com 15-Mar-2012 08:38
<?php
$str = '            ';
var_dump(empty($str)); // boolean false
?>

So remember to trim your strings first!

<?php
$str = '        ';
$str = trim($str);
var_dump(empty($str)); // boolean true
?>
qeremy 07-Mar-2012 03:33
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _empty($val) { return empty($val); }
?>
chris dot wisefool at gmail dot com 09-Sep-2011 12:44
Note that checking the existence of a subkey of an array when that subkey does not exist but the parent does and is a string will return false for empty.

i.e.

<?php
$params = array('search'=>'1');
empty($params['search']['filter']); # returns false
?>

This is correct, per the documentation (http://php.net/manual/en/language.types.string.php); quite a bit down the page is the Warning: "Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer." ) I didn't receive a warning but perhaps that's correct too...depends on whether the string -> integer conversion is considered "illegal": "Illegal offset type emits E_NOTICE."

(i.e. since $params['search'] is a string, the 'filter' subscript is converted to 0, so the test becomes empty($params['search'][0]), which is obviously false), but it tripped me up enough to mistakenly file a bug report (which I've since closed).
steven at nevvix dot com 02-May-2011 09:16
When you need to accept these as valid, non-empty values:
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)

<?php
function is_blank($value) {
    return empty($value) && !is_numeric($value);
}
?>

This is similar to Rails' blank? method.
phpsort 21-Jan-2011 11:13
I'm summarising a few points on empty() with inaccessible properties, in the hope of saving others a bit of time. Using PHP 5.3.2.
<?php
class MyClass {
    private $foo = 'foo';
}
$myClass = new MyClass;
echo $myClass->foo;
?>
As expected, this gives "Fatal error: Cannot access private property MyClass::$foo".
But substitute the line
if (empty($myClass->foo)) echo 'foo is empty'; else echo 'foo is not empty';
and we get the misleading result "foo is empty".
There is NO ERROR OR WARNING, so this is a real gotcha. Your code will just go wrong silently, and I would say it amounts to a bug.
If you add two magic functions to the class:
public function __get($var) { return $this->$var; }
public function __isset($var) { return isset($this->$var); }
then we get the expected result. You need both functions.
For empty($myClass->foo), I believe PHP calls __isset, and if that is true returns the result of empty on the result of __get. (Some earlier posts wrongly suggest PHP just returns the negation of __isset).
BUT …
See the earlier post by php at lanar dot com. I confirm those results, and if you extend the test with isset($x->a->b->c) it appears that __isset is only called for the last property in the chain. Arguably another bug. empty() behaves in the same way. So things are not as clear as we might hope.
See also the note on empty() at
http://uk3.php.net/manual/en/language.oop5.overloading.php
Clear as mud!
christian dot achatz at adventure-php-framework dot org 17-Jan-2011 12:54
Since this special case is not mentioned already: the empty() check does not work for mysqli resources / connections stored within a private variable.

Instead of

if(!empty($this->dbConn->error)){...}

you have to use

$error = $this->dbConn->error;
if(!empty($error)){...}

otherwise the condition will not evaluate to true in case a mysqli error is given for the present connection.
e dot klerks at i-bytes dot nl 08-Nov-2010 06:16
To make an empty function, which only accepts arrays, one can use type-hinting:

<?php
// emptyArray :: [a] -> Bool

function emptyArray(array $xs){
 return empty($xs);
}
?>

Type hinting is a good thing to use in your code, because it makes it more easy to reason about your code. Besides that, it automatically documents the code.
serkons at yahoo dot com 28-Oct-2010 02:01
Hi you can check the status of multiple array or any variable is empty with below code.

<?php
$microtimeref = microtime ( true );
//$variable=null; // false,true,0,''
//$variable = array ('id' => 10, 'name' => 'serkon' );
$variable = array (array (0) );
echo '<pre>';
function getArray($dizi) {
    foreach ( $dizi as $value )
        return $value;
}
function isEmpty($array) {
    if (is_array ( $array )) {
        $dizi = getArray ( $array );
        if (is_array ( $dizi ))
            $ref = isEmpty ( $dizi );
        else
            if (strlen ( $dizi ) >= 1)
                return false;
            else
                return true;
    }
    else
        if (strlen ( $array ) >= 1)
            return false;
        else
            return true;

    if ($ref === false)
        return false;
    else
        return true;
}
$sonuc = isEmpty ( $variable );
var_dump ( $sonuc );
echo "Total time: <b>" . round ( microtime ( true ) - $microtimeref, 4 ) . 's</b><br />';
echo '</pre>';
?>

Response:

bool(false)  // not empty
Total time: 0s
rodolphe dot bodeau at free dot fr 25-Oct-2010 06:37
Be careful, if "0" (zero as a string), 0 (zero as an integer) and -0 (minus zero as an integer) return true, "-0" (minus zero as a string (yes, I already had some customers that wrote -0 into a form field)) returns false. You need to cast your variable before testing it with the empty() function :

<?php
$var = "-0";
echo empty($var);  // returns false
$var = (int) $var; // casts $var as an integer
echo empty($vat);  // returns true
?>
ehsmeng 21-Sep-2010 05:25
I can't use empty() in all situations because '0' is usually not considered empty to me. I did a quick benchmark over the most common ways of testing it. '' == var suffers from '' == 0 is true so that's just there for curiosity.

<?php
    $microtimeref = microtime(true);
    $a = 0;
    $b = 'asd';
    for ($i = 0; $i < 5000000; $i++)
    {
        if (0 == mb_strlen ($b))
        {
            $a++;
        }
    }
    echo "Total time 0 == mb_strlen(var): <b>" . round(microtime(true) - $microtimeref,3) . 's</b><br />';
?>

The results:

Total time 0 == mb_strlen(var): 3.141s
Total time 0 === strlen(var): 2.904s
Total time 0 == strlen(var): 2.878s
Total time '' == var: 1.774s
Total time '' === var: 1.706s
Total time empty(var): 1.496s

Thus '' === var will be my zero length string test.
marko dot crni at gmail dot com 16-Sep-2010 11:06
Calling non existing object property, empty($object->prop), will trigger __isset(), the same way as isset($object->prop) does, but there is one difference. If __isset() returns TRUE, another call to __get() will be made and actual return value will be result of empty() and result of __get().
php at sethsyberg dot com 06-May-2010 10:30
To find if an array has nothing but empty (string) values:

<?php
$foo = array('foo'=>'', 'bar'=>'');
$bar = implode('', $foo);

if (empty($bar)) {
    echo "EMPTY!";
} else {
    echo "NOT EMPTY!";
}
?>
aidan1103 at yahoo dot com 26-Mar-2010 10:11
empty() should not necessarily return the negation of the __isset() magic function result, if you set a data member to 0, isset() should return true and empty should also return true.  A simpler implementation of the __isset magic function would be:

public function __isset($key) {
  return isset($this->{$key});
}

I don't understand why this isn't included in stdClass and inherited by default.
kleingeist 24-Nov-2009 05:23
Another, simpler, implementation to test if mulitarrays are empty.

<?php
function array_empty($mixed) {
    if (is_array($mixed)) {
        foreach ($mixed as $value) {
            if (!array_empty($value)) {
                return false;
            }
        }
    }
    elseif (!empty($mixed)) {
        return false;
    }
    return true;
}
?>
Janci 24-Aug-2009 08:57
Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it's noted in the documentation above, I think it's worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add  __isset() magic function to your class:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
    public function __isset($key)
    {
        if (isset($this->_items[$key])) {
            return (false === empty($this->_items[$key]));
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // false, finally!
?>

It actually seems that empty() is returning negation of the __isset() magic function result, hence the negation of the empty() result in the __isset() function above.
denobasis-bozic et yahoo.com 18-Jul-2009 04:54
test if all multiarray's are empty

<?php
function is_multiArrayEmpty($multiarray) {
    if(is_array($multiarray) and !empty($multiarray)){
        $tmp = array_shift($multiarray);
            if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
                return false;
            }
            return true;
    }
    if(empty($multiarray)){
        return true;
    }
    return false;
}

$testCase = array (
0 => '',
1 => "",
2 => null,
3 => array(),
4 => array(array()),
5 => array(array(array(array(array())))),
6 => array(array(), array(), array(), array(), array()),
7 => array(array(array(), array()), array(array(array(array(array(array(), array())))))),
8 => array(null),
9 => 'not empty',
10 => "not empty",
11 => array(array("not empty")),
12 => array(array(),array("not empty"),array(array()))
);

foreach ($testCase as $key => $case ) {
    echo "$key is_multiArrayEmpty= ".is_multiArrayEmpty($case)."<br>";
}
?>

OUTPUT:
========

0 is_multiArrayEmpty= 1
1 is_multiArrayEmpty= 1
2 is_multiArrayEmpty= 1
3 is_multiArrayEmpty= 1
4 is_multiArrayEmpty= 1
5 is_multiArrayEmpty= 1
6 is_multiArrayEmpty= 1
7 is_multiArrayEmpty= 1
8 is_multiArrayEmpty= 1
9 is_multiArrayEmpty=
10 is_multiArrayEmpty=
11 is_multiArrayEmpty=
12 is_multiArrayEmpty=
mlibazisi mabandla 28-May-2009 02:47
in cases when "0" is not intended to be empty, here is a simple function to safely test for an empty string (or mixed variable):

<?php
function _empty($string){
     $string = trim($string);
     if(!is_numeric($string)) return empty($string);
     return FALSE;
}
?>
emperoruk at dontspam dot hotmail dot com 08-May-2009 08:07
When using the php empty() function to check submitted variables such as $_POST or $_GET, be careful to remember that values 0 (integer) and "0" (string with zero character) are all considered empty. eg. in a simple cms a page ID of zero might be used to indicate that the homepage should be displayed but using the following code:

<?php
if (isset($_GET['pid'] && !empty($_GET['pid']) {
  // assign value to local variable
  $pageID = $_GET['pid'];
} else {
  echo "missing variable 'pageID'";
}
?>

When attempting to display the homepage using a pid of zero the above code will fail.

So as a result i wrote a small function to replace the php empty() function in situations where you want 0 and "0" not to be considered empty.

<?php
function is_empty($var, $allow_false = false, $allow_ws = false) {
    if (!isset($var) || is_null($var) || ($allow_ws == false && trim($var) == "" && !is_bool($var)) || ($allow_false === false && is_bool($var) && $var === false) || (is_array($var) && empty($var))) {
        return true;
    } else {
        return false;
    }
}
?>

This function will allow you to test a variable is empty and considers the following values as empty:

an unset variable -> empty
null -> empty
0 -> NOT empty
"0" -> NOT empty
false -> empty
true -> NOT empty
'string value' -> NOT empty
"    " (white space) -> empty
array() (empty array) -> empty

There are two optional parameters:

$allow_false: setting this to true will make the function consider a boolean value of false as NOT empty. This parameter is false by default.

$allow_ws: setting this to true will make the function consider a string with nothing but white space as NOT empty. This parameter is false by default.

In Testing:

<?php
// an unset variable
echo 'unset variable ($notset) - Empty: ';
echo is_empty($notset) ? 'yes<br />' : 'no<br />';
// NULL variable
echo 'null - Empty: ';
$var = null;
echo is_empty($var) ? 'yes<br />' : 'no<br />';
// integer 0
echo '0 - Empty: ';
$var = 0;
echo is_empty($var) ? 'yes<br />' : 'no<br />';
// string "0"
echo 'string "0" - Empty: ';
$var = "0";
echo is_empty($var) ? 'yes<br />' : 'no<br />';
// boolean value false
echo 'false - Empty: ';
$var = false;
echo is_empty($var) ? 'yes<br />' : 'no<br />';
// allow boolean value false
echo 'false ($allow_false = true) - Empty: ';
$var = false;
echo is_empty($var, true) ? 'yes<br />' : 'no<br />';
// boolean value true
echo 'true - Empty: ';
$var = true;
echo is_empty($var) ? 'yes<br />' : 'no<br />';
// string
echo 'string "foo" - Empty: ';
$var = "foo";
echo is_empty($var) ? 'yes<br />' : 'no<br />';
// white space
echo 'white space "     " - Empty: ';
$var = "    ";
echo is_empty($var) ? 'yes<br />' : 'no<br />';
// allow white space
echo 'white space ($allow_ws = true) "     " - Empty: ';
$var = "    ";
echo is_empty($var, false, true) ? 'yes<br />' : 'no<br />';
// empty array
echo 'empty array - Empty: ';
$var = array();
echo is_empty($var) ? 'yes<br />' : 'no<br />';
?>

the above code outputs the following:

unset variable ($notset) - Empty: yes
null - Empty: yes
0 - Empty: no
string "0" - Empty: no
false - Empty: yes
false ($allow_false = true) - Empty: no
true - Empty: no
string "foo" - Empty: no
white space " " - Empty: yes
white space ($allow_ws = true) " " - Empty: no
empty array - Empty: yes

Hope this code is useful for someone.

Michael
contato at andersonfraga dot net 10-Feb-2009 11:24
<?php

function _empty() {
    foreach(func_get_args() as $args) {
        if( !is_numeric($args) ) {
            if( is_array($args) ) { // Is array?
                if( count($args, 1) < 1 ) return true;
            }
            elseif(!isset($args) || strlen(trim($args)) == 0)
                return true;
            }
        }
    }
    return false;
}

?>
thomas at thomasnoest dot nl 28-Nov-2008 01:54
Note on the selfmade empty function below:

function_exists() returns false on language constructs and empty is a language construct.
nizamgok at gmail dot com 27-Oct-2008 06:52
By definition empty( mixed* $var  ) cannot accept all types. For example, define constants will cause error if you try to test them.

* mixed indicates that a parameter may accept multiple (but not necessarily all) types.

This will produce error:
define("CONSTANT", "Hello world.");
var_dump( empty( CONSTANT ) );

At  first, this seemed to me very legal, but then I realized the fact that it just doesn't work.
justin at booleangate dot org 22-Aug-2008 04:59
How about this improvement to Karl Jung's my_empty

<?php
function my_empty($val) {
    $val = trim($val);

    return empty($val) && $val !== 0;
}
?>
Anonymous 20-Aug-2008 02:41
To add on to what anon said, what's happening in john_jian's example seems unusual because we don't see the implicit typecasting going on behind the scenes.  What's really happening is:

$a = '';
$b = 0;
$c = '0';

(int)$a == $b -> true, because any string that's not a number gets converted to 0
$b==(int)$c -> true, because the int in the string gets converted
and
$a==$c -> false, because they're being compared as strings, rather than integers.  (int)$a==(int)$c should return true, however.

Note: I don't remember if PHP even *has* typecasting, much less if this is the correct syntax.  I'm just using something for the sake of examples.
tom at tomwardrop dot com 22-May-2008 05:01
In reply to "admin at ninthcircuit dot info",

Using str_replace is unnecessary. I would encourage the use of trim which would most likely be faster (haven't tested) and easier. Trim also takes care of other white space like line breaks and tabs. Actually, in most of the applications I code, I use a multi-dimensional array map function with trim on the Super Globals such as $_POST, $_GET and $_COOKIE as so far, there hasn't been an instance where I would want any user input to begin or end with whitespace. The good thing about doing this is that you never have to worry about 'trimming' your input which makes your code easier and more reliable (incase you forget to trim some input).
Greg Hartwig 02-May-2008 02:55
David from CodeXplorer:
>> The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check.
>> So, don't bother using EMPTY in the real world.

This is NOT true.  empty() will not generate warnings if you're testing against an undefined variable as a simple boolean check will.  On production systems, warnings are usually shut off, but they are often active on development systems.

You could test a flag with
   <?php if ($flagvar)  ... ?>
but this can generate a warning if $flagvar is not set.

Instead of
   <?php if (isset($flagvar) && $flagvar)  ... ?>
you can simply use
   <?php if (!empty($flagvar))  ... ?>

for easy readability without warnings.
David from CodeXplorer 10-Mar-2008 08:29
Mad Hampster did  his test wrong. empty is NOT faster than a simple boolean check. The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check. But if you are dealing with intermediate or higher level coders this function has no other benefit.

So, don't bother using EMPTY in the real world.

I ran an array with 5000 simple true/false values through four checks (both types twice) in case of any gain one type might have by going first. These are my results generated one one page request. (PHP5)

0.015328 Time EMPTY
0.014281 Time IF/ELSE
0.015239 Time EMPTY
0.013404 Time IF/ELSE

The page was accessed a couple times to reduce caching effects.
Andrea Giammarchi 31-Jan-2008 07:34
In addiction to Ed comment:
http://uk.php.net/manual/en/function.empty.php#80106

if an instance variable is assigned with an empty value, i.e. false, empty returns true.

<?php
class TestEmpty{
    protected           $empty;
    public  function    __construct(){
        var_dump(empty($this->empty)); // true
        $this->empty = false;
        var_dump(empty($this->empty)); // true
    }
}
new TestEmpty;
?>

I think this is an expected behaviour but at the same time the note about classes variables is too ambiguous.

''var $var; (a variable declared, but without a value in a class)''

Please change them into something like:
''var $var; (a variable undeclared or declared with an empty value in a class)''
jay at w3prodigy dot com 28-Jan-2008 10:59
Also note, that if you have a URI that looks like this:

/page/index.php?query=

performing isset($_GET['query']) will return TRUE. as query is set, though null, in the QUERY.

To counteract this behavior, check isset($_GET['query']) and !empty($_GET['query']) as empty will detect the null value.
Ed 29-Dec-2007 12:08
Also, it doesn't appear to mention in the documentation, if a variable hasn't previously been declared, empty also returns true.

E.g.
var $bar;
empty( $bar ); // declared variable returns true.
empty( $foo ); // undeclared variable also returns true.

The closest the documentation comes to saying this is:
"var $var; (a variable declared, but without a value in a class)"
which isn't really the same, as the variable doesn't necessarily have to be declared first.
MaD HamsteR 12-Dec-2007 07:33
SAME RESULT! But somehow using empty() function is faster for about 10-13%

<?php

$array[] = "";
$array[] = '';
$array[] = 0;
$array[] = "0";
$array[] = NULL;
$array[] = false;
$array[] = array();
$array[] = $var;

foreach($array as $value){
    echo (!empty($value))? 'Not empty!' : 'Empty!';
    echo '<br />'."\r\n";
}

echo '<br />'."\r\n";

foreach($array as $value){
    echo ($value)? 'Not empty!' : 'Empty!';
    echo '<br />'."\r\n";
}

?>
EllisGL 04-Oct-2007 02:48
Here's what I do for the zero issue issue:
if($val == '' && $val !== 0 && $val !== '0')
Antone Roundy 15-Sep-2007 06:55
There's a faster and easier to write method than (isset($a) && strlen($a)) -- isset($a{0}). It evaluates to false if $a is not set or if it has zero length (ie. it's first character is not set). My tests indicate that it's about 33% faster.
rkulla2 at gmail dot com 05-Sep-2007 03:57
Since I didn't like how empty() considers 0 and "0" to be empty (which can easily lead to bugs in your code), and since it doesn't deal with whitespace, i created the following function:

<?php
function check_not_empty($s, $include_whitespace = false)
{
    if ($include_whitespace) {
        // make it so strings containing white space are treated as empty too
        $s = trim($s);
    }
    return (isset($s) && strlen($s)); // var is set and not an empty string ''
}
?>

Instead of saying if (!empty($var)) { // it's not empty } you can just say if (check_not_empty($var)) { // it's not empty }.

If you want strings that only contain whitespace (such as tabs or spaces) to be treated as empty then do: check_not_empty($var, 1)

If you want to check if a string IS empty then do: !check_not_empty($var).

So, whenever you want to check if a form field both exists and contains a value just do: if (check_not_empty($_POST['foo'], 1))

no need to do if (isset() && !empty()) anymore =]
florian.sonner [at] t-online.de 11-Jun-2007 12:06
Since a few people here mentioned that empty will not work with magic-overloading ("__get($var)"):

empty(..) goes the same way as isset(..) do, to check if a property exists. Thus you have to override the magic-function __isset($var) to produce correct results for empty(..) in combination with a magic-overloaded property.
nobody at example dot com 28-Feb-2006 12:06
Re: inerte is my gmail.com username's comment:

While that may be true, those two statements (empty($var), $var == '') are NOT the same. When programming for web interfaces, where a user may be submitting '0' as a valid field value, you should not be using empty().

<?php
    $str = '0';

    // outputs 'empty'
    echo empty($str) ? 'empty' : 'not empty';

    // outputs 'not empty'
    echo $str == '' ? 'empty' : 'not empty';
?>
nahpeps at gmx dot de 19-Aug-2005 03:14
When using empty() on an object variable that is provided by the __get function, empty() will always return true.

For example:

<?php
class foo {

   public function __get($var) {
      if ($var == "bar") {
         return "bar";
      }
   }
}
$object_foo = new foo();
echo '$object_foo->bar is ' . $object_foo->bar;
if (empty($object_foo->bar)) {
   echo '$object_foo->bar seems to be empty';
}
?>

produces the following output:
$object_foo->bar is bar
$object_foo->bar seems to be empty
jmarbas at hotmail dot com 01-Jul-2005 09:10
empty($var) will return TRUE if $var is empty (according to the definition of 'empty' above) AND if $var is not set.

I know that the statement in the "Return Values" section of the manual already says this in reverse:

"Returns FALSE if var has a non-empty and non-zero value."

but I was like "Why is this thing returning TRUE for unset variables???"... oh i see now... Its supposed to return TRUE for unset variables!!!

<?php
  ini_set('error_reporting',E_ALL);
  ini_set('display_errors','1');
  empty($var);
?>
admin at ninthcircuit dot info 24-May-2005 10:14
Something to note when using empty():

empty() does not see a string variable with nothing but spaces in it as "empty" per se.

Why is this relevant in a PHP application? The answer is.. if you intend to use empty() as a means of input validation, then a little extra work is necessary to make sure that empty() evaluates input with a more favorable outcome.

Example:
<?php
  $spaces = "       ";
  /* This will return false! */
  if (empty($spaces))
     print "This will never be true!";
  else
     print "Told you!";
?>

To make empty() behave the way you would expect it to, use str_replace().

<?php
  $spaces = str_replace(" ","","      ");
  /* This will return true! */
  if (empty($spaces))
      print "This will always be true!";
  else
      print "Told you!";
?>

This might seem trivial given the examples shown above; however, if one were to be storing this information in a mySQL database (or your preferred DB of choice), it might prove to be problematic for retrieval of it later on.
paul at worldwithoutwalls dot co dot uk 22-May-2004 10:09
Note the exceptions when it comes to decimal numbers:

<?php
$a = 0.00;
$b = '0.00';
echo (empty($a)? "empty": "not empty"); //result empty
echo (empty($b)? "empty": "not empty"); //result not empty
//BUT...
$c = intval($b);
echo (empty($c)? "empty": "not empty"); //result empty
?>

For those of you using MySQL, if you have a table with a column of decimal type, when you do a SELECT, your data will be returned as a string, so you'll need to do apply intval() before testing for empty.

e.g.
TABLE t has columns id MEDIUMINT and d DECIMAL(4,2)
and contains 1 row where id=1, d=0.00
<?php
$q = "SELECT * FROM t";
$res = mysql_query($q);
$row = mysql_fetch_assoc($res);
echo (empty($row['d'])? "empty": "not empty"); //result not empty
?>
doubleval
floatval
Функции для работы с переменными


Возвращает значение переменной в виде числа с плавающей точкой

empty
get_defined_vars
Функции для работы с переменными
PHP Manual

floatval

(PHP 4 >= 4.2.0, PHP 5)

floatval — Возвращает значение переменной в виде числа с плавающей точкой

Описание

float floatval ( mixed $var )

Возвращает значение переменной var в виде числа с плавающей точкой (float).

Список параметров

var

Может быть любого скалярного типа. floatval() нельзя использовать с объектами, в этом случае возникнет ошибка уровня E_NOTICE и функция вернет 1.

Возвращаемые значения

Значение заданной переменной в виде числа с плавающей точкой. Пустые массивы в качестве аргумента возвращают 0, непустые массивы возвращают 1.

Примеры

Пример #1 Пример использования floatval()

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

Смотрите также

  • intval() - Возвращает целое значение переменной
  • strval() - Возвращает строковое значение переменной
  • settype() - Присваивает переменной новый тип
  • Манипуляции с типами

User Contributed Notes

PapaPinguoin 31-Oct-2011 07:26
To view the very large and very small numbers (eg from a database DECIMAL), without displaying scientific notation, or leading zeros.

FR : Pour afficher les très grand et très petits nombres (ex. depuis une base de données DECIMAL), sans afficher la notation scientifique, ni les zéros non significatifs.

<?php
function floattostr( $val )
{
    preg_match( "#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o );
    return $o[1].sprintf('%d',$o[2]).($o[3]!='.'?$o[3]:'');
}
?>

<?php
echo floattostr("0000000000000001");
echo floattostr("1.00000000000000");
echo floattostr("0.00000000001000");
echo floattostr("0000.00010000000");
echo floattostr("000000010000000000.00000000000010000000000");
echo floattostr("-0000000000000.1");
echo floattostr("-00000001.100000");

// result
// 1
// 1
// 0.00000000001
// 0.0001
// 10000000000.0000000000001
// -0.1
// -1.1

?>
secretr at NOSPAM dot e107 dot org 03-Jan-2011 08:37
setlocale() and floatval() duo could break your DB queries in a very simple way:

<?php
setlocale(LC_ALL, 'bg_BG', 'bgr_BGR');
echo floatval(0.15); // output 0,15
?>

You would need simple workaround like:

<?php
function number2db($value)
{
    $larr = localeconv();
    $search = array(
        $larr['decimal_point'],
        $larr['mon_decimal_point'],
        $larr['thousands_sep'],
        $larr['mon_thousands_sep'],
        $larr['currency_symbol'],
        $larr['int_curr_symbol']
    );
    $replace = array('.', '.', '', '', '', '');

    return str_replace($search, $replace, $value);
}

setlocale(LC_ALL, 'bg_BG', 'bgr_BGR');
$testVal = floatval(0.15); // result 0,15
var_dump($testVal, number2db($testVal));

// Result:
// float(0,15)
// string(4) "0.15"
?>
balai01 at yahoo dot com 13-Oct-2010 03:56
//changes comma to dot if any
//removes any currency symbol and gets the floatVar

$price_fl_point=(preg_replace("/,/",".",$price));
$price_c=floatval(preg_replace("/^[^0-9\.]/","",$price_fl_point));
chris at georgakopoulos dot com 29-Jul-2009 08:12
locale aware floatval:

<?php
function ParseFloat($floatString){
    $LocaleInfo = localeconv();
    $floatString = str_replace($LocaleInfo["mon_thousands_sep"] , "", $floatString);
    $floatString = str_replace($LocaleInfo["mon_decimal_point"] , ".", $floatString);
    return floatval($floatString);
}
?>
ted devito 09-Mar-2009 09:10
i noticed all (well, unless i missed something) the functions working with decimals destroy trailing decimal places. this function restores them in case you want to be able to display a consistent precision for users.

<?php
function decimal($val, $precision = 0) {
    if ((float) $val) :
        $val = round((float) $val, (int) $precision);
        list($a, $b) = explode('.', $val);
        if (strlen($b) < $precision) $b = str_pad($b, $precision, '0', STR_PAD_RIGHT);
        return $precision ? "$a.$b" : $a;
    else : // do whatever you want with values that do not have a float
        return $val;
    endif;
}
?>
info at marc-gutt dot de 26-Aug-2008 03:55
<?php
function floatvalue($value) {
     return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}
?>

It is much shorter and able to handle those one, too:
xx,-
xx,--
xx'xxx,xx

After using floatvalue() you can go forward with number_format() as usual.
Michiel 30-Jul-2008 05:21
The last getFloat() function is not completely correct.

1.000.000 and 1,000,000 and its negative variants are not correctly parsed. For the sake of comparing and to make myself clear I use the name parseFloat in stead of getFloat for the new function:

<?php
function parseFloat($ptString) {
            if (strlen($ptString) == 0) {
                    return false;
            }

            $pString = str_replace(" ", "", $ptString);

            if (substr_count($pString, ",") > 1)
                $pString = str_replace(",", "", $pString);

            if (substr_count($pString, ".") > 1)
                $pString = str_replace(".", "", $pString);

            $pregResult = array();

            $commaset = strpos($pString,',');
            if ($commaset === false) {$commaset = -1;}

            $pointset = strpos($pString,'.');
            if ($pointset === false) {$pointset = -1;}

            $pregResultA = array();
            $pregResultB = array();

            if ($pointset < $commaset) {
                preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
            }
            preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
            if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
                    || strstr($preResultA[0],$pregResultB[0]) == 0
                    || !$pointset))) {
                $numberString = $pregResultA[0];
                $numberString = str_replace('.','',$numberString);
                $numberString = str_replace(',','.',$numberString);
            }
            elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
                    || strstr($pregResultB[0],$preResultA[0]) == 0
                    || !$commaset)) {
                $numberString = $pregResultB[0];
                $numberString = str_replace(',','',$numberString);
            }
            else {
                return false;
            }
            $result = (float)$numberString;
            return $result;
}
?>

Comparing of float parsing functions with the following function:

<?php
function testFloatParsing() {
    $floatvals = array(
        "22 000,76",
        "22.000,76",
        "22,000.76",
        "22 000",
        "22,000",
        "22.000",
        "22000.76",
        "22000,76",
        "1.022.000,76",
        "1,022,000.76",
        "1,000,000",
        "1.000.000",
        "1022000.76",
        "1022000,76",
        "1022000",
        "0.76",
        "0,76",
        "0.00",
        "0,00",
        "1.00",
        "1,00",
        "-22 000,76",
        "-22.000,76",
        "-22,000.76",
        "-22 000",
        "-22,000",
        "-22.000",
        "-22000.76",
        "-22000,76",
        "-1.022.000,76",
        "-1,022,000.76",
        "-1,000,000",
        "-1.000.000",
        "-1022000.76",
        "-1022000,76",
        "-1022000",
        "-0.76",
        "-0,76",
        "-0.00",
        "-0,00",
        "-1.00",
        "-1,00"
    );

    echo "<table>
        <tr>
            <th>String</th>
            <th>floatval()</th>
            <th>getFloat()</th>
            <th>parseFloat()</th>
        </tr>";

    foreach ($floatvals as $fval) {
        echo "<tr>";
        echo "<td>" . (string) $fval . "</td>";

        echo "<td>" . (float) floatval($fval) . "</td>";
        echo "<td>" . (float) getFloat($fval) . "</td>";
        echo "<td>" . (float) parseFloat($fval) . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}
?>
steve at opilo dot net 20-Jul-2008 06:07
Most of the functions listed here that deal with $ and , are unnecessarily complicated. You can use ereg_replace() to strip out ALL of the characters that will cause floatval to fail in one simple line of code:

<?php $output = floatval(ereg_replace("[^-0-9\.]","",$input)); ?>
leprau at leprau dot de 19-Jul-2007 09:26
For those of you, who are looking for a function that rips the first,
but longest possible float (or at least integer) from a string,
like 123.45 from the string "Price: 123,45$"

If no useable value is found, the function returns false.

Checks for both comma and dot as decimal-separator,
but does not check for 3 digits between thousands,
so 1,234.5 is as valid as 1,23,4.5 (both will return 1234.5)

12,.3 will return 12
1,000,000 will return 1000.0 !

(if thousands separator is defined,
decimals should be defined too ...
in fact I was too lazy to check for that too)

Here you go, and feel free to optimize the function ;)
<?php
function getFloat($pString) {
    if (strlen($pString) == 0) {
            return false;
    }
    $pregResult = array();

    $commaset = strpos($pString,',');
    if ($commaset === false) {$commaset = -1;}

    $pointset = strpos($pString,'.');
    if ($pointset === false) {$pointset = -1;}

    $pregResultA = array();
    $pregResultB = array();

    if ($pointset < $commaset) {
        preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
    }
    preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
    if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
            || strstr($preResultA[0],$pregResultB[0]) == 0
            || !$pointset))) {
        $numberString = $pregResultA[0];
        $numberString = str_replace('.','',$numberString);
        $numberString = str_replace(',','.',$numberString);
    }
    elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
            || strstr($pregResultB[0],$preResultA[0]) == 0
            || !$commaset)) {
        $numberString = $pregResultB[0];
        $numberString = str_replace(',','',$numberString);
    }
    else {
        return false;
    }
    $result = (float)$numberString;
    return $result;
}
?>
aa at geb-team dot de 04-Sep-2006 08:03
@pillepop2003 at yahoo dot de

<?php
float('-100.00', array('single_dot_as_decimal' => true)); // whoops, returns -10000
?>

use: "/^[0-9-]*[\.]{1}[0-9-]+$/"
instead of: "/^[0-9]*[\.]{1}[0-9-]+$/"
19-Apr-2005 05:30
you can also use typecasting instead of functions:

(float) $value;
pillepop2003 at yahoo dot de 14-Dec-2004 02:38
Use this snippet to extract any float out of a string. You can choose how a single dot is treated with the (bool) 'single_dot_as_decimal' directive.
This function should be able to cover almost all floats that appear in an european environment.

<?php

    function float($str, $set=FALSE)
    {
        if(preg_match("/([0-9\.,-]+)/", $str, $match))
        {
            // Found number in $str, so set $str that number
            $str = $match[0];

            if(strstr($str, ','))
            {
                // A comma exists, that makes it easy, cos we assume it separates the decimal part.
                $str = str_replace('.', '', $str);    // Erase thousand seps
                $str = str_replace(',', '.', $str);    // Convert , to . for floatval command

                return floatval($str);
            }
            else
            {
                // No comma exists, so we have to decide, how a single dot shall be treated
                if(preg_match("/^[0-9]*[\.]{1}[0-9-]+$/", $str) == TRUE && $set['single_dot_as_decimal'] == TRUE)
                {
                    // Treat single dot as decimal separator
                    return floatval($str);

                }
                else
                {
                    // Else, treat all dots as thousand seps
                    $str = str_replace('.', '', $str);    // Erase thousand seps
                    return floatval($str);
                }
            }
        }

        else
        {
            // No number found, return zero
            return 0;
        }
    }

// Examples

echo float('foo 123,00 bar'); // returns 123.00
echo float('foo 123.00 bar' array('single_dot_as_decimal'=> TRUE)); //returns 123.000
echo float('foo 123.00 bar' array('single_dot_as_decimal'=> FALSE)); //returns 123000
echo float('foo 222.123.00 bar' array('single_dot_as_decimal'=> TRUE)); //returns 222123000
echo float('foo 222.123.00 bar' array('single_dot_as_decimal'=> FALSE)); //returns 222123000

// The decimal part can also consist of '-'
echo float('foo 123,-- bar'); // returns 123.00

?>

Big Up.
Philipp
anonymous at start dot be 15-Jun-2004 07:00
Easier-to-grasp-function for the ',' problem.

<?php
function Getfloat($str) {
  if(strstr($str, ",")) {
    $str = str_replace(".", "", $str); // replace dots (thousand seps) with blancs
    $str = str_replace(",", ".", $str); // replace ',' with '.'
  }

  if(preg_match("#([0-9\.]+)#", $str, $match)) { // search for number that may contain '.'
    return floatval($match[0]);
  } else {
    return floatval($str); // take some last chances with floatval
  }
}

echo Getfloat("$ 19.332,35-"); // will print: 19332.35
?>
vickers at hotpop dot com 26-Jan-2004 03:45
floatval() does not work with "$35,234.43", as it could not handle the '$' and the ','.  The following takes care of all values, such that only numeric and the decimal sign are input into floatval().  (It probably shows I'm an old 'c' guy)...this function only lightly tested.

<?php
function strtflt($str) {
    $il = strlen($str);
    $flt = "";
    $cstr = "";

    for($i=0;$i<$il;$i++) {
        $cstr = substr($str, $i, 1);
        if(is_numeric($cstr) || $cstr == ".")
            $flt = $flt.$cstr;
    }
    return floatval($flt);
}
?>

Richard Vickers
vickers@hotpop.com
Zipi 25-Apr-2003 02:51
This function converts a string to a float no matter is the decimal separator dot (.) or comma (,). It also converts integers correctly. It takes the digits from the beginning of the string and ignores all other characters.

<?php
function floatval($strValue) {
   $floatValue = ereg_replace("(^[0-9]*)(\\.|,)([0-9]*)(.*)", "\\1.\\3", $strValue);
   if (!is_numeric($floatValue)) $floatValue = ereg_replace("(^[0-9]*)(.*)", "\\1", $strValue);
   if (!is_numeric($floatValue)) $floatValue = 0;
   return $floatValue;
  }
?>

-Zipi (Finland)
jason at shadonet dot com 07-Mar-2003 07:07
Instead of using floatval which only appeared in PHP 4.2 you could juse use $variable = (float)$variable

This function doesn't seem to add any functionality that wasn't already there.
empty
get_defined_vars
Функции для работы с переменными


Возвращает массив всех определенных переменных

floatval
get_resource_type
Функции для работы с переменными
PHP Manual

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5)

get_defined_vars — Возвращает массив всех определенных переменных

Описание

array get_defined_vars ( void )

Эта функция возвращает многомерный массив, содержащий список всех определенных переменных, будь то переменные окружения, серверные переменные или переменные, определенные пользователем, в той области видимости, в которой была вызвана get_defined_vars().

Возвращаемые значения

Многомерный массив со всеми переменными.

Примеры

Пример #1 Пример использования get_defined_vars()

<?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// печатает $b
print_r($arr["b"]);

/* печатает путь до интерпретатора PHP (при использовании режима CGI)
 * например, /usr/local/bin/php */
echo $arr["_"];

// печатает параметры командной строки, если они есть
print_r($arr["argv"]);

// печатает все серверные переменные
print_r($arr["_SERVER"]);

// печатает все доступные ключи для массивов переменных
print_r(array_keys(get_defined_vars()));
?>

Список изменений

Версия | Описание
5.0.0 | Переменная $GLOBALS включена в возвращаемый результирующий массив.

Смотрите также

  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • get_defined_functions() - Возвращает массив всех определённых функций
  • get_defined_constants() - Возвращает ассоциативный массив с именами и значениями всех предопределенных констант

User Contributed Notes

Anonymous 18-Apr-2011 05:32
get_defined_vars() returns ALL the vars (in the current scope), what if you just want all YOUR vars, not PHP's super-globals?

<?php
    var_export(array_diff(get_defined_vars(), array(array())));
?>

Example...

<?php
    $TOP_LEVEL_VAR=1;
    var_export(array_diff(get_defined_vars(), array(array())));
?>

The output (with register_globals off) should be...

array (
  'TOP_LEVEL_VAR' => 1,
)

...it perfectly eliminated all the super-globals, without me having to specify them! (note with register_globals on, the output includes those globals, then TOP_LEVEL_VAR).

Here it is, as a function...(it's the best I could do {I can't call get_defined_vars() inside get_user_defined_vars() cuz of the scope issue}).

<?php
    header('Content-type: text/plain');

    $TOP_LEVEL_VAR=1;

    echo 'register_globals(';
    echo ini_get('register_globals');
    echo ') '.phpversion()."\n";

    var_export(get_user_defined_vars(get_defined_vars()));

    function get_user_defined_vars($vars) {
        return array_diff($vars, array(array()));
    }
?>

Note that originally I had an array of the super-globals I wanted removed from get_defined_vars()'s array, then I noticed even an empty double-array, array(array()), made it give me the correct result. Weird.

This was tested on PHP 5.2.9.
meint at meint dot net 11-Jan-2011 12:46
Please be aware that function_get_vars only returns the variables defined at the point before you call the function_get_vars function, it does not scan the entire function for you, only the lines before you call it.
Johan de Vries 17-Jun-2010 08:09
Note that this only returns things you've used. See http://bugs.php.net/bug.php?id=52110 . So don't expect this to have the $this entry, unless you assign $this to return $this.
donovan at example dot com 21-Oct-2008 09:15
As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

<?php

// define a variable
$my_var = "foo";

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars["my_var"] = "bar";

echo $my_var, "\n";

?>

will output "foo" (the original value). It'd be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

<?php

$defined_vars = array();
$var_names = array_keys(get_defined_vars());

foreach ($var_names as $var_name)
{
    $defined_vars[$var_name] =& $$var_name;
}

?>
SyCo 21-Aug-2008 03:52
Here's a very simple function for debugging. It's far from perfect but I find it very handy. It outputs the var value and the var name on a new line. The problem is it'll echo any vars and their name if they share the same value. No big deal when debugging and saves the hassle of writing the HTML and var name when echoing a variable. (ev=echo variable). Using get_defined_vars() inside a function renames the var name to the functions variable so isn't as useful for debugging. Of course, you'll need access to the $GLOBALS array
<?
function ev($variable){
    foreach($GLOBALS as $key => $value){
        if($variable===$value){
            echo '<p>'.$key.' - '.$value.'</p>';
        }
    }
}

$a=0;
ev($a);
$b=0;
ev($b);
$c=0;
ev($c);
?>
Will output
a - 0

a - 0
b - 0

a - 0
b - 0
c - 0
kailashbadu at hotmail dot com 03-Mar-2007 03:09
After a fruitless attempt find a built-in function whic did this, I wrote this functions to find out all the variables (well, those I wanted) in current scope and their values. I believe this is going to be handy in debugging.

<?php
  /**
   * @desc   works out the variables in the current scope(from where function was called).
   *         Returns an array with variable name as key and vaiable value as value
   * @param  $varList: variables returned by get_defined_vars() in desired scope.
   *         $excludeList: variables to be excluded from the list.
   * @return array
   */
  function getDefinedVars($varList, $excludeList)
  {
      $temp1 = array_values(array_diff(array_keys($varList), $excludeList));
      $temp2 = array();
      while (list($key, $value) = each($temp1)) {
          global $$value;
          $temp2[$value] = $$value;
      }
      return $temp2;
  }

  /**
   * @desc   holds the variable that are to be excluded from the list.
   *         Add or drop new elements as per your preference.
   * @var    array
   */
  $excludeList = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', 'excludeList');

  //some dummy variables; add your own or include a file.
  $firstName = 'kailash';
  $lastName = 'Badu';
  $test = array('Pratistha', 'sanu', 'fuchhi');

  //get all variables defined in current scope
  $varList = get_defined_vars();

  //Time to call the function
  print "<pre>";
  print_r(getDefinedVars($varList, $excludeList));
  print "</pre>";
?>
zabmilenko at hotmail dot com 31-Aug-2006 07:32
A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

<?php
Array
(
    [GLOBALS] => Array
        (
            [GLOBALS] => Array
 *RECURSION*
            [_POST] => Array()
            [_GET] => Array()
            [_COOKIE] => Array()
            [_FILES] => Array()
        )

    [_POST] => Array()
    [_GET] => Array()
    [_COOKIE] => Array()
    [_FILES] => Array()

)
?>

Notice that $_SERVER isn't there.  It seems that php only loads the superglobal $_SERVER if it is used somewhere.  You could do this:

<?php
print '<pre>' . htmlspecialchars(print_r(get_defined_vars(), true)) . '</pre>';
print '<pre>' . htmlspecialchars(print_r($_SERVER, true)) . '</pre>';
?>

And then $_SERVER will appear in both lists.  I guess it's not really a gotcha, because nothing bad will happen either way, but it's an interesting curiosity nonetheless.
lbowerh at adelphia dot net 04-Jun-2004 08:19
Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

<?php
function generateDebugReport($method,$defined_vars,$email="undefined"){
    // Function to create a debug report to display or email.
    // Usage: generateDebugReport(method,get_defined_vars(),email[optional]);
    // Where method is "browser" or "email".

    // Create an ignore list for keys returned by 'get_defined_vars'.
    // For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
    // redundant (same as _POST, _GET)
    // Also include vars you want ignored for security reasons - i.e. PHPSESSID.
    $ignorelist=array("HTTP_POST_VARS","HTTP_GET_VARS",
    "HTTP_COOKIE_VARS","HTTP_SERVER_VARS",
    "HTTP_ENV_VARS","HTTP_SESSION_VARS",
    "_ENV","PHPSESSID","SESS_DBUSER",
    "SESS_DBPASS","HTTP_COOKIE");

    $timestamp=date("m/d/y h:m:s");
    $message="Debug report created $timestamp\n";

    // Get the last SQL error for good measure, where $link is the resource identifier
    // for mysql_connect. Comment out or modify for your database or abstraction setup.
    global $link;
    $sql_error=mysql_error($link);
    if($sql_error){
      $message.="\nMysql Messages:\n".mysql_error($link);
    }
    // End MySQL

    // Could use a recursive function here. You get the idea ;-)
    foreach($defined_vars as $key=>$val){
      if(is_array($val) && !in_array($key,$ignorelist) && count($val) > 0){
        $message.="\n$key array (key=value):\n";
        foreach($val as $subkey=>$subval){
          if(!in_array($subkey,$ignorelist) && !is_array($subval)){
            $message.=$subkey." = ".$subval."\n";
          }
          elseif(!in_array($subkey,$ignorelist) && is_array($subval)){
            foreach($subval as $subsubkey=>$subsubval){
              if(!in_array($subsubkey,$ignorelist)){
                $message.=$subsubkey." = ".$subsubval."\n";
              }
            }
          }
        }
      }
      elseif(!is_array($val) && !in_array($key,$ignorelist) && $val){
        $message.="\nVariable ".$key." = ".$val."\n";
      }
    }

    if($method=="browser"){
      echo nl2br($message);
    }
    elseif($method=="email"){
      if($email=="undefined"){
        $email=$_SERVER["SERVER_ADMIN"];
      }

      $mresult=mail($email,"Debug Report for ".$_ENV["HOSTNAME"]."",$message);
      if($mresult==1){
        echo "Debug Report sent successfully.\n";
      }
      else{
        echo "Failed to send Debug Report.\n";
      }
    }
}
?>
jgettys at gnuvox dot com 22-Feb-2002 07:09
Simple routine to convert a get_defined_vars object to XML.

<?php
function obj2xml($v, $indent='') {
  while (list($key, $val) = each($v)) {
    if ($key == '__attr') continue;
    // Check for __attr
    if (is_object($val->__attr)) {
      while (list($key2, $val2) = each($val->__attr)) {
        $attr .= " $key2=\"$val2\"";
      }
    }
    else $attr = '';
    if (is_array($val) || is_object($val)) {
      print("$indent<$key$attr>\n");
      obj2xml($val, $indent.'  ');
      print("$indent</$key>\n");
    }
    else print("$indent<$key$attr>$val</$key>\n");
  }
}

//Example object
$x->name->first = "John";
$x->name->last = "Smith";
$x->arr['Fruit'] = 'Bannana';
$x->arr['Veg'] = 'Carrot';
$y->customer = $x;
$y->customer->__attr->id='176C4';

$z = get_defined_vars();
obj2xml($z['y']);
?>

will output:
<customer id="176C4">
  <name>
    <first>John</first>
    <last>Smith</last>
  </name>
  <arr>
    <Fruit>Bannana</Fruit>
    <Veg>Carrot</Veg>
  </arr>
</customer>
floatval
get_resource_type
Функции для работы с переменными


Возвращает тип ресурса

get_defined_vars
gettype
Функции для работы с переменными
PHP Manual

get_resource_type

(PHP 4 >= 4.0.2, PHP 5)

get_resource_type — Возвращает тип ресурса

Описание

string get_resource_type ( resource $handle )

Функция возвращает тип данного ресурса.

Список параметров

handle

Определяемый дескриптор ресурса.

Возвращаемые значения

Если данный параметр handle является ресурсом, функция возвращает строку, указывающую его тип. Если тип не определяется этой функцией, возвращаемым значением будет строка Unknown.

Функция возвращает FALSE и вызывает ошибку, если handle не является ресурсом (resource).

Примеры

Пример #1 Пример использования get_resource_type()

<?php
// выводит: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// выводит: file
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// выводит: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";
?>

User Contributed Notes

avp200681 at gmail dot com 13-Jun-2011 03:11
This function will generate an error and return NULL instead FALSE in the next example:

<?php

$var = 3;
var_dump(get_resource_type($var));

?>
hessodreamy at gmail dot com 29-May-2007 04:07
Furthermore, this function returns 'stream' on php 4.3 on windows & linux.
You if you want to differentiate between a file resource and other stream resources, as stated before stream_get_meta_data() gives you an array which, on my system, contains the following elements which might suggest a file handle:
[wrapper_type] => plainfile
[stream_type] => STDIO

However I've only compared this to a stream from a url, so I include this only as a suggestion.
jdhawk _at_ gmail 05-Oct-2005 01:18
In PHP5 (on Linux), the above example identifies the "file" handler as a 'stream', not 'file'.

This can be particularly worrisome if you're trying to determine the type of stream using this function.

The alternative is to use <?php stream_get_meta_data() ?>, which returns an array containing "stream_type (string) - a label describing the underlying implementation of the stream."
get_defined_vars
gettype
Функции для работы с переменными


Возвращает тип переменной

get_resource_type
import_request_variables
Функции для работы с переменными
PHP Manual

gettype

(PHP 4, PHP 5)

gettype — Возвращает тип переменной

Описание

string gettype ( mixed $var )

Возвращает тип PHP-переменной var. Для проверки типа переменной используйте функции is_*.

Список параметров

var

Переменная, у которой проверяется тип.

Возвращаемые значения

Возможными значениями возвращаемой строки являются:

  • "boolean"
  • "integer"
  • "double" (по историческим причинам в случае типа float возвращается "double", а не просто "float")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "NULL"
  • "unknown type"

Примеры

Пример #1 Пример использования gettype()

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

?>

Результатом выполнения данного примера будет что-то подобное:

integer
double
NULL
object
string

Смотрите также

  • settype() - Присваивает переменной новый тип
  • get_class() - Возвращает имя класса, к которому принадлежит объект
  • is_array() - Определяет, является ли переменная массивом
  • is_bool() - Проверяет, является ли переменная булевой
  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_null() - Проверяет, является ли значение переменной равным NULL
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_object() - Проверяет, является ли переменная объектом
  • is_resource() - Проверяет, является ли переменная ресурсом
  • is_scalar() - Проверяет, является ли переменная скалярным значением
  • is_string() - Проверяет, является ли переменная строкой
  • function_exists() - Возвращает TRUE, если указанная функция определена
  • method_exists() - Проверяет, существует ли метод в данном классе

User Contributed Notes

Wilson212 01-Jul-2011 07:20
I did some benchmarking and your method here is alot slower then using the actual gettype(); (Using php 5.3.4)
langpavel at phpskelet dot org 01-Jun-2011 08:20
This function returns string representation of type. This is generalization of get_class(). I try to order is_* tests by density of occurence, but is bad idea to use result of this call in conditions for performance reasons, usefull and better than gettype for debugging messages.
Note, that last line should not be never executed.
Also has no sense to make input parameter optional.

<?php
function get_type($var)
{
    if(is_object($var))
        return get_class($var);
    if(is_null($var))
        return 'null';
    if(is_string($var))
        return 'string';
    if(is_array($var))
        return 'array';
    if(is_int($var))
        return 'integer';
    if(is_bool($var))
        return 'boolean';
    if(is_float($var))
        return 'float';
    if(is_resource($var))
        return 'resource';
    //throw new NotImplementedException();
    return 'unknown';
}
?>
Crysis nerd 19-Dec-2010 06:40
I wanted to compare the type of 2 vars.
1st method: Use this Funktion (gettype) and compare with ==
2nd method: Compare every type per is_[type]
Here a little Benchmark:
(I had to break line twice..)

<?php
$var1 = "Hallo";
$var2 = "Käsekuchen";
$var3 = 3.141526;
$Start = microtime(true);
for($i=0;$i<10000;$i++)
{
if(is_bool($var1)&&is_bool($var2)||is_int($var1)&&
is_int($var2)||is_string($var1)&&is_string($var2)||
is_object($var1)&&is_object($var2)||is_array($var1)
&&is_array($var2))
    {
        //same
    }
    if(is_bool($var3)&&is_bool($var2)||is_int($var3)&&
is_int($var2)||is_string($var3)&&is_string($var2)||
is_object($var3)&&is_object($var2)||is_array($var3)
&&is_array($var2))
    {
        //same
    }
}
$time = microtime(true)-$Start;
echo "Zeit fuer if abfrage:  ".$time."<br>";

$Start = microtime(true);
for($i=0;$i<10000;$i++)
{
    if(gettype($var1)==gettype($var2))
    {
        //same
    }
    if(gettype($var3)==gettype($var2))
    {
        //same
    }
}
$time = microtime(true)-$Start;
echo "Zeit fuer funktion  :  ".$time;
?>

Output:
Zeit fuer if abfrage: 0.0257611274719
Zeit fuer funktion : 0.0139331817627

So the function isnt so slow...

Lukas
PPKu-N0-SPAM-schy at mediasoft-berlin dot de 29-Nov-2010 06:57
After some testing I found a bug in my function "myGetType":
The check for "is_callable" was done before "is_string", so that something like <?php echo myGetType("max"); ?> would output: "function reference" instead of "string"

"is_callable" and "is_string" can't be checked together in this method, so I've removed the check for is_callable because it's a very rare usage case and if it's a valid string the check for is_callable never executes because is_string would be reached first (or vice-versa).

So here is the new function without "is_callable"-Check:
<?php
    /**
     * Returns the type of the var passed.
     *
     * @param mixed $var Variable
     * @return string Type of variable
     */
    function myGetType($var)
    {
        if (is_array($var)) return "array";
        if (is_bool($var)) return "boolean";
        if (is_float($var)) return "float";
        if (is_int($var)) return "integer";
        if (is_null($var)) return "NULL";
        if (is_numeric($var)) return "numeric";
        if (is_object($var)) return "object";
        if (is_resource($var)) return "resource";
        if (is_string($var)) return "string";
        return "unknown type";
    }
?>
SoN9ne at gmail dot com 08-Jun-2010 11:32
This is my work around for the gettype warning. Hope some find it useful.

<?php
    /**
     * Returns the type of the passed var
     * - PHP warns against using gettype(), this is my workaround
     *
     * @param mixed $var
     * @return string
     */
    function myGetType($var)
    {
        if (is_array($var)) return "array";
        if (is_bool($var)) return "boolean";
        if (is_callable($var)) return "function reference";
        if (is_float($var)) return "float";
        if (is_int($var)) return "integer";
        if (is_null($var)) return "NULL";
        if (is_numeric($var)) return "numeric";
        if (is_object($var)) return "object";
        if (is_resource($var)) return "resource";
        if (is_string($var)) return "string";
        return "unknown type";
    }
?>

[EDITOR thiago NOTE: Code has been updated by PPKu-N0-SPAM-schy at mediasoft-berlin dot de]
skatebiker at hotmail dot com 22-Feb-2008 05:51
In some rare cases a class instance object returns false when an object but gettype() returns "object".

<?php
$x = new classvar();

$save = serialize($x);

// ......

$obj = unserialize($save);
// here sometimes is_object() returns FALSE
if (is_object($x) || gettype($x) === "object")
{
   // ... do something
}
?>
andrey at php dot net 17-Jul-2007 10:08
The function returns "unicode" for Unicode strings in PHP6.
sneskid at hotmail dot com 05-Mar-2007 01:56
I wrote my own gettype function by just using the default is_? functions, but it took twice as long as gettype... So I decided to use gettype with a twist.

Taking the warnings about gettype to heart, and depending on your custom needs, it's worthwhile to dynamically test the gettype result with a known variable, and link the result to a predefined result. Like so:

<?php
/*
 dynamically create an array by using known variable types
 link with a predefined value
*/
$R=array();
$R[gettype(.0)]='number';
$R[gettype(0)]='number';
$R[gettype(true)]='boolean';
$R[gettype('')]='string';
$R[gettype(null)]='null';
$R[gettype(array())]='array';
$R[gettype(new stdClass())]='object';

// what is
function wis_($v){
    global $R;
    return $R[gettype($v)];
}

echo wis_('hello') . '<br/>'; // "string"
echo wis_(24) . '<br/>'; // "number"
echo wis_(0.24) . '<br/>'; // "number"
echo wis_(null) . '<br/>'; // "null"
echo wis_($R) . '<br/>'; // "array"
?>
You won't need to worry about changes in gettype's return strings in future versions.
If the result evaluates to false then you know the variable tested is some "other" type.

I also find these useful
<?php
function is_num($v){return (is_int($v) || is_double($v));}
function is_box($v){return (is_array($v)||is_object($v));}

echo is_num(null) . '<br/>'; // false
echo is_num(false) . '<br/>'; // false
echo is_num('123') . '<br/>'; // false
echo is_num(123) . '<br/>'; // true
echo is_num(123.0) . '<br/>'; // true
?>
gilthansNOSPAM at gmail dot com 11-Sep-2005 01:18
NaN and #IND will return double or float on gettype, while some inexistent values, like division by zero, will return as a boolean FALSE. 0 by the 0th potency returns 1, even though it is mathematically indetermined.

<?php
$number = 5/0;
$number2 = sqrt(-3);
$number3 = pow(0, 0);
$number4 = 0/0;

echo $number."<br />";
echo $number2."<br />";
echo $number3."<br />";
echo $number4."<br />";
echo "<br />";
echo gettype($number)."<br />";
echo gettype($number2)."<br />";
echo gettype($number3)."<br />";
echo gettype($number4);
?>

This will return:

-1.#IND
1

boolean
double
integer
boolean

0
1
1
0
PHP Warning: Division by zero in C\test.php on line 2 PHP Warning: Division by zero in C:\test.php on line 5
matt at appstate 16-Dec-2004 11:10
Here is something that had me stumped with regards to gettype and is_object.
Gettype will report an incomplete object as such, whereas is_object will return FALSE.

<?php
if (!is_object($incomplete_obj)) {
   echo 'This variable is not an object, it is a/an ' . gettype($incomplete_obj);
}
?>

Will print:
This variable is not an object, it is a/an object
get_resource_type
import_request_variables
Функции для работы с переменными


Импортирует переменные GET/POST/Cookie в глобальную область видимости

gettype
intval
Функции для работы с переменными
PHP Manual

import_request_variables

(PHP 4 >= 4.1.0, PHP 5 < 5.4.0)

import_request_variables — Импортирует переменные GET/POST/Cookie в глобальную область видимости

Описание

bool import_request_variables ( string $types [, string $prefix ] )

Импортирует переменные GET/POST/Cookie в глобальную область видимости. Это бывает полезно, если при отключенной директиве register_globals и желании видеть некоторые переменные в глобальной области видимости.

Если необходимо импортировать в глобальную область видимости другие переменные, такие, как $_SERVER, воспользуйтесь функцией extract().

Список параметров

types

С помощью параметра types, можно указать, какие переменные запроса необходимо импортировать. Можно использовать символы 'G', 'P' и 'C' соответственно для GET, POST и Cookie. Данные символы не являются регистро-зависимыми, поэтому также можно использовать любую комбинацию из 'g', 'p' и 'c'. POST включает в себя информацию о загруженных файлах методом POST.

Замечание:

Имейте в виду, что порядок букв имеет значение, т.е. при использовании "GP" переменные POST перезапишут переменные GET с таким же именем. Любые буквы, отличные от GPC, игнорируются.

prefix

Префикс имени переменной, добавляемый перед всеми именами переменных, импортируемых в глобальную область видимости. То есть, если есть переменная GET с именем "userid", и указан префикс "pref_", то результатом будет глобальная переменная с именем $pref_userid.

Замечание:

Несмотря на то, что prefix - необязательный параметр, будет вызвана ошибка уровня E_NOTICE, если префикс не будет указан или будет указана пустая строка в качестве префикса. Это потенциальная брешь в безопасности. Ошибки уровня Notice не отображаются при использовании уровня отображения ошибок по умолчанию.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования import_request_variables()

<?php
// В примере импортируются переменные GET и POST
// с префиксом "rvar_"
import_request_variables("gp", "rvar_");

echo $rvar_foo;
?>

Смотрите также

  • $_REQUEST
  • register_globals
  • Предопределенные переменные
  • extract() - Импортирует переменные из массива в текущую таблицу символов

User Contributed Notes

rustamabd at gmail dot com 12-May-2012 04:45
import_request_variables() is gone from PHP since version 5.4.0. A simple plug-in replacement it extract().

For example:

import_request_variables('gp', 'v_');

Can be replaced with:

extract($_REQUEST, EXTR_PREFIX_ALL|EXTR_REFS, 'v');
michal dot kocarek at NO_SPAM dot seznam dot cz 23-Sep-2007 02:47
Regarding the last post:

When $_GET[$k] is compared against NULL or '' (empty string) inside the foreach loop, it should be compared only against one of the expressions or strict equality operator should be used.
In this case, second part of expression ($_GET[$k] == NULL) will be *never* executed, because of NULL gets converted to empty string.
Also be aware that zero is equal (==) to empty string, so if passing zeroes through the $_GET, use strict comparsion to check whether variable exist or not.
Next notice: when nothing will be set into $_GET array, all comparsions will generate lot of E_NOTICE errors, because you are accessing unassigned variable.

<?
// Slightly modified previous example
$input = array('name' => null, 'age' => 26) ;
// 26 is the default age, if $_GET['age'] is empty or not set

/**
 * Extracts $_GET variables to global scope by the definition from the $input array
 * @return void
 */
function extract_get() {
    global $input;

    if (isset($input) && is_array($input)) foreach ($input as $k => $v) {
        if (!isset($_GET[$k])) {
            $GLOBALS[$k] = $v;
            continue;
        }
        $getval = $_GET[$k];
        if ($getval === null || $getval === '') {
            $getval = $v;
        } elseif (is_numeric($v)) {
            $getval = (int) $getval;
        } elseif (get_magic_quotes_gpc() == 1) {
            $getval = stripslashes_deep($getval);
        }
        $GLOBALS[$k] = $getval;
        unset($getval);
    }
}

/**
 * Performs stripslashes function recursively on the array or on the single variable
 * @param mixed $var Variable - can be scalar variable or the array
 * @return mixed Variable with slashes stripped with function stripslashes()
 */
function stripslashes_deep($var) {
    if (!is_array($var))
        return stripslashes($var);
    foreach($var as $k => $v) {
        $var[$k] = stripslashes_deep($v);
    }
    return $var;
}
?>
samb06 at gmail dot com 15-May-2006 04:09
What i do is have a small script in my header file that takes an array called $input, and loops through the array to extract variables. that way the security hole can be closed, as you specify what variables you would like extracted

$input = array('name' => null, 'age' => 26) ;

// 26 is the default age, if $_GET['age'] is empty or not set

function extract_get()
    {
        global $input ;

        if ($input)
            {
                foreach ($input as $k => $v)
                    {
                        if ($_GET[$k] == '' or $_GET[$k] == NULL)
                            {
                                $GLOBALS[$k] = $v ;
                            }
                        else
                            {
                                $GLOBALS = $_GET[$k] ;
                            }
                    }
            }
    }
jason 08-Jul-2005 12:35
reply to ceo AT l-i-e DOT com:

I don't think it's a risk, as all of your request variables will be tagged with the prefix. As long as you don't prefix any of your internal variables with the same, you should be fine.

If someone tries to access an uninitiated security-related variable like $admin_level through request data, it will get imported as $RV_admin_level.
nexxer at rogers dot com 10-Feb-2005 10:47
PHP5 seems to have fixed that, in the sense that import_request_variables("g") works like extract($_GET). It doesn't seem to be passing a reference to the global, but instead creating a copy of it as expected
cornflake4 at gmx dot at 10-Jan-2005 02:52
oops, a typo in my comment:

The last line in the second example (the on using the extract() function) should read:

echo $_GET['var']; # prints 1, so $_GET has been unchanged
cornflake4 at gmx dot at 09-Jan-2005 09:39
Beware:

import_request_variables() does not copy the request variables into local scope variables. Instead, it copies the *reference* to the request variable content to local variables Important implication: any change to the local variable means a changes to the respective request variable, too!

This is a clear difference to extract($_GET) which copies the content of the request variables into local variables.

To shed some light on the implication, consider this (assuming the query string "...&var=1"):

echo $_GET['var']; # prints: 1
import_request_variables();
echo $var; # prints 1
$var = 2;
echo $_GET['var']; # prints 2 !!!!

So, $_GET has changed as well!

On the other hand:

echo $_GET['var']; # prints: 1
extract($_GET);
echo $var; # prints 1
$var = 2;
echo $_GET['var']; # prints 2 !!!!

Because of this, I recommend NOT using import_request_variables(), but extract($_GET); extract($_POST); extract($_COOKIE); instead, since this combination bears not these unexspected side effects.

PS: not to mention that you have to reconsider your coding style if any need to import_request_variables arises at all!
ceo AT l-i-e DOT com 10-Dec-2004 12:56
Call me crazy, but it seems to me that if you use this function, even WITH the prefix, then you might as well just turn register_globals back on...

Sooner or later, somebody will find a "hole" with your prefixed variables in an un-initialized variable.

Better to import precisely the variables you need, and initialize anything else properly.
brian at enchanter dot net 07-Dec-2004 05:19
import_request_variables does *not* read from the $_GET, $_POST, or $_COOKIE arrays - it reads the data directly from what was submitted. This is an important distinction if, for example, the server has magic_quotes turned on and you massage the data to run stripslashes on it; if you then use import_request_variables, your variables will still have slashes in them.

In other words: even if you say $_GET=""; $_POST=""; then use import_request_variables, it'll still get all the request data.

If you change the contents of $_GET and you then want to bring this data into global variables, use extract($_GET, EXTR_PREFIX_ALL, "myprefix") instead.
gettype
intval
Функции для работы с переменными


Возвращает целое значение переменной

import_request_variables
is_array
Функции для работы с переменными
PHP Manual

intval

(PHP 4, PHP 5)

intval — Возвращает целое значение переменной

Описание

int intval ( mixed $var [, int $base = 10 ] )

Возвращает целое значение переменной var, используя указанное основание системы исчисления base для преобразования (по умолчанию основание равно 10). intval() нельзя использовать с объектами, попытка это сделать вызовет ошибку уровня E_NOTICE и вернет значение 1.

Список параметров

var

Скалярное значение для конвертации в целое

base

Основание системы исчисления для преобразования

Возвращаемые значения

Целое значение переменной var в случае успеха, или 0 в случае неудачи. Для пустых массивов возвращается 0, для непустых возвращается 1.

Максимальное значение зависит от операционной системы. В 32-х битных системах максимальное знаковое целое лежит в диапазоне от -2147483648 до 2147483647. Так, например, в такой системе, intval('1000000000000') вернет 2147483647. Максимальное знаковое целое значение для 64-х битных систем - 9223372036854775807.

Для строк функция скорее всего вернет 0, хотя это зависит от первого символа в строке. Применяются общие правила преобразований в целые.

Примеры

Пример #1 Примеры использования intval()

Следующие примеры приведены для 32-х битной системы.

<?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
echo intval(array());                 // 0
echo intval(array('foo', 'bar'));     // 1
?>

Примечания

Замечание:

Параметр base применяется только в том случае, если параметр var является строкой.

Список изменений

Версия | Описание
5.1.0 | Генерирует ошибку уровня E_NOTICE и возвращает 1, если в качестве var передан объект.

Смотрите также

  • floatval() - Возвращает значение переменной в виде числа с плавающей точкой
  • strval() - Возвращает строковое значение переменной
  • settype() - Присваивает переменной новый тип
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • Манипуляции с типами
  • Математические Функции Произвольной Точности BCMath

User Contributed Notes

Ken 11-Nov-2011 11:50
Not mentioned elsewhere: intval(NULL) also returns 0.
christianblumer 09-Nov-2011 07:48
inval work well with numbers except the kind:
intval("10.2e+2")
which gives 10
the trick around is to use the following function:

<?php
function smart_val($string) {
  eval("\$number=$string;");
  return $number;
}
?>

Doing <?php echo smart_val("10.2e+2"); ?>
gives: 1020
yves 27-Dec-2010 08:53
The behaviour of intval() is interesting when supplying a base, and you better check your intval base-based expressions, as it is counter-intuitive.
As the example shows
<?php
  intval('42', 8); // => 34
  intval(42, 8);   // => 42 !
?>
PHP considers the 42 as being already an integer, and doesn't apply any conversion. And supplying
<?php
  intval(49, 8);  // => 49 !
?>
produces no error and no warning.
winbill at hotmail dot com 16-Dec-2010 08:31
Be careful :

<?php
$n="19.99";
print intval($n*100); // prints 1998
print intval(strval($n*100)); // prints 1999
?>
tr at comcar dot co dot uk 16-Sep-2010 06:35
Be careful when passing this function a string value with a leading "0". If you give it "09" for example, it will treat it as BASE 8 - 9. I was going crazy as my code was telling me that 09 > 9.
gom3r 17-Aug-2010 06:19
Here is one example how to use this function to

<?php
echo $_GET['userId']; // 1 or 1=1
$id=intval($_GET['userId']);
echo $id; // 1

mysql_query('SELECT * FROM users WHERE id='.$id); // a (very) safe query

?>
jeremy at cfegames dot com 11-Aug-2010 07:41
When retrieving numbers or integers from a MySQL DB, it's best to use intval(), or it will continue to be a string.

<?php
while($row = mysql_fetch_array($check)
{
 $_SESSION['id'] = inval($row['id']);
 $user_id = intval($_SESSION['id']); // Not sure if you need to do it again, but doesn't hurt.
}

is_int($_SESSION['id'])
is_int($user_id)
is_string($_SESSION['id'])
is_string($user_id)

// Output
true
true
false
false
?>
spoon_reloaded at gmail dot com 21-Jun-2009 10:35
Here is a really useful undocumented feature:

You can have it automatically deduce the base of the number from the prefix of the string using the same syntax as integer literals in PHP ("0x" for hexadecimal, "0" for octal, non-"0" for decimal) by passing a base of 0 to intval():

<?php
echo intval("0x1a", 0), "\n"; // hex; prints "26"
echo intval("057", 0), "\n"; // octal; prints "47"
echo intval("42", 0), "\n"; // decimal; prints "42"
?>
bert at nospam dot thinc dot nl 06-Jun-2009 04:16
If you need the reverse function of intval(), the code hereunder might be helpfull.

<?php
function itoa( $ii, $radix=10, $stritoa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabc" ) {
    if ( $radix > strlen( $stritoa ) )    //    does request makes sense?
        return "";    //    think of your own way to handle this case
    $sign = $ii<0 ? "-": "";
    $ii = abs( $ii );
    $rc = "";
    do {
        $rc .= $stritoa[ $ii % $radix ];
        $ii = floor( $ii / $radix );
        } while ( $ii >0 );
    return $sign . strrev( $rc );
    }
?>
ittasks at gmail dot com 24-Mar-2009 01:47
when converting some optional form values to positive integers and to be on the safe side, you can use this:

<?php $q=intval("0".$_REQUEST['q']); ?>
jeromakay at yahoo dot com 02-Mar-2009 02:40
To convert a string to a number, and avoid the 32 bit issues of intval you can use:

<?php

$no = "214742780440" + 0;

var_dump($no); // float(214742780440)

?>

I used to intval() everything before entering it into the DB, but it seems impractical with values over 2147483647.

To get even better idea of how it validates, try this:

<?php

$no = "qwerty1234" + 0;

var_dump($no); // int(0)

?>
Ben L 24-Oct-2008 05:37
I was browsing around the site, and I seen some people commented on my comment down the way a while back...

re: Disturbing issue with intval()

I was of the opinion then as I'm of the opinion now that if you are going to have a function like intVal in a language in conjunction with a standard type casting syntax such as (int)$var, then it should not be vulnerable to floating point issues.

It's obvious that it would be very easy to do so, as when you do: echo 19.99 * 100; or intVal((string)(19.99 * 100));

it gives you 1999.

However if you do intVal(19.99 * 100), then echo it out, it outputs 1998...

This shows that type casting the float val of 19.99 * 100 to a string gives you a happy 19.99, instead of outputting 19.989999...etc

I would expect this behavior of (int)(19.99 * 100)...

But not of the function intVal, which was my point of the comment in the first place.  Once I noticed that behavior a long time ago I started using round, on such values and only use intVal/typecasting to int from string variables such as $_REQUEST variables that I expect to be in integer format.

I still wish intVal handled all that for you though.
Seally 28-Aug-2008 02:47
Re: nobodyisperfect88 at hotmail dot de
jay at w3prodigy dot com had it right. I believe it is an issue with the floating point registers on computers, which have a precision of about 17 digits. When you get more precise than that, it rounds.

Since the second example can fit in the register, no rounding occurs, and PHP can truncate the portion after the decimal. However, the system automatically rounds the first example to 1, which is what PHP returns.

(Tested on Windows XP 32bit)
yhoko at yhoko dot com 16-Aug-2008 07:29
Note that this function behaves different in PHP4/5 when parsing NAN-values. Try the following example:

<?php die( "Result = " . intval( NAN ) ); ?>

- In PHP 4 the result is 0
- In PHP 5 the result is 2^31 (running on 32bit)

Yhoko
phpben hood id au 10-Jun-2008 05:17
kris at mha dot ca:

Implicit typing. This is a feature, not a bug.

The == operator will convert your string to an int automatically (in this case) so that it is really comparing 123 and 123, which is of course the same.

If you use the === operator then this will not occur, as it will only match on the same value and type. This works as expected:

<?php

$tmp_array = "123,232,141";

if (intval($tmp_array) === $tmp_array)
{
    echo "'".intval($tmp_array)."' equals '$tmp_array'\n";
}
else
{
    echo "'".intval($tmp_array)."' does not equal '$tmp_array'\n";
}

?>
nobodyisperfect88 at hotmail dot de 14-May-2008 11:46
jay at w3prodigy dot com
25-Mar-2008 09:05
Note:

$int = 0.99999999999999999;
echo intval($int); // returns 1

and

$int = 0.9999999999999999;
echo intval($int); // returns 0
----------------------------------------------------------

^^the first is wrong ... i think it should be called

$int = 1.99999999999999999;
echo intval($int); // returns 1
and not

$int = 0.99999999999999999;
echo intval($int); // returns 1
jay at w3prodigy dot com 25-Mar-2008 12:05
Note:

$int = 0.99999999999999999;
echo intval($int); // returns 1

and

$int = 0.9999999999999999;
echo intval($int); // returns 0
michiel ed thalent nl 11-Dec-2007 05:44
A function to get an integer from everywhere in a string (concatenated or not).

<?php
function str2int($string, $concat = true) {
    $length = strlen($string);
    for ($i = 0, $int = '', $concat_flag = true; $i < $length; $i++) {
        if (is_numeric($string[$i]) && $concat_flag) {
            $int .= $string[$i];
        } elseif(!$concat && $concat_flag && strlen($int) > 0) {
            $concat_flag = false;
        }
    }

    return (int) $int;
}
echo var_dump(str2int('sh12apen11')); // int(12)
echo var_dump(str2int('sh12apen11', false)); // int(1211)
echo var_dump(str2int('shap99en')); // int(99)
echo var_dump(intval('shap99en')); // int(0)
?>
lrdsatyr8 at hotmail dot com 31-Oct-2007 05:09
If you just want to get the integer value of a number without all the hassle, just use intval()... like so:

$a1 = 10.4;
$a2 = -12.5;
$a3 = 44.1238503;

print intval($a1);   // returns 10
print intval($a2);   // returns -12
print intval($a3);   // returns 44

it's that easy!
shermy at shermys dot com 17-Oct-2007 05:35
<?php

$tmp_array = "123,232,141";

if (strval(intval($tmp_array)) == $tmp_array)
{
    echo "'".intval($tmp_array)."' equals '$tmp_array'\n";
}
else
{
    echo "'".intval($tmp_array)."' does not equal '$tmp_array'\n";

}

?>

Output:

'123' does not equal '123,232,141'
jazeik at gmail dot com 31-Jul-2007 06:15
@kris:
If you had followed the following links:
"The common rules of integer casting apply." => http://us.php.net/manual/en/language.types.integer.php
"See String conversion to numbers" => http://us.php.net/manual/en/language.types.integer.php

Then you would have found the following: "The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used."

So this behaviour is a feature not a bug.

The following code will work:
<?php

$tmp_array = str_replace(",", "", "123,232,141");

if(intval($tmp_array) == $tmp_array){
    echo intval($tmp_array) . " equals $tmp_array\n";
}else{
    echo intval($tmp_array) . " does not equal $tmp_array\n";
}

?>

Output:
123232141 equals 123232141
kris at mha dot ca 17-Jul-2007 03:41
More intval wierdness (tested with PHP 5.2.3 and 4.3.10).

<?php

$tmp_array = "123,232,141";

if (intval($tmp_array) == $tmp_array)
{
    echo "'".intval($tmp_array)."' equals '$tmp_array'\n";
}
else
{
    echo "'".intval($tmp_array)."' does not equal '$tmp_array'\n";

}

?>

Output:

'123' equals '123,232,141'

Odd.  Not what was expected.  Maybe if I put it into a temporary variable it will normalize itself.

<?php

$tmp_array = "123,232,141";
$tmp = intval($tmp_array);

if ($tmp == $tmp_array)
{
    echo "'$tmp' equals '$tmp_array'\n";
}
else
{
    echo "'$tmp' does not equal '$tmp_array'\n";

}

?>

Output:

'123' equals '123,232,141'

I don't know if this is a feature, or a bug in PHP (I would certainly classify this as a bug, but since it is in both PHP 4 and PHP 5 maybe not).  If it is a feature, could someone explain it to me?
vizigr0u at gmail dot com 23-Jun-2007 04:50
intval used on bools returns either 1 or 0
I usually use this to properly set bools in my tables
(assuming you use some kind of int like tinyints as booleans) :
<?php
$myvar = 'right value';
mysql_query('INSERT INTO mytable (activated)
VALUES(' . intval($myvar === 'right value') . ')');
?>
aryel at redtwilightNO dot comSPAM dot brNOT 26-Apr-2007 10:42
Since integers are stored on multiple bytes in the memory in binary format, once an signed long integer reaches the maximum value of 2147483646 (which is the maximum value that 8 bits of memory, size of a long int, can store, binary-wise), atleast on C/C++ the number starts to roll back, going gradually to ...45, ...45 and eventually reaching a negative value. Some REALLY large values will return -1, probably because PHP simply rejects the number, though I'm not sure why.

For further info:
http://www.rwc.uc.edu/koehler/comath/13.html
maciek dot iwanowskis at glasspartnership dot co dot uk 04-Apr-2007 10:36
It seems that if you're trying to cast to integer (or use intval()) on integer of value bigger then 2147483646 it's hard to predict returned value.
27-Apr-2006 10:36
Operating on integers gives puzzling results--which don't seem to have to do with the number of bits...

<?php
echo intval(1e10);  // -1 on my system; 1410065408 in the example
echo intval(1e5); // 100000 (my own example: lower number--works all right)
echo intval(4e9);  // -294967296 ! (my own example: somewhere in the middle)

echo intval(42000000);  // 42000000 (as in the manual; reasonable)
echo intval(420000000000000000000);  // -1 on my system at least. 0 in the example
// ...and yet still odder...
echo intval(4200000000);  // -94967296! (my own example: somewhere in between)
?>
mkamerma at science dot uva dot nl 06-Mar-2006 11:48
As addendum, the "if ($int > 0)" check in the encode function is redundant. It doesn't do anything bad to keep it in since it will always be true when reaching that point, but it's a meaningless conditional this way. It's a remnant from when I tried to write the function in terms of bitshifts, which could lead to negative ints when shifting if the 32nd bit was set (instead of always padding with 0's when using >> it pads with 1's leading to negative ints).
mkamerma at science dot uva dot nl 05-Mar-2006 02:04
When you need to work with integer values that exceed maxint, the following functions may be of use to you - they form a codec pair for integers of variable length rather than fixed length, encoded in a byte as a 7 bit numberal with a 1 bit has-more flag, indicating that the next byte encodes a higher order part of the same number still.

<?php
/* encode integer as 7bit with has-more bit numeral,
    ordered lowest byte first. */
function encode_7bhm($int) {
  if ($int==0) return chr(0); // shortcut
  $ret = "";
  while($int != 0) {
    $high = floor($int / 128);     // overflow for this round
    $low = $int - ($high * 128); // 7 bit numeral
    if ($int > 0) {
      if ($high > 0) { $low = $low + 128; } // has-more flag
      $ret .= chr($low); } //encode
    $int = $high;  // set overflow as next round's number
  }
  return $ret;
}

/* decode a 7bit with has-more bit numeral,
    ordered lowest byte first. */
function decode_7bhm($hmb) {
  $ret = 0;
  $pos = 0;
  $high = 1;
  while($high == 1) {
    $byte = ord(substr($hmb, $pos, 1));
    $high = floor($byte/128); // gets has-more flag
    $low = $byte - ($high*128);
    $ret += $low * pow(128, $pos++); // decode
  }
  return $ret;
}
?>

This codec pair is also quite useful when needing to write ints to files, as this is a low-numeral biased encoding: most of the time this will only require 8 or 16 bit rather than the 32 bits an int will use in fixed-length encoding.

The encoding range:

  1 byte  - 0 through 128 (2^7)
  2 bytes - 129 through 16,384 (2^14)
  3 bytes - 16,385 through 2,097,152 (2^21)
  4 bytes - 2,097,153 through 268,435,456 (2^28)

while indeed a 32 bit encoded variable length integer will be lower than maxint, rather than needing a new 32 bit block to represent higher range only 8 more bits are required to represent this higher number (for completeness the range of representation by bytes 5-8 are listed):

  5 bytes - 268,435,457 through 34,359,738,368 (2^35)
  6 bytes - 343,59,738,369 through 4,398,046,511,104 (2^42)
  7 bytes - 4,398,046,511,105 through 562,949,953,421,312 (2^49)
  8 bytes - 562,949,953,421,313 through 720,57,594,037,927,936 (2^56)

Also for completeness, the function to read a 7 bit with has-more bit from a filepointer:

<?php
// read a 7bhm numeral from file
function read_7bhm($fp) {
  $bytestring = "";
  $high = 1;
  while($high==1) {
    $byte = fread($fp, 1);
    $high = floor(ord($byte)/128); // check for has-more bit
    $bytestring .= $byte;
  }
  return decode_7bhm($bytestring); }
?>
simon at npkk dot cz 30-Jan-2006 08:03
Still have on mind, that if you convert big numbers by adding zero, PHP makes automatic "to a float" conversion, so it is same as floatVal(). So if the number is realy big (over 13 digits), you can lose preciosity. Do not use it for such long numbers, if all bits do matter (IPv6 addresses and similar).
simon at npkk dot cz 30-Jan-2006 06:48
intval() returns maxint on number_in_string, if the result would be bigger than it. But for float returns the signed 32 bit integer with the "same" value:
<?php
$num=-1000;
print($num."\n");
$i_str=sprintf("%u",$num);
print($i_str."\n");
$i1=intval($i_str);
print($i1."\n");
$i2=intval(floatval($i_str));
print($i2."\n");
?>

prints:

-1000
4294966296
2147483647
-1000
anonymous at place dot com 17-Jan-2006 09:37
re: Disturbing issue with intval()

It's probably just good practice to round decimals anyways.  i.e...

$amount = round(19.99 * 100);
$test2 = intVal($amount);
$test3 = intVal("$amount");

echo $test2 . "<br />\n";
echo $test3 . "<br />\n";
Ben Laurienti 16-Jan-2006 01:21
You guys are going to love this.  I found something that I found quite disturbing.

$test1 = intVal(1999);

$amount = 19.99 * 100;
$test2 = intVal($amount);
$test3 = intVal("$amount");

echo $test1 . "<br />\n";
echo $test2 . "<br />\n";
echo $test3 . "<br />\n";

expected output:
1999
1999
1999

actual output
1999
1998
1999

Appears to be a floating point issue, but the number 1999 is the only number that I was able to get to do this.  19.99 is the price of many things, and for our purpose we must pass it as 1999 instead of 19.99.
adspeed.com 29-Jul-2005 08:32
Say you have a string $s="3763328634" to be used as a key into the database, intval() this string will result in a different,smaller number (depends on the machine/OS). To keep the number intact but as an int/long type, do $s +=0; instead.
23-May-2004 08:38
When trying to read 32bit values (32 bit limitation depends on the word size of your machine)  from a string that is represented in hex with the high bit set,
eg. F9833234

intval returns -1. The reason is the sign bit being set. This number is larger than can be saved in a signed int.

The way around this is to read the value in using two calls to intval.

eg.

$val = intval(substr($str,0,4), 16); // read high 16 bit word
$val <<= 16; // shift hi word correct position
$val |= intval(substr($str, 4, 4), 16); //  read low 16 bit word
tuxedobob at mac dot com 07-Feb-2004 04:56
Sometimes intval just won't cut it. For example if you want to use an unsigned 32-bit int and need all 32 bits. Recently, I wrote a little script that took and integer and converted it to an IP address. After realizing I couldn't just mod the whole thing, since the sign bit throws it off (and compensating for that), we ran into a problem where if it was entered into a form, the value somehow wasn't converted to an integer properly, at least not implicitly. The solution for this, and the way I recommend converting a string to an integer, is:

$num = $num + 0;

and PHP will leave your number alone; it'll just know it's a number. Such is the fun of a loosely-typed language. :)
Robin Y. Millette http://rym.waglo.com 15-May-2003 01:29
Rob_Kohr at no_need_to_email dot me dot com
11-Nov-2002 12:24

[snip]

$var=intval("122.5");
//$var==122

This is nice if you want to turn a double into an int automatically rounding down

Hum, I had a bug earlier today, involving ===. Coming from a c++ background, I can't help testing for types. I was using floor() to get an integer from a division by 2, and comparing that to a known integer from a for loop. Well, first I changed the === to == because the test would always be false otherwise. Next, I looked up this function, and converted most of my floor() calls to intval() calls, because I really meant to get an int, and not a float with no decimal part. So I have to disagree with the editor note here. Oh, and I'm comfortably back to using ===.
cleong at letstalk dot com 01-Oct-2001 05:21
intval() handles overflow differently depending on the type of the argument.

intval('10000000000') = 2147483647
intval(1e10) = 1410065408

intval(float) yields essentially non-defined result when the argument is beyond the range of int.
zak at php dot net 12-Aug-2000 01:38
intval converts doubles to integers by truncating the fractional component of the number.

When dealing with some values, this can give odd results.  Consider the following:

print intval ((0.1 + 0.7) * 10);

This will most likely print out 7, instead of the expected value of 8.

For more information, see the section on floating point numbers in the PHP manual (http://www.php.net/manual/language.types.double.php)

Also note that if you try to convert a string to an integer, the result is often 0.

However, if the leftmost character of a string looks like a valid numeric value, then PHP will keep reading the string until a character that is not valid in a number is encountered.

For example:

"101 Dalmations" will convert to 101

"$1,000,000" will convert to 0 (the 1st character is not a valid start for a number

"80,000 leagues ..." will convert to 80

"1.4e98 microLenats were generated when..." will convert to 1.4e98

Also note that only decimal base numbers are recognized in strings.

"099" will convert to 99, while "0x99" will convert to 0.

One additional note on the behavior of intval.  If you specify the base argument, the var argument should be a string - otherwise the base will not be applied.

For Example:

print intval (77, 8);   // Prints 77
print intval ('77', 8); // Prints 63
import_request_variables
is_array
Функции для работы с переменными


Определяет, является ли переменная массивом

intval
is_bool
Функции для работы с переменными
PHP Manual

is_array

(PHP 4, PHP 5)

is_array — Определяет, является ли переменная массивом

Описание

bool is_array ( mixed $var )

Определяет, является ли данная переменная массивом.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если переменная var является массивом array, или FALSE в противном случае.

Примеры

Пример #1 Проверяет, является ли переменная массивом

<?php
$yes = array('это', 'массив');

echo is_array($yes) ? 'Массив' : 'Не массив';
echo "\n";

$no = 'это строка';

echo is_array($no) ? 'Массив' : 'Не массив';
?>

Результат выполнения данного примера:

Массив
Не массив

Смотрите также

  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_string() - Проверяет, является ли переменная строкой
  • is_object() - Проверяет, является ли переменная объектом

User Contributed Notes

magentix at gmail dot com 26-Feb-2011 09:12
If you wanted to have 'pure' associative arrays,
you could filter out non-string keys and then compare the count of the original array with the count of the filtered array.

<?php
    // Only validates empty or completely associative arrays
    function is_assoc ($arr) {
        return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
    }

    $a = '';
    $b = 'z';
    $c = array();
    $d = array('x','y','z');
    $e = array('x','y','zed'=>'z');
    $f = array('ex'=>'x','why'=>'y','zed'=>'z');

    echo '$a: ' . ( (is_assoc($a)) ? 'true' : 'false' ) ."\n"; // False
    echo '$b: ' . ( (is_assoc($b)) ? 'true' : 'false' ) ."\n"; // False
    echo '$c: ' . ( (is_assoc($c)) ? 'true' : 'false' ) ."\n"; // True
    echo '$d: ' . ( (is_assoc($d)) ? 'true' : 'false' ) ."\n"; // False
    echo '$e: ' . ( (is_assoc($e)) ? 'true' : 'false' ) ."\n"; // False
    echo '$f: ' . ( (is_assoc($f)) ? 'true' : 'false' ) ."\n"; // True
?>

I've tested the point of checking whether the array is empty first.
The overall result was a 200% speed increase when the array was indeed empty,
but an average 10% slow when it had elements inside.

<?php
    /***********************************************************
     *    Benchmarks: checking for empty array vs. not checking  *
     ***********************************************************/

    // With empty check
    function is_assoc ($arr) {
        return (is_array($arr) && (!count($arr) || count(array_filter(array_keys($arr),'is_string')) == count($arr)));
    }

    function test_speed($arr) {
        $t = microtime(true);
        for($i = 0; $i < 100000; ++$i) is_assoc($arr);
        return (microtime(true) - $t);
    }

    echo '$a: ' . test_speed($a) ."\n"; // 0.20597505569458
    echo '$b: ' . test_speed($b) ."\n"; // 0.19199514389038
    echo '$c: ' . test_speed($c) ."\n"; // 0.28803396224976
    echo '$d: ' . test_speed($d) ."\n"; // 0.94685983657837
    echo '$e: ' . test_speed($e) ."\n"; // 0.96698403358459
    echo '$f: ' . test_speed($f) ."\n"; // 0.98052096366882

    // Without empty check
    function is_assoc_2 ($arr) {
        return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
    }

    function test_speed_2($arr) {
        $t = microtime(true);
        for($i = 0; $i < 100000; ++$i) is_assoc_2($arr);
        return (microtime(true) - $t);
    }

    echo '$a: ' . test_speed_2($a) ."\n"; // 0.18811202049255 = FASTER:  91.3% of is_assoc
    echo '$b: ' . test_speed_2($b) ."\n"; // 0.18782901763916 = FASTER:  97.8% of is_assoc
    echo '$c: ' . test_speed_2($c) ."\n"; // 0.64437484741211 = SLOWER: 223.7% of is_assoc
    echo '$d: ' . test_speed_2($d) ."\n"; // 0.84632205963135 = FASTER:  89.4% of is_assoc
    echo '$e: ' . test_speed_2($e) ."\n"; // 0.86739897727966 = FASTER:  89.7% of is_assoc
    echo '$f: ' . test_speed_2($f) ."\n"; // 0.87963700294495 = FASTER:  89.7% of is_assoc
?>
JTS 08-Jun-2010 04:22
I would change the order of the comparison, because if it is really an empty array, it is better to stop at that point before doing several 'cpu & memory intensive' function calls.

In the end on a ratio of 3 not empty arrays to 1 empty array computed for 1000000 iterations it needed 10% less time.
Or the other way round:
It needed approx 3% to 4% more time if the array is not empty, but was at least 4 times faster on empty arrays.

Additionally the memory consumption veritably lesser.

<?php
function is_assoc($array) {
    return (is_array($array) && (count($array)==0 || 0 !== count(array_diff_key($array, array_keys(array_keys($array))) )));
}
?>
hperrin at gmail dot com 28-May-2010 10:02
I've found a faster way of determining an array. If you use is_array() millions of times, you will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using is_array().

Cast the value to an array, then check (using ===) if it is identical to the original.

<?php
if ( (array) $unknown !== $unknown ) {
    echo '$unknown is not an array';
} else {
    echo '$unknown is an array';
}
?>

You can use this script to test the speed of both methods.

<pre>
What's faster for determining arrays?

<?php

$count = 1000000;

$test = array('im', 'an', 'array');
$test2 = 'im not an array';
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'is_array  :  '.($end_time - $start_time)."\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'cast, === :  '.($end_time - $start_time)."\n";

echo "\nTested $count iterations."

?>
</pre>

Prints something like:

What's faster for determining arrays?

is_array  :  7.9920151233673
cast, === :  1.8978719711304

Tested 1000000 iterations.
Anonymous 16-May-2009 02:18
Using empty() in the previous example posted by Anonymous will result in a "Fatal error: Can't use function return value in write context".  I suggest using count() instead:

<?php
function is_assoc($array) {
    return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
?>
Anonymous 06-May-2009 04:34
strictly speaking: array_diff_key does not return boolean, so using it in a comparison might eventually be considered 'bad'.
perhaps add a bit more cruft...?

<?php
function is_assoc($var)
{
        return is_array($var) AND ! empty ( array_diff_key($var,array_keys(array_keys($var))));
}
?>
skaimauve at yahoo dot ca 03-Mar-2009 12:12
Or you could make use of the array_diff_key and array_key function:

<?php

function is_assoc($var)
{
        return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

function test($var)
{
        echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}

// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);

// an array
$b = array_values($a);
test($b);

// an object
$c = (object)$a;
test($c);

// other types
test($a->a);
test($a->b);
test($a->c);

?>

The above code outputs:
I'm an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
Matthias Loitsch 03-Dec-2008 11:36
Or you could make use of the array_diff_key and range functions:

<?php

function isVector($var) { return count(array_diff_key($var, range(0, count($var) - 1))) == 0; }

function isAssociative($var) { return !isVector($var); }

?>
jim at akubo dot net 28-Oct-2008 11:02
yousef's example was wrong because is_vector returned true instead of false if the key was found
here is the fixed version (only 2 lines differ)
<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return false;
      $next++;
   }
   return true;
}
?>
yousuf at philipz dot com 16-Oct-2008 03:41
alex frase's example is fast but elanthis at awesomeplay dot com's example is faster and Ilgar's modification of alex's code is faulty (the part " || $_array[$k] !== $v"). Also, Ilgar's suggestion of giving a false return value when the variable isnt an array is not suitable in my opinion and i think checking if the array is empty would also be a suitable check before the rest of the code runs.

So here's the modified (is_vector) version

<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return true;
      $next++;
   }
   return false;
}
?>

and the modified (alex's is_assoc) version

<?php
function is_assoc($_array) {
    if ( !is_array($_array) || empty($array) ) {
        return -1;
    }
    foreach (array_keys($_array) as $k => $v) {
        if ($k !== $v) {
            return true;
        }
    }
    return false;
}
?>
alex frase 16-Jul-2008 08:05
Yet another simpler, faster is_assoc():

<?php
function is_assoc($array) {
  foreach (array_keys($array) as $k => $v) {
    if ($k !== $v)
      return true;
  }
  return false;
}
?>

In my tests it runs about twice as fast as Michael/Gabriel's array_reduce() method.

(Speaking of which: Gabriel's version doesn't work as written; it reports associative arrays as numeric if only the first key is non-numeric, or if the keys are numeric but ordered backwards.  Michael solves this problem by comparing array_reduce() to count(), but that costs another function call; it also works to just compare to -1 instead of 0, and therefore return -1 as the ternary else from the callback).
Michael 11-Sep-2007 12:37
A slight modification of what's below:

<?php

function is_assoc($array)
{
    return is_array($array) && count($array) !== array_reduce(array_keys($array), 'is_assoc_callback', 0);
}

function is_assoc_callback($a, $b)
{
    return $a === $b ? $a + 1 : 0;
}

?>
gabriel at bumpt dot nothing-here dot net 29-Aug-2007 08:34
Yet another safer, faster way of detecting whether an array is associative.

The principle is: using array reduction on the keys, we verify that each key is numeric and is equal to its rank.

Beware: integer keys that are not in sequence, or are negative, or with "holes", still make an associative array.

<?php
/**
  * @param array $arr
  * @returns boolean
  */
function isNotAssocArray($arr)
{
    return (0 !== array_reduce(
        array_keys($arr),
        create_function('$a, $b', 'return ($b === $a ? $a + 1 : 0);'),
        0
        )
    );
}
?>

Of course, it is still faster if the callback for array_reduce is not an anonymous function:

<?php
function callbackReduceNotArray($a, $b)
{
    return ($b === $a ? $a + 1 : 0);
}
function isVector($arr)
{
    return (0 !== array_reduce(
        array_keys($arr),
        'callbackReduceNotArray',
        0
        )
    );
}
?>
Alfred J Fazio <alfred dot fazio at gmail dot com> 04-Apr-2007 04:32
Yet another associative array test:

<?php
function binary_nand ($a, $b) { return !$a && !$b; }
function binary_nor ($a, $b)  { return !$a || !$b; }

// Returns true if array has elements with non-numeric keys
function is_associative_array ($arr) {
  return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nor", true);
}

// Returns true if all elements of array have a non-numeric key
function is_strict_associative_array ($arr) {
  return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nand", false);
}
?>
angelo [at] mandato <dot> com 26-Feb-2007 01:32
The is_associative_array() and is_sequential_array() functions posted by 'rjg4013 at rit dot edu' are not accurate.

The functions fail to recognize indexes that are not in sequence or in order.  For example, array(0=>'a', 2=>'b', 1=>'c') and array(0=>'a', 3=>'b', 5=>'c') would be considered as sequential arrays. A true sequential array would be in consecutive order with no gaps in the indices.

The following solution utilizes the array_merge properties. If only one array is given and the array is numerically indexed, the keys get re-indexed in a continuous way.  The result must match the array passed to it in order to truly be a numerically indexed (sequential) array.  Otherwise it can be assumed to be an associative array (something unobtainable in languages such as C).

The following functions will work for PHP >= 4.

<?php
    function is_sequential_array($var)
    {
        return (array_merge($var) === $var && is_numeric( implode( array_keys( $var ) ) ) );
    }

    function is_assoc_array($var)
    {
        return (array_merge($var) !== $var || !is_numeric( implode( array_keys( $var ) ) ) );
    }
?>

If you are not concerned about the actual order of the indices, you can change the comparison to == and != respectively.
jupiter at nospam dot com 29-May-2006 11:42
Will check a Multi-Dimentional Array to any specified level.  This is a fix to 11/16/05 submission, which would break since you must supply a foreach with an array. Beware recursive functions shouldn't go over 100 deep or could break the memory stack on server.

<?php
// checks for multiarray to defined depth level recursively
// original $level must be 2 or more, else will instantly return true
function isDeepMultiArray($multiarray, $level = 2) {  // default is simple multiarray
    if (is_array($multiarray)) {  // confirms array
        if ($level == 1) {  // $level reaches 1 after specified # of recursions
            return true;  // returns true to recursive function conditional
        }  // end conditional
        foreach ($multiarray as $array) {  // goes one level deeper into array
            if (isDeepMultiArray($array, $level - 1)) {  // check subarray
                $message = "I'm a multiarray";  // optional message
                return $message;  // best if $message = true so function returns boolean
            }  // end recursive function
        }  // end loop
    } else {  // not an array at specified level
    return false;  // is also used recursively so can't change to message
    }
}

if (isDeepMultiArray(array(array()), 2)); // beware this returns true eventhough arrays are empty

?>
BTW my notation is consistent with the PEAR manual on coding standards, which is what php.net says to follow. I hope a function like this gets included in PHP6.
jupiter at nospam dot com 29-May-2006 09:15
Simple check for a Multi-Dimentional Array of any depth
<?php
// checks for multiarray (2 or more levels deep)
function isMultiArray($multiarray) {
  if (is_array($multiarray)) {  // confirms array
    foreach ($multiarray as $array) {  // goes one level deeper
      if (is_array($array)) {  // is subarray an array
        return true;  // return will stop function
      }  // end 2nd check
    }  // end loop
  }  // end 1st check
  return false;  // not a multiarray if this far
}
?>
March 30-Mar-2006 06:28
And here is another variation for a function to test if an array is associative. Based on the idea by mot4h.

<?php
function is_associative($array)
{
  if (!is_array($array) || empty($array))
    return false;

  $keys = array_keys($array);
  return array_keys($keys) !== $keys;
}
?>
dan at cain dot sh 10-Dec-2004 05:05
is_array() under PHP 5.0.2 will return FALSE when passed an object descended from the internal class interface ArrayAccess(http://www.php.net/spl) even though said object behaves as an array would in most instances.

I've found the following user function helpful with my own classes and functions that expect array(s) as arguments, but work fine with objects that behave as an array would.

<?php
function is_array_abled(&$x)
{
    return (bool)($x instanceof ArrayAccess or is_array($x));
}
?>
vhermecz at ixpert dot hu 01-Apr-2004 04:58
Mike's function is quite cool, it is just the one, I was searching for. Using range is a great idea! But it's a bit long for me. Here is a shorter version:

<?php
function is_assoc_array($var) {
    if (!is_array($var)) {
        return false;
    }
    return array_keys($var)!==range(0,sizeof($var)-1);
}
?>

Or, if you don't want to type that much:

<?php
function is_assoc($var) {
    return is_array($var) && array_keys($var)!==range(0,sizeof($var)-1);
}
?>
mike-php at spam dot emerge2 dot spam dot com 22-Aug-2003 03:20
All arrays in PHP are associative arrays, but it is quite easy to treat an associative array just like it is a sequential array. However, when dealing with XML-RPC, it is necessary to know whether an array is associative or sequential, so I created this function.

It isn't perfect, since an associative array that just happens to have sequential, integer keys starting with 0 will 'look' exactly like a sequential array, and will fool this function.

<?php
/****************************************************************
* is_assoc_array tries to decide whether or not a given array   *
* is an associative array, or a sequential array. Of course, no *
* such distinction is made by PHP, so it really just tests      *
* whether or not a given array could possibly be a sequential   *
* array. Since an associative array with sequential, integer    *
* keys 'looks' just like a sequential array, this function will *
* be fooled.                                                    *
*                                                               *
* BUG: Associative arrays with sequential, integer keys 'look'  *
* just like sequential arrays, and will be identified as such.  *
*                                                               *
****************************************************************/
function is_assoc_array( $php_val ) {
   if( !is_array( $php_val ) ){
      # Neither an associative, nor non-associative array.
      return false;
   }

   $given_keys = array_keys( $php_val );
   $non_assoc_keys = range( 0, count( $php_val ) );

   if( function_exists( 'array_diff_assoc' ) ) { # PHP > 4.3.0
      if( array_diff_assoc( $given_keys, $non_assoc_keys ) ){
         return true;
      }
      else {
         return false;
      }
   }
   else {
      if( array_diff( $given_keys, $non_assoc_keys ) and array_diff( $non_assoc_keys, $given_keys ) ){
         return true;
      }
      else {
         return false;
      }
   }
}
?>
intval
is_bool
Функции для работы с переменными


Проверяет, является ли переменная булевой

is_array
is_callable
Функции для работы с переменными
PHP Manual

is_bool

(PHP 4, PHP 5)

is_bool — Проверяет, является ли переменная булевой

Описание

bool is_bool ( mixed $var )

Проверяет, является ли данная переменная булевой.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является переменной типа boolean, или FALSE в противном случае.

Примеры

Пример #1 Пример использования is_bool()

<?php
$a = false;
$b = 0;

// Так как $a является булевой переменной, функция вернет true
if (is_bool($a) === true) {
    echo "Да, это булевая переменная";
}

// Так как $b не является булевой переменной, функция вернет false
if (is_bool($b) === false) {
    echo "Нет, это не булевая переменная";
}
?>

Смотрите также

  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_string() - Проверяет, является ли переменная строкой
  • is_object() - Проверяет, является ли переменная объектом
  • is_array() - Определяет, является ли переменная массивом

User Contributed Notes

vincent at lycoops dot be 28-Apr-2012 12:22
For those of you who think that micro-optimization is important:

It's quicker to strictly compare a value to TRUE and FALSE, than using is_bool(), because it's a function.

<?php
if (is_bool($var)) { // 100% of time
}

if ($var === true || $var === false) { // 50% of time, if $var is true and 75% of time if $var is false.

}
?>
Spektrum 27-Jun-2011 01:21
If you want to convert a string representation of a boolean ,like "yes", "on", "true", "false",etc..., to an actual boolean, you can try this:

<?php
$myString = "On";
$b = filter_var($myString, FILTER_VALIDATE_BOOLEAN);
?>

This will return TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.
kim at steinhaug dot com 26-Aug-2009 10:48
Seems this is a most wanted function, so here is my version of it. I have been using this one for several years no and it works perfect for my needs. I have added "sloppy" human logic to it, and you could easily extend to your flavour. Like in norway some would use "ja" and "nei" instead of "yes" and "no".

<?php
/**
 * Checks a variable if it is true or false, humanlike.
 * We account for values as 'on', '1', '' and so on.
 * Finally, for some reare occurencies we account with
 * crazy logic to fit some arrays and objects.
 *
 * @author Kim Steinhaug, <kim@steinhaug.com>
 * @param mixed $var, the variable to check
 *
 * Example:
 * $test = 'true';
 * if(_bool($test)){ echo 'true'; } else { echo 'false'; }
 */
function _bool($var){
  if(is_bool($var)){
    return $var;
  } else if($var === NULL || $var === 'NULL' || $var === 'null'){
    return false;
  } else if(is_string($var)){
    $var = trim($var);
    if($var=='false'){ return false;
    } else if($var=='true'){ return true;
    } else if($var=='no'){ return false;
    } else if($var=='yes'){ return true;
    } else if($var=='off'){ return false;
    } else if($var=='on'){ return true;
    } else if($var==''){ return false;
    } else if(ctype_digit($var)){
      if((int) $var)
        return true;
        else
        return false;
    } else { return true; }
  } else if(ctype_digit((string) $var)){
      if((int) $var)
        return true;
        else
        return false;
  } else if(is_array($var)){
    if(count($var))
      return true;
      else
      return false;
  } else if(is_object($var)){
    return true;// No reason to (bool) an object, we assume OK for crazy logic
  } else {
    return true;// Whatever came though must be something,  OK for crazy logic
  }
}
?>
moty66 at gmail dot com 20-Aug-2009 02:18
Here is the function which I use when pasring boolean variables from config files

<?php
function boolVal($var) {
    switch ($var) {
        case $var == true:
        case $var == 1:
        // case $var == '1': // no need for this, because we used
                             // $val == 1 not $var === 1
        case strtolower($var) == 'true':
        case strtolower($var) == 'on':
        case strtolower($var) == 'yes':
        case strtolower($var) == 'y':
            $out = 1;
            break;
        default: $out = 0;
    }

    return $out;
}

?>

I am woundering why php does not have a function to do this

Motaz Abuthiab
sam+nospam at samuellevy dot com 01-Feb-2009 04:30
Just another little function which doesn't exist yet, but I find mighty useful, especially when working with AJAX and APIs.

<?php
/** Checks a variable to see if it should be considered a boolean true or false.
 *     Also takes into account some text-based representations of true of false,
 *     such as 'false','N','yes','on','off', etc.
 * @author Samuel Levy <sam+nospam@samuellevy.com>
 * @param mixed $in The variable to check
 * @param bool $strict If set to false, consider everything that is not false to
 *                     be true.
 * @return bool The boolean equivalent or null
 */
function boolval($in, $strict=false) {
    $out = null;
    // if not strict, we only have to check if something is false
    if (in_array($in,array('false', 'False', 'FALSE', 'no', 'No', 'n', 'N', '0', 'off',
                           'Off', 'OFF', false, 0, null), true)) {
        $out = false;
    } else if ($strict) {
        // if strict, check the equivalent true values
        if (in_array($in,array('true', 'True', 'TRUE', 'yes', 'Yes', 'y', 'Y', '1',
                               'on', 'On', 'ON', true, 1), true)) {
            $out = true;
        }
    } else {
        // not strict? let the regular php bool check figure it out (will
        //     largely default to true)
        $out = ($in?true:false);
    }
    return $out;
}
?>

It may be pretty inefficient, but it does the job.
bb at kingdom dot cjb dot net 27-Jun-2007 02:57
@ emmanuel del grande

You don't need to break when you return...

function bool($var) {
    switch (strtolower($var)) {
        case ("true"): return true;
        case ("false"): return false;
        default: die("whatever you want it to tell");
    }
}
kevin at metalaxe dot com 05-Jun-2007 01:32
@ emanueledelgrande at email dot it

http://us.php.net/manual/en/language.types.type-juggling.php

(bool) or (boolean) is allowed for type casting a variable. No function like intval, etc but the functionality exists.
emanueledelgrande at email dot it 22-May-2007 09:12
I think there's a hole in the PHP typecasting methods:
you have the (int) function, the (float) function and the (string) function, but no function to force a string variable into the boolean type.

It's obvious that forcing unconditionally the type of variables into arrays and objects is inappropriate, but boolean type is the most basic one for each programming language, that's why I guessed that a (bool) function already existed.

Moreover, with the increasing trend of RSS data streaming, the parsing of an XML string into an object often requires to typecast as boolean values the content of XML tags, normally returned as string by the object method get_content().

I wrote the following function, which also uses a "native PHP style" error message:

<?php
// strings tyecasting as boolean values:
function bool($var) {
    switch (strtolower($var)) {
        case ("true"):
            return true;
            break;
        case ("false"):
            return false;
            break;
        default:
            die("<br />\n<b>Warning:</b> Invalid argument supplied for ".__FUNCTION__." function in <b>".__FILE__."</b> on line <b>".__LINE__."</b>: the argument can contain only 'true' or 'false' values as a string.<br />\n");
    }
}
?>

Here it is a small example:

<?php
$xmlResponse = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
$xmlResponse .= "<Result>";
$xmlResponse .= "<AuthError>false</AuthError>";
$xmlResponse .= "<TransferStatus>true</TransferStatus>";
$xmlResponse .= "</Result>";

if (! $responseDoc = domxml_open_mem($xmlResponse, DOMXML_LOAD_PARSING, $XmlParsingError)) {
    echo "Error while parsing the XML string:<br />".print_r($XmlParsingError, TRUE);
} else {
    $ResultNode = $responseDoc->get_elements_by_tagname('Result');

    $AuthError = $ResultNode[0]->get_elements_by_tagname('AuthError');
    $auth_error = bool($AuthError[0]->get_content());

    $TransferStatus = $ResultNode[0]->get_elements_by_tagname('TransferStatus');
    $transfer_status = bool($TransferStatus[0]->get_content());

    if (! $auth_error) { echo "Auth OK<br />"; } else { echo "Auth error<br />"; }
    if ($transfer_status) { echo "Transfer OK<br />"; } else { echo "Transfer error<br />"; }
}

?>

It would be useful this function to be implemented in the core of PHP5.
21-Apr-2006 04:12
Small caveat to rh's post: back in PHP 3, "0" would be considered non-empty (i.e., empty would return false), even though (bool) on "0" would also evaluate to false; thus, they would not be complete opposites for someone using PHP 3.
rh at richardhoward dot net 22-May-2005 11:17
punkpuke is wrong here; what he means to say is that empty($x) is the opposite of (bool)$x.  is_bool($x) returns true where $x === false.
is_array
is_callable
Функции для работы с переменными


Проверяет, может ли значение переменной быть вызвано в качестве функции

is_bool
is_double
Функции для работы с переменными
PHP Manual

is_callable

(PHP 4 >= 4.0.6, PHP 5)

is_callable — Проверяет, может ли значение переменной быть вызвано в качестве функции

Описание

bool is_callable ( callable $name [, bool $syntax_only = false [, string &$callable_name ]] )

Проверяет, может ли значение переменной быть вызвано в качестве функции. С помощью данной функции можно проверить, что простая переменная содержит корректное имя функции, или что массив содержит правильно заданный объект и имя функции.

Список параметров

name

Может быть как именем функции, заданным строковой переменной, так и объектом и именем вызываемого метода, например:

array($SomeObject, 'MethodName')

syntax_only

Если равен TRUE, функция только проверяет, что name может быть функцией или методом. В этом случае будут игнорироваться переменные, не являющиеся строкой или массивом c неправильной структурой для имени callback-функции. Правильная структура предполагает наличие только 2 элементов, первый из которых - объект или строка, а второй - строка.

callable_name

Получает "имя для вызова". В примере ниже это "someClass::someMethod". Следует иметь ввиду, что хотя запись someClass::SomeMethod() означает вызываемый статический метод, в данном случае это не так.

Возвращаемые значения

Возвращает TRUE, если name может быть вызвана, или FALSE в противном случае.

Примеры

Пример #1 Пример использования is_callable()

<?php
//  Как проверить переменную, чтобы узнать, может ли она быть вызвана
//  как функция.

//
//  Простая переменная, содержащая имя функции
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name));  // bool(true)

echo $callable_name, "\n";  // someFunction

//
//  Массив, содержащий метод класса
//

class someClass {

  function someMethod()
  {
  }

}

$anObject = new someClass();

$methodVariable = array($anObject, 'someMethod');

var_dump(is_callable($methodVariable, true, $callable_name));  //  bool(true)

echo $callable_name, "\n";  //  someClass::someMethod

?>

Смотрите также

  • function_exists() - Возвращает TRUE, если указанная функция определена
  • method_exists() - Проверяет, существует ли метод в данном классе

User Contributed Notes

Athari 13-May-2012 03:58
For closures, the function will return true and $callable_name will be set to "Closure::__invoke".
passivesmoking AT yahoo DOT com 07-Jan-2012 06:06
is_callable doesn't seem able to resolve namespaces.  If you're passing a string, then the string has to include the function's full namespace.

<?php
namespace foo\bar\baz;

function something ()
{
    return (42);
}

var_dump (is_callable ('something')); // false
var_dump (is_callable ('foo\bar\baz\something')); // true
?>

It's easy to forget, but if you just prepend __NAMESPACE__ to your function name strings you should be fine in most cases.
fgm at osinet dot fr 27-Jun-2011 05:03
Note that, for the purpose of this function, an abstract method, although necessarily non-callable since it does not have a body, is still considered to be callable:

<?php
abstract class Foo {
  abstract function bar();
}

echo is_callable(array('Foo', 'bar'));
// display: 1
?>
Andy at txtNation dot com 27-Jun-2011 03:50
Note that is_callable is aware of context, and you can ask it things like parent::__construct from within a child constructor

<?php

    class TestClass extends TestClassParent {

        /** @brief Object initialisation callback
            @returns void */
        public function __construct() {

            # do initialisation

            # ...

            # if we have a parent

            if(is_callable('parent::__construct')) {

                # then bubble up

                parent::__construct();
            }
        }
    }
?>
lx at webactives dot ru 21-Apr-2011 01:10
is_callable correctly work with Closure (PHP 5.3). Simple test:
<?php
function is_callable_test(Closure $func=null){
    if (is_callable($func)){
        $func();
    }else{
        echo 'uncaleble', "\n";
    }
}
$win_text = 'is_callable function work correctly!';
is_callable_test(function () use ($win_text){
    echo $win_text, "\n";
});
?>
V.Suhanov 16-Mar-2011 06:11
is_callable("{$class}::{$method}"); will return false if method is not defined as static in PHP 5.2 and will return true in PHP 5.3

<?php
class foo {
public function bar(){}
}
var_dump(is_callable("foo::bar")); // true in 5.3, but false in 5.2
?>
Jaik Dean 01-Dec-2010 03:52
It's worth noting that passing an object and method name will not work for lambdas/closures stored within an object property. Here's a test case in 5.3.3.

<?php

class TestClass
{
    public $testMethod;

    public function __construct()
    {
        $this->testMethod = function(){};
    }
}

$test = new TestClass();

is_callable(array($test, 'testMethod')); // false
is_callable($this->testMethod); // true
?>
colin 03-Oct-2010 11:30
I haven't seen anyone note this before, but is_callable will correctly determine the existence of methods made with __call. The method_exists function will not.

Example:
<?php

class Test {

    public function testing($not = false) {
        $not = $not ? 'true' : 'false';
        echo "testing - not: $not<br/>";
    }

    public function __call($name, $args) {
        if(preg_match('/^not([A-Z]\w+)$/', $name, $matches)) {
            $fn_name = strtolower($matches[1]);
            if(method_exists($this, $fn_name)) {
                $args[] = true; // add NOT boolean to args
                return call_user_func_array(array($this, $matches[1]), $args);
            }
        }
        die("No method with name: $name<br/>");
    }

}

$t = new Test();
$t->testing();
$t->notTesting();

echo "exists: ".method_exists($t, 'notTesting').'<br/>';
echo "callable: ".is_callable(array($t, 'notTesting'));

?>

Output:

testing - not: false
testing - not: true
exists:
callable: 1
minty at nospam dot com 10-Jul-2010 02:34
Although not mentioned anywhere on the manual page, is_callable works as expected with closures.

<?php

$func = function() { return; };
var_dump(is_callable($func)); // boolean (true)

?>
Constantin Kpplinger 10-Jun-2010 12:16
It seems the only issue left with is_callable() is the disable_functions ini-setting. Apart from that, is_callable() will reliably evaluate whether the passed function or method can be called from within the same context is_callable() was called from, taking visibility and inheritance into account. This includes functions, regular and static methods, magic functions and methods and implemented interfaces (which are regular methods within the implementing class anyway).

<?php
function regular_function() {}

abstract class ParentTest
{
    public function public_parent_method() {}
    protected function protected_parent_method() {}
    public static function static_method() {}
    protected static function protected_static_method() {}
}

class CallableTest extends ParentTest implements Countable
{
    public function __invoke() { } // Introduced in 5.3, see http://php.net/manual/language.oop5.magic.php
    protected function protected_method() { }
    public function is_callable($args)
    {
        return is_callable($args);
    }
    // Countable
    public function count()
    {
        return 1;
    }
}

$o = new CallableTest();

// Regular function:
var_dump(is_callable('regular_function')); // true

// Magic __invoke method:
var_dump(is_callable($o)); // true if PHP >= 5.3, false otherwise

// Countable implementation (regular method really):
var_dump(is_callable(array($o, 'count'))); // true

// Protected method from outside the object's scope:
var_dump(is_callable(array($o, 'protected_method'))); // false

// Protected method from inside the object's scope via public proxy method:
var_dump($o->is_callable(array($o, 'protected_method'))); // true

// Parent's public method
var_dump(is_callable(array($o, 'public_parent_method'))); // true

// Parent's protected method
var_dump(is_callable(array($o, 'protected_parent_method'))); // false

// Parent's protected method via proxy
var_dump($o->is_callable(array($o, 'protected_parent_method'))); // true

// Parent's static public method
var_dump(is_callable('CallableTest::static_method')); // true

// Parent's static protected method
var_dump(is_callable('CallableTest::protected_static_method')); // false

// Parent's static protected method via proxy
var_dump($o->is_callable('CallableTest::protected_static_method')); // true
?>

Tested PHP versions were 5.2.9 on openSUSE 10.3 (x64) and 5.3.1 on Windows Server 2003 (x86).
juand at softwarecubes dot com 21-Feb-2009 11:39
Revised function with static support:

<?php
    /**
    * The is_callable php function only considers methods declared in the class itself, and ignores the parent's.
    * This version considers all of the hierarchy.
    *
    * @param (string|Object) $class_name
    * @param string $method_name
    * @param bool $static the method being tested is static.
    */
    public static function isCallable( $class_name, $method_name, $static = false ){

        if( !is_string( $class_name ) ){
            $class_name = get_class( $class_name );
        }

        // Define Callable
        if( $static ){
            $callable = "{$class_name}::{$method_name}";
        }else{
            $callable = array( $class_name, $method_name );
        }

        // Check class itself
            if( @is_callable( $callable ) === true ){
                if( $method_name == 'setEmailAddressTypeHash' ) {
                    ErrorHandler::preDump($callable);
                }
                return true;
            }

        // Check all parents
            while( $parent_class = get_parent_class( $class_name ) ){
                if( @is_callable( $callable ) === true ){
                    return true;
                }
                $class_name = $parent_class;
            }

        return false;
    }
?>
Rafael M. Salvioni 20-May-2008 09:10
The PHP's function is_callable not verify the visibility of the tested method.

The following function uses the Reflection classes of the PHP5 to check it.

<?php

/**
 * Function is_callback().
 *
 * @param mixed $var Var
 * @return bool
 */
function is_callback($var)
{
    if (is_array($var) && count($var) == 2) {
        $var = array_values($var);
        if ((!is_string($var[0]) && !is_object($var[0])) || (is_string($var[0]) && !class_exists($var[0]))) {
            return false;
        }
        $isObj = is_object($var[0]);
        $class = new ReflectionClass($isObj ? get_class($var[0]) : $var[0]);
        if ($class->isAbstract()) {
            return false;
        }
        try {
            $method = $class->getMethod($var[1]);
            if (!$method->isPublic() || $method->isAbstract()) {
                return false;
            }
            if (!$isObj && !$method->isStatic()) {
                return false;
            }
        } catch (ReflectionException $e) {
            return false;
        }
        return true;
    } elseif (is_string($var) && function_exists($var)) {
        return true;
    }
    return false;
}

?>
rahadotaboulfethatgmail.com 01-Mar-2008 04:44
is_callable generates an [E_STRICT] error if the  tested method cannot be called staticly. (and returns the good value)

I used @is_called
i'm using php 5.2.1
crestfresh at gmail dot com 17-Feb-2008 09:23
Furthuring mw's note [is_callable correctly takes into account scope so that is_callable(array($obj, 'privateMethod'))  correctly returns false when called from outside $obj's scope]:

It works in 5.1.6 too.
Quis strrev TA omicidio strrev TOD com 13-Nov-2007 03:50
is_callable() does _not_ check wheter this function is disabled by php.ini's disable_functions

use:

<?PHP
function is_disabled($function) {
  $disabled_functions=explode(',',ini_get('disable_functions'));
  return in_array($function, $disabled_functions);
}
?>

I`m running PHP 5.2.4
mw at NO-SPAM hire mason wolf dot com 19-Oct-2007 07:35
As empyone noted, early versions of php 5 incorrectly returned true if is_callable checked on a protected or private method. Later versions of php 5 will now only return true if the method is public and can be called externally. I do not know precisely when this behavior was changed, so you may have to test on your own. But sometime between 5.0.4, which empyone said he was using, and 5.2.4 where I tested it myself, the behavior was modified.
cipri at php dot net 15-Jun-2007 07:24
is_callable also takes the php.ini "disable_functions" setting into consideration; it will return false for functions that have been disabled by your administrator.
hcblue 24-Aug-2006 01:51
True that method_exists() is faster than is_callable(). However, is_callable() will be able to correctly recognize method calls handled by __call() in PHP 5, while method_exists() will not.
jphp at dsf dot org dot uk 12-Feb-2006 03:38
bob at theshirdshift:

"function_exists" doesn't do this, no, but "method_exists" works fine, and is still faster than is_callable:

<?php
function doTimes($start, $end)
  {
   $start_time = explode (" ", $start);
   $start_time = $start_time[1] + $start_time[0];
   $end_time = explode (" ", $end);
   $end_time = $end_time[1] + $end_time[0];
   $time = $end_time - $start_time;
   return $time;
  }

class test
  {
     function test()
     {
         return true;
     }
  }

$test = new test;

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
     if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
     if(method_exists('test', 'test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists    = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>method_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 method_exists in ".$timeExists." seconds";
?>

is_callable = TRUE, method_exists = TRUE

Did 10000 is_callables in 0.410346984863 seconds
Did 10000 method_exists in 0.175447940826 seconds
yetanotheruser at hotmail etc 15-Dec-2005 06:47
I have come across a strange oddity in versions around the 4.3.11 mark - I may have missunderstood the purpose of this function but hope this'll be helpful for some.

The point the code below is supposed to illustrate is that in some cases with

    <? $myFunc = Array( $myObj, 'myMethod' ); ?>

    <? is_callable( $myFunc, true, $callMe ); ?>

will return true, and give you $callMe set to myObj::myMethod but calling

    <? $callMe(); ?>

doesn't work... however calling

    <? $myFunc[0]->$myFunc[1](); ?>

seems to work fine..

... the reason all the code is down there is I think this oddity is due to how/the order in which I've instantiated my classes or something...

anyhow... HTH someone! :-)

Code follows:

FILE 1 :
<?
    include('myTools');

    $foo = new myClass();

    print $foo->getMySource();

    class myClass{

        var $flibble = 'wibble';

        function myClass(
            // Initialise loads of stuff.. including..
            $this->tools = new myTools();
        )

        function getMySource(){
            // This just returns the source.. ok, like some HTML to go into an email for example.
            // Some arguments;
            $args   = $this->flibble;
            // Call our Tool that returns the source..
            $source = $this->tools->returnSource( Array ( $this, 'someHTML' ), $args );
            // and return it..
            return ( $source );
        }

        function someHTML($args){
            // Leave PHP
            ?>
            Here is some HTML.. that we want to build outside a PHP block,
            possibly just cos it's tidier in <B>your favourite text editor</B>..
            .. or you want this function to be elsewhere.. for your designers
            to play with etc.. ... incidentally I'd like to say "<?=$args?>" etc.
            <?
            // .. and we're back.
        }
    }

?>

FILE 2:

<?
    /* OK - this is some other big library and a whole load more
       faff but this is the particular function in question... it
       just calls the function it's been asked to and uses an output
       buffer to grab the output and return it as a string rather than
       letting it go to terminal/browser.... useful for grabbing PHP pages
       for spidering, emailing etc. etc. etc..
    */

    class myTools(){

        function returnSource($func, $args){

            if ( is_callable ( $func, true, $callMe ){
                // Start a buffer
                ob_start();
                // Calling the function like this DOESN'T seem to work:
                // ~~~~~~~~
                // "Command not found : myClass::someHTML"
                // $callMe($args);
                // ~~~~~~~~
                // But - what I've discovered is that this behaves fine..
                if ( is_array($func) ){
                    $func[0]->$func[1]($args);
                } else {
                    $func($args);
                }
                // Then we just carry on with our code..
                $rtn =     ob_get_contents();
                ob_clean();
                return ( $rtn );
            } else {
                error_log("Doh!");
            }
        }
    }

?>
empyone at tiscalinet dot it 08-Nov-2005 12:41
To corey at eyewantmedia dot com:

your misunderstanding lies in passing in the naked $object parameter. It is correct for is_callable to return FALSE since you cannot 'call an object', you can only call one of its methods, but you don't specify which one. Hence:

is_callable(array($object, 'some_function'), [true or false], $callable_name)

will yield the correct result.

Notice, though, that a quick test I made (PHP 5.0.4) showed that is_callable incorrectly returns TRUE also if you specify the name of a protected/private method from outside of the context of the defining class, so, as wasti dot redl at gmx dot net pointed out, reflection is the way to go if you want to take visibility into account (which you should for true OOP, IMHO).
wasti dot redl at gmx dot net 09-Oct-2005 04:14
The way to discover whether a method exists in face of a __call is reflection.

It should be mentioned that although array('Test', 'func') is callable according to this function (where func is a public static method of Test), actually calling this construct as $fn() fails.
corey at eyewantmedia dot com 18-Mar-2005 03:39
I've been spending a month on and off trying to figure out why

is_callable($object, [true or false], $varContainingFunctionName)

returned false when it should not have (ie: $object->FunctionName() was callable), I realized I must have misunderstood its purpose. If you find yourself in the same situation, try

function_exists(string functionname)

or

method_exists ( object object, string method_name )

before you rip your hair out :)
mcroghan at digitalkeg dot com 10-Feb-2005 07:36
Be careful when using this function and __call (PHP5).  This function will always report true when using __call.

Need a specific function for the purpose of checking if a class method exists explicitly even when using __call.

Haven't ruled out the possibility of the existence of such a function yet.  So if someone knows of one, please point it out.
bob at thethirdshift dot net 23-Jun-2004 09:54
I, too, was wondering whether is_callable or function exists is faster when checking class methods.  So, I setup the following test:

<?php
function doTimes($start, $end)
  {
    $start_time = explode (" ", $start);
    $start_time = $start_time[1] + $start_time[0];
    $end_time = explode (" ", $end);
    $end_time = $end_time[1] + $end_time[0];
    $time = $end_time - $start_time;
    return $time;
  }

class test
  {
      function test()
      {
          return true;
      }
  }

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(function_exists('test::test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists     = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>function_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 function_exists in ".$timeExists." seconds";
?>

This gives the output :

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0640790462494 seconds
Did 10000 function_exists in 0.0304429531097 seconds

So the fact that function_exists is twice as fast is slightly over shadowed by the fact that it doesn't work on class methods, at least not as far as I can tell.
webmaster __AT__ digitalanime __DOT__ nl 03-Apr-2004 02:30
<?php
while(list($key,$value)=each($HTTP_POST_VARS))
{
  $tmpVar = 'return isset($' . 'this->' . $key . ');';
  if(is_callable($key) && eval($tmpVar) && trim($value) != "")
  {
  $tmpSet = '$this->set' . ucfirst($key) . "('" . $value . "');";
   eval($tmpSet);
}
}
?>
Why do you use this?

Isn't this a better solvation (or.. Whatever :P)

<?php
foreach($_POST as $key => $value)
{
 if(is_callable($key) && isset($this->{$key}) && trim($value != '')
 {
  $this->{'set' . ucfirst($key)}($value);
 }
}
?>

Tada.. Variable objects, that's what they are..
is_bool
is_double
Функции для работы с переменными


Псевдоним is_float

is_callable
is_float
Функции для работы с переменными
PHP Manual

is_double

(PHP 4, PHP 5)

is_double — Псевдоним is_float()

Описание

Эта функция является псевдонимом: is_float().

User Contributed Notes

There are no user contributed notes for this page.
is_callable
is_float
Функции для работы с переменными


Проверяет, является ли переменная числом с плавающей точкой

is_double
is_int
Функции для работы с переменными
PHP Manual

is_float

(PHP 4, PHP 5)

is_float — Проверяет, является ли переменная числом с плавающей точкой

Описание

bool is_float ( mixed $var )

Проверяет, является ли данная переменная числом с плавающей точкой.

Замечание:

Чтобы проверить, является ли переменная числом или строкой, содержащей число (как поле ввода в форме, которое всегда является строкой), используйте is_numeric().

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является переменной типа float, FALSE в противном случае.

Примеры

Пример #1 Пример использования is_float()

<?php
if (is_float(27.25)) {
    echo "is float\n";
} else {
    echo "is not float\n";
}
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7));  //Научная форма записи
var_dump(is_float(true));
?>

Результат выполнения данного примера:

is float
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)

Смотрите также

  • is_bool() - Проверяет, является ли переменная булевой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_string() - Проверяет, является ли переменная строкой
  • is_array() - Определяет, является ли переменная массивом
  • is_object() - Проверяет, является ли переменная объектом

User Contributed Notes

ircadhikari at gmail dot com 14-Mar-2012 06:22
The final version of function to check the actual float value based on previous Kenaniah's version.
<?php
public function isTrueFloat($val){

        if( is_float($val) || ( (float) $val > (int) $val || strlen($val) != strlen( (int) $val) ) && (ceil($val)) != 0 ) return true;
        else return false;
    }
?>

<?php
//Tests
'4.0'       returns true
'2.1'       returns true
0           returns false
"0"         returns false
3.          returns true
13          returns false
"12"        returns false
3.53        returns true
// Additional Tested ones
"0.27"      returns true
0.24        returns true
?>
Boylett 20-Sep-2008 09:29
If you want to test whether a string is containing a float, rather than if a variable is a float, you can use this simple little function:

function isfloat($f) return ($f == (string)(float)$f);
ckelley at the ca - cycleworks dot com 14-Jul-2008 03:39
Personally, I use an implicit cast:

if( is_float($value+1) ){
    $value=sprintf("%.2f",$value);
}

Which turns 22.0000000 query result into 22.00 for display to users.
kshegunov at gmail dot com 31-Mar-2008 01:32
As celelibi at gmail dot com stated, is_float checks ONLY the type of the variable not the data it holds!

If you want to check if string represent a floating point value use the following regular expression and not is_float(),
or poorly written custom functions.

/^[+-]?(([0-9]+)|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*)|
(([0-9]+|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*))[eE][+-]?[0-9]+))$/
celelibi at gmail dot com 03-Mar-2008 08:31
Unlike others comment may let you think, this function tests *only* the type of the variable. It does not perform any other test.
If you want to check if a string represents a valid float value, please use is_numeric instead.
WHITE new media architects - Jeroen 10-Jan-2008 03:24
The above printed "is_true_float" function is not correct.
It gives wrong answers on the following tests:
is_true_float("-4,123"); # returns false
is_true_float("0,123");  # returns false

So I changed the function to correctly handle qouted negative floats and quoted floats near zero:

<?php

function is_true_float($mVal)
{
  return ( is_float($mVal)
           || ( (float) $mVal != round($mVal)
                || strlen($mVal) != strlen( (int) $mVal) )
              && $mVal != 0 );
}

?>
Kenaniah Cerny 06-Nov-2007 11:21
For those of you who have discovered that is_float() does not behave exactly the way you would expect it to when passing a string, here is a function that extends is_float properly report floating numbers given any sort of mixed variable.

<?php
function is_true_float($val){
    if( is_float($val) || ( (float) $val > (int) $val || strlen($val) != strlen( (int) $val) ) && (int) $val != 0  ) return true;
    else return false;
}
?>

<?php
//Tests
'4.0'       returns true
'2.1'       returns true
0           returns false
"0"         returns false
3.          returns true
13          returns false
"12"        returns false
3.53        returns true
?>

Enjoy
phper 25-Jan-2006 12:08
A better way to check for a certain number of decimal places is to use :

$num_dec_places = 2;
number_format($value,$num_dec_places);
kirti dot contact at gmail dot com 18-Oct-2005 11:18
To check a float only should contain certain number of decimal places, I have used this simple function below

<?
function is_deccount($number,$decimal=2){
    $m_factor=pow(10,$decimal);
    if((int)($number*$m_factor)==$number*$m_factor)
        return true;
    else
        return false;
 }
?>
is_double
is_int
Функции для работы с переменными


Проверяет, является ли переменная переменной целочисленного типа

is_float
is_integer
Функции для работы с переменными
PHP Manual

is_int

(PHP 4, PHP 5)

is_int — Проверяет, является ли переменная переменной целочисленного типа

Описание

bool is_int ( mixed $var )

Проверяет, является ли тип переменной целочисленным.

Замечание:

Чтобы проверить, что переменная является числом или строкой, содержащей число (как поле ввода в форме, которое всегда является строкой), используйте is_numeric().

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является целым числом, или FALSE в противном случае.

Примеры

Пример #1 Пример использования is_int()

<?php
if (is_int(23)) {
    echo "целое\n";
} else {
    echo "не целое\n";
}
var_dump(is_int(23));
var_dump(is_int("23"));
var_dump(is_int(23.5));
var_dump(is_int(true));
?>

Результат выполнения данного примера:

целое
bool(true)
bool(false)
bool(false)
bool(false)

Смотрите также

  • is_bool() - Проверяет, является ли переменная булевой
  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_string() - Проверяет, является ли переменная строкой
  • is_array() - Определяет, является ли переменная массивом
  • is_object() - Проверяет, является ли переменная объектом

User Contributed Notes

Anonymous 25-May-2012 03:07
Simple checking for integer:

<?php
if (strval(intval($var)) == strval($var)) {
  // $var is integer
}
?>

This return true if and only if $var is really integer. Without letters next to it, without "+" sign etc.
We can use it in mysql query for example.
arturs at indigo dot lv 04-May-2012 11:31
Sometime needed check if string containing numbers is integer or not. Then I created this small function:
<?php
function is_integer2($v) {
  $i = intval($v);
  if ("$i" == "$v") {
    return TRUE;
  } else {
    return FALSE;
  }
}
?>
derek at storkey dot co dot uk 20-Feb-2011 05:56
I noticed that is_int(sqrt(16)) is false, and I wanted the sqrt to really return an int if it was an int.

So I wrote
<?php
    function is_really_int(&$val) {
        $num = (int)$val;
        if ($val==$num) {
            $val=$num;
            return true;
        }
        return false;
    }
?>

You'll may criticise the side effects but I don't think they hurt.
andre dot roesti at 7flex dot net 27-Jul-2010 05:51
With this function you can check if every of multiple variables are int. This is a little more comfortable than writing 'is_int' for every variable you've got.

<?php
function are_int ( ) {
    $args = func_get_args ();
    foreach ( $args as $arg )
        if ( ! is_int ( $arg ) )
            return false;
    return true;
}

// Example:
are_int ( 4, 9 ); // true
are_int ( 22, 08, 'foo' ); // false
?>
Robin 27-Mar-2010 08:22
Keep in mind that is_int() operates in signed fashion, not unsigned, and is limited to the word size of the environment php is running in.

In a 32-bit environment:

<?php
is_int( 2147483647 );           // true
is_int( 2147483648 );           // false
is_int( 9223372036854775807 );  // false
is_int( 9223372036854775808 );  // false
?>

In a 64-bit environment:

<?php
is_int( 2147483647 );           // true
is_int( 2147483648 );           // true
is_int( 9223372036854775807 );  // true
is_int( 9223372036854775808 );  // false
?>

If you find yourself deployed in a 32-bit environment where you are required to deal with numeric confirmation of integers (and integers only) potentially breaching the 32-bit span, you can combine is_int() with is_float() to guarantee a cover of the full, signed 64-bit span:

<?php
$small = 2147483647;         // will always be true for is_int(), but never for is_float()
$big = 9223372036854775807;  // will only be true for is_int() in a 64-bit environment

if( is_int($small) || is_float($small) );  // passes in a 32-bit environment
if( is_int($big) || is_float($big) );      // passes in a 32-bit environment
?>
thierryreeuwijk at hotmail dot com 14-Jan-2010 02:04
If you only want integer values like 23 or 0155, or form/string integer values like "23" or "0155" to be valid, this should work just fine.

<?php

    function int($int){

        // First check if it's a numeric value as either a string or number
        if(is_numeric($int) === TRUE){

            // It's a number, but it has to be an integer
            if((int)$int == $int){

                return TRUE;

            // It's a number, but not an integer, so we fail
            }else{

                return FALSE;
            }

        // Not a number
        }else{

            return FALSE;
        }
    }

    print("155".int(155)."<br>");
    print("15.5".int(15.5)."<br>");
    print("\"155\"".int("155")."<br>");
    print("\"15.5\"".int("15.5")."<br>");
    print("\"0155\"".int("0155")."<br>");
    print("\"I'm 155\"".int("I'm 155")."<br>");
    print("\"test\"".int("test")."<br>");
    print("\"\"".int(""));
?>

The above returns:

155        TRUE
15.5       FALSE
"155"      TRUE
"15.5"     FALSE
"0155"     TRUE
"I'm 155"  FALSE
"test"     FALSE
""         FALSE
me at rexxars dot com 16-Sep-2009 05:23
I was looking for the fastest way to check for an unsigned integer which supported large numbers like 4318943448871348 or 0xFFFFFFFF.

Fastest I came up with is this:
<?php
function is_unsigned_int($val) {
    return ctype_digit((string) $value));
}
?>

Will return true on 1515, 0xFFFFFFFF, '3515' and '1365158185855141'.
Will return false on 0.1515, '415.4134' and '-616'.

Be aware though, before PHP 5.1.0 this will return true on an empty string.

According to my benchmarks this is about 30% faster than the regex ^\d+$.
Roberto Rama 21-Jul-2009 11:39
Use this instead if you wanna know if a string is explicitly a number:

<?php

function isint( $mixed )
{
    return ( preg_match( '/^\d*$/'  , $mixed) == 1 );
}

var_export( isint( '123' ) ); //This will return true

var_export( isint( 123 ) ); //This will return true

var_export( isint( 'asd' ) ); //This will return false

var_export( isint( '123asd123' ) ); //This will return false

?>
corey at effim dot com 09-Jun-2009 01:21
If you're concerned with speed, you can save yourself about 50% of the time it takes to check whether or not something is an integer pretty easily...

Running through 10,000 iterations of each of the following 3 methods outputs fairly consistently...

<?php
$foo = is_int($i);
// 0.0032429695129395 seconds

$foo = ((int) $i) == $i;
// 0.0020270347595215 seconds

$foo = ((int) $i) === $i;
// 0.001600980758667 seconds
?>

So if you want the best performance and know you're not going to be passed a string that needs to be typed as an integer, use === to compare the type as well.
Anonymous 03-Jun-2009 08:39
Typecasting will return false if a string has leading zeroes. If you prefer '023' return true, try:

<?php
function really_is_int($val)
{
    if(func_num_args() !== 1)
        exit(__FUNCTION__.'(): not passed 1 arg');

    return ($val !== true) && ((string)abs((int) $val)) === ((string) ltrim($val, '-0'));
}
?>
e dot sand at elisand dot com 09-Apr-2009 08:27
Simon Neaves was close on explaining why his function is perfect choice for testing for an int (as possibly most people would need).  He made some errors on his ctype_digit() output though - possibly a typo, or maybe a bug in his version of PHP at the time.

The correct output for parts of his examples should be:

<?php
var_dump(ctype_digit(23)); //bool(false)
var_dump(ctype_digit("23")); //bool(true)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(false)
?>

As you can see, the reason why using *just* ctype_digit() may not always work is because it only returns TRUE when given a string as input - given a number value and it returns FALSE (which may be unexpected).
leonix at motd dot ru 16-Dec-2008 12:08
another_is_int() is almost perfect, but it treats boolean true as int because
1 == (int) true == (string) true == '1'.

Fixed version:

<?php
/**
 * Checks if the given value represents integer
 */
function int_ok($val)
{
    return ($val !== true) && ((string)(int) $val) === ((string) $val);
}
?>
paulo dot koch at g_mail dot com 17-Oct-2008 12:30
Don't over-engineer it.

<?php
function another_is_int($a){
    return ((string) $a) === ((string)(int) $a);
}
?>
Wryel Covo - ryryel[at]gmail[dot]com 14-Oct-2008 11:53
<?php
function onlyNumbers($string){
    //This function removes all characters other than numbers
    //Esta função limpa a url e conserva apenas os numeros
    $string = preg_replace("/[^0-9]/", "", $string);
    return (int) $string;
}

echo $test = onlyNumbers("as87d68a6db8a7d686dx8a6dx"); //2147483647
echo "<br/>";
echo onlyNumbers("xn89d9x797d9a8x7-"); //899797987
echo "<br/>";
if(is_int($test)){
    echo "Is int ! - É inteiro !"; // This OK !
} else {
    echo "Not int ! - Não é inteiro";
}
?>
mark at codedesigner dot nl 26-Jun-2008 06:34
updated version from Simon Neaves

<?php
function isInteger($input){
  return preg_match('@^[-]?[0-9]+$@',$input) === 1;
}
?>

this function checks if the string:
- starts with a - sign (optional)
- ends with 1 or more numeric chars
Julien Picalausa 11-May-2008 02:44
To check if a string ($s) is a representation of an integer (including representations is scientific notation and negative numbers), you can use the following test, provided that you don't expect values that are out of bounds for an integer.

is_numeric($s) && floatval($s) == intval(floatval($s))

If the test returns true, the string is a representation of an integer.
is_numeric (if it works as intended) protects from strings that are not proper numbers.
The comparison filters anything that is non_integer

If, for performance reasons, you want to avoid converting to float twice, it can also be written:
is_numeric($s) && ($f = floatval($s)) == intval($f)

If you plan to get values that cannot be representated with an integer and are ready to deal with a float, you can use floor instead of intval, as long as you are ready to deal with floats. Even so, that method will become unreliable when the precision of the float becomes insufficient for getting to the fractional part of the number
Simon Neaves 29-Apr-2008 11:14
I've found that both that is_int and ctype_digit don't behave quite as I'd expect, so I made a simple function called isInteger which does. I hope somebody finds it useful.

<?php
function isInteger($input){
    return(ctype_digit(strval($input)));
}

var_dump(is_int(23)); //bool(true)
var_dump(is_int("23")); //bool(false)
var_dump(is_int(23.5)); //bool(false)
var_dump(is_int(NULL)); //bool(false)
var_dump(is_int("")); //bool(false)

var_dump(ctype_digit(23)); //bool(true)
var_dump(ctype_digit("23")); //bool(false)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(true)

var_dump(isInteger(23)); //bool(true)
var_dump(isInteger("23")); //bool(true)
var_dump(isInteger(23.5)); //bool(false)
var_dump(isInteger(NULL)); //bool(false)
var_dump(isInteger("")); //bool(false)
?>
qlimmax at gmail dot com 07-Apr-2008 10:58
function is_natural($natural,$zero=true)
{
if(ctype_digit($natural))
{
    if($zero)
    {
        $natural_test=(int)$natural;
        if((string)$natural_test !== $natural) return false;
        else return true;
    }
    else return true;
}
else return false;
}

true for ("0","1","2","3",...) false for("-1","01","adS","#@!$%^&*-...","0.7","0,7", "0x12",...)
if $zero=false
true for("0","00","1","01",...) false("-1","#@!$%^&*-...","adS","0.7","0,7", "0x12",...)
wes9999 a myfastmail com 30-Nov-2007 09:28
a small modification to the isInt checks provided by lclkk at urbanvagabond dot net to make them work for scientific notation integers that are provided in string form:

function myIsInt ($x) {
    return (is_numeric($x) ? intval($x+0) == $x : false);
}

function Test($x) {
    echo "$x is " . ( myIsInt($x) ? ('an integer. The integer value is ' . intval($x+0)) : 'not an integer.');
    echo "\n";
}

Note the additional adding of 0 to $x in both functions.

This would allow the following tests to return true:
Test('53.45e2'); // 5345
Test('53.45e3'); // 53450

and this one to return false:
Test('53.45e1'); // 534.5
tudor at tudorholton dot com 04-Jul-2007 06:27
Please note this from the Integer datatype page:

"The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined from PHP_INT_SIZE, maximum value from PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5."

This is particularly important if you are doing validation of large keys or any number larger than 2,000,000,000 (e.g. telephone numbers)
Ender at soldat dot nl 16-Feb-2006 03:38
Be aware that is_numeric (mentioned in this article as the proper way to validate string numbers) also allows numbers in scientific and hexadecimal annotation. Thus DO NOT USE that function to validate user input that will be used as id number for in a query for example, this could cause mysql errors. Use ctype_digit instead.
ludvig dot ericson at gmail dot com 06-Jan-2006 01:00
I would like to say that is_int() is pretty helpfull when looking for neat proper ways to check functions that return either integers or booleans (false) on failure (strpos, socket_select, etc.)
<?php
function mySelect() {
    global $someSockets;
    $ret = socket_select($someSockets, $o = array(), $e = array(), 0);
    if (!$ret)
        return is_int($ret);
    /* FURTHER PROCESSING HERE */
    return true;    // Return true if the function proceeded as expected.
}
?>
The point of doing this is that if you put this in a while() loopo, you'll break it when the select fails.
<?php
while (mySelect());
?>

Hope you get the point
 - toxik
lclkk at urbanvagabond dot net 15-Sep-2003 07:24
I think the function below is a robust test for integers working on all datatypes. It works by first checking that a number can be evaluated numerically, and then secondly that the integer evaluation matches the original number.

Test cases are included.

<?
function myIsInt ($x) {
    return (is_numeric($x) ? intval($x) == $x : false);
}

function Test($x) {
    echo "$x is " . ( myIsInt($x) ? ('an integer. The integer value is ' . intval($x)) : 'not an integer.');
    echo "\n";
}

echo "These should be integers...\n";
Test(1);
Test(5);
Test(10);
Test(10.0);
Test(20.0);
Test(-20.0);
Test(0+4+4.5+4.5);
Test("10.0");
Test("+14");
Test("-15");
Test("0");

echo "\nThese should not be integers...\n";
Test(true); // watch out, this displays as '1'
Test(false);
Test("moose");
Test("3.5");
Test("-214235.5");
Test(""); // empty string
Test(array(1,2,3));
Test(dir('.')); // object
Test(null);
?>
gabe at websaviour dot com 14-Jul-2003 11:08
Although this can be inferred from the documentation, beware of numeric strings.  I ran into the problem in a MySQL app where I would either SELECT an INT PRIMARY KEY or INSERT a new record and use mysql_insert_id() to get the KEY before continuing onto the new section.

I used is_int() to make sure the subsequent queries wouldn't break when using the key variable.  Unfortunately I failed to realize that while mysql_insert_id() returns an int, mysql_result() always returns a string even if you are SELECTing from an INT field.

Spent at least 30 minutes trying to figure out why existing records weren't getting linked, but new records would link fine.  I ended up using intval() on mysql_result() to make sure subsequent queries still always work.
logan at logannet dot net 10-Feb-2003 03:42
[[Editors note: Or you can simply use is_numeric()]]

Some people have offered their ways to find out if a string from a form is an integer or not, here's my way:

if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] = (int)$_POST["number"];

In psuedo code:
if you are a string full of numbers then convert yourself to an integer

So instead of just checking if its a string full of numbers you check and then convert it, which means you can use the standard is_int. You can also do:

if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] += 0;

I think the first way i mentioned is better because your coding what you want to do, rather than the second way that uses a side effect of adding 0 to convert the string.

The first way also may make your code ever so slightly faster (nothing noticeable) as php does not need to add 0 to the number after it converts it.

Also note an integer is full numbers (1, 2, 3 etc) not decimal numbers (1.1, 2.4, 3.7 etc), to convert decimal numbers you could use something like:

if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] = (float)$_POST["number"];

OR

if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] += 0;

But note that these would not work with is_int(), because they are not integers.
is_float
is_integer
Функции для работы с переменными


Псевдоним is_int

is_int
is_long
Функции для работы с переменными
PHP Manual

is_integer

(PHP 4, PHP 5)

is_integer — Псевдоним is_int()

Описание

Эта функция является псевдонимом: is_int().

User Contributed Notes

There are no user contributed notes for this page.
is_int
is_long
Функции для работы с переменными


Псевдоним is_int

is_integer
is_null
Функции для работы с переменными
PHP Manual

is_long

(PHP 4, PHP 5)

is_long — Псевдоним is_int()

Описание

Эта функция является псевдонимом: is_int().

User Contributed Notes

Mark Slemko 21-Apr-2010 09:57
It should be noted here that 64 bit values need a 64-bit OS as they are converted on a 32 bit OS and are not stored as 64 bit values.
is_integer
is_null
Функции для работы с переменными


Проверяет, является ли значение переменной равным NULL

is_long
is_numeric
Функции для работы с переменными
PHP Manual

is_null

(PHP 4 >= 4.0.4, PHP 5)

is_null — Проверяет, является ли значение переменной равным NULL

Описание

bool is_null ( mixed $var )

Проверяет, является ли значение данной переменной равным NULL.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если значение var равно null, или FALSE в противном случае.

Примеры

Пример #1 Пример использования is_null()

<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>
Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

Смотрите также

  • The NULL type
  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • is_bool() - Проверяет, является ли переменная булевой
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_string() - Проверяет, является ли переменная строкой
  • is_object() - Проверяет, является ли переменная объектом
  • is_array() - Определяет, является ли переменная массивом

User Contributed Notes

claude dot pache at gmail dot com 09-May-2009 09:38
A small but important difference between "is_null" and "isset" is the following: "is_null" tests if an *expression* (not a *variable*) is null, while "isset" tests if a *variable* has null value or is undefined. The difference is manifested in the two following experiments:

Experiment 1:
<?php
function test() { return null; }
var_dump(is_null(test())); // displays "true"
var_dump(isset(test())); // parse error, because "test()" is not a variable
?>

Experiment 2:
<?php
error_reporting(E_ALL);
var_dump(isset($an_undefined_variable)); // displays "false" since "$an_undefined_variable" is not defined
var_dump(is_null($an_undefined_variable)); // displays "true" (as expected), but throws a notice because "$an_undefined_variable" is not defined.
?>
george at fauxpanels dot com 01-Dec-2008 01:58
See how php parses different values. $var is the variable.

$var        =    NULL    ""    0    "0"    1

strlen($var)    =    0    0    1    1    1
is_null($var)    =    TRUE    FALSE    FALSE    FALSE    FALSE
$var == ""    =    TRUE    TRUE    TRUE    FALSE    FALSE
!$var        =    TRUE    TRUE    TRUE    TRUE    FALSE
!is_null($var)    =    FALSE    TRUE    TRUE    TRUE    TRUE
$var != ""    =    FALSE    FALSE    FALSE    TRUE    TRUE
$var        =    FALSE    FALSE    FALSE    FALSE    TRUE

Peace!
mdufour at gmail dot com 19-Aug-2008 09:31
Testing for a NULL field/column returned by a mySQL query.

Say you want to check if field/column “foo” from a given row of the table “bar” when returned by a mySQL query is null.
You just use the “is_null()” function:

[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
     if (is_null($qValues["foo"]))
         echo "No foo data!";
     else
         echo "Foo data=".$qValues["foo"];
[…]
Malfist 01-Jul-2008 07:54
Micro optimization isn't worth it.

You had to do it ten million times to notice a difference, a little more than 2 seconds

$a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s

difference = 2.46449494362
difference/10,000,000 = 0.000000246449494362

The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters.
strrev xc.noxeh@ellij 03-Jun-2008 05:42
$var===NULL is much faster than is_null($var) (with the same result)

I did some benchmarking with 10 million iterations:

$a=null;
 isset($a); Took: 1.71841216087s
 $a==NULL; Took: 1.27205181122s
 $a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s
$a=5;
 isset($a); Took: 1.15165400505s
 $a==NULL; Took: 1.41901302338s
 $a===NULL; Took: 1.21655392647s
 is_null($a); Took: 3.78501200676s
error_reporting(E_ALL&~E_NOTICE);
unset($a);
 isset($a); Took: 1.51441502571s
 $a==NULL; Took: 16.5414860249s
 $a===NULL; Took: 16.1273870468s
 is_null($a); Took: 23.1918480396s

Please note, that isset is only included because it gives a good performance in any case; HOWEVER isset is NOT the same, or the opposite.
But you might be able to use isset() instead of null-checking.

You should not use is_null, except when you need a callback-function, or for conformity with is_int, is_float, etc.
ai dot unstmann at combase dot de 14-Jan-2008 12:17
For what I realized is that  is_null($var)  returns exactly the opposite of  isset($var) , except that is_null($var) throws a notice if $var hasn't been set yet.

the following will prove that:

<?php

$quirks = array(null, true, false, 0, 1, '', "\0", "unset");

foreach($quirks as $var) {
    if ($var === "unset") unset($var);

    echo is_null($var) ? 1 : 0;
    echo isset($var) ? 1 : 0;
    echo "\n";
}

?>

this will print out something like:

10    // null
01    // true
01    // false
01    // 0
01    // 1
01    // ''
01    // "\0"
Notice:  Undefined variable: var in /srv/www/htdocs/sandbox/null/nulltest.php on line 8
10    // (unset)

For the major quirky types/values is_null($var) obviously always returns the opposite of isset($var), and the notice clearly points out the faulty line with the is_null() statement. You might want to examine the return value of those functions in detail, but since both are specified to return boolean types there should be no doubt.

A second look into the PHP specs tells that is_null() checks whether a value is null or not. So, you may pass any VALUE to it, eg. the result of a function.
isset() on the other hand is supposed to check for a VARIABLE's existence, which makes it a language construct rather than a function. Its sole porpuse lies in that checking. Passing anything else will result in an error.

Knowing that, allows us to draw the following unlikely conclusion:

isset() as a language construct is way faster, more reliable and powerful than is_null() and should be prefered over is_null(), except for when you're directly passing a function's result, which is considered bad programming practice anyways.
powderz at gmail dot com 11-Aug-2006 09:41
Actually, since a wrapper is going to be written, you can check for your own version null values...if you want to be creative for some reason.

<?php
function isnull($data)
{
  /** only if you need this
  if (is_string($data)) {
    $data = strtolower($data);
  }
  */
  switch ($data) {
    // Add whatever your definition of null is
    // This is just an example
    //-----------------------------
    case 'unknown': // continue
    case 'undefined': // continue
    //-----------------------------
    case 'null': // continue
    case 'NULL': // continue
    case NULL:
      return true;
  }
  // return false by default
  return false;
}
?>
MARSIK 31-Jul-2005 07:54
I've tested different values in order to compare 'em with NULL with the help of different operators...

<?php
$arr=array(0, 0.0, '0', '0.0', '',FALSE,'false',NULL, 'NULL');
for ($i=0; $i<count($arr); $i++)
   $arr[$i]=array(
      $arr[$i],
      ((integer)($arr[$i]==NULL))
     .((integer)($arr[$i]===NULL))
     .((integer)is_null($arr[$i]))
      );

var_dump($arr);
?>

it gave the following results:

0 : ==NULL
0.0 : ==NULL
'0' : nothing worked =)
'0.0' : nothing...
'' : ==NULL
FALSE : ==NULL
'false' : nothing
NULL : ==NULL, ===NULL, is_null()
'NULL' : nothing

enjoy =)
michael at cannonbose dot com 30-Dec-2003 09:42
Regarding avoidance of NULLs in your MySQL queries, why not use  IS NULL and IS NOT NULL in your WHERE clauses.

SELECT *
FROM someDatabase
WHERE someAttribute IS NOT NULL

Cheers,

Michael
uioreanu at hotmail dot com 23-Mar-2001 06:36
Don't try to test
if ($intSomething==NULL) {
 ...
}
use is_null() instead.
The first statement misses 0 values.

Regards,
Calin

[Ed. note: this is because == tests for equivalence of value, but not type. NULL evaluates to
false, as does 0, so NULL == 0 is true--even though 0 is type int and NULL is type null.
You should use either is_null() as noted or ===, which returns true only if its operands are
equal and of the same type.]
is_long
is_numeric
Функции для работы с переменными


Проверяет, является ли переменная числом или строкой, содержащей число

is_null
is_object
Функции для работы с переменными
PHP Manual

is_numeric

(PHP 4, PHP 5)

is_numeric — Проверяет, является ли переменная числом или строкой, содержащей число

Описание

bool is_numeric ( mixed $var )

Проверяет, является ли данная переменная числом. Строки, содержащие числа, состоят из необязательного знака, любого количества цифр, необязательной десятичной части и необязательной экспоненциальной части. Так, +0123.45e6 является верным числовым значением. Шестнадцатеричная запись (0xFF) также допускается, но только без знака, десятичной и экспоненциальной части.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является числом или строкой, содержащей число, в противном случае возвращается FALSE.

Примеры

Пример #1 Примеры использованияis_numeric()

<?php
$tests = array(
    "42",
    1337,
    "1e4",
    "not numeric",
    array(),
    9.1
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo "'{$element}' - число", PHP_EOL;
    } else {
        echo "'{$element}' - НЕ число", PHP_EOL;
    }
}
?>

Результат выполнения данного примера:

'42' - число
'1337' - число
'1e4' - число
'not numeric' - НЕ число
'Array' - НЕ число
'9.1' - число

Смотрите также

  • ctype_digit() - Проверяет на наличие цифровых символов в строке
  • is_bool() - Проверяет, является ли переменная булевой
  • is_null() - Проверяет, является ли значение переменной равным NULL
  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_string() - Проверяет, является ли переменная строкой
  • is_object() - Проверяет, является ли переменная объектом
  • is_array() - Определяет, является ли переменная массивом

User Contributed Notes

dave dot marr at gmail dot com 31-Jan-2012 04:30
If you want the numerical value of a string, this will return a float or int value:

<?php
function get_numeric($val) {
  if (is_numeric($val)) {
    return $val + 0;
  }
  return 0;
}
?>

Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>
akam at akameng dor com 22-Jan-2012 09:22
<?php
$d = @$_GET['d'];

/*
assuming that passing value of d in the mysql
$sql = "select * from books where bookid = '$d' "
*/

/*
now check if $d is numeric?
*/

if(!is_numeric($d)){
 $d = preg_replace("/[^0-9]+/", "", $d);
}
echo "Cleared value: $d \n<br />Original Vlaue:".@$_GET['d'];
//then using clear value of $d in the mysql query
$sql = "select * from books where bookid = '$d' ";
?>
Example:
?d=52;d;s;s'2233l'[[22

Outpt:

Cleared value: 52223322
Original Vlaue:52;d;s;s'2233l'[[22
holdoffhunger at gmail dot com 30-Dec-2011 09:20
I wanted an Is_hex function that does the same as is_numeric, except for hex.  Here's one with decent efficiency that uses direct iteration.  $result stores the result as a TRUE/FALSE string (which can be changed to bool, depending on how you want to implement it), and $string_to_test is the string of possible-hex values you want to test.

<?php

    // Released Under Affero General Public License, Version 3 (AGPL3)
    // Author: holdoffhunger@gmail.com

$result = "TRUE";

$testable_string = strtolower($string_to_test);
$testable_string_length = strlen($string_to_test);

for($i_string = 0; $i_string < $testable_string_length; $i_string++)
{
    $current_value_to_test = $testable_string[$i_string];

    if(    ($current_value_to_test != "0")        &&
        ($current_value_to_test != "1")        &&
        ($current_value_to_test != "2")        &&
        ($current_value_to_test != "3")        &&
        ($current_value_to_test != "4")        &&
        ($current_value_to_test != "5")        &&
        ($current_value_to_test != "6")        &&
        ($current_value_to_test != "7")        &&
        ($current_value_to_test != "8")        &&
        ($current_value_to_test != "9")        &&
        ($current_value_to_test != "a")        &&
        ($current_value_to_test != "b")        &&
        ($current_value_to_test != "c")        &&
        ($current_value_to_test != "d")        &&
        ($current_value_to_test != "e")        &&
        ($current_value_to_test != "f")        )
    {
        $result = "FALSE";
        $i_string = $testable_string_length;
    }
}

?>
sobolanx at gmail dot com 22-Jan-2011 03:55
Note that the function accepts extremely big numbers and correctly evaluates them.

For example:

<?php
    $v = is_numeric ('58635272821786587286382824657568871098287278276543219876543') ? true : false;

    var_dump ($v);
?>

The above script will output:

bool(true)

So this function is not intimidated by super-big numbers. I hope this helps someone.

PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
Martyn Ranyard 10-Jan-2011 04:14
The documentation does not clarify what happens if you the input is an empty string - it correctly returns false in my experience.  Useful to state these odd cases, for when you see code that checks for an empty string and is_numeric, you can tell it's a waste of a comparison.
Nitrogen 11-Sep-2010 10:40
I find it a little weird that people are having issues with ordinal numbers, it's pretty easy..
Notes are in the commenting, check out the example outputs.

<?php

function ordinal($i='') {
  // a temporary value we can change, and keep the original value.
  $o=$i;

  // suffixes = 0th, 1st, 2nd, third == zeroth, first, second, third
  $s=array('th','st','nd','rd');

  // if input just so happens to be a string, we check to make sure it
  // still holds a numeric value and only acquire the last 2 numbers.
  // if it's not a string, nor an integer, we freak out and say no.
  if(!is_int($o))
    if(ctype_digit($o))
      $o=(int)substr($o,-2,2);
    else
      return(false);

  // basically, if $o is between 11 and 19, we use 'th'
  // otherwise we use the last digit and if it's over
  // 4 then we use 0 (for the $s array index).
  return($i.$s[($o%100>10&&$o%100<20)?0:($o%10<4?$o%10:0)]);
}

var_dump(ordinal(5));

/* Example Outputs of ordinal():
  0th, 1st, 2nd, 3rd, 4th, ..., 9th,
  10th, 11th, 12th, 13th, 14th, ..., 19th,
  110th, 111th, ..., 199th, 200th, 201st.

  ordinal('-1'); returns false because ctype_digit hates anything that
  isn't strictly 0 through 9 and '-' trips it to false.

  ordinal('asdf'); returns false for the exact same reason.

  ordinal(); returns false because it's blank.

  signed integers on a 32-bit system (and the same issue on a 64-bit
  system using 0x7FFFFFFFFFFFFFFF because of two's compliment,
  anything higher will become a negative number):
  ordinal(0x7FFFFFFF  ); returns 2147483647th (which is correct)
  ordinal(0x7FFFFFFF+1); returns false.
*/

?>
derek dot p dot moore at gmail dot com 22-Jul-2010 09:39
To verify large hex numbers or hexadecimal strings use:
http://php.net/ctype_xdigit
purdue at nc dot rr dot com 18-May-2010 04:57
I see a lot of examples below to get the ordinal string for a given number ("1st", "2nd", "3rd", "4th", etc).  If you only need small ordinals (up to "31st" at most), this one-line trick works:

<?php

function ordinal ($i) {
   return date("jS", strtotime("Jan $i"));
}

?>
dustout at gmail dot com 02-Mar-2010 06:38
I had troubles when using this as an is_hex function, if anyone else runs into troubles here is an alternative approach. Not a very efficient one, but it worked quite well for what i needed it for.

<?php
function is_hex($hexValue){
if($hexValue == dechex(hexdec($hexValue)))
        return true;
    return false;
}
?>
Kiam 23-Jul-2009 11:02
empty(trim($test, '+-.,0123456789')) doesn't assure you $test contains a number. It returns TRUE also for a string containing ".+1234.56", which is not a valid number.
codeslinger at compsalot dot com 15-Jul-2009 01:34
if speed is important, the liberal use of regex should be avoided, especially complex ones like those here.

For most purposes, this will be sufficient and has the advantages of both speed and clarity.

$BoolResult = empty(trim($Test, '+-.,0123456789'));

If the $Test contains any character that is not a valid part of a number the remaining string will not be empty.

if you want to be more restrictive of the '+-'  then you can use a separate trim for that and nest it.  Keep in mind that some notations pt the sign to the right of the number instead of to the left.  Depending upon your specific application you can also choose to ignore spaces and allow for 'e' notation.

I also use this approach when testing for other character sets such as Hex.
info at DriaConsulting dot Com 04-Jul-2009 11:34
is_numeric() does not escape the string. It validates it's numeric nature with true/false.

However, (int) before the string, converts the string to numeric.
Magnus Deininger, dma05 at web dot de 07-Jan-2009 06:01
regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren't grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim's regexen are slightly suboptimal at one point having an unescaped '.' operator, and the whole thing could easily be combined into a single regex (speed and all).

adjustments:

<?php
$eng_or_world = preg_match
  ('/^[+-]?'. // start marker and sign prefix
  '(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'. // american
  '((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'. // world
  '(e[0-9]+)?'. // exponent
  '$/', // end marker
  $str) == 1;
?>

i'm sure this still isn't optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.
nadim (nadim at alienworkers dot com) 04-Nov-2008 01:53
Using SpT_King James example, i've re-wrote to cater for digits starting with '+', commas ',' or period '.'

<?php
function is_numeric_regex($str)
{
    $str    = "{$str}";

    if (in_array($str[0], array('-', '+')))    $str = "{$str[0]}0" . substr($str, 1);
    else $str = "0{$str}";

    $eng    = preg_match ("/^[+,-]{0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/" , $str) == 1;
    $world    = preg_match ("/^[+,-]{0,1}([0-9]+)(.[0-9][0-9][0-9])*([,][0-9]){0,1}([0-9]*)$/" , $str) == 1;

    return ($eng or $world);
}
?>
jbezorg at gmail dot com 07-Oct-2008 04:50
"$e = (int) substr( $n , -2 );"

What the heck am I thinking.

<?php
function number_suffix2($n)
{
    $s = array( 1->'st' , 2=>'nd' , 3=>'rd' );
    $e = $n % 100;
    $x = $n % 10;

    return $n.( ( $x > 0 && $x < 4 && ( $e < 11 || $e > 13 ) ) ? $s[$x] : 'th' );
}
?>
vezquex at gmail dot com 28-Jul-2008 06:13
I needed a number_suffix function that was really sweet.
<?php
function number_suffix($n){
{
    $suffix = 'th';
    if(!($n >= 10 && $n < 20));
    {
        $s = ['st','nd','rd'];
        $s = $s[$n % 10 - 1];
        $suffix = $s ? $s : 'th';
    }
    return $n . $suffix;
}
?>
SpT_King James (tiagovix2000 (at) gmail) 11-Jan-2008 10:31
To Elwin van Huissteden, by his answer at 27-Mar-2007 05:05.

Your code didnt work (you said not tested it). So i fixed it:

<?
function my_is_numeric($value)  {
    $american = preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
    $world = preg_match ("/^(-){0,1}([0-9]+)(.[0-9][0-9][0-9])*([,][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
   return ($american or $world);
}
?>

-the English/American way of writing a float million number: 1,000,000.00
-the global way of writing a float million number: 1.000.000,02
kendsnyder at gmail dot com 29-Jun-2007 10:49
Be careful when using is_numeric() to escape SQL strings.  is_numeric('0123') returns true but 0123 without quotes cannot be inserted into SQL.  PHP interprets 0123 without quotes as a literal octal number; but SQL just throws a syntax error.

<?php
is_numeric('0123'); // true
is_numeric(0.123); // true
is_numeric('0.123'); // true
is_numeric(123); // true
is_numeric('123'); // true
is_numeric('foo'); // false
?>

Casting a value to float then string and comparing it to the original value cast as string as the same effect as is_numeric but returns false for numeric strings that begin with zero and have no decimal point.  Examples:
<?php
function isDecimalNumber($n) {
  return (string)(float)$n === (string)$n;
}

isDecimalNumber('0123'); // false
isDecimalNumber(0.123); // true
isDecimalNumber('0.123'); // true
isDecimalNumber(123); // true
isDecimalNumber('123'); // true
isDecimalNumber('foo'); // true

?>
Carlos Madeira 02-Jun-2007 10:46
If I may, i think there is a simpler way to determine if a number is odd or even:

if( $number & 1 ) //Just check the last bit!
  echo 'It's odd!';
else
  echo 'It's even!';
Kenn 11-May-2007 11:45
A side note, finding out if an integer is even or odd, given the integer = $i ...

if (($i % 2) == 0) // This will test TRUE if the integer is even.
   {
xxx insert code here xxx
   }
Q1712 at online dot ms 24-Apr-2007 01:33
a regex doing the same as is_numeric() is:
"^((-?[0-9]*\.[0-9]+|[[:space:]]*[+-]?[0-9]+(\.[0-9]*)?)
([eE][+-]?[0-9]+)?|0x[0-9a-fA-F]+)$" (took me some testing to figure this out)
regex: "^(decimal|hex)$"
  decimal: "(base1|base2)(exponent)?"
    base1: "-?[0-9]*\.[0-9]+"
           if there are no prepanded spaces and no "+" the
           base may be any of "0", ".0", "0.0".
    base2: "[[:space:]]*[+-]?[0-9]+(\.[0-9]*)?"
           if there are empty spaces or a "+" prepanded the
           base may only be "0" or "0.0" (no idea why)
    exponent: "[eE][+-]?[0-9]+"
              the exponent is opional
  hex: "0x[0-9a-fA-F]+"
usage: preg_match("/regex/D", $str); or ereg("regex", $str);

Just to know what is_numeric() is doing. Of cause the regex should be much slower and is_numeric() also returns false if the number would be to big to fit into a double.
Elwin van Huissteden 27-Mar-2007 04:05
To James holwell:

Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world's way:

<?php
  function my_is_numeric($value)
  {
   return (preg_match ("/\A(-){0, 1}([0-9]+)((,|.)[0-9]{3, 3})*((,|.)[0-9]){0, 1}([0-9]*)\z/" ,$value) == 1);
  }
?>

Other than that, i'd recommend using yours, if it works (i havent tested either yours or mine)
By using mine, there might be a slight chance to not being able to do calculations with the numeric string if it's not the English/American way.

(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02
james.holwell( at )exeter.ox.ac.uk 20-Mar-2007 02:07
In reply to www.kigoobe.com, a more strict expression is

<?php
  function my_is_numeric($value)
  {
    return (preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/", $value) == 1);
  }
?>

This will not match strings like -6,77.8,8 which are matched by the below expression, and instead requires a single decimal point, with at least one character following, and only permits comma-separation when the right hand side is a triplet.
Stephen 25-Jan-2007 09:31
The documentation is not completely precise here. is_numeric will also return true if the number begins with a decimal point  and/or a space, provided a number follows (rather than a letter or punctuation). So, it doesn't necessarily have to start with a digit.
mariusads::at::helpedia.com 19-Jan-2007 01:56
Test if a number is positive and contains only 0-9:

function is_number($number)
{
    $text = (string)$number;
    $textlen = strlen($text);
    if ($textlen==0) return 0;
    for ($i=0;$i < $textlen;$i++)
    { $ch = ord($text{$i});
       if (($ch<48) || ($ch>57)) return 0;
    }
    return 1;
}

returns

0 : number contain character outside 0-9
1 : valid number.
meagar at gmail dot com 13-Jan-2007 07:52
Miero: Your function doesn't match some special cases: '+1', '-0', '+0', all of which are valid integers.  The easiest and most reliable way to get a definite integer match is with a regular expression:

function is_intval($value) {
     return 1 === preg_match('/^[+-]?[0-9]+$/', $value);
}

This has two "problems" based on your input:  it matches both '00' and '999999999999999999999999999999999' as valid integers.

I'm not sure why you wouldn't want to match "00".  Regardless of whether somebody entered it in a form by accident or on purpose, it /is/ a valid integer, and in most instances you should accept it.

The second value, "999..." is also a valid integer, even if PHPs internal int type isn't precise enough to represent it.
alexander dot j dot summers at imperial dot ac dot uk 23-Oct-2006 09:05
Note that the even simpler functions for checking if a variable contains an odd or even number below don't produce good results if you apply them to arguments which aren't numeric; I guess that was the idea of the originals.

e.g. using the functions defined in two posts below..

IS_ODD(null)  returns false
IS_EVEN(null) returns true
is_odd(null)    returns false
is_even(null)  returns false
ja at krystof dot org 02-Sep-2006 06:10
Here is a simple function to recognize whether the value is a natural number: (Zero is often exclude from the natural numbers, that's why there's the second parameter.)

<?php
function is_natural($val, $acceptzero = false) {
 $return = ((string)$val === (string)(int)$val);
 if ($acceptzero)
  $base = 0;
 else
  $base = 1;
 if ($return && intval($val) < $base)
  $return = false;
 return $return;
}
?>
moskalyuk at gmail dot com 21-Aug-2006 10:18
is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number
rontarrant at NO_SPAMsympatico dot ca 23-Jul-2006 07:15
Here's an even simpler pair of functions for finding out if a number is odd or even:

function IS_ODD($number) { return($number & 1); }

function IS_EVEN($number) { return(!($number & 1)); }

Test:
$myNumber = 151;

if(IS_ODD($myNumber))
    echo("number is odd\n");
else
    echo("number is NOT odd\n");

if(IS_even($myNumber))
    echo("number is even\n");
else
    echo("number is NOT even\n");

Results:
number is odd
number is NOT even
Miero 08-Jul-2006 09:31
function is_intval($a) {
    return ((string)$a === (string)(int)$a);
}

true for ("123", "0", "-1", 0, 11, 9011, 00, 0x12, true)
false for (" ", "", 1.1, "123.1", "00", "0x123", "123a", "ada", "--1", "999999999999999999999999999999999", false, null, '1 ')
andrea dot vacondio at gmail dot com 13-Dec-2005 07:52
Two simple functions using is_numeric:

<?php

 function is_odd($num){
     return (is_numeric($num)&($num&1));
 }

 function is_even($num){
     return (is_numeric($num)&(!($num&1)));
 }

 //examples
echo "1: odd? ".(is_odd(1)? "TRUE": "FALSE")."<br />";
//is_numeric(0) returns true
echo "0: odd? ".(is_odd(0)? "TRUE": "FALSE")."<br />";
echo "6: odd? ".(is_odd(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": odd? ".(is_odd("italy")? "TRUE": "FALSE")."<br />";
echo "null: odd? ".(is_odd(null)? "TRUE": "FALSE")."<br /><br />";
echo "1: even? ".(is_even(1)? "TRUE": "FALSE")."<br />";
echo "0: even? ".(is_even(0)? "TRUE": "FALSE")."<br />";
echo "6: even? ".(is_even(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": even? ".(is_even("italy")? "TRUE": "FALSE")."<br />";
echo "null: even? ".(is_even(null)? "TRUE": "FALSE")."<br />";

?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
"italy": odd? FALSE
null: odd? FALSE

1: even? FALSE
0: even? TRUE
6: even? TRUE
"italy": even? FALSE
null: even? FALSE
jamespam at hotmail dot com 08-Aug-2005 02:31
Here's a function to determine if a variable represents a whole number:

function is_whole_number($var){
  return (is_numeric($var)&&(intval($var)==floatval($var)));
}

just simple stuff...
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true
namik at hub-cafe dot net 29-Jul-2005 06:11
I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function).  Note that this doesn't properly handle decimals.

Example:
<?= number_suffix('1,021') ?> returns: 1,021st

Also, increasing the range above the condition statements increases efficiency.  That's almost 20% of the numbers between 0 and 100 that get to end early.

<?
  function number_suffix($number)
  {
    // Validate and translate our input
    if ( is_numeric($number) )
    {
      // Get the last two digits (only once)
      $n = $number % 100;
    } else {
     // If the last two characters are numbers
     if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches ) )
     {
       // Return the last one or two digits
       $n = array_pop($matches);
     } else {
       // Return the string, we can add a suffix to it
       return $number;
     }
    }
    // Skip the switch for as many numbers as possible.
    if ( $n > 3 && $n < 21 )
      return $number . 'th';

    // Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
    switch ( $n % 10 )
    {
      case '1': return $number . 'st';
      case '2': return $number . 'nd';
      case '3': return $number . 'rd';
      default:  return $number . 'th';
    }
  }
?>
maninblack00 at mail dot ru 29-Jul-2005 04:23
blazatek at wp dot pl wrote a function to check POST inputs for ASCII-keys or smth like that. there was an error while filtering $varvalue (it was only the value of the last filter 'addslashes')

here's the corrected function:
<?

function is_num ($num) {
      // .....
}

function test_post($tab) {
   $post = array();
   $post = $tab;
   foreach ($post as $varname => $varvalue) {
       echo $tab[$varname];
       if (empty($varvalue)) {
                 $post[$varname] = null;
       }
       elseif (is_num($varvalue)) {
                 $varvalue=trim($varvalue);
                 $varvalue=strip_tags($varvalue);
                 $varvalue=intval($varvalue);
                 $post[$varname]=addslashes($varvalue);
       }
       else {
                 $post[$varname]=NULL;
       }
   }//forech
    return $post;
}
?>

hope that correction is correct ;)
sebu 28-Jul-2005 04:37
Referring to previous post "Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')":

This is totally wrong!

This was the example code:

-----
  set_locale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return False
  is_numeric(12,25); // Return True
  is_float(12.25); //Return False
  is_float(12,25); //Return True
-----

This is nonsense!

- set_locale() does not exist, you must use setlocale() instead
- you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
- if you don't enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE

Corrected Example:

----
  setlocale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return True
  is_numeric("12,25"); // Return False
  is_float(12.25); //Return True
  is_float("12,25"); //Return False
----

Remarks:
- is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a "value") and the way PHP interpretes files is definitely _not_ affected by the locale
- is_float("12,25") is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats

And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.
ishmaelmakitla at yahoo dot com 20-May-2005 05:05
//hello mates I just wanted to bring this forth so that you may see what I have been to
I tried to validate a certain field (name ) on my project web site design so that the only field acceptable is alphabetic the problem was that it has to include a space as in "Makitla M.I"
now ctype_alpha returned false as this includes a space
the same with
<?
  if(!ctype_alpha($name)||!ctype_space($name))
?>

now this is what I did
<?
    $name=explode(" ",$name);//to get rid of space charecter
   $name=explode(".",$name)//to get rid of the dod
//finally I tested if the resulting $name is purely alphabetic
if(!ctype_alpha($name))
     {
        echo"the name entered contained some   unacceptable       charecters...please reenter";
     exit;
    }
//this solved my problem...hope this helps some of you!!
?>
Gregory Boshoff 14-May-2005 03:01
As mentioned above use the ctype character type functions to determine a strings type as ctype is faster. ctype_digit has far better benchmarks than is_numeric.

// Example:
$num = '888';
if(ctype_digit($num) === TRUE):
echo 'The string variable $num contains the decimal value '.$num;
endif;
Titouthat 27-Apr-2005 12:47
This function converts an input string into bool, int or float depending on its content.

<?php
function convert_type( $var )
{
    if( is_numeric( $var ) )
    {
        if( (float)$var != (int)$var )
        {
            return (float)$var;
        }
        else
        {
            return (int)$var;
        }
    }

    if( $var == "true" )    return true;
    if( $var == "false" )    return false;

    return $var;
}
?>

'90' return an int
'90.9' return a float
'true' return a bool
'90.0' return a int
lukesneeringer at gmail dot com 18-Mar-2005 08:32
Regarding renimar at yahoo's function to yield ordinal numbers, the function lacks one thing. It accounts for numbers in the teens only if the number is below 100. If you used this function and gave 212 as the input, it would give 212nd, and not 212th. (Also, checking for numbers between 11 and 13 is sufficient, since 14-19 yield th either way.)

Therefore,
<?php if ($num >= 11 and $num <= 19) ?>
should be changed to...
<?php if ($num % 100>= 11 and $num % 100 <= 13) ?>

It will then work perfectly all the time.

Here's the entire function with the one line changed:
<?php
function ordinalize($num) {
       if (!is_numeric($num))
               return $num;

       if ($num % 100 >= 11 and $num % 100 <= 13)
               return $num."th";
       elseif ( $num % 10 == 1 )
               return $num."st";
       elseif ( $num % 10 == 2 )
               return $num."nd";
       elseif ( $num % 10 == 3 )
               return $num."rd";
       else // $num % 10 == 0, 4-9
               return $num."th";
}
?>
codeslinger at compsalot dot com 17-Feb-2005 09:00
in version 4.3.10  I find the following

".73"  TRUE
"0.73"  TRUE
"+0.73"  TRUE

"+.73"   FALSE

I would not call it a bug, just something to be aware of.

-----

Also be aware that if you give php a huge number and then you convert it to a string you get

"INF"

if you pass that to mySQL etc. you could have a problem...
mdallaire at virtuelcom dot com 17-Nov-2004 04:23
Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:

    function new_is_unsigned_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_unsigned_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+$",$val);
    }

    function new_is_signed_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_signed_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+$",$val);
    }

It returns 1 if okay and returns nothing "" if it's bad number formating.
php at thefriedmans dot net 13-Oct-2004 10:19
is_numeric() in php5 returns false for strings with a leading decimal point:

<?php
is_numeric('5'); // true
is_numeric('5.5'); // true
is_numeric('.5'); // false

// but...

is_numeric('.0.5'); // true
?>

In certain situations, it may be useful to prepend a '0' to the string you're verifying with is_numeric():

<?php
if (is_numeric('0' . $user_input)) // ...
?>
renimar no spam at nospam yahoo dot com 03-May-2004 12:54
A little function to ordinalize numbers using is_numeric() and accounting for the numbers in the teens.

<?php
function ordinalize($num) {

        if (!is_numeric($num))
                return $num;

        if ($num >= 11 and $num <= 19)
                return $num."th";
        elseif ( $num % 10 == 1 )
                return $num."st";
        elseif ( $num % 10 == 2 )
                return $num."nd";
        elseif ( $num % 10 == 3 )
                return $num."rd";
        else
                return $num."th";

}

// Demo
for ($i=1; $i<=25; $i++) {
        print ordinalize($i) . " ";
}

// The loop returns:
// 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th
// 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd
// 23rd 24th 25th

?>
joe at kewlmail dot net 16-Jan-2004 03:12
Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:

$userString = "$654.4r5";

function numpass_filter($userString){
    $money = explode(".", $userString);
    //now $money[0] = "$645" and $money[1] = "4r5"

    //next remove all characters save 0 though 9
    //in both elements of the array
    $dollars = eregi_replace("[^0-9]", null, $money[0]);
    $cents = eregi_replace("[^0-9]", null, $money[1]);

    //if there was a decimal in the original string, put it back
    if((string)$cents!=null){
        $cents = "." . $cents;
    }

   $result = $dollars . $cents;

    return($result);
}

The output in this case would be '654.45'.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.
kouber at saparev dot com 24-Nov-2003 03:05
Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.

However, this behaviour is platform-specific.

http://www.php.net/manual/en/language.types.float.php

In such a case, it is suitable to use regular expressions:

function is_numeric_big($s=0) {
  return preg_match('/^-?\d+$/', $s);
}
blazatek at wp dot pl 20-Oct-2003 08:05
the best way to check whether
variable is numeric is to check its ascii code :)

function is_num($var)
{
    for ($i=0;$i<strlen($var);$i++)
    {
        $ascii_code=ord($var[$i]);

        if ($ascii_code >=49 && $asci_code <=57)
            continue;
        else
            return false;
    }

        return true;
}
this function can be usefull if you wont to chec eg $_POST

function test_post($tab)
{

        $post = array();
        $post=$tab;
        echo $tab["user_name"];
        foreach ($post as $varname => $varvalue)
        {
        if (empty($varvalue))
        {
            $post[$varname] = null;

        }elseif (is_num($varvalue))
        {
                        $post[$varname]=trim($varvalue);
    $post[$varname]=strip_tags($varvalue);
    $post[$varname]=intval($varvalue);
    $post[$varname]=addslashes($varvalue);
    }else
    {
                  $post[$varname]=NULL;
    }
            }
        }//forech
    return $post;
}
stew_wilde at hotmail dot com 07-Aug-2003 01:25
When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.

ie : two scripts test.php:

<?php
$val = trim($argv[1]);
echo is_string($val);
?>

and testwrapper.php:

<?php
$tmp = 5;
exec("php ./test.php ".$tmp);
?>

Executing testwrapper.php on the command line will echo nothing (ie false), and false will be returned regardless of any escaping of parameters or other such attempts to overcome this.  The solution then is to explicitly cast $val in test.php to be an int and then is_numeric will work.  But as stated the same test was performed using a string for $val and the is_string() function and the same thing occurs.  Not the end of the world, but something to be aware of :)
andi_nrw at hotmail dot com 12-Feb-2003 08:25
<?php
/* This function is not useful if you want
to check that someone has filled in only
numbers into a form because for example
4e4 and 444 are both "numeric".

I used a regular expression for this problem
and it works pretty good. Maybe it is a good
idea to write a function and then to use it.

$input_number = "444"; // Answer 1
$input_number = "44 "; // Answer 2
$input_number = "4 4"; // Answer 2
$input_number = "4e4"; // Answer 2
$input_number = "e44"; // Answer 2
$input_number = "e4e"; // Answer 2
$input_number = "abc"; // Answer 2
*/
$input_number = "444";

if (preg_match ("/^([0-9]+)$/", $input_number)) {
     print "Answer 1";
} else {
     print "Answer 2";
}
?>
php dot net at davidmcarthur dot com 17-Jan-2003 12:02
This is a little more explicit and won't break when the value can't be legally cast as an int

function is_intValued($var)
{
    // Determines if a variable's value is an integer regardless of type
    // meant to be an analogy to PHP's is_numeric()
    if (is_int($var)) return TRUE;
    if (is_string($var) and $var === (string)(int) $var) return TRUE;
    if (is_float($var) and $var === (float)(int) $var) return TRUE;
    else return FALSE;
}
redy dot r at madagascan dot com 10-Dec-2002 04:54
Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')

Example :
If at the beginning of your script, you declare :

<?php
set_locale(LC_NUMERIC,'fr');
?>

and after, you will get this :

<?php
is_numeric(12.25); // Return False
is_numeric(12,25); // Return True
is_float(12.25); //Return False
is_float(12,25); //Return True
?>

Because, for french language the decimal separator is ',' (Comma) instead of '.' (Dot).
martijnt at dataserve dot nl 02-Dec-2002 05:21
If you want to make sure that a variable contains only one or more numbers as in the range 0-9, you could use this:

eregi("[^0-9]",$var)

This checks your variable for anything that is NOT in the range 0-9.

If you use is_numeric() while checking an IP address, you should not be surprised if the following is accepted as a valid IP: 1e13.3.4.12e3 -> is_numeric() considers 1e13 and 12e3 as valid numeric values (which is correct).

Have fun.

Martijn Tigchelaar,
DataServe.
eagleflyer2 at lycos dot com 06-Sep-2002 01:02
Hi !
Many of you may have experienced that the 'is_numeric' function seems to fail always when form entries are checked against their variable type. So the function seems to return  'false' even if the form entry was aparently a number or numeric string.

The solution is pretty simple and no subroutines or fancy operations are necessary to make the 'is_numeric' function usable for form entry checks:

Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.

Just use the 'trim' function before 'is_numeric'.

Example:

$variable = trim($variable);
if (is_numeric($variable)
{...#do something#...}
else
{...#do something else#...}
mjbraca at NOSPAM dot hotmail dot com 24-Oct-2001 10:36
Some examples. Note that leading white space is OK, but not trailing white space, and there can't be white space between the "-" and the number.

is_numeric("1,000") = F
is_numeric("1e2")   = T
is_numeric("-1e-2") = T
is_numeric("1e2.3") = F
is_numeric("1.")    = T
is_numeric("1.2")   = T
is_numeric("1.2.3") = F
is_numeric("-1")    = T
is_numeric("- 1")   = F
is_numeric("--1")   = F
is_numeric("1-")    = F
is_numeric("1A")    = F
is_numeric(" 1")    = T
is_numeric("1 ")    = F
tvali at email dot ee 10-Oct-2001 12:53
I changed function sent by
"ealma@hotmail.com 18-May-2001 12:02"
a little bit (it should be faster now).

Here is some code that will detect large values for numeric and for PHP3.

function is_num($s) {
  for ($i=0; $i<strlen($s); $i++) {
    if (($s[$i]<'0') or ($s[$i]>'9')) {return false;}
  }
return true;
}

You can also check only the first char in string (($s[0])<'9')and($s[0]>'0')), since php converts string to numeric only from beginning to the last digit.
aulbach at unter dot franken dot de 17-Sep-2001 11:07
If you want to check, if a string will be converted into the exactly same number, you have to test the following:

if ( (string)(int)$val === (string)$val ) ...

This is not the same as

if ( is_numeric($val) ) ...

cause

<?php

$a="0000001";
if ( is_numeric($a) ) echo "a is numeric";
if ( (string)(float)$a !== (string)$a) echo "a cannot be converted 100%-correctly";
?>

will output:
a is numeric
a cannot be converted 100%-correctly

Ok, ok, I know. This is a hysteric type-check. It depends on the type of application, if you use it. The aim should always be, that the user could be warned, if the value cannot be stored in the way, the user types it into.

Why? Therefore is the following example:
If you set
$a="1E+17";
the above script says that it is all right.

But then we want to convert to INT, not FLOAT. is_numeric() doesn't distinct between INT and FLOAT, so a is_numeric('1E+17') is true, but the Integer of it returns 1, which isn't perhaps, what the user expects.
is_null
is_object
Функции для работы с переменными


Проверяет, является ли переменная объектом

is_numeric
is_real
Функции для работы с переменными
PHP Manual

is_object

(PHP 4, PHP 5)

is_object — Проверяет, является ли переменная объектом

Описание

bool is_object ( mixed $var )

Проверяет, является ли данная переменная объектом.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является объектом, или FALSE в противном случае.

Примеры

Пример #1 Пример использования is_object()

<?php
// Объявляем простую функцию, которая возвращает
// массив из нашего объекта
function get_students($obj)
{
    if (!is_object($obj)) {
        return false;
    }

    return $obj->students;
}

// Создаем новый экземпляр класса
// и заполняем некоторыми значениями

$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');

var_dump(get_students(null));
var_dump(get_students($obj));
?>

Примечания

Замечание:

Функция вернет FALSE, если применяется к десериализованному объекту, у которого отсутствует объявление класса (даже если gettype() возвращает object).

Смотрите также

  • is_bool() - Проверяет, является ли переменная булевой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_string() - Проверяет, является ли переменная строкой
  • is_array() - Определяет, является ли переменная массивом

User Contributed Notes

mark at not4you dot com 21-Sep-2011 12:23
Unserializes data as returned by the standard PHP serialize() function. If the unserialized object is not an array, it will be converted to one, particularily useful if it returns a __PHP_Incomplete_Class.

<?php
/**
 *
 * @param string $data Serialized data
 *
 * @return array    Unserialized array
 */
function unserialize2array($data) {
    $obj = unserialize($data);
    if(is_array($obj)) return $obj;
    $arr = array();
    foreach($obj as $k=>$v) {
        $arr[$k] = $v;
    }
    unset($arr['__PHP_Incomplete_Class_Name']);
    return $arr;
}
?>
peter dot nagel at portavita dot nl 22-Mar-2011 01:46
Note: is_object(null) returns false

This should actually be part of the input/output specification at the top of this page.
will 20-Mar-2010 02:36
Just discovered:
is_a  (  object $object  ,  string $class_name  )
Which checks if the object is of this class or has this class as one of its parents

Which seems to do what a lot here are trying to replicate
ldean at saleamp dot com 01-Sep-2009 07:16
Use instanceof() to check for a specific type.
Senthryl 17-Mar-2009 06:03
Cleaning it up even more:

<?php
function is_obj(&$object, $className = null, $caseSensitive = true) {
    return is_object($object) && (!is_string($className) || preg_match('/^'.$className.'$/D'.($caseSensitive ? '' : 'i'), get_class($object)));
}
?>
gregdangelo at gmail dot com 14-Apr-2008 12:03
cleaned up peter's code... use only one return statement

function is_obj( &$object, $check=null, $strict=true )
{
$result = false;
  if (is_object($object)) {
      if ($check == null) {
          $result =  true;
      } else {
           $object_name = get_class($object);
           $result =  ($strict === true)?
               ( $object_name == $check ):
               ( strtolower($object_name) == strtolower($check) );
      }
  }
return $result;
}
peter at i-node dot com dot br 20-May-2006 01:03
Optimizing the is_obj() from corychristison, and with the "return false" suggested by xixulon.

function is_obj( &$object, $check=null, $strict=true )
{
  if (is_object($object)) {
      if ($check == null) {
          return true;
      } else {
           $object_name = get_class($object);
           return ($strict === true)?
               ( $object_name == $check ):
               ( strtolower($object_name) == strtolower($check) );
      }
  } else {
      return false;
  }
}
corychristison[aT-]lavacube(.dot)com 02-Feb-2005 05:06
Thank you victor AT fourstones DOT net.

I have written a function to do what victor has suggested, with the ease of use of is_object. It can be used to replace is_object(), but has an extra field [$check], to compare to a certain name. If $check is left empty, it will just check if &$object is an object.

<?php

function is_obj( &$object, $check=null, $strict=true )
{
    if( $check == null && is_object($object) )
    {
        return true;
    }
    if( is_object($object) )
    {
        $object_name = get_class($object);
        if( $strict === true )
        {
            if( $object_name == $check )
            {
                return true;
            }
        }
        else
        {
            if( strtolower($object_name) == strtolower($check) )
            {
                return true;
            }
        }
    }
}

?>

This could probably be cleaned up, but it's spaced out to be easy to read.
victor AT fourstones DOT net 01-Jan-2005 03:49
er, I don't think that's right, especially if calling from another object instance:

<?

function test_this()
{
    $c2 = new C2();
    $c2->func();
    $c1 = new C1();
    $c1->func();
    C1::func();
}

class C2
{
    function func()
    {
        C1::func();
    }
}

class C1
{
    function func()
    {
        if( isset($this) )
        {
            if( strtolower(get_class($this)) != 'c1' )
                print("oops\n");
            else
                print("this is ok\n" );
        }
        else
        {
            print("static call\n");
        }
    }
}

test_this();
?>

yields:
---------- run-php ----------

oops
this is ok
static call
corychristison[aT-]lavacube(.dot)com 01-Jan-2005 07:47
You can use is_object($this) to detect if the function is being called via instance or procedure.

Example:

<?php

class mrClass {

    function test( )
    {
        if( is_object($this) )
        {
         // do something for instance method
            echo 'this is an instance call <br />' . "\n";
        }
        else
        {
         // do something different for procedural method
            echo 'this is a procedure call <br />' . "\n";
        }
    }

}

$inst = new mrClass();
$inst->test();

mrClass::test();

?>

This would output:
this is an instance call <br />
this is a procedure call <br />

:-) Happy coding!
lbjay can be emailed at reallywow dot com 02-May-2003 12:18
I'm not even sure how to articulate this, so I'm going to just include test code. Maybe someone else will someday wonder the same thing.

<?
    error_reporting(E_ALL);
    class testParent
    {
        var $child;

        function testParent()
        {
            $this->child = new testChild();
        }
    }

    class testChild
    {
        function testChild()
        {
        }
    }

    $parent = new testParent();
    $parent2 = 'foobar';

    print join(',', Array(
        is_object($parent) ? 'yes' : 'no',
        is_object($parent->child) ? 'yes' : 'no',
        is_object($parent2) ? 'yes' : 'no',
        is_object($parent2->child) ? 'yes' : 'no'
    ));

?>

This prints "yes,yes,no,no". Basically this shows that you can use is_object to test if the child object is an object without worrying about an error if the parent object isn't an object either.
is_numeric
is_real
Функции для работы с переменными


Псевдоним is_float

is_object
is_resource
Функции для работы с переменными
PHP Manual

is_real

(PHP 4, PHP 5)

is_real — Псевдоним is_float()

Описание

Эта функция является псевдонимом: is_float().

User Contributed Notes

charlescbe16 at gmail dot com 24-Jul-2010 12:53
is_float — Finds whether a variable is a floatDescriptionbool is_float ( mixed var )

Finds whether the given variable is a float.

example:
<?php
$float=50.97;
if(is_float($float))
{
    echo $float."is a float";
}
else
{
    echo $float. "is not a float";
}
?>

output:
50.97 is a float
is_object
is_resource
Функции для работы с переменными


Проверяет, является ли переменная ресурсом

is_real
is_scalar
Функции для работы с переменными
PHP Manual

is_resource

(PHP 4, PHP 5)

is_resource — Проверяет, является ли переменная ресурсом

Описание

bool is_resource ( mixed $var )

Проверяет, является ли данная переменная ресурсом.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является ресурсом, или FALSE в противном случае.

Примеры

Пример #1 Пример использования is_resource()

<?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('Ошибка соединения : ' . mysql_error());
}

?>

Смотрите также

  • "Тип "ресурс""
  • get_resource_type() - Возвращает тип ресурса

User Contributed Notes

btleffler [AT] gmail [DOT] com 12-May-2011 01:55
I was recently trying to loop through some objects and convert them to arrays so that I could encode them to json strings.

I was running into issues when an element of one of my objects was a SoapClient. As it turns out, json_encode() doesn't like any resources to be passed to it. My simple fix was to use is_resource() to determine whether or not the variable I was looking at was a resource.

I quickly realized that is_resource() returns false for two out of the 3 resources that are typically in a SoapClient object. If the resource type is 'Unknown' according to var_dump() and get_resource_type(), is_resource() doesn't think that the variable is a resource!

My work around for this was to use get_resource_type() instead of is_resource(), but that function throws an error if the variable you're checking isn't a resource.

So how are you supposed to know when a variable is a resource if is_resource() is unreliable, and get_resource_type() gives errors if you don't pass it a resource?

I ended up doing something like this:

<?php

function isResource ($possibleResource) { return !is_null(@get_resource_type($possibleResource)); }

?>

The @ operator suppresses the errors thrown by get_resource_type() so it returns null if $possibleResource isn't a resource.

I spent way too long trying to figure this stuff out, so I hope this comment helps someone out if they run into the same problem I did.
tacomage at NOSPAM dot devilishly-deviant dot net 06-Aug-2004 06:10
Note that the use of is_resource isn't necessary in the example.  mysql_connect (along with any other function that would return a resouce, I imagine) returns false on failure, so the same results could be obtained with:
<?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!$db_link) {
   die('Can\'t connect : ' . mysql_error());
}

?>

Or even:
<?php
  $db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass')
  or die('Can\'t connect : ' . mysql_error());
}
?>

You'd be more likely to use is_resource AFTER the initial conection, to make sure the variable you intend to use as a resource is, in fact, a connection resource.  You might also use is_resource as a sanity-check prior to serializing an object, since resource variables can't be serialized.
is_real
is_scalar
Функции для работы с переменными


Проверяет, является ли переменная скалярным значением

is_resource
is_string
Функции для работы с переменными
PHP Manual

is_scalar

(PHP 4 >= 4.0.5, PHP 5)

is_scalar — Проверяет, является ли переменная скалярным значением

Описание

bool is_scalar ( mixed $var )

Проверяет, является ли данная переменная скалярным значением.

Скалярными переменными - это переменные с типами integer, float, string и boolean. Типы array, object и resource не являются скалярными.

Замечание:

is_scalar() не считает переменные типа resource скалярными, так как ресурсы являются абстрактными типами данных, которые в настоящее время основаны на целом типе. Не стоит полагаться на данную деталь реализации, так как она может измениться.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является скалярным значением, или FALSE в противном случае.

Примеры

Пример #1 Пример использования is_scalar()

<?php
function show_var($var)
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
show_var($proteins)

?>

Результат выполнения данного примера:

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

Смотрите также

  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_real() - Псевдоним is_float
  • is_string() - Проверяет, является ли переменная строкой
  • is_bool() - Проверяет, является ли переменная булевой
  • is_object() - Проверяет, является ли переменная объектом
  • is_array() - Определяет, является ли переменная массивом

User Contributed Notes

webmaster at oehoeboeroe dot nl 04-May-2009 12:15
Here's a little function that will test whether a variable can be used as offset to an array.

<?php
function is_offset(&$var) {
    return (is_scalar($var) || is_null($var)) && !is_resource($var);
}
?>

The resource check is currently redundant, but according to the manual that may change in the future.
31-Jul-2006 08:59
Another warning in response to the previous note:
> just a warning as it appears that an empty value is not a scalar.

That statement is wrong--or, at least, has been fixed with a later revision than the one tested.  The following code generated the following output on PHP 4.3.9.

CODE:
<?php
    echo('is_scalar() test:'.EOL);
    echo("NULL: "      . print_R(is_scalar(NULL),     true) . EOL);
    echo("false: "    . print_R(is_scalar(false),   true) . EOL);
    echo("(empty): "  . print_R(is_scalar(''),      true) . EOL);
    echo("0: "         . print_R(is_scalar(0),       true) . EOL);
    echo("'0': "      . print_R(is_scalar('0'),     true) . EOL);
?>

OUTPUT:
is_scalar() test:
NULL:
false: 1
(empty): 1
0: 1
'0': 1

THUS:
   * NULL is NOT a scalar
   * false, (empty string), 0, and "0" ARE scalars
docey 20-May-2006 07:02
just a warning as it appears that an empty value is not a scalar.

although the manual says scalars are:
-> integers (eg. 243)
-> floats (eg. 14.4)
-> strings (eg "this is a string")
-> booleans (eg true or false)

this might seem easy but rembere that empty values are:
-> NULL
-> false
-> empty string
-> 0
-> "0"

thus the true list of scalars must be:
-> integers large then zero
-> floats larger then zero
-> strings with a lenght large then zero
-> string that do not contain only the number 0
-> boolean value of true.

especialy the boolean value false can be tricky as true is
considerd to be scalar but false is not. or a string that is
initialized with a zero lenght here's an example.

$string = ""; //initialize our string.

function store_var($var)
{
 if(is_scalar($var)){
  print("our var is a scalar.");
 }else{
  print("you tried to store something else here.");
 }
}

$this->store_var($string); // does not work as expected

this might be usefull when you create method to store a
variable inside a class but do not want to store other stuff
like object, arrays or resources, but storing an empy value
is oke. then is_scalar does not work as empty values are
incorrectly not seens as a bool, string, integer or float.

this is an important downside to is_scalar wich might cause
some people to loose there hair from headscrachting.

this might be added to the manual as a warning or something.
efelch at gmail dot com 17-Aug-2005 02:31
A scalar is a single item or value, compared to things like arrays and objects which have multiple values. This tends to be the standard definition of the word in terms of programming. An integer, character, etc are scalars. Strings are probably considered scalars since they only hold "one" value (the value represented by the characters represented) and nothing else.
Dr K 14-Aug-2005 03:48
Having hunted around the manual, I've not found a clear statement of what makes a type "scalar" (e.g. if some future version of the language introduces a new kind of type, what criterion will decide if it's "scalar"? - that goes beyond just listing what's scalar in the current version.)

In other lanuages, it means "has ordering operators" - i.e. "less than" and friends.

It (-:currently:-) appears to have the same meaning in PHP.
popanowel HAT hotmailZ DOT cum 14-May-2004 12:31
Hi ... for newbees here, I just want to mention that reference and scalar variable aren't the same. A reference is a pointer to a scalar, just like in C or C++.

<? php  // simple reference to scalar

  $a = 2;
  $ref = & $a;

  echo "$a <br> $ref";

?>
this should print out: "2 <br> 2".

Scalar class also exists. Look below:
<? php

  class Object_t {

     var $a;

     function Object_t ()  // constructor
     {
        $this->a = 1;
     }

  }

  $a = new Object_t; // we define a scalar object

  $ref_a = &a;

  echo "$a->a <br> $ref->a";

?>
again, this should echo: "1 <br> 1";

Here is another method isued in OOP to acheive on working only over reference to scalar object. Using this, you won't ever have to  ask yourself if you work on a copy of the scalar or its reference. You will only possess reference to the scalar object. If you want to duplicate the scalar object, you will have to create a function for that purpose that would read by the reference the values and assign them to another scalar of the same type... or an other type, it is as you wish at that moment.
<?php

  class objet_t {
     var $a;

     function object_t
     {
        $this->a = "patate_poil";
     }
  }

   function &get_ref($object_type)
   {
      // here we create a scalar object in memory
      // and we return it by reference to the calling
      // control scope.
      return &new $object_type;
   }

   $ref_object_t = get_ref(object_t);

   echo "$ref_object_t->a <br>";

?>
this should echo: "patate_poit <br>".

The only thing that I try to demonstrate is that scalar variable ARE object in memory while a reference is usualy a variable (scalar object) that contain the address of another scalar object, which contain the informations you want by using the reference.

Good Luck!

otek is popanowel HAT hotmailZ DOT cum
bps7j at yahoNOSPAMo.com 08-Feb-2004 09:56
is_scalar(null) is false.  Apparently a variable needs to have a value to be considered a scalar.
is_resource
is_string
Функции для работы с переменными


Проверяет, является ли переменная строкой

is_scalar
isset
Функции для работы с переменными
PHP Manual

is_string

(PHP 4, PHP 5)

is_string — Проверяет, является ли переменная строкой

Описание

bool is_string ( mixed $var )

Проверяет, является ли данная переменная строкой.

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является строкой, и FALSE в противном случае.

Примеры

Пример #1 Пример использования is_string()

<?php
if (is_string("23")) {
    echo "строка\n";
} else {
    echo "не строка\n";
}
var_dump(is_string('abc'));
var_dump(is_string("23"));
var_dump(is_string(23.5));
var_dump(is_string(true));
?>

Результат выполнения данного примера:

строка
bool(true)
bool(true)
bool(false)
bool(false)

Смотрите также

  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_bool() - Проверяет, является ли переменная булевой
  • is_object() - Проверяет, является ли переменная объектом
  • is_array() - Определяет, является ли переменная массивом

User Contributed Notes

slicky at newshelix dot com 20-Mar-2001 05:06
Be aware that this function could result into unwanted results if you check single chars in an array.
For instance:
You have a simple string and want to repeat this string evertime it ends.

<?php
for ($i=0; $i < strlen($string);$i++){
    if(!is_string($key[$x]))
        $x = 0;
    echo $key[$x];
    $x++;
}
?>

This will print you out the key, but won't iterate it since $x won't be reset. is_string function will give out true at element in that string, even if it doesn't exist. for instance is_string $key[1000] while your string is just 10chars long.
However this doesn't matter just use $key[$x] == '' instead.
Of course you won't use this to iterate a string, but you might come across something where this get useful, for instance for a en/decrypt engine.
is_scalar
isset
Функции для работы с переменными


Определяет, была ли установлена переменная значением отличным от NULL

is_string
print_r
Функции для работы с переменными
PHP Manual

isset

(PHP 4, PHP 5)

isset — Определяет, была ли установлена переменная значением отличным от NULL

Описание

bool isset ( mixed $var [, mixed $... ] )

Определяет, была ли установлена переменная значением отличным от NULL

Если переменная была удалена с помощью unset(), то она больше не считается установленной. isset() вернет FALSE, если проверяемая переменная имеет значение NULL. Следует помнить, что NULL-байт ("\0") не является эквивалентом константе PHP NULL.

Если были переданы несколько параметров, то isset() вернет TRUE только в том случае, если все параметры определены. Проверка происходит слева направо и заканчивается, как только будет встречена неопределенная переменная.

Список параметров

var

Проверяемая переменная.

...

Другая переменная ...

Возвращаемые значения

Возвращает TRUE, если var определена и значение отличное от NULL, и FALSE в противном случае.

Список изменений

Версия | Описание
5.4.0 | Проверка нечислового индекса строки теперь возвращает FALSE.

Примеры

Пример #1 Пример использования isset()

<?php

$var = '';

// Проверка вернет TRUE, поэтому текст будет напечатан.
if (isset($var)) {
    echo "Эта переменная определена, поэтому меня и напечатали.";
}

// В следующем примере мы используем var_dump для вывода
// значения, возвращаемого isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?>

Функция также работает с элементами массивов:

<?php

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// Элемент с ключом 'hello' равен NULL, поэтому он считается неопределенным
// Если Вы хотите проверить существование ключей со значением NULL, используйте:
var_dump(array_key_exists('hello', $a)); // TRUE

// Проверка вложенных элементов массива
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>

Пример #2 isset() и строковые индексы

В PHP 5.4 был изменен способ обработки строковых индексов в isset().

<?php
$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));
?>

Результат выполнения данного примера в PHP 5.3:

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Результат выполнения данного примера в PHP 5.4:

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

Примечания

Внимание

isset() работает только с переменными, поэтому передача в качестве параметров любых других значений приведет к ошибке парсинга. Для проверки определения констант используйте функцию defined().

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

При использовании isset() на недоступных свойствах объекта, будет вызываться перегруженный метод __isset(), если он существует.

Смотрите также

  • empty() - Проверяет, пуста ли переменная
  • __isset()
  • unset() - Удаляет переменную
  • defined() - Проверяет существование указанной именованной константы
  • Таблица сравнения типов
  • array_key_exists() - Проверяет, присутствует ли в массиве указанный ключ или индекс
  • is_null() - Проверяет, является ли значение переменной равным NULL
  • Оператор управления ошибками @

User Contributed Notes

Daniel Klein 29-May-2012 03:49
How to test for a variable actually existing, including being set to null. This will prevent errors when passing to functions.

<?php
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

$myvar;
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

$myvar = null;
// true
var_export(
  array_key_exists('myvar', get_defined_vars())
);

unset($myvar);
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

if (array_key_exists('myvar', get_defined_vars())) {
  myfunction($myvar);
}
?>

Note: you can't turn this into a function (e.g. is_defined($myvar)) because get_defined_vars() only gets the variables in the current scope and entering a function changes the scope.
glitch dot mr at gmail dot com 23-May-2012 06:02
This is very simple implementation of issetor() for PHP. It works like ?? in C#, // in Perl (it can access undefined hash keys without it nevertheless) or ? in CoffeeScript (also can access undefined hash keys too). You shouldn't use directly $_GET['something'] (it can generate E_NOTICEs in case somebody would try hacking your site), but isset($_GET['something']) ? $_GET['something'] : '' is long for many people (for so common operation). This alternative makes using superglobals easier.

<?php
function issetor(&$variable, $or = NULL) {
    return $variable === NULL ? $or : $variable;
}
?>

Now you can do:

<?php
echo issetor($_GET['a']);       // $_GET['a'] or NULL
echo issetor($_GET['b'], '42'); // $_GET['b'] or 42
echo issetor($_GET['c']['d']);  // $_GET['c']['d'] or NULL
?>

This code doesn't generate notices in case variable doesn't exist.
david at thegallagher dot net 09-Mar-2012 02:20
Just to reiterate on what everyone has already said before, you should not use wrapper functions for isset. Using a wrapper function will generate a Notice unless you pass the unset variable by reference, in which case it is the equivalent to writing using $var === null (which is a lot faster). Even if you do pass the variable by reference, you could still get notices using multidimensional arrays where isset() would silently return false.
qeremy 07-Mar-2012 03:36
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _isset($val) { return isset($val); }
?>
Dr. McKay 09-Feb-2012 05:18
It's worth noting that if a GET variable is passed without a variable, isset will return true on it.

http://www.example.com/?somevar

<?php
if(isset($_GET['somevar'])) {
    // this is true and will be executed
}
?>
dfugi9488 at yahoo dot com 08-Jan-2012 07:56
it is also worth noting that isset() will return FALSE when its argument is a class attribute that is simply defined with no value given. e.g.

<?php

class Test
{
    public static $set;

    public static function setTest() {
        if(!isset(self::$set)) {
            return "not set";
        }else {
            return "set";
        }
    }
}

echo Test::setTest(); //returns "not set"

?>
john at darven dot co dot uk 14-Nov-2011 02:37
It is worth noting that in order to check for the existence of a key within an array, regardless of it's contents one should use array_key_exists() not isset().

isset() will (correctly) return false if the value of your array key is null, which may be a perfectly valid condition.
gonchalox at gmail dot com 25-Jun-2011 04:33
Useful to check if the variable have some value...specially for GET POST variables

<?php
function isset_or(&$check, $alternate = NULL)
{
    return (isset($check)) ? (empty($check) ? $alternate : $check) : $alternate;
}

function getGETPOST($var)
{
      return isset_or($_GET[$var],isset_or($_POST[$var],"Empty"));
}
?>

Example
echo getGETPOST('na'); //Find the na varriabl by get and post
benallfree at gmail dot com 21-Apr-2011 06:21
isset() returns TRUE if a value is NULL. That seems wrong to me as there is no way to distinguish between a value set to NULL and a truly undefined value.

If you have this problem inside a class, there is a fix:

<?php
class T
{
  function __isset($att)
  {
    $props = get_object_vars($this);
    return array_key_exists($att, $props);
  }
}

$x = new T();
$x->foo_exists = 4;

var_dump(isset($x->foo_exists)); // TRUE
var_dump(isset($x->bar_exists)); // FALSE
?>
[EDITOR thiago NOTE: This snippet has improvements by "Paul Lashbrook"]
Cuong Huy To 23-Mar-2011 05:08
1) Note that isset($var) doesn't distinguish the two cases when $var is undefined, or is null. Evidence is in the following code.

<?php
unset($undefined);
$null = null;
if (true === isset($undefined)){echo 'isset($undefined) === true'} else {echo 'isset($undefined) === false'); // 'isset($undefined) === false'
if (true === isset($null)){echo 'isset($null) === true'} else {echo 'isset($null) === false');              // 'isset($null)      === false'
?>

2) If you want to distinguish undefined variable with a defined variable with a null value, then use array_key_exist

<?php
unset($undefined);
$null = null;

if (true !== array_key_exists('undefined', get_defined_vars())) {echo '$undefined does not exist';} else {echo '$undefined exists';} // '$undefined does not exist'
if (true === array_key_exists('null', get_defined_vars())) {echo '$null exists';} else {echo '$null does not exist';}                // '$null exists'
?>
francois vespa 22-Dec-2010 07:21
Now this is how to achieve the same effect (ie, having isset() returning true even if variable has been set to null) for objects and arrays

<?php

// array

$array=array('foo'=>null);

return isset($array['foo']) || array_key_exists('foo',$array)
  ? true : false ; // return true

return isset($array['inexistent']) || array_key_exists('inexistent',$array)
  ? true : false ; // return false

// static class

class bar

{
  static $foo=null;
}

return isset(bar::$foo) || array_key_exists('foo',get_class_vars('bar'))
  ? true : false ; // return true

return isset(bar::$inexistent) || array_key_exists('inexistent',get_class_vars('bar'))
  ? true : false ; // return false

// object

class bar
{
    public $foo=null;
}

$bar=new bar();

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

// stdClass

$bar=new stdClass;
$bar->foo=null;

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

?>
Raphael Campos 06-Jul-2010 04:10
Keep in mind that an empty string is not null, and an empty GET or POST field returns an empty string instead of NULL, thus...

file.php?foo

<?php
$a = '';
$b = NULL;

isset($a); // => TRUE
isset($b); // => FALSE
(isset($a) && $a === ''); // => TRUE
?>

With that in mind, one probably would use isset() to check if a variable has been declared somehow and it's value is not the special value NULL. If you want to check if the value is an empty string, it's probably a better idea to check it literally:

<?php
(isset($a) && $a == '') // => TRUE
?>
i [at] nemoden [dot] com 14-Jun-2010 11:48
Simple, but very useful:

<?php
function issetOr($var, $or = false) {
  return isset($var) ? $var : $or;
}
?>

Some examples:
<?php
$a = '1';
$b = '2';
echo issetOr($a,issetOr($b,3)); // 1
?>
<?php
$b = '2';
echo issetOr($a,issetOr($b,3)); // 2
?>
<?php
echo issetOr($a,issetOr($b,3)); // 3
?>
senthil sent222 at gmail dot com 26-May-2010 07:14
just as note: if you want to check isset() with string variables
<?php
$var='string value';
if(isset($var['somekey']){          //it will be treated as true
echo 'This will be printed';
}
?>
mohd at bahrain dot bz 10-Jan-2010 04:02
HTML table to displays how different variables are evaluated ..
<?php
$TEST_VAR = array(
'|NULL' => NULL,
'|"NULL"' => "NULL",
'|false' => false,
'|true' => true,
'|FALSE' => FALSE,
'|TRUE' => TRUE,
'|"false"' => "false",
'|"true"' => "true",
'|0' => 0,
'|1' => 1,
'|"0"' => "0",
'|"1"' => "1",
'|NotExsist' => $notexist,
'|""' => "",
'|array()' => array(),
'|array("A", "B")' => array("A", "B"),
'|$_GET' => $_GET,
'|$_POST' => $_POST,
'|count($_GET)' => count($_GET),
'|count($_POST)' => count($_POST),
'|1.5' => 1.5,
'|1e7' => 1e7,
'|-14' => -14,
'|005' => 005,
'|(object) "Halo"' => (object) "Halo",
'|fopen("php://stdin")' => fopen("php://stdin", "r")
);
$CASE = array(
'$var != ""',
'!isset($var)',
'!is_null($var)',
'$var != NULL',
'$var !== NULL',
'!empty($var)',
'$var != true',
'$var !== true',
'$var != false',
'$var !== false',
'!is_bool($var)',
'!is_numeric($var)',
'!is_int($var)',
'!is_float($var)',
'!is_array($var)',
'!is_object($var)',
'!is_resource($var)',
);

$T = 'TRUE'; $F = 'FALSE';

/* CSS */
$lf = "\r\n"; $ds = "  "; $gt = '>'; $q = '"'; $ac = ' align="center"';
$t = ' style='; $b = 'background-'; $c = 'color:'; $c1 = $t.$q.$b.$c.'#EBEBEB'.$q;
$w = 'white-space:nowrap;';
$br = '<br />'; $s1 = '<span'; $s2 = '</span>';
$T = $s1.$t.$q.$c.'#0000FF'.$q.$gt.$T.$s2; $F = $s1.$t.$q.$c.'#FF0000'.$q.$gt.$F.$s2;
$t1 = '<table border="1" cellspacing="2" cellpadding="5"'.$t.$q;
$t1 .= 'font-weight:bold; font-size:9px; font-family:Tahoma,Arial;'.$q.$gt;
$t2 = '</table>'; $r1 = '<tr'; $r2 = '</tr>'; $d1 = '<td'; $d2 = '</td>';

$K = array_keys($TEST_VAR); $n = count($K); $m = count($CASE);

$da = $ds.$ds.$d1.$ac.$gt;
$dz = $d2.$lf;

echo $t1.$lf;

$v = 14;
for ($i=0; $i<$n; $i++) {
if ( ($i != ($n-1)) && ($v > 13) ) {
    echo $ds.$r1.$t.$q.$b.$c.'#CCCCCC'.$q.$gt.$lf;
    echo $ds.$ds.$d1.$ac.$gt
    .'$VAR/IF NOT'
    .$dz;
    for ($j=0; $j<$m; $j++) {
        echo $ds.$ds.$d1.$ac.$t.$q.$w.$q.$gt
        .htmlspecialchars($CASE[$j],ENT_QUOTES)
        .$dz;
    }
    echo $ds.$ds.$d1.$ac.$gt
    .'$VAR/IF NOT'
    .$dz;
    echo $ds.$r2.$lf;
    $v = 0;
}
$v += 1;

echo $ds.$r1.(($ch=(($ch)?false:true))?'':$c1).$gt.$lf;

echo $ds.$ds.$d1.$ac.$t.$q.$w.$q.$gt
.(htmlspecialchars(trim($K[$i],"|"),ENT_QUOTES))
.$dz;

/* ($var != "")? */
echo $da
.(( $TEST_VAR[($K[$i])] != "" ) ? $T:$F)
.$dz;
/* (!isset($var))? */
echo $da
.(( !isset($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* (!is_null($var))? */
echo $da
.(( !is_null($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* ($var != NULL)? */
echo $da
.(( $TEST_VAR[($K[$i])] != NULL ) ? $T:$F)
.$dz;
/* ($var !== NULL)? */
echo $da
.(( $TEST_VAR[($K[$i])] !== NULL ) ? $T:$F)
.$dz;
/* (!empty($var))? */
echo $da
.(( !empty($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* ($var != true)? */
echo $da
.(( $TEST_VAR[($K[$i])] != true ) ? $T:$F)
.$dz;
/* ($var !== true)? */
echo $da
.(( $TEST_VAR[($K[$i])] !== true ) ? $T:$F)
.$dz;
/* ($var != false)? */
echo $da
.(( $TEST_VAR[($K[$i])] != false ) ? $T:$F)
.$dz;
/* ($var !== false)? */
echo $da
.(( $TEST_VAR[($K[$i])] !== false ) ? $T:$F)
.$dz;
/* (!is_bool($var))? */
echo $da
.(( !is_bool($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* (!is_numeric($var))? */
echo $da
.(( !is_numeric($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* (!is_int($var))? */
echo $da
.(( !is_int($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* (!is_float($var))? */
echo $da
.(( !is_float($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* (!is_array($var))? */
echo $da
.(( !is_array($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* (!is_object($var))? */
echo $da
.(( !is_object($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
/* (!is_resource($var))? */
echo $da
.(( !is_resource($TEST_VAR[($K[$i])]) ) ? $T:$F)
.$dz;
echo $ds.$ds.$d1.$ac.$t.$q.$w.$q.$gt
.(htmlspecialchars(trim(trim($K[$i],"|")),ENT_QUOTES))
.$dz;

echo $ds.$r2.$lf;

}
echo $t2.$lf;
@fclose($file_handle);

function n0t($var=false) {
    return (( (!isset($var)) || ((!$var) && ($var !== "0")) )? true: false);
}
?>
Robert dot VanDell at cbs dot com 08-Jan-2010 02:19
Here's a nice little function that I use everywhere that'll help with setting alternate values so you don't have a bunch of situations like:

<?php
if(isset($a))
{
    $b = $a;
}
else
{
    $b = "default";
}

function isset_or(&$check, $alternate = NULL)
{
    return (isset($check)) ? $check : $alternate;
}

// Example usage:
$first_name = isset_or($_POST['first_name'], "Empty");
$total        = isset_or($row['total'], 0);

?>
Anl zselgin 14-Aug-2009 03:30
Note: Because this is a language construct and not a function, it cannot be called using variable functions.

So why it is under "Variable handling Functions". Maybe there should be some good documentation field for language constructs.
alexander dot holmback at gmail dot com 23-Mar-2009 02:48
<?php
$abc = 'test';
?>

$abc is not an array, but you can use the brackets to reach a single byte in the string using numbers.

<?php
$abc[0] = 't'        //first letter in 'test'
$abc[1] = 'e'        //second letter in 'test'
$abc[2] = 's'        //third letter in 'test'
$abc[3] = 't'        //fourth letter in 'test'
?>

When using $abc['astring'], php will cast any string to 0 (see type juggling) which result in the letter 't' which indeed is set.

isset($abc['astring'] = isset($abc[0]) = true.
yarco dot w at gmail dot com 18-Mar-2009 12:30
just following what edsko said, it is very amazing when you use isset to check a string. look at what i found:

[yarco@localhost ~]$ php -a
Interactive shell

php > $abc = 'test';
php > print isset($abc['e']) ? 'yes' : 'no';
yes
php > print isset($abc['d']) ? 'yes' : 'no';
yes
php > print isset($abc['aaaaaaa']) ? 'yes' : 'no';
yes
php > print isset($abc[23]) ? 'yes' : 'no';
no

If you use string as index, isset would always return true.
(but i don't think it should return true)
Ashus 08-Dec-2008 01:05
Note that array keys are case sensitive.

<?php
$ar['w'] = true;

var_dump(isset($ar['w']),
      isset($ar['W']));
?>

will report:
bool(true) bool(false)
jwvdveer at gmail dot com 10-Nov-2008 10:29
Here a short note on the function tomek wrote:
Don't use it, because it is still better to use !$var than !is($var).

Some comments on the body of the function:
<?php
function is($var)
{
if (!isset($var)) return false; # Variable is always set... Otherwise PHP would have thrown an error on call.
if ($var!==false) return true; # So, 0, NULL, and some other values may not behave like isNot? And what about the difference between a class and NULL?
return false;
}
?>

The reason why you shall not use this function:
Notice: Undefined variable: {variablename} in {file} on line {__LINE__}

It's me as plain as the nose on your face that the piece of code hasn't been tested with E_NOTICE.

So my advice in this case is: don't use the above function, but simply use !, and functions such like is_null in the situation they are made for.
tomek 26-Oct-2008 06:48
Here's a simple function to test if the variable is set:

<?php
function is($var)
{
if (!isset($var)) return false;
if ($var!==false) return true;
return false;
}
?>

Now instead of very popular (but invalid in many situations):

if (!$var) $var=5;

you can write:

if (!is($var)) $var=5;
a dot schaffhirt at sedna-soft dot de 12-Oct-2008 08:01
You can safely use isset to check properties and subproperties of objects directly. So instead of writing

    isset($abc) && isset($abc->def) && isset($abc->def->ghi)

or in a shorter form

    isset($abc, $abc->def, $abc->def->ghi)

you can just write

    isset ($abc->def->ghi)

without raising any errors, warnings or notices.

Examples
<?php
    $abc = (object) array("def" => 123);
    var_dump(isset($abc));                // bool(true)
    var_dump(isset($abc->def));           // bool(true)
    var_dump(isset($abc->def->ghi));      // bool(false)
    var_dump(isset($abc->def->ghi->jkl)); // bool(false)
    var_dump(isset($def));                // bool(false)
    var_dump(isset($def->ghi));           // bool(false)
    var_dump(isset($def->ghi->jkl));      // bool(false)

    var_dump($abc);                       // object(stdClass)#1 (1) { ["def"] => int(123) }
    var_dump($abc->def);                  // int(123)
    var_dump($abc->def->ghi);             // null / E_NOTICE: Trying to get property of non-object
    var_dump($abc->def->ghi->jkl);        // null / E_NOTICE: Trying to get property of non-object
    var_dump($def);                       // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi);                  // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi->jkl);             // null / E_NOTICE: Trying to get property of non-object
?>
edsko 05-Oct-2008 04:13
It has been remarked by various people that isset is the opposite of is_null "in all but buggy cases". This is not true:

<?php
  $str = "hi";
  var_dump(isset($str[1]));
  var_dump(@!is_null($str[1]));
  var_dump(isset($str[2]));
  var_dump(@!is_null($str[2]));
?>

outputs

bool(true)
bool(true)
bool(false)
bool(true)
mark dot fabrizio at gmail dot com 15-Sep-2008 07:01
I know this is probably not the recommended way to do this, but it seems to work fine for me. Instead of the normal isset check to extract variables from arrays (like $_REQUEST), you can use the @ prefix to squelch any errors.

For example, instead of:
<?php
$test = isset($_REQUEST['test']) ? $_REQUEST['test'] : null;
?>
you can use:
<?php
$test = @$_REQUEST['test'];
?>

It saves some typing, but doesn't give the opportunity to provide a default value. If 'test' is not an assigned key for $_REQUEST, the assigned value will be null.
mandos78 AT mail from google 29-Jul-2008 02:40
Careful with this function "ifsetfor" by soapergem, passing by reference means that if, like the example $_GET['id'], the argument is an array index, it will be created in the original array (with a null value), thus causing posible trouble with the following code. At least in PHP 5.

For example:

<?php
$a = array();
print_r($a);
ifsetor($a["unsetindex"], 'default');
print_r($a);
?>

will print

Array
(
)
Array
(
    [unsetindex] =>
)

Any foreach or similar will be different before and after the call.
soapergem at gmail dot com 02-Jul-2008 01:34
It is possible to encapsulate isset() calls inside your own functions if you pass them by reference (note the ampersand in the argument list) instead of by value. A prime example would be the heavily-requested "ifsetor" function, which will return a value when it is set, otherwise a default value that the user specifies is used.

<?php

function ifsetor(&$val, $default = null)
{
    return isset($val) ? $val : $default;
}

//    example usage
$id = intval(ifsetor($_GET['id'], 0));

?>
soapergem at gmail dot com 04-Jun-2008 02:19
Below a user by the name of Scott posted an isval() function; I just wanted to point out a revision to his method since it's a bit lengthy for what it does. The trick is to realize that a boolean AND clause will terminate with false as soon as it encounters anything that evaluates to false, and will skip over any remaining checks.

Instead of taking up the space to define isval(), you could just run inline commands for each variable you need to check this:

<?php

$isval = isset($_POST['var']) && !empty($_POST['var']);

?>

Also be warned that if you try to encapsulate this into a function, you might encounter problems. It's meant to stand alone.
John A. Bilicki III 10-Mar-2008 11:08
I was attempting to use isset to detect if a class existed or not and kept having an error...

Call to a member function get() on a non-object...

For example I have some pages where I want to disable my own error reporting for non-existent HTTP queries. The HTTP query error handling file was merely included in my templates though now I can declare a class that uses that template system, declare an error class, and have the template system not serve the error handling when I will be using a large array of queries that I will not be tracking...
<?php if (!class_exists('error')) {include("includes.php");} ?>
anonymousleaf at gmail dot com 25-Feb-2008 10:16
isset expects the variable sign first, so you can't add parentheses or anything.

<?php
    $foo = 1;
    if(isset(($foo))) { // Syntax error at isset((
        $foo = 2;
    }
?>
muratyaman at gmail dot com 07-Feb-2008 04:40
To organize some of the frequently used functions..

<?php

/**
 * Returns field of variable (arr[key] or obj->prop), otherwise the third parameter
 * @param array/object $arr_or_obj
 * @param string $key_or_prop
 * @param mixed $else
 */
function nz($arr_or_obj, $key_or_prop, $else){
  $result = $else;
  if(isset($arr_or_obj)){
    if(is_array($arr_or_obj){
      if(isset($arr_or_obj[$key_or_prop]))
        $result = $arr_or_obj[$key_or_prop];
    }elseif(is_object($arr_or_object))
      if(isset($arr_or_obj->$key_or_prop))
        $result = $arr_or_obj->$key_or_prop;
    }
  }
  return $result;
}

/**
 * Returns integer value using nz()
 */
function nz_int($arr_or_obj, $key_or_prop, $else){
  return intval(nz($arr_or_obj, $key_or_prop, $else));
}

$my_id = nz_int($_REQUEST, 'id', 0);
if($my_id > 0){
  //why?
}
?>
packard_bell_nec at hotmail dot com 25-Dec-2007 11:18
Note: isset() only checks variables as anything else will result in a parse error. In other words, the following will not work: isset(trim($name)).

isset() is the opposite of is_null($var) , except that no warning is generated when the variable is not set.
sam b 13-Nov-2007 10:51
Check out this ifsetor function. If $var is set, do nothing, otherwise $var = $default.

<?php

$name = ifsetor($name, 'default name') ;

function ifsetor(&$var, $default)
    {
        return isset($var) ? $var : $default) ;
    }

?>
contact at scottbyrns dot com 07-Nov-2007 05:51
If you have for example a variable in your URL say url.php?var= and some one types in %00 the variable will pass isset. For post and get variables I wrote this function to filter out varables that are set but empty.

function isval($inp){
    if(isset($inp)){
        $len = strlen($inp);
        if($len > 0){
            return true;
        }
        else{
            return false;
        }
    }
    else{
        return false;
    }
}
petruzanauticoyahoo?com!ar 14-Oct-2007 11:22
I've come up with a little not-so-clean but useful function to avoid checking if a variable is set before reading its value, specially useful for $_REQUEST and the like:

<?php
function toLocal( $source, &$dest, $default = null )
{
    if( isset( $source ) )
        $dest = $source;
    else
        $dest = $default;
}
?>

and then call it this way:
<?php
@toLocal( $_REQUEST['item_id'], $item_id, 0 );
?>

It checks wether the variable is set, copies it to a local variable, and if it wasn't set, it assigns the new variable a default value, all in one line, preventing you to have to always check for isset() before trying to read its value.
Gotta call it with @ because if the variable is not set, then trying to pass it as an argument will yield a warning.

Petruza.
phpnotes dot 20 dot zsh at spamgourmet dot com 22-Sep-2007 02:50
Note that isset is lazy -- the first undefined variable causes it to return. Have a look at this example:

<?php
class Foo {
    public function __isset($varname) {
        echo "ZOMG! isset was called on my $varname!\n";
    }
}
$foo = new Foo;
// bar will never get checked
var_dump(isset($foo->foo, $foo->bar));

// Output:
// ZOMG! isset was called on my foo!
// bool(false)
?>
codeslinger at compsalot dot com 13-Aug-2007 08:31
The behavior of isset is complex and the results are sometimes not what people expected -- to their peril.

After dealing with isset() for awhile and peppering my code with additional checks for edge cases.  I eventually got to know and love  empty()

Most of the places that you are using isset(), empty() would do a better job.

And when you are dealing with arrays what you probably want to use instead of isset() is   array_key_exists()

These days, I almost never use isset() and I write a lot of code.
talbutt(at)mail(dot)med(dot)upenn(edu) 13-Aug-2007 08:30
In PHP 5.2.3, really returns true if the variable is set to null.
black__ray at myway dot com 03-Jul-2007 04:40
if(isset($_POST['in_qu']))
          {

          include("qanda/in_qu.php");
          $content.=$message;
          include("qanda/view_qanda.php");
    }
elseif(isset($_GET['rq']))
          {
          include("qanda/add_answer.php");
    }
elseif(isset($_POST['add_answer']))
          {
          include("qanda/in_an.php");
          $content.=$message;
          include("qanda/view_qanda.php");
    }
elseif($_GET['act']== 'v_qanda' && !(isset($_GET['rq'])))
{
include("qanda/view_qanda.php");
}
/*
if(isset($_POST['add_answer']))
beuc at beuc dot net 01-Jan-2007 01:56
Beware that the chk() function below creates the variable or the array index if it didn't existed.

<?php
function chk(&$var) {
  if (!isset($var))
    return NULL;
  else
    return $var;
}

echo '<pre>';
$a = array();
var_dump($a);
chk($a['b']);
var_dump($a);
echo '</pre>';

// Gives:
// array
//   empty
//
// array
//   'b' => null
?>
beuc at beuc dot net 16-Dec-2006 12:35
"empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set."

So essentially
<?php
if (isset($var) && $var)
?>
is the same as
<?php
if (!empty($var))
?>
doesn't it? :)

!empty() mimics the chk() function posted before.
roberto at spadim dot com dot br 03-Dec-2006 10:04
test:

<?php
$qnt=100000;
$k=array();
for ($i=0;$i<$qnt;$i++)
$k[$i]=1;

echo microtime()."\n";
for ($i=0;$i<$qnt;$i++)if(isset($k[$i]));
echo microtime()."\n";
for ($i=0;$i<$qnt;$i++)if(array_key_exists($i,$k));
echo microtime()."\n";
for ($i=0;$i<$qnt;$i++)if($k[$i]==1);
echo microtime()."\n";

?>

the interesting result:
isset is the fastest
php at bagnara dot org 29-Nov-2006 03:14
See also property_exists() which allows detection of protected variables existing in a class even if they are NULL.
randallgirard at hotmail dot com 27-Sep-2006 11:51
The unexpected results of isset has been really frustrating to me. Hence, it doesn't work how you'd think it would, (as documented) a var currently in the scope with a null value will return false.

Heres a quick solution, perhaps there are better ways of going about this, but heres my solution...

<?php
function is_set( $varname, $parent=null ) {
  if ( !is_array( $parent ) && !is_object($parent) ) {
    $parent = $GLOBALS;
  }
  return array_key_exists( $varname, $parent );
}
?>

Hence, $varname should be a mixed value of var's to check for, and $parent can be an array or object, which will default to the GLOBAL scope. See the documentation of array_key_exists for further information.

This will allow to check if a var is in the current scope, object, or array... Whether it's a null, false, true, or any value. It depends on ARRAY_KEY_EXISTS for it's functionality which also works with Objects. Feel free to improve on this anyone ;D
DerSpezialist at Hotmail dot com 29-Aug-2006 10:09
Note that isset() doesnt recognize $_FILES - Arrays.. additionally, i think it doesnt recognize Arrays in general at all (untested, but logical)!
Checking $_FILES will always result in Boolean FALSE i think, at least it caused my Script to calculate false Positives / Negatives... Solution: Use empty() or !empty() :-)
Tee Cee 20-Aug-2006 05:20
In response to 10-Feb-2006 06:02, isset($v) is in all (except possibly buggy) cases equivalent to !is_null($v). And no, it doesn't actually test if a variable is set or not by my definition "$v is set if unset($v) has no effect".

<?php
unset($c); //force $c to be unset
var_dump($a=&$c); // NULL, but this actually sets $a and $c to the 'same' NULL.
var_dump(isset($c)); // bool(false)
var_dump($a = 5); // int(5)
var_dump($c); // int(5)

unset($c);
var_dump($a=&$c); // NULL
var_dump(isset($c)); // bool(false)
unset($c);
var_dump($a = 5); // int(5)
var_dump($c); // NULL
?>

In the following example, we see an alternate method of testing if a variable is actually set or not:
<?php
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump(isset($c));                                // also false
var_dump($c);                                       // manipulate $c a bit...
var_dump((string)$c);
var_dump(print_r($c,true));
var_dump($a=$c);
var_dump(array_key_exists('c',get_defined_vars())); // ... still false
var_dump($c = NULL);                                // this sets $c
var_dump(array_key_exists('c',get_defined_vars())); // true!
var_dump(isset($c));                                // false; isset() still says it's unset
unset($c);                                          // actually unset it
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump($a=&$c);
var_dump(array_key_exists('c',get_defined_vars())); // true!
unset($c);                                          // unset it again
var_dump(&$c);                                      // &NULL
var_dump(array_key_exists('c',get_defined_vars())); // true!
?>

Obviously, null values take up space (or they wouldn't show up in get_defined_vars). Also, note that &$v sets $v to NULL if it is unset.
purpleidea 17-Aug-2006 12:13
fyi:
you *cannot* do assignments inside of the isset() function. although you *can* while inside of other functions such as is_null().

<?php
if (isset($var = $_GET['key'])) echo 'whatever'; //this will throw an error :(

if (is_null($var = $_GET['key'])) echo 'whatever'; //this will not :)
?>

hope someone finds this useful.
ludie-at-vibage-punkt-kom 16-Aug-2006 05:26
If you don't want to bother checking every single var with isset or empty, use this function on every var you use:

<?php

function chk( & $var )
{
    if ( !isset($var) )
    {
        return NULL;
    }
    else
    {
        return $var;
    }
}

?>

It takes ANYTHING as argument, and returns the exact same thing, but without Notice if the var doesn't actually exist
21-Jul-2006 07:08
I tried the example posted previously by Slawek:

$foo = 'a little string';
echo isset($foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';

He got yes yes, but he didn't say what version of PHP he was using.

I tried this on PHP 5.0.5 and got:  yes no

But on PHP 4.3.5 I got:  yes yes

Apparently, PHP4 converts the the string 'aaaa' to zero and then returns the string character at that position within the string $foo, when $foo is not an array. That means you can't assume you are dealing with an array, even if you used an expression such as isset($foo['aaaa']['bbb']['cc']['d']), because it will return true also if any part is a string.

PHP5 does not do this. If $foo is a string, the index must actually be numeric (e.g. $foo[0]) for it to return the indexed character.
soywiz at php dot net 14-Apr-2006 06:12
Sometimes you have to check if an array has some keys. To achieve it you can use "isset" like this: isset($array['key1'], $array['key2'], $array['key3'], $array['key4'])
You have to write $array all times and it is reiterative if you use same array each time.

With this simple function you can check if an array has some keys:

<?php
function isset_array() {
    if (func_num_args() < 2) return true;
    $args = func_get_args();
    $array = array_shift($args);
    if (!is_array($array)) return false;
    foreach ($args as $n) if (!isset($array[$n])) return false;
    return true;
}
?>

Use: isset_array($array, 'key1', 'key2', 'key3', 'key4')
First parameter has the array; following parameters has the keys you want to check.
kariedoo 09-Mar-2006 10:27
Before:

//ask, if is set
$number = isset($_GET['number']) ? $_GET['number'] : '';
$age = isset($_GET['age']) ? $_GET['age'] : '';
$street = isset($_GET['street']) ? $_GET['street'] : '';

After: --> it's easier to read

//ask, if is set
 $parameter = array('number', 'age', 'street');
 foreach($parameter as $name)
 {
    $$name = isset($_GET[$name]) ? $_GET[$name] : '';
 }
red at iklanumum dot com 09-Feb-2006 10:02
This could be viewed as a philosophy. I wonder why a NULL variabel is being considered FALSE rather than TRUE while in isset, because if the variable has been unset it becomes undefined but a NULL variabel is still defined although it has no value. Or, perhaps, it's based on the memory usage, if it is how about $x="" ? Is empty value use memory too? This leads me to another thinking that the isset isn't have family relationship with unset although both of it are a language construct and have 'set' word :)
Slawek Petrykowski 29-Nov-2005 03:06
<?php
$foo = 'a little string';
echo isset($foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';
>

results with unexpected values:
yes yes

Well, it is necessary to check type of $foo first !
Peter Beckman <beckman at purplecow dot com> 21-Sep-2005 12:16
Based on the previous post, I've found this code even more useful:

<?php
function isset_sum(&$var, $val) {
    if (isset($var))  $var += $val;
    else              $var  = $val;
}
?>

Now instead of:

<?php
if (isset($foo[$bar][$baz][$fooz])) $foo[$bar][$baz][$fooz] += $count;
else                                $foo[$bar][$baz][$fooz] = $count;
?>

No more "Undefined variable" warnings, and you save your fingers and sanity!  Thanks to the previous poster for inspiration.
14-Sep-2005 03:41
I don't know if you guys can use this but i find this piece of code pretty useful (for readabillity at least):

function isset_else( $&v, $r )
{
    if( isset( $v ))
        return $v;
    else
        return $r;
}

This way you can go:

$a = 4;

$c += isset_else( $a, 0 );
$c += isset_else( $b, 0 );

echo $c;

Of course, this code would work anyway, but you get the point.
onno at itmaze dot com dot au ##php==owh 12-Aug-2005 12:33
In PHP4, the following works as expected:

if (isset($obj->thing['key'])) {
  unset($obj->thing['key']) ;
}

In PHP5 however you will get a fatal error for the unset().

The work around is:

if (is_array($obj->thing) && isset($obj->thing['key'])) {
  unset($obj->thing['key']) ;
}
richard william lee AT gmail 10-Jun-2005 11:38
Just a note on the previous users comments. isset() should only be used for testing if the variable exists and not if the variable containes an empty "" string. empty() is designed for that.

Also, as noted previosuly !empty() is the best method for testing for set non-empty variables.
darkstar_ae at hotmail dot com 25-May-2005 01:03
isset doesn't reliably evaluate variables with blank strings (not necessarily NULL).
i.e.
$blankvar = ""; // isset will return true on this.

This is a very common pitfall when handling HTML forms that return blank text fields to the script. You're better off doing this:

if ($var != "")
return true;
else
return false;

This more of a programming practice rather than the function's shortcomings. So if you have a habit of initializing variables you're likely to run into problems with isset() if your code or php project become very large.
Andrew Penry 11-May-2005 08:17
The following is an example of how to test if a variable is set, whether or not it is NULL. It makes use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL will not.

<?php

function var_exists($var){
    if (empty($GLOBALS['var_exists_err'])) {
        return true;
    } else {
        unset($GLOBALS['var_exists_err']);
        return false;
    }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
   $GLOBALS['var_exists_err'] = true;
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
restore_error_handler();

?>

Outputs:
True False

The problem is, the set_error_handler and restore_error_handler calls can not be inside the function, which means you need 2 extra lines of code every time you are testing. And if you have any E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they will not be dealt with properly. One solution:

<?php

function var_exists($var){
   if (empty($GLOBALS['var_exists_err'])) {
       return true;
   } else {
       unset($GLOBALS['var_exists_err']);
       return false;
   }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
    $filearr = file($errfile);
    if (strpos($filearr[$errline-1], 'var_exists') !== false) {
        $GLOBALS['var_exists_err'] = true;
        return true;
    } else {
        return false;
    }
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
is_null($j);
restore_error_handler();

?>

Outputs:
True False
Notice: Undefined variable: j in filename.php on line 26

This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an E_NOTICE error happens, the file it originated from will be loaded into an array.
phpnet dot 5 dot reinhold2000 at t spamgourmet dot com 10-Apr-2005 08:33
if you want to check whether the user has sent post vars from a form, it is a pain to write something like the following, since isset() does not check for zero-length strings:

if(isset($form_name) && $form_name != '') [...]

a shorter way would be this one:

if($form_name && $form_message) [...]

but this is dirty since you cannot make sure these variables exist and php will echo a warning if you refer to a non-existing variable like this. plus, a string containing "0" will evaluate to FALSE if casted to a boolean.

this function will check one or more form values if they are set and do not contain an empty string. it returns false on the first empty or non-existing post var.

<?
function postvars() {
    foreach(func_get_args() as $var) {
        if(!isset($_POST[$var]) || $_POST[$var] === '') return false;
    }
    return true;
}
?>

example: if(postvars('form_name','form_message')) [...]
yaogzhan at gmail dot com 20-Mar-2005 04:52
in PHP5, if you have

<?PHP
class Foo
{
    protected $data = array('bar' => null);

    function __get($p)
    {
        if( isset($this->data[$p]) ) return $this->data[$p];
    }
}
?>

and
<?PHP
$foo = new Foo;
echo isset($foo->bar);
?>
will always echo 'false'. because the isset() accepts VARIABLES as it parameters, but in this case, $foo->bar is NOT a VARIABLE. it is a VALUE returned from the __get() method of the class Foo. thus the isset($foo->bar) expreesion will always equal 'false'.
dubmeier aaattt Y! daht calm 01-Mar-2005 03:13
Here are some handy wrappers to isset that I use when I need to do common evaluations like: this variable is set and has a length greater than 0, or: I want the variables value, or a blank, if not set.

/**
 * isset_echo()
 *
 * Accomplishes the following w/o warnings:
 *    echo $x;
 *    echo $x[$y];
 *    echo $x[$y][$z];
 *
 * FIXME: make this recursive so it works for N args?
 */
function isset_echo($x, $y=Null, $z=Null)
{
    if (is_array($x)) {
        if (array_key_exists($y, $x)) {
            if (is_array($x[$y])) {
                if (array_key_exists($z, $x[$y])) { echo $x[$y][$z]; }
            }
            else { echo $x[$y]; }
        }
    }
    else { echo $x; }
}

/**
 * isset_value()
 *
 * As above, but returns value instead of echoing
 */
function isset_value(&$x, $y=Null)
{
    if (is_array($x)) {
        if (array_key_exists($y, $x)) { return $x[$y]; }
    }
    else { return $x; }
}

/**
 * isset_and_equals()
 *
 * As above, but ...
 * Returns true if variable (or array member) is set and equaL to the first parameter
 */
function isset_equals($val, $w, $x=null, $y=null, $z=null) {
    if (is_array($w)) {
                if (array_key_exists($x, $w)) {
                if (is_array($w[$x])) {
                        if (array_key_exists($y, $w[$x])) {
                                    if (is_array($w[$x][$y])) {
                                        if(array_key_exists($z, $w[$x][$y])) {
                                                return ($w[$x][$y][$z] == $val) ? true : false;
                                        }
                                    } else {
                                        return ($w[$x][$y] == $val) ? true : false;
                                    }
                            }
                    } else {
                        return ($w[$x] == $val) ? true : false;
                    }
        }
    } else {
                return ($w == $val) ? true : false;
        }
}

/**
 * isset_gt0()
 *
 * As above, but returns true only if var is set and it's length is > 0
 */
function isset_gt0(&$x)
{
    if (isset($x) && strlen($x) > 0) { return true; }
    else { return false; }
}
codeslinger at compsalot dot com 06-Feb-2005 10:21
according to the docs -- "isset() will return FALSE if testing a variable that has been set to NULL."

That statment is not always correct, sometimes isset() returns TRUE for a NULL value.  But the scenarios are obtuse.  There are a tons of bugs on this subject, all marked as bogus.

Problems occur when NULLs are in named fields of arrays and also when vars are passed by reference.

do lots of testing and code defensively.

is_null()   is your friend...
pianistsk8er at gmail dot com 09-Dec-2004 06:23
This function is very useful while calling to the URL to specify which template to be used on certain parts of your application.

Here is an example...

<?php

    $cat = $_GET['c'];
    $id = $_GET['id'];
    $error = 'templates/error.tpl';

    if( isset($cat))
    {
        if( isset($id))
        {
            $var = 'templates/pics/' . $cat . '-' . $id . '.tpl';
            if (is_file($var))
            {
                include($var);
            }
            else
            {
                include($error);
            }
        }
        else
        {
            $var = 'templates/pics/' . $cat . '.tpl';
            if (is_file($var))
            {
                include($var);
            }
            else
            {
                include($error);
            }
        }
    }
    else
    {
        include('templates/alternative.'.tpl);
    }

?>

You can see several uses of the isset function being used to specify wheter a template is to be called upon or not.  This can easily prevent other generic PHP errors.
jc dot michel at symetrie dot com 15-Nov-2004 02:35
Using
  isset($array['key'])
is useful, but be careful!
using
  isset($array['key']['subkey'])
doesn't work as one could expect, if $array['key'] is a string it seems that 'subkey' is converted to (integer) 0 and $array['key']['subkey'] is evaluated as the first char of the string.
The solution is to use
  is_array($array['key']) && isset($array['key']['subkey'])

Here is a small code to show this:

<?php
$ex = array('one' => 'val1','two' => 'val2');
echo '$ex = ';print_r($ex);
echo "<br />";

echo " isset(\$ex['one']['three']) : ";
if (isset($ex['one']['three']))
    echo 'true';
else
    echo 'false';

echo "<br />";
echo "is_array(\$ex['one']) &&  isset(\$ex['one']['three']) : ";
if (is_array($ex['one']) && isset($ex['one']['three']))
    echo 'true';
else
    echo 'false';
?>

shows:
$ex = Array ( [one] => val1 [two] => val2 )
isset($ex['one']['three']) : true
is_array($ex['one']) && isset($ex['one']['three']) : false
jon 07-Dec-2003 10:19
Since PHP will check cases in order, I often end up using this bit of code:

<?php
if (isset($var) && $var) {
    // do something
}
?>

In short, if you have error reporting on, and $var is not set, PHP will generate an error if you just have:

<?php
if ($var) { // do something }
?>

...but, as noted elsewhere, will return True if set to False in this case:
<?php
if (isset($var)) { // do something }
?>

Checking both to see if $var is set, and that it equals something other than Null or False is something I find very useful a lot of times.  If $var is not set, PHP will never execute the second part of "(isset($var) && $var)", and thus never generate an error either.

This also works very nice for setting variable as well, e.g.:
<?php
$var = (isset($var) && $var) ? $var : 'new value';
?>
flobee at gmx dot net 08-Sep-2003 02:16
just as note: if you want to check variables by boolean value: true or false , "isset" has a different meaning!
<?php
$var=null;
// sample 1
if($var) {
   // if true or another value exept "false" , "null": go on here
   echo "1. var is true or has a value $var<br>";
} else {
   echo "1. var is &quot;false&quot; or &quot;null&quot;<br>";
}

if(!$var) {
   // if false or "null": go on here
   echo "2. var has no value $var<br>";
} else {
   echo "2. var is &quot;false&quot; or &quot;null&quot;<br>";
}

// sample 2
$var =false;
if(isset($var)) {
  // $var is false so it is set to a value and the execution goes here
   echo "3. var has value: $var<br>";
}

$var=null;
if(!isset($var)) {
  // $var is null (does not exist at this time) and the execution goes here
   echo "4. var was not set $var<br>";
}
?>
is_string
print_r
Функции для работы с переменными


Выводит удобочитаемую информацию о переменной

isset
serialize
Функции для работы с переменными
PHP Manual

print_r

(PHP 4, PHP 5)

print_r — Выводит удобочитаемую информацию о переменной

Описание

mixed print_r ( mixed $expression [, bool $return = false ] )

print_r() выводит информацию о переменной в удобочитаемом виде.

print_r(), var_dump() и var_export() могут также показывать защищенные (protected) и закрытые (private) атрибуты объектов в PHP 5. Статические элементы класса не будут отображены.

Следует помнить, что print_r() установит внутренний указатель массива в его конец. Используйте функцию reset() для установки его в начало массива.

Список параметров

expression

Выражение для вывода на экран.

return

Если вы хотите перехватить вывод print_r(), используйте параметр return. Если его значение равно TRUE, то print_r() вернет результат вывода вместо вывода в браузер (который производится по умолчанию).

Возвращаемые значения

Если в функцию передаются значения типов string, integer или float, будет напечатано само значение. Если передается массив array, значения будут напечатаны в формате, показывающем ключи и элементы массива. Аналогичный формат вывода используется для объектов.

Если параметр return установлен в TRUE, данная функция вернет строку (string). В противном случае возвращаемое значение будет равно TRUE.

Примечания

Замечание:

При использовании параметра return данная функция использует внутреннюю буферизацию вывода, поэтому она не может быть использована внутри callback-функции ob_start().

Список изменений

Версия | Описание
4.3.0 | Добавлен параметр return. Если вам необходимо перехватить вывод print_r() в ранних версиях PHP, используйте функции буферизации вывода.
4.0.4 | В версиях PHP до 4.0.4, print_r() будет выполняться бесконечно, если передается массив или объект, содержащий прямую или косвенную ссылку на себя. Примером является print_r($GLOBALS), поскольку $GLOBALS является глобальной переменной, которая содержит ссылку на себя.

Примеры

Пример #1 Пример использования print_r()

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

Результат выполнения данного примера:

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Пример #2 Пример использования параметра return

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results теперь содержит вывод print_r
?>

Смотрите также

  • ob_start() - Включение буферизации вывода
  • var_dump() - Выводит информацию о переменной
  • var_export() - Выводит в браузер или возвращает интерпретируемое строковое представление переменной

User Contributed Notes

henzeberkheij at gmail dot com 28-Jan-2012 03:10
print_r is used for debug purposes. Yet I had some classes where I just wanted the values coming out of the database, not all the other crap. thus i wrote the following function. If your class has an toArray function, that one will be called otherwise it will return the object as is. print_neat_classes_r is the function that should be called!

<?php
print_neat_classes_r($array, $return=false){
        return print_r(self::neat_class_print_r($array), $return);
    }

function do_print_r($array, $return=false){
        if(is_object($array) && method_exists($array, 'toArray')){
            return $array->toArray();
        }else if(is_array($array)){
            foreach($array as $key=>$obj){
                $array[$key] = self::do_print_r($obj, $return);
            }
            return $array;
        }else{
            return $array;
        }
    }
?>
eithed 21-Oct-2011 02:25
Bear in mind that print_r actually reserves some memory to do something - so, for example thing like:

<?php
function shutdown_handler()
{
    file_put_contents($_SERVER['DOCUMENT_ROOT']."/log.txt", print_r($_REQUEST, true));
}

ini_set('memory_limit', '1M');
register_shutdown_function("shutdown_handler");

$array = array();
while(true)
    $array[] = new stdClass();
?>

will just not work. Try using var_export, and presto, everything is fine.
jwood at JPL dot gov (w/ Bug fixed) 10-Aug-2011 04:04
<?php

// Displays a multi-dimensional array as a HTML List (Tree structure).
function displayTree($var) {
     $newline = "\n";
     foreach($var as $key => $value) {
         if (is_array($value) || is_object($value)) {
             $value = $newline . "<ul>" . displayTree($value) . "</ul>";
         }

         if (is_array($var)) {
             if (!stripos($value, "<li class=")) {
                $output .= "<li class=\"file\">" . $value . "</li>" . $newline;
             }
             else {
                $output .= $value . $newline;
             }

         }
         else { // is_object
            if (!stripos($value, "<li class=")) {
               $value = "<ul><li class=\"file\">" . $value . "</li></ul>" . $newline;
            }

            $output .= "<li class=\"folder\">" . $key . $value . "</li>" . $newline;
         }

     }

     return $output;
}
?>
///////////////////

Also need to add this to your style sheet (and get the necessary images...):

li.folder
 {
 list-style-image: url(../img/folder.gif);
 }

li.file
 {
 list-style-image: url(../img/file.gif);
 }

///////////////////

Example Usage:

<?php
     ...

    echo "<ul>";
     echo displayTree($array);
     echo "</ul>";
 ?>
Robert Heine (joomla-jquery-internet.de) 18-Apr-2011 07:09
Since i use print_r for debugging a lot, i always use the following function in my scripts, which makes life a lot easier :-)

<?php
if (!function_exists("preprint")) {
    function preprint($s, $return=false) {
        $x = "<pre>";
        $x .= print_r($s, 1);
        $x .= "</pre>";
        if ($return) return $x;
        else print $x;
    }
}
?>

-------------------

USAGE:  preprint($x);   <- where $x = array().

-------------------

The optional 2. parameter can be set to "true", so the html-code is returned.

Have fun,
machuidel 03-Feb-2011 04:01
The following will output an array in a PHP parsable format:

<?php
function serialize_array(&$array, $root = '$root', $depth = 0)
{
        $items = array();

        foreach($array as $key => &$value)
        {
                if(is_array($value))
                {
                        serialize_array($value, $root . '[\'' . $key . '\']', $depth + 1);
                }
                else
                {
                        $items[$key] = $value;
                }
        }

        if(count($items) > 0)
        {
                echo $root . ' = array(';

                $prefix = '';
                foreach($items as $key => &$value)
                {
                        echo $prefix . '\'' . $key . '\' => \'' . addslashes($value) . '\'';
                        $prefix = ', ';
                }

                echo ');' . "\n";
        }
}
?>
Jake Lodwick 08-Jan-2011 09:31
This function removes clutter from print_r's output.
I use it instead of print_r now.

Here is an example:

<?PHP

$data = array(
    "mode" => "sets",
    "sets" => array(
        123,
        456,
        789
    ),
    "etc" => array(
        "letters" => array(
            "a",
            "b"
        ),
        "pie",
        "sharks"
    )
);

print_r($data);

/*
Array
(
    [mode] => sets
    [sets] => Array
        (
            [0] => 123
            [1] => 456
            [2] => 789
        )

    [etc] => Array
        (
            [letters] => Array
                (
                    [0] => a
                    [1] => b
                )

            [0] => pie
            [1] => sharks
        )

)
*/

neat_r($data);

/*
mode: sets
sets:
  123
  456
  789
etc:
  letters:
    a
    b
  pie
  sharks

*/
?>

Here is the function:

<?PHP

/*
    neat_r works like print_r but with much less visual clutter.
    By Jake Lodwick. Copy freely.
*/
function neat_r($arr, $return = false) {
    $out = array();
    $oldtab = "    ";
    $newtab = "  ";

    $lines = explode("\n", print_r($arr, true));

    foreach ($lines as $line) {

        //remove numeric indexes like "[0] =>" unless the value is an array
        if (substr($line, -5) != "Array") {    $line = preg_replace("/^(\s*)\[[0-9]+\] => /", "$1", $line, 1); }

        //garbage symbols
        foreach (array(
            "Array"        => "",
            "["            => "",
            "]"            => "",
            " =>"        => ":",
        ) as $old => $new) {
            $out = str_replace($old, $new, $out);
        }

        //garbage lines
        if (in_array(trim($line), array("Array", "(", ")", ""))) continue;

        //indents
        $indent = "";
        $indents = floor((substr_count($line, $oldtab) - 1) / 2);
        if ($indents > 0) { for ($i = 0; $i < $indents; $i++) { $indent .= $newtab; } }

        $out[] = $indent . trim($line);
    }

    $out = implode("\n", $out) . "\n";
    if ($return == true) return $out;
    echo $out;
}

?>
Levofski 14-May-2010 05:19
Hi all, here is a function that will display any variable, including objects, as XML so you can expand and collapse in browsers etc. Note that it will output all variables, not just public ones.

<?php

/**
 * Will output in a similar form to print_r, but the nodes are xml so can be collapsed in browsers
 *
 * @param mixed $mixed
 */
function print_r_xml($mixed)
{
    // capture the output of print_r
    $out = print_r($mixed, true);

    // Replace the root item with a struct
    // MATCH : '<start>element<newline> ('
    $root_pattern = '/[ \t]*([a-z0-9 \t_]+)\n[ \t]*\(/i';
    $root_replace_pattern = '<struct name="root" type="\\1">';
    $out = preg_replace($root_pattern, $root_replace_pattern, $out, 1);

    // Replace array and object items structs
    // MATCH : '[element] => <newline> ('
    $struct_pattern = '/[ \t]*\[([^\]]+)\][ \t]*\=\>[ \t]*([a-z0-9 \t_]+)\n[ \t]*\(/miU';
    $struct_replace_pattern = '<struct name="\\1" type="\\2">';
    $out = preg_replace($struct_pattern, $struct_replace_pattern, $out);
    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '</var>
    $out = preg_replace('/^\s*\)\s*$/m', '</struct>', $out);

    // Replace simple key=>values with vars
    // MATCH : '[element] => value<newline>'
    $var_pattern = '/[ \t]*\[([^\]]+)\][ \t]*\=\>[ \t]*([a-z0-9 \t_\S]+)/i';
    $var_replace_pattern = '<var name="\\1">\\2</var>';
    $out = preg_replace($var_pattern, $var_replace_pattern, $out);

    $out =  trim($out);
    $out='<?xml version="1.0"?><data>'.$out.'</data>';

    return $out;
}

?>
Alexander 19-Mar-2010 05:20
A simple function to send the output of print_r to firebug.
The script creates a dummy console object with a log method for when firebug is disabled/not available.

<?php
function debug ($data) {
    echo "<script>\r\n//<![CDATA[\r\nif(!console){var console={log:function(){}}}";
    $output    =    explode("\n", print_r($data, true));
    foreach ($output as $line) {
        if (trim($line)) {
            $line    =    addslashes($line);
            echo "console.log(\"{$line}\");";
        }
    }
    echo "\r\n//]]>\r\n</script>";
}
?>
liamtoh6 at hotmail dot com 03-Feb-2010 10:01
I add this function to the global scope on just about every project I do, it makes reading the output of print_r() in a browser infinitely easier.

<?php
function print_r2($val){
        echo '<pre>';
        print_r($val);
        echo  '</pre>';
}
?>

It also makes sense in some cases to add an if statement to only display the output in certain scenarios, such as:

if(debug==true)
if($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
imikay at gmail dot com 06-Jan-2010 08:03
print_r now can reset the pointer after processing.
jeremy dot ruten at gmail dot com 26-Sep-2009 07:16
Here's an array_depth() function that calculates the depth of an array using the indentation in the output of print_r():

<?php

function array_depth($array) {
    $max_indentation = 1;

    $array_str = print_r($array, true);
    $lines = explode("\n", $array_str);

    foreach ($lines as $line) {
        $indentation = (strlen($line) - strlen(ltrim($line))) / 4;

        if ($indentation > $max_indentation) {
                $max_indentation = $indentation;
        }
    }

    return ceil(($max_indentation - 1) / 2) + 1;
}

?>

It's better than writing a recursive function to do the same thing, as print_r() handles the problem of infinitely-deep arrays for you quite nicely.
Matt 14-Sep-2009 12:53
Here is another version that parses the print_r() output. I tried the one posted, but I had difficulties with it. I believe it has a problem with nested arrays. This handles nested arrays without issue as far as I can tell.

<?php
function print_r_reverse($in) {
    $lines = explode("\n", trim($in));
    if (trim($lines[0]) != 'Array') {
        // bottomed out to something that isn't an array
        return $in;
    } else {
        // this is an array, lets parse it
        if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
            // this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
            $spaces = $match[1];
            $spaces_length = strlen($spaces);
            $lines_total = count($lines);
            for ($i = 0; $i < $lines_total; $i++) {
                if (substr($lines[$i], 0, $spaces_length) == $spaces) {
                    $lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
        array_shift($lines); // Array
        array_shift($lines); // (
        array_pop($lines); // )
        $in = implode("\n", $lines);
        // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
        preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $pos = array();
        $previous_key = '';
        $in_length = strlen($in);
        // store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
        foreach ($matches as $match) {
            $key = $match[1][0];
            $start = $match[0][1] + strlen($match[0][0]);
            $pos[$key] = array($start, $in_length);
            if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
            $previous_key = $key;
        }
        $ret = array();
        foreach ($pos as $key => $where) {
            // recursively see if the parsed out value is an array too
            $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return $ret;
    }
}

?>
Federico Bricker 29-Jun-2009 04:02
Here is a nice version of print_r that prints things with colors and tables.
I've called it print_nice

<?php
function print_nice($elem,$max_level=10,$print_nice_stack=array()){
    if(is_array($elem) || is_object($elem)){
        if(in_array(&$elem,$print_nice_stack,true)){
            echo "<font color=red>RECURSION</font>";
            return;
        }
        $print_nice_stack[]=&$elem;
        if($max_level<1){
            echo "<font color=red>nivel maximo alcanzado</font>";
            return;
        }
        $max_level--;
        echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
        if(is_array($elem)){
            echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
        }else{
            echo '<tr><td colspan=2 style="background-color:#333333;"><strong>';
            echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></td></tr>';
        }
        $color=0;
        foreach($elem as $k => $v){
            if($max_level%2){
                $rgb=($color++%2)?"#888888":"#BBBBBB";
            }else{
                $rgb=($color++%2)?"#8888BB":"#BBBBFF";
            }
            echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
            echo '<strong>'.$k."</strong></td><td>";
            print_nice($v,$max_level,$print_nice_stack);
            echo "</td></tr>";
        }
        echo "</table>";
        return;
    }
    if($elem === null){
        echo "<font color=green>NULL</font>";
    }elseif($elem === 0){
        echo "0";
    }elseif($elem === true){
        echo "<font color=green>TRUE</font>";
    }elseif($elem === false){
        echo "<font color=green>FALSE</font>";
    }elseif($elem === ""){
        echo "<font color=green>EMPTY STRING</font>";
    }else{
        echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
    }
}
?>
Bob 08-May-2009 03:19
Here is a function that formats the output of print_r as a expandable/collapsable tree list using HTML and JavaScript.
<?php
function print_r_tree($data)
{
    // capture the output of print_r
    $out = print_r($data, true);

    // replace something like '[element] => <newline> (' with <a href="javascript:toggleDisplay('...');">...</a><div id="..." style="display: none;">
    $out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',"'\\1<a href=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'\\0'), 0, 7)).'\');\">\\2</a><div id=\"'.\$id.'\" style=\"display: none;\">'", $out);

    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '</div>
    $out = preg_replace('/^\s*\)\s*$/m', '</div>', $out);

    // print the javascript function toggleDisplay() and then the transformed output
    echo '<script language="Javascript">function toggleDisplay(id) { document.getElementById(id).style.display = (document.getElementById(id).style.display == "block") ? "none" : "block"; }</script>'."\n$out";
}
?>
Pass it a multidimensional array or object and each sub-array/object will be hidden and replaced by a html link that will toggle its display on and off.
Its quick and dirty, but great for debugging the contents of large arrays and objects.
Note: You'll want to surround the output with <pre></pre>
sebasg37 at gmail dot com 25-Jan-2009 09:35
If you have to catch the output without showing it at all at first (for example, if you want to append the print_r output to a file), you can do this:

<?php

ob_start();
print_r( $some_array );
$output = ob_get_clean();

// if you want to append the print_r output of $some_array to, let's say, log.txt:

file_put_contents( 'log.txt', file_get_contents( 'log.txt' ) . $output )

?>
afisher8 at cox dot net 17-Dec-2008 08:53
I use this all the time when debugging objects, but when you have a very large object with big arrays of sub-objects, it's easy to get overwhelmed with the large amount of output....sometimes you don't want to see absolutely every sub-object.

I made this function to debug objects while "hiding" sub-objects of certain types.  This also color codes the output for a more readable printout.

<?php

function wtf($var, $arrayOfObjectsToHide=null, $fontSize=11)
{
    $text = print_r($var, true);

    if (is_array($arrayOfObjectsToHide)) {

        foreach ($arrayOfObjectsToHide as $objectName) {

            $searchPattern = '#('.$objectName.' Object\n(\s+)\().*?\n\2\)\n#s';
            $replace = "$1<span style=\"color: #FF9900;\">--&gt; HIDDEN - courtesy of wtf() &lt;--</span>)";
            $text = preg_replace($searchPattern, $replace, $text);
        }
    }

    // color code objects
    $text = preg_replace('#(\w+)(\s+Object\s+\()#s', '<span style="color: #079700;">$1</span>$2', $text);
    // color code object properties
    $text = preg_replace('#\[(\w+)\:(public|private|protected)\]#', '[<span style="color: #000099;">$1</span>:<span style="color: #009999;">$2</span>]', $text);

    echo '<pre style="font-size: '.$fontSize.'px; line-height: '.$fontSize.'px;">'.$text.'</pre>';
}

// example usage:
wtf($myBigObject, array('NameOfObjectToHide_1', 'NameOfObjectToHide_2'));

?>
vista_ at live dot se 04-Dec-2008 08:31
Do you think it is difficult to see what print_r() returns?

<?php
   echo '<pre>';
   print_r($array);
   echo '</pre>';
?>

And if you have to write this many times in a page, use this:

<?php
   function preint_r($array)
   {
      echo '<pre>';
      print_r($array);
      echo '</pre>';
   }
?>
everett at myersnetwork dot com 23-Nov-2008 03:02
I like the print_r() function as I am sure many of you do, however when I am working on a script via a browser the output it not easy to read so I have created my own variation hope this helps any of you guys who have had the same frustration.

Start File ###########################################
<?php
/*
File Name: print_ar.php
PHP: 5.2.3
*/

function print_ar($array, $count=0) {
    $i=0;
    $tab ='';
    while($i != $count) {
        $i++;
        $tab .= "&nbsp;&nbsp;|&nbsp;&nbsp;";
    }
    foreach($array as $key=>$value){
        if(is_array($value)){
            echo $tab."[<strong><u>$key</u></strong>]<br />";
            $count++;
            print_ar($value, $count);
            $count--;
        }
        else{
            $tab2 = substr($tab, 0, -12);
            echo "$tab2~ $key: <strong>$value</strong><br />";
        }
        $k++;
    }
    $count--;
}

?>
End File ###########################################

Use is exactly like the print_r() function example;

<?php
require("print_ar.php");

$array = array(
        "Main1" => array(
                "Sub1" => "Data 1-1",
                "Sub2" => "Data 1-2",
                "Sub3" => "Data 1-3",
        ),

        "Main2" =>
        array (
                "Sub1" => "Data 2-1",
                "Sub2" => "Data 2-2",
                "Sub3" => "Data 2-3",
        )
);

print_ar($array);
?>

Will give you:
[Main1]
  |~ Sub1: Data 1-1
  |~ Sub2: Data 1-2
  |~ Sub3: Data 1-3
[Main2]
  |~ Sub1: Data 2-1
  |~ Sub2: Data 2-2
  |~ Sub3: Data 2-3

Vice:
Array ( [Main1] => Array ( [Sub1] => Data 1-1 [Sub2] => Data 1-2 [Sub3] => Data 1-3 ) [Main2] => Array ( [Sub1] => Data 2-1 [Sub2] => Data 2-2 [Sub3] => Data 2-3 ) )
kurt krueckeberg 28-Oct-2008 10:53
This is an alternative for printing arrays. It bolds array values.

<?php
function print_array(&$a, $str = "")
{
    if ($str[0]) {
        echo "$str =";
    }
    echo ' array( ';
    foreach ($a as $k => $v) {

        echo "[$k]".' => ';

        if (is_array($v)) {
            print_array($v);
        }
        else {
               echo "<strong>$a[$k]</strong> ";
        }
    }
    echo ')  ';
}
$a1 = array ("apples", "oranges", "pears");
$a2 = array ("potatos", "green beans", "squash");
$a3 = array ("euros", "dollars", "pesos", "dinars");
$test = range(1, 9);
array_push($test, array ("fruit" => $a1, "vegies" => $a2, "money" => $a3));
print_array($test, "test");
?>
schizo do not spamme duckie at gmail dot com 07-Oct-2008 05:00
my take on the highlighted markupped debug function:

<?php
/**
 * print_array()
 * Does a var_export of the array and returns it between <pre> tags
 *
 * @param mixed $var any input you can think of
 * @return string HTML
 */
function print_array($var)
{
    $input =var_export($var,true);
    $input = preg_replace("! => \n\W+ array \(!Uims", " => Array ( ", $input);
    $input = preg_replace("!array \(\W+\),!Uims", "Array ( ),", $input);
    return("<pre>".str_replace('><?', '>', highlight_string('<'.'?'.$input, true))."</pre>");
}
?>
brenden at beagleproductions dot com 28-Aug-2008 01:58
Many developers have submitted bugs to the PHP development team with regards to print_r showing protected and private properties of objects (PHP 5).  This is not a bug; sensitive information (ex. database connection object) should be  encapsulated within a private member function of your class.
admin at swivelgames dot com 17-Aug-2008 01:44
I was having problems using print_r because I didn't like the fact that if tags where included in the array it would still be parsed by the browsers.

Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser's "view source" or CLI.

Script:
<?php

     $MyArray[0]="<div align='center'>My Text</div>";

     echo "<pre>".htmlspecialchars(print_r($MyArray,true))."</pre>";

?>

Output:
<pre>Array
(
    [0] =&gt; &lt;div align='center'&gt;My Text&lt;/div&gt;
)
</pre>
mayank dot chaudhary dot 30 at gmail dot com 01-Aug-2008 06:51
I use a function. Since browsers neglect extra spaces and line feeds.
<?php
function print_a($subject){
echo str_replace("=>","&#8658;",str_replace("Array","<font color=\"red\"><b>Array</b></font>",nl2br(str_replace(" "," &nbsp; ",print_r($subject,true)))));
}
?>
Anonymous 28-Jun-2008 01:21
I have written a nice debugging function.
This function handles arrays beautifully.
<?php
//Debug variables, $i and $k are for recursive use
function DebugDisplayVar($input, $name = "Debug", $i = "0", $k = array("Error")){
    if(is_array($input))
    {    foreach ($input as $i => $value){
            $temp = $k;
            $temp[] = $i;
            DebugDisplayVar($value, $name, $i, $temp);}
    }else{//if not array
        echo "$".$name;//[$k]
        foreach ($k as $i => $value){
            if($value !=="Error"){echo "[$value]";}
        }
        echo " = $input<br>";
}    }

//outputs
Debug[0] = value
Debug[1] = another value
ect...

?>
janci 13-May-2008 02:49
You cannot use print_r(), var_dump() nor var_export() to get static member variables of a class. However, in PHP5 you can use Reflection classes for this:

<?php

$reflection = new ReflectionClass('Static');
print_r($reflection->getStaticProperties());

?>
sruwhof at intervisionit dot nl 09-Apr-2008 05:27
@highstrike at gmail dot com 08-Jan-2008 02:34
You have an bug in your debug script, the script only prints public properties of the exported object.

If you want to export all object properties (public, private, protected) to an array, then simply cast the object to an array:

<?php
class some
{
   public $pub = 1;
   protected $prot = 2;
   private $priv = 3;

}
var_dump( (array) new some() );
?>

result:
--------------
array(3) {
  ["pub"]=>
  int(1)
  ["*prot"]=>
  int(2)
  ["somepriv"]=>
  int(3)
}
tylmann at corvent dot ch 28-Mar-2008 02:07
There is a library to create nice output of variables, arrays, hash-tables and even objects. It is great for developing/debugging and looks very much better than any print_r output.

Usage:
<?php
debug::show($myVar, 'caption');
?>

You can download it for free at http://sourceforge.net/projects/phpcorestdfuncs

For an example take a look at http://demo.corvent.ch/stdfuncs/
helpful at maybe dot com 06-Mar-2008 08:13
Another slight modification to the previous post to allow for empty array elements

added the following lines after the first preg_match block
<?php
        } else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\>$/', $trim, $matches)) { // array element
            // the array element is blank
            list ($fullMatch, $key) = $matches;
            $topArray[$key] = $element;
        }

?>
anon at anon dot com 29-Feb-2008 10:30
A slight modification to the previous post to allow for arrays containing mutli line strings. haven't fully tested it with everything, but seems to work great for the stuff i've done so far.

<?php

function print_r_reverse(&$output)
{
    $expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
    $lines = explode("\n", $output);
    $result = null;
    $topArray = null;
    $arrayStack = array();
    $matches = null;
    while (!empty($lines) && $result === null)
    {
        $line = array_shift($lines);
        $trim = trim($line);
        if ($trim == 'Array')
        {
            if ($expecting == 0)
            {
                $topArray = array();
                $expecting = 1;
            }
            else
            {
                trigger_error("Unknown array.");
            }
        }
        else if ($expecting == 1 && $trim == '(')
        {
            $expecting = 2;
        }
        else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)) // array element
        {
            list ($fullMatch, $key, $element) = $matches;
            if (trim($element) == 'Array')
            {
                $topArray[$key] = array();
                $newTopArray =& $topArray[$key];
                $arrayStack[] =& $topArray;
                $topArray =& $newTopArray;
                $expecting = 1;
            }
            else
            {
                $topArray[$key] = $element;
            }
        }
        else if ($expecting == 2 && $trim == ')') // end current array
        {
            if (empty($arrayStack))
            {
                $result = $topArray;
            }
            else // pop into parent array
            {
                // safe array pop
                $keys = array_keys($arrayStack);
                $lastKey = array_pop($keys);
                $temp =& $arrayStack[$lastKey];
                unset($arrayStack[$lastKey]);
                $topArray =& $temp;
            }
        }
        // Added this to allow for multi line strings.
    else if (!empty($trim) && $expecting == 2)
    {
        // Expecting close parent or element, but got just a string
        $topArray[$key] .= "\n".$line;
    }
        else if (!empty($trim))
        {
            $result = $line;
        }
    }

    $output = implode(n, $lines);
    return $result;
}

/**
 * @param string $output : The output of a multiple print_r calls, separated by newlines
 * @return mixed[] : parseable elements of $output
 */
function print_r_reverse_multiple($output)
{
    $result = array();
    while (($reverse = print_r_reverse($output)) !== NULL)
    {
        $result[] = $reverse;
    }
    return $result;
}

$output = '
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
            [3] => Array
            (
                [nest] => yes
                [nest2] => Array
                (
                    [nest] => some more
                    asffjaskkd
                )
                [nest3] => o rly?
            )
        )
)

some extra stuff
';
var_dump(print_r_reverse($output), $output);

?>

This should output

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  array(4) {
    [0]=>
    string(1) "x"
    [1]=>
    string(1) "y"
    [2]=>
    string(1) "z"
    [3]=>
    array(3) {
      ["nest"]=>
      string(3) "yes"
      ["nest2"]=>
      array(1) {
        ["nest"]=>
        string(40) "some more
                    asffjaskkd"
      }
      ["nest3"]=>
      string(6) "o rly?"
    }
  }
}
string(18) "nsome extra stuffn"

Added:
else if (!empty($trim) && $expecting == 2)
{
    // Expecting close parent or element, but got just a string
    $topArray[$key] .= "\n".$line;
}
ario at mail dot utexas dot [education - 3 letters] 19-Feb-2008 12:34
This is a better print_r reverse algorithm, that works with arbitrary nested arrays.  Anything else it treats as strings.  The second function allows you to take a string with multiple print_r results concatenated, and returns the result of parsing each of them.

<?php

/**
 * @param string &$output : The output of a print_r call; this parameter is DESTRUCTIVE, and will be set to the remainder
 *                             of $output which is not parsed.
 * @return mixed : the first parseable element of $output
 */
function print_r_reverse(&$output)
{
    $expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
    $lines = explode("\n", $output);
    $result = null;
    $topArray = null;
    $arrayStack = array();
    $matches = null;
    while (!empty($lines) && $result === null)
    {
        $line = array_shift($lines);
        $trim = trim($line);
        if ($trim == 'Array')
        {
            if ($expecting == 0)
            {
                $topArray = array();
                $expecting = 1;
            }
            else
            {
                trigger_error("Unknown array.");
            }
        }
        else if ($expecting == 1 && $trim == '(')
        {
            $expecting = 2;
        }
        else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)) // array element
        {
            list ($fullMatch, $key, $element) = $matches;
            if (trim($element) == 'Array')
            {
                $topArray[$key] = array();
                $newTopArray =& $topArray[$key];
                $arrayStack[] =& $topArray;
                $topArray =& $newTopArray;
                $expecting = 1;
            }
            else
            {
                $topArray[$key] = $element;
            }
        }
        else if ($expecting == 2 && $trim == ')') // end current array
        {
            if (empty($arrayStack))
            {
                $result = $topArray;
            }
            else // pop into parent array
            {
                // safe array pop
                $keys = array_keys($arrayStack);
                $lastKey = array_pop($keys);
                $temp =& $arrayStack[$lastKey];
                unset($arrayStack[$lastKey]);
                $topArray =& $temp;
            }
        }
        else if (!empty($trim))
        {
            $result = $line;
        }
    }

    $output = implode(n, $lines);
    return $result;
}

/**
 * @param string $output : The output of a multiple print_r calls, separated by newlines
 * @return mixed[] : parseable elements of $output
 */
function print_r_reverse_multiple($output)
{
    $result = array();
    while (($reverse = print_r_reverse($output)) !== NULL)
    {
        $result[] = $reverse;
    }
    return $result;
}

$output = '
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
            [3] => Array
            (
                [nest] => yes
                [nest2] => Array
                (
                    [nest] => some more
                )
                [nest3] => o rly?
            )
        )
)

some extra stuff
';
var_dump(print_r_reverse($output), $output);

?>

The above example will output:

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  array(4) {
    [0]=>
    string(1) "x"
    [1]=>
    string(1) "y"
    [2]=>
    string(1) "z"
    [3]=>
    array(3) {
      ["nest"]=>
      string(3) "yes"
      ["nest2"]=>
      array(1) {
        ["nest"]=>
        string(9) "some more"
      }
      ["nest3"]=>
      string(6) "o rly?"
    }
  }
}
string(20) "
some extra stuff
"
Goose 06-Feb-2008 03:31
A one line command that serves to nl2br but have it so it displays in html is
function nl2br2($arg){print(nl2br(str_replace(' ','&nbsp;',print_r($arg,true))));}
Kokos 31-Jan-2008 04:52
A simple function that will output an array more easily to read than print_r();

<?php
function echo_array($array,$return_me=false){
    if(is_array($array) == false){
        $return = "The provided variable is not an array.";
    }else{
        foreach($array as $name=>$value){
            if(is_array($value)){
                $return .= "";
                $return .= "['<b>$name</b>'] {<div style='margin-left:10px;'>\n";
                $return .= echo_array($value,true);
                $return .= "</div>}";
                $return .= "\n\n";
            }else{
                if(is_string($value)){
                    $value = "\"$value\"";
                }
                $return .= "['<b>$name</b>'] = $value\n\n";
            }
        }
    }
    if($return_me == true){
        return $return;
    }else{
        echo "<pre>".$return."</pre>";
    }
}
?>
highstrike at gmail dot com 08-Jan-2008 05:34
made 2 nifty functions based of what some people contributed here. Hope you find them usefull

usage ... call for the dump function. EG: dump($array, "Array dump");

<?php
////////////////////////////////////////////////////////
// Function:         dump
// Inspired from:     PHP.net Contributions
// Description: Helps with php debugging

function dump(&$var, $info = FALSE)
{
    $scope = false;
    $prefix = 'unique';
    $suffix = 'value';

    if($scope) $vals = $scope;
    else $vals = $GLOBALS;

    $old = $var;
    $var = $new = $prefix.rand().$suffix; $vname = FALSE;
    foreach($vals as $key => $val) if($val === $new) $vname = $key;
    $var = $old;

    echo "<pre style='margin: 0px 0px 10px 0px; display: block; background: white; color: black; font-family: Verdana; border: 1px solid #cccccc; padding: 5px; font-size: 10px; line-height: 13px;'>";
    if($info != FALSE) echo "<b style='color: red;'>$info:</b><br>";
    do_dump($var, '$'.$vname);
    echo "</pre>";
}

////////////////////////////////////////////////////////
// Function:         do_dump
// Inspired from:     PHP.net Contributions
// Description: Better GI than print_r or var_dump

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#eeeeee;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>";

        $var = $var[$keyvar];
    }
}
?>
bart at mediawave dot nl 30-Oct-2007 04:27
Here's a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage:

void u_print_r ( mixed $expression [, array $ignore] )

Use the $ignore parameter to provide an array of property names that shouldn't be followed recursively.

<?php

function u_print_r($subject, $ignore = array(), $depth = 1, $refChain = array())
{
    if ($depth > 20) return;
    if (is_object($subject)) {
        foreach ($refChain as $refVal)
            if ($refVal === $subject) {
                echo "*RECURSION*\n";
                return;
            }
        array_push($refChain, $subject);
        echo get_class($subject) . " Object ( \n";
        $subject = (array) $subject;
        foreach ($subject as $key => $val)
            if (is_array($ignore) && !in_array($key, $ignore, 1)) {
                echo str_repeat(" ", $depth * 4) . '[';
                if ($key{0} == "\0") {
                    $keyParts = explode("\0", $key);
                    echo $keyParts[2] . (($keyParts[1] == '*')  ? ':protected' : ':private');
                } else
                    echo $key;
                echo '] => ';
                u_print_r($val, $ignore, $depth + 1, $refChain);
            }
        echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
        array_pop($refChain);
    } elseif (is_array($subject)) {
        echo "Array ( \n";
        foreach ($subject as $key => $val)
            if (is_array($ignore) && !in_array($key, $ignore, 1)) {
                echo str_repeat(" ", $depth * 4) . '[' . $key . '] => ';
                u_print_r($val, $ignore, $depth + 1, $refChain);
            }
        echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
    } else
        echo $subject . "\n";
}

?>

Example:

<?php

class test {

    public $var1 = 'a';
    protected $var2 = 'b';
    private $var3 = 'c';
    protected $array = array('x', 'y', 'z');

}

$test = new test();
$test->recursiveRef = $test;
$test->anotherRecursiveRef->recursiveRef = $test;
$test->dont->follow = 'me';

u_print_r($test, array('dont'));

?>

Will produce:

test Object (
    [var1] => a
    [var2:protected] => b
    [var3:private] => c
    [array:protected] => Array (
        [0] => x
        [1] => y
        [2] => z
    )
    [recursiveRef] => *RECURSION*
    [anotherRecursiveRef] => stdClass Object (
        [recursiveRef] => *RECURSION*
    )
)
php at deboom dot biz 21-Sep-2007 05:17
If you need to import an print_R output back to an array you could use this.

This could also be (ab)used to convert a object into a array...

<?php
function object2array($printr) {
        $newarray = array();
        $a[0] = &$newarray;
        if (preg_match_all('/^\s+\[(\w+).*\] => (.*)\n/m', $printr, $match)) {
            foreach ($match[0] as $key => $value) {
                (int)$tabs = substr_count(substr($value, 0, strpos($value, "[")), "        ");
                if ($match[2][$key] == 'Array' || substr($match[2][$key], -6) == 'Object') {
                    $a[$tabs+1] = &$a[$tabs][$match[1][$key]];
                }
                else {
                    $a[$tabs][$match[1][$key]] = $match[2][$key];
                }
            }
        }
        return $newarray;
    }
?>
motin at demomusic dot nu 19-Jun-2007 04:01
This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky...):

<?php
/**
  * An alternative to print_r that unlike the original does not use output buffering with
  * the return parameter set to true. Thus, Fatal errors that would be the result of print_r
  * in return-mode within ob handlers can be avoided.
  *
  * Comes with an extra parameter to be able to generate html code. If you need a
  * human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/
  *
  * Support for printing of objects as well as the $return parameter functionality
  * added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in
  * replacement for print_r (Except for that this function does not output
  * paranthesises around element groups... ;) )
  *
  * Based on return_array() By Matthew Ruivo (mruivo at gmail)
  * (http://se2.php.net/manual/en/function.print-r.php#73436)
  */
function obsafe_print_r($var, $return = false, $html = false, $level = 0) {
    $spaces = "";
    $space = $html ? "&nbsp;" : " ";
    $newline = $html ? "<br />" : "\n";
    for ($i = 1; $i <= 6; $i++) {
        $spaces .= $space;
    }
    $tabs = $spaces;
    for ($i = 1; $i <= $level; $i++) {
        $tabs .= $spaces;
    }
    if (is_array($var)) {
        $title = "Array";
    } elseif (is_object($var)) {
        $title = get_class($var)." Object";
    }
    $output = $title . $newline . $newline;
    foreach($var as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $level++;
            $value = obsafe_print_r($value, true, $html, $level);
            $level--;
        }
        $output .= $tabs . "[" . $key . "] => " . $value . $newline;
    }
    if ($return) return $output;
      else echo $output;
}
?>

Built on a function earlier posted in these comments as stated in the Doc comment. Cheers! /Fredrik (Motin)
mrasnika at users dot sourceforge dot net 26-Apr-2007 11:30
We can all agree that print_r() output is very spartan looking. The debug data needs to be organized better, and presented in a graceful way. In the era of Web 2.0 it is somewhat strange to use plain text to dump information. A DHTML powered informatiion dumping tool will be quite better - like the the open-source alternative of print_r(); -- Krumo (http://krumo.sourceforge.net).

It renders the output using DHTML and collapsible nodes, it's layout is "skinable" and you can change it to fit your aesthetic taste. Krumo makes the output "human-readable" for real :) Plus it is compliant with both PHP4 and PHP5. Plus it detects "reference recursion". Plus you can use it to dump all various sort of data like debug back-traces, the superglobals ($_SERVER, $_ENV, $_REQUEST, $_COOKIE, $_GET, $_POST, $_SESSION), all the included files, all the declared classes, all the declared constants, all your PHP settings, all your php.ini values (if it is readable), all the loaded extensions, all the HTTP request headers, all the declared interfaces (for PHP5), all the file paths from INCLUDE_PATH, all the values of any particular INI file. Additionally it is designed to be easy to use - for example you can disable all the Krumo dumps instead of cleaning your code out of all print_r()'s and var_dump()'s. Anyway, if you check the site (http://krumo.sourceforge.net), you can found a lot of examples, demonstrations, documentation and all sort of helpful information.
Enthusiastic PHPers 22-Mar-2007 12:03
We had an interesting problem dumping an object that
contained embedded HTML. The application makes use
of buffer manipulation functions, so print_r's 2nd argument
wasn't helpful. Here is how we solved the problem:

$object = new ObjectContainingHTML();
$savedbuffercontents = ob_get_clean();
print_r($object);
$print_r_output = ob_get_clean();
ob_start();
echo $savedbuffercontents;
echo htmlentities($print_r_output);
mading25 at hotmail dot com 01-Mar-2007 11:34
None of the function to output to HTML was working for me so I had to write something that suited my needs. It's probably super not efficient but, hey it works well for me on a small scale.

function print_r_html($data,$return_data=false)
{
    $data = print_r($data,true);
    $data = str_replace( " ","&nbsp;", $data);
    $data = str_replace( "\r\n","<br>\r\n", $data);
    $data = str_replace( "\r","<br>\r", $data);
    $data = str_replace( "\n","<br>\n", $data);

    if (!$return_data)
        echo $data;
    else
        return $data;
}

Simple, isn't? :)
Matthew Ruivo (mruivo at gmail) 22-Feb-2007 10:47
For those of you needing to print an array within a buffer callback function, I've created this quick function. It simply returns the array as a readable string rather than printing it. You can even choose whether to return it in normal text-mode or HTML. It's recursive, so multi-dimensial arrays are supported. I hope someone finds this useful!

<?php

    function return_array($array, $html = false, $level = 0) {
        $space = $html ? "&nbsp;" : " ";
        $newline = $html ? "<br />" : "\n";
        for ($i = 1; $i <= 6; $i++) {
            $spaces .= $space;
        }
        $tabs = $spaces;
        for ($i = 1; $i <= $level; $i++) {
            $tabs .= $spaces;
        }
        $output = "Array" . $newline . $newline;
        foreach($array as $key => $value) {
            if (is_array($value)) {
                $level++;
                $value = return_array($value, $html, $level);
                $level--;
            }
            $output .= $tabs . "[" . $key . "] => " . $value . $newline;
        }
        return $output;
    }

?>
sakabako at gmail dot com 07-Feb-2007 12:45
I've got four functions for printing arrays out in a readable fashion, I hope someone finds them useful.

//prints an array in a HTML table. Top row is the keys.
function table( $array ) {
    $array = array_values( $array );

    $keys = array_keys( $array[0] );

    echo '<table border="1"><tr>';
    foreach( $keys as $key ) {
        echo '<td>'.$key.'</td>';
    }
    echo '</tr>';

    foreach( $array as $row ) {
        echo '<tr>';
        foreach( $row as $value ) {
            echo '<td>'.$value.'</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
}

//print_r enclosed in a <pre>, except it will always print something, even if the variable is null, number 0 or false. It also lets you label the dump.
function dump( $var, $label=null ) {
    if( $var === '' or $var === null or $var === 0 ) {
        var_dump( $var );
        return;
    }
    echo '<pre style="text-align: left; font-size: 10px;">';
    if( $label ) {
        echo $label."\n";
    }
    print_r( $var );
    echo '</pre>';
}

//This one gives you output you can copy and paste back into your PHP code to recreate the array.
function dump_array( $array, $tabs=1 ) {
    $html = "<pre style=\"text-align: left; font-size: 10px;\">array( \n";
    foreach( $array as $key => $val ) {
        $html .= str_repeat( "\t", $tabs )."'$key' => ";
        if( is_array( $val ) ) {
            $html .= dump_array( $array, $tabs+1 );
        } else {
            $html .= "'$val',\n";
        }
    }
    $html .= ')</pre>';
    return $html;
}

//just add header( 'content-type: application/vnd.ms-excel' ) and you've got an excel file.
function excel( $array ) {
    $array = array_values( $array );

    $keys = array_keys( $array[0] );

    foreach( $keys as $key ) {
        echo $key."\t";
    }
    echo "\n";

    foreach( $array as $row ) {
        foreach( $row as $value ) {
            echo $value."\t";
        }
        echo "\n";
    }
}
markus (at) maxxmaster (dot) org 17-Jan-2007 06:11
i've been using a similar idea like Sawey's for quite a long time,
but was always disappointed that you don't see the name of the
variable passed to the function (eg calling it many times, you don't
know which value was provided by a certain variable at a certain time).
so i combined sawey's idea with one found on php.net to solve that problem.
for shellscripting the function only uses <pre>-tags when called in the web.

<?php
/* how print_r should be ;) */
function my_r(&$var, $scope=false, $label=false){

  if (is_string($scope) && $label==false) $label=$scope;
  if (!is_array($scope)) $scope = &$GLOBALS;

  $origin = $var;
  $var = $checker = "very_weird_value#".rand()."#isnt_it";
  $vname = false;

  foreach ($scope as $key => $value){
    if ($value === $checker){ $vname = "\$".$key; }
    if (is_array($value) && $key!="GLOBALS"){
      if ($pfad=aver($var,$value)){
        $vname = "\$${key}[\"". implode("\"][\"",$pfad)."\"]";
      }
    }
    if (is_object($value)){
      if ($pfad=aver($var,get_object_vars($value))){
        if (sizeof($pfad)<2) $vname = "\$${key}->".$pfad[0];
        else{
          $vname ="\$${key}->".$pfad[0];
          $vname.="[\"".implode("\"][\"", array_slice($pfad,1))."\"]";
        }
      }
    }
    if ($vname) break;
  }
  $var = $origin;

  if ($_SERVER["SERVER_NAME"] && !isset($_SERVER["TERM"])) echo "<pre>";
  if ($vname){
    echo $vname;
    if ($label) echo " #" . $label . "# ";
    else echo ": ";
  }else{
    if ($label) echo "$label: ";
  }
  print_r($var);
  if ($_SERVER["SERVER_NAME"] && !isset($_SERVER["TERM"])) echo "</pre>";
}

/* this function is needed to check in multidimensional arrays
if the value of interest exists. if yes, the path is returned */
function aver($needle,$haystack) { // array value exists recursive
  foreach($haystack as $key=>$val) {
    if(is_array($val) && $needle != $val && $key != "GLOBALS") {
      if($foo=aver($needle,$val)) return array_merge(array($key),$foo);
    }elseif($val === $needle) return array($key);
  }
  return false;
}
?>
markus (at) maxxmaster (d0t) org 17-Jan-2007 05:33
Explanation:
The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope ( semi recursively ) the variable is contained in and when there is a match of our modified value, we can grab the correct key and output the name.

Bugs:
You can see in the 5th Example, that the so-called non-existant variable infact exists ;|, the problem with referenced variables (as used in the my_r function) is, that they have to exist at call-time to reference them. that is why my_r("test") will result in a fatal error. if you have ideas to solve that, don't hesitate to mention them.

Examples:

1.  Use of a variable contained in the global scope (default):
<?php
  $my_global_variable = array("nice", "try", "guybrush");
  my_r($my_global_variable);

/* Outputs:
$my_global_variable: Array
(
    [0] => nice
    [1] => try
    [2] => guybrush
)
*/
?>

2.  Use of a local variable (in a function):
<?php
function my_local_function()
{
  $my_local_variable = array("nice", "try", "guybrush");
  my_r($my_local_variable,get_defined_vars());
}
my_local_function();

/* Outputs:
$my_local_variable: Array
(
    [0] => nice
    [1] => try
    [2] => guybrush
)
*/
?>

3.  Use of an object property:
<?php
class myclass{
  public function __constructor(){ // depending on php version ;)
    $this->my_object_property = array("nice", "try", name => array("guybrush"));
  }
  public function myclass(){ // depending on php version ;)
    $this->my_object_property = array("nice", "try", name => array("guybrush"));
  }
}

$obj = new myclass;
my_r($obj->my_object_property);
/* Outputs:
$obj->my_object_property: Array
(
    [0] => nice
    [1] => try
    [name] => Array
        (
            [0] => guybrush
        )

)
*/
?>

4. Use of a sub-array and an additional label
<?php
$foo=array("nice","try",name => array("guybrush","threapwood"))
my_r($foo["name"],"position 1");
/* Outputs:
$foo["name"] #position 1# Array
(
    [0] => guybrush
    [1] => threapwood
)
*/
?>

5. Use of non existant Variables (standard-behaviour of print_r)
<?php
my_r($foo=array("nice","try","guybrush"));
/* Outputs:
Array
(
    [0] => nice
    [1] => try
    [2] => guybrush
)
*/
?>
SaWey @ localdomain 15-Jan-2007 11:44
I've seen a lot of tries to give an easy way to output the "print_r" info in a decent way in you favorite browser.

Here's mine:

echo ("<pre>");
print_r("-->here goes your data to output<--");
echo ("<pre>");

I personaly think this is the easyest way.
Grz
auditor400 at gmail dot com 02-Nov-2006 07:56
some functions I find useful for debugging.
/**
 *    dump the object in a base.class.php :: print_r2() fashon
     this function is for debugging purposes only (obviously)
    @see d2()
    @param $obj an array of elements, that may have elements that are also arrays.
    @param $color the color of the output (useful, when you need to call this several times,
    and you need a certain structure to stand out from the others, or simply to differentiate them)
    color-coding stuff is a great wa to work, consider this:
    @code
    p2($struct,'red');
    @endcode

        to find the function call, just search "red".
        in case you find yourself lost, you can always sue the line numbers, @see $dinfo

    @param $dinfo see http://www.php.net/debug_backtrace for nifo on debug info.,
        0: no info, 1: function call, 2: full backtrace.
        @param $title simple remarks you can put to aid you in development. i.e.
        @code
        $a=array(1,2,3,5,6)

        //this

        p2($a,'',0,'the numbers');

        //is more meaningful than this:

        p2($a);

        @code
        This is particulary true when dealing with many p2()

        It is recomended that you *don't* delete p2()'s calls from your code,
        but rather document them:
        @code

        //insightfull comments about spected output
        //p2($a123,'',1,'Items in list')

        @endcode

        or, if you feel more confortable with logging, use this:
        $this->log(gp2($struct)); @see gp2()

        You can also use p2() as a call trace: helper

        @code
        function a(){
            b();
        }

        function b(){
            c();
        }
        function d(){
            a();
        }

        function c(){
            p2(1,'',2,'backtrace');
        }

        d();
        @endcode

        note the use of p2(1), as a simple backtrace enables, you can use
        p2($anything,'',2) to display the log, or p2($anything) to show the call route.

        the call route follows the following format:

        @ file : function : function_call_line_number -> current_line_number

        i.e.

        @std.php:filter_link():1222->2142

        where current line number is the line where the p2() call is, and "function call number"
        is the line where the current function was called from (useful as hell).

        --

 * */
    function p2($obj,$color='black',$dinfo=1,$title=''){
        //echo();
        $dbg=debug_backtrace();
        if($dinfo!=0){
            //':'.$dbg[1]['class'].
            $dinfo="@".basename($dbg[1]['file']).':'.$dbg[1]['function'].'():'.
                $dbg[1]['line'].'->'.$dbg[0]['line']."\n";
        }
        if($dinfo==2){
            $dinfo.=print_r(debug_backtrace(),true);
        }
        if($color==''){$color='rgb(50,50,200)';}
        echo("<h3 style='color:$color'>".$title.'</h3><xmp style="color:'.$color.'">'.
        $dinfo.print_r($obj,1)."</xmp>");
    }
    function gp2($obj,$color='black'){
        return("<xmp style='color:$color'>".print_r($obj,1)."</xmp>");
    }

    /**
     * @see d2()
     * */
    function d2_recursive($obj,$label='',$color='rgb(100,100,100)'){
        if(is_array($obj)){
            $dx="\n<table style='border:1px solid ".$color."' cellspacing=0 cellpadding=2 width=100%>";
            if($label!=''){
                $dx.="\n<tr><td style='background-color:".$color.";border:1px solid ".$color.
                    "' colspan=2>".$label."</td></tr>";
            }
            foreach($obj as $k=>$v){
                $dx.="\n<tr><td style='width:1%;color:white;font-weight:bold;font-family:verdana;".
                    "font-size:10pt;background-color:".$color.";border:1px solid ".$color."'>".$k
                    .'</td><td style="border:1px solid '.$color.'">';
                $dx.=d2_recursive($v,'',$color)."</td></tr>";
            }
            $dx.="\n</table>";
        }else{
            $dx=$obj;
        }
        return($dx);
    }
    /** \brief nice html object inspector
     * @see p2()
     * */
    function d2($obj,$label='',$color='black'){
        echo("\n<!--DUMP:$label START-->\n".d2_recursive($obj,$label,$color)."\n<!--DUMP END-->\n");
    }
Dmitry Kochin <dco at mail dot ru> 08-Sep-2006 01:20
Sometimes print_r produces large output, especially when the data hierarchy is too deep. It is very difficult to analyze the dump about 1Mb length.

It would be great to have some way to fold arrays and objects and to look deeper into hierarchy only on demand.

Here is the solution. Just pass the print_r output to debug_var function:

debug_var('title', print_r($var, true));

and it will produce nice html with folding option.

<?php
  ob_start();
?>
Locals: Array
(
    [arr] => Array
        (
            [0] => Bon Object
                (
                    [n] => id
                    [v] => 1
                    [dv] =>
                    [dn] =>
                )

        )

    [b] => Bon Object
        (
            [n] => id
            [v] => 1
            [dv] =>
            [dn] =>
        )

    [k] => 0
    [row] => Array
        (
            [aid] => 1
            [bonus] => spell.id: 125;
            [req] =>
            [brcache] =>
            [auto] => 0
        )

    [sp] =>
)
<?php
  $str = ob_get_contents();
  ob_end_clean();

  debug_var('locals', $str);

function debug_var($name,$data)
{
    $captured = preg_split("/\r?\n/",$data);
    print "<script>function toggleDiv(num){
      var span = document.getElementById('d'+num);
      var a = document.getElementById('a'+num);
      var cur = span.style.display;
      if(cur == 'none'){
        a.innerHTML = '-';
        span.style.display = 'inline';
      }else{
        a.innerHTML = '+';
        span.style.display = 'none';
      }
    }</script>";
    print "<b>$name</b>\n";
    print "<pre>\n";
    foreach($captured as $line)
    {
        print debug_colorize_string($line)."\n";
    }
    print "</pre>\n";
}

function next_div($matches)
{
  static $num = 0;
  ++$num;
  return "$matches[1]<a id=a$num href=\"javascript: toggleDiv($num)\">+</a><span id=d$num style=\"display:none\">(";
}

/**
* colorize a string for pretty display
*
* @access private
* @param $string string info to colorize
* @return string HTML colorized
* @global
*/
function debug_colorize_string($string)
{
    $string = preg_replace("/\[(\w*)\]/i", '[<font color="red">$1</font>]', $string);
    $string = preg_replace_callback("/(\s+)\($/", 'next_div', $string);
    $string = preg_replace("/(\s+)\)$/", '$1)</span>', $string);
    /* turn array indexes to red */
    /* turn the word Array blue */
    $string = str_replace('Array','<font color="blue">Array</font>',$string);
    /* turn arrows graygreen */
    $string = str_replace('=>','<font color="#556F55">=></font>',$string);
    return $string;
}
?>

This example uses ideas from this article:
http://www.zend.com/zend/tut/tutorial-DebugLib.php
ohira (atto) web. de 13-Apr-2006 07:01
Bases on thbley´s sript i use this one to log some actions.
It will return a tabbed like string which you can output or whatever.

Input fields like "Password" will not be shown.

<?php

function print_r_string($arr,$first=true,$tab=0)
{
    $output = "";
    $tabsign = ($tab) ? str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$tab) : '';
    if ($first) $output .= "<pre><br>\n";
    foreach($arr as $key => $val)
    {
        switch (gettype($val))
        {
            case "array":
                $output .= $tabsign."[".htmlspecialchars($key)."] = array(".count($val).")<br>\n".$tabsign."(<br>\n";
                $tab++;
                $output .= print_r_string($val,false,$tab);
                $tab--;
                $output .= $tabsign.")<br>\n";
            break;
            case "boolean":
                $output .= $tabsign."[".htmlspecialchars($key)."] bool = '".($val?"true":"false")."'<br>\n";
            break;
            case "integer":
                $output .= $tabsign."[".htmlspecialchars($key)."] int = '".htmlspecialchars($val)."'<br>\n";
            break;
            case "double":
                $output .= $tabsign."[".htmlspecialchars($key)."] double = '".htmlspecialchars($val)."'<br>\n";
            break;
            case "string":
                $output .= $tabsign."[".htmlspecialchars($key)."] string = '".((stristr($key,'passw')) ? str_repeat('*', strlen($val)) : htmlspecialchars($val))."'<br>\n";
            break;
            default:
                $output .= $tabsign."[".htmlspecialchars($key)."] unknown = '".htmlspecialchars(gettype($val))."'<br>\n";
            break;
        }
    }
    if ($first) $output .= "</pre><br>\n";
    return $output;
}

echo print_r_string(array($_POST,$_GET)); // for Example
?>
sanya at hik dot hu 05-Apr-2006 07:13
I find a possibly bug, when I wanted to print the structure of a DOMDocument or a DOMDocumentType object.
print_r() outputs the object type correctly, but the properties are missing.

$doc = $imp->createDocument();
$doc->loadXML($xmlString);
print_r($doc->doctype);

the code outputs:

DOMDocumentType Object
(
)

But the subobjects of $doc->doctype exist.
reinder at fake-address dot com 31-Jan-2006 09:09
I always use this function in my code, because most of my functions return an Array or Boolean :

<?php

function printr ( $object , $name = '' ) {

    print ( '\'' . $name . '\' : ' ) ;

    if ( is_array ( $object ) ) {
        print ( '<pre>' )  ;
        print_r ( $object ) ;
        print ( '</pre>' ) ;
    } else {
        var_dump ( $object ) ;
    }

}

?>

( print_r gives no output on FALSE and that can be annoying! )
thbley at gmail dot com 16-Nov-2005 12:10
Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)

<?php
header('Content-Type: text/xml; charset=UTF-8');
echo print_r_xml($some_var);

function print_r_xml($arr,$first=true) {
  $output = "";
  if ($first) $output .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<data>\n";
  foreach($arr as $key => $val) {
    if (is_numeric($key)) $key = "arr_".$key; // <0 is not allowed
    switch (gettype($val)) {
      case "array":
        $output .= "<".htmlspecialchars($key)." type='array' size='".count($val)."'>".
          print_r_xml($val,false)."</".htmlspecialchars($key).">\n"; break;
      case "boolean":
        $output .= "<".htmlspecialchars($key)." type='bool'>".($val?"true":"false").
          "</".htmlspecialchars($key).">\n"; break;
      case "integer":
        $output .= "<".htmlspecialchars($key)." type='integer'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      case "double":
        $output .= "<".htmlspecialchars($key)." type='double'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      case "string":
        $output .= "<".htmlspecialchars($key)." type='string' size='".strlen($val)."'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      default:
        $output .= "<".htmlspecialchars($key)." type='unknown'>".gettype($val).
          "</".htmlspecialchars($key).">\n"; break;
    }
  }
  if ($first) $output .= "</data>\n";
  return $output;
}

?>
jamin42b at gmail dot com 02-Sep-2005 05:52
Here's a short function that can export php arrays to javascript arrays.

<?php

function php_to_js($array, $base) {
    $js = '';
    foreach ($array as $key=>$val) {
        if (is_array($val)) {
            $js .= php_to_js($val, $base.(is_numeric($key) ? '['.$key.']' : "['".addslashes($key)."']"));
        } else {
            $js .= $base;
            $js .= is_numeric($key) ? '['.$key.']' : "['".addslashes($key)."']";
            $js .= ' = ';
            $js .= is_numeric($val) ? ''.$val.'' : "'".addslashes($val)."'";
            $js .= ";\n";
        }
    }
    return $base." = new Array();\n".$js;
}

?>

Example use:

<?php
$my_array = array('gdsag' => 4, 'hello', array(5, 6));
echo '<script>'.php_to_js($my_array).'</script>';
?>

This would output:

<script>
jsvarname = new Array();
jsvarname['gdsag'] = 4;
jsvarname[0] = 'hello';
jsvarname[1] = new Array();
jsvarname[1][0] = 5;
jsvarname[1][1] = 6;

</script>

Now the array is loaded in the browser as javascript. As you can see, it supports multidimensional arrays too.
warhog at warhog dot net 11-Aug-2005 05:01
For very long arrays I have written a little function which formats an array quite nice and uses javascript for browsing it like a tree. The function is very customizable with the $style parameter.
For me it's of great use for browsing large array's, for example when those are used in language-files in some script and so on. It may even be used in "real" scripts for the "real" front-end, cause the tree can very easily be styled (look at the function or the outputted source and you'll see what i mean).

Here's the function:

<?php

function print_r_html($arr, $style = "display: none; margin-left: 10px;")
{ static $i = 0; $i++;
  echo "\n<div id=\"array_tree_$i\" class=\"array_tree\">\n";
  foreach($arr as $key => $val)
  { switch (gettype($val))
    { case "array":
        echo "<a onclick=\"document.getElementById('";
        echo array_tree_element_$i."').style.display = ";
        echo "document.getElementById('array_tree_element_$i";
        echo "').style.display == 'block' ?";
        echo "'none' : 'block';\"\n";
        echo "name=\"array_tree_link_$i\" href=\"#array_tree_link_$i\">".htmlspecialchars($key)."</a><br />\n";
        echo "<div class=\"array_tree_element_\" id=\"array_tree_element_$i\" style=\"$style\">";
        echo print_r_html($val);
        echo "</div>";
      break;
      case "integer":
        echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
      break;
      case "double":
        echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
      break;
      case "boolean":
        echo "<b>".htmlspecialchars($key)."</b> => ";
        if ($val)
        { echo "true"; }
        else
        { echo "false"; }
        echo  "<br />\n";
      break;
      case "string":
        echo "<b>".htmlspecialchars($key)."</b> => <code>".htmlspecialchars($val)."</code><br />";
      break;
      default:
        echo "<b>".htmlspecialchars($key)."</b> => ".gettype($val)."<br />";
      break; }
    echo "\n"; }
  echo "</div>\n"; }

?>

The function as it is now does not support the $return parameter as print_r does and will create an endless loop like print_r did in php-versions < 4.0.3 when there is an element which contains a reference to a variable inside of the array to print out :-/

I've tested it with PHP 5.0.6 and PHP 4.2.3 - no problems except those already mentioned.

please e-mail me if you've got a solution for the problems i've mentioned, i myself are not able to solve them 'cause i don't know how the hell i can find out whether a variable is a reference or not.
nicky dot weber at siner dot de 11-Jun-2005 02:13
Print arrays formatted for a browser easily:

<?php
function print_html_r( $aData ) {
    echo nl2br( eregi_replace( " ", " ", print_r( $data, TRUE ) ) );
}
?>
general at NOSPAMbugfoo dot com 20-Jan-2005 01:23
You can't use print_r($var, TRUE) inside a function which is a callback from ob_start() or you get the following error:
Fatal error: print_r(): Cannot use output buffering in output buffering display handlers
isset
serialize
Функции для работы с переменными


Генерирует пригодное для хранения представление переменной

print_r
settype
Функции для работы с переменными
PHP Manual

serialize

(PHP 4, PHP 5)

serialize — Генерирует пригодное для хранения представление переменной

Описание

string serialize ( mixed $value )

Генерирует пригодное для хранения представление переменной

Это полезно для хранения или передачи значений PHP между скриптами без потери их типа и структуры.

Для превращения сериализованной строки обратно в PHP-значение, используйте функцию unserialize().

Список параметров

value

Значение, которое необходимо сериализовать. serialize() обрабатывает все типы, кроме resource. Возможно также сериализовать массивы, которые содержат ссылки на себя. Циклические ссылки внутри сериализуемого массива/объекта также сохраняются. Любые другие ссылки будут потеряны.

При сериализации объекта PHP пытается вызвать магический метод __sleep() перед сериализацией. Это делается для того, чтобы позволить объекту в последний момент произвести очистку и тому подобные операции перед сериализацией. Аналогично, когда объект восстанавливается функцией unserialize(), вызывается магический метод __wakeup().

Замечание:

В начало имен приватных членов объекта дополняется имя класса, а в начало имен защищенных членов '*'. Эти дополненные значения окружаются нулевым байтом (0x00) с обеих сторон.

Возвращаемые значения

Возвращает строку, содержащую потоковое представление переменной value, которая может быть сохранена где угодно.

Примеры

Пример #1 Пример использования serialize()

<?php
// $session_data содержит многомерный массив с сессионной
// информацией о текущем пользователе. Мы используем serialize() для сохранения
// этой информации в базе данных в конце запроса.

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, $sqldata)) {
        /* Код, выполняемый при ошибке.. */
    }
}
?>

Список изменений

Версия | Описание
4.0.7 | Был исправлен процесс сериализации объектов.

Примечания

Замечание:

Заметьте, что много встроенных в PHP объектов не может быть сериализовано. Однако, те из них, которые поддерживают эту возможность, реализуют или интерфейс Serializable, или магические методы __sleep() и __wakeup(). Если встроенный класс не удовлетворяет этим требованиям, он не может быть надежно сериализован.

Исторически есть некоторые исключения из вышеуказанного правила, когда некоторые внутренние объекты могут быть сериализованы без реализации интерфейса или магических методов. К примеру, ArrayObject до PHP 5.2.0.

Смотрите также

  • unserialize() - Создает PHP-значение из хранимого представления
  • Сериализация объектов
  • __sleep()
  • __wakeup()

User Contributed Notes

Anonymous 28-Feb-2012 07:44
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

I've encountered this too many times in my career, it makes for difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
tickthokk at gmail dot com 02-May-2011 11:39
On the topic of serialization, the comments seemed split on which was faster: serialize() or json_encode().

I used an array with a serialized strlen() of 1604.

At 5,000 itterations, serialize won over (by .0001 seconds).  At 50,000 itterations, serialize still won.  I then tested it with the suggested gzcompress() and base64_encode() combo.  Both times json_encode won; first by .25 seconds, and second (at 50k) 2.85 seconds.

However, that's only half the battle.  Please take into consideration the difference between unserialize() and json_decode().  In every instance, unserialize() was always faster.  In the 5k test, it was faster by .22 seconds (.13 with compression).  In the 50k test, it was faster by 2.4 seconds (1.8 with compression).

Even if serialize() has it's downfalls, unserialize() balances that out.
jmanuel at ciges dot net 29-Apr-2011 08:03
Hello,

I wanted to serialize a complex array (an array of arrays with a few levels, it's a configuration file) and I think I have found a bug in the 'serialize' function. I work with PHP 5.2.5 (from SLES 10).

I had as result always the string "N;". This value corresponds to NULL value.

So I did my own 'serialize' function. Here it is in case you had the same problem.

<?php
    # Function which returns serialization string for a scalar value
    private function ser_value($value)    {
        if (is_null($value))    {  return "N";  }
        elseif (is_bool($value))    {  return $value ? "b:0":"b:1";  }
        elseif (is_integer($value))    {  return "i:".$value;  }
        else    {  return "s:".strlen($value).":\"".$value."\"";  }
        }

    # Recursive function which returns serialization string for an array
    function serialize_data($array)    {
        $n = count($array);
        $result = "a:".$n.":{";
        $i = 1;
        foreach ($array as $key => $value)    {
            $result .= ser_value($key).";";
            $result .= (is_array($value)) ? serialize_data($value) : ser_value($value).";";
            }
        $result .= "}";

        return $result;
        }
?>

Greetings from Spain

José M. Ciges
kevin at tra dot as 13-Apr-2011 12:45
In addition to base64_encode(), save space in the DB by compressing the serialized object.  As follows:

<?php
mySerialize( $obj ) {
   return base64_encode(gzcompress(serialize($obj)));
}

myUnserialize( $txt ) {
   return unserialize(gzuncompress(base64_decode($txt)));
}
?>
pgl at yoyo dot org 03-Feb-2011 09:13
Another suggestion for coping with binary data in serialize()d variables is just to base64_encode() those fields before serializing. It will increase the size of the variable, but not by too much.
reiners dot joh at googlemail dot com 18-Jan-2011 11:02
I just realized a certain behaviour when I serialize objects, store them in $_SESSION and unserialize them after a reload.
More precisely, static fields of the object will be available when serializing/unserializing but NOT when you do a page reload.

This is because the static fields are on class level, and certainly, the classes will be completly initialized again when you do a page reload.
Actually that behaviour is correct, but i spent long long time to debug a script before i actually realized this.

<?php
session_start();
echo "<pre>Press F5

";
class MyClass {
    //static variable
    static private $foo_static;
    //normal variable
    private $foo = null;

    static function getString_static() {
        return self::$foo_static;
    }

    static function setString_static($str) {
        self::$foo_static = $str;
    }

    function setString($str) {
        $this->foo = $str;
    }

    function getString() {
        return $this->foo;
    }

}
if (!isset($_SESSION['myObj'])) {
    $myObj = new MyClass();
    $myObj->setString_static("Will NOT be stored!!!");
    $myObj->setString("Will be stored");

    echo "Print content: \n";
    echo 'Normal Var: ' . $myObj->getString() . "\n";
    echo 'Static Var: ' . $myObj->getString_static();

    echo "\t\n\nNow serialize and unserialize object\n";
    $myObj = unserialize(serialize($myObj));

    echo "And print again..\n";
    echo 'Normal Var: ' . $myObj->getString() . "\n";
    echo 'Static Var: ' . $myObj->getString_static();

    //Store object in session
    $_SESSION['myObj'] = serialize($myObj);

} else {
    //if myobj was stored
    $myObj_loaded = unserialize($_SESSION['myObj']);

    echo "Print content when serialized, stored in session and unserialized after a relaod:\n";
    echo 'Normal Var: ' . $myObj_loaded->getString() . "\n";
    echo 'Static Var: ' . $myObj_loaded->getString_static();

    unset($_SESSION['myObj']);
}

?>
</pre>
jcastromail at yahoo dot es 26-Oct-2010 05:05
i did a benchmark between serialization and json_serialize and i found that serialize is 12% fast than json_encode (no tag, php 5.2.12).

I used this array as a example of serialization (10'000 iterations)
<?php
$arr=array(
   "in"=>array("in1"=>"valin1","in2"=>506,"in33"=>"valin3")
   ,"out"=>array("in1"=>"valin1","in2"=>"valin2"));
?>
and unserialize is 70% fast than json_decode.

in conclusion:
a) as expected, serialize is the fast way to.. ahem, serialize objects and array (at least for some complex cases).
b) but json produce a smaller string (and is more standard).
Anonymous 16-Oct-2010 11:03
if you just want a way to store array as string, you should use "json_encode" and "json_decode" because:

1. json_encode + json_decode is much faster than serialize + unserialize

2. json format is readable

3. json format is smaller than serialized result
regality at gmail dot com 27-May-2010 03:30
serialize can be a handy tool for protecting against page expirations if you are using POST's.

In my code I call the following function whenever I detect that the page has expired.

<?php
function savePost() {
    // Save this in the login form
    if (isset($_POST['savePost'])) {
        echo "<input type='hidden' name='savePost' value=\"{$_POST[savePost]}\">";
    } else {
        $savePost = htmlspecialchars(serialize($_POST));
        echo "<input type='hidden' name='savePost' value=\"$savePost\">";
    }
}
?>

and when I load each page I call the function:

<?php
function restorePost() {
    if (isset($_POST[savePost])) {
        $_POST = unserialize(stripslashes(htmlspecialchars_decode($_POST[savePost])));
    }
}
?>

That way if a user takes a long time doing something, they can re-authenticate and have their work restored.
travis at travishegner dot com 02-Mar-2010 12:37
If serializing objects to be stored into a postgresql database, the 'null byte' injected for private and protected members throws a wrench into the system. Even pg_escape_bytea() on the value, and storing the value as a binary type fails under certain circumstances.

For a dirty work around:
<?php

$serialized_object = serialize($my_object);
$safe_object = str_replace("\0", "~~NULL_BYTE~~", $serialized_object);

?>

this allows you to store the object in a readable text format as well. When reading the data back:

<?php

$serialized_object = str_replace("~~NULL_BYTE~~", "\0", $safe_object);
$my_object = unserialize($serialized_object);

?>

The only gotcha's with this method is if your object member names or values may somehow contain the odd "~~NULL_BYTE~~" string. If that is the case, then str_replace() to a string that you are guaranteed not to have any where else in the string that serialize() returns.
Also remember to define the class before calling unserialize().

If you are storing session data into a postgresql database, then this workaround is an absolute must, because the $data passed to the session's write function is already serialized.

Thanks,
Travis Hegner
darlan at rdacom.com.br 09-Feb-2010 10:54
I've made a simple code to serialize small arrays.. may be useful if someone needs to read the data in JS or store the array in database in a simple format. base64_encode/decode functions in JS can be found over the web...

<?php
function array2str($array,$level=1) {
  $str = array();
  foreach($array as $key=>$value) {
    $nkey = base64_encode($key);
    $nvalue = is_array($value)?'$'.base64_encode(array2str($value)) : (string)base64_encode($value);
    $str[] = $nkey.'&'.$nvalue;
    //printf("Encoded %s,%s to %s,%s\n",$key,$value,$nkey,$nvalue);
  }
  return implode('|',$str);
}
function str2array($str) {
  $rest = array();
  if(strpos($str,'|')>0) {
    $array = explode('|',$str);
  } else $array=array($str);

  foreach($array as $token) {
    list($key,$value) = explode('&',$token);
    $nkey=base64_decode($key);
    $nvalue = (    substr($value,0,1) != '$' ? base64_decode($value) : str2array(base64_decode(substr($value,1))) );
    $rest[$nkey] = $nvalue;
    //printf("Decoded %s,%s to %s,%s\n",$key,$value,$nkey,$nvalue);
  }
  return $rest;
}
?>

[]'s
Anonymous 21-Jan-2010 09:23
you should really use mysql_real_escape_string() for escaping (serialized) strings that got thrown into a query (visit php.net/mysql_real_escape_string for further information)
Alastair Lynn 16-Sep-2009 01:46
This may be obvious, but for the record: as of the time of writing (PHP 5.3.0) you can't serialise a Closure object.
donotmail at me dot com 02-Sep-2009 11:16
NOTE: php's serialize does not properly serialize arrays with which a slice of the array is a reference to the array itself, observe:

<?php
$a = array();
$a[0] = "blah";
$a[1] =& $a;

$a[1][0] = "pleh"; // $a[0] === "pleh"

$b = unserialize(serialize($a));

// $b[0] == "pleh", $b[1][0] == "pleh"

$b[1][0] = "blah";
?>

now $b[1][0] == "blah", but $b[0] == "pleh"
after serializing and unserializing, slice 1 is no longer a reference to the array itself... I have found no way around this problem... even manually modifying the serialized string from
'a:2:{i:0;s:4:"pleh";i:1;a:2:{i:0;s:4:"pleh";i:1;R:3;}}'
to
'a:2:{i:0;s:4:"pleh";i:1;R:1;}'

to force the second slice to be a reference to the first element of the serialization (the array itself), it seemed to work at first glance, but then unreferences it when you alter it again, observe:

<?php
    $testser = 'a:2:{i:0;s:4:"pleh";i:1;R:1;}';

    $tmp = unserialize($testser);

    print_r($tmp);

    print "\n-----------------------\n";

    $tmp[1][0] = "blah";

    print_r($tmp);

?>

outputs:
Array
(
    [0] => pleh
    [1] => Array
 *RECURSION*
)

-----------------------
Array
(
    [0] => pleh
    [1] => Array
        (
            [0] => blah
            [1] => Array
                (
                    [0] => pleh
                    [1] => Array
 *RECURSION*
                )

        )

)
Alessandro Segala 17-Jul-2009 08:18
I needed to serialize an array to store it inside a database.
I was looking for a fast, simple way to do serialization, and I came out with 2 options: serialize() or json_encode().

I ran some benchmarks to see which is the faster, and, surprisingly, I found that serialize() is always between 46% and 96% SLOWER than json_encode().
So, if you don't need to serialize objects and have the json extension available, consider using it instead of serialize().
NWdev 08-Jun-2009 07:27
If you're serializing a small array of values and sending them from page to page for display/navigation purposes (versus storing them as session values) via $_GET, save yourself some time and ensure your php.ini magic_quotes_gpc values are set the same on your hosting and localhost severs.

In my case I had magic_quotes_gpc OFF locally, and it took a while to see why the values weren't unserializing properly (actually at all -- unserialize produced FALSE) on the action page (form action page) of the hosted version. A quick look at phpinfo() showed a difference -- Thanks to others mentioning use of magic_quotes when saving to mysql triggered a thot that this mismatch might cause the problem.
Chieftl (chieftl at ua dot fm) 27-Sep-2008 02:32
I think serialized data must be compact. But serialize() function saves float values in bulky format. It possible to squeeze float values, using preg_replace():
<?php
$val = 3.14159;
var_dump($val);  // initial value: float(3.14159)
$val = serialize($val);
var_dump($val);  // standart float format: string(55) "d:3.14158999999999988261834005243144929409027099609375;"
$val = preg_replace('/d:([0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?);/e', "'d:'.((float)$1).';'", $val);
var_dump($val);  // compact float format: string(10) "d:3.14159;"
$val = unserialize($val);
var_dump($val);  // unserialization successed: float(3.14159)
?>
In result becomes slowly serilization, but faster unserialization and less disk space.

WARNING! Some values can be rounded off
<?php
$val = 1/3;
var_dump($val);  // initial value: float(0.333333333333)
$val = serialize($val);
var_dump($val);  // standart float format: string(55) "d:0.333333333333333303727386009995825588703155517578125;"
$val = preg_replace('/d:([0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?);/e', "'d:'.((float)$1).';'", $val);
var_dump($val);  // compact float format: string(10) "d:0.333333333333;"
$val = unserialize($val);
var_dump($val);  // unserialization successed: float(0.333333333333)
$val = serialize($val);
var_dump($val);  // but value is rounded off!: string(55) "d:0.3333333333330000147753935380023904144763946533203125;"
?>

WARNING! Do not use for recursive serializations (serialize(serialize(...)))!

Sorry for my poor English.
Aditya P Bhatt (adityabhai at gmail dot com) 31-Mar-2008 03:29
Here is a simple code to understand serialize function:

<?php
class dog {

    var $name;
    var $age;
    var $owner;

    function dog($in_name="unnamed",$in_age="0",$in_owner="unknown") {
        $this->name = $in_name;
        $this->age = $in_age;
        $this->owner = $in_owner;
    }

    function getage() {
        return ($this->age * 365);
    }

    function getowner() {
        return ($this->owner);
    }

    function getname() {
        return ($this->name);
    }
}
?>
<body bgcolor=white>
<h1>Beware the dog</h1>
<?php
$ourfirstdog = new dog("Rover",12,"Lisa and Graham");
$dogdisc = serialize($ourfirstdog);

$pet = unserialize($dogdisc);
$old = $pet->getage();
$name = $pet->getname();
print "Our first dog is called $name and is $old days old<br>";
print $dogdisc;
?>
Marek Soldt 21-Nov-2007 09:50
serialize() and unserialize() behave a bit crazy if you try to work with bigger strings (100kb of size). It helps to divide the string parts to array:

<?php
// string in $data
                $ko = 4096;
                $data2 = array();
                for($i=0;$i<ceil(strlen($data) / $ko);$i++) {
                  $data2[] = substr($data,($i * $ko),(($i+1) * $ko));
                }
// prepared array in $data2
?>

...before serialize()

and

<?php
// array in $data2
              $data = '';
              for($i=0;$i<count($data2);$i++) {
                $data .= $data2[$i];
              }
// your string in $data
?>

...after unserialize()
Feral 15-Nov-2007 07:30
While it may not be recommended, it is possible to convert an object to another class while conserving all of its properties (public, protected and private), using serialize.

<?php
function cast_class($object, $newclass)
{
    if( !is_object($object) )
    {
        trigger_error('cast_class expects parameter 1 to be object, ' . gettype($object) . ' given', E_USER_WARNING);
        return false;
    }
    if( !class_exists($newclass) )
    {
        // We'll save unserialize the work of triggering an error if the class does not exist
        trigger_error('Class ' . $newclass . ' not found', E_USER_ERROR);
        return false;
    }
    $serialized_parts = explode(':', serialize($object));
    $serialized_parts[1] = strlen($newclass);
    $serialized_parts[2] = '"' . $newclass . '"';
    return unserialize(implode(':', $serialized_parts));
}

?>

Please note that several built-in classes (or classes that are declared in PECL extensions) will not behave as PHP-declared classes and will ne be able to be serialized properly. Because of that, you will not be able to change their class using this function.

Please also note that serialize and unserialize are memory-hungry functions.
barbuj at NOSPAM dot yahoo dot com 14-Nov-2007 02:19
In my specific situation, I wanted to be able to pass some data from page to page, but without relying on a session variable. The answer I came up with was to serialize() the object in question, pass it on to the next page as a hidden form field, then unserialize() it. When ALL class variables are public, this worked fine. However, if there was at least one private/protected variable, the code no longer worked as expected ("Fatal error: Call to a member function display() on a non-object in page2.php on line 4")

As others have already mentioned, private/protected class variables will not behave nicely (private variables are prefixed by class_name + &#65533;, while protected variables are only prefixed by &#65533; - when looking at the page source using Firefox). Internet Explorer does NOT display the extra character between the class name and variable name, but the code still doesn't work as one would expect.

Suppose you have a simple class:

testclass.php
=============
<?php
class TestClass {
  var $i = 1;

  function display() {
    echo "i=" . $this->i;
  }
?>

page1.php
=========
<?php
  require_once 'testclass.php';
  $tc = new TestClass;
  $tc->display();
?>
<form method = "post" action = "page2.php">
<input type = "hidden" name = "str" value = "<?php echo htmlspecialchars( serialize( $tc ) ); ?>">
<input type = "submit">
</form>

page2.php
=========
<?php
  require_once 'testclass.php';
  $tc = unserialize( stripslashes( htmlspecialchars_decode( $_POST["str"] ) ) );
  $tc->display();
?>

The fix, suggested by evulish on #php/irc.dal.net, is to replace htmlspecialchars()/htmlspecialchars_decode() by base64_encode()/base64_decode. The code becomes:

page1.php
=========
<input type = "hidden" name = "str" value = "<?php echo base64_encode( serialize( $tc ) ); ?>">

page2.php
=========
<?php
  $tc = unserialize( base64_decode( $_POST["str"] ) );
?>

Hope this will help someone...
Jeex 06-Nov-2007 02:59
It may be worth noting that, depending on the size of the object you are serializing, the serialize function can take up a lot of memory.

If your script isn't working as expected, your serialize call may have pushed the memory usage over the limit set by memory_limit in php.ini.

More info on memory limits here: http://www.php.net/manual/en/ini.core.php
aksel at metal dot ee 13-Sep-2007 03:31
To serialize objects with fields that contain unicode values use that logic.

Note! Obviously it does not convert correctly possible unicode values in arrays that may be member values of the object. Use an array class for that that inherits from the same base object that implements that serialization;)

<?php
/**
                  * Serializes object with/without unicode fields
                  * Before serializing encodes unicode values
                  *
                  * @return string
                  */
                  public function serialize(){
                       $serialized = array();
                       foreach(array_keys(get_class_vars(get_class($this))) as $key){
                           if(is_array($this->$key) ){
                               eval('$serialized["'.$key.'"] = serialize($this->'.$key.');');
                           }else{
                                eval('$serialized["'.$key.'"] = utf8_encode($this->'.$key.');');
                           }
                       }
                       $str = serialize($serialized);
                       return $str;
                  }
                  /**
                   * Unserializes object with/without unicode fields
                   *
                   * @param string Serialized data
                   */
                   public function unserialize($serialized){
                       $data = unserialize($serialized);
                       foreach($data as $prop => $val){
                           if(is_array($this->$prop) ){
                                $this->$prop = unserialize($val);
                           }else{
                                $this->$prop = utf8_decode($val);
                           }
                       }
                   }
?>
nothanks at nothanks dot no 16-Aug-2007 03:02
I had to put a massive multidimensional array in a single field in the database. Unfortunatly the array contained lots of "forbidden" characters: ", ', ;, :, and so on and so forth, breaking the query and my later attempts at deserialize().

Here's a quick and dirty solution:
<?php
$safe_string_to_store = base64_encode( serialize( $multidimensional_array ) ) ;
?>

And in the other end:
<?php
$encoded_serialized_string = dbh->query("SELECT archives_arr FROM ". $table_name . " WHERE id=0")

$array_restored_from_db = unserialize( base64_decode( $encoded_serialized_string ));
?>
deminy at deminy dot net 08-Aug-2007 09:44
Reply to erudd's post:

The regular expression you used to unserialize a PHP session file won't work if the session file contains string variable which contains character "|".

As I can see now, there is no any regular expression that can easily split data in a PHP session file. To read data from a session file, we may have to write a function to read content from the file, and then parse the content.
btbeat at gmail dot com 28-Jun-2007 01:09
Generally when I do an insert into a database table of posted data, I use the recommended mysql_real_escape_string function, with stripslashes if the get_magic_quotes_gpc is on.
<?php
function prepData($var) {
  if (get_magic_quotes_gpc()) {
    $var = stripslashes($var);
  }
return mysql_real_escape_string($var);
}
?>
I've been having a problem inserting a serialized array into a MySQL database that contained single and double quotes for values.

ex: "quotes" => "some 'quoted' "text""
you'd think it would be:
a:1:{s:6:"quotes";s:20:"some 'quoted' "text"";}
as prepData function would strip the slashes.

However, what goes into the database is:
a:1:{s:6:"quotes";s:24:"some 'quoted' "text"";}
as if there are slashes before the single and double quotes.

Obviously on unserializing the data, there is an error, as 24 chars are expected, when there are only 20.

So, the solution I've coded for my safe insert prepData function is:
<?php
function prepData($var, $serialized = 0) {
  if( $serialized == 0 )  {
    if (get_magic_quotes_gpc()) {
      $var = stripslashes($var);
    }
  }
return mysql_real_escape_string($var);
}
?>

when inserting plain data from a post:
<? $data = prepData($data); ?>

for serialized data:
<? $data = prepData($data, 1); ?>

cracked my head on this one a bit :|

strange behaviour for serialize(), i.e. string count, counts slashes that are not there.
friday13 at ig dot com dot br 19-Jun-2007 07:15
I have problem to use serialize function with hidden form field and the resolution was use htmlentities.

Ex.:

<?

$lista = array( 'pera', 'maça', 'laranja' );

print "< input type='hidden' name='teste' value='htmlentities( serialize( $lista ) )'" >";

?>
lacent at gmail dot com 13-Jun-2007 10:22
i noticed the same problem related to quotes, but the person below had no code detailing it. i can only assume he wrote it to fix values, and not to fix the whole array, so heres 2 functions to handle encoding the array.

    function slw_serial ( $var = array(), $recur = FALSE )
    {
        if ( $recur ) {
            foreach ( $var as $k => $v )
            {
                if ( is_array($v) ) {
                    $var[$k] = slw_serial($v, 1);
                } else {
                    $var[$k] = base64_encode($v);
                }
            }
            return $var;
        } else {
            return serialize(slw_serial($var, 1));
        }
    }

    function slw_unserial ( $var = FALSE, $recur = FALSE )
    {
        if ( $recur ) {
            foreach ( $var as $k => $v )
            {
                if ( is_array($v) ) {
                    $var[$k] = slw_unserial($v, 1);
                } else {
                    $var[$k] = base64_decode($v);
                }
            }
            return $var;
        } else {
            return slw_unserial(unserialize($var), 1);
        }
    }

---------
USAGE:
---------

    $array = array();
    $array[] = 'this "is a" test';
    $array[] = array('pos'=>'test', 'name'=>'some "dude in" cali');
    $array = slw_serial($array);
    echo $array . '<Br><br>';
    $array = slw_unserial($array);
    echo print_r($array, 1);
kris dover 21-Apr-2007 05:45
The PHPSerialization class linked in my last comment now supports serialize()'ing java objects to the php serialization text format, thus facilitating a means of data inter-change between php and java communicating against a common php serialized data source.

reverse mappings are as follows:
   _PHP Type_   <-----------------   _Java Type_
      array                            java.lang.Object[]
      int                                java.lang.Byte
      int                                java.lang.Short
      double                           java.lang.Float
      double                           java.lang.Long
      double                           java.lang.BigInteger
      double                           java.lang.BigDecimal
      string                            java.lang.Character
      string                            java.lang.CharBuffer
      string                            java.lang.StringBuffer
admin at goodsoft dot lv 19-Nov-2006 08:25
When I serialized an object and looked into resulting string, I mentioned that all private properties' names were prefixed by class name.

This code:
<?php
        class myclass {
                private $priv1 = "val1",
                           $myclasspriv2 = "val2";
                public $pub = "val3";
        }

        $inst = new myclass ();
        echo serialize($inst);
?>
resulted in (don't look at word wrapping):
O:7:"myclass":3:{s:14:"myclasspriv1";
s:4:"val1";s:21:"myclassmyclasspriv2";
s:4:"val2";s:3:"pub";s:4:"val3";}
Ates Goral 18-Jul-2006 11:59
Corrections/clarifications to  "Anatomy of a serialize()'ed value":

All strings appear inside quotes. This applies to string values, object class names and array key names. For example:

s:3:"foo"
O:7:"MyClass":1:{...
a:2:{s:3:"bar";i:42;...

Object property names and values are delimited by semi-colons, not colons. For example:

O:7:"MyClass":2:{s:3:"foo";i:10;s:3:"bar";i:20}

Double/float values are represented as:

d:0.23241446
egingell at sisna dot com 15-May-2006 05:12
<?
/*
Anatomy of a serialize()'ed value:

 String
 s:size:value;

 Integer
 i:value;

 Boolean
 b:value; (does not store "true" or "false", does store '1' or '0')

 Null
 N;

 Array
 a:size:{key definition;value definition;(repeated per element)}

 Object
 O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}

 String values are always in double quotes
 Array keys are always integers or strings
    "null => 'value'" equates to 's:0:"";s:5:"value";',
    "true => 'value'" equates to 'i:1;s:5:"value";',
    "false => 'value'" equates to 'i:0;s:5:"value";',
    "array(whatever the contents) => 'value'" equates to an "illegal offset type" warning because you can't use an
    array as a key; however, if you use a variable containing an array as a key, it will equate to 's:5:"Array";s:5:"value";',
     and
    attempting to use an object as a key will result in the same behavior as using an array will.
*/
?>
erudd at netfor dot com 30-Mar-2006 01:36
To unserialize a PHP session file, unserlize can not be used directly.
The data must be split, as the php session file also contains the names of the variables which serialize/unserialize do not do.  Here is a simple preg_split that will acomplish the split.. (regex not thuroughly tested, but should work for most all circumstances)

<?php
$session = file_get_contents($session_file);
$data = preg_split('/([A-Za-z_][A-Za-z0-9_]*)\|/',$session,-1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
?>

$data[0] will contain the variable name, and $data[1] will contain the serialized data.  so in effect
<?php
$$data[0] = unserialize($data[1]);
?>
will restore that one variable.

just go through the $data array evens being the variable name, odd being the data.  You can use this to create a simple command line session viewer:)
angel at support-24 dot com 09-Feb-2006 12:25
I recently had a problem inserting serialized array in mysql DB using PEAR DB_Base class functions. mySQL fails to insert the serialized array because the serialized data contains semicolon. A way to solve that problem is to make same changes to the serialized data:

$serializeorder = serialize($order);
$serializeorder = preg_replace("#;#msi",'0x3B',$serializeorder);
$serializeorder = preg_replace("/(\n)|(\r)/"," ",$serializeorder);
$serializeorder = addcslashes($serializeorder, "\0..\37!@\@\177..\377");
$serializeorder = addslashes($serializeorder);

Here we substitute the semicolon with it's hex. We alse get rid of cariage return. Remember to make the vise versa substitution again when extracting the data.
Neil Green 02-Feb-2006 05:23
Are you trying to store and retrieve an object from session and it's disappearing?  Did you look at what the serialized object looked like and saw a strange "N;"?  Does the object you're trying to serialize or store in a session define the __call magic method?

Here's the problem:  If you try to serialize an object that uses the __call magic method you are not going to be able to unserialize it.

Here's what happens:

1.  You try to serialize an object with the __call magic method defined
2.  The magic method __sleep is always called on an object being serialized
3.  __call traps __sleep because it's not defined
4.  __call does not respond to __sleep with what is expected: an array of properties to serialize

The solution is defining a __sleep method that returns what it's supposed to when you define a __call:

<?
// This is just a handy debug function
function show( $object ){ echo "<pre>" . print_r( $object, true ) . "</pre>"; }

class foo
{
    private $private = "private value";
    public $public = "public value";

    public function __call( $method, $arguments )
    {

    }

    // Remove this and serialise/unserialse won't work
    public function __sleep()
    {
        return array_keys( get_object_vars( $this ) );
    }
}

$foo = new Foo();

show( $foo );

$serializedFoo = serialize( $foo );
show( $serializedFoo );
show( unserialize( $serializedFoo ) );
?>

BTW, I'm using PHP Version 5.0.4 on Windows.

To the editor:  This post may be useful under the __call, __unserialise, and session pages as well.
Embeded nulls with private vars 17-Jan-2006 08:08
If you are serializing an object with private variables, beware. The serialize() function returns a string with null (\x00) characters embedded within it, which you have to escape. Not great if you're trying to save objects into a DB...
16-Jan-2006 07:47
I use PHP 4.3.10 and I found out that if you use a class "MyClass", the constructor of the class must be called "__construct()" and NOT "MyClass()" like in Java or other languages.

If you use the "MyClass()" constructor, the following won't work :
    $_SESSION['obj_my_class'] = new MyClass();
If you don't believe me, you can have a look in the directory "session.save_path" (default /var/lib/php4) where is stored the session's file. You will see this :
    obj_my_class|N;
and not your complete class!

It took me almost one day to understand what was happening... :-(
varrah NO_GARBAGE_OR_SPAM AT mail DOT ru 13-Jan-2006 01:21
Worked with Andrea, so the script is now updated to support at least UTF-8 correctly. Details can be found at http://www.sitepoint.com/blogs/2004/04/22/ serializing-php-data-structures-for-javascript (had to insert space after the 22/  otherwise the link was too long and comments engine didn't want to pass it :-) )
varrah NO_GARBAGE_OR_SPAM AT mail DOT ru 10-Jan-2006 05:52
andrea at 3site dot it gave a link for a JavaScript serialization class, but be prepared! This class works only on single-byte symbols, since JS str.length property gives the length of the string in SYMBOLS, not bytes (as PHP serialize() does), so a Unicode string JS-serialized in a way like:

strSerialized = "s:" + strOriginal.length + ":" + strOriginal;

will not be unserialized correctly by PHP.
MC_Gurk at gmx dot net 03-Jan-2006 07:44
If you are going to serialie an object which contains references to other objects you want to serialize some time later, these references will be lost when the object is unserialized.
The references can only be kept if all of your objects are serialized at once.
That means:

$a = new ClassA();
$b = new ClassB($a); //$b containes a reference to $a;

$s1=serialize($a);
$s2=serialize($b);

$a=unserialize($s1);
$b=unserialize($s2);

now b references to an object of ClassA which is not $a. $a is another object of Class A.

use this:
$buf[0]=$a;
$buf[1]=$b;
$s=serialize($buf);
$buf=unserialize($s);
$a=$buf[0];
$b=$buf[1];

all references are intact.
Alexander Podgorny 02-Dec-2005 11:47
Here is an example of a base class to implement object persistence using serialize and unserialize:

<?php
class Persistent
{
    var $filename;

    /**********************/
    function Persistent($filename)
    {
        $this->filename = $filename;
        if(!file_exists($this->filename)) $this->save();
    }
    /**********************/
    function save()
    {
        if($f = @fopen($this->filename,"w"))
        {
            if(@fwrite($f,serialize(get_object_vars($this))))
            {
                @fclose($f);
            }
            else die("Could not write to file ".$this->filename." at Persistant::save");
        }
        else die("Could not open file ".$this->filename." for writing, at Persistant::save");

    }
    /**********************/
    function open()
    {
        $vars = unserialize(file_get_contents($this->filename));
        foreach($vars as $key=>$val)
        {
            eval("$"."this->$key = $"."vars['"."$key'];");
        }
    }
    /**********************/
}

?>

When an object is extended from this one it can be easily saved and re-opened using it's own methods as follows:

<?

class foo extends Persistent
{
   var $counter;
   function inc()
   {
       $this->counter++;
   }
}

$fooObj = new $foo;
$foo->open();
print $foo->counter; // displays incrementing integer as page reloads
$foo->inc();
$foo->save();

?>
andrea at 3site dot it 26-Nov-2005 09:31
Hello!
Here you can find a JavaScript Object that should serialize JS vars for PHP and unserialize PHP vars for JavaScript.
http://www.devpro.it/javascript_id_102.html

Please read notes inside the code to know more about vars compatibility.

It was created to resolve AJAX interaction and maybe usefull for other situations .... such:

<?php
// example nested array
$myarray = array(
    true,
    123,
    array(
        'nested',
        array(
            1,
            'test'=>false
        )
    ),
    'other'=>'value'
);
// array serializzation
$serialized = serialize($myarray);
?>
<script type="text/javascript" src="PHP_Serializer.js"></script>
<script type="text/javascript">
// function to dump an object
function showObject(obj, level) {
    var l = '';
    var tmp = '';
    for(var a = 0; a < level; a++)
        l += '[_]';
    for(var a in obj) {
        var type = typeof(obj[a]);
        if(type == 'object')
            tmp += showObject(obj[a], (level + 1));
        else
            tmp += l + ' key: ' + a + ' = value: ' +
            obj[a] + ' < ' + type + '\n';
    }
    return tmp;
}
// new PHP_Serializer variable
var php = new PHP_Serializer();
// dinamyc JS var creation
var myJSvar = php.unserialize("<?php echo str_replace('"', '\\"', $serialized); ?>");
// look at dump :-)
alert(showObject(myJSvar, 0));
</script>

Regards
pavic at ieee dot org 01-Nov-2005 11:18
Hi, if You get code like
d:234 and than string You wanted, it's the problem, that
s dot marechal at jejik dot com
explanied.

Well, here is a workaround for that problem, function safe serialize, which won't produce that unwanted chars...

function safe_serialize($string) {
    return preg_replace("/(\n)|(\r)/"," ",$string);
}
stephen dot adamson at smius dot com 01-Nov-2005 09:40
If you are serializing an object to store it in the database, using __sleep() can save you some space. The following code will not store empty (null) variables in the serialized string. For my purposes this saved a lot of space, since some of the member variables would not be given values.

function __sleep()
{
    $allVars = get_object_vars($this);
    $toReturn = array();
    foreach(array_keys($allVars) as $name)
    {
        if (isset($this->$name))
        {
            $toReturn[] = $name;
        }
    }
    return $toReturn;
}
php barryhunter co uk 29-Oct-2005 04:51
if you wanting to do something similar to 'mwwaygoo AT hotmail DOT com', then you may want to look at the built in function var_export.

"var_export() gets structured information about the given variable. It is similar to var_dump()  with one exception: the returned representation is valid PHP code."
Sean at http://seanj dot jcink dot com 11-Oct-2005 02:07
Very short function I made to turn arrays into a string for fwriting, doesnt create unnecessary commas either:

<?
function arraytostring($array){
$text.="array(";
$count=count($array);
foreach ($array as $key=>$value){
$x++;
if (is_array($value)) {$text.=$key."=>".arraytostring($value); continue;}
$text.="\"$key\"=>\"$value\"";
if ($count!=$x) $text.=",";
}
$text.=")";
return $text;
}
?>
eggyknap at gmail dot com 10-Oct-2005 09:01
My thanks to the editor who pointed out the serialization bug. According to the bug report, this should be fixed in version 5.0.4, and is confirmed fixed in v 5.0.5. Unfortunately I'm not in a position to update my installation, but I found that passing the serialized string through addslashes before saving it to the database does the trick. It may be a bit inefficient, but it works.
eggyknap at gmail dot com 08-Oct-2005 09:12
[Editor's note: This has been fixed. Protected and private members were serialized with a leading \0 (zero byte). Bug report here, http://bugs.php.net/29865 - aidan@php.net]

Be careful trying to serialize objects containing private or protected data members. It appears that the serialization process includes characters in the result string to indicate the visibility of each member, but the characters used to denote protected or private data are outside the normal character set and can cause problems as you pass them through applications. I haven't found the culprit in my particular case, so I can't say that this is a bug in PHP, but it certainly is causing me some annoyance in my particular situation.
mwwaygoo AT hotmail DOT com 18-Jul-2005 08:03
Hello people,

I had major problems getting serialize to work properly, as I wanted to sync two databases via email, and needed a way of converting a retrieved row to a string. It works the reverse of array(), in that it creates a statement that you can use to evaluate to the original array, so I called it unarray().
Its a recursive function (self calling), so it doesnt matter how complex the array is.

<?php

$source=array(1,4,'x'=>'test');
$text=unarray($source);

$destination=array(); // prime the variable incase of failure.
eval('$destination='.$text);
print_r($destination);

// unarray.php    REVERSE of array();

function unarray($array, $first=TRUE)
{
    $text="";
    if(is_array($array))
    {
        $text.="array(";
        while(list($key,$value)=each($array))
        {
            if(is_string($key))
            {
                $text.="'".$key."'";
            }
            else
            {
                $text.=$key;
            }
            $text.="=>";
            $text.=unarray($array[$key], FALSE);
        }
        $text=$text."), ";
    }
    else
    {
        if(is_string($array))
        {
            $text.="'".addslashes($array)."', ";
        }
        else
        {
            if(is_bool($array))
            {
                if($array)
                {
                    $text.="TRUE, ";
                }
                else
                {
                    $text.="FALSE, ";
                }
            }
            else
            {
                if(is_null($array))
                {
                    $text.="NULL, ";
                }
                else
                {
                    $text.=$array.", ";
                }
            }
        }
    }
    if($first) $text=substr($text,0,-2).";";
    return $text;
}

?>

p.s. I realise that it also creates unnecessary commas, but these are ignored when re-creating it. array(1,2,) is the same as array(1,2).
abductee _at_ texture _minus_ editor.com 14-Jun-2005 04:44
wiart at yahoo dot com wrote:
>As you can see, the original array :
>$arr["20041001103319"] = "test"
>
>after serialize/unserialize is:
>$arr[683700183] = "test"

yepp, and i can explain it.

the internal compiler of php does not hit anys rule wich foces him to make that number a string during serialisation. since it becomes an integer and php supports 32bit interger not arbitary bitwidth this is what happens:

"20041001103319"
equals hexadecimal:

0x123A28C06FD7h

if you cut away the frontpart cutting down to 32bis,
you get:

0x28C06FD7h

wich equals 683700183.

of, for those of you who speak binary:

20041001103319 =
100100011101000101000110000000110111111010111bin

----cut-away----00101000110000000110111111010111bin
=683700183

so, what can you do to prevent stuff like this?
eihter use only numbers between 0..9999999999
or force strings, best way ist to add a character
like

foo["c2342303"]

cheers, abductee
gafunchal NOSPAN at inf dot ufrgs dot br 22-Jan-2005 04:33
(please, excuse my poor English)

'serialize' does strange things with floats, this code:

  $a = 3.14;
  $s = serialize($a);
  $fp = fopen("storage", "w");
  fwrite($fp, $s);
  fclose($fp);

outputs something like (PHP 5.0.2):

d:3.140000000000000124344978758017532527446746826171875;

I wonder why serialize doesn't store data (not only float, I mean all types of data) in a more 'economic' format. Maybe binary is not the best option (there can be trouble storing it in databases), but there are still a lot of other possibilities.
cjmeyer at npcc dot net 23-Dec-2004 11:16
More on troubles with recursive object references and serialization.

In my PHP 4.2.2 the solution suggested above (by james at gogo dot co dot nz), to pass a reference to the object to serialize(), does not help.  There are still multiple copies of the objects woken up, and the recursive reference is no longer recursive.

The only solution I have found is to use the __sleep and __wakeup magic functions to only serialize the link one-way, then recreate it manually on unserialize.  This isn't too difficult;  here is some code demonstrating this approach:

class A {
  var $data = Null;
  var $b = Null;

  function A($data, $bData) {
    $this->data = $data;
    $this->b = new B(&$this, $bData);
  }

  function printData() {
    print 'A thinks A data is ' . $this->data . "\n";
    print 'A thinks B data is ' . $this->b->data . "\n";
  }

  function __sleep() {
    print "A is going to sleep.\n";
    return array('data', 'b');
  }

  function __wakeup(){
    print "A is waking up.\n";
    $this->b->reLinkA($this);
  }

}

class B {
  var $data = Null;
  var $a = Null;

  function B(&$a, $data) {
    $this->a =& $a;
    $this->data = $data;
  }

  function printData() {
    print 'B thinks A data is ' . $this->a->data . "\n";
    print 'B thinks B data is ' . $this->data . "\n";
  }

  function __sleep() {
    print "B is going to sleep.\n";
    return array('data');
  }

  function __wakeup(){
    print "B is waking up.\n";
  }

  function reLinkA(&$a) {
    $this->a =& $a;
  }

}

$a = new A("origAdata", "origBdata");

print '<pre>';

print "I think A data is " . $a->data . "\n";
print "I think B data is " . $a->b->data . "\n";
$a->printData();
$a->b->printData();

$serA = serialize($a);
$newA = unserialize($serA);

$newA->data = 'newAdata';
$newA->b->data = 'newBdata';

print "I think new A data is " . $newA->data . "\n";
print "I think new B data is " . $newA->b->data . "\n";
$newA->printData();
$newA->b->printData();
wiart at yahoo dot com 16-Dec-2004 03:40
Warning: on 64 bits machines,  if you use a long string only composed of numbers as a key in an array and serialize/unserialize it, you can run into problems:

an example code:
$arr["20041001103319"] = 'test';
var_dump( $arr);
$arr_in_str = serialize($arr);
print "Now result is: $arr_in_str<BR />";
$final_arr = unserialize($arr_in_str);
print "The final unserialized array:<BR />";
var_dump($final_arr);

The result:
array(1) { [20041001103319]=>  string(4) "test" }
Now result is: a:1:{i:20041001103319;s:4:"test";}
The final unserialized array:
array(1) { [683700183]=> string(4) "test" }

As you can see, the original array :
$arr["20041001103319"] = "test"

after serialize/unserialize is:
$arr[683700183] = "test"

As you can see,  the key has changed ...

Apparently a problem of implicit casting + integer overflow (I posted a PHP bug report: http://bugs.php.net/bug.php?id=31117)

I tested with the latest 4.3.10 compiled on my laptop (32 bits, Mandrake 9.1) --> no such problem. But compiled on AMD 64 bits (Red Hat Taroon), the problem is present.

Hope this will help some of you to not loose almost a whole day of debugging ;-)
richard dot prangnell at ntlworld dot com 12-Dec-2004 02:08
Although the serialise function has its proper uses, it is a relatively slow process. I try to avoid using it wherever possible in the interests of performance. You can store text records in a database as plain text even when it contains PHP variables. The variable values are lost, naturally; but if they can easily be re-attached to retrieved records, zillions of clock cycles can be saved simply by using the str_replace() function:

  if($convert)
  {
    $mainContent = str_replace('$fixPath', $fixPath, $mainContent);
    $mainContent = str_replace('$theme', $theme, $mainContent);
  }

The above snippet is used in a CMS project. $fixPath contains  something like '.' or '..' to prepend relative paths (allowing the record to be used by scripts located in different parts of the directory hierarchy) and $theme inserts the name of the users custom page rendering scheme, which obviously would be undefined at record storage time anyway.
corey at eyewantmedia dot com 08-Dec-2004 10:47
If this helps anybody, I was looking for a few quick calls to cache stuff to files. I settled on the below functions. By the way, if I am doing something stupid here, I'd appreciate some comments on that also. Anyway, on with the code:

First, the usage:

//Use:

$var = tuncache('MyCacheName');
if (is_null($var)) {
    $var = 'a really expensive process';
    $check = tcache('MyCacheName', $var, '+25 minutes');
    if (is_null($check)) {
        die('I need to reset my permissions or get a bigger hard drive');
    }
}

//use $var now

Now, the functions:

//uses strtotime to decide how long to cache $cacheVar based on $lifespan
//so anything but a timestamp works. +1 day works, 09/14/2010 works, etc
function tcache($cacheName, $cacheVar, $lifespan=null) {
    if (!is_null($lifespan)) { //a lifespan was provided
        if (strpos($lifespan, '+') === 0 || strpos($lifespan, '-') === 0) {
            //Have to do this to counter for bug in php5 to
            //properly evaluate now to do the date math
            $endTime = strtotime(date('m/d/Y H:i:s') . ' ' .$lifespan);
        } else {
            //we can safely use anything else I think
            $endTime = strtotime($lifespan);
        }
    } else {
        //cache forever (forever being ten years) until manually deleted
        $endTime = strtotime(date('m/d/Y H:i:s') . ' +10 years');
    }

    $cVal = serialize($cacheVar);
    $file = tFindcache($cacheName);
    $result = true;

    $f = fopen($file, 'w');
    if ($f === false) {
        $result = null; //barf if we can't open the file
    } else { //write the cache
        fwrite($f, $endTime . "\n");
        fwrite($f, $cVal);
        fclose($f);
    }

    return $result;
}

function tuncache($cacheName) {
    $file = tFindCache($cacheName);

    if (is_readable($file)) {
        //open file
        $f = fopen($file, 'r');
        $time = time();
        $expTime = trim(fgets($f));
        //check time
        if ($time > $expTime) {
            //It expired
            $result = null;
        } else {
            //Read it and unserialize it
            $data = fread($f, filesize($file));
            $result = unserialize($data);
        }
    } else {
        //barf
        $result = null;
    }

    return $result;
}

//just to set a few options for setting where to save stuff
function tFindCache($cacheName) {
    if (isset($_ENV['PHP_CACHE_PATH'])) {
        $cachePath = $_ENV['PHP_CACHE_PATH'];
    } else if (isset($_SERVER['PHP_CACHE_PATH'])) {
        $cachePath = $_SERVER['PHP_CACHE_PATH'];
    } else {
        $cachePath = './'; //Potential danger here
    }

    $cachePath .= 'PHP_CACHE_' . $cacheName . '.cache';

    return $cachePath;
}
01-Dec-2004 01:30
This is just a modification of what Alan Reddan (areddan at silverarm dot ie) posted below.

I figured it would be faster than walking an array, and it works wonderfully with cookies

<?php
$data[qwerty] = "blah";
$data[1][a] = "1aa";
$data[2][b] = "2bb";
$data[3][c] = ";;;;;;";
$data[name][first] = "Bob";
$data[name][last] = "Jones";
$data[val] = "This is a real long test string, to see how well the compression works!";

//To Serialise Call :
$string = gzcompress(serialize($data), 9);
setcookie("my_var", $string, time()+60*60*24*60, '/');
//print "String: $string\n<br>"; //uncomment to see serialized array

//To Unserialize Call
if (isset($_COOKIE[my_var])) {
  $array = unserialize(gzuncompress($_COOKIE[my_var]));

  echo "<pre>";
  print_r($array);
  echo "</pre>";
}
?>

you can replace gzcompress with base64_encode and gzuncompress with base64_decode to have a similar experience

Alan, thanks for the tip though, it got me where I wanted to be!
paul at moveNOtoSPAMiceland DOT com 18-Nov-2004 08:29
I was trying to submit a serialized array through a hidden form field using POST and was having a lot of trouble with the quotes. I couldn't figure out a way to escape the quotes in the string so that they'd show up right inside the form, so only the characters up to the first set of quotes were being sent.

My solution was to base64_encode() the string, put that in the hidden form field, and send that through the POST method. Then I decoded it (using base64_decode()) on the other end. This seemed to solve the problem.
Alexei dot Filine at cern dot ch 24-Oct-2004 07:57
A simple way to transfer PHP variables between PHP scripts running on different hosts can be done with HTTP_Request PEAR module. I think it is much more fast way than one done with XML-RPC but less portable (there were described ways to exchange vars between Perl and PHP below). Recieved PHP obects are required to be created before recieving by class definition similar to definition used on sending side. A script sending variable must output nothing except data sent by function 'sendVariable' so a 'composite variable' is to be used to transfer some variables by one request.

<?php
// exchange-protocol.php
ini_set( 'include_path', '.' );
require_once "config.php"; // set $PEAR_path
ini_set( 'include_path', ini_get( 'include_path' ).$PEAR_path );

// PEAR module
require_once "HTTP/Request.php";

// magic words for HTTP header
$gzcompressed_serialized_type = 'application/serialized_gzcompressed_PHP_variable';
$serialized_type = 'application/serialized_PHP_variable';

$compression_flag_name = '_compressionFlag_';

// Date in the past
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );

// always modified
header( "Last-Modified: ".gmdate( "D, d M Y H:i:s" )." GMT" );

// returns non-zero on success
function recieveVariable( $url,
              &$var,
              $user = '',
              $passw = '',
                  $compression_flag = 1 ) {

    global $gzcompressed_serialized_type;
    global $serialized_type;
    $req =& new HTTP_Request( "" );
      $req->setURL( $url );
      $req->setMethod( HTTP_REQUEST_METHOD_POST );

      // set user/password if required
    if ( $user && $passw ) {
          $req->addPostData( $user,
                             $passw );
    }
      $response = $req->sendRequest();
      $req->clearPostData();
    if ( $compression_flag ) {
        $req->addPostData( $compression_flag_name, 1 );
    }
      if ( PEAR::isError( $response ) ) {
            echo $response->getMessage();
      } else {
            $header = $req->getResponseHeader();
            if ( $req->getResponseCode() != 200 ||
                 ! ( $header['content-type'] == $gzcompressed_serialized_type ||
                    $header['content-type'] == $serialized_type ) ) {
                    // type error message
                    echo $req->getResponseBody();
            } else {
                    if ( $header['content-type'] == $gzcompressed_serialized_type )
{
                            $data = gzuncompress( $req->getResponseBody() );
                    } else {
                            $data = $req->getResponseBody();
                    }
                    $var = unserialize( $data );
            return 1;
            }
    }
    return 0;
}

// just for extra flexibility, if data chunk is small enough we can skip gzipping on the sending side: $compression_flag = 0;
// in other case we use client preference: $compression_flag = $_REQUEST[$compression_flag_name];
function sendVariable( &$var, $compression_flag = 1 ) {

    global $gzcompressed_serialized_type;
    global $serialized_type;
    // Date in the past
    header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );

    // always modified
    header( "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

    if ( $compression_flag ) {
        // set specialised content type to inform about data type
        header( 'content-type: '.$gzcompressed_serialized_type );
        echo gzcompress( serialize( $var ) );
    } else {
        // set specialised content type to inform about data type
        header( 'content-type: '.$serialized_type );
        echo serialize( $var );
    }
}
?>

on client side:
<?php
...
require_once "exchange-protocol.php";
...
if (recieveVariable( $url, $var) ) {
    // success...
} else {
    // there was something wrong...
}
?>

on the server side:
<?php
...
require_once "exchange-protocol.php";
...
// there must not be output before the function is called!!! execution is to 'die' if an error occures.
sendVariable( $var, $compression_flag )
?>
areddan at silverarm dot ie 23-Oct-2004 01:56
<?php
/*
This is an array_walk style serialize that works with multi dimensional arrays, it also base64 encodes and decodes to allow ';' to exist in the array.
 -- Alan Reddan
*/
$data[qwerty] = "blah";
$data[1][a] = "1aa";
$data[2][b] = "2bb";
$data[3][c] = ";;;;;;";

//To Serialise Call :

array_walk($data,'base64_encoder_multi');
$serialized_string = serialize($data);
//print $serialized_string . '\n'; //uncomment to see serialized array

//To Unserialize Call

$array = unserialize($serialized_string);
array_walk($array,'base64_cleaner_multi');

print_r($array);
//start functions
function base64_encoder_multi(&$val,$key) {
   if (is_array($val)) array_walk($val,'base64_encoder_multi',$new);
   else {
      $val = base64_encode($val);
   }
}

function base64_cleaner_multi(&$val,$key) {
   if (is_array($val)) array_walk($val,'base64_cleaner_multi',$new);
   else {
      $val = base64_decode($val);
   }
}
//ends

?>
brooklynphil hotmail com 06-Oct-2004 01:07
In my experience of the (far and few in between) times when it is necessary to store large (megabytes) amounts of data in a php-readable ascii file format, using var_export() and require() is much faster serialize() and unserialize(file_get_contents()) (I have tested it on classes encapsulating arrays, i.e. <?php class blah { $a = array(megsofstuffhere); $b = array(megsofstuffhere); $c=... }; $data = new blah ?>)   (var_export is also more readable and notepadable than serialize!)

However, since var_export produces only the rvalue (or uninstantiation), of the data needed, dont forget to cosmetically modify output of var_export( , true): in case of classes, you will need to use "$var = new classname" (and rename a possible stdClass) and in case of arrays, etc, just use "$var = ".var_export().  The file being var_export()ed to and require()ed must also be encapculated in "<?php ?>" when written to (or else its just dumped to browser/stdout as a textfile).

Hope this helps :)

--Phil

P.S. (in cases of small amounts of data, serialize is better, especially for cross-URL data transport using <?php base64_encode(gzdeflate(serialize()))?>)
jan at bestbytes dot de 05-Oct-2004 01:58
This should be EXTREMELY helpful when you are getting lost in php 4 circular references and sessions or serializing ...

<?php

// this example is for php 4

class Node {
  var $value;
  var $child;
  var $parent;
  var $load;
  var $__destroyed = false;
  function Node($value)
  {
    $this->value = $value;
    global $load;
    $this->load = $load;
  }
  function setParent(&$parent)
  {
    $this->parent = &$parent;
  }
  function setChild(&$child)
  {
    $this->child = &$child;
  }
  /**
  * @return void
  * @desc fake __destroy from a php 4 point of view
  */
  function __destroy()
  {
    $props = get_object_vars($this);
    foreach($props as $propName => $propValue) {
      unset($propValue);
      if(is_object($this->$propName)) {
        if(method_exists($this->$propName, '__destroy') AND $this->$propName->__destroyed !== false) {
          $this->$propName->__destroy();
        }
      }
      if(isset($this->$propName)) {
        unset($this->$propName);
      }
    }
  }
}
header('Content-type: text/plain');

// small load to check the serialized string
$loadSize = 4;

// big load to check leaking
//$loadSize = 32 * 1024;

$load     = str_repeat('.', $loadSize);

for($i = 0;$i<10;$i++) {
  echo '-------------------- '.(memory_get_usage()/1024).' -------------------------'.chr(10);

  $serMe = array();
  $serMe['parent'] =& new Node('parent');
  $serMe['child']  =& new Node('child');

  /*
   * this will work too !!
   *   $serMe['parent'] = new Node('parent');
   *   $serMe['child']  = new Node('child');
   */

  $serMe['parent']->setChild($serMe['child']);
  $serMe['child']->setParent($serMe['parent']);

  $str = serialize($serMe);

  /*
   * 1.Problem:
   *
   * You have 2 or more objects with circular references to one another.
   * Serializing these objects will result in unexpected behaviour when
   * unserializing them:
   *
   * Former references will become copies.
   *
   * This is because the php serialize handler can not handle references,
   * unless all involved objects, variables ... are within an array(),
   * that will be serialized.
   *
   * This should be selfexplaining (just take a look at the length ...):
   * echo serialize($serMe['parent']);
   * echo serialize($serMe);
   *
   * results in:
   *
   * O:4:"node":5:{s:5:"value";s:6:"parent";s:5:"child";O:4:"node
   * ":5:{s:5:"value";s:5:"child";s:5:"child";N;s:6:"parent";O:4:
   * "node":5:{s:5:"value";s:6:"parent";s:5:"child";R:3;s:6:"pare
   * nt";N;s:4:"load";s:4:"....";s:11:"__destroyed";b:0;}s:4:"loa
   * d";s:4:"....";s:11:"__destroyed";b:0;}s:6:"parent";N;s:4:"lo
   * ad";s:4:"....";s:11:"__destroyed";b:0;}
   *
   * a:2:{s:6:"parent";O:4:"node":5:{s:5:"value";s:6:"parent";s:5
   * :"child";O:4:"node":5:{s:5:"value";s:5:"child";s:5:"child";N
   * ;s:6:"parent";R:2;s:4:"load";s:4:"....";s:11:"__destroyed";b
   * :0;}s:6:"parent";N;s:4:"load";s:4:"....";s:11:"__destroyed";
   * b:0;}s:5:"child";R:4;}
   *
   * PLEASE GIVE THE WORLD PROPER DOCUMENTATION ON THIS (or prove us wrong)
   *
   * 2.Problem:
   *
   * The loop below will result in extensive leaking (use the big $loadsize ...),
   * unless you help yourself and unset all the properties manually
   * see Node::__destroy()
   *
   */

  $serMe['parent']->__destroy();
  $serMe['child']->__destroy();
  $serMe = unserialize($str);
  unset($str);
  $serMe['parent']->value = 'new parent';
  echo '-->'.$serMe['parent']->child->parent->value.chr(10);
  echo '-->'.$serMe['parent']->value.chr(10);

  $serMe['parent']->__destroy();
  $serMe['child']->__destroy();
  unset($serMe);
}

?>
mary at nospam dot com 20-Sep-2004 01:57
If you use serialize() to easily convert an array to a sort of string which you can add to a URL, pay attention to the length of the serialized array.
A URL has a limit when it comes to passing variables and values and it cuts off whatever is over limit. If your serialized array is too long, it will be cut off and you will end up with strange results on your other pages.
jasbarne NOSPAM indiana SPAMSUCKS edu 22-Aug-2004 01:01
ignatiev at users dot sourceforge dot net and others using __sleep():

If you decide to add this functionality (for whatever reason) you can serialize a modified copy of the object instead of the original object.  There's added overhead of copying, but doing this allows you to continue using the original object after you've serialize it.
goetas at lignano dot it - GoetAs 11-Aug-2004 10:41
the serialize dont function properly when a variable contain a ;
I wrote these two functions that resolve this problem:
this function work only with arrays:
<?php

function base64_unserialize($str){
    $ary = unserialize($str);
    if (is_array($ary)){
        foreach ($ary as $k => $v){
            if (is_array(unserialize($v))){
                $ritorno[$k]=base64_unserialize($v);
            }else{
                $ritorno[$k]=base64_decode($v);
            }
        }
    }else{
        return false;
    }
    return $ritorno;
}
function base64_serialize($ary){
    if (is_array($ary)){
        foreach ($ary as $k => $v){
            if (is_array($v)){
                $ritorno[$k]=base64_serialize($v);
            }else{
                $ritorno[$k]=base64_encode($v);
            }
        }
    }else{
        return false;
    }
    return serialize ($ritorno);
}
?>
Andrew dot Morrison at stanford dot edu 29-Jun-2004 03:02
Correction to my last note:

__sleep should return an array only containing the names of instance-variables to serialize.

A simple (if not a little wasteful) hack to serialize all but a few class vars is to use get_class_vars as follows:

<?php

class strawman
{
  var $good_var;
  var $lame_var;

  function __sleep()
  {
    print "Function __sleep() called\n";

    $vars = get_class_vars('strawman');
    unset($vars['lame_var']);
    return array_keys($vars);
  }

  function __wakeup()
  {
   print "Function __wakeup() called\n";
  }

  function strawman() { }
}

session_start();

if(session_is_registered('strawman'))
{
  print("session data:\n");
  print_r($_SESSION['strawman']);
  session_destroy();
}

else
{
  $strawman =& new strawman();
  session_register('strawman');
  print("new session data:\n");
  print_r($_SESSION['strawman']);
}

?>
dr dot slump at cyteknt dot com 27-Apr-2004 09:15
regarding PHP to JS serialization I did some time ago a function which works using "eval" as Harry points out.

<?php
//helper function, returns true if the array is associative
function is_assoc_array( $var ) {
    //false if not an array or empty
    if ( (!is_array($var)) || (!count($var)) ) return false;

    foreach($var as $k=>$v)
        if (! is_int($k)) return true;

    return false;
}
?>

Serialize function which generates JavaScript's eval's compatible code.

Usage (JavaScript) :
var myVar = eval('<?php js_serialize($phpvar); ?>');

Notes:
Objects and associative arrays are encoded as JS Objects
Doesn't serialize object methods
Serializes 'resource' types as nulls
Assoc. Arrays containing integer keys, those keys are prefixed with 'idx_'

<?php
function js_serialize($var, $recursed = false) {
    if (is_null($var) || is_resource($var)) return 'null';

    $js = '';

    //object or assoc. array
    if (is_object($var) || is_assoc_array($var)) {
        //typecast to array in the case it could be an object
        $props = (array)$var;

        foreach($props as $k=>$v) {
            //index values are preffixed with 'idx_'
            if (is_int($k)) $k = "idx_$k";
            $js .= $k.':'.js_serialize($v, true).',';
        }
        if (count($props))
             $js = substr($js, 0, strlen($js)-1);

         $js = '{'.$js.'}';
         if (! $recursed) $js = "($js)";

    } elseif (is_array($var)) {
        foreach($var as $v)
            $js .= js_serialize($v, true).",";
        if (count($var))
            $js = substr($js, 0, strlen($js)-1);
        $js = "[$js]";

    } elseif (is_string($var)) {
        //escape the string
        $var = str_replace( array('"', "\n", "\r"), array('\\"', '\\n'), $var );
        $js = $recursed ? "\"$var\"" : "(new String(\"$var\"))";

    } elseif (is_bool($var)) {

        $var = ($var)?'true':'false';

        $js = $recursed ? $var : "(new Boolean($var))";

    } else { //should be an int or a float in theory

        $js = $recursed ? $var : "(new Number($var))";
    }

    return $js;
}
?>
hfuecks at phppatterns dot com 21-Apr-2004 08:20
Regarding serializing PHP data types to Javascript, following Ivans note below, theres an example at http://www.tekool.net/php/js_serializer/.

The basic serialization looks good although, in its current form, it works on the basis of generating Javascript source which a browser executes as a page loads. Using Javascripts eval() the same can be done with strings containing Javascript if youre working with something like XMLHTTPRequest
Antonie 20-Apr-2004 10:12
Passing of multiple select (single dimensional or even multidimensional) arrays is even harder, even using serialize.
Jouhni [jouhni at web dot de] 08-Feb-2004 05:48
In order to save serialized values in cookies you have to pay attention to the following:
A serialized array looks like this:

a:2:{i:0;s:9:"Element 1";i:1;s:9:"Element 2";}

Because quotation marks are saved with a backslash in front of it in cookies it is not possible to unserialize a cookie-saved serialized array. You have to do a stripslashes() before unserializing the cookie.
info at b1g dot de 07-Feb-2004 10:37
If you are using Cache_Lite from pear.php.net and if you are logging in your users using cookies, use this cache-ID for example:

<?php
$cache_id = base64_encode($_SERVER['REQUEST_URI'] . serialize($_COOKIE));
?>

This will create a new page in cache when a user logs in. Anyway he can't login properly. Works fine for me.

Sorry for my broken English.
tino at infeon dot com 24-Nov-2003 02:20
While writing shopping cart applications i needed a way to keep track of many variables beteween page loads.. i was using a cookie for each but this became hard to manage so I cam up with this simple session object. It serializes the object, base 64 encodes it and sets a cookie for it.. vice versa on page load where it detects the cookie

add whatever variables you need to this class

btw if you like it, hate it or have any comments send me an email to let me know

<?php
class session {
    var $cartID;
    var $userID;
    var $userAuth;

    function session () {
        //Attempt to load previous session from user cookie

        //First see if the session was passed through the URL
        //This is useful to pass stuff between different URL
                if ($_GET['session']) {
            $this = unserialize (base64_decode ($_GET['session']));

                //Check for the cookie, if none a blank session is created
                } else {
            if ($_COOKIE['session']) {
                $this = unserialize (base64_decode ($_COOKIE['session']));
            }
        }
    }

    function save () {
        setcookie ('session', base64_encode (serialize ($this)));
    }

    function delete () {
        setcookie ('session');
        unset ($this);
    }

}
?>
ignatiev at users dot sourceforge dot net 23-Oct-2003 06:35
One problem with serialize() is that by default it does NOT alter the object, so nothing prevents you from continuing using you object after serialize()'ing it.

After a while, you or someone else decides to optimize storage of this object and add a __sleep and __wakeup functions; now, serialize()'ing this same class calls __sleep() member function, potentially changing the object - old code unexpectedly breaks.

Possible solutions: in the above scenario old code would most likely still work if __sleep() only creates new object variables, not altering existing ones.  Another option is to always call __wakeup(), if it exists, after each serialize(), or immediately destroy the object if it is no longer used.
iam4webwork at hotmail dot com 14-Sep-2003 05:00
I think an example is in order to specify what is meant by "returns a string containing a byte-stream representation of value that can be stored anywhere."

Here's an example:

<?php
echo serialize("php");
?>

Result is as follows:

s:3:"php";

The cryptic result is a string indicating that the serialized data is itself a string of 3 bytes whose value is "php".
james at gogo dot co dot nz 30-Jul-2003 03:04
I just spent an hour rifling through code to find the cause of a problem
only to find it's an oddity with serialization and recursive objects, so
figured I'd post for the next person who gets the same problem.

********************************* Symptoms *********************************
When unserializing a previously serialized object, the __wakeup() function
is mysteriously called more than once, and the accessing the objects
properties from the "outside" gives different results than accessing them
from an object contained within the object and holding  a recursive
reference to the object.

********************************** Example *********************************
<?php
class foo2 {
        var $foo = NULL;
        function foo2(&$foo) {
                $this->foo =& $foo;
        }

        function fooName() {
                echo 'foo2 thinks foo->name is ' . $this->foo->name . '<br>';
        }
}

class foo {
        var $name  = 'unnamed';
        var $foo2 = NULL;

        function foo() {
                $this->foo2 =& new foo2($this);
        }

        function fooName() {
                echo 'foo thinks foo->name is ' . $this->name . '<br>';
        }

        function __wakeup() {
                echo "foo is waking up<br>";
        }
}

$myFoo         =& new foo();
$myFoo->name   = 'myFoo';
echo "I think foo->name is {$myFoo->name}.<br>";
$myFoo->fooName();
$myFoo->foo2->fooName();

$serializedFoo = serialize($myFoo);
$myNewFoo      = unserialize($serializedFoo);

$myNewFoo->name = 'myNewFoo';
echo "I think foo->name is {$myNewFoo->name}.<br>";
$myNewFoo->fooName();
$myNewFoo->foo2->fooName();
?>

********************************** Analysis ********************************
execution of the example produces...

I think foo->name is myFoo.
foo thinks foo->name is myFoo
foo2 thinks foo->name is myFoo
foo is waking up
foo is waking up
I think foo->name is myNewFoo.
foo thinks foo->name is myNewFoo
foo2 thinks foo->name is myFoo

We can see that the first three lines are as expected, however we see
__wakeup is happening twice, and then the final line is in error as foo2
apparently does not see the changed name.

What is happening is that there are actually two seperate foo objects being
deserialized, the "top level one" and the one that was originally
referenced in foo2, that is, the reference is not being serialized as a
reference but rather a whole object.  This is evident in the two __wakeup()
calls, there are two foo objects being woken up.

******************************** Solution **********************************
The solution is very simple, when serializing it is necessary to force the
passing of a reference to the top-level object being serialized thus..

$serializedFoo = serialize(&$myFoo);

with that form of the serialization (note the ampersand to force passing of
reference), the example produces the following..

I think foo->name is myFoo.
foo thinks foo->name is myFoo
foo2 thinks foo->name is myFoo
foo is waking up
I think foo->name is myNewFoo.
foo thinks foo->name is myNewFoo
foo2 thinks foo->name is myNewFoo

We note now there is only one __wakeup() call being made and that all
parties agree on the name property of the foo object.

******************************** Notes ************************************
I was of the belief that ampersand's in the arguments to functions was
deprecated in favour of ampersands in the function's parameter list
declaration (i.e instead of "blah(&$my_thing)" we declare blah as "function
blah(&$your_thing) {...}"), however this required use of serialize seems to
contravene this deprecation as it is plainly necessary to use the ampersand
in the function call here.  Perhaps this is a hold-over from earlier times
and will be changed in the future ?

--
James Sleeman (http://www.gogo.co.nz/)
dan at mojavelinux dot com 18-Jul-2003 12:08
In order to safely unserialize a complex object in any context, it is wise to save two files at the time of serialization (or save the file in two parts).  One file will contain the result of get_included_files() at the time of serialization and the other file contains the serialized version of the object.  To unserialize, simply read in the included file list and call include_once on all of those files and then call unserialize on your object data.

While this may be slightly inefficient because certain files that were included are no longer needed (maybe they were only needed when creating the object), at least you can be sure the object data is going to come out of serialization okay.

Note: If you stick to the convention of classes beginning with uppercase (and the filenames following the classnames) then you can even filter the get_included_files() list to get only the class definition files.
webmaster at feeltong dot com 12-Jun-2003 03:49
People usually use 'hidden' fields when they submit some variables from previous step to the next step even if they have so many varibles to send. It will look like following form.

<form name='tmpForm' method='post' action='nextStep.php'>
<input type='hidden' name='var[name]' value='<?=$var[name]?>'>
<input type='hidden' name='var[id]' value='<?=$var[id]?>'>
<input type='hidden' name='var[address]' value='<?=$var[address]?>'>
<input type='hidden' name='var[age]' value='<?=$var[age]?>'>
<input type='hidden' name='var[gender]' value='<?=$var[gender]?>'>
<input type='hidden' name='var[car]' value='<?=$var[car]?>'>
.
.
.
</form>

Look at the following codes. It is more simplified. I'd better use base64_encode and serialize than stripslashes and serialize.

<form name='tmpForm' method='post' action='nextStep.php'>
<input type='hidden' name='var' value='<?=base64_encode(serialize($var))?>'>
</form>

Have Fun !!!
rodrigo at ditech dot com dot br 17-Apr-2003 11:38
Hi!
If you wanna save all the POST data and reload it again in another time... you can use this:
(Thanks for my_stripslashes() function ;-)

<?php
// saving POST
if ($REQUEST_METHOD=="POST") {
    $fp = fopen("postData.txt","w");
  $data = addslashes(serialize($_POST));
  fwrite($fp, $data);
   fclose($fp);
}

// reloading POST and passing to variables
if (file_exists("postData.txt")) {
  $data = file("postData.txt");
  $data = my_stripslashes($data[0]); // catches it in some message above
  $postData = unserialize($data);
    extract($postData, EXTR_OVERWRITE);
}
?>

Now you have all variables from old POST in your actual script.
Well useful when you have a great form very used and of course, DEPENDING of your tool.
pli9 at itsa dot ucsf dot edu 31-Jan-2003 11:05
I have also written some code for importing serialized PHP data into PERL and then writing it back into PHP.  I think the similar library posted above is actually more robust for a few select cases, but mine is more compact and a little easier to follow.  I'd really like comments if anyone finds this useful or has improvements.  Please credit me if you use my code.

http://www.hcs.harvard.edu/~pli/code/serialPHP.pm
kjh90 at orgio dot net 20-Mar-2002 12:43
If you want to put serialized data into DB, you have to add slashes.
At this point, there's a problem. If you got data via HTTP POST method, the data has slashes already. I tried to work with "array_walk" or "array_map", but it doesn't work when the data has array.
So make extended stripslashes function.

<?php
function my_stripslashes($vals) {
    if (is_array($vals)) {
        foreach ($vals as $key=>$val) {
            $vals[$key]=my_stripslashes($val);
        }
    } else {
        $vals = stripslashes($vals);
    }
    return $vals;
}

$data = addslashes(serialize($_POST));
...
$SQL="insert into DB() values($data)";
...
$SQL="select data from DB";
...
$data = my_stripslashes($data);
...
?>
17-Jul-2001 06:39
BEWARE: if you serialize to store values on a database, and the variables you are serializing already have the " (double-quote) char, you may have a problem. After serializing you will have var delimiters as " and content " (double-quotes) escaped, but your databse may just treat them like the same. You end up with a failed unserialize. You want something like:

a:5:{s:9:"this is a \"quote\"";a:1:{s:(ETC)

And not:
a:5:{s:9:"this is a "quote"";a:1:{s:(ETC)

So just make sure you double escape content quotes ...

It's simple, but i can't explain it any simpler =(
scott (at) hurring.com 12-Jul-2001 02:44
I have written a perl module that does the same thing as PHP's serialize() and unserialize() commands so that Perl can now serialize and unserialize data in the same format as PHP.

It's quite handy for storing information in databases or files (or anywhere, really) that both PHP and Perl scripts need to read from and write to.

It supports string, double, integer, and array types (no object or reference support).

It's free code, too. :)

URL: http://hurring.com/code/perl/serialize/
sbarnum at mac dot com 24-May-2001 07:53
If you're having trouble with serialized strings, try this function.  Pass it the name of an array whose value you want to include in hidden form inputs, a url, or session variable.  Works with strings or multidimensional arrays.

<?php
    //////////////////////////////////////////////
    // propogate v0.8 by sbarnum
    // method can be 'form' or 'url' or 'session'
    //////////////////////////////////////////////
function propogate ($arrayName, $method='form', $arrayData=''){
    if($arrayData){
        // custom values passed to array, use these instead of globals
        ${$arrayName} = $arrayData;
    }else{
        // use global values
        global ${$arrayName};
    }
    if ($method == "session"){
        session_register(${$arrayName});
        return TRUE;
    }

    @reset(${$arrayName});
    while (list($key,$value)=@each(${$arrayName})){
        if (is_array($value)){
            $subArrayName = $arrayName . "[" . $key . "]";
            $html .= propogate ($subArrayName, $method, $value);
        }else{
            switch ($method){
                case "form":
                $html .= "<INPUT type='hidden' name='".$arrayName."[".$key."]' value='".htmlspecialchars($value)."'>\n";
                break;
                case "url":
                $html .= "&".$arrayName."[".$key."]=" . urlencode($value);
                break;
            }
        }
    }
    return $html;
}
?>
MarkRoedel at letu dot edu 21-Feb-2000 10:58
A call to serialize() appears to mess with the array's internal pointer.  If you're going to be walking through your array after serializing it, you'll want to make a call to reset() first.
print_r
settype
Функции для работы с переменными


Присваивает переменной новый тип

serialize
strval
Функции для работы с переменными
PHP Manual

settype

(PHP 4, PHP 5)

settype — Присваивает переменной новый тип

Описание

bool settype ( mixed &$var , string $type )

Присваивает переменной var тип type.

Список параметров

var

Преобразуемая переменная.

type

Допустимыми значениями параметра type являются:

  • "boolean" (или, начиная с PHP версии 4.2.0, "bool")
  • "integer" (или, начиная с PHP версии 4.2.0, "int")
  • "float" (возможно только c PHP 4.2.0, для предыдущих версий используйте устаревший вариант "double")
  • "string"
  • "array"
  • "object"
  • "null" (начиная с PHP версии 4.2.0)

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования settype()

<?php
$foo = "5bar"; // строка
$bar = true;   // булевое значение

settype($foo, "integer"); // $foo теперь 5   (целое)
settype($bar, "string");  // $bar теперь "1" (строка)
?>

Примечания

Замечание:

Максимальное значение для "int" равно PHP_INT_MAX.

Смотрите также

  • gettype() - Возвращает тип переменной
  • Приведение типов
  • Манипуляции с типами

User Contributed Notes

Special Notes 26-Feb-2012 12:00
Note that you can't use this to convert a string 'true' or 'false' to a boolean variable true or false as a string 'false' is a boolean true. The empty string would be false instead...

<?php
$var = "true";
settype($var, 'bool');
var_dump($var); // true

$var = "false";
settype($var, 'bool');
var_dump($var); // true as well!

$var = "";
settype($var, 'bool');
var_dump($var); // false
?>
brent_hathaway at yahoo dot com 30-Jun-2011 02:03
Use intval instead of settype for integers. Much more reliable.
contact[at]covac-software[dot]com 28-Aug-2010 02:17
With reply to Chris Sullins and Michael Benedict, I don't find this behavior strange:

<?php
  echo var_dump( (int)'' );                    // int(0)

  echo var_dump( (float)array('a'=>'b') );    // float(1)
?>

This is due to the fact that an uninitialized variable is null, which converts to a 0. As does boolean false or an empty string or array.
When a value is not empty, such as my above array, it is converted to a 1 (integer/float) or true (boolean).
When changing between arrays and objects, it of course made sense to keep the fields intact (array key/values and object properties/values).

Cheers,
Chris.
Chris Sullins 18-Apr-2010 11:59
settype() has some really strange, potentially buggy behavior.

As noted by Michael Benedict, using settype() on a variable will initialize that variable.  What is stranger is that using settype() on an uninitialized variable that you are treating as an array or object will also initialize the variable.  So:

<?php
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

This works for a chain of any length: $foo->bar['baz']->etc

Next we look at what happens if $foo is already set.

<?php
$foo = false;
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

In and of itself, this wouldn't be problematic.  It might even make sense.  But in all other cases where $foo is defined, even if (boolean) $foo === false, it will throw an error unless $foo->bar is valid (i.e. $foo is an object already).

<?php
$foo = true;
settype($foo->bar,"integer"); // Notice: Trying to get property of non-object
?>
michaltrutman at centrum dot cz 03-Feb-2009 08:32
You can change variable type also in another way instead of using function settype().

<?PHP
$a = '125'; //$a is string
var_dump($a);

$a *= 1; //this convert $a to integer
var_dump($a);

$a *= 1.0; //$a is converted to float
var_dump($a);

$a .= ''; //now $a is string again
var_dump($a);

$a = NULL; //and finally $a is null
var_dump($a);
?>

With this you can easily change variable type to string, float or integer (but you can't change float to integer).

Positive side effect of this is that it is about 50% faster than using settype() function. This is because simple expression is executed more quickly than function.
NWdev 17-Nov-2008 09:38
In trying to convert an array of strings to an array of ints,
I attempted to use settype with array_walk.

<?php
//$numArray is generated by another process
$numArray = array('13','14','33');

var_dump($numArray);

//my conversion function
function str_to_int($val){
  //remember: settype($x, 'int') returns boolean (1=success, 0=failure)
  //--> so return $x to return new value
    settype($val,'int');
    echo "<br />gettype = ".gettype($val)."<br />";
    return $val;
}

array_walk($numArray,'str_to_int');

var_dump($numArray);
?>

The var_dumps both return the following:
<?php
array(3) { [0]=> string(2) "13" [1]=> string(2) "14" [2]=> string(2) "33" }
?>

The gettype echo will show the value as an integer.

So it seems that settype($val,'int') makes the conversion,
but the function return value remains a string.
Since settype returns a boolean, using
<?php $val = settype($val, 'int'); ?>
is not a option.

I resolved my array value conversion using this instead:
<?php
$numArray =
      array_map(create_function('$value', 'return (int)$value;'),$numArray);
?>
Thanks to the posting here:
http://usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html

Perhaps this will save someone else spinning wheels a bit.

Also thanks to robin at barafranca dot com for
pointing out the boolean return value of settype.
mtinsley at dallasairmotive dot com 22-Jun-2008 01:36
Yes, just look for the ampersand (&) in the function signature. Here you see:

bool settype  ( mixed &$var  , string $type  )

There is an & before the first parameter ($var). This means the variable is passed in by reference. So the function is working with the original variable and not a copied local version. You will see this in other php functions such as asort();

References Explained: http://us3.php.net/manual/en/language.references.php
robin at barafranca dot com 05-Mar-2008 04:20
Just a quick note, as this caught me out very briefly:

settype() returns bool, not the typecasted variable - so:

$blah = settype($blah, "int"); // is wrong, changes $blah to 0 or 1
settype($blah, "int"); // is correct

Hope this helps someone else who makes a mistake.. ;)
sneskid at hotmail dot com 05-Mar-2007 02:57
In response to the guy who was having troubles with leading zeros and wrote the convertToInt function.

I benchmarked it and it is faster to just use base_convert than ltrim & friends.

base_convert also has a lower "first time call" cost than ltrim (this could be related to server settings).
It's about 2/3 that of ltrim.

If you only use this type of conversion once per script then it's far more beneficial to use base_convert.

The average values listed are ignoring the first time call costs.
<?php

$t = '0100';

// avg: 0.0000025 (0.0000036 wrapped as a function)
$x = base_convert($t, 10, 10);

// avg: 0.0000028 (0.0000039 wrapped as a function)
$x = 0+ltrim($t,'0');
?>
ludvig dot ericson gmail.dot com 09-Apr-2006 08:36
To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/

As a part of a framework or something.

Plus, you can probably call this with call_user_func
matt at mattsoft dot net 06-Dec-2005 09:49
using (int) insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.
Michael Benedict 29-Oct-2005 10:55
note that settype() will initialize an undefined variable.  Therefore, if you want to preserve type and value, you should wrap the settype() call in a call to isset().

<?php
settype($foo, "integer");
echo("|$foo|");
?>

prints "|0|", NOT "||".

To get the latter, use:
<?php
if(isset($foo)) settype($foo, "integer");
echo("|$foo|");
?>
25-Oct-2005 06:30
James Reiher (IL) writes:
23-Feb-2005 06:50

$agentnum = "007";
$agentnum = settype($agentnum, "int");
echo $agentnum; // will show up as 1 instead of 7!

James, the return value of settype function is boolean, 1 if succsess.
Correct code: $success=settype($agentnum, "int");
The $agentnum is now 7 (not 007 or not 1)!
25-Sep-2005 01:24
In response to the comment by Neoja regarding validating every variable in the URL using settype -- that is wrong.

All value passed in the URL are strings, even if they are numbers. (Remember, they are passed in the header, which is a specially formatted string).
nospamplease at veganismus dot ch 22-Jul-2005 07:38
you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.
16-May-2005 12:22
I needed to pull a zerofilled integer out of a MySQL table and increment it by a certain amount.  Unfortunately, PHP treated this integer as if it were a string when I tried to add an amount to it.  For instance:

<?php
$a = '0100';
$b = $a + 1;
print $b;
// This would print 64 instead of 101.
?>

To fix this I created a simple function:

<?php
function convertToInt($string) {
    $y = ltrim($string, '0');
    $z = 0 + $y;
    return $z;
}
// Now I can add any integer to my converted integer
$a = '0100';
$b = 2 + convertToInt($a);
print $b;
// This prints 102
?>
reinier_deblois at hotmail dot com 13-Mar-2005 09:18
Instead of settype you could use:
<?php

$int=593;  // $int is a integer

$int.="";   // $int is now a string
James Reiher (IL) 22-Feb-2005 09:50
I had a problem with PHP destroying the value of my integer with leading zeros as follows:

$agentnum = "007";
$agentnum = settype($agentnum, "int");
echo $agentnum; // will show up as 1 instead of 7!

Oddly enough, this works fine, (at least for PHP 4.3):
$agentnumber = "007";
$agentnumber += 0; // convert $number to numeric type
echo $agentnumber; // will now show up as 7!

If you do this for gods sake leave a comment on the line because its definitely not by-the-book coding. Another commentor here has used regular expressions to weed out the leading zeros, so I know its not the only solution.

I also tried the equivelant of:
$agentnum = "007";
$agentnum = (int)$agentnumber;
echo $agentnum;

But the result is a nonsense number, probably by using the concatenation of the ASCII codes as the integer.
memandeemail at gmail dot com 09-Dec-2004 05:17
/**
    * @return bool
    * @param array[byreference] $values
    * @desc Convert an array or any value to Escalar Object [not tested in large scale]
    */
    function setobject(&$values) {
        $values = (object) $values;
        foreach ($values as $tkey => $val) {
            if (is_array($val)) {
                setobject($val);
                $values->$tkey = $val;
            }
        }
        return (bool) $values;
    }
23-Nov-2004 01:34
in PHP3 converting a string to any number results in the value becoming 0.  To check if a string represents a number try this:
<PRE>
$test = "0001";
$testcp = $test;
settype($testcp,"double");

if (strval($testcp) === $test) {
   echo("\$test is a number");
} else {
   echo ("\$test is not a number");
}
</PRE>
sdibb at myway dot com 06-Sep-2003 10:03
Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins.  The function intval($string) does the same thing.

If you're looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes),  try this instead:

<?
     $number=ereg_replace("[^0-9]","",$number);
?>
djworld at php dot net 17-Jul-2002 06:02
Usually it won't be necessary to use this function, but some times you need to be sure the variables are of some kind. For example, if you send a number to a database query from a variable passed by GET or POST, you may get sure it's a number by doing SetType ($var, 'integer'); so you can avoid security holes if it isn't a number and you don't need to addslashes() it, or for example, if you need to be sure that a number won't have any decimals after rounding it, you may do the same and as it will be an integer, it won't contain decimals.

(ed: change to reflect deleted of other notes)
r dot schechtel at web dot de 06-Aug-2001 02:59
To: neoja@hotmail.com

I believe in this case testing the $id using is_numeric() would be the better solution.

E.g something like this:

<?php
 if (is_numeric($id)) {
  $db->query($sql);
 }
?>

Roman Schechtel
neoja at hotmail dot com 17-Feb-2001 06:42
It is always good to validate all the variables that are given in the url and would cause an error if they are of wrong type. For example, if your page is products.php?id=123 then run settype($id, "integer") in the script, before getting the product info from the database. If the user enters a non-numeric value in the url -- either pasting it wrong or intentionally :) -- the $id will be set to zero and database query will have no errors.
ns at canada dot com 05-May-2000 04:38
This settype() behaviour seems consistent to me. Quoting two sections from the manual:

"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "
<pre>
2 $var = 'ciao';
3 $arr = (array) $var;
4 echo $arr[0];  // outputs 'ciao'
</pre>

And if (like your code above) you do a settype on an empty variable, you'll end up with a one element array with an empty (not unset!) first element. So appeanding to it will start appending at index 1. As for why reset() doesn't do anything:

"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."

It doesn't matter where the array counter is; values are added at the end, not at the counter.
serialize
strval
Функции для работы с переменными


Возвращает строковое значение переменной

settype
unserialize
Функции для работы с переменными
PHP Manual

strval

(PHP 4, PHP 5)

strval — Возвращает строковое значение переменной

Описание

string strval ( mixed $var )

Возвращает строковое значение переменной. См. документацию по типу string для более подробной информации о преобразовании в строку.

Эта функция не производит форматирование возвращаемого значения. Если необходимо привести числовое значение к строке с особым форматом, воспользуйтесь sprintf() или number_format().

Список параметров

var

Переменная, которую необходимо преобразовать в строку.

var может быть любого скалярного типа или объектом, который реализует метод __toString(). strval() нельзя применить к массиву или объекту, которые не реализуют метод __toString().

Возвращаемые значения

Строковое значение (string) параметра var.

Примеры

Пример #1 Пример использования strval() с магическим методом PHP 5 __toString().

<?php
class StrValTest
{
    public function __toString()
    {
        return __CLASS__;
    }
}

// Выводит 'StrValTest'
echo strval(new StrValTest);
?>

Смотрите также

  • floatval() - Возвращает значение переменной в виде числа с плавающей точкой
  • intval() - Возвращает целое значение переменной
  • settype() - Присваивает переменной новый тип
  • sprintf() - Возвращает отформатированную строку
  • number_format() - Форматирует число с разделением групп
  • Манипуляции с типами
  • __toString()

User Contributed Notes

Hayley Watson 21-Aug-2007 08:53
As of PHP 5.2, strval() will return the string value of an object, calling its __toString() method to determine what that value is.
NyctoFixer at gmail dot com 11-Jun-2007 12:19
As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

<?

/**
 * Returns the string value of a variable
 *
 * This differs from strval in that it invokes __toString if an object is given
 * and the object has that method
 */
function stringVal ($value)
{
    // We use get_class_methods instead of method_exists to ensure that __toString is a public method
    if (is_object($value) && in_array("__toString", get_class_methods($value)))
        return strval($value->__toString());
    else
        return strval($value);
}

?>
kendsnyder+phpnet at gmail dot com 01-Jun-2007 10:08
The only way to convert a large float to a string is to use printf('%0.0f',$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf('%0.0f',pow(2,50)); // 112589906846624
echo sprintf('%0.0f',pow(2,50)); // 112589906846624
portos_ze_retour at hotmail dot fr 10-Mar-2006 08:15
In complement to Tom Nicholson's contribution, here is the french version (actually it's possible to change the language, but you should check the syntax ;) )

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
     $w = '#';
   else if(fmod($x, 1) != 0)
     $w = '#';
   else {
     if($x < 0) {
         $w = $nwords['minus'].' ';
         $x = -$x;
     } else
         $w = '';
     // ... now $x is a non-negative integer.

     if($x < 21)  // 0 to 20
         $w .= $nwords[$x];
     else if($x < 100) {  // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
           $w .= '-'. $nwords[$r];
     } else if($x < 1000) {  // 100 to 999
         $w .= $nwords[floor($x/100)] .' '.$nwords['hundred'];
         $r = fmod($x, 100);
         if($r > 0)
           $w .= ' '.$nwords['separator'].' '. int_to_words($r);
     } else if($x < 1000000) {  // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' '.$nwords['thousand'];
         $r = fmod($x, 1000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $w .= $nwords['separator'].' ';
           $w .= int_to_words($r);

         }
     } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' '.$nwords['million'];
         $r = fmod($x, 1000000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $word .= $nwords['separator'].' ';
           $w .= int_to_words($r);
         }
     }
   }
   return $w;
}

 // Usage in English
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" , "hundred" => "hundred", "thousand"=> "thousand", "million"=>"million",
                   "separator"=>"and", "minus"=>"minus");

echo 'There are currently '. int_to_words(-120223456) . ' members logged on.<br>';

 //Utilisation en Francais
$nwords = array( "zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept",
                   "huit", "neuf", "dix", "onze", "douze", "treize",
                   "quatorze", "quinze", "seize", "dix-sept", "dix-huit",
                   "dix-neuf", "vingt", 30 => "trente", 40 => "quarante",
                   50 => "cinquante", 60 => "soixante", 70 => "soixante-dix", 80 => "quatre-vingt",
                   90 => "quatre-vingt-dix" , "hundred" => "cent", "thousand"=> "mille", "million"=>"million",
                   "separator"=>"", "minus"=>"moins");

echo 'Il y a actuellement '. int_to_words(-120223456) . ' membres connectés.<br>';
anthony dot parsons at manx dot net 09-Jan-2006 09:59
If you have to compare object variables like this be careful not to make a typo, or you could end up calling __set() -
<?php
/* Does what you'd expect it to */
if ( $user->password == $user2->password )

/* Doesn't */
if ( $user->password = $user2->password )
?>

To avoid that ever happening, do it like this:
<?php
if ( strval($user->password) == $user2->password )
?>
php at ianco dot co dot uk 07-Oct-2005 04:36
I can't help being surprised that

(string)"0" == (string)"0.00"

evaluates to true. It's the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.
Steve Ball 08-Sep-2005 07:18
It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

2326201276 - (-1968766020) =  4294967296.
brettsg at serialio dot com 02-Aug-2005 09:07
How come this code in version 4.4 does something different than in version 4.3?

$val = 538759009 ^ 0xAABBCCDD;
print "val=" . $val;

= 2326201276 (version 4.4)

and

= -1968766020 (version 4.3)
Redbeard 24-Aug-2004 02:40
You can also use the PEAR package Numbers_Words, which handles many other languages.
Tom Nicholson 28-Apr-2004 09:13
If you want to convert an integer into an English word string, eg. 29 -> twenty-nine, then here's a function to do it.

Note on use of fmod()
  I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven't bothered with "billion" because the word means 10e9 or 10e12 depending who you ask.

The function returns '#' if the argument does not represent a whole number.

<?php
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" );

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
      $w = '#';
   else if(fmod($x, 1) != 0)
      $w = '#';
   else {
      if($x < 0) {
         $w = 'minus ';
         $x = -$x;
      } else
         $w = '';
      // ... now $x is a non-negative integer.

      if($x < 21)   // 0 to 20
         $w .= $nwords[$x];
      else if($x < 100) {   // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
            $w .= '-'. $nwords[$r];
      } else if($x < 1000) {   // 100 to 999
         $w .= $nwords[floor($x/100)] .' hundred';
         $r = fmod($x, 100);
         if($r > 0)
            $w .= ' and '. int_to_words($r);
      } else if($x < 1000000) {   // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' thousand';
         $r = fmod($x, 1000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $w .= 'and ';
            $w .= int_to_words($r);
         }
      } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' million';
         $r = fmod($x, 1000000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $word .= 'and ';
            $w .= int_to_words($r);
         }
      }
   }
   return $w;
}

?>

Usage:
<?php
echo 'There are currently '. int_to_words($count) . ' members logged on.';
?>
settype
unserialize
Функции для работы с переменными


Создает PHP-значение из хранимого представления

strval
unset
Функции для работы с переменными
PHP Manual

unserialize

(PHP 4, PHP 5)

unserialize — Создает PHP-значение из хранимого представления

Описание

mixed unserialize ( string $str )

unserialize() принимает одну сериализованную переменную и конвертирует ее обратно в значение PHP.

Список параметров

str

Сериализованная строка.

Если переменная, требующая десериализации, является объектом, то после успешного восстановления объекта PHP автоматически попытается вызвать магический метод __wakeup() (если он существует).

Замечание: Директива unserialize_callback_func

Существует возможность указать функцию обратного вызова, которая будет вызвана, если в процессе десериализации должен быть проинициализирован неопределенный класс. (для предотвращения получения неполного объекта object "__PHP_Incomplete_Class".) Используйте php.ini, ini_set() или .htaccess для определения функции 'unserialize_callback_func'. Данная функция будет вызываться каждый раз, когда должен быть проинициализирован неопределенный класс. Для отключения этой возможности просто оставьте значение директивы пустым.

Возвращаемые значения

Возвращается преобразованное значение, которое принимать один из типов boolean, integer, float, string, array или object.

В случае, если переданная строка не поддается десериализации, возвращается FALSE и генерируется E_NOTICE.

Список изменений

Версия | Описание
4.2.0 | Стала доступна директива unserialize_callback_func.

Примеры

Пример #1 Пример использования unserialize()

<?php
// Мы используем функцию unserialize() для загрузки сессионных данных в массив
// $session_data из строки, извлекаемой из базы данных.
// Данный пример дополняет пример, описывающий использование serialize().

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array($_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) {
    // если процедура извлечения данных не удалась, то инициализируем пустой массив
    $session_data = array();
} else {
    // сейчас у нас должны быть сериализованные данные в $tmp[0].
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
        // что-то пошло не так, инициализируем пустой массив
        $session_data = array();
    }
}
?>

Пример #2 Пример использования unserialize_callback_func

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

// директива unserialize_callback_func доступна с PHP 4.2.0
ini_set('unserialize_callback_func', 'mycallback'); // определяем свою функцию обратного вызова

function mycallback($classname)
{
    // просто подключаете файл, содержащий определение класса
    // $classname указывает, для какого класса требуется определение
}
?>

Примечания

Внимание

FALSE возвращается как в случае ошибки, так и в случае, если десериализуется сериализованное значение FALSE. Этот особый случай можно отловить, используя сравнение str со значением serialize(false), или перехватив сгенерированную ошибку E_NOTICE.

Смотрите также

  • serialize() - Генерирует пригодное для хранения представление переменной
  • Автозагрузка объектов
  • unserialize_callback_func
  • __wakeup()

User Contributed Notes

php at deltatech-v2 dot de 26-Mar-2012 11:00
I used Google-Oauth for authentication, got a &quot;Person-Object&quot; back and saved this in the database (serialized).
After unserializing, i got the PHP_INCOMPLETE-Class, because the Person-Class was not included.

To avoid this i converted the original-class to a PHP stdClass via Json:

&lt;?php
// Before: $me_data == Person()
$me_data = json_encode($me_data);
$me_data = json_decode($me_data);
// After: $me_data == stdClass()
?&gt;
suman dot jis at gmail dot com 13-Mar-2012 09:12
I was getting unserialize()  Error at offset error.

If you face similar problem  then use the following procedure

$auctionDetails = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $dataArr[$i]['auction_details'] );
$auctionDetails = unserialize($auctionDetails);
dcz at phpbb-seo dot com 08-Nov-2011 06:00
If you are unserializing content from user input and you don't expect objects to be passed (which should be the most common case), you can use this to prevent any object reviving threat :

<?php
/**
* mixed safe_unserialize(string $serialized)
* Safely unserialize, that is only unserialize string, numbers and arrays, not objects
*
* @license Public Domain
* @author dcz (at) phpbb-seo (dot) com
*/
function safe_unserialize($serialized) {
    // unserialize will return false for object declared with small cap o
    // as well as if there is any ws between O and :
    if (is_string($serialized) && strpos($serialized, "\0") === false) {
        if (strpos($serialized, 'O:') === false) {
            // the easy case, nothing to worry about
            // let unserialize do the job
            return @unserialize($serialized);
        } else if (!preg_match('/(^|;|{|})O:[0-9]+:"/', $serialized)) {
            // in case we did have a string with O: in it,
            // but it was not a true serialized object
            return @unserialize($serialized);
        }
    }
    return false;
}
?>

Will simply return false if the serialized input contains an object or is not valid.

Example of a successful use of the object reviving threat : http://www.suspekt.org/2009/12/09/advisory-032009-piwik-cookie-unserialize-vulnerability/
frank at interactinet dot com 30-Aug-2011 09:32
When dealing with sessions, try session_decode($data) instead of unserialize($data).
walf 22-Aug-2011 08:22
a replacement for unserialize that returns whether it worked and populates the unserialized variable by reference:
<?php
function funserialize($serialized, &$into) {
    static $sfalse;
    if ($sfalse === null)
        $sfalse = serialize(false);
    $into = @unserialize($serialized);
    return $into !== false || rtrim($serialized) === $sfalse;//whitespace at end of serialized var is ignored by PHP
}

$s_foo = 'b:0;';
var_dump(funserialize($s_foo, $foo), $foo);

$s_bar = 'bar';
var_dump(funserialize($s_bar, $bar), $bar);

$s_foo = 'a:0:{};';
var_dump(funserialize($s_foo, $foo), $foo);

?>
gives:

bool(true)
bool(false)

bool(false)
bool(false)

bool(true)
array(0) {
}
MBa 02-Aug-2011 03:49
To check if a string is serialized:

$blSerialized=(@unserialize($sText)||$sText=='b:0;');
chris at colourlovers dot com 16-Jun-2011 05:31
Anyone having trouble serializing data with SimpleXMLElement objects stored within it, check this out:

This will traverse $data looking for any children which are instances of SimpleXMLElement, and will run ->asXML() on them, turning them into a string and making them serializable. Other data will be left alone.

<?php
function exportNestedSimpleXML($data) {
    if (is_scalar($data) === false) {
        foreach ($data as $k => $v) {
            if ($v instanceof SimpleXMLElement) {
                $v = str_replace("&#13;","\r",$v->asXML());
            } else {
                $v = exportNestedSimpleXML($v);
            }

            if (is_array($data)) {
                $data[$k] = $v;
            } else if (is_object($data)) {
                $data->$k = $v;
            }
        }
    }

    return $data;
}

$data = array (
    "baz" => array (
        "foo" => new stdClass(),
        "int" => 123,
        "str" => "asdf",
        "bar" => new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>'),
    )
);

var_dump($data);
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    object(SimpleXMLElement)#4 (1) {
      [0]=>
      string(3) "bar"
    }
  }
}*/

var_dump(exportNestedSimpleXML($data));
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    string(54) "<?xml version="1.0" encoding="UTF-8"?>
<foo>bar</foo>
"
  }
}
*/
?>
martijntje at martijnotto dot nl 09-Jun-2011 01:50
If you are storing serialized objects that persists between pageviews and you are using an autoloader, things may fall apart.

By default, when unserializing PHP will not call the autoloader when it discovers an unknown class. This can be fixed easily with the following directive in php.ini

unserialize_callback_func = 'spl_autoload_call'
i dot chiriac at yahoo dot com 01-May-2011 10:14
Hi,

I'm working with serialized objects stored on files and I've found a problem and his fix when you modify the serialized object subclassing. When you serialize a class with a private property, the subclassing of this private property will simply not work because each private property is attached to it's class level.

For example, you start to implement and serialize this class :

<?php
  class bar {
    private $var = 'bar value';
    public function getValue() {
      return $this->var;
    }
  }
?>

You store an instance of the bar class into a file as a serialized string.

After some code refactoring you prefer to store the value in a subclass like this :

<?php
  class foo {
    private $var = 'bar value';
    public function getValue() {
      return $this->var;
    }
  }
  class bar extends foo {
  }
?>

When you retrieve the stored bar instance from the srialized file, you have lose the $var value.

The only solution is to store private vars as protected properties and not private ones.

If you want to migrate/convert serialized private values as protected values you can use the following code :

<?php
    function setProtected($serialized, $vars) {
      if ($serialized[0] != 'O') {
        throw new Exception('The serialized string is not representing a class');
      }
      $size = '';
      for($i = 2; $i < strlen($serialized); $i++) {
        if ($serialized[$i] == ':') break;
        $size .= $serialized[$i];
      }
      $class = substr($serialized, $i + 2, $size);
      $find = array();
      $replace = array();
      foreach($vars as $name) {
        $from = chr(0).$class.chr(0).$name;
        $to = chr(0).'*'.chr(0).$name;
        $find[] = 's:'.strlen($from).':"'.$from.'";';
        $replace[] = 's:'.strlen($to).':"'.$to.'";';
      }
    return str_replace($find, $replace, $serialized);
  }
  // example of use
  $obj = unserialize(
    setProtected(
      file_get_contents('object.ser'),
      array('property1', 'propetyN')
    )
  );
?>

Hope this will helps someone,
aKhEnAtHoN
frank at interactinet dot com 28-Feb-2011 02:19
When using a custom session handler to store sessions in a database,  loss of session data is probably not from unserializing data.

It is common to use regenerate_session_id() when a user logs in to prevent session fixation.

It turns out regenerate_session_id() does not automatically update the database. You need to do this manually:

<?php
$old = session_id();
regenerate_session_id();
$new = session_id

$sql = "update session_table set session_id = '$new' where session_id = '$old'";

?>

Hope this saves you some time.
daniel at fourstaples dot com 23-Mar-2010 08:46
Here's a simple function to get the class of a serialized string (that is, the type of object that will be returned if it's unserialized):

<?php
function get_serial_class($serial) {
    $types = array('s' => 'string', 'a' => 'array', 'b' => 'bool', 'i' => 'int', 'd' => 'float', 'N;' => 'NULL');

    $parts = explode(':', $serial, 4);
    return isset($types[$parts[0]]) ? $types[$parts[0]] : trim($parts[2], '"');
}
?>

I use this when saving a serialized object to a cookie, to make sure it is the right type when I go to unserialize it.

The type names are the same format/case as you would see if you did a var_dump().
Fagzal 09-Mar-2010 10:10
To all who have problem with quoting and slashes when storing serialized data in MySQL: you are probably doing it wrong.

Use e.g. PDO with placeholders and the blob column type, and it will Just Work.
VladSavitsky 21-Oct-2009 09:57
To avoid data loss (problem with '\r\n') you can convert string to array and serialize an array.

Example:
<?php
//Store data:
$array = explode('\r\n', $string);
$serialized = serialize($array);

//Restore data:
$array = unserialize($serialized);
$text = implode('\r\n', $array);
?>
matty dot burke75 at gmail dot com 21-Sep-2009 03:18
I've been having horrendous problems getting my saved to mysql serialized data to unserialize. All I got back was false.

However, one handy tip saved the day.

<?php
//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));

//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));
?>
chaos 17-Sep-2009 07:15
The methods here for correcting string lengths in UTF-8 encoded serialized data weren't reliable for me; various of the data I had stored broke them.  This is the method that handled all of my cases:

<?php
$serialized = preg_replace_callback(
    '!(?<=^|;)s:(\d+)(?=:"(.*?)";(?:}|a:|s:|b:|d:|i:|o:|N;))!s',
    'serialize_fix_callback',
    $serialized
);

function serialize_fix_callback($match) {
    return 's:' . strlen($match[2]);
}
?>

[EDITOR thiago NOTE: This note has fixes from user "w33ble"]
TBag 17-Sep-2009 02:39
With regard to might_serialize(), might_unserialize()  - which I posted about a week ago on this page. I've found that empy arrays will be serialized, but not unserialized.  To patch...

in: is_serialized()
change: preg_match("/^(i|s|a|o|d):(.*);/si",$val)
to: preg_match("/^(i|s|a|o|d):(.*);/si",$val) !== false
arbie samong 10-Sep-2009 07:42
__PHP_Incomplete_Class Object Demystified

1. First take note of the output. A simple example:

__PHP_Incomplete_Class Object (
[__PHP_Incomplete_Class_Name] => SomeObject1
[obj1property1] => somevalue1 [obj1property2] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => SomeObject2 [obj2property1] => somevalue1 [obj2property2] => Array (
['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

2. We analyze this and break it down.
__PHP_Incomplete_Class Object tells you there is an object that needs to be declared somehow.
__PHP_Incomplete_Class_Name simply tells you the expected class name. It is just one of the properties for now.

So we have:
a) an unknown object that has a class name SomeObject1 (first class)
b) it has 2 properties, namely obj1property1 and obj2property2
c) obj2property2 is itself an object whose class name is SomeObject2 (the second class)
d) SomeObject2 has two properties, obj2property1 and obj2property2
e) obj2property2 is an array that contains two elements

3. Now that we have an idea of the structure, we shall create class definitions based from it. We will just create properties for now, methods are not required as a minimum.

<?php
class SomeObject1 {
        public $obj1property1;
        public $obj1property2;
}
class SomeObject2 {
        public $obj2property1;
        public $obj2property2;
}
?>

4. Have that accessible to your script and it will solve the __PHP_Incomplete_Class Object problem as far as the output is concerned. Now you will have:

SomeObject1 ( [obj1property1] => somevalue1 [obj1property2] => SomeObject2 ( [obj2property1] => somevalue1 [obj2property2] => Array ( ['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

As you will notice, __PHP_Incomplete_Class Object is gone and replaced by the class name. The property __PHP_Incomplete_Class_Name is also removed.

5. As for the array property obj2property2, we can directly access that and just assume that it is an array and loop through it:

<?php

// this will be SomeObject1
$data = unserialize($serialized_data);

// this will be SomeObject2
$data2 = $data->obj1property2();

foreach($data2->obj2property2 as $key => $value):
         print $key.' : '. $value .'<br>';
endforeach;

?>

Outputs:
key1 : somevalue3
key2 : somevalue4

That's it. You can add more methods on the class declarations for the given properties, provided you keep your original output as basis for the data types.
TBag 07-Sep-2009 12:46
My first post on php.net.  Hope someone finds it helpfull.  These few functions will serialize and unserialize arrays and objects.  It works recursively too.  I call them "might_..." because they test to see if any action is required.

<?php
function might_serialize($val){
    if(is_object($val)){
        $obj_keys = array_keys(get_object_vars($val));
        foreach($obj_keys as $k){ $val->$k = might_serialize($val->$k); }
        $val = serialize($val);
    }
    if(is_array($val)){
        foreach($val as &$v){ $v = might_serialize($v); }
        $val = serialize($val);
    }

    return $val;
}
function might_unserialized($val){
    //$pattern = "/.*\{(.*)\}/";
    if(is_serialized($val)){
        $ret = unserialize($val);
            foreach($ret as &$r){
                    $r = might_unserialized($r);
            }

            return $ret;
    }else { return $val; }
}
function is_serialized($val){
    if (!is_string($val)){ return false; }
    if (trim($val) == "") { return false; }
    //if (preg_match("/^(i|s|a|o|d)(.*);/si",$val)) { return true; }
    if (preg_match("/^(i|s|a|o|d):(.*);/si",$val) !== false) { return true; }
    return false;
}
?>
CEO at CarPool2Camp dot org 26-Apr-2009 09:12
Be aware that this function may not play nicely with SimpleXML

<?php // RAY_serialize.php
error_reporting(E_ALL);
echo "<pre>";

// SOME TEST DATA
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<books>
  <book>Book 1</book>
  <book>Book 2</book>
  <book>Book 3</book>
</books>';

// MAKE OBJECT
$obj = SimpleXML_Load_String($xml);

// HAVE A LOOK AT THE OBJECT
var_dump($obj);

// SERIALIZE THE OBJECT
$txt = serialize($obj);

// SHOW THE TEXT FORM OF THE SERIALIZED OBJECT
var_dump($txt);

// TRY TO RETURN IT TO OBJECT STATUS
$new = unserialize($txt); // Warning: unserialize() [function.unserialize]: Node no longer exists in /home/www/public_html/RAY_serialize.php on line 38
?>
w dot laurencine at teknoa dot net 07-Apr-2009 05:54
When dealing with a string which contain "\r", it seems that the length is not evaluated correctly. The following solves the problem for me :

<?php
// remove the \r caracters from the $unserialized string
$unserialized = str_replace("\r","",$unserialized);

// and then unserialize()
unserialize($unserialized);
?>
Gary 02-Apr-2009 05:49
Removing __PHP_Incomplete_Class Object

this code will remove the __PHP_Incomplete_Class Object error when trying to pull data from a text sql file you dont know the class name of. i am simply using the data to generate a report
i have looked for something like this so hopefully this example will help someone the basic php to call the function is

$session_data = base64_decode($YOURSERIALIZEDDATA);
       $decodedtext=unserializeUnknownObject($session_data);

if base64 encoded

or
       $decodedtext=unserializeUnknownObject($YOURSERIALIZEDDATA);

if simply serialized

include_once 'include\phperrorclass.php';
<?php
   class MyClass {}
   $object = unserialize($serializedData);
?>
include_once 'include\phperrorfunction.php';
<?php
   function unserializeUnknownObject($text)
   {
       $matches = Array();
       preg_match_all('/O:(\d)*:"([^":]*)":/', $text, $matches);
       foreach ($matches[2] as $class)
       {
       if (!class_exists($class, False)) {
                       eval('class '.$class.' { }');
                                            }
       }
       return unserialize($text);
   }
   $object = unserializeUnknownObject($serializedData);
?>
sample code

<?php
//declare the unknown object
include_once 'include\phperrorclass.php';
include_once 'include\phperrorfunction.php';
//declare the unserialize function
$abs_path = dirname(dirname(__FILE__));
include $abs_path.'\sunshop_reports\include\config.php';
// Connects to your Database
$connection=mysql_connect($servername, $dbusername, $dbpassword) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$sql_query=" SELECT * FROM `ss_orders_products` LIMIT 0 , 30";
$result=mysql_query($sql_query,$connection);
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
 $session_data = array();
   while($row=mysql_fetch_array($result))
   {
       $return[] = $row;
       echo("  OrderID - ");
       print_r($row[1]);
       echo("  Data Array - ");
       $pulledata=($row[4]);
       $session_data = base64_decode($row[4]);
       $decodedtext=unserializeUnknownObject($session_data);
       echo nl2br("\n");
       print_r($decodedtext);
       echo nl2br("\n");
       echo nl2br("\n");
   }

?>
John Smart 09-Feb-2009 04:35
I also had a problem unserializing UTF-8 TEXT data from mysql.  However, the problem isn't with the text as much as it is from the connection layer.  Make sure you are connecting to mysql with the default-character-set optional set to utf8. Otherwise, you'll get back a bunch of ???? characters for UTF-8 text.
Ariz JAcinto 07-Oct-2008 11:47
Here's another way of removing the  "__PHP_Incomplete_Class" notice especially if you're fetching the serialized object from a remote web service meaning, you don't have local copy of the class defining the object.

You can fix this by creating a class on the local machine that would define the object (*methods wouldn't be necessary).

Ex.

Object (Before):

object(__PHP_Incomplete_Class)#123 (3) {
  ["__PHP_Incomplete_Class_Name"]=>
    string(10) "SomeObject"
  ["property_one"]=>
    string(5) "Hello"
  ["property_two"]=>
    string(5) "World"
}

Class:

class SomeObject{

 public $property_one;
 public $property_two;

}

Object (After):

object(SomeObject)#31 (2) {
  ["property_one"]=>
    string(5) "Hello"
  ["property_two"]=>
    string(5) "World"
}
ogjuiceloc at yahoo dot com 15-Sep-2008 10:32
Good time saving post by campbell at vertesi dot com on 24-May-2008 01:52 for how base64_encode is needed before storing as mySQL text.

The order of unserializing is reversed however as you need to call base64_decode before unserialize.  Example:

<?php
$unserialized_array = unserialize (base64_decode($serialized_array));
?>
chris AT cmbuckley DOT co DOT uk 14-Aug-2008 06:47
As mentioned in the notes, unserialize returns false in the event of an error and for boolean false. Here is the first solution mentioned, without using error handling:

<?php
function isSerialized($str) {
    return ($str == serialize(false) || @unserialize($str) !== false);
}

var_dump(isSerialized('s:6:"foobar";')); // bool(true)
var_dump(isSerialized('foobar'));        // bool(false)
var_dump(isSerialized('b:0;'));          // bool(true)
?>
chris at r3i dot it 27-Jul-2008 04:24
@ Igor for single quote trouble:

<?php
function mb_unserialize($serial_str) {
$out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
return unserialize($out);
}
?>

Unserialize with utf8 content get trouble and the code provided by the guy works fine.

Code isn't mine: thanks to http://www.lastfm.pl/user/TheMariner
pierre dot spring at liip dot ch 23-Jun-2008 05:18
props to steve at bluearena dot com and getmequick at gmail dot com

when using the regex proposed by steve at bluearena dot com when working with serialized objects that have been utf-8 encoded, i ran into a problem...

"\0" became 2 characters, instead of the zero ascii character.

the solution is pretty subtle:
<? php
# zero ascii "\0" becomes '\0'
$error = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $unserialized );
$works = preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $unserialized );
?>
campbell at vertesi dot com 24-May-2008 01:52
One thing to note - if you're storing your serialized string in a MySQL TEXT field, it will remove the {s and }s that make your string valid for unserialization.

I almost killed myself figuring this out - I'm sure it's basic but I had to post my solution - encode the serialized string in base 64.

$mood = array('angry','sad','happy');

$storable = base64_encode(serialize($mood));

then when you retrieve it from the database, you can access the string with

$mood=base64_decode(unserialize($storable));
dev at atshop3d dot com 13-Mar-2008 04:19
Thanks to Igor who helped provide the solution to this. Serialize is very strict when it comes to quotes, and I spent _days_ figuring out why MySQL/PostgreSQL/etc. and locally set serialized strings returned a blank array, testing with both double and single quotes to see which one works.

Changing literal single quotes to "&#039" (I'm using numeric reference since &rsquo; and &lsquo; are different) and double quotes to "&quot;" cures all problems, while changing only one at a time only remedies a few of them. I'm interested to hear if other people have different experiences.

For example, the following string works:

<?php
//--------------------------------------------
// Set the example value. It doesn't matter if the string is from
// a database query or locally set - the side-effects are the same.
$heightoptionslist = <<<HEIGHTEND
a:3:{s:37:"Hands/inches (eg. 13&#039; 2&quot;HH)";s:6:"option";s:25:"Inches only (eg.39&quot;)";s:6:"option";s:24:"Centimeters (eg. 153cms)";s:6:"option";}
HEIGHTEND;
//--------------------------------------------
// Change the serialized string back to an array.
$heightoptionslist = unserialize($heightoptionslist);
//--------------------------------------------
// Output the value in a format we can understand.
echo "<div><pre>\$heightoptionslist = [\n".print_r($heightoptionslist, true)."\n]</pre></div>";
?>

while a string containing literal quotes doesn't (in nearly all cases on this machine):

<?php
//--------------------------------------------
// Another example value,
// this time with escaped literal quotes
$heightoptionslist = <<<HEIGHTEND
a:3:{s:26:"Hands/inches (eg. 13\' 2\"HH)";s:6:"option";s:20:"Inches only (eg.39\")";s:6:"option";s:24:"Centimeters (eg. 153cms)";s:6:"option";}
HEIGHTEND;
//--------------------------------------------
// Change the serialized string back to an array.
$heightoptionslist = unserialize($heightoptionslist);
//--------------------------------------------
// And return a blank array for some fun.
echo "<div><pre>\$heightoptionslist = [\n".print_r($heightoptionslist, true)."\n]</pre></div>";
?>
rhm31 at cam dot ac dot uk 29-Jan-2008 05:44
Problem: I needed a way to call an object that I did not know the name of. This forced me to use a variable for the class name.

Solution: unserialize();

GACK! This is imaginative, but horrid.

Firstly, I thought this would work:
$object=new $class_name();

Otherwise, something like below will work:
$object=eval("new $class_name()");

You can use a normal constructor this way too.
jsa1971 at gmail dot com 14-Sep-2007 07:41
Ignore all the advice to implement __autoload-ers or magical handlers, to solve problems when retrieving class instances from sessions.  It leads to terrible debugging nightmares.

After fussing with all sorts of such solutions and getting nowhere, I've found a very simple solution that works correctly and explicitly:

$_SESSION['myInstance'] = serialize($myInstance);

....

$myInstance_s = @$SESSION['myInstance']
if (!is_null($myInstance_s)) {
    $myInstance = unserialize($myInstance_s);
}

In other words, serialize the thing as a string, and put it in the session in this state - you regain control of the unserialization process and can code to handle exception cases rather than praying php's black magic does the right thing (and being sorely disappointed when it doesn't).
cory at lavacube dot com 02-Sep-2007 06:45
Problem: I needed a way to call an object that I did not know the name of. This forced me to use a variable for the class name.

Solution: unserialize();

Unserialize supports opening objects/classes from a serialized string. In order to do so I had to do something to this effect:

<?php

// this is the variable part
$class_name = 'Some_Obscure_Class';

// here is where we take the name and dynamically create a serialize-compliant string.
$quickload = 'O:' . strlen($class_name) . ':"' .$class_name. '":0:{}';

// and here we inject the string into unserialize, this creating an object! :-)
$object = unserialize($quickload);

?>

From here I used the __wakeup() magic function to initialize/construct the class as needed. :-)
deminy at deminy dot net 08-Aug-2007 09:46
Reply to eoin's post:

The regular expression you used to unserialize a PHP session file won't work if the session file contains string variable which contains character "|".

As I can see now, there is no any regular expression that can easily split data in a PHP session file. To read data from a session file, we may have to write a function to read content from the file, and then parse the content.

(This reply was also posted at http://www.php.net/manual/en/function.serialize.php to reply Erudd's post)
skinnepa at hotmail dot com 26-Jun-2007 10:42
props to steve at bluearena dot com and getmequick at gmail dot com

Here's my implementation :p

function mb_unserialize($serial_str) {
    $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
    return unserialize($out);
}

Works great for serialized UTF-8 content that doesn't like to be unserialized!
steve at bluearena dot com 15-Jun-2007 05:18
To getmequick at gmail dot com

Your outstanding preg_replace

<? php
$unserialized = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $unserialized );
?>

helped me out of a hole after converting a database from latin1 to UTF8 and forgetting about how strict the strlen of serialized strings needs to be!

I just added the s modifier for it to be able to support whitespace and it fixed everything.

Thanks a million.
Ates Goral 04-May-2007 11:02
If instead of using JSON, you'd like to stick with PHP-style serialization, here's some JavaScript code I posted at http://magnetiq.com for serializing JavaScript objects in PHP fashion:

/* Returns the class name of the argument or undefined if
   it's not a valid JavaScript object.
*/
function getObjectClass(obj)
{
    if (obj && obj.constructor && obj.constructor.toString)
    {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2)
        {
            return arr[1];
        }
    }

    return undefined;
}

/* Serializes the given argument, PHP-style.

   The type mapping is as follows:

   JavaScript Type    PHP Type
   ---------------    --------
   Number             Integer or Decimal
   String             String
   Boolean            Boolean
   Array              Array
   Object             Object
   undefined          Null

   The special JavaScript object null also becomes PHP Null.
   This function may not handle associative arrays or array
   objects with additional properties well.
*/
function phpSerialize(val)
{
    switch (typeof(val))
    {
    case "number":
        return (Math.floor(val) == val ? "i" : "d") + ":" +
            val + ";";
    case "string":
        return "s:" + val.length + ":\"" + val + "\";";
    case "boolean":
        return "b:" + (val ? "1" : "0") + ";";
    case "object":
        if (val == null)
        {
            return "N;";
        }
        else if ("length" in val)
        {
            var idxobj = { idx: -1 };

            return "a:" + val.length + ":{" + val.map(
                function (item)
                {
                    this.idx++;

                    var ser = phpSerialize(item);

                    return ser ?
                        phpSerialize(this.idx) + ser :
                        false;
                }, idxobj).filter(
                function (item)
                {
                    return item;
                }).join("") + "}";
        }
        else
        {
            var class_name = getObjectClass(val);

            if (class_name == undefined)
            {
                return false;
            }

            var props = new Array();

            for (var prop in val)
            {
                var ser = phpSerialize(val[prop]);

                if (ser)
                {
                    props.push(phpSerialize(prop) + ser);
                }
            }
            return "O:" + class_name.length + ":\"" +
                class_name + "\":" + props.length + ":{" +
                props.join("") + "}";
        }
    case "undefined":
        return "N;";
    }

    return false;
}

On the client side, you can pass in a complex (nested) JavaScript object to the phpSerialize function to get a PHP-style serialized representation. This string can be posted back and directly passed to the unserialize function to yield a representation of the complex object in PHP realm. Use of this technique requires caution on security matters.
me at no-spam dot com 10-Apr-2007 08:49
A note to the last person. To avoid the incomplete class notice, all you need to do is make sure you include the class definition before session_start(); is called. Simple as that.
Elise van Looij 07-Apr-2007 02:15
Thank you, thank you, thank you to Chris Hayes for

$_SESSION['my_object'] = unserialize(serialize($_SESSION['my_object']))

I wrestled through several very learned articles that dealt with creating factory classes for serializing objects and including the entire class definition in each and every file, yet one single line was all it took to stop my drupal module from whining about __PHP_Incomplete_Class when I tried to use load an instance from a session.
BenBE at omorphia dot de 02-Mar-2007 06:20
When trying to serialize or unserialize recursive arrays or otherwise linked data you might find the undocumented R data type quite useful.

If you want a array like the one produced with
<?
$a = array();
$a[0] =& $a;
?>
serialized you can store it using a string simular to this one:
<?
$a = unserialize("a:1:{i:0;R:1;}");
?>

Both sources will make $a hold an array that self-references itself in index 0.

The argument for R is the index of the created sub-variable of the serialize-string beginning with 1.
julabz at laposte dot net 26-Feb-2007 08:07
I couldn't get it with all these solutions, but it worked for me by mixing some of them this way:
<?php

function __serialize($object) {
    $serialized = serialize($object);
       return htmlentities($serialized,ENT_QUOTES);
}
//
function __unserialize($string) {
    $unserialized = stripslashes($string);
       $unserialized = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $unserialized );
       return unserialize($unserialized);
}

?>
Angel from 4hoursgift.com 22-Feb-2007 09:16
To Igor Defaye:

Thanks a lot. It worked to me.

unserialize() parameter ends when it first find a ' character, so if there is any it truncates the data and it does work properly.

(tested with PHP 4.4.1)
fuzzywoodlandcreatureSPAM at SUCKSgmail dot com 21-Feb-2007 08:59
To Igor Defaye:
unserialize() works fine with anything I've thrown at it, single quotes included.  My guess is you're running into problems created by Magic Quotes.
Igor Defaye 16-Feb-2007 08:08
It took me a good hour to figure out why serialized data stored in mysql database would not unserialize.
This is what I was trying to unserialize :
a:4:{i:0;s:43:"Date_Format(dateEntree,'%Y%m%d')";}

Addslashes did not work for me, I had to use :
str_replace("'", "\'", $serializedData)
in order to replace only sigle quotes and not double quotes, so I obtained this :
a:4:{i:0;s:43:"Date_Format(dateEntree,\'%Y%m%d\')";}

unserialize does not like single quotes.
Hope it can help someome.
double at dumpit dot com 19-Dec-2006 05:09
This little function will check whether the serialized string is well formed.

PHP < 6 because i'd heard changes will be made in this php-intern function,
maybe it could be edited easy for it.

<?php

function wd_check_serialization( $string, &$errmsg )
{

    $str = 's';
    $array = 'a';
    $integer = 'i';
    $any = '[^}]*?';
    $count = '\d+';
    $content = '"(?:\\\";|.)*?";';
    $open_tag = '\{';
    $close_tag = '\}';
    $parameter = "($str|$array|$integer|$any):($count)" . "(?:[:]($open_tag|$content)|[;])";
    $preg = "/$parameter|($close_tag)/";
    if( !preg_match_all( $preg, $string, $matches ) )
    {
        $errmsg = 'not a serialized string';
        return false;
    }
    $open_arrays = 0;
    foreach( $matches[1] AS $key => $value )
    {
        if( !empty( $value ) && ( $value != $array xor $value != $str xor $value != $integer ) )
        {
            $errmsg = 'undefined datatype';
            return false;
        }
        if( $value == $array )
        {
            $open_arrays++;
            if( $matches[3][$key] != '{' )
            {
                $errmsg = 'open tag expected';
                return false;
            }
        }
        if( $value == '' )
        {
            if( $matches[4][$key] != '}' )
            {
                $errmsg = 'close tag expected';
                return false;
            }
            $open_arrays--;
        }
        if( $value == $str )
        {
            $aVar = ltrim( $matches[3][$key], '"' );
            $aVar = rtrim( $aVar, '";' );
            if( strlen( $aVar ) != $matches[2][$key] )
            {
                $errmsg = 'stringlen for string not match';
                return false;
            }
        }
        if( $value == $integer )
        {
            if( !empty( $matches[3][$key] ) )
            {
                $errmsg = 'unexpected data';
                return false;
            }
            if( !is_integer( (int)$matches[2][$key] ) )
            {
                $errmsg = 'integer expected';
                return false;
            }
        }
    }
    if( $open_arrays != 0 )
    {
        $errmsg = 'wrong setted arrays';
        return false;
    }
    return true;
}

?>
getmequick at gmail dot com 20-Nov-2006 03:22
for those who has error like "
error at offset .."

but doesn't know why.

This function might be usefull

<?php

$sObject3 = 'a:2:{i:0;s:1:"1";i:1;s:3654:"1a1dc91c907325c69271ddf0c944bc72";}';

print_r( __unserialize($sObject3  ));

function __unserialize($sObject) {

    $__ret =preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $sObject );

    return unserialize($__ret);

}

?>
eakolb at dygel dot nizzet 02-Nov-2006 08:10
Apparently, unserialize is really picky about anyone messing with the serial string. Just spent an hour debugging why unserialize wasn't working on a serial string stored in a database where, per client requirement, all inserted data is strtoupper'd. Can't just strtolower on a serial string, though -- if there are null values in there (signified as N;), they must be upper case.

The following call may be a bit convoluted, but it works.

unserialize(preg_replace('/;n;/', ';N;', strtolower($serial)))

Of course, if you have string data within that array, that'll get clobbered by the strtolower. In my case, I was dealing with integer values (aside from the key names). But this might save someone else out there a little trouble.
Are Pedersen 09-Aug-2006 01:46
Be aware that if useing serialize/unserialize in a serverfarm with both 32bit and 64bit servers you can get unexpected results.

Ex: if you serialize an integer with value of 2147483648 on a 64bit system and then unserialize it on a 32bit system you will get the value -2147483648 instead. This is because an integer on 32bit cannot be above 2147483647 so it wraps.
chad 0x40 herballure 0x2e com 05-May-2006 09:08
When unserializing in PHP5 (behavior observed with 5.1.2), __autoload() will be checked first, and unserialize_callback_func called only if __autoload failed to load the class definition.
fhummel at hotmail dot com 01-Mar-2006 09:37
I have noticed that using the eval function as described in other posts might produce class redefinitions if separate class files are used and included.

My solution was to include_once at the top all .php files with classes that will be used on a particular page. This way the class definition exists when unserialize is called and you get the no duplicate check for free by using include_once.

Maybe someone can chime in on how this might affect performance.
onuryerlikaya at hotmail dot com 09-Feb-2006 04:00
<?php

// Create your array()
$array = array("First","Second","Third");
// Create your package
$package = serialize($array);

// You can print your serialized package
// a:3:{i:0;s:5:"First";i:1;s:6:"Second";i:2;s:5:"Third";}
print $package."<br>";

// Unserialize your serialized package with print_r or var_dump
$data    = unserialize($package);
print_r($data);
// var_dump($data); // It's same as print_r
// Array ( [0] => First [1] => Second [2] => Third )
?>
Jules 29-Jan-2006 08:49
"Moreover, you must be *very* careful when using eval() as it can be easily used to do something nasty."

Actually, you should probably be equally careful with unserialize, as using it might result in code from your (or standard PHP) classes being executed when you aren't expecting it.  It's clearly harder to exploit, but the possibility is there.  Therefore, only unserialize data that you know you generated yourself (either because it's stored where you put it, or because its signed, or has been validated in some other way).
mina86 at projektcode dot org 19-Jan-2006 10:28
Accualy artistan's function does not work (there should be $serialized_data instead of $text in function body). Moreover, you must be *very* careful when using eval() as it can be easily used to do something nasty. Here comes what I've made basing on the two available versions:

<?php
function unserialize_data($str, $objs = true) {
    if ($objs && preg_match_all('/O:\d+:"([a-zA-Z0-9_]+)":/', $str, $arr)) {
        $callback = ini_get('unserialize_callback_func');
        foreach ($arr[1] as $cls) {
            if (!class_exists($cls)) {
                call_user_func($callback, $cls);
            }
            if (!class_exists($cls)) {
                eval('class ' . $cls . ' { }');
            }
        }
    }
    return unserialize($str);
}
?>

However, better (not tested though) sollution seems to be:

<?php
function declare_empty_class($classname) {
    static $callback = null;
    if ($callback===null) {
        $callback = $classname;
        return;
    }
    if ($callback) {
        call_user_func($callback, $classname);
    }
    if (!class_exists($classname)) {
        eval('class ' . $classname . ' { }');
    }
}
declare_empty_class(ini_get('unserialize_callback_func'));
ini_set('unserialize_callback_func', 'declare_empty_class');
?>
artistan at cableone dot net 11-Jan-2006 08:46
// thanks to user comments I created this

    /**
        UnSerialize and return data
        @param string [$serialized_data] data to unserialize
        @return mixed
    */
    function unserialize_data($serialized_data,$objects=true){
        if($objects){
            // thanks to comment from veg@rd.no 04-Jan-2006 10:34 at http://us2.php.net/manual/en/function.unserialize.php
            // make classes for those that do not exist
            $matches = Array();
            preg_match_all('/O:(\d)*:"([^":]*)":/', $text, $matches);
            foreach ($matches[2] as $class)
            {
                if(!class_exists($class))
                    eval('class '.$class.' { }');
            }
        }
         return unserialize($serialized_data);
    }

// if using php5 you may want to modify to use __autoload function.
veg at rd dot no 04-Jan-2006 10:34
Unserializing an object of a class that hasn't been declared where it is being unserialized will result in an unusable object. I do not know why this happens, but I know of two workarounds which I've written about here; http://vega.rd.no/entry/200601_serializing_objects_in_php

In short, the solution is to declare the class before unserializing the object; so this code will do when unserializing an object of type MyClass;

<?php
    class MyClass {}
    $object = unserialize($serializedData);
?>

However, if you have several different classes, which you don't necessarily know the names of beforehand, use this short function to handle it for you;

<?php
    function unserializeUnknownObject($text)
    {
        $matches = Array();
        preg_match_all('/O:(\d)*:"([^":]*)":/', $text, $matches);
        foreach ($matches[2] as $class)
        {
            eval('class '.$class.' { }');
        }
        return unserialize($text);
    }
    $object = unserializeUnknownObject($serializedData);
?>

This could also have been accomplished by using unserialize_callback_func.
tarwin at gmail dot com 18-Dec-2005 05:30
I screwed around with this for hours and hours and it was doing my head in. Hopefully this can help.

When I was loading my page which was unserializing a string it would just hang (not finish sending information to the browser) at random places if I had not put the Class information first.

This is probably obvious (I know it says that it "will not work" if I do not declare the classes first) but the strange error of randomly stopping putting data to the page was very offputting from the actual error. It seems to go for a few KB or something and then just decide to stop.
none at none dot none 10-Dec-2005 07:57
The only complaint I have about serializing, is that it will not save the variable name.  To fix this, as well as add support for more then one variable/array, I chose to write this class:

 class SaveVar
 {
  function store($list)
  {
   $sl = explode("|", $list);
   for ($i = 0; $i < count($sl); $i++)
   {
    $varname    = $sl[$i];
    global $$varname;
    $thevar     = $$varname;
    $serialized = serialize($thevar);
    $saved[$i] = base64_encode($varname)."@".base64_encode($serialized);
   }
   $data = implode("|", $saved);
   return($data);
  }

  function restore($stored)
  {
   $sv = explode("|", $stored);
   for ($i = 0; $i < count($sv); $i++)
   {
    $svp   = $sv[$i];
    list($name64, $value64) = explode("@", $svp);
    $name  = base64_decode($name64);
    $value = base64_decode($value64);
    global $$name;
    $$name = unserialize($value);
   }
  }
 }

----

An example of using this class is as follows...

----

 $arr1 = array("Hello", "World");
 $arr2 = array("World", "Hello");

 $sv = new SaveVar;

 $saved = $sv->store("arr1|arr2");

 $arr1 = NULL;
 $arr2 = NULL;

 echo $saved;
 echo "<HR>";
 $sv->restore($saved);

 print_r($arr1);
 echo "<BR>";
 print_r($arr2);

----

I hope someone finds this useful...

   -Jestin S Larson
martin dot goldinger at netserver dot ch 15-Aug-2005 04:48
When you use sessions, its very important to keep the sessiondata small, due to low performance with unserialize. Every class shoud extend from this class. The result will be, that no null Values are written to the sessiondata. It will increase performance.

<?
class BaseObject
{
    function __sleep()
    {
        $vars = (array)$this;
        foreach ($vars as $key => $val)
        {
            if (is_null($val))
            {
                unset($vars[$key]);
            }
        }
        return array_keys($vars);
    }
};
?>
ungu at terong dot com 05-Feb-2005 10:20
I got the same case as yabba at the dot hut with his post
>> caveat: stripslashes!!!

In my server configutation the magic_quotes_gpc is on therefore it will automatically escape ' (single-quote), " (double quote), \ (backslash) and NUL's with a backslash.
And the stripslashes is the workaround for my case as well.

Erwin
Chris Hayes (chris at hypersites dot com) 23-Oct-2004 09:27
In reply to the earlier post about having to include object definitions *before* using unserialize.  There is a workaround for this.

When an object is serialized, the first bit of the string is actually the name of the class.  When an unknown object is unserialized, this is maintained as a property.  So if you serialize it again, you get back the exact same string as if you'd serialized the original object.  Basically, to cut to the point...

If you use

$_SESSION['my_object'] = unserialize(serialize($_SESSION['my_object']))

then you get back an object of the correct type, even if the session had originally loaded it as an object of type stdClass.
hfuecks at phppatterns dot com 09-Sep-2004 04:14
If you are accepting a serialized string from an untrusted source (e.g. generated in Javascript), you need to be careful to check that it doesn't result in "unexpected" objects being created when you unserialize it.

The following function pulls out the class names of all objects in a _valid_ serialized string. It works by first removing an serialized string values (which might contain serialized object syntax) then pulling out the class names from the remaining string. The returned value is a unique list of class names which the serialized string contains.

Note it assumes the serialized string is valid (that it will be accepted by unserialize()). There may be invalid serialized strings that could trick this function but these should fail when unserialized.

<?php
function getSerializedClassNames($string) {

    // Stip any string representations (which might contain object syntax)
    $string = preg_replace('/s:[0-9]+:".*"/Us','',$string);

    // Pull out the class named
    preg_match_all('/O:[0-9]+:"(.*)"/U', $string, $matches, PREG_PATTERN_ORDER);

    // Make sure names are unique (same object serialized twice)
    return array_unique($matches[1]);

}
?>

Unit tests for a version of this function can be found at:

http://cvs.sourceforge.net/viewcvs.py/xmlrpccom
    /scriptserver/tests/php/classparser.test.php?view=auto

See also the discussion here;
http://marc.theaimsgroup.com/?t=109439858700006&r=1&w=2
http://marc.theaimsgroup.com/?l=php-dev&m=109444959007776&w=2
pfister at avenir dot de 02-Sep-2004 02:25
Having had a problem with an mysql-stored serialized array which I had edited I found out that unserialize seems to have got a problem with "\r" within the string I wanted to unserialize.

It simply quits it's job with "false".

To work arround this problem I just replaced \r with "":

<?php
$serializedArray = 'a:1:{i:0;a:2:{s:4:"name";s:70:"Here comes the newline\r\nthis is the new line";s:5:"value";d:2.20;}}';

var_dump(unserialize($serializedArray)); //This just outputs bool(false)

$serializedArray = str_replace("\r", "", $serializedArray);

var_dump(unserialize($serializedArray)); //This outputs the array structure
?>
eoin at joy dot ucc dot ie 17-Aug-2004 11:38
I recently found myself in need of unserializing PHP session data (stored in a database) that had expired but was not yet deleted i.e. I needed to get at the contents of the session but was unable to use the usual PHP interface. The following function takes a string of serialized session data and returns an array of PHP values. The structure of the returned array is the same as the $_SESSION array if you were using the normal interface. I haven't tested this extensively but it did the job for me.

<?php
function unserialize_session_data( $serialized_string ) {
    $variables = array(  );
    $a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
    for( $i = 0; $i < count( $a ); $i = $i+2 ) {
        $variables[$a[$i]] = unserialize( $a[$i+1] );
    }
    return( $variables );
}
?>
yonman at gamer dot co dot il 30-May-2004 09:29
yabba at the dot hut:

The cookie mechanism for the webserver adds the slashes automatically. instead of just dumping strings into the cookie, make sure you base64_encode them first - to protect the cookie's content from escape characters.

Of course, this means that when retrieving the cookie, you'll need to base64_decode the string.
13-Mar-2004 10:42
If a a string is unserializeable FALSE is returned as well as an E_NOTICE error. This is odd since you may want to know if a given string converts back to a PHP value and act accordingly. If you run your script with E_ALL reporting this will show up.

I noticed this debugging this line of code:
$b = unserialize(base64_decode($a));

Curiously, base64_decode() does not throw errors if the string can't be decoded. The only workaround is to prepend the @ operator to unserialize() or to change the error level.
yabba at the dot hut 28-Jan-2004 01:09
caveat: stripslashes!!!

if using
       setcookie('hubba',serialize($data));
to set a cookie, you might want to check
       $data(unserialize(stripslashes($_COOKIE['hubba']));
to retrieve them back!!!

this is, if unserialize fails. you can also print_r($_COOKIE) to look into what you've got back.

beats me how the slashes got there in the first place....
Terry Johnson 09-Dec-2003 05:27
It is possible to make a neat autoloader for class definitions using this, but there are some gotchas for the unwary programmer:

1) If you are setting the unserialize_callback_func directive in the ini or .htaccess file, use auto_prepend_file to load the definition of your callback function - otherwise objects that stay in the session may trigger errors on pages where you didn't expect the object to be used.

2) It helps if you define all your classes in files with lowercase file names from the beginning.  The callback function is always call with the class name in lower case, and it is a lot quicker to use that directly than make a lookup table:

function callback_func($classname) {
    @include_once("${classname}.class.php");
}

3) It does not appear to be possible to use a static member fuction of a class (for example, a your object persistence layer) as the unserialize callback function, so this will cause confusion:

php_value auto_prepend_file "Persist.php"
php_value unserialize_callback_func Persist::factory

The next best solution is to make it a function in the global scope and have your object factory call it as required:

Class Persist
{
    function &factory($type) {
        callback_func(strtolower($type));
        $classname = "${type}";
        if (!class_exists($classname)) {
            return PEAR::raiseError('Class Not Found',PERSIST_ERROR_CLASS_NOT_FOUND,PEAR_ERROR_RETURN);
        }
        @$obj =& new $classname;
        return $obj;
    }
...
}
aderyn at nowhere dot tld 30-Oct-2003 10:02
A quick note:
If you store a serialized object in a session, you have to include the class _before_ you initialize (session_start()) the session.
strval
unset
Функции для работы с переменными


Удаляет переменную

unserialize
var_dump
Функции для работы с переменными
PHP Manual

unset

(PHP 4, PHP 5)

unset — Удаляет переменную

Описание

void unset ( mixed $var [, mixed $... ] )

unset() удаляет перечисленные переменные.

Поведение unset() внутри пользовательской функции может отличаться, в зависимости от того, какой тип имеет переменная, которую необходимо удалить.

Если переменная, объявленная глобальной, удаляется внутри функции, то будет удалена только локальная переменная. Переменная в области видимости вызова функции сохранит то же значение, что и до вызова unset().

<?php
function destroy_foo()
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

Результат выполнения данного примера:

bar

Если необходимо удалить глобальную переменную внутри функции, то для этого нужно использовать массив $GLOBALS:

<?php
function foo()
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>

Если переменная, которая передается ПО ССЫЛКЕ, удаляется внутри функции, то будет удалена только локальная пременная. Переменная в области видимости вызова функции сохранит то же значение, что и до вызова unset().

<?php
function foo(&$bar)
{
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

Результат выполнения данного примера:

something
something

Если статическая переменная удаляется внутри функции, unset() удалит переменную только в контексте дальнейшего выполнения функции. При последующем вызове предыдущее значение переменной будет восстановлено.

<?php
function foo()
{
    static $bar;
    $bar++;
    echo "До удаления: $bar, ";
    unset($bar);
    $bar = 23;
    echo "После удаления: $bar\n";
}

foo();
foo();
foo();
?>

Результат выполнения данного примера:

До удаления: 1, После удаления: 23
До удаления: 2, После удаления: 23
До удаления: 3, После удаления: 23

Список параметров

var

Удаляемая переменная.

...

Другая переменная ...

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

Версия | Описание
4.0.1 | Добавлена поддержка нескольких аргументов.

Примеры

Пример #1 Пример использования unset()

<?php
// удаляем одну переменную
unset($foo);

// удаляем один элемент массива
unset($bar['quux']);

// удаляем несколько переменных
unset($foo1, $foo2, $foo3);
?>

Пример #2 Использование приведения типа (unset)

Приведение типа (unset) часто путают с функцией unset(). Приведение типа (unset) приводит только к значению NULL и было добавлено исключительно для полноты реализации. Оно не меняет значение приводимой переменной.

<?php
$name = 'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

Результат выполнения данного примера:

NULL
string(6) "Felipe"

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

Существует возможность удалить даже аттрибуты объекта, видимые в текущем контексте.

Замечание:

Начиная с PHP 5 невозможно удалить $this внутри метода объекта.

Замечание:

При использовании unset() на недоступных или необъявленных свойствах объекта, будет вызван встроенный метод объекта __unset(), если он определен.

Смотрите также

  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • empty() - Проверяет, пуста ли переменная
  • __unset()
  • array_splice() - Удаляет часть массива и заменяет её чем-нибудь ещё

User Contributed Notes

pfreilly at umd dot umich dot edu 29-Sep-2011 04:56
Despite much searching, I have not yet found an explanation as to how one can manually free resources from variables, not so much objects, in PHP.  I have also seen many comments regarding the merits and demerits of unset() versus setting a variable to null.  Thus, here are the results of some benchmarks performed comparing unset() of numerous variables to setting them to null (with regards to memory usage and processing time):

10 variables:
Unset:
Memory Usage: 296
Time Elapsed: 1.0013580322266E-5

Null set:
Memory Usage: 1736
Time Elapsed: 5.9604644775391E-6

50 variables:
Unset:
Memory Usage: 296
Time Elapsed: 3.6001205444336E-5

Null set:
Memory Usage: 8328
Time Elapsed: 3.2901763916016E-5

100 variables:
Unset:
Memory Usage: 296
Time Elapsed: 5.6982040405273E-5

Null set:
Memory Usage: 15928
Time Elapsed: 5.8174133300781E-5

1000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.00041294097900391

Null set:
Memory Usage: 168096
Time Elapsed: 0.00067591667175293

10000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.0042569637298584

Null set:
Memory Usage: 1650848
Time Elapsed: 0.0076930522918701

100000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.042603969573975

Null set:
Memory Usage: 16249080
Time Elapsed: 0.087724924087524

300000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.13177299499512

Null set:
Memory Usage: 49796320
Time Elapsed: 0.28617882728577

Perhaps my test code for the null set was flawed, but despite that possibility it is simple to see that unset() has minimal processing time impact, and no apparent memory usage impact (unless the values returned by memory_get_usage() are flawed).  If you truly care about the ~4 microseconds saved over <50 variables, more power to you.  Otherwise, use unset() to minimize script impact on your system.
Note: Tested on PHP 5.3.8 installed via RPM on Fedora 14
Metasansana 21-May-2011 09:19
A simple function to unset unwanted keys in an array:

<?php

        $a = array("A"=>1, "B"=>2, "C"=>"a");

        foreach($a as $key=>&$value){
            if(is_string($value){
              unset($a[$key]);
            }
         }

        print_r($a);

?>

This should print:  A=1 B=2.
edouard dot berge at gmail dot com 24-Sep-2010 09:09
Warning!

When unset from an array, if you unset all elements, the array is always set

$tab=array('A'=>1,'B'=>2);
unset($tab['A']);
unset($tab['B']);
echo isset($tab)." ".count($tab);

output: 1 0
Andreas 24-Sep-2010 05:51
You can not unset a numeric key of an array, if key is a string. See this example:

// Create a simple array with 3 different key types
$test[1] = array(
    10 => array('apples'),
    "20" => array('bananas'),
    '30' => array('peaches')
);
$test[2] = (array) json_decode(json_encode($test[1]));
$test[3] = (array) (object) $test[1];
// array form a stdClass object
$testClass = new stdClass();
$testClass->{10} =  array('apples');
$testClass->{"20"} =  array('bananas');
$test[4] = (array) $testClass[6];

echo "<pre>";
foreach($test as $testNum => $arr) {

    echo "\nTest: " . $testNum  . " \n";
    var_dump($arr);

    foreach($arr as $key => $fruit) {
        echo "key: " . $key . "\n";
        echo "key exists: ";
        var_dump(array_key_exists(strval($key), $arr));
        echo "typeof key is: " . gettype($key) . "\n";

        unset($arr[$key]);
    }
    var_dump($arr);
    echo "\n" . str_repeat("-", 80);
}
echo "</pre>";

And here is the output:

Test: 1
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 2
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
key: 30
key exists: bool(false)
typeof key is: string
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}

--------------------------------------------------------------
Test: 3
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 4
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}

--------------------------------------------------------------

Fix the problem with a rebuild of the array:
$oldArray = $array();
$array = array();
foreach($oldArray as $key => $item) {
    $array[intval($key)] = $item;
}
j dot vd dot merwe at enovision dot net 26-Aug-2010 05:08
A sample how to unset array elements from an array result coming from a mysql request. In this sample it is checking if a file exists and removes the row from the array if it not exists.

<?php
$db->set_query("select * from documents where document_in_user = 0"); //1
$documents = $db->result_to_array($db->get_result()); //1

foreach ($documents as $key => $row) { //2

    $file     = "uploads/".rawurldecode($row['document_name']);

    if ( file_exists ( $file ) == FALSE ) {
         unset($documents[$key]);  //3
    }
}

$documents = array_values($documents); // reindex the array (4)
?>

variables:
mysql table = documents,
array = $documents
array key (index) = $key
array row (record sort of speak) = $row

explanation:

1.
it gets the array from the table (mysql)

2.
foreach goes through the array $documents

3.
unset if record does not exist

4.
the array_values($documents) reindexes the $documents array, for otherwise you might end up in trouble when your  process will start expecting an array starting with key ($key) 0 (zero).
Anonymous 02-Jul-2010 07:20
further I realized that an object, when getting detroyed, does care about destroying variable in object space visibility but not those in local visibility, be aware of the found pattern:

<?php
class release_test{
  private $buffer;
  private $other_object;
  public function __construct(){
    $this->other_object=new other_object_class();
  }
  public function __destruct(){
    //note that you always have to unset class objects, in order to get the resources released
    unset($this->other_object);
  }
  public allocate_mem_A(){
    $this->buffer=file("/tmp/bigfile");
  }
  public allocate_mem_B(){
    $buffer=file("/tmp/bigfile");
  }
  public allocate_mem_C(){
    $buffer=file("/tmp/bigfile");
    unset($buffer);
  }
  public allocate_mem_D(){
    $this->other_buffer=file("/tmp/bigfile");
  }
}

//this does not lead to a resource problem
$A=new release_test();
$A->allocate_mem_A();
$A->__destruct();
unset($A);

//this DOES lead to a resource problem
$B=new release_test();
$B->allocate_mem_B();
$B->__destruct();
unset($B);

//this does not lead to a resource problem
$C=new release_test();
$C->allocate_mem_C();
$C->__destruct();
unset($C);

//this does not lead to a resource problem
$D=new release_test();
$D->allocate_mem_D();
$D->__destruct();
unset($D);
?>
alex at bartl dot net 30-Jun-2010 10:11
unset($class_object) does not release resources allocated by the object. If used in loops, which create and destroy objects, that might easily lead to a resource problem. Explicitly call the destructor to circumvent the problem.

<?php
//this causes a resource problem
for($f=0;$f<10000;$f++){
  $my_class_object=new my_class_name();
  unset($my_class_object);
}

//this releases the resources allocate by the object
for($f=0;$f<10000;$f++){
  $my_class_object=new my_class_name();
  $my_class_object->__destruct();
  unset($my_class_object);
}
?>
alexanderashleyboese at gmail dot com 21-Apr-2010 11:09
I have noticed that sometimes if you have a globally declared instantiation of a class, unsetting that instance does not always call destruct like you think it should.

For instance, something like this might actually call the destruct later than implied by the "unset":

<?php
class Data {

public function __destruct() {
echo "These are my last words...";
}

}

function main(){
$data = new Data;
one();
two();
}

function one ()
{
global $data;
echo "Running 1st";
unset($data);
}

function two()
{
echo "Running 2nd";
}

main();

//"Running 1stRunning 2ndThese are my last words..."
?>
phpmanual at kennel17 dot co dot uk 26-Feb-2010 08:55
Note that PHP 4 will generate a warning if you try to unset an array index that doesn't exist and whose parent doesn't exist.

Example:

<?php

  $foo = array();

  unset($foo['Bar']['Baz']);

?>

RESULT: "Notice:  Undefined index:  Bar"

On PHP5 no error is raised, which seems to me like the correct behaviour.

Note that using unset($foo['Bar']) in the above example does not generate a warning in either version.

(Tested on 4.4.9 and 5.2.4)
obsidianproject.co.uk 09-Sep-2009 06:41
A quick note on (unset) vs unset().

<?php
$a="test";
unset($a);
var_dump($a);
?>
will return

Notice: Undefined variable: a
NULL

<?php
$a="test";
var_dump((unset) $a);
?>
will return

NULL

When using unset() php will throw an E_NOTICE if you try and access the variable after it has been unset, (unset) won't.

This has been tested in PHP 5.3.0
David Sawyer, Metaface Development 23-Apr-2009 09:26
Here's a simple function to remove a variable from an HTTP Query String:

<?php

function unset_query_string_var($varname,$query_string) {
    $query_array = array();
    parse_str($query_string,$query_array);
    unset($query_array[$varname]);
    $query_string = http_build_query($query_array);
    return $query_string;
}

?>

----------------------------

Example Usage #1:
Let's say you want to remove the variable "fruit" from $page_url below...

<?php
$page_url = "http://www.example.com/script.php?fruit=apple&color=red";
$url_data = parse_url($page_url);
$query_string = unset_query_string_var("fruit",$url_data['query']);
$page_url_new = $url_data['scheme'].'://'.$url_data['host'].$url_data['path'];
if (!empty($query_string)) $page_url_new .= '?'.$query_string;
$page_url_new .= $url_data['fragment'];
print $page_url_new;
?>

Output:
http://www.example.com/script.php?color=red

----------------------------

Example Usage #2:
To remove the variable "q" from the query string of the current page, try something like...

<?php

$page_url = 'http://'.$_SERVER["SERVER_NAME"].$_SERVER['PHP_SELF'];
$query_string = unset_query_string_var("q",$_SERVER["QUERY_STRING"]);
if (!empty($query_string)) $page_url .= '?'.$query_string;

?>
macnimble at gmail dot com 26-Mar-2009 02:39
Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,
);

echo "<pre>Original Array:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
                                    "beets",
                                    "carrots");
echo "<pre>Array after key removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';
?>
lion_cat at mail ru 12-Nov-2008 02:22
about unset for arrays

if you unset the last array member
$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

after addition a new member by $ar[]=7,

you will get
$ar[0]==2
$ar[1]==7
$ar[3]==7,

So, unset has no effect to internal array counter!!!
thijs NOSPACE putman at gmail dot com 04-Nov-2008 05:17
"It is possible to unset even object properties visible in current context"

Although the note is clear, in my case it required a little example to grasp its full impact:

If your object uses overloaded properties (using the "__set()" magic method) and you unset one of your "real" properties, the "__set()" method will take over if you try to assign a value to this property again.
In most cases, the "__set()" method is very much limited in the properties it can set. In my case, I only allow "__set()" to change a limited, predefined, set of properties. Most of them through their "public" name instead of their actual name...

This generates a somewhat counter-intuitive situation: If you unset a variable, you expect its value to become "null", which remains true. You also expect to be able to set it again to another value.
In the example described above this is not the case: The "__get()" method is invoked and, in my case, doesn't allow the property to be set again!
molotster on google mail com 14-Oct-2008 05:50
unset() does just what it's name says - unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.

If you are doing $whatever = null; then you are rewriting variable's data. You might get memory freed / shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.
nox at oreigon dot de 05-Aug-2008 12:24
if you try to unset an object, please be careful about references.

Objects will only free their resources and trigger their __destruct method when *all* references are unsetted.
Even when they are *in* the object... sigh!

<?php

class A {
  function __destruct() {
    echo "cYa later!!\n";
  }
}

$a = new A();
$a -> a = $a;
#unset($a); # Just uncomment, and you'll see

echo "No Message ... hm, what now?\n";
unset($a -> a);
unset($a);

echo "Finally that thing is gone\n";

?>

Of course the object completely dies at the end of the script.
stacionari at gmail dot com 17-Mar-2008 01:41
Sometimes you need to assigne values to an array index in some loop (if, while, foreach etc.) but you wish to set starting index key to some number greater then zero (lets say 5). One idea how to do this is:

<?php
    $values = array(5, 10, 15, 100);  //array of values that we wish to add to our new array

    $myArray = array(4=>0);   //sets starting key to be 4 and assigns some value (lets say 0)
    unset($myArray[4]);   //delete this index key, but preserves further enumeration

    foreach($values as $value){
        $myArray[] = $value;   //asign values to our array
    }

    print_r($myArray);

/* Output:

Array ( [5] => 5 [6] => 10 [7] => 15 [8] => 100 )

*/

?>
pauljamescampbell at gmail dot com 15-Mar-2008 05:22
Here's my variation on the slightly dull unset method. It throws in a bit of 80's Stallone action spice into the mix. Enjoy!

<?php
/**
 * function rambo (first blood)
 *
 * Completely and utterly destroys everything, returning the kill count of victims
 *
 * @param    It don't matter, it’s Rambo baby
 * @return    Integer    Body count (but any less than 500 and it's not really worth mentioning)
 */
function rambo() {

    // Get the victims and initiate that body count status
    $victims = func_get_args();
    $body_count = 0;

    // Kill those damn punks
    foreach($victims as $victim) {
        if($death_and_suffering = @unset($victim)) {
            $body_count++;
        }
    }

    // How many kills did Rambo tally up on this mission?
    return($body_count);
}
?>
Kai Kunstmann 10-Mar-2008 05:09
Since unset() is a language construct, it cannot be passed anything other than a variable. It's sole purpose is to "unset" this variable, ie. to remove it from the current scope and destroy it's associated data. This is true especially for reference variables, where not the actual value is destroyed but the reference to that value. This is why you can't wrap 'unset()' in a user defined function: You would either unset a copy of the data if the parameter is passed by value, or you would just unset the reference variable within the functions scope if the parameter is passed by reference. There is no workaround for that, as you cannot pass 'scope' to a function in PHP. Such a function can only work for variables that exist in a common or global scope (compare 'unset($_GLOBALS[variable])').

I don't know how PHP handles garbage collection internally, but I guess this behavior can result in a huge memory leak: if a value variable goes out of scope with a second variable still holding a reference to the in-memory value, then unsetting that reference would still hold the value in memory but potentially unset the last reference to that in-memory data, hence: occupied memory that is rendered useless as you cannot reference it anymore.
levitating at gmail dot com 07-Jan-2008 04:19
>> shame, but it doesn't seem to pop the stack.

There is a simple solution to that. Delete the value, then use array_merge() on your array:

<?php $folders= array_merge($folders) ; ?>
Maresa 15-Oct-2007 05:41
Note that since unset() returns void, you can't do this:

isset($some_var) && unset($some_var);

You'll get: Parse error: syntax error, unexpected T_UNSET in ...

The reason is because it would parse as
<bool> && <void>;
which is not a valid PHP statement.

Thus, the only alternative is to actually use if statement.
gerry+phpnet at buzka dot com 19-Sep-2007 09:07
Quote from http://fr.php.net/session_unset

"Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal."

So basically don't do:
unset($_SESSION)

Instead do:
$_SESSION = array();
Hayley Watson 23-Aug-2007 09:02
In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don't exist....

Unsetting variables that don't exist, as in
<?php
unset($undefinedVariable);
?>
does not trigger an "Undefined variable" notice. But
<?php
unset($undefinedArray[$undefinedKey]);
?>
triggers two notices, because this code is for unsetting an element of an array; neither $undefinedArray nor $undefinedKey are themselves being unset, they're merely being used to locate what should be unset. After all, if they did exist, you'd still expect them to both be around afterwards. You would NOT want your entire array to disappear just because you unset() one of its elements!
Sinured 17-Jul-2007 09:08
The main difference between <?php unset($var);?> and <?php $var = null;?> is, that unset() will reset the state to $var to something like "not set at all".

<?php
// register_globals = Off
error_reporting(E_ALL);
echo $var; // Notice

$var = null;
echo $var; // Nothing

unset($var);
echo $var; // Notice
?>
chris at maedata dot com 18-Jun-2007 10:35
Regarding the 14-May-2007 note from anonymous:

As far as array elements go, unset() is really only useful for removing named keys. For numeric keys, you can use array_splice to "unset" the element.

<?php
$a = array(
    'foo' => array('a', 'b', 'c'),
    'bar' => array('d', 'e', 'f')
);

print_r($a);

array_splice($a['foo'], 1, 1);

print_r($a);

unset($a['foo']);

print_r($a);
?>
chad 0x40 herballure 0x2e com 31-May-2007 07:11
It is observed on PHP 5.1.6 that <?php unset($this); ?> inside of a method will remove the reference to $this in that method. $this isn't considered "special" as far as unset() is concerned.
14-May-2007 10:51
shame, but it doesn't seem to pop the stack.

Array( [1\=>1
         [2\=>2
         [3\=>3
)

then unset($array[2\)

results in:

Array( [1\=>1
         [3\=>3
)

not

Array( [1\=>1
         [2\=>3
)

Shame really
RQuadling at GMail dot com 28-Mar-2007 05:28
If you want to remove a value from an array, then there is no direct mechanism.

The following function uses the array_keys() function to find the key(s) of the value that you want to remove and then removes the elements for that key.

I've also given some examples and the output.

<?php
/**
  * array array_remove ( array input, mixed search_value [, bool strict] )
  **/
function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False) {
    $a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
    foreach($a_Keys as $s_Key) {
        unset($a_Input[$s_Key]);
    }
    return $a_Input;
}
?>

Beside scalar variables (integers, floats, strings, boolean), you can also use arrays as the values you want to remove.

<?php
// Results in array(8, 8.0, '8', '8.0')
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8));

// Results in array(8, 8.0, '8', '8.0', array('8'))
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8), True);
?>
09-Feb-2007 08:10
Just to confirm, USING UNSET CAN DESTROY AN ENTIRE ARRAY. I couldn't find reference to this anywhere so I decided to write this.

The difference between using unset and using $myarray=array(); to unset is that obviously the array will just be overwritten and will still exist.

<?php

$myarray=array("Hello","World");

echo $myarray[0].$myarray[1];

unset($myarray);
//$myarray=array();

echo $myarray[0].$myarray[1];

echo $myarray;
?>

Output with unset is:
<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Output with $myarray=array(); is:
?>

<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Array
?>
hessodreamy at gmail dot com 17-Jan-2007 03:51
To clarify what hugo dot dworak at gmail dot com said about unsetting things that aren't already set:

unsetting a non-existent key within an array does NOT throw an error.
<?
$array = array();

unset($array[2]);
//this does not throw an error

unset($array[$undefinedVar]);
//Throws an error because of the undefined variable, not because of a non-existent key.
?>
dibakar dot datta at gmail dot com 31-Mar-2006 11:31
Instead of using the unset function  for unregistering your session or other array values you can also do this samll feature and get this task done with just 1 line code.

Suppose, if you like to unregister your session store values.
You can use:

      $_SESSION = array();

Well this syntax saves lot's of time instead of unsetting each values.
hugo dot dworak at gmail dot com 26-Dec-2005 06:23
If one tries to unset a typical variable that does not exist, no errors, warning or noticies will occur. However, if one tries to unset a non-existent array or an array with non-existent key, this will result in a notice. For instance:

<?php
  $true = true;
  $array = array ();
  unset ($true, $undefinedVariable, $array [$undefinedKey], $undefinedArray [$undefinedKey]);
?>

The output is (PHP 5.0.5):

Notice: Undefined variable: undefinedKey
Notice: Undefined variable: undefinedKey
Notice: Undefined variable: undefinedArray
clark at everettsconsulting dot com 11-Sep-2005 12:50
In PHP 5.0.4, at least, one CAN unset array elements inside functions from arrays passed by reference to the function.
As implied by the manual, however, one can't unset the entire array by passing it by reference.

<?php
function remove_variable (&$variable)  // pass variable by reference
{
    unset($variable);
}

function remove_element (&$array, $key) // pass array by reference
{
    unset($array[$key]);
}

$scalar = 'Hello, there';
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

remove_variable($scalar); // try to unset the variable
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

$array = array('one' => 1, 'two' => 2, 'three' => 3);
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_variable($array); // try to unset the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_element($array, 'two'); // successfully remove an element from the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [three] => 3 )

?>
no at spam dot com 30-Aug-2005 03:22
In addition to what timo dot hummel at 4fb dot de said;

>For the curious: unset also frees memory of the variable used.
>
>It might be possible that the in-memory size of the PHP Interpreter isn't reduced, but your scripts won't touch the memory_limit boundary. Memory is reused if you declare new variables.

It might be worth adding that functions apparently don't free up memory on exit the same way unset does..
Maybe this is common knowledge, but although functions destroys variables on exit, it (apparently) doesn't help the memory.

So if you use huge variables inside functions, be sure to unset them if you can before returning from the function.

In my case, if I did not unset before return, then the script would use 20 MB more of memory than if I did unset.
This was tested with php 5.0.4 on apache 2 on windows xp, with no memory limit.

Before I did the test, I was under the impression that when you exit from functions, the memory used inside it would be cleared and reused. Maybe this should be made clear in the manual, for either unset() or in the chapter for functions.
tom at diacope dot com 04-Aug-2005 03:51
when working with $_SESSION or any other array like that and you want to delete part of the session array it's always worked for me to do:

$_SESSION['data'] = NULL;
unset($_SESSION['data']);
muhamad_zakaria at yahoo dot com 04-Jul-2005 07:08
We have experienced when we applied 'unset' to the overloaded properties (PHP5), consider the code below:
<?php
    class TheObj {
        public $RealVar1, $RealVar2, $RealVar3, $RealVar4;
        public $Var = array();

        function __set($var, $val) {
            $this->Var[$var] = $val;
        }
        function __get($var) {
            if(isset($this->Var[$var])) return $this->Var[$var];
            else return -1;
        }
    }

    $SomeObj = new TheObj;

    // here we set for real variables
    $SomeObj->RealVar1 = 'somevalue';
    $SomeObj->{'RealVar2'} = 'othervalue';
    $SomeObj->{'RealVar'.(3)} = 'othervaluetoo';
    $SomeObj->{'RealVar'.'4'} = 'anothervalue';

    // and here we set for virtual variables
    $SomeObj->Virtual1 = 'somevalue';
    $SomeObj->{'Virtual2'} = 'othervalue';
    $SomeObj->{'Virtual'.(3)} = 'othervaluetoo';
    $SomeObj->{'Virtual'.'4'} = 'anothervalue';

    // now we will try to unset these variables
    unset($SomeObj->RealVar1);
    unset($SomeObj->{'RealVar'.(3)});

    //the lines below will catch by '__get' magic method since these variables are unavailable anymore
    print $SomeObj->RealVar1."\n";
    print $SomeObj->{'RealVar'.(3)}."\n";

    // now we will try to unset these variables
    unset($SomeObj->Virtual1);
    unset($SomeObj->{'Virtual'.(3)});

    //but, these variables are still available??? eventhough they're "unset"-ed
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>

Please note that PHP doesn't have magic callback to unset overloaded properties. This is the reason why unset($SomeObj->Virtual1) doesn't work.

But it does work when we set 'null' value such as the following code:
<?php
    // now we will set 'null' value instead of using unset statement
    $SomeObj->Virtual1 = null;
    $SomeObj->{'Virtual'.(3)} = null;

    // and now these variables are no longer available
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>
Sound ugly, yeah?

This applied to the "virtual" array variable too, see more at http://bugs.php.net/bug.php?id=33513 (at feedback) about it.
PS: we used PHP version 5.1.0-dev from the CVS snapshot when we wrote the above codes.
franckraynal at free dot fr 26-Feb-2005 05:02
Here is another way to make 'unset' work with session variables from within a function :

<?php
function unsetSessionVariable ($sessionVariableName) {
   unset($GLOBALS[_SESSION][$sessionVariableName]);
}
?>

May it work with others than me...
F.
bedbin at gmail dot com 02-Feb-2005 06:33
usefull tip:
if you have session variables like these.
<?php
echo "<pre>";
$_SESSION["num"] = array(1,2,3,4);
var_dump($_SESSION);

echo "-<br>";
unset($_SESSION);
var_dump($_SESSION);
?>
gives out:

array(1) {
  ["num"]=>
  array(4) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
    [3]=>
    int(4)
  }
}
-
NULL

if you use empty instead unset you get same output as first var_dump($_SESSION) gives.
I hope help sb.
Nghia 05-Jan-2005 08:41
I saw this mentioned somewhere else but if you do

$var = NULL

then I've noticed less memory usuage than with unset(). In fact, unset didn't do anything.

This might be useful if you're doing a php-gtk app, thats starting to consume significant memory over a long period of time. This was the code I used to test

// Check memory before here

for($i = 0; $i < 100; $i++)
{
  $dialog = &new GtkDialog();
  $dialog->realize();
  $dialog->destroy();

  $dialog = NULL;
  //unset($dialog);
}

// Check memory after here

Doing a difference between after and before results in:

Using destroy() and unset() ->  ~31kb
Using $dialog = NULL -> ~13 kb

The expected memory usuage should be 0kb or around there.
harycary at netscape dot net 14-Dec-2004 09:56
If you ever have to unset all the variables of a class from within a funciton of that class use the following code:

<?php

class User
{

     function User_login ( ... )
     {...}

     function User_logout ( $greeting )
     {

          ...
          foreach ( array_keys ( get_object_vars ( &$this ) ) as $val)
          {    unset( $this->$val );    }
          $this->greeting = $greeting;
          ...

     }

}

?>
If anyone knows of a more effective way please post a reply.
mv at brasil dot com 08-Nov-2004 08:04
If you want to remove one element of Query String use this function, than place the returned values in <a href="script.php?'. remove_query("arg1") .'">

    function remove_query($key) {

        $arrquery = explode("&", $_SERVER["QUERY_STRING"]);

        foreach ($arrquery as $query_value) {

            $valor = substr($query_value, strpos($query_value, "=") + 1);
            $chave = substr($query_value, 0, strpos($query_value, "="));
            $querystring[$chave] = $valor;

        }

        unset($querystring[$key]);

        foreach ($querystring as $query_key => $query_value) {

            $query[] = "{$query_key}={$query_value}";

        }

        $query = implode("&", $query);

        return $query;

    }
dan AT --nospam-- cubeland DOT co DOT uk 04-Nov-2004 11:38
dh at argosign dot de -
it is possible to unset globals from within functions thanks to the $GLOBALS array:

<?php
$x = 10;

function test() {
    // don't need to do ' global $x; '
    unset ($GLOBALS['x']);
    echo 'x: ' . $GLOBALS['x'] . '<br />';
}

test();
echo "x: $x<br />";

// will result in
/*
x:
x:
*/
?>
timo dot hummel at 4fb dot de 07-Sep-2004 06:24
For the curious: unset also frees memory of the variable used.

It might be possible that the in-memory size of the PHP Interpreter isn't reduced, but your scripts won't touch the memory_limit boundary. Memory is reused if you declare new variables.
thorry at thorry dot net 05-Aug-2004 02:15
The documentation is not entirely clear when it comes to static variables. It says:

If a static variable is unset() inside of a function, unset() destroys the variable and all its references.

<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
}

foo();
foo();
foo();
?>

The above example would output:

1
2
3

And it does! But the variable is NOT deleted, that's why the value keeps on increasing, otherwise the output would be:

1
1
1

The references are destroyed within the function, this handeling is the same as with global variables, the difference is a static variable is a local variable.

Be carefull using unset and static values as the output may not be what you expect it to be. It appears to be impossible to destroy a static variable. You can only destroy the references within the current executing function, a successive static statement will restore the references.

The documentation would be better if it would say:
"If a static variable is unset() inside of a function, unset() destroys all references to the variable. "

Example: (tested PHP 4.3.7)
<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
   echo "$a\n";
   static $a;
   echo "$a\n";
}

foo();
foo();
foo();
?>

Would output:

1

1
2

2
3

3
anon at no spam dot no address dot com 16-Jul-2004 09:19
Adding on to what bond at noellebond dot com said, if you want to remove an index from the end of the array, if you use unset, the next index value will still be what it would have been.

Eg you have
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    unset($x[(count($x)-1)]); //remove last set key in the array

    $x[] = $i;
 }
?>

You would expect:
Array([0] => 1, [1] => 4)
as you want it to remove the last set key....

but you actually get
Array ( [0] => 1 [4] => 2 [5] => 3 [6] => 4 )

This is since even though the last key is removed, the auto indexing still keeps its previous value.

The only time where this would not seem right is when you remove a value off the end. I guess different people would want it different ways.

The way around this is to use array_pop() instead of unset() as array_pop() refreshes the autoindexing thing for the array.
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    array_pop($x); // removes the last item in the array

    $x[] = $i;
 }
?>

 This returns the expected value of x = Array([0] => 1, [1] => 4);

Hope this helps someone who may need this for some odd reason, I did.
bond at noellebond dot com 26-May-2004 02:34
Note that though global arrays will not be altered by a function, an array in an object WILL be altered if referenced within one of its methods.  For example:

  function remove_index ($i)
  {
    unset($this->test_array[$i]);
    $temp_array = array_values($this->test_array);
    $this->test_array = $temp_array;

  }

Will remove key $i from the object's array and reindex it.
andre at twg dot com dot au 06-Mar-2004 09:16
Only This works with register_globals being 'ON'.

unset( $_SESSION['variable'] );

The above will not work with register_globals turned on (will only work outside of a function).

$variable = $_SESSION['variable'];
unset( $_SESSION['variable'], $variable );

The above will work with register_globals on & inside a function
warhog at warhog dot net 27-Jan-2004 08:52
you may wan't to unset all variables which are defined, here's one way:

<?php

function unset_all_vars($a)
{ foreach($a as $key => $val)
  { unset($GLOBALS[$key]); }
  return serialize($a); }

unset_all_vars(get_defined_vars());

?>

you can also save than a serialized var of the "memory" and perhaps store this in a temporary file.. very usefull if you work with text files and/or file uploads when you've got very large variables.

greetz
kdechant at midwestarts dot com 23-Nov-2003 03:47
As of PHP version 4.3.3, unset() results in a parse error if it is used with the @ error suppression operator.

For example:

@unset($var); // parse error
unset(@$var); // parse error
unset($var); // okay
frank at agentbrand dot com 09-Nov-2003 09:59
Use array_values() after unset() to reindex your array.
 Note that unset() removes the index as a key, you will need to reindex your array again to get expected behavior
vmizuba at queens dot org 27-Oct-2003 07:25
for what it's worth...

in php 4.1, using unset to destroy a session variable, i.e. unset($_SESSION['variable']); destroys it by erasing variable information but leaves behind the variable name appended with a '!' in front of the name in the session file... leaving the session file larger and x bytes wasted depending on the variable name length
unserialize
var_dump
Функции для работы с переменными


Выводит информацию о переменной

unset
var_export
Функции для работы с переменными
PHP Manual

var_dump

(PHP 4, PHP 5)

var_dump — Выводит информацию о переменной

Описание

void var_dump ( mixed $expression [, mixed $... ] )

Функция отображает структурированную информацию об одном или нескольких выражениях, включая их тип и значение. Массивы и объекты анализируются рекурсивно с разным отступом у значений для визуального отображения структуры.

В PHP 5 все общедоступные, закрытые и защищенные свойства объекта будут возвращены при выводе.

Подсказка

Как и с любой другой функцией, осуществляющей вывод непосредственно в браузер, вы можете использовать функции контроля вывода, чтобы перехватывать выводимые этой функцией данные и сохранять их, например, в string.

Список параметров

expression

Переменная, значение которой необходимо отобразить.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования var_dump()

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

Результат выполнения данного примера:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

Результат выполнения данного примера:

float(3.1)
bool(true)

Смотрите также

  • var_export() - Выводит в браузер или возвращает интерпретируемое строковое представление переменной
  • print_r() - Выводит удобочитаемую информацию о переменной

User Contributed Notes

stlawson *AT* joyfulearthtech *DOT* com 10-Aug-2011 09:31
<?php
/**
 * Better GI than print_r or var_dump -- but, unlike var_dump, you can only dump one variable.
 * Added htmlentities on the var content before echo, so you see what is really there, and not the mark-up.
 *
 * Also, now the output is encased within a div block that sets the background color, font style, and left-justifies it
 * so it is not at the mercy of ambient styles.
 *
 * Inspired from:     PHP.net Contributions
 * Stolen from:       [highstrike at gmail dot com]
 * Modified by:       stlawson *AT* JoyfulEarthTech *DOT* com
 *
 * @param mixed $var  -- variable to dump
 * @param string $var_name  -- name of variable (optional) -- displayed in printout making it easier to sort out what variable is what in a complex output
 * @param string $indent -- used by internal recursive call (no known external value)
 * @param unknown_type $reference -- used by internal recursive call (no known external value)
 */
function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#666666;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    // So this is always visible and always left justified and readable
    echo "<div style='text-align:left; background-color:white; font: 100% monospace; color:black;'>";

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#666666'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#666666'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#666666'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color\"".htmlentities($avar)."\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> ".htmlentities($avar)."<br>";

        $var = $var[$keyvar];
    }

    echo "</div>";
}
?>
kobrasrealm at gmail dot com 23-Jun-2011 01:28
I wrote this dandy little function for using var_dump() on HTML documents so I don't have to view the source.

<?php
function htmldump($variable, $height="9em") {
echo "<pre style=\"border: 1px solid #000; height: {$height}; overflow: auto; margin: 0.5em;\">";
var_dump($variable);
echo "</pre>\n";
}
?>

You can pass arguments like this:
<?php
$sql = mysql_query("SELECT id, name, value FROM table WHERE cond = 'value'");
$s = mysql_fetch_assoc($sql);

// Dump variable containing the result of the MySQL query
var_dump($s);
?>

The second parameter lets you specify the height of the box. Default is 9em, but if you're expecting a huge output you'll probably want a higher value.

<?php
var_dump($s, "17em");
?>

Happy var_dumping.
flyfy1 at gmail dot com 22-Jun-2011 12:22
for output the var as string, include this function:
<?php
function var_dump_to_string($var){
    $output = "<pre>";
    _var_dump_to_string($var,$output);
    $output .= "</pre>";
    return $output;
}

function _var_dump_to_string($var,&$output,$prefix=""){
    foreach($var as $key=>$value){
        if(is_array($value)){
            $output.= $prefix.$key.": \n";
            _var_dump_to_string($value,$output,"  ".$prefix);
        } else{
            $output.= $prefix.$key.": ".$value."\n";
        }
    }
}
?>

 (say if you want to output $var to string $output)
<?
php $output = var_dump_to_string($var);
?>
divinity76 at gmail dot com 23-Apr-2011 06:53
a html-encoded var_dump

<?php
function htmlvardump(){ob_start(); $var = func_get_args(); call_user_func_array('var_dump', $var); echo htmentities(ob_get_clean());}
?>

(creds: ekneuss / mOo @ irc.freenode.net/#php )
andresa dot ms at gmail dot com 03-Sep-2010 12:56
I made this recursive version of var_dump to show array values into a HTML table.

<?php

#Recursive Funcition

function dump_table($var, $title=false, $level=0)
{
    if($level==0)
    {
        echo '<table width="400" border="0" cellspacing="1" cellpadding="3" class="dump">';

        if($title)
              echo '<tr>
                     <th align="center" colspan="2">'.$title.'</th>
                   </tr>';

        echo '
          <tr>
            <th align="right">VAR NAME</th>
            <th align="left">VALUE</th>
          </tr>';
    }
    else
    {
        echo '<tr>
                <td colspan="2">
                    <table width="100%" border="0" cellspacing="3" cellpadding="3" class="dump_b">
                </td>
              </tr>';
    }

    foreach($var as $i=>$value)
    {
        if(is_array($value) or is_object($value))
        {
            dump_table($value, false, ($level +1));
        }
        else
        {
                echo '<tr>
                        <td align="right" width="50%" >'.$i.'</th>
                        <td align="left" width="50%" >'.$value.'</th>
                       </tr>';
        }
    }
    echo '</table>';
}

#### HOW TO USE

$libertadores[0]='Palmeiras';
$libertadores[1]='Sao Paulo';
$libertadores[2]='Santos';

dump_table($libertadores, 'Libertadores - Brazilian Champions');

?>

CSS Styles: http://andresa.net/exemplos/dump_table.css
PHP LIVE DEMO:  http://andresa.net/exemplos/dump_table.php
geoff at spacevs dot com 07-Apr-2010 08:10
var_export does not return the same output as var_dump, if you want the var_dump output in a return you can wrap the call in ob_* functions.

<?PHP
  ob_start();
  var_dump($_SERVER);
  $dump = ob_get_clean();
?>
david at exposito dot mobi 07-Feb-2010 11:36
If you want to save exactly the content of an array into a variable to save ir later for example, use this:

<?php $xml = var_export($xml, true); ?>

You'll have in your same variable the content readable, instead of written down or anything else
ivolucien at gmail dot calm 06-Dec-2009 02:12
For the special case where you know that you are only dealing with arrays,
<?php string implode(string $glue, array $pieces) ?>
may be all that's necessary, and the $glue parameter can be used to insert placeholders if you need to do more complex formatting. Nested arrays and such are discussed on the implode() page.
www.phella.net 30-Jul-2009 10:56
Here is another var_dump() substitution for more compact and informative look. Everything prepared for clear output within HTML environment. Try it and you will love it.

<?php
function dump($value,$level=0)
{
  if ($level==-1)
  {
    $trans[' ']='&there4;';
    $trans["\t"]='&rArr;';
    $trans["\n"]='&para;;';
    $trans["\r"]='&lArr;';
    $trans["\0"]='&oplus;';
    return strtr(htmlspecialchars($value),$trans);
  }
  if ($level==0) echo '<pre>';
  $type= gettype($value);
  echo $type;
  if ($type=='string')
  {
    echo '('.strlen($value).')';
    $value= dump($value,-1);
  }
  elseif ($type=='boolean') $value= ($value?'true':'false');
  elseif ($type=='object')
  {
    $props= get_class_vars(get_class($value));
    echo '('.count($props).') <u>'.get_class($value).'</u>';
    foreach($props as $key=>$val)
    {
      echo "\n".str_repeat("\t",$level+1).$key.' => ';
      dump($value->$key,$level+1);
    }
    $value= '';
  }
  elseif ($type=='array')
  {
    echo '('.count($value).')';
    foreach($value as $key=>$val)
    {
      echo "\n".str_repeat("\t",$level+1).dump($key,-1).' => ';
      dump($val,$level+1);
    }
    $value= '';
  }
  echo " <b>$value</b>";
  if ($level==0) echo '</pre>';
}
?>
egorinsk at gmail com 02-Feb-2009 04:08
Note that var_dump reset()'s array internal pointer!
csaba at alum dot mit dot edu 25-Jun-2008 03:09
Note that var_dump does not do HTML escaping.  How does this affect you?  Well, if you have references to integers, then var_dump will output
&int(integerValue)

Now &int; translates into an integral sign, and since the browser may be inclined to overlook the missing semicolon, you may be seeing integrals where you were expecting &int
rich dot schu at gmail dot com 09-Apr-2008 05:56
Keep in mind if you have xdebug installed it will limit the var_dump() output of array elements and object properties to 3 levels deep.

To change the default, edit your xdebug.ini file and add the folllowing line:
xdebug.var_display_max_depth=n

More information here:
http://www.xdebug.org/docs/display
highstrike at gmail dot com 08-Jan-2008 05:33
made 2 nifty functions based of what some people contributed here. Hope you find them usefull

usage ... call for the dump function. EG: dump($array, "Array dump");

<?php
////////////////////////////////////////////////////////
// Function:         dump
// Inspired from:     PHP.net Contributions
// Description: Helps with php debugging

function dump(&$var, $info = FALSE)
{
    $scope = false;
    $prefix = 'unique';
    $suffix = 'value';

    if($scope) $vals = $scope;
    else $vals = $GLOBALS;

    $old = $var;
    $var = $new = $prefix.rand().$suffix; $vname = FALSE;
    foreach($vals as $key => $val) if($val === $new) $vname = $key;
    $var = $old;

    echo "<pre style='margin: 0px 0px 10px 0px; display: block; background: white; color: black; font-family: Verdana; border: 1px solid #cccccc; padding: 5px; font-size: 10px; line-height: 13px;'>";
    if($info != FALSE) echo "<b style='color: red;'>$info:</b><br>";
    do_dump($var, '$'.$vname);
    echo "</pre>";
}

////////////////////////////////////////////////////////
// Function:         do_dump
// Inspired from:     PHP.net Contributions
// Description: Better GI than print_r or var_dump

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#eeeeee;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>";

        $var = $var[$keyvar];
    }
}
?>
vladimir at pixeltomorrow dot com 10-Sep-2007 12:45
You can also use the PEAR package available at http://pear.php.net/package/Var_Dump

which parses the variable content in a very pleasant manner, a lot more easier to "follow" than the built-in var_dump() function.

Of course there are many others, but I prefer this one, because it's simply to use.

Just add at the begining of your file:

<?php

require('Var_Dump.php'); // make sure the pear package path is set in php.ini
Var_Dump::displayInit(array('display_mode' => 'HTML4_Text'), array('mode' => 'normal','offset' => 4));
?>

then, instead of simply using var_dump($foo), use:

<?php

Var_Dump::display($foo);

?>

Read the documentation if you're looking for different output layouts.

Cheers!
Vladimir Ghetau
thriller dot ze at gmail dot com 21-Aug-2007 01:49
As Bryan said, it is possible to capture var_dump() output to a string. But it's not quite exact if the dumped variable contains HTML code.

You can use this instead:

<?php
echo '<pre>'; // This is for correct handling of newlines
ob_start();
var_dump($var);
$a=ob_get_contents();
ob_end_clean();
echo htmlspecialchars($a,ENT_QUOTES); // Escape every HTML special chars (especially > and < )
echo '</pre>';
?>
vendiddy at gmail dot com 20-Aug-2007 11:54
I made a function that I use instead of var_dump. It works well for hierarchical data. The trick is to used nested tables.

May not be the best code but it's not that long so you could improve/modify it. Don't think it will work if any self-referencing is involved.

<?php
function variable_to_html($variable) {
    if ($variable === true) {
        return 'true';
    } else if ($variable === false) {
        return 'false';
    } else if ($variable === null) {
        return 'null';
    } else if (is_array($variable)) {
        $html = "<table border=\"1\">\n";
        $html .= "<thead><tr><td><b>KEY</b></td><td><b>VALUE</b></td></tr></thead>\n";
        $html .= "<tbody>\n";
        foreach ($variable as $key => $value) {
            $value = variable_to_html($value);
            $html .= "<tr><td>$key</td><td>$value</td></tr>\n";
        }
        $html .= "</tbody>\n";
        $html .= "</table>";
        return $html;
    } else {
        return strval($variable);
    }
}
?>

Try it with this completely made-up data:
<?php
$meeting = array(
    'title' => 'Sales Meeting',
    'start_time' => array(
        'hours' => 11,
        'minutes' => 15,
        'ampm' => 'am'
    ),
    'end_time' => array(
        'hours' => 1,
        'minutes' => 30,
        'ampm' => 'pm'
    ),
    'attendees' => array(
        array('first_name' => 'Bob', 'last_name' => 'Smith', 'email' => 'bobsmith@email.com'),
        array('first_name' => 'James', 'last_name' => 'Andrews', 'email' => 'jamesandrews@email.com'),
        array('first_name' => 'Tom', 'last_name' => 'Schmoe', 'email' => 'bobsmith@email.com')
    )
);
echo variable_to_html($meeting);
?>
php at mikeboers dot com 28-Jun-2007 01:08
Howdy!

I am working on a pretty large project where I needed to dump a human readable form of whatever into the log files... and I thought var_export was too difficult to read. BigueNique at yahoo dot ca has a nice solution, although I needed to NOT modify whatever was being passed to dump.

So borrowing heavily from BigueNique's (just reworked his function) and someone's idea over in the object cloning page, I came up with the following function.

It makes a complete copy of whatever object you initially pass it, including all recursive definitions and outside objects references, then does the same thing as BigueNique's function. I also heavily reworked what it output, to suit my needs.

<?php

function var_log(&$varInput, $var_name='', $reference='', $method = '=', $sub = false) {

    static $output ;
    static $depth ;

    if ( $sub == false ) {
        $output = '' ;
        $depth = 0 ;
        $reference = $var_name ;
        $var = serialize( $varInput ) ;
        $var = unserialize( $var ) ;
    } else {
        ++$depth ;
        $var =& $varInput ;

    }

    // constants
    $nl = "\n" ;
    $block = 'a_big_recursion_protection_block';

    $c = $depth ;
    $indent = '' ;
    while( $c -- > 0 ) {
        $indent .= '|  ' ;
    }

    // if this has been parsed before
    if ( is_array($var) && isset($var[$block])) {

        $real =& $var[ $block ] ;
        $name =& $var[ 'name' ] ;
        $type = gettype( $real ) ;
        $output .= $indent.$var_name.' '.$method.'& '.($type=='array'?'Array':get_class($real)).' '.$name.$nl;

    // havent parsed this before
    } else {

        // insert recursion blocker
        $var = Array( $block => $var, 'name' => $reference );
        $theVar =& $var[ $block ] ;

        // print it out
        $type = gettype( $theVar ) ;
        switch( $type ) {

            case 'array' :
                $output .= $indent . $var_name . ' '.$method.' Array ('.$nl;
                $keys=array_keys($theVar);
                foreach($keys as $name) {
                    $value=&$theVar[$name];
                    var_log($value, $name, $reference.'["'.$name.'"]', '=', true);
                }
                $output .= $indent.')'.$nl;
                break ;

            case 'object' :
                $output .= $indent.$var_name.' = '.get_class($theVar).' {'.$nl;
                foreach($theVar as $name=>$value) {
                    var_log($value, $name, $reference.'->'.$name, '->', true);
                }
                $output .= $indent.'}'.$nl;
                break ;

            case 'string' :
                $output .= $indent . $var_name . ' '.$method.' "'.$theVar.'"'.$nl;
                break ;

            default :
                $output .= $indent . $var_name . ' '.$method.' ('.$type.') '.$theVar.$nl;
                break ;

        }

        // $var=$var[$block];

    }

    -- $depth ;

    if( $sub == false )
        return $output ;

}

// var_log( $var, '$name' ) ;

?>

Hope it works well for you!
Bryan 04-Jun-2007 09:38
Here's how you use output buffering to save var_dump to a string, as described in the Tip box.

<?php
ob_start();
var_dump($my_variable);
$my_string = ob_get_contents();
ob_end_clean();
?>
Zak Scott 24-May-2007 10:45
One of the most used approaches to this I have is:
<?php
echo "<pre>";
print_r($array); // or var_dump()
echo "</pre><br>";
?>

This is great for debugging purposes, no need for a long-winded debug class in most cases. Unless maybe you have a gigantic project that you didn't build yourself.
kaloyan at gmail dot com 26-Apr-2007 11:32
We can all agree that var_dump(); output is very spartan looking. The debug data needs to be organized better, and presented in a graceful way. In the era of Web 2.0 it is somewhat strange to use plain text to dump information. A DHTML powered informatiion dumping tool will be quite better - like the the open-source alternative of var_dump(); -- Krumo (http://krumo.sourceforge.net).

It renders the output using DHTML and collapsible nodes, it's layout is "skinable" and you can change it to fit your aesthetic taste. Krumo makes the output "human-readable" for real :) Plus it is compliant with both PHP4 and PHP5. Plus it detects "reference recursion". Plus you can use it to dump all various sort of data like debug back-traces, the superglobals ($_SERVER, $_ENV, $_REQUEST, $_COOKIE, $_GET, $_POST, $_SESSION), all the included files, all the declared classes, all the declared constants, all your PHP settings, all your php.ini values (if it is readable), all the loaded extensions, all the HTTP request headers, all the declared interfaces (for PHP5), all the file paths from INCLUDE_PATH, all the values of any particular INI file. Additionally it is designed to be easy to use - for example you can disable all the Krumo dumps instead of cleaning your code out of all print_r()'s and var_dump()'s. Anyway, if you check the site (http://krumo.sourceforge.net), you can found a lot of examples, demonstrations, documentation and all sort of helpful information.
thc at forestfactory dot de 06-Mar-2007 12:01
Well, like many others I was looking for a way to get nice dumps of variables. I think I'm about to solve this once and for all; or at least for PHP 5.1. Have a look at my project HLI. http://hli.forestfactory.de

It dumps and highlights not only Arrays and Object but also DOMDocument (as XML), DB results (as table), GD-Images (as PNG), DirectoryIterators (as table), Serialized Strings and many more.

It prints backtrace, object reflection (including PHPDoc) and the position of the dump. Dumps are movable, resizeable and foldable.

It is plugin-based, so its easy to write new dump-modes for other objects/resources. It generates XML output that is parsed by XSLT to HTML and will soon be able to be handled over AJAX (I will do this the next time I program some AJAX stuff).

It runs out of the box (tested with PHP 5.1 and PHP 5.2), but this is only a 0.1 release, so please tell me if something in wrong and I'll be happy to fix it.

Oh, and it's LGPL, so just use and enjoy it. I couldn't work without it any more.

Thomas
sneskid at hotmail dot com 19-Jan-2007 08:48
Since PHP and Javascript are friends:
<?php
function js_dump($js,$n,$z='') {
    if($z) {$a = $z . "['" . $n . "']";}
    else {$r = 'var '; $a = $n;}
    $r .= $a;
    if(is_array($js)) {
        $r .= ' = new Array();' . "\r\n";
        foreach($js as $k => $v) {
            if(is_array($v)) {$r .= js_dump($v, $k, $a);}
            else {$r .= $a . "['" . $k . "']" . to_js_safe($v);}
        }
    }
    else {$r .= to_js_safe($js);}
    return $r;
}
function to_js_safe($js) {return " = '" . addcslashes($js,"\\'") . "';\r\n";}

// example:
$arr = array();
$arr['hello'] = 'ba\'\\"by';
$arr['arr2']['h'] = 'zero';
$arr['arr2']['j'] = 'one';
$arr['arr2']['2']['0'] = 'zero';
$arr['arr2']['2']['1'] = 'one';
$arr[123] = 'but avoid these names in method 1';

// method 1
foreach($arr as $k=>$v) $j .= js_dump($v, $k);
//or method 2 (probably a better idea)
//$j = js_dump($arr,'result');

//then:
//$j = 'AJAX=' . rawurlencode($j);

echo $j;

?>

js_dump( variable/array to dump , starter name )

It's not very optimized and I'm no fan of recursion, but for small arrays this works well. I left 2 "\r\n" in there for readability, you should take them out.
NOTE it doesn't check for numerically named variables.

The result is Javascript eval() friendly.
See this tutorial if you are new to AJAX programming:
http://www.boutell.com/newfaq/creating/ajaxfetch.html
eric at ITCbrandt dot com swap ITC/brandt 30-Dec-2006 10:57
Very new to this and really appreciate the contributions of everyone.  I really rely on this site .  BigueNique inspired me with the last post.

I am writing an application that is WAY above my head and am buried in pages of variables and objects.  I really wanted an easier way to read them.

I had two problems - 1. The lists were too long; 2. It was hard to tell where one ended and the other began; 3.  By the time I saw my rendered forms, I forgot where my variable listing was. (Yeah, I can't count, get over it - now you know why this is so hard for me)

I had a variable dumping routine that worked better than the print_r, but elegant_dump was MUCH nicer.

I added a little bit of CSS and javascript to mine, and I have a really quick and easy way to display a colored title with a toggle control to expand or contract the variable structure and contents.

It might be too rudimentary for most of you guys, and I'm not answering anyone's question specifically, but perhaps this creative implementation will make someone's life a little easier.  At a minimum, It might be a good example of mixing in the different languages which was initially a big challenge for me.

simply call: dump_e($var,[$TracerMessage],[$ColorBackground],[$ColorContentBox]);

I have explained my functions as well as posted the required code to make it work here: http://tech.brandtitc.com/dump_e.php

It is a little too long to post in this venue.

Best Regards.
BigueNique at yahoo dot ca 02-Nov-2006 08:33
Geez! That was a hard one!

Wanted a more 'elegant' way do dump variable contents, but soon discovered the 'PHP reference problem', which makes it hard to deal recursive occurence of the same variable.

The only way I found to detect recursion was to actually modify the variable content (passed by reference) in order to be able to know that it was actually parsed.

References in PHP are quite confusing and often PHP got some strange behaviors....

TIP: don't use FOREACH($array as $key->$value) with arrays containing references...  You'll get the values the references had at the time they were put in the array, not their actual values.  You have to do $value=&$a['key']; (notice the amp) otherwise you're screwed!

Enjoy!

<?php
// An elegant dump
// By BigueNique@yahoo.ca
$elegant_dump_indent = '|&nbsp;&nbsp;&nbsp;&nbsp';
function elegant_dump(&$var, $var_name='', $indent='', $reference='') {
    global $elegant_dump_indent;
    $reference=$reference.$var_name;

    // first check if the variable has already been parsed
    $keyvar = 'the_elegant_dump_recursion_protection_scheme';
    $keyname = 'referenced_object_name';
    if (is_array($var) && isset($var[$keyvar])) {
        // the passed variable is already being parsed!
        $real_var=&$var[$keyvar];
        $real_name=&$var[$keyname];
        $type=gettype($real_var);
        echo "$indent<b>$var_name</b> (<i>$type</i>) = <font color=\"red\">&amp;$real_name</font><br>".br;
    } else {

        // we will insert an elegant parser-stopper
        $var=array($keyvar=>$var,
                   $keyname=>$reference);
        $avar=&$var[$keyvar];

        // do the display
        $type=gettype($avar);
        // array?
         if (is_array($avar)) {
            $count=count($avar);
            echo "$indent<b>$var_name</b> (<i>$type($count)</i>) {<br>".br;
            $keys=array_keys($avar);
            foreach($keys as $name) {
                $value=&$avar[$name];
                elegant_dump($value, "['$name']", $indent.$elegant_dump_indent, $reference);
            }
            echo "$indent}<br>".br;
        } else
        // object?
         if (is_object($avar)) {
            echo "$indent<b>$var_name</b> (<i>$type</i>) {<br>".br;
            foreach($avar as $name=>$value) elegant_dump($value, "-&gt;$name", $indent.$elegant_dump_indent, $reference);
            echo "$indent}<br>".br;
        } else
        // string?
        if (is_string($avar)) echo "$indent<b>$var_name</b> (<i>$type</i>) = \"$avar\"<br>".br;
        // any other?
        else echo "$indent<b>$var_name</b> (<i>$type</i>) = $avar<br>".br;

        $var=$var[$keyvar];
    }
}

$a=array();
$b['refers to a']=&$a;
$c['refers to b']=&$b;
$a['refers to c']=&$c;
elegant_dump($a,'$a');

/* Outputs:

$a (array(1)) {
|    ['refers to c'] (array(1)) {
|    |    ['refers to b'] (array(1)) {
|    |    |    ['refers to a'] (array) = &$a <-- stops recursing there
|    |    }
|    }
}

Works with objects too: */

$d->ref2f='';
$e->ref2d=&$d;
$f->ref2e=&$e;
$d->ref2f=&$f;
elegant_dump($d,'$d');

/* Outputs:

$d (object) {
|    ->ref2f (object) {
|    |    ->ref2e (object) {
|    |    |    ->ref2d (object) = &$d
|    |    }
|    }
}

*/
?>
jonbarnett at gmail dot com 02-Oct-2006 12:25
dumping objects that reference each other could lead to infinite recursion
<?php
$brother = new Sibling();
$sister = new Sibling();
$brother->sister = $sister;
$sister->brother = $brother;

var_dump($brother);
/* dumps all of $brother's properties, including "sister", which dumps all of $sister's properties, including "brother", etc. */
?>
Storm 19-Aug-2006 10:12
ul_var_dump - dump $var to <ul><li></li></ul>

<?php

function ul_var_dump(&$var,$type=0)
{
    if(!$type)
        echo "<ul type='circle' style='border:1px solid #a0a0a0;padding-bottom:4px;padding-right:4px'>\n<li>";
    if(is_array($var))
    {
        echo "[array][".count($var)."]";
        echo "<ul type='circle' style='border:1px solid #a0a0a0;padding-bottom:4px;padding-right:4px'>\n";
        foreach($var as $k=>$v)
        {
            echo "<li>\"{$k}\"=>";
            ul_var_dump(&$v,1);
        }
        echo "</ul>\n";
    }
    else
        echo "[".gettype($var)."][{$var}]</li>\n";
    if(!$type)
        echo "</ul>\n";
}

?>
andre at webkr dot de 04-Oct-2005 02:45
var_dump prefixes the variable type with & if the variable has more than one reference.
This is only true for variables that are part of an array, not for scalar types.

Example:
<?php
$a['foo'] = 'other';
$a['bar'] = 'i_have_ref';
$b =& $a['bar'];

var_dump($a);
var_dump($b);
?>

Result:
array(2) {
 ["foo"]=>
  string(5) "other"
 ["bar"]=>
  &string(10) "i_have_ref"
}
string(10) "i_have_ref"
ospinto at hotmail dot com 06-Aug-2005 09:43
Just created this neat class that dumps a variable in a colored tabular structure similar to the cfdump tag in Coldfusion. Very easy to use and makes it so much easier to see the contents of variable. For examples and download, visit http://dbug.ospinto.com
edwardzyang at thewritingpot dot com 20-Mar-2005 02:06
If you're like me and uses var_dump whenever you're debugging, you might find these two "wrapper" functions helpful.

This one automatically adds the PRE tags around the var_dump output so you get nice formatted arrays.

<?php

function var_dump_pre($mixed = null) {
  echo '<pre>';
  var_dump($mixed);
  echo '</pre>';
  return null;
}

?>

This one returns the value of var_dump instead of outputting it.

<?php

function var_dump_ret($mixed = null) {
  ob_start();
  var_dump($mixed);
  $content = ob_get_contents();
  ob_end_clean();
  return $content;
}

?>

Fairly simple functions, but they're infinitely helpful (I use var_dump_pre() almost exclusively now).
anon 28-Jan-2005 06:31
var_dump(get_defined_vars());
will dump all defined variables to the browser.
unset
var_export
Функции для работы с переменными


Выводит в браузер или возвращает интерпретируемое строковое представление переменной

var_dump
Веб-сервисы
Функции для работы с переменными
PHP Manual

var_export

(PHP 4 >= 4.2.0, PHP 5)

var_export — Выводит в браузер или возвращает интерпретируемое строковое представление переменной

Описание

mixed var_export ( mixed $expression [, bool $return = false ] )

var_export() возвращает структурированную информацию о данной переменной. Функция аналогична var_dump() за одним исключением: возвращаемое представление является полноценным PHP кодом.

Список параметров

expression

Переменная, которую необходимо экспортировать.

return

Если передано и значение равно TRUE, var_export() вернет представление переменной вместо его вывода.

Возвращаемые значения

Возвращает представление переменной, если параметр return передан и равен TRUE. В противном случае функция возвращает NULL.

Примечания

Замечание:

При использовании параметра return данная функция использует внутреннюю буферизацию вывода, поэтому она не может быть использована внутри callback-функции ob_start().

Список изменений

Версия | Описание
5.1.0 | Стало возможным экспортировать классы и массивы, содержащие другие классы, используя магический метод __set_state().

Примеры

Пример #1 Примеры использования var_export()

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

Результат выполнения данного примера:

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?>

Результат выполнения данного примера:

3.1

Пример #2 Экспорт классов в PHP с версии 5.1.0

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

Результат выполнения данного примера:

A::__set_state(array(
   'var' => 5,
))

Пример #3 Использование __set_state() (в PHP с версии 5.1.0)

<?php
class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);
?>

Результат выполнения данного примера:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Примечания

Замечание:

Переменные типа resource не могут быть экспортированы с помощью этой функции.

Замечание:

var_export() не обрабатывает циклические ссылки, так как было бы почти невозможно сгенерировать интерпретируемый PHP код для такого случая. Если необходимо производить какие-то действия с полным представлением массива или объекта, используйте функцию serialize().

Смотрите также

  • print_r() - Выводит удобочитаемую информацию о переменной
  • serialize() - Генерирует пригодное для хранения представление переменной
  • var_dump() - Выводит информацию о переменной

User Contributed Notes

programistka dot php at gmail dot com 19-Apr-2012 09:25
Example below shows how to use (e.g.) database stored settings as structurized array/object

My input array (pairs settings name and its value) is:

Array
(
    [commision.makler.level.1] => 1.0
    [commision.makler.level.2] => 1.2
    [commision.makler.level.3] => 1.4
    [commision.makler.level.4] => 1.5
    [commision.makler.level.5] => 2
    [commision.makler.level.6] => 3
    [commision.customer.level.0] => 10
    [commision.customer.level.1] => 4
    [commision.customer.level.2] => 3
    [commision.customer.level.3] => 2
    [commision.customer.level.4] => 1
)

When i use my paramsToVar() function on this array

$oSettings = paramsToVar($myArray,true);

... i'll get struturized object:

stdClass Object
(
    [commision] => stdClass Object
        (
            [makler] => stdClass Object
                (
                    [level] => stdClass Object
                        (
                            [1] => 1.0
                            [2] => 1.2
                            [3] => 1.4
                            [4] => 1.5
                            [5] => 2
                            [6] => 3
                        )

                )

            [customer] => stdClass Object
                (
                    [level] => stdClass Object
                        (
                            [0] => 10
                            [1] => 4
                            [2] => 3
                            [3] => 2
                            [4] => 1
                        )

                )

        )
)

Now I can easily access my settings or group of settings e.g.
    $oSettings->makler->level

function settingsToVar($inputArray, $returnAsObject =false, $levelSeparator ='.')
{
    $temp = array();
    foreach ($inputArray as $key => $setting) {
        $value = var_export($setting,true);
        eval('$temp["'.str_replace($levelSeparator,'"]["',$key).'"] = '.$value.';');
    }

    if (!$returnAsObject) {
        return $temp;
    }

     $replacements = array('array ('=>' (object) array(');
    $varToStr = str_replace(array_keys($replacements), array_values($replacements),  var_export($temp,true));
     eval('$return = '.$varToStr.';');
     return $return;
}
jodybrabec at gmail dot com 28-Mar-2012 05:52
WORKAROUND for error "Nesting level too deep - recursive dependency":
ob_start();
var_dump($GLOBALS);
$dataDump = ob_get_clean();
echo $dataDump;
Anonymous 11-Nov-2011 09:13
There is an even simpler way to have clean output from var_export and print_r in html pages:

<?php
function pretty_var($myArray)
{
    echo "<pre>";
    var_export($myArray);
    echo "</pre>";
}
?>
Hayley Watson 27-Oct-2011 07:10
Although var_export() describes an object in terms of code that calls its class's __set_state() method, that code is only useful as such (for code generation purposes, say) if the class actually HAS a __set_state() method.

Classes don't have __set_state(), in other words; you have to provide it with one yourself (just like __toString()).
laszlo dot heredy at gmail dot com 06-Oct-2010 01:57
Try this function instead of var_export($GLOBALS) or var_dump($GLOBALS) when all you want to know is the values of the variables you set on the current page.

<?php
function globalvars(){
    $result=array();
    $skip=array('GLOBALS','_ENV','HTTP_ENV_VARS',
                        '_POST','HTTP_POST_VARS','_GET',
                        'HTTP_GET_VARS',
                        '_COOKIE',
                        'HTTP_COOKIE_VARS','_SERVER',
                        'HTTP_SERVER_VARS',
                        '_FILES','HTTP_POST_FILES',
                        '_REQUEST','HTTP_SESSION_VARS',
                        '_SESSION');
    foreach($GLOBALS as $k=>$v)
        if(!in_array($k,$skip))
            $result[$k]=$v;
    return $result;
}//functionglobalvars

var_export(globalvars());
?>
4n4jmza02 at sneakemail dot com 17-Jun-2010 04:50
I learned the hard way that if var_export encounters a resource handle it exports it as "NULL", even if it is a valid handle. The documentation states that a handle cannot be exported, but it does not describe what happens if you try to do so anyway.

I had been using var_export in some debugging code while tracing a problem with a resource handle not being generated and ended up thinking that null handles were still being generated long after the problem had been fixed.
john dot risken at gmail dot com 16-Jan-2010 03:53
I didn't see this simple little item anywhere in the user notes. Maybe I'm blind!

Anyway, var_export and print_r both use spaces and carriage returns for formatting.  Sent to an html page, most of the formatting is lost. This simple function prints a nicely formatted array to an html screen:

<?php
function pretty_var($myArray){
    print str_replace(array("\n"," "),array("<br>","&nbsp;"), var_export($myArray,true))."<br>";
}
?>
rarioj at gmail dot com 28-Oct-2009 10:43
NOTE: If an object Foo has __set_state() method, but if that object contains another object Bar with no __set_state() method implemented, the resulting PHP expression will not be eval()-able.

This is an example (object Test that contains an instance of Exception).

<?php

class Test
{
  public $one;
  public $two;
  public function __construct($one, $two)
  {
    $this->one = $one;
    $this->two = $two;
  }
  public static function __set_state(array $array)
  {
    return new self($array['one'], $array['two']);
  }
}

$test = new Test('one', new Exception('test'));

$string = var_export($test, true);

/* $string =
Test::__set_state(array(
   'one' => 'one',
   'two' =>
  Exception::__set_state(array(
     'message' => 'test',
     'string' => '',
     'code' => 0,
     'file' => 'E:\\xampp\\htdocs\\test.Q.php',
     'line' => 35,
     'trace' =>
    array (
    ),
     'previous' => NULL,
  )),
))
*/

eval('$test2 = '.$string.';'); // Fatal error: Call to undefined method Exception::__set_state

?>

So avoid using var_export() on a complex array/object that contains other objects. Instead, use serialize() and unserialize() functions.

<?php

$string = 'unserialize('.var_export(serialize($test), true).')';

eval('$test2 = '.$string.';');

var_dump($test == $test2); // bool(true)

?>
ravenswd at gmail dot com 07-Jul-2009 10:32
(This replaces my note of 3-July-2009. The original version produced no output if a variable contained an empty array, or an array consisting only of empty arrays. For example, $bigarray['x'] = array(); Also, I have added a second version of the function.)

The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray = array()
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    print $varname . " = array()<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>

For those who want a version that produces valid PHP code, use this version:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
  else:
    print $varname . " = array();<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
    endforeach;
  endif;
}
?>

If your output is to a text file and not an HTML page, remove the <br>s.
ravenswd at gmail dot com 03-Jul-2009 05:21
The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray['firstelement'] = 'something'
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>
cmusicfan (at) gmail (daught) com 11-Jun-2009 09:19
Caution! var_export will add a backslash to single quotes (').

You may want to use stripslashes() to remove the mysteriously added backslashes.
stangelanda at arrowquick dot com 29-Jun-2007 04:20
I have been looking for the best method to store data in cache files.

First, I've identified two limitations of var_export verus serialize.  It can't store internal references inside of an array and it can't store a nested object or an array containing objects before PHP 5.1.0.

However, I could deal with both of those so I created a benchmark.  I used a single array containing from 10 to 150 indexes.  I've generate the elements' values randomly using booleans, nulls, integers, floats, and some nested arrays (the nested arrays are smaller averaging 5 elements but created similarly).  The largest percentage of elements are short strings around 10-15 characters.  While there is a small number of long strings (around 500 characters).

Benchmarking returned these results for 1000 * [total time] / [iterations (4000 in this case)]

serialize 3.656, 3.575, 3.68, 3.933, mean of 3.71
include 7.099, 5.42, 5.185, 6.076, mean of 5.95
eval 5.514, 5.204, 5.011, 5.788, mean of 5.38

Meaning serialize is around 1 and a half times faster than var_export for a single large array.  include and eval were consistently very close but eval was usually a few tenths faster (eval did better this particular set of trials than usual). An opcode cache like APC might make include faster, but otherwise serialize is the best choice.
Glen 23-May-2007 05:47
Like previously reported, i find var_export() frustrating when dealing with recursive structures.  Doing a :

<?php
var_export($GLOBALS);
?>

fails.  Interestingly, var_dump() has some logic to avoid recursive references.  So :

<?php
var_dump($GLOBALS);
?>

works (while being more ugly).  Unlike var_export(), var_dump() has no option to return the string, so output buffering logic is required if you want to direct the output.
niq 21-Mar-2007 05:44
To import exported variable you can use this code:

<?
$str=file_get_contents('exported_var.str');
$var=eval('return '.$str.';')
// Now $val contains imported variable
?>
dosperios at dot gmail dot nospam do com 10-Oct-2006 11:19
Here is a nifty function to export an object with var_export without the keys, which can be useful if you want to export an array but don't want the keys (for example if you want to be able to easily add something in the middle of the array by hand).

<?
function var_export_nokeys ($obj, $ret=false) {
    $retval = preg_replace("/'?\w+'?\s+=>\s+/", '', var_export($obj, true));
    if ($ret===true) {
        return $retval;
    } else {
        print $retval;
    }
}
?>

Works the same as var_export obviously. I found it useful, maybe someone else will too!
nobody at nowhere dot de 30-Aug-2006 03:48
Here is a bit code, what will read an saved object and turn it into an array.
Please note: It is very lousy style. Only an an idea.

$data = file_get_contents("test.txt");
$data = preg_replace('/class .*{/im', 'array (', $data);
$data = preg_replace('/\}/im', ')', $data);
$data = preg_replace('/var /im', '', $data);
$data = preg_replace('/;/im', ',', $data);
$data = preg_replace('/=/im', '=>', $data);
$data = preg_replace('/=>>/im', '=>', $data);
$data = preg_replace('/\$(.*?) /im', '"$1"', $data);
eval('$O = ' . $data . ';');
print_r($O);
Zorro 04-Sep-2005 11:24
This function can't export EVERYTHING. Moreover, you can have an error on an simple recursive array:

$test = array();
$test["oops"] = & $test;

echo var_export($test);

=>

Fatal error:  Nesting level too deep - recursive dependency? in ??.php on line 59
linus at flowingcreativity dot net 04-Jul-2005 09:50
<roman at DIESPAM dot feather dot org dot ru>, your function has inefficiencies and problems. I probably speak for everyone when I ask you to test code before you add to the manual.

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>
roman at DIESPAM dot feather dot org dot ru 18-Mar-2005 01:46
Function that exports variables without adding any junk to the resulting string:
<?php
function encode($var){
    if (is_array($var)) {
        $code = 'array(';
        foreach ($var as $key => $value) {
            $code .= "'$key'=>".encode($value).',';
        }
        $code = chop($code, ','); //remove unnecessary coma
        $code .= ')';
        return $code;
    } else {
        if (is_string($var)) {
            return "'".$var."'";
        } elseif (is_bool($code)) {
            return ($code ? 'TRUE' : 'FALSE');
        } else {
            return 'NULL';
        }
    }
}

function decode($string){
    return eval('return '.$string.';');
}
?>
The resulting string can sometimes be smaller, that output of serialize(). May be useful for storing things in the database.
paul at worldwithoutwalls dot co dot uk 24-Nov-2004 11:22
var_export() differs from print_r() for variables that are resources, with print_r() being more useful if you are using the function for debugging purposes.
e.g.
<?php
$res = mysql_connect($dbhost, $dbuser, $dbpass);
print_r($res); //output: Resource id #14
var_export($res); //output: NULL
?>
aidan at php dot net 10-Jun-2004 09:53
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
php_manual_note at bigredspark dot com 16-Oct-2003 12:43
[john holmes]
True, but that method would require you to open and read the file into a variable and then unserialize it into another variable.

Using a file created with var_export() could simply be include()'d, which will be less code and faster.

[kaja]
If you are trying to find a way to temporarily save variables into some other file, check out serialize() and unserialize() instead - this one is more useful for its readable property, very handy while debugging.

[original post]
If you're like me, you're wondering why a function that outputs "correct PHP syntax" is useful. This function can be useful in implementing a cache system. You can var_export() the array into a variable and write it into a file. Writing a string such as

<?php
$string = '<?php $array = ' . $data . '; ?>';
?>

where $data is the output of var_export() can create a file that can be easily include()d back into the script to recreate $array.

The raw output of var_export() could also be eval()d to recreate the array.

---John Holmes...
var_dump
Веб-сервисы
Функции для работы с переменными


Веб-сервисы

  • OAuth
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • OAuth Функции
    • OAuth — The OAuth class
    • OAuthProvider — The OAuthProvider class
    • OAuthException — OAuthException class
  • SCA
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • SCA Функции
  • SOAP
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • SOAP Функции
    • SoapClient — The SoapClient class
    • SoapServer — The SoapServer class
    • SoapFault — The SoapFault class
    • SoapHeader — The SoapHeader class
    • SoapParam — The SoapParam class
    • SoapVar — The SoapVar class
  • XML-RPC
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • XML-RPC Функции

User Contributed Notes

There are no user contributed notes for this page.
var_export
OAuth
Справочник функций


OAuth

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • FireEagle
  • OAuth Функции
    • oauth_get_sbs — Generate a Signature Base String
    • oauth_urlencode — Encode a URI to RFC 3986
  • OAuth — The OAuth class
    • OAuth::__construct — Create a new OAuth object
    • OAuth::__destruct — The destructor
    • OAuth::disableDebug — Turn off verbose debugging
    • OAuth::disableRedirects — Turn off redirects
    • OAuth::disableSSLChecks — Turn off SSL checks
    • OAuth::enableDebug — Turn on verbose debugging
    • OAuth::enableRedirects — Turn on redirects
    • OAuth::enableSSLChecks — Turn on SSL checks
    • OAuth::fetch — Fetch an OAuth protected resource
    • OAuth::generateSignature — Generate a signature
    • OAuth::getAccessToken — Fetch an access token
    • OAuth::getCAPath — Gets CA information
    • OAuth::getLastResponse — Get the last response
    • OAuth::getLastResponseHeaders — Get headers for last response
    • OAuth::getLastResponseInfo — Get HTTP information about the last response
    • OAuth::getRequestHeader — Generate OAuth header string signature
    • OAuth::getRequestToken — Fetch a request token
    • OAuth::setAuthType — Set authorization type
    • OAuth::setCAPath — Set CA path and info
    • OAuth::setNonce — Set the nonce for subsequent requests
    • OAuth::setRequestEngine — The setRequestEngine purpose
    • OAuth::setRSACertificate — Set the RSA certificate
    • OAuth::setSSLChecks — Tweak specific SSL checks for requests.
    • OAuth::setTimestamp — Set the timestamp
    • OAuth::setToken — Sets the token and secret
    • OAuth::setVersion — Set the OAuth version
  • OAuthProvider — The OAuthProvider class
    • OAuthProvider::addRequiredParameter — Add required parameters
    • OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest — Check an oauth request
    • OAuthProvider::__construct — Constructs a new OAuthProvider object
    • OAuthProvider::consumerHandler — Set the consumerHandler handler callback
    • OAuthProvider::generateToken — Generate a random token
    • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter — Remove a required parameter
    • OAuthProvider::reportProblem — Report a problem
    • OAuthProvider::setParam — Set a parameter
    • OAuthProvider::setRequestTokenPath — Set request token path
    • OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler — Set the tokenHandler handler callback
  • OAuthException — OAuthException class

User Contributed Notes

There are no user contributed notes for this page.
Веб-сервисы
Введение
Веб-сервисы


Введение

This extension provides OAuth consumer and provider bindings. OAuth is an authorization protocol built on top of HTTP which allows applications to securely access data without having to store usernames and passwords.

User Contributed Notes

There are no user contributed notes for this page.
OAuth
Установка и настройка
OAuth


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

Ryan Ewen 15-Jul-2011 10:28
Here is what I had to do to get it to install on CentOS

yum install pcre prce-devel
pecl install oauth

Create a file in /etc/php.d/ called oauth.ini containing:
extension=oauth.so

server httpd restart
waitman at waitman dot net 23-Jun-2011 05:51
`pecl install oauth` had problems locating curl/curl.h installed in  /usr/local/include

this seems to work:

1) download source from http://pecl.php.net/package/oauth

2) build

tar xzvf oauth-1.1.0.tgz
cd oauth-1.1.0
phpize
CPPFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib ./configure
make && make install
matthew dot general at gmail dot com 15-Jan-2011 07:48
installing using pecl:

# pecl install oauth

may need to install pcre headers (debian based)

# apt-get install libpcre3-dev
kosso1 at gmail dot com 04-Jan-2010 07:38
installing oauth pecl extension on fedora:

yum install php-devel
yum install libcurl-devel

pecl install -R /usr/lib/php oauth-0.99.9

add extension=oauth.so to php.ini  or create and add to/etc/php.d/oauth.ini

restart apache
Введение
Требования
OAuth


Требования

PECL/oauth requires PHP 5.1 or newer, ext/hash and ext/pcre.

PECL/oauth may optionally require libcurl if selected at build time. If configured with libcurl, it must be built with HTTPS support.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pear.php.net/package/oauth

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

Most of these constants involve problems, which are also described within the official OAuth » Problem Reporting documentation. Note however, that these constant names are specific to PHP, although the naming scheme is similar.

OAUTH_SIG_METHOD_RSASHA1 (string)
OAuth RSA-SHA1 signature method.
OAUTH_SIG_METHOD_HMACSHA1 (string)

OAuth HMAC-SHA1 signature method.

OAUTH_SIG_METHOD_HMACSHA256 (string)
OAuth HMAC-SHA256 signature method.
OAUTH_AUTH_TYPE_AUTHORIZATION (string)

This constant represents putting OAuth parameters in the Authorization header.

OAUTH_AUTH_TYPE_NONE (string)

This constant indicates a NoAuth OAuth request.

OAUTH_AUTH_TYPE_URI (string)

This constant represents putting OAuth parameters in the request URI.

OAUTH_AUTH_TYPE_FORM (string)

This constant represents putting OAuth parameters as part of the HTTP POST body.

OAUTH_HTTP_METHOD_GET (string)

Use the GET method for the OAuth request.

OAUTH_HTTP_METHOD_POST (string)

Use the POST method for the OAuth request.

OAUTH_HTTP_METHOD_PUT (string)

Use the PUT method for the OAuth request.

OAUTH_HTTP_METHOD_HEAD (string)

Use the HEAD method for the OAuth request.

OAUTH_HTTP_METHOD_DELETE (string)
Use the DELETE method for the OAuth request.
OAUTH_REQENGINE_STREAMS (integer)
Used by OAuth::setRequestEngine() to set the engine to PHP streams, as opposed to OAUTH_REQENGINE_CURL for Curl.
OAUTH_REQENGINE_CURL (integer)
Used by OAuth::setRequestEngine() to set the engine to Curl, as opposed to OAUTH_REQENGINE_STREAMS for PHP streams.
OAUTH_OK (integer)
Life is good.
OAUTH_BAD_NONCE (integer)
The oauth_nonce value was used in a previous request, therefore it cannot be used now.
OAUTH_BAD_TIMESTAMP (integer)
The oauth_timestamp value was not accepted by the service provider. In this case, the response should also contain the oauth_acceptable_timestamps parameter.
OAUTH_CONSUMER_KEY_UNKNOWN (integer)
The oauth_consumer_key is temporarily unacceptable to the service provider. For example, the service provider may be throttling the consumer.
OAUTH_CONSUMER_KEY_REFUSED (integer)
The consumer key was refused.
OAUTH_INVALID_SIGNATURE (integer)
The oauth_signature is invalid, as it does not match the signature computed by the service provider.
OAUTH_TOKEN_USED (integer)
The oauth_token has been consumed. It can no longer be used because it has already been used in the previous request(s).
OAUTH_TOKEN_EXPIRED (integer)
The oauth_token has expired.
OAUTH_TOKEN_REVOKED (integer)
The oauth_token has been revoked, and will never be accepted.
OAUTH_TOKEN_REJECTED (integer)
The oauth_token was not accepted by the service provider. The reason is not known, but it might be because the token was never issued, already consumed, expired, and/or forgotten by the service provider.
OAUTH_VERIFIER_INVALID (integer)
The oauth_verifier is incorrect.
OAUTH_PARAMETER_ABSENT (integer)
A required parameter was not received. In this case, the response should also contain the oauth_parameters_absent parameter.
OAUTH_SIGNATURE_METHOD_REJECTED (integer)
The oauth_signature_method was not accepted by service provider.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
OAuth


Примеры

Содержание

  • FireEagle

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
FireEagle
OAuth


FireEagle

<?php
$req_url = 'https://fireeagle.yahooapis.com/oauth/request_token';
$authurl = 'https://fireeagle.yahoo.net/oauth/authorize';
$acc_url = 'https://fireeagle.yahooapis.com/oauth/access_token';
$api_url = 'https://fireeagle.yahooapis.com/api/0.1';
$conskey = 'your_consumer_key';
$conssec = 'your_consumer_secret';

session_start();

// In state=1 the next request should include an oauth_token.
// If it doesn't go back to 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
  $oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
  $oauth->enableDebug();
  if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
    $request_token_info = $oauth->getRequestToken($req_url);
    $_SESSION['secret'] = $request_token_info['oauth_token_secret'];
    $_SESSION['state'] = 1;
    header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
    exit;
  } else if($_SESSION['state']==1) {
    $oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
    $access_token_info = $oauth->getAccessToken($acc_url);
    $_SESSION['state'] = 2;
    $_SESSION['token'] = $access_token_info['oauth_token'];
    $_SESSION['secret'] = $access_token_info['oauth_token_secret'];
  }
  $oauth->setToken($_SESSION['token'],$_SESSION['secret']);
  $oauth->fetch("$api_url/user.json");
  $json = json_decode($oauth->getLastResponse());
  print_r($json);
} catch(OAuthException $E) {
  print_r($E);
}
?>

User Contributed Notes

There are no user contributed notes for this page.
Примеры
OAuth Функции
Примеры


OAuth Функции

Содержание

  • oauth_get_sbs — Generate a Signature Base String
  • oauth_urlencode — Encode a URI to RFC 3986

User Contributed Notes

There are no user contributed notes for this page.
FireEagle
oauth_get_sbs
OAuth


Generate a Signature Base String

OAuth Функции
oauth_urlencode
OAuth Функции
PHP Manual

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — Generate a Signature Base String

Описание

string oauth_get_sbs ( string $http_method , string $uri [, array $request_parameters ] )

Generates a Signature Base String according to pecl/oauth.

Список параметров

http_method

The HTTP method.

uri

URI to encode.

request_parameters

Array of request parameters.

Возвращаемые значения

Returns a Signature Base String.

User Contributed Notes

There are no user contributed notes for this page.
OAuth Функции
oauth_urlencode
OAuth Функции


Encode a URI to RFC 3986

oauth_get_sbs
OAuth
OAuth Функции
PHP Manual

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — Encode a URI to RFC 3986

Описание

string oauth_urlencode ( string $uri )

Encodes a URI to » RFC 3986.

Список параметров

uri

URI to encode.

Возвращаемые значения

Returns an » RFC 3986 encoded string.

User Contributed Notes

bohwaz 30-Mar-2010 07:20
Note that php5.3 rawurlencode will do exactly the same thing.

For PHP 5.2, easy replacement to this function :

<?php

function rfc3986_encode($str)
{
  $str = rawurlencode($str);
  $str = str_replace('%E7', '~', $str);
  return $str;
}

?>
oauth_get_sbs
OAuth
OAuth Функции


The OAuth class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

The OAuth extension provides a simple interface to interact with data providers using the OAuth HTTP specification to protect private resources.

Обзор классов

OAuth {
/* Properties */
public $debug ;
public $sslChecks ;
public $debugInfo ;
/* Методы */
public __construct ( string $consumer_key , string $consumer_secret [, string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 [, int $auth_type = 0 ]] )
public void __destruct ( void )
public bool disableDebug ( void )
public bool disableRedirects ( void )
public bool disableSSLChecks ( void )
public bool enableDebug ( void )
public bool enableRedirects ( void )
public bool enableSSLChecks ( void )
public mixed fetch ( string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] )
public string generateSignature ( string $http_method , string $url [, mixed $extra_parameters ] )
public array getAccessToken ( string $access_token_url [, string $auth_session_handle [, string $verifier_token ]] )
public array getCAPath ( void )
public string getLastResponse ( void )
public string getLastResponseHeaders ( void )
public array getLastResponseInfo ( void )
public string getRequestHeader ( string $http_method , string $url [, mixed $extra_parameters ] )
public array getRequestToken ( string $request_token_url [, string $callback_url ] )
public mixed setAuthType ( int $auth_type )
public mixed setCAPath ([ string $ca_path [, string $ca_info ]] )
public mixed setNonce ( string $nonce )
public void setRequestEngine ( int $reqengine )
public mixed setRSACertificate ( string $cert )
public bool setSSLChecks ( int $sslcheck )
public mixed setTimestamp ( string $timestamp )
public bool setToken ( string $token , string $token_secret )
public bool setVersion ( string $version )
}

Свойства

debug

sslChecks

debugInfo

Содержание

  • OAuth::__construct — Create a new OAuth object
  • OAuth::__destruct — The destructor
  • OAuth::disableDebug — Turn off verbose debugging
  • OAuth::disableRedirects — Turn off redirects
  • OAuth::disableSSLChecks — Turn off SSL checks
  • OAuth::enableDebug — Turn on verbose debugging
  • OAuth::enableRedirects — Turn on redirects
  • OAuth::enableSSLChecks — Turn on SSL checks
  • OAuth::fetch — Fetch an OAuth protected resource
  • OAuth::generateSignature — Generate a signature
  • OAuth::getAccessToken — Fetch an access token
  • OAuth::getCAPath — Gets CA information
  • OAuth::getLastResponse — Get the last response
  • OAuth::getLastResponseHeaders — Get headers for last response
  • OAuth::getLastResponseInfo — Get HTTP information about the last response
  • OAuth::getRequestHeader — Generate OAuth header string signature
  • OAuth::getRequestToken — Fetch a request token
  • OAuth::setAuthType — Set authorization type
  • OAuth::setCAPath — Set CA path and info
  • OAuth::setNonce — Set the nonce for subsequent requests
  • OAuth::setRequestEngine — The setRequestEngine purpose
  • OAuth::setRSACertificate — Set the RSA certificate
  • OAuth::setSSLChecks — Tweak specific SSL checks for requests.
  • OAuth::setTimestamp — Set the timestamp
  • OAuth::setToken — Sets the token and secret
  • OAuth::setVersion — Set the OAuth version

User Contributed Notes

There are no user contributed notes for this page.
oauth_urlencode
OAuth::__construct
OAuth


Create a new OAuth object

OAuth
OAuth::__destruct
OAuth
PHP Manual

OAuth::__construct

(PECL OAuth >= 0.99.1)

OAuth::__construct — Create a new OAuth object

Описание

public OAuth::__construct ( string $consumer_key , string $consumer_secret [, string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 [, int $auth_type = 0 ]] )

Creates a new OAuth object

Список параметров

consumer_key

The consumer key provided by the service provider.

consumer_secret

The consumer secret provided by the service provider.

signature_method

This optional parameter defines which signature method to use, by default it is OAUTH_SIG_METHOD_HMACSHA1 (HMAC-SHA1).

auth_type

This optional parameter defines how to pass the OAuth parameters to a consumer, by default it is OAUTH_AUTH_TYPE_AUTHORIZATION (in the Authorization header).

User Contributed Notes

There are no user contributed notes for this page.
OAuth
OAuth::__destruct
OAuth


The destructor

OAuth::__construct
OAuth::disableDebug
OAuth
PHP Manual

OAuth::__destruct

(PECL OAuth >= 0.99.9)

OAuth::__destruct — The destructor

Описание

public void OAuth::__destruct ( void )

The destructor.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • OAuth::__construct() - Create a new OAuth object

User Contributed Notes

There are no user contributed notes for this page.
OAuth::__construct
OAuth::disableDebug
OAuth


Turn off verbose debugging

OAuth::__destruct
OAuth::disableRedirects
OAuth
PHP Manual

OAuth::disableDebug

(PECL OAuth >= 0.99.3)

OAuth::disableDebug — Turn off verbose debugging

Описание

public bool OAuth::disableDebug ( void )

Turns off verbose request information (off by default). Alternatively, the debug property can be set to a FALSE value to turn debug off.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE

Список изменений

Версия | Описание
0.99.8 | The related debug property was added.

Смотрите также

  • OAuth::enableDebug() - Turn on verbose debugging

User Contributed Notes

There are no user contributed notes for this page.
OAuth::__destruct
OAuth::disableRedirects
OAuth


Turn off redirects

OAuth::disableDebug
OAuth::disableSSLChecks
OAuth
PHP Manual

OAuth::disableRedirects

(PECL OAuth >= 0.99.9)

OAuth::disableRedirects — Turn off redirects

Описание

public bool OAuth::disableRedirects ( void )

Disable redirects from being followed automatically, thus allowing the request to be manually redirected.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE

Смотрите также

  • OAuth::enableRedirects() - Turn on redirects

User Contributed Notes

There are no user contributed notes for this page.
OAuth::disableDebug
OAuth::disableSSLChecks
OAuth


Turn off SSL checks

OAuth::disableRedirects
OAuth::enableDebug
OAuth
PHP Manual

OAuth::disableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::disableSSLChecks — Turn off SSL checks

Описание

public bool OAuth::disableSSLChecks ( void )

Turns off the usual SSL peer certificate and host checks, this is not for production environments. Alternatively, the sslChecks member can be set to FALSE to turn SSL checks off.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE

Список изменений

Версия | Описание
0.99.8 | The sslChecks member was added

Смотрите также

  • OAuth::enableSSLChecks() - Turn on SSL checks

User Contributed Notes

There are no user contributed notes for this page.
OAuth::disableRedirects
OAuth::enableDebug
OAuth


Turn on verbose debugging

OAuth::disableSSLChecks
OAuth::enableRedirects
OAuth
PHP Manual

OAuth::enableDebug

(PECL OAuth >= 0.99.3)

OAuth::enableDebug — Turn on verbose debugging

Описание

public bool OAuth::enableDebug ( void )

Turns on verbose request information useful for debugging, the debug information is stored in the debugInfo member. Alternatively, the debug member can be set to a non-FALSE value to turn debug on.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE

Список изменений

Версия | Описание
0.99.8 | The debug and debugInfo members were added

Смотрите также

  • OAuth::disableDebug() - Turn off verbose debugging

User Contributed Notes

There are no user contributed notes for this page.
OAuth::disableSSLChecks
OAuth::enableRedirects
OAuth


Turn on redirects

OAuth::enableDebug
OAuth::enableSSLChecks
OAuth
PHP Manual

OAuth::enableRedirects

(PECL OAuth >= 0.99.9)

OAuth::enableRedirects — Turn on redirects

Описание

public bool OAuth::enableRedirects ( void )

Follow and sign redirects automatically, which is enabled by default.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE

Смотрите также

  • OAuth::disableRedirects() - Turn off redirects

User Contributed Notes

There are no user contributed notes for this page.
OAuth::enableDebug
OAuth::enableSSLChecks
OAuth


Turn on SSL checks

OAuth::enableRedirects
OAuth::fetch
OAuth
PHP Manual

OAuth::enableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::enableSSLChecks — Turn on SSL checks

Описание

public bool OAuth::enableSSLChecks ( void )

Turns on the usual SSL peer certificate and host checks (enabled by default). Alternatively, the sslChecks member can be set to a non-FALSE value to turn SSL checks off.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE

Список изменений

Версия | Описание
0.99.8 | The sslChecks member was added

Смотрите также

  • OAuth::disableSSLChecks() - Turn off SSL checks

User Contributed Notes

There are no user contributed notes for this page.
OAuth::enableRedirects
OAuth::fetch
OAuth


Fetch an OAuth protected resource

OAuth::enableSSLChecks
OAuth::generateSignature
OAuth
PHP Manual

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch — Fetch an OAuth protected resource

Описание

public mixed OAuth::fetch ( string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] )

Fetch a resource.

Список параметров

protected_resource_url

URL to the OAuth protected resource.

extra_parameters

Extra parameters to send with the request for the resource.

http_method

One of the OAUTH_HTTP_METHOD_* OAUTH constants, which includes GET, POST, PUT, HEAD, or DELETE.

HEAD (OAUTH_HTTP_METHOD_HEAD) can be useful for discovering information prior to the request (if OAuth credentials are in the Authorization header).

http_headers

HTTP client headers (such as User-Agent, Accept, etc.)

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.
0.99.5 | The http_method parameter was added
0.99.8 | The http_headers parameter was added

Примеры

Пример #1 OAuth::fetch() example

<?php
try {
    $oauth = new OAuth("consumer_key","consumer_secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauth->setToken("access_token","access_token_secret");

    $oauth->fetch("http://photos.example.net/photo?file=vacation.jpg");

    $response_info = $oauth->getLastResponseInfo();
    header("Content-Type: {$response_info["content_type"]}");
    echo $oauth->getLastResponse();
} catch(OAuthException $E) {
    echo "Exception caught!\n";
    echo "Response: ". $E->lastResponse . "\n";
}
?>

Смотрите также

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::setToken() - Sets the token and secret

User Contributed Notes

sun at drupal dot org 09-Aug-2011 06:40
Make sure that your $extra_parameters is an array.

If it's not, then OAuth will silently skip the malformed data type and produce a signature base string that is invalid (doesn't contain POST parameters, as defined in the RFC).

You should file a critical bug report against any REST API you find in the wild that accepts such a bogus signature to pass authentication.
contact info at mech dot cx 23-Mar-2011 04:00
I was having troubles getting fetch() to post, the remote server (Twitter, in this case) complained at me that their "resource only supports POST". Turned out to be a known bug in OAuth 1.1, downgrading to 1.0 fixed it.

Don't lose as much time over this as I did :-)
Lyuben Penkovski (l_penkovski at yahoo dot com) 26-Aug-2010 11:51
If the provider's web server is configured to use Keep-Alive extension to HTTP protocol (HTTP 1.1), there can be a big delay in the response time from the provider. By default Apache is configured to use Keep-Alive for 5 seconds. This is the delay after which the response will come back to the consumer. If you have this issue of delayed result, you can pass in HTTP headers when calling $consumer->fetch():

<?php
$consumer = new OAuth("consumer_key", "consumer_secret", OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
$consumer->fetch('http://example.com/api/', null, OAUTH_HTTP_METHOD_POST, array('Connection'=>'close'));
?>

Then the provider will send the result immediately after it's ready with the processing and the connection will be closed. Unfortunately, when calling $consumer->getRequestToken() and $consumer->getAccessToken() there's no way provided to pass in HTTP headers and this delay (if present) cannot be avoided, or at least we could not find a way to avoid it.

The solution that worked for us is to send this header from the provider when returning result to the consumer:

<?php
$result = 'oauth_callback_accepted=true&oauth_token=' . $this->urlencode($token->oauth_token) .
          '&oauth_token_secret='.$this->urlencode($token->oauth_token_secret);

header('HTTP/1.1 200 OK');
header('Content-Length: '.strlen($result));
header('Content-Type: application/x-www-form-urlencoded');
header('Connection:close');
echo $result;
?>

This can work if you have the possibility to modify the code of the provider, e.g. if you are the provider yourself or if you can talk with the people that develop it and ask them to send this header for your request.
OAuth::enableSSLChecks
OAuth::generateSignature
OAuth


Generate a signature

OAuth::fetch
OAuth::getAccessToken
OAuth
PHP Manual

OAuth::generateSignature

(Информация о версии неизвестна, возможно, только в SVN)

OAuth::generateSignature — Generate a signature

Описание

public string OAuth::generateSignature ( string $http_method , string $url [, mixed $extra_parameters ] )

Generate a signature based on the final HTTP method, URL and a string/array of parameters.

Список параметров

http_method

HTTP method for request

url

URL for request

extra_parameters

String or array of additional parameters.

Возвращаемые значения

A string containing the generated signature или FALSE в случае возникновения ошибки

User Contributed Notes

There are no user contributed notes for this page.
OAuth::fetch
OAuth::getAccessToken
OAuth


Fetch an access token

OAuth::generateSignature
OAuth::getCAPath
OAuth
PHP Manual

OAuth::getAccessToken

(PECL OAuth >= 0.99.1)

OAuth::getAccessToken — Fetch an access token

Описание

public array OAuth::getAccessToken ( string $access_token_url [, string $auth_session_handle [, string $verifier_token ]] )

Fetch an access token, secret and any additional response parameters from the service provider.

Список параметров

access_token_url

URL to the access token API.

auth_session_handle

Authorization session handle, this parameter does not have any citation in the core OAuth 1.0 specification but may be implemented by large providers. » See ScalableOAuth for more information.

verifier_token

For service providers which support 1.0a, a verifier_token must be passed while exchanging the request token for the access token. If the verifier_token is present in $_GET or $_POST it is passed automatically and the caller does not need to specify a verifier_token (usually if the access token is exchanged at the oauth_callback URL). » See ScalableOAuth for more information.

Возвращаемые значения

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.
0.99.9 | The verifier_token parameter was added

Примеры

Пример #1 OAuth::getAccessToken() example

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $oauth->setToken($request_token,$request_token_secret);
    $access_token_info = $oauth->getAccessToken("https://example.com/oauth/access_token");
    if(!empty($access_token_info)) {
        print_r($access_token_info);
    } else {
        print "Failed fetching access token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Смотрите также

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::setToken() - Sets the token and secret

User Contributed Notes

There are no user contributed notes for this page.
OAuth::generateSignature
OAuth::getCAPath
OAuth


Gets CA information

OAuth::getAccessToken
OAuth::getLastResponse
OAuth
PHP Manual

OAuth::getCAPath

(PECL OAuth >= 0.99.8)

OAuth::getCAPath — Gets CA information

Описание

public array OAuth::getCAPath ( void )

Gets the Certificate Authority information, which includes the ca_path and ca_info set by OAuth::setCaPath().

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

An array of Certificate Authority information, specifically as ca_path and ca_info keys within the returned associative array.

Смотрите также

  • OAuth::setCAPath() - Set CA path and info
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response

User Contributed Notes

There are no user contributed notes for this page.
OAuth::getAccessToken
OAuth::getLastResponse
OAuth


Get the last response

OAuth::getCAPath
OAuth::getLastResponseHeaders
OAuth
PHP Manual

OAuth::getLastResponse

(PECL OAuth >= 0.99.1)

OAuth::getLastResponse — Get the last response

Описание

public string OAuth::getLastResponse ( void )

Get the raw response of the most recent request.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Returns a string containing the last response.

Смотрите также

  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::fetch() - Fetch an OAuth protected resource

User Contributed Notes

There are no user contributed notes for this page.
OAuth::getCAPath
OAuth::getLastResponseHeaders
OAuth


Get headers for last response

OAuth::getLastResponse
OAuth::getLastResponseInfo
OAuth
PHP Manual

OAuth::getLastResponseHeaders

(Информация о версии неизвестна, возможно, только в SVN)

OAuth::getLastResponseHeaders — Get headers for last response

Описание

public string OAuth::getLastResponseHeaders ( void )

Get headers for last response.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

A string containing the last response's headers или FALSE в случае возникновения ошибки

User Contributed Notes

There are no user contributed notes for this page.
OAuth::getLastResponse
OAuth::getLastResponseInfo
OAuth


Get HTTP information about the last response

OAuth::getLastResponseHeaders
OAuth::getRequestHeader
OAuth
PHP Manual

OAuth::getLastResponseInfo

(PECL OAuth >= 0.99.1)

OAuth::getLastResponseInfo — Get HTTP information about the last response

Описание

public array OAuth::getLastResponseInfo ( void )

Get HTTP information about the last response.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Returns an array containing the response information for the last request. Constants from curl_getinfo() may be used.

Смотрите также

  • OAuth::fetch() - Fetch an OAuth protected resource
  • OAuth::getLastResponse() - Get the last response

User Contributed Notes

There are no user contributed notes for this page.
OAuth::getLastResponseHeaders
OAuth::getRequestHeader
OAuth


Generate OAuth header string signature

OAuth::getLastResponseInfo
OAuth::getRequestToken
OAuth
PHP Manual

OAuth::getRequestHeader

(Информация о версии неизвестна, возможно, только в SVN)

OAuth::getRequestHeader — Generate OAuth header string signature

Описание

public string OAuth::getRequestHeader ( string $http_method , string $url [, mixed $extra_parameters ] )

Generate OAuth header string signature based on the final HTTP method, URL and a string/array of parameters

Список параметров

http_method

HTTP method for request.

url

URL for request.

extra_parameters

String or array of additional parameters.

Возвращаемые значения

A string containing the generated request header или FALSE в случае возникновения ошибки

User Contributed Notes

There are no user contributed notes for this page.
OAuth::getLastResponseInfo
OAuth::getRequestToken
OAuth


Fetch a request token

OAuth::getRequestHeader
OAuth::setAuthType
OAuth
PHP Manual

OAuth::getRequestToken

(PECL OAuth >= 0.99.1)

OAuth::getRequestToken — Fetch a request token

Описание

public array OAuth::getRequestToken ( string $request_token_url [, string $callback_url ] )

Fetch a request token, secret and any additional response parameters from the service provider.

Список параметров

request_token_url

URL to the request token API.

callback_url

OAuth callback URL. If callback_url is passed and is an empty value, it is set to "oob" to address the OAuth 2009.1 advisory.

Возвращаемые значения

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.
0.99.9 | The callback_url parameter was added

Примеры

Пример #1 OAuth::getRequestToken() example

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $request_token_info = $oauth->getRequestToken("https://example.com/oauth/request_token");
    if(!empty($request_token_info)) {
        print_r($request_token_info);
    } else {
        print "Failed fetching request token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

Результатом выполнения данного примера будет что-то подобное:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Смотрите также

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response

User Contributed Notes

bohwaz 29-Mar-2010 07:29
Please note that if you don't supply callback_url, the oauth parameter oauth_callback will not be sent to the server and will result in an error from the server, as this parameter is REQUIRED in the OAuth spec.
OAuth::getRequestHeader
OAuth::setAuthType
OAuth


Set authorization type

OAuth::getRequestToken
OAuth::setCAPath
OAuth
PHP Manual

OAuth::setAuthType

(PECL OAuth >= 0.99.1)

OAuth::setAuthType — Set authorization type

Описание

public mixed OAuth::setAuthType ( int $auth_type )

Set where the OAuth parameters should be passed.

Список параметров

auth_type

auth_type can be one of the following flags (in order of decreasing preference as per OAuth 1.0 section 5.2):

OAUTH_AUTH_TYPE_AUTHORIZATION
Pass the OAuth parameters in the HTTP Authorization header.
OAUTH_AUTH_TYPE_FORM
Append the OAuth parameters to the HTTP POST request body.
OAUTH_AUTH_TYPE_URI
Append the OAuth parameters to the request URI.
OAUTH_AUTH_TYPE_NONE
None.

Возвращаемые значения

Returns TRUE if a parameter is correctly set, otherwise FALSE (e.g., if an invalid auth_type is passed in.)

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.

User Contributed Notes

There are no user contributed notes for this page.
OAuth::getRequestToken
OAuth::setCAPath
OAuth


Set CA path and info

OAuth::setAuthType
OAuth::setNonce
OAuth
PHP Manual

OAuth::setCAPath

(PECL OAuth >= 0.99.8)

OAuth::setCAPath — Set CA path and info

Описание

public mixed OAuth::setCAPath ([ string $ca_path [, string $ca_info ]] )

Sets the Certificate Authority (CA), both for path and info.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

ca_path

The CA Path being set.

ca_info

The CA Info being set.

Возвращаемые значения

Returns TRUE on success, or FALSE if either ca_path or ca_info are considered invalid.

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.

Смотрите также

  • OAuth::getCaPath() - Gets CA information

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setAuthType
OAuth::setNonce
OAuth


Set the nonce for subsequent requests

OAuth::setCAPath
OAuth::setRequestEngine
OAuth
PHP Manual

OAuth::setNonce

(PECL OAuth >= 0.99.1)

OAuth::setNonce — Set the nonce for subsequent requests

Описание

public mixed OAuth::setNonce ( string $nonce )

Sets the nonce for all subsequent requests.

Список параметров

nonce

The value for oauth_nonce.

Возвращаемые значения

Returns TRUE on success, or FALSE if the nonce is considered invalid.

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.

Смотрите также

  • OAuth::setToken() - Sets the token and secret
  • OAuth::setAuthType() - Set authorization type
  • OAuth::setVersion() - Set the OAuth version

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setCAPath
OAuth::setRequestEngine
OAuth


The setRequestEngine purpose

OAuth::setNonce
OAuth::setRSACertificate
OAuth
PHP Manual

OAuth::setRequestEngine

(PECL OAuth >= 1.0.0)

OAuth::setRequestEngine — The setRequestEngine purpose

Описание

public void OAuth::setRequestEngine ( int $reqengine )

Sets the Request Engine, that will be sending the HTTP requests.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

reqengine

The desired request engine. Set to OAUTH_REQENGINE_STREAMS to use PHP Streams, or OAUTH_REQENGINE_CURL to use Curl.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Emits an OAuthException exception if an invalid request engine is chosen.

Примеры

Пример #1 OAuth::setRequestEngine() example

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

Смотрите также

  • Curl
  • PHP streams
  • OAuthException

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setNonce
OAuth::setRSACertificate
OAuth


Set the RSA certificate

OAuth::setRequestEngine
OAuth::setSSLChecks
OAuth
PHP Manual

OAuth::setRSACertificate

(PECL OAuth >= 1.0.0)

OAuth::setRSACertificate — Set the RSA certificate

Описание

public mixed OAuth::setRSACertificate ( string $cert )

Sets the RSA certificate.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

cert

The RSA certificate.

Возвращаемые значения

Returns TRUE on success, or FALSE on failure (e.g., the RSA certificate cannot be parsed.)

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.

Примеры

Пример #1 An OAuth::setRsaCertificate() example

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

Смотрите также

  • OAuth::setCaPath() - Set CA path and info

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setRequestEngine
OAuth::setSSLChecks
OAuth


Tweak specific SSL checks for requests.

OAuth::setRSACertificate
OAuth::setTimestamp
OAuth
PHP Manual

OAuth::setSSLChecks

(Информация о версии неизвестна, возможно, только в SVN)

OAuth::setSSLChecks — Tweak specific SSL checks for requests.

Описание

public bool OAuth::setSSLChecks ( int $sslcheck )

Tweak specific SSL checks for requests.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

sslcheck

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setRSACertificate
OAuth::setTimestamp
OAuth


Set the timestamp

OAuth::setSSLChecks
OAuth::setToken
OAuth
PHP Manual

OAuth::setTimestamp

(PECL OAuth >= 1.0.0)

OAuth::setTimestamp — Set the timestamp

Описание

public mixed OAuth::setTimestamp ( string $timestamp )

Sets the OAuth timestamp for subsequent requests.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

timestamp

The timestamp.

Возвращаемые значения

Returns TRUE, unless the timestamp is invalid, in which case FALSE is returned.

Список изменений

Версия | Описание
1.0.0 | Раньше при ошибке возвращался NULL вместо FALSE.

Смотрите также

  • OAuth::setNonce() - Set the nonce for subsequent requests

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setSSLChecks
OAuth::setToken
OAuth


Sets the token and secret

OAuth::setTimestamp
OAuth::setVersion
OAuth
PHP Manual

OAuth::setToken

(PECL OAuth >= 0.99.1)

OAuth::setToken — Sets the token and secret

Описание

public bool OAuth::setToken ( string $token , string $token_secret )

Set the token and secret for subsequent requests.

Список параметров

token

The OAuth token.

token_secret

The OAuth token secret.

Возвращаемые значения

TRUE

Примеры

Пример #1 OAuth::setToken() example

<?php
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
$oauth->setToken("token","token-secret");
?>

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setTimestamp
OAuth::setVersion
OAuth


Set the OAuth version

OAuth::setToken
OAuthProvider
OAuth
PHP Manual

OAuth::setVersion

(PECL OAuth >= 0.99.1)

OAuth::setVersion — Set the OAuth version

Описание

public bool OAuth::setVersion ( string $version )

Sets the OAuth version for subsequent requests

Список параметров

version

OAuth version, default value is always "1.0"

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setToken
OAuthProvider
OAuth


The OAuthProvider class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Manages an OAuth provider class.

See also an external in-depth tutorial titled » Writing an OAuth Provider Service, which takes a hands-on approach to providing this service. There are also » OAuth provider examples within the OAuth extensions sources.

Обзор классов

OAuthProvider {
/* Methods */
final public bool addRequiredParameter ( string $req_params )
public void callconsumerHandler ( void )
public void callTimestampNonceHandler ( void )
public void calltokenHandler ( void )
public void checkOAuthRequest ([ string $uri [, string $method ]] )
public __construct ([ array $params_array ] )
public void consumerHandler ( callable $callback_function )
final public static string generateToken ( int $size [, bool $strong = false ] )
public void is2LeggedEndpoint ( mixed $params_array )
public void isRequestTokenEndpoint ( bool $will_issue_request_token )
final public bool removeRequiredParameter ( string $req_params )
final public static string reportProblem ( string $oauthexception [, bool $send_headers = true ] )
final public bool setParam ( string $param_key [, mixed $param_val ] )
final public bool setRequestTokenPath ( string $path )
public void timestampNonceHandler ( callable $callback_function )
public void tokenHandler ( callable $callback_function )
}

Содержание

  • OAuthProvider::addRequiredParameter — Add required parameters
  • OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback
  • OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback
  • OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback
  • OAuthProvider::checkOAuthRequest — Check an oauth request
  • OAuthProvider::__construct — Constructs a new OAuthProvider object
  • OAuthProvider::consumerHandler — Set the consumerHandler handler callback
  • OAuthProvider::generateToken — Generate a random token
  • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
  • OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint
  • OAuthProvider::removeRequiredParameter — Remove a required parameter
  • OAuthProvider::reportProblem — Report a problem
  • OAuthProvider::setParam — Set a parameter
  • OAuthProvider::setRequestTokenPath — Set request token path
  • OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback
  • OAuthProvider::tokenHandler — Set the tokenHandler handler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuth::setVersion
OAuthProvider::addRequiredParameter
OAuth


Add required parameters

OAuthProvider
OAuthProvider::callconsumerHandler
OAuthProvider
PHP Manual

OAuthProvider::addRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::addRequiredParameter — Add required parameters

Описание

final public bool OAuthProvider::addRequiredParameter ( string $req_params )

Add required oauth provider parameters.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

req_params

The required parameters.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • OAuthProvider::removeRequiredParameter() - Remove a required parameter

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider
OAuthProvider::callconsumerHandler
OAuthProvider


Calls the consumerNonceHandler callback

OAuthProvider::addRequiredParameter
OAuthProvider::callTimestampNonceHandler
OAuthProvider
PHP Manual

OAuthProvider::callconsumerHandler

(Информация о версии неизвестна, возможно, только в SVN)

OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback

Описание

public void OAuthProvider::callconsumerHandler ( void )

Calls the registered consumer handler callback function, which is set with OAuthProvider::consumerHandler().

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Если callback-функция не может быть вызвана или отсутствует, то генерируется ошибка уровня E_ERROR.

Смотрите также

  • OAuthProvider::consumerHandler() - Set the consumerHandler handler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::addRequiredParameter
OAuthProvider::callTimestampNonceHandler
OAuthProvider


Calls the timestampNonceHandler callback

OAuthProvider::callconsumerHandler
OAuthProvider::calltokenHandler
OAuthProvider
PHP Manual

OAuthProvider::callTimestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback

Описание

public void OAuthProvider::callTimestampNonceHandler ( void )

Calls the registered timestamp handler callback function, which is set with OAuthProvider::timestampNonceHandler().

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Если callback-функция не может быть вызвана или отсутствует, то генерируется ошибка уровня E_ERROR.

Смотрите также

  • OAuthProvider::timestampNonceHandler() - Set the timestampNonceHandler handler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::callconsumerHandler
OAuthProvider::calltokenHandler
OAuthProvider


Calls the tokenNonceHandler callback

OAuthProvider::callTimestampNonceHandler
OAuthProvider::checkOAuthRequest
OAuthProvider
PHP Manual

OAuthProvider::calltokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback

Описание

public void OAuthProvider::calltokenHandler ( void )

Calls the registered token handler callback function, which is set with OAuthProvider::tokenHandler().

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Если callback-функция не может быть вызвана или отсутствует, то генерируется ошибка уровня E_ERROR.

Смотрите также

  • OAuthProvider::tokenHandler() - Set the tokenHandler handler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::callTimestampNonceHandler
OAuthProvider::checkOAuthRequest
OAuthProvider


Check an oauth request

OAuthProvider::calltokenHandler
OAuthProvider::__construct
OAuthProvider
PHP Manual

OAuthProvider::checkOAuthRequest

(PECL OAuth >= 1.0.0)

OAuthProvider::checkOAuthRequest — Check an oauth request

Описание

public void OAuthProvider::checkOAuthRequest ([ string $uri [, string $method ]] )

Checks an OAuth request.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

uri

The optional URI, or endpoint.

method

The HTTP method. Optionally pass in one of the OAUTH_HTTP_METHOD_* OAuth constants.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

Emits an E_ERROR level error if the HTTP method cannot be detected.

Смотрите также

  • OAuthProvider::reportProblem() - Report a problem

User Contributed Notes

Lyuben Penkovski (l_penkovski at yahoo dot com) 23-Aug-2010 03:59
This function checks if OAuth request is valid and signed correctly.

$provider->checkOAuthRequest();

It does this by first calling timestampNonceHandler and expects result OAUHT_OK from it. If the result is different, an exception is thrown. It's up to you to write the code that checks timestamp/nonce combinations.

Secondly, it calls consumerHandler and expects your code in the consumerHandler function to set $provider->consumer_secret to the correct value (you should take it from your consumer storage location where it's saved with consumer key). If $provider->consumer_secret is not set, or is not set with the proper value an exception is thrown. Proper value means that it should be the same consumer key that was used to sign the request by the consumer before sending it to here (the provider). Again expected result from this function is OAUTH_OK or some OAUTH error code if you want to throw exception.

Third, it calls tokenHandler, but only WHEN you are requesting ACCESS token or requesting protected data with authorized ACCESS TOKEN. In order for the provider to call tokenHandler, before a call to the checkOAuthRequest function is made, the provider should call the method that says that this is not a request token endpoint (this is access token endpoint):

$provider->isRequestTokenEndpoint (false);
$provider->checkOAuthRequest();

Again here OAuthProvider is expecting your code in the tokenHandler to set $provider->token_secret to the correct value (you should take it from your token storage place) because during the signing process it uses CONSUMER SECRET (for request token) and CONSUMER SECRET AND TOKEN SECRET (for access token and fetch of protected data) to sign the request.

After these 3 handler functions are called and return good results (OAUTH_OK) and set the values of the required fields $provider->consumer_secret and $provider->token_secret, then the checkOAuthRequest function signs the request. If something goes wrong, it throws exception, otherwise there comes the place for your code to proceed and handle the request:

- you can create request token (if it's a first request for request token)
- you can create access token (if it's a request for access token)
- you can return protected data to the consumer (if it's a request to fetch protected data)

This is how the functions in my code look like, however please have in mind that I've just implemented it and it's possible that I have something missed or forgotten, but generally I think the idea should be clear:

$this->dbModel is the object for working with database and save/retrieve token and consumer data

<?php

public function timestampNonceHandler ( $provider )
{
    return $this->dbModel->checkTimestampNonce ( $provider->consumer_key,
                                                 $provider->token,
                                                 $provider->timestamp,
                                                 $provider->nonce );
}

public function consumerHandler ( $provider )
{
    $consumer = $this->dbModel->getConsumerSecrets ($provider->consumer_key);

    if($consumer['consumer_key'] != $provider->consumer_key)
    {
        return OAUTH_CONSUMER_KEY_UNKNOWN;
    }

    if( (int)$consumer['disabled'] != 0 )
    {
        return OAUTH_CONSUMER_KEY_REFUSED;
    }

    $provider->consumer_id = $consumer['consumer_id']; # this is not required by OAuthProvider but I use it later in tokenHandler
    $provider->consumer_secret = $consumer['consumer_secret']; # this is REQUIRED

    return OAUTH_OK;
}

public function tokenHandler ( $provider )
{
    $token = $this->dbModel->getToken( $provider->token );

    if( time() > $token['expire'] )
    {
        return OAUTH_TOKEN_EXPIRED;
    }

    if($token['consumer_id'] != $provider->consumer_id)
    {
        return OAUTH_TOKEN_REJECTED;
    }

    if( (int)$token['authorized'] == 0 )
    {
        return OAUTH_TOKEN_REJECTED;
    }

    if($token['token_type'] != 'access')
    {
        if($token['verifier'] != $provider->verifier)
            return OAUTH_VERIFIER_INVALID;
    }

    $provider->token_id = $token['token_id']; # not required to be set by OAuthProvider
    $provider->token_secret = $token['token_secret']; # this is REQUIRED

    return OAUTH_OK;
}

?>
OAuthProvider::calltokenHandler
OAuthProvider::__construct
OAuthProvider


Constructs a new OAuthProvider object

OAuthProvider::checkOAuthRequest
OAuthProvider::consumerHandler
OAuthProvider
PHP Manual

OAuthProvider::__construct

(PECL OAuth >= 1.0.0)

OAuthProvider::__construct — Constructs a new OAuthProvider object

Описание

public OAuthProvider::__construct ([ array $params_array ] )

Initiates a new OAuthProvider object.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

params_array

Setting these optional parameters is limited to the CLI SAPI.

Возвращаемые значения

An OAuthProvider object.

Примеры

Пример #1 OAuthProvider::__construct() example

<?php
try {

    $op = new OAuthProvider();

    // Uses user-defined callback functions
    $op->consumerHandler(array($this, 'lookupConsumer'));
    $op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
    $op->tokenHandler(array($this, 'myTokenHandler'));

    // Ignore the foo_uri parameter
    $op->setParam('foo_uri', NULL);

    // No token needed for this end point
    $op->setRequestTokenPath('/v1/oauth/request_token');

    $op->checkOAuthRequest();

} catch (OAuthException $e) {

    echo OAuthProvider::reportProblem($e);
}
?>

Смотрите также

  • OAuthProvider::setParam() - Set a parameter

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::checkOAuthRequest
OAuthProvider::consumerHandler
OAuthProvider


Set the consumerHandler handler callback

OAuthProvider::__construct
OAuthProvider::generateToken
OAuthProvider
PHP Manual

OAuthProvider::consumerHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::consumerHandler — Set the consumerHandler handler callback

Описание

public void OAuthProvider::consumerHandler ( callable $callback_function )

Sets the consumer handler callback, which will later be called with OAuthProvider::callConsumerHandler().

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

callback_function

The callable functions name.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Example OAuthProvider::consumerHandler() callback

<?php
function lookupConsumer($provider) {

    if ($provider->consumer_key === 'unknown') {
        return OAUTH_CONSUMER_KEY_UNKNOWN;
    } else if($provider->consumer_key == 'blacklisted' || $provider->consumer_key === 'throttled') {
        return OAUTH_CONSUMER_KEY_REFUSED;
    }

    $provider->consumer_secret = "the_consumers_secret";

    return OAUTH_OK;
}
?>

Смотрите также

  • OAuthProvider::callConsumerHandler() - Calls the consumerNonceHandler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::__construct
OAuthProvider::generateToken
OAuthProvider


Generate a random token

OAuthProvider::consumerHandler
OAuthProvider::is2LeggedEndpoint
OAuthProvider
PHP Manual

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken — Generate a random token

Описание

final public static string OAuthProvider::generateToken ( int $size [, bool $strong = false ] )

Generates a string of pseudo-random bytes.

Список параметров

size

The desired token length, in terms of bytes.

strong

Setting to TRUE means /dev/random will be used for entropy, as otherwise the non-blocking /dev/urandom is used. This parameter is ignored on Windows.

Возвращаемые значения

The generated token, as a string of bytes.

Ошибки

If the strong parameter is TRUE, then an E_WARNING level error will be emitted when the fallback rand() implementation is used to fill the remaining random bytes (e.g., when not enough random data was found, initially).

Примеры

Пример #1 OAuthProvider::generateToken() example

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t),  PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

Результатом выполнения данного примера будет что-то подобное:

4
b6a82c27

Примечания

Замечание:

When not enough random data is available to the system, this function will fill the remaining random bytes using the internal PHP rand() implementation.

Смотрите также

  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • mcrypt_create_iv() - Creates an initialization vector (IV) from a random source

User Contributed Notes

carlosouza at me dot com 28-Mar-2012 02:32
Be careful when setting the 'strong' parameter to true.

If you system doesn't have enough entropy your script will block which can cause timeouts in other parts of your code.

In my case, the most serious symptom was my script blocking when trying to read from /dev/random and causing a 'MySQL has gone away' error.

Hopefully this saves someone the trouble when deciding to use /dev/random entropy
OAuthProvider::consumerHandler
OAuthProvider::is2LeggedEndpoint
OAuthProvider


is2LeggedEndpoint

OAuthProvider::generateToken
OAuthProvider::isRequestTokenEndpoint
OAuthProvider
PHP Manual

OAuthProvider::is2LeggedEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint

Описание

public void OAuthProvider::is2LeggedEndpoint ( mixed $params_array )

The 2-legged flow, or request signing. It does not require a token.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

params_array

Возвращаемые значения

An OAuthProvider object.

Примеры

Пример #1 OAuthProvider::is2LeggedEndpoint() example

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

Смотрите также

  • OAuthProvider::__construct() - Constructs a new OAuthProvider object

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::generateToken
OAuthProvider::isRequestTokenEndpoint
OAuthProvider


Sets isRequestTokenEndpoint

OAuthProvider::is2LeggedEndpoint
OAuthProvider::removeRequiredParameter
OAuthProvider
PHP Manual

OAuthProvider::isRequestTokenEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint

Описание

public void OAuthProvider::isRequestTokenEndpoint ( bool $will_issue_request_token )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

will_issue_request_token

Sets whether or not it will issue a request token, thus determining if OAuthProvider::tokenHandler() needs to be called.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • OAuthProvider::setRequestTokenPath() - Set request token path
  • OAuthProvider::reportProblem() - Report a problem

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::is2LeggedEndpoint
OAuthProvider::removeRequiredParameter
OAuthProvider


Remove a required parameter

OAuthProvider::isRequestTokenEndpoint
OAuthProvider::reportProblem
OAuthProvider
PHP Manual

OAuthProvider::removeRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::removeRequiredParameter — Remove a required parameter

Описание

final public bool OAuthProvider::removeRequiredParameter ( string $req_params )

Removes a required parameter.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

req_params

The required parameter to be removed.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • OAuthProvider::setParam() - Set a parameter
  • OAuthProvider::addRequiredParameter() - Add required parameters

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::isRequestTokenEndpoint
OAuthProvider::reportProblem
OAuthProvider


Report a problem

OAuthProvider::removeRequiredParameter
OAuthProvider::setParam
OAuthProvider
PHP Manual

OAuthProvider::reportProblem

(PECL OAuth >= 1.0.0)

OAuthProvider::reportProblem — Report a problem

Описание

final public static string OAuthProvider::reportProblem ( string $oauthexception [, bool $send_headers = true ] )

Pass in a problem as an OAuthException, with possible problems listed in the OAuth constants section.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

oauthexception

The OAuthException.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • OAuthProvider::checkOAuthRequest() - Check an oauth request
  • OAuthProvider::isRequestTokenEndpoint() - Sets isRequestTokenEndpoint

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::removeRequiredParameter
OAuthProvider::setParam
OAuthProvider


Set a parameter

OAuthProvider::reportProblem
OAuthProvider::setRequestTokenPath
OAuthProvider
PHP Manual

OAuthProvider::setParam

(PECL OAuth >= 1.0.0)

OAuthProvider::setParam — Set a parameter

Описание

final public bool OAuthProvider::setParam ( string $param_key [, mixed $param_val ] )

Sets a parameter.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

param_key

The parameter key.

param_val

The optional parameter value.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • OAuthProvider::addRequiredParameter() - Add required parameters

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::reportProblem
OAuthProvider::setRequestTokenPath
OAuthProvider


Set request token path

OAuthProvider::setParam
OAuthProvider::timestampNonceHandler
OAuthProvider
PHP Manual

OAuthProvider::setRequestTokenPath

(PECL OAuth >= 1.0.0)

OAuthProvider::setRequestTokenPath — Set request token path

Описание

final public bool OAuthProvider::setRequestTokenPath ( string $path )

Sets the request tokens path.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

path

The path.

Возвращаемые значения

TRUE

Смотрите также

  • OAuthProvider::tokenHandler() - Set the tokenHandler handler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::setParam
OAuthProvider::timestampNonceHandler
OAuthProvider


Set the timestampNonceHandler handler callback

OAuthProvider::setRequestTokenPath
OAuthProvider::tokenHandler
OAuthProvider
PHP Manual

OAuthProvider::timestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback

Описание

public void OAuthProvider::timestampNonceHandler ( callable $callback_function )

Sets the timestamp nonce handler callback, which will later be called with OAuthProvider::callTimestampNonceHandler(). Errors related to timestamp/nonce are thrown to this callback.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

callback_function

The callable functions name.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Example OAuthProvider::timestampNonceHandler() callback

<?php
function timestampNonceChecker($provider) {

    if ($provider->nonce === 'bad') {
        return OAUTH_BAD_NONCE;
    } elseif ($provider->timestamp == '0') {
        return OAUTH_BAD_TIMESTAMP;
    }

    return OAUTH_OK;
}
?>

Смотрите также

  • OAuthProvider::callTimestampNonceHandler() - Calls the timestampNonceHandler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::setRequestTokenPath
OAuthProvider::tokenHandler
OAuthProvider


Set the tokenHandler handler callback

OAuthProvider::timestampNonceHandler
OAuthException
OAuthProvider
PHP Manual

OAuthProvider::tokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::tokenHandler — Set the tokenHandler handler callback

Описание

public void OAuthProvider::tokenHandler ( callable $callback_function )

Sets the token handler callback, which will later be called with OAuthProvider::callTokenHandler().

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

callback_function

The callable functions name.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Example OAuthProvider::tokenHandler() callback

<?php
function tokenHandler($provider) {

    if ($provider->token === 'rejected') {
        return OAUTH_TOKEN_REJECTED;
    } elseif ($provider->token === 'revoked') {
        return OAUTH_TOKEN_REVOKED;
    }

    $provider->token_secret = "the_tokens_secret";
    return OAUTH_OK;
}
?>

Смотрите также

  • OAuthProvider::callTokenHandler() - Calls the tokenNonceHandler callback

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::timestampNonceHandler
OAuthException
OAuthProvider


OAuthException class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

This exception is thrown when exceptional errors occur while using the OAuth extension and contains useful debugging information.

Обзор классов

OAuthException extends Exception {
/* Свойства */
public $lastResponse ;
public $debugInfo ;
/* Наследуемые методы */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Свойства

message

A human readable message about what went wrong

code

Exception code

file

File where exception was thrown

line

File where exception was thrown

lastResponse

The response of the exception which occurred, if any

debugInfo

User Contributed Notes

There are no user contributed notes for this page.
OAuthProvider::tokenHandler
SCA
OAuth


SCA

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • The structure of a Service Component
    • Obtaining a proxy for another Service Component
    • Calling another Service Component
    • Locating and calling services from a script which is not an SCA Component
    • Exposing a Service Component as a Web service
    • Deploying an SCA component
    • Obtaining the WSDL for an SCA component offering a Service as a Web service
    • Understanding how the WSDL is generated
    • Working with Data Structures
    • Error handling
  • SCA Функции
    • SCA::createDataObject — create an SDO
    • SCA::getService — Obtain a proxy for a service
    • SCA_LocalProxy::createDataObject — create an SDO
    • SCA_SoapProxy::createDataObject — create an SDO

User Contributed Notes

There are no user contributed notes for this page.
OAuthException
Введение
Веб-сервисы


Введение

Внимание

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и любую другую относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

SCA for PHP makes it possible for a PHP programmer to write reusable components, which can be called in a variety of ways, with an identical interface and with a minimum of fuss. At present components can call each other either locally or via Web services, but in the future it is expected that other ways will be possible. It provides the programmer with a way of doing this which will look as natural as possible in PHP.

SCA components use phpDocumentor-style (see http://www.phpdoc.org/) annotations to declare dependencies on other SCA components or Web services. The SCA for PHP runtime resolves these dependencies at runtime on behalf of the components, and thus allows the PHP programmer to focus on the business logic rather than on locating and obtaining references to dependencies.

The SCA for PHP programming model can be extended to support a number of service types, such as REST and Atompub. However, Web services (more accurately, WSDL defined, SOAP/HTTP services), are the only type currently specified.

Components also use annotations to define the interface which they expose as a service. The SCA for PHP runtime will automatically generate WSDL from these annotations, so that an SCA component is easily exposed as a web service. These annotations are a natural extension to those provided by phpDocumentor. Deploying a Web service can be as simple as placing a PHP component under the document root of a web server.

Components also use annotations to specify data structures (expressed using XML schema complex types) which are then handled using Service Data Objects (SDOs).

A PHP script which is not an SCA component and which contains no annotations can use the services of an SCA component. A PHP script or component can make calls to a web service that is not an SCA component, but using the same system of calls or annotations to obtain a reference.

First we show a single SCA component, ConvertedStockQuote which illustrates many of the features of SCA for PHP. It has one method, getQuote(), which given a stock "ticker" obtains a price quote for that stock, converted to a given currency. We shall be using this example as a basis for explaining the SCA for PHP throughout the rest of this document.

Пример #1 A sample SCA component

<?php

include "SCA/SCA.php";

/**
 * Calculate a stock price for a given ticker symbol in a given currency.
 *
 * @service
 * @binding.soap
 */
class ConvertedStockQuote {

    /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;

    /**
     * The stock quote service to use.
     *
     * @reference
     * @binding.soap ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;

    /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this->stock_quote->getQuote($ticker);
        $rate   = $this->exchange_rate->getRate($currency);
        return  $rate * $quote;
    }
}
?>

In this example, we see that an SCA component is implemented by a script containing a PHP class and includes SCA.php. The class contains a mixture of business logic and references to other components or services. In the illustrated getQuote() method there is only business logic, but it relies on the instance variables $stock_quote and $exchange_rate having been initialized. These refer to two other components and will be initialized by the SCA runtime with proxies for these two services, whenever this component executes. The annotations for these two services show one to be a local component, which will be called within the same PHP runtime, and one to be a remote component which will be called via a SOAP request. This component also exposes the getQuote() method both locally and as a web service, so it in turn can be called either locally or remotely.

User Contributed Notes

There are no user contributed notes for this page.
SCA
Установка и настройка
SCA


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
SCA


Требования

If you want to use SCA to consume or produce Web services then you need PHP 5.2.0 or later, built with the soap extension enabled. If you just want to use local components, and do not wish to use the Web service bindings, then this version of SCA for PHP will also run with PHP 5.1.6.

SCA is packaged along with SDO in one combined package on PECL. See http://www.php.net/sdo#sdo.installation for installing the SCA_SDO package from PECL. The SCA code must be on the include path of your PHP installation, for example if it is installed as /usr/local/lib/php/SCA, the include_path directive must include /usr/local/lib/php

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pecl.php.net/package/sca.

DLL для этого расширения PECL в данный момент недоступна. См. также раздел сборка на Windows.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
SCA


Примеры

Содержание

  • The structure of a Service Component
  • Obtaining a proxy for another Service Component
  • Calling another Service Component
  • Locating and calling services from a script which is not an SCA Component
  • Exposing a Service Component as a Web service
  • Deploying an SCA component
  • Obtaining the WSDL for an SCA component offering a Service as a Web service
  • Understanding how the WSDL is generated
  • Working with Data Structures
  • Error handling

The examples in the subsequent sections illustrate the following aspects of PHP for SCA:

  • How PHP annotations are used to define PHP classes as SCA components, and how annotations are used to define the services.

  • How an SCA component can be exposed as a Web service

  • How an SCA component can consume a Web service, whether provided by another SCA component or by some other service which knows nothing of SCA

  • How an SCA component can call another SCA component locally (within the same process and on the same call stack)

  • How a client script which is not an SCA component can use the getService call to obtain a proxy for an SCA component.

  • How data structures such as Addresses, or Puchase Orders, are represented as Service Data Objects, and handled.

  • How SCA components are deployed, and in particular how and when WSDL is generated for a service.

  • How parameters are always passed by value (and not by reference) between components, even when the calls are local. This ensures that the semantics of a call do not change depending on the location of a component.

  • How positional parameters to a service are supported, even when the underlying WSDL is document literal wrapped, and naturally supports only named parameters.

  • How business and runtime exceptions are handled.

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
The structure of a Service Component
SCA


The structure of a Service Component

A service component is implemented by a class. To identify it as a service component, it contains an @service annotation. The SCA runtime will use the file name of the script to determine the component name, by convention. The class and script file must therefore share the same name.

PHP SCA components always expose a service, and there is no way for a component to be invoked other than to be called as a result of a Web service request, or called directly from another component or from a script. For this reason a valid PHP SCA component will always contain an @service annotation and at least one public method.

Each SCA Component requires that the SCA.php script is included. As well as containing the definition of the SCA class, this script contains executable PHP code that will run whenever the script is called, and which will be responsible for making the component behave as needed.

Предостережение

It is very important that if your file contains other includes, they come before the include for SCA.php. If there are includes after the include for SCA.php, they will not have been processed when the SCA runtime runs your class.

The example below illustrates this overall structure

Пример #1 The structure of an SCA for PHP component

<?php

// any includes

include "SCA/SCA.php";

/**
 * @service
 */

class ConvertedStockQuote {

       // instance variables, business logic, including at least one public method

}
?>

User Contributed Notes

There are no user contributed notes for this page.
Примеры
Obtaining a proxy for another Service Component
Примеры


Obtaining a proxy for another Service Component

One SCA component can call the service provided by another SCA component. The service a component provides is made up of all of its public methods. SCA for PHP currently provides two ways for one component to call another: either locally (i.e. within the same PHP run-time, and on the same call stack) or remotely if the called component exposes a Web service binding.

In order for one component to call another, the calling component needs a proxy for the called component. This proxy is usually provided as an instance variable in the calling component, though proxies can also be obtained with the SCA::getService() call, as we shall see later. When a component is constructed, proxies are constructed for any instance variable which refer to another component, and these proxies are "injected" into the instance variables. Proxies are always used, whether the component is local or remote, in order to provide identical calling behavior between remote and local calls (for example, local calls are made to always pass data by-value). The proxies know how to locate the required component and to pass the calls made on to them.

Instance variables which are intended to hold proxies for services are indicated by the two PHPDocumentor-style annotations, @reference and @binding. Both annotations are placed in the documentation section for a class instance variable, as shown by the code below.

The @reference annotation before an instance variable indicates that the instance variable is to be initialized with a proxy to a component.

The @binding annotation has two forms @binding.php and @binding.soap, and indicates that the proxy is either for a local component or for a Web service respectively. For both @binding.php and @binding.soap, the annotation gives a target URI.

At the moment, with the annotation-based method of specifying dependencies, the only way to alter the intended target of a reference is to alter the annotation within the component.

In our ConvertedStockQuote example, the $exchange_rate instance variable will be initialized with a proxy to the local ExchangeRate component whenever an instance of the ConvertedStockQuote is constructed.

Пример #1 Obtaining a proxy for a local PHP class

<?php
   /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;
?>

For @binding.php, the URI identifies the location of the script containing the implementation of the component. The component will be called locally. The service provided is the set of public methods of the component. The URI must be a simple pathname, either absolute or relative. The component will be loaded with the PHP include directive, after testing to see if it is already loaded with class_exists(). If the URI is a relative path, it is resolved relative to the component containing the annotation. Note that this is different from the normal PHP behaviour where scripts would be looked for along the PHP include_path, This is intended to provide some location-independence for cross-component references.

If this ExchangeRate service were remote and to be called as a Web service, only the @binding line changes. Instead of giving the location of a PHP class, it gives the location of the WSDL describing the web service. In our example component, this is illustrated by the second reference:

Пример #2 Obtaining a proxy for a web service

<?php
/**
     * The stock quote service to use.
     *
     * @reference
     * @binding.soap ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;
?>

The StockQuote component will be called via a Web service request. In this case the URI for the WSDL can be a simple pathname, or may contain a PHP wrapper and begin, for example, with file:// or http://. In the event that it is a simple pathname, it can be absolute or relative, and if relative will be resolved relative to the component containing the annotation. Note that this is like the behaviour for @binding.php, and different from the normal PHP behaviour where the file would be looked for relative to the PHP current working directory, which would usually be the location of the first script to be called. This behaviour is intended to give consistency across the different bindings and to provide some location-independence for references between components.

User Contributed Notes

There are no user contributed notes for this page.
The structure of a Service Component
Calling another Service Component
Примеры


Calling another Service Component

The ConvertedStockQuote example also calls the proxies for the two components to which it refers.

Пример #1 Calling services

<?php
$quote  = $this->stock_quote->getQuote($ticker);
$rate   = $this->exchange_rate->getRate($currency);
?>

The call to the StockQuote service is a call to a local service; the call to the ExchangeRate service is a call to a remote service. Note that the way the call is made looks the same regardless of whether the call is to a local service or a remote one.

The proxies which have been injected ensure that the way calls to components look and behave are the same way regardless of whether they are to a local or remote service, so that components are not sensitive to whether a call is to a local or a remote service. For example, the proxy for a local service takes copies of the arguments and passes only those copies, to ensure that calls are made to be pass-by-value, as they would be for a remote call. Also, the proxy for a remote service takes the arguments from a positional parameter list and ensures they are packaged properly in a SOAP request and converted back to a positional parameter list at the far end.

In the example above, the $ticker and $currency are clearly PHP scalar types. Components can pass the PHP scalar types string, integer, float and boolean, but data structures on service calls are always passed as Service Data Objects (SDOs). A later section describes how a component can create an SDO to pass on a local or Web service call, or how a component can create an SDO to return. The PHP SDO project documentation describes how to work with the SDO APIs (see the SDO pages).

User Contributed Notes

There are no user contributed notes for this page.
Obtaining a proxy for another Service Component
Locating and calling services from a script which is not an SCA Component
Примеры


Locating and calling services from a script which is not an SCA Component

SCA components obtain proxies for other components or services as instance variables annotated with @reference, but this is not possible for a script that is not itself also a component. A client script which is not a component must use the SCA::getService() static method to obtain a proxy for a service, whether local or remote. The getService() method takes a URI as the argument. Typically this is the location of a local PHP script containing a component, or of a wsdl file, and is used in exactly the same way as the targets of the @binding annotations described in the previous section: that is, relative URIs are resolved against the location of the client script and not against the PHP include_path or current working directory.

For example, a script that needed to obtain proxies for the ExchangeRate and StockQuote services but was not a component would use the getService() method as follows:

Пример #1 Obtaining a proxy using getService

<?php
$exchange_rate = SCA::getService('../ExchangeRate/ExchangeRate.php');
$stock_quote   = SCA::getService('../StockQuote/StockQuote.wsdl');
?>

Methods on services can then be called on the returned proxy, just as they can in a component.

Пример #2 Making calls on the proxy

<?php
$quote  = $stock_quote->getQuote($ticker);
$rate   = $exchange_rate->getRate($currency);
?>

User Contributed Notes

There are no user contributed notes for this page.
Calling another Service Component
Exposing a Service Component as a Web service
Примеры


Exposing a Service Component as a Web service

SCA for PHP can generate WSDL from the annotations within a service component, so that it can be easily deployed and exposed as a Web service. To provide SCA with the information it needs to generate the WSDL, it is necessary to add the annotation @binding.soap under the @service annotation and to specify the parameters and return values of the methods using the @param and @return annotations. These annotations will be read when WSDL is generated, and the order and types of the parameters determine the contents of the <schema> section of the WSDL.

SCA for PHP always generates document/literal wrapped WSDL for components that are exposing a Web service. Note that this does not stop components from consuming Web services which are not SCA components and which are documented with WSDL written in a different style.

The scalar types which can be used in the @param annotation are the four common PHP scalar types: boolean, integer, float and string. These are simply mapped to the XML schema types of the same name in the WSDL. The example below, which is a trivial implementation of the StockQuote service that the ConvertedStockQuote component calls, illustrates string and float types.

Пример #1 StockQuote Service

<?php

include "SCA/SCA.php";

/**
 * Scaffold implementation for a remote StockQuote Web service.
 *
 * @service
 * @binding.soap
 *
 */
class StockQuote {

    /**
     * Get a stock quote for a given ticker symbol.
     *
     * @param string $ticker The ticker symbol.
     * @return float The stock quote.
     */
    function getQuote($ticker) {
        return 80.9;
  }
}
?>

WSDL much like the following (though with a service location other than 'localhost', probably) would be generated from this service:

Пример #2 Generated WSDL

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xsi:type="tDefinitions"
    xmlns:tns2="http://StockQuote" xmlns:tns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:tns3="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" targetNamespace="http://StockQuote">
  <types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://StockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

  <message name="getQuoteRequest">
    <part name="getQuoteRequest" element="tns2:getQuote"/>
  </message>
  <message name="getQuoteResponse">
    <part name="return" element="tns2:getQuoteResponse"/>
  </message>
  <portType name="StockQuotePortType">
    <operation name="getQuote">
      <input message="tns2:getQuoteRequest"/>
      <output message="tns2:getQuoteResponse"/>
    </operation>
  </portType>
  <binding name="StockQuoteBinding" type="tns2:StockQuotePortType">
    <operation name="getQuote">
      <input>
        <tns3:body xsi:type="tBody" use="literal"/>
      </input>
      <output>
        <tns3:body xsi:type="tBody" use="literal"/>
      </output>
      <tns3:operation xsi:type="tOperation" soapAction=""/>
    </operation>
    <tns3:binding xsi:type="tBinding" transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
  </binding>
  <service name="StockQuoteService">
    <port name="StockQuotePort" binding="tns2:StockQuoteBinding">
      <tns3:address xsi:type="tAddress" location="http://localhost/StockQuote/StockQuote.php"/>
    </port>
  </service>
</definitions>

<!-- this line identifies this file as WSDL generated by SCA for PHP. Do not remove -->

User Contributed Notes

deadguysfrom at gmail dot com 31-Jul-2009 11:44
In order for SCA to find the service class, the script filename must match the service class name.  In this case, StockQuote.php
Locating and calling services from a script which is not an SCA Component
Deploying an SCA component
Примеры


Deploying an SCA component

There are no special steps needed to deploy a PHP SCA component. It is sufficient to place the component PHP script in its proper place under the web server document root, just like any other PHP script. It is the SCA::initComponent() executable line within each component that will be executed whenever the script is called, and which will be responsible for making the component respond appropriately to Web service calls, local calls, or requests for WSDL.

User Contributed Notes

There are no user contributed notes for this page.
Exposing a Service Component as a Web service
Obtaining the WSDL for an SCA component offering a Service as a Web service
Примеры


Obtaining the WSDL for an SCA component offering a Service as a Web service

SCA components that expose a Web service interface (i.e. have an @binding.soap annotation) will return their WSDL definition in response to an HTTP request with a get parameter of "wsdl". The usual way to obtain this is with "?wsdl" on the end of a URL. The example below uses file_get_contents() to obtain WSDL from a service and writes it to a temporary file before then obtaining a proxy for the service in the usual way. You could of course also obtain the WSDL in a browser, or by some other means, and save the file yourself.

Пример #1 Generated WSDL

<?php
$wsdl = file_get_contents('http://www.example.com/Services/Example.php?wsdl');
file_put_contents("service.wsdl",$wsdl); //write the wsdl to a file
$service = SCA::getService('service.wsdl');
?>

NOTE: If the wsdl requires imported xsds, these will need to be fetched separately.

User Contributed Notes

There are no user contributed notes for this page.
Deploying an SCA component
Understanding how the WSDL is generated
Примеры


Understanding how the WSDL is generated

SCA for PHP generates WSDL for components which contain an @binding.soap annotation after the @service annotation. To generate WSDL, the SCA runtime reflects on the component and examines the @param and @return annotations for each public method, as well as any @types annotations within the component. The information from the @param and @return annotations is used to build the <types> section of the WSDL. Any @types annotations which specify a separate schema file will result in an <import> element for that schema within the WSDL.

Location attribute of the <service> element

At the bottom of the WSDL is the <service> element which uses the location attribute to identify the URL of the service. For example this might look as follows:

Пример #1 location attribute

<service name="ConvertedStockQuote"
...
location="http://localhost/ConvertedStockQuote/ConvertedStockQuote.php"/>

Note that this location is relative to the document root of the web server, and cannot be worked out in advance. It can only be worked out once the component is in its proper place under a running web server, when the hostname and port can be known and placed in the WSDL. Detail from the URL that requests the WSDL is used, so for example if the WSDL is generated in response to a request to http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php?wsdl, a location of http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php is what will be inserted into the location attribute in the WSDL.

Document/literal wrapped WSDL and positional parameters

SCA for PHP generates WSDL in the document/literal wrapped style. This style encloses the parameters and return types of a method in 'wrappers' which are named after the corresponding method. The <types> element at the top of the WSDL defines each of these wrappers. If we consider the getQuote() method of the ConvertedStockQuote example:

Пример #2 method with two arguments

<?php
   /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this->stock_quote->getQuote($ticker);
        $rate   = $this->exchange_rate->getRate($currency);
        return  $rate * $quote;
    }
?>

The WSDL generated to define this method will name both the method and the parameters, and give an XML schema type for the parameters. The types section of the WSDL looks like this:

Пример #3 types section illustrating named parameters

<types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://ConvertedStockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
            <xs:element name="currency" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

The SCA run-time has special processing to handle how positional parameter lists in the interface are converted to XML containing named parameters in the soap request, and then back to positional parameter lists again. To see why this matters, consider how a PHP script which used a different interface to make a SOAP call would need to construct the parameter list. A PHP script using the PHP SoapClient, for example, would need to pass the SoapClient a single parameter giving the values for "ticker" and "currency", perhaps as an associative array. To insist that SCA components construct parameter lists to make Web service calls in this way would be to make local and remote calls look different, so a different approach is needed.

When SCA generates WSDL for an SCA component it includes a comment in the WSDL which marks that WSDL as being the interface for an SCA component. In this case, when one SCA component calls another through a Web service, the SCA runtime on the calling end takes the positional parameter list from the call and assigns the values one by one to the named elements in the soap message. For example a call to the getQuote() method defined above that passes the values 'IBM' and 'USD' and looks like this:

<?php
  $quote = $remote_service->getQuote('IBM','USD');
?>

will result in a soap message containing the following:

<getQuote>
  <ticker>IBM</ticker>
  <currency>USD</currency>
</getQuote>

On the service-providing end, the SCA run-time takes the parameters one by one from the soap message and forms a positional parameter list from them, re-forming the argument list ('IBM','USD').

Предостережение

At both ends the SCA runtime relies on the order in which the parameters appear in the soap message being the same as that in the target method's parameter list. This is ultimately determined by the order of the @param annotations: this determines the order in which the parameters appear in the WSDL and thereby the order in which they appear in the soap message. Therefore it is essential that the order of the @param annotations matches that of the parameters in the method's parameter list.

User Contributed Notes

There are no user contributed notes for this page.
Obtaining the WSDL for an SCA component offering a Service as a Web service
Working with Data Structures
Примеры


Working with Data Structures

SCA components can pass and return the four PHP scalar types boolean, integer, float and string, but to pass or return data structures, SCA components use Service Data Objects (SDOs). SDOs are described in much more detail in the SDO pages of this manual. Readers familiar with SDOs will know that they are suitable for representing the sort of structured and semi-structured data that is frequently modeled in XML, and that they serialize very naturally for passing between remote components, or in Web services. SDOs are presently the only supported way to pass and return data structures. It is not possible to pass or return PHP objects, or PHP arrays.

The SCA runtime always assures data is passed by-value, even for local calls. To do this, the SCA runtime copies any SDOs in the parameter list before passing them on, just as it does for scalar types.

How data structures are defined to SCA components

Currently the only mechanism for specifying the location of a data structure definition is by specifying the types in an XML schema file. However, in the future it may be possible to define types in other ways, such as based on PHP classes or interfaces, or based on definitions expressed as associative arrays.

To illustrate the use of SDOs we introduce a new component. The PortfolioMangement service below returns an SDO representing a stock portfolio for a given customer.

Пример #1 A Component that uses Data Structures

<?php

include "SCA/SCA.php";

/**
 * Manage the portfolio for a customer.
 *
 * @service
 * @binding.soap
 *
 * @types http://www.example.org/Portfolio PortfolioTypes.xsd
 *
 */
class PortfolioManagement {

    /**
     * Get the stock portfolio for a given customer.
     *
     * @param integer $customer_id The id for the customer
     * @return Portfolio http://www.example.org/Portfolio The stock portfolio (symbols and quantities)
     */
    function getPortfolio($customer_id) {
        // Pretend we just got this from a database
        $portfolio = SCA::createDataObject('http://www.example.org/Portfolio', 'Portfolio');
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'AAPL';
        $holding->number = 100.5;
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'INTL';
        $holding->number = 100.5;
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'IBM';
        $holding->number = 100.5;
        return $portfolio;
    }

}
?>

The @types annotation:

<?php
@types http://www.example.org/Portfolio PortfolioTypes.xsd
?>

indicates that types in the namespace http://www.example.org/Portfolio will be found in the schema file located by the URI PortfolioTypes.xsd. The generated WSDL would reproduce this information with an import statement as follows:

<xs:import schemaLocation="PortfolioTypes.xsd"
                      namespace="http://www.example.org/Portfolio"/>

so the URI, absolute or relative, must be one that can be resolved when included in the schemaLocation attribute.

Creating SDOs

Readers familiar with SDOs will know that they are always created according to a description of the permitted structure (sometimes referred to as the 'schema' or 'model') and that, rather than creating them directly using 'new', some form of data factory is needed. Often, an existing data object can be used as the data factory, but sometimes, and especially in order to get the first data object, something else must act as the data factory.

In SCA, either the SCA runtime class or the proxies for services, whether local or remote, can act as the data factories for SDOs. The choice of which to use, and when, is described in the next two sections.

We switch to a new example in order to illustrate the creation of SDOs, both to pass to a service, and to be returned from a service.

Creating an SDO to pass to a service

A caller of a service which requires a data structure to be passed in to it uses the proxy to the service as the data factory for the corresponding SDOs. For example, suppose a component makes use of a proxy for a service provided by a local AddressBook component.

<?php
/**
 * @reference
 * @binding.local AddressBook.php
 */
$address_book;
?>

The AddressBook component that it wishes to call is defined as follows:

<?php
/**
* @service
* @binding.soap
* @types http://addressbook ../AddressBook/AddressBook.xsd
*/
class AddressBook {

    /**
     * @param personType $person http://addressbook (a person object)
     * @return addressType http://addressbook (the address object for the person object)
     */
    function lookupAddress($person)  {
        ...
    }
}
?>

The AddressBook component provides a service method called lookupAddress() which uses types from the http://addressbook namespace. The lookupAddress method takes a personType data structure and returns an addressType. Both types are defined in the schema file addressbook.xsd.

Once the component that wishes to use the AddressBook component has been constructed, so that the $address_book instance variable contains a proxy for the service, the calling component can use the proxy in $address_book to create the person SDO, as shown below:

<?php
$william_shakespeare        = $address_book->createDataObject('http://addressbook','personType');
$william_shakespeare ->name = "William Shakespeare";
$address                    = $address_book->lookupAddress($william_shakespeare);
?>

Note, the use of the proxy as the means to create the SDO is not limited to SCA components. If a service is being called from a general PHP script, and the proxy was obtained with getService() then the same approach is used.

<?php
$address_book = SCA::getService('AddressBook.php');
$william_shakespeare = $address_book->createDataObject('http://addressbook','personType');
?>

Creating an SDO to return from a component

A component that needs to create a data object for return to a caller will not have a proxy to use as a data object, In this case it uses the createDataObject() static method on SCA.php. Hence if the AddressBook component described above needed to create an object of type addressType within the namespace http://addressbook, it might do so as follows:

<?php
$address = SCA::createDataObject('http://addressbook','addressType');
?>

User Contributed Notes

There are no user contributed notes for this page.
Understanding how the WSDL is generated
Error handling
Примеры


Error handling

This section describes how errors are handled. There are two types of errors:

  • SCA runtime exceptions are those that signal problems in the management of the execution of components, and in the interaction with remote services. These might occur due to network or configuration problems.

  • Business exceptions are those that are defined by the programmer. They extend the PHP Exception class, and are thrown and caught deliberately as part of the business logic.

Handling of Runtime exceptions

There are two types of SCA runtime exception:

  • SCA_RuntimeException - signals a problem found by or perhaps occurring within the SCA runtime. This can be thrown for a variety of reasons, many of which can occur regardless of whether a connection is being made to a local or a remote service: an error in one of the annotations within a component, a missing WSDL or php file, and so on. In the case of Web services, an SCA_RuntimeException can also be thrown if a SoapFault is received from a remote Web service and the fault code in the SoapFault indicates that a retry is unlikely to be successful.

  • SCA_ServiceUnavailableException - this is a subclass of SCA_RuntimeException and signals a problem in connecting to or using a remote service, but one which might succeed if retried. In the case of Web services, this exception is thrown if a SoapFault is received with a fault code that indicates that a retry might be successful.

Handling of Business exceptions

Business exceptions may be defined and thrown by a component in the normal way, regardless of whether the component has been called locally or remotely. The SCA runtime does not catch business exceptions that have been thrown by a component called locally, so they will be returned to a caller in the normal way. If a component has been called via a Web service, on the other hand, the SCA runtime on the service providing end does catch business exceptions, and will ensure these are passed back to the calling end and re-thrown. Assuming that the calling end has a definition of the exception (that is, is able to include a file containing the PHP class defining the exception) the re-thrown exception will contain the same details as the original, so that the getLine() and getFile() methods for example will contain the location where the exception was thrown within the business logic. The exception will be passed in the detail field of a soap fault with a fault code of "Client".

User Contributed Notes

There are no user contributed notes for this page.
Working with Data Structures
SCA Функции
Примеры


Error handling
SCA::createDataObject
SCA
PHP Manual

SCA Функции

Предопределенные классы

Most of the interface to SCA is through the annotations within SCA components so there are few public classes and methods. The only SCA classes that scripts or components can call are the SCA class itself, and the proxy classes SCA_LocalProxy and SCA_SoapProxy.

SCA

Much of the work of the SCA class is performed when the file SCA.php is included within an SCA component. However, a PHP script may include SCA.php and call the getService() method on the SCA class in order to obtain a proxy for a service. A component will not need to do this as proxies are obtained instead by defining an instance variable with the @reference annotation.

Components that need to create an SDO to return to a caller will need a data factory to call. For this purpose the SCA class supports the createDataObject() method, which will create an SDO according to the model defined by the component's @types annotations. The arguments to createDataObject() are the same as those to SDO's XML Data Access Service.

Методы

  • getService - obtain a proxy for a service

  • createDataObject - create an SDO

SCA_LocalProxy

When getService() is called with the target of a local PHP component, a local proxy is returned. A local proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.php anotation. When the script or component makes calls on the local proxy, they are passed on to the target component itself.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_LocalProxy class supports the createDataObject() method, which will create an SDO according to the model defined by the components' @types annotations. The arguments to the createDataObject() are the same as those to SDO's XML Data Access Service.

Методы

  • createDataObject - create an SDO

SCA_SoapProxy

When getService() is called with the target of a WSDL file, a SOAP proxy is returned. A SOAP proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.soap anotations. When the script or component makes calls on the SOAP proxy, they are formed into Web service SOAP requests and passed on to the target component, with the help of the PHP Soap extension.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_SoapProxy class supports the createDataObject() method, which will create an SDO according to the model defined within the target WSDL. The arguments to the createDataObject() are the same as those to SDO's XML Data Access Service.

Методы

  • createDataObject - create an SDO

Содержание

  • SCA::createDataObject — create an SDO
  • SCA::getService — Obtain a proxy for a service
  • SCA_LocalProxy::createDataObject — create an SDO
  • SCA_SoapProxy::createDataObject — create an SDO

User Contributed Notes

There are no user contributed notes for this page.
Error handling
SCA::createDataObject
SCA
PHP Manual


create an SDO

SCA Функции
SCA::getService
SCA Функции
PHP Manual

SCA::createDataObject

(PECL SDO >= 0.5.0)

SCA::createDataObject — create an SDO

Описание

SDO_DataObject SCA::createDataObject ( string $type_namespace_uri , string $type_name )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

This method is used inside an SCA component that needs to create an SDO to return. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in one of the schema files which are specified on the @types annotation within the component.

Список параметров

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Возвращаемые значения

Returns the newly created SDO_DataObject.

Ошибки

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations.

User Contributed Notes

There are no user contributed notes for this page.
SCA Функции
SCA::getService
SCA Функции


Obtain a proxy for a service

SCA::createDataObject
SCA_LocalProxy::createDataObject
SCA Функции
PHP Manual

SCA::getService

(PECL SDO >= 0.5.0)

SCA::getService — Obtain a proxy for a service

Описание

mixed SCA::getService ( string $target [, string $binding [, array $config ]] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Examine the target and initialize and return a proxy of the appropriate sort. If the target is for a local PHP component the returned proxy will be an SCA_LocalProxy. If the target is for a WSDL file, the returned proxy will be a SCA_SoapProxy.

Список параметров

target

An absolute or relative path to the target service or service description (e.g. a URL to a json-rpc service description, a PHP component, a WSDL file, and so on.). A relative path, if specified, is resolved relative to the location of the script issuing the getService() call, and not against the include_path or current working directory.

binding

The binding (i.e. protocol) to use to communicate with the service (e.g binding.jsonrpc for a json-rpc service). Note, some service types can be deduced from the target parameter (e.g. if the target parameter ends in .wsdl then SCA will assume binding.soap). Any binding which can be specified in an annotation can be specified here. For example 'binding.soap' is equivalent to the '@binding.soap' annotation.

config

Any additional configuration properties for the binding (e.g. array('location' => 'http://example.org')). Any binding configuration which can be specified in an annotation can be specified here. For example, 'location' is equivalent to the '@location' annotation to configure the location of a target soap service.

Возвращаемые значения

The SCA_LocalProxy or SCA_SoapProxy.

Примеры

Пример #1 An SCA::getService() example

This example shows how to get a proxy to an email soap service described by EmailService.wsdl and located at http://example.org.

<?php
include 'SCA/SCA.php';
$service = SCA::getService('EmailService.wsdl', 'binding.soap', array('location' => 'http://example.org'));
$service->send(...);
?>

Результат выполнения данного примера:

User Contributed Notes

There are no user contributed notes for this page.
SCA::createDataObject
SCA_LocalProxy::createDataObject
SCA Функции


create an SDO

SCA::getService
SCA_SoapProxy::createDataObject
SCA Функции
PHP Manual

SCA_LocalProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_LocalProxy::createDataObject — create an SDO

Описание

SDO_DataObject SCA_LocalProxy::createDataObject ( string $type_namespace_uri , string $type_name )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a local service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined in one of the schema files which are specified on the @types annotation within the component for which the SCA_LocalProxy object is a proxy.

Список параметров

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Возвращаемые значения

Returns the newly created SDO_DataObject.

Ошибки

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations within the component for which the SCA_LocalProxy object is a proxy..

User Contributed Notes

There are no user contributed notes for this page.
SCA::getService
SCA_SoapProxy::createDataObject
SCA Функции


create an SDO

SCA_LocalProxy::createDataObject
SOAP
SCA Функции
PHP Manual

SCA_SoapProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_SoapProxy::createDataObject — create an SDO

Описание

SDO_DataObject SCA_SoapProxy::createDataObject ( string $type_namespace_uri , string $type_name )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a web service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined within the WSDL for the web service. If the web service is also an SCA component then the types will have been defined within one of the schema files which are specified on the @types annotation within the component for which the SCA_SoapProxy object is a proxy.

Список параметров

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Возвращаемые значения

Returns the newly created SDO_DataObject.

Ошибки

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type found in the WSDL that was used to initialise this SCA_SoapProxy.

User Contributed Notes

There are no user contributed notes for this page.
SCA_LocalProxy::createDataObject
SOAP
SCA Функции


SOAP

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • SOAP Функции
    • is_soap_fault — Checks if a SOAP call has failed
    • use_soap_error_handler — Set whether to use the SOAP error handler
  • SoapClient — The SoapClient class
    • SoapClient::__call — Вызывает SOAP-функцию (устаревший)
    • SoapClient::__construct — Конструктор SoapClient
    • SoapClient::__doRequest — Выполняет SOAP-запрос
    • SoapClient::__getFunctions — Возвращает список доступных SOAP функций
    • SoapClient::__getLastRequest — Возвращает последний SOAP-запрос
    • SoapClient::__getLastRequestHeaders — Возвращает SOAP-заголовки последнего запроса
    • SoapClient::__getLastResponse — Возвращает последний SOAP-ответ
    • SoapClient::__getLastResponseHeaders — Возвращает SOAP-заголовки последнего ответа
    • SoapClient::__getTypes — Возвращает список SOAP-типов
    • SoapClient::__setCookie — Устанавливает cookie
    • SoapClient::__setLocation — Устанавливает адрес используемой веб-службы
    • SoapClient::__setSoapHeaders — Устанавливает SOAP-заголовки для последующих вызовов
    • SoapClient::__soapCall — Вызывает SOAP-функцию
    • SoapClient::SoapClient — Конструктор SoapClient
  • SoapServer — The SoapServer class
    • SoapServer::addFunction — Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader — Add a SOAP header to the response
    • SoapServer::__construct — SoapServer constructor
    • SoapServer::fault — Issue SoapServer fault indicating an error
    • SoapServer::getFunctions — Returns list of defined functions
    • SoapServer::handle — Handles a SOAP request
    • SoapServer::setClass — Устанавливает класс, который будет обрабатывать SOAP-запросы
    • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence — Sets SoapServer persistence mode
    • SoapServer::SoapServer — SoapServer constructor
  • SoapFault — The SoapFault class
    • SoapFault::__construct — SoapFault constructor
    • SoapFault::SoapFault — SoapFault constructor
    • SoapFault::__toString — Obtain a string representation of a SoapFault
  • SoapHeader — The SoapHeader class
    • SoapHeader::__construct — SoapHeader constructor
    • SoapHeader::SoapHeader — SoapHeader constructor
  • SoapParam — The SoapParam class
    • SoapParam::__construct — SoapParam constructor
    • SoapParam::SoapParam — SoapParam constructor
  • SoapVar — The SoapVar class
    • SoapVar::__construct — SoapVar constructor
    • SoapVar::SoapVar — SoapVar constructor

User Contributed Notes

rafinskipg at gmail dot com 14-May-2012 02:54
Support for MTOM addign this code to your project:

<?php
class MySoapClient extends SoapClient
{
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        // parse $response, extract the multipart messages and so on

        //this part removes stuff
        $start=strpos($response,'<?xml');
        $end=strrpos($response,'>');
        $response_string=substr($response,$start,$end-$start+1);
        return($response_string);
    }
}

?>

Then you can do this
<?php
  new MySoapClient($wsdl_url);
?>
dennis at pleasedontspam dot clansman dot nl 02-Dec-2011 03:53
When you receive the soapfault message: "looks like we got no XML document" it might be that you're talking to a server that supports MTOM (http://www.w3.org/TR/soap12-mtom/).

MTOM is, as of yet (5.3.6), not supported by the SoapClient.
Jadidi 13-Apr-2011 09:30
I needed to perform SOAP actions and get information from a Windows ASP.NET server and encountered many errors along the way.
At first I had it solved with NUSOAP, and sending my own XMLs with it, but then when I needed to use SSL it failed again.

So I went back to a regular SoapClient (as opposed to nusoap_client) and now I am using the WSDL defined functions ($client->function($params)).

The ASP.NET server I'm consuming is quite strange, the WSDL definition does not define the parameters I need to send, they only define one parameter and they expect me to send another XML within that.

So here's my solution, in case it helps anyone:
$params['trace'] = true;
$client = new soapclient('https://www.example.com/WebService.asmx?WSDL', $params);
$msg['AccountData']['any'] = "<somexml></somexml><otherxml></otherxml>";
$client->Function($msg);
$resulta = xml2array($client->__getLastResponse());
mariamr at gmail dot com 16-Oct-2010 06:38
“SOAP-ERROR: Parsing WSDL: Couldn’t find in ‘PATH/TO/YOUR/WSDL’”

This error occurs because some versions of PHP SOAP client  do not send the user name and password that you pass as the options input parameter of the SoapClient constructor  . Yu need to pass the credentials in the web service URL like this:
$soapClient =new SoapClient(“http://user:password@example.com/blahblah.wsdl”);
Warren 19-Jul-2010 10:44
It can be a nightmare trying to get all the details for a SOAP implementation into a handy class for PHP. If you are ever in this situation, thought I would let you know about a site that generates a PHP class ready to use with a SOAP server using native SoapClient in PHP 5. Its free to use, and can be found at www.apigenerator.com.
vishal dot thakkar at exateam dot com 22-Feb-2010 06:19
I was trying to figure out for days and days to make SOAP server return an associative array and NOT an object ....

To get an array (not object) in the SOAP response, just serialize the array before returning it to the clent..

hope it helps...
Thanks.....
Vishal Thakkar.
stephenlansell at gmail dot com 03-Feb-2010 07:19
Here is an example of a php client talking to a asmx server:

<?php

        $soapClient = new SoapClient("https://soapserver.example.com/blahblah.asmx?wsdl");

        // Prepare SoapHeader parameters
        $sh_param = array(
                    'Username'    =>    'username',
                    'Password'    =>    'password');
        $headers = new SoapHeader('http://soapserver.example.com/webservices', 'UserCredentials', $sh_param);

        // Prepare Soap Client
        $soapClient->__setSoapHeaders(array($headers));

        // Setup the RemoteFunction parameters
        $ap_param = array(
                    'amount'     =>    $irow['total_price']);

        // Call RemoteFunction ()
        $error = 0;
        try {
            $info = $soapClient->__call("RemoteFunction", array($ap_param));
        } catch (SoapFault $fault) {
            $error = 1;
            print("
            alert('Sorry, blah returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.". We will now take you back to our home page.');
            window.location = 'main.php';
            ");
        }

        if ($error == 0) {
            $auth_num = $info->RemoteFunctionResult;

            if ($auth_num < 0) {
                ....

                // Setup the OtherRemoteFunction() parameters
                $at_param = array(
                            'amount'        => $irow['total_price'],
                            'description'    => $description);

                // Call OtherRemoteFunction()
                $trans = $soapClient->__call("OtherRemoteFunction", array($at_param));
                $trans_result = $trans->OtherRemoteFunctionResult;
            ....
                } else {
                    // Record the transaction error in the database

                // Kill the link to Soap
                unset($soapClient);
            }
        }
    }
}

?>
moazzam at moazzam-khan dot com 05-Oct-2009 09:37
If anyone is trying to use this for accessing Sabre's web services, it won't work. Sabre checks the request header "Content-Type" to see if it is "text/xml" . If it is not text/xml then it sends an error back.

You will need to create a socket connection and use that to send the request over.
Raphal Gertz 18-Apr-2009 09:50
Juste a note to avoid wasting time on php-soap protocol and format support.

Until php 5.2.9 (at least) the soap extension is only capable of understanding wsdl 1.0 and 1.1 format.

The wsdl 2.0, a W3C recommendation since june 2007, ISN'T supported in php soap extension.
(the soap/php_sdl.c source code don't handle wsdl2.0 format)

The wsdl 2.0 is juste the 1.2 version renamed because it has substantial differences from WSDL 1.1.

The differences between the two format may not be invisible if you don't care a lot.

The wsdl 1.0 format structure (see http://www.w3.org/TR/wsdl) :
<definitions ...>
    <types ...>
    </types>
    <message ...>
        <part ...>
    </message>
    <portType ...>
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </portType>
    <binding ...>
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </binding>
    <service ...>
        <port ...>
    </service>
</definitions>

And the wsdl 2.0 format structure (see http://www.w3.org/TR/wsdl20/) :
<description ...>
    <types ...>
    </types>
    <interface ...>
        <fault ... />
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </interface>
    <binding ...>
        <fault ... />
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </binding>
    <service ...>
        <endpoint ...>
    </service>
</description>

The typical error message if you provide a wsdl 2.0 format file :
PHP Fatal error:  SOAP-ERROR: Parsing WSDL: Couldn't find <definitions> in 'wsdl/example.wsdl' in /path/client.php on line 9
jeff at jeffrodriguez dot com 03-Feb-2009 01:37
Named parameters are actually super easy once you know how to do it. No need to bother with SoapParam or SoapVar for the most part.

The code:
<?php
$ws->getAsset(array(
  'assetId' => 5967
));
?>

Generates the following SOAP body: (formatted for readability)
<SOAP-ENV:Body>
  <ns1:getAsset>
    <assetId>5967</assetId>
  </ns1:getAsset>
</SOAP-ENV:Body>
Ryan 28-Oct-2008 07:01
To save yourself a couple days of heart-ache, if you are trying to access a Windows server using SOAP and it seems as though the parameters are not being passed through to the Windows server, it is because of a bug in PHP. Because if you examine the SOAP packets going out (with Wireshark), you'll see that the parameter names are there in the <soap:Body>, but they have no values.

So instead, you should use the NuSOAP class and it will work perfectly: http://sourceforge.net/projects/nusoap/

I hope this helps and saves you pulling out your hair over this issue. :)

Ryan - http://operation513.blogspot.com
beau dot scott at gmail dot com 22-Oct-2008 03:34
If you've been trying to send null to a service that considers empty property tags as empty strings rather than null, here's an extending class that fixes this using xsi:nil:

<?php
class XSoapClient extends SoapClient
{
    const XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
    const _NULL_ = "xxx_replacedduetobrokephpsoapclient_xxx";

    protected $mustParseNulls = false;

    public function __doRequest($request, $location, $action, $version, $one_way = null)
    {
        if($this->mustParseNulls)
        {
            $this->mustParseNulls = false;
            $request = preg_replace('/<ns1:(\w+)>'.self::_NULL_.'<\/ns1:\\1>/',
                        '<ns1:$1 xsi:nil="true"/>',
                        $request, -1, &$count);

            if ($count > 0)
            {
                $request = preg_replace('/(<SOAP-ENV:Envelope )/',
                    '\\1 xmlns:xsi="'.self::XSI_NS.'" ',
                    $request);
            }
        }
        return parent::__doRequest($request, $location, $action, $version, $one_way);
    }

    public function __call($method, $params)
    {
        foreach($params as $k => $v)
        {
            if($v === null)
            {
                $this->mustParseNulls = true;
                $params[$k] = self::_NULL_;
            }
        }
        return parent::__call($method, $params);
    }
}
?>
Ryan 22-Oct-2008 06:21
If you are having an issue where SOAP cannot find the functions that are actually there if you view the wsdl file, it's because PHP is caching the wsdl file (for a day at a time). To turn this off, have this line on every script that uses SOAP: ini_set("soap.wsdl_cache_enabled", "0"); to disable the caching feature.
ivan dot cubillas at xeridia dot com 08-Aug-2008 01:02
The problem with the PHP WebService Client

We've a JAVA WebService Server which could have attached documents. When the PHP Client send the dates, the Server take it correctly, but when
the server return it to the PHP Client, the client reply always that is not a XML valid document.

The problem could be than the JAVA Server adds (to this type of XML binary files)  the documentType head: xml+xop and the clean doesn't understand
this head as a XML document.

There is some possibility to solve this problem in the PHP Client without doing changes in the JAVA Server?
aeg at mallxs dot nl 28-May-2008 05:19
SoapFault exception: [SOAP-ENV:Client] looks like we got no XML document

This error can have to reasons:
1: Your server script has some hidden output like spaces before or afher <?php ... ?> or echoing some text
2: You have a bug in your server script;
    resulting in a error message output

Test your server script by calling it direct  from the browser.
The result should be a clean output like :

−<SOAP-ENV:Envelope>
−<SOAP-ENV:Body>
−<SOAP-ENV:Fault>
  <faultcode>SOAP-ENV:Server</faultcode>
  <faultstring>Bad Request. Can't find HTTP_RAW_POST_DATA</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

This tell's you there was a request but without data; This is OK
Now if you get the error when calling with your soap client;
remember that your server now will call other functions in the server.php script because it now has some data to process
nodkz at mail dot ru 24-May-2008 02:25
PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

<?php
/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

Function "getAsSoap" call for encoding object for transmission. After encoding it can be properly transmitted.
*/
abstract class SOAPable {
    public function getAsSOAP() {
        foreach($this as $key=>&$value) {
            $this->prepareSOAPrecursive($this->$key);
        }
        return $this;
    }

    private function prepareSOAPrecursive(&$element) {
        if(is_array($element)) {
            foreach($element as $key=>&$val) {
                $this->prepareSOAPrecursive($val);
            }
            $element=new SoapVar($element,SOAP_ENC_ARRAY);
        }elseif(is_object($element)) {
            if($element instanceof SOAPable) {
                $element->getAsSOAP();
            }
            $element=new SoapVar($element,SOAP_ENC_OBJECT);
        }
    }
}

// ------------------------------------------
//  ABSTRACT EXAMPLE
// ------------------------------------------

class PersonList extends SOAPable {
  protected $ArrayOfPerson; // variable MUST be protected or public!
}

class Person extends SOAPable {
   //any data
}

$client=new SoapClient("test.wsdl", array( 'soap_version'=>SOAP_1_2, 'trace'=>1, 'classmap' => array('Person' => "Person", 'PersonList' => "PersonList")  ));

$PersonList=new PersonList;

// some actions

$PersonList->getAsSOAP();

$client->someMethod($PersonList);

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

So in code before transmitting simply call $obj->getAsSOAP()
SCA_SoapProxy::createDataObject
Введение
Веб-сервисы


Введение

The SOAP extension can be used to write SOAP Servers and Clients. It supports subsets of » SOAP 1.1, » SOAP 1.2 and » WSDL 1.1 specifications.

User Contributed Notes

There are no user contributed notes for this page.
SOAP
Установка и настройка
SOAP


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
SOAP


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

User Contributed Notes

benero at gmail dot com 12-May-2011 11:57
If you use https, SOAP modules need to configure with openssl, otherwise will be catch a error like:
SOAP-ERROR: Parsing WSDL: Couldn't load from url
suchasplus at gmail dot com 24-May-2010 08:34
Typically, on microsoft windows(sometimes linux), we got "I/O warning : failed to load external entity" and "Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from somewhere".
only xml lib is not enough, php-soap also need cURL, and openssl  if you wants connect to https
Установка и настройка
Установка
Установка и настройка


Установка

To enable SOAP support, configure PHP with --enable-soap .

User Contributed Notes

bty-adminf4 at trebly dot net 09-Oct-2011 06:05
Not a bug, not an enhancement, but incident with a solution which is needed to take care of a parameters coherency problem with wdsl_cache.

This need which could disappear in future (next) version .

If soap is enable (default), in php.ini after the parameter which enables the cache for wdsl :
soap.wsdl_cache_enable=1

if the other parameter
soap.wsdl_cache=
is not explicitly set (>0)

A request :
$mysoap_inst = NEW SoapClient ( https://...../*.wsdl)
will crash because the class SoapClient will not be loaded and initiated.

The following parameters are requested into php.ini :
soap.wsdl_cache
soap.wsdl_cache_dir (not completely checked)

This is because default value are not enabled by a simple
soap.wsdl_cache_enable=1
You can't try to set dynamically the value if they are not defined in php.ini explicitly with the default value.
warren at mojohost dot com 03-Mar-2011 01:51
You may not need anything extra, just --enable-soap. For some reason reading these notes made me think some other installation was required. You can just recompile with --enable-soap.

For linux try php -i | grep configure and run your new configure with that same list, just append --enable-soap at the end.
Anonymous 03-Nov-2010 08:03
If you are using 3rd party all-in-one servers on windows (like Uniform Server etc), "php_soap.dll" may not be included in the default distribution. If this is the case, the do phpinfo(); first, check what compiler is used - you need to find out if it's VC6 or VC9, then got to official php download page, get windows binary distribution (.zip archive recommended), and copy php_soap.dll from that archive to your server (on Uniform it's <path>usr\local\php\extensions\ and then restart the apache service. Please note that despite of compiler difference, PHP comes in two flavours - thread safe and non thread safe. If one does not work for you (check logs - "unable to load dynamic library '...' usually means file is not there (not the case) or cannot be loaded (due to compiler ABI mismatch or ts/nts mismatch). Try thread safe binaries first.
ifzen at yahoo dot com 04-Oct-2010 12:36
And CentOS or Red-Hat : yum install php-soap
walter 11-Jun-2010 12:06
Gentoo: add the 'soap' use flag to /etc/make.conf and emerge -av php
Julian 15-Apr-2010 06:26
on Ubuntu or Debian serived servers...

sudo aptitude install php-soap
Требования
Настройка во время выполнения
Установка и настройка


Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

SOAP Опции настройки
Имя | По умолчанию | Меняемо | Список изменений
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |

Краткое разъяснение конфигурационных директив.

soap.wsdl_cache_enabled integer

Enables or disables the WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where the SOAP extension will put cache files.

soap.wsdl_cache_ttl integer

Sets the number of seconds (time to live) that cached files will be used instead of the originals.

soap.wsdl_cache integer

If soap.wsdl_cache_enabled is on, this setting determines the type of caching. It can be any of: WSDL_CACHE_NONE (0), WSDL_CACHE_DISK (1), WSDL_CACHE_MEMORY (2) or WSDL_CACHE_BOTH (3). This can also be set via the options array in the SoapClient or SoapServer constructor.

soap.wsdl_cache_limit integer

Maximum number of in-memory cached WSDL files. Adding further files into a full memory cache will delete the oldest files from it.

User Contributed Notes

hpralow at users dot sf dot net 24-Jul-2008 07:40
If you want to dissable WSDL-caching, you can do so with
<?php
ini_set('soap.wsdl_cache_enabled', '0');
ini_set('soap.wsdl_cache_ttl', '0');
?>
However you must do this before creating a SOAP object (soap_client or soap_server).
Changing the settings like above does not have any effect on already existing soap-objects.

[EDIT BY danbrown AT php DOT net: Typofix provided by (james AT voodoo DOT co DOT uk) on 4-FEB-09.]
Установка
Типы ресурсов
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

SOAP constants
Constant | Value | Description
SOAP_1_1 (integer) | 1 |
SOAP_1_2 (integer) | 2 |
SOAP_PERSISTENCE_SESSION (integer) | 1 |
SOAP_PERSISTENCE_REQUEST (integer) | 2 |
SOAP_FUNCTIONS_ALL (integer) | 999 |
SOAP_ENCODED (integer) | 1 |
SOAP_LITERAL (integer) | 2 |
SOAP_RPC (integer) | 1 |
SOAP_DOCUMENT (integer) | 2 |
SOAP_ACTOR_NEXT (integer) | 1 |
SOAP_ACTOR_NONE (integer) | 2 |
SOAP_ACTOR_UNLIMATERECEIVER (integer) | 3 |
SOAP_COMPRESSION_ACCEPT (integer) | 32 |
SOAP_COMPRESSION_GZIP (integer) | 0 |
SOAP_COMPRESSION_DEFLATE (integer) | 16 |
SOAP_AUTHENTICATION_BASIC (integer) | 0 |
SOAP_AUTHENTICATION_DIGEST (integer) | 1 |
UNKNOWN_TYPE (integer) | 999998 |
XSD_STRING (integer) | 101 |
XSD_BOOLEAN (integer) | 102 |
XSD_DECIMAL (integer) | 103 |
XSD_FLOAT (integer) | 104 |
XSD_DOUBLE (integer) | 105 |
XSD_DURATION (integer) | 106 |
XSD_DATETIME (integer) | 107 |
XSD_TIME (integer) | 108 |
XSD_DATE (integer) | 109 |
XSD_GYEARMONTH (integer) | 110 |
XSD_GYEAR (integer) | 111 |
XSD_GMONTHDAY (integer) | 112 |
XSD_GDAY (integer) | 113 |
XSD_GMONTH (integer) | 114 |
XSD_HEXBINARY (integer) | 115 |
XSD_BASE64BINARY (integer) | 116 |
XSD_ANYURI (integer) | 117 |
XSD_QNAME (integer) | 118 |
XSD_NOTATION (integer) | 119 |
XSD_NORMALIZEDSTRING (integer) | 120 |
XSD_TOKEN (integer) | 121 |
XSD_LANGUAGE (integer) | 122 |
XSD_NMTOKEN (integer) | 123 |
XSD_NAME (integer) | 124 |
XSD_NCNAME (integer) | 125 |
XSD_ID (integer) | 126 |
XSD_IDREF (integer) | 127 |
XSD_IDREFS (integer) | 128 |
XSD_ENTITY (integer) | 129 |
XSD_ENTITIES (integer) | 130 |
XSD_INTEGER (integer) | 131 |
XSD_NONPOSITIVEINTEGER (integer) | 132 |
XSD_NEGATIVEINTEGER (integer) | 133 |
XSD_LONG (integer) | 134 |
XSD_INT (integer) | 135 |
XSD_SHORT (integer) | 136 |
XSD_BYTE (integer) | 137 |
XSD_NONNEGATIVEINTEGER (integer) | 138 |
XSD_UNSIGNEDLONG (integer) | 139 |
XSD_UNSIGNEDINT (integer) | 140 |
XSD_UNSIGNEDSHORT (integer) | 141 |
XSD_UNSIGNEDBYTE (integer) | 142 |
XSD_POSITIVEINTEGER (integer) | 143 |
XSD_NMTOKENS (integer) | 144 |
XSD_ANYTYPE (integer) | 145 |
XSD_ANYXML (integer) | 147 |
APACHE_MAP (integer) | 200 |
SOAP_ENC_OBJECT (integer) | 301 |
SOAP_ENC_ARRAY (integer) | 300 |
XSD_1999_TIMEINSTANT (integer) | 401 |
XSD_NAMESPACE (integer) | http://www.w3.org/2001/XMLSchema |
XSD_1999_NAMESPACE (integer) | http://www.w3.org/1999/XMLSchema |
SOAP_SINGLE_ELEMENT_ARRAYS (integer) | 1 |
SOAP_WAIT_ONE_WAY_CALLS (integer) | 2 |
SOAP_USE_XSI_ARRAY_TYPE (integer) | 4 |
WSDL_CACHE_NONE (integer) | 0 |
WSDL_CACHE_DISK (integer) | 1 |
WSDL_CACHE_MEMORY (integer) | 2 |
WSDL_CACHE_BOTH (integer) | 3 |

User Contributed Notes

User 01-Oct-2010 08:56
We are casting the values (float) to simulate the 64-bits long. seem to work fine, of course, the values we are using have no decimal point.
SOAP User 23-Sep-2008 03:32
Important note: The 64-bit long defined in XML Schema is not supported in the SOAP extension. A 32-bit integer is the longest supported due to the use of strtol internally.
Типы ресурсов
SOAP Функции
SOAP


SOAP Функции

Содержание

  • is_soap_fault — Checks if a SOAP call has failed
  • use_soap_error_handler — Set whether to use the SOAP error handler

User Contributed Notes

admin at localfm dot info 13-Oct-2008 12:01
As you may find, SOAP functions return result of type stdClass, not array. It means that you'll need to use $row->id instead of $row['id'] which may be inconvenient.

You can cast stdClass to array using this construction:

<?php
$data = $soap->getMyData($someParams);
$data = (array)$data;

print $data['field']; // now it works
?>
vIceBerg 23-Sep-2008 07:18
I have PHP 5.2.5 on my computer. I get this result:

Array
(
    [0] => stdClass Object
        (
            [Client] => stdClass Object
                (
                    [Nom] => LeNom:00000
                    [Prenom] => LePrenom:00000
                )

        )

My host have 5.1.6, the same call returns this result:
Array
(
    [0] => stdClass Object
        (
            [Client] => Array
                (
                    [0] => stdClass Object
                        (
                            [Nom] => LeNom:00000
                            [Prenom] => LePrenom:00000

                        )

5.2.5 is the good structure.

Take care of the version you're using. It can be a lot of work to change all the code
daniel dot harding at chaptereight dot com 28-Jul-2008 08:13
Setting Attributes for Complex Type Elements PHP5/SOAP
=========================================

// Setting attributes for simple elements:
<parentEl id="ref1">12345</foo>
<?php
array("parentEl" => array("_" => 12345, "id" => "ref1"));
?>

// Setting attributes for complex elements:
<parentEl id="ref1">
    <childEl>blah</childEl>
</parentEl>

'parentEl' => array(
        array('childEl' => 'blah')
    ),
    'id' => 'ref1'
)
nodkz at mail dot ru 24-May-2008 02:28
PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

<?php
/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

Function "getAsSoap" call for encoding object for transmission. After encoding it can be properly transmitted.
*/
abstract class SOAPable {
    public function getAsSOAP() {
        foreach($this as $key=>&$value) {
            $this->prepareSOAPrecursive($this->$key);
        }
        return $this;
    }

    private function prepareSOAPrecursive(&$element) {
        if(is_array($element)) {
            foreach($element as $key=>&$val) {
                $this->prepareSOAPrecursive($val);
            }
            $element=new SoapVar($element,SOAP_ENC_ARRAY);
        }elseif(is_object($element)) {
            if($element instanceof SOAPable) {
                $element->getAsSOAP();
            }
            $element=new SoapVar($element,SOAP_ENC_OBJECT);
        }
    }
}

// ------------------------------------------
//  ABSTRACT EXAMPLE
// ------------------------------------------

class PersonList extends SOAPable {
  protected $ArrayOfPerson; // variable MUST be protected or public!
}

class Person extends SOAPable {
   //any data
}

$client=new SoapClient("test.wsdl", array( 'soap_version'=>SOAP_1_2, 'trace'=>1, 'classmap' => array('Person' => "Person", 'PersonList' => "PersonList")  ));

$PersonList=new PersonList;

// some actions

$PersonList->getAsSOAP();

$client->someMethod($PersonList);

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

So in code before transmitting simply call $obj->getAsSOAP()
aeolianmeson at dontfindme dot blitzeclipse dot com 07-May-2008 08:42
A quick example to do a login using a WSDL, do a second request using the session ID from the login response, and then dump the XML from that request.

    // Setting "trace" will allow us to view the request that we are making, after we have made it.
    $objClient = new SoapClient("http://www.somewhere.com/wsdls/some.wsdl", array('trace' => true));

    // These parameters satisfy this specific remote call.
    $arrParameters_Login = array('username' => 'username', 'password' => 'password', 'company' => 'Company');

    // Invoke the remote call "login()".
    $objLogin =  $objClient->login($arrParameters_Login);

    // Grab session ID that this remote call will provide.
    $strSessionID = $objLogin->loginReturn->sessionId;

    // Set headers-- The remote call "query()" will require a header pointing to our session.

    $strHeaderComponent_Session = "<SessionHeader><sessionId>$strSessionID</sessionId></SessionHeader>";

    $objVar_Session_Inside = new SoapVar($strHeaderComponent_Session, XSD_ANYXML, null, null, null);
    $objHeader_Session_Outside = new SoapHeader('namespace.com', 'SessionHeader', $objVar_Session_Inside);

    // More than one header can be provided in this array.
    $objClient->__setSoapHeaders(array($objHeader_Session_Outside));

    // Set the query parameters.

    $strQuery = 'select empID from Time where empID = 92389278';
    $arrParameters_Query = array('queryString' => $strQuery);

    // Make call.

    $objResponse = $objClient->query($arrParameters_Query);

    header('Content-Type: text/xml; ');
    print($objClient->__getLastRequest());

The request that goes out:

<SOAP-ENV:Envelope>
    <SOAP-ENV:Header>
        <SessionHeader>
            <sessionId>8789364113604871127</sessionId>
        </SessionHeader>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <ns1:query>
            <ns1:queryString>select empID from Time where empID = 92389278</ns1:queryString>
        </ns1:query>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
rlee at melbournechapter dot net 01-May-2008 05:38
Just a note on "DTD not recognised..." faults. Check to make sure your wsdl file contains:

<?xml version ='1.0' encoding ='UTF-8' ?>

Also make sure you use full paths, to your service (in the wsdl, client and server)
...
<wsdlsoap:address location='http://www.mysite.com.au/web_services/myserver.php' />
...
<?php
// SOAP Server
$server = new SoapServer('http://www.mysite.com.au/web_services/hello.wsdl');
...
...
?>

<?php
// SOAP Client
 $client = new SoapClient('http://www.mysite.com.au/web_services/hello.wsdl');
...
...
?>

FYI im no SOAP expert but I hope this helps someone out ;)
Aurlien Christman 31-Mar-2008 01:34
From PHP 5, you can use the undocumented method SoapClient::__setLocation() to redefine the target EPR :

<?php

$client = new SoapClient("some_wsdl");
$client->__setLocation("http://new/target/epr");

$client->someFunction("param1", "param2");

?>
Andr Hnsel 24-Mar-2008 11:42
Note that HTTP auth is not done when fetching the WSDL file, only when carrying out the actual SOAP request.

Bug #27777 states that it is possible to supply credentials for the WSDL file using URL notation:

<?php
$client = new SoapClient("http://yourLogin:yourPassword@foo.com/bar.wsdl");
?>
bananos at dev dot co dot ua 17-Mar-2008 04:12
Be aware when working with long integers in SOAP requests (PHP supports only 32-bit signed int with upper limit of
2147483647 )

If you need to make requests with 64-bit integers consider following code:

<?php

 $ID = (float) "6146109011";
 $params["campaignID"] = new SoapVar($ID, XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema");
 $res    = $client->getCampaign(new SoapParam($params, "getCampaign"));

?>

If you'll try to pass such $ID in a direct way:

<?
  $ID = (float) "6146109011";
  $res    = $client->getCampaign(array('campaignID'  => $ID));
?>

the request will fail, because php_soap.dll will generate

<campaignID>2147483647</campaignID>

and not
<campaignID>6146109011</campaignID>

as expected
thomas dot rabaix at gmail dot com 13-Mar-2008 08:41
I have set up a small article which explains how to use SOAP with NTLM authentication.

http://tinyurl.com/328rgv (Ghrrr ! the url is too long)

Hope it can help you !

Thomas
Drydenmaker 13-Jan-2008 07:59
Working with a third party service I got: "SOAP-ERROR: Parsing Schema: unexpected <text> in restriction"

Thought it would be worth it to share.  What it is saying is that there is some text in an invalid place.  C# seems to ignore it, and if you are using nusoap it doesn't notice it either.  But what was causing my problem was something like:
<types>
    <schema ...

            <simpleType name="some type">
                <restriction base="xsd:string">
                    <enumeration value="foo"/>;
                </restriction>
            </simpleType>

Note the semicolon (;).  Filter that out and your good.
sam dot lowry at ministryofinformation dot com 10-Jan-2008 03:52
From the "I'll just do it manually" school of frustration.

If you've been having trouble getting complex types to work with no, or an entirely non-descript wsdl (my particular complaint... every method just has one child, a complex type element sequence of any... unnngh). Anyway I found the following works to fully replace the contents of the soap body with a pre-built xml string.  I haven't tested what this does for calls expecting multiple parameters, since that usually means I can call it with an actual paremeters argument, but I imagine it would still work the same way.

----------------------------------

$Result=$Client->SomeCall(new SoapVar('<Element attr="AttrValue">ElValue</Element>', XSD_ANYXML));

----------------------------------

it's really quite hackish and I'd prefer to know the proper method to add custom arguments to a SoapVar or SoapParam Object, but this worked and I'm leaving it there for now so can I lose the urge to break things.

NOTE: documentation says XSD_ANYXML wasn't added until 5.1.0
Dominik 07-Dec-2007 01:31
If you are working
- on localhost
- in WSDL mode
and encounter the following error when you try to connect the soap client with the soap server

Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host...

then change "localhost" to "127.0.0.1" in your WSDL file:
<soap:address location='http://127.0.0.1/soap-server.php'/>
Emanuele Colonnelli 06-Dec-2007 05:24
Hi,

I'd like to add this trick to get SoapClient correctly running with a WSDD-generated Axis 1 webservice.

By default, Apache Axis 1 generates a SOAP RPC/Encoded WSDL with "urn:" prefixes before all <SERVICE_NAME> occurrences.

Axis 1 WSDL also uses an "impl:" namespace prefix.

Suppose your service's name is "myWS", your WSDL will contains a "<wsdl:binding>" element with the name attribute valued "urn:myWSSoapBinding":

<wsdl:binding name="myWSSoapBinding">

PHP SoapClient has a problem (I hope it will be fixed soon ) parsing this WSDL and generates this error:

SOAP-ERROR: Parsing WSDL: No  element with name 'myWSSoapBinding'

This error arise because PHP SoapClient could not resolve the "urn:impl:myWSSoapBinding" QName in generated WSDL:

<wsdl:service name="myWSService">
<wsdl:port binding="impl:urn:myWSSoapBinding" name="urn:myWS">
<wsdlsoap:address location="http://URL/services/urn:myWS"/>
</wsdl:port>
</wsdl:service>

To solve this problem I parse WSDL applying a preg_replace to delete all "urn:" occurrences.

Then I save this generated WSDL somewhere in my site and point my SoapClient to this location.

I also need to specify additional parameters to SoapClient constructor:

<?php
$soap = new SoapClient("wsdl/myWS.wsdl",
array(
  "style" => SOAP_RPC,
  "use" => SOAP_ENCODED,
  "soap_version" => SOAP_1_1,
  "uri"=>"urn:myWS"
));
?>

I suggest you this resources to a full understanding of this kind of problems:

http://www.ibm.com/developerworks/
webservices/library/ws-whichwsdl/

http://wso2.org/wiki/display/wsfphp/
PHP+SOAP+Extension+API+-+Backward+Compatibility

I hope this save you hours of imprecations! :)

Emanuele Colonnelli
AL13N 28-Nov-2007 04:05
this might be helpful, as it took quite some time for me to find this out:

if you're using some .wsdl and there's a sequence that can be there more than once (ie: maxOccurs > 1), you can specify an non-associative array for it if you have more than 1 items OR you could just specify the one item if there is only one:

<?php
'items' => array(
    array(
        'itemId' => 5,
        'name' => 'some name',
    ),
    array(
        'itemId' => 6,
        'name' => 'some other name',
    ),
),
?>

this also works:

<?php
'items' => array(
    'itemId' => 5,
    'name' => 'some name',
),
?>
Anonymous 27-Nov-2007 08:58
I had to add the following to be able to call the PHP webservice from .Net Client
It seems that eighter PHPs implementation of SoapServer or Microsofts .Net way is wrong. The Namespace SOAP-ENV must be removed inside of the SOAP-ENV:Body

function callback($input) {
    $search = '/(<SOAP-ENV:Body>)\s*(<SOAP-ENV:)/';
    $replace = '$1<';
    $input = preg_replace($search, $replace, $input);

    $search = '/(<\/SOAP-ENV:)([A-Za-z0-9]*>)\s*(<\/SOAP-ENV:Body>)/';
    $replace = '</$2$3';
    $input = preg_replace($search, $replace, $input);

    return ($input);
}

ob_start('callback');
$server->handle();
ob_end_flush();
Anonymous 26-Nov-2007 11:54
when dealing with wsdl and flash soap with php
(not exactly php, but proper wsdl - took me hours to figure it to work properly in flash webservice)

when naming definitions,
don't use "tns:" but use "typens:"

makesure your "definitions/targetNamespace"
is same as your "soap:body" namespace
example: "urn:mynamespace"

makesure your "binding/type" is declared with "typens"

makesure your service/port/binding is set to 'typens:...'

if you did not do it properly, you will end up with
WSDL.UnrecognizedNamespace - in flash
but seems okay in php soapclient...

happy coding :)
hope this help you to save your time on the wsdl :)
james at mercstudio dot com 24-Nov-2007 01:45
If you use wsdl,

makesure you define the input correctly.
if your method does not contain any input parameter,
you got to makesure that you:

 - do not create the message tag for the input..
 - do not put input within porttype / operation
 - do not put input within binding / operation

if not, you will get the error:
[Client] looks like we got no XML

d***, took me several hours figuring that out...
Dennis Du Krger 23-Nov-2007 07:15
A word of warning:

Do NOT use associative arrays or arrays not starting with element number 0...

Various versions of the soap extension will not send it through properly.
t dot kloppenburg at billiton dot de 22-Nov-2007 03:33
I had the "DTD are not supported by SOAP" message, too. It helped me to var_dump the complete "SoapFault" exception to find helpful information in a field "["faultstring"]=>....".

It was an error my soap handler (adding a non existant function).
dirk at waferthin dot com 20-Jun-2007 04:31
I hope this will save someone time. When developing and testing your SOAP server, remember to disable WSDL caching in BOTH client and server:

$ini = ini_set("soap.wsdl_cache_enabled", 0);
jochen dot munz at municons dot com 11-Jun-2007 08:56
When encountering an error message like this

[faultstring] => Function ("yourMethod") is not a valid method for this service

although it is present in the WSDL etc., be aware that PHP caches the wsdl locally for better performance. You can disable the caching via php.ini/.htaccess completely or remove the cache file (/tmp/wsdl-.. if you are on Linux) to force regeneration of it.
Marcio Annunciato 17-May-2007 02:22
In case your soap response containts an ampersand, in certain cases you might get an "unterminated entity reference" warning and data might appear truncated (related to bug #36795?). Maybe there is a more formal fix or setting, but since I couldn't find anything I came with the following:

class MySoapClient extends SoapClient {
    function __doRequest($request, $location, $action, $version) {
        $res = parent::__doRequest($request, $location, $action, $version);
        $resx = str_replace('&amp;', '&amp;amp;', $res);
        print_r($resx);
        return ($resx);
    }
}
albert at jool dot nl 27-Mar-2007 02:59
A note for ppl who use certificates with SOAP under a Windows config: it seems to be required to give the full path to the certificate file - and don't prepend 'file://' :

<?php

$wsdl = "test.wsdl";
$local_cert = "c:\htdocs\mycert.pem";
$passphrase = "xyz";

$client = new SoapClient($wsdl, array('local_cert' => $local_cert, 'passphrase' => $passphrase);

?>
kroesjnov at hotmail dot com 09-Feb-2007 07:38
If you dont want to manually maintain the classmap, make sure you use the same names for your PHP object classes and your WSDL complexTypes, and use the following code:

$classmap = array();
$tmpClient = new SoapClient("soapserver.wsdl");

foreach($tmpClient->__getTypes() as $type)
{
    $array = split(" ", $type);
    if($array[0] == "struct" && class_exists($array[1]))
    {
        $classmap[$array[1]] = $array[1];
    }
}
unset($tmpClient);

$server = new SoapServer("soapserver.wsdl", array("classmap" => $classmap));
unset($classmap);
$server->setClass("someclass");
$server->handle();
Herman Hiddema 07-Feb-2007 06:32
I recently found that when using SoapClient with client certificates (the 'local_cert' and 'passphrase' options), PHP needs to have CURL enabled. (At least with PHP 5 and Apache on Windows)

I kept getting errors like this:
Unable to set local cert chain file `filename.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in somescript.php on line ##

I tried everything I could find on the net (correct .pem format, constructing and passing my own stream context, etc) but nothing would work. Enabling CURL (by uncommenting extension=php_curl.dll in php.ini) instantly caused my client to work.
brephophagist 18-Jan-2007 09:45
For those working from a wsdl full of complex types that just want a class structure to hang your code on and not worry about typing in long parameter lists (or creating a script to do so): wsdl2php is a wonderful time-saver. Gets a structure going so you can go in and add what validation and special data munging you need: http://www.urdalen.no/wsdl2php/

Big up yourself, Knut.
Olaf Krische 21-Nov-2006 01:48
If you use SSL with a cert and password authentication:

$wsdl = "https://ws.ecopatz.de/ProductInfo?wsdl";
$pass = 'a password';
$certFile = "./mycert.pem";

  $client = new SoapClient($wsdl,
    array(
     'local_cert' => $certFile,
     'passphrase' => $pass
    )
  );

If you have problems with the certfile like this:

  Warning: SoapClient::__construct(): Unable to set local cert chain file `./mycert.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in productinfo.php on line 27

then the certFile is probably in the "wrong format" (the wrong format for php maybe). It worked for me, when i appended the content of the private key file and the certificate file to a single file "mycert.pem":

  cat mycert.key >mycert.pem # mycert.key was the private key
  cat mycert.crt >>mycert.pem # mycert.crt was the signed certificate

Thanks to an author somewhere, who pointed to "curl --cert", where this little "so unimportant" dependency has been mentioned.
Gerôme <kontakt at bmservices dot de> 16-Nov-2006 08:27
When compiling SOAP support for PHP 5.2.0 it was not sufficient to use "--with-soap" in the "./configure" statement. I also had to include "--enable-soap" to get it work.
nico 25-Aug-2006 06:20
If you want to build a Soap Server for Microsoft Office's client (like Microsoft Office Research Service) you need to rewrite SOAP's namespaces :

<?php
// (...)

$server = new SoapServer($wsdl, array('uri' => $uri, 'classmap' => $classmap));
$server->setClass($class);
function callback($buffer)
{
    $s = array('<ns1:RegistrationResponse>', 'ns1:', 'xmlns:ns1="urn:Microsoft.Search"');
    $r = array('<RegistrationResponse xmlns="urn:Microsoft.Search">', '', '');
   return (str_replace($s, $r, $buffer));
}
ob_start('callback');
$server->handle();
ob_end_flush();

// (...)
?>

There are a complete example at this URL : http://touv.ouvaton.org/article.php3?id_article=104
info at webability dot info 22-Aug-2006 12:30
If you want to use soap over https, you *must* compile php with the configure option with-openssl or you will have the error "[HTTP] SSL support not available in this build" while trying to use the web services over SSL
mini at freebsd dot org 08-Jul-2006 04:54
wokan at cox dot net is incorrect about the security of URI-passed values to HTTPS URIs.  HTTPS connections are HTTP inside SSL -- all of the HTTP traffic, including the request, are encrypted.
lists at 5etdemi dot com 13-Mar-2006 06:26
To enable SoapClient on Windows, simply add a line:

extension=php_soap.dll

in php.ini in the extensions section.
adm 01-Mar-2006 11:27
Wondering why the function you just added to your WSDL file is not available to your SOAP client? Turn off WSDL caching, which (as the documentation says) is on by default.

At the top of your script, use:

$ini = ini_set("soap.wsdl_cache_enabled","0");
Matthew Glubb 20-Jan-2006 08:05
For anyone wondering why they are getting a "DTD are not supported by SOAP" fault string. It is because you are probably being returned an HTML page due to an internal server error, 404, etc.

Refer to the documentation for SoapClient->__getLastResponse in order to see what returned by the server.
ckl at ecw dot de 16-Jan-2006 11:54
To debug a SOAP service using SoapServer(), a WSDL file and Zend Studio Client/Server, you have to append ?start_debug=1&amp;debug_port=10000 to the service location:
--- snip ---
... method / service definition ....

<service name="SOAPService">
  <port
    name="SOAPServicePort"
    binding="typens:SOAPServiceBinding">
   <soap:address
   location="$URL?start_debug=1&amp;debug_port=10000"/>
  </port>
</service>
--- snap ---
Rui Martins 18-Dec-2005 08:33
Here's an example on how to pass ArrayOfAnyType arguments
containing complex types.

Suppose your WSDL file defines "http://any.url.com/" as the default namespace and a complex type "SomeComplexType".

If you want to call a WebServices which takes an ArrayOfAnyType argument of "SomeComplexType"s you need to perform the following:

<?php
// complexTypes being an array containing several instances of SomeComplexType

myWSParameter = array();
foreach (complexTypes as ct)
{
   // Don't misspell the type or the namespace. Also note that php won't assume the default namespace defined in the WSDL file.
   myWSParameter []= new SoapVar(ct, 0, "SomeComplexType", "http://any.url.com/");
}
?>

On the other hand, when a WebService returns an ArrayOfAnyType you have to do the following to access each of its elements.

<?php
// Here, we will be echoing each return item
$res = $someWS->myFunction($myArgs)

// If only one element is returned, an array won't be built
if (is_array(myFunctionResult->anyType))
{
   foreach (myFunctionResult->anyType as $soapVar)
   {
      echo $soapVar->enc_value;
   }
}
else
{
   echo myFunctionResult->anyType->enc_value;
}
?>

This has all been tested using a .NET WebService.
ChrisB 23-Oct-2005 11:03
Heads up for anyone using PHP Soap + Sessions + PEAR DB classes.

Every time you make a call, via the soap client to your web service, your PEAR DB session is put to sleep and it doesnt by default wake upon the next request.

To fix this I simply called my particular database close call ifx_close() below my $soap->handle();
Bob 11-Oct-2005 01:17
If you are scratching your head why NuSOAP not working on PHP 5.x , the reason is this built-in SOAP Extenstion uses same soapclient() class name as Nusoap.

replace 'soapclient' with 'soapclient_xxx'  in nusoap.php and you are good to go...
johnjawed at gmail dot com 22-Sep-2005 09:29
For those wondering on how to set attributes on nodes with PHP5 SOAP, it would be done as such:

<... soap env/header>
<foo bar="blah">12345</foo>

array("foo" => array("_" => 12345, "bar" => "blah"));
Darryl 20-Jul-2005 11:46
Having trouble passing complex types over SOAP using a PHP SoapServer in WSDL mode?  Not getting decoded properly?  This may be the solution you're looking for!

When using ComplexType in the schema portion of the WSDL file, You need use an additional step to tell PHP SOAP how to encode the objects.  The first method would be to explicitely encapsulate the object in a SoapVar object - telling PHP to use generalized SOAP encoding rules (which encodes all ComplexTypes as Structs).  This won't work, though, if the client is expecting the objects to be encoded according to the WSDL's schema.  So, The actual way to do this is:

* First, define a specific PHP class which is actually just a data structure holding the various properties, and the appropriate  ComplexType in the WSDL.

<?php
 class MyComplexDataType {
     public $myProperty1;
     public $myProperty2;
 }
?>
 <complexType name="MyWSDLStructure">
 <sequence>
    <element name="MyProperty1" type="xsd:integer"/>
    <element name="MyProperty2" type="xsd:string"/>
 </sequence>
 </complexType>

* Next, Tell the SoapServer when you initialize it to map these two structures together.

<?php
 $classmap = array('MyWSDLStructure' => 'MyComplexDataType');
 $server = new SoapServer("http://MyServer/MyService.wsdl", array('classmap' => $classmap))
?>

* Finally, have your method return an instance of your class directly, and let the SoapServer take care of encoding!

<?php
 public function MySoapCall() {
     $o = new MyComplexDataType();

     $o->myProperty1 = 1;
     $o->myProperty2 = "MyString";

     return $o
 }
?>
Jim Plush 12-Jul-2005 04:45
If you're trying to use the SOAP Extension over SSL with a custom PEM file you need to do this:

$client->_local_cert = "C:\\path\myCert.pem";
pash_ka 18-May-2005 12:52
One good tutorial on using this extension is on IBM web site:
"Using the PHP 5 SOAP extension to consume a WebSphere Web service"
http://www.ibm.com /developerworks/library/os-phpws/?ca=dgr-lnxw06PHP5soap
flobee at gmail dot com 11-May-2005 01:25
wow, actually a cool program and soap is new for me.
I found out some interessting things i can not debug because the scripts exit without any error messages or notes. :-(

you may have problems with the memory and/or especially on "shared servers" when server load is high.
sometimes the script does the job, sometimes it just stopping at any unknown point.
these are the steps my script does:
* get data from remote server ( ~ 4.5 MB)
* parsing requested object and store the data in a database.

the return with debug messages was intressting:
-> check Mem limit: 30M
-> $client = new new SoapClient($url_wsdl, $options);
-> Memory usage: 185888
-> $client->[requested_method_to_get_data]();
-> check: __getLastResponseHeaders() - after:
-> HTTP/1.1 200 OK // remote server is fine with me :-)
-> Content-Length: 4586742  // I got the data
-> check: Memory usage now: 23098872 // ups !!! this can't be true!!

so, and if now someone on the server takes the rest of RAM  the walk thought the data breaks :-(

so, i need to store the xml tree ($client->client->__last_response) and parsing it by the classical way. (if you would request more RAM, you may get in trouble with the admin if you run a script like this more often! (on shared servers)
OrionI 18-Apr-2005 08:12
If you're having problems calling a .NET web service, see the comments over on http://php.net/soap_soapclient_soapcall (the __soapCall method).
kucerar at hhmi dot org 25-Mar-2005 12:04
Here are 73 test cases that detail the kinds of schemas that PHP5 currently supports and the structures you are expected to plug into them for the return value from your services.   Much better than trying to guess!

http://cvs.php.net/co.php/pecl/soap/tests/schema

You can cycle through the listings by changing the main index in the URL below,  rather than go in and out of the pages

http://cvs.php.net/co.php/pecl/soap/tests/schema/schema052.phpt?r=1.2

I downloaded the whole thing with this,  CVS might work too.
http://www.httrack.com/

With them all downloaded I just browse them with Textpad.
Norman Clarke <norman at dontblink dot com> 21-Feb-2005 04:29
Note that if you should need to set the timeout for your soap request,  you can use ini_set to change the value for the default_socket_timeout. I previously used NuSOAP, whose soap client class has a timeout option, and it took me a while to figure out that PHP's soap uses the same socket options as everything else.
wokan at cox dot net 05-Feb-2005 05:06
It's not good security practice to pass the username and password in the URI when the point of SSL is to prevent that information from being intercepted.  Putting that information in the URI makes it interceptable.  HTTPS-Posted values are safe because values passed in the headers are sent after the SSL handshake has been completed.
mikx at mikx dot de 29-Mar-2004 08:12
It took me a while to properly establish a password protected client connection via https on windows/apache1.3. Here my little guide:

1. The SOAP extension isn't activated by default (PHP5 RC1). Just add "extension=php_soap.dll" to the php.ini and don't forget to set the extension_dir properly (in most cases "c:\php\ext").

2. Add "extension=php_openssl.dll" to the php.ini. This module depends on libeay32.dll and ssleay32.dll - copy them from your php folder to your system32 folder.

3. Restart apache

4. The sourcecode

$client = new SoapClient("https://yourLogin:yourPassword@foo.com/bar.wsdl", array(
    "login"      => "yourLogin",
    "password"   => "yourPassword",
    "trace"      => 1,
    "exceptions" => 0));

$client->yourFunction();

print "<pre>\n";
print "Request: \n".htmlspecialchars($client->__getLastRequest()) ."\n";
print "Response: \n".htmlspecialchars($client->__getLastResponse())."\n";
print "</pre>";

Currently it seems to be necessary to add your login and password both in the uri and in the options array. Not sure if this is the expected behavior.
Предопределенные константы
is_soap_fault
SOAP


Checks if a SOAP call has failed

SOAP Функции
use_soap_error_handler
SOAP Функции
PHP Manual

is_soap_fault

(Unknown)

is_soap_fault — Checks if a SOAP call has failed

Описание

bool is_soap_fault ( mixed $object )

This function is useful to check if the SOAP call failed, but without using exceptions. To use it, create a SoapClient object with the exceptions option set to zero or FALSE. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).

If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.

Список параметров

object

The object to test.

Возвращаемые значения

This will return TRUE on error, and FALSE otherwise.

Примеры

Пример #1 is_soap_fault() example

<?php
$client = new SoapClient("some.wsdl", array('exceptions' => 0));
$result = $client->SomeFunction();
if (is_soap_fault($result)) {
    trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
}
?>

Пример #2 SOAP's standard method for error reporting is exceptions

<?php
try {
    $client = new SoapClient("some.wsdl");
    $result = $client->SomeFunction(/* ... */);
} catch (SoapFault $fault) {
    trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
}
?>

Смотрите также

  • SoapClient::SoapClient() - Конструктор SoapClient
  • SoapFault::SoapFault() - SoapFault constructor

User Contributed Notes

There are no user contributed notes for this page.
SOAP Функции
use_soap_error_handler
SOAP Функции


Set whether to use the SOAP error handler

is_soap_fault
SoapClient
SOAP Функции
PHP Manual

use_soap_error_handler

(Unknown)

use_soap_error_handler — Set whether to use the SOAP error handler

Описание

bool use_soap_error_handler ([ bool $handler = true ] )

This function sets whether or not to use the SOAP error handler in the SOAP server. It will return the previous value. If set to TRUE, details of errors in a SoapServer application will be sent to the clients. If FALSE, no information will be sent.

Список параметров

handler

Set to TRUE to send error details to clients.

Возвращаемые значения

Returns the original value.

Смотрите также

  • set_error_handler() - Задает определенный пользователем обработчик ошибок
  • set_exception_handler() - Задает пользовательский обработчик исключений

User Contributed Notes

msynak dot no dot spam dot please at wp dot pl 02-Mar-2006 06:45
This function seems to disable/enable automatic error reporting through SOAP. Use it to prevent user "on the other side" from seeing internal errors of your application.
Sometimes it is better to send no answer at all than to inform users that your application has e.g. parse errors.

Usage:

// disable error reporting
use_soap_error_handler(false);

// enable error reporting
use_soap_error_handler(true);

Default state of soap error handler is ENABLED.

It seems that the best practice is to disable it in constructor of your SOAP request handling class and enable in destructor.

For some situations, you may want to create your own error handling function instead (see set_error_handler and set_exception_handler) and throw custom SoapFaults with info like: "We have technical difficulties at the moment. Sorry!".
is_soap_fault
SoapClient
SOAP Функции


The SoapClient class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

The SoapClient class provides a client for » SOAP 1.1, » SOAP 1.2 servers. It can be used in WSDL or non-WSDL mode.

Обзор классов

SoapClient {
/* Методы */
public mixed __call ( string $function_name , string $arguments )
public SoapClient ( mixed $wsdl [, array $options ] )
public string __doRequest ( string $request , string $location , string $action , int $version [, int $one_way = 0 ] )
public array __getFunctions ( void )
public string __getLastRequest ( void )
public string __getLastRequestHeaders ( void )
public string __getLastResponse ( void )
public string __getLastResponseHeaders ( void )
public array __getTypes ( void )
public void __setCookie ( string $name [, string $value ] )
public string __setLocation ([ string $new_location ] )
public bool __setSoapHeaders ([ mixed $soapheaders ] )
public mixed __soapCall ( string $function_name , array $arguments [, array $options [, mixed $input_headers [, array &$output_headers ]]] )
public SoapClient ( mixed $wsdl [, array $options ] )
}

Содержание

  • SoapClient::__call — Вызывает SOAP-функцию (устаревший)
  • SoapClient::__construct — Конструктор SoapClient
  • SoapClient::__doRequest — Выполняет SOAP-запрос
  • SoapClient::__getFunctions — Возвращает список доступных SOAP функций
  • SoapClient::__getLastRequest — Возвращает последний SOAP-запрос
  • SoapClient::__getLastRequestHeaders — Возвращает SOAP-заголовки последнего запроса
  • SoapClient::__getLastResponse — Возвращает последний SOAP-ответ
  • SoapClient::__getLastResponseHeaders — Возвращает SOAP-заголовки последнего ответа
  • SoapClient::__getTypes — Возвращает список SOAP-типов
  • SoapClient::__setCookie — Устанавливает cookie
  • SoapClient::__setLocation — Устанавливает адрес используемой веб-службы
  • SoapClient::__setSoapHeaders — Устанавливает SOAP-заголовки для последующих вызовов
  • SoapClient::__soapCall — Вызывает SOAP-функцию
  • SoapClient::SoapClient — Конструктор SoapClient

User Contributed Notes

Guillermo Prandi 20-Feb-2012 02:10
To make an HTTPS call with a client certificate, you can do it this way:

1) Create a file containing both the key and the signed certificate. I did this by concatenating my (.pem) key and the certificate I've got signed from my CA (also .pem format). The file looked like this:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKagQC1N27Ilb9pWil2NaX2qM8FquXBXK5T1AydOv7sCotsc8MAwbi7
......(snip)......
wAiOCD4K9TyMS76pIS8UyfJl/oIrn7EF24BUpaUfsh8=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIC/zCCAmigAwIBAgIEAIl1JzANBgkqhkiG9w0BAQQuADBQMQswCQYxVQQGEaJV
......(snip)......
eSPds1hLKYSg0bd3uI7LhaDLOC1PPgb77sYe/uYkUWuHBzllts5x/pfue0zaIBKG
Omjy
-----END CERTIFICATE-----

2) Reference your certificate in the creation of the SOAP client, like this:

$protected_url = "https://my-server/?wsdl";
$my_cert_file = "/my/path/to/mycert.pem";

$client = new SoapClient($protected_url, array('local_cert', $my_cert_file) );
egiardina at badatmath dot com 03-Aug-2011 06:05
This one drove me nuts... if you are connecting to a web service run on Cassini, (Visual Studio's web server) from php, you may not be able to call web service functions or load a WSDL out-of-the-box.

My set up is that I am using xampp on my windows development machine, and also using Visual Studio's built in web-server. I built a web service in visual studio. I wrote a simple PHP script, running under xampp, to access this service, so the two projects can 'talk' to each other. What I found was the WSDL was never loaded.

So I moved the WSDL local to the PHP file and accessed it directly. Still no calls. Turns out, PHP's SoapClient seems to have a problem with 'localhost' as a web service endpoint. So I hand-edited the web service endpoint URL to read 127.0.0.1 instead of localhost, and Voila! Web Service calls work:

Here is my PHP, now working:
<?php
$client = new SoapClient("http://localhost/code/soap.wsdl");
$something =  $client->HelloWorld(array());
echo $something->HelloWorldResult;
die();

?>

Here is my modified WSDL:
  <wsdl:service name="MyService">
    <wsdl:port name="MyServiceSoap" binding="tns:MyServiceSoap">
      <soap:address location="http://127.0.0.1:55274/MyService/MyService.asmx" />
....

    </wsdl:port>
stepan dot zarubin at gmail dot com 30-Jun-2011 11:51
Well, this example works fine:

<?php
try {
    $x = @new SoapClient("non-existent.wsdl");
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Just make sure use NEW with @.
tlk 19-May-2011 06:35
Make sure to prefix constructor calls with @ and catch SoapFault exceptions, otherwise you risk having the php interpreter exit/die on simple network issues.

Robust sample code by Rasmus from http://bugs.php.net/bug.php?id=47584

<?php
try {
    $x = @new SoapClient("non-existent.wsdl",array("exceptions" => 1));
} catch (SoapFault $E) {
    echo $E->faultstring;
}
echo "ok\n";
?>
jjlopez 09-Mar-2011 11:36
If you are making soap calls in WSDL mode , and the address of your web service includes a port different from 80 (like http://my_ip_address:8080//service.asmx?wsdl), the WSDL file is fetched correctly, but all subsequent requests are made without any port in the host field. This causes a SoapFault exception when trying to call any of the service’s methods.

You need to redefine the soapClient class and force the port in each call.

See this example:

http://www.victorstanciu.ro/php-soapclient-port-bug-workaround/
hugues at zonereseau dot com 17-Feb-2011 09:17
When you need to connect to services requiring to send extra header use this method.

Here how we can to it with PHP and SoapClient

<?php
class exampleChannelAdvisorAuth
{
    public $DeveloperKey;
    public $Password;

    public function __construct($key, $pass)
    {
        $this->DeveloperKey = $key;
        $this->Password = $pass;
    }
}

$devKey        = "";
$password    = "";
$accountId    = "";

// Create the SoapClient instance
$url         = "";
$client     = new SoapClient($url, array("trace" => 1, "exception" => 0));

// Create the header
$auth         = new ChannelAdvisorAuth($devKey, $password);
$header     = new SoapHeader("http://www.example.com/webservices/", "APICredentials", $auth, false);

// Call wsdl function
$result = $client->__soapCall("DeleteMarketplaceAd", array(
    "DeleteMarketplaceAd" => array(
        "accountID"        => $accountId,
        "marketplaceAdID"    => "9938745"        // The ads ID
    )
), NULL, $header);

// Echo the result
echo "<pre>".print_r($result, true)."</pre>";
if($result->DeleteMarketplaceAdResult->Status == "Success")
{
    echo "Item deleted!";
}
?>
jeffmixpute 24-Jan-2011 03:15
Simple php client and server:

Client:

<?php

// bind SOAP/Client.php -> path of the php file
require_once "SOAP/Client.php";

// URI delivered to web service
$sc = new SOAP_Client("http://localhost/SOAP/Server.php");

// start call function to use the function of the Web Service
$parameter = array();
$result = $sc->call ("now", &$parameter, "urn:TimeSerivce");

// print result
print $result."\n";

?>

Server:

<?php

// bind PEAR::SOAP
require_once "SOAP/Server.php";
$skiptrace =& PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
$skiptrace = true;

// program service class
class TimeSerivce {
    public function now () {

        date_default_timezone_set("Europe/Berlin");
        return (date ("H:i"));
    }
}

// web service classs develop
$service = new TimeSerivce();

// server develop
$ss = new SOAP_SERVER();

// assing the name to the service
$ss->addObjectMap($service, "urn:TimeSerivce");

// Einstellung, dass POST-Daten an den Service weiter gegeben werden
// preferene to forword POST data to the service
$ss->service ($HTTP_RAW_POST_DATA);

?>
fourat dot zouari at tritux dot com 20-Jun-2009 08:08
In addition to the KeepAlive trick which is a "server-side" modification, on the "client side" default_socket_timeout should be increased from its default value (60) when you deal with ~slow SOAP servers.
As for the KeepAlive, if creating a new separate vhost for the soap api is not possible, you can add this to your existing vhost: BrowserMatch "^PHP-SOAP" nokeepalive
where PHP-SOAP is the agent name of your soap client, if you dont know what agent name your client use, just checkout the access.log of your apache.
peter dot hansen at fastit dot net 01-May-2009 06:57
When you get errors like:
"Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in"
after a few (time intensive) SOAP-Calls, check your webserver-config.

Sometimes the webservers "KeepAlive"-Setting tends to result in this error. For SOAP-Environments I recommend you to disable KeepAlive.

Hint: It might be tricky to create a dedicated vhost for your SOAP-Gateways and disable keepalive just for this vhost because for normal webpages Keepalive is a nice speed-boost.
use_soap_error_handler
SoapClient::__call
SOAP


Вызывает SOAP-функцию (устаревший)

SoapClient
SoapClient::__construct
SoapClient
PHP Manual

SoapClient::__call

(PHP 5 >= 5.0.1)

SoapClient::__call — Вызывает SOAP-функцию (устаревший)

Описание

public mixed SoapClient::__call ( string $function_name , string $arguments )

Этот метод устаревший. Используйте SoapClient::__soapCall вместо него.

User Contributed Notes

KRavEN 17-Jun-2009 06:56
extend of __call thats adds a retry to handle the occasional 'Could not connect to host' exceptions

<?php
class LocalSoapClient extends SoapClient
{

  public function __call($function_name, $arguments)
  {
    $result = false;
    $max_retries = 5;
    $retry_count = 0;

    while(! $result && $retry_count < $max_retries)
    {
      try
      {
        $result = parent::__call($function_name, $arguments);
      }
      catch(SoapFault $fault)
      {
        if($fault->faultstring != 'Could not connect to host')
        {
          throw $fault;
        }
      }
      sleep(1);
      $retry_count ++;
    }
    if($retry_count == $max_retries)
    {
      throw new SoapFault('Could not connect to host after 5 attempts');
    }
    return $result;
  }
}
?>
bananos at dev dot co dot ua 11-Apr-2008 05:13
I'm writing PHP SOAP client (based on php_soap extension) which uses Google AdService,
today, I tried to create sample Ad using   AdService::addAds()  and discovered that my SOAP library does not pass
"headline", "description1", "description2"  parameters in SOAP request.

First, I thought that this was something wrong with my data, coz I was getting validation errors like
"One or more input elements failed validation."   Then I decided to take a look at WSDL description
https://adwords.google.com/api/adwords/v11/AdService?wsdl

And voilà !  I've found this:

<complexType name="Ad" abstract="true">
<sequence>
  <element name="adGroupId" type="xsd:int"/>
  <element name="adType" nillable="true" minOccurs="0" type="impl:AdType"/>
  <element name="destinationUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="disapproved" type="xsd:boolean"/>
  <element name="displayUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="exemptionRequest" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="id" type="xsd:long"/>
  <element name="status" nillable="true" minOccurs="0" type="impl:AdStatus"/>
</sequence>

</complexType>

There is no any ''description", "headline1", "headline2", however there is another complexType

<complexType name="TextAd">
    <complexContent>
    <extension base="impl:Ad">
    <sequence>

<element name="description1" nillable="true" type="xsd:string"/>
<element name="description2" nillable="true" type="xsd:string"/>
<element name="headline" nillable="true" type="xsd:string"/>
</sequence>

</extension>
</complexContent>
</complexType>

So, the thing is when you are working with php_soap be aware of complexType extensions which does not work in php_soap when you try to do things like:

<?php

$client = new
    SoapClient(
       "https://adwords.google.com/api/adwords/v11/AdService?wsdl",
        array(  'trace'      => true,
                'exceptions' => true,
             )

    );

$entropy     = substr(md5(rand(0, time())), 0, 10);
//create Ad test structure
$sample_ad =  array(
               "id" => 0,
               "adGroupId" => 0,
               "adType" => 'TextAd',
               "disapproved" => false,
               "destinationUrl" => 'http://test.com',
               "displayUrl" => 'www.Test.com',
               "status" => "Paused", //  Enabled / Disabled
               "descr_iption1" => 'D1_'.$entropy,
               "des_cription2" => 'D2_'.$entropy,
               "head_line" => 'H_'.$entropy
        );

$client->addAds(array('ads' => array($sample_ad) );
?>
Samil Abud 19-Dec-2007 12:00
Hi,
This is a good example, for the SOAP function "__call".
However it is deprecated.

<?php
$wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
$int_zona = 5;
$int_peso = 1001;
$cliente = new SoapClient($wsdl);
print "<p>Envio Internacional: ";
$vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
print $vem;
print "</p>";
?>
SoapClient
SoapClient::__construct
SoapClient


Конструктор SoapClient

SoapClient::__call
SoapClient::__doRequest
SoapClient
PHP Manual

SoapClient::__construct

(PHP 5 >= 5.0.1)

SoapClient::__construct — Конструктор SoapClient

Описание

public SoapClient::SoapClient ( mixed $wsdl [, array $options ] )

Эта функция является псевдонимом: SoapClient::SoapClient()

User Contributed Notes

There are no user contributed notes for this page.
SoapClient::__call
SoapClient::__doRequest
SoapClient


Выполняет SOAP-запрос

SoapClient::__construct
SoapClient::__getFunctions
SoapClient
PHP Manual

SoapClient::__doRequest

(PHP 5 >= 5.0.1)

SoapClient::__doRequest — Выполняет SOAP-запрос

Описание

public string SoapClient::__doRequest ( string $request , string $location , string $action , int $version [, int $one_way = 0 ] )

Выполняет SOAP-запрос поверх HTTP.

Этот метод может быть переопределен в подклассах для реализации других транспортных уровней, выполнения дополнительной обработки XML или других целей.

Список параметров

request

XML SOAP запрос.

location

URL для запроса.

action

SOAP-действие.

version

Версия SOAP.

one_way

Если one_way равен 1, то метод ничего не возвращает. Этот параметр используется, когда не ожидается ответа.

Возвращаемые значения

XML SOAP ответ.

Список изменений

Версия | Описание
5.1.3 | Добавлен параметр one_way.

Примеры

Пример #1 Пример использования SoapClient::__doRequest()

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version, $one_way = 0) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));
var_dump($x->Add(3,4));
?>

User Contributed Notes

alireza dot meskin at gmail 02-Apr-2012 12:29
Change Blocking mode for Socket stream and set Timeout for Soap requests

<?php

class TimeoutSoapClient extends SoapClient
{
    const TIMEOUT = 20;
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $url_parts = parse_url($location);
        $host = $url_parts['host'];
        $http_req = 'POST '.$location.' HTTP/1.0'."\r\n";
        $http_req .= 'Host: '.$host."\r\n";
        $http_req .= 'SoapAction: '.$action."\r\n";
        $http_req .= "\r\n";
        $http_req .= $request;
        $port = 80;
        if ($url_parts['scheme'] == 'https')
        {
            $port = 443;
            $host = 'ssl://'.$host;
        }
        $socket = fsockopen($host, $port);
        fwrite($socket, $request);
        stream_set_blocking($socket, false);
        $response = '';
        $stop = microtime(true) + self::TIMEOUT;
        while (!feof($socket))
        {
            $response .= fread($socket, 2000);
            if (microtime(true) > $stop)
            {
                throw new SoapFault('Client', 'HTTP timeout');
            }
        }
        return $response;
    }
}
bwhitehead at tableausoftware dot no dot com dot spam 12-Aug-2011 02:49
Note that the SoapClient.__doRequest() method circumvents the throwing of SoapFault exceptions.

Specifically, if you call the __doRequest() method and it fails, it would normally throw a SoapFault exception.  However, the __doRequest() method doesn't actually throw the exception. Instead, the exception is saved in a class attribute called SoapFault.__soap_fault, and is actually thrown AFTER the __doRequest method completes (but the call stack will show that the exception was created inside the __doRequest method.

I successfully used the following code to query the locally cached exception object that was not thrown:

<?php
$exception = null;
try {
    $result = parent::__doRequest($request, $location, $action, $version, $one_way);
}
catch (SoapFault $sf) {
    //this code was not reached
    $exception = $sf;
}
catch (Exception $e) {
    //nor was this code reached either
    $exception = $e;
}
if((isset($this->__soap_fault)) && ($this->__soap_fault != null)) {
    //this is where the exception from __doRequest is stored
    $exception = $this->__soap_fault;
}

//decide what to do about the exception here
// [enter code here]
//or throw the exception
if($exception != null) {
    throw $exception;
}
//note: you may want to unset the __soap_fault value if you don't want it thrown again up the call stack
?>
psfere at hotmail dot com 21-Sep-2010 09:52
I was needing to add a blank soap header (<SOAP-ENV:Header /> and found no other place that has done this.  The only way I was able to support this was to extend SoapClient and re-define __doRequest.  Hope this helps someone or if there is support for this in the library, please point me in the right direction:

<?php
class MySoapCli extends SoapClient {
  function __doRequest($request, $location, $action, $version) {
    $dom = new DomDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($request);
    $hdr = $dom->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'SOAP-ENV:Header');
    $dom->documentElement->insertBefore($hdr, $dom->documentElement->firstChild);
    $request = $dom->saveXML();
    return parent::__doRequest($request, $location, $action, $version);
  }
}
?>
lepidosteus 19-Nov-2009 02:59
If you happen to get an error during your request which says "SOAP-ERROR: Encoding: Can't decode apache map, only Strings or Longs are allowd as keys", the reason seems to be the response xml using integer for keys and php failling to understand them

Here is something that worked for me (converts integer keys to strings):

<?php
class mySoap extends SoapClient
{
    public function __doRequest($request, $location, $action, $version)
    {
        $result = parent::__doRequest($request, $location, $action, $version);
        $result = str_replace('<key xsi:type="xsd:int">', '<key xsi:type="xsd:string">', $result);
        return $result;
    }
}

// $soap = new mySoap(...
?>
Artur Graniszewski 08-Nov-2009 04:35
Beware of PHP incosistent behaviour in __doRequest() method. It seems that some arguments passed to this method are passed by reference!

If you try to create your own __doRequest() method and store it's arguments as SoapClient properties you will find that after __soapCall all of them will be null or unknown.

<?php
    protected $__soapAction = '';

    public function __doRequest($request, $location, $action, $version, $oneWay = 0) {
        ob_start();
        $this->server->handle($request);
        $response = ob_get_contents();
        ob_end_clean();
        $this->__soapAction = $action;
        return $response;
    }
?>

In above example $this->__soapAction will be null after $obj->__soapCall()..

To store $action value, you must cast it to a string (so PHP will be forced to create a new variable with different memory pointer):

<?php
    public function __doRequest($request, $location, $action, $version, $oneWay = 0) {
        ob_start();
        $this->server->handle($request);
        $response = ob_get_contents();
        ob_end_clean();
        $this->__soapAction = (string)$action;
        return $response;
    }
?>
james dot ellis at gmail dot com 04-Feb-2008 04:12
If your application interacts with SOAP services and you wish to cache the responses for consumption later, then overriding SoapClient::__doRequest is the way to go.

For instance, if you know that the information presented doesn't change that often and you don't want to do a superfluous HTTP request, you can grab a response from a local cache and let SoapClient do the transformation to PHP data types.

<?php
class YourNamespace_SoapClient_Local extends SoapClient {
    protected $cacheDocument = "";
    public function __construct($wsdl, $options) {
        parent::__construct($wsdl, $options);
    }

    /**
     * SetCacheDocument() sets the previously cached document contents
     */
    public function SetCacheDocument($document) {
        $this->cacheDocument = $document;
    }

    /**
     * __doRequest() overrides the standard SoapClient to handle a local request
     */
    public function __doRequest() {
        return $this->cacheDocument;
    }
}

//---- code snippet showing usage within a class
//$document is a cached SOAP response document from a previous request, saved with SoapClient::__getLastResponse() to some cache somewhere
//for the purpose of this example, it is assumed that $this->wsdl, $this->options, $this->method and $this->params are set.

public function SoapRequest($document) {
    $method = $this->method;
    if($document == "") {
        //uncached
        try {
            //default options
            $client = new SoapClient($this->wsdl, $this->options);
            $result = $client->$method($this->params);
            //send the response to the cache
            $this->CacheResponse($client->__getLastResponse());
        } catch(SoapFault $fault) {
            //log something
            return FALSE;
        }
    } else {
        //cached document
        try {
            /**
             * the WSDL needs to be set to allow the method to be called on the client object
             * and to trigger SoapClient to decode the response to native data types
             */
            $client = new YourNamespace_SoapClient_Local($this->wsdl, $this->options);
            $client->SetCacheDocument($document);
            $result = $client->$method($this->params);
        } catch (SoapFault $fault) {
            //log something
            return FALSE;
        }
    }
    return $result;
}
?>

I'll leave you to work out the caching, plenty of options there.. ;)
albert at jool dot nl 26-Mar-2007 06:28
If you want to communicate with a default configured ASP.NET server with SOAP 1.1 support, override your __doRequest with the following code. Adjust the namespace parameter, and all is good to go.

<?php
class MSSoapClient extends SoapClient {

    function __doRequest($request, $location, $action, $version) {
        $namespace = "http://tempuri.com";

        $request = preg_replace('/<ns1:(\w+)/', '<$1 xmlns="'.$namespace.'"', $request, 1);
        $request = preg_replace('/<ns1:(\w+)/', '<$1', $request);
        $request = str_replace(array('/ns1:', 'xmlns:ns1="'.$namespace.'"'), array('/', ''), $request);

        // parent call
        return parent::__doRequest($request, $location, $action, $version);
    }
}

$client = new MSSoapClient(...);
?>

Hope this will save people endless hours of fiddling...
jfitz at spacelink dot com 05-Dec-2006 09:56
Note that __getLastRequest() data are buffered _before_ the call to __doRequest().  Thus any modifications you make to the XML while in __doRequest() will not be visible in the output of __getLastRequest().   This is so in at least v5.2.0
06-Jul-2006 01:17
Do you have problems with the PHP5 SoapClient when you need to send a request to a service with a ComplexType parameter?

Maybe because my service is build in Delphi with REMObjects SDK 3.0 I had the problems, maybe not. Anyway, this was my remedy:
<?php
$versie = new stdClass();//define a basic class object
$versie->versieID = $aVersie->versieID();//fill it with the exact attributes as your complextype Object in the wsdl is
$versie->versieNummer = $aVersie->versieNummer();
$versie->isActief = $aVersie->isActief();

$soapVersieType = new SoapVar($versie , SOAP_ENC_OBJECT, "Versie", "http://127.0.0.1:8999/SOAP?wsdl"); //create the complex soap type, Versie is the name of my complex type in the wsdl, the latter url beeing the location of my wsdl.

try{
  $result =  $soapClient->BewaarVersie($this->sessieId,$soapVersieType); //BewaarVersie is a function derived from my WSDL with two params.
}
catch(SoapFault $e){
  trigger_error('Something soapy went wrong: '.$e->faultstring,E_USER_WARNING);            }
?>
After some more testing i found out that the conversion to the StdClass() object was not required. My 'Versie' local object has the attributes for the 'Versie' wsdl complex type defined as private vars and give no pain when i create the SoapVar with an instance of the local 'Versie' Object.
metator at netcabo dot pt 20-Oct-2005 04:32
You can use this method to correct the SOAP request before sending it, if necessary. You can use the DOM API to accomplish that.

<?php

public ExtendedClient extends SoapClient {

   function __construct($wsdl, $options = null) {
      parent::__construct($wsdl, $options);
   }

   function __doRequest($request, $location, $action, $version) {
      $dom = new DOMDocument('1.0');

      try {

         //loads the SOAP request to the Document
         $dom->loadXML($request);

      } catch (DOMException $e) {
         die('Parse error with code ' . $e->code);
      }

      //create a XPath object to query the request
      $path = new DOMXPath($dom);

      //search for a node
      $nodesToFix = $path->query('//SOAP-ENV:Envelope/SOAP-ENV:Body/path/to/node');

      //check if nodes are ok
      $this->checkNodes($path, $nodesToFix);

      //save the modified SOAP request
      $request = $dom->saveXML();

      //doRequest
      return parent::__doRequest($request, $location, $action, $version);
   }

   function checkNodes(DOMXPath $path, DOMNodeList $nodes) {
      //iterate through the node list
      for ($i = 0; $ < $nodes->length; $i++) {
         $aNode = $nodes->item($i);

         //just an example
         if ($node->nodeValue == null) {
            //do something. For instance, let's remove it.
            $node->parentNode->removeChild($node);
         }
      }
   }
}
?>

This gives the developer the chance to solve interoperability problems with a web service.
SoapClient::__construct
SoapClient::__getFunctions
SoapClient


Возвращает список доступных SOAP функций

SoapClient::__doRequest
SoapClient::__getLastRequest
SoapClient
PHP Manual

SoapClient::__getFunctions

(PHP 5 >= 5.0.1)

SoapClient::__getFunctions — Возвращает список доступных SOAP функций

Описание

public array SoapClient::__getFunctions ( void )

Возвращает массив функций веб-служб, описанных в WSDL.

Замечание:

Эта функция работает только в режиме WSDL.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив (array) прототипов SOAP функций c описанием типа возвращаемого значения, имени функции и параметров с типами.

Примеры

Пример #1 Пример использования SoapClient::__getFunctions()

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

Результат выполнения данного примера:

array(26) {
  [0]=>
  string(70) "ProductInfo KeywordSearchRequest(KeywordRequest $KeywordSearchRequest)"
  [1]=>
  string(79) "ProductInfo TextStreamSearchRequest(TextStreamRequest $TextStreamSearchRequest)"
  [2]=>
  string(64) "ProductInfo PowerSearchRequest(PowerRequest $PowerSearchRequest)"
...
  [23]=>
  string(107) "ShoppingCart RemoveShoppingCartItemsRequest(RemoveShoppingCartItemsRequest $RemoveShoppingCartItemsRequest)"
  [24]=>
  string(107) "ShoppingCart ModifyShoppingCartItemsRequest(ModifyShoppingCartItemsRequest $ModifyShoppingCartItemsRequest)"
  [25]=>
  string(118) "GetTransactionDetailsResponse GetTransactionDetailsRequest(GetTransactionDetailsRequest $GetTransactionDetailsRequest)"
}

Смотрите также

  • SoapClient::SoapClient() - Конструктор SoapClient

User Contributed Notes

hasegeli at arebt dot com 02-Jun-2009 12:19
This function did not work if schema is not in wsdl file.
Dougal Matthews 17-Jul-2008 01:24
example for amazon webservice

<?php

$wsdl_url =
  "http://soap.amazon.com/schemas3/AmazonWebServices.wsdl";
$client     = new SoapClient($wsdl_url);
var_dump($client->__getFunctions());

?>
SoapClient::__doRequest
SoapClient::__getLastRequest
SoapClient


Возвращает последний SOAP-запрос

SoapClient::__getFunctions
SoapClient::__getLastRequestHeaders
SoapClient
PHP Manual

SoapClient::__getLastRequest

(PHP 5 >= 5.0.1)

SoapClient::__getLastRequest — Возвращает последний SOAP-запрос

Описание

public string SoapClient::__getLastRequest ( void )

Возвращает XML, переданный в последнем SOAP-запросе.

Замечание:

Метод работает только для объекта SoapClient, созданного с настройкой trace, равной TRUE.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Последний SOAP-запрос в виде строки с XML.

Примеры

Пример #1 Пример использования SoapClient::__getLastRequest()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

Смотрите также

  • SoapClient::__getLastRequestHeaders() - Возвращает SOAP-заголовки последнего запроса
  • SoapClient::__getLastResponse() - Возвращает последний SOAP-ответ
  • SoapClient::__getLastResponseHeaders() - Возвращает SOAP-заголовки последнего ответа

User Contributed Notes

Anonymous 26-Jan-2010 01:32
Adding htmlentities() can be helpful since it makes the XML visible in your browser without needing to view the source.

<?php

echo "REQUEST:\n" . htmlentities($client->__getLastRequest()) . "\n";

?>
Ersin DOGAN 12-Apr-2009 10:40
I guess many peoples calls getLastRequest and it returns nothing. "Heey where is the my last request". Now we will see our request,  when you created a SoapClient instance, you should give a option parameter as below :

<?php
// below $option=array('trace',1);
// correct one is below
$option=array('trace'=>1);

$client=new SoapClient('some.wsdl',$option);

try{
  $client->aMethodAtRemote();
}catch(SoapFault $fault){
  // <xmp> tag displays xml output in html
  echo 'Request : <br/><xmp>',
  $client->__getLastRequest(),
  '</xmp><br/><br/> Error Message : <br/>',
  $fault->getMessage();
}
?>

"trace" parameter enables output of request. Now, you should see SOAP request.
Omar Nabil 12-Nov-2008 06:14
the getLastResult function doesn't require that the server answers.
as my browser handled and hided the xml code I thought the function doesn't return the last request
SoapClient::__getFunctions
SoapClient::__getLastRequestHeaders
SoapClient


Возвращает SOAP-заголовки последнего запроса

SoapClient::__getLastRequest
SoapClient::__getLastResponse
SoapClient
PHP Manual

SoapClient::__getLastRequestHeaders

(PHP 5 >= 5.0.1)

SoapClient::__getLastRequestHeaders — Возвращает SOAP-заголовки последнего запроса

Описание

public string SoapClient::__getLastRequestHeaders ( void )

Возвращает SOAP-заголовки последнего запроса.

Замечание:

Функция работает только, если объект SoapClient был создан с настройкой trace, равной TRUE.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Заголовки последнего SOAP-запроса.

Примеры

Пример #1 Пример использования SoapClient::__getLastRequest()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

Смотрите также

  • SoapClient::__getLastResponseHeaders() - Возвращает SOAP-заголовки последнего ответа
  • SoapClient::__getLastRequest() - Возвращает последний SOAP-запрос
  • SoapClient::__getLastResponse() - Возвращает последний SOAP-ответ

User Contributed Notes

There are no user contributed notes for this page.
SoapClient::__getLastRequest
SoapClient::__getLastResponse
SoapClient


Возвращает последний SOAP-ответ

SoapClient::__getLastRequestHeaders
SoapClient::__getLastResponseHeaders
SoapClient
PHP Manual

SoapClient::__getLastResponse

(PHP 5 >= 5.0.1)

SoapClient::__getLastResponse — Возвращает последний SOAP-ответ

Описание

public string SoapClient::__getLastResponse ( void )

Возвращает XML, полученный в последнем SOAP-ответе.

Замечание:

Метод работает только для объекта SoapClient, созданного с настройкой trace, равной TRUE.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Последний SOAP-ответ в виде строки с XML.

Примеры

Пример #1 Пример использования SoapClient::__getLastResponse()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Ответ:\n" . $client->__getLastResponse() . "\n";
?>

Смотрите также

  • SoapClient::__getLastResponseHeaders() - Возвращает SOAP-заголовки последнего ответа
  • SoapClient::__getLastRequest() - Возвращает последний SOAP-запрос
  • SoapClient::__getLastRequestHeaders() - Возвращает SOAP-заголовки последнего запроса

User Contributed Notes

bshafs at gmail dot com 22-Jun-2011 12:45
You don't need to surround SoapClient in a try-catch block.  Just set the "exceptions" option to false, and the SoapFault instance will be returned instead of thrown.
ceo at l-i-e dot com 04-Jan-2006 01:31
D'oh!
That example needs:
$soapClient = new SoapClient($url, array('trace'=>1));
to turn ON tracing in the first place.
ceo at l-i-e dot com 04-Jan-2006 01:30
You almost for sure will need to wrap a try/catch block around your SOAP call in order to use these to debug something that's not working.

Otherwise, PHP throws a fatal error before you can execute this function.

For example:
<?php
    $soapClient = new SoapClient($url);
    echo htmlentities($soapClient->__getFunctions());
    //Assume that has output 'someFunction' (among others)
    try {
        $results = $soapClient->someFunction(...);
    }
    catch (SoapFault $soapFault) {
        var_dump($soapFault);
        echo "Request :<br>", htmlentities($soapClient->__getLastRequest()), "<br>";
        echo "Response :<br>", htmlentities($soapClient->__getLastResponse()), "<br>";
    }
?>

Without try/catch, your just get the Fatal Error and PHP commits suicide before you can call __getLastRequest/__getLastResponse
SoapClient::__getLastRequestHeaders
SoapClient::__getLastResponseHeaders
SoapClient


Возвращает SOAP-заголовки последнего ответа

SoapClient::__getLastResponse
SoapClient::__getTypes
SoapClient
PHP Manual

SoapClient::__getLastResponseHeaders

(PHP 5 >= 5.0.1)

SoapClient::__getLastResponseHeaders — Возвращает SOAP-заголовки последнего ответа

Описание

public string SoapClient::__getLastResponseHeaders ( void )

Возвращает SOAP-заголовки последнего ответа.

Замечание:

Функция работает только, если объект SoapClient был создан с настройкой trace, равной TRUE.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Заголовки последнего SOAP-ответа.

Примеры

Пример #1 Пример использования SoapClient::__getLastResponse()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "ЗАГОЛОВКИ ОТВЕТА:\n" . $client->__getLastResponseHeaders() . "\n";
?>

Смотрите также

  • SoapClient::__getLastRequestHeaders() - Возвращает SOAP-заголовки последнего запроса
  • SoapClient::__getLastRequest() - Возвращает последний SOAP-запрос
  • SoapClient::__getLastResponse() - Возвращает последний SOAP-ответ

User Contributed Notes

jeroen{at}asystance{dot}nl 17-Aug-2009 03:20
Note SoapClient does not wait for a response for one-way operations (i.e. <wsdl:operation>s that do not have a <wsdl:response>)! To see if a request failed, use
$sc = new SoapClient( 'some.wsdl', array('features'=>SOAP_WAIT_ONE_WAY_CALLS));

See http://bugs.php.net/bug.php?id=36083 and http://bugs.php.net/bug.php?id=49278
SoapClient::__getLastResponse
SoapClient::__getTypes
SoapClient


Возвращает список SOAP-типов

SoapClient::__getLastResponseHeaders
SoapClient::__setCookie
SoapClient
PHP Manual

SoapClient::__getTypes

(PHP 5 >= 5.0.1)

SoapClient::__getTypes — Возвращает список SOAP-типов

Описание

public array SoapClient::__getTypes ( void )

Возвращает массив типов, описанных в WSDL для веб-службы.

Замечание:

Эта функция работает только в режиме WSDL.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Массив (array) SOAP-типов с подробным описанием всех структур и типов.

Примеры

Пример #1 Пример использования SoapClient::__getTypes()

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getTypes());
?>

Результат выполнения данного примера:

array(88) {
  [0]=>
  string(30) "ProductLine ProductLineArray[]"
  [1]=>
  string(85) "struct ProductLine {
 string Mode;
 string RelevanceRank;
 ProductInfo ProductInfo;
}"
  [2]=>
  string(105) "struct ProductInfo {
 string TotalResults;
 string TotalPages;
 string ListName;
 DetailsArray Details;
}"
...
  [85]=>
  string(32) "ShortSummary ShortSummaryArray[]"
  [86]=>
  string(121) "struct GetTransactionDetailsRequest {
 string tag;
 string devtag;
 string key;
 OrderIdArray OrderIds;
 string locale;
}"
  [87]=>
  string(75) "struct GetTransactionDetailsResponse {
 ShortSummaryArray ShortSummaries;
}"
}

Смотрите также

  • SoapClient::SoapClient() - Конструктор SoapClient

User Contributed Notes

There are no user contributed notes for this page.
SoapClient::__getLastResponseHeaders
SoapClient::__setCookie
SoapClient


Устанавливает cookie

SoapClient::__getTypes
SoapClient::__setLocation
SoapClient
PHP Manual

SoapClient::__setCookie

(PHP 5 >= 5.0.4)

SoapClient::__setCookie — Устанавливает cookie

Описание

public void SoapClient::__setCookie ( string $name [, string $value ] )

Определяет cookie, которые будут отправлены с SOAP-запросами.

Замечание:

Вызов этого метода отразится на всех последующих вызовах методов SoapClient.

Список параметров

name

Имя cookie.

value

Значение cookie. Если не указано, то cookie удаляется.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

Jaygiri Goswami 17-Dec-2011 01:22
You can access the cookies sent by SOAP server using $client->_cookies

Most you need to send session cookies back to server.
lukasz at szostak dot biz 14-Aug-2006 10:53
On the server side you can access the cookie via $_COOKIE['cookie_name'].

Also remember that since HTTP is a stateless protocol, you have to send the cookie with every single SOAP call in order for it to be visible at server site.

It seems obvious but might save one a lot of time.
SoapClient::__getTypes
SoapClient::__setLocation
SoapClient


Устанавливает адрес используемой веб-службы

SoapClient::__setCookie
SoapClient::__setSoapHeaders
SoapClient
PHP Manual

SoapClient::__setLocation

(PHP 5 >= 5.0.1)

SoapClient::__setLocation — Устанавливает адрес используемой веб-службы

Описание

public string SoapClient::__setLocation ([ string $new_location ] )

Устанавливает URL, затрагивающий последующие SOAP-запросы. Эквивалентна настройке location, указываемой в конструкторе SoapClient.

Замечание:

Вызов метода необязателен. По умолчанию SoapClient использует адрес из WSDL-файла.

Список параметров

new_location

Новый URL.

Возвращаемые значения

Старый URL.

Примеры

Пример #1 Пример использования SoapClient::__setLocation()

<?php
$client = new SoapClient('http://example.com/webservice.php?wsdl');

$client->__setLocation('http://www.somethirdparty.com');

$old_location = $client->__setLocation(); // сбрасывает настройку адреса (location)

echo $old_location;

?>

Результатом выполнения данного примера будет что-то подобное:

http://www.somethirdparty.com

Смотрите также

  • SoapClient::SoapClient() - Конструктор SoapClient

User Contributed Notes

There are no user contributed notes for this page.
SoapClient::__setCookie
SoapClient::__setSoapHeaders
SoapClient


Устанавливает SOAP-заголовки для последующих вызовов

SoapClient::__setLocation
SoapClient::__soapCall
SoapClient
PHP Manual

SoapClient::__setSoapHeaders

(PHP 5 >= 5.0.5)

SoapClient::__setSoapHeaders — Устанавливает SOAP-заголовки для последующих вызовов

Описание

public bool SoapClient::__setSoapHeaders ([ mixed $soapheaders ] )

Определяет заголовки, которые буду отправлены с SOAP-запросами.

Замечание:

Вызов этого метода перезаписывает предыдущие значения.

Список параметров

soapheaders

Устанавливаемые заголовки. Это может быть объект SoapHeader или массив объектов SoapHeader. Если не указаны или равны NULL, то заголовки удалятся.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования SoapClient::__setSoapHeaders()

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$header = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$client->__setSoapHeaders($header);

$client->__soapCall("echoVoid", null);
?>

Пример #2 Установка нескольких заголовков

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$headers = array();

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world again');

$client->__setSoapHeaders($headers);

$client->__soapCall("echoVoid", null);
?>

User Contributed Notes

mlconnor at yahoo dot com 11-Nov-2010 01:28
Does anyone know how to get the response headers?  The getLastResponseHeader returns a string response, not the complex object I was expecting...
peamik1953 at NOSPAM dot btinternet dot com 12-Jul-2010 11:06
You cannot add an additional header. If you want two headers, and one already exists, first delete it with $client->__setSoapHeaders(NULL). Then issue $client->__setSoapHeaders($headers) where $headers is an array of soapHeader() objects.
kedar dot purohit @ mavs dot uta dot edu 10-Sep-2009 12:58
To create complex SOAP Headers, you can do something like this:

Required SOAP Header:

<soap:Header>
    <RequestorCredentials xmlns="http://namespace.example.com/">
      <Token>string</Token>
      <Version>string</Version>
      <MerchantID>string</MerchantID>
      <UserCredentials>
        <UserID>string</UserID>
        <Password>string</Password>
      </UserCredentials>
    </RequestorCredentials>
</soap:Header>

Corresponding PHP code:

<?php

$ns = 'http://namespace.example.com/'; //Namespace of the WS.

//Body of the Soap Header.
$headerbody = array('Token' => $someToken,
                    'Version' => $someVersion,
                    'MerchantID'=>$someMerchantId,
                      'UserCredentials'=>array('UserID'=>$UserID,
                                             'Password'=>$Pwd));

//Create Soap Header.
$header = new SOAPHeader($ns, 'RequestorCredentials', $headerbody);

//set the Headers of Soap Client.
$soap_client->__setSoapHeaders($header);

?>
jayrajput at gmail dot com 30-Mar-2009 01:07
With multiple SOAP headers, when using SoapVar for creation of SoapHeader the PHP code just terminates (command terminated). I am not sure if that is a bug.

Without the SOAPVar the code worked fine for me

There are different way to creart SoapHeader I was using SoapVar and the code was not working. I am still a novice with this SOAP stuff.

Tried using normal strings and it worked fine. SoapHeader can take SoapVar or string as the third argument.

my code:

<?php
// first soap header.
$var = new SoapVar($header, XSD_ANYXML);
$soapHeader = new SoapHeader(NAME_SPACE, "Security", $var);
// second soap header.
$var2 = new SoapVar($header2, XSD_ANYXML);
$soapHeader2 = new SoapHeader(DIFF_NAME_SPACE, "ID", $var2);

$client = new SoapClient($wsdl, array("location" => $location));

$headers = array();
$headers[] = $soapHeader;
$headers[] = $soapHeader2;

// Here my code was just terminating.
$client->__setSoapHeaders($headers);
?>
SoapClient::__setLocation
SoapClient::__soapCall
SoapClient


Вызывает SOAP-функцию

SoapClient::__setSoapHeaders
SoapClient::SoapClient
SoapClient
PHP Manual

SoapClient::__soapCall

(PHP 5 >= 5.0.1)

SoapClient::__soapCall — Вызывает SOAP-функцию

Описание

public mixed SoapClient::__soapCall ( string $function_name , array $arguments [, array $options [, mixed $input_headers [, array &$output_headers ]]] )

Это низкоуровневая функция API, которая позволяет сделать SOAP-вызов. Обычно в WSDL-режиме SOAP-функции вызываются как методы объекта SoapClient. Этот же метод полезен в не WSDL-режиме, когда soapaction не известен, uri отличается от URI по умолчанию или когда отправляются и/или принимаются SOAP-заголовки.

В случае ошибки, вызов SOAP-функции может привести к исключению или к возврату объекта SoapFault, если исключения отключены. Проверить, что вызов функции завершился неудачей, можно обработав исключение SoapFault или проверить результат с помощью функции is_soap_fault().

Список параметров

function_name

Имя вызываемой SOAP-функции.

arguments

Массив аргументов, передаваемых в функцию. Это может быть упорядоченный или ассоциативный массив.

options

Ассоциативный массив настроек, передаваемых клиенту.

Настройка location - URL удаленной веб-службы.

Настройка uri - целевое пространство имен SOAP-службы.

Настройка soapaction - действия для вызова.

input_headers

Массив заголовков, которые будут отправлены с SOAP-запросом.

output_headers

Если указан, то этот массив будет заполнен заголовками SOAP-ответа.

Возвращаемые значения

SOAP-функции могут возвращать одно или несколько значений. Если SOAP-функция возвращает только одно значение, то __soapCall вернет простое значение (например, число, строку и так далее). Если возвращается несколько значений, то __soapCall вернет ассоциативный массив именованных возвращаемых параметров.

В случае ошибки, если объект SoapClient был создан с настройкой trace, установленной в FALSE, будет возвращен объект SoapFault.

Примеры

Пример #1 Пример использования SoapClient::__soapCall()

<?php

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);

$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c), NULL,
                    new SoapHeader(), $output_headers);

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->SomeFunction($a, $b, $c);
$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c),
                    array('soapaction' => 'some_action',
                          'uri'        => 'some_uri'));
?>

Смотрите также

  • SoapClient::SoapClient() - Конструктор SoapClient
  • SoapParam::SoapParam() - SoapParam constructor
  • SoapVar::SoapVar() - SoapVar constructor
  • SoapHeader::SoapHeader() - SoapHeader constructor
  • SoapFault::SoapFault() - SoapFault constructor
  • is_soap_fault() - Checks if a SOAP call has failed

User Contributed Notes

Chris Gunawardena 14-May-2012 03:35
For all those poor souls getting the "Fatal error: Uncaught SoapFault exception: [soap:Server] Server was unable to process request. ---> Object reference not set to an instance of an object. in xyz.php"  using WSDL.

Aparently all sorts of things cause this but for me the fix was to passin all parameters (not only the requied onces). I just passed the rest as empty strings and the problem was solved.

example below
    <?php
    ini_set('display_errors', true);
    ini_set("soap.wsdl_cache_enabled", "0");
    error_reporting(E_ALL);
    $client = new SoapClient('http://example.com/searchhsd.asmx?WSDL', array(    'trace' => true,  'exceptions' => true,
                                                                                'connection_timeout'=>9999,
                                                                                'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
                                                                                'soap_version' => SOAP_1_1, 'encoding' => 'ISO-8859-1',
                                                                                ));
    //var_dump($client->__getFunctions());
    //var_dump($client->__getTypes());

    $search_results_xml = $client->HSDSiteSearch ( array(    'startPos' => 1,
                                                            'maxResults' => 100,
                                                            'resultOrderVal' => 'Site',
                                                            'searchSimilarNames' => true,
                                                            'name' => '',
                                                            'includePracName' => true,
                                                            'suburbsAndPostcodes' => 'Melbourne',
                                                            'searchSurroundingSuburbs' => true,
                                                            'pcpDesc' => '',
                                                            'cityOrShireDesc' => '',
                                                            'siteGPDivDesc' => '',
                                                            'serviceCategoryDesc' => '',
                                                            'serviceTypeDesc' => '',
                                                            'keywords' => '',
                                                            'targetGroup' => '',
                                                            'freeServicesOnly' => false,
                                                            'afterHoursOnly' => false,
                                                            'startTimeDesc' => '',
                                                            'endTimeDesc' => '',
                                                            'openOnDesc' => '',
                                                            'pracFamilyName' => '',
                                                            'pracGivenName' => '',
                                                            'pracNoAppointmentRequired' => false,
                                                            'pracSpecialInterests' => '',
                                                            'pracSexDesc' => '',
                                                            'pracLanguageSpokenDesc' => '',
                                                            'pracSpecialityDesc' => '',
                                                            'pracEthnicityDesc' => ''
                                                            ) );

    print_r($search_results_xml);

    /*print "Request: \\n".
    $client->__getLastRequestHeaders() ."\\n";
    print "Request: \\n".
    $client->__getLastRequest() ."\\n";
    print "Response: \\n".
    $client->__getLastResponseHeaders()."\\n";
    print "Response: \\n".
    $client->__getLastResponse()."\\n";    */

    ?>
orrd101 at gmail dot com 10-May-2012 12:18
If you need CDATA from the returned value of the SOAP function you have to do something like this...

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$client->SomeFunction();
$responseXML = $client->__getLastResponse();
$response = simplexml_load_string($responseXML, 'SimpleXMLElement', LIBXML_NOCDATA);
?>
snuufix+nospam at gmail dot com 11-Feb-2011 03:23
I am using SOAP call response headers to sign request results.

After alot of hours, I finally got the best way to get SOAP response headers (other than parsing __getLastResponse() witch requires trace option enabled) is using __soapCall() wrapper.

You can extend SoapClient class and wrap some functions to make sure you get the headers.

<?php

class API extends SoapClient
{

    // ... Constructor, etc.

    // Get SOAP Server response headers
    public function __soapCall($function, $arguments, $options = array(), $input_headers = null, &$output_headers = null)
    {
        parent::__soapCall($function, $arguments, $options, $input_headers, $output_headers);

        print_r($output_headers); // Array of response headers
    }

    // If you are using WSDL you need this, so you still can call functions directly without calling __soapCall manualy
    public function __call($func, $args)
    {
        return $this->__soapCall($func, $args);
    }

?>
niko dot hujanen at gmail dot com 09-Nov-2010 11:06
I was integrating a local warehouse system with a SOAP to our system and noticed some things.

1) Service uses "dot-namespacing" (fe. Item.Price) I classmapped this to Item_Price and used magical __get() and __set() to strip off 'Item.' from variable names. Works like a charm.

Example:
<Item.Price>1.52</Item.Price>

<?php
class Item_Price {
    public $price;
    public function __get($field) { $field = str_replace('Item.', '', $field); return $this->$field; }
    public function __set($field, $value) { $field = str_replace('Item.', '', $field); $this->$field = $value; }
?>

2) I noticed that classmapping a segment with attributes and value is possible. Class uses variables as attributes and $_ is the value.

Example:
<?php
class Foo {
    public $item = 'Bar';
    public $_ = 'Value here';
}
?>
Turns to <Foo item="Bar">Value here</Foo>

Example of using classes with soapcalls:
<?php
    $client = ExtendSoapClient::getInstance();
    $foo = new Foo();
    $response = $client->sendFoo($foo);
?>

Posted these since I think the documentation is lacking and very obsolete. Hopefully someone's burden eases.
Anonymous 29-Sep-2010 02:11
For those getting "SOAP-ERROR: Encoding: object hasn't 'newOrderRequest' property" type errors, there is an additional bug that doesn't seem to be documented anywhere.

For 2+ elements, you need a numeric array but the keys *must* start from 0 and *must* be sequential. If not, you will get this validation error. The fix is as simple as sending the array through array_values().
yoyoy at yopmail dot com 24-Sep-2010 02:44
Please, please please ...
is it possible to find the name of parameters of any function ?

example

$params = array( 'I_DONT_KNOW_THIS_NAME'=>$val_1, 'I_WANT_TO_FIND_THIS_NAME'=>$val_2 );
$client->call('MethodName', array('parameters' => $params));

thanks
james dot ellis at gmail dot com 09-Jun-2010 07:12
If you are using this method, remember that the array of arguments need to be passed in with the ordering being the same order that the SOAP endpoint expects.

e.g
<?php
//server expects: Foo(string name, int age)

//won't work
$args = array(32, 'john');
$out = $client->__soapCall('Foo', $args);

//will work
$args = array('john', 32);
$out = $client->__soapCall('Foo', $args);
?>
jarrod at squarecrow dot com 16-Dec-2009 12:59
If you find yourself needing to consume entire datatables from .NET there are two quick ways to do this.

If you are writing the web services yourself there is a very handy trick to return a datatable as a schema-less XML document. Create a new module file in .NET with this code -

Imports System.Xml

Module PHPDatatable
    Public Function parse(ByVal dt As DataTable)
        Dim xmlstream As New StringBuilder
        Dim write As XmlWriter = XmlWriter.Create(xmlstream)
        write.WriteProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
        dt.WriteXml(write)
        Return xmlstream.ToString()
    End Function
End Module

To use it (where MyTable is the datatable we are using.......)

return PHPDatatable.parse(MyTable)    'your return type will need to be a STRING.

Back in PHP, after you have made your SOAP call and have the results you can use SimpleXML to parse out the datatable into an array of objects like so (where $soap are my soap results.......)

<?php

$datatable = simplexml_load_string($soap->myfunctionResult);

?>

In the unfortunate situation where you have no choice but to consume a full-blown datatable (ie: you aren't writing the web services yourself) I have a basic SOAP client available on Codeplex that can parse .NET datatables into an array of objects.  http://superdotnet.codeplex.com/

Both methods are fairly simply to implement, and should save you the headache of mapping out your datatables to prebaked .NET objects and manually setting each value.
jarrod at squarecrow dot com 10-Aug-2009 07:37
When dealing with .NET web services, its a good to remember that moving data back and forth between PHP and .NET can be a little cumbersome if you aren't familiar with the object structures of both.

.NET will return everything inside of an object - usually your function name with "Result" tagged onto the end.

Example.

<?php
$client = new soapclient(SOAP_ADDRESS);
$objectresult = $client->GetDataByID(array('PeopleVendorsID'=> 'N21248'));
?>

.... where GetDataByID is my .NET web service function, PeopleVendorsID is name of the parameter I pass it, and "N21248" happens to be the value of the parameter.

.NET was supposed to return an array to $objectresult but instead I found myself with a triple-nested object.

Basically, if you ever find yourself in a situation where you can't seem to access your data, make use of var_dump.

<?php
var_dump($objectresult);
?>

This will print out a very handy array/object structure for you to sift through - invaluable if you're dealing with cryptic results from .NET.
l dot tomov at raz dot bg 01-Aug-2009 06:47
I was trying to call a .net service and it took me quite some hours to get the exact object structure.
I was getting a "SOAP-ERROR: Encoding: object hasn't 'newOrderRequest' property"

This is how I got it working:

<?php
class NewOrderRequestElement
{
    public $merchantID = "1234";
    public $terminalID = "001";
}

class NewOrder
{
    public $newOrderRequest;
}

$no = new NewOrder;
$no->newOrderRequest = new NewOrderRequestElement;

$response = $client->NewOrder($no);

?>

And in order to get the exact class structure, you need to call
$client->__getTypes();

Hope this helps somebody.
jayrajput at gmail dot com 26-Jun-2009 09:56
I see notes from lot of users where they wanted to convert the response to an array.

Problem description as told by one of the user:
--------------------------------------------------------
When a SOAP call returns an array [max_elements=">1"] - you may not actually get an array... (this may be a fault in the wsdl, but it's certainly a potential headache).

foreach($result->field as $field) {
  doSomethingWith($field);
}

With more than 1 <field>, you'll loop through the <field> tags (as expected)...

However, with exactly 1 <field>, you'll instead loop through the child elements of the first <field> (almost certainly *not* what you wanted to happen)...

Solution:
-----------
Use SoapClient features option:

new SoapClient($wsdl, array("features" => SOAP_SINGLE_ELEMENT_ARRAYS);

and then the PHP takes care of converting result to an array.

I have been bitten by this before and never looked into this option ...duh...duh
lesley at casbah dot com dot au 21-Apr-2009 06:55
If you are calling a weblogic service with a certificate and you are getting this error on the soap method call statement:

[EJB:010160]Security Violation: User: '<anonymous>' has insufficient permission to access EJB: type=<ejb>, application=app2_0_52_3, module=appsejb.jar, ejb=AppMethod, method=AppMethod, methodInterface=Remote, signature={java.lang.String}.

then check the wsdl in the soap open call - it must be https.  Supplied with an http wsdl this took some time to figure out.

<?php
    $client = new SoapClient("https://example.com/AppWs/Service?WSDL",
                array('trace'=>true,
                      'exceptions'=>true,
                      'local_cert' => "/var/www/html/app/newcert.pem",
                      'passphrase' => "thepassphrase"));
    $response = $client->__soapCall("MyMethod", array("param1" => $value1));
?>

Thanks to the authors for their comments on enabling openssl and curl by uncommenting extension=php_opensll.dll and extension=php_curl.dll in php.ini.  Also for Olaf's instructions "append the content of the private key file and the certificate file to a single file". I did this using copy command on the DOS prompt:

copy mycert.pem+mykey.pem newcert.pem
Tim Williams 08-Apr-2009 06:55
One little gotcha when passing the parameters where you need to have attributes and a simpletype value:

To get the xml

<foo bar="moo">cheese</foo>

You'd pass in:

<?php
array("foo" => array("_" => "cheese", "bar"=>"moo"));
?>

See that "_" bit? It really wasn't obvious from the documentation.
deWarlock 02-Apr-2009 04:10
The most annoying thing is that you'll get no warning trying to pass object not matching wsdl e.g. if server expects smth like $Object->expName->... and you would pass $Object->otherName the client will send empty request without notifying you.
Also pay attention that names are key sensitive.

In my case I spent hours trying to pass $Post->Lead->... object instead of $Post->lead-> ...
Shto 03-Mar-2009 03:17
One thing to note.

This happened to me and it took a while until I discovered what the problem was.

I was trying to get .NET objects from a provided web service, however it always seemed to return empty objects. It did return the backbone, but nothing within the objects that made up the structure.

Anyhow, it seems that you have to be very precise with the arrays when calling these functions. Par example, do this:

<?php
$obj = $client->__soapCall($SOAPCall, array('parameters'=>$SoapCallParameters));
?>

meaning that you must put an array as the second argument with 'parameters' as the key and the soap call parameters as the value.

Also make sure that the parameter variable, in my case $SoapCallParameters is in the form of what is requested by the webservice.

So, don't just make an array of the form:
<?php

(
   [0] => 'Mary',
   [1] => 1983
)

?>

but if the webservice requests a 'muid' variable as 'Mary' and a 'birthyear' as 1983, then make your array like this:

<?php

(
   [muid] => 'Mary',
   [birthyear] => 1983
)

?>

The above arrays refer to the $SoapCallParameters variable.

Hope this helps somebody, not having to spend too much time figuring out the problems.
dennis at born05 dot nl 04-Feb-2009 09:43
To properly override the __soapCall() method use the following syntax:

<?php
public function __soapCall ($function_name, $arguments, $options = null, $input_headers = null, &$output_headers = null)
{
    // your code goes here..
    return parent::__soapCall($function_name, $arguments, $options, $input_headers, $output_headers);
}
?>

This had me puzzled for a while..
uwe dot trotzek at gmx dot de 06-Jan-2009 01:07
Receiving .NET Datatables in PHP:

<?php
        public function getDataBySQL($strSQL){
            $arrParams = array( 'strSQL' => $strSQL);

            try{
                 $arrOptions = array('location' => WBSRV_URI);

                 $this->_sclWebService = new  SoapClient(WBSRV_WSDL_PATH, $arrOptions);

                 $dt = $this->_sclWebService
                         ->getTableFromSQL($arrParams)
                         ->getTableFromSQLResult
                         ->any;

                 $dt = simplexml_load_string($dt)->NewDataSet;

                 return $dt;
             }catch (Exception $e){
                 echo $e->getMessage();
             }
        }
?>
The serialized xml String has to be converted first using the function simplexml_load_string.
Now the complete dataset is represented in $dt
stephan 18-Sep-2008 10:23
When I try to convert result to array I get "Cannot use object of type stdClass as array ..." so I use next:

<?php
function toArray($obj){
    $return=array();
    if (is_array($obj)) {
        $keys=array_keys($obj);
    } elseif (is_object($obj)) {
        $keys=array_keys(get_object_vars($obj));
    } else {return $obj;}
    foreach ($keys as $key) {
        $value=$obj->$key;
        if (is_array($obj)) {
            $return[$key]=toArray($obj[$key]);
        } else {
            $return[$key]=toArray($obj->$key);
        }
    }
    return $return;
}
?>
skunkrecords at gmail . com 30-Aug-2008 10:09
I spent an entire day trying to figure out why I couldn't interface with a .net server! Read  sethm at uoregon dot edu's comment. It will save your life :P
elementation at gmail dot com 30-Jul-2008 12:15
Just as a note, when working with base64'd content, calling a function which returns a base64'd binary value will automagically base64_decode() the value for you, rendering any data unusable if you base64_decode() again.
dess at dessben dot net 30-Apr-2008 01:51
I had several problems with the error "Object reference not set to an instance of an object." with .NET Webservices.
This problem also can be a "non-type" problem.

I can resolved this problem, defining previously the type of the soap functions arguments, with settype() function.

<?php
settype($foo, "string");
?>
sethm at uoregon dot edu 25-Mar-2008 03:05
Trying to connect to a .NET webservice using the PHP SOAP client, we ran into much strangeness.

When using __soapCall do:
$params = array('a'=>$a, 'b'=>$b);
$result = $client->__soapCall('someFunction', array($params));

When using calling the function directly use:
$params = array('a'=>$a, 'b'=>$b);
$result = $client->someFunction($params);

If $params isn't associative, the client doesn't form the call correctly. Calling it other ways lead to having the first parameter dropped or the parameters not being displayed in the request.
Alejandro Cavallo 19-Mar-2008 07:38
I get the same problem reported above by ryan:
"ryan at grunt dot tv
22-Sep-2005 01:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason."

When defined variable soapVar I assigned the type XSD_STRING rather than as XSD_ANYXML.
And when calls to the function you must pass the soapVar in an associative array.

For example if the function (called myFunc) expect a parameter called xmlInput you should do something like this:
$soapvar = new SoapVar($query, XSD_STRING);
$result = $client->myFunc(array('xmlInput'=>$soapvar));

This XML fragment are wrapped around xmlImput tags.-
stefan at datax dot biz 24-Oct-2007 07:28
The call to __soapCall returned an object to me either. This is the function which makes my life easier:

function obj2array($obj) {
  $out = array();
  foreach ($obj as $key => $val) {
    switch(true) {
        case is_object($val):
         $out[$key] = obj2array($val);
         break;
      case is_array($val):
         $out[$key] = obj2array($val);
         break;
      default:
        $out[$key] = $val;
    }
  }
  return $out;
}

Usage:
...
$response = $client ->__soapCall("track", array('parameters' => $request));
$response = obj2array($response);

Hope it helps.
stephen at sekka dot co dot uk 01-Aug-2007 07:30
If you are trying to use a .NET web service and every call you make returns the following error,

"Server was unable to process request. --> Object reference not set to an instance of an object."

... then you need to pass Objects into the method rather than the standard variables.

To do this, you need to create mini classes that have properties of the variables you are trying to pass, map them to the types of the WSDL, then pass them into the methods.

Here is an example,

<?php

class Test {
    public $account;
    public $password;
}

$parameters = new Test;
$parameters -> account = $username;
$parameters -> password = $password;

try {
    $client = new SoapClient ("https://www.somewebsite.com/Service.asmx?wsdl", array('classmap' => array('CheckUser' => 'Test')));
    $client -> CheckUser ($parameters);
    echo "Valid Credentials!";
}
catch (Exception $e) {
    echo "Error!<br />";
    echo $e -> getMessage ();
}

?>
andrewa at bigpond dot net dot au 16-Jun-2007 04:14
In response to dumbo's comment on the request not always returning an array:

"more than 1 <field>, you'll loop through the <field> tags (as expected)..."

Here's some quick code to get around it:

<?php
function getArrayFromResponse($data)
{
    if (sizeof($data) < 2) {
        $new = array();
        $new[] = $data;
        return $new;
    }

    return $data;
}
?>

Usage:

$result = $soap->__soapCall('DoSomething', array('parameters' => $param))

foreach(getArrayFromResponse($result['ResponseKeyHere']) as $a) {
 // $a will always be an object
}
zeta2ste2000 at yahoo dot it 11-May-2007 01:10
When I have to manage a long number in the header,
 the __soapCall function returns a float number in exponential format.
The returned value can't be sent to the server because it is different
from the original one ( for the floating point values limited precision ).

Example :

// Server sended value : 339051398236687110
$soapclient->__soapCall('beginSession',$parameters, null, null,$header);

echo $header["sessionID"];   // returns 3.3905139823669E+17 or 339051398236687050 ( converted to sting)
                            // and that is different from the original 339051398236687110

$strNum =  $soapclient->__getLastResponse();

preg_match("([0-9-]{19,20})", $strNum, $args); // Extracts the correct sessionID value as a string
$headers = new SoapHeader( "http://xml.apache.org/axis/session", "sessionID", $args[0]);

$soapclient->__soapCall('nextCall', $parameters, null, $headers);
bliu at computer dot org 16-Apr-2007 06:17
Using  wsdl file automatically generated by the jboss4.2CR1 deployer,
I tried dozens of methods to marshal parameters to a JAXWS endpoint. And the service constantly got null parameters. At last, I found the right way to call is
<?
        $params = array('param1'=>"foo", 'param2'=>"bar");
        $client->__soapCall('yourMethod', array('parameters' => $params));
?>
By this way, the parameters' names and values are correctly enclosed by the method name, and the service gives expected replies.
dumbo 02-Apr-2007 06:02
Note that when a SOAP call returns an array [max_elements=">1"] - you may not actually get an array... (this may be a fault in the wsdl, but it's certainly a potential headache).

foreach($result->field as $field) {
  doSomethingWith($field);
}

With more than 1 <field>, you'll loop through the <field> tags (as expected)...

However, with exactly 1 <field>, you'll instead loop through the child elements of the first <field> (almost certainly *not* what you wanted to happen)...
GoodHater 14-Mar-2007 07:20
I would just like to add to OrionI's example that if the result is an array eg int, int, string, string then those values can be retrieved as follows:

<?php
...
$simpleresult = $objectresult->SumResult;
echo $simpleresult->element name;
temp at mailinator dot com 30-Jan-2007 04:43
The options in the third argument is documented in http://php.net/manual/en/function.soap-soapclient-construct.php
paulsjv at gmail dot com 11-Jan-2006 07:44
I was working with SOAP for the first time and I had to create a client that sent a date range to a WSDL (Web Services Description Language) to return some information I needed.  I didn't know how to pass the params and there really was no documentation about it.  The main thing you have to make sure to do is when you pass params to a method that is definied by the WSDL that you are calling is that you use the same param name for the key of the array or the object variable as shown below.  Also, if you don't know what the methods/functions that a WSDL has or the params that you need to pass it you can use the __getFunctions() and __getTypes() methods after you declare your new SoapClient.

<?php
// From and to are the two params that the execute function needs
// when called from the WSDL so make you to have them as the
// key to an array like below
$params["From"] = "06/01/2005"; // also can use $params->From = "date";
$params["to"] = "12/31/2005"; // also can use $params->to = "date";

$client = new SoapClient("some.wsdl");

try {
        print($client->execute($params));
} catch (SoapFault $exception) {
        echo $exception;
}
?>
ryan at grunt dot tv 21-Sep-2005 09:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason.

Therefore, to get this to work you must either register the XSD_ANYXML #define as a PHP constant, or use the integer value of the constant when creating the SoapVar, which is 147.

$soapvar = new SoapVar($xml_text, 147);

$params = array("ItemXml" => $soapvar, "PropertyView" => "blah");
$result = $this->soapclient->__soapCall("SaveItem", array("parameters"=>$params), null, $this->soapheaders);

However, this still doesnt give the correct result. For some reason, the ItemXml parameter node is not wrapped around the associated xml parameter in the soap request, and the following soap is produced (assumming '<item>blah</item>' is used as the $xml_text):

<SOAP-ENV:Envelope xmlns:SOAP-ENV="..." xmlns:ns1="...">
<SOAP-ENV:Header>...</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:SaveItem>
<item>blah</item>
<ns1:PropertyView>blah</ns1:PropertyView>
</ns1:SaveItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
DesmondJ 04-May-2005 03:36
Following OrionI's example:

<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "-1"
?>

Please note that the lines:

"$client->Sum($params);"

and

"$simpleresult = $objectresult->SumResult;"

are based off of each other. If your web service function is called "Sum", then add "Result" to the end of it to get the results of the call.

EG:

<?php
 $client = new SoapClient("http://server/mathservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Minus($params); // note the name of the function is "Minus"
 $simpleresult = $objectresult->MinusResult; // note the name of the result is referenced as "MinusResult"
 print($simpleresult); //produces "5"
?>
OrionI 18-Apr-2005 07:27
Correction on the previously submitted code snippet...the incoming parameter for .NET also has to be in object or array form for it to be correctly converted to the XML form that .NET expects (as already mentioned by Llu?s P?mies). The full example (when using WSDL) should be like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $params->param1 = $value1;
 $params->param2 = $value2;
 $objectresult = $client->MyMethod($params);
 $simpleresult = $objectresult->MyMethodResult;
?>
So if you have a C# function like this:
//sumservice.asmx
...
[WebMethod]
public int Sum(int a, int b)
{
  return a + b;
}
...
The PHP client would be this:
<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "5"
?>
OrionI 15-Apr-2005 11:46
When calling over SOAP to a .NET application, you may end up with an object as a result instead of a simple type, even if you're just grabbing a simple type (like a boolean result). Use a property accessor to get the actual result, like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $objectresult = $client->MyMethod($param1, $param2);
 $simpleresult = $objectresult->MyMethodResult;
?>
Note that .NET seems to name the result MethodNameResult for method MethodName.
Llu�s P�mies 17-Feb-2005 03:19
If your service is a .NET doc/lit, which means the input message has a single part named 'parameters' that is a structure that wraps the parameters.  Your call should look like this:

<?php

$params = array('param_name_1'=>$val_1,'param_name_2'=>$val_2);
$client->call('MethodName', array('parameters' => $params));

?>
SoapClient::__setSoapHeaders
SoapClient::SoapClient
SoapClient


Конструктор SoapClient

SoapClient::__soapCall
SoapServer
SoapClient
PHP Manual

SoapClient::SoapClient

(PHP 5 >= 5.0.1)

SoapClient::SoapClient — Конструктор SoapClient

Описание

public SoapClient::SoapClient ( mixed $wsdl [, array $options ] )

Конструктор создает объект SoapClient в WSDL или не-WSDL режиме.

Список параметров

wsdl

URI файла WSDL или NULL, если работа происходит в режиме не-WSDL.

Замечание:

Во время разработки кэширование WSDL можно отключить, используя настройку soap.wsdl_cache_ttl в php.ini, иначе изменения, сделанные в WSDL файле, не будут иметь эффекта до тех пор, пока не истечет время, указанное в soap.wsdl_cache_ttl.

options

Массив настроек. Если работа происходит в режиме WSDL, то этот параметр необязательный. Если в не-WSDL режиме, то должны быть установлены опции location и uri, где location - URL сервера SOAP, к которому отправляется запрос, и uri - целевое пространство имен SOAP-сервиса.

Опции style и use используются только в не-WSDL режиме. В WSDL режиме они берутся из WSDL файла.

Опция soap_version определяет, будет ли использоваться SOAP-клиент версии 1.1 (по умолчанию) или 1.2.

Для HTTP аутентификации могут быть использованы опции login и password для получения полномочий. Для реализации HTTP соединения через proxy-сервер используются настройки proxy_host, proxy_port, proxy_login и proxy_password. Для HTTPS сертификата аутентификации клиента используются опции local_cert и passphrase. Аутентификация может быть передана через authentication. Метод аутентификации может быть SOAP_AUTHENTICATION_BASIC (по умолчанию) или SOAP_AUTHENTICATION_DIGEST.

Опция compression позволяет сжимать запросы и ответы HTTP SOAP.

Опция encoding определяет внутреннюю кодировку. Опция не меняет кодировку SOAP-запросов (она всегда utf-8), но преобразует строки в нее.

Опция trace включает отслеживание запроса и в случае ошибки можно получить обратную трассировку. По умолчанию имеет значение FALSE.

Опция classmap может использоваться для перевода некоторых WSDL-типов в PHP классы. Опция должна представлять собой массив, в качестве ключей которого указаны WSDL-типы, а в качестве значений - имена PHP классов.

Установленная булевая опция trace
позволяет использовать следующие методы:

SoapClient->__getLastRequest,

SoapClient->__getLastRequestHeaders,

SoapClient->__getLastResponse и

SoapClient->__getLastResponseHeaders.

Опция exceptions принимает булевые значения и определяет будут ли SOAP-ошибки бросать исключения типа SoapFault.

Опция connection_timeout определяет тайм-аут в секундах для соединения с SOAP-сервисом. Опция не устанавливает тайм-аут для сервисов с медленными ответами. Для ограничения времени ожидания вызовов используется default_socket_timeout.

Опция typemap является массивом сопоставления типов. Массив сопоставления типов - это массив с ключами type_name, type_ns (URI пространства имен), from_xml (функция обратного вызова принимает один строковый параметр) и to_xml (функция обратного вызова принимает объект в качестве параметра).

Опция cache_wsdl принимает одно из значений: WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY или WSDL_CACHE_BOTH.

Опция user_agent определяет строку для использования в User-Agent заголовке.

Опция stream_context - это resource для context.

Опция features является битовой маской SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE, SOAP_WAIT_ONE_WAY_CALLS.

Опция keep_alive принимает булево значение, определяющее какой заголовок отправлять: Connection: Keep-Alive или Connection: close.

Список изменений

Версия | Описание
5.4.0 | Новая опция keep_alive.

Примеры

Пример #1 Пример использования SoapClient::SoapClient()

<?php

$client = new SoapClient("some.wsdl");

$client = new SoapClient("some.wsdl", array('soap_version'   => SOAP_1_2));

$client = new SoapClient("some.wsdl", array('login'          => "some_name",
                                            'password'       => "some_password"));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080,
                                            'proxy_login'    => "some_name",
                                            'proxy_password' => "some_password"));

$client = new SoapClient("some.wsdl", array('local_cert'     => "cert_key.pem"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/",
                                     'style'    => SOAP_DOCUMENT,
                                     'use'      => SOAP_LITERAL));

$client = new SoapClient("some.wsdl",
  array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));

$server = new SoapClient("some.wsdl", array('encoding'=>'ISO-8859-1'));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

User Contributed Notes

chris at phblock dot atNoSpam 04-Nov-2011 05:57
this is the syntax of typemap (found at http://svn.php.net/viewvc/php/php-src/trunk/ext/soap/tests/typemap012.phpt?view=markup)
<?php
$options=Array(
'typemap' => array(
array("type_ns"  => "http://schemas.nothing.com",
         "type_name" => "soap",
         "to_xml"  => "some_funktion_name")
));
?>
Chris Gunawardena 15-Aug-2011 12:56
To monitor SOAP calls in and out of a unix server:

sudo tcpdump -nn -vv -A -s 0 -i eth0 dst or src host xxx.xxx.xxx.xxx and port 80

And always use 'cache_wsdl' => WSDL_CACHE_NONE
svenr at selfhtml dot org 27-Jul-2011 03:51
The "classmap" option actually is a mapping from the "ComplexType" used within the SOAP to your PHP Classes.

Do not confuse the XML tag names returned for your request with these ComplexTypes. SOAP allows them to be different.

I had something like this:
...
<soapenv:body>
<ns1:TagName>
  <ns1:Content>FooBar</ns1:Content>
</ns1:TagName>
</soapenv:body>

TagName is not the key you want to put in your classmap, you have to know the name of the ComplexType this TagName refers to. This info is contained inside the WSDL resource.
paulovitorbal at gmail dot com 05-Jul-2011 08:17
When using certificates, in the parameter 'local_cert', use the file contents, not the name of the file.

example:

new soapclient("http://localhost/index.php?wsdl", array('local_cert'=>file_get_contents('./key.pem'),'passphrase'=>'password'));
willem dot stuursma at hyves dot nl 30-May-2011 04:56
In PHP, you can have private properties defined in the classes you use in your classmap. So if you create a private property $foo in you class, and the SOAP element has a child element <foo />, the contents of $foo will be set to the contents of <foo />. This way you can control acces to the properties in your classes.

(Note: This does not work in Facebook's HPHP).
willem dot stuursma at hyves dot nl 30-May-2011 02:00
If you want to use classes in a different namespace in your classmap, just use the backslash in the the target class name.

Example:
<?php
$classmap = array('result' => 'MyNamespace\\Result');
?>

You need to specify the backslash twice because it is the escape character in strings.
simonlang at gmx dot ch 06-Apr-2011 06:35
Example for a soap client with HTTP authentication over a proxy:

<?php
new SoapClient(
    'service.wsdl',
    array(
        // Stuff for development.
        'trace' => 1,
        'exceptions' => true,
        'cache_wsdl' => WSDL_CACHE_NONE,
        'features' => SOAP_SINGLE_ELEMENT_ARRAYS,

        // Auth credentials for the SOAP request.
        'login' => 'username',
        'password' => 'password',

        // Proxy url.
        'proxy_host' => 'example.com', // Do not add the schema here (http or https). It won't work.
        'proxy_port' => 44300,

        // Auth credentials for the proxy.
        'proxy_login' => NULL,
        'proxy_password' => NULL,
    )
);
?>

Providing an URL to a WSDL file on the remote server (which as well is protected with HTTP authentication) didn't work. I downloaded the WSDL and stored it on the local server.
Asaf Meller 13-Jan-2011 05:57
a full working php .net soap configuration :
notes
1. web.config on .net server must work with basichttp binding.
2. paramaters to soap functions must be passed as :
array ('parm1_name'=>'parm1_value',
         'parm2_name'=>'parm2_value'...)

<?php
header('Content-Type: text/plain');

try {
            $options = array(
                'soap_version'=>SOAP_1_1,
                'exceptions'=>true,
                'trace'=>1,
                'cache_wsdl'=>WSDL_CACHE_NONE
            );
            $client = new SoapClient('http://www.example.com/end_point.wsdl', $options);
    // Note where 'Get' and 'request' tags are in the XML

        } catch (Exception $e) {
            echo "<h2>Exception Error!</h2>";
            echo $e->getMessage();
        }

echo 'running HelloWorld :';

 try {
   $response=$client->HelloWorld();

}
catch (Exception $e)
{
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

print_r($response);
?>

good luck !
Asaf.
faebu at faebu dot ch 21-Dec-2010 06:58
I'm experiencing the same problems when trying to load a WDSL fiel which is protected by basic http authentication, since the parameters login and password are just used for the request but not when reading the wdsl file. I just use the following workaround by downloading the xml file to a non-protected location on my server. Please notice that this doesn't support any kind of caching.

Hope it helps

<?php
class SoapAuthClient extends SoapClient {
    /**
     * Since the PHP SOAP package does not support basic authentication
     * this class downloads the WDSL file using the cURL package and
     * creates a local copy of the wdsl on your server.
     * Make sure you provide the following additional parameter in the
     * $options Array:
     * wdsl_local_copy => true
     */

    private $cache_dir = '/home/example/htdocs/cache/';
    private $cache_url = 'http://www.example.com/cache/';

    function SoapAuthClient($wdsl, $options) {
        if (isset($options['wdsl_local_copy']) &&
            $options['wdsl_local_copy'] == true &&
            isset($options['login']) &&
            isset($options['password'])) {

            $file = md5(uniqid()).'.xml';

            if (($fp = fopen($this->cache_dir.$file, "w")) == false) {
                throw new Exception('Could not create local WDSL file ('.$this->cache_dir.$file.')');
            }

            $ch = curl_init();
            $credit = ($options['login'].':'.$options['password']);
            curl_setopt($ch, CURLOPT_URL, $wdsl);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, $credit);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_FILE, $fp);
            if (($xml = curl_exec($ch)) === false) {
                //curl_close($ch);
                fclose($fp);
                unlink($this->cache_dir.$file);

                throw new Exception(curl_error($ch));
            }

            curl_close($ch);
            fclose($fp);
            $wdsl = $this->cache_url.$file;
        }

        unset($options['wdsl_local_copy']);
        unset($options['wdsl_force_local_copy']);

        echo $wdsl;
        parent::__construct($wdsl, $options);

        unlink($this->cache_dir.$file);
    }
}
?>
tatupheba at gmail dot com 20-Dec-2010 02:30
Hello folks!

A hint for developers:

When programming some soap server set the "soap.wsdl_cache_enabled" directive in php.ini file to 0:

soap.wsdl_cache_enabled=0

Otherwise it will give a bunch of strange errors saying that your wsdl is incorrect or is missing.

Doing that will save you from a lot of useless pain.
titan at phpdevshell dot org 06-Oct-2010 06:11
It should be noted that if you receive a return error : 'Object reference not set to an instance of an object.'. This could be due to something as simple as passing the incorrect parameters. When you look at this XML:

    <Get xmlns="http://example.com">
      <request>
        <CustomerId>string</CustomerId>
        <From>dateTime</From>
        <To>dateTime</To>
      </request>
    </Get>

Your code should look something like this:

<?php
        try {
            $options = array(
                'soap_version'=>SOAP_1_2,
                'exceptions'=>true,
                'trace'=>1,
                'cache_wsdl'=>WSDL_CACHE_NONE
            );
            $client = new SoapClient('http://example.com/doc.asmx?WSDL', $options);
// Note where 'Get' and 'request' tags are in the XML
            $results = $client->Get(array('request'=>array('CustomerId'=>'1234')));
        } catch (Exception $e) {
            echo "<h2>Exception Error!</h2>";
            echo $e->getMessage();
        }

$results = $client->Get(array('request'=>array('CustomerId'=>'842115')));
?>
marcovtwout at hotmail dot com 29-Jun-2010 08:30
If your WSDL file containts a parameter with a base64Binary type, you should not use base64_encode() when passing along your soap vars. When doing the request, the SOAP library automatically base64 encodes your data, so otherwise you'll be encoding it twice.

WSDL snipplet:
<element name="content" type="base64Binary" xmime:expectedContentTypes="*/*"/>

<?php
$string = 'data_you_want_to_send___like_xml_in_soap';
$soap_data = array(
        'foo' => 'bar',
      //'content' => base64_encode($string ) // don't do this
        'content' => $string //do this
);
$response = $client->Send($soap_data);
?>
marcovtwout at hotmail dot com 26-Jun-2010 06:20
Being new to SOAP, I was searching for a while to find out why my message was getting a response in soapUI, but not with my php code. The specific service I was addressing gives a HTTP 202 Accepted on success (no response), but returns a SOAP message on errors.

Situation:
Using an (authenticated) client connection, and a WDSL file, SOAP calls with type "One-Way" don't give a response header, even though a response is expected.

Solution:
When calling the client constructor, set SOAP_WAIT_ONE_WAY_CALLS in the $options['features'].
tim at tdinternet dot com 10-Jun-2010 08:05
PHP 5.2.11 seems to not be very picky about the correctness of a WSDL.

Other SOAP clients were complaining about schema and namespace issues, while PHP's SoapClient worked completely fine.  Fixing those issues for the other clients however broke PHP's SoapClient to the point where objects being passed to the SOAP method were becoming empty arrays on the server side.

Lesson learned:  some elements were being prefixed with xsd: and others were not -- make absolutely sure your WSDL is correct and consistent (I'm using a tweaked WSDL_Gen.php).
james dot ellis at gmail dot com 09-Jun-2010 07:06
I was having troubles getting responses from a Coldfusion SOAP server, with no obvious issues in the SoapClient used.

Eventually I found that the server was only accepting SOAP 1.1 requests and not 1.2. Not sure if this is  a system wide Coldfusion setting but if you hit the same wall, try setting the SoapClient option "soap_version" to the constant SOAP_1_1 (which is the default but mine was defaulting to 1.2 as the client was being reused for another service)
ajcartmell at fonant dot com 09-Jun-2010 03:57
There seems to be a problem with specifying empty strings for proxy_host and proxy_port options in recent versions of PHP (from a version later than 5.2.9, and equal to or earlier than 5.2.11).

Supplying empty string values for proxy_host and proxy_port causes "host not found" type errors: supplying NULL or FALSE works fine.
reinaldo at mandic dot com dot br 25-May-2010 07:43
You need both certificates, privateKey and publicKey on the same file, on local_cert path to work.

# cat publicKey.pem privateKey.pem > key.pem
bhargav dot khatana at gmail dot com 11-Apr-2010 11:10
It took me longer than a week to figure out how to implement WSSE (Web Service Security) headers in native PHP SOAP. There are no much resource available on this, so thought to add this here for community benefit.

Step1: Create two classes to create a structure for WSSE headers

<?php
class clsWSSEAuth {
          private $Username;
          private $Password;
        function __construct($username, $password) {
                 $this->Username=$username;
                 $this->Password=$password;
              }
}

class clsWSSEToken {
        private $UsernameToken;
        function __construct ($innerVal){
            $this->UsernameToken = $innerVal;
        }
}
?>

Step2: Create Soap Variables for UserName and Password

<?php
$username = 1111;
$password = 1111;

//Check with your provider which security name-space they are using.
$strWSSENS = "http://schemas.xmlsoap.org/ws/2002/07/secext";

$objSoapVarUser = new SoapVar($username, XSD_STRING, NULL, $strWSSENS, NULL, $strWSSENS);
$objSoapVarPass = new SoapVar($password, XSD_STRING, NULL, $strWSSENS, NULL, $strWSSENS);
?>

Step3: Create Object for Auth Class and pass in soap var

<?php
$objWSSEAuth = new clsWSSEAuth($objSoapVarUser, $objSoapVarPass);
?>

Step4: Create SoapVar out of object of Auth class

<?php
$objSoapVarWSSEAuth = new SoapVar($objWSSEAuth, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS);
?>

Step5: Create object for Token Class

<?php
$objWSSEToken = new clsWSSEToken($objSoapVarWSSEAuth);
?>

Step6: Create SoapVar out of object of Token class

<?php
$objSoapVarWSSEToken = new SoapVar($objWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS);
?>

Step7: Create SoapVar for 'Security' node

<?php
$objSoapVarHeaderVal=new SoapVar($objSoapVarWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'Security', $strWSSENS);
?>

Step8: Create header object out of security soapvar

<?php
$objSoapVarWSSEHeader = new SoapHeader($strWSSENS, 'Security', $objSoapVarHeaderVal,true, 'http://abce.com');

//Third parameter here makes 'mustUnderstand=1
//Forth parameter generates 'actor="http://abce.com"'
?>

Step9: Create object of Soap Client

<?php
$objClient = new SoapClient($WSDL, $arrOptions);
?>

Step10: Set headers for soapclient object

<?php
$objClient->__setSoapHeaders(array($objSoapVarWSSEHeader));
?>

Step 11: Final call to method

<?php
$objResponse = $objClient->__soapCall($strMethod, $requestPayloadString);
?>
peter at webacoustics dot com 31-Mar-2010 09:58
I found that WSDL fetching fails when using basic authentication in the soapclient. So I implemented the following workaround using wget. I realize wget may not be an option for some environments, in that case cURL would be the next simplest thing.

<?php
$wsdl = get_wsdl("https://example.com/soap/service?wsdl");
$this->client = new SoapClient($wsdl, array('user'=>'someuser', 'password'=>'somepassword'));

private function get_wsdl($url) {
    global $g;
    $url = escapeshellarg($url);
    $cache_file = "/tmp/soap.wsdl." . md5($url);

    //only fetch a new wsdl every hour
    if(!file_exists($cache_file) || filectime($cache_file) < time() - 3600) {
        $agent = escapeshellarg("--user-agent={$g['useragent']}");
        mwexec("wget --quiet --timeout=5 {$agent} --no-check-certificate --output-document={$cache_file} {$url}");
        if(!file_exists($cache_file)) {
            throw new Exception("Couldn't load WSDL at {$url}");
        }
    }
    return $cache_file;
}
?>
meltir at meltir dot com 29-Mar-2010 05:59
To those fighting with NTLM authenticated proxy servers, here's a solution I'm using atm:

<?php
/**
 * A child of SoapClient with support for ntlm proxy authentication
 *
 * @author Meltir <meltir@meltir.com>
 *
 */
class NTLM_SoapClient extends SoapClient {

    public function __construct($wsdl, $options = array()) {
        if (empty($options['proxy_login']) || empty($options['proxy_password'])) throw new Exception('Login and password required for NTLM authentication!');
        $this->proxy_login = $options['proxy_login'];
        $this->proxy_password = $options['proxy_password'];
        $this->proxy_host = (empty($options['proxy_host']) ? 'localhost' : $options['proxy_host']);
        $this->proxy_port = (empty($options['proxy_port']) ? 8080 : $options['proxy_port']);
        parent::__construct($wsdl, $options);
    }

    /**
     * Call a url using curl with ntlm auth
     *
     * @param string $url
     * @param string $data
     * @return string
     * @throws SoapFault on curl connection error
     */
    protected function callCurl($url, $data) {
    $handle   = curl_init();
    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_URL, $url);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);
    curl_setopt($handle, CURLOPT_HTTPHEADER, Array("PHP SOAP-NTLM Client") );
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
    curl_setopt($handle, CURLOPT_PROXYUSERPWD,$this->proxy_login.':'.$this->proxy_password);
    curl_setopt($handle, CURLOPT_PROXY, $this->proxy_host.':'.$this->proxy_port);
    curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
    $response = curl_exec($handle);
    if (empty($response)) {
      throw new SoapFault('CURL error: '.curl_error($handle),curl_errno($handle));
    }
    curl_close($handle);
    return $response;
    }

    public function __doRequest($request,$location,$action,$version,$one_way = 0) {
        return $this->callCurl($location,$request);
    }

}
?>

Requires curl and could be extended, but it works for my simple needs.
eric dot caron at gmail dot com 31-Jan-2010 01:26
Though pointed out by jan at bestbytes, and discussed in bug #27777, one common source of the "Parsing WSDL: Couldn't find <definitions>" error is from trying to access a WSDL that is protected by HTTP authentication. Passing the login/password in the 2nd parameter doesn't always work; so if you encounter this error message and are trying to access a protected WSDL file, try passing the username and password in with the first parameter.
Anonymous 10-Jan-2010 06:53
I had to struggle with a rather strange behavior when trying to consume standard Parlay X web services with no success. However, I found a remedy to my problem.

The problem which I faced was about an erroneous invalid HTTP basic authentication request sent to the web service. Although I was sending the right credentials, I was getting an authentication error. It turns out that PHP was sending HTTP requests to another endpoint which is not exposed directly through the web service and that end point does not require authentication.

My remedy for that issue was by using this simple lines in the example of using sendSms Paraly-X method.

First, creating a soap client without any HTTP authentication options:

<?php
$client = new SoapClient($wsdl_url);
?>

The above request will cache the wsdl in the /tmp directory. Immediately after this construction we create another soap client, this time with HTTP authentication options:

<?php
try {
        $client = new SoapClient($wsdl_url, array('login' => "griffin",
                                            'password'       => "password"));
} catch (Exception $e) {
        printf("Error:sendSms: %s\n",$e->__toString());
        return false;
}
?>

Now it should work without any problem. Without the second call, PHP will call sendSms without credentials resulting in a failed attempt due to missing authentication information. I found this procedure to be the simplest.

This process should be done every time the cached wsdl expires, or simply a one can increase the time-to-live for the cached wsdl from php.ini
jon dot gilbert at net-entwicklung dot de 12-Dec-2009 09:55
Note that creating a soap client for an invalid URL (you do test what happens, when a service is not available, right?) usually throws an exception which can be caught with try..catch. However, if xdebug is active you will get a fatal error, which obviously cannot be caught.
sloloem at gmail dot com 19-Oct-2009 01:14
I had an issue figuring out the use of classmap that took me quite a while to figure out.  I was assuming the WSDL type the docs were referring to was the name of the element being returned in the SOAP, so like,
<ns1:node id="8675309" />

and I was wondering why mapping
'classmap'=>array('node'=>'MyNode')

did nothing.
That's because in my WSDL I defined node as:

<xsd:element name="node" type="tns:nodeType" />

The classmap I needed was:
'classmap'=>array('nodeType'=>'MyNode')

I was able to find the type names using SoapClient->__getTypes()
Later, I realized where I could look inside the WSDL for the typename I needed.

I dunno if I missed something painfully obvious but maybe this can clear up some of the docs.
Jon 06-May-2009 03:13
We've had some problems using SoapClient connecting to an external server via Microsoft ISA (presently v.2006 but this may apply to other versions too). We supply the proxy_host, proxy_port, proxy_login and proxy_password but the ISA server reports the login in its logs as "anonymous".

Our sysadmin believes this is because PHP is not supplying NTLN information (Windows security protocol) in the correct format (and whether it should work with proprietary proxies is of course another debate). We'd tried "username", "DOMAIN\username" to no effect. The solution is to add an exception in the ISA server for the target hostname/IP; null can then be supplied for proxy_login and proxy_password and the connection should then work as expected.

On a slightly related note, if you are having problems make sure the port number is supplied as an integer. Some versions of PHP will not use the proxy with SoapClient if the port number is supplied as a string.
jan at bestbytes dot de 12-Feb-2009 07:32
You CAN get a wsdl, if basic authentication is required:

<?php

$login = 'bert';
$password = 'berts password';

$client = new SoapClient(
    'http://' . urlencode($login) . ':' . urlencode($password) . '@www.server.com/path/to/wsdl',
    array(
        'login' => $login,
        'password' => $password
    )
);

?>
info at nicksilvestro dot net 09-Nov-2008 10:40
For anyone having trouble with ArrayOf_xsd_string and getting an error similar to 'No deserializer defined for array type {http://www.w3.org/2001/XMLSchema}string'
Try using the 'features' param, set to SOAP_USE_XSI_ARRAY_TYPE - this makes sure the correct deserializer is used.

eg,
<?php
$client = new SoapClient("some.wsdl", array('features' => SOAP_USE_XSI_ARRAY_TYPE));
?>
sniper 27-Sep-2008 11:46
i was looking for a good example and couldnt find one,
finally found it somewhere(forgot where) i think this is
the best example to make a soap request with multiple params

$params->AWSAccessKeyId = AMAZON_API_KEY;
$params->Request->SearchIndex = 'Books';
$params->Request->Keywords = 'php5 oop';

$amazon = new SoapClient('http://webservices.amazon.com
/AWSECommerceService/AWSECommerceService.wsdl');
$result = $amazon->itemSearch($params);
taras dot dot dot di at gmail dot com 16-Sep-2008 09:23
This took me a while to figure out.

As described at the bottom of here: http://bugs.php.net/bug.php?id=38703

having xdebug may interfere with the constructor throwing exceptions
alex on reutone comma com 10-Sep-2008 06:53
To connect PHP SOAP to MS SOAP (CRM/EXCHANGE/...) I have created some classes using the explanation below and in other places.
www.reutone.com/heb/articles.php?instance_id=62&actions=show&id=521
naugtur at gmail dot com 19-Jun-2008 06:48
SoapFault exception: [Client] looks like we got no XML document in <document> has been already mentioned to occur when your server outputs something before <?xml ... > tag.

For all those having problems with that, and no access to the server code:
This is how to make a proxy that would clean responses for You

<?php
/**
 * Simple class taken from a note by James Ellis [in __doRequest() page of manual]
 */
class Proxy_Client extends SoapClient {
    protected $cacheDocument = "";
    public function __construct($wsdl, $options) {
        parent::__construct($wsdl, $options);
    }

    /**
     * SetCacheDocument() sets the previously cached document contents
     */
    public function SetCacheDocument($document) {
        $this->cacheDocument = $document;
    }

    /**
     * __doRequest() overrides the standard SoapClient to handle a local request
     */
    public function __doRequest() {
        return $this->cacheDocument;
    }
}

//put this code in your function or wherever You have all required variables set

$client = new SoapClient($wsdl_url,$settings_array);
$void=$client->$method($params);  //call this to get response from server

$response_string=$client->__getLastResponse();

//this part removes stuff
$start=strpos($response_string,'<?xml');
$end=strrpos($response_string,'>');
$response_string=substr($response_string,$start,$end-$start+1);

//get your proxy prepared
$proxy = new Proxy_Client($wsdl_url,$settings_array);
//and fill it with the server's response
$proxy->SetCacheDocument($response_string);

$and_finally_the_result_is=$proxy->$method($params);

print_r($and_finally_the_result_is); //this allows You to see what's there

?>

$method is the method's name eg. $method='getVersion';
$params - typical params for a soap method
david at globulebleu dot com 09-Jun-2008 12:44
When using classmap option to map the SOAP results to a class, the constructor
of the object you've mapped to is not called.

$client = new SoapClient("url_to_wsdl",
   array('classmap' => array('contact' => "Contact"));

$params = array("1");

$contact = $client->__soapCall("get_contact", $params);

Expected result:

A contact object that has properties initialized (i.e. db connections,
....).

Actual result:

A contact object without the properties.

Thanks for your help.

David Georges.
Anno v. Heimburg 27-May-2008 10:23
> When using HTTP basic authentication, PHP will only send
> the credentials when invoking the service, not when
> fetching the WSDL.

The same goes for using an SSL client certficate, the SoapClient will only present the certificate on the actual remote call, not when getting the WSDL. The workaround is the same as above. HttpRequest works as expected.
cw at netresearch dot de 30-Apr-2008 01:24
The "cache_wsdl" option takes constants like WSDL_CACHE_NONE or WSDL_CACHE_DISK that are listed on the "SOAP constants" page -> /manual/en/soap.constants.php
james dot ellis at gmail dot com 29-Jan-2008 05:10
A note regarding boolean values that may seem obvious on reflection but could be a gotcha for some:

Seeing a SOAP request example with <SomeBooleanParam>true</SomeBooleanParam> may lead you to pass in string "true" or "false" as the parameter, which is incorrect - the correct method is to use boolean data types.

<?php
$client = new SoapClient($wsdl,$options);
$method = "DoSomething";
$params = new stdClass;

$params->SomeBooleanParam = TRUE;
$client->$method($params);
/**
 simplified request snippet would be
 <SomeBooleanParam>true</SomeBooleanParam>
**/

//this will also be correct, but not for the right reasons:
$params->SomeBooleanParam = "true";
$client->$method($params);
/**
 simplified request snippet would be
 <SomeBooleanParam>true</SomeBooleanParam>
**/

//this is where you may be wondering what is going on
$params->SomeBooleanParam = "false";
$client->$method($params);
/**
 simplified request snippet would be
 <SomeBooleanParam>true</SomeBooleanParam>
**/

//you need to do this instead
$params->SomeBooleanParam = FALSE;
$client->$method($params);
/**
 simplified request snippet would be
 <SomeBooleanParam>false</SomeBooleanParam>
**/
?>

Hope that helps!
dastephdev (at) gmail.com 20-Dec-2007 02:22
If you want to use compression there is a missing parameter in the example above:

<?php
$client = new SoapClient("some.wsdl",
  array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 5));
?>

If you use SOAP_COMPRESSION_GZIP you have to add the compression level. Otherwise it will not compress the request. Took me some hours ;)

Stephan
giosh94mhz 08-Jul-2007 11:46
Oops!

I have written the wrong exception message in my last post.

The correct exception is:

SoapFault exception: [Client] looks like we got no XML document in <document>
giosh94mhz 08-Jul-2007 11:28
If you get the following exception:

'Cannot open the XML file: the file is not well-formatted!'

PHP files of your SOAP-server contains syntax-error (probably).

If everything looks ok, try to remove EVERY blank-space and new-line outside the <?php ... ?> tag... this should save you an headache!
lsmith at php dot net 08-Feb-2007 07:20
As noted in the bug report http://bugs.php.net/bug.php?id=36226, it is considered a feature that sequences with a single element do not come out as arrays. To override this "feature" you can do the following:

$x = new SoapClient($wsdl, array('features' =>
SOAP_SINGLE_ELEMENT_ARRAYS));
matt_schiros at academicsuperstore dot com 30-Nov-2006 12:26
When using classmap to map the SOAP results to a class, the constructor of the object you've mapped to is _not_ called.  This applies to the PHP5 __construct() and the PHP4 ClassName() constructors.
Marius Mathiesen 01-Mar-2006 04:57
I kept having a problem using an HTTP proxy with SOAP. The proxy_port parameter has to be an integer, ie. "proxy_port"=>"80" won't work, you'll have to use "proxy_port"=>80.

HTH,
Marius
php at sowen dot de 22-Dec-2005 06:40
If you're using CLI and there are multiple IP addresses available for outgoing SOAP-requests, try this "secret" to set outgoing IP:

e.g. for local IP 10.1.4.71:

$opts = array('socket' => array('bindto' => '10.1.4.71:0'));
$context = stream_context_create($opts);
$client  = new SoapClient(null, array('location'=>'http://...','uri' => '...','stream_context' => $context));

You can also set other options for the stream context, please refer to this page:

Appendix M: http://www.php.net/manual/en/wrappers.php

Bye,
   Nils Sowen
jared at ws-db dot com 28-Aug-2005 02:31
If you connect to a SoapServer, that has been created with session persistence, you can access the server's session id via SoapClient->_cookies[<session_id_name>][0]. This property becomes available after your first client method call.

I have only tested this with session.use_cookies=1.
Arjan van Bentem 11-Aug-2005 11:31
When using HTTP basic authentication, PHP will only send the credentials when invoking the service, not when fetching the WSDL.

To solve this, one needs to fetch the WSDL manually (or using PHP, of course!) and store it on the file system. Obviously, the first parameter for SoapClient(..) then needs to refer to that local copy.

Alternatively, the user annotations at http://nl3.php.net/manual/en/ref.soap.php state that one could encode the login and password into the URL as well.

See http://bugs.php.net/bug.php?id=27777
Jim Plush 11-Jul-2005 12:56
As of version 5.0.4 you can now dynamically change your location even if you're using a wsdl

<?php

$client = new SoapClient("http://some.host.net/wsdl/somefile.wsdl",array(
    "location" => 'myurl.com'));

?>

notice you can now use the "location" key.
This means you can have the same wsdl file not define a location until runtime which is great if you have a development test site or if you distribute your files to other companies.
Prior to this change you would have to ship a custom wsdl file to every client you had with their location hardcoded.
Brian Grayless 04-Mar-2005 02:30
Using a WSDL file is the way to go, however, for my particular application, the LOCATION:PORT needed to be dynamic so that my SOAP clients would be able to call a different service based on the client domain.

If you are using a WSDL, SoapClient() requires a URL direct to an actual URL and does not let you use a PHP file that outputs the dynamic WSDL XML in its stead. So, I ended up making a separate WSDL for each possible service needed and had to maintain them all if the service description changed.

Finally, after some fiddling, I was able to create a PHP page with the proper Mime type headers so that I could then trick SoapClient() to think that it was being passed a file with a ".wsdl" extension.

Example:

<?php

// filename: wsdl.php

header('Content-Type: application/xml; charset=UTF-8');
header('Content-Disposition: attachment; filename="filename.wsdl"');

$wsdl = 'path/wsdl_name.wsdl';

// read in file
$handle = fopen($wsdl, "r");
$wsdl_xml = fread($handle, filesize($wsdl));
fclose($handle);

// put code here to replace url and port in xml

echo $wsdl_xml;

?>

Now, in order to make this work, you can't just call a relative path to the file. I believe it has to go through Apache to properly set the mime type headers, etc... So you would use a full "http://....." address as the path to the wsdl.php file.

<?php

//... somewhere in your soap client code

$wsdl_loc = "http://yourdomain.com/wsdl.php";

$soap_client = new SoapClient($wsdl_loc, $client_param_array);

?>

Another, perhaps not so clean, way of achieving this would be to modify your .htaccess file in the directory where your WSDL file exists to force ".wsdl" files to run through the PHP engine. Add the following to your .htaccess:

AddType application/x-httpd-php .php .wsdl

You can then put dynamic PHP code snippets in your *.wsdl files to change whatever values you need to.

There are pros and cons to each solutions. The Mime solution probably taxes the system more as it has to read the file in every time a soap request is made. The htaccess solution makes it so you have to depend on either a modified .htaccess or Apache conf file.

Perhaps if you set the "soap.wsdl_cache_enabled", using ini_set(), to 1 (default), the caching will make it so it doesn't read the file every time for the Mime solution.
SoapClient::__soapCall
SoapServer
SoapClient


The SoapServer class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

The SoapServer class provides a server for the » SOAP 1.1 and » SOAP 1.2 protocols. It can be used with or without a WSDL service description.

Обзор классов

SoapServer {
/* Методы */
public void addFunction ( mixed $functions )
public void addSoapHeader ( SoapHeader $object )
public __construct ( mixed $wsdl [, array $options ] )
public void fault ( string $code , string $string [, string $actor [, string $details [, string $name ]]] )
public array getFunctions ( void )
public void handle ([ string $soap_request ] )
public void setClass ( string $class_name [, mixed $args [, mixed $... ]] )
public void setObject ( object $object )
public void setPersistence ( int $mode )
public SoapServer ( mixed $wsdl [, array $options ] )
}

Содержание

  • SoapServer::addFunction — Adds one or more functions to handle SOAP requests
  • SoapServer::addSoapHeader — Add a SOAP header to the response
  • SoapServer::__construct — SoapServer constructor
  • SoapServer::fault — Issue SoapServer fault indicating an error
  • SoapServer::getFunctions — Returns list of defined functions
  • SoapServer::handle — Handles a SOAP request
  • SoapServer::setClass — Устанавливает класс, который будет обрабатывать SOAP-запросы
  • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
  • SoapServer::setPersistence — Sets SoapServer persistence mode
  • SoapServer::SoapServer — SoapServer constructor

User Contributed Notes

php1221 at klox dot net 18-Aug-2011 01:39
While there are plenty of mentions online that SoapServer doesn't support SOAP Headers, this isn't true.

In your class, if you declare a function with the name of the header, the function will be called when that header is received.

<?php
class MySoapService {
  private $user_is_valid;

  function MyHeader($header) {
    if ((isset($header->Username)) && (isset($header->Password))) {
      if (ValidateUser($header->Username, $header->Password)) {
        $user_is_valid = true;
      }
    }
  }

  funstion MySoapRequest($request) {
    if ($user_is_valid) {
      // process request
    }
    else {
      throw new MyFault("MySoapRequest", "User not valid.");
    }
  }
}
?>
tom at samplonius dot org 18-Mar-2011 05:45
Mentions on this page of:

require 'SOAP/SoapServer.php'

are actually referring to PEAR SOAP, not PHP SOAP.  This is the PHP SOAP page.
hawky83 at googlemail dot com 21-Jan-2011 02:46
Another simple example for SOAP_SERVER with errorhandling an params and wsdl:

SERVER (soap_all_srv.php):

<?php
// PEAR::SOAP einbinden
require_once "SOAP/Server.php";
$skiptrace =& PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
$skiptrace = true;

// Service-Class
class mytimeserv {

  // __dispatch_map
  public $__dispatch_map = array ();

  // In/Out param -> __dispatch_map
  public function __construct() {
    $this->__dispatch_map["now"] =
      array ("in" => array("format" => "string"),
             "out" => array("time" => "string"));
  }

  // get back __dispatch_map in __dispatch
  public function __dispatch($methodname) {

    if (isset($this->__dispatch_map[$methodname])) {
      return $this->__dispatch_map[$methodname];
    }

    return NULL;
  }

  // servicemthod with parameters
  function now ($format) {

    // formaterror?
    if (($format == null) || (trim($format) == "")) {

      // send errormessage
      return new SOAP_Fault("Kein Parameter angegeben","0815", "Client");
    }

    date_default_timezone_set('Europe/Berlin');

    $time = date ($format);

    // return SOAP-Obj.
    return (new SOAP_Value('time','string', $time));
  }
}

// service-class
$service = new mytimeserv();

// server
$ss = new SOAP_Server();

// add service with name
$ss->addObjectMap (&$service,"urn:mytimeserv");

// service or wsdl
if (isset($_SERVER["REQUEST_METHOD"])&& $_SERVER["REQUEST_METHOD"] == "POST") {

    // postdata -> service
    $ss->service ($HTTP_RAW_POST_DATA);

} else {

  // wsdl-param in url
  if (isset($_SERVER['QUERY_STRING']) && strcasecmp($_SERVER['QUERY_STRING'],'wsdl') == 0) {

    // DISCO_Server for WSDL
    require_once "SOAP/Disco.php";
    $disco = new SOAP_DISCO_Server ($ss,"mytimeserv","My Time Service");

    // set HTML-Header
    header("Content-type: text/xml");

    // return wsdl
    print $disco->getWSDL ();
  }
}

?>

CLIENT (soap_all_client.php) (for wsdl: http://example.com/soap_all_srv.php?wsdl):
<?php

require_once "SOAP/Client.php";

// SOAP/WSDL
$sw = new SOAP_WSDL ("http://example.com/soap_all_srv.php?wsdl");

// Proxy-Obj.
$proxy = $sw->getProxy ();

// servicemthod
$erg = $proxy->now ("H:i:s");

// return
print $erg."\n";

?>
mikkel at nsales dot dk 02-Jun-2010 03:15
If you want to return a custom object array from a nusoap webservice, you have to cast the objects to arrays like so:

<?php
$users = array();
while($res = $db_obj->fetch_row())
{
  $user = new user();
  $user->Id = $res['id'];
  $user->Username = $res['username'];
  $user->Email = $res['email'];

  $users[] = (array) $user;
}

return ($users);
?>
junk2cm at gmx dot de 25-May-2010 12:54
As the SoapServer class lacks the possibility of dealing with SOAP-Headers, my following workaround is suitable to my needs when I had to do authentication via the SOAP-Headers:
1. Use a class which handles SOAP requests and let the constructor of this class take the sent headers.
2. Before invoking the SoapServer extract the SOAP-Header from the incoming raw data.
3. When using setClass pass the extracted header to the handling class.

In Your Server-Skript do things like this
<?php
$hdr = file_get_contents("php://input");
if (strpos($hdr,'<s:Header>')===false) {
    $hdr = null;
} else {
    $hdr = explode('<s:Header>',$hdr);
    $hdr = explode('</s:Header>',$hdr[1]);
    $hdr = $hdr[0];
}
$srv = new SoapServer('Your_wsdl');
$srv->setClass("ServiceClass",$hdr);
$srv->handle();
?>

And the service class is like this:
<?php
class ServiceClass {
    var $IsAuthenticated;

    function __construct($hdr) {
        $this->IsAuthenticated = false;
        if ($hdr!=null) {
            $this->header = simplexml_load_string($hdr);
            //Your authentication stuff goes here...
        }
    }

    function SomeFunctionOfTheService($a) {
        if ($this->IsAuthenticated) {
            //here Your function...
        }
    }

}
?>
carlos dot vini at gmail dot com 20-May-2010 01:55
SoapServer does not support WSDL with literal/document. I have a class:

<?php
class My_Soap {
    /**
     * Returns Hello World.
     *
     * @param string $world
     * @return string
     */
    public function getInterAdmins($world) {
        return 'hello' . $world;
    }
}
?>

To fix this I had to create proxy class:
<?php
class My_Soap_LiteralDocumentProxy {
   public function __call($methodName, $args) {
       $soapClass = new My_Soap();
       $result = call_user_func_array(array($soapClass, $methodName),  $args[0]);
       return array($methodName . 'Result' => $result);
   }
}
?>

Now make sure that the WSDL is created using My_Soap. And that the Server is created using My_Soap_LiteralDocumentProxy:

<?php

if (isset($_GET['wsdl'])) {
    $wsdl = new Zend_Soap_AutoDiscover(); // It generates the WSDL
    $wsdl->setOperationBodyStyle(array(
        'use' => 'literal'
    ));
    $wsdl->setBindingStyle(array(
        'style' => 'document'
    ));
    $wsdl->setClass('My_Soap');
    $wsdl->handle();
} else {
    $server = new Zend_Soap_Server('http://localhost/something/webservice.php?wsdl');
    $server->setClass('My_Soap_LiteralDocumentProxy');
    $server->handle();
}

?>
dsubar at interna dot com 25-Dec-2009 09:49
Do not put a SoapServer and a SoapClient in the same PHP file. This seems to cause arbitrary behavior. On the PHP interpreter in Eclipse, everything worked fine. Under MAMP, I got an undocumented error. In moving the client from the same file as the server, everything worked fine.
SoapClient::SoapClient
SoapServer::addFunction
SOAP


Adds one or more functions to handle SOAP requests

SoapServer
SoapServer::addSoapHeader
SoapServer
PHP Manual

SoapServer::addFunction

(PHP 5 >= 5.0.1)

SoapServer::addFunction — Adds one or more functions to handle SOAP requests

Описание

public void SoapServer::addFunction ( mixed $functions )

Exports one or more functions for remote clients

Список параметров

functions

To export one function, pass the function name into this parameter as a string.

To export several functions, pass an array of function names.

To export all the functions, pass a special constant SOAP_FUNCTIONS_ALL.

Замечание:

functions must receive all input arguments in the same order as defined in the WSDL file (They should not receive any output parameters as arguments) and return one or more values. To return several values they must return an array with named output parameters.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 SoapServer::addFunction() example

<?php

function echoString($inputString)
{
    return $inputString;
}

$server->addFunction("echoString");

function echoTwoStrings($inputString1, $inputString2)
{
    return array("outputString1" => $inputString1,
                 "outputString2" => $inputString2);
}
$server->addFunction(array("echoString", "echoTwoStrings"));

$server->addFunction(SOAP_FUNCTIONS_ALL);

?>

Смотрите также

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::setClass() - Устанавливает класс, который будет обрабатывать SOAP-запросы

User Contributed Notes

dotpointer at gmail dot com 26-Oct-2007 06:52
Be careful with SOAP_FUNCTIONS_ALL, as it adds ALL availiable PHP functions to your server.

This can be a potential security threat, imagine clients doing this:

echo $client->file_get_contents("c:\\my files\\my_passwords.doc");

And voila, they have the contents of your file my_passwords.doc.
Evan Borgstrom 23-Aug-2006 03:42
In response to comment by Nathan O'Sullivan about returning (or passing) a complex type, you can also use the stdClass() object.

Assume you define a complex type like so:

<xsd:complexType name="TestType">
        <xsd:all>
                <xsd:element name="A" type="xsd:string" />
                <xsd:element name="B" type="xsd:int" />
                <xsd:element name="C" type="xsd:boolean" />
        </xsd:all>
</xsd:complexType>

To use an object in place of an array you can do:

$test = new stdClass();
$test->A = "test string";
$test->B = 45;
$test->C = false;

$result = $client->Test($test);
15-Jun-2005 05:10
function Login($username, $password)
{
  return array("LoginResult" => array("Id"=>1, "Name"=>"Nathan", "Nickname"=>"Nathan", "Email"=>"email address") );
}

Ok, Only a litte error in the last note.. :
"LoginResult" => array    and NOT      "LoginResult" , array
Nathan O'Sullivan 28-Apr-2005 11:36
You may be left wondering, as I was, how to return a complex type - consider the following WSDL snippets, for a method called Login:

 <xs:element name="Login">
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="1" name="username" type="xs:string" />
            <xs:element minOccurs="0" maxOccurs="1" name="password" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

   <xs:complexType name="UserInfo">
        <xs:sequence>
          <xs:element minOccurs="0" maxOccurs="1" name="Id" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Nickname" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Email" type="xs:string" />
        </xs:sequence>
      </xs:complexType>

   <xs:element name="LoginResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="1" name="LoginResult" type="s0:UserInfo" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

Here's a working Login function  that I've added with add SoapServer::addFunction

function Login($username, $password)
{
  return array("LoginResult", array("Id"=>1, "Name"=>"Nathan", "Nickname"=>"Nathan", "Email"=>"email address") );
}

The UserInfo complextype is represented by the inner array.  The outer array has just one element, "LoginResult".  The LogineResponse element  seems to be treated as a one-member array by PHP.
SoapServer
SoapServer::addSoapHeader
SoapServer


Add a SOAP header to the response

SoapServer::addFunction
SoapServer::__construct
SoapServer
PHP Manual

SoapServer::addSoapHeader

(PHP 5 >= 5.0.1)

SoapServer::addSoapHeader — Add a SOAP header to the response

Описание

public void SoapServer::addSoapHeader ( SoapHeader $object )

Adds a SOAP header to be returned with the response to the current request.

Список параметров

object

The header to be returned.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

There are no user contributed notes for this page.
SoapServer::addFunction
SoapServer::__construct
SoapServer


SoapServer constructor

SoapServer::addSoapHeader
SoapServer::fault
SoapServer
PHP Manual

SoapServer::__construct

(PHP 5 >= 5.0.1)

SoapServer::__construct — SoapServer constructor

Описание

public SoapServer::__construct ( mixed $wsdl [, array $options ] )

Эта функция является псевдонимом: SoapServer::SoapServer()

User Contributed Notes

There are no user contributed notes for this page.
SoapServer::addSoapHeader
SoapServer::fault
SoapServer


Issue SoapServer fault indicating an error

SoapServer::__construct
SoapServer::getFunctions
SoapServer
PHP Manual

SoapServer::fault

(PHP 5 >= 5.0.1)

SoapServer::fault — Issue SoapServer fault indicating an error

Описание

public void SoapServer::fault ( string $code , string $string [, string $actor [, string $details [, string $name ]]] )

Sends a response to the client of the current request indicating an error.

Замечание:

This can only be called when handling a request.

Список параметров

code

The error code to return

string

A brief description of the error

actor

A string identifying the actor that caused the fault.

details

More details of the fault

name

The name of the fault. This can be used to select a name from a WSDL file.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • SoapFault::SoapFault() - SoapFault constructor

User Contributed Notes

brian dot reynolds at risaris dot com 21-Feb-2012 09:44
Example Usage:

return new SoapFault( "Client", "foo or bar must be supplied");

SOAP Fault Codes

VersionMismatch: Found an invalid namespace for the SOAP Envelope element
MustUnderstand    : An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood
Client: The message was incorrectly formed or contained incorrect information
Server: There was a problem with the server so the message could not proceed
dub357 at gmail dot com 08-Feb-2012 08:01
This function also sends a 500 response code back to the client with the request.
This was causing issues with an Apache Axis 1.2 client I had so I instead implemented by own fault handling:

<?php
header("Content-Type: text/xml");
header("Status: 200");
die("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\\"http://schemas.xmlsoap.org/soap/envelope/\\">
  <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
      <faultcode>500</faultcode>
      <faultstring>".$ex->getMessage())."</faultstring>
    </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>");
?>
Amr Mostafa 09-Sep-2009 06:16
This function currently terminates execution as well, which may be undesirable. See: http://bugs.php.net/bug.php?id=49513
Anonymous 16-Jul-2008 12:12
If you use Adobe Flex, Flash or AIR as SOAP client and are unable to get the error message in case of a soap fault, upgrade to PHP 5.2.6.

Details in:
http://bugs.php.net/bug.php?id=43507
SoapServer::__construct
SoapServer::getFunctions
SoapServer


Returns list of defined functions

SoapServer::fault
SoapServer::handle
SoapServer
PHP Manual

SoapServer::getFunctions

(PHP 5 >= 5.0.1)

SoapServer::getFunctions — Returns list of defined functions

Описание

public array SoapServer::getFunctions ( void )

Returns a list of the defined functions in the SoapServer object. This method returns the list of all functions added by SoapServer::addFunction() or SoapServer::setClass().

Список параметров

У этой функции нет параметров.

Возвращаемые значения

An array of the defined functions.

Примеры

Пример #1 SoapServer::getFunctions() example

<?php
$server = new SoapServer(NULL, array("uri" => "http://test-uri"));
$server->addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $server->handle();
} else {
  echo "This SOAP server can handle following functions: ";
  $functions = $server->getFunctions();
  foreach($functions as $func) {
    echo $func . "\n";
  }
}
?>

Смотрите также

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::addFunction() - Adds one or more functions to handle SOAP requests
  • SoapServer::setClass() - Устанавливает класс, который будет обрабатывать SOAP-запросы

User Contributed Notes

mariuz at gmail dot com 16-Jun-2008 05:21
example for amazon webservice

<?php

$wsdl_url =
  "http://soap.amazon.com/schemas3/AmazonWebServices.wsdl";
$client     = new SoapClient($wsdl_url);
var_dump($client->__getFunctions());

?>
SoapServer::fault
SoapServer::handle
SoapServer


Handles a SOAP request

SoapServer::getFunctions
SoapServer::setClass
SoapServer
PHP Manual

SoapServer::handle

(PHP 5 >= 5.0.1)

SoapServer::handle — Handles a SOAP request

Описание

public void SoapServer::handle ([ string $soap_request ] )

Processes a SOAP request, calls necessary functions, and sends a response back.

Список параметров

soap_request

The SOAP request. If this argument is omitted, the request is assumed to be in the raw POST data of the HTTP request.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 SoapServer::handle() example

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Смотрите также

  • SoapServer::SoapServer() - SoapServer constructor

User Contributed Notes

dub357 at gmail dot com 08-Feb-2012 10:54
After much headache and looking through PHP source code, I finally found out why the handle() function would immediately send back a fault with the string "Bad Request".
Turns out that my client was sending valid XML, but the first line of the XML was the actual XML declaration:

<?xml version="1.0" encoding="UTF-8"?>

When the "handle" function in the SoapServer class is called, it first tries to parse the XML.  When the XML document can't be parsed, a "Bad Request" fault is returned and execution of the script immediately stops.  I assume that the XML parser built into PHP (libxml2) already assumes the document to be XML and when it finds the declaration, it thinks it isn't valid.

I added some XML parsing calls to my service before the handle() function is called to check for valid XML and avoid the "Bad Request" fault.  This also allows me to send back a more suitable error message:

<?php
$parser = xml_parser_create("UTF-8");
if (!xml_parse($parser,$HTTP_RAW_POST_DATA,true)){
   $webService->fault("500", "Cannot parse XML: ".
      xml_error_string(xml_get_error_code($parser)).
       " at line: ".xml_get_current_line_number($parser).
       ", column: ".xml_get_current_column_number($parser));
}
?>
prenaud at profideo dot com 09-Jan-2012 02:23
Please note that when defining several services in one wsdl file, and calling one of those services, you may always get the response for your first service.

This is a known bug. You will find its description and some workarounds here  : https://bugs.php.net/bug.php?id=49169
Artur Graniszewski 15-Nov-2009 10:19
Be aware that SoapServer::handle(); method sends additional HTTP headers to the browser. One of them is "Content-Type: application/soap+xml". If you want to execute SOAP methods locally as a part of SoapClient::__doRequest() (see example at http://pl2.php.net/manual/en/soapclient.dorequest.php ) you may need to reset (override) this header back to "Content-Type: text/html" like so:

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));

header("Content-Type: text/html");

var_dump($x->Add(3,4));

?>
tom at backslashinteractive dot com 03-Oct-2008 10:54
In response to Blizzke:

Sometimes this problem can be hidden by an Apache segmentation fault along with an HTTP headers error SoapFault thrown to the client.

If you get either of those 2, try checking to make sure that style="rpc" in your WSDL file's soap:operation's.

-T
Blizzke at gmail dot com 12-Mar-2008 04:39
Seems pretty logical once you find the solution, but it took me quite a while to figure this one out:
If you are using WSDL based SOAP requests and you have more than one operation in your binding (with the same parameters), make sure the <soap:operation> style is set to rpc, NOT body!

When you specify 'body' here, all that will be transmitted in the request is the parameters for the function call, and SoapServer->handle() will use the first function it finds with the same parameter-makeup to handle the call.

ie If you have 2 functions:
<?php
function One ( string $blah );
function Two ( string $blah );
?>
Making a client call with SoapClient -> Two ( 'test' ); will result in One ( ) being called when your 'type' is set to 'body'

The actual method to call will only be included in the request when your type is set to 'rpc', resulting in the expected behavior
king dot maxemilian at noos dot fr 21-Aug-2007 09:23
Sometime, it happens that PHP does not detect anything in $HTTP_RAW_POST_DATA.

To solve this problem and make it work in any case:

function soaputils_autoFindSoapRequest()    {
    global $HTTP_RAW_POST_DATA;

    if($HTTP_RAW_POST_DATA)
        return $HTTP_RAW_POST_DATA;

    $f = file("php://input");
    return implode(" ", $f);
}

$server = new SoapServer($wsdl);
$server->setClass($MyClass);

$server->handle(soaputils_autoFindSoapRequest());
SoapServer::getFunctions
SoapServer::setClass
SoapServer


Устанавливает класс, который будет обрабатывать SOAP-запросы

SoapServer::handle
SoapServer::setObject
SoapServer
PHP Manual

SoapServer::setClass

(PHP 5 >= 5.0.1)

SoapServer::setClass — Устанавливает класс, который будет обрабатывать SOAP-запросы

Описание

public void SoapServer::setClass ( string $class_name [, mixed $args [, mixed $... ]] )

Экспортирует все методы из заданного класса

Чтобы сохранить объект для каждого последующего запроса в рамках данной PHP-сессии, можно использовать метод SoapServer::setPersistence()

Список параметров

class_name

Имя передаваемого класса.

args

Необязательные параметры, которые будут переданы в конструктор класса в процессе создания объекта.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::addFunction() - Adds one or more functions to handle SOAP requests
  • SoapServer::setPersistence() - Sets SoapServer persistence mode

User Contributed Notes

funky2step at gmail dot com 25-Nov-2011 01:54
When passing arguments to the default class constructor, make sure that you don't try and use the magic __construct method because that won't work.

<?php

class MyClass
{
  function MyClass($arg1, $arg2)
  {

  }
}

// Not:

class MyClass
{
  function __construct($arg1, $arg2)
  {

  }
}

?>
Matt 03-Jul-2009 08:25
As expected, using SoapServer::setClass() on a class with private or protected methods does not expose those methods.

Calling a private/protected method from the SoapClient causes this: E_ERROR "Call to protected method my_class::myPrivateMethod() from context"
christiaan at oakfox dot net 04-May-2009 04:21
You can also retrieve object properties the following way while using __autoload($class_name).

<?php

# Start Session
session_start();

# Auto Load Class as Required
function __autoload($class_name)
{
    require_once "/var/www/example/class/". $class_name. ".php";
}

//service

$_SESSION[_bogus_session_name] = unserialize($_SESSION[_bogus_session_name]);
$server = new SoapServer('service.wsdl');
$server->setClass("MyClass");
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
$_SESSION[_bogus_session_name] = serialize($_SESSION[_bogus_session_name])

?>
Ariz Jacinto 04-Dec-2008 04:38
If you want your SOAP client to be able to save and then retrieve the object properties, you need to set the SOAP server to be persistent by setting session.auto_start=0, invoking session_start(), and SoapServer->setPersistence(SOAP_PERSISTENCE_SESSION) in the following manner:

<?php
  //set ini
  ini_set("soap.wsdl_cache_enabled", 0);
  ini_set("session.auto_start", 0);

  //class file
  require_once('MyClass.php');

  //for persistent session
  session_start();

  //service
  $server = new SoapServer('service.wsdl');
  $server->setClass("MyClass");
  $server->setPersistence(SOAP_PERSISTENCE_SESSION);
  $server->handle();
?>
SoapServer::handle
SoapServer::setObject
SoapServer


Sets the object which will be used to handle SOAP requests

SoapServer::setClass
SoapServer::setPersistence
SoapServer
PHP Manual

SoapServer::setObject

(PHP 5 >= 5.2.0)

SoapServer::setObject — Sets the object which will be used to handle SOAP requests

Описание

public void SoapServer::setObject ( object $object )

This sets a specific object as the handler for SOAP requests, rather than just a class as in SoapServer::setClass().

Список параметров

object

The object to handle the requests.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • SoapServer::setClass() - Устанавливает класс, который будет обрабатывать SOAP-запросы

User Contributed Notes

There are no user contributed notes for this page.
SoapServer::setClass
SoapServer::setPersistence
SoapServer


Sets SoapServer persistence mode

SoapServer::setObject
SoapServer::SoapServer
SoapServer
PHP Manual

SoapServer::setPersistence

(PHP 5 >= 5.1.2)

SoapServer::setPersistence — Sets SoapServer persistence mode

Описание

public void SoapServer::setPersistence ( int $mode )

This function allows changing the persistence state of a SoapServer object between requests. This function allows saving data between requests utilizing PHP sessions. This method only has an affect on a SoapServer after it has exported functions utilizing SoapServer::setClass().

Замечание:

The persistence of SOAP_PERSISTENCE_SESSION makes only objects of the given class persistent, but not the class static data. In this case, use $this->bar instead of self::$bar.

Замечание:

SOAP_PERSISTENCE_SESSION serializes data on the class object between requests. In order to properly utilize resources (e.g. PDO), __wakeup() and __sleep() magic methods should be utilized.

Список параметров

mode

One of the SOAP_PERSISTENCE_XXX constants.

SOAP_PERSISTENCE_REQUEST - SoapServer data does not persist between requests. This is the default behavior of any SoapServer object after setClass is called.

SOAP_PERSISTENCE_SESSION - SoapServer data does persists between requests. This is accomplished by serializing the SoapServer class data into $_SESSION['_bogus_session_name'], because of this session_start() must be called before this persistence mode is set.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 SoapServer::setPersistence() example

<?php
 class MyFirstPersistentSoapServer {
     private $resource; // (Such as PDO, mysqli, etc..)
     public $myvar1;
     public $myvar2;

     public function __construct() {
         $this->__wakeup(); // We're calling our wakeup to handle starting our resource
     }

     public function __wakeup() {
         $this->resource = CodeToStartOurResourceUp();
     }

     public function __sleep() {
         // We make sure to leave out $resource here, so our session data remains persistent
         // Failure to do so will result in the failure during the unserialization of data
         // on the next request; thus, our SoapObject would not be persistent across requests.
         return array('myvar1','myvar2');
     }
 }

 try {
     session_start();
     $server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
     $server->setClass('MyFirstPersistentSoapServer');
     // setPersistence MUST be called after setClass, because setClass's
     // behavior sets SESSION_PERSISTENCE_REQUEST upon enacting the method.
     $server->setPersistence(SOAP_PERSISTENCE_SESSION);
     $server->handle();
 } catch(SoapFault $e) {
     error_log("SOAP ERROR: ". $e->getMessage());
 }
?>

Смотрите также

  • SoapServer::setClass() - Устанавливает класс, который будет обрабатывать SOAP-запросы

User Contributed Notes

csnaitsirch at web dot de 01-Apr-2010 05:25
I want to give one example for the order of commands if you want to use a class in persistence mode.

<?php
// 1. class definition or include
class UserService
{
    public function __construct() { }
}

// 2. start the session after defining or including the class!!
session_start();

// 3. instanciate the server
$server = new SoapServer(null, array("something"));

// 4. set the class to use
$server->setClass('UserService');

// 5. set persistance mode
$server->setPersistence(SOAP_PERSISTENCE_SESSION);

// 6. handle the request
$server->handle();
?>
doug dot manley at gmail dot com 30-May-2008 12:54
When using "SoapServer::setPersistence( SOAP_PERSISTENCE_SESSION )", you apparently MUST include the class that was used in "SoapServer::setClass()" BEFORE any "session_*" commands.

I found this out using "__autoload()" and a whole lot of "syslog()"; it kept failing to include the class that I was using for my soap server, but that class is ONLY ever referenced by the page itself, and even then only for the purposes of setting the class for the soap server; none of my code would ever cause it to autoload.  The problem was that I was including my session-handling code first.

If the session gets started BEFORE the page defines the class definition, then persistence CANNOT happen.

The order should be:
1. Include the class for use with the soap server.
2. Start up your session.
3. Set up your soap server.
4. Handle your soap request.
boogiebug at gmail dot com 25-Mar-2008 07:40
setPersistence works only for a single instance of service class.

To use multiple instance of services objects, you need to instantiate the classes into objects and use an undocumented SoapServer's method - setObject() to add the service object into the SoapServer object, and handle the service object persistence with $_SESSION instead.

For example:

$ServiceObjects = array()
$ServiceObjects[0] = new ServiceClass1();
$ServiceObjects[1] = new ServiceClass2();
$ServiceObjects[2] = new ServiceClass3();

$_SESSION['ServiceClass1'] = $ServiceObjects[0];
$_SESSION['ServiceClass2'] = $ServiceObjects[1];
$_SESSION['ServiceClass3'] = $ServiceObjects[2];

...

$Servers = array()
for ( $i = 0; $i < count($ServiceObjects); i++)
{
  $s = new SoapServer($wsdl);
  $s->setObject($ServiceObject[$i]);
  $Servers[] = $s;
}

...

$Server[$i]->handle()

...
jan at pinna dot nl 26-Jan-2008 03:28
I found that using both modes (SOAP_PERSISTENCE_SESSION and SOAP_PERSISTENCE_REQUEST) cannot be used simultaniously. Because it didn't work at once, I started experimenting by using different settings and as stated below in the comments, "...also use SOAP_PERSISTENCE_REQUEST to save objects between requests" led me to think it was nessecary to use both modes. Well, it might for others, be but for me it turned out a day of freaking out ;) (trying all kinds of session stuff, etc etc).
Also, if persistence doesn't work, please check if session_start() is called somewhere in the script and try not to call it twice or whatsoever: it won't work...
leon at leonsio dot com 05-Jan-2008 01:10
attention, if you are using a custon session-handler, the SOAP_PERSISTENCE_SESSION methode will use the files-session handler and not your custom handler. also use SOAP_PERSISTENCE_REQUEST to save objects between requests
jared at ws-db dot com 28-Aug-2005 12:07
I had some issues getting session persistence (SOAP_PERSISTENCE_SESSION) to work. I finally got it working after setting session.auto_start=0, and then only calling session_start() in the script containing the SoapServer. Maybe this is obvious, but took me a bit to figure it out.

I only tried it with session.use_cookies=1, so if the settings above don't work for you, make sure cookies are enabled, though it may work without the need for cookies.
cperez1000 at hotmail dot com 28-May-2005 08:54
Always remember to place the "setPersistence" method before the handle method, otherwise it won't work.  It sounds obvious, but it's still a very common mistake, since no errors are shown.
SoapServer::setObject
SoapServer::SoapServer
SoapServer


SoapServer constructor

SoapServer::setPersistence
SoapFault
SoapServer
PHP Manual

SoapServer::SoapServer

(PHP 5 >= 5.0.1)

SoapServer::SoapServer — SoapServer constructor

Описание

public SoapServer::SoapServer ( mixed $wsdl [, array $options ] )

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

Список параметров

wsdl

To use the SoapServer in WSDL mode, pass the URI of a WSDL file. Otherwise, pass NULL and set the uri option to the target namespace for the server.

options

Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor).

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

There is also a features option which can be set to SOAP_WAIT_ONE_WAY_CALLS, SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE.

Примеры

Пример #1 SoapServer::SoapServer() example

<?php

$server = new SoapServer("some.wsdl");

$server = new SoapServer("some.wsdl", array('soap_version' => SOAP_1_2));

$server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C"));

$server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1'));

$server = new SoapServer(null, array('uri' => "http://test-uri/"));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

Список изменений

Версия | Описание
5.2.0 | Added the typemap option.

Смотрите также

  • SoapClient::SoapClient() - Конструктор SoapClient

User Contributed Notes

andyidol at gmail dot com 03-Apr-2012 11:21
Here's my solution to make SOAP-headers based authentication.

1). First of all we define the decorator class for our service class:

<?php

class SOAP_Service_Secure
{
    protected $class_name    = '';
    protected $authenticated = false;

    // -----

    public function __construct($class_name)
    {
        $this->class_name = $class_name;

    }

    public function AuthHeader($Header)
    {
        if($Header->username == 'foo' && $Header->password == 'bar')
            $this->authenticated = true;

    }

    public function __call($method_name, $arguments)
    {
        if(!method_exists($this->class_name, $method_name))
            throw new Exception('method not found');

        $this->checkAuth();

        return call_user_func_array(array($this->class_name, $method_name), $arguments);

    }

    // -----

    protected function checkAuth()
    {
        if(!$this->authenticated)
            HTML_Output::error(403);

    }

}

?>

2). Then we pass an instance of it to the SoapServer object.

<?php

    $Service = new SOAP_Service_Secure('My_Service');

    $Server = new SoapServer('my-service.wsdl');

    $Server->setObject($Service);

    $Server->handle();

?>

3). Implementing a client:

<?php

class AuthHeader
{
    public $username;
    public $password;

}

// -----

$Client = new SoapClient('http://example.com/my-service.wsdl', array(
    'exceptions' => true
));

// -----

$AuthHeader = new AuthHeader();

$AuthHeader->username = 'foo';
$AuthHeader->password = 'bar';

$Headers[] = new SoapHeader('http://example.com', 'AuthHeader', $AuthHeader);

$Client->__setSoapHeaders($Headers);

// -----

$Result = $Client->someMethod();

?>

As you can see SoapServer uses our decorator class to answer client requests. If request contains "AuthHeader" SOAP-header then our wrapper checks the credentials and sets $authenticated parameter to TRUE (on success). Then SoapServer calls requested method on our wrapper, we are intercepting it with __call(), checking authentication and if everything is allright we are calling real method on the "My_Service" class.
jille at quis dot cx 07-May-2011 08:04
The SoapServer can not generate WSDL's yet. (PHP 5.3.5)
It'll exit with "SOAP-ENV:ServerWSDL generation is not supported yet"
ricohn hotmail com 28-Jan-2011 07:18
If you're running $soapServer->handle() and getting an empty server response and no errors (even in the logs), check if you're instantiating the SOAP server like this:

<?php
$soapServer = new SoapServer('http://www.example.com/soap/endpoint?wsdl');
//...
$soapServer->handle(); // Result: Empty response
?>

Instantiating the SOAP server with one the following should fix it:

<?php
// With slash before ?wsdl:
$soapServer = new SoapServer('http://www.example.com/soap/endpoint/?wsdl');
// Or instantiate with the "uri" option, which works with or without the trailing slash:
$soapServer = new SoapServer(null, array('uri' => 'http://www.example.com/soap/endpoint?wsdl'));
$soapServer = new SoapServer(null, array('uri' => 'http://www.example.com/soap/endpoint/?wsdl'));
?>

Hope that helps somebody! Zend_Soap_Server wasn't working for me, and I eventually found that it had to do with the native PHP SOAP class (which ZF uses).
nilzor at gmail dot com 12-May-2010 03:04
Calling a server from .NET:
If you intend to call a PHP SOAP server from a .NET Client, there are a couple of things to be aware of. First of all, I've only got it working in WSDL mode. If anyone have made it work in non-WSDL-mode, I'd be interested in hearing that. In WSDL-mode it works, but both input and output-parameters are wrapped from .NET.

Basically, a function with this signature:

<?php
function SomeFunction($param1, $param2)
{
   return $param1+$param2;
}
?>

Must be rewritten to this, without changing the WSDL:

<?php
function SomeFunction($data)
{
 $valueArray = get_object_vars($data);
 $param1 = $valueArray["param1"];
 $param2 = $valueArray["param2"];
 return Array("SomeFunctionResult" => $param1+$param2);
}
?>
Sloloem 07-Oct-2009 08:31
typemap isn't very well documented at all, but I thought I might be able to use it to clean some things up and map between object fields and XML attributes that have different names but are conceptually the same thing.

Unfortunately type map works at the object level, not the field level like I was hoping, requiring you to provide functions for building the entire object from an XML string (using the XML parser of your choice) and vice versa.  I found the wording of the docs very confusing, both parameters are strings which are function names.

the to_xml function will take the object as a parameter and return a string,
the from_xml function will take an xml string as a parameter and should return an object of the correct type.

Both methods can also throw SOAPFaults or other exceptions which can be caught from the actual client method call ($client->someRemoteMethod())

There are decent usage examples in the PHP build tests:  http://cvs.php.net/viewvc.cgi/php-src/ext/soap/tests/?diff_format=u
The typemap tests are at the bottom.
spiro79 at gmail dot com 21-Sep-2009 01:12
If you are getting an error about always_populate_raw_post_data or Can't find HTTP_RAW_POST_DATA then it means the server isn't getting info from the (you guessed!) raw post data.
Try doing something like this when coding your server:

<?php
$server = new SoapServer(null,array('uri' => "http://localhost/namespace"));
$server->setClass('myClass');
$data = file_get_contents('php://input');
$server->handle($data);
?>

Worked for me!
kostya[.]chumickin [at] 9mail[.]c0m 28-Mar-2009 03:06
Beware: in wsdl mode SoapServer does not properly validate if
request matches the given WSDL. It just skips invalid elements. http://bugs.php.net/bug.php?id=45966
beckman at angryox.com 04-Nov-2008 02:01
While others may not do what I did, I thought if my WSDL was not local and needed to be grabbed via HTTP, I should set the $wsdl var in __construct() to NULL, and set the 'uri' value in the additional parameters.

This does enable non-WSDL mode, which only causes problems when using complex types.  Since your complex types are not respected/imported, you get unexpected problems out the wazoo.

So if you are exposing your class via "setClass" to the SOAP server and for some reason your "types" aren't being returned, you can do this:

<?php
$server = new SoapServer('http://soap.example.com/genwsdl.php?api');
$server->setClass('myClass'); // previously included or defined
$server->handle();
?>

This is NOT correct:
<?php
$server = new SoapServer(NULL, array('uri' => 'http://soap.example.com/genwsdl.php?api'));
?>

I sure wish someone really smart would go into a bit more detail in this documentation of the SoapServer options, why they exist, when to use them, etc.  I find the SOAP docs lacking polish.
lordi at msdi dot ca 29-Jul-2008 09:45
Things that I've searched a lot for that might be useful to somebody:

If you are using Zend Studio, you can easily generate a wsdl file using the WSDL Generator if you document your code using PHPDOC.

One thing a lot of people are searching everywhere, is the way to pass/return an array of variables... In your PHPDOC block use the [] after the variable name like this

<?php
class SoapServer {
  /**
   * This is My Soap Server
   * @param integer[] $a
   * @param string[] $b
   * @param bar[] $c
  */
  public function foo ($a, $b, $c){
  }
}
?>
This way, the function will require an array of integers for $a, an array of strings for $b and an array of objets of Class "bar" for $c

In the WSDL, you'll find something like this

<xsd:complexType name="barArray">
  <xsd:complexContent>
    <xsd:restriction base="soapenc:Array">
      <xsd:attribute ref="soapenc:arrayType" wsdl:arrayType="typens:bar[]"/>
    </xsd:restriction>
  </xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="bar">
  <xsd:all>
    <xsd:element name="var1" type="xsd:boolean"/>
    <xsd:element name="var2" type="xsd:integer"/>
    <xsd:element name="var3" type="xsd:string"/>
  </xsd:all>
</xsd:complexType>

I didn't define anywhere the barArray type, Zend's WSDL Generator generated it automatically...

If you are not using Zend you can generate the wsdl file manually.

Hope it helps someone
alan dot bryan at gmail dot com 01-Feb-2008 04:48
This site helped me put it all together.
http://techblog.bronto.com/brontotechblog/2007/04/php_and_soap_he.html

My issue was I was trying the below example but missing parts in the wsdl.  The above link filled in the pieces that I was missing so it all worked.
php dot net at juamei dot com 31-Oct-2007 03:42
In response to Timo, it is possible to access Soap Headers from the SoapServer class and call methods to handle them. Rather than treat them seperately, they are treated as part of the Soap request.

To pass approximately wss standard headers (note that I couldn't get attributes from the header tags without text preprocessing, so standards compliance failed me), first create the following class on the client:
<?php
/*
 * Login credentials to be supplied as a SOAP header
 * Class used to ensure Soap Head tags in correct format.
 */
class SoapHeaderUsernameToken
{
    /** @var int Password */
    public $Password;
    /** @var int Username */
    public $Username;

    public function __construct($l, $p)
    {
        $this->Password = $p;
        $this->Username = $l;
    }
}
?>

Now, set the Soap Headers:

<?php
    // Set the login headers
    $wsu = 'http://schemas.xmlsoap.org/ws/2002/07/utility';
    $usernameToken = new SoapHeaderUsernameToken($this->username, $this->password);
    $soapHeaders[] = new SoapHeader($wsu, 'UsernameToken', $usernameToken);
?>

Next instantiate the client object, add the headers and make the call:

<?php
    $client = new SoapClient( $wsdl);
    $client->__setSoapHeaders( $soapHeaders );
    $client->__soapCall( $method, $params );
?>

Moving to the Server, you'll handle the Soap call somewhat like:
<?php
// Instantiate server with relevant wsdl & class.
$server = new SoapServer( 'mysoapwsdl.wsdl' );
$server->setClass(  'mysoapclass' );
$server->handle();
?>

The key here is that the headers will be handled first by the server which will call the method mysoapclass::UsernameToken. The way we work this is the UsernameToken method authenticates the username / password combo and sets a protected class var. Then when the Soap Body is handled and the appropriate class method called, a check is made at the start of callable method to ensure authentication has been passed.

If the Soap auth header is missing, the soap body method will be called anyway so the check is essential in case a malevolent client deliberately leaves the headers off.

An example server class is below (missing various methods which I leave as an exercise to the reader to provide):
<?php
class mysoapclass {
    /*
     * Authentication function
     * This is called by the Soap header of the same name. The function name is a Ws-security standard auth tag
     * and corresponds to the header tag.
     *
     * @param string username
     * @param string password
     */
    public function UsernameToken( $username, $password ){
        // Store username for logging
        $this->Username = $username;

        $auth = new $this->AuthClass( $username, $password, get_class($this) );
        if( $auth->IsValid() ){
            $this->Authenticated = true;
        } else {
            $this->ThrowSoapFault( 'auth' );
        }
    }

    /*
     * Test method
     */
    public function felineResponse( $action ){

        // Place this at the start of every exposed method
        // This is because the SoapServer will attempt to call
        // if no authentication headers are passed.
        if(!$this->Authenticated){
            $this->ThrowSoapFault( 'auth' );
        }

        if( $action == 'stroke' ){
            return 'purr';
        } elseif( $action == 'tease' ){
            return 'hiss';
        }
    }

}
?>

This is a adaptation of stuff I found online somewhere...
joel dot pearson at gmail dot com 10-Jul-2007 10:12
In response to jas [at] dansupport (dot) dk:

All you need to do is disable wsdl caching like so:

ini_set("soap.wsdl_cache_enabled", "0");

Then you don't need to delete any cache files.
jas [at] dansupport (dot) dk 29-May-2007 11:24
A general thing i've experienced with SOAP and which, for some reason, isn't mentioned in ANY tutorials I've read, is this: The server tends to cache the interface. This means that if you add a function you'll usually get errors that the function doesn't exist.
If your SOAP server is written in PHP just delete the cache files, usually located in /tmp, whenever you add a function, or modify the parameters. These are named wsdl-******something******
I hope this will spare someone the grief I've experienced with this.
Timo 03-Aug-2006 05:46
It is currently not possible to process soap headers from within a SoapServer instance. If soap headers are specified within a WSDL file, you have to extract the headers manually from the request.

For more information please see http://bugs.php.net/bug.php?id=38309
SoapServer::setPersistence
SoapFault
SoapServer


The SoapFault class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Represents a SOAP fault.

Обзор классов

SoapFault extends Exception {
/* Свойства */
/* Методы */
__construct ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )
SoapFault ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )
public string __toString ( void )
/* Наследуемые методы */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Свойства

message

Prop description

code

Prop description

file

Prop description

line

Prop description

Содержание

  • SoapFault::__construct — SoapFault constructor
  • SoapFault::SoapFault — SoapFault constructor
  • SoapFault::__toString — Obtain a string representation of a SoapFault

User Contributed Notes

chris AT cmbuckley DOT co DOT uk 13-May-2010 03:53
A bit more digging in ext/soap/soap.c and the set_soap_fault function reveals the other undocumented properties from the constructor:

<?php
try {
    throw new SoapFault('code', 'string', 'actor', 'detail', 'name', 'header');
} catch (Exception $ex) {
    var_dump($ex->faultcode, $ex->faultstring, $ex->faultactor, $ex->detail, $ex->_name, $ex->headerfault);
}
?>
dmitry dot koterov at gmail dot com 29-Oct-2009 02:21
You may use undocumented and invisible property $e->faultcode to access string version of $code. Because standard $e->getCode() does not work:

<?php
$e = new SoapFault("test", "msg");
var_dump($e->getCode()); // prints "0"
var_dump($e->faultcode); // prints "test"
?>

Also you may use namespaced fault codes:

<?php
$e = new SoapFault(array("namespace", "test"), "msg");
?>

- see ext/soap/soap.php, PHP_METHOD(SoapFault, SoapFault). To access the namespace, use $e->faultcodens
SoapServer::SoapServer
SoapFault::__construct
SOAP


SoapFault constructor

SoapFault
SoapFault::SoapFault
SoapFault
PHP Manual

SoapFault::__construct

(PHP 5 >= 5.0.1)

SoapFault::__construct — SoapFault constructor

Описание

SoapFault::__construct ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )

Эта функция является псевдонимом: SoapFault::SoapFault()

User Contributed Notes

csnaitsirch at web dot de 01-Apr-2010 05:04
The first Parameter of the constructor, the faultcode, of SoapFault must be a string. Otherwise it will lead to an error.

<?php
throw new SoapFault(1, "Error message!"); // wrong
throw new SoapFault("1", "Error message!"); // right
?>
SoapFault
SoapFault::SoapFault
SoapFault


SoapFault constructor

SoapFault::__construct
SoapFault::__toString
SoapFault
PHP Manual

SoapFault::SoapFault

(PHP 5 >= 5.0.1)

SoapFault::SoapFault — SoapFault constructor

Описание

SoapFault::SoapFault ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )

This class is used to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and detail are standard elements of a SOAP Fault.

Список параметров

faultcode

The error code of the SoapFault.

faultstring

The error message of the SoapFault.

faultactor

A string identifying the actor that caused the error.

detail

More details about the cause of the error.

faultname

Can be used to select the proper fault encoding from WSDL.

headerfault

Can be used during SOAP header handling to report an error in the response header.

Примеры

Пример #1 Some examples

<?php
function test($x)
{
    return new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

It is possible to use PHP exception mechanism to throw SOAP Fault.

Пример #2 Some examples

<?php
function test($x)
{
    throw new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Смотрите также

  • SoapServer::fault() - Issue SoapServer fault indicating an error
  • is_soap_fault() - Checks if a SOAP call has failed

User Contributed Notes

Istratov Vadim 15-Dec-2010 06:46
In case you need to return SOAP Fault for SOAP Client based on Adobe Flash/Flex/AIR and stuck with Flash's inability to process SOAP messages with HTTP code 500 (that's what SOAP Fault returns; read more on this error here: http://bugs.php.net/bug.php?id=43507) then try this dirty hack:

<?php
$server = new SoapServer ( "SomeWSDL.wsdl" );
$server->setClass ( "SOAP_Class" );

/**
 * Catching SOAP Server response and overriding HTTP Status code.
 */
ob_start();
$server->handle ();
$soapResponse = ob_get_contents();
ob_end_clean();

header('HTTP/1.0 200 OK');
echo $soapResponse;
?>

Keep in mind that from PHP 5.2.6 SOAP Fault has an HTTP Status Code = 200 if User-agent is "Shockwave Flash", but when Flash object is integrated into HTML page SOAP Server receives User-agent = Broswer-agent and NOT "Shockwave Flash".

Also it'll be a good idea to return HTTP 200 Code only if 500 Error is caused by known service faults.
klemens dot r at gmail dot com 20-May-2010 02:17
To get custom Soap Error Codes use in the catch $e->faultcode instead of $e->getCode.

<?php
try {
    // ...
} catch (SoapFault $e) {
    echo $e->faultcode;
}
?>
del at babel dot com dot au 14-Jul-2008 12:10
There are only a few legitimate "codes" that a SOAP fault can have and be understood by most clients in accordance with the protocol.  You can't just pass in, for example, a database error code or you'll get a fatal error like "SoapFault::__construct(): Invalid parameters. Invalid fault code."

The ones you generally want to use are "Sender" where you've gotten bad parameters, or "Receiver" where the server has gotten an error for some reason.

See here:

http://www.w3.org/TR/soap12-part1/#faultcodes
doug 30-Jul-2007 11:59
SoapFault extends the base Exception class.
SoapFault::__construct
SoapFault::__toString
SoapFault


Obtain a string representation of a SoapFault

SoapFault::SoapFault
SoapHeader
SoapFault
PHP Manual

SoapFault::__toString

(PHP 5 >= 5.0.1)

SoapFault::__toString — Obtain a string representation of a SoapFault

Описание

public string SoapFault::__toString ( void )

Returns a string representation of the SoapFault.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

A string describing the SoapFault.

User Contributed Notes

There are no user contributed notes for this page.
SoapFault::SoapFault
SoapHeader
SoapFault


The SoapHeader class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Represents a SOAP header.

Обзор классов

SoapHeader {
/* Методы */
__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )
SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = false [, string $actor ]]] )
}

Содержание

  • SoapHeader::__construct — SoapHeader constructor
  • SoapHeader::SoapHeader — SoapHeader constructor

User Contributed Notes

john at jtresponse dot co dot uk 13-Mar-2012 01:30
None of the examples really do it for me.
Note: you should NOT need to hard-code any XML.

Here is an example of creating a nested header and including a parameter.

$client = new SoapClient(WSDL,array());

$auth = array(
        'UserName'=>'USERNAME',
        'Password'=>'PASSWORD',
        'SystemId'=> array('_'=>'DATA','Param'=>'PARAM'),
        );
  $header = new SoapHeader('NAMESPACE','Auth',$auth,false);
  $client->__setSoapHeaders($header);

Gives the following header XML:

  <SOAP-ENV:Header>
    <ns1:Auth>
      <ns1:SystemId Param="PARAM">DATA</ns1:SystemId>
      <ns1:UserName>USERNAME</ns1:UserName>
      <ns1:Password>PASSWORD</ns1:Password>
    </ns1:Auth>
  </SOAP-ENV:Header>
jstilow at mobileobjects dot de 10-Oct-2011 07:03
It cost me some time to figure out how to add a SoapHeader to a server response. For me the following solution works well enough:

<?php
class SoapService {
    private $server = null;

    public function __construct($server)
    {
        $this->server = $server;
    }

    public function soap($request) {
        // do something useful

        // These are the two "magic" lines:
        $header = new SoapHeader("namespace", "name", new HeaderClass("possible some parameters"));
        $this->soap_server->addSoapHeader($header);

        // do more useful stuff
    }
}

$soap_server = new SoapServer("./your.wsdl");
$soap_server->setClass("SoapService", $soap_server);
$soap_server->handle();
?>

See also:
https://bugs.php.net/bug.php?id=32410
SoapFault::__toString
SoapHeader::__construct
SOAP


SoapHeader constructor

SoapHeader
SoapHeader::SoapHeader
SoapHeader
PHP Manual

SoapHeader::__construct

(PHP 5 >= 5.0.1)

SoapHeader::__construct — SoapHeader constructor

Описание

SoapHeader::__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )

Эта функция является псевдонимом: SoapHeader::SoapHeader()

User Contributed Notes

There are no user contributed notes for this page.
SoapHeader
SoapHeader::SoapHeader
SoapHeader


SoapHeader constructor

SoapHeader::__construct
SoapParam
SoapHeader
PHP Manual

SoapHeader::SoapHeader

(PHP 5 >= 5.0.1)

SoapHeader::SoapHeader — SoapHeader constructor

Описание

SoapHeader::SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = false [, string $actor ]]] )

Constructs a new SoapHeader object.

Список параметров

namespace

The namespace of the SOAP header element.

name

The name of the SoapHeader object.

data

A SOAP header's content. It can be a PHP value or a SoapVar object.

mustUnderstand

Value of the mustUnderstand attribute of the SOAP header element.

actor

Value of the actor attribute of the SOAP header element.

Примеры

Пример #1 SoapHeader::SoapHeader() example

<?php
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->__soapCall("echoVoid", null, null,
                new SoapHeader('http://soapinterop.org/echoheader/',
                               'echoMeStringRequest',
                               'hello world'));
?>

Смотрите также

  • SoapClient::__soapCall() - Вызывает SOAP-функцию
  • SoapVar::SoapVar() - SoapVar constructor
  • SoapParam::SoapParam() - SoapParam constructor
  • SoapServer::addSoapHeader() - Add a SOAP header to the response

User Contributed Notes

daniuf at gmail dot com 18-Oct-2010 01:20
Just for you to know, when trying to get header -using SOAP- input you should do this:

<?php

//SOAP Server class constructor

$xml = file_get_contents('php://input');

/*
In $xml you'll have all the XML input and then with a simple Regexp you can get Usr & Pass when you need to validate a Web Service using SOAP
*/

?>

Hope it helps someone as it helped me :D
yacahuma 27-Jan-2009 06:29
I was unable to connect to .net using any of the previous notes. I found out that the easiest way is the one that works. Everyone is trying to use soapvar . but you dont need to.

$ns = 'http://blabla.com/Services/Services';
$AuthHeader = new AuthHeader($LoginResponse);
$header =  new SoapHeader($ns,"AuthHeader",  $AuthHeader,false);
$this->soapClient->__setSoapHeaders(array($header));

my header was suppose to look like this
<soapenv:Header>
<ns1:AuthHeader>
<ns1:SessionKey>xxxx</ns1:SessionKey>
<ns1:SessionRole>xxxxx</ns1:SessionRole>
<ns1:UserType>xx</ns1:UserType>
<ns1:UserName>xxx</ns1:UserName>
</ns1:AuthHeader>
</soapenv:Header>

so my AuthHeader is just a simple class
class AuthHeader
{
  var $SessionKey;//string
  var $SessionRole;//string
  var $UserType;//string
  var $UserName;//string

  function __construct($LoginResponse)
  {
     $this->SessionKey  = $LoginResponse->LoginResult->SessionKey;
     $this->SessionRole = $LoginResponse->LoginResult->SessionRole;
     $this->UserType    = $LoginResponse->LoginResult->UserType;
     $this->UserName    = $LoginResponse->LoginResult->UserName;

  }
}

The important lesson here is the when you build your header you can use a normal class. It does not need to be a soapvar
aeolianmeson at dontfindme dot blitzeclipse dot com 07-May-2008 08:31
To do headers (the raw way):

    // Setting "trace" will allow us to view the request that we are making, after we have made it.
    $objClient = new SoapClient("http://www.somewhere.com/wsdls/some.wsdl", array('trace' => true));

    // These parameters satisfy this specific remote call.
    $arrParameters_Login = array('username' => 'username', 'password' => 'password', 'company' => 'Company');

    // Invoke the remote call "login()".
    $objLogin =  $objClient->login($arrParameters_Login);

    // Grab session ID that this remote call will provide.
    $strSessionID = $objLogin->loginReturn->sessionId;

    // Set headers-- The remote call "query()" will require a header pointing to our session.

    $strHeaderComponent_Session = "<SessionHeader><sessionId>$strSessionID</sessionId></SessionHeader>";

    $objVar_Session_Inside = new SoapVar($strHeaderComponent_Session, XSD_ANYXML, null, null, null);
    $objHeader_Session_Outside = new SoapHeader('namespace.com', 'SessionHeader', $objVar_Session_Inside);

    // More than one header can be provided in this array.
    $objClient->__setSoapHeaders(array($objHeader_Session_Outside));

    // Set the query parameters.

    $strQuery = 'select empID from Time where empID = 92389278';
    $arrParameters_Query = array('queryString' => $strQuery);

    // Make call.

    $objResponse = $objClient->query($arrParameters_Query);

    header('Content-Type: text/xml; ');
    print($objClient->__getLastRequest());

The request that goes out:

<SOAP-ENV:Envelope>
    <SOAP-ENV:Header>
        <SessionHeader>
            <sessionId>8789364113604871127</sessionId>
        </SessionHeader>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <ns1:query>
            <ns1:queryString>select empID from Time where empID = 92389278</ns1:queryString>
        </ns1:query>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
harlan at plauditdesign dot com 15-Mar-2006 11:04
Here is a way to get headers on the server side. It will fill up an assoc with all headers in a namespace. In its current state, it only handles text content; but each header is expanded to a DOMNode, so you can do whatever you wish to parse custom types.

In my case this method is useful because I want to pass PHPSESSID in a SOAP header, and I need to set it before I even call SoapServer::handle().

//
// READ SOAP HEADERS, STOP READING AT SOAPENV:BODY ELEMENT
//
$xml = new XmlReader();
$xml->XML( $HTTP_RAW_POST_DATA );

$shoppingCartHeaders = array();
while( $xml->read() ) {
    if( $xml->namespaceURI == "urn:com.plauditdesign.shoppingcart.client.headers#"
        && $xml->nodeType == XMLReader::ELEMENT ) {

        $headerNode = $xml->expand();
        $shoppingCartHeaders[ $xml->localName ] = $headerNode->textContent;
    } elseif( $xml->namespaceURI == "http://schemas.xmlsoap.org/soap/envelope/"
        && $xml->nodeType == XMLReader::ELEMENT
        && $xml->localName == "Body" ) {

        $xml->close();
    }
}

...

if( isset( $shoppingCartHeaders["sessionId"] ) ) {
    session_id( $shoppingCartHeaders["sessionId"] );
}

...

$server->setPersistence( SOAP_PERSISTENCE_SESSION );
$server->handle();
jared DOT kuolt at gmail dot com 28-Oct-2005 09:57
To build the authentication headers like below FOR WSDL:

**NOTE** I cannot find documentation on the __setSoapHeaders() method, though it does work in 5.0.4

<?php

class MySoapClass
{

    function __construct(){
        // Blah blah blah
        $this->soap = new SoapClient($this->foo, $this->bar);

    }

    // Build that header!
    private function build_auth_header(){
        // Build an object with parameters
        $auth->username = $this->username;
        $auth->password = $this->password;

        $authvalues = new SoapVar($auth, SOAP_ENC_OBJECT);
        $header =  new SoapHeader($this->name_space, "Authentication", // Rename this to the tag you need
                                                          $authvalues, false);

        $this->soap->__setSoapHeaders(array($header));

    }

    // Wrapper so we can build auth header first
    public function MySoapFunction($params){

        $this->build_auth_header();
        $this->soap->MySoapFunction($params);

    }

}
?>
mobi at delfnet dot pl 31-May-2005 12:24
In botoom code is bug.

is:

// create authentication header values
$authvalues=new SoapVar($auth,SOAP_ENC_OBJECT,'authenticate');

should be:

// create authentication header values
$authvalues=new SoapVar($auth,SOAP_ENC_OBJECT);
clewis at myfonts dot com 09-Feb-2005 08:52
If you are using WSDL to define your SOAP Headers, note that PHP's SoapServer class will not process incoming headers unless the <message> and <part> names are identical for the header methods.

Define a SOAP header function like this in WSDL:

<!-- replace "tns:" with your own namespace abbreviation -->

<!-- define method arguments using a complexType -->
<xsd:complexType name="HeaderMethodArgs">
    <xsd:all>
        <xsd:element ... name="arg1"/>
        <xsd:element ... name="arg2"/>
    </xsd:all>
</xsd:complexType>

<!-- define method message with single part -->
<message name='headerMethodName'>
    <part name='headerMethodName' type='tns:HeaderMethodArgs'/>
</message>

<!-- add header tag to operations that use this header -->
<operation name='someBodyMethod'>
    ...
    <input>
        <soap:body .../>
        <soap:header
            ...
            message='tns:headerMethodName'
            part='headerMethodName'
        />
    </input>
    <output>...</output>
</operation>
php dot net at sowen dot de 18-Jan-2005 03:02
If you are trying to create a header like this:

<SOAP-ENV:Header>
<ns2:authenticate SOAP-ENV:actor="http://schemas.xmlsoap.org/soap/actor/next">
<username>myuser</username>
<password>secret</password>
</ns2:authenticate>
</SOAP-ENV:Header>

Try to use a class to create Header-vars:

class authentication_header {
  private $username;
  private $password;
  public function __construct($username,$password) {
     $this->username=$username;
     $this->password=$password;
  }
}

In your soap client program:

// generate new object
$auth=new authentication_header('myuser','secret');
// create authentication header values
$authvalues=new SoapVar($auth,SOAP_ENC_OBJECT,'authenticate');
// generate header
$header=new SoapHeader("myURN",
                           "authenticate",
                           $authvalues,
                           false,
                            "http://schemas.xmlsoap.org/soap/actor/next");

And do the request like this (non-WSDL version):

$client->__call('function', $params, null, $header);

Have fun,
Nils Sowen
SoapHeader::__construct
SoapParam
SoapHeader


The SoapParam class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Represents parameter to a SOAP call.

Обзор классов

SoapParam {
/* Методы */
__construct ( mixed $data , string $name )
SoapParam ( mixed $data , string $name )
}

Содержание

  • SoapParam::__construct — SoapParam constructor
  • SoapParam::SoapParam — SoapParam constructor

User Contributed Notes

There are no user contributed notes for this page.
SoapHeader::SoapHeader
SoapParam::__construct
SOAP


SoapParam constructor

SoapParam
SoapParam::SoapParam
SoapParam
PHP Manual

SoapParam::__construct

(PHP 5 >= 5.0.1)

SoapParam::__construct — SoapParam constructor

Описание

SoapParam::__construct ( mixed $data , string $name )

Эта функция является псевдонимом: SoapParam::SoapParam()

User Contributed Notes

There are no user contributed notes for this page.
SoapParam
SoapParam::SoapParam
SoapParam


SoapParam constructor

SoapParam::__construct
SoapVar
SoapParam
PHP Manual

SoapParam::SoapParam

(PHP 5 >= 5.0.1)

SoapParam::SoapParam — SoapParam constructor

Описание

SoapParam::SoapParam ( mixed $data , string $name )

Constructs a new SoapParam object.

Список параметров

data

The data to pass or return. This parameter can be passed directly as PHP value, but in this case it will be named as paramN and the SOAP service may not understand it.

name

The parameter name.

Примеры

Пример #1 SoapParam::SoapParam() example

<?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
                                    'uri'      => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?>

Смотрите также

  • SoapClient::__soapCall() - Вызывает SOAP-функцию
  • SoapVar::SoapVar() - SoapVar constructor

User Contributed Notes

Alex 24-Feb-2010 05:20
You probably want to try SoapVar instead of SoapParam if you want to specify attributes/namespace.
Alex 24-Feb-2010 05:18
Make sure to always cast your parameters prior to creating a SoapParam.  Otherwise you will wind up with an incorrect xsi:type and possibly no value.

$value = 0;
$param0 = new SoapParam(
                $value, $param0_name);

will give you:

<$param0_name xsi:type="xsd:null"></$param0_name>

while:

$value = 0;
$param0 = new SoapParam(
                (int)$value, $param0_name);

<$param0_name xsi:type="xsd:int">0</$param0_name>

which is probably what you want.
barryking93 at gmail dot com 05-Dec-2007 02:42
You have to use SoapVar instead of SoapParam if you want it to do something fancy like using different opening and closing tags.  I ran into this using the SOAP API for Zimbra.
Jeremy 12-Jul-2007 08:31
Is there anyway to create a SOAP parameter like:

<a n="something">DATA</a>

If I try to form a param using the following code the resulting request is:

Code: SoapParam("DATA", "a n=\"something\"");
Result: <a n="something">DATA</a n="something">

This is giving me an error from the SOAP server because its expecting a properly formed closing tag without the encapsulated attribute.
SoapParam::__construct
SoapVar
SoapParam


The SoapVar class

(Информация о версии неизвестна, возможно, только в SVN)

Введение

A class representing a variable or object for use with SOAP services.

Обзор классов

SoapVar {
/* Методы */
__construct ( string $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )
SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )
}

Содержание

  • SoapVar::__construct — SoapVar constructor
  • SoapVar::SoapVar — SoapVar constructor

User Contributed Notes

There are no user contributed notes for this page.
SoapParam::SoapParam
SoapVar::__construct
SOAP


SoapVar constructor

SoapVar
SoapVar::SoapVar
SoapVar
PHP Manual

SoapVar::__construct

(PHP 5 >= 5.0.1)

SoapVar::__construct — SoapVar constructor

Описание

SoapVar::__construct ( string $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

Эта функция является псевдонимом: SoapVar::SoapVar()

User Contributed Notes

There are no user contributed notes for this page.
SoapVar
SoapVar::SoapVar
SoapVar


SoapVar constructor

SoapVar::__construct
XML-RPC
SoapVar
PHP Manual

SoapVar::SoapVar

(PHP 5 >= 5.0.1)

SoapVar::SoapVar — SoapVar constructor

Описание

SoapVar::SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

Constructs a new SoapVar object.

Список параметров

data

The data to pass or return.

encoding

The encoding ID, one of the XSD_... constants.

type_name

The type name.

type_namespace

The type namespace.

node_name

The XML node name.

node_namespace

The XML node namespace.

Примеры

Пример #1 SoapVar::SoapVar() example

<?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f)
    {
        $this->varString = $s;
        $this->varInt = $i;
        $this->varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>

Смотрите также

  • SoapClient::__soapCall() - Вызывает SOAP-функцию
  • SoapParam::SoapParam() - SoapParam constructor

User Contributed Notes

tcell 29-Feb-2012 06:53
One potential gotcha with this is that if the XML you are passing in has the <?xml... declaration, it may cause problems on the server side. It's best to strip this out with str_replace.
jbbrunsveld at gmail dot com 20-May-2011 07:05
It took me more than one day to figure out how to use the SoapVar object in a multilevel/complex SOAP request.
If you want to set-up a multilevel/complex SOAP call with parameters in subnodes, you can use the following methods:

<?php
/* Simple example with array as parameter */
$wsdl_url = '';
$client     = new SoapClient($wsdl_url, array('trace' => true));
$parameters = array(
    'FromCurrency' => 'EUR',
    'ToCurrency' => 'AUD',
);

$client->ConversionRate($parameters);
echo htmlentities($client->__getLastRequest());

/* Simple example with stdClass object as parameter */
$wsdl_url  = '';
$client = new SoapClient($wsdl_url, array('trace' => true));

$parameters = new stdClass();
$parameters->FromCurrency = 'EUR';
$parameters->ToCurrency = 'AUD';

$client->ConversionRate($parameters);
echo htmlentities($client->__getLastRequest());

/* Example with complex/nested node structure using an array as param*/
$wsdl_url = "http://yourwsdlfile";
$client  = new SoapClient($wsdl_url, array('trace' => true));
$client->YourCall(array(
    'YourContainerNodeName' => array(
        'Level1NodeFoo' => '100',
        'Level1NodeBar' => '100',
        'Subnodes' => array(
            'NodeLevel2' => 'test'
        )
    )
));

/* Example with complex/nested node structure using an stdClass as param */
$wsdl_url = "http://yourwsdlfile";
$client  = new SoapClient($wsdl_url, array('trace' => true));
$params = new stdClass();
$params->YourContainerNodeName = new stdClass();
$params->YourContainerNodeName->Level1NodeFoo = 100;
$params->YourContainerNodeName->Level1NodeBar = 100;
$params->YourContainerNodeName->Subnodes = new stdClass();
$params->YourContainerNodeName->Subnodes->NodeLevel2 = 'test';

$client->YourCall($params);

/* Example with complex/nested node structure using an stdClass and SoapVars as param */
$wsdl_url = "http://yourwsdlfile";
$client  = new SoapClient($wsdl_url, array('trace' => true));

$params = new stdClass();
$params->YourContainerNodeName = new stdClass();
$params->YourContainerNodeName->Level1NodeFoo = 100;
$params->YourContainerNodeName->Level1NodeBar = 100;
$params->YourContainerNodeName->Subnodes = new stdClass();
$params->YourContainerNodeName->Subnodes->NodeLevel2 = new SoapVar(3, XSD_INT, 'xsd:int');
$params->YourContainerNodeName->Subnodes->NodeLevel3 = new SoapVar("<ns1:AdText><![CDATA[hallo<br><br>test]]></ns1:AdText>", XSD_ANYXML);
$params->YourContainerNodeName->Subnodes->NodeLevel4 = array(
    new SoapVar(1, XSD_INT, 'xsd:int'),
    new SoapVar(2, XSD_INT, 'xsd:int'),
    new SoapVar(3, XSD_INT, 'xsd:int')
);
?>
Krzych 03-Dec-2010 06:54
It might be obvious to some but not to everyone
if you ever wondered how to encode attribute in soap object, use proper coding and not hacking by passing xml and flag XSD_ANYXML

try using this
<?php
 $amount['_'] = 25;
 $amount['currencyId'] = 'GBP';
 $encodded = new SoapVar($amount, SOAP_ENC_OBJECT);

?>
and end result wound be
<amount currencyId="GBP">25</amount>

hope that helps someone
cb at wasteland dot org 02-Jul-2009 02:01
If you need to add attributes XML entities in your SOAP query like this:

"<FilterBy Column="Id" FilterOperator="=" FilterValue="NUMBER" Table="Case">"

Use SoapVar() with the type XSD_ANYXML as shown below.  Example uses __soapCall and other SoapParams.

<?php
$response = $client->__soapCall('GetFilteredRecordList',
    array(new SoapParam($DSToken, 'Token'),
          new SoapParam('Slide', 'TableName'),
          new SoapVar('<FilterBy Column="Id" FilterOperator="=" FilterValue="NUMBER" Table="Case"/>', XSD_ANYXML)),
    array('soapaction' => 'http://www.example.com/webservices/GetFilteredRecordList'));
?>

Use this so you don't waste HOURS looking around:
clement006 at gmail dot com 08-Sep-2008 05:23
I spent hours trying to send an XML document
(in XSD_ANYXML format) to a .NET webservice...

I don't know if it's always the case with .NET webservices,
but I had to use a little trick with the SoapVar object
to finally get this thing working.

Here is the code that works for me;
Hope it will help someone!

<?php

// xml content
$xmlDocument = '<Result>
    <Product id="12345" language="fr-BE">
        <Data>
            <Brand>BrandName</Brand>
            <ProductName>Bag</ProductName>
        </Data>
    </Product>
</Result>';

// initiate soap client
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient(
            "http://dotnetwebservice.com/Products.asmx?wsdl",
            array(
                'trace' => 1,
                'exceptions' => 1,
                'soap_version' => SOAP_1_1,
                'encoding' => 'ISO-8859-1',
                'features' => SOAP_SINGLE_ELEMENT_ARRAYS
            )
);

// prepare xml
// I debugged using $client->__getLastRequest() and
// then saw that the node around the XML was missing.
// So the trick here is to manually add the parameter
// (see the WSDL to catch the right parameter name of course).
$xmlvar = new SoapVar(
            '<ns1:xmlDocument>'.$xmlDocument.'</ns1:xmlDocument>',
            XSD_ANYXML
);

// send xml
try {
    $params->xmlDocument = (object)$xmlvar;
    $save_result = $client->SaveProduct($params);
    echo "<pre>\n\n";
    echo "Result :\n";
    var_dump($save_result);
    echo "</pre>";
} catch (SoapFault $e) {
    echo "SOAP Fault: ".$e->getMessage()."<br />\n";
}

//* DEBUG
echo "<pre>\n\n";
echo "Request :\n";
echo htmlspecialchars($client->__getLastRequest())."\n";
echo "</pre>";
//*/

?>
OrionI 11-Jul-2005 07:30
This class is useful when dealing with the "anyType" type (generic object reference): it lets you specify the xsd type to provide "late binding" type information.

Here's a really simple example: I have a .NET service that can take a string, a date, and integer, or other types, so I use the .NET "object" type. Here's an example of such a service--this one just tells me what type I passed in. (It's nice to use when checking to see if PHP passed in the type information the way .NET expects it.)

//inside a service.asmx.cs file...
[WebMethod]
public string WhatTypeIsThis(object ObjectParameter)
{
   return "You passed in a " + ObjectParameter.GetType().Name
     + ": " + ObjectParamter.ToString();
}

To call this service with a string from PHP, I used this code:
<?php
//set up the service client using WSDL
$client = new SoapClient("http://localhost/folder/service.asmx?WSDL");

//This is the variable that will be typed as an XSD string
$typedVar = new SoapVar("mystring", XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema");
//This is the wrapper object for incoming parameters
$wrapper->ObjectParameter = $typedVar;
//This is the named parameter object that will be passed in to the service
$params = new SoapParam($wrapper, "WhatTypeIsThis");

//call the service with the string
$result = $client->WhatTypeIsThis($params);
//show the result
echo $result->WhatTypeIsThisResult;
?>

The output from this should be:
"You passed in a String: mystring"

The SOAP message that is passed in looks like this:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="http://tempuri.org/">
    <SOAP-ENV:Body>
        <ns1:WhatTypeIsThis>
            <ns1:ObjectParameter xsi:type="xsd:string">mystring</ns1:ObjectParameter>
        </ns1:WhatTypeIsThis>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

It's that xsi:type="xsd:string" that gives .NET the heads up that though the ObjectParameter is being passed in as an object, it is also a string.

When trying other types, it's helpful to see exactly what is being sent to the service--to see the SOAP messages like the one above, use the trace option when making your SOAP client and then call the $client->__getLastRequest() function. (See http://www.php.net/soap_soapclient_getlastrequest)  You may need to use try/catch constructs if you're generating errors.

Another helpful function is var_dump($client->__getTypes())--it shows how PHP parsed the WSDL file to create types to pass back and forth.
SoapVar::__construct
XML-RPC
SoapVar


XML-RPC

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • XML-RPC Функции
    • xmlrpc_decode_request — Декодирует XML в нативные типы PHP
    • xmlrpc_decode — Декодирует XML в нативные типы PHP
    • xmlrpc_encode_request — Генерирует XML для метода запроса
    • xmlrpc_encode — Генерирует XML для PHP значения
    • xmlrpc_get_type — Получает XML-RPC тип для значения PHP
    • xmlrpc_is_fault — Определяет, является ли массив значений представлением ошибки XMLRPC
    • xmlrpc_parse_method_descriptions — Декодирует XML в список описаний методов
    • xmlrpc_server_add_introspection_data — Добавляет документацию самоанализа
    • xmlrpc_server_call_method — Разбирает XML запросы и вызывающие методы
    • xmlrpc_server_create — Создаёт XML-RPC сервер
    • xmlrpc_server_destroy — Уничтожает серверные ресурсы
    • xmlrpc_server_register_introspection_callback — Регистрирует функцию PHP для генерации документации
    • xmlrpc_server_register_method — Регистрирует функцию PHP к методу ресурса, соответствующему method_name
    • xmlrpc_set_type — Устанавливает тип XML-RPC, base64 или datetime для значения строки PHP

User Contributed Notes

aim at secoya dot dk 15-Sep-2009 08:08
Here is a little wrapper class I just developed. It simply calls the methods you register with it.

<?php
class XMLRPCServer {

    private $serverHandler;

    private $externalFunctions;

    public function __construct() {
        $this->serverHandler = xmlrpc_server_create();
        $this->externalFunctions = array();
    }

    public function registerMethod($externalName, $function, $parameterNames) {
        if($function == null) $function = $externalName;
        xmlrpc_server_register_method($this->serverHandler, $externalName, array(&$this, 'callMethod'));
        $this->externalFunctions[$externalName] =
            array('function'       => $function,
                  'parameterNames' => $parameterNames);
    }

    public function callMethod($functionName, $parametersFromRequest) {
        $function = $this->externalFunctions[$functionName]['function'];
        $parameterNames = $this->externalFunctions[$functionName]['parameterNames'];
        $parameters = array();
        foreach($parameterNames as $parameterName) {
            $parameters[] = $parametersFromRequest[0][$parameterName];
        }
        return call_user_func_array($function, $parameters);
    }

    public function computeAnswer() {
        return xmlrpc_server_call_method($this->serverHandler, file_get_contents('php://input'), null);
    }
}

// USAGE EXAMPLE HERE
$xmlRPCServer = new XMLRPCServer();
$someServer = new SomeXmlRPCServer($xmlRPCServer);
$answer = $xmlRPCServer->computeAnswer();
header('Content-Type: text/xml');
print($answer);
class SomeXmlRPCServer{

    private $xmlRPCServer;

    public function __construct($xmlRPCServer) {
        $this->xmlRPCServer = $xmlRPCServer;
        $this->xmlRPCServer->registerMethod(
            'selectDatabase',        // The name the XML-RPC Client calls
            array(&$this, 'selectDatabaseInternal'),    // Pointer to the method, can be a simple string if you have global functions
            array('dbName', 'something')        // Name of the parameters and their ordering
        );
    }

    public function selectDatabaseInternal($dbName, $test) {
        return 'dbName:.'.$dbName.'.test:'.$test;
    }
}
?>
SoapVar::SoapVar
Введение
Веб-сервисы


Введение

Эти функции могут быть использованы для написания XML-RPC серверов и клиентов. Вы можете найти более подробную информацию о XML-RPC по ссылке » http://www.xmlrpc.com/, и много документации для этого расширения и его функций по ссылке » http://xmlrpc-epi.sourceforge.net/.

Внимание

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и любую другую относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

User Contributed Notes

There are no user contributed notes for this page.
XML-RPC
Установка и настройка
XML-RPC


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
XML-RPC


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Поддержка XML-RPC в PHP не включена по умолчанию. Вам нужно будет использовать конфигурационную опцию --with-xmlrpc[=DIR] при компиляции PHP для включения поддержки XML-RPC. Это расширение входит в комплектацию PHP начиная с версии 4.1.0.

User Contributed Notes

SalmanAbbas007 13-Mar-2011 05:53
Note: On Windows you just have to uncomment the following line in php.ini :-

;extension=php_xmlrpc.dll
Требования
Настройка во время выполнения
Установка и настройка


Типы ресурсов

Это расширение определяет XML-RPC серверный ресурс, возвращаемый xmlrpc_server_create().

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
XML-RPC Функции
XML-RPC


XML-RPC Функции

Содержание

  • xmlrpc_decode_request — Декодирует XML в нативные типы PHP
  • xmlrpc_decode — Декодирует XML в нативные типы PHP
  • xmlrpc_encode_request — Генерирует XML для метода запроса
  • xmlrpc_encode — Генерирует XML для PHP значения
  • xmlrpc_get_type — Получает XML-RPC тип для значения PHP
  • xmlrpc_is_fault — Определяет, является ли массив значений представлением ошибки XMLRPC
  • xmlrpc_parse_method_descriptions — Декодирует XML в список описаний методов
  • xmlrpc_server_add_introspection_data — Добавляет документацию самоанализа
  • xmlrpc_server_call_method — Разбирает XML запросы и вызывающие методы
  • xmlrpc_server_create — Создаёт XML-RPC сервер
  • xmlrpc_server_destroy — Уничтожает серверные ресурсы
  • xmlrpc_server_register_introspection_callback — Регистрирует функцию PHP для генерации документации
  • xmlrpc_server_register_method — Регистрирует функцию PHP к методу ресурса, соответствующему method_name
  • xmlrpc_set_type — Устанавливает тип XML-RPC, base64 или datetime для значения строки PHP

User Contributed Notes

digibrisk at gmail dot NOSPAM dot SPAMNO dot com 05-Oct-2007 03:24
Adding to what giunta dot gaetano at sea-aeroportimilano dot it and astrolox at lawyersonline dot co dot uk said about the Sourceforge PHP XML-RPC project: You can probably use function_exists() to determine whether the extension is installed so you don't have to incur performance costs. If it's not installed, then the function won't exist, and function_exists() returns false. You can then fall back on the alternative library if that's the case. For example:

<?php

if(!function_exists("xmlrpc_server_create")) {
    // include necessary files.
}

?>
handco at gmail dot com 20-Feb-2007 08:19
Hi,

A little snippet to implement OO XML RPC Server.

File RPCPlugin.php :

class RPCPlugins {

    private $plugins;

    function __construct ($pathname, $rpcServer) {
        $d = dir($pathname);
        while (($file = $d->read()) !== false) {
            if (ereg('(.*)\.php$', $file, $regs)) {
                include_once ($pathname . '/' . $file);
                $class=$regs[1];
                $this->plugins = new $class($rpcServer);
            }
        }
    }

}

class RPCPlugin {

    private $_rpcServer;

    function __construct($rpcServer) {
        $this->_rpcServer = $rpcServer;

        $methods = get_class_methods($this);

        foreach ($methods as $method) {
            if (substr($method, 0,1) != '_') {
                xmlrpc_server_register_method($rpcServer,get_class($this) . "." . $method,array(&$this,$method));
            }
        }

    }

}

An example of plugin in plugins/Test.php  :

 class Test extends RPCPlugin {

     function HelloWorld ($method, $params) {
         return "Hello World --->>" . $params[0];
     }

 }

Now the real server :

require_once 'RPCPlugin.php';

 $rpcServer = xmlrpc_server_create();

$plugins = new RPCPlugins(realpath('plugins/'), $rpcServer);

 $resp = xmlrpc_server_call_method($rpcServer,$HTTP_RAW_POST_DATA,null);
 if ($resp) {
     header ('Content-Type: text/xml');
     echo $resp;
 }
 xmlrpc_server_destroy($rpcServer)

Then you can call ethod by classname.method.
For this sample Test.HelloWorld

Hn'Co
giunta dot gaetano at sea-aeroportimilano dot it 13-Sep-2006 06:40
If you need to use this extension but are stuck on a server where it can not be installed, the php-xmlrpc library found at http://phpxmlrpc.sourceforge.net includes an emulation layer that aims to be 100% compatible with the API of the native extension (as part of the "extras" package since version 0.2).
This means your code should be able to run unmodified on top of the php-xmlrpc library. Of course performance will be at least an order of magnitude worse...
keithNO dot SPAMthornhill at gmail dot com 17-May-2006 02:16
for others attempting the same thing, here is what a function would look like if you wanted to send a base64 encoded file from a client and then save it onto the server. the other code necessary to call this function via an RPC is available in other comments so i won't repeat it.

parameters:
1 - name of file
2 - base64 encoded data of file

note the use of $file_data->scalar

<?
    function sendFile($method_name, $params, $user_data) {
        $file = "/somedir/" . $params[0];
        $file_data = $params[1];

        $fh = @fopen($file, "wb");
        if ($fh) {
            if (@fwrite($fh, $file_data->scalar)) {
                $msg = "success msg";
            } else {
                $msg = "couldn't write to file";
            }
            fclose($fh);
            return $msg;
        } else {
            return "couldn't open file";
        }
    }
?>
09-Mar-2006 12:47
This XML-RPC Service makes the use XML-RPC very esay.

<?php

/**
* function myfun() returns
*@return array
*/
function myfunc(){
    return $some_array;
}

$ws = new XML_RPC_Server();
$ws->registerFunction('myfunc');
$ws->run();

?>

http://www.pure-php.de/node/31

It creates also a simple docu.
http://www.pure-php.com/php/service.php?doc
john # curioussymbols com 19-Oct-2005 04:37
I couldn't make the 'xmlrpc_errors' php.ini setting do anything
noticeable (PHP 4.3.11), so I used the following code to report errors
from my XMLRPC server. Hope it's helpful for someone.

<?php
function return_xmlrpc_error($errno,$errstr,$errfile=NULL,$errline=NULL
       ,$errcontext=NULL){
    global $xmlrpc_server;
    if(!$xmlrpc_server)die("Error: $errstr in '$errfile', line '$errline'");

    header("Content-type: text/xml; charset=UTF-8");
    print(xmlrpc_encode(array(
        'faultCode'=>$errno
        ,'faultString'=>"Remote XMLRPC Error from
          ".$_SERVER['HTTP_HOST'].": $errstr in at $errfile:$errline"
    )));
    die();
}
set_error_handler('return_xmlrpc_error');
?>

In my server function, I just trigger_error("message",E_USER_ERROR)]
 if something can't be completed.

Then on the client side,
<?php
        $data =& xmlrpc_decode($response['body']);

        if(xmlrpc_is_fault($data)){
            trigger_error($data['faultString'],E_USER_ERROR);
        }
?>
martin dot rode at programmfabrik dot de 04-Aug-2005 05:28
To connect to a python xmlrpc server I use:

function do_call($host, $port, $request) {

    $url = "http://$host:$port/";
    $header[] = "Content-type: text/xml";
    $header[] = "Content-length: ".strlen($request);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
        return $data;
    }
}

$request = xmlrpc_encode_request('add', array(3, 4));
$response = do_call($host, $port, $request);
astrolox at lawyersonline dot co dot uk 22-Mar-2005 04:20
The PHP XML-RPC project at SourceForge makes life a hell of a lot easier. However, the project uses some function names which are identical to thoses provided by the XML-RPC extention.

If you are on a server with XML-RPC extension compiled in but wish to use the PHP based version then you will have to rename some of the functions.

I notice that sourceforce says there is activity on the project in 2005 but the last release was January 12, 2003.

I recommend that you use this not so friendly PHP extention if available. However this sourceforce project is still a good idea if you don't control which extenions are be available on the server.

http://phpxmlrpc.sourceforge.net/
Jerome Delamarche 14-Oct-2004 02:58
The documentation lacks an example that shows how to send a fault in a response. Here is how to do it:

$args = array("faultCode" => $errcode, "faultString" => $errmsg);
$resp = xmlrpc_encode_request(NULL,$args);
//echo $resp;
php at hendrik-krauss dot de 13-Aug-2004 12:38
On "datetime" values:

If you implement an XML-RPC server with these functions and a client calls a method on your server, sending a datetime as parameter (in ISO 8601 format, as specified at http://www.xmlrpc.com/spec), the PHP XML-RPC will pass your registered server method an object as parameter. That object, for example, looks like:
obj->type="datetime"
obj->scalar="20040420T13:32:40"
obj->timestamp=1082460760

If you do xmlrpc_get_type(obj), it will return "datetime", so presumably that function just returns the value of 'type'. 'scalar' seems to be the on-the-wire representation of the datetime (ISO 8601, exactly as received). 'timestamp' appears to be the ISO value in 'scalar' converted into a normal PHP timestamp (i.e. Unix time_t).

Note on 'scalar': Using a MySQL DB, we did something like  "select blah where start_time >= $obj->scalar ;". That actually worked and returned expected results, so MySQL appears to handle that ISO 8601 format correctly.
swunderlin at REMOVE-telemedia dot ch 09-Jun-2004 03:20
pear hs an XML_RPC package, if you can't recompile your php:
http://pear.php.net/package/XML_RPC
steph at zend dot com 08-Jun-2004 04:04
It took me a while to get a client together without external libraries.  This very basic client/server pair works on my home set-up - hopefully it will save the next xml-rpc virgin some grief.

/* clienttest.php */
<?php
function do_call($host, $port, $request) {

    $fp = fsockopen($host, $port, $errno, $errstr);
    $query = "POST /home/servertest.php HTTP/1.0\nUser_Agent: My Egg Client\nHost: ".$host."\nContent-Type: text/xml\nContent-Length: ".strlen($request)."\n\n".$request."\n";

    if (!fputs($fp, $query, strlen($query))) {
        $errstr = "Write error";
        return 0;
    }

    $contents = '';
    while (!feof($fp)) {
        $contents .= fgets($fp);
    }

    fclose($fp);
    return $contents;
}

$host = 'localhost';
$port = 80;
$request = xmlrpc_encode_request('cycle', 'egg');
$response = do_call($host, $port, $request);
/* do something with $response, e.g. print it */
?>

/* servertest.php */
<?php
function lifecycle($method, $params) {
/* $method = 'cycle', $params = (array of) request parameter(s); $data is also passed from xmlrpc_server_call_method, if we had any data to pass */
    switch($params[0]) {
        case 'egg':
            $reply = 'All eggs will be birds one day.';
        break;
        default:
            $reply = 'That must have been an otheregg';
    }
    return $reply;
}

$server = xmlrpc_server_create();

/* register the 'external' name and then the 'internal' name */
xmlrpc_server_register_method($server, "cycle", "lifecycle");

$request = $HTTP_RAW_POST_DATA; // no you don't need 'always on', and no $_POST doesn't work.

/* the parameters here are 'server, xml-string and user data'.  There's supposed to be an optional 'output options' array too, but I can't get it working :( hence header() call */
$response = xmlrpc_server_call_method($server, $request, null);
header('Content-Type: text/xml');
print $response;

xmlrpc_server_destroy($server);
?>
mboeren at php dot net 25-Feb-2004 04:34
Just a quick addition to my previous xmlrpc_client class: since you cannot use remote methods containing capital letters or methods from subhandlers (like 'system.listMethods()'), I added a 'call(...)' method to the class.

<?php
    // this method should be copy/pasted in the
    // xmlrpc_client class

    function call($function)
    {
        $return = NULL;
        $argv = func_get_args();
        array_shift($argv); // remove function argument
        $this->__call($function, $argv, &$return);
        return $return;
    }

    // now, you can also do
    $result = $client->call('system.listMethods');
    $sum = client->call('add', '1', '2');
?>
mboeren at php dot net 24-Feb-2004 07:01
I use the following code (requires the overload extension) to make developing clients easier:

<?php
include("utils/utils.php"); // from xmlrpc-epi utils

/*
Usage:
    $client = new xmlrpc_client("http://localhost:7080");
    print $client->echo('x')."\n";
    print $client->add(1, 3)."\n";

*/
class xmlrpc_client
{
    var $url;
    var $urlparts;

    function xmlrpc_client($url)
    {
        $this->url = $url;
        $this->urlparts = parse_url($this->url);
        foreach(array('scheme', 'host', 'user', 'pass', 'path',
                      'query', 'fragment')
                as $part) {
            if (!isset($this->urlparts[$part])) {
                $this->urlparts[$part] = NULL;
                }
            }
    }

    function __call($function, $arguments, &$return)
    {
        $requestprms['host'] = $this->urlparts['host'];
        $requestprms['port'] = $this->urlparts['port'];
        $requestprms['uri'] = $this->urlparts['path'];
        $requestprms['method'] = $function;
        $requestprms['args'] = $arguments;
        $requestprms['debug'] = 0;
        $requestprms['timeout'] = 0;
        $requestprms['user'] = NULL;
        $requestprms['pass'] = NULL;
        $requestprms['secure'] = 0;

        $result = xu_rpc_http_concise($requestprms);
        if (is_array($result) && isset($result['faultCode'])) {
            print('Error in xmlrpc call \''.$function.'\''."\n");
            print('  code   : '.$result['faultCode']."\n");
            print('  message: '.$result['faultString']."\n");
            return false;
            }
        $return = $result;
        return true;
    }

}
overload('xmlrpc_client');

?>
bmichael at goldparrot dot com 08-Feb-2003 09:52
If anyone is interested in making XMLRPC requests directly from the client, I have been able to get xmlrpc to
work with vcXMLRPC javascript backend.

After about 1 week of scanning the market, I found this solution to be the best on Javascript back end.  It uses the Microsoft.HTTP activeX control for IE, or HTTPRequest Object for Mozilla.

You include vc(Virtual Cowboys) vcXMLRPC.js file into your pages and make the rpc calls from with javascript to create the requests.

It works both ways.

Two Notes:

I have tested it on IE 6.02 and you need to change lines in ProcessRequest :
function to read:

  dom = this.getObject("XMLDOM",http.responseText);

and change the getObject function to use the latest ActiveX Control:

 MSXML2.XMLHTTP.3.0  (or 4.0)
 MSXML2.DOMDocument.3.0  (or 4.0)

The controls are found on MSDN in the Web Services -> XML area.

As another note, you DO NOT NEED the rpcproxy.cgi script to use this.  That is a proxy script to get around JS Security.  You can use PHP to build the proxy.  But, I was able to get the CGI working with GCC compiler on Solaris (change the -KPCI, depend and -x03 optimizer settings in the Makefile )
steve at orangeNOSPAMimagineering dot com 24-Aug-2002 01:32
There's a handy library by Keith Devens (version 2.2.1) at
http://www.keithdevens.com/software/xmlrpc/

Here is a sample client. It remotely calls sample.sumAndDifference
with two parameters (3 and 5).
It returns:

sum => 8
difference => -2

<?php
include ("kd_xmlrpc.php");
// define("XMLRPC_DEBUG", 0);    // Set to 1 for handy debugging

$method = "sample.sumAndDifference";
$params = XMLRPC_prepare(array(3,5));

$site = "xmlrpc-c.sourceforge.net";
$location = "/api/sample.php";

list($success, $result) = XMLRPC_request( $site, $location, $method, $params );

// XMLRPC_debug_print();    // uncomment for debugging

foreach ( $result as $key => $value ) {
          echo(" $key => $value \n");
}

?>
hfuecks at pinkgoblin dot com 15-Aug-2002 08:32
This extension does not handle the process of making making XML-RPC client requests via HTTP; it only prepares the XML-RPC request payload.

This differs from many other XML-RPC implementations but offers greater flexibility, allowing SSL connections, authentication headers and XML-RPC via other transports like SMTP.
ivanr at webkreator dot com 21-Jun-2002 11:50
For a really easy way to use this XML-RPC extension take a look at

XML-RPC Class Server (http://www.webkreator.com/php/xcs/)

It automatically creates servers out of PHP classes. Creating clients is almost as easy, especially with the recent addition of the overload extension to PHP (see http://www.php.net/manual/en/ref.overload.php).
nic at uklinux dot NOSPAM dot net 24-Apr-2002 09:05
An alternative XML-RPC implementation is available at http://xmlrpc.usefulinc.com - it's written in PHP so you can use it on servers for which you don't have the luxury of rebuilding PHP on.

nic
Предопределенные константы
xmlrpc_decode_request
XML-RPC


Декодирует XML в нативные типы PHP

XML-RPC Функции
xmlrpc_decode
XML-RPC Функции
PHP Manual

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode_request — Декодирует XML в нативные типы PHP

Описание

mixed xmlrpc_decode_request ( string $xml , string &$method [, string $encoding ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

e dot sand at elisand dot com 22-Jun-2009 08:20
This function works exactly the same as xmlrpc_decode() except it gives you access to the method being called as well (xmlrpc_decode() only outputs the params from the XML-RPC call).

To use this function, simply create an empty variable to store the method string in, and then pass by reference like so:

<?php
$method = null;
$params = xmlrpc_decode_request('<xml rpc request>', &$method);
?>

What you will get back are the params stored in $params, and $method will have the method being requested.
XML-RPC Функции
xmlrpc_decode
XML-RPC Функции


Декодирует XML в нативные типы PHP

xmlrpc_decode_request
xmlrpc_encode_request
XML-RPC Функции
PHP Manual

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode — Декодирует XML в нативные типы PHP

Описание

mixed xmlrpc_decode ( string $xml [, string $encoding = "iso-8859-1" ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

xml

XML ответ, возвращаемый методом XMLRPC.

encoding

Входящая кодировка, поддерживаемая iconv.

Возвращаемые значения

Возвращает массив, или число, или строку, или логическое значение в соответствии с ответом, возвращаемым методом XMLRPC.

Примеры

Смотрите пример xmlrpc_encode_request().

Смотрите также

  • xmlrpc_encode_request() - Генерирует XML для метода запроса
  • xmlrpc_is_fault() - Определяет, является ли массив значений представлением ошибки XMLRPC

User Contributed Notes

phil dot berry at elise-international dot net 05-Sep-2011 08:09
Make sure the server isn't returning a string with a space for the first character, this fails in version 5.3.3 and the function returns null (though seems to be ok in 5.2).

Easily sorted by  trimming the response data:

<?php xmlrpc_decode( trim($response) ); ?>
ryon dot sherman at gmail dot com 21-Aug-2009 04:18
64 bit (i8) integers are not parsed by xmlrpc_decode().
Use a string replacement to work around this:

<?php

$xml = str_replace('i8>', 'i4>', $xml);

$decoded_xml = xmlrpc_decode($xml);

?>
david dot bachelart at polytechnique dot org 18-Jul-2004 08:18
Be careful with encodings, the xmlrpc-decode function is rather strict. For example, the following response parse returns NULL :

<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>a & b</string></value>
         </param>
      </params>
   </methodResponse>

You should use entities :
<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>a &amp; b</string></value>
         </param>
      </params>
   </methodResponse>

If your server does not encode responses properly, you may have to process responses before parse.
hfuecks at pinkgoblin dot com 16-Aug-2002 03:57
Use this with an XML-RPC client to decode a server response into native PHP variables. It will automatically translate the response XML-RPC data types into their PHP equivalents.

This function will return only false is there is any problem with format of the XML it receives.

The HTTP response header will need to be stripped off with something like;

<?php
$xml=(substr($response, strpos($response, "\r\n\r\n")+4));

$phpvars = xmlrpc_decode ($xml);
?>
xmlrpc_decode_request
xmlrpc_encode_request
XML-RPC Функции


Генерирует XML для метода запроса

xmlrpc_decode
xmlrpc_encode
XML-RPC Функции
PHP Manual

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode_request — Генерирует XML для метода запроса

Описание

string xmlrpc_encode_request ( string $method , mixed $params [, array $output_options ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

method

Имя метода для вызова.

params

Параметры метода, совместимые с сигнатурой вызова.

output_options

Массив, уточняющий параметры вывода, может содержать (значения по умолчанию выделены):

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (может быть строка с одним значением или массив с несколькими значениями)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, другой набор символов, поддерживаемый iconv

Возвращаемые значения

Возвращает строку, содержащую XML-представление запроса.

Примеры

Пример #1 Пример клиентской функции XMLRPC

<?php
$request = xmlrpc_encode_request("method", array(1, 2, 3));
$context = stream_context_create(array('http' => array(
    'method' => "POST",
    'header' => "Content-Type: text/xml",
    'content' => $request
)));
$file = file_get_contents("http://www.example.com/xmlrpc", false, $context);
$response = xmlrpc_decode($file);
if ($response && xmlrpc_is_fault($response)) {
    trigger_error("xmlrpc: $response[faultString] ($response[faultCode])");
} else {
    print_r($response);
}
?>

Смотрите также

  • stream_context_create() - Создаёт контекст потока
  • file_get_contents() - Читает содержимое файла в строку
  • xmlrpc_decode() - Декодирует XML в нативные типы PHP

User Contributed Notes

ph at km-it dot de 01-Aug-2011 05:13
<?php
/**
 * A small Xml-Rpc Client class as simple as it can be.
 * It uses PHP's magic overloads for a simple worklow.
 *
 * Example:
 *
 * $rpc  = new XmlRpcClient( "http://www.example.com/xmlrpc/" );
 * $data = $rpc->namespace->namespace->method(); // Will produce a method called namespace.namespace.method
 *
 * var_dump( $data );
 */
class XmlRpcClient
{
    protected $_url;
    protected $_namespace;
    protected $_clients;

    public function __construct( $url, $namespace = '' )
    {
        $this->_url       = (string)$url;
        $this->_namespace = (string)$namespace;
        $this->_clients   = array();
    }

    public function __get( $namespace )
    {
        if( !key_exists( $namespace, $this->_clients ) )
            $this->_clients[ $namespace ] = new XmlRpcClient( $this->_url, strlen( $this->_namespace ) > 0 ? "$this->_namespace.$namespace" : $namespace );

        return $this->_clients[ $namespace ];
    }

    public function __call( $method, array $parameters = array() )
    {
        $request = xmlrpc_encode_request( strlen( $this->_namespace ) > 0 ? "$this->_namespace.$method" : $method, $parameters );
        $context = stream_context_create(
            array(
                'http' => array(
                    'method'  => "POST",
                    'header'  => "Content-Type: text/xml",
                    'content' => $request
                )
            )
        );

        $file       = file_get_contents( $this->_url, false, $context );
        $response = xmlrpc_decode( $file );

        if( !$response )
            throw new XmlRpcClientException( array( 'faultString' => 'Invalid response from ' . $this->_url ) );

        if( xmlrpc_is_fault( $response ) )
            throw new XmlRpcClientException( $response );

        return $response;
    }
}

/**
 * Will be thrown by XmlRpcClient on faults.
 */
class XmlRpcClientException extends Exception
{
    public function __construct( $response )
    {
        parent::__construct( $response[ 'faultString' ], $response[ 'faultCode' ] );
    }
}

$rpc  = new XmlRpcClient( "http://example.com/astroportal/public/xmlrpc/" );
$data = $rpc->tarocards->getCardData();

var_dump( $data );
?>
Anonymous 27-Aug-2009 12:33
ever tried transmitting an array like the following with xmlrpc?
$var1=array(7=>14,9=>18);

The output array looks quite different! It will look like that:
$var2=array(14,18);

The only solution i found is to prepend a space to the index:
$var3=array(' 7'=>14,' 9'=>18);

Using that method you'll get the right result. ($var1)
cometfish at hotmail dot com 01-Sep-2008 12:47
The example above is incorrect - the header needs to be an array, see post by "chris dot vigelius at gmx dot net": http://au.php.net/manual/en/function.stream-context-create.php#74431
His post also shows how to do browser authentication, as below:
<?php
   $request = xmlrpc_encode_request("methodName", array("methodParam"));
   $auth = base64_encode($username.":".$password);
   $header = (version_compare(phpversion(), '5.2.8'))
     ? array("Content-Type: text/xml","Authorization: Basic $auth")
     : "Content-Type: text/xml\r\nAuthorization: Basic $auth" ; //[1]
   $context = stream_context_create(array('http' => array(
      'method' => "POST",
      'header' => $header,
      'content' => $request
   )));
   $webservice="http://www.example.com/rpc";
   $file = file_get_contents($webservice, false, $context);
   $response = xmlrpc_decode($file);
   if (xmlrpc_is_fault($response)) {
      return "xmlrpc: $response[faultString] ($response[faultCode])";
   } else {
      return $response;
   }
?>

1 - EDITOR NOTE: THIS IS A FIX FROM "SandersWang dt php at gmail dot com"
fredrik at it dot cdon dot com 06-Feb-2008 05:05
It should be noted that encoding does not seem to encode anything, just specify what goes into the XML header.

We had problems with double-encoded UTF strings being saved to database when using this function, sending it of to a apache xml-rpc servlet and storing it in mysql database. It was solved by setting 'escaping' to just 'markup' and 'encoding' to 'UTF-8' (don't forget to set 'utf-8' in xmlrpc_decode too).

It seems that UTF-8 encoded strings gets escaped with their bytes as entities instead of their characters as entites.
handco at gmail dot com 12-Mar-2007 08:39
Simple OO client with function Overload :

the php metho test_helloworld is translated to xmlrpc method test.helloworld.

class RpcClient {

    private $_methods;
    private $_context;
    private $_url;

    function __construct ($url, $user, $passwd) {
        $auth = base64_encode(sprintf('%s:%s', $user,$passwd));
        $this->_context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => "Content-Type: text/xml\r\n".
                            "Authorization: Basic $auth" ,

            )
        ));
        $this->_url = $url;

        $this->registerMethod ("Test_HelloWorld");

    }

    function __call($methodName, $params) {
        if (array_key_exists($methodName,$this->_methods)) {
            // on appelle la fonction RPC
            $m = str_replace('_', '.', $methodName);
            $r = xmlrpc_encode_request($m, $params,array('verbosity'=>'newlines_only'));
            $c = $this->_context;
            stream_context_set_option($c,'http','content',$r);
            $f = file_get_contents($this->_url,false,$c);
            $resp = xmlrpc_decode($f);
            return $resp;
        } else {
            // on appelle la fonction de l'objet
            call_user_method_array($methodName, $this,$params);
        }
    }

    private function registerMethod ($method) {
        $this->_methods[$method] = true;
    }

}
giunta dot gaetano at sea-aeroportimilano dot it 21-Aug-2006 03:54
Take care that this function will generate invalid xmlrpc content when invoked with certain parameters (said content will be happily parsed by the lib itself, but not by other implementations).

xmlrpc_encode_request(null, null)
will generate a response without a value

xmlrpc_encode_request('myfunc', array('faultCode' => 666, 'faultString' => 'hello world')
will generated a request containing a <fault> member instead of <params>
php at hendrik dash krauss dot de 28-May-2005 02:29
For examples / documentation of the array output_options, see http://xmlrpc-epi.sourceforge.net/main.php?t=php_api#output_options

In short, output_options lets you send compact xmlrpc (without all the "pretty whitespace" xmlrpc_encode adds normally), apply an own escaping table prior to sending, set the encoding, and a couple of other things (the page even says something about soap 1.1 ... I don't know details).
<URL:http://www.dlitz.net/go/contact/> 03-May-2004 11:28
Note that as far as I can tell, the &#10; characters generated by PHP in the base64 fields don't appear to violate the XML-RPC standard at all.  XML-RPC messages *are* in XML format, and as such, the XML entities should be getting decoded before being passed to a base64 decoder.  So, the previously-mentioned Jakarta-based XML-RPC server appears to violate the XML spec.  i.e. There's nothing here that needs to be "fixed" in PHP.
kelly at seankelly dot biz 28-Dec-2002 04:02
Binary strings (set with xmlrpc_set_type) go into a <base64>...</base64> block like you'd expect. But after every 80th character, this function inserts the XML entity "&#10;", which is a Unicode newline, as if to cause a line-wrap, which is admittedly silly.

Silly though it may be, it causes real problems for some XML-RPC servers, such as http://jakarta.apache.org/xmlrpc/ (nee Helma). Stripping out those entities with something like

$req = preg_replace('/&#10;/', '', xmlrpc_encode_request("my.method", $args));

works around the problem.
hfuecks at pinkgoblin dot com 15-Aug-2002 09:06
This function should be used by an XML-RPC client to create an XML payload for an XML-RPC request;

<?php
$params = "system.methodSignature";
$method = "system.methodHelp";
$request = xmlrpc_encode_request($method,$params);
echo ( $request );
?>

Produces;

<?xml version='1.0' encoding="iso-8859-1" ?>
<methodCall>
<methodName>system.methodHelp</methodName>
<params>
 <param>
  <value>
   <string>system.methodSignature</string>
  </value>
 </param>
</params>
</methodCall>

The second argument recognises the type of variable and generates the correct XML-RPC structure. See xmlrpc_encode() for more details.
xmlrpc_decode
xmlrpc_encode
XML-RPC Функции


Генерирует XML для PHP значения

xmlrpc_encode_request
xmlrpc_get_type
XML-RPC Функции
PHP Manual

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode — Генерирует XML для PHP значения

Описание

string xmlrpc_encode ( mixed $value )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

remi 13-May-2009 01:56
This xmlrpc_encode function doesn't generate the "methodResponse" tag required by some clients.

Using xmlrpc_encode_request seems better:

<?php
$xmlresponse = xmlrpc_encode_request(NULL, $phpresponse);

xmlrpc_encode(1) generate
<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <int>1</int>
 </value>
</param>
</params>

xmlrpc_encode_request(NULL,1) generate
<?xml version="1.0" encoding="iso-8859-1"?>
<methodResponse>
<params>
 <param>
  <value>
   <int>1</int>
  </value>
 </param>
</params>
</methodResponse>
?>
dave dot wilcock at gmail dot com 21-Sep-2007 07:05
Worth noting, you can use this function to generate fault response xml.

If you pass a pre-determined array into this function, as follows

<?
$myArray = array ("faultCode"=>1,"faultString"=>"Too many params");
$xml = xmlrpc_encode($myArray);
?>

... you will get output much like the following:

<?xml version="1.0" encoding="utf-8"?>
<fault>
<value>
 <struct>
  <member>
   <name>faultCode</name>
   <value>
    <int>4</int>
   </value>
  </member>
  <member>
   <name>faultString</name>
   <value>
    <string>Too many params</string>
   </value>
  </member>
 </struct>
</value>
</fault>

All that is needed to do here to make it valid XML-RPC is inject some of your own methodResponse tags.

Check the XML-RPC specification at http://www.xmlrpc.com/spec
08-Jun-2006 07:32
Another quirk (more of a bug i think) is the automatic encoding of hashes where all keys that begin with a digit between 1 and 9 are lost:
http://bugs.php.net/bug.php?id=37746

Luckily I found a quick workaround. Just append chr(0x00) to your keys and the xmlrpc response will be correct. Maybe this will apply to encoding of hashes for requests too.
Amir.LaherATcomplinetDOTcom 26-Aug-2005 01:54
Beware this quirk: when you xmlrpc_encode a hash into xmlrpc, numeric keys will not be kept. Even strings containing numbers-only will be lost.

i.e.: xmlrpc_decode(xmlrpc_encode(array('123'=>456)));
returns: array(0=>456);

Apparently this is intentional functionality (see http://bugs.php.net/bug.php?id=21949)

2 workarounds:
1. prepend/append a string (even whitespace) to all keys, and strip them out at the other end. eg array('key_123'=>456);
2. create an array of hashes. array(array('key'=>123,'value'=>456));

I favour the second option because it's more deliberate.

... this also applies to xmlrpc_encode_request()
hfuecks at pinkgoblin dot com 15-Aug-2002 08:16
This function would be used by an XML-RPC server to convert PHP variables into an XML-RPC response.

It would be used within the PHP functions defined using xmlrpc_server_register_method()

Uses PHP variable reflection to assign the correct data types for the XML-RPC response. For example;

<?php
$params = array ( "one"=>"red","two"=>"blue","three"=>"green" );

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

Produces;

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <struct>
   <member>
    <name>one</name>
    <value>
     <string>red</string>
    </value>
   </member>
   <member>
    <name>two</name>
    <value>
     <string>blue</string>
    </value>
   </member>
   <member>
    <name>three</name>
    <value>
     <string>green</string>
    </value>
   </member>
  </struct>
 </value>
</param>
</params>

While
<?php
$params = array ( "red", "blue", "green" );

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

produces;

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <array>
   <data>
    <value>
     <string>red</string>
    </value>
    <value>
     <string>blue</string>
    </value>
    <value>
     <string>green</string>
    </value>
   </data>
  </array>
 </value>
</param>
</params>

And

<?php
$params = 1;

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

produces

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <int>1</int>
 </value>
</param>
</params>

It's useful to be aware of the settype() function (http://www.php.net/settype).

For binary base64 data and XML-RPC iso8601 date times the xmlrpc_set_type() function should be used on a PHP variable before using xmlrpc_encode()
xmlrpc_encode_request
xmlrpc_get_type
XML-RPC Функции


Получает XML-RPC тип для значения PHP

xmlrpc_encode
xmlrpc_is_fault
XML-RPC Функции
PHP Manual

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_get_type — Получает XML-RPC тип для значения PHP

Описание

string xmlrpc_get_type ( mixed $value )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Эта функция особенно полезна для base64 и строки, содержащей дату.

Список параметров

value

Значение PHP

Возвращаемые значения

Возвращает тип XML-RPC.

Примеры

Пример #1 Пример XML-RPC типа

<?php
echo xmlrpc_get_type(null) . "\n"; // base64
echo xmlrpc_get_type(false) . "\n"; // boolean
echo xmlrpc_get_type(1) . "\n"; // int
echo xmlrpc_get_type(1.0) . "\n"; // double
echo xmlrpc_get_type("") . "\n"; // string
echo xmlrpc_get_type(array()) . "\n"; // array
echo xmlrpc_get_type(new stdClass) . "\n"; // array
echo xmlrpc_get_type(STDIN) . "\n"; // int
?>

Смотрите также

  • xmlrpc_set_type() - Устанавливает тип XML-RPC, base64 или datetime для значения строки PHP

User Contributed Notes

hfuecks at pinkgoblin dot com 16-Aug-2002 10:41
This function returns the type of a PHP variable in XML-RPC terms. It won't "spot" base64 or iso8601 types unless they have been defined using xmlrpc_set_type().

For iso8601 type it returns "datetime".

Otherwise it returns strings corresponding directly the XML-RPC data types e.g. "struct","int","string","base64" etc.
xmlrpc_encode
xmlrpc_is_fault
XML-RPC Функции


Определяет, является ли массив значений представлением ошибки XMLRPC

xmlrpc_get_type
xmlrpc_parse_method_descriptions
XML-RPC Функции
PHP Manual

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5)

xmlrpc_is_fault — Определяет, является ли массив значений представлением ошибки XMLRPC

Описание

bool xmlrpc_is_fault ( array $arg )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

arg

Массив, возвращаемый xmlrpc_decode().

Возвращаемые значения

Возвращает TRUE, если аргумент означает ошибку, в противном случае - FALSE. Описание ошибки доступно в $arg["faultString"],а код ошибки в $arg["faultCode"].

Примеры

Смотри пример xmlrpc_encode_request().

Смотрите также

  • xmlrpc_decode() - Декодирует XML в нативные типы PHP

User Contributed Notes

angelo at at dot com 25-Jan-2011 12:31
A note, response from xmlrpc_decode is not always an array. Whenever the XMLRPC server returns a string, xmlrpc_is_fault will complain about not being an array.

Best way to detect errors is

<?php

    $response = xmlrpc_decode($file);

    if (is_array($response) && xmlrpc_is_fault($response)) {
        throw new Exception($response['faultString'], $response['faultCode']);
    }

?>
xmlrpc_get_type
xmlrpc_parse_method_descriptions
XML-RPC Функции


Декодирует XML в список описаний методов

xmlrpc_is_fault
xmlrpc_server_add_introspection_data
XML-RPC Функции
PHP Manual

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_parse_method_descriptions — Декодирует XML в список описаний методов

Описание

array xmlrpc_parse_method_descriptions ( string $xml )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
xmlrpc_is_fault
xmlrpc_server_add_introspection_data
XML-RPC Функции


Добавляет документацию самоанализа

xmlrpc_parse_method_descriptions
xmlrpc_server_call_method
XML-RPC Функции
PHP Manual

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_add_introspection_data — Добавляет документацию самоанализа

Описание

int xmlrpc_server_add_introspection_data ( resource $server , array $desc )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
xmlrpc_parse_method_descriptions
xmlrpc_server_call_method
XML-RPC Функции


Разбирает XML запросы и вызывающие методы

xmlrpc_server_add_introspection_data
xmlrpc_server_create
XML-RPC Функции
PHP Manual

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_call_method — Разбирает XML запросы и вызывающие методы

Описание

string xmlrpc_server_call_method ( resource $server , string $xml , mixed $user_data [, array $output_options ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

marco.buratto at tiscali punto it 28-Dec-2006 08:15
xmlrpc_server_call_method() with class methods

<?php
require_once ('Connections/adodb_mysql_connection.php');

// Instantiating my own class
$my_report = new external_report($db_connection);

// Setting up the XML-RPC "server"
$xmlrpc_server_handler = xmlrpc_server_create();
xmlrpc_server_register_method($xmlrpc_server_handler, "external_method", array(&$my_report, "export"));

// Creating XML return data
if ($response = xmlrpc_server_call_method($xmlrpc_server_handler, $HTTP_RAW_POST_DATA, null))
    {
    header('Content-Type: text/xml');
    echo $response;
    }

// **************** class definition ****************

class external_report
    {
    protected $db_connection;

    public function __construct($db_connection_pointer)
        {
        if (method_exists($db_connection_pointer, "Execute")) $this->db_connection = $db_connection_pointer;
        else die("...");
        }

    public function export($method_name, $params_array)
        {
        $id_dir = (int)$params_array[0];
        $id_usr = (int)$params_array[1]; // not used, just an example
        // We have to add arguments' validating code here and NOT inside the constructor (as usual)
        // because arguments are passed directly by xmlrpc_server_call_method (?!!)

        $myexport = array();

        $dirs_query = "SELECT documento_id FROM tabella_cartelle WHERE cartella_id = ".$id_dir;
        $dirs_result = $this->db_connection->Execute($dirs_query) or die("...");

        $index = 0;
        while(!$dirs_result->EOF)
            {
            $docs_query = "SELECT codice, titolo FROM tabella_documenti WHERE id_documento = ".$dirs_result->Fields('documento_id');
            $docs_result = $this->db_connection->Execute($docs_query) or die("...");

            $myexport[$index]['codice'] = $docs_result->Fields('codice');
            $myexport[$index]['titolo'] = $docs_result->Fields('titolo');

            $index++;
            $dirs_result->MoveNext();
            }

        return $myexport;
        }
    }
?>
nyvsld at gmail dot com 27-Nov-2005 05:08
<?php
/* method implementation */
function impl($method_name,$params,$user_data){
  var_dump(func_get_args('impl'));
  return array_sum($params);
}

/* create server */
$s=xmlrpc_server_create();
xmlrpc_server_register_method($s,'add','impl');

/* calling server method */
$req=xmlrpc_encode_request('add',array(1,2,3));
$resp=xmlrpc_server_call_method($s,$req,array(3,4));

/* process result */
$decoded=xmlrpc_decode($resp);
if(xmlrpc_is_fault($decoded)){
    echo 'fault!';
}

var_dump($decoded);
?>
xmlrpc_server_add_introspection_data
xmlrpc_server_create
XML-RPC Функции


Создаёт XML-RPC сервер

xmlrpc_server_call_method
xmlrpc_server_destroy
XML-RPC Функции
PHP Manual

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_create — Создаёт XML-RPC сервер

Описание

resource xmlrpc_server_create ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
xmlrpc_server_call_method
xmlrpc_server_destroy
XML-RPC Функции


Уничтожает серверные ресурсы

xmlrpc_server_create
xmlrpc_server_register_introspection_callback
XML-RPC Функции
PHP Manual

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_destroy — Уничтожает серверные ресурсы

Описание

int xmlrpc_server_destroy ( resource $server )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

nospam at bigbadweb dot co dot uk 22-Nov-2005 02:26
This function returns true (1) if successful and false (0) if resource is invalid or could not be destroyed.
xmlrpc_server_create
xmlrpc_server_register_introspection_callback
XML-RPC Функции


Регистрирует функцию PHP для генерации документации

xmlrpc_server_destroy
xmlrpc_server_register_method
XML-RPC Функции
PHP Manual

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_introspection_callback — Регистрирует функцию PHP для генерации документации

Описание

bool xmlrpc_server_register_introspection_callback ( resource $server , string $function )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
xmlrpc_server_destroy
xmlrpc_server_register_method
XML-RPC Функции


Регистрирует функцию PHP к методу ресурса, соответствующему method_name

xmlrpc_server_register_introspection_callback
xmlrpc_set_type
XML-RPC Функции
PHP Manual

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_method — Регистрирует функцию PHP к методу ресурса, соответствующему method_name

Описание

bool xmlrpc_server_register_method ( resource $server , string $method_name , string $function )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

giunta dot gaetano at sea-aeroportimilano dot it 11-Aug-2006 06:55
To have an xmlrpc fault response programatically generated by the server, the php function registered as method handler must return an array containing a FaultCode and a FaultString members.

function $myfunc($methodname, $vals, $extra_data)
{
...
return array('faultCode' => 666, 'faultString' => 'DOH!');
}
nyvsld at gmail dot com 27-Nov-2005 05:03
prototype of registered function:

function method_impl(string $method_name, array $params, array $user_data);

$method_name
    the public method name, known by calling client
$params
    parameters specified by calling client
$user_data
    any local data, passed by `xmlrpc_server_call_method'
dante at lorenso dot com 11-Aug-2005 12:46
To register a callback to a 'static' function within the same class, consider a syntax like the following:
<code>
$callback = array (__CLASS__, "my_function_name");
xmlrpc_server_register_method($xmlrpc_server, "my_function", $callback);
</code>
Doing it this way makes it easier to rename your class later.
eiriks at hollowmatrix dot com 28-Mar-2005 03:08
Remember that you can't do like Chrigu and Nate said if you want to add methods from a static class (Hence you can't create any instances of it).
A workaround is to create lambda functions calling the
methods:

// Our static handler class
static class MyHandler
{
    public function getPrice($item)
    {
        $prices = array("apple" => 4, "orange" => 5);
        return $prices[$item];
    }
    public function buy($item, $number)
    {
        $price = self::getPrice($item) * $number;
        do_thing_to_sell_the_item();
        return $price;
    }
}

// Use reflection to get method names and parameters
$mirror = new ReflectionClass("MyHandler");
foreach ($mirror->getMethods() as $method)
{
    // Create new "lambda" function for each method

    // Generate argument list
    $args = array();
    foreach ($method->getParameters() as $param)
    {
        $args[] = '$'.$param->getName();
    }
    $args = implode(',', $args);

    // Generate code
    $methodname = $method->getName();
    $code = "return {$real_class}::{$methodname}({$args});";

    // Create function, retrieve function name
    $function_name = create_function($args, $code);

    // Register the function
    xmlrpc_server_register_method($myserver, $methodname, $function_name);
}
Nate Parsons 29-Apr-2003 03:12
In case its not completely obvious what Chrigu meant,

You can register a method inside your class by doing the following:

xml_rpc_server_register_methode($xmlrpc_server, "myClientCall", array(&$this, "handleClientCallFunc"));

where $this == the magic class $this. =)
18-Nov-2002 10:40
Here is an example how to register a class methode:

xml_rpc_server_register_methode($xmlrpc_server, "foo", array(&$bar, "foo_func"));

where $bar is the instance of your class and foo_func a methode of this class. Don't forget the '&'!

hope this may be useful...

Chrigu
xmlrpc_server_register_introspection_callback
xmlrpc_set_type
XML-RPC Функции


Устанавливает тип XML-RPC, base64 или datetime для значения строки PHP

xmlrpc_server_register_method
Расширения только для Windows
XML-RPC Функции
PHP Manual

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_set_type — Устанавливает тип XML-RPC, base64 или datetime для значения строки PHP

Описание

bool xmlrpc_set_type ( string &$value , string $type )

Устанавливает XML-RPC тип, base64 или datetime для значения строки PHP.

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Список параметров

value

Значение для установки типа.

type

'base64' или 'datetime'

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. В случае успеха, value конвертируется в объект.

Примеры

Пример #1 Пример использования xmlrpc_set_type()

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

Результатом выполнения данного примера будет что-то подобное:

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

Ошибки

Выдает сообщение E_WARNING для не поддерживаемых типов XMLRPC.

User Contributed Notes

bmatheny at mobocracy dot net 24-Mar-2006 03:08
The following code segfaults some older (pre 5.1.2) versions of PHP:

$foo = date('c', time());
xmlrpc_set_type($foo, 'datetime');

Please upgrade before reporting as a bug.
shem((at))etkDOTca [aka.Przemyslaw Szot] 30-Oct-2004 02:23
Once you use the xmlrpc_set_type function, the data is encoded into a PHP object.  In your XMLRPC server, in order to access the data you must be able to access the necessary part of the object.

So.. to expend on the example above:

<---------- CLIENT ---------->
$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

In order to retrieve the binary file data you would need to get the scalar portion of the object:

<---------- SERVER ------------>
$string=$params[0];
$date_obj=$params[1];
$binary_obj=$params[2];

$date=$date_obj->scalar;
$binary_data=$binary_obj->scalar;

// Then you can proceed to write the binary
fwrite($handle,$binary_data);
kelly at seankelly dot biz 28-Dec-2002 07:53
The problem is that PHP has a string type which is also used to hold binary data and dates.  But XML-RPC defines three separate types for strings, binary data, and dates.  How do you tell how you want strings encoded?  That's where this function comes in.

Suppose the XML-RPC method "log.data" took a string, a date, and a binary object.  To tell XML-RPC that the date (which is a PHP string) is a really a date and that the binary data (which is also a PHP string) is really binary data, try:

$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

Note the reference passing in the calls to xmlrpc_set_type; that enables the function to change the values from strings into what xmlrpc_encode/_request expects (which are objects that include a bonus field that tells the desired XML-RPC type).
xmlrpc_server_register_method
Расширения только для Windows
XML-RPC Функции


Расширения только для Windows

  • .NET
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • .NET Функции
  • COM — COM и .Net (Windows)
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Errors and error handling
    • Примеры
    • COM — The COM class
    • DOTNET — The DOTNET class
    • VARIANT — VARIANT class
    • COM Функции
  • Принтер
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Принтер
  • W32api
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • W32api
  • win32ps
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • win32ps Функции
  • win32service
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • win32service

User Contributed Notes

There are no user contributed notes for this page.
xmlrpc_set_type
.NET
Справочник функций


.NET

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • .NET Функции
    • dotnet_load — Загружает модуль DOTNET

User Contributed Notes

There are no user contributed notes for this page.
Расширения только для Windows
Введение
Расширения только для Windows


Введение

Внимание

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и любую другую относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

User Contributed Notes

There are no user contributed notes for this page.
.NET
Установка и настройка
.NET


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
.NET


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
.NET Функции
.NET


.NET Функции

Содержание

  • dotnet_load — Загружает модуль DOTNET

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
dotnet_load
.NET


Загружает модуль DOTNET

.NET Функции
COM
.NET Функции
PHP Manual

dotnet_load

(PHP 4)

dotnet_load — Загружает модуль DOTNET

Описание

int dotnet_load ( string $assembly_name [, string $datatype_name [, int $codepage ]] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список изменений

Версия | Описание
4.1.0 | Добавлен параметр codepage

User Contributed Notes

Rudi Lippert 25-Oct-2010 02:50
If you got here looking for the standard way to load DOTNET modules, you might be better off looking here:
http://php.net/manual/en/class.dotnet.php
sunside 30-Jun-2007 07:46
The

  if (parameters[0].GetType().ToString() == "System.Int32")

below can be compacted to

  if (parameters[0] is System.Int32)

as well as

  if (parameters[0] is int)

(if you are on a 32bit platform, that is)
thomas dot weidner at voxtronic dot com 23-Jul-2002 03:54
To realise functions within Microsoft.NET which can use with every type of parameter as boolean, integer, string or any other type you want to use do the following.

Write your function in .NET :
CSharp Example :
MyFunction (params object[] parameters)
{
    if (parameters[0].GetType().ToString() == "System.Int32")
        return "Parameter 0 is an Integer";
    return "Parameter 0 is no Integer";
}

Within PHP do the following :

$parameter[0] = 12345;
$parameter[1] = "My String";
$parameter[2] = false;
$obj = new COM ("NameSpace.Class");
$value = $obj -> MyFunction($parameter)
print($value);

How to work with params and object you could read within the .NET Documentation.

If you have any further question dont be afraid and write me...

Bye
Thomas
Thomas dot Weidner at voxtronic dot com 22-Jul-2002 02:12
I`ve found an workaround to use the Microsoft.NET within PHP but without the need of compiling the DOTNET.DLL of PHP.

At first write the functions you want to need within PHP in the Microsoft.NET Languages (I`m working in CSharp).

Then make your FunctionsLibrary StrongNamed. Read about how to do this in the SDK-Help. (Key, Version...)

Then you have to register your DLL in GAC.
For this you have to do REGASM /tlb:your.tlb your.dll
Then you have to do GACUTIL /if your.dll

After this your DLL will be recognised with in the whole .NET.

Now... to use your DLL within PHP you just have to use an ordinary COM Object.

$MyObj = new COM ("NameSpace.Class");
$ReturnValue = $MyObj -> MyFunction($MyParams);
$MyObj = NULL;

$MyParams could be any type. For example an Array.

I tested this with PHP 4.2.1, RDK-Framework, SDK-Frwamework, Visual Studio and SharpDevelop. You have not to recompile PHP because you don�t need the DOTNET.DLL .

The only negative aspect within this way due to COMRestrictions is, that REF or OUT Values are not returned. So you have only one return value.
But for an good written function this should be no great restriction.

If you have any further question dont be afraid and write to me...

Bye
Thomas
mb at netminers dot dk 29-Apr-2002 11:34
Now we are working!
Well that means that if you want to use the .NET modules, from PHP, you'll have to build a new php_dotnet.dll file.
The problem with the existing code is the interface versions of the COM object needed to mix unmanaged code with managed code.

To fix this minor issue, replace
#include "mscorlib.h", in the extensions project of the PHP4.2 source, with the following type library binary file import.
#import "mscorlib.tlb" raw_interfaces_only high_property_prefixes("_get","_put","_putref")

The type library file is converted to a type library header file which is then automatically included by Visual Studio, presuming you are using that. :o)
Have fun! (Mail me if this description was too bad, I can mail the new php_dotnet.dll)

By the way the tlbexp.exe SDK tool can generate the .tlb file.

I'll check with the PHP group to verify they are aware of the issue, so it's nicely fixed in a future release of PHP.

Great stuff,
Michael
.NET Функции
COM
.NET Функции


COM и .Net (Windows)

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Errors and error handling
  • Примеры
    • For Each
    • Arrays and Array-style COM properties
  • COM — The COM class
  • DOTNET — The DOTNET class
  • VARIANT — VARIANT class
  • COM Функции
    • com_addref — Increases the components reference counter [deprecated]
    • com_create_guid — Generate a globally unique identifier (GUID)
    • com_event_sink — Connect events from a COM object to a PHP object
    • com_get_active_object — Returns a handle to an already running instance of a COM object
    • com_get — Gets the value of a COM Component's property [deprecated]
    • com_invoke — Calls a COM component's method [deprecated]
    • com_isenum — Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
    • com_load_typelib — Loads a Typelib
    • com_load — Creates a new reference to a COM component [deprecated]
    • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
    • com_propget — Псевдоним com_get
    • com_propput — Псевдоним com_set
    • com_propset — Псевдоним com_set
    • com_release — Decreases the components reference counter [deprecated]
    • com_set — Assigns a value to a COM component's property
    • variant_abs — Returns the absolute value of a variant
    • variant_add — "Adds" two variant values together and returns the result
    • variant_and — Performs a bitwise AND operation between two variants
    • variant_cast — Convert a variant into a new variant object of another type
    • variant_cat — concatenates two variant values together and returns the result
    • variant_cmp — Compares two variants
    • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
    • variant_div — Returns the result from dividing two variants
    • variant_eqv — Performs a bitwise equivalence on two variants
    • variant_fix — Returns the integer portion of a variant
    • variant_get_type — Returns the type of a variant object
    • variant_idiv — Converts variants to integers and then returns the result from dividing them
    • variant_imp — Performs a bitwise implication on two variants
    • variant_int — Returns the integer portion of a variant
    • variant_mod — Divides two variants and returns only the remainder
    • variant_mul — Multiplies the values of the two variants
    • variant_neg — Performs logical negation on a variant
    • variant_not — Performs bitwise not negation on a variant
    • variant_or — Performs a logical disjunction on two variants
    • variant_pow — Returns the result of performing the power function with two variants
    • variant_round — Rounds a variant to the specified number of decimal places
    • variant_set_type — Convert a variant into another type "in-place"
    • variant_set — Assigns a new value for a variant object
    • variant_sub — Subtracts the value of the right variant from the left variant value
    • variant_xor — Performs a logical exclusion on two variants

User Contributed Notes

Anonymous 23-Sep-2009 05:00
Add hyperlink at a Word Document's bookmark

<?php
// Create COM instance to word
       function clsMSWord($Visible = false)
       {
           $this->handle = new COM("word.application") or die("Unable to instanciate Word");
           $this->handle->Visible = $Visible;
       }

function WriteHyperlink($Bookmark,$Path,$Text)
       {
               $objBookmark = $this->handle->ActiveDocument->Bookmarks($Bookmark);
               $range = $objBookmark->Range;
               $objHyperlink = $this->handle->ActiveDocument->Hyperlinks;
               $objHyperlink->add($range,$Path,"","",$Text);

       }
?>
Dave Bachtel 27-May-2009 02:20
Hello everybody!

Here is some helpful advice for people attempting to use COM with Microsoft MapPoint 2006 or 2009 with PHP.

If you are using apache, it MUST be running under the same credentials as a desktop user that has already installed/run mappoint or modifiy the service and select the "Allow Service to Interact with Desktop" option.  Otherwise, it won't work due to the EULA popup having to be accepted.  Mappoint 2004 works just fine, this only applies to 2006 and 2009.

For troubleshooting, the error that appears in the System event viewer is:
The server {31851F82-AFE6-11D2-A3C9-00C04F72F340} did not register with DCOM within the required timeout.

The error generated by PHP, if you happen to get lucky and let the COM() function timeout by cranking up set_time_limit() timeout is:
<?php

set_time_limit(1000) ;

$mapoint =  new COM("MapPoint.Application") or die("Unable to instantiate Mappoint COM object");

?>
Generates:
Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `MapPoint.Application': Server execution failed ' in [somefile.php]:9 Stack trace: #0 [somefile.php](9): com->com('MapPoint.Applic...') #1 {main} thrown in [somefile.php] on line 9

Also, if you have multiple versions of MapPoint installed, you will need to run:
c:\path\to\mappoint\MapPoint.exe /registerserver

(using the correct folder path) to select the right version of the com object to use.  Gooood luck!
acsandeep at gmail dot com 04-Apr-2009 09:40
If you are trying to get the properties of a Word document opened via COM object, you may need to define some constants in your script like so.

<?php
define('wdPropertyTitle', 1);
define('wdPropertySubject', 2);
define('wdPropertyAuthor', 3);
define('wdPropertyKeywords', 4);
define('wdPropertyComments', 5);
define('wdPropertyTemplate', 6);
define('wdPropertyLastAuthor', 7);

$word = new COM("word.application") or die ("Could not initialise MS Word object.");
$word->Documents->Open(realpath("Sample.doc"));
$Author = $word->ActiveDocument->BuiltInDocumentProperties(wdPropertyAuthor);

echo $Author;
?>
long2hu3 ATT yahoo DOTT com 18-Mar-2009 04:38
When you work with MS Excel, Word, ... and other applications, never forget that COM doesn’t know their predefined constants, thus if you want to do sth. that would look like this in VB:

With myRange.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

you should either use numbers or define constants above, like this:

<?php

define('xlEdgeBottom', 9);
define('xlContinuous', 1);
define('xlThin', 2);
define('xlAutomatic', -4105);

$ex = new COM("Excel.Application", NULL, CP_UTF8) or Die ("Did not instantiate Excel");
$wb = $ex->Application->Workbooks->Add();
$ws = $wb->Worksheets(1);

$xra = $ws->Range("A1:A6");

$bs = $xra->Borders(xlEdgeBottom);
$bs->LineStyle = xlContinuous;
$bs->Weight = xlThin;
$bs->ColorIndex = xlAutomatic;

?>

It is pointless to try to use text strings, i.e.

<?php

$bs = $xra->Borders('xlEdgeBottom');
$bs->Weight = 'xlThin';

?>

this will cause an error: Unable to set property Weight of class Border ...
ilayansmano at gmail dot com 26-Aug-2008 01:39
Extracting text from Word Documents via PHP and COM

<?php
$word = new COM("word.application") or die ("Could not initialise MS Word object.");
$word->Documents->Open(realpath("Sample.doc"));

// Extract content.
$content = (string) $word->ActiveDocument->Content;

echo $content;

$word->ActiveDocument->Close(false);

$word->Quit();
$word = null;
unset($word);
?>
dotnet_load
Введение
Расширения только для Windows


Введение

COM (акроним от Component Object Model) — это объектно-ориентированный слой (и связанные с ним сервисы), базирующийся на DCE RPC (открытый стандарт), который определяет общие соглашения, позволяющие коду, написанному на любом языке вызывать и взаимодействовать с кодом, написанным на любом другом языке (при условии, что эти языки являются COM-ориентированными). Не только код может быть написан на любом языке, но даже нет необходимости, чтобы он был частью одного и того же исполняемого файла: код может быть загружен из библиотеки DLL, может быть найден в другом процессе на одном и том же компьютере или, с помощью DCOM (Distributed COM), может быть найден в другом процессе на удаленной машине, и все это без необходимости вашему коду знать где находится компонент.

Подмножество COM, известное как OLE Automation, включает набор COM-интерфейсов, которые позволяют осуществлять легкое связывание COM-объектов, также любой объект можно проанализировать и вызывать во время работы без знания о деталях его работы на этапе компиляции. PHP-расширение COM использует интерфейсы OLE Automation, позволяющие вам создавать и вызывать совместимые объекты из ваших скриптов. Говоря техническим языком, это следовало бы назвать "Расширение OLE Automation для PHP", так как не все COM-объекты являются OLE-совместимыми.

Теперь, почему вам следует использовать COM ? COM — один из основных способов склеить вместе приложения и компоненты на платформе Windows. Используя COM, вы можете запустить Microsoft Word, заполнить шаблон документа и сохранить результаты как документ Word, и затем отправить посетителю вашего веб-сайта. Вы также можете использовать COM для выполнения задач администрирования для вашей сети и конфигурирования вашего IIS-сервера. Это только обычные применения, с COM вы сможете больше.

Начиная с PHP 5, это расширение и документация к нему были переписаны с нуля и многие неточности из старой версии были удалены. Дополнительно расширение поддерживает создание экземпляра класса и создание .NET-сборок, используя слой взаимодействия с COM, предоставляемый Miсrosoft.

Прочтите, пожалуйста, » эту статью для краткого обзора измений в этом расширении для PHP 5.

User Contributed Notes

There are no user contributed notes for this page.
COM
Установка и настройка
COM


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
COM


Требования

COM functions are only available for the Windows version of PHP.

.Net support requires PHP 5 and the .Net runtime.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Для использования этих функций не требуется проведение установки, поскольку они являются частью ядра PHP.

Версия PHP для Windows имеет встроенную поддержку данного расширения. Это означает, что для использования данных функций не требуется загрузка никаких дополнительных расширений.

You are responsible for installing support for the various COM objects that you intend to use (such as MS Word); we don't and can't bundle all of those with PHP.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

Com configuration options
Имя | По умолчанию | Меняемо | Список изменений
com.allow_dcom | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Available since PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.

Краткое разъяснение конфигурационных директив.

com.allow_dcom

When this is turned on, PHP will be allowed to operate as a D-COM (Distributed COM) client and will allow the PHP script to instantiate COM objects on a remote server.

com.autoregister_typelib

When this is turned on, PHP will attempt to register constants from the typelibrary of objects that it instantiates, if those objects implement the interfaces required to obtain that information. The case sensitivity of the constants it registers is controlled by the configuration directive.

com.autoregister_verbose

When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.

com.autoregister_casesensitive

When this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.

com.code_page

It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.

If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.

Замечание: This configuration directive was introduced with PHP 5.

com.typelib_file

When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.

User Contributed Notes

There are no user contributed notes for this page.
Установка
Типы ресурсов
Установка и настройка


Типы ресурсов

This extension defines a reference to a COM component returned by deprecated com_load() (this function does not exist in PHP 5; use the COM class instead).

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

COM constants
Constant | Value | Description | Notes
CLSCTX_INPROC_SERVER (integer) | 1 | The code that creates and manages objects of this class is a DLL that runs in the same process as the caller of the function specifying the class context. |
CLSCTX_INPROC_HANDLER (integer) | 2 | The code that manages objects of this class is an in-process handler. This is a DLL that runs in the client process and implements client-side structures of this class when instances of the class are accessed remotely. |
CLSCTX_LOCAL_SERVER (integer) | 4 | The EXE code that creates and manages objects of this class runs on same machine but is loaded in a separate process space. |
CLSCTX_REMOTE_SERVER (integer) | 16 | A remote context. The code that creates and manages objects of this class is run on a different computer. |
CLSCTX_SERVER (integer) | 21 | Indicates server code, whether in-process, local, or remote. This definition ORs CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, and CLSCTX_REMOTE_SERVER. |
CLSCTX_ALL (integer) | 23 | Indicates all class contexts. This definition ORs CLSCTX_INPROC_HANDLER and CLSCTX_SERVER. |
VT_NULL (integer) | 1 | NULL pointer reference. |
VT_EMPTY (integer) | 0 | A property with a type indicator of VT_EMPTY has no data associated with it; that is, the size of the value is zero. |
VT_UI1 (integer) | 17 | 1-byte unsigned integer. |
VT_I2 (integer) | 2 | Two bytes representing a 2-byte signed integer value. |
VT_I4 (integer) | 3 | 4-byte signed integer value. |
VT_R4 (integer) | 4 | 32-bit IEEE floating point value. |
VT_R8 (integer) | 5 | 64-bit IEEE floating point value. |
VT_BOOL (integer) | 11 | Boolean value. |
VT_ERROR (integer) | 10 | Error code; containing the status code associated with the error. |
VT_CY (integer) | 6 | 8-byte two's complement integer (scaled by 10,000). |
VT_DATE (integer) | 7 | A 64-bit floating point number representing the number of days (not seconds) since December 31, 1899. For example, January 1, 1900, is 2.0, January 2, 1900, is 3.0, and so on). This is stored in the same representation as VT_R8. |
VT_BSTR (integer) | 8 | Pointer to a null-terminated Unicode string. |
VT_DECIMAL (integer) | 14 | A decimal structure. |
VT_UNKNOWN (integer) | 13 | A pointer to an object that implements the IUnknown interface. |
VT_DISPATCH (integer) | 9 | A pointer to a pointer to an object was specified. |
VT_VARIANT (integer) | 12 | A type indicator followed by the corresponding value. VT_VARIANT can be used only with VT_BYREF. |
VT_I1 (integer) | 16 | 1-byte signed integer. |
VT_UI2 (integer) | 18 | 2-byte unsigned integer. |
VT_UI4 (integer) | 19 | 4-byte unsigned integer. |
VT_INT (integer) | 22 | 4-byte signed integer value (equivalent to VT_I4). |
VT_UINT (integer) | 23 | 4-byte unsigned integer (equivalent to VT_UI4). |
VT_ARRAY (integer) | 8192 | If the type indicator is combined with VT_ARRAY by an OR operator, the value is a pointer to a SAFEARRAY. VT_ARRAY can use the OR with the following data types: VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4, VT_INT, VT_UINT, VT_R4, VT_R8, VT_BOOL, VT_DECIMAL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DISPATCH, VT_UNKNOWN and VT_VARIANT. |
VT_BYREF (integer) | 16384 | If the type indicator is combined with VT_BYREF by an OR operator, the value is a reference. Reference types are interpreted as a reference to data, similar to the reference type in C++. |
CP_ACP (integer) | 0 | Default to ANSI code page. |
CP_MACCP (integer) | 2 | Macintosh code page. |
CP_OEMCP (integer) | 1 | Default to OEM code page. |
CP_UTF7 (integer) | 65000 | Unicode (UTF-7). |
CP_UTF8 (integer) | 65001 | Unicode (UTF-8). |
CP_SYMBOL (integer) | 42 | SYMBOL translations. |
CP_THREAD_ACP (integer) | 3 | Current thread's ANSI code page |
VARCMP_LT (integer) | 0 | The left bstr is less than right bstr. |
VARCMP_EQ (integer) | 1 | The two parameters are equal. |
VARCMP_GT (integer) | 2 | The left bstr is greater than right bstr. |
VARCMP_NULL (integer) | 3 | Either expression is NULL. |
NORM_IGNORECASE (integer) | 1 | Ignore case sensitivity. |
NORM_IGNORENONSPACE (integer) | 2 | Ignore nonspacing characters. |
NORM_IGNORESYMBOLS (integer) | 4 | Ignore symbols. |
NORM_IGNOREWIDTH (integer) | 131072 | Ignore string width. |
NORM_IGNOREKANATYPE (integer) | 65536 | Ignore Kana type. |
NORM_IGNOREKASHIDA (integer) | 262144 | Ignore Arabic kashida characters. | Availability is dependent upon under lying library.
DISP_E_DIVBYZERO (integer) | -2147352558 | A return error that indicates a divide by zero error. |
DISP_E_OVERFLOW (integer) | -2147352566 | An error that indicates that a value could not be coerced to its expected representation. |
MK_E_UNAVAILABLE (integer) | -2147221021 | iMoniker COM status code, return on errors where the function call failed due to unavailability. |

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Errors and error handling
COM


Errors and error handling

Exceptions (PHP 5)

This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Примеры
COM


Примеры

Содержание

  • For Each
  • Arrays and Array-style COM properties

User Contributed Notes

There are no user contributed notes for this page.
Errors and error handling
For Each
COM


For Each

Starting with PHP 5, you may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In layman's terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

Пример #1 For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Пример #2 while() ... Next() in PHP 4

<?php
$domainObject = new COM("WinNT://Domain");
while ($obj = $domainObject->Next()) {
   echo $obj->Name . "<br />";
}
?>

Пример #3 foreach in PHP 5

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj->Name . "<br />";
}
?>

User Contributed Notes

szir at sch dot bme dot hu 05-Jul-2011 02:54
As described in the PHP 5 COM changes article: http://devzone.zend.com/node/view/id/762
You not just "may use foreach statement", but you have to, because $domainObject->Next() is not available in PHP 5 (syntax has been dropped, not backwards compatible)
Примеры
Arrays and Array-style COM properties
Примеры


Arrays and Array-style COM properties

Many COM objects expose their properties as arrays, or using array-style access. In PHP 4, you may use PHP array syntax to read/write such a property, but only a single dimension is allowed. If you want to read a multi-dimensional property, you could instead make the property access into a function call, with each parameter representing each dimension of the array access, but there is no way to write to such a property.

PHP 5 introduces the following new features to make your life easier:

  • Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.

  • Iterate SafeArrays ("true" arrays) using the foreach control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at For Each for more information on this topic.

User Contributed Notes

There are no user contributed notes for this page.
For Each
COM
Примеры


The COM class

(PHP 4 >= 4.1.0, PHP 5)

Description

The COM class allows you to instantiate an OLE compatible COM object and call its methods and access its properties.

$obj = new COM("Application.ID")

Methods

COM::COM ( string $module_name [, mixed $server_name [, int $codepage [, string $typelib ]]] )

COM class constructor. The parameters have the following meanings:

module_name
Can be a ProgID, Class ID or Moniker that names the component to load. A ProgID is typically the application or DLL name, followed by a period, followed by the object name. e.g: Word.Application. A Class ID is the UUID that uniquely identifies a given class. A Moniker is a special form of naming, similar in concept to a URL scheme, that identifies a resource and specifies how it should be loaded. As an example, you could load up Word and get an object representing a word document by specifying the full path to the word document as the module name, or you can use LDAP: as a moniker to use the ADSI interface to LDAP.
server_name
The name of the DCOM server on which the component should be loaded and run. If NULL, the object is run using the default for the application. The default is typically to run it on the local machine, although the administrator might have configured the application to launch on a different machine. If you specify a non-NULL value for server, PHP will refuse to load the object unless the configuration option is set to TRUE.

If server_name is an array, it should contain the following elements (case sensitive!). Note that they are all optional (although you need to specify both Username and Password together); if you omit the Server setting, the default server will be used (as mentioned above), and the instantiation of the object will not be affected by the directive.

DCOM server name
server_name key | type | description
Server | string | The name of the server.
Username | string | The username to connect as.
Password | string | The password for Username.
Flags | integer | One or more of the following constants, logically OR'd together: CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER and CLSCTX_ALL. The default value if not specified here is CLSCTX_SERVER if you also omit Server, or CLSCTX_REMOTE_SERVER if you do specify a server. You should consult the Microsoft documentation for CoCreateInstance for more information on the meaning of these constants; you will typically never have to use them.

codepage
Specifies the codepage that is used to convert strings to unicode-strings and vice versa. The conversion is applied whenever a PHP string is passed as a parameter or returned from a method of this COM object. The code page is sticky in PHP 5, which means that it will propagate to objects and variants returned from the object. Possible values are CP_ACP (use system default ANSI code page - the default if this parameter is omitted), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (use codepage/locale set for the current executing thread), CP_UTF7 and CP_UTF8. You may also use the number for a given codepage; consult the Microsoft documentation for more details on codepages and their numeric values.

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM.

Starting with PHP 5, PHP will automatically detect methods that accept parameters by reference, and will automatically convert regular PHP variables to a form that can be passed by reference. This means that you can call the method very naturally; you needn't go to any extra effort in your code.

In PHP 4, to pass parameters by reference you need to create an instance of the VARIANT class to wrap the byref parameters.

Pseudo Methods

In PHP versions prior to 5, a number of not very pleasant hacks meant that the following method names were not passed through to COM and were handled directly by PHP. PHP 5 eliminates these things; read the details below to determine how to fix your scripts. These magic method names are case insensitive.

void COM::AddRef ( void )

Artificially adds a reference count to the COM object.

Внимание

You should never need to use this method. It exists as a logical complement to the Release() method below.

void COM::Release ( void )

Artificially removes a reference count from the COM object.

Внимание

You should never need to use this method. Its existence in PHP is a bug designed to work around a bug that keeps COM objects running longer than they should.

Pseudo Methods for Iterating

These pseudo methods are only available if com_isenum() returns TRUE, in which case, they hide any methods with the same names that might otherwise be provided by the COM object. These methods have all been eliminated in PHP 5, and you should use For Each instead.

variant COM::All ( void )

Returns a variant representing a SafeArray that has 10 elements; each element will be an empty/null variant. This function was supposed to return an array containing all the elements from the iterator, but was never completed. Do not use.

variant COM::Next ( void )

Returns a variant representing the next element available from the iterator, or FALSE when there are no more elements.

variant COM::Prev ( void )

Returns a variant representing the previous element available from the iterator, or FALSE when there are no more elements.

void COM::Reset ( void )

Rewinds the iterator back to the start.

COM examples

Пример #1 COM example (1)

<?php
// starting word
$word = new COM("word.application") or die("Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}\n";

//bring it to front
$word->Visible = 1;

//open an empty document
$word->Documents->Add();

//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//closing word
$word->Quit();

//free the object
$word = null;
?>

Пример #2 COM example (2)

<?php

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Recordset

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++) {
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF) {
    for ($i=0; $i < $num_columns; $i++) {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs = null;
$conn = null;

?>

User Contributed Notes

rogier 28-Oct-2011 10:09
Took me a while to figure this out by trial and error:

If your frustrated when getting a com-exception like "Error [0x80004002] ..." (with a message nagging you about an unsupported interface), and you're calling a class method through COM that expects a char as an argument, you should NOT call the method with a single-character string.

The correct way of calling a method like this is to use a VARIANT with a type of VT_UI1.

COM enabled method definition:

public bool DoSomething(char arg);

<?php

$com = new COM('Some.Class.Name');

// This will fail
$var = 'a';
$com->DoSomething($var);

// This works correctly
$var = new VARIANT(ord('a'), VT_UI1);
$com->DoSomething($var);

?>

I hope this helps some people
sparrowstail at googlemail dot com 12-Nov-2010 11:35
This script reports all Windows drives, drive type, status (if not available), free space and total drive size:

<?php

    $fso = new COM('Scripting.FileSystemObject');
    $D = $fso->Drives;
    $type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk");
    foreach($D as $d ){
       $dO = $fso->GetDrive($d);
       $s = "";
       if($dO->DriveType == 3){
           $n = $dO->Sharename;
       }else if($dO->IsReady){
           $n = $dO->VolumeName;
           $s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize);
       }else{
           $n = "[Drive not ready]";
       }
   echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>";

    }

      function file_size($size)
      {
      $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
      }

?>

There are a number of other properties of the drive object which can be called this way - see:

http://msdn.microsoft.com/en-us/library/ts2t8ybh%28VS.85%29.aspx
z3n at overflow dot biz 24-Sep-2009 08:35
On a query reply using ADODB.Connection object, all my $rs->Fields['field_name']->Value returned `variable Object` when inserted into a array, like this:

<?php
for ($rl[$v]=array(),_qm($_query);!$res->EOF;$res->MoveNext()) {
    $rl[$v][]=$res->Fields['x']->Value;
}
?>

I figured out that converting the value into a INT fixed the issue:

<?php $rl[$v][]=intval($res->Fields['x']->Value); ?>
rupams2002 at yahoo dot com 24-Jul-2009 10:38
If you make a DLL in VB6 and want to access from PHP, here is the example. Only connection method is defined. You need to create rest....

How to use in PHP
DLL refers ProjectName . ClassName
$Obj = new COM ('ProjectName.ClassName');
$dw->MsSql_Connect('MachineName', 'DB_NAme');

If you want to connect Database through DLL then

Open project in VB6 Class Module :
And add this code and compile and make DLL.

Public Function MsSql_Connect(ByVal DBMachineID As String, ByVal DBName As String) As Boolean
    Dim LocalCn As New ADODB.Connection
    Dim conStr As String, DB_UserID As String, DB_Password As String

    On Error GoTo ErrorHandler

    DB_UserID = "DBUserName"
    DB_Password = "DBPassword"

    Set LocalCn = New ADODB.Connection
    LocalCn.CursorLocation = adUseClient

    conStr = "Provider=SQLOLEDB.1;Password=" & DB_Password & ";Persist Security Info=True;User ID=" & DB_UserID & ";Initial Catalog=" & DBName & ";Data Source=" & DBMachineID & ";"
    LocalCn.Open conStr

    DBConnection = conStr

    MsSql_Connect = True
    Set LocalCn = Nothing

ErrorHandler:
    If Err.Number <> 0 Then
       MsSql_Connect = False
       Set LocalCn = Nothing
       Err.Raise vbObjectError + 513, App.EXEName, Err.Description
    End If
End Function

"DBConnection" is a variable you need to Set + Get property in VB6 to keep the connection string alive in DLL.

Remember :
Err.Raise vbObjectError + 513, App.EXEName, Err.Description

will raise error in PHP, user can see error in browser and stop execution php code.

If you need any help email me.

Mohammed Ziaul Hasan [Rupam]
rupams2002@yahoo.com
Senior Developer
Canada
pavanphp Gudipati 17-Jun-2009 06:49
Here I Am describing a Program from which you can connect any exe(software) using COM component.
pdf2swf is a software for converting PDf to SWF files.

This is best example for  WScript.Shell

<?php
#code for pdf to swf using pdf2swf software
#this codeworks in windows environment.

## Important Parameters
$software_path  ="C:\\SWFTools\\pdf2swf" ;
$pdf_path       ="C:\\SWFTools\\abcd.pdf" ;
$argument       = "-o";
$swf_output     ="C:\\SWFTools\\abcd.swf" ;

#actual code
$cmd        =" $software_path $pdf_path  $argument $swf_output";

$WshShell   = new COM("WScript.Shell");
$oExec      = $WshShell->Run("cmd /C $cmd ", 0, true);

# 0 for command prompt invisible mode
# 3 for visible

?>
tsintra at humansoft dot pt 11-May-2009 08:18
After one week of trying to understand what was wrong with my PHP communication with MS Word, i finally got it working...
It seems that if you're running IIS, the COM object are invoked with restricted privileges.
If you're having permission problems like not being able to opening or saving a document and you're getting errors like:

 - This command is not available because no document is open
or
 - Command failed

try this (if you're running IIS):

- Execute "dcomcnfg"
- Open Component Services > Computers > My Computer > DCOM Config
- Search for Microsoft Office Word 97-2003 Document (it will be something like this translated to your language, so take a while and search for it)
- Right-Click on it and open the properties
- Choose "Identity" tab
- Normally this is set to "the launching user". You have to change this to "the interactive user" or a admin user of your choice.
- Apply these new settings and test your COM application. It should work fine now.

I hope I save lots and lots of hours of headaches to some of you :)
fernando at digitins dot com dot br 08-Apr-2009 07:30
When you save a MS Word document with this:
<?php
$word->Documents[1]->SaveAs('myfile.doc');
?>

Your file maybe go to this location:
C:\WINDOWS\system32\config\systemprofile\My documents (and not to your script directory)
dpchiesa at hotmail dot com 27-Mar-2009 09:35
Here's a way to create an AES-Encrypted ZIP file in PHP, using DotNetZip via the COM class.

<?php
try
{
  $fname = "zip-generated-from-php-" . date('Y-m-d-His') . ".zip";
  $zipOutput = "c:\\temp\\" . $fname;
  $zip = new COM("Ionic.Zip.ZipFile");
  $zip->Name = $zipOutput;
  $dirToZip= "c:\\temp\\psh";
  #$dirToZip= "c:\\dinoch\\webs\\php";
  $zip->Encryption = 3;
  $zip->Password = "AES-Encryption-Is-Secure";
  $zip->AddDirectory($dirToZip);
  $zip->Save();
  $zip->Dispose();

  if (file_exists($zipOutput))
  {
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-Type: application/x-zip');
    header('Content-Disposition: attachment; filename=' . $fname);
    header('Content-Length: ' . filesize($zipOutput));
    readfile($zipOutput);
    unlink($zipOutput);
  }
  else
  {
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '</body>';
    echo '</html>';
  }
}
catch (Exception $e)
{
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '<p>Caught exception: ',  $e->getMessage(), '</p>', "\n";
    echo '<pre>';
    echo $e->getTraceAsString(), "\n";
    echo '</pre>';
    echo '</body>';
    echo '</html>';
}

?>
pavanphp at sparsh dot net 14-Feb-2009 05:42
This is the code for entering Values in MS word through Php Program.

First : You need to make word file with including Boolmark
(Ms word 2003 , Insert -> Bookmark ->Bookmark Name -> add).
Example
Name : add here bookmark
 This is something like input as a text box.  Here I given 5 fields.
Name , TODAYDATE , Company ,project , Features

Here I opened a word file, and put data into Bookmark fields using PHP.

Just note : it works in c:/ only. (not sure why), C:/program files may take longer time. (waiting for ...)

<?php

com_load_typelib('Word.Application');

$word = new COM("word.application") or die("Unable to instantiate Word");

// use like this. Place your's word file in C drive
$word->Documents->Open('C:/reminder_new.doc');
echo $current_date = date("m/d/Y");

$tim= date("Y-m-d");

$info_array=array(  "Name"      => "pavan",
                    "TODAYDATE" => "$tim" ,
                    "Company"   => "sparsh" ,
                    "project"   => "Myrepc",
                    "Features"   => "Auto fill form editor") ;

foreach($info_array as $bookmarkname => $re)
    {

        $objBookmark = $word->ActiveDocument->Bookmarks($bookmarkname);
        $range = $objBookmark->Range;
        echo $range->Text = $re ;

    }

$new_file = "c:/reminder_filled.doc";

$word->Documents[1]->SaveAs($new_file);

$word->ActiveDocument->Close(false);

$word->Quit();
$word = null;

?>
CLICIU at YAHOO dot com 03-Feb-2009 03:18
What's really cool is that you can write anything you like in C#/VB.NET and easily access it via COM in PHP
This is a image Rotation Example using C# and PHP

<form name="form1" method="get" action="#">
<input name="angle" type="text" value="<?echo $_GET["angle"];?>">
  <input type="submit" name="Submit" value="Submit">
</form>

<?php
if(!isset($_GET["angle"]) && !is_Numeric($_GET["angle"]) )
{
  $angle=5;
}else{
    $angle=intval($_GET["angle"]);
}

        //         $img =new COM("MyImageProcessor.MyImageProcessing");
                 $img =  new DOTNET("MyImageProcessor","MyImageProcessing");
                  $img->LoadImage("D:\\htdocs\\TT\\Flower.jpg");
                  $img->RotateImage($angle);
                  $img->SaveImage("D:\\htdocs\\TT\\new.jpg");
?>
Otput image:<br>
<img src="new.jpg" width="520"/>
<br><br>
 Original   image <br>
<img src="Flower.jpg" width="520"/>

The complete source code PHP and C# :
http://www.navioo.com/php/tutorials/PHP_and_NET_876.html
james dot m dot love at gmail dot com 07-Jan-2009 03:27
If you're using COM to create a DSN Less connection to an MS Access 2007 database, you'll find through Googling that you need to use an updated version of Jet, so the connection string I've found looks like this:

<?php
$databaselocation = "C:\Path\to\db.accdb";
$conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
$conn->Open("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=$databaselocation") or die('Cannot start with Jet');
?>

However, on my setup (WinVista, Access 2007, PHP526) I found that it always 'dies' with "Cannot start with Jet", even if the connection was successful ($conn->State reads "1").

I figured to just drop the die() command on $conn->Open(). If something catastrophic happens with the ADO connection then it's own error handling engine passes stack traces, etc back to the console/standard output.

Therefore, my Open() command looks like this:

<?php
$conn->Open("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=$databaselocation");
?>
casanoteva at yahoo dot com 26-Dec-2008 01:19
Hi, just wanna share to everyone after tried and tested many many times to create report in PDF format from Crystal Report.
Finally I can do it without any error.
 Here is my system; PHP 5.1.6, MSSQL2005 and Crystal Report Server XI RL2

<?php

//- Variables - for your RPT and PDF
echo "Print Report Test";
$my_report = "D:\\Folder1\\SubFolder1\\Report.rpt"; //
rpt source file
$my_pdf = "D:\\Folder1\\SubFolder1\\Report.pdf"; // RPT export to pdf file
//-Create new COM object-depends on your Crystal Report version
$ObjectFactory= new COM("CrystalReports115.ObjectFactory.1") or die ("Error on load"); // call COM port
$crapp = $ObjectFactory-> CreateObject("CrystalDesignRunTime.Application"); // create an instance for Crystal
$creport = $crapp->OpenReport($my_report, 1); // call rpt report

// to refresh data before

//- Set database logon info - must have
$creport->Database->Tables(1)->SetLogOnInfo("servername", "DBname", "user", "password");

//- field prompt or else report will hang - to get through
$creport->EnableParameterPrompting = 0;

//- DiscardSavedData - to refresh then read records
$creport->DiscardSavedData;
$creport->ReadRecords();

//export to PDF process
$creport->ExportOptions->DiskFileName=$my_pdf; //export to pdf
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // export to file
$creport->ExportOptions->FormatType=31; // PDF type
$creport->Export(false);

//------ Release the variables ------
$creport = null;
$crapp = null;
$ObjectFactory = null;

//------ Embed the report in the webpage ------
print "<embed src=\"D:\\Folder1\\SubFolder1\\Report.pdf\" width=\"100%\" height=\"100%\">"

?>

 That's all for me, anyway in Crystal Report I have to check DisCardSavedData, Save data with report and AutoSave (1 min) in Option Tab and also in Report Options I have to check save dat with report, too.

Hope this should be help to anybody

Casanoteva
johnno1985 at gmail dot com 21-Aug-2008 11:34
I couldn't find an example anywhere on what I was trying to do.  After taking bits from everyone I ended up with something that worked.

Im using Crystal Reports 10, MS SQL Server 2005, Apache2, and PHP5.

My report uses an SQL Store Procedure and passes some parameter to get the report data, so our PHP must set the database logon info and pass the parameters.

Below is the solution I came up with:

<?php

//------  Variables ------
$my_report = "C:\\Apache2\htdocs\\test\\MyReport.rpt";  //This must be the full path to the file
$my_pdf = "C:\\Apache2\htdocs\\test\\MyReport.pdf";

//------ Create a new COM Object of Crytal Reports 10 ------
$ObjectFactory= new COM("CrystalReports10.ObjectFactory.1");

//------ Create a instance of library Application -------
$crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application.10");

//------ Open your rpt file ------
$creport = $crapp->OpenReport($my_report, 1);

//------ Set database logon info ------
$creport->Database->Tables(1)->SetLogOnInfo("MYSERVER", "Database", "user", "password");

//------ Suppress the Parameter field prompt or else report will hang ------
$creport->EnableParameterPrompting = 0;

//------ DiscardSavedData make a Refresh in your data -------
$creport->DiscardSavedData;
$creport->ReadRecords();

//------ Pass formula fields --------
$creport->FormulaFields->Item(1)->Text = ("'My Report Title'");
$creport->ParameterFields(1)->AddCurrentValue ("FirstParameter");
$creport->ParameterFields(2)->AddCurrentValue (2000);

//------ Export to PDF -------
$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->FormatType=31;
$creport->ExportOptions->DestinationType=1;
$creport->Export(false);

//------ Release the variables ------
$creport = null;
$crapp = null;
$ObjectFactory = null;

//------ Embed the report in the webpage ------
print "<embed src=\"MyReport.pdf\" width=\"100%\" height=\"100%\">"

?>

Obviously there's plenty of room for refinement in there, but it works and should get you going on the right track.  I also found that during testing, the script was hanging before supressing the parameter prompt. Once this had happened, some exports that had been working earlier stopped completely and wouldn't work again untill I restarted Apache.  This might be something worth doing if you keep having issues after a script has hung.
jkruse [at] unlnotes [dot] unl [dot] edu 20-Aug-2008 01:22
This is my first php.net comment so go easy on me :)

I was having trouble using COM to convert from ppt/pptx to an image for every slide (this works for outputting pdf,html,pptx->ppt, etc)

$app = new COM("PowerPoint.application") or die("Unable to instantiate PowerPoint");
$app->Visible = true;
$pres = $app->Presentations->Open("E:/tmp/test.pptx") or die ("Could not open presentation");
$app->Presentations[1]->SaveAs("E:/tmp/outdir",18);
$app->Presentations[1]->Close();
$app->Quit();
$app = null;

This code converts pptx to a png of every frame. Thats what 18 stands for (Its a class constant, you can see all the other formats here: http://msdn.microsoft.com/en-us/library/bb265906.aspx)

Hope this helps someone. Feel free to email me at the address above.
verticka at hotmail dot com 01-Aug-2008 04:38
Voila une deuxime fonction pour excel 2007 et le plugin pdf

<?php
function xls2pdf($doc,$pdf)
{

// Pas de paramétres requis
$empty = new VARIANT();

/* Supression du pdf si il existe */
if(file_exists ($pdf))
@unlink($pdf);

/* Démarrage de Word */
$w = new COM("excel.application") or die("Impossible d'instancier l'application Word");

/* Test de Word 2007 */
if($w->Version > 11)
{
    /* Amener Word devant */
    $w->Visible = 1;

    /* Test du fichier */
    if(file_exists ($doc))
        $w->Workbooks->Open($doc);
    else
        return false;

    /* Quelques commandes */
    $w->Workbooks[1]->ExportAsFixedFormat(0,$pdf);

    /* Fermeture de word */
    $w->Workbooks[1]->Close(false);
}
$w->Quit();

/* Libération des ressources */
$w = null;
unset($w);

/* Test du fichier */
if(file_exists ($pdf))
    return true;
else
    return false;

}

if(xls2pdf("c:\\test.xls","c:\\test.pdf"))
echo "ok";
else
echo "nok";
?>

Pour les options d'exportation :
http://msdn.microsoft.com/en-us/library/bb238907.aspx

http://verticka.blogspot.com/
mastrboy.servebeer.com 13-Jun-2008 05:03
quick wmi query example:

<?php
    $obj = new COM ( 'winmgmts://localhost/root/CIMV2' );
    $wmi_computersystem =     $obj->ExecQuery("Select * from Win32_ComputerSystem");
    $wmi_bios             =    $obj->ExecQuery("Select * from Win32_BIOS");
    foreach ( $wmi_computersystem as $wmi_call )
    {
        $model = $wmi_call->Model;
    }

    foreach ( $wmi_bios as $wmi_call )
    {
        $serial = $wmi_call->SerialNumber;
        $bios_version = $wmi_call->SMBIOSBIOSVersion;
    }
    echo "Bios version   : $bios_version\n".
         "Serial number  : $serial\n".
         "Hardware Model : $model\n";
?>
mbirth at webwriters dot de 08-Jun-2008 03:19
Using the DynamicWrapper from http://freenet-homepage.de/gborn/WSHBazaar/WSHDynaCall.htm and after registering it via "regsvr32 dynwrap.dll", you can easily set output colors to make colorful CLI scripts even on Windows.

<?php

$dw = new COM('DynamicWrapper');  // needs dynwrap.dll (regsvr32 dynwrap.dll)

// register needed features
$dw->Register('kernel32.dll', 'GetStdHandle', 'i=h', 'f=s', 'r=l');
$dw->Register('kernel32.dll', 'SetConsoleTextAttribute', 'i=hl', 'f=s', 'r=t');
$dw->Register('kernel32.dll', 'SetConsoleTitle', 'i=s', 'f=s', 'r=l');

// get console handle
$ch = self::$dw->GetStdHandle(-11);  // -11 = STD_OUTPUT_HANDLE

?>

After these initialization steps, you can set the console output color using:

<?php
$dw->SetConsoleTextAttribute($ch, 14);
echo 'This is yellow text!';
$dw->SetConsoleTextAttribute($ch, 7);
echo 'Back to normal gray!';
?>

Using SetConsoleTitle you can even set the title displayed in the console window.

Color values are 0..7 for dark colors and 8..15 for light colors. Sequence is (black/silver, blue, green, cyan, red, magenta, yellow/brown, white/gray). I also found that if you add 16384 to the value, it should be inverse. 32768 added should get underlined text. But these latter two didn't work for me.
amenthes at NOSPAM dot gmail dot com 03-Mar-2008 10:13
If you ever want to save an Excel(.xls) file into the Office Excel 2003 XML format, just use

$excel->Workbooks[1]->SaveAs('new_file_name.xml', 46);

That's the number you need, 46.
halfer 21-Jun-2007 05:03
Thanks to paul at completewebservices who added a note earlier; I have used his code to solve a particularly difficult issue with the Crystal 9 runtime component. For some reason, VBA/VBS can pass a native Date type as a parameter to a Crystal Report requiring a date, but in PHP I've tried all manner of strings, unix timestamps, COM variant dates etc and all of these resulted in a com_exception.

My solution was to employ VBScript to borrow the CDate function, which works correctly. Not the most elegant of solutions, but this parameterised approach is to be preferred to search-n-replacing the RecordSelectionFormula string. Of course if anyone here has an even better approach, do post it here - I am sure it would be of use.

<?php
// $rptParam is a report parameter object having a type of date
$oScript = new COM("MSScriptControl.ScriptControl");
$oScript->Language = "VBScript";
$oScript->AllowUI = false;
$oScript->AddObject('rptParam', $rptParam, true);
$oScript->AddCode('Function SetDateParameter(strDate)
rptParam.AddCurrentValue(CDate(strDate))
End Function');
$oScript->Run("SetDateParameter", "25 April 2006");
?>
hwcshirley at gmail dot com 21-May-2006 10:59
Reply to: djogopatrao at gmail dot com
I have change little bit your code. Its work.

$COM_Object = "CrystalDesignRunTime.Application";
$my_report = "C:\\appserv\\www\\mc\\test.rpt";
$my_pdf = "C:\\appserv\www\\mc\\test.pdf";

$crapp= New COM($COM_Object) or die("Unable to Create Object");
$creport = $crapp->OpenReport($my_report, 1);
$creport->ReadRecords(); // attention!

$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // Export to File
$creport->ExportOptions->FormatType=31; // Type: PDF
$creport->Export(false);
djogopatrao at gmail dot com 05-Apr-2006 12:25
My previous notes about Crystal Reports have vanished away, but anyway I was up to correct them.

The code above connects to COM (beware of the version number! search on the Registry Editor for the correct name to put in $COM_Object), opens a report from a file ($my_report), reload records from database and then exports it to a PDF file ($my_pdf).

* IMPORTANT * this code, when invoked from the browser (I'm using Apache) AND with a report that connects to a ODBC database, does not work (the problem is specificly the line ReadRecords(), but may arise without it too when data is not saved into the report file).

But when you run this code by PHP-CLI (that is, by the command line), it works ok! I bug-reported this, but have no answer till now ( give it a vote, if you thing it's important: http://bugs.php.net/bug.php?id=36959 ).

Also, exceptions may arise, so put it on a try_catch block.

--------------------------

// by dfcp '06 (djogopatrao@gmail.com)

$COM_Object = "CrystalReports11.ObjectFactory.1";
$my_report = "C:\\report.rpt";
$my_pdf = "C:\\report.pdf";

$ObjectFactory= New COM($COM_Object);
$crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
$creport = $crapp->OpenReport($my_report, 1);
$creport->ReadRecords(); // attention!

$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // Export to File
$creport->ExportOptions->FormatType=31; // Type: PDF
$creport->Export(false);
djogopatrao at gmail dot com 04-Mar-2006 07:27
I found somewhere (http://www.recrystallize.com/merchant/supportfaq/supportfaq0003.htm) a list relating each version of Crystal Reports to its respective progID - it may help some fellows out there.

7          Crystal.CRPE.Application

8.0        CrystalRuntime.Application or CrystalRuntime.Application.8

8.5        CrystalRuntime.Application or CrystalRuntime.Application.8.5

9 (RDC)    CrystalRuntime.Application.9
9 (RAS)    CrystalReports.ObjectFactory.2
10 (RDC)   CrystalRuntime.Application.11
10 (CEE)   CrystalReports10.ObjectFactory.1

XI (RDC)   CrystalRuntime.Application.11
XI (RAS)   CrystalReports11.ObjectFactory.1
paul at completewebservices dot com dot au 28-Jan-2006 03:49
It seems that PHP does not support setting of properties with arguments.  This is how I got around the problem:

        // Object with method I want to set
        $auth = new COM("AUTHXOCX.AuthXOCXCtrl.1");

        // ScriptControl
        $oScript = new COM("MSScriptControl.ScriptControl");
        $oScript->Language = "VBScript";
        $oScript->AllowUI = TRUE;

        // Add out object to the control
        $oScript->AddObject('auth', $auth, true);

        // Create a VBScript function that allow me to set them
       $oScript->AddCode(
'Function fixAccess(accessname)
    auth.AuthDataReferrerEnabled(accessname) = 1
    auth.AuthDataAuthentiXDBEnabled(accessname) = 0
End Function');

        // Execute function
        $oScript->Run("fixAccess", $dir);
volker at kybs dot de 07-Oct-2005 12:51
To use the windows speech system install the "Speech SDK 5.1 for Windows� applications" from the Microsoft homepage (free download).
Then you can do Text2Speech like this:

$voice = new COM("SAPI.SpVoice");
$voice->Speak("Hello, lets have a conversation");
sadi at unicornsoftbd dot com 06-Oct-2005 01:56
If your PHP is configured as ISAPI module then the COM object you create in ur php page will use the same memory space as the web server. If your COM object takes too much memory then this may force some COM error as PHP does not handle the memory usage of COM itself. And also Web server doesnt know what do to free COM memory. But if you use PHP as CGI then PHP itself handle the memory usage of COM. Once in a script where i used COM and PHP as ISAPI module i got unknown COM error.But when i used PHP as CGI there was no error. So those who want to use COM object in your application please be careful about it.
deletethis@bjoern(at)syltonline(doot)de 15-Sep-2005 07:36
If you can get the old "TaskScheduler.dll" and register it, it is quite simple to handle and start Windows tasks from PHP.
This is extremely useful when you got things to do which must be run in a different user context. Prepare a task with the user and use PHP & Com to build a webinterface for it.

Here is an example how to start a Windows task:

  function start_task ($taskname) {
    $SchedObj = new COM("Scheduler.SchedulingAgent.1");
    foreach ($SchedObj->Tasks as $task) {
      if (strtolower( (string) $task) == strtolower( $taskname.".job" )) {
         $task->Run();
      }
    }
  }

I'm also working on a class to handle infos, adding and removing of tasks via PHP. If you are interested drop me a line.
jbr at ya-right dot com 19-Aug-2005 01:07
Getting * directory * permissions ( attributes ) with COM

PHP (5) example...

<?
    $dir = 'e:/www/docs/www/docs/junk/';

    define ( 'READ_ONLY', 1 );
    define ( 'IS_HIDDEN', 2 );
    define ( 'IS_SYSTEM', 4 );

    $hold = array ();

    $obj = new COM ( 'scripting.filesystemobject' );

    if ( is_object ( $obj ) )
    {
        $all = $obj->getfolder ( $dir );

        foreach ( $all->subfolders AS $directory )
        {
            if ( substr ( $directory->name, - 3 ) != 'cnf' )
            {
                $hold[$dir . $directory->name . '/'] =  array ( 'read_only' => ( ( $directory->Attributes & READ_ONLY ) <> 0 ? 1 : 0 ), 'is_hidden' => ( ( $directory->Attributes & IS_HIDDEN ) <> 0 ? 1 : 0 ), 'is_system' => ( ( $directory->Attributes & IS_SYSTEM ) <> 0 ? 1 : 0 ) );
            }
        }

        $obj = null;
    }
    else
    {
        echo 'sorry can not crate object: file_system_object';
    }

    print_r ( $hold );
?>

To do the same thing for * files * with in the directory named in $dir, change above ( foreach() ) to what is below...

        foreach ( $all->files AS $file )
        {
            $hold[$file->name] =  array ( 'read_only' => ( ( $file->Attributes & READ_ONLY ) <> 0 ? 1 : 0 ), 'is_hidden' => ( ( $file->Attributes & IS_HIDDEN ) <> 0 ? 1 : 0 ), 'is_system' => ( ( $file->Attributes & IS_SYSTEM ) <> 0 ? 1 : 0 ) );
        }

pretty much anything you could think of doing in windows can be done using PHP and COM...

John
csaba at alum dot mit dot edu 03-Mar-2005 05:21
Getting IE to the foreground
If you are using a command line (CLI) version of PHP on a Win32 platform (e.g. XP Pro, SP2), you might want to have output directed to IE (perhaps you'll want to work with the output there) when Popup does not suffice (see my earlier post, below).

It's easy enough to get an instance of IE using $ie = new COM("InternetExplorer.Application");.  The problem is, you don't necessarily see it in the foreground (especially if you already have one open) and who wants to waste keystrokes getting to it?  The code below has been working for me (If you want to do other adjustments (e.g. $ie->Document->ParentWindow->resizeTo(800,500); or $ie->Document->Body->bgColor = "yellow";), doing them before the $ie->Visible = true; line will avoid screen distractions):

<?php
function newIEtoForeground($title, $evtPrefix="") {
    // brings new instance of IE to foreground with title $title
    if (!$extPrefix) $ie = new COM("InternetExplorer.Application");
    else $ie = new COM("InternetExplorer.Application", $evtPrefix);
    $ie->Navigate2("about:blank");
    $oWSH = new COM("WScript.Shell");
    while ($ie->ReadyState!=4) usleep(10000);

    $ie->Document->Title = ($tmpTitle = mt_rand());  //unique title
    $ie->Visible = true;
    while (!$oWSH->AppActivate("$tmpTitle - M")) usleep(10000);

    $ie->Document->Title = $title;
    $ie->Document->ParentWindow->opener="me";  // allows self.close()
    return $ie;
}
?>

Csaba Gabor from Vienna
csaba at alum dot mit dot edu 14-Feb-2005 12:22
Basic Windows IO
If you are using a command line (CLI) version of PHP on a Win32 platform, you might like to have a simple graphical interface to get input and output.  The following gives an illustration for both.

<?php
    // first we get some input
    $oScript = new COM("MSScriptControl.ScriptControl");
    $oScript->Language = "VBScript";
    $title = "I/O Demo: Input half";
    $initial = "Change this value";
    $prompt = "Please enter a value";

    $code = <<<EOF
Function getInput()
    inVal = InputBox("$prompt", "$title", "$initial")
    getInput = inVal         'how return values are assigned in VB
End Function
EOF;

    $oScript->AddCode($code);
    $input = $oScript->Eval("getInput()");
    if (gettype($input)=="NULL") $input = "Input box was cancelled";

    // now we show some output
    $oWSH = new COM("WScript.Shell");
    $title = "I/O Demo: Output half";
    $timeout = 2;        // 0 for no timeout
    $style = 0 + 48;    // buttons to show + alert symbol
    $oWSH->Popup($input, $timeout, $title, $style);
?>

This is example is overblown for illustrative purposes.  The whole input part collapses if the amount of code used is a single statement.  So, this would have sufficed:
$code = "InputBox(\"$prompt\", \"$title\", \"$initial\")";
$input = $oScript->Eval($code);

This technique exposes quite a bit of scripting power tied into the Windows operating system and VBScript.  However, you should have a really specific reason for using it since VBScript tends to be dog slow when compared to PHP in my tests.  Simple IO like this is good, however, and the popup size can be quite large.  Furthermore, this could be a viable route to go for accessing WinAPI's.

http://www.ss64.com/wsh/popup.html shows some documentation for $oWSH->Popup

Csaba Gabor from Vienna
phpguy _from_ toshpro _dot_ com 12-Nov-2004 05:55
if you ever need to connect to an access database (on the server, using the IIS or APACHE user account), here is code below that can help to ease the process.  It is written like this because we have a MySQL as well as an Access database and need to be able to switch back and forth.  The runQuery function will return a 2 dimensional array and can use column names or numbers for the index of the internal arrays.  External arrays are always integer-indexed.  We also have found issues with Access staying open and growing from 7MB to 2.5GB within two hours, so we open and close it each time we run a query.  If it is not a select query it will return TRUE.  if it fails with errors, it will return false.

There is a showErr flag that we mostly only use for MySQL, since you can output MySQL errors without PHP errors.  Access doesn't appear to be that friendly.

<?php

function runQuery(&$conn,
                    $strSQL,
                    $associative=true,
                    $debug=false,
                    $showSQL=false,
                    $showErr=false) {
    return runMSQuery($conn,$strSQL,$associative,$debug,$showSQL,$showErr);
    //return runMyQuery($conn,$strSQL,$associative,$debug,$showSQL,$showErr);
}

function openMSDB($dbfile="c:/path/and/filename.mdb") {
    if (!@$conn = new COM("ADODB.Connection"))
        exit("Unable to create an ADODB connection<br>");
    $strConn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$dbfile;
    @$conn->open($strConn);
    if($conn->State == 0) return false;
    return $conn;
}

function closeMSDB(&$conn) {
    @$conn->Close();
    $conn = null;
    return true;
}

function runMSQuery(&$conn,
                    $strSQL,
                    $associative=true,
                    $debug=false,
                    $showSQL=false,
                    $showErr=false) {
    if(!is_object($conn)) if(!$conn=openMSDB()) return false;
    if( $showSQL || $debug ) echo $strSQL."\n<br>\n";
    $rtn = false;
    if($debug) $rs = $conn->execute($strSQL);
    else $rs = @$conn->execute($strSQL);

    if(!$rs) {
        if($showErr) echo "Error running SQL.<br>\n";
        closeMSDB($conn);
        return false;
    }
    if ($rs->State == 0) {
        closeMSDB($conn);
        return true;
    } else {
        $rows=0;
        while(!$rs->EOF) {
            for($i=0;$i<$rs->Fields->count;$i++) {
                $rsf = $rs->Fields($i);
                if($associative) $rtn[$rows][$rsf->Name] = $rsf->value;
                else $rtn[$rows][$i] = $rsf->value;
            }
            $rows++;
            $rs->MoveNext();
        }
        if($rs->State != 0) $rs->Close();
        $rs = null;
    }
    if($debug) var_dump($rtn);
    closeMSDB($conn);
    return $rtn;
}
?>
sodeh at dana dot ir 30-Oct-2004 03:11
for connection to sql server and know the utf-8 code
use this method to connect the database

$db = new COM("ADODB.Connection",NULL, 65001 );
jbr at ya-right dot net 12-May-2004 11:23
"Keeping an instance of a Server object loaded"

When dealing with COM objects like 'Word' or 'Excel' you are pretty
much dealing with personal COM type objects. The reason I say this
is because they in no way have any direct relationship to a real COM
server object. The differences between a 'Server COM Object' and a
'Personal COM Type Object' are great. Server COM objects, do not contain
and properties or methods related to any type of program dialog.

Most Enterprise COM objects are designed to run under IIS where they
are loaded into the server process. So once the first instance call is
made or when the server is started the object loads it properties, methods
and data related to the service the object provides!

Many objects load large data set(s) 10 MB to 200 MB into memory, this makes
any process after the initial loading of the object fast and very system
friendly!

In PHP, when an initial instance of an object is loaded some where in a
PHP script, PHP will check if an instance of the object is already running
if it is, then it will use that instance. If it can not find an instance to
the object running, it will create a new instance to the object!

In the case of personal COM type objects, you can point to a running instance
of an object, and reference that instance...

<?

$obj = new COM ( 'X:\reports\june.doc' );

?>

For Server type COM objects that load large data set(s), you really have no option
because each script run will unload the instance at the end of the script's run time.
Unless another http request is running and the new http request can access the other
object instance, you will have to load all the objects properties and methods and data
set(s) used by the object!

One way to work around this is to write a wrapper that can load the object into the
PHP or the Server process! I did this for the objects I use.

Another unorthodox way is to load your web browser to a PHP script that uses a combination
of ignore_user_abort(), set_time_limit(), load the object, sleep();!

Before I wrote the wrapper for a 'Map Server Object' I use in one of my project. I used
the 'unorthodox way' for almost a year and had over 15,000 object requests a day, and
never did the instance of the object ever have to start a new instance, ie: reload all the properties and methods and data
set(s) used by the object!

Like I said this is a very 'unorthodox way' to keep an object loaded, but it works!

set the object 'My.Object' in the script, call the script from the browser, then close the browser!

<?

    ignore_user_abort ( 'true' );

    set_time_limit ( 0 );

    com_load_typelib ( 'My.Object' ) or die ( 'Could not load TypeLib' );

    $obj = new COM ( 'My.Object' ) or die ( 'Could not load object' );

    $obj = null;

    sleep ( 63166608000 ); // one year

?>

John
flintjt at hotmail dot com 11-Mar-2004 11:45
I have searched for ways to open and read an excel document and I found some information which I thought that I would document.  Information on the object model to help with programming COM objects can be found in your MS Office help files, search for VBA*.chm.
Also, here is a script that I used to pull a cell from each worksheet, complete w/ variable for pathnames & worksheets.  This script also closes excel completely.  The coding might be dirty, but it gets the job done.
--------copy from here-----------
<pre>
<?PHP
$filename = "c:/spreadhseet/test.xls";
$sheet1 = 1;
$sheet2 = "sheet2";
$excel_app = new COM("Excel.application") or Die ("Did not connect");
print "Application name: {$excel_app->Application->value}\n" ;
print "Loaded version: {$excel_app->Application->version}\n";
$Workbook = $excel_app->Workbooks->Open("$filename") or Die("Did not open $filename $Workbook");
$Worksheet = $Workbook->Worksheets($sheet1);
$Worksheet->activate;
$excel_cell = $Worksheet->Range("C4");
$excel_cell->activate;
$excel_result = $excel_cell->value;
print "$excel_result\n";
$Worksheet = $Workbook->Worksheets($sheet2);
$Worksheet->activate;
$excel_cell = $Worksheet->Range("C4");
$excel_cell->activate;
$excel_result = $excel_cell->value;
print "$excel_result\n";
#To close all instances of excel:
$Workbook->Close;
unset($Worksheet);
unset($Workbook);
$excel_app->Workbooks->Close();
$excel_app->Quit();
unset($excel_app);
?>
</pre>
----------------------------------
jon at jonroig dot com 03-Dec-2003 12:28
Here's a simple example of printing formatted templates with MS Word.

To begin with, I've already built my invoice in Word and saved it as an RTF file.
In this case, I'm using "sampleInvoice.php"

Fields that will be replaced have been marked as ||CUSTOMER ID|| and so on.

<?php
$dataText = "";

// open the file
if(!($fp= fopen ("C:\wordTest\sampleInvoice.rtf", "r"))) die ("Can't open");
$dataText = fread($fp, 2000000);
fclose ($fp);

// replace the template fields
$dataText = str_replace ("||CUSTOMER ID||",$customerIDValue, $dataText);

// save the file as an rtf
$timeStamp = time();
$saveFile = "C:/wordTemp/".$timeStamp."-invoice-".$customerIDValue.".rtf";
if(!($fq= fopen ($saveFile, "w+"))) die ("Can't open");
fwrite ($fq, $dataText);
fclose ($fq);

// initialize the word components
$word = new COM("word.application") or die("Unable to instantiate Word");

print "Loaded word version ($word->Version)\n";
$word->visible = true;
$word->Documents->Add();

// open the file
$word->Documents->Open("$saveFile");

// output the file to the default printer
$word->ActiveDocument->PrintOut(1);

// shutdown word
$word->Quit();
?>
jnv at jnv dot ch 03-Dec-2003 03:42
Be sure you have Word, Excel, .. on your server or it will not work !
drich at nea-online dot net 18-Nov-2003 02:47
Changing Fields (Not FORMFIELDS) In MS Word....

Searched most of the afternoon for this, as it is something needed here for our projects.  Maybe this can help someone else as well.

<?php
$input = "x:\\path\\to\\test.doc";
$word = @new COM("word.application") or die("Unable to instantiate Word");
print "Loaded Word, version {$word->Version}\n<br>";
$word->Visible = 1;
print "Set Word To Visible<br>";
$word->Documents->Open($input);
print "Opened $input<br>";
$word->Activate;
print "Activated Word<br>";

print "Editing Fields<br>";
$Field = $word->ActiveDocument->Fields(1);
$fieldData = $Field->Result;
$fieldData->Text = "Testing";

// Print the document.
$word->Printout();

// closing word
$word->Quit();

// free the object
$word->Release();
$word = null;

?>
Mihael Peternelj; Slovenia 18-Oct-2003 05:22
If you wnat to connect to Access MDB Library you can use this small "progy". It works so, that if someone other accesses the library, it waits for so long to access it again because (as i know) MDB librarys can be accessed only once at the same time.

<?php
function mdb($sql, $array = 0, $base = "Base.mdb", $timelimit = 5)
    {
    $r_items = array();
    $c = new COM("ADODB.Connection");
    $r = false;
    $time = time();
    $process = $i = 0;
    while($r == false && $process <= $timelimit)
        {
        $deb = $c->open('DRIVER={Microsoft Access Driver (*.mdb)}; Dbq='. realpath($base) .';');
        $r = $c->execute($sql);
        $process = time() - $time;
        }
    if($process >= $timelimit) exit("mdbSQL Query Timeout!");
    if(strtolower(substr($sql, 0, 6)) == "insert" or strtolower(substr($sql, 0, 6)) == "update" or strtolower(substr($sql, 0, 6)) == "delete") return true;
    $num_fields = $r->fields->count();
    while (!$r->EOF)
        {
        for($j = 0; $j < $num_fields; $j++)
            {
            $key = $r->Fields($j);
            if($array == 0) $r_items[$i][$key->name] = $key->value;
            else $r_items[$i][$j] = $key->value;
            }
        $i++;
        $r->MoveNext();
        }
    $r->close();
    $c->close();
    $r = null;
    $c = null;
    return $r_items;
    }
?>

I got the source from the Manual, what i did is that i made it more compatible and user frendly. :)

I hope it could some day help someone so as it did me...

Greetings from Slovenia!

Mihael Peternelj
admin at CdnDomainRegistry dot ca 20-Sep-2003 03:57
Here's an example/comparison of VBScript vs PHP's COM component to connect to an IIS Webserver.
The examples backup the IIS MetaBase (your server's website(s) configuration) in IIS.

VBScript:
  Dim obj, iFlags
  Set obj = GetObject("IIS://LocalHost")
  ' Backup to next available version number.
  ' Set flags to save the metabase first and
  ' force the backup even if save fails.
  iFlags = (MD_BACKUP_SAVE_FIRST or MD_BACKUP_FORCE_BACKUP)
  obj.Backup "MyBackups", MD_BACKUP_NEXT_VERSION, iFlags
  ' Note: The above was copied from Microbucks.
  ' This is how you would have to do it.
  ' i.e. use the actual constant's value.
  iFlags = (2 or 4)
  obj.Backup "MyBackups", &HFFFFFFFF, iFlags

PHP:
  <?php
  $obj = new COM("IIS://LocalHost")or die("Unable to instantiate IIS");
  $err = com_invoke ($obj, "Backup", "MyBackups", "&HFFFFFFFF", 2|4 );
  $obj = null;
  print "err=".$err; // returns 0 on success
  ?>

Glen
20-Sep-2003 10:49
Example on how to read a registry value:

<?php
  $shell= &new COM('WScript.Shell');
  var_dump($shell->regRead('HKEY_CURRENT_USER\Environment\TEMP'));
?>

(outputs string(39) "%USERPROFILE%\Lokale Einstellungen\Temp" on my system)
EuresMan 01-Aug-2003 03:21
To mstaiger
I have encountered the same problem you report.
I tried to use the above code for a word document but it doesn't works, although the same code was good if i use it on a excel sheet.

The solution is explained at the following link :
http://www.phpbuilder.net/columns/venkatesan20030501.php3
rickardsjoquist at hotmail dot com 09-Jul-2003 10:33
If you want to use a DSN-less connection to a database (access for example) and return the results of a query as a multidimensional array with the fieldnames as identifier try this. Hope it helps someone :-)
--------------------------------------------------------

<?php
function db($sql) {
    $c = new COM("ADODB.Connection");
    $c->open('DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=' . realpath("relative_path/db.mdb"));
    $r = $c->execute($sql);
    $i = 0;
    $num_fields = $r->fields->count();
    while (!$r->EOF)
        {
            for($j = 0;$j<$num_fields;$j++) {
            $key = $r->Fields($j);
            $r_items[$i][$key->name] = $key->value;
        }
        $i++;
        $r->MoveNext();
    }
    $r->close();
    $c->close();
    $r = null;
    $c = null;
    return $r_items;
}
?>

--------------------------------------------------------
use it like this:
--------------------------------------------------------
<?php
$results = db("SELECT field_a, field_b FROM table");
foreach($result as $i => $item) {
    echo $item['field_a'];
    echo $item['field_b'];
}
?>
--------------------------------------------------------
You can also use: print_r($result); if you want the structure of the array to be printed.
info at sharedprojects dot nl 16-Jun-2003 09:41
<?php
// An other way to connect
// this connect to a ODBC-datasourced added in the
// ODBC Data Source Administrator under System DSN

$odbcname = "northwind";
$conn->Open("DSN=$odbcname");
?>
eguan1ao_at_yahoo_dot_com 20-Nov-2002 01:35
An example of connecting to a Microsoft Access database, executing an SQL query, and displaying the results in HTML.

<?php

$db = 'C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb';

$conn = new COM('ADODB.Connection');

// Two ways to connect. Choose one.
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$db");
//$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");

$sql = 'SELECT   ProductName, QuantityPerUnit, UnitPrice
         FROM     Products
          ORDER BY ProductName';
$rs = $conn->Execute($sql);

?>

<table>
<tr>
          <th>Product Name</th>
         <th>Quantity Per Unit</th>
         <th>Unit Price</th>
</tr>
<?php while (!$rs->EOF): ?>
         <tr>
                  <td><?= $rs->Fields['ProductName']->Value ?></td>
                   <td><?= $rs->Fields['QuantityPerUnit']->Value ?></td>
                  <td><?= $rs->Fields['UnitPrice']->Value ?></td>
          </tr>
         <?php $rs->MoveNext() ?>
<?php endwhile ?>
</table>

<?php

$rs->Close();
$conn->Close();

?>
kmason at avaya dot com 29-Jul-2002 09:56
It should be noted that to run anything that needs to interact with the UI (the word example), one needs to ensure that the process that the Web server is running under can access the UI.  For Apache, this is an option in the Services control panel.
nospam at zamang dot co dot uk 08-Jun-2002 03:20
The above Word example did not work for me when I tried it using Office 2000. I had to install the Office 2000 SR 2 upgrade to get everything working. It seems that the upgrade fixes some problems with permissions that affect PHP and some other applications that use COM.

David McCormack
yinon at xacct dot com 06-Apr-2002 12:33
In order to get the Word exaple running, do the following on the server side.
Worked for me...
1. Click START-->RUN and enter "dcomcnfg"
2. In the "Applications" tab, go down to "Microsoft Word Document"
3. Click PROPERTIES button
4. Go to the "Security" Tab
5. Click "Use custom access permissions", and then click EDIT
6. Click ADD and then click SHOW USERS
7. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD
8. Go back to the "Security" tab by hitting OK
9. Click "Use custom launch permissions", and the click EDIT
10. Click ADD and then click SHOW USERS
11. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD
12. Hit OK, and then hit APPLY.

Also, you should look at the "Identity" tab in the Microsoft Word Document PROPERTIES and see that it is set to "Interactive User"

ALSO, log into the machine AS the IUSR_<machinename> account, start word, and make sure to click through the dialog boxes that Word shows the first time it is run for a certain user.  In other words, make sure Word opens cleanly for the IUSR_ user.

More useful information could be found here:
http://www.email-screen.com/support-doc2txt.html
Franky at boucheros dot com 19-Mar-2002 06:38
For Access to Ms Access
use another Provider like this:

<?php
$conn = new COM("ADODB.Connection")
or die("Cannot start ADO");
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=./thefile.mdb;");
$rs = $conn->Execute("SELECT * FROM thetable");
?>
mstaiger at informatik dot uni-siegen dot de 23-Jan-2002 06:17
The example above (MS Word) is quiet unsatisfying, as I find. Especially since I couldn't find anybody who actually got it running, including myself.

You might therefore give this Powerpoint-example a chance:
----------------------------------
#Instantiate a PowerPoint object.
$ppoint = new COM("PowerPoint.application") or die("Unable to instantiate PowerPoint");

<?php
#Create a new presentation
$ppoint->Presentations->Add() or die ("Could not create presentation");

//Add a slide
$slide=$ppoint->Presentations[1]->Slides->Add(1,1);

//Get the name of this slide
$slidename = $slide->Name();
echo"<br>slidename : $slidename";

//Change the name of this new slide
$slide->Name = "New Slidename";
$slidename = $slide->Name();
echo"<br>NEW slidename : $slidename";

//Save the presentation
$ppoint->Presentations[1]->SaveAs("c:/InetPub/www/test.ppt");
$ppoint->Presentations[1]->Close();

//closing powerpoint
$ppoint->Quit();

//free the object
$ppoint->Release();
$ppoint = null;
-----------------------
?>

the config is :
w2k-server/office2k/iis5/php 4.1.1 isapi

If you happen to run into a working word2k-example, please let me know.

Marc
Arrays and Array-style COM properties
DOTNET
COM


The DOTNET class

(PHP 4 >= 4.1.0, PHP 5)

Description

The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.

$obj = new DOTNET("assembly", "classname")

Methods

DOTNET::DOTNET ( string $assembly_name , string $class_name [, int $codepage ] )

DOTNET class constructor. assembly_name specifies which assembly should be loaded, and class_name specifices which class in that assembly to instantiate. You may optionally specify a codepage to use for unicode string transformations; see the COM class for more details on code pages.

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.

Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.

Пример #1 DOTNET example

<?php
 $stack = new DOTNET("mscorlib", "System.Collections.Stack");
 $stack->Push(".Net");
 $stack->Push("Hello ");
 echo $stack->Pop() . $stack->Pop();
?>

Замечание:

You need to install the .Net runtime on your web server to take advantage of this feature.

User Contributed Notes

sandips (yardi) 29-Jun-2011 02:57
exercise to try different type of method signature and calling them in php.

VB.net Code
Public Class Class1
    Public Function SayHello(ByVal input As String) As String
        Return "Php input: " & input & "</BR>Dot net library said- 'Hello'"
    End Function
    Public Function ConcatArray(ByVal Values As Object()) As String
        Dim ret As String = String.Empty
        For Each sval As Object In Values
            ret = ret & sval.ToString & " "
        Next
        Return ret.Substring(1, ret.Length - 1)
    End Function
    Public Function ReturnObject(ByVal FirstName As String, ByVal LastName As String) As Name
        Dim obj As New Name
        obj.FirstName = FirstName
        obj.LastName = LastName
        Return obj
    End Function
'To explain Byref doesn't work with php
    Public Function CallByRef(ByRef value As String) As String
        value = "Value to ByRef parameter set in dot net."
        Return "ByRef CallByRef() method called."
    End Function
End Class

Public Class Name
    Public FirstName As String = String.Empty
    Public LastName As String = String.Empty
End Class

Php code to test .net library
<?php
  $class1 = new DOTNET("DotNetTest,"
              ."Version=1.0.0.0,"
                          ."Culture=neutral,"
                      ."PublicKeyToken=6675daefc27eafc4"
              ,"DotNetTest.Class1");
 echo $class1->SayHello("Hi PHP!!!!");
 echo "</P>";

 $parameter[0] = 12345;
 $parameter[1] = "MyString";
 $parameter[2] = false;
 $ret = $class1 -> ConcatArray($parameter);
 echo $ret;
 echo "</P>";

 $Obj = $class1 -> ReturnObject("Sandip","Shimpi");
 echo $Obj->FirstName." ".$Obj->LastName;

 echo "</P>";
 $myByRef = "";
 echo "Value of ByRef Variable before calling .net CallByRef() method: ".$myByRef;
 echo "</BR>";
 echo $class1 -> CallByRef($myByRef);
 echo "</BR>";
 echo "Now value of ByRef Variable: ".$myByRef;
 echo $myByRef;
?>
Anonymous 04-Jul-2010 05:17
As suggested before, you'll likely have to use a full assembly string including the assembly name, the assembly version (not the dll file version), the culture, and the public key token.  Otherwise, you'll get a 'file not found' catchable error.  To quickly find this on your own system to get the ball rolling, open C:\Windows\assembly in explorer (not in cmd as that shows a different view), scroll down the list until you find the assembly you want to work with, hover the mouse over it, and the tooltip shows the exact string to use (though processcorArchitecture if shown is optional).  You'll have to use .net utilities or other methods to automate collecting this info on other machines.

You'll also have to use the fully-qualified class name.  In other words, if you want to use the 'Form' class within 'System.Windows.Forms', you have to use the full class hierarchy 'System.Windows.Forms.Form'.  Otherwise you'll get an unhelpful 'Failed to instantiate .Net object' catchable error.

The following example shows the correct syntax to use the 'Form' class to pop up a blank form from php-cli, which can be used in leu of many Windows GUI PHP extensions out there.  Replace Version with your local version, and PublicKeyToken with your own local key token.

<?php

$full_assembly_string = 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a8425bc35256e463';
$full_class_name = 'System.Windows.Forms.Form';
$form = new DOTNET($full_assembly_string, $full_class_name);

// code to add buttons, menus, text, etc

$form->Show();

$form_event = '';
while($form_event !== 'close') {

  // handle form functions and events

  }
?>
murat at muratyaman dot co dot uk 11-Feb-2010 05:46
First, I hit the same mine:

"... Failed to instantiate .Net object [Unwrapped, QI for IDispatch] [0x80004002] No such interface supported ..."

In order to load the assembly and class in it successfully, I had to change my AssemblyInfo.cs file regarding the visibility of the types in it.

// some code above

// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(true)]

// some code below
m holmes at windowlogic dot com dot au 21-Sep-2009 09:31
For strongly-named NET assemblies that are registered in the GAC, you can just use the assembly name
e.g: $x = new DOTNET ("myAssembly", "myClass");

For strongly-named NET assemblies that aren't registered in the GAC, you need to use the full assembly string
e.g. $x = new DOTNET('myAssembly, Version=X.X.X.X, Culture=neutral, PublicKeyToken=ZZZZZZZZZZZZ', 'myClass');

You can't instantiate assemblies that haven't been strongly named.

"Strongly named" means that the assembly has a public key. To strongly name your own classes in Visual Studio, go to the Signing tab in the project properties and click the 'sign the assembly' box and choose a key file name.

To register an assembly in the GAC, there are various tools around to do that, but the easiest method is to drag-and-drop the compiled assembly into c:\windows\assembly using windows explorer (a shell extension is installed by default that handles registering dragged files).
kschroeder at mirageworks dot com 08-Apr-2009 11:55
In order to find out what the PublicKeyToken value is, open up Explorer and go to c:\windows\assembly.  In that directory you will see all of the registered assemblies along with their PublicKeyToken value.
Kai Sellgren 26-Mar-2009 09:14
My HTTPD crashed everytime I used this feature. To fix it, I had to switch to CGI and now everything works fine.
G dot B dot Yahav at Gmail dot com 05-Mar-2009 12:30
Here is a simple example using .NET Framework in PHP

<?php
$console = new DOTNET("mscorlib", "System.Console");
$varible = $console->ReadLine();
$console->WriteLine( "Varible: " . $varible );
$console->WriteLine();

unset( $varible );
unset( $console );
exit();
?>
sam at bitopia dot co dot uk 02-May-2008 08:54
If you want to load any other assembly apart from mscorlib, you'll need to include it like the following

$x = new DOTNET('The.Assembly.Name, Version=X.X.X.X, Culture=neutral, PublicKeyToken=ZZZZZZZZZZZZ', 'The.Class.Name');

Replace all relevant details.
COM
VARIANT
COM


VARIANT class

(PHP 4 >= 4.1.0, PHP 5)

Description

The VARIANT is COM's equivalent of the PHP zval; it is a structure that can contain a value with a range of different possible types. The VARIANT class provided by the COM extension allows you to have more control over the way that PHP passes values to and from COM.

$vVar = new VARIANT($var)

Methods

VARIANT::VARIANT ([ mixed $value [, int $type [, int $codepage ]]] )

VARIANT class constructor. Parameters:

value
initial value. if omitted, or set to NULL an VT_EMPTY object is created.
type
specifies the content type of the VARIANT object. Possible values are one of the VT_XXX Предопределенные константы. In PHP versions prior to PHP 5, you could force PHP to pass a variant object by reference by OR'ing VT_BYREF with the type. In PHP 5, this hack is not supported; instead, PHP 5 can detect parameters passed by reference automatically; they do not even need to be passed as VARIANT objects. Consult the MSDN library for additional information on the VARIANT type.
codepage
specifies the codepage that is used to convert strings to unicode. See the parameter of the same name in the COM class for more information.

PHP versions prior to PHP 5 define a number of (undocumented) virtual properties for instances of the VARIANT class; these properties have all been removed in PHP 5 in favour of its more natural syntax; these differences are best highlighted by example:

Пример #1 Variant example, PHP 4.x style

<?php
$v = new VARIANT(42);
print "The type is " . $v->type . "<br/>";
print "The value is " . $v->value . "<br/>";
?>

Пример #2 Variant example, PHP 5 style

<?php
$v = new VARIANT(42);
print "The type is " . variant_get_type($v) . "<br/>";
print "The value is " . $v . "<br/>";
?>

The reason for the change is that, internally, the COM extension sees VARIANT, COM and DOTNET classes as the same thing, and the design philosophy for these classes is that all property and member accesses are passed through to COM with no interference. The new syntax is more natural and less effort, and most of the removed virtual properties didn't make any sense in a PHP context in any case.

Замечание:

PHP 5 takes a much simpler approach to handling VARIANTs; when returning a value or fetching a variant property, the variant is converted to a PHP value only when there is a direct mapping between the types that would not result in a loss of information. In all other cases, the result is returned as an instance of the VARIANT class. You can force PHP to convert or evaluate the variant as a PHP native type by using a casting operator explicitly, or implicitly casting to a string by print()ing it. You may use the wide range of variant functions to perform arithmetic operations on variants without forcing a conversion or risking a loss of data.

See also variant_get_type().

User Contributed Notes

darren at dcook dot org 17-Jul-2007 05:59
If you are frustrated that print_r($obj) (where $obj is something returned from a call to a function on a COM object) does not return anything helpful, and that variant_get_type($obj) just returns a number, the function you are actually after is:
  com_print_typeinfo($obj);

It lists all functions, variables, their types in a human-readable (well, programmer-readable) format. Lovely!
mark dot pearson at capita dot co dot uk 29-Oct-2003 11:51
Running PHP 4.3.2 on Windows 2000 I had to use the following expression to create an empty Variant:

<?php
 $empty = new Variant(null);
 print $empty->type //     ==>   1
?>

NOT

<?php
 $empty = new Variant();
 print $empty->type //     ==>   0
?>

The two expressions return different Variant type values!
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:50
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.
alain at samoun dot com 02-Sep-2001 01:37
<?php
# I think that we need some examples of this thing:
# Lets define a real variant:
$varREAL=  new Variant("9.34 is a real number",VT_R8);
print "Value:". $varREAL->value; # Will print 9.34
# Now an integer
  $varINT=  new Variant("9.34 Printed as an integer",VT_INT);
print "Value:". $varINT->value; # Will print 9
# Now a string
  $varSTR=  new Variant("9.34 Printed as a string",VT_BSTR);
print "Value:". $varSTR->value; # Will 9.34 Printed as a string

?>
DOTNET
COM Функции
COM


COM Функции

Смотрите также

Для получения дальнейшей информации о COM прочтите» Спецификацию COM или, возможно, посмотрите библиотеку Don Box » Yet Another COM Library (YACL). Вы можете найти дополнительную информацию в нашем FAQ PHP и COM. Если вы хотите использовать приложение MS Office на стороне сервера, необходимо прочитать представленную здесь информацию:» Использование MS Office на стороне сервера.

Содержание

  • com_addref — Increases the components reference counter [deprecated]
  • com_create_guid — Generate a globally unique identifier (GUID)
  • com_event_sink — Connect events from a COM object to a PHP object
  • com_get_active_object — Returns a handle to an already running instance of a COM object
  • com_get — Gets the value of a COM Component's property [deprecated]
  • com_invoke — Calls a COM component's method [deprecated]
  • com_isenum — Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
  • com_load_typelib — Loads a Typelib
  • com_load — Creates a new reference to a COM component [deprecated]
  • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
  • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
  • com_propget — Псевдоним com_get
  • com_propput — Псевдоним com_set
  • com_propset — Псевдоним com_set
  • com_release — Decreases the components reference counter [deprecated]
  • com_set — Assigns a value to a COM component's property
  • variant_abs — Returns the absolute value of a variant
  • variant_add — "Adds" two variant values together and returns the result
  • variant_and — Performs a bitwise AND operation between two variants
  • variant_cast — Convert a variant into a new variant object of another type
  • variant_cat — concatenates two variant values together and returns the result
  • variant_cmp — Compares two variants
  • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
  • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
  • variant_div — Returns the result from dividing two variants
  • variant_eqv — Performs a bitwise equivalence on two variants
  • variant_fix — Returns the integer portion of a variant
  • variant_get_type — Returns the type of a variant object
  • variant_idiv — Converts variants to integers and then returns the result from dividing them
  • variant_imp — Performs a bitwise implication on two variants
  • variant_int — Returns the integer portion of a variant
  • variant_mod — Divides two variants and returns only the remainder
  • variant_mul — Multiplies the values of the two variants
  • variant_neg — Performs logical negation on a variant
  • variant_not — Performs bitwise not negation on a variant
  • variant_or — Performs a logical disjunction on two variants
  • variant_pow — Returns the result of performing the power function with two variants
  • variant_round — Rounds a variant to the specified number of decimal places
  • variant_set_type — Convert a variant into another type "in-place"
  • variant_set — Assigns a new value for a variant object
  • variant_sub — Subtracts the value of the right variant from the left variant value
  • variant_xor — Performs a logical exclusion on two variants

User Contributed Notes

eisfux.execbase.de 09-Jun-2010 04:15
DynamicWrapper|DynaWrap:
(The webpage given below seems to be gone away, too)

The latest dynwrap.dll (created by Michael Hines, Günter Born and Ton Plooy) is available for Win9x and a WinNT:

http://www.borncity.com/web/WSHBazaar1/WSHDynaCall.htm

Gilles Laurent has made an enhanced version which should work with Windows2000 and above:

http://glsft.free.fr/index.php?option=content&task=view&id=47
codeslinger at compsalot dot com 18-Dec-2009 02:59
it took me awhile to track this down, the website given below is long gone, and it was hard to find the new site, so thought I would post it here.

Here is the current website for DynamicWrapper
http://freenet-homepage.de/gborn/WSHBazaar/WSHDynaCall.htm

DynamicWrapper and WinBinder are dlls which enable php to call windows api's directly.

see notes below for an example of using DynamicWrapper.

It is an interesting alternative to http://www.winbinder.org  which does similar things.
larrywalker at at chelseagroton dot com 02-Sep-2008 08:53
To run a php script in a background process and pass it you var use

<?php

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("c:\\xampp\\php\\php.exe

c:\\xampp\\Not_on_Web\\ftptestback.php --user=$username", 7, false);

?>

Works for me.
monica at digitaldesignservices dot com 27-Dec-2007 02:41
Working with Word 2003 COM object.

Have you been trying to work with the Word.Application COM and the Word Document would crash and the PHP script would hang?

Turns out that there is an issue within the Office COM object that doesn't let the web application (IIS, Apache) scripting engine release the object after instancing the COM.  The Service Pack 3 office update claims to remedy this.  Will test and post findings.
Bandorka 12-Dec-2007 08:52
Guys, I found a way to pass parameters from PHP to Crystal Reports 11 without hanging!!!!

So the problem is the prompt for params dialog:

<?php
$ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport($my_report, 1);

$creport->Database->Tables->
Item(1)->ConnectionProperties['User ID'] =  'blablabla';

$creport->Database->Tables->
Item(1)->ConnectionProperties['Password'] = 'blablabla';

$creport->FormulaSyntax = 0;
$creport->RecordSelectionFormula= "{TABLENAME.FIELDNAME}='$USRID'";

//This is it, this avoids the hanging!
$creport->EnableParameterPrompting = 0;

$creport->DiscardSavedData;
$creport->ReadRecords();

//it is essential to assign the param values here after the readrecords otherwise you will not pass anything...

$zz= $creport->ParameterFields(1)->SetCurrentValue(500);

 $creport->ExportOptions->DiskFileName=$exp_pdf;
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=31;
  $creport->Export(false);

$creport->ExportOptions->DiskFileName=$exp_xls;
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=29;
  $creport->Export(false);

$len = filesize($exp_pdf);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=reportin.pdf");
readfile("reportin.pdf");

//------ Release the variables
$creport = null;
$crapp = null;
$ObjectFactory = null;
?>

Have fun,
Andras
tomfmason at nospam-gmail dot com 08-Oct-2007 07:26
To get the cpu load percentage you can do something like this.

<?php
$wmi = new COM('winmgmts://');
$processor = $wmi->ExecQuery("SELECT * FROM Win32_Processor");
foreach($processor as $obj){
    $cpu_load_time = $obj->LoadPercentage;
}
echo $cpu_load_time;
?>

reference http://msdn2.microsoft.com/en-us/library/aa394373.aspx

To list current apache instances

<?php
$wmi = new COM('winmgmts://');
$processes = $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'httpd.exe'");
foreach($processes as $process){
    echo $process->CommandLine . "<br />";
    echo $process->ProcessId . "<br />";
}
?>

reference http://msdn2.microsoft.com/en-us/library/aa394372.aspx

To run a php script in a background process

<?php
$dir = "C:\\path\\to\\dir";
$php_path = "C:\\path\\to\\php.exe";
$file = "somescript.php";
//send time current timestamp
$cmd_options = "-t " . time();
$wscript = new COM('WScript.Shell');
$wscript->Run("cmd /K CD $php_path $dir\\$file  &  ", 0, false);
?>

Enjoy

Tom
sk89q 27-Sep-2007 11:13
The only way I've been able to call Win32 API functions with PHP5 has been through COM and DynamicWrapper.

Here's an example to play a beep sound with your computer speaker:
<?php
$com = new COM("DynamicWrapper");
$com->Register("KERNEL32.DLL", "Beep", "i=ll", "f=s", "r=l");
$com->Beep(5000, 100);
?>
naveed at php dot net 10-Mar-2007 05:24
Here is a spell check implementation that displays the suggestion list for each misspelled word.

<?php
function SpellCheck($input)
{
    $word=new COM("word.application") or die("Cannot create Word object");
    $word->Visible=false;
    $word->WindowState=2;
    $word->DisplayAlerts=false;
    $doc=$word->Documents->Add();
    $doc->Content=$input;
    $doc->CheckSpelling();
    $result= $doc->SpellingErrors->Count;
    if($result!=0)
    {
        echo "Input text contains misspelled words.\n\n";
        for($i=1; $i <= $result; $i++)
        {
            echo "Original Word: " .$doc->SpellingErrors[$i]->Text."\n";
            $list=$doc->SpellingErrors[$i]->GetSpellingSuggestions();
            echo "Suggestions: ";
            for($j=1; $j <= $list->Count; $j++)
            {
                $correct=$list->Item($j);
                echo $correct->Name.",";
            }
            echo "\n\n";
        }
    }
    else
    {
        echo "No spelling mistakes found.";
    }
    $word->ActiveDocument->Close(false);
    $word->Quit();
    $word->Release();
    $word=null;
}

$str="Hellu world. There is a spellling error in this sentence.";
SpellCheck($str);
?>
Francois-R dot Boyer at PolyMtl dot ca 13-Feb-2007 08:32
I had the problem when trying to call Access VBA scripts from PHP; the call was working but Access would never quit.  The problem was that the Apache server is running as SYSTEM, and not a user we normally use to run Office.  And as the first time a user runs Office, it asked the SYSTEM user to enter its name and initials! ;-)

To correct this problem: Stop Apache, go to Services, Apache, Properties, "Log On" tab, and check "Allow service to interact with desktop.  Restart Apache, then open your office application, in a page loaded by the Apache server, with a small PHP code like this, :

<?php
$app = new COM("Access.Application"); // or Word.Application or Excel.Application ...
$app->Visible = true; // so that we see the window on screen
?>

Put the name you want and quit the application.  Now your Office application should terminate correctly the next time you load it with a COM object in PHP.  You can stop Apache uncheck the "Allow service to interact with desktop", and restart Apache if you like.  I don't even require a Quit or anything to be sent to Access, it quits automatically when PHP terminates.

And for those who wish to know how I'm calling Access VBA scripts, instead of using ODBC or any other way to send SQL requests, which does not seem to work to call VBA scripts, I open the database as a COM object and it works fine:

<?php
$db_com = new COM("pathname of the file.mdb");
$result = $db_com->Application->Run("function_name", 'param1', 'param2', '...');
?>
wiliamfeijo at gmail dot com 05-Feb-2007 12:10
This code use a Crystal Reports file with a connection on
 Oracle 9i Database, suports manipulate and refresh data
 and export to PDF file:

------ REMEMBER ------
These functions are only available if you had instaled the
Crystal Reports Developer Edition. Catch the trial on the
http://www.businessobjects.com web site.

<?php
//------  Variables ------
$my_report = "C:\\rel_apontamento.rpt";
$my_pdf = "C:\\teste.pdf";

//------ Create a new COM Object of Crytal Reports XI ------
$ObjectFactory= new
 COM("CrystalReports11.ObjectFactory.1");

//------ Create a instance of library Application -------
$crapp
=$ObjectFactory->
CreateObject("CrystalDesignRunTime.Application.11");

//------ Open your rpt file ------
$creport = $crapp->OpenReport($my_report, 1);

//------ Connect to Oracle 9i DataBase ------
$crapp->LogOnServer('crdb_oracle.dll','YOUR_TNS',
'YOUR_TABLE','YOUR_LOGIN','YOUR_PASSWORD');

//------ Put the values that you want --------
$creport->RecordSelectionFormula=
"{YOUR_TABLE.FIELD}='ANY_VALUE'";

//------ This is very important. DiscardSavedData make a
 Refresh in your data -------
$creport->DiscardSavedData;

//------ Read the records :-P -------
$creport->ReadRecords();

//------ Export to PDF -------
$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->FormatType=31;
$creport->ExportOptions->DestinationType=1;
$creport->Export(false);

//------ Release the variables
$creport = null;
$crapp = null;
$ObjectFactory = null;
?>

It's functional and perfectly !!!!!!!

Thanks.....
03-Oct-2006 04:11
If someone want to get a COM object out of a DCOM object can do something like that:

<?php
  $dcom_obj = new COM('dacom.object','remotehost') or die("Unable to get DCOM object!");
  $com_obj = new Variant(NULL);
  $dcom_obj->Get_Module($com_obj); //user function which returns a custom IDispatch (casted as variant*)
?>

Hopefully this will help someone, because it took me quite long to figure this out.
kiotech at hotmail dot com 18-Jul-2006 06:35
For use parameters with PHP this is a Code Example

<?php
$ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport("//report1.rpt", 1);

      $z= $creport->ParameterFields(1)->SetCurrentValue("Mango");
      $z= $creport->ParameterFields(2)->SetCurrentValue(5000);

  $creport->ExportOptions->DiskFileName="reportin.pdf";
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=31;
  $creport->Export(false);

$len = filesize("reportin.pdf");
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=reportin.pdf");
readfile("reportin.pdf");
?>
a dot kulikov at pool4tool dot com 13-Mar-2006 09:36
In case you are wondering how to group rows or columns in the freshly created EXCEL files, then this may help you

<?php
   /***
    * Grouping Rows optically in Excel Using a COM Object
    *
    * That was not easy, I have spent several hours of trial and error to get
    * this thing to work!!!
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @since  13.03.2006
    *
    * @see    Open Excel, Hit Alt+F11, thne Hit F2 -- this is your COM bible
    ***/

   //starting excel
   $excel = new COM("excel.application") or die("Unable to instanciate excel");
   print "Loaded excel, version {$excel->Version}\n";

   //bring it to front
   #$excel->Visible = 1;//NOT

   //dont want alerts ... run silent
   $excel->DisplayAlerts = 0;

   //create a new workbook
   $wkb = $excel->Workbooks->Add();

   //select the default sheet
   $sheet=$wkb->Worksheets(1);

   //make it the active sheet
   $sheet->activate;

   //fill it with some bogus data
   for($row=1;$row<=7;$row++){
       for ($col=1;$col<=5;$col++){

          $sheet->activate;
          $cell=$sheet->Cells($row,$col);
          $cell->Activate;
          $cell->value = 'pool4tool 4eva ' . $row . ' ' . $col . ' ak';
       }//end of colcount for loop
   }

   ///////////
   // Select Rows 2 to 5
   $r = $sheet->Range("2:5")->Rows;

   // group them baby, yeah
   $r->Cells->Group;

   // save the new file
   $strPath = 'tfile.xls';
   if (file_exists($strPath)) {unlink($strPath);}
   $wkb->SaveAs($strPath);

   //close the book
   $wkb->Close(false);
   $excel->Workbooks->Close();

   //free up the RAM
   unset($sheet);

   //closing excel
   $excel->Quit();

   //free the object
   $excel = null;
?>
Pedro Heliodoro 05-Mar-2006 02:38
Using the Windows Media Player OCX and the latest snap of PHP 5.1 i was able to eject a CD-ROM drive

<?php
//create an instance of Windows Media Player
$mp = new COM("WMPlayer.OCX");
//ejects the first cd-rom on the drive list
$mp->cdromcollection->item(0)->eject();

?>
vedanta dot barooah at gmail dot com 29-Jan-2006 07:59
Microsoft provides two binaries to create windows services: INSTSRV.EXE and SRVANY.EXE, using these php scripts can be run as windows services.

More information is available at: http://support.microsoft.com/?kbid=137890
sadi at unicornsoftbd dot com 17-Nov-2005 04:18
There's no way to use static dlls in php. only way to use a dll in php is to make it a com object first and then using it in php like this

<?php
$NewCom=new COM("uni.example");
?>

once we created the COM object this can be used like any other php classes.
                       sadi
                       www.unicornsoftbd.com
allan666 at gmail dot com 29-Sep-2005 03:37
If you are using a COM object that opens windows or dialogs (like Office applications), those windows or dialogs will not appear and will stay invisible even if you use codes like

$word->visible = true;

To solve this problem, go to the web service properties (Administrative Tools) and click (in the Logon TAB) "Allow the Service to Iterate with desktop".

This explain lots of problems to close applications. When you try to close, the dialos asking to save the file must appear, but only in the option to iterate with desktop is on.

Hope it helps.
dazb@localhost 26-May-2005 01:53
For permissions problems, etc. including "Could Not Open Macro Storage" with Word;
How To Configure Office Applications to Run Under the Interactive User Account

http://theether.net/download/Microsoft/kb/288366.html

[EDITOR NOTE: As reported by "damir@example", the link originally provided in this note is dead. The note was updated with a new link sent from "damir". - Editor thiago AT php DOT net]
mpg123 at thinstall dot com 09-May-2005 01:21
I found the lack of good online docs about how to access a windows environment very frustrating.  I finally found something here: http://www.sitepoint.com/forums/showthread.php?t=92358 but it's a php4 way.  I cleaned up the code, added introspection for methods and voila.  Thanks and credit to the original posters.

<?php
// php translation of asp script by Bill Wooten from
// http://www.4guysfromrolla.com/webtech/082802-1.shtml
function showServices($vComputerName, $vClass)  {
    $objLocator = new COM("WbemScripting.SWbemLocator");

    if($vComputerName == "") $objService = $objLocator->ConnectServer();
    else                     $objService = $objLocator->ConnectServer($vComputerName);

    $objWEBM = $objService->Get($vClass);
    $objProp = $objWEBM->Properties_;
    $objMeth = $objWEBM->Methods_;

    foreach($objMeth as $methItem) echo "Method: " . $methItem->Name ."\r\n";

    echo "\r\n";

    $objWEBMCol = $objWEBM->Instances_();

    foreach($objWEBMCol as $objItem) {

        echo "[" . $objItem->Name . "]\r\n";

        foreach($objProp as $propItem) {
           $tmp = $propItem->Name;
           echo "$tmp: " . $objItem->$tmp . "\r\n";
        }

         echo "\r\n";
    }
}

// Test the function:
showServices("", "Win32_Processor");
showServices("", "Win32_LogicalDisk");
angelo [at] mandato <dot> com 25-Apr-2005 09:11
ADO + PHP5 + SQL DATE FIELDS

Using a COM("ADODB.Connection") object in PHP4 and PHP5 to return date fields in databases will have different results.

In PHP4, the date is returned as a string as represented in the database.  In my case, '2005-04-11 11:35:44'.

In PHP5, the date is returned as a VARIANT type, when printed or implicitly casted would result as '4/11/2005 11:35:44 AM'.

For this example, the solution is to use the variant conversion function variant_date_to_timestamp() to convert the value to a Unix timestamp.

Please refer to this as an example.  Other date types may be converted using one of the other variant_<convert> functions.
bruce at yourweb dot com dot au 23-Apr-2005 05:47
Simple convert xls to csv
<?php
// starting excel
$excel = new COM("excel.application") or die("Unable to instanciate excel");
print "Loaded excel, version {$excel->Version}\n";

//bring it to front
#$excel->Visible = 1;//NOT
//dont want alerts ... run silent
$excel->DisplayAlerts = 0;

//open  document
$excel->Workbooks->Open("C:\\mydir\\myfile.xls");
//XlFileFormat.xlcsv file format is 6
//saveas command (file,format ......)
$excel->Workbooks[1]->SaveAs("c:\\mydir\\myfile.csv",6);

//closing excel
$excel->Quit();

//free the object
$excel->Release();
$excel = null;
?>
Jack dot CHLiang at gmail dot com 10-Apr-2005 10:02
If you want to search an Excel file and don't connect with ODBC, you can try the function I provide. It will search a keyword in the Excel find and return its sheet name, text, field and the row which found the keyword.

<?php

// The example of print out the result
$result = array();
searchEXL("C:/test.xls", "test", $result);

foreach($result as $sheet => $rs){
    echo "Found at $sheet";

    echo "<table width=\"100%\" border=\"1\"><tr>";

    for($i = 0; $i < count($rs["FIELD"]); $i++)
        echo "<th>" . $rs["FIELD"][$i] . "</th>";

    echo "</tr>";

    for($i = 0; $i < count($rs["TEXT"]); $i++) {
        echo "<tr>";

        for($j = 0; $j < count($rs["FIELD"]); $j++)
            echo "<td>" . $rs["ROW"][$i][$j] . "</td>";

        echo "</tr>";
    }
    echo "</table>";

}

/**
 * @param $file string The excel file path
 * @param $keyword string The keyword
 * @param $result array The search result
 */

function searchEXL($file, $keyword, &$result) {
       $exlObj = new COM("Excel.Application") or Die ("Did not connect");
       $exlObj->Workbooks->Open($file);
       $exlBook = $exlObj->ActiveWorkBook;
       $exlSheets = $exlBook->Sheets;

       for($i = 1; $i <= $exlSheets->Count; $i++) {
           $exlSheet = $exlBook->WorkSheets($i);

           $sheetName = $exlSheet->Name;

           if($exlRange = $exlSheet->Cells->Find($keyword)) {
            $col = 1;
            while($fields = $exlSheet->Cells(1, $col)) {
                        if($fields->Text == "")
                    break;

                $result[$sheetName]["FIELD"][] = $fields->Text;
                $col++;
            }

            $firstAddress = $exlRange->Address;
            $finding = 1;
            $result[$sheetName]["TEXT"][] = $exlRange->Text;

            for($j = 1; $j <= count($result[$sheetName]["FIELD"]); $j++) {
                $cell = $exlSheet->Cells($exlRange->Row ,$j);
                $result[$sheetName]["ROW"][$finding - 1][$j - 1] = $cell->Text;
            }

            while($exlRange = $exlRange->Cells->Find($keyword)) {
                   if($exlRange->Address == $firstAddress)
                    break;

                $finding++;
                $result[$sheetName]["TEXT"][] = $exlRange->Text;

                for($j = 1; $j <= count($result[$sheetName]["FIELD"]); $j++) {
                    $cell = $exlSheet->Cells($exlRange->Row ,$j);
                    $result[$sheetName]["ROW"][$finding - 1][$j - 1] = $cell->Text;
                }

            }

           }

    }

   $exlBook->Close(false);
   unset($exlSheets);
   $exlObj->Workbooks->Close();
   unset($exlBook);
   $exlObj->Quit;
   unset($exlObj);
}
?>

For more information, please visit my blog site (written in Chinese)
http://www.microsmile.idv.tw/blog/index.php?p=77
Gianluca GIMIGLIANO 13-Mar-2005 09:17
NOTE: Using COM with windows XP with apache as a service
 - Compact a Microsoft Access Database
Be careful $sourceFile and $destFile cannot be the same and $destFile must be unexistent

<?php
Function CompactMSAccess($sourceFile,$destFile) {
$com = new COM("JRO.JetEngine");
$com->CompactDatabase("Data Source=$sourceFile",
"Data Source=$destFile");
$com->Release();
$com=null;
return is_file($destFile);
//if $destFile exists it's a compact DB
}

CompactMSAccess('C:\directory\source.mdb',
'C:\directory\compact.mdb');
?>
michael at example dot com 23-Feb-2005 12:42
After alot of trouble with IIS 6/Windows 2003 and PHP 5.0.2 I figured out how to use Imagemagick COM+/OLE interface. Seems you have to recreate the COM object after each convert() otherwise it will sometimes fail with very strange errors, since the PHP COM interface is not as stable as the old ASP one apparently is.
pelegk2 at walla DOT co DOT il 13-Feb-2005 08:49
Printing to a network printer :
read this note for :

NOTE: Using COM with windows NT/2000/XP with apache as a service
- Run dcomcnfg.exe
- Find word application and click properties
- Click the Security tab
- Use Custom Access Permissions
- Add the user who runs the web server service
- Use Custom Launch permissions
- Add the user who runs the web server service

THEN

<?php
// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";

// bring it to front
$word->Visible = 1;
//this is for example a printer on my network
$word->ActivePrinter = "\\\\192.168.4.201\\printer1";

// Open a word document, or anything else that word
// can read
$input ="c:\\test.html";
$word->Documents->Open($input);

$word->ActiveDocument->PrintOut();

// closing word
$word->Documents[1]->Close(false);
$word->Quit();

// free the object
$word->Release();
$word = null;
unset($word);
?>
06-Jan-2005 09:11
if you want to add a new hyperlink with excel :

<?php
$cell=$sheet->Range('O'.$j);
$cell->Hyperlinks->Add($cell ,'here_your_file');
?>

I write this note because is very difficult to find
the good method to do that .

Merci beaucoup
sorin dot andrei at mymail dot ro 25-Sep-2004 02:24
[Editor's Note:
Serializing the object, storing it and then (on the next page) unserializing it WILL work.
End Note]

the big problem for PHP is it can't save in session an COM object

an samples code is here. This works just first time, then give the error:
Call to undefined method com::Refresh() on line  $mMap->Refresh();
the reson is he can't save the object $mMap in session

<?php
    session_start();
      if (isset($_SESSION['map'])) {
            $mMap = $_SESSION['map'];
        }
        else
        {
        $ArcIMSConnector = new COM ("aims.ArcIMSConnector")  or die("can not create AIMS message object");
            echo "Loaded ArcIMSConnector, <br>";
            $ArcIMSConnector->ServerName = "map.sdsu.edu";
            $ArcIMSConnector->ServerPort = 5300;

            $mMap = new COM ("aims.Map")  or die("can not create aims.Map message object");
            echo "Loaded aims.Map, <br>";
            print "AIMS-ServerName= $ArcIMSConnector->ServerName <br>";

            $resultInit= $mMap->InitMap($ArcIMSConnector,"Worldgeography");

            $mMap->Width    = 400;            //                                'Width of the map in pixels
            $mMap->Height   = 300;            //                                'Height of the map in pixels
            $mMap->BackColor = 15130848;
            $_SESSION['map'] = $mMap;
        }

    $resultRefresh = $mMap->Refresh();                                //Refresh the map
    $urlImage      = $mMap->GetImageAsUrl();
    print "<br>urlImage=$urlImage<br>";

    print "<br><IMG SRC='$urlImage'>";

/*
    $ArcIMSConnector->Release();
    $ArcIMSConnector = null;

    $mMap->Release();
    $mMap = null;
*/

?>
ferozzahid [at] usa [dot] com 24-Aug-2004 12:06
To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it.

As an example, calling a function that retrieves the name of a person will look like:

<?php
$Name = new VARIANT;

$comobj = new COM("MyCOMOBj.Component") or die("Couldn't create the COM Component");

if(!$comobj->GetName($Name)) {
    echo("Could not retrieve name");
}
else {
    echo("The name retrieved is : " . $Name->value);
}
?>

$Name->type will contain the type of the value stored in the VARIANT e.g. VT_BSTR.

Note For PHP 5:

Insted of '$Name->value', we can use only '$Name' for getting the value stored in the VARIANT. To get the type of the value stored in the VARIANT, use 'variant_get_type($Name)'.

Feroz Zahid
Shawn Coppock 11-Aug-2004 01:15
For those of us that are not experts with object models, if you have Microsoft Excel or Microsoft Word available, go into the Visual Basic Editor (Alt+F11). Now you can open the object browser window (F2) and see what you find.

If you select "Word" in the object browser, then the classes and members of that class are displayed below. For example, if you click on "Selection" in the classes column, and then "Font" in the members column, you will then see "Property Font As Font Member of Word.Selection" displayed at the bottom. Click on the "Font" link there.

Click on Word "Selection" again in the classes column, and then "PageSetup" in the members column, you will then see "Property PageSetup As PageSetup Member of word.Selection" displayed at the bottom. Click on the "PageSetup" link there.

Using the above examples, you can now formulate your Word Document from php. Here is a simple example that creates a 1 & 1/2" space for text based on the margin settings & with dark red text and an 8pt Helvetica font face:

<?php
$content = "Insert Sample Text Here\n\nThis starts a new paragraph line.";
$word= new COM("word.application") or die("Unable to create Word document");
print "Loaded Word, version {$word->Version}\n";
$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '3"';
$word->Selection->PageSetup->RightMargin = '4"';
$word->Selection->Font->Name = 'Helvetica';
$word->Selection->Font->Size = 8;
$word->Selection->Font->ColorIndex= 13; //wdDarkRed = 13
$word->Selection->TypeText("$content");
$word->Documents[1]->SaveAs("some_tst.doc");
$word->quit();
echo "done";
?>

This example (and others) worked for me with Microsoft Word 10.0 Object Library (MS Word 2002), Apache & PHP on Windows XP. Experimenting using the Visual Basic editor will yield some amazing documents from PHP as it will help you see the relationships of the objects used and give you an idea as to how to construct your code. But be prepared for an occaisional PHP.exe crash if your code is way off base.

Hope this helps!
Jason Neal 21-Jul-2004 12:48
If you are having issues with the outlook.application locking up when you try to access it, ensure that your apache server is running in the context of a user on the machine instead of the system account.
angelo [at] mandato <dot> com 03-Jun-2004 11:37
Useful PHP MSWord class I created to do some simple file conversions.  This class could have a lot more to it but I am not familiar with all the COM MS Word function calls.
<?php
    // msword.inc.php

    // NOTE: Using COM with windows NT/2000/XP with apache as a service
    // - Run dcomcnfg.exe
    // - Find word application and click properties
    // - Click the Security tab
    // - Use Custom Access Permissions
    //      - Add the user who runs the web server service
    // - Use Custom Launch permissions
    //      - Add the user who runs the web server service

    $wdFormatDocument = 0;
    $wdFormatTemplate = 1;
    $wdFormatText = 2;
    $wdFormatTextLineBreaks = 3;
    $wdFormatDOSText = 4;
    $wdFormatDOSTextLineBreaks = 5;
    $wdFormatRTF = 6;
    $wdFormatUnicodeText = 7;
    $wdFormatHTML=8;

    class MSWord
    {
        // Vars:
        var $handle;

        // Create COM instance to word
        function MSWord($Visible = false)
        {
            $this->handle = new COM("word.application") or die("Unable to instanciate Word");
            $this->handle->Visible = $Visible;
        }

        // Open existing document
        function Open($File)
        {
            $this->handle->Documents->Open($File);
        }

        // Create new document
        function NewDocument()
        {
            $this->handle->Documents->Add();
        }

        // Write text to active document
        function WriteText( $Text )
        {
            $this->handle->Selection->Typetext( $Text );
        }

        // Number of documents open
        function DocumentCount()
        {
            return $this->handle->Documents->Count;
        }

        // Save document as another file and/or format
        function SaveAs($File, $Format = 0 )
        {
            $this->handle->ActiveDocument->SaveAs($File, $Format);
        }

        // Save active document
        function Save()
        {
            $this->handle->ActiveDocument->Save();
        }

        // close active document.
        function Close()
        {
            $this->handle->ActiveDocument->Close();
        }

        // Get word version
        function GetVersion()
        {
            return $this->handle->Version;
        }

        // get handle to word
        function GetHandle()
        {
            return $this->handle;
        }

        // Clean up instance with word
        function Quit()
        {
            if( $this->handle )
            {
                // close word
                $this->handle->Quit();

                // free the object
                $this->handle->Release();
                $this->handle = null;
            }
        }
    };

?>

Example 1, opens an html file, writes text to it, then saves it as a document:
<?php
    $input = "C:\\test.htm";
    $output = "C:\\test.doc";

    $Word = new MSWord;
    $Word->Open($input);
    $Word->WriteText("This is a test ");
    $Word->SaveAs($output);
    $Word->Quit();
?>

Example 2, opens an html file, then saves it as a rtf file:
<?php
    $input = "C:\\test.htm";
    $output = "C:\\test.rtf";

    $Word = new MSWord;
    $Word->Open($input);
    $Word->SaveAs($output, $wdFormatRTF);
    $Word->Quit();
?>
angelo [at] mandato <dot> com 18-May-2004 04:30
Useful PHP functions I created (similar to other standard PHP database functions) for working with an ADO datasource:
<?php
    // ado.inc.php

    $ADO_NUM = 1;
    $ADO_ASSOC = 2;
    $ADO_BOTH = 3;

    function ado_connect( $dsn )
    {
        $link = new COM("ADODB.Connection");
        $link->Open($dsn);
        return $link;
    }

    function ado_close( $link )
    {
        $link->Close();
    }

    function ado_num_fields( $rs )
    {
        return $rs->Fields->Count;
    }

    function ado_error($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Number;
    }

    function ado_errormsg($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Description;
    }

    function ado_fetch_array( $rs, $result_type,  $row_number = -1 )
    {
        global $ADO_NUM, $ADO_ASSOC, $ADO_BOTH;
        if( $row_number > -1 ) // Defined in adoint.h - adBookmarkFirst    = 1
            $rs->Move( $row_number, 1 );

        if( $rs->EOF )
            return false;

        $ToReturn = array();
        for( $x = 0; $x < ado_num_fields($rs); $x++ )
        {
            if( $result_type == $ADO_NUM || $result_type == $ADO_BOTH )
                $ToReturn[ $x ] = $rs->Fields[$x]->Value;
            if( $result_type == $ADO_ASSOC || $result_type == $ADO_BOTH )
                $ToReturn[ $rs->Fields[$x]->Name ] = $rs->Fields[$x]->Value;
        }
        $rs->MoveNext();
        return $ToReturn;
    }

    function ado_num_rows( $rs )
    {
        return $rs->RecordCount;
    }

    function ado_free_result( $rs )
    {
        $rs->Close();
    }

    function ado_query( $link, $query )
    {
        return $link->Execute($query);
    }

    function ado_fetch_assoc( $rs,  $row_number = -1 )
    {
        global $ADO_ASSOC;
        return  ado_fetch_array( $rs, $ADO_ASSOC, $row_number);
    }

    function ado_fetch_row( $rs,  $row_number = -1 )
    {
        global $ADO_NUM;
        return ado_fetch_array( $rs, $ADO_NUM, $row_number);
    }

    // Extra functions:
    function ado_field_len( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Precision;
    }

    function ado_field_name( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Name;
    }

    function ado_field_scale( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->NumericScale;
    }

    function ado_field_type( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Type;
    }

?>

The aod version was a typo.
markshane1 at fuse dot net 10-May-2004 04:41
Here is a COM function that creates an excel spreadsheet with any number of worksheets, containing data from a matching number of SQL queries.  Be ware of the upper limit of excel worksheets.  This function properly shuts down Excel on the server.

<?php
/***************************/
    function WriteExcel($strPath,$astrSheetName,$astrSQL){
/* This function takes a file save path, and array of sheet names and a corresponding array */
/* of SQL queries for each sheet and created a multi-worksheet excel spreadsheet*/
    $C_NAME=__CLASS__."::".__FUNCTION__;
        $dbs=new clsDB;
        $exapp = new COM("Excel.Application") or Die ("Did not connect");
        $intSheetCount=count($astrSheetName);
        $wkb=$exapp->Workbooks->Add();
            $exapp->Application->Visible = 1;
        for ($int=0;$int<$intSheetCount;$int++){
            $sheet=$wkb->Worksheets($int+1);
            $sheet->activate;
            $sheet->Name=$astrSheetName[$int];
            $intRow=1;
            $qrySQL=$dbs->GetQry($astrSQL[$int],$C_NAME,__LINE__);
            $rstSQL=$qrySQL->fetchRow(DB_FETCHMODE_ASSOC);
            $astrKeyNames=array_keys($rstSQL);
            $intCols=count($astrKeyNames);
            $qrySQL=$dbs->GetQry($astrSQL[$int],$C_NAME,__LINE__);
            while($rstSQL=$qrySQL->fetchRow(DB_FETCHMODE_ASSOC)){
                $strOut="";//initialize the output string
                for ($int2=0;$int2<$intCols;$int2++){//we start at 1 because don't want to output the table's index
                    if($intRow==1){
                        $strOut=$astrKeyNames[$int2];
                    }else{
                        $strOut=$rstSQL[$astrKeyNames[$int2]];
                    }
                        $sheet->activate;
                        $cell=$sheet->Cells($intRow,($int2+1));//->activate;
                        $cell->Activate;
                          $cell->value = $strOut;
                    }//end of colcount for loop
                $intRow++;
            }//end while loop
        }//end sheetcount for loop
        if (file_exists($strPath)) {unlink($strPath);}
        $wkb->SaveAs($strPath);
        $wkb->Close(false);
        unset($sheet);
        $exapp->Workbooks->Close(false);
        unset($wkb);
        $exapp->Quit;
        unset($exapp);
        unset($dbs);
    }//function WriteExcel
?>
Haseldow 05-Apr-2004 05:31
Simple example for creating your own dll's which can be called as COM objects in PHP:

First create your ActiveX dll (Visual Basic):
Name your project as "foo" and class as "bar".

'---start VB code---
Public Function hello() As String
    hello = "Hello World!"
End Function
'---end VB code---

Then make the dll and register it with regsvr32.exe

Now create your PHP script:

<?php
$obj = new COM("foo.bar");
$output=$obj->hello(); // Call the "hello()" method
echo $output; // Displays Hello World! (so this comes from the dll!)
?>
mark dickens at mindspring dot com 29-Feb-2004 08:03
Just a note to those wanting to use COM to interface to printers under Windows 2000/XP.  If it doesn't work or seems to hang, try changing the logon identity under which the Apache (assuming you're using Apache) service is running from the System account to another account.  By default most services will install to run under the System account and although the System account has total authority on the computer it is running on, it has no authority outside of that realm as I understand it.  Apparently accessing printers is considered "outside the realm".  I used this technique to interface a Dymo thermal label printer to my server and it works now.
platiumstar at canada dot com 12-Feb-2004 03:08
I didn't found any working examples of PHP using the MSMQ COM object, so I made up one, thought I share it with everybody..it works ok.
You have to create a local Public message queue named "TestQueue" first.

<?php
define(MQ_SEND_ACCESS , 2);
define(MQ_DENY_NONE , 0);

$msgQueueInfo =  new COM("MSMQ.MSMQQueueInfo") or die("can not create MSMQ Info object");
$msgQueueInfo->PathName = ".\TestQueue";

$msgQueue =  new COM("MSMQ.MSMQQueue") or die("can not create MSMQ object");
$msgQueue=$msgQueueInfo->Open(MQ_SEND_ACCESS, MQ_DENY_NONE );

$msgOut = new COM("MSMQ.MSMQMessage") or die("can not create MSMQ message object");
$msgOut->Body = "Hello world!";
$msgOut->Send($msgQueue);

$msgQueue->Close();
unset($msgOut);
unset($msgQueue);
unset($msgQueueInfo);
?>

enjoy
PS
kleontiv -at- combellga -dot- ru 15-Dec-2003 11:47
And here is an example of using ADSI via ADODB. This sample is unique because only ADODB can provide recursive Active directory searching and listing. But ADODB can only READ Active directory. So you can find something by ADODB and then modify that directly by ADSI.

With previos example this help build you PHP coded interface to Menaging and browsing Microsoft Active Directory.

Also ADODB on ADSI helps you sort recordset and search on it.

<?php

$objConnection = new COM ("ADODB.Connection") ;
$objConnection->Open("Provider=ADsDSOObject;user id=DOMAIN\\login;password=your_passowrd;") ;

$objCommand = new COM("ADODB.Command") ;
$objCommand->ActiveConnection = $objConnection ;

$Cmd  = "<LDAP://dc=mydomain,dc=com>;" ;
$Cmd .= "(&(objectClass=user)(mail=*)(!cn=SystemMailbox*));" ;
$Cmd .= "name,mail,telephoneNumber;subtree" ;

$objCommand->Properties['Sort On']->Value = "name" ;

$objCommand->CommandText = $Cmd ;
$objRecordSet = $objCommand->Execute() ;

$OrderNumber = 0 ;
while(!$objRecordSet->EOF())
 {
  $OrderNumber ++ ;
  $nn = $objRecordSet->Fields['name']->Value ;
  $mm = $objRecordSet->Fields['mail']->Value ;
  $ph = $objRecordSet->Fields['telephoneNumber']->Value ;
  echo "$OrderNumber: $nn mail: $mm phone: $ph<br>" ;
  $objRecordSet->MoveNext() ;
 }

Echo "===========================<br>" ;
Echo "All MailBoxes: " ;
Echo $objRecordSet->RecordCount() ;
$objRecordSet->Close() ;
$objCommand->Close() ;
$objConnection->Close() ;

unset($objRecordSet) ;
unset($objCommand) ;
unset($objConnection) ;

?>
kleontiv -at- combellga -dot- ru 15-Dec-2003 09:27
I think some one wants to access to Microsoft Active Directory using ADSI with different credential by PHP. You can also do it via pure LDAP but using ADSI it is more simpler.

On VB, VBS or ASP you can do like folowing (so not trivial):

<%
Set dso = GetObject("LDAP:")

Set DsObj = dso.OpenDSObject( _
    "LDAP://DC=mydomain,DC=com", _
    "DOMAIN\login", _
    "password", _
    ADS_SECURE_AUTHENTICATION + ADS_SERVER_BIND + ADS_USE_ENCRYPTION)

for each Obj in DsObj
    Response.Write Obj.name & " with class of: " & Obj.class & "<br>"
next
%>

On PHP you can do like that:

<?php
$ADSI = new COM("LDAP:") ;

$DsObj = $ADSI->OpenDsObject("LDAP://DC=mydomain,DC=com",
                             "DOMAIN\login",
                             "password",
                             515) ;

while($Obj = $DsObj->Next())
 {
  echo $Obj->name.' with class of: '.$Obj->class.'<br>' ;
 }
?>

The access type enumeration you can use as ADS_AUTHENTICATION_ENUM.
david at wu-man dot com 06-Dec-2003 02:42
After many hours of trial and error, I have finally discovered how to kill the notorious Word process.  I hope my solution works for everyone else.

#1) $word->Quit() is perfectly fine.  Don't bother feeding in as parameter those empty variants.

#2) Do NOT have com_load_typelib('Word.Application') anywhere in your script.

#3) Make sure you have the following line before $word->Quit() :

$word->Documents[1]->Close(false);

#4) Add the following lines after $word->Quit() :

<?php
$word->Release();
$word = null;
unset($word);
?>

If my solution indeed helped you with your problem, please email me and let me know.  I would like to see if the problem was indeed solved.
alanraycom at el hogar dot net com 03-Dec-2003 03:50
XSLT transformations using MSXML can be done with this code

<?php
function xsltransform1($xslpath,$xmlstring)
 {
  $xml= new COM("Microsoft.XMLDOM");
  $xml->async=false;
  // $xmlstring is an xml string
  $xml->load($xmlstring);
  $xsl = new COM("Microsoft.XMLDOM");
  $xsl->async=false;
  // $xslpath is path to an xsl file
  $xsl->load($xslpath);
  $response=$xml->transformNode($xsl);
  unset($xml);
  unset($xsl);
  return $response;
 }
?>

enjoy
Alan Young
chris at hitcatcher dot com 01-Dec-2003 04:19
Many COM objects don't do well when passing long (win32) filenames as function parameters.  You can get the 8.3 name of the folder or file on *most* (some win platforms don't support it, and it can be toggled off in the registry for performance reasons) servers using the following:

<?php
//create FSO instance
$exFSO = new COM("Scripting.FileSystemObject") or die ("Could not create Scripting.FileSystemObject");

//set vars
$myDir = "C:\\Program Files\\";
$myFile = "a long file name.txt";

//get folder & file objects
$exDir = $exFSO->GetFolder($myDir);
$exFile = $exFSO->GetFile($myDir . $myFile);
echo $exDir->ShortPath;
echo $exFile->ShortPath;
?>
23-Nov-2003 09:57
Here is an example of reading the custom properties like Author, Keywords, etc. which are stored in MS Office and other Windows files. You must install and register dsofile as described at http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224351. The .frm file in that distribution lists most of the available properties.

<?php
// the file you wish to access
$fn = '/docs/MFA.xls';

$oFilePropReader = new COM('DSOleFile.PropertyReader');
$props = $oFilePropReader->GetDocumentProperties($fn);

// one syntax
$au = com_get($props, 'Author');
print "au: $au \n";

//another syntax
$str = 'LastEditedBy';
$lsb = $props->$str;
var_dump($lsb);

// set a property if you wish
if (!$props->IsReadOnly()) {
  $props->Subject = 'tlc';
}
?>
brana 17-Nov-2003 05:17
How to send email via MAPI (works with Windows NT4, apache launched as a service)

<?php
#New MAPI session...
$session = new COM("MAPI.Session");

#Login
$strProfileInfo = "exchange_server" . chr(10) . "exchange_user";
$session->Logon("", "", 0, 1, 0, 1, $strProfileInfo);

# New message...
$msg = $session->Outbox->Messages->Add();
$msg->Subject = "Subject";
$msg->Text = "body";

#set recipients...
$rcpts = $msg->Recipients;
$rcpts->AddMultiple("toto@toto.com", 1);   #To...
$rcpts->AddMultiple("titi@titi.com", 2);   #Cc...
$rcpts->AddMultiple("tutu@tutu.com", 3);   #Bcc...

# Resolve senders
$rcpts->Resolve();

#Send message
$msg->Send();

#Logoff
$session->Logoff();

#Cleanup
if($msg!=null) {
    $msg->Release();
    $msg = null;
}
if($session!=null) {
    $session->Release();
    $session = null;
}
?>

ps : NT account launching the service and exchange user must match !
03-Oct-2003 12:55
Convert Microsoft word document .DOC to adobe acrobat .PS or .PDF files:

Drawback: if any dialog boxes pop up, the conversion will become non-automated.

<?php
// You must have word and adobe acrobat distiller on
// your system, although theoretically any printer driver
// that makes .PS files would work.

// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";

// bring it to front
$word->Visible = 1;

// Select the acrobat distiller as the active printer.
// I presume that you could also use the Acrobat PDF writer // driver that comes with Acrobat full version.
$word->ActivePrinter = "Acrobat Distiller";

// Open a word document, or anything else that word
// can read
$word->Documents->Open($input);

// This will create a .PS file called $output
$word->ActiveDocument->PrintOut(0, 0, 0, $output);

// If you need a .pdf instead, use the acrobat
// distiller's watched folder option.

// closing word
$word->Quit();

// free the object
$word->Release();
$word = null;

?>
court shrock 26-Sep-2003 05:24
took me a while until I found out how to loop through COM objects in PHP.... in ASP, you use something like:

<%
set domainObject = GetObject("WinNT://Domain")

for each obj in domainObject
  Response.write obj.Name & "<br>"
next

%>

I finally found a note in a PHP bogus bug report that said you needed to do something like this (this is using ADSI):

<?php
$adsi = new COM("WinNT://Domain");

while($obj = $adsi->Next()) {
  echo $obj->Name.'<br>';
}// while

// will list all the names of all objects in the domain 'Domain'
?>

Also, you can access the IIS metabase by doing something like the following:

<?php
$iis = new COM("IIS://localhost/w3svc");

while($obj = $iis->Next()) {
  if ($obj->Class == 'IISWebServer') {
    $site = new COM("IIS://Localhost/w3svc/".$obj->Name);
    echo 'serviceID ('.$obj->Name.'): '.$site->ServerComment.'<br>';
    $bindings = $site->ServerBindings;

    echo '<ul>';
    foreach($bindings as $binding) {
      list($ip, $port, $hostHeader) = explode(':', $binding);
      echo "<li>$ip:$port -- $hostHeader</li>";
    }// foreach
    echo '</ul>';

    // hint: ssl bindings are in $site->SecureBindings

    unset($site);

  }// if

}// while
unset($iis);

// will list all the sites and their bindings on 'localhost'
?>
php at dictim dot com 06-Sep-2003 01:17
This took me days to work out how to do so I gotta share it:

How to get the word count from a MS Word Document:

<?php
#Instantiate the Word component.

$word = new COM("word.application") or die("Unable to instantiate Word");

$word->Visible = 1;

$word->Documents->Open("c:/anydocument.doc");
$temp = $word->Dialogs->Item(228);
$temp->Execute();
$numwords = $temp->Words();

echo $numwords;

$word->Quit();
?>

Note that this is the only way to get the word count accurately:
$word->ActiveDocument->Words->Count;
Will see all carriage returns and punctuation as words so is wildy innaccurate.
seidenberg at cf-mail dot net 11-Jul-2003 03:36
open PDF Documents with Internet Explorer

<?php
$browser = new COM("InternetExplorer.Application");
$browser->Visible = true;
$browser->Navigate("path_to_your_pdf_document");
?>

this works for me with php-gtk
tomas dot pacl at atlas dot cz 16-Jun-2003 06:07
Passing parameters by reference in PHP 4.3.2 (and in a future releases of PHP )

In PHP 4.3.2 allow_call_time_pass_reference option is set to "Off" by default and future versions may not support this option any longer.
Some COM functions has by-reference parameters. VARIANT object must be used to call this functions, but it would be passed without an '&' before variable name.

Example:

<?php
$myStringVariant = new VARIANT("over-write me", VT_BSTR);

/* works */
$result = $comobj->DoSomethingTo($myStringVariant );

/* works only with allow_call_time_pass_reference option set to "On" and may not work in a future release of PHP */
$result = $comobj->DoSomethingTo(&$myStringVariant );

/* The value in the variant can be retrieved by: */
$theActualValue = $myStringVariant->value;
?>
php at racinghippo dot co dot uk 22-Mar-2003 05:47
PASSING/RETURNING PARAMETERS BY REFERENCE
=========================================

Some COM functions not only return values through the return value, but also act upon a variable passed to it as a parameter *By Reference*:

RetVal = DoSomethingTo (myVariable)

Simply sticking an '&' in front of myVariable doesn't work - you need to pass it a variant of the correct type, as follows:

  $myStringVariant = new VARIANT("over-write me", VT_BSTR);
  $result = $comobj->DoSomethingTo( &$myStringVariant );

The value in the variant can then be retrieved by:

  $theActualValue = $myStringVariant->value;

Other types of variant can be created as your needs demand - see the preceding section on the VARIANT type.
alex at domini dot net 05-Mar-2003 02:55
To manage the Windows Register at HKEY_LOCAL_MACHINE\SOFTWARE\ use these functions:

<?php

/**
 * @return string
 * @param aplicacio string
 * @param nom string
 * @desc Retorna el valor del registre HKEY_LOCAL_MACHINE\SOFTWARE\aplicacio\nom
 */
function rtv_registre($aplicacio, $nom)
{
    Global $WshShell;
    $registre =  "HKEY_LOCAL_MACHINE\SOFTWARE\\" . $aplicacio . "\\"  . $nom;
    $valor = $WshShell->RegRead($registre);
    return($valor);

}

/**
 * @return string
 * @param aplicacio string
 * @param nom string
 * @param valor string
 * @param tipus string
 * @desc Actualitza el valor del registre HKEY_LOCAL_MACHINE\SOFTWARE\aplicacio\nom
 */
function put_registre($aplicacio, $nom, $valor, $tipus="REG_SZ")
{
    Global $WshShell;
    $registre =  "HKEY_LOCAL_MACHINE\SOFTWARE\\" . $aplicacio . "\\"  . $nom;
    $retorn = $WshShell->RegWrite($registre, $valor, $tipus);
    return($retorn);

}

//
// Creem una inst�ncia del COM que ens serveix per
// accedir al registre de Windows, i la mantenim.
// D'aquesta manera millorem el rendiment.
$WshShell = new COM("WScript.Shell");
?>
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:51
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.
pchason at juno dot com 11-Dec-2002 11:23
Searched for days on how to set up a multi-column html output grid that didn't use an array when creating an ADODB connection. Couldn't find one so I figured it out myself. Pretty simple. Wish I would have tried it myself sooner. Commented code with database connection is below...

<html>
<body>
<table>
<?php
//create the database connection
$conn = new COM("ADODB.Connection");
$dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
$conn->Open($dsn);
//pull the data through SQL string
$rs = $conn->Execute("select clients from web");
$clients = $rs->Fields(1);
//start the multicolumn data output
$i = 0;
$columns = 5;
while (!$rs->EOF){
//if $i equals 0, start a row
if($i == 0){
echo "<tr>";
}
//then start writing the cells in the row, increase $i by one, and move to the next record
echo "<td>" . $clients->value . "</td>";
$i++;
$rs->movenext();
//once $i increments to equal $columns, end the row,
//and start the process over by setting $i to 0
if($i == $columns || $rs->EOF) {
echo "</tr>";
$i = 0;
    }
}
//end multicolumn data output

//close the ADO connections and release resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null; ?>
</table>
</body>
</html>
tedknightusa at hotmail dot com 26-Sep-2002 09:29
A Notes example:

<?php
$session = new COM "Lotus.NotesSession" );
$session->Initialize($password);

$someDB = "C:\Lotus\Notes\Data\somedb.nsf";
$db = $session->GetDatabase("", $someDB) or die("Cannot get someDB.nsf");
$view = $db->GetView("some_view") or die("Some View not found");

$doc = $view->GetFirstDocument() or die("Unable to get Initial Some Document");

// loop through
while($doc){
  $col_vals = $doc->ColumnValues();
  echo $col_vals[0];
  $doc = $view->GetNextDocument($doc);
}
?>
dwt at myrealbox dot com 27-Aug-2002 03:31
When first writing applications instancing COM objects I always faced the problem of the instanced program not terminating correctly although everything else worked fine. In fact the process had to be killed manually by using the task manager. When experimenting a bit I was able to isolate the cause for this peculiar behaviour to be illustrated by the sample code below:

<?php

//Accessing arrays by retrieving elements via function ArrayName(Index) works, but certainly is neither efficient nor good style
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$book=$excel->Workbooks(1);
$sheet=$book->Worksheets(1);

$sheet->Name="Debug-Test";
$book->saveas("C:\\debug.xls");

$book->Close(false);
unset($sheet);
unset($book);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

//Accessing arrays as usual (using the [] operator) works, buts leads to the application not being able to terminate by itself
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$excel->Workbooks[1]->Worksheets[1]->Name="Debug-Test";
$excel->Workbooks[1]->saveas("C:\\debug.xls");

$excel->Workbooks[1]->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

?>

The sample code performs the same action twice and each time the file is properly created. Yet for some mysterious reason the instanced excel process won't terminate once you've accessed an array the way most programmers (especially those who do a lot of oop in c++) do! Therefore until the PHP developers become aware of this problem we'll have to use the inefficient coding style illustrated in the first example.
nospam at bol dot com dot br 21-Aug-2002 03:30
This is a sample to make a parametrized query using ADO via COM, this sample was used with Foxpro but will work's with most ADO complient databases. This was tested on IIS with WIN XP pro.

<?php
// Create the main connection
$dbc = new COM("ADODB.Connection")  or die ("connection create fail");
$dbc->Provider = "MSDASQL";
$dbc->Open("FoxDatabase");
// Creates a temporary record set
$RSet = new COM("ADODB.Recordset");
// Create one ADO command
$cm   = new COM("ADODB.Command");
$cm->Activeconnection = $dbc;
// the ? inside values will be the parameters $par01 and $par02
$cm->CommandText =  "Insert Into testtable ( mycharfield,mymemofield) VALUES (?,?)" ;
$cm->Prepared = TRUE;
// Creates and append 2 parameters
$par01 = $cm->CreateParameter('ppar01',129,1,50,'ABCDEFGHIKL');
$cm->Parameters->Append($par01);
$par02 = $cm->CreateParameter('ppar01',129,1,50,'123456789012346789');
$cm->Parameters->Append($par02);
// Call 10 times the exec comand to show 10 different queries
for ($i = 1; $i <= 10; $i++) {
  $par01->Value = 'Count '.$i;
  $par02->Value = 'Passing here'.$i.' times';
  $RSet = $cm->Execute;
}
$RSet = $dbc->Execute("select * from testtable");
while (!$RSet->EOF){
  echo $RSet->fields["mycharfield"]->value.' ' ;
  echo $RSet->fields["mymemofield"]->value ;
  echo '<BR>';
  $RSet->movenext();
}
$RSet->close;
$dbc->close;
$cm->close;
$RSet = null;
$dbc = null;
$cm = null;
?>
admin at purplerain dot org 19-Apr-2002 04:34
an easy way to convert your file from .doc to .html

<?php
// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");

// if you want see thw World interface the value must be '1' else '0'
$word->Visible = 1;

//doc file location
$word->Documents->Open("E:\\first.doc");

//html file location  '8' mean HTML format
$word->Documents[1]->SaveAs("E:\\test_doc.html",8);

//closing word
$word->Quit();

//free the object from the memory
$word->Release();
$word = null;
?>
admin at purplerain dot org 02-Apr-2002 03:01
An easy way to send e-mail using your default Outlook account:

<?php
$objApp = new COM("Outlook.Application");
$myItem = $objApp->CreateItem(olMailItem);
$a=$myItem->Recipients->Add("admin@purplerain.org");
$myItem->Subject="Subject";
$myItem->Body="This is a Body Section now.....!";
$myItem->Display();
$myItem->Send();
?>
madon at cma-it dot com 07-Mar-2002 12:59
I thought this excel chart example could be useful.

Note the use of Excel.application vs Excel.sheet.

<pre>
<?php
    print "Hi";
#Instantiate the spreadsheet component.
#    $ex = new COM("Excel.sheet") or Die ("Did not connect");
$exapp = new COM("Excel.application") or Die ("Did not connect");

#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";

$wkb=$exapp->Workbooks->add();
#$wkb = $ex->Application->ActiveWorkbook or Die ("Did not open workbook");
print "we opened workbook<BR>";

$ex->Application->Visible = 1; #Make Excel visible.
print "we made excell visible<BR>";

$sheets = $wkb->Worksheets(1); #Select the sheet
print "selected a sheet<BR>";
$sheets->activate; #Activate it
print "activated sheet<BR>";

#This is a new sheet
$sheets2 = $wkb->Worksheets->add(); #Add a sheet
print "added a new sheet<BR>";
$sheets2->activate; #Activate it
print "activated sheet<BR>";

$sheets2->name="Report Second page";

$sheets->name="Report First page";
print "We set a name to the sheet: $sheets->name<BR>";

# fills a columns
$maxi=20;
for ($i=1;$i<$maxi;$i++) {
    $cell = $sheets->Cells($i,5) ; #Select the cell (Row Column number)
    $cell->activate; #Activate the cell
    $cell->value = $i*$i; #Change it to 15000
}

$ch = $sheets->chartobjects->add(50, 40, 400, 100); # make a chartobject

$chartje = $ch->chart; # place a chart in the chart object
$chartje->activate; #activate chartobject
$chartje->ChartType=63;
$selected = $sheets->range("E1:E$maxi"); # set the data the chart uses
$chartje->setsourcedata($selected); # set the data the chart uses
print "set the data the chart uses <BR>";

$file_name="D:/apache/Apache/htdocs/alm/tmp/final14.xls";
if (file_exists($file_name)) {unlink($file_name);}
#$ex->Application->ActiveWorkbook->SaveAs($file_name); # saves sheet as final.xls
$wkb->SaveAs($file_name); # saves sheet as final.xls
print "saved<BR>";

#$ex->Application->ActiveWorkbook->Close("False");
$exapp->Quit();
unset($exapp);
?>

</pre>

Alex Madon
VARIANT
com_addref
COM


Increases the components reference counter [deprecated]

COM Функции
com_create_guid
COM Функции
PHP Manual

com_addref

(PHP 4 >= 4.1.0)

com_addref — Increases the components reference counter [deprecated]

Описание

void com_addref ( void )

Increases the components reference counter.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примечания

Внимание

You should never need to use this function.

User Contributed Notes

There are no user contributed notes for this page.
COM Функции
com_create_guid
COM Функции


Generate a globally unique identifier (GUID)

com_addref
com_event_sink
COM Функции
PHP Manual

com_create_guid

(PHP 5)

com_create_guid — Generate a globally unique identifier (GUID)

Описание

string com_create_guid ( void )

Generates a Globally Unique Identifier (GUID).

A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

Возвращаемые значения

Returns the GUID as a string.

Смотрите также

  • uuid_create() in the PECL uuid extension

User Contributed Notes

Alix Axel 16-Aug-2010 03:59
The phunction PHP framework (http://sourceforge.net/projects/phunction/) uses the following function to generate valid version 4 UUIDs:

<?php

function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

?>

The output generated by the sprintf() and mt_rand() calls is identical to com_create_guid() results.
Kristof_Polleunis at yahoo dot com 28-Apr-2005 08:16
A guid function that works in all php versions:

<?php
function guid(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
        return $uuid;
    }
}
echo guid();
?>
com_addref
com_event_sink
COM Функции


Connect events from a COM object to a PHP object

com_create_guid
com_get_active_object
COM Функции
PHP Manual

com_event_sink

(PHP 4 >= 4.2.0, PHP 5)

com_event_sink — Connect events from a COM object to a PHP object

Описание

bool com_event_sink ( variant $comobject , object $sinkobject [, mixed $sinkinterface ] )

Instructs COM to sink events generated by comobject into the PHP object sinkobject.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

Список параметров

comobject

sinkobject

sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

sinkinterface

PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 COM event sink example

<?php
class IEEventSinker {
    var $terminated = false;

   function ProgressChange($progress, $progressmax) {
      echo "Download progress: $progress / $progressmax\n";
    }

    function DocumentComplete(&$dom, $url) {
      echo "Document $url complete\n";
    }

    function OnQuit() {
      echo "Quit!\n";
      $this->terminated = true;
    }
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the & for PHP 5!
$sink = new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.example.org");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

Смотрите также

  • com_print_typeinfo() - Print out a PHP class definition for a dispatchable interface
  • com_message_pump() - Process COM messages, sleeping for up to timeoutms milliseconds

User Contributed Notes

fjortiz 14-Jul-2005 12:33
In case someone needs a skeleton sink for ADODB.Connection events:

class ADOConnectionEventSink    {

    function BeginTransComplete( $translevel, $objerror, $status, $objconn )    {
        return 0;
    }

    function CommitTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function RolbackTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function WillConnect ( $ConnectionString, $userid, $psword, $options, $status, $objconn )    {
        return 0;
    }

    function ConnectComplete ( $objerror, $status, $objconn)    {
        return 0;
    }

    function Disconnect( $status, $objConn )    {
        return 0;
    }

    function WillExecute ( $src, $cursortyp, $locktyp, $options, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function ExecuteComplete ( $recaffected, $objerror, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function InfoMessage ( $objerror, $status, $objconn)    {
        return 0;
    }
}

// later on...
$db = new COM("ADODB.Connection", NULL, $charPage);
$sink = new ADOConnectionEventSink();
com_event_sink($db, $sink, "ConnectionEvents");
//...
com_create_guid
com_get_active_object
COM Функции


Returns a handle to an already running instance of a COM object

com_event_sink
com_get
COM Функции
PHP Manual

com_get_active_object

(PHP 5)

com_get_active_object — Returns a handle to an already running instance of a COM object

Описание

variant com_get_active_object ( string $progid [, int $code_page ] )

com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the "Running Object Table" to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

Список параметров

progid

progid must be either the ProgID or CLSID for the object that you want to access (for example Word.Application).

code_page

Acts in precisely the same way that it does for the COM class.

Возвращаемые значения

If the requested object is running, it will be returned to your script just like any other COM object.

Ошибки

There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

Примечания

Внимание

Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read » Considerations for Server-Side Automation of Office for more information on the general issues involved.

User Contributed Notes

gerrit at timingteam dot nl 04-Jan-2009 09:25
Please note the next behavior (Apache 2.2.8, W2K, WXP)

If Apache runs as a service, com_get_active_object() always returns MK_E_UNAVAILABLE, even when it is definitely sure that the Running Object Table contains a reference to the required object.

If Apache runs in a console, com_get_active_object()  returns the object handle as required.

This apparently is a Windows issue.
com_event_sink
com_get
COM Функции


Gets the value of a COM Component's property [deprecated]

com_get_active_object
com_invoke
COM Функции
PHP Manual

com_get

(PHP 4)

com_get — Gets the value of a COM Component's property [deprecated]

Описание

Deprecated, use the OO syntax instead.

Пример #1 OO syntax

<?php
// do this
$var = $obj->property;
// instead of this:
$var = com_get($obj, 'property');
?>

Примечания

Замечание: Эта функция не существует в PHP 5; вместо этого для доступа к свойствам и вызову методов используйте обычный и более привычный объектно-ориентированный синтаксис.

User Contributed Notes

There are no user contributed notes for this page.
com_get_active_object
com_invoke
COM Функции


Calls a COM component's method [deprecated]

com_get
com_isenum
COM Функции
PHP Manual

com_invoke

(PHP 4)

com_invoke — Calls a COM component's method [deprecated]

Description

mixed com_invoke ( resource $com_object , string $function_name [, mixed $function_parameters ] )

com_invoke() invokes the method named function_name of the COM component referenced by com_object. com_invoke() returns FALSE on error, returns the function_name's return value on success. All the extra parameters function_parameters are passed to the method function_name.

Пример #1 Don't use com_invoke(), use OO syntax instead

<?php
// do this
$val = $obj->method($one, $two);
// instead of this:
$val = com_invoke($obj, 'method', $one, $two);
?>

Замечание: Эта функция не существует в PHP 5; вместо этого для доступа к свойствам и вызову методов используйте обычный и более привычный объектно-ориентированный синтаксис.

User Contributed Notes

tomer at parity-bit dot com 01-Feb-2005 12:21
Note that if you want to use a string to specify the method to call (e.g. a drop-down list to decide what to do to a server process) you can do this in three ways.

The first is to use this function, as in <?php com_invoke($obj, $_GET['func']); ?>
That's bad.

The second is to use eval(), as in <?php eval("\$obj->{$_GET['func']}();"); ?>
That's very very very *very* bad.

The third is to use call_user_func(), as in <?php call_user_func(array($obj, $_GET['func'])); ?>
That's very good.

Remember to validate the user input against a list of allowed methods if a non-admin is at the console.

http://php.net/manual/en/function.call-user-func.php
com_get
com_isenum
COM Функции


Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]

com_invoke
com_load_typelib
COM Функции
PHP Manual

com_isenum

(PHP 4 >= 4.1.0)

com_isenum — Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]

Описание

bool com_isenum ( variant $com_module )

Checks to see if a COM object can be enumerated using the Next() method hack. See COM class for more details on these methods.

Список параметров

com_module

The COM object.

Возвращаемые значения

Returns TRUE if the object can be enumerated, FALSE otherwise.

Примечания

Замечание:

This function does not exist in PHP 5; use the more natural foreach statement to iterate over the contents of COM objects. See For Each for more details.

User Contributed Notes

There are no user contributed notes for this page.
com_invoke
com_load_typelib
COM Функции


Loads a Typelib

com_isenum
com_load
COM Функции
PHP Manual

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5)

com_load_typelib — Loads a Typelib

Описание

bool com_load_typelib ( string $typelib_name [, bool $case_insensitive = true ] )

Loads a type-library and registers its constants in the engine, as though they were defined using define().

Note that it is much more efficient to use the configuration setting to pre-load and register the constants, although not so flexible.

If you have turned on , then PHP will attempt to automatically register the constants associated with a COM object when you instantiate it. This depends on the interfaces provided by the COM object itself, and may not always be possible.

Список параметров

typelib_name

typelib_name can be one of the following:

  • The filename of a .tlb file or the executable module that contains the type library.

  • The type library GUID, followed by its version number, for example {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • The type library name, e.g. Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP will attempt to resolve the type library in this order, as the process gets more and more expensive as you progress down the list; searching for the type library by name is handled by physically enumerating the registry until we find a match.

case_insensitive

The case_insensitive behaves in the same way as the parameter with the same name in the define() function.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

tomas dot burba at softneta dot lt 12-Mar-2012 11:38
I had some problems with a third-party Word-controlling code that is somewhat similar to Richard's example. (Word 2007 SP1, XP SP2.) Rewrote some parts according to that example, no luck. Error messages from Word were crazy:

"Bad parameter" -- it didn't like wdGoToBookmark but was ok with its numeric equivalent -1;

"Call to undefined method variant::SaveAs()" -- the same with Save() that was suitable in my case, so no options were remaining.

But then I ran the example via php.exe in the command line, and it worked! Eventually it turned out that Apache service must be run as some real user instead of SYSTEM.
RQuadling at GMail dot com 17-Jun-2008 03:40
Some libraries load other libraries as part of their functionality. For example Crystal Reports Object Factory uses the CreateObject() method to create an instance of a Crystal Design RunTime Application. If you want to use constants defined in the newly loaded library, you will need to manually register the library - even with com.autoregister_typelib set to true.

<?php
echo 'com.autoregister_typelib = ', ini_get('com.autoregister_typelib'), PHP_EOL;

$o_CrObjectFactory = New COM('CrystalReports11.ObjectFactory.1');

$o_CrApplication = $o_CrObjectFactory->CreateObject("CrystalDesignRunTime.Application");

echo 'Will not be defined : ', crOpenReportByDefault, PHP_EOL;

com_load_typelib('CrystalDesignRunTime.Application');

echo 'Will now be defined : ', crOpenReportByDefault, PHP_EOL;
?>

outputs ...

com.autoregister_typelib = 1
Will not be defined :
Notice: Use of undefined constant crOpenReportByDefault - assumed 'crOpenReportByDefault' in C:\refl.php on line 8
crOpenReportByDefault
Will now be defined : 0
03-May-2004 07:18
In case any of you were wondering what com_load_typelib actually DOES, I have found that it loads constants\enums that the COM obeject has defined.  The example below is using the Nero COM object (from Nero Burning rom, version 6+).  The Nero object defines a bunch of constants, but they can not be used as PHP constants unless you use the mentioned function.  So the example below will work just fine:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
com_load_typelib("Nero.Nero");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

But this one will not, since PHP will return a message saying that the constant is undefined:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

This one took me a while to figure out, hope it helps.

Also, check out http://www.php.net/manual/en/faq.com.php to find out how to get COM events working in PHP.
ojpp at webdevfm dot com 30-Jan-2004 06:33
Hello PHP community, I want to help in a problem I found in this COM built-in function: com_load_typelib(), when I executed it in order to open a COM Server process (for example: Word, Excel, etc.) I was in trouble to release the object from memory, I figured it out, this is the solution:

Change a configuration in the php.ini:

; autoregister constants of a components typlib on com_load()
com.autoregister_typelib = true

When com.autoregister_typelib directive is true, PHP parser manage the COM server type library, I hope it helps.
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:55
<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.
com_isenum
com_load
COM Функции


Creates a new reference to a COM component [deprecated]

com_load_typelib
com_message_pump
COM Функции
PHP Manual

com_load

(PHP 4)

com_load — Creates a new reference to a COM component [deprecated]

Описание

Deprecated, use the OO syntax instead.

Пример #1 OO syntax

<?php
// do this
$obj = new COM($module);
// instead of this:
$obj = com_load($module);
?>

Примечания

Замечание: Эта функция не существует в PHP 5; вместо этого для доступа к свойствам и вызову методов используйте обычный и более привычный объектно-ориентированный синтаксис.

User Contributed Notes

There are no user contributed notes for this page.
com_load_typelib
com_message_pump
COM Функции


Process COM messages, sleeping for up to timeoutms milliseconds

com_load
com_print_typeinfo
COM Функции
PHP Manual

com_message_pump

(PHP 4 >= 4.2.0, PHP 5)

com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds

Описание

bool com_message_pump ([ int $timeoutms = 0 ] )

This function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

Список параметров

timeoutms

The timeout, in milliseconds.

If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.

Возвращаемые значения

If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE.

User Contributed Notes

There are no user contributed notes for this page.
com_load
com_print_typeinfo
COM Функции


Print out a PHP class definition for a dispatchable interface

com_message_pump
com_propget
COM Функции
PHP Manual

com_print_typeinfo

(PHP 4 >= 4.2.0, PHP 5)

com_print_typeinfo — Print out a PHP class definition for a dispatchable interface

Описание

bool com_print_typeinfo ( object $comobject [, string $dispinterface [, bool $wantsink = false ]] )

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

Список параметров

comobject

comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()).

dispinterface

The name of an IDispatch descendant interface that you want to display.

wantsink

If set to TRUE, the corresponding sink interface will be displayed instead.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • com_event_sink() - Connect events from a COM object to a PHP object
  • com_load_typelib() - Loads a Typelib

User Contributed Notes

Richard Lynch 03-Oct-2006 04:51
In my particular version of PHP, the second and third arguments are not, in fact, optional.

Passing in '' for both, however, yielded a bucketful of information.

YMMV
csaba at alum dot mit dot edu 14-Feb-2005 12:49
com_print_typeinfo is really useful if you're trying to figure out what properties and methods you have access to.  For example, I might do:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer);
?>

The first line shows me the class of the object (what VBScript calls 'typename'), in my case IShellDispatch4.  It's frequently the case that if you plunk that in as the second argument to com_print_typeinfo, you get way more methods/properties coming back.  Thus:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer, "IShellDispatch4");
?>

Furthermore, you might get additional functions listed if you try lower number suffixes (or not).  At any rate, it would be useful for PHP to have a typename function like VBScript does.  For example, if you iterate through the Windows of $oExplorer you get both IE and Explorer windows and typename is the easy way to differentiate between them.  Here's what I'm using:

<?php
    function typeName($objCOM) {
    if (empty($objCOM)) return "no COM object";
    if (gettype($objCOM)!="object") return "not a COM object";
    ob_start();
    com_print_typeinfo($objCOM);
    $typeInfo = ob_get_contents();
    ob_end_clean();
    $pattern = "/^\\s*class (.*) \\{/";
    if (!($matchCnt = preg_match($pattern, $typeInfo, $aMatch))) return "Not found";
    return $aMatch[1];
}
?>

Csaba Gabor from Vienna
com_message_pump
com_propget
COM Функции


Псевдоним com_get

com_print_typeinfo
com_propput
COM Функции
PHP Manual

com_propget

(PHP 4)

com_propget — Псевдоним com_get()

Описание

Эта функция является псевдонимом: com_get().

Замечание: Эта функция не существует в PHP 5; вместо этого для доступа к свойствам и вызову методов используйте обычный и более привычный объектно-ориентированный синтаксис.

User Contributed Notes

There are no user contributed notes for this page.
com_print_typeinfo
com_propput
COM Функции


Псевдоним com_set

com_propget
com_propset
COM Функции
PHP Manual

com_propput

(PHP 4)

com_propput — Псевдоним com_set()

Описание

Эта функция является псевдонимом: com_set().

Замечание: Эта функция не существует в PHP 5; вместо этого для доступа к свойствам и вызову методов используйте обычный и более привычный объектно-ориентированный синтаксис.

User Contributed Notes

There are no user contributed notes for this page.
com_propget
com_propset
COM Функции


Псевдоним com_set

com_propput
com_release
COM Функции
PHP Manual

com_propset

(PHP 4)

com_propset — Псевдоним com_set()

Описание

Эта функция является псевдонимом: com_set().

Замечание: Эта функция не существует в PHP 5; вместо этого для доступа к свойствам и вызову методов используйте обычный и более привычный объектно-ориентированный синтаксис.

User Contributed Notes

There are no user contributed notes for this page.
com_propput
com_release
COM Функции


Decreases the components reference counter [deprecated]

com_propset
com_set
COM Функции
PHP Manual

com_release

(PHP 4 >= 4.1.0)

com_release — Decreases the components reference counter [deprecated]

Описание

void com_release ( void )

Decreases the components reference counter.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

Версия | Описание
5.0.0 | This function was removed.

Примечания

Внимание

You should never need to use this function.

User Contributed Notes

30-Mar-2007 07:31
The function is replaced by Release() method of the COM object variable.
 (correct me if i`m wrong)
com_propset
com_set
COM Функции


Assigns a value to a COM component's property

com_release
variant_abs
COM Функции
PHP Manual

com_set

(PHP 4)

com_set — Assigns a value to a COM component's property

Описание

Deprecated, use the OO syntax instead.

Пример #1 OO syntax

<?php
// do this
$obj->property = $value;
// instead of this:
com_set($obj, 'property', $value);
?>

Примечания

Замечание: Эта функция не существует в PHP 5; вместо этого для доступа к свойствам и вызову методов используйте обычный и более привычный объектно-ориентированный синтаксис.

User Contributed Notes

dan at kuykendall dot org 15-Aug-2002 07:38
This should also work using the newer OOP style that is still undocumented.

<?php
$obj = new COM('Some.app');
$obj->somevar = 'somevalue';
?>
com_release
variant_abs
COM Функции


Returns the absolute value of a variant

com_set
variant_add
COM Функции
PHP Manual

variant_abs

(PHP 5)

variant_abs — Returns the absolute value of a variant

Описание

mixed variant_abs ( mixed $val )

Returns the absolute value of a variant.

Список параметров

val

The variant.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the absolute value of val.

Смотрите также

  • abs() - Модуль числа

User Contributed Notes

There are no user contributed notes for this page.
com_set
variant_add
COM Функции


"Adds" two variant values together and returns the result

variant_abs
variant_and
COM Функции
PHP Manual

variant_add

(PHP 5)

variant_add — "Adds" two variant values together and returns the result

Описание

mixed variant_add ( mixed $left , mixed $right )

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

Variant Addition Rules
If | Then
Both expressions are of the string type | Concatenation
One expression is a string type and the other a character | Addition
One expression is numeric and the other is a string | Addition
Both expressions are numeric | Addition
Either expression is NULL | NULL is returned
Both expressions are empty | Integer subtype is returned

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the result.

Смотрите также

  • variant_sub() - Subtracts the value of the right variant from the left variant value

User Contributed Notes

There are no user contributed notes for this page.
variant_abs
variant_and
COM Функции


Performs a bitwise AND operation between two variants

variant_add
variant_cast
COM Функции
PHP Manual

variant_and

(PHP 5)

variant_and — Performs a bitwise AND operation between two variants

Описание

mixed variant_and ( mixed $left , mixed $right )

Performs a bitwise AND operation. Note that this is slightly different from a regular AND operation.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant AND Rules
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | FALSE
TRUE | NULL | NULL
FALSE | TRUE | FALSE
FALSE | FALSE | FALSE
FALSE | NULL | FALSE
NULL | TRUE | NULL
NULL | FALSE | FALSE
NULL | NULL | NULL

Смотрите также

  • variant_or() - Performs a logical disjunction on two variants

User Contributed Notes

There are no user contributed notes for this page.
variant_add
variant_cast
COM Функции


Convert a variant into a new variant object of another type

variant_and
variant_cat
COM Функции
PHP Manual

variant_cast

(PHP 5)

variant_cast — Convert a variant into a new variant object of another type

Описание

variant variant_cast ( variant $variant , int $type )

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

Список параметров

variant

The variant.

type

type should be one of the VT_XXX constants.

Возвращаемые значения

Returns a VT_DATE variant.

Смотрите также

  • variant_set_type() - Convert a variant into another type "in-place"

User Contributed Notes

There are no user contributed notes for this page.
variant_and
variant_cat
COM Функции


concatenates two variant values together and returns the result

variant_cast
variant_cmp
COM Функции
PHP Manual

variant_cat

(PHP 5)

variant_cat — concatenates two variant values together and returns the result

Описание

mixed variant_cat ( mixed $left , mixed $right )

Concatenates left with right and returns the result.

This function is notionally equivalent to $left . $right.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the result of the concatenation.

Смотрите также

  • Строковые операторы for the string concatenation operator

User Contributed Notes

There are no user contributed notes for this page.
variant_cast
variant_cmp
COM Функции


Compares two variants

variant_cat
variant_date_from_timestamp
COM Функции
PHP Manual

variant_cmp

(PHP 5)

variant_cmp — Compares two variants

Описание

int variant_cmp ( mixed $left , mixed $right [, int $lcid [, int $flags ]] )

Compares left with right.

This function will only compare scalar values, not arrays or variant records.

Список параметров

left

The left operand.

right

The right operand.

lcid

A valid Locale Identifier to use when comparing strings (this affects string collation).

flags

flags can be one or more of the following values OR'd together, and affects string comparisons:

Variant Comparision Flags
value | meaning
NORM_IGNORECASE | Compare case insensitively
NORM_IGNORENONSPACE | Ignore nonspacing characters
NORM_IGNORESYMBOLS | Ignore symbols
NORM_IGNOREWIDTH | Ignore string width
NORM_IGNOREKANATYPE | Ignore Kana type
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns one of the following:

Variant Comparision Results
value | meaning
VARCMP_LT | left is less than right
VARCMP_EQ | left is equal to right
VARCMP_GT | left is greater than right
VARCMP_NULL | Either left, right or both are NULL

User Contributed Notes

There are no user contributed notes for this page.
variant_cat
variant_date_from_timestamp
COM Функции


Returns a variant date representation of a Unix timestamp

variant_cmp
variant_date_to_timestamp
COM Функции
PHP Manual

variant_date_from_timestamp

(PHP 5)

variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp

Описание

variant variant_date_from_timestamp ( int $timestamp )

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

Список параметров

timestamp

A unix timestamp.

Возвращаемые значения

Returns a VT_DATE variant.

Смотрите также

  • variant_date_to_timestamp() - Converts a variant date/time value to Unix timestamp
  • mktime() - Возвращает метку времени Unix для заданной даты
  • time() - Возвращает текущую метку времени Unix

User Contributed Notes

There are no user contributed notes for this page.
variant_cmp
variant_date_to_timestamp
COM Функции


Converts a variant date/time value to Unix timestamp

variant_date_from_timestamp
variant_div
COM Функции
PHP Manual

variant_date_to_timestamp

(PHP 5)

variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp

Описание

int variant_date_to_timestamp ( variant $variant )

Converts variant from a VT_DATE (or similar) value into a Unix timestamp. This allows easier interopability between the Unix-ish parts of PHP and COM.

Список параметров

variant

The variant.

Возвращаемые значения

Returns a unix timestamp.

Смотрите также

  • variant_date_from_timestamp() - Returns a variant date representation of a Unix timestamp
  • date() - Форматирует вывод системной даты/времени
  • strftime() - Форматирует текущую дату/время с учетом текущих настроек локали

User Contributed Notes

There are no user contributed notes for this page.
variant_date_from_timestamp
variant_div
COM Функции


Returns the result from dividing two variants

variant_date_to_timestamp
variant_eqv
COM Функции
PHP Manual

variant_div

(PHP 5)

variant_div — Returns the result from dividing two variants

Описание

mixed variant_div ( mixed $left , mixed $right )

Divides left by right and returns the result.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Double is returned
One expression is a string type and the other a character | Division and a double is returned
One expression is numeric and the other is a string | Division and a double is returned.
Both expressions are numeric | Division and a double is returned
Either expression is NULL | NULL is returned
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty. | 0 as type double is returned
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown

Смотрите также

  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.
variant_date_to_timestamp
variant_eqv
COM Функции


Performs a bitwise equivalence on two variants

variant_div
variant_fix
COM Функции
PHP Manual

variant_eqv

(PHP 5)

variant_eqv — Performs a bitwise equivalence on two variants

Описание

mixed variant_eqv ( mixed $left , mixed $right )

Performs a bitwise equivalence on two variants.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.

User Contributed Notes

There are no user contributed notes for this page.
variant_div
variant_fix
COM Функции


Returns the integer portion of a variant

variant_eqv
variant_get_type
COM Функции
PHP Manual

variant_fix

(PHP 5)

variant_fix — Returns the integer portion of a variant

Описание

mixed variant_fix ( mixed $variant )

Gets the integer portion of a variant.

Список параметров

variant

The variant.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

Примечания

Внимание

This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation.

Смотрите также

  • variant_int() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Округляет дробь в меньшую сторону
  • ceil() - Округляет дробь в большую сторону
  • round() - Округляет число типа float

User Contributed Notes

There are no user contributed notes for this page.
variant_eqv
variant_get_type
COM Функции


Returns the type of a variant object

variant_fix
variant_idiv
COM Функции
PHP Manual

variant_get_type

(PHP 5)

variant_get_type — Returns the type of a variant object

Описание

int variant_get_type ( variant $variant )

Returns the type of a variant object.

Список параметров

variant

The variant object.

Возвращаемые значения

This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

In PHP versions prior to 5, you could obtain this information from instances of the VARIANT class ONLY, by reading a fake type property. See the VARIANT class for more information on this.

User Contributed Notes

There are no user contributed notes for this page.
variant_fix
variant_idiv
COM Функции


Converts variants to integers and then returns the result from dividing them

variant_get_type
variant_imp
COM Функции
PHP Manual

variant_idiv

(PHP 5)

variant_idiv — Converts variants to integers and then returns the result from dividing them

Описание

mixed variant_idiv ( mixed $left , mixed $right )

Converts left and right to integer values, and then performs integer division.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant Integer Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Division and integer is returned
One expression is a string type and the other a character | Division
One expression is numeric and the other is a string | Division
Both expressions are numeric | Division
Either expression is NULL | NULL is returned
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown

Смотрите также

  • variant_div() - Returns the result from dividing two variants

User Contributed Notes

There are no user contributed notes for this page.
variant_get_type
variant_imp
COM Функции


Performs a bitwise implication on two variants

variant_idiv
variant_int
COM Функции
PHP Manual

variant_imp

(PHP 5)

variant_imp — Performs a bitwise implication on two variants

Описание

mixed variant_imp ( mixed $left , mixed $right )

Performs a bitwise implication operation.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant Implication Table
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | TRUE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | TRUE
FALSE | NULL | TRUE
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

User Contributed Notes

There are no user contributed notes for this page.
variant_idiv
variant_int
COM Функции


Returns the integer portion of a variant

variant_imp
variant_mod
COM Функции
PHP Manual

variant_int

(PHP 5)

variant_int — Returns the integer portion of a variant

Описание

mixed variant_int ( mixed $variant )

Gets the integer portion of a variant.

Список параметров

variant

The variant.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

Смотрите также

  • variant_fix() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Округляет дробь в меньшую сторону
  • ceil() - Округляет дробь в большую сторону
  • round() - Округляет число типа float

User Contributed Notes

There are no user contributed notes for this page.
variant_imp
variant_mod
COM Функции


Divides two variants and returns only the remainder

variant_int
variant_mul
COM Функции
PHP Manual

variant_mod

(PHP 5)

variant_mod — Divides two variants and returns only the remainder

Описание

mixed variant_mod ( mixed $left , mixed $right )

Divides left by right and returns the remainder.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the remainder of the division.

Смотрите также

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.
variant_int
variant_mul
COM Функции


Multiplies the values of the two variants

variant_mod
variant_neg
COM Функции
PHP Manual

variant_mul

(PHP 5)

variant_mul — Multiplies the values of the two variants

Описание

mixed variant_mul ( mixed $left , mixed $right )

Multiplies left by right.

Список параметров

left

The left operand.

right

The right operand.

Boolean values are converted to -1 for FALSE and 0 for TRUE.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant Multiplication Rules
If | Then
Both expressions are of the string, date, character, boolean type | Multiplication
One expression is a string type and the other a character | Multiplication
One expression is numeric and the other is a string | Multiplication
Both expressions are numeric | Multiplication
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Смотрите также

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.
variant_mod
variant_neg
COM Функции


Performs logical negation on a variant

variant_mul
variant_not
COM Функции
PHP Manual

variant_neg

(PHP 5)

variant_neg — Performs logical negation on a variant

Описание

mixed variant_neg ( mixed $variant )

Performs logical negation of variant.

Список параметров

variant

The variant.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the result of the logical negation.

User Contributed Notes

There are no user contributed notes for this page.
variant_mul
variant_not
COM Функции


Performs bitwise not negation on a variant

variant_neg
variant_or
COM Функции
PHP Manual

variant_not

(PHP 5)

variant_not — Performs bitwise not negation on a variant

Описание

mixed variant_not ( mixed $variant )

Performs bitwise not negation on variant and returns the result.

Список параметров

variant

The variant.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the bitwise not negation. If variant is NULL, the result will also be NULL.

User Contributed Notes

There are no user contributed notes for this page.
variant_neg
variant_or
COM Функции


Performs a logical disjunction on two variants

variant_not
variant_pow
COM Функции
PHP Manual

variant_or

(PHP 5)

variant_or — Performs a logical disjunction on two variants

Описание

mixed variant_or ( mixed $left , mixed $right )

Performs a bitwise OR operation. Note that this is slightly different from a regular OR operation.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant OR Rules
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | TRUE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
FALSE | NULL | NULL
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

Смотрите также

  • variant_and() - Performs a bitwise AND operation between two variants
  • variant_xor() - Performs a logical exclusion on two variants

User Contributed Notes

There are no user contributed notes for this page.
variant_not
variant_pow
COM Функции


Returns the result of performing the power function with two variants

variant_or
variant_round
COM Функции
PHP Manual

variant_pow

(PHP 5)

variant_pow — Returns the result of performing the power function with two variants

Описание

mixed variant_pow ( mixed $left , mixed $right )

Returns the result of left to the power of right.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the result of left to the power of right.

Смотрите также

  • pow() - Возведение в степень

User Contributed Notes

There are no user contributed notes for this page.
variant_or
variant_round
COM Функции


Rounds a variant to the specified number of decimal places

variant_pow
variant_set_type
COM Функции
PHP Manual

variant_round

(PHP 5)

variant_round — Rounds a variant to the specified number of decimal places

Описание

mixed variant_round ( mixed $variant , int $decimals )

Returns the value of variant rounded to decimals decimal places.

Список параметров

variant

The variant.

decimals

Number of decimal places.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Returns the rounded value.

Смотрите также

  • round() - Округляет число типа float

User Contributed Notes

There are no user contributed notes for this page.
variant_pow
variant_set_type
COM Функции


Convert a variant into another type "in-place"

variant_round
variant_set
COM Функции
PHP Manual

variant_set_type

(PHP 5)

variant_set_type — Convert a variant into another type "in-place"

Описание

void variant_set_type ( variant $variant , int $type )

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

Список параметров

variant

The variant.

type

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • variant_cast() - Convert a variant into a new variant object of another type

User Contributed Notes

martin at itmission dot com 22-May-2009 10:55
In my application I was using ADODB to retrieve data from Microsoft Access.  During queries, fields defined as "Date/Time" in Access were being returned to PHP as instances of the Variant class.

For some reason, the variant_date_to_timestamp function returned incorrect timestamps.  As a workaround, I used variant_set_type($variant, VT_BSTR) to get a string representation of the date.  This can be used for most variant types PHP doesn't handle.
variant_round
variant_set
COM Функции


Assigns a new value for a variant object

variant_set_type
variant_sub
COM Функции
PHP Manual

variant_set

(PHP 5)

variant_set — Assigns a new value for a variant object

Описание

void variant_set ( variant $variant , mixed $value )

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

Список параметров

variant

The variant.

value

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

There are no user contributed notes for this page.
variant_set_type
variant_sub
COM Функции


Subtracts the value of the right variant from the left variant value

variant_set
variant_xor
COM Функции
PHP Manual

variant_sub

(PHP 5)

variant_sub — Subtracts the value of the right variant from the left variant value

Описание

mixed variant_sub ( mixed $left , mixed $right )

Subtracts right from left.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant Subtraction Rules
If | Then
Both expressions are of the string type | Subtraction
One expression is a string type and the other a character | Subtraction
One expression is numeric and the other is a string | Subtraction.
Both expressions are numeric | Subtraction
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Смотрите также

  • variant_add() - "Adds" two variant values together and returns the result

User Contributed Notes

There are no user contributed notes for this page.
variant_set
variant_xor
COM Функции


Performs a logical exclusion on two variants

variant_sub
Принтер
COM Функции
PHP Manual

variant_xor

(PHP 5)

variant_xor — Performs a logical exclusion on two variants

Описание

mixed variant_xor ( mixed $left , mixed $right )

Performs a logical exclusion.

Список параметров

left

The left operand.

right

The right operand.

Замечание:

Как и со всеми вариантными арифметическими функциями, параметры этой функции могут быть как родными PHP типами (integer, string, floating point, boolean или NULL), так и экземплярами классов COM, VARIANT или DOTNET. Родные PHP типы будут преобразованы в варианты (variants) по тем же самым правилам, что и в конструкторе класса VARIANT. У объектов COM и DOTNET будет взято и использовано их значение по умолчанию в качестве значения варианта.

Вариантные арифметические функции являются обертками вокруг одноименных функций в библиотеке COM; для более подробной информации по этим функциям проконсультируйтесь с библиотекой MSDN. Названия PHP-функций немного отличаются; например, variant_add() в PHP соответствует VarAdd() в документации MSDN.

Возвращаемые значения

Variant XOR Rules
If left is | If right is | then the result is
TRUE | TRUE | FALSE
TRUE | FALSE | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
NULL | NULL | NULL

Смотрите также

  • variant_or() - Performs a logical disjunction on two variants
  • variant_and() - Performs a bitwise AND operation between two variants

User Contributed Notes

tinelbarb at yahoo dot com 30-Aug-2010 12:21
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com dot RE-MO-VE dot ME 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
variant_sub
Принтер
COM Функции


Принтер

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Принтер
    • printer_abort — Удаляет файл из буфера подготовки к печати
    • printer_close — Закрывает соединение с принтером
    • printer_create_brush — Create a new brush
    • printer_create_dc — Создает новый контекст устройства
    • printer_create_font — Create a new font
    • printer_create_pen — Create a new pen
    • printer_delete_brush — Удаляет кисть
    • printer_delete_dc — Удаляет контекст устройства
    • printer_delete_font — Удаляет выбранный шрифт
    • printer_delete_pen — Удаляет перо
    • printer_draw_bmp — Рисует bmp
    • printer_draw_chord — Рисует хорду
    • printer_draw_elipse — Рисует эллипс
    • printer_draw_line — Рисует линию
    • printer_draw_pie — Рисует сектор круга
    • printer_draw_rectangle — Рисует прямоугольник
    • printer_draw_roundrect — Рисует прямоугольник со сглаженными углами
    • printer_draw_text — Рисует текст
    • printer_end_doc — Закрывает документ
    • printer_end_page — Закрывает активную страницу
    • printer_get_option — Получает настройки принтера
    • printer_list — Возвращает массив принтеров, подсоединенных к серверу
    • printer_logical_fontheight — Получает логическую высоту шрифта
    • printer_open — Открывает соединение с принтером
    • printer_select_brush — Выбирает кисть
    • printer_select_font — Выбирает шрифт
    • printer_select_pen — Выбирает перо
    • printer_set_option — Настройка соединения с принтером
    • printer_start_doc — Начинает новый документ
    • printer_start_page — Начинает новую страницу
    • printer_write — Отправляет данные на принтер

User Contributed Notes

There are no user contributed notes for this page.
variant_xor
Введение
Расширения только для Windows


Введение

Этим функции доступны только в Windows 9.x, ME, NT4 и 2000. Они были добавлены в PHP 4.0.4.

User Contributed Notes

There are no user contributed notes for this page.
Принтер
Установка и настройка
Принтер


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
Принтер


Установка

Этот модуль » PECL не поставляется с PHP.

Для использования этих функций пользователи Windows должны включить файл php_printer.dll в php.ini. DLL для этого расширения PECL в данный момент недоступна. См. также раздел сборка на Windows.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

Опции конфигурации принтера
Имя | По умолчанию | Меняемо | Список изменений
printer.default_printer | "" | PHP_INI_ALL | Доступно с PHP 4.0.6. Удалено в PHP 4.1.1.
Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.

User Contributed Notes

There are no user contributed notes for this page.
Установка
Типы ресурсов
Установка и настройка


Типы ресурсов

Этот модуль определяет дискрипторы к соединению с принтером, к кисти, к шрифту, к перу.

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

PRINTER_COPIES (integer)
PRINTER_MODE (integer)
PRINTER_TITLE (integer)
PRINTER_DEVICENAME (integer)
PRINTER_DRIVERVERSION (integer)
PRINTER_OUTPUT_FILE (integer)
PRINTER_RESOLUTION_Y (integer)
PRINTER_RESOLUTION_X (integer)
PRINTER_SCALE (integer)
PRINTER_BACKGROUND_COLOR (integer)
PRINTER_PAPER_LENGTH (integer)
PRINTER_PAPER_WIDTH (integer)
PRINTER_PAPER_FORMAT (integer)
PRINTER_FORMAT_CUSTOM (integer)
PRINTER_FORMAT_LETTER (integer)
PRINTER_FORMAT_LEGAL (integer)
PRINTER_FORMAT_A3 (integer)
PRINTER_FORMAT_A4 (integer)
PRINTER_FORMAT_A5 (integer)
PRINTER_FORMAT_B4 (integer)
PRINTER_FORMAT_B5 (integer)
PRINTER_FORMAT_FOLIO (integer)
PRINTER_ORIENTATION (integer)
PRINTER_ORIENTATION_PORTRAIT (integer)
PRINTER_ORIENTATION_LANDSCAPE (integer)
PRINTER_TEXT_COLOR (integer)
PRINTER_TEXT_ALIGN (integer)
PRINTER_TA_BASELINE (integer)
PRINTER_TA_BOTTOM (integer)
PRINTER_TA_TOP (integer)
PRINTER_TA_CENTER (integer)
PRINTER_TA_LEFT (integer)
PRINTER_TA_RIGHT (integer)
PRINTER_PEN_SOLID (integer)
PRINTER_PEN_DASH (integer)
PRINTER_PEN_DOT (integer)
PRINTER_PEN_DASHDOT (integer)
PRINTER_PEN_DASHDOTDOT (integer)
PRINTER_PEN_INVISIBLE (integer)
PRINTER_BRUSH_SOLID (integer)
PRINTER_BRUSH_CUSTOM (integer)
PRINTER_BRUSH_DIAGONAL (integer)
PRINTER_BRUSH_CROSS (integer)
PRINTER_BRUSH_DIAGCROSS (integer)
PRINTER_BRUSH_FDIAGONAL (integer)
PRINTER_BRUSH_HORIZONTAL (integer)
PRINTER_BRUSH_VERTICAL (integer)
PRINTER_FW_THIN (integer)
PRINTER_FW_ULTRALIGHT (integer)
PRINTER_FW_LIGHT (integer)
PRINTER_FW_NORMAL (integer)
PRINTER_FW_MEDIUM (integer)
PRINTER_FW_BOLD (integer)
PRINTER_FW_ULTRABOLD (integer)
PRINTER_FW_HEAVY (integer)
PRINTER_ENUM_LOCAL (integer)
PRINTER_ENUM_NAME (integer)
PRINTER_ENUM_SHARED (integer)
PRINTER_ENUM_DEFAULT (integer)
PRINTER_ENUM_CONNECTIONS (integer)
PRINTER_ENUM_NETWORK (integer)
PRINTER_ENUM_REMOTE (integer)

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Принтер
Принтер


Принтер
PHP Manual

Принтер

Содержание

  • printer_abort — Удаляет файл из буфера подготовки к печати
  • printer_close — Закрывает соединение с принтером
  • printer_create_brush — Create a new brush
  • printer_create_dc — Создает новый контекст устройства
  • printer_create_font — Create a new font
  • printer_create_pen — Create a new pen
  • printer_delete_brush — Удаляет кисть
  • printer_delete_dc — Удаляет контекст устройства
  • printer_delete_font — Удаляет выбранный шрифт
  • printer_delete_pen — Удаляет перо
  • printer_draw_bmp — Рисует bmp
  • printer_draw_chord — Рисует хорду
  • printer_draw_elipse — Рисует эллипс
  • printer_draw_line — Рисует линию
  • printer_draw_pie — Рисует сектор круга
  • printer_draw_rectangle — Рисует прямоугольник
  • printer_draw_roundrect — Рисует прямоугольник со сглаженными углами
  • printer_draw_text — Рисует текст
  • printer_end_doc — Закрывает документ
  • printer_end_page — Закрывает активную страницу
  • printer_get_option — Получает настройки принтера
  • printer_list — Возвращает массив принтеров, подсоединенных к серверу
  • printer_logical_fontheight — Получает логическую высоту шрифта
  • printer_open — Открывает соединение с принтером
  • printer_select_brush — Выбирает кисть
  • printer_select_font — Выбирает шрифт
  • printer_select_pen — Выбирает перо
  • printer_set_option — Настройка соединения с принтером
  • printer_start_doc — Начинает новый документ
  • printer_start_page — Начинает новую страницу
  • printer_write — Отправляет данные на принтер

User Contributed Notes

php at mailinator dot com 19-Feb-2009 07:17
If you want to print to a network printer on another machine:

If you are running PHP on a web server that is running as the System user (quite likely), it won't have access to network resources, including network printers. Changing the web server service to run as an account with access to network printers fixes the issue.
extremesanity 30-May-2007 01:35
I have gotten very reliable printing using this set of functions coupled with Windows 2000, IIS, the PECL extension, and the php_printer.dll.

Basically I have a linux web server that sends a request to the windows 2000 IIS web server (acting as the role of print server) sending the information to be printed in the query string.

I use this primarily for printing barcoded labels, where the barcode itself is a barcode font found on the web.

I got terrible reliability out of all versions of apache running on windows 2000 and xp.
mdwyer at timestreamtech dot com 24-Jan-2007 03:06
I was able to print nice looking reports (under unix) by sending out formatted text out through 'enscript'.  The various configuration options on enscript took care of fonts and headers etc.  The result was a postscript file which I just sent to the server's local printer.

One could also pipe it through a PS to PDF filter and send it back to the user, I suppose.

For another job, I learned how to write postscript and just wrote directly to postscript files.  Learning how to write postscript is probably only marginally harder than learning how to use this API, and is probably more portable.
arne dot briesenick at soxabo dot de 28-Sep-2004 07:42
Printing in UN*X is possible too:

<?php
function lpr($STR,$PRN) {
  $prn=(isset($PRN) && strlen($PRN))?"$PRN":C_DEFAULTPRN ;
  $CMDLINE="lpr -P $prn ";
  $pipe=popen("$CMDLINE" , 'w' );
  if (!$pipe) {print "pipe failed."; return ""; }
  fputs($pipe,$STR);
  pclose($pipe);
} // lpr()
?>

You pipe the stream/string/char/sign whatever to the system. In the example shown above you have to add at least the string for printing in the function call. The second arg is a printer name which if you don't set will be set to the C_DEFAULTPRN. This is a constant definition from an ini file.

Hope this will help to save a lot of time ;-)
jason at matteson dot com 11-Mar-2004 03:01
You can print in XP. AND, you can print to a shared printer with XP. The drivers for the printer MUST be installed on ther server as well as on the computer you wish to print with. Also, the printer must be shared on the client computer.

I am using a Zebra LP2844 Thermal Barcode Printer in my application. I am running XP Pro,Apache 1.3.27, PHP 4.3+.

Here is a function I use in our churches checkin system.  I use this to print directly to our printer with out having to use any Javascript.

First, i give the function the name of the shared printer.

Second, I get the client computers host name. You could use just REMOTE_ADDR too I suppose.

Then I return a correctly formatted Windows path to the shared printer for the

function getPrinter($SharedPrinterName) {
    global $REMOTE_ADDR;
    $host  =  getHostByAddr($REMOTE_ADDR);
    return "\\\\".$host."\\".$SharedPrinterName;
}

$handle  =  printer_open(getPrinter("Eltron"));

So, as long as you KNOW the computers are suppose to have a shared printer called "Eltron", you're all set to start sending info to the printer with the other Printer functions.

-j
macagomez at yahoo dot com 27-Jul-2003 02:35
Please notice that what is printed is NOT measured in pixels, it is measured in pronter's dots.
Apply to fonts, coordinates and bit maps.
jwlash at acm dot org 19-Feb-2003 11:40
I have noticed the for unix based systems you can also do this:

system("lp $filename")

:)
bertATnerdstockDOTorg 20-Jan-2003 04:22
If you want to address the printer from your PHP-application in a Un*x environment:
This is possible if you use a different method.
In Unix it would not be logical to address your printer directly from php, but you could for instance generate a PDF-file with PDFlib (or a textfile, or a PNG/JPEG image with GD or what have you) and write it from your php-script to a directory that you use as a "printer-outbox."

Next, you write a shellscript that calls some unix tool to print all pdf or other documents in your "outbox" directory and then deletes all files in that directory.

Then you use crontab to run this script every minute or as often as you think it's neccessary.

You could of course also call the shellscript from your php-application with exec() but you'll probably want to avoid using exec() and the like for security reasons.
Предопределенные константы
printer_abort
Принтер
PHP Manual


Удаляет файл из буфера подготовки к печати

Принтер
printer_close
Принтер
PHP Manual

printer_abort

(PECL printer SVN)

printer_abort — Удаляет файл из буфера подготовки к печати

Описание

void printer_abort ( resource $printer_handle )

Эта функция удаляет файл из буфера подготовки к печати.

Список параметров

printer_handle

printer_handle должен быть действующим дескриптором принтера.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_abort()

<?php
$handle = printer_open();
printer_abort($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
Принтер
printer_close
Принтер


Закрывает соединение с принтером

printer_abort
printer_create_brush
Принтер
PHP Manual

printer_close

(PECL printer SVN)

printer_close — Закрывает соединение с принтером

Описание

void printer_close ( resource $printer_handle )

Эта функция закрывает соединение с сервером. printer_close() также закрывает активный контекст устройства.

Список параметров

printer_handle

printer_handle должен быть активным дескриптором устройства.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_close()

<?php
$handle = printer_open();
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_abort
printer_create_brush
Принтер


Create a new brush

printer_close
printer_create_dc
Принтер
PHP Manual

printer_create_brush

(PECL printer SVN)

printer_create_brush — Create a new brush

Описание

resource printer_create_brush ( int $style , string $color )

The function creates a new brush and returns a handle to it. A brush is used to fill shapes. For an example see printer_select_brush().

Список параметров

style

style must be one of the following constants:

  • PRINTER_BRUSH_SOLID: creates a brush with a solid color.
  • PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).
  • PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).
  • PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).
  • PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).
  • PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).
  • PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).
  • PRINTER_BRUSH_CUSTOM: creates a custom brush from an BMP file. The second parameter is used to specify the BMP instead of the RGB color code.

color

color must be a color in RGB hex format, i.e. "000000" for black.

Возвращаемые значения

Returns a brush handle or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.
printer_close
printer_create_dc
Принтер


Создает новый контекст устройства

printer_create_brush
printer_create_font
Принтер
PHP Manual

printer_create_dc

(PECL printer SVN)

printer_create_dc — Создает новый контекст устройства

Описание

void printer_create_dc ( resource $printer_handle )

Эта функция создает новый контекст устройства. Контекст устройства используется для настройки графических объектов документа.

Список параметров

printer_handle

printer_handle должен быть активным дескриптором устройства.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_create_dc()

<?php
$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);

printer_create_dc($handle);
/* Тут выполняем некоторые операции с контекстом устройства */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);

/* Создаем другой контекст устройства */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* Тут выполняем некоторые операции с контекстом устройства */

printer_delete_dc($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_create_brush
printer_create_font
Принтер


Create a new font

printer_create_dc
printer_create_pen
Принтер
PHP Manual

printer_create_font

(PECL printer SVN)

printer_create_font — Create a new font

Описание

resource printer_create_font ( string $face , int $height , int $width , int $font_weight , bool $italic , bool $underline , bool $strikeout , int $orientation )

The function creates a new font and returns a handle to it. A font is used to draw text. For an example see printer_select_font().

Список параметров

face

face must be a string specifying the font face.

height

height specifies the font height.

width

width specifies the font width.

font_weight

The font_weight specifies the font weight (400 is normal), and can be one of the following predefined constants.

  • PRINTER_FW_THIN: sets the font weight to thin (100).
  • PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).
  • PRINTER_FW_LIGHT: sets the font weight to light (300).
  • PRINTER_FW_NORMAL: sets the font weight to normal (400).
  • PRINTER_FW_MEDIUM: sets the font weight to medium (500).
  • PRINTER_FW_BOLD: sets the font weight to bold (700).
  • PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).
  • PRINTER_FW_HEAVY: sets the font weight to heavy (900).

italic

italic can be TRUE or FALSE, and sets whether the font should be italic.

underline

underline can be TRUE or FALSE, and sets whether the font should be underlined.

strikeout

strikeout can be TRUE or FALSE, and sets whether the font should be stroked out.

orientaton

orientation specifies a rotation.

Возвращаемые значения

Returns a font handle on success or FALSE on error.

User Contributed Notes

extremesanity 19-Sep-2006 10:12
Two tips:

- An orientation of -900 is up and down.

- You can print barcodes by installing a free barcode font like Code39 on the window machine with php installed and then selecting it as a font.
josh at engledental dot com 29-Jun-2002 08:30
Note that the orientation value is a 3-digit number where, for instance, an orientation of 90� requires a value of 900.
printer_create_dc
printer_create_pen
Принтер


Create a new pen

printer_create_font
printer_delete_brush
Принтер
PHP Manual

printer_create_pen

(PECL printer SVN)

printer_create_pen — Create a new pen

Описание

resource printer_create_pen ( int $style , int $width , string $color )

The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an example see printer_select_pen().

Список параметров

style

style must be one of the following constants:

  • PRINTER_PEN_SOLID: creates a solid pen.
  • PRINTER_PEN_DASH: creates a dashed pen.
  • PRINTER_PEN_DOT: creates a dotted pen.
  • PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.
  • PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.
  • PRINTER_PEN_INVISIBLE: creates an invisible pen.

width

width specifies the width of the pen.

color

color must be a color in RGB hex format, i.e. "000000" for black.

Возвращаемые значения

Returns a pen handle or FALSE on error.

User Contributed Notes

Pierchi 05-Feb-2006 02:55
<?

$pen = printer_create_pen(stile, larghezza, "colore");

//EXAMPLE:
$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");

?>
printer_create_font
printer_delete_brush
Принтер


Удаляет кисть

printer_create_pen
printer_delete_dc
Принтер
PHP Manual

printer_delete_brush

(PECL printer SVN)

printer_delete_brush — Удаляет кисть

Описание

void printer_delete_brush ( resource $brush_handle )

Эта функция удаляет выбранную кисть. За примером обращайтесь к описанию функции printer_select_brush().

Список параметров

brush_handle

brush_handle должен быть действительным дескриптором кисти.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

There are no user contributed notes for this page.
printer_create_pen
printer_delete_dc
Принтер


Удаляет контекст устройства

printer_delete_brush
printer_delete_font
Принтер
PHP Manual

printer_delete_dc

(PECL printer SVN)

printer_delete_dc — Удаляет контекст устройства

Описание

bool printer_delete_dc ( resource $printer_handle )

Эта функция удаляет контекст устройства. За примером обращайтесь к описанию функции printer_create_dc().

Список параметров

printer_handle

printer_handle должен быть активным дескриптором устройства.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
printer_delete_brush
printer_delete_font
Принтер


Удаляет выбранный шрифт

printer_delete_dc
printer_delete_pen
Принтер
PHP Manual

printer_delete_font

(PECL printer SVN)

printer_delete_font — Удаляет выбранный шрифт

Описание

void printer_delete_font ( resource $font_handle )

Эта функция удаляет выбранный шрифт. За примером обращайтесь к описанию функции printer_select_font().

Список параметров

font_handle

font_handle должен быть действительным дескриптором шрифта.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

There are no user contributed notes for this page.
printer_delete_dc
printer_delete_pen
Принтер


Удаляет перо

printer_delete_font
printer_draw_bmp
Принтер
PHP Manual

printer_delete_pen

(PECL printer SVN)

printer_delete_pen — Удаляет перо

Описание

void printer_delete_pen ( resource $pen_handle )

Эта функция удаляет выбранное перо. За примером обращайтесь к описанию функции printer_select_pen().

Список параметров

pen_handle

pen_handle должен быть действительным дескриптором пера.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

There are no user contributed notes for this page.
printer_delete_font
printer_draw_bmp
Принтер


Рисует bmp

printer_delete_pen
printer_draw_chord
Принтер
PHP Manual

printer_draw_bmp

(PECL printer SVN)

printer_draw_bmp — Рисует bmp

Описание

bool printer_draw_bmp ( resource $printer_handle , string $filename , int $x , int $y [, int $width ], int $height )

Эта функция рисует картинку из файла с расширением .bmp.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

filename

Путь к рисуемому файлу bmp.

x

Верхняя левая координата x картинки.

y

Верхняя левая координата y картинки.

width

Ширина картинки.

height

Высота картинки.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример printer_draw_bmp()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_draw_bmp($handle, "c:\\image.bmp", 1, 1);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

codeslinger at compsalot dot com 21-Feb-2007 11:47
Don't get confused by the example.  The X Y offset is Base 0  not 1.  The example was trying to show that you could position the image elsewhere.

Also, the X Y offsets accept a negative value which can be very handy if you want to print just part of the image.  Such as when splitting an image across multiple pages.

Most (all?) printers will shift your output by the amount of the "unprintable" area.

Suppose you want to print an image at exactly X = 0.25, Y = 0.25 inches (from the top left).

On a typical printer with an unprintable area of 0.116 inches, the printer adds that amount as an offset.  So, to compensate you just subtract the offset.

$X = 0.25 - 0.116;
$Y = 0.25 - 0.116;

With the result being that your image will be physically located where you intended.

Keep in mind that the unprintable area can be a different amount for the X and Y, for this example printer they both just happen to be the same.

Now the catch is that printer_get_option does not provide a way to get the unprintable area size.
Fuzzmaster 31-Jan-2006 03:30
Added a bit a fuzz:

  function print_img($doc,$img,$res,$pos_x,$pos_y)
    {
     $img_size = getimagesize($img);
     $img_resolution = $res;

     $img_width = $img_size[0];
     $img_height = $img_size[1];

     echo $img_width.'<BR>';
     echo $img_height.'<BR>';

     $ptr_resolution_x = printer_get_option($doc, PRINTER_RESOLUTION_X);
     $ptr_resolution_y = printer_get_option($doc, PRINTER_RESOLUTION_Y);

     echo $ptr_resolution_x.'<BR>';
     echo $ptr_resolution_y.'<BR>';

     $img_scale_x = $ptr_resolution_x / $img_resolution;
     $img_scale_y = $ptr_resolution_y / $img_resolution;

     echo $img_scale_x.'<BR>';
     echo $img_scale_y.'<BR>';

     $ptr_width = $img_width * $img_scale_x;
     $ptr_height = $img_height * $img_scale_y;

     echo $doc.'<BR>';
     echo $ptr_width.'<BR>';
     echo $ptr_height.'<BR>';

     printer_draw_bmp($doc,$img,$pos_x,$pos_y,$ptr_width,$ptr_height);
    }

print_img($handle, '../img/someimage.bmp', 72, 10, 10);

Of course, if someone can figure out how to capture the resolution of the image from the file that's one less value to manually assign.
ramiro_puc[AT]hotmail[DOT]com 15-Jan-2006 02:51
When trying to print any image file it was getting a very, very small as someone said above. To solve this problem, ive made a script that will calculate the correct size of image before output it to printer.

Most of InkJet printers use 300 dpi. You can change values if you have any other printer... In this case, im using a HP DeskJet 930c.

To make this script better, you can use GD to discover image resolution automatically.

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$largura = 415; //Image Width in Pixels
$altura = 284;  //Image Height in Pixels

$fator_x = $largura / 72; //Image Resolution (72 ppi)
$fator_y = $largura / 300; //Printer Resolution (300 dpi)
$fator_z = $fator_x / $fator_y;

$largura_f = $largura * $fator_z;
$altura_f = $altura * $fator_z;

printer_set_option($handle, PRINTER_MODE, "RAW");
printer_draw_bmp($handle, "c:\image.bmp", 1, 1, $largura_f, $altura_f);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>
da_vinci7[at]hotmail[dot]com 17-Mar-2005 02:25
what i notice was that
[qoute]
void printer_draw_bmp ( resource handle, string filename, int x, int y)
[/qoute]
is only that here only the starting x and y are shown
and that if you have an bmp with the size 600 x 120 wil be shown as 600x120 pixels and printed very very smale

and when i tried giving ending x and y like this:
<?
  printer_draw_bmp($handle, $file, 1, 1, 4600, 860)
?>

it printed the image in the correct size
lapoA at TseanetD dot O dot Tcom 08-Dec-2004 10:08
something I found out the hard way...
in order for the example above to work, the file being printed must be in a directory that has been opened for reading.
The example in the docs should probably have been listed as:
(There should probably be a check for the filename, but this should give an idea)

<?php
$dir = 'c:\\somedir';
$file = 'myimage.bmp';

if (is_dir($dir)) {
   if($dhandle = opendir($dir)) {
      $handle = printer_open();
      printer_start_doc($handle, "My Document");
      printer_start_page($handle);

      printer_draw_bmp($handle, $file, 1, 1);

      printer_end_page($handle);
      printer_end_doc($handle);
      printer_close($handle);
   }
   closedir($dhandle);
}
?>
printer_delete_pen
printer_draw_chord
Принтер


Рисует хорду

printer_draw_bmp
printer_draw_elipse
Принтер
PHP Manual

printer_draw_chord

(PECL printer SVN)

printer_draw_chord — Рисует хорду

Описание

void printer_draw_chord ( resource $printer_handle , int $rec_x , int $rec_y , int $rec_x1 , int $rec_y1 , int $rad_x , int $rad_y , int $rad_x1 , int $rad_y1 )

Эта функция рисует хорду.

Список параметров

printer_handle

printer_handle должен быть корректным дескриптором принтера.

rec_x

rec_x - координата x верхнего левого угла ограничивающего прямоугольника.

rec_y

rec_y - координата y верхнего левого угла ограничивающего прямоугольника.

rec_x1

rec_x1 - координата x нижнего правого угла ограничивающего прямоугольника.

rec_y1

rec_y1 - координата y нижнего правого угла ограничивающего прямоугольника.

rad_x

rad_x - координата x луча, определяющая начало хорды.

rad_y

rad_y - координата y луча, определяющая начало хорды.

rad_x1

rad_x1 - координата x луча, определяющая конец хорды.

rad_y1

rad_y1 - координата y луча, определяющего конец хорды.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования printer_draw_chord()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_chord($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_draw_bmp
printer_draw_elipse
Принтер


Рисует эллипс

printer_draw_chord
printer_draw_line
Принтер
PHP Manual

printer_draw_elipse

(PECL printer SVN)

printer_draw_elipse — Рисует эллипс

Описание

void printer_draw_elipse ( resource $printer_handle , int $ul_x , int $ul_y , int $lr_x , int $lr_y )

Эта функция рисует эллипс.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

ul_x

ul_x - верхняя левая координата x эллипса.

ul_y

ul_y - верхняя левая координата y эллипса.

lr_x

lr_x - нижняя правая координата x эллипса.

lr_y

lr_y - нижняя правая координата y эллипса.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_draw_elipse()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_elipse($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_draw_chord
printer_draw_line
Принтер


Рисует линию

printer_draw_elipse
printer_draw_pie
Принтер
PHP Manual

printer_draw_line

(PECL printer SVN)

printer_draw_line — Рисует линию

Описание

void printer_draw_line ( resource $printer_handle , int $from_x , int $from_y , int $to_x , int $to_y )

Эта функция рисует линию, используя выбранное перо.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

from_x

from_x - координата x начальной точки.

from_y

from_y - координата y начальной точки.

to_x

to_x - координата x конечной точки.

to_y

to_y - координата y конечной точки.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_draw_line()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 10, 1000, 10);
printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_draw_elipse
printer_draw_pie
Принтер


Рисует сектор круга

printer_draw_line
printer_draw_rectangle
Принтер
PHP Manual

printer_draw_pie

(PECL printer SVN)

printer_draw_pie — Рисует сектор круга

Описание

void printer_draw_pie ( resource $printer_handle , int $rec_x , int $rec_y , int $rec_x1 , int $rec_y1 , int $rad1_x , int $rad1_y , int $rad2_x , int $rad2_y )

Эта функция рисует сектор круга.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

rec_x

rec_x - верхняя левая координата x ограничивающего прямоугольника.

rec_y

rec_y - верхняя левая координата y ограничивающего прямоугольника.

rec_x1

rec_x1 - нижняя правая координата x ограничивающего прямоугольника.

rec_y1

rec_y1 - нижняя правая координата y ограничивающего прямоугольника.

rad1_x

rad1_x - координата x окончания первого луча.

rad1_y

rad1_y - координата y окончания первого луча.

rad2_x

rad2_x - координата x окончания второго луча.

rad2_y

rad2_y - координата y окончания второго луча.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_draw_pie()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_pie($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_draw_line
printer_draw_rectangle
Принтер


Рисует прямоугольник

printer_draw_pie
printer_draw_roundrect
Принтер
PHP Manual

printer_draw_rectangle

(PECL printer SVN)

printer_draw_rectangle — Рисует прямоугольник

Описание

void printer_draw_rectangle ( resource $printer_handle , int $ul_x , int $ul_y , int $lr_x , int $lr_y )

Эта функция рисует прямоугольник.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

ul_x

ul_x - верхняя левая координата x прямоугольника.

ul_y

ul_y - верхняя левая координата y прямоугольника.

lr_x

lr_x - нижняя правая координата x прямоугольника.

lr_y

lr_y - нижняя правая координата y прямоугольника.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_draw_rectangle()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_draw_pie
printer_draw_roundrect
Принтер


Рисует прямоугольник со сглаженными углами

printer_draw_rectangle
printer_draw_text
Принтер
PHP Manual

printer_draw_roundrect

(PECL printer SVN)

printer_draw_roundrect — Рисует прямоугольник со сглаженными углами

Описание

void printer_draw_roundrect ( resource $printer_handle , int $ul_x , int $ul_y , int $lr_x , int $lr_y , int $width , int $height )

Эта функция рисует прямоугольник со сглаженными углами.

Список параметров

printer_handle

printer_handle должен быть действительный дескриптор.

ul_x

ul_x - координата x верхнего левого угла прямоугольника.

ul_y

ul_y - координата y верхнего левого угла прямоугольника.

lr_x

lr_x - координата x нижнего правого угла прямоугольника.

lr_y

lr_y - координата y нижнего правого угла прямоугольника.

width

width - ширина эллипса.

height

height - высота эллипса.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_draw_roundrect()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_roundrect($handle, 1, 1, 500, 500, 200, 200);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_draw_rectangle
printer_draw_text
Принтер


Рисует текст

printer_draw_roundrect
printer_end_doc
Принтер
PHP Manual

printer_draw_text

(PECL printer SVN)

printer_draw_text — Рисует текст

Описание

void printer_draw_text ( resource $printer_handle , string $text , int $x , int $y )

Эта функция рисует текст text на позиции x, y, используя выбранный шрифт.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

text

Текст, который должен быть отрисован.

x

Координата x места отрисовки текста.

y

Координата y места отрисовки текста.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_draw_text()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 72, 48, 400, false, false, false, 0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

frank dot liebelt at edico-gmbh dot de 22-Jun-2004 01:03
Placing text or other elements on a page could be a worst thing.
I wrote and use now the following code to print out a page as orientation help.
The creation time will be much shorter...

[CODE]
<?php
$p = printer_open();
printer_set_option($p, PRINTER_PAPER_FORMAT, PRINTER_FORMAT_A4);
printer_start_doc($p, "Testpage");
printer_start_page($p);
$pen = printer_create_pen(PRINTER_PEN_SOLID, 1, "000000");
$font = printer_create_font("Courier", 37, 19, PRINTER_FW_NORMAL, false, false, false, 0);

printer_select_pen($p, $pen);
printer_select_font($p, $font);

for ($i = 0; $i < 4600; $i+=100)
{
printer_draw_line($p, $i,0,$i,6700);
printer_draw_text($p,$i,$i,0);
}
for ($i = 0; $i < 6700; $i+=100)
{
printer_draw_line($p, 0,$i,4600,$i);
printer_draw_text($p,$i,0,$i);
}

printer_delete_font($font);
printer_delete_pen($pen);
printer_end_page($p);
printer_end_doc($p);
printer_close($p);
?>
[/CODE]

btw.
Has anyone a list for character sizes (x,y)? Like:
12px = 50, 12
14px = 60, 20

Frank
firman at fibconsultant dot biz 14-Oct-2003 06:20
I've a problem with the right alignment for number with draw_text so I make a small function and it is work for me, hopefully it will help other.

function write_num($input,$printer,$ypos,$xpos){
    $s=strlen($input);
    $y=$xpos;
    for ($i=1;$i<$s+1;$i++){
        $u=$i*-1;
        printer_draw_text($printer,substr($input,$u,1),$y,$ypos);
        $y=$y-15;
    }
}

Firman, Indonesia
printer_draw_roundrect
printer_end_doc
Принтер


Закрывает документ

printer_draw_text
printer_end_page
Принтер
PHP Manual

printer_end_doc

(PECL printer SVN)

printer_end_doc — Закрывает документ

Описание

bool printer_end_doc ( resource $printer_handle )

Закрывает новый документ в спулере принтера. После этого документ готов к печати. За примером обращайтесь к описанию функции printer_start_doc().

Список параметров

printer_handle

printer_handle должен быть действительным дескриптером принтера.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
printer_draw_text
printer_end_page
Принтер


Закрывает активную страницу

printer_end_doc
printer_get_option
Принтер
PHP Manual

printer_end_page

(PECL printer SVN)

printer_end_page — Закрывает активную страницу

Описание

bool printer_end_page ( resource $printer_handle )

Функция закрывает активную страницу в активном документе. За примером обращайтесь к описанию функции printer_start_doc().

Список параметров

printer_handle

printer_handle должен быть действительным дескриптером принтера.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
printer_end_doc
printer_get_option
Принтер


Получает настройки принтера

printer_end_page
printer_list
Принтер
PHP Manual

printer_get_option

(PECL printer SVN)

printer_get_option — Получает настройки принтера

Описание

mixed printer_get_option ( resource $printer_handle , string $option )

Эта функция получает настройки опции, указанной в параметре option.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

option

Прочитайте о функции printer_set_option(), чтобы узнать какие опции вы можете прочитать. Также доступны следующие настройки:

  • PRINTER_DEVICENAME возвращает название принтера.
  • PRINTER_DRIVERVERSION возвращает версию драйвера принтера.

Возвращаемые значения

Возвращает значение параметра, указанного в option.

Примеры

Пример #1 Пример printer_get_option()

<?php
$handle = printer_open();
echo printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_end_page
printer_list
Принтер


Возвращает массив принтеров, подсоединенных к серверу

printer_get_option
printer_logical_fontheight
Принтер
PHP Manual

printer_list

(PECL printer SVN)

printer_list — Возвращает массив принтеров, подсоединенных к серверу

Описание

array printer_list ( int $enumtype [, string $name [, int $level ]] )

Функция перечисляет доступные принтеры и их возможности.

Список параметров

enumtype

enumtype должен равнятся одной из нижеперечисленных констант:

  • PRINTER_ENUM_LOCAL: указывает локально установленные принтеры.
  • PRINTER_ENUM_NAME: указывает принтеры, принадлежащие name, который может быть сервером, доментом или провайдером печати.
  • PRINTER_ENUM_SHARED: этот параметр не может быть использован индивидуально, он должен быть присоединен к другим параметрам битовой операцией ИЛИ (|), к примеру к PRINTER_ENUM_LOCAL, чтобы определить локальные расшаренные принтеры.
  • PRINTER_ENUM_DEFAULT: (Только для Win9.x) указывает принтер по-умолчанию.
  • PRINTER_ENUM_CONNECTIONS: (Только для WinNT/2000) указывает принтеры, с которыми пользователь установил соединение.
  • PRINTER_ENUM_NETWORK: (Только для WinNT/2000) указывает сетевые принтеры в домене компьютера. Работает только если параметр level равен 1.
  • PRINTER_ENUM_REMOTE: (Только для WinNT/2000) указывает сетевые принтеры и сервера печати домене компьютера. Работает только если параметр level равен 1.

name

Используется с PRINTER_ENUM_NAME.

level

level указывает уровень запроса информации. Может быть 1,2,4 или 5.

Возвращаемые значения

Возвращает массив принтеров.

Примеры

Пример #1 Пример printer_list()

<?php
/* обнаружает локальные расшаренные принтеры */
var_dump(printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED));
?>

User Contributed Notes

ewilde aht bsmdevelopment dawt com 06-Feb-2007 11:14
First, before you do anything, make sure you have a copy of php_printer.dll that is dated later than the first of February, 2007 because there were several parameter handling bugs that were fixed just prior to that date.

Also, beware that the Windows function EnumPrinters often does not return all of the networked printers until someone on the Web server uses the file manager to look at the networked printers, first.  I'm presuming this causes the server to contact the domain controller for the browse list, which is then used to enumerate the printers.  It does not appear that EnumPrinters will do this on its own, although some of the other values for flags may cause it to do so.

Having said all that, the following code should show you both local and networked printers:

if (function_exists("printer_list"))
  {
  $PrintCurr = 0;

  // Get the local printers.
  $PrintDests = printer_list(PRINTER_ENUM_LOCAL);

  if (isset($PrintDests))
    foreach ($PrintDests as $PrintDest)
      $PrinterList[$PrintCurr++] = $PrintDest["NAME"];

  // We should be able to enumerate the remote printers too.  Let's have a
  // shot at it.
  //
  // Start by looking for the remote printers tree.
  $PrintDoms = printer_list(PRINTER_ENUM_NAME); $PrintTree = "";

  if (isset($PrintDoms))
    foreach ($PrintDoms as $PrintDomain)
      {
      if (preg_match("/Remote/i", $PrintDomain["NAME"]))
        { $PrintTree = $PrintDomain["NAME"]; break; }
      }

  // If we found a remote printers tree, we need to enumerate all of the
  // domains/workgroups/nodes within the tree and all the printers attached
  // to those nodes.
  if ($PrintTree != "")
    {
    // Enumerate all of the domains.
    $PrintDoms = printer_list(PRINTER_ENUM_NAME, $PrintTree);

    if (isset($PrintDoms))
      foreach ($PrintDoms as $PrintDomain)
        {
        // Enumerate all of the nodes within the domain.
        $PrintNodes = printer_list(PRINTER_ENUM_NAME, $PrintDomain["NAME"]);

        if (isset($PrintNodes))
          foreach ($PrintNodes as $PrintNode)
            {
            // Enumerate all of the printers within the node.
            $PrintDests = printer_list(PRINTER_ENUM_NAME,
              $PrintNode["NAME"]);

            if (isset($PrintDests))
              foreach ($PrintDests as $PrintDest)
                $PrinterList[$PrintCurr++] = $PrintDest["NAME"];
            }
        }
    }
  }
ewilde aht bsmdevelopment dawt com 30-Jan-2007 07:21
printer_list was not working for me and the docs are a little sparse.  So, I took a look at the code for php_printer.dll (which is at http://viewcvs.php.net/viewvc.cgi/pecl/printer/printer.c, BTW) to figure out what was going on.

Basically, this function is a wrapper for the Windows function EnumPrinters.  You can find this function documented in MSDN (which is at http://msdn.microsoft.com).  Do a search for EnumPrinters and you should see the function itself as the first hit in the search list.

There is a lot more information about what the parameters to the function mean and the results returned.  The printer_list function basically copies the enumtype, name and level parameters directly to the Flags, Name and Level parameters of EnumPrinters, calls the function and then copies all of the fields, in the appropriate data structure returned for the level of information requested, back to the results array.
gabriel dot smagghe at laposte dot net 13-Oct-2005 01:33
You can use all the array data, with no crash.
For that you can do this :

$getprt=printer_list(PRINTER_ENUM_LOCAL| PRINTER_ENUM_SHARED );

if ($debugprt){echo "<pre> get prt";
    print_r($getprt);
    echo "</pre>";
    echo count($getprt);
}
$printers = serialize($getprt);
//echo $printers ;
$pp=str_replace _
(";s:11:\"DESCRIPTION\";",";s:4:\"DESC\";",_
str_replace(";s:7:\"COMMENT\";",";s:4:\"COMM\";",$printers));
$printers=unserialize($pp);
if ($debugprt){echo "<pre> pp :";

    print_r($printers);
    echo "</pre>";
    echo count($printers);
}

An that's ok
jt at jtis dot de 06-Dec-2004 03:19
As saidyjade mentioned below, printer_list crashes Apache when you pound the resulting array too much. I don't know why this happens, somebody should look deeper into the subject...
I have found out, contrary to saidyjade, that also just getting the NAME attribute (and remember, it's case-sensitive! :-) can crash Apache.

Here's what I had:
<?php
    foreach (printer_list(PRINTER_ENUM_CONNECTIONS) as $printer)
        echo "<option value=\"" . addslashes(strtoupper($printer["NAME"])) . "\">" . strtoupper($printer["NAME"]) . "\n";
?>
This snippet worked alright, whereas
<?php
    foreach (printer_list(PRINTER_ENUM_CONNECTIONS) as $printer)
        echo "<option value=\"" . addslashes(strtoupper($printer["NAME"])) . "\"" . ((strtoupper($printer["NAME"])) ? " selected" : "") . ">" . strtoupper($printer["NAME"]) . "\n";
?>
crashed Apache everytime the page was loaded.

I played around a bit and found this snippet not crashing:
<?php
    foreach (printer_list(PRINTER_ENUM_CONNECTIONS) as $printer)
    {
        $curprin = strtoupper($printer["NAME"]);
        echo "<option value=\"" . addslashes($curprin) . "\"" . (($curprin == $user["drucker"]) ? " selected" : "") . ">$curprin\n";
    }
?>

So, in essence you just need to be careful about how much you use the array and if necessary define help variables that you can use as much as you want.

Hope this saves somebody some more minutes...
saidyjade at hotmail dot com 14-Jun-2003 11:52
You can still get the "NAME" of printers through the printer_list as only the array keys "DESCRIPTION" and "COMMENT" crash and not the "NAME" key.

$list_printers = printer_list(PRINTER_ENUM_LOCAL |
PRINTER_ENUM_SHARED);

// get the name of the first returned printer
//(you can add array walk function to get all printer names if you wish.. but I am lazy)

$this_printer = $list_printers[0]["NAME"];

// open a connection to your printer
$my_printer = printer_open($this_printer);

.. blah blah

The output of var_dump (as an example)

var_dump( printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED) );

array(1) {
  [0]=> array(3) {
  ["NAME"]=> string(14) "Canon BJC-4550"
  ["DESCRIPTION"]=> string(30) "Canon BJC-4550,Canon BJC-4550,"
  ["COMMENT"]=> string(0) "This is my funky printer!" } }

As you can see var_dump (under variable functions in the manual) shows and/or retrieves the corrent information but if you try to place into a variable or read the variable it crashes either apache using php4apache.dll or php when you the command line client or cgi.

So as long as you do not get the comment or description it will list your printers.
printer_get_option
printer_logical_fontheight
Принтер


Получает логическую высоту шрифта

printer_list
printer_open
Принтер
PHP Manual

printer_logical_fontheight

(PECL printer SVN)

printer_logical_fontheight — Получает логическую высоту шрифта

Описание

int printer_logical_fontheight ( resource $printer_handle , int $height )

Функция вычисляет логическую высоту шрифта height.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором шрифта.

height

Высота шрифта.

Возвращаемые значения

Возвращает логическую высоту шрифта или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример printer_logical_fontheight()

<?php
$handle = printer_open();
echo printer_logical_fontheight($handle, 72);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_list
printer_open
Принтер


Открывает соединение с принтером

printer_logical_fontheight
printer_select_brush
Принтер
PHP Manual

printer_open

(PECL printer SVN)

printer_open — Открывает соединение с принтером

Описание

resource printer_open ([ string $printername ] )

Функция пытается открыть соединение с указанным принетром.

printer_open() также создает контекст устройства.

Список параметров

printername

Имя принтера. Если параметр не указан, функция пытается установить соединение с принтером по-умолчанию (если он не указан в php.ini как printer.default_printer, PHP попытается найти его самостоятельно).

Возвращаемые значения

В случае успеха возвращает дескриптор принтера или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример printer_open()

<?php
$handle = printer_open("HP Deskjet 930c");
$handle = printer_open();
?>

User Contributed Notes

Sunny Chan from HK 18-Jun-2009 09:03
If you cannot print on a client shared printer, you may create a admin user account, and assign it to run Apache under Windows Service.
John Middleton 20-Mar-2009 10:09
I had been playing around with trying to get PHP to print to a network server off and on for quite some time, and I finally came across somebody who had the piece of the puzzle I've been missing.

Like I said, the printer I've been trying to print to is a network printer, so I had been trying to open the printer as follows:

<?php printer_open("\\\\servername\\printername"); ?>

What I had been missing is that the function needed the internet host name of the server, which includes the domain name.  So, let's say my print server was called "PServer" and my network's domain was called php.net:

<?php printer_open("\\\\Pserver.php.net\\printername"); ?>

This will more than likely work, then you can open and print a file as follows:

<?php
$printer = "\\\\Pserver.php.net\\printername");
if($ph = printer_open($printer))
{
   // Get file contents
   $fh = fopen("filename.ext", "rb");
   $content = fread($fh, filesize("filename.ext"));
   fclose($fh);

   // Set print mode to RAW and send PDF to printer
   printer_set_option($ph, PRINTER_MODE, "RAW");
   printer_write($ph, $content);
   printer_close($ph);
}
else "Couldn't connect...";
?>
knightcon at bluebottle dot com 14-Dec-2006 05:04
If you are desperate to do server-side printing with PHP on a *nix machine then you can always use the fsockopen() function and send a pre-build PJL (Printer Job Language) string directly to the printer. As long as your printer supports PJL then there should be no problem. Just also bare in mind that unless you are doing something very special, like sending the print job to a remote printer and not the printer the client is at you should just make a report page generated by php and apply a css stylesheet which makes the page styled for printing.
philip 29-Mar-2005 02:39
This function may also return NULL on failure, instead of FALSE.
jt at jtis dot de 31-Aug-2004 03:39
Revision: Single quotes DO work, but with a triple slash, like
printer_open('\\\SERVERNAME\PRINTERNAME');

Weird.
jasonlam_ at hotmail dot com 04-Jun-2003 04:22
Connecting to Network Printers
<?php
   $handle = printer_open("\\\\DOMAIN_NAME\\Printer_Name");
?>
Similiar to how you would locate a domain on your network
you need to have 2 prefix slashes.  But as reminder
you need to escape it.  So really you need 4 slashes.  It
worked me. Hopefully this helps who is having problems
connecting to network printer.
csammis at iastate dot edu 30-Apr-2002 07:38
As stated on the index page for all the printer functions, these are supported under Win32 *only*...in fact, they're frontends API calls. I'd go ahead and say that they would probably never be ported to *nix because of the many various ways of handling printers. Windows, for all its faults, at least has a unified printing system.

As to editing the php.ini, try it with no path at all, like the first example here
printer_logical_fontheight
printer_select_brush
Принтер


Выбирает кисть

printer_open
printer_select_font
Принтер
PHP Manual

printer_select_brush

(PECL printer SVN)

printer_select_brush — Выбирает кисть

Описание

void printer_select_brush ( resource $printer_handle , resource $brush_handle )

Эта функция выбирает выбирает кисть, которая становится активным объектом рисования для текущего контекста устройства. Кисть используется для закраски фигур. Если вы рисуете прямоугольник, кисть используется для рисования фигуры, а перо используется для рисования краев.

Если вы не выберите кисть до рисования фигуры, фигура будет незакрашенной.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором устройства.

brush_handle

brush_handle должен быть действительным дескриптором кисти.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_select_brush()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);
$brush = printer_create_brush(PRINTER_BRUSH_CUSTOM, "c:\\brush.bmp");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1, 501, 500, 1001);
printer_delete_brush($brush);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_open
printer_select_font
Принтер


Выбирает шрифт

printer_select_brush
printer_select_pen
Принтер
PHP Manual

printer_select_font

(PECL printer SVN)

printer_select_font — Выбирает шрифт

Описание

void printer_select_font ( resource $printer_handle , resource $font_handle )

Эта функция выбирает шрифт для рисования текста.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором устройства.

font_handle

font_handle должен быть действительным дескриптором шрифта.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_select_font()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_select_brush
printer_select_pen
Принтер


Выбирает перо

printer_select_font
printer_set_option
Принтер
PHP Manual

printer_select_pen

(PECL printer SVN)

printer_select_pen — Выбирает перо

Описание

void printer_select_pen ( resource $printer_handle , resource $pen_handle )

Эта функция выбирает выбирает перо, которое становится активным объектом рисования для текущего контекста устройства. Перо используется для рисования прямых и кривых линий. К примеру, если вы рисуете одиночную линию, используется перо. Если вы рисуете прямоугольник, перо используется для рисования краев, а кисть используется для закраски фигуры. Если вы не выберите перо перед рисованием, фигура не будет иметь кромки.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

pen_handle

pen_handle должен быть действительным дескриптором пера.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример printer_select_pen()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "2222FF");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_select_font
printer_set_option
Принтер


Настройка соединения с принтером

printer_select_pen
printer_start_doc
Принтер
PHP Manual

printer_set_option

(PECL printer SVN)

printer_set_option — Настройка соединения с принтером

Описание

bool printer_set_option ( resource $printer_handle , int $option , mixed $value )

Эта функция настраивает опции для текущего соединения.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптором принтера.

option

Этот параметр может быть одной из следующих констант:

  • PRINTER_COPIES: указывает, сколько копий должно быть напечатано, value должен быть целым числом(integer).
  • PRINTER_MODE: указывает тип данных (text, raw или emf), value должен быть строкового типа(string).
  • PRINTER_TITLE: указывает имя документа, value должен быть строкового типа(string).
  • PRINTER_ORIENTATION: указывает ориентирование бумаги, value может быть или PRINTER_ORIENTATION_PORTRAIT, или PRINTER_ORIENTATION_LANDSCAPE
  • PRINTER_RESOLUTION_Y: указывает вертикальное разрешение в точках на дюйм, value должен быть целым числом(integer).
  • PRINTER_RESOLUTION_X: указывает горизонтальное разрешение в точках на дюйм, value должен быть целым числом(integer).
  • PRINTER_PAPER_FORMAT: указывает предопределенный формат бумаги, установите значение value равным PRINTER_FORMAT_CUSTOM, если вы хотите указать нестандартный формат с шириной PRINTER_PAPER_WIDTH и длиной PRINTER_PAPER_LENGTH. value может быть одной из следующих констант:
    • PRINTER_FORMAT_CUSTOM: Позволяет задать нестандартный формат.
    • PRINTER_FORMAT_LETTER: задает стандартный формат писем (8 1/2 на 11 дюймов).
    • PRINTER_FORMAT_LEGAL: задает стандартный формат legal (8 1/2 на 14 дюймов).
    • PRINTER_FORMAT_A3: задает стандартный формат A3 (297 на 420 миллиметров).
    • PRINTER_FORMAT_A4: задает стандартный формат A4 (210 на 297 миллиметров).
    • PRINTER_FORMAT_A5: задает стандартный формат A5 (148 на 210 миллиметров).
    • PRINTER_FORMAT_B4: задает стандартный формат B4 (250 by 354 миллиметров).
    • PRINTER_FORMAT_B5: задает стандартный формат B5 (182 на 257 миллиметров).
    • PRINTER_FORMAT_FOLIO: задает стандартный формат FOLIO (8 1/2 на 13 дюймов).
  • PRINTER_PAPER_LENGTH: Если PRINTER_PAPER_FORMAT равен PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH указывает длину бумаги в миллиметрах, value должен быть типа integer.
  • PRINTER_PAPER_WIDTH: Если PRINTER_PAPER_FORMAT равен PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH указывает ширину бумаги в миллиметрах, value должен быть типа integer.
  • PRINTER_SCALE: Задает коэффициент масштабировки вывода печати. размер страницы масштабируется от физического размера страницы коэффициентом равным scale/100. К примеру, если вы установите scale равным 50, вывод печати будет равен половине первончального размера. value должен быть типа integer.
  • PRINTER_BACKGROUND_COLOR: задает фоновый цвет для текущего контекста устройства, value должен быть строкой, содержащей rgb информацию в шестнадцатеричном формате, к примеру "005533".
  • PRINTER_TEXT_COLOR: задает цвет текста для текущего контекста устройства, value должен быть строкой, содержащей rgb информацию в шестнадцатеричном формате, к примеру "005533".
  • PRINTER_TEXT_ALIGN: задает выравнивание текста для текущего контекста устройства, value может быть скомбенирован через операцию ИЛИ (|) с нижеследующими константами:
    • PRINTER_TA_BASELINE: текст будет выровнен по базовой линии.
    • PRINTER_TA_BOTTOM: текст будет выровнен по низу.
    • PRINTER_TA_TOP: текст будет выровнен по верху.
    • PRINTER_TA_CENTER: текст будет выровнен по центру.
    • PRINTER_TA_LEFT: текст будет выровнен по левому краю.
    • PRINTER_TA_RIGHT: текст будет выровнен по правому краю.

value

Значение option.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример printer_set_option()

<?php
$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);
?>

User Contributed Notes

saiko1 at gmail dot com 23-Apr-2009 02:13
Note that printer_set_option will not work due to a bug in php_printer.dll. As far as I can tell this extension has been abandoned for quite some time.
info at sima-pc dot com 20-Oct-2002 06:36
Warning :

PRINTER_FORMAT_LETTER = LETTER 8.5x11
PRINTER_FORMAT_LEGAL = LEGAL 8.5x14

If your printer uses custom paper size, printer_get_option will return an unpredictable code.
printer_select_pen
printer_start_doc
Принтер


Начинает новый документ

printer_set_option
printer_start_page
Принтер
PHP Manual

printer_start_doc

(PECL printer SVN)

printer_start_doc — Начинает новый документ

Описание

bool printer_start_doc ( resource $printer_handle [, string $document ] )

Эта функция создает новый документ в спулере принтера. Документ может содержать несколько страниц, используется для планировки задачи печати в спулере.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптером принтера.

document

Необязательный параметр document может использоватся для указания альтернативного имени документа.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример printer_start_doc()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.
printer_set_option
printer_start_page
Принтер


Начинает новую страницу

printer_start_doc
printer_write
Принтер
PHP Manual

printer_start_page

(PECL printer SVN)

printer_start_page — Начинает новую страницу

Описание

bool printer_start_page ( resource $printer_handle )

Эта функция создает новую страницу в активном документе. Для примера смотрите функцию printer_start_doc().

Список параметров

printer_handle

printer_handle должен быть действующим дескриптором устройства.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
printer_start_doc
printer_write
Принтер


Отправляет данные на принтер

printer_start_page
W32api
Принтер
PHP Manual

printer_write

(PECL printer SVN)

printer_write — Отправляет данные на принтер

Описание

bool printer_write ( resource $printer_handle , string $content )

Отправляет content прямо на принтер.

Список параметров

printer_handle

printer_handle должен быть действительным дескриптером принтера.

content

Данные, отправляемые на печать.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример printer_write()

<?php
$handle = printer_open();
printer_write($handle, "Текст для печати");
printer_close($handle);
?>

User Contributed Notes

jt at jtis dot de 28-Sep-2004 04:47
To "statline" below:
Please read http://php.net/printer regarding the printer package _not_ being a part of PHP but a PECL extension and only working in a Windows environment.
You need to download and install the php_printer.dll!
steen_hansen at yahoo dot ca 14-Feb-2004 08:58
couldn't allocate the printerjob [1804] - error on windows 2000

I was printing in several places in one module, and kept getting this error after just two printer_write()'s.  It was solved by printing everything into a buffer first, then calling printer_write() just once.

EX:
  $_SESSION['PrintBuffer']='';         //printer buffer
  print_sub_1();
  print_sub_2();
  print_sub_3();

  $handle=printer_open("EPSON TM-T88III Receipt");
  printer_set_option($handle, PRINTER_MODE, "RAW");
  printer_write($handle, $_SESSION['PrintBuffer']);
//print $_SESSION['PrintBuffer'];         //for testing
  printer_close($handle);
a dot prenz at libero dot it 25-Jul-2002 06:17
If you need printer_write you must to change the datatype:
printer_set_option($handle, PRINTER_MODE, "RAW");
printer_start_page
W32api
Принтер


W32api

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • Примеры w32api
  • W32api
    • w32api_deftype — Defines a type for use with other w32api_functions
    • w32api_init_dtype — Creates an instance of the data type typename and fills it with the values passed
    • w32api_invoke_function — Invokes function funcname with the arguments passed after the function name
    • w32api_register_function — Registers function function_name from library with PHP
    • w32api_set_call_method — Sets the calling method used

User Contributed Notes

There are no user contributed notes for this page.
printer_write
Введение
Расширения только для Windows


Введение

Это расширение является общим расширением API для DLL. Изначально оно было написано для того, чтобы осуществить доступ к API Win32 из PHP, а также обеспечить доступ к функциям, полученным из других DLL.

На данный момент поддерживаются общие типы данных PHP (string, boolean, float, integer и null) и типы, которые вы определили с помощью w32api_deftype().

Замечание:

Это расширение было перемещено в репозиторий » PECL и больше не поставляется с PHP 5.1.0.

Внимание

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и любую другую относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

User Contributed Notes

ratkinson at tbs-ltd dot co dot uk 22-Nov-2011 03:53
If you are looking for a way to access DLL's from PHP, then please see http://www.php.net/manual/en/intro.com.php.

This extension also has support for .Net libraries.
W32api
Установка и настройка
W32api


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
W32api


Требования

Расширение будет работать только на системах Windows.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Это расширение не поддерживается и считается умершим. Однако, его исходный код все еще доступен в PECL SVN вот здесь: » http://svn.php.net/viewvc/pecl/w32api.

Это расширение было перемещено в репозиторий » PECL и больше не поставляется с PHP 5.1.0

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Типы ресурсов

Это расширение определяет один тип ресурса, используемый для определяемых пользователем типов. Имя этого ресурса "dynaparm"

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

DC_MICROSOFT (integer)
DC_BORLAND (integer)
DC_CALL_CDECL (integer)
DC_CALL_STD (integer)
DC_RETVAL_MATH4 (integer)
DC_RETVAL_MATH8 (integer)
DC_CALL_STD_BO (integer)
DC_CALL_STD_MS (integer)
DC_CALL_STD_M8 (integer)
DC_FLAG_ARGPTR (integer)

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
W32api


Примеры

Содержание

  • Примеры w32api

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Примеры w32api
W32api


Примеры w32api

Этот пример получает время работы системы и отображает его в окне сообщения.

Пример #1 Получить аптайм и отобразить его в окне сообщения

<?php
// Определение необходимых констант, полученных из
// Visual Studio/Tools/Winapi/WIN32API.txt
define("MB_OK", 0);

// Загрузка расширения
dl("php_w32api.dll");

// Регистрация функции GetTickCount из kernel32.dll
w32api_register_function("kernel32.dll",
                         "GetTickCount",
                         "long");

// Регистрация функции MessageBoxA из User32.dll
w32api_register_function("User32.dll",
                         "MessageBoxA",
                         "long");

// Получение аптайма
$ticks = GetTickCount();

// Конвертация аптайма в удобочитаемый текст
$secs  = floor($ticks / 1000);
$mins  = floor($secs / 60);
$hours = floor($mins / 60);

$str = sprintf("Вы используете ваш компьютер уже:" .
                "\r\n %d милисекунд, или \r\n %d секунд" .
                "или \r\n %d минут или\r\n %d часов %d минут.",
                $ticks,
                $secs,
                $mins,
                $hours,
                $mins - ($hours*60));

// Отобразить окно сообщения только с кнопкой ОК и текстом аптайма
MessageBoxA(NULL,
            $str,
            "Аптайм",
            MB_OK);
?>

User Contributed Notes

There are no user contributed notes for this page.
Примеры
W32api
Примеры


W32api
PHP Manual

W32api

Содержание

  • w32api_deftype — Defines a type for use with other w32api_functions
  • w32api_init_dtype — Creates an instance of the data type typename and fills it with the values passed
  • w32api_invoke_function — Invokes function funcname with the arguments passed after the function name
  • w32api_register_function — Registers function function_name from library with PHP
  • w32api_set_call_method — Sets the calling method used

User Contributed Notes

sk89q 27-Sep-2007 11:14
The only way I've been able to call Win32 API functions with PHP5 has been through COM and DynamicWrapper.

Get DynamicWrapper at:
http://ourworld.compuserve.com/homepages/Guenter_Born/
WSHBazaar/WSHDynaCall.htm
(remove new line)

Here's an example to play a beep sound with your computer speaker:
<?php
$com = new COM("DynamicWrapper");
$com->Register("KERNEL32.DLL", "Beep", "i=ll", "f=s", "r=l");
$com->Beep(5000, 100);
?>
MagicalTux at FF dot st 16-Feb-2005 08:10
Answer to the note posted by me at nullflux dot com (see below)

The Win32 API *does* work in other versions of PHP than between 4.2.0 and 4.2.3. However the documented functions are not available. You will have to use the "win32" class to access functions. For an example, read Philip Soeberg's post just below.
serdar_soydemir at hotmail dot com 30-May-2004 10:34
It seems that this extension will be replaced by FFI extension in PHP5. FFI stands for "Foreign Function Interface" and it's not limited by Windows API, but also supports Linux APIs. You may reach this extension's website at http://pecl.php.net/package/ffi . For Windows, you may try this code from commandline php.exe:

<?php
dl ("php_ffi.dll");

$windows = new ffi ("[lib='user32.dll'] int MessageBoxA( int handle, char *text, char *caption, int type );" );

echo $windows->MessageBoxA(0, "Message For You", "Hello World", 1);
?>
chris at ramsoft dot biz 18-May-2004 11:46
The win32 support appears to be pretty flaky in php. This of course is to be expected with an experimental extension. That being said, if you are having trouble using the win32 functionality you may want to look into creating a PHP extension instead.

We were having some problems interfacing PHP with a 3rd party dll. As such we created an extension which wraps the interface with the aforementioned dll. The solution was surprisingly quick and painless.
Because we use Delphi primarily we found the following extremely useful and easy to use. http://users.chello.be/ws36637/php4delphi.html#download

more info here:
http://php.us.themoes.org/manual/en/zend.creating.php
me at nullflux dot com 20-Apr-2004 04:27
The w32api extension -does not- work on versions of php that are not between 4.2.0 and 4.2.3. This is mentioned on the individual function's manual pages, but not on the extension's main page. Perhaps I'm just missing something, but if you want to interact with the Win32 API via PHP you have to use an outdated version, or just not bother with it at all.
Philip Soeberg 19-Jan-2004 08:09
In response to post by Jan Kleinsorge.

To get the proper windows system uptime, one should use the Performance Monitoring system... GetTickCount is limited to 49.7 days, as the result is a dword.

<?php
if (!dl("php_w32api.dll")) {
  echo "Unable to load php_w32api.dll";
  exit;
}

$api = new win32;
$api->registerfunction("bool QueryPerformanceCounter (float &lpPerformanceCount) From kernel32.dll");
$api->registerfunction("bool QueryPerformanceFrequency (float &lpPerformanceFrequency) From kernel32.dll");

$api->QueryPerformanceCounter($a);
$api->QueryPerformanceFrequency($b);
$c = $a/$b;
$days = floor($c / 86400);
echo gmstrftime("System uptime is $days Days, %H Hr, %M Min, %S Sec<br>", $c);
?>

The above snippet will return the true uptime for an unlimited time for a windows OS. (Disregarding the fact that windows needs reboot every 10 days or so :))
A tiny dange though is the lack of 64bit variable types in php.. (the "float &lpPerformanceCount" should be "long long &lpPerformanceCount") .. Nevertheless.. It works :)

Philip S.
Jan Kleinsorge 02-Jan-2004 05:55
Or google for "win32.hlp". Almost every API-function is listed in there.
Sami Fouad 12-Dec-2003 09:33
http://msdn.microsoft.com/library/ contains functions for use with this extension.

Beware! The menu system is very dense, and confusing at first if you don't know where your going.

Luckily for you I am going to add how to get there in this note. ;)

Windows Development > Development Guides > Windows API > Windows API Reference

Enjoy.
23-Aug-2003 01:42
The small, unofficial documentation is now available here http://wobster.mynnga.de/w32api.txt .
The old link from the post above is dead.

Note that the W32API doesn't seem to be under development anymore. E-Mails to the author stayed unanswered.
If you really have to use it, just some hints here: There are often problems concerning Apache webservers. This extension doesn't seem to work with mod_php.
I used the API on IIS5 with PHP as CGI. Additionally the IUSR_<hostname> (that's the user IIS runs php.exe by default) might need additional rights to be able to call certain API-functions.
silver_dragoon77 at hotmail dot com 27-Jun-2003 12:03
hi

for phpgtk users, who might want to add some sound to their apps, here is the code, assuming ding.wav is in the script's directory

$api = new win32;
$api->registerfunction("long sndPlaySound (string a, int b) From winmm.dll");
$api->sndPlaySound("ding.wav", 0);

you can use the big win32.hlp file containing the win32 api reference to get some other multimedia functions

regards
wobble at gmx dot de 31-Mar-2003 01:09
I played a bit around with the W32API. Here is some code that actually works with the current release of W32API.
The interface changed completely, so all documentation about this extension is out-dated. While the old release
just implemented "plain" functions, the current version offers a class to handle all the API-related operations.
Additionally, functions are now registered using a SQL-like language with a single string.

<?php

$api = new win32;

/*
     BOOL GetUserName(
        LPTSTR lpBuffer,    // address of name buffer
        LPDWORD nSize       // address of size of name buffer
     );
    Returns the current thread's username
    "&" passes argument as "refrence" not as "copy"
*/
$api->registerfunction("long GetUserName (string &a, int &b) From advapi32.dll");

/*
    DWORD GetTickCount(VOID)
    Returns the ms the OS is running
*/
$api->registerfunction("long GetTickCount () From Kernel32.dll");

$len = 255;                   // set the length your variable should have
$name = str_repeat("\0", $len); // prepare an empty string
if ($api->GetUserName($name, $len) == 0)
{
    die("failed");
}

if (!($time = $api->GetTickCount()))
{
    die("failed");
}

echo "Username: $name<br>\nSystemtime: $time<br>\n";

?>

GOOD LUCK !!

Jan Kleinsorge
arunasphp at anm dot org 06-Aug-2002 01:32
In order to use most (perhaps all?) of the win32 API while running with a web server you have to give the server service permission to interact with the desktop.  This is especially noticeable with the given example, where the script will try to display message boxes on the server's display.

Keep in mind, however, that you should think hard about the consequences of letting a web server interact with your desktop, especially if you're not the only one using the web server.
Примеры w32api
w32api_deftype
W32api
PHP Manual


Defines a type for use with other w32api_functions

W32api
w32api_init_dtype
W32api
PHP Manual

w32api_deftype

(PHP 4 >= 4.2.0)

w32api_deftype — Defines a type for use with other w32api_functions

Описание

bool w32api_deftype ( string $typename , string $member1_type , string $member1_name [, string $... [, string $... ]] )

You need to call this function if you would like to define a type for a w32api call.

Список параметров

typename

The name of the type.

member1_type

A member type can be a user defined type. All the type names are case sensitive. Built in type names should be provided in lowercase.

member1_name

The member name of member1_type.

...

...

This function takes 2n+1 arguments, where n is the number of members the type has. After that is the type of the member followed by the members name (in pairs).

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примечания

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

User Contributed Notes

nospam_ctramen at earthlink dot net 28-Dec-2001 08:01
The variable types appear to be case sensitive, so byte, not BYTE. Also you use string, not CHAR.
W32api
w32api_init_dtype
W32api


Creates an instance of the data type typename and fills it with the values passed

w32api_deftype
w32api_invoke_function
W32api
PHP Manual

w32api_init_dtype

(PHP 4 >= 4.2.0)

w32api_init_dtype — Creates an instance of the data type typename and fills it with the values passed

Описание

resource w32api_init_dtype ( string $typename , mixed $value [, mixed $... ] )

This function creates an instance of the data type named typename, filling in the values of the data type.

Список параметров

typename

The typename parameter is case sensitive.

value

You should give the values in the same order as you defined the data type with w32api_deftype().

...

Возвращаемые значения

Returns a dynaparm resource.

Примечания

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

User Contributed Notes

There are no user contributed notes for this page.
w32api_deftype
w32api_invoke_function
W32api


Invokes function funcname with the arguments passed after the function name

w32api_init_dtype
w32api_register_function
W32api
PHP Manual

w32api_invoke_function

(PHP 4 >= 4.2.0)

w32api_invoke_function — Invokes function funcname with the arguments passed after the function name

Описание

mixed w32api_invoke_function ( string $funcname , mixed $argument [, mixed $... ] )

w32api_invoke_function() tries to find the previously registered function, passing the parameters you provided.

Список параметров

funcname

The function name.

argument

Any of the arguments can be of any PHP type or w32api_deftype() defined type, as needed.

...

Возвращаемые значения

The return type is the one you set when you registered the function, the value is the one returned by the function itself.

Примечания

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

User Contributed Notes

ryan at wonko dot com 22-Apr-2002 08:01
As of PHP 4.2.0, this function doesn't appear to do anything useful (nor does it even work). Instead, use w32api_register_function to register your function and then simply call the function you registered just like you would call any normal PHP function. For example, the following snippet will display a standard messagebox:

w32api_register_function("User32.dll",
                         "MessageBoxA",
                         "long");
MessageBoxA(NULL,
            "Hello World!",
            "PHP MessageBox",
            0);
w32api_init_dtype
w32api_register_function
W32api


Registers function function_name from library with PHP

w32api_invoke_function
w32api_set_call_method
W32api
PHP Manual

w32api_register_function

(PHP 4 >= 4.2.0)

w32api_register_function — Registers function function_name from library with PHP

Описание

bool w32api_register_function ( string $library , string $function_name , string $return_type )

This function tries to find the function_name function in library, and tries to import it into PHP.

Список параметров

library

The library name, as a string.

function_name

The function name, as a string.

return_type

The function will be registered with the given return_type. This type can be a generic PHP type, or a type defined with w32api_deftype(). All type names are case sensitive. Built in type names should be provided in lowercase.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примечания

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

User Contributed Notes

There are no user contributed notes for this page.
w32api_invoke_function
w32api_set_call_method
W32api


Sets the calling method used

w32api_register_function
win32ps
W32api
PHP Manual

w32api_set_call_method

(PHP 4 >= 4.2.0)

w32api_set_call_method — Sets the calling method used

Описание

void w32api_set_call_method ( int $method )

This function sets the method call type.

Список параметров

method

Can be one of DC_CALL_CDECL or DC_CALL_STD (the extension default).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примечания

Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

User Contributed Notes

There are no user contributed notes for this page.
w32api_register_function
win32ps
W32api


win32ps

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • Примеры Win32ps
  • win32ps Функции
    • win32_ps_list_procs — List running processes
    • win32_ps_stat_mem — Stat memory utilization
    • win32_ps_stat_proc — Stat process

User Contributed Notes

There are no user contributed notes for this page.
w32api_set_call_method
Введение
Расширения только для Windows


Введение

Расширение win32ps является специфическим расширением для Windows, которое позволяет PHP получать статистику о процессе и использовании памяти.

User Contributed Notes

There are no user contributed notes for this page.
win32ps
Установка и настройка
win32ps


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
win32ps


Требования

Windows NT, Windows 2000, Windows XP или Windows Server 2003. Любая версия Windows, производная от Windows NT, должна быть совместимой.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pecl.php.net/package/win32ps.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
win32ps


Примеры

Содержание

  • Примеры Win32ps

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Примеры Win32ps
win32ps


Примеры Win32ps

Пример #1 Статистические данные о текущем процессе PHP

<?php
print_r(win32_ps_stat_proc());
/*
    Array
    (
        [pid] => 936
        [exe] => D:\Daten\Source\php-5.1\Debug_TS\php.exe
        [mem] => Array
            (
                [page_fault_count] => 2062
                [peak_working_set_size] => 8396800
                [working_set_size] => 8396800
                [quota_peak_paged_pool_usage] => 32080
                [quota_paged_pool_usage] => 31876
                [quota_peak_non_paged_pool_usage] => 4240
                [quota_non_paged_pool_usage] => 3888
                [pagefile_usage] => 5865472
                [peak_pagefile_usage] => 5865472
            )

        [tms] => Array
            (
                [created] => 0.093
                [kernel] => 0.015
                [user] => 0.062
            )

    )
*/
?>

Пример #2 Статистические данные о глобальном использовании памяти

<?php
print_r(win32_ps_stat_mem());
/*
    Array
    (
        [load] => 37
        [unit] => 1024
        [total_phys] => 1048096
        [avail_phys] => 649960
        [total_pagefile] => 2521368
        [avail_pagefile] => 2237940
        [total_virtual] => 2097024
        [avail_virtual] => 2057848
    )
*/
?>

User Contributed Notes

There are no user contributed notes for this page.
Примеры
win32ps Функции
Примеры


win32ps Функции

Содержание

  • win32_ps_list_procs — List running processes
  • win32_ps_stat_mem — Stat memory utilization
  • win32_ps_stat_proc — Stat process

User Contributed Notes

There are no user contributed notes for this page.
Примеры Win32ps
win32_ps_list_procs
win32ps


List running processes

win32ps Функции
win32_ps_stat_mem
win32ps Функции
PHP Manual

win32_ps_list_procs

(PECL win32ps >= 1.0.1)

win32_ps_list_procs — List running processes

Описание

array win32_ps_list_procs ( void )

Retrieves statistics about all running processes.

Возвращаемые значения

Returns FALSE on failure, or an array consisting of process statistics like win32_ps_stat_proc() returns for all running processes on success.

Смотрите также

  • win32_ps_stat_proc() - Stat process

User Contributed Notes

cf at chronofish dot com 10-Sep-2007 11:27
For those of you in the WAMP environment, here is a little function that you may find handy:

<?
function kill_proc($processName)
{
    @$processList = win32_ps_list_procs();
    foreach ($processList as $processArray)
    {
        $pid = $processArray['pid'];
        if (basename($processArray['exe']) == $processName)
        {
            `taskkill /f /PID $pid 2>&1`;
        }
    }
}
?>

-CF
win32ps Функции
win32_ps_stat_mem
win32ps Функции


Stat memory utilization

win32_ps_list_procs
win32_ps_stat_proc
win32ps Функции
PHP Manual

win32_ps_stat_mem

(PECL win32ps >= 1.0.1)

win32_ps_stat_mem — Stat memory utilization

Описание

array win32_ps_stat_mem ( void )

Retrieves statistics about the global memory utilization.

Возвращаемые значения

Returns FALSE on failure, or an array consisting of the following information on success:

load

The current memory load in percent of physical memory.

unit

This is always 1024, and indicates that the following values are the count of 1024 bytes.

total_phys

The amount of total physical memory.

avail_phys

The amount of still available physical memory.

total_pagefile

The amount of total pageable memory (physical memory + paging file).

avail_pagefile

The amount of still available pageable memory (physical memory + paging file).

total_virtual

The amount of total virtual memory for a process.

avail_virtual

The amount of still available virtual memory for a process.

User Contributed Notes

There are no user contributed notes for this page.
win32_ps_list_procs
win32_ps_stat_proc
win32ps Функции


Stat process

win32_ps_stat_mem
win32service
win32ps Функции
PHP Manual

win32_ps_stat_proc

(PECL win32ps >= 1.0.1)

win32_ps_stat_proc — Stat process

Описание

array win32_ps_stat_proc ([ int $pid = 0 ] )

Retrieves statistics about the process with the process id pid.

Список параметров

pid

The process id of the process to stat. If omitted, the id of the current process.

Возвращаемые значения

Returns FALSE on failure, or an array consisting of the following information on success:

pid

The process id.

exe

The path to the executable image.

mem

An array containing information about the following memory utilization indicators: page_fault_count, peak_working_set_size, working_set_size, quota_peak_paged_pool_usage, quota_paged_pool_usage, quota_peak_non_paged_pool_usage, quota_non_paged_pool_usage, pagefile_usage and peak_pagefile_usage.

tms

An array containing information about the following CPU time utilization indicators: created, kernel and user.

Смотрите также

  • win32_ps_list_procs() - List running processes

User Contributed Notes

There are no user contributed notes for this page.
win32_ps_stat_mem
win32service
win32ps Функции


win32service

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
    • Win32Service Service Type Bitmasks
    • Win32Service Service Status Constants
    • Win32Service Service Control Message Constants
    • Win32Service Service Control Message Accepted Bitmasks
    • Win32Service Service Start Type Constants
    • Win32Service Service Error Control Constants
    • Win32Service Service Flag Constants
    • Win32 Error Codes
    • Win32 Base Priority Classes
  • Примеры
  • win32service
    • win32_continue_service — Возобновляет работу приостановленной службы
    • win32_create_service — Creates a new service entry in the SCM database
    • win32_delete_service — Deletes a service entry from the SCM database
    • win32_get_last_control_message — Returns the last control message that was sent to this service
    • win32_pause_service — Pauses a service
    • win32_query_service_status — Queries the status of a service
    • win32_set_service_status — Update the service status
    • win32_start_service_ctrl_dispatcher — Добавляет в Диспетчер Служб скрипт, который может быть использован как служба с заданным именем
    • win32_start_service — Запускает службу
    • win32_stop_service — Останавливает службу

User Contributed Notes

There are no user contributed notes for this page.
win32_ps_stat_proc
Введение
Расширения только для Windows


Введение

Расширение win32service - это специальное Windows-расширение, которое позволяет PHP взаимодействовать с диспетчером управления службами для запуска, остановки, добавления и удаления служб, и даже запускать ваши PHP скрипты как службы.

User Contributed Notes

There are no user contributed notes for this page.
win32service
Установка и настройка
win32service


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
win32service


Требования

Windows NT, Windows 2000, Windows XP или Windows Server 2003. Любая версия Windows, начиная с Windows NT, совместима.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pecl.php.net/package/win32service

User Contributed Notes

Josh 24-Aug-2010 02:17
The Win32Service extension for PHP 5.3 can be found at http://downloads.php.net/pierre/

[EDIT] 2011-05-19 RQuadling : The version that is available on Pierre's site is an old version. At the moment, the only way to get this extension that matches the current documentation is to build your own.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Содержание

  • Win32Service Service Type Bitmasks
  • Win32Service Service Status Constants
  • Win32Service Service Control Message Constants
  • Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Start Type Constants
  • Win32Service Service Error Control Constants
  • Win32Service Service Flag Constants
  • Win32 Error Codes
  • Win32 Base Priority Classes

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Win32Service Service Type Bitmasks
win32service


Win32Service Service Type Bitmasks

Предопределенные константы
Win32Service Service Status Constants
Предопределенные константы
PHP Manual
Win32Service Service Type Bitmasks
Constant | Value | Description
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | The service runs in its own process.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | The service can interact with the desktop. This option is not available on Windows Vista or later.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | The service runs in its own process and can interact with the desktop. This option is not available on Windows Vista or later.

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Win32Service Service Status Constants
Предопределенные константы


Win32Service Service Status Constants

Win32Service Service Type Bitmasks
Win32Service Service Control Message Constants
Предопределенные константы
PHP Manual
Win32Service Service Status Constants
Constant | Value | Description
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | The service continue is pending.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | The service pause is pending.
WIN32_SERVICE_PAUSED | 0x00000007 | The service is paused.
WIN32_SERVICE_RUNNING | 0x00000004 | The service is running.
WIN32_SERVICE_START_PENDING | 0x00000002 | The service is starting.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | The service is stopping.
WIN32_SERVICE_STOPPED | 0x00000001 | The service is not running.

User Contributed Notes

There are no user contributed notes for this page.
Win32Service Service Type Bitmasks
Win32Service Service Control Message Constants
Предопределенные константы


Win32Service Service Control Message Constants

Win32Service Service Status Constants
Win32Service Service Control Message Accepted Bitmasks
Предопределенные константы
PHP Manual
Win32Service Service Control Message Constants
Constant | Value | Description
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Notifies a paused service that it should resume.
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Notifies a service that it should report its current status information to the service control manager.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Notifies a service that it should pause.
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Notifies a service that the system will be shutting down. A service that handles this notification blocks system shutdown until the service stops or the preshutdown time-out interval expires. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Notifies a service that the system is shutting down so the service can perform cleanup tasks. If a service accepts this control code, it must stop after it performs its cleanup tasks. After the SCM sends this control code, it will not send other control codes to the service.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Notifies a service that it should stop.

User Contributed Notes

There are no user contributed notes for this page.
Win32Service Service Status Constants
Win32Service Service Control Message Accepted Bitmasks
Предопределенные константы


Win32Service Service Control Message Accepted Bitmasks

Win32Service Service Control Message Constants
Win32Service Service Start Type Constants
Предопределенные константы
PHP Manual
Win32Service Service Control Message Accepted Bitmasks
Constant | Value | Description
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | The service can be paused and continued. This control code allows the service to receive WIN32_SERVICE_CONTROL_PAUSE and WIN32_SERVICE_CONTROL_CONTINUE notifications.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | The service can perform preshutdown tasks. This control code enables the service to receive WIN32_SERVICE_CONTROL_PRESHUTDOWN notifications. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | The service is notified when system shutdown occurs. This control code allows the service to receive WIN32_SERVICE_CONTROL_SHUTDOWN notifications.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | The service can be stopped. This control code allows the service to receive WIN32_SERVICE_CONTROL_STOP notifications.

User Contributed Notes

There are no user contributed notes for this page.
Win32Service Service Control Message Constants
Win32Service Service Start Type Constants
Предопределенные константы


Win32Service Service Start Type Constants

Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Error Control Constants
Предопределенные константы
PHP Manual
Win32Service Service Start Type Constants
Constant | Value | Description
WIN32_SERVICE_AUTO_START | 0x00000002 | A service started automatically by the service control manager during system startup.
WIN32_SERVICE_DEMAND_START | 0x00000003 | A service started by the service control manager when a process calls the StartService function.
WIN32_SERVICE_DISABLED | 0x00000004 | A service that cannot be started. Attempts to start the service result in the error code WIN32_ERROR_SERVICE_DISABLED.

User Contributed Notes

There are no user contributed notes for this page.
Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Error Control Constants
Предопределенные константы


Win32Service Service Error Control Constants

Win32Service Service Start Type Constants
Win32Service Service Flag Constants
Предопределенные константы
PHP Manual
Win32Service Service Error Control Constants
Constant | Value | Description
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | The startup program ignores the error and continues the startup operation.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | The startup program logs the error in the event log but continues the startup operation.

User Contributed Notes

There are no user contributed notes for this page.
Win32Service Service Start Type Constants
Win32Service Service Flag Constants
Предопределенные константы


Win32Service Service Flag Constants

Win32Service Service Error Control Constants
Win32 Error Codes
Предопределенные константы
PHP Manual
Win32Service Service Flag Constants
Constant | Value | Description
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | The service runs in a system process that must always be running.

User Contributed Notes

There are no user contributed notes for this page.
Win32Service Service Error Control Constants
Win32 Error Codes
Предопределенные константы


Win32 Error Codes

Win32Service Service Flag Constants
Win32 Base Priority Classes
Предопределенные константы
PHP Manual
Win32 Error Codes
Constant | Value | Description
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | The handle to the SCM database does not have the appropriate access rights.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | A circular service dependency was specified.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | The specified database does not exist.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | The service cannot be stopped because other running services are dependent on it.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | The display name already exists in the service control manager database either as a service name or as another display name.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | This error is returned if the program is being run as a console application rather than as a service. If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | The buffer is too small for the service status structure. Nothing was written to the structure.
WIN32_ERROR_INVALID_DATA | 0x0000000D | The specified service status structure is invalid.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | The handle to the specified service control manager database is invalid.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | The InfoLevel parameter contains an unsupported value.
WIN32_ERROR_INVALID_NAME | 0x0000007B | The specified service name is invalid.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | A parameter that was specified is invalid.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | The user account name specified in the user parameter does not exist. See win32_create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | The requested control code is not valid, or it is unacceptable to the service.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | The service binary file could not be found.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | An instance of the service is already running.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | The requested control code cannot be sent to the service because the state of the service is WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING, or WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | The database is locked.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | The service depends on a service that does not exist or has been marked for deletion.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | The service depends on another service that has failed to start.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | The service has been disabled.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | The specified service does not exist as an installed service.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | The specified service already exists in this database.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | The service did not start due to a logon failure. This error occurs if the service is configured to run under an account that does not have the "Log on as a service" right.
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | The specified service has already been marked for deletion.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | A thread could not be created for the service.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | The service has not been started.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | The system is shutting down; this function cannot be called.
WIN32_NO_ERROR | 0x00000000 | No error.

User Contributed Notes

There are no user contributed notes for this page.
Win32Service Service Flag Constants
Win32 Base Priority Classes
Предопределенные константы


Win32 Base Priority Classes

Win32 Error Codes
Примеры
Предопределенные константы
PHP Manual
Win32 Base Priority Classes
Constant | Value | Description
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Process that has priority above WIN32_NORMAL_PRIORITY_CLASS but below WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Process that has priority above WIN32_IDLE_PRIORITY_CLASS but below WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Process that performs time-critical tasks that must be executed immediately. The threads of the process preempt the threads of normal or idle priority class processes. An example is the Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class application can use nearly all available CPU time.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Process whose threads run only when the system is idle. The threads of the process are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle-priority class is inherited by child processes.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Process with no special scheduling needs.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Process that has the highest possible priority. The threads of the process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.

User Contributed Notes

There are no user contributed notes for this page.
Win32 Error Codes
Примеры
Предопределенные константы


Примеры

Пример #1 Registering a PHP script to run as a service

<?php
win32_create_service(array(
    'service'     => 'dummyphp',                                           # the name of your service
    'display'     => 'sample dummy PHP service',                           # short description
    'description' => 'This is a dummy Windows service created using PHP.', # long description
    'params'      => '"' . __FILE__ . '"  run',                            # path to the script and parameters
));
?>

Пример #2 Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Пример #3 Running as a service

<?php
if ($argv[1] == 'run') {
  win32_start_service_ctrl_dispatcher('dummyphp');

  while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
    # do your work here.
    # try not to take up more than 30 seconds before going around the loop
    # again
  }
}
?>

User Contributed Notes

There are no user contributed notes for this page.
Win32 Base Priority Classes
win32service
win32service


win32service
PHP Manual

win32service

Содержание

  • win32_continue_service — Возобновляет работу приостановленной службы
  • win32_create_service — Creates a new service entry in the SCM database
  • win32_delete_service — Deletes a service entry from the SCM database
  • win32_get_last_control_message — Returns the last control message that was sent to this service
  • win32_pause_service — Pauses a service
  • win32_query_service_status — Queries the status of a service
  • win32_set_service_status — Update the service status
  • win32_start_service_ctrl_dispatcher — Добавляет в Диспетчер Служб скрипт, который может быть использован как служба с заданным именем
  • win32_start_service — Запускает службу
  • win32_stop_service — Останавливает службу

User Contributed Notes

brian dot ngure at gmail dot com 30-Apr-2010 03:03
An example of how it should be done:

<?php

class TestClass {
    private $args;

    function __construct($arg) {
        $this->args = $arg;
        $this->run();
    }

    private function run() {
        if ($this->args == 'run') {
            win32_start_service_ctrl_dispatcher('test_service');

            while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
                # do your work here.
                # try not to take up more than 30 seconds before going around the loop
                # again
            }
        }
    }
}

$object = new TestClass($argv[1]);

?>
me at sylvain tiret besse point fr 20-Nov-2007 12:45
Just to help a little, the service control command must be in the first script called. If you try to type this portion of code in a separate file and include it, the SCM will not get the controls.
example :

- file1.inc :
<?PHP
class MyClass{

 function __construct() {

    $x = win32_start_service_ctrl_dispatcher('service');

    while (WIN32_SERVICE_CONTROL_STOP!=win32_get_last_control_message()){
        //your code
  }
}
?>

- service.php :
<?PHP
include("file1.inc");
$object = new MyClass();

?>

WON'T WORK !
Примеры
win32_continue_service
win32service
PHP Manual


Возобновляет работу приостановленной службы

win32service
win32_create_service
win32service
PHP Manual

win32_continue_service

(PECL win32service SVN)

win32_continue_service — Возобновляет работу приостановленной службы

Описание

int win32_continue_service ( string $servicename [, string $machine ] )

Возобновляет работу обозначенной приостановленной службы. Требует административных привилегий.

Список параметров

servicename

Короткое название службы.

machine

Необязательное имя машины. Если не указано, используется на локальной машине.

Возвращаемые значения

Возвращает WIN32_NO_ERROR в случае успешного завершения , FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Смотрите также

  • win32_start_service() - Запускает службу
  • Коды Ошибок Win32

User Contributed Notes

There are no user contributed notes for this page.
win32service
win32_create_service
win32service


Creates a new service entry in the SCM database

win32_continue_service
win32_delete_service
win32service
PHP Manual

win32_create_service

(PECL win32service SVN)

win32_create_service — Creates a new service entry in the SCM database

Описание

mixed win32_create_service ( array $details [, string $machine ] )

Список параметров

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

description

The long description of the service. This is the description that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run. If the script name or path contains spaces, then wrap the full path to the PHP script with ".

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

delayed_start

If delayed_start is set to TRUE, then this will inform the SCM that this service should be started after other auto-start services are started plus a short delay.

Any service can be marked as a delayed auto-start service; however, this setting has no effect unless the service's start_type is WIN32_SERVICE_AUTO_START.

This setting is only applicable on Windows Vista and Windows Server 2008 or greater.

base_priority

To reduce the impact on processor utilisation, it may be necessary to set a base priority lower than normal.

The base_priority can be set to one of the constants define in Win32 Base Priority Classes.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

Возвращаемые значения

Возвращает WIN32_NO_ERROR в случае успешного завершения , FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Примеры

Пример #1 A win32_create_service() example

Create a service with the short name 'dummyphp'.

<?php
$x = win32_create_service(array(
    'service'     => 'dummyphp',                                           # the name of your service
    'display'     => 'sample dummy PHP service',                           # short description
    'description' => 'This is a dummy Windows service created using PHP.', # long description
    'params'      => '"' . __FILE__ . '"  run',                            # path to the script and parameters
));
debug_zval_dump($x);
?>

Смотрите также

  • win32_delete_service() - Deletes a service entry from the SCM database
  • Win32 Base Priority Classes
  • Win32 Error Codes

User Contributed Notes

Anonymous 08-Oct-2010 10:05
[An example of how to create a Windows service.  Evaluate code first and use at your own risk!]

<?php

//No timeouts, Flush Content immediatly
    set_time_limit(0);
    ob_implicit_flush();

//Service Settings
    $phpPath = "D:\\php\\php5.2.9";
    $ServiceName = 'phpServiceName';
    $ServiceDisplay = 'phpDisplayName';

//Windows Service Control
    $ServiceAction = "status";
    //$ServiceAction = "debug";
    if ( isset($_GET['ServiceAction']) and strlen($_GET['ServiceAction']) ) {
        $ServiceAction = addslashes($_GET['ServiceAction']);
    } else if ( isset($argv) and isset($argv[1]) and strlen($argv[1]) ) {
        $ServiceAction = $argv[1];
    }
    if( $ServiceAction == "status" ) {
        $ServiceStatus = win32_query_service_status($ServiceName);
        if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOPPED ) {
            echo "Service Stopped\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_START_PENDING ) {
            echo "Service Start Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOP_PENDING ) {
            echo "Service Stop Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_RUNNING ) {
            echo "Service Running\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_CONTINUE_PENDING ) {
            echo "Service Continue Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSE_PENDING ) {
            echo "Service Pause Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSED ) {
            echo "Service Paused\n\n";
        } else{
            echo "Service Unknown\n\n";
        }
      exit;
    } else if ( $ServiceAction == "install" ) {
    //Install Windows Service
        win32_create_service( Array(
            'service' => $ServiceName,
            'display' => $ServiceDisplay,
            'params' => __FILE__ . " run",
            'path' => $phpPath."\\php.exe",
        ));
        echo "Service Installed\n\n";
        exit;
    } else if ( $ServiceAction == "uninstall" ) {
    //Remove Windows Service
        win32_delete_service($ServiceName);
        echo "Service Removed\n\n";
        exit;
    } else if( $ServiceAction == "start") {
    //Start Windows Service
      win32_start_service($ServiceName);
      echo "Service Started\n\n";
      exit;
    } else if( $ServiceAction == "stop" ) {
    //Stop Windows Service
      win32_stop_service($ServiceName);
      echo "Service Stopped\n\n";
      exit;
    } else if ( $ServiceAction == "run" ) {
    //Run Windows Service
        win32_start_service_ctrl_dispatcher($ServiceName);
        win32_set_service_status(WIN32_SERVICE_RUNNING);
    } else if ( $ServiceAction == "debug" ) {
    //Debug Windows Service
        set_time_limit(10);
    } else {
        exit();
    }

//Server Loop
    while (1) {
    //Handle Windows Service Request
        usleep(100*1000);
        if ( $ServiceAction == "run" ) {
            switch ( win32_get_last_control_message() ) {
                case WIN32_SERVICE_CONTROL_CONTINUE:
                    break;
                case WIN32_SERVICE_CONTROL_INTERROGATE:
                    win32_set_service_status(WIN32_NO_ERROR);
                break;
                case WIN32_SERVICE_CONTROL_STOP:
                    win32_set_service_status(WIN32_SERVICE_STOPPED);
                    exit;
                default:
                    win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED);
            }
        }
    //User Loop
        sleep(1);
        echo "\n<BR>YOUR CODE HERE";
    }

//Exit
    if ( $ServiceAction == "run" ) {
        win32_set_service_status(WIN32_SERVICE_STOPPED);
    }
    exit();
?>
pauljamesthomson at gmail dot com 22-Jan-2007 04:54
Other start_type values:

0x00000002: A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services.

0x00000000: A device driver started by the system loader. This value is valid only for driver services.

0x00000003: A service started by the service control manager when a process calls the win32_start_service() function.

0x00000004: A service that cannot be started. Attempts to start the service result in the error code

0x00000001: A device driver started by the IoInitSystem function. This value is valid only for driver services.

I can confirm that 0x00000003 works as expected (service is created, but must be started manually).

More here:

http://msdn2.microsoft.com/en-us/library/ms682450.aspx
win32_continue_service
win32_delete_service
win32service


Deletes a service entry from the SCM database

win32_create_service
win32_get_last_control_message
win32service
PHP Manual

win32_delete_service

(PECL win32service SVN)

win32_delete_service — Deletes a service entry from the SCM database

Описание

mixed win32_delete_service ( string $servicename [, string $machine ] )

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

Список параметров

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Возвращаемые значения

Возвращает WIN32_NO_ERROR в случае успешного завершения , FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Примеры

Пример #1 A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

Смотрите также

  • win32_create_service() - Creates a new service entry in the SCM database
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.
win32_create_service
win32_get_last_control_message
win32service


Returns the last control message that was sent to this service

win32_delete_service
win32_pause_service
win32service
PHP Manual

win32_get_last_control_message

(PECL win32service SVN)

win32_get_last_control_message — Returns the last control message that was sent to this service

Описание

int win32_get_last_control_message ( void )

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Возвращаемые значения

Returns a control constant which will be one of the Win32Service Service Control Message Constants: WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_PRESHUTDOWN, WIN32_SERVICE_CONTROL_SHUTDOWN, WIN32_SERVICE_CONTROL_STOP.

Смотрите также

  • win32_start_service_ctrl_dispatcher() - Добавляет в Диспетчер Служб скрипт, который может быть использован как служба с заданным именем
  • Win32Service Service Control Message Constants

User Contributed Notes

kermodebea at kermodebear dot Oh Are Gee 02-May-2006 11:35
The definitions of some of these control codes can be found here (URL broken due to comment system, sorry about that!): http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/dllproc/base/handler.asp

However, for your convenience (and mine):
SERVICE_CONTROL_STOP, 0x00000001
Notifies a service that it should stop.

If a service accepts this control code, it must stop upon receipt. After the SCM sends this control code, it does not send other control codes.

Windows XP/2000:  If the service returns NO_ERROR and continues to run, it continues to receive control codes. This behavior changed starting with Windows Server 2003 and Windows XP SP2.

SERVICE_CONTROL_PAUSE, 0x00000002
Notifies a service that it should pause.
(Although I guess that there is no requirement that you must.)

SERVICE_CONTROL_CONTINUE, 0x00000003
Notifies a paused service that it should resume.

SERVICE_CONTROL_INTERROGATE, 0x00000004
Notifies a service that it should report its current status information to the service control manager.
(I'm guessing that a call to win32_set_service_status() would satisfy interrogation?)

SERVICE_CONTROL_SHUTDOWN, 0x00000005
Notifies a service that the system is shutting down so the service can perform cleanup tasks.
win32_delete_service
win32_pause_service
win32service


Pauses a service

win32_get_last_control_message
win32_query_service_status
win32service
PHP Manual

win32_pause_service

(PECL win32service SVN)

win32_pause_service — Pauses a service

Описание

int win32_pause_service ( string $servicename [, string $machine ] )

Pauses a named service. Requires administrative privileges.

Список параметров

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Возвращаемые значения

Возвращает WIN32_NO_ERROR в случае успешного завершения , FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Смотрите также

  • win32_start_service() - Запускает службу
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.
win32_get_last_control_message
win32_query_service_status
win32service


Queries the status of a service

win32_pause_service
win32_set_service_status
win32service
PHP Manual

win32_query_service_status

(PECL win32service SVN)

win32_query_service_status — Queries the status of a service

Описание

mixed win32_query_service_status ( string $servicename [, string $machine ] )

Queries the current status for a service, returning an array of information.

Список параметров

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Возвращаемые значения

Returns an array consisting of the following information on success, FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

ServiceType

The dwServiceType. See Win32Service Service Type Bitmasks.

CurrentState

The dwCurrentState. See Win32Service Service Status Constants.

ControlsAccepted

Which service controls are accepted by the service. See Win32Service Service Control Message Accepted Bitmasks.

Win32ExitCode

If the service exited, the return code from the process.

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here.

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The Windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags. See Win32Service Service Service Flag Constants.

Смотрите также

  • Win32Service Predefined Constants

User Contributed Notes

demers dot alex at gmail dot com 21-Jul-2009 08:39
This function will return an array containing the above information as a return value, but if this fails it will return an integer which is a System Error Code. All the System Error Codes can be found here:

http://msdn.microsoft.com/en-us/library/ms681381%28VS.85%29.aspx

In my case, it returned 5, in which I immediately knew why and fixed the issue right away.

In the case of mnemotronic at netscape dot net, here in the documentation notes, it returned 1060 which is:

ERROR_SERVICE_DOES_NOT_EXIST
1060 (0x424)
The specified service does not exist as an installed service.

Again, it should not return FALSE, instead an System Error Code for Windows.
CM at chaosmixed dot com 16-Jun-2009 10:29
***Notice the name is IISADMIN and not IIS Admin
right click the serivce then, type in the "Service Name" not the "Display Name" or you will get 1060

<?php
$servicename ="IISADMIN";
$machine ="desktopper";
//print_r (win32_query_Service_status($servicename,$machine));

echo  $servicename;

$sray = win32_query_Service_status($servicename,$machine);

echo "<br>";

print_r ($sray);

echo "<ul>";
echo "<li>Service Type: " .$sray[ServiceType] . "</li>";
echo "<li>CurrentState: " .$sray[CurrentState] . "</li>";
echo "<li>Controls Accpeted: " .$sray[ControlsAccepted] . "</li>";
echo "<li>Win32 Exit Code: " .$sray[Win32ExitCode] . "</li>";
echo "<li>Service Specific Exit Code: " .$sray[ServiceSpecificExitCode] . "</li>";
echo "<li>Check Point: " .$sray[CheckPoint] . "</li>";
echo "<li>Wait Hint: " .$sray[WaitHint] . "</li>";
echo "<li>Process Id: " .$sray[ProcessId] . "</li>";
echo "<li>Service Flags: " .$sray[ServiceFlags] . "</li>";
?>
mnemotronic at netscape dot net 25-Oct-2006 07:30
If the service specified is non-existant, "win32_query_service_status" seems to return an integer, not  the expected FALSE value:

<?php
$svcStatus=win32_query_service_status ('_bogons_');
echo $svcStatus ;
?>

prints 1060

-- This is for xampp PHP; v5.1.6
win32_pause_service
win32_set_service_status
win32service


Update the service status

win32_query_service_status
win32_start_service_ctrl_dispatcher
win32service
PHP Manual

win32_set_service_status

(PECL win32service SVN)

win32_set_service_status — Update the service status

Описание

bool win32_set_service_status ( int $status [, int $checkpoint = 0 ] )

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Список параметров

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

checkpoint

The checkpoint value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up.

The checkpoint is only valid when the status is one of WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING or WIN32_SERVICE_PAUSE_PENDING.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения, FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Смотрите также

  • win32_start_service_ctrl_dispatcher() - Добавляет в Диспетчер Служб скрипт, который может быть использован как служба с заданным именем
  • Win32Service Service Status Constants

User Contributed Notes

paul_nelson57071 at yahoo dot com 13-May-2010 11:04
So after much searching I finally found all the peices to make a working windows service & server including:
- Installing & Uninstalling the service
- Starting & Stopping the Service
- Actually running a basic Server
- Responding to windows Service to Stop/Start/Restart

I hope you find this useful! I did this using PHP 5.2 and the PECL library for 5.2 (PHP 5.3 at the time does not have a PECL Library compiled for it)

<?php
    //Service Settings
    $Service = 'MyServiceFinal';
    $Display = 'My PHP Service';

    //Server Settings
    $host = '127.0.0.1';        //Bind to IP #
    $port = 23;                            //On port #
    $max = 20;                            //Maximum Clients

    //Exit if no start-up argument is passed
    if (!isset($argv[1])){ShowHelp(); exit;}

    //Create Windows Service
    if ($argv[1] == 'install') {
    $x = win32_create_service(array(
        'service' => $Service,
        'display' => $Service,
        'params' => __file__ . ' run',
        'path' => 'c:\\php\\php.exe',
    ));
    debug_zval_dump($x);
    echo "Service Installed\n\n";
    exit;

  //Remove Windows Service
    } else if ($argv[1] == 'uninstall') {
        $x = win32_delete_service($Service);
        debug_zval_dump($x);
        echo "Service Removed\n\n";
        exit;

  //Start Windows Service
    } elseif($argv[1] == "start") {
      $x = win32_start_service($Service);
      debug_zval_dump($x);
      echo "Service Started\n\n";
      exit;

    //Stop Windows Service
    } elseif($argv[1] == "stop") {
      $x = win32_stop_service($Service);
      debug_zval_dump($x);
      echo "Service Stopped\n\n";
      exit;

    //Unkown Command
    } else if ($argv[1] != 'run') {
        ShowHelp(); exit();
    }

//Tell windows the service has started...
if (!win32_start_service_ctrl_dispatcher($Service)) die("Could not connect to service : $Service");
win32_set_service_status(WIN32_SERVICE_RUNNING);

// No timeouts, flush content immediatly
set_time_limit(0);
ob_implicit_flush();

//Server Loop
while (1) {
    usleep(500);

    //Handle Windows Service Request
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }
    //Acutal Server Code

}

//Clean up and Exit
win32_set_service_status(WIN32_SERVICE_STOPPED);
exit;

//*************** FUNCTIONS ***************
function ShowHelp(){
    echo "Usage:
    install:\t installs servce
    uninstall:\t deletes service
    start:\t\t Start the windows service
    stop:\t\t Stops the windows service
    run:\t\t called by CMS to run the service

For information on code numbers type 'net helpmsg xxxx'
EXAMPEL: 'net helpmsg 1072'

    ";
}
?>
m dot hald at surfto dot ch 12-May-2008 04:16
On my Machine (Win XP SP2) the function "win32_get_last_control_message" never returns 4 so i will have to reply to 0 also.

finally after mixing several examples i now have a version working woithout filling my event log with errors:

<?php

/*
 * PHP SAMPLE TEMPLATE
 */

/*
 * APP MAIN FUNCTION
 * Called each second after the function last time finished
 * Should not take longer than max 20 seconds to execute
 * ELSE you should call NTServiceResponder(); at least each 20 secs
 * WARNING: NTServiceResponder will exit; if there was a STOP request
 */
function Service_Main()
{
    // YOU APPLICATION CODE HERE !!!
    sleep(1); // dummy something
}

/********************************************************************
 *
 * SERVICE CONTROLLING
 *
 ********************************************************************/

$SERVICE_NAME = "phptestservice";
$SERVICE_DISPLAY = "Test Service with PHP";

// so u can get: $SERVICE_PATH_PARTS["dirname"] $SERVICE_PATH_PARTS["basename"]  $SERVICE_PATH_PARTS["extension"]
$SERVICE_PATH_PARTS = pathinfo(__FILE__);

$SERVICE_PARAMS = " run";

    if (!isset($argv[1]))
    {
        die("this application need to be installed as a service.\n run with param install");
    }

    if ($argv[1] == 'install')
    {
        $x = win32_create_service(array(
                                        'service' => $SERVICE_NAME,
                                        'display' => $SERVICE_DISPLAY,
                                        'params' =>  __FILE__ . $SERVICE_PARAMS,
                                        //'path' =>  $SERVICE_PATH_PARTS["dirname"] . '\php.exe'
                                        ));
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] == 'uninstall')
    {
        $x = win32_delete_service('dummyphp');
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] != 'run')
    {
        die("bogus args, needs to run as service");
    }

    // Connect to service dispatcher and notify that startup was successful
    if (!win32_start_service_ctrl_dispatcher($SERVICE_NAME)) die('Could not connect to service :'.$SERVICE_NAME);
    win32_set_service_status(WIN32_SERVICE_RUNNING);

    // Main Server Loop
    while (1)
    {
        NTServiceResponder();

        // Main script goes here
        Service_Main();

        sleep(1); // at least 1 sec delay per loop
    }
    win32_set_service_status(WIN32_SERVICE_STOPPED);

/*
 * Response to NTServiceRequests
 */
function NTServiceResponder()
{

    switch (win32_get_last_control_message())
    {
    case 0: // PATCH for: seems never to go to 4 (WIN32_SERVICE_CONTROL_INTERROGATE)
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE;
        break;
    case WIN32_SERVICE_CONTROL_CONTINUE:
        return TRUE; // "Continue"
    case WIN32_SERVICE_CONTROL_INTERROGATE:
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE; // Respond with status
    case WIN32_SERVICE_CONTROL_STOP:
        win32_set_service_status(WIN32_SERVICE_STOPPED);
        exit; // Terminate script
    default:
        win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    return FALSE;
}

?>
win32_query_service_status
win32_start_service_ctrl_dispatcher
win32service


Добавляет в Диспетчер Служб скрипт, который может быть использован как служба с заданным именем

win32_set_service_status
win32_start_service
win32service
PHP Manual

win32_start_service_ctrl_dispatcher

(PECL win32service SVN)

win32_start_service_ctrl_dispatcher — Добавляет в Диспетчер Служб скрипт, который может быть использован как служба с заданным именем

Описание

mixed win32_start_service_ctrl_dispatcher ( string $name )

При запуске с помощью диспетчера служб, процессу службы необходимо сверяться с ним для мониторинга службы и связи с ней. Эта функция выполняет сверку посредством создания потока для обработки низкоуровневой связи с диспетчером служб.

После запуска процесс службы должен осуществить два действия. Первое - сообщить диспетчеру служб, что служба запущена. Это осуществляется путем вызова win32_set_service_status() с константой WIN32_SERVICE_RUNNING. Если вам необходимо выполнить некий длительный процесс перед запуском службы, то вы можете использовать константу WIN32_SERVICE_START_PENDING. Второе - продолжить сверку с диспетчером служб, чтобы определить необходимость отключения. Это осуществляется посредством периодического вызова win32_get_last_control_message() и обработки кода возврата соответствующим образом.

Список параметров

name

Короткое имя службы, как при добавлении с помощью win32_create_service().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения, FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Примеры

Пример #1 Пример win32_start_service_ctrl_dispatcher()

Проверьте, запущен ли сервис в диспетчере служб.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {

  die("Я, вероятно, не запущен в диспетчере служб");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Некий длительный процесс для обработки и запуска службы.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
  # здесь производятся какие-то действия, не занимающие больше чем 30 секунд
  # перед соответствующим переходом в цикл.
}
?>

Смотрите также

  • win32_set_service_status() - Update the service status
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • Коды Ошибок Win32

User Contributed Notes

andrea 09-Oct-2009 03:07
Insert value of params between " if the string have a space:

<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => '"c:\\my folder\myphpservice.php"',
    'path' => 'c:\\PHP\\php.exe'));
*/
?>
dylan at nopower dot org 14-Jul-2007 07:59
<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => 'c:\\myphpservice.php',
    'path' => 'c:\\PHP\\php.exe'));
*/

$myservicename = 'myphpservice';

// Connect to service dispatcher and notify that startup was successful
if (!win32_start_service_ctrl_dispatcher($myservicename)) die('Could not connect to service :'.$myservicename);
win32_set_service_status(WIN32_SERVICE_RUNNING);

// Main Server Loop
while (1) {
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    // Main script goes here

    sleep(10); // Run every 10 seconds
}
win32_set_service_status(WIN32_SERVICE_STOPPED);
?>
Guibod 10-Jul-2007 05:41
Don't try to call "win32_start_service_ctrl_dispatcher" too late in your code. You'd trigger a #2186 error : "The service is not responding to the control function." (from commande line) or a #1053 error : "The service did not respond to the start or control request in a timely fashion." (from services GUI).

Try not to load a bunch of PEAR classes before to register php script as Service like I did.

Another good hint, to get a verbose version of the return code, you can call "NET HELPMSG ###" from command line where ### is your error code.
win32_set_service_status
win32_start_service
win32service


Запускает службу

win32_start_service_ctrl_dispatcher
win32_stop_service
win32service
PHP Manual

win32_start_service

(PECL win32service SVN)

win32_start_service — Запускает службу

Описание

int win32_start_service ( string $servicename [, string $machine ] )

Производит попытку запуска обозначенной службы. Обычно требует административных привилегий.

Список параметров

servicename

Короткое название службы.

machine

Необязательное имя машины. Если не указано, используется на локальной машине.

Возвращаемые значения

Возвращает WIN32_NO_ERROR в случае успешного завершения , FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Смотрите также

  • win32_stop_service() - Останавливает службу
  • Коды Ошибок Win32

User Contributed Notes

edo888 at gmail dot com 18-Mar-2010 05:23
[This] can solve 1053 issue.
You just need to add " if you have spaces in your path...

<?php
win32_create_service(array(
        'service' => 'COMPLAINTS',                 # the name of your service
        'display' => 'Receive email complaints and direct them to the website', # description
        'params' => '"' . __FILE__ . '"' . ' run', # path to the script and parameters
    ));
?>
gunday at poczta dot onet dot pl 16-Oct-2007 06:40
If you get a 1053 error when trying to launch your service, check your service script for errors!

E.g. if you have some syntax errors, the service will attempt to run the php interpreter, but the script won't answer to the service manager with
win32_start_service_ctrl_dispatcher('servicename').

Don't think it is because the call comes to late. It just never came, because there were errors. Test your services with CLI php and then try to run the service.
win32_start_service_ctrl_dispatcher
win32_stop_service
win32service


Останавливает службу

win32_start_service
Обработка XML
win32service
PHP Manual

win32_stop_service

(PECL win32service SVN)

win32_stop_service — Останавливает службу

Описание

int win32_stop_service ( string $servicename [, string $machine ] )

Останавливает обозначенную службу. Требует административных привилегий.

Список параметров

servicename

Короткое название службы.

machine

Необязательное имя машины. Если не указано, используется на локальной машине.

Возвращаемые значения

Возвращает WIN32_NO_ERROR в случае успешного завершения , FALSE если была обнаружена проблема с параметрами или код ошибки Win32 при неудачном завершении работы.

Смотрите также

  • win32_start_service() - Запускает службу
  • Коды Ошибок Win32

User Contributed Notes

There are no user contributed notes for this page.
win32_start_service
Обработка XML
win32service


Обработка XML

  • DOM — Document Object Model
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • DOMAttr — Класс DOMAttr
    • DOMCdataSection — Класс DOMCdataSection
    • DOMCharacterData — Класс DOMCharacterData
    • DOMComment — Класс DOMComment
    • DOMDocument — Класс DOMDocument
    • DOMDocumentFragment — Класс DOMDocumentFragment
    • DOMDocumentType — Класс DOMDocumentType
    • DOMElement — Класс DOMElement
    • DOMEntity — Класс DOMEntity
    • DOMEntityReference — Класс DOMEntityReference
    • DOMException — Класс DOMException
    • DOMImplementation — Класс DOMImplementation
    • DOMNamedNodeMap — Класс DOMNamedNodeMap
    • DOMNode — Класс DOMNode
    • DOMNodeList — Класс DOMNodeList
    • DOMNotation — Класс DOMNotation
    • DOMProcessingInstruction — Класс DOMProcessingInstruction
    • DOMText — The DOMText class
    • DOMXPath — Класс DOMXPath
    • DOM Функции
  • DOM XML (PHP 4)
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • DOM XML (PHP 4) Функции
  • libxml
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • libXMLError — Класс libXMLError
    • libxml Функции
  • qtdom
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • qtdom
  • SDO — Service Data Objects
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Limitations
    • Примеры
    • SDO Функции
  • SDO-DAS-Relational — SDO Relational Data Access Service
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • Limitations
    • SDO-DAS-Relational Функции
  • SDO DAS XML — SDO XML Data Access Service
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • SDO DAS XML Функции
  • SimpleXML
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • SimpleXMLElement — Класс SimpleXMLElement
    • SimpleXMLIterator — Класс SimpleXMLIterator
    • SimpleXML
  • WDDX
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • WDDX Функции
  • XML-анализатор
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Обработчики событий
    • Приведение к одному регистру
    • Коды ошибок
    • Кодировка символов
    • Примеры
    • Функции парсера XML
  • XMLReader
    • Введение
    • Установка и настройка
    • XMLReader — Класс XMLReader
  • XMLWriter
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • XMLWriter
  • XSL
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • XSLTProcessor — Класс XSLTProcessor
  • XSLT (PHP 4)
    • Введение
    • Установка и настройка
    • Предопределенные константы
    • XSLT (PHP 4) Функции

User Contributed Notes

There are no user contributed notes for this page.
win32_stop_service
DOM
Справочник функций


Document Object Model

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • DOMAttr — Класс DOMAttr
    • DOMAttr::__construct — Создает экземпляр класса DOMAttr
    • DOMAttr::isId — Проверяет, является ли атрибут описанным в DTD ID
  • DOMCdataSection — Класс DOMCdataSection
    • DOMCdataSection::__construct — Создает новый экземпляр класса DOMCdataSection
  • DOMCharacterData — Класс DOMCharacterData
    • DOMCharacterData::appendData — Добавляет строку в конец символьных данных узла
    • DOMCharacterData::deleteData — Удаление диапазона символов из узла
    • DOMCharacterData::insertData — Вставляет строку после заданного отступа из 16-битных блоков
    • DOMCharacterData::replaceData — Заменяет подстроку в узле типа DOMCharacterData
    • DOMCharacterData::substringData — Извлекает определенный диапазон данных из узла
  • DOMComment — Класс DOMComment
    • DOMComment::__construct — Создает новый экземпляр класса DOMComment
  • DOMDocument — Класс DOMDocument
    • DOMDocument::__construct — Создание нового DOMDocument объекта
    • DOMDocument::createAttribute — Создает новый атрибут
    • DOMDocument::createAttributeNS — Создает новый узел-атрибут с соответствующим ему пространством имен
    • DOMDocument::createCDATASection — Создает новый cdata узел
    • DOMDocument::createComment — Создает новый узел-комментарий
    • DOMDocument::createDocumentFragment — Создание фрагмента докуента
    • DOMDocument::createElement — Создает новый узел-элемент
    • DOMDocument::createElementNS — Создание нового узла-элемента с соответствующим пространством имен
    • DOMDocument::createEntityReference — Создание нового узла-ссылки на сущность
    • DOMDocument::createProcessingInstruction — Создает новый PI-узел
    • DOMDocument::createTextNode — Создает новый текстовый узел
    • DOMDocument::getElementById — Ищет элемент с заданным id
    • DOMDocument::getElementsByTagName — Ищет все элементы с заданным локальным именем
    • DOMDocument::getElementsByTagNameNS — Ищет элементы с заданным именем в определенном пространстве имен
    • DOMDocument::importNode — Импорт узла в текущий документ
    • DOMDocument::load — Загрузка XML из файла
    • DOMDocument::loadHTML — Загрузка HTML из строки
    • DOMDocument::loadHTMLFile — Загрузка HTML из файла
    • DOMDocument::loadXML — Загрузка XML из строки
    • DOMDocument::normalizeDocument — Нормализует документ
    • DOMDocument::registerNodeClass — Регистрация расширенного класса, используемого для создания базового типа узлов
    • DOMDocument::relaxNGValidate — Производит проверку документа на правильность построения посредством relaxNG
    • DOMDocument::relaxNGValidateSource — Проверяет документ посредством relaxNG
    • DOMDocument::save — Сохраняет XML дерево из внутреннего представления в файл
    • DOMDocument::saveHTML — Сохраняет документ из внутреннего представления в строку, используя HTML форматирование
    • DOMDocument::saveHTMLFile — Сохраняет документ из внутреннего представления в файл, используя HTML форматирование
    • DOMDocument::saveXML — Сохраняет XML дерево из внутреннего представления в виде строки
    • DOMDocument::schemaValidate — Проверяет действительности документа, основываясь на заданной схеме
    • DOMDocument::schemaValidateSource — Проверяет действительность документа, основываясь на схеме
    • DOMDocument::validate — Проверяет документ на соответствие его DTD
    • DOMDocument::xinclude — Проводит вставку XInclude разделов в объектах DOMDocument
  • DOMDocumentFragment — Класс DOMDocumentFragment
    • DOMDocumentFragment::appendXML — Добавление необработанных XML данных
  • DOMDocumentType — Класс DOMDocumentType
  • DOMElement — Класс DOMElement
    • DOMElement::__construct — Создание нового объекта класса DOMElement
    • DOMElement::getAttribute — Возвращает значение атрибута
    • DOMElement::getAttributeNode — Возвращает узел атрибута
    • DOMElement::getAttributeNodeNS — Возвращает узел атрибута
    • DOMElement::getAttributeNS — Возвращает значение атрибута
    • DOMElement::getElementsByTagName — Возвращает элементы по имени тэга
    • DOMElement::getElementsByTagNameNS — Получение элементов по локальному имени в заданном пространстве имен
    • DOMElement::hasAttribute — Проверяет наличие атрибута
    • DOMElement::hasAttributeNS — Проверяет, существует ли заданный атрибут
    • DOMElement::removeAttribute — Удаляет атрибут
    • DOMElement::removeAttributeNode — Удаляет атрибут
    • DOMElement::removeAttributeNS — Удаляет атрибут
    • DOMElement::setAttribute — Устанавливает значение атрибута
    • DOMElement::setAttributeNode — Добавляет новый узел атрибута к элементу
    • DOMElement::setAttributeNodeNS — Добавляет новый атрибут к элементу
    • DOMElement::setAttributeNS — Добавляет новый атрибут
    • DOMElement::setIdAttribute — Объявляет атрибут с заданным именем ключевым атрибутом
    • DOMElement::setIdAttributeNode — Объявляет заданный узал атрибута ключевым
    • DOMElement::setIdAttributeNS — Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим
  • DOMEntity — Класс DOMEntity
  • DOMEntityReference — Класс DOMEntityReference
    • DOMEntityReference::__construct — Создает новый объект класса DOMEntityReference
  • DOMException — Класс DOMException
  • DOMImplementation — Класс DOMImplementation
    • DOMImplementation::__construct — Создает новый объект класса DOMImplementation
    • DOMImplementation::createDocument — Создает объект класса DOMDocument заданного типа с элементом document
    • DOMImplementation::createDocumentType — Создает пустой объект класса DOMDocumentType
    • DOMImplementation::hasFeature — Тестирует реализацию специфичных возможностей объекта DOMImplementation
  • DOMNamedNodeMap — Класс DOMNamedNodeMap
    • DOMNamedNodeMap::getNamedItem — Извлекает узел с заданным именем
    • DOMNamedNodeMap::getNamedItemNS — Извлекает узел с заданным локальным именем и URI пространства имен
    • DOMNamedNodeMap::item — Извлекает узел с заданным индексом
  • DOMNode — Класс DOMNode
    • DOMNode::appendChild — Добавляет новый дочерний узел в конец списка потомков
    • DOMNode::C14N — Canonicalize nodes to a string
    • DOMNode::C14NFile — Canonicalize nodes to a file
    • DOMNode::cloneNode — Клонирует узел
    • DOMNode::getLineNo — Возвращает номер строки узла
    • DOMNode::getNodePath — Получение XPath пути к узлу
    • DOMNode::hasAttributes — Проверяет, содержит ли данный узел атрибуты
    • DOMNode::hasChildNodes — Проверяет, содержит ли данный узел потомков
    • DOMNode::insertBefore — Добавляет новый дочерний узел перед опорным узлом
    • DOMNode::isDefaultNamespace — Проверяет, совпадает ли URI пространства имен узла с пространством имен по умолчанию
    • DOMNode::isSameNode — Проверяет, являются ли два узла одним и тем же узлом
    • DOMNode::isSupported — Проверяет, поддерживается ли заданное свойство в определенной версии
    • DOMNode::lookupNamespaceURI — Получает URI пространства имен узла по префиксу
    • DOMNode::lookupPrefix — Возвращает префикс пространства имен узла из URI пространства имен
    • DOMNode::normalize — Нормализует узел
    • DOMNode::removeChild — Удаляет дочерний узел из списка потомков
    • DOMNode::replaceChild — Заменяет дочерний узел
  • DOMNodeList — Класс DOMNodeList
    • DOMNodelist::item — Извлекает узел с заданным индексом
  • DOMNotation — Класс DOMNotation
  • DOMProcessingInstruction — Класс DOMProcessingInstruction
    • DOMProcessingInstruction::__construct — Создает новый объект классаDOMProcessingInstruction
  • DOMText — The DOMText class
    • DOMText::__construct — Создает объект класса DOMText
    • DOMText::isWhitespaceInElementContent — Определяет, содержит ли текстовый узел пробел в содержимом
    • DOMText::splitText — Разделяет узел на два, начиная с заданной позиции
  • DOMXPath — Класс DOMXPath
    • DOMXPath::__construct — Создает новый объект класса DOMXPath
    • DOMXPath::evaluate — Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно
    • DOMXPath::query — Выполняет заданное XPath выражение
    • DOMXPath::registerNamespace — Ассоциирует пространство имен с объектом DOMXPath
    • DOMXPath::registerPhpFunctions — Регистрация функций PHP как XPath функций
  • DOM Функции
    • dom_import_simplexml — Получает объект класса DOMElement из объекта класса SimpleXMLElement

User Contributed Notes

Drupella 16-Sep-2011 09:18
Here is a fast innerHTML function that returns the result without iterating over child nodes.

<?php
function innerHTML($el) {
  $doc = new DOMDocument();
  $doc->appendChild($doc->importNode($el, TRUE));
  $html = trim($doc->saveHTML());
  $tag = $el->nodeName;
  return preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>$@', '', $html);
}
?>

Example
<?php
$doc = new DOMDocument();
// A corrupt HTML string
$doc->loadHTML('<HTML><A HREF="ss">asd</A>');
$body = $doc->getElementsByTagName('body')->item(0);
print htmlspecialchars(innerHTML($body));
// Prints <a href="ss">asd</a>
?>
ben_demott at hotmail dot com 23-Apr-2010 01:36
A function among several others to parse a google results page, I wrote this some time ago - google has probably changed their site since then, but I thought this might be helpful to someone.

I'm moving servers, but I will probably throw this up on my blog when I get it back up.

<?php

function googleResult($listItem) {
    // given a LIST ITEM element, this will validate, and return an array for that LI entry as an inline result from google.
    /*
     * <li class='g w0'>
     *   <h3 class='r'>
     *     <a href='the URL' class='l'>
     *       Description <em>description</em>
     *     </a>
     *   </h3>
     * </li>
     *
       UPDATE:
       This function will now look for any subcontainer that has an href, it doesn't have to be an H3
       this will make it work with a few more formatted search results.
     */

    $listItem = $listItem->childNodes;
        // Yes I don't use instanceof - I guess you'll have to deal.
    foreach($listItem as $element) {
        if(is_object($element) && get_class($element) == 'DOMElement' && $element->hasChildNodes()) {
            $hrefContainer = $element->childNodes;
            foreach($hrefContainer as $element2) {
                if(is_object($element2) && get_class($element2) == 'DOMElement' && $element2->nodeName == 'a' && $element2->hasAttribute('href')) {
                    $anchor = $element2;
                    unset($h3);
                    unset($element2);
                    break;
                } else {
                  //print __LINE__ ." :: Breaking out of loop (normal result) element is not an annchor Element='".$element2->nodeName."'\n";
                }
            }
            unset($element);
            unset($listItem);
            break;
        }
    }
    if(empty($anchor) || !is_object($anchor) || get_class($anchor) != 'DOMElement') {
        //print __LINE__ ." :: Returning false, did not locate anchor through iteration...";
        return false;
    }
    $href = $anchor->getAttribute('href');
    if(empty($href)) {
        //print __LINE__ ." :: Found anchor object, could not read href attribute / href is empty? href='$href'\n";
        return false;
    }
    $description = $anchor->childNodes;
    $urlDescription = '';
    foreach($description as $words) {
        $name =  trim($words->nodeName);
        if($name == 'em' || $name == '#text' || $name == 'b') {
            if(!empty($words->nodeValue)) {
                $text = trim($words->nodeValue);
                $urlDescription = $urlDescription . $text . ' ';
            }
        }
    }
    $urlDescription = htmlspecialchars_decode($urlDescription, ENT_QUOTES);
    $urlDescription = trim($urlDescription);
    return array('description' => $urlDescription, 'href' => $href);
}
sweisman at pobox dot com 24-Sep-2009 01:19
I had problems with the dom2array_full function by "nospam at ya dot ru". Here's my function, which works correctly for my project, and might work for yours:

<?php
function dom_to_array($root)
{
    $result = array();

    if ($root->hasAttributes())
    {
        $attrs = $root->attributes;

        foreach ($attrs as $i => $attr)
            $result[$attr->name] = $attr->value;
    }

    $children = $root->childNodes;

    if ($children->length == 1)
    {
        $child = $children->item(0);

        if ($child->nodeType == XML_TEXT_NODE)
        {
            $result['_value'] = $child->nodeValue;

            if (count($result) == 1)
                return $result['_value'];
            else
                return $result;
        }
    }

    $group = array();

    for($i = 0; $i < $children->length; $i++)
    {
        $child = $children->item($i);

        if (!isset($result[$child->nodeName]))
            $result[$child->nodeName] = dom_to_array($child);
        else
        {
            if (!isset($group[$child->nodeName]))
            {
                $tmp = $result[$child->nodeName];
                $result[$child->nodeName] = array($tmp);
                $group[$child->nodeName] = 1;
            }

            $result[$child->nodeName][] = dom_to_array($child);
        }
    }

    return $result;
}
?>
odessa131 at aol dot nospam dot com 20-Sep-2009 06:49
I had the hardest time updating a complex XML document. Here's a quick example on how to do it.

<?php

// Load the XML from a file.
$xml = "a2062.xml"; // This is an XFDL form previously unencoded and ungzipped.
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->Load($xml);

// Create an XPath query.
// Note: you must define the namespace if the XML document has defined namespaces.
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xfdl', "http://www.PureEdge.com/XFDL/6.5");

// Locate the value for the first Item Description field.
$query = "//xfdl:page/xfdl:field[@sid='ITEMDESA']/xfdl:value";
$nodeList = $xpath->query($query);

$nodeList->item(0)->nodeValue = "This is the text in the value node of the first Item Description field inside the DA 2062 PureEdge form.";

$dom->save($xml);

?>

I hope this helps someone.
philipwaynerollins at gmail dot com 29-Jul-2009 02:06
You can get the "innerHTML" by nodeValue so

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p', 'Sensei Ninja' );
    print $ele->nodeValue;
?>

You can even set it if you want

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p' );
    $ele->nodeValue = 'Sensei Ninja';
    $doc->appendChild( $ele );
    print $doc->saveHTML( );
?>
xwisdom at yahoo dot com 23-Mar-2009 08:49
Hello,

Here's another way you can  get the inner and outer html content of a element:

<?php
// code taken from the Raxan PDI framework
// returns the html content of an element
protected function nodeContent($n, $outer=false) {
    $d = new DOMDocument('1.0');
    $b = $d->importNode($n->cloneNode(true),true);
    $d->appendChild($b); $h = $d->saveHTML();
    // remove outter tags
    if (!$outer) $h = substr($h,strpos($h,'>')+1,-(strlen($n->nodeName)+4));
    return $h;
}
?>

 There are lots of other PHP DOM manipulation and traversing APIs available at the website. See here http://raxanpdi.com/pdi-overview.html
Junior 20-Mar-2009 01:26
innerHTML in PHP DOM

<?php
function DOMinnerHTML($element)
{
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $tmp_dom = new DOMDocument();
        $tmp_dom->appendChild($tmp_dom->importNode($child, true));
        $innerHTML.=trim($tmp_dom->saveHTML());
    }
    return $innerHTML;
}
?>

Example:

<?php
$dom= new DOMDocument();
$dom->load($html_string);
$dom->preserveWhiteSpace = false;

$domTable = $dom->getElementsByTagName("table");

foreach ($domTable as $tables)
{
    echo DOMinnerHTML($tables);
}
?>
nospam at ya dot ru 06-Jan-2009 10:18
<?PHP
function dom2array_full($node){
    $result = array();
    if($node->nodeType == XML_TEXT_NODE) {
        $result = $node->nodeValue;
    }
    else {
        if($node->hasAttributes()) {
            $attributes = $node->attributes;
            if(!is_null($attributes))
                foreach ($attributes as $index=>$attr)
                    $result[$attr->name] = $attr->value;
        }
        if($node->hasChildNodes()){
            $children = $node->childNodes;
            for($i=0;$i<$children->length;$i++) {
                $child = $children->item($i);
                if($child->nodeName != '#text')
                if(!isset($result[$child->nodeName]))
                    $result[$child->nodeName] = dom2array($child);
                else {
                    $aux = $result[$child->nodeName];
                    $result[$child->nodeName] = array( $aux );
                    $result[$child->nodeName][] = dom2array($child);
                }
            }
        }
    }
    return $result;
}
?>
fantasyman3000 at gmail dot com 06-Dec-2008 05:37
In response to "simlee at indiana dot edu",
- First of all thanks for sharing your funciton.
- It didn't work for me so i rewrite it from scratch using different method.

Here is the new version, hope it helps someone :

<?php
/**
* result sample : /html[1]/body[1]/span[1]/fieldset[1]/div[1]
* @return string
*/
function getNodeXPath( $node ) {
    $result='';
    while ($parentNode = $node->parentNode) {
        $nodeIndex=-1;
        $nodeTagIndex=0;
        do {
            $nodeIndex++;
            $testNode = $parentNode->childNodes->item( $nodeIndex );

            if ($testNode->nodeName==$node->nodeName and $testNode->parentNode->isSameNode($node->parentNode) and $testNode->childNodes->length>0) {
                //echo "{$testNode->parentNode->nodeName}-{$testNode->nodeName}-{}<br/>";
                $nodeTagIndex++;
            }

        } while (!$node->isSameNode($testNode));

        $result="/{$node->nodeName}[{$nodeTagIndex}]".$result;
        $node=$parentNode;
    };
    return $result;
}
?>

By Sina.Salek.ws
cgorbit spamless_at ya dot ru 18-Oct-2008 10:39
Show expandable DOM like in Firebug.

http://cgorbit.itkm.ru/temp/phpdotnet/common.js needed for script, sorry, but it's my framework.

<?php
    function gaie( $node, &$arr, $attr )
    {
        if ( $value = $node->getAttribute( $attr ) )
            $arr[ $attr ] = u2w( $value );
    }

    function innerXML( $l, $collapse_all = true, $top_run = true )
    {
        $atts4elements = array(
            'a' => 'href',
            'table' => 'border,cellpadding,cellspacing',
            'td' => 'colspan,rowspan'
        );
        $s = '';

        if ( $top_run ) :
            ob_start();
            ?><html>
            <head>
                <meta http-uquiv="Content-type" content="text/html; charset=windows-1251" />
                <script type="text/javascript" src="/common.js"></script>
            </head>
            <body>
            <style type="text/css">
                body {
                }

                .root-inner-xml-list {
                    list-style-type: none;

                    font-size: 1em;
                    font-family: monospace;
                }

                .root-inner-xml-list ul {
                    list-style-type: none;
                }

                .root-inner-xml-list li.text-node span.value {
                    color: black;
                    font-weight: bold;
                    background-color: lightgrey;

                    margin-right: 1em;
                    padding: 0em 0.2em;
                }

                .root-inner-xml-list li.text-node span.hex {
                    color: gray;
                    font-style: italic;
                }

                .root-inner-xml-list li.element-node {
                    color: blue;
                }

                .root-inner-xml-list .attribute-name {
                    color: green;
                }

                .root-inner-xml-list .attribute-value {
                    color: red;
                    color: rgb( 205, 0, 0 );
                }

                .root-inner-xml-list .node-with-childs {
                    cursor: pointer;
                    //cursor: hand;
                }

                .root-inner-xml-list .collapsed-node {
                    background-color: yellow;
                }

                .root-inner-xml-list .collapsed-node + ul {
                    display: none;
                }
            </style>

            <ul class="root-inner-xml-list">
            <?
            $s .= ob_get_clean();
        endif;

        //if ( $top_run ) $l = $l->childNodes;

        foreach ( $l as $i => $node )
        {
            if ( $node->nodeType == XML_ELEMENT_NODE )
            {
                $atts = array();
                $atts2get = array( 'id', 'class', 'style' );

                if ( @$atts4elements[ $node->tagName ] )
                    $atts2get = array_merge( $atts2get, explode( ',', $atts4elements[ $node->tagName ] ) );

                foreach ( $atts2get as $att2get )
                    gaie( $node, $atts, $att2get );

                $attr_arr = array();
                foreach ( $atts as $name => $value )
                    $attr_arr[] = sprintf( '<span class="attribute-name">%s</span>="<span class="attribute-value">%s</span>"', $name, $value );

                $atts_s = '';
                if ( $attr_arr )
                    $atts_s = join( ' ', $attr_arr );

                $span_class_name = array( 'node-name' );
                if ( $node->childNodes->length )
                    $span_class_name[] = 'node-with-childs';
                if ( $collapse_all )
                    $span_class_name[] = 'collapsed-node';
                $span_class_name = join( ' ', $span_class_name );

                $inner = '<span class="' . $span_class_name . '">&lt;'. $node->tagName . ' ' . $atts_s . '&gt;</span>';

                if ( $node->childNodes->length )
                    $inner .= '<ul>' . innerXML( $node->childNodes, $collapse_all, false ) . '</ul>';

                $className = 'element-node';
            }
            elseif ( $node->nodeType == XML_TEXT_NODE )
            {
                $value = htmlspecialchars( u2w( $node->nodeValue ) );
                $inner = '<span class="value">' . $value . '</span><span class="hex">' . string2hex( $value ) . '</span>';

                $className = 'text-node';
            }
            else
                continue;

            $s .= '<li class="' . $className . '">' . $inner . '</li>';

            if ( $top_run ) echo '<hr />';
        }

        if ( $top_run ):
        ob_start();
        ?></ul>
            <script type="text/javascript">
                onLoad( function(){
                    addEvent( $( '.root-inner-xml-list .node-with-childs', true ), 'click', function( e ){
                        var el = e.target;

                        ul = getNextSibling( el );

                        if ( !ul || ul.tagName != 'UL' ) return;

                        invertClass( el, 'collapsed-node' );
                    });
                });

                globalInit();
            </script>
        </body>
        </html>
        <?
        $s .= ob_get_clean();
        endif;

        return $s;
    }
?>
miguelangelhdz at NOSPAM dot com 22-Sep-2008 06:19
After searching how to extend the DOMDocument and DOMElement I found a way in the bug: http://bugs.php.net/bug.php?id=35104. The following code shows how:

<?php
class extDOMDocument extends DOMDocument {
 public function createElement($name, $value=null) {
  $orphan = new extDOMElement($name, $value); // new  sub-class object
  $docFragment = $this->createDocumentFragment(); // lightweight container maintains "ownerDocument"
  $docFragment->appendChild($orphan); // attach
  $ret = $docFragment->removeChild($orphan); // remove
  return $ret; // ownerDocument set; won't be destroyed on  method exit
 }
 // .. more class definition
}

class extDOMElement extends DOMElement {
 function __construct($name, $value='', $namespaceURI=null) {
  parent::__construct($name, $value, $namespaceURI);
 }
  //  ... more class definition here
}

$doc = new extDOMDocument('test');
$el = $doc->createElement('tagname');
$el->setAttribute("attr", "val");
$doc->appendChild($el);

// append discards the DOMDocumentFragment and just adds its child nodes, but ownerDocument is maintained.
echo get_class($el)."<br/>";
echo get_class($doc->documentElement)."<br/>";
echo "<xmp>".$doc->saveXML()."</xmp>";
?>
tobiasz.cudnik[at]gmail.com 29-Jul-2008 06:47
If you need simple interface to DOM check out phpQuery - jQuery port to PHP:
http://code.google.com/p/phpquery/

It uses CSS selectors to fetch nodes.
Here's example how it works:
<?php
// just one file to include
require('phpQuery/phpQuery.php');

$html = '
<div>
    mydiv
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
</div>';

// intialize new DOM from markup
phpQuery::newDocument($markup)
    ->find('ul > li')
        ->addClass('my-new-class')
        ->filter(':last')
            ->addClass('last-li');

// query all unordered lists in last used DOM
pq('ul')->insertAfter('div');

// iterate all LIs from last used DOM
foreach(pq('li') as $li) {
    // iteration returns plain DOM nodes, not phpQuery objects
    pq($li)->addClass('my-second-new-class');
}

// same as pq('anything')->htmlOuter()
// but on document root (returns doctype etc)
print phpQuery::getDocument();
?>

It uses DOM extension and XPath so it works only in PHP5.
Sven Arduwie 16-Mar-2008 06:28
I needed a function that quickly converts an xml with key/value pairs to an array.

for example:
<?xml version="1.0" encoding="UTF-8"?>
<test>
    <key id="Array key #1" value="Value #1"/>
    <key id="Array key #2" value="Value #2"/>
    <key id="Dupe" value="Duplicate keys"/>
    <key id="Dupe" value="create numeric arrays"/>
    <key id="And another key">
        <![CDATA[
            Multiline
            data
            works
            just
            as
            well.
        ]]>
    </key>
    <nested>
        <key id="Nested key" value="Nested data works as well, but it still results in a 1 dimensional array."/>
    </nested>
</test>

Results in the following array:
array(5) {
  ["Array key #1"]=>
  string(8) "Value #1"
  ["Array key #2"]=>
  string(8) "Value #2"
  ["Dupe"]=>
  array(2) {
    [0]=>
    string(14) "Duplicate keys"
    [1]=>
    string(21) "create numeric arrays"
  }
  ["And another key"]=>
  string(49) "Multiline
            data
            works
            just
            as
            well."
  ["Nested key"]=>
  string(73) "Nested data works as well, but it still results in a 1 dimensional array."
}

Here's the code:
<?php
    function xml2array($xml) {
        $domDocument = new DOMDocument;
        $domDocument->loadXML($xml);
        $domXPath = new DOMXPath($domDocument);
        $array = array();
        foreach ($domXPath->query('//key') as $keyDOM) {
            $id = $keyDOM->getAttribute('id');
            $value = $keyDOM->hasAttribute('value') ? $keyDOM->getAttribute('value') : trim($keyDOM->textContent);
            if (array_key_exists($id, $array)) {
                if (is_array($array[$id])) {
                    $array[$id][] = $value;
                } else {
                    $array[$id] = array($array[$id]);
                    $array[$id][] = $value;
                }
            } else {
                $array[$id] = $value;
            }
        }
        return $array;
    }
?>
danf dot 1979 at []gmail[] dot com 24-Feb-2008 07:47
This is a couple of classes to deal with yahoo yui menu.

/*
  $menubar = new MenuBar();

  $file = new Menu("File");
  $file->setAttribute("href", "http://file.com");

  $quit = new Menu("Quit");
  $quit->setAttribute("href", "http://quit.com");

  $file->appendChild($quit);
  $menubar->appendChild($file);

  echo $menubar->grab();
*/

//
// Author: Daniel Queirolo.
// LGPL
//

/** ---------------------------------
/**  Class MenuBar()
/**  Creates a the menubar and appends
/**  yuimenubaritems to it.
/** ---------------------------------*/

class MenuBar extends DOMDocument
{

  public $menuID = "nav_menu";  // holds the css id that javascript yui menu code should have to recognize
  private $UL;                  // This node holds every menu, This is THE node.

  /** ---------------------------------
  /**  Constructor
  /**  Generates a menubar skeleton and the UL node
  /** ---------------------------------*/

  public function __construct() {

    parent::__construct();

    $rootdiv = parent::createElement("div");
    $rootdiv->setAttribute("class", "yui-skin-sam");

    parent::appendChild($rootdiv);

    $yui_menubar = parent::createElement("div");
    $yui_menubar->setAttribute("id", $this->menuID);
    $yui_menubar->setAttribute("class", "yuimenubar");

    $rootdiv->appendChild($yui_menubar);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yui_menubar->appendChild($bd);

    $ul = parent::createElement("ul");
    $ul->setAttribute("class", "first-of-type");

    // ALL Menu() instances ocurr inside an <ul> tag.

    $this->UL = $bd->appendChild($ul);

  }

  /** ---------------------------------
  /**  appendChild()
  /**  Appends a new yuimenubaritem to the menubar UL node.
  /**  This function changes <li> and <a> classes to yuiMENUBARsomething
  /** ---------------------------------*/

  public function appendChild($child) {

    $li = parent::importNode($child->LI, true);

    $li->setAttribute("class", "yuimenubaritem");

    $li->getElementsByTagName("a")->item(0)->setAttribute("class", "yuimenubaritemlabel");

    $this->UL->appendChild($li);

  }

  public function grab() {

    return parent::saveHTML();

  }

}

/** ---------------------------------
/**  Class Menu()
/**  Creates a yuimenuitem li node
/** ---------------------------------*/

class Menu extends DOMDocument {

  public $LI; // stores the <li> node (THE link) that will be exported to MenuBar() or used on appendChild()

  /** ---------------------------------
  /**  Constructor
  /**  Generates a yuimenuitem li node
  /**  No yuimenubar items are created here. MenuBar handles that.
  /** ---------------------------------*/

  public function __construct($link_name) {

    parent::__construct();

    $li = parent::createElement("li");
    $li->setAttribute("class", "yuimenuitem");

    // LI node stores THE link.
    // if appendChild is used, the new (sub) Menu() would be LI node child.

    $this->LI = parent::appendChild($li);

    $a = parent::createElement("a", $link_name);
    $a->setAttribute("class", "yuimenuitemlabel");

    $li->appendChild($a);

    $this->li = $li;
    $this->a = $a;

  }

  /** ---------------------------------
  /**  appendChild
  /**  Appends a (sub) Menu() to current Menu() in LI
  /** ---------------------------------*/

  public function appendChild($child) {

    $yuimenu = parent::createElement("div");
    $yuimenu->setAttribute("class", "yuimenu");

    $this->LI->appendChild($yuimenu);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yuimenu->appendChild($bd);

    $ul = parent::createElement("ul");

    $bd->appendChild($ul);

    // child->NODE holds THE link from the new child (from child's __construct())

    $ul->appendChild(parent::importNode($child->LI, true));

  }

  public function setAttribute($name, $value, $node="a") {

      if ($node == "a") {
        $this->a->setAttribute($name, $value);
      }

      else {
        $this->li->setAttribute($name, $value);
      }
  }

}
ptichy at pobox dot sk 09-Feb-2008 02:40
How to get contents of node with all tags by PHP Dom:
<?php
// XML data
$xml_string = "<?xml version='1.0' ?>
<sentence>
How to get contents of node with all tags by PHP Dom: <br/>
<b>cabbages</b>, <i>tomatoes</i>,
  <i>apples</i>, <font  color='purple'>aubergines</font>
<ol>
   <li> row 1</li>
   <li> row 2 </li>
   <li> row 3 </li>
 </ol>
 <table border = '1'>
  <tbody>
    <tr>
      <td>I am best</td>
    </tr>
    <tr>
      <td>Programmer</td>
    </tr>
  </tbody>
</table>
You see my projects at:
<strong><a href='http://www.itdeveloping.eu' >www.itdeveloping.eu</a></strong>
</sentence>";

// parse it
$doc= new DOMDocument();
if (!$doc->loadXML($xml_string))
{
   echo ("Error in XML document");
}

$nody = $doc->getElementsByTagName('sentence'); // gets NodeList

$nod=$nody->item(0);//Node
getContent($Content,$nod);
echo $Content;

function getContent(&$NodeContent="",$nod)
{    $NodList=$nod->childNodes;
    for( $j=0 ;  $j < $NodList->length; $j++ )
    {       $nod2=$NodList->item($j);//Node j
        $nodemane=$nod2->nodeName;
        $nodevalue=$nod2->nodeValue;
        if($nod2->nodeType == XML_TEXT_NODE)
            $NodeContent .=  $nodevalue;
        else
        {     $NodeContent .= "<$nodemane ";
           $attAre=$nod2->attributes;
           foreach ($attAre as $value)
              $NodeContent .="{$value->nodeName}='{$value->nodeValue}'" ;
            $NodeContent .=">";
            getContent($NodeContent,$nod2);
            $NodeContent .= "</$nodemane>";
        }
    }

}
?>
Anonymous 29-Jan-2008 11:37
In response to...
"If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement."

... it is not a bug, it is a feature. The DOMDocument::$documentElement property name may be misleading but according to the DOM Level 2 Core specification it is a convenience attribute meant to access the root element of your DOMDocument. See here: http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document
ryoroxdahouse at hotmail dot com 25-Jan-2008 12:14
I use DOM to generate dynamically XHTML document.

When trying to extend the DOMDocument and DOMElement classes, I found a very annoying bug concerning DOMDocument::$documentElement.

If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement.

In my situation, I cannot use DOMDocument::registerNodeClass() because the document element is not necessarily the base class for all the elements in my document.

*******
problem
*******

See bellow for the repro step:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $myDocument->appendChild(new MyElement('myElement','myElement'));
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

Notice: Undefined property: DOMElement::$myProp in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 11
$myElement->myProp :

Fatal error: Call to undefined method DOMElement::myMethod() in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 12

*******
solution
*******

After searching around, I found a pretty odd way to fix this problem. It seems that you have to stock a reference to your appended document element in an user-defined (and persistent) variable (in other words, not only in DOMDocument::$documentElement). See below:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $mydocumentElement=$myDocument->appendChild(new MyElement('myElement','myElement')); //here is the hack
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

$myElement->myProp :myProp
$myElement->myMethod :myMethod()

Hope it will help.
moshedolev at gmail dot com 08-Jan-2008 10:15
I developed a group of functions that make it very easy to extract any information you want from any page you load from the internet. All based on the DOMDocument object.
You can read the entire documentation and download the source code here:
http://www.tintetoner-shop.de/DomUtilities/

Enjoy !!
naudyj at aus3d.com 03-Jan-2008 05:06
The following can take a XML_TEXT_NODE node and return the contents in an array. Yanick's contribution rocks - but
it overwrote with duplicates only keeping the last line
in the returned array. All the other functions i tested from various sources failed to handle text nodes correctly. Hope this helps someone. It is adapted from code on this site.

function myTextNode($n, &$a)
{
 static $depth = 0;
 static $sz = '';

 if ($cn = $n->firstChild)
 {
  while ($cn)
  {
   if ($cn->nodeType == XML_TEXT_NODE)
   {
    $sz .= $cn->nodeValue;
   }
   elseif ($cn->nodeType == XML_ELEMENT_NODE)
   {
    $b = 1;
    if ($cn->hasChildNodes())
    {
     $depth++;
     if ($this->myHeadings($cn, $a))
     {
      if ($sz){
       array_push($a, $sz);
       $sz = '';
      }
     }
     $depth--;
    }
   }
   $cn = $cn->nextSibling;
  }
  return $b;
 }
}

so you could use:

$nodes = $dom->getElementsByTagName("td");
if($nodes){
 foreach ($nodes as $node){
  $a = Array();
  myTextNode($node, $a);
 }
}
trollboy at shoggoth dot net 12-Nov-2007 03:12
I wrote a simple class to turn an associative array into xml, as this seems like something fairly simple, but nothing out there does it that I know of.  That said,  enjoy.

<?php

    /**
     * basic class for converting an array to xml.
     * @author Matt Wiseman (trollboy at shoggoth.net)
     *
     */
    class array2xml {

        public $data;
        public $dom_tree;

        /**
         * basic constructor
         *
         * @param array $array
         */
        public  function __construct($array){
            if(!is_array($array)){
                throw new Exception('array2xml requires an array', 1);
                unset($this);
            }
            if(!count($array)){
                throw new Exception('array is empty', 2);
                unset($this);
            }

            $this->data = new DOMDocument('1.0');

            $this->dom_tree = $this->data->createElement('result');
            $this->data->appendChild($this->dom_tree);
            $this->recurse_node($array, $this->dom_tree);
        }

        /**
         * recurse a nested array and return dom back
         *
         * @param array $data
         * @param dom element $obj
         */
        private function recurse_node($data, $obj){
            $i = 0;
            foreach($data as $key=>$value){
                if(is_array($value)){
                    //recurse if neccisary
                    $sub_obj[$i] = $this->data->createElement($key);
                    $obj->appendChild($sub_obj[$i]);
                    $this->recurse_node($value, $sub_obj[$i]);
                } elseif(is_object($value)) {
                    //no object support so just say what it is
                    $sub_obj[$i] = $this->data->createElement($key, 'Object: "' . $key . '" type: "'  . get_class($value) . '"');
                    $obj->appendChild($sub_obj[$i]);
                } else {
                    //straight up data, no weirdness
                    $sub_obj[$i] = $this->data->createElement($key, $value);
                    $obj->appendChild($sub_obj[$i]);
                }
                $i++;
            }
        }

        /**
         * get the finished xml
         *
         * @return string
         */
        public function saveXML(){
            return $this->data->saveXML();
        }
    }

    $test = array(
        'cat'=>'animal',
        'container'=> array(
            'thing'=>'stuff',
            'thing2'=>'stuff2',
            'thing3'=>3,
            'thing4'=>4,
            'wtf'=> new stdClass(),
        ),
        'foo'=>'bar',
    );

    var_dump($test);
    try {
    $o_test = new array2xml($test);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    echo $o_test->saveXML();
    ?>
jim.filter (at gmail.com) 03-Nov-2007 07:42
Array to DOM

Here is a recursive function to turn a multidimensional array into an XML document.  It will handle multiple elements of the same tag, but only one per parent element. IE:

Can't generate:         Can generate:
<root>                  <root>
  <sub1>data1</sub1>      <subs1>
  <sub1>data2</sub1>         <value>data1</value>
  <sub2>data1</sub2>         <value>data2</value>
  <sub2>data2</sub2>      </subs1>
</root>                   <subs2>
                            <value>data1</value>
                            <value>data2</value>
                          <subs2>
                        </root>

Also, the function performs no type of error checking on your array and will throw a DOMException if a key value you used in your array contains invalid characters for a proper DOM tag. This function is untested for "deep" multidimensional arrays.

Complete code ready to run with example:

<?PHP
  function AtoX($array, $DOM=null, $root=null){

    if($DOM  == null){$DOM  = new DOMDocument('1.0', 'iso-8859-1');}
    if($root == null){$root = $DOM->appendChild($DOM->createElement('root'));}

    $name = $array['#MULTIPLE_ELEMENT_NAME'];

      foreach($array as $key => $value){
        if(is_int($key) && $name != null){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($name));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($name, $value));
          }
        }
        else if(is_string($key) && $key != '#MULTIPLE_ELEMENT_NAME'){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($key));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($key, $value));
          }
        }
      }
    return $DOM;
  }

  $array = array(
                    '#MULTIPLE_ELEMENT_NAME' => 'GenericDatas',
                    'Date'      => 'November 03, 2007',
                    'Company'   => 'Facility One',
                    'Field'     => 'Facility Management Software',
                    'Employees' => array(
                                      '#MULTIPLE_ELEMENT_NAME' => 'Employee',
                                      'Cindy',
                                      'Sean',
                                      'Joe',
                                      'Owen',
                                      'Jim',
                                      'Dale',
                                      'Kelly',
                                      'Ryan',
                                      'Johnathan',
                                      'Robin',
                                      'William Marcus',
                                      'NewCoops' => array(
                                                          '#MULTIPLE_ELEMENT_NAME' => 'Coop',
                                                          'John',
                                                          'Tyler',
                                                          'Ray',
                                                          'Dawn'
                                                         )
                                    ),
                    'Datas',
                    'DATAS',
                    'OtherDatas'
                );

  $DOM  = new DOMDocument('1.0', 'iso-8859-1');
  $root = $DOM->appendChild($DOM->createElement('CompanyData'));
  $DOM  = AtoX($array, $DOM, $root);
  $DOM->save('C:\test.xml');
?>
freyjkell at gmail dot com 02-Nov-2007 10:02
In order to REALLY well handle XHTML entities with DOM, you can do following things:

1. Add this DOCTYPE to your documents
<!DOCTYPE xhtmlentities PUBLIC "-//W3C//ENTITIES XHTML Character Entities 1.0//EN" "/xhtml11.ent">

2. Copy http://freyjkell.ovh.org/xhtml11.ent into your document root.

3. In your PHP:
<?php
$dom=new DOMDocument();
$dom->load('file.xhtml',LIBXML_DTDLOAD); // NOT resolveExternals - it needs true doctype, and includes crap code
// some DOM operations
$doctype=DOMImplementation::createDocumentType("html","-//W3C//DTD XHTML 1.1//EN","http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"); // creating real doctype
$output=DOMImplementation::createDocument('','',$doctype);
$output->appendChild($output->importNode($dom->documentElement,true));
$output->encoding='utf-8';
$output=$output->saveXML();
$xhtml=preg_match(
    '/application\/xhtml\+xml(?![+a-z])'.
    '(;q=(0\.\d{1,3}|[01]))?/i',
    $_SERVER['HTTP_ACCEPT'],$xhtml) &&
    (isset($xhtml[2])?$xhtml[2]:1) > 0 ||
    strpos($_SERVER["HTTP_USER_AGENT"],
    "W3C_Validator")!==false ||
    strpos($_SERVER["HTTP_USER_AGENT"],
    "WebKit")!==false; // XHTML Content-Negotiation
header('Content-Type: '.($xhtml?'application/xhtml+xml':'text/html').'; charset=utf-8');
print $output;
?>
PHPdeveloper 06-Sep-2007 02:46
The Yanik's dom2array() function (added on 14-Mar-2007 08:40) does not handle multiple nodes with the same name, i.e.:

<foo>
  <name>aa</name>
  <name>bb</name>
</foo>

It will overwrite former and your array will contain just the last one ("bb")
Francois Hill 01-Aug-2007 11:21
In response to lutfi at smartconsultant dot us :

(see my post on
http://fr2.php.net/manual/en/
function.dom-domdocument-getelementsbytagname.php
)

Use this class I wrote:

class XPathableNode extends DOMNode
{
    protected $Node;
    protected $DOMDocument_from_node;
    protected $DOMXpath_for_node;

    public function __construct(/* DOMNode */ $node)
    {
        $this->Node=$node;
        $this->DOMDocument_from_node=new
                                                          DomDocument();
        $domNode=$this->DOMDocument_from_node
                                  ->importNode($this->Node, true);
        $this->DOMDocument_from_node
                                 ->appendChild($domNode);
        $this->DomXpath_for_node =
                    new Domxpath($this->
                                         DOMDocument_from_node);
    }

    public function convertHTML()
    {    return $this->DOMDocument_from_node
                                                             ->saveHTML();
    }

    public /*DomNodeList*/ function applyXpath($xpath)
    {    return $this->DomXpath_for_node
                                                       ->query($xpath);
    }
}

(sorry for the display... What a terrible hinderance on the
part of php.net !)

Then :
Make a new XPathableNode out of your parent node.
You may then retrieve a DOMNodeList from it by applying a
xpath (thus being able to specify the depth  and name of
elements you want).

Has got me around some (of the many) DOM awkwardnesses a few times.

;o)
lpetrov AT axisvista.com 20-Jul-2007 05:41
Basicly there are alot of problems on dynamic namespaces registering and other maybe 'not well' documented parts of DOM.

Here is an article covering some of the problems that our company web developers found while we were developing a template engine for our new framework.

The link:
http://blog.axisvista.com/?p=35
lutfi at smartconsultant dot us 19-Jul-2007 09:06
i have some problem parsing recurred xml tree here:

<menu name='parent1' >
  <submenu name='file' >
     <submenu name='open' >Open file</submenu>
     <submenu name='close' >Close file</submenu>
  </submenu>
  <submenu name='edit' >
     <submenu name='cut' >Cut Clipboards</submenu>
     <submenu name='copy' >Copy Clipboards</submenu>
     <submenu name='paste' >Paste Clipboards</submenu>
  </submenu>
</menu>

with getElementsByTagName all submenu is on the same level.
i want it to be structured like tree list, but not change the 'submenu' tag
Sanados at failure dot at 05-Jun-2007 02:45
appended to
brian dot reynolds at risaris dot com
20-Feb-2007 10:09

when you got variable nodes at start you array fails and looses nodes  beneath.
solution that counts occurance though eats up performance:

function xmlToArray($n)
{
    $xml_array = array();
    $occurance = array();

     foreach($n->childNodes as $nc)
     {
         $occurance[$nc->nodeName]++;
     }

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() )
        {
            if($occurance[$nc->nodeName] > 1)
            {
                $xml_array[$nc->nodeName][] = xmlToArray($nc);
            }
            else
            {
                $xml_array[$nc->nodeName] = xmlToArray($nc);
            }
        }
        else
        {
            return utf8_decode($nc->nodeValue);
        }
    }
    return $xml_array;
}
Yanik <clonyara(at)ahoo(dot)com> 13-Mar-2007 11:40
I hate DOM model !
so I wrote dom2array simple function (simple for use):

function dom2array($node) {
  $res = array();
  print $node->nodeType.'<br/>';
  if($node->nodeType == XML_TEXT_NODE){
      $res = $node->nodeValue;
  }
  else{
      if($node->hasAttributes()){
          $attributes = $node->attributes;
          if(!is_null($attributes)){
              $res['@attributes'] = array();
              foreach ($attributes as $index=>$attr) {
                  $res['@attributes'][$attr->name] = $attr->value;
              }
          }
      }
      if($node->hasChildNodes()){
          $children = $node->childNodes;
          for($i=0;$i<$children->length;$i++){
              $child = $children->item($i);
              $res[$child->nodeName] = dom2array($child);
          }
      }
  }
  return $res;
}
Nevyn at N dot O dot S dot P dot A dot M dot emai dot it 10-Mar-2007 07:35
I wrote a couple of functions to:
 - create a DOMDocument from a file
 - parse the namespaces in it
 - create a XPath object with all the namespaces registered
 - load the schemalocations
 - validate the file on the main schema (the one without prefix)

It is useful for me, see if it is also for someone else!!

Giulio

function decodeNode($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<((?:\\w*:)?\\w*)". //the tag name
    "[\\s\n\r]*((?:[\\s\n\r]*".
    "(?:\\w*:)?\\w+[\\s\n\r]*=[\\s\n\r]*". //possible attribute name
    "(?:\"[^\"]*\"|\'[^\']*\'))*)". //attribute value
    "[\\s\n\r]*>[\r\n]*".
    "((?:.*[\r\n]*)*)". //content
    "[\r\n]*</\\1>$}"; //closing tag
    preg_match($re, $out, $mat);
    return $mat;
}

function innerXml($node)
{
    $mat = decodeNode($node);
    return $mat[3];
}

function getnodeAttributes($node)
{
    $mat = decodeNode($node);
    $txt = $mat[2];
    $re = "{((?:\\w*:)?\\w+)[\\s\n\r]*=[\\s\n\r]*(\"[^\"]*\"|\'[^\']*\')}";
    preg_match_all($re, $txt, $mat);
    $att = array();
    for ($i=0; $i<count($mat[0]); $i++)
    {
        $value = $mat[2][$i];
        if ($value[0] == "\'" || $value[0] == "\"")
        {
            $len = strlen($value);
            $value = substr($value, 1, strlen($value)-2);
        }
        $att[ $mat[1][$i] ] = $value;
    }
    return $att;
}

function loadXml($file)
{
    $doc = new DOMDocument();
    $doc->load($file);
    //cerca l'attributo xmlns
    $xsi = false;
    $doc->namespaces = array();
    $doc->xpath = new DOMXPath($doc);

    $attr = getnodeAttributes($doc->documentElement);
    foreach ($attr as $name => $value)
    {
        if (substr($name,0,5) == "xmlns")
        {
            $uri = $value;
            $pre = $doc->documentElement->lookupPrefix($uri);
            if ($uri == "http://www.w3.org/2001/XMLSchema-instance")
                $xsi = $pre;
            $doc->namespaces[$pre] = $uri;
            if ($pre == "")
                $pre = "noname";
            $doc->xpath->registerNamespace($pre, $uri);
        }
    }

    if ($xsi)
    {
        $doc->schemaLocations = array();
        $lst = $doc->xpath->query("//@$xsi:schemaLocation");
        foreach($lst as $el)
        {
            $re = "{[\\s\n\r]*([^\\s\n\r]+)[\\s\n\r]*([^\\s\n\r]+)}";
            preg_match_all($re, $el->nodeValue, $mat);
            for ($i=0; $i<count($mat[0]); $i++)
            {
                $value = $mat[2][$i];
                $doc->schemaLocations[ $mat[1][$i] ] = $value;
            }
        }

        $olddir = getcwd();
        chdir(dirname($file));
        $schema = $doc->schemaLocations[$doc->namespaces[""]];
        if (substr($schema,0,7) == "file://")
        {
            $schema = substr($value,7);
        }
        if (!$doc->schemaValidate($schema))
            dbg()->err("Invalid file");
        chdir($olddir);
    }

    return $doc;
}
brian dot reynolds at risaris dot com 20-Feb-2007 01:09
I found the xml2array function below very useful, but there seems to be a bug in it. The $item variable was never getting set. I've expanded this out to be a bit more readable, and the corrected code is :

function xmlToArray($n)
{
    $return=array();

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() ){
            if( $n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1){
                $item = $n->firstChild;
                $return[$nc->nodeName][]=$this->xmlToArray($item);
            }
            else{
                 $return[$nc->nodeName]=$this->xmlToArray($nc);
            }
       }
       else{
           $return=$nc->nodeValue;
       }
    }
    return $return;
}
cooper at asu dot ntu-kpi dot kiev dot ua 22-Nov-2006 02:32
If you are using not object-oriented functions and it takes too much time to change them all (or you'll be replacing them later) then as a temporary decision can be used this modules:

For DOM XML:
http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/

For XSLT:
http://alexandre.alapetite.net/doc-alex/xslt-php4-php5/
cormac at idreamproducts dot com 17-Oct-2006 03:48
Most email clients ignore stylesheets in HTML formatted emails.  The best way to ensure your HTML is formatted correctly by a broad spectrum of email clients, including webmail implementations as Gmail, is to use inline style attributes.  The following function uses DOM to parse an inline stylesheet, and will replace element class and id attributes with inline style attributes, and add inline style attributes for generic tag stylesheet rules.  It will remove the stylesheet and any used class and id attributes as these are defunct for most email clients.  It is a fairly lightweight function and does not support CSS inheritance, but will work for simple stylesheets e.g.:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>HTML EMAIL</title>
<style type="text/css">
body {
  margin: 10px 10px;
  font: 8pt arial;
  background: #fff;
  color: #000;
}
p {
  margin: 0 0 10px;
  line-height: 1.2em;
  text-align: justify;
}
p.centered {
  text-align: centre;
}
p#right {
  text-align: right;
}
</style>
</head>
<body>
<p>Sample text justified</p>
<p class="centered">Centered text here</p>
<p id="right">Right-aligned text</p>
</body>
</html>

Here's the function:

<?php
function parseStyleSheetfor Email($html)
{
  $doc = new DOMDocument;
  $doc->loadHTML($html);
  // grab inline stylesheet as DOM object
  $oStyle = $doc->getElementsByTagName('style')->item(0);
  // grab rule identifiers and rules
  preg_match_all('/^([-#._a-z0-9]+) ?\{(.*?)\}/ims', $oStyle->nodeValue, $aMatches, PREG_SET_ORDER);
  foreach ($aMatches as $aRule) {
    $rule_id = $aRule[1];
    // clean up rules
    $rule = str_replace(array("\r", "\n", '  ', '; '), array('', '', ' ', ';'), $aRule[2]);
    $rule = preg_replace(array('/^ /', '/;$/'), '', $rule);
    // generic rules
    if (!strstr($rule_id, '.') && !strstr($rule_id, '#')) {
      $items = $doc->getElementsByTagName($rule_id);
      // set style attribute equal to rule from stylesheet
      foreach ($items as $item) {
        // if there is already inline style append it to end of stylesheet rule
        $current_style = $item->getAttribute('style');
        if (!empty($current_style)) {
          $item->setAttribute('style', $rule . ';' . $current_style);
        } else {
          $item->setAttribute('style', $rule);
        }
      }
    // classes
    } elseif (strstr($rule_id, '.')) {
      list($rule_tag, $rule_class) = explode('.', $rule_id);
      $items = $doc->getElementsByTagName($rule_tag);
      foreach ($items as $item) {
        $class = $item->getAttribute('class');
        if ($class == $rule_class) {
          // if there is already inline style append it to end of stylesheet rule
          $current_style = $item->getAttribute('style');
          if (!empty($current_style)) {
            $item->setAttribute('style', $current_style . ';' . $rule);
          } else {
            $item->setAttribute('style', $rule);
          }
          // remove class as it won't be used now
          $item->removeAttribute('class');
        }
      }
    // ids
    } elseif (strstr($rule_id, '#')) {
      list($rule_tag, $id) = explode('#', $rule_id);
      $item = $doc->getElementById($id);
      $current_style = $item->getAttribute('style');
      if (!empty($current_style)) {
        $item->setAttribute('style', $current_style . ';' . $rule);
      } else {
        $item->setAttribute('style', $rule);
      }
      // remove class as it won't be used now
      $item->removeAttribute('id');
    }
  }
  // remove inline stylesheet
  $oStyle->parentNode->removeChild($oStyle);
  return $doc->saveHTML();
}
?>
sean at lookin3d dot com 17-Aug-2006 10:21
$xmlDoc=<<<XML
<?xml version="1.0"?>
<methodCall>
   <methodName>examples.getStateName</methodName>
   <params>
      <param>
         <value><i4>41</i4></value>
         </param>
      </params>
   </methodCall>
XML;

$xml= new DOMDocument();
$xml->preserveWhiteSpace=false;
$xml->loadXML($xmlDoc);
print_r(xml2array($xml));

function xml2array($n)
{
    $return=array();
    foreach($n->childNodes as $nc)
    ($nc->hasChildNodes())
    ?($n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1)
    ?$return[$nc->nodeName][]=xml2array($item)
    :$return[$nc->nodeName]=xml2array($nc)
    :$return=$nc->nodeValue;
    return $return;
}
simlee at indiana dot edu 29-Dec-2005 12:16
The project I'm currently working on uses XPaths to dynamically navigate through chunks of an XML file.  I couldn't find any PHP code on the net that would build the XPath to a node for me, so I wrote my own function.  Turns out it wasn't as hard as I thought it might be (yay recursion), though it does entail using some PHP shenanigans...

Hopefully it'll save someone else the trouble of reinventing this wheel.

<?php
    function getNodeXPath( $node ) {
        // REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0!!!

        // Get the index for the current node by looping through the siblings.
        $parentNode = $node->parentNode;
        if( $parentNode != null ) {
            $nodeIndex = 0;
            do {
                $testNode = $parentNode->childNodes->item( $nodeIndex );
                $nodeName = $testNode->nodeName;
                $nodeIndex++;

                // PHP trickery!  Here we create a counter based on the node
                //  name of the test node to use in the XPath.
                if( !isset( $$nodeName ) ) $$nodeName = 1;
                else $$nodeName++;

                // Failsafe return value.
                if( $nodeIndex > $parentNode->childNodes->length ) return( "/" );
            } while( !$node->isSameNode( $testNode ) );

            // Recursively get the XPath for the parent.
            return( getNodeXPath( $parentNode ) . "/{$node->nodeName}[{$$nodeName}]" );
        } else {
            // Hit the root node!  Note that the slash is added when
            //  building the XPath, so we return just an empty string.
            return( "" );
        }
    }
?>
johanwthijs-at-hotmail-dot-com 14-Dec-2005 06:25
Being an experienced ASP developer I was wondering how to replace textual content of a node (with msxml this is simply acheived by setting the 'text' property of a node). Out of frustration I started to play around with SimpleXml but I could not get it to work in combination with xPath.

I took me a lot of time to find out so I hope this helps others:

function replaceNodeText($objXml, $objNode, $strNewContent){
    /*
    This function replaces a node's string content with strNewContent
    */
    $objNodeListNested = &$objNode->childNodes;
    foreach ( $objNodeListNested as $objNodeNested ){
         if ($objNodeNested->nodeType == XML_TEXT_NODE)$objNode->removeChild ($objNodeNested);
    }

    $objNode->appendChild($objXml->createTextNode($strNewContent));
}

$objXml= new DOMDocument();
$objXml->loadXML('<root><node id="1">bla</note></root>');
$objXpath = new domxpath($objXml);

$strXpath="/root/node[@id='1']";
$objNodeList = $objXpath ->query($strXpath);
foreach ($objNodeList as $objNode){
//pass the node by reference
replaceNodeText($objXml, &$objNode, $strImportedValue);
}
mark at vectrex dot org dot uk 17-Nov-2005 02:10
Note that these DOM functions expect (and presumably return) all their data in UTF-8 character encoding, regardless of what PHP's current encoding is. This means that text nodes, attribute values etc, should be in utf8.

This applies even if you're generating an XML document which is not ultimately in utf8.

Mark
toby at tobiasly dot com 22-Oct-2005 11:08
This module is not included by default either in the CentOS 4 "centosplus" repository. For those using PHP5 on CentOS 4, a simple "yum --enablerepo=centosplus install php-xml" will do the trick (this will install both the XML and DOM modules).
pes_cz 29-Sep-2005 12:32
When I tried to parse my XHTML Strict files with DOM extension, it couldn't understand xhtml entities (like &copy;). I found post about it here (14-Jul-2005 09:05) which adviced to add resolveExternals = true, but it was very slow. There was some small note about xml catalogs but without any glue. Here it is:

XML catalogs is something like cache. Download all needed dtd's to /etc/xml, edit file /etc/xml/catalog and add this line: <public publicId="-//W3C//DTD XHTML 1.0 Strict//EN" uri="file:///etc/xml/xhtml1-strict.dtd" />

Thats all. Thanks to http://www.whump.com/moreLikeThis/link/03815
amir.laherATcomplinet.com 22-Aug-2005 05:09
This particular W3C page provides invaluable documentation for the DOM classes implemented in php5 (via libxml2). It fills in plenty of php.net's gaps:

http://www.w3.org/TR/DOM-Level-2-Core/core.html

Some key examples:
* concise summary of the class heirachy (1.1.1)
* clarification that DOM level 2 doesn't allow for population of internal DTDs
* explanation of DOMNode->normalize()
* explanation of the DOMImplementation class

The interfaces are described in OMG's Interface Definition Language
aidan at php dot net 19-Jul-2005 06:04
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
aidan at php dot net 18-Jul-2005 08:27
When dealing with validation or loading, the output errors can be quite annoying.

PHP 5.1 introduces libxml_get_errors().

http://php.net/libxml_get_errors
php at webdevelopers dot cz 14-Jul-2005 12:05
[Editor's Note: If you're using entities, then you have no choice. XML Catalogs can speed DTD resolution.]

Never use

$dom->resolveExternals=true;

when parsing XHTML document that has the DOCTYPE declaration with DTD URL specified in it.

Otherwise parsing the XHTML with DOCTYPE like this one:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

will result in PHP/DOM downloading the DTD file from W3C site when parsing your document. It will add extra delay to your script - I experienced that $dom->load()'s total time was from 1 to 16 seconds.

elixon
spammable69 at hotmail dot com 11-Apr-2005 10:18
I wrote a framework to implement the StyleSheet interfaces as specified on the W3C website.  The code is written in PHP, and is NOT a complete implementation.  Use it how ya like.  I was planning on adding the CSSStyleSheet interfaces as well.  Feel free to ask.

<?
    class StyleSheetList {
        public length;
        private self;

        function __construct ( ) {
            $this->self = array();
        }

        function __get($property, $&ret) {
            if($property == 'length')
                $ret = count($this->self);
            return true;
        }

        function __set($property, $val) {
            if($property == 'length')
                return true;
        }

        function item( $index ) {
            return $this->self[$index];
        }
    }

    class MediaList extends StyleSheetList {

        function appendMedium ( $newMedium ) {
            array_push($this->self, $newMedium);
        }

        function deleteMedium ( $oldMedium ) {
            foreach($this->self as $item) {
                if( $item == $oldMedium ) {
                    $item = $this->self[ $this->length-1 ];
                    array_pop($this->self);
                    break;
                }
            }
        }
    }

    class DocumentStyle {
        public styleSheets;

        function __construct ( ) {
            $this->styleSheets = new StyleSheetList();
        }

        function __set($property, $val) {
            if($property == 'styleSheets')
                return true;
        }
    }

    class LinkStyle {
        public sheet;

        function __construct () {
            $this->sheet = new StyleSheet();
        }

        function __set($property, $val) {
            if($property == 'sheet')
                return true;
        }
    }

    class StyleSheet {
        public type;
        public disabled;
        public ownerNode;
        public parentStyleSheet;
        public href;
        public title;
        public media;

        function __construct( $type, $disabled, $ownerNode, $parentStyleSheet, $href, $title){
            $this->type = $type;
            $this->disabled = $disabled;
            $this->media = new MediaList();
            $this->ownerNode = $ownerNode;
            $this->parentStyleSheet = $parentStyleSheet;
            $this->href = $href;
            $this->title = $title;
        }
    }
?>

Only contactable via http://murpsoft.com/contact.html
Обработка XML
Введение
Обработка XML


Введение

Расширение DOM позволяет вам работать с XML-документами через DOM API с PHP 5.

Для PHP 4 используйте DOM XML.

Замечание:

Расширение DOM использует кодировку UTF-8. Используйте функции utf8_encode ()() и utf8_decode ()() для работы с текстами в кодировке ISO-8859-1 или функцию Iconv для других кодировок.

User Contributed Notes

richso 15-May-2008 08:49
this module parse and decode XML into utf-8 characters for no matter what the encoding is in you source XML, therefore use carefully for some not-so-standard encoding like "big5-hkscs"
DOM
Установка и настройка
DOM


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

d at duane dot com 10-May-2012 05:02
On Fedora 16, you can use
yum -y install php-xml
and then be sure to add
extension=dom.so
in the php.ini file for this to work.
Anonymous 05-Oct-2011 07:40
In Redhat 5.5 using php53 you need to not only install php53-xml but php53-devel as well to install DOMDocument
eugenekay at kashpureff dot org 24-Jan-2011 10:08
Certain Linux distributions do not have this extension included in the minimum PHP package. It can usually be found in one of the "optional" php-* packages.

For CentOS, you will need to run "yum install php-xml", which provides this extension.
Sergey A. 05-Apr-2010 05:38
don't forget
extension=dom.so
in extensions.ini
on freebsd
z1mok at yahoo dot com 22-Apr-2009 05:45
You need the DOM MODULE installed if you want to use Youtube Data Api with the Zend GData Library.

Otherwise you cannot obtain a valid Upload Form Token.
Введение
Требования
DOM


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

User Contributed Notes

david at brayworth dot com dot au 12-Jun-2011 05:55
Under Fedora packaging ssystems you will need php-xml
 => yum install php-xml
James 18-Apr-2010 10:58
You also need to check libxml is installed. Check phpinfo() > Dom to see if it is. Bug report filed to get this added here.
Установка и настройка
Установка
Установка и настройка


Установка

Это расширение включено по умолчанию. Оно может быть отключено во время выполнения с помощью следующей опции: --disable-dom

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

XML констаты
Констата | Значение | Описание
XML_ELEMENT_NODE (integer) | 1 | Узел класса DOMElement
XML_ATTRIBUTE_NODE (integer) | 2 | Узел класса DOMAttr
XML_TEXT_NODE (integer) | 3 | Узел класса DOMText
XML_CDATA_SECTION_NODE (integer) | 4 | Узел класса DOMCharacterData
XML_ENTITY_REF_NODE (integer) | 5 | Узел класса DOMEntityReference
XML_ENTITY_NODE (integer) | 6 | Узел класса DOMEntity
XML_PI_NODE (integer) | 7 | Узел класса DOMProcessingInstruction
XML_COMMENT_NODE (integer) | 8 | Узел класса DOMComment
XML_DOCUMENT_NODE (integer) | 9 | Узел класса DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) | 10 | Узел класса DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) | 11 | Узел класса DOMDocumentFragment
XML_NOTATION_NODE (integer) | 12 | Узел класса DOMNotation
XML_HTML_DOCUMENT_NODE (integer) | 13 |
XML_DTD_NODE (integer) | 14 |
XML_ELEMENT_DECL_NODE (integer) | 15 |
XML_ATTRIBUTE_DECL_NODE (integer) | 16 |
XML_ENTITY_DECL_NODE (integer) | 17 |
XML_NAMESPACE_DECL_NODE (integer) | 18 |
XML_ATTRIBUTE_CDATA (integer) | 1 |
XML_ATTRIBUTE_ID (integer) | 2 |
XML_ATTRIBUTE_IDREF (integer) | 3 |
XML_ATTRIBUTE_IDREFS (integer) | 4 |
XML_ATTRIBUTE_ENTITY (integer) | 5 |
XML_ATTRIBUTE_NMTOKEN (integer) | 7 |
XML_ATTRIBUTE_NMTOKENS (integer) | 8 |
XML_ATTRIBUTE_ENUMERATION (integer) | 9 |
XML_ATTRIBUTE_NOTATION (integer) | 10 |
Константы DOMException
Констата | Значение | Описание
DOM_PHP_ERR (integer) | 0 | Эта ошибка не является частью спецификации DOM. Предназначена для обработки ошибок PHP.
DOM_INDEX_SIZE_ERR (integer) | 1 | Если индекс отрицательный или выходит за пределы возможных значений.
DOMSTRING_SIZE_ERR (integer) | 2 | Если указанный фрагмент текста не помещается в DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | Если невозможно вставить узел
DOM_WRONG_DOCUMENT_ERR (integer) | 4 | Если узел используется в другом документе в котором был создан.
DOM_INVALID_CHARACTER_ERR (integer) | 5 | Если указан недопустимый символ в названии.
DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | Если данные, указанные для узла, не поддерживаются.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | Если происходит попытка изменить объект, который не поддерживает изменения.
DOM_NOT_FOUND_ERR (integer) | 8 | Если пытаться изменить контекст узла, которого не существует
DOM_NOT_SUPPORTED_ERR (integer) | 9 | Если не поддерживается требуемый тип объекта или операции.
DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | Если пытаться добавить атрибут, который используется в другом месте.
DOM_INVALID_STATE_ERR (integer) | 11 | Если пытаться использовать объект, которого нет или не возможно использовать.
DOM_SYNTAX_ERR (integer) | 12 | Используются недопустимые символы.
DOM_INVALID_MODIFICATION_ERR (integer) | 13 | Если пытаться изменить тип базовому объекту.
DOM_NAMESPACE_ERR (integer) | 14 | Если пытаться создать или изменить объект с некорректным пространством имён.
DOM_INVALID_ACCESS_ERR (integer) | 15 | Если параметр или операция не поддерживается базовым объектом.
DOM_VALIDATION_ERR (integer) | 16 | Если при вызове методов insertBefore или removeChild узел становиться недействительным, то срабтает это исключение и операция не будет выполнена.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
DOMAttr
DOM


Класс DOMAttr

(PHP 5)

Введение

DOMAttr предоставляет работу с атрибутами в объекте DOMElement.

Обзор классов

DOMAttr extends DOMNode {
/* Свойства */
public readonly string $name ;
public readonly DOMElement $ownerElement ;
public readonly bool $schemaTypeInfo ;
public readonly bool $specified ;
public string $value ;
/* Методы */
__construct ( string $name [, string $value ] )
bool isId ( void )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

name

Имя атрибута

ownerElement

Элемент, который содержит атрибут

schemaTypeInfo

В данный момент не реализованно, возвращает NULL

specified

В данный момент не реализованно, возвращает NULL

value

Значение атрибута

Смотрите также

  • » спецификация W3C элемента Attr

Содержание

  • DOMAttr::__construct — Создает экземпляр класса DOMAttr
  • DOMAttr::isId — Проверяет, является ли атрибут описанным в DTD ID

User Contributed Notes

chregu at php dot net 23-Mar-2009 11:20
See also the properties from the inherited class DOMNode ( http://php.net/manual/en/class.domnode.php ), eg. namespaceURI, prefix, localName, etc, especially if you have to deal with namespaced attributes
Предопределенные константы
DOMAttr::__construct
DOM


Создает экземпляр класса DOMAttr

DOMAttr
DOMAttr::isId
DOMAttr
PHP Manual

DOMAttr::__construct

(PHP 5)

DOMAttr::__construct — Создает экземпляр класса DOMAttr

Описание

DOMAttr::__construct ( string $name [, string $value ] )

Создает новый объект класса DOMAttr. Объект будет доступен только для чтения. Он может быть добавлен к документу, другие узлы нельзя добавить к этому объекту, пока он присоединен к документу. Для создания узла с возможностью модификации используйте DOMDocument::createAttribute.

Список параметров

name

Имя (тэг) атрибута.

value

Значение атрибута.

Примеры

Пример #1 Создание нового объекта класса DOMAttr

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML();

?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

Смотрите также

  • DOMDocument::createAttribute() - Создает новый атрибут

User Contributed Notes

There are no user contributed notes for this page.
DOMAttr
DOMAttr::isId
DOMAttr


Проверяет, является ли атрибут описанным в DTD ID

DOMAttr::__construct
DOMCdataSection
DOMAttr
PHP Manual

DOMAttr::isId

(PHP 5)

DOMAttr::isId — Проверяет, является ли атрибут описанным в DTD ID

Описание

bool DOMAttr::isId ( void )

Эта функция проверяет, является ли атрибут ID, описанным в DTD.

В соответствии со стандартом DOM это требует наличия DTD, которая предписывает ID атрибуту иметь соответствующий ID тип. Перед применением этой функции необходимо проверять документ на действительность с помощью DOMDocument::validate или DOMDocument::validateOnParse.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DOMAttr::isId()

<?php

$doc = new DomDocument;

// Необходимо проверить документ на действительность перед тем как ссылаться на id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// Достаем атрибут с именем id из элемента chapter
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

User Contributed Notes

There are no user contributed notes for this page.
DOMAttr::__construct
DOMCdataSection
DOMAttr


Класс DOMCdataSection

(PHP 5)

Введение

Класс DOMCdataSection наследуется от DOMText текстового представления CData структур.

Обзор классов

DOMCdataSection extends DOMText {
/* Методы */
public __construct ( string $value )
/* Наследуемые методы */
public bool DOMText::isWhitespaceInElementContent ( void )
public DOMText DOMText::splitText ( int $offset )
}

Содержание

  • DOMCdataSection::__construct — Создает новый экземпляр класса DOMCdataSection

User Contributed Notes

There are no user contributed notes for this page.
DOMAttr::isId
DOMCdataSection::__construct
DOM


Создает новый экземпляр класса DOMCdataSection

DOMCdataSection
DOMCharacterData
DOMCdataSection
PHP Manual

DOMCdataSection::__construct

(PHP 5)

DOMCdataSection::__construct — Создает новый экземпляр класса DOMCdataSection

Описание

public DOMCdataSection::__construct() ( string $value )

Создает новый CDATA узел. Работает так же, как класс DOMText.

Список параметров

value

Значение CDATA узла. Если переданное значение не поддерживается, будет создан пустой CDATA узел.

Примеры

Пример #1 Создание объекта класса DOMCdataSection

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

Смотрите также

  • DOMText::__construct() - Создает объект класса DOMText
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

There are no user contributed notes for this page.
DOMCdataSection
DOMCharacterData
DOMCdataSection


Класс DOMCharacterData

(PHP 5)

Введение

Представляет узлы с символьными данными. Нельзя создать узел из этого класса напрямую, узлы создаются из наследуемых от него классов.

Обзор классов

DOMCharacterData extends DOMNode {
/* Свойства */
public string $data ;
readonly public int $length ;
/* Методы */
void appendData ( string $data )
void deleteData ( int $offset , int $count )
void insertData ( int $offset , string $data )
void replaceData ( int $offset , int $count , string $data )
string substringData ( int $offset , int $count )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

data

Содержимое узла.

length

Длина строки содержащейся в узле.

Смотрите также

  • » W3C спецификация символьных данных

Содержание

  • DOMCharacterData::appendData — Добавляет строку в конец символьных данных узла
  • DOMCharacterData::deleteData — Удаление диапазона символов из узла
  • DOMCharacterData::insertData — Вставляет строку после заданного отступа из 16-битных блоков
  • DOMCharacterData::replaceData — Заменяет подстроку в узле типа DOMCharacterData
  • DOMCharacterData::substringData — Извлекает определенный диапазон данных из узла

User Contributed Notes

jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:35
In case you're looking for the CDATA class to which nodes /do/ correspond, it's called DOMCdataSection (per my PHP installation) and isn't documented on php.net.  Presumably, it doesn't add anything to this API.

See also: http://www.php.net/manual/en/domdocument.createcdatasection.php
DOMCdataSection::__construct
DOMCharacterData::appendData
DOM


Добавляет строку в конец символьных данных узла

DOMCharacterData
DOMCharacterData::deleteData
DOMCharacterData
PHP Manual

DOMCharacterData::appendData

(PHP 5)

DOMCharacterData::appendData — Добавляет строку в конец символьных данных узла

Описание

void DOMCharacterData::appendData ( string $data )

Добавляет строку data в конец символьных данных узла.

Список параметров

data

Добавляемая строка.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • DOMCharacterData::deleteData() - Удаление диапазона символов из узла
  • DOMCharacterData::insertData() - Вставляет строку после заданного отступа из 16-битных блоков
  • DOMCharacterData::replaceData() - Заменяет подстроку в узле типа DOMCharacterData
  • DOMCharacterData::substringData() - Извлекает определенный диапазон данных из узла

User Contributed Notes

There are no user contributed notes for this page.
DOMCharacterData
DOMCharacterData::deleteData
DOMCharacterData


Удаление диапазона символов из узла

DOMCharacterData::appendData
DOMCharacterData::insertData
DOMCharacterData
PHP Manual

DOMCharacterData::deleteData

(PHP 5)

DOMCharacterData::deleteData — Удаление диапазона символов из узла

Описание

void DOMCharacterData::deleteData ( int $offset , int $count )

Удаляет count символов, начиная с позиции offset.

Список параметров

offset

Позиция, с которой будут удаляться символы.

count

Количество удаляемых символов. Если offset и count в сумме окажется больше значения длины строки данных узла, будут удалены все символы до конца данных.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

DOM_INDEX_SIZE_ERR

Возникает, если offset меньше нуля или больше количества 16-битных блоков в области данных, либо если count имеет отрицательное значение.

Смотрите также

  • DOMCharacterData::appendData() - Добавляет строку в конец символьных данных узла
  • DOMCharacterData::insertData() - Вставляет строку после заданного отступа из 16-битных блоков
  • DOMCharacterData::replaceData() - Заменяет подстроку в узле типа DOMCharacterData
  • DOMCharacterData::substringData() - Извлекает определенный диапазон данных из узла

User Contributed Notes

There are no user contributed notes for this page.
DOMCharacterData::appendData
DOMCharacterData::insertData
DOMCharacterData


Вставляет строку после заданного отступа из 16-битных блоков

DOMCharacterData::deleteData
DOMCharacterData::replaceData
DOMCharacterData
PHP Manual

DOMCharacterData::insertData

(PHP 5)

DOMCharacterData::insertData — Вставляет строку после заданного отступа из 16-битных блоков

Описание

void DOMCharacterData::insertData ( int $offset , string $data )

Вставляет строку data в позицию offset.

Список параметров

offset

Отступ в символах, начиная с которого будет вставлена строка.

data

Вставляемая строка.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

DOM_INDEX_SIZE_ERR

Возникает, если offset меньше нуля или больше количества 16-битных блоков в данных.

Смотрите также

  • DOMCharacterData::appendData() - Добавляет строку в конец символьных данных узла
  • DOMCharacterData::deleteData() - Удаление диапазона символов из узла
  • DOMCharacterData::replaceData() - Заменяет подстроку в узле типа DOMCharacterData
  • DOMCharacterData::substringData() - Извлекает определенный диапазон данных из узла

User Contributed Notes

There are no user contributed notes for this page.
DOMCharacterData::deleteData
DOMCharacterData::replaceData
DOMCharacterData


Заменяет подстроку в узле типа DOMCharacterData

DOMCharacterData::insertData
DOMCharacterData::substringData
DOMCharacterData
PHP Manual

DOMCharacterData::replaceData

(PHP 5)

DOMCharacterData::replaceData — Заменяет подстроку в узле типа DOMCharacterData

Описание

void DOMCharacterData::replaceData ( int $offset , int $count , string $data )

Заменяет count символов, начиная с позиции offset, на строку data.

Список параметров

offset

Позиция, с которой начинается замена.

count

Количество символов для замены. Если offset и count в сумме превышают длину строки данных, будут заменены все символы до конца данных.

data

Строка, на которую будет производиться замена.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

DOM_INDEX_SIZE_ERR

Возникает, если offset меньше нуля или больше количества 16-битных блоков в области данных, либо если count имеет отрицательное значение.

Смотрите также

  • DOMCharacterData::appendData() - Добавляет строку в конец символьных данных узла
  • DOMCharacterData::deleteData() - Удаление диапазона символов из узла
  • DOMCharacterData::insertData() - Вставляет строку после заданного отступа из 16-битных блоков
  • DOMCharacterData::substringData() - Извлекает определенный диапазон данных из узла

User Contributed Notes

There are no user contributed notes for this page.
DOMCharacterData::insertData
DOMCharacterData::substringData
DOMCharacterData


Извлекает определенный диапазон данных из узла

DOMCharacterData::replaceData
DOMComment
DOMCharacterData
PHP Manual

DOMCharacterData::substringData

(PHP 5)

DOMCharacterData::substringData — Извлекает определенный диапазон данных из узла

Описание

string DOMCharacterData::substringData ( int $offset , int $count )

Возвращает требуемую подстроку.

Список параметров

offset

Начало извлекаемой подстроки.

count

Количество извлекаемых символов.

Возвращаемые значения

Запрашиваемая подстрока. Если offset и count в сумме превышают длину строки данных узла, будут извлечены все символы до конца строки.

Ошибки

DOM_INDEX_SIZE_ERR

Возникает, если offset меньше нуля или больше количества 16-битных блоков в области данных, либо если count имеет отрицательное значение.

Смотрите также

  • DOMCharacterData::appendData() - Добавляет строку в конец символьных данных узла
  • DOMCharacterData::deleteData() - Удаление диапазона символов из узла
  • DOMCharacterData::insertData() - Вставляет строку после заданного отступа из 16-битных блоков
  • DOMCharacterData::replaceData() - Заменяет подстроку в узле типа DOMCharacterData

User Contributed Notes

There are no user contributed notes for this page.
DOMCharacterData::replaceData
DOMComment
DOMCharacterData


Класс DOMComment

(PHP 5)

Введение

Представляет узлы комментариев, строки отделенные символами <!-- и -->.

Обзор классов

DOMComment extends DOMCharacterData {
/* Методы */
__construct ([ string $value ] )
/* Наследуемые методы */
void DOMCharacterData::appendData ( string $data )
void DOMCharacterData::deleteData ( int $offset , int $count )
void DOMCharacterData::insertData ( int $offset , string $data )
void DOMCharacterData::replaceData ( int $offset , int $count , string $data )
string DOMCharacterData::substringData ( int $offset , int $count )
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Смотрите также

  • » W3C спецификация комментариев

Содержание

  • DOMComment::__construct — Создает новый экземпляр класса DOMComment

User Contributed Notes

There are no user contributed notes for this page.
DOMCharacterData::substringData
DOMComment::__construct
DOM


Создает новый экземпляр класса DOMComment

DOMComment
DOMDocument
DOMComment
PHP Manual

DOMComment::__construct

(PHP 5)

DOMComment::__construct — Создает новый экземпляр класса DOMComment

Описание

DOMComment::__construct ([ string $value ] )

Создает новый объект класса DOMComment. Объект будет доступен только для чтения. Его можно добавить к документу. Другие узлы нельзя добавлять к объекту, пока он присоединен к документу. Для создания модифицируемого узла используйте DOMDocument::createComment.

Список параметров

value

Значение комментария.

Примеры

Пример #1 Создание объекта DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

Смотрите также

  • DOMDocument::createComment() - Создает новый узел-комментарий

User Contributed Notes

There are no user contributed notes for this page.
DOMComment
DOMDocument
DOMComment


Класс DOMDocument

(PHP 5)

Введение

Представляет все содержимое HTML или XML документа; служит в качестве корня дерева документа.

Обзор классов

DOMDocument extends DOMNode {
/* Свойства */
readonly public string $actualEncoding ;
readonly public DOMConfiguration $config ;
readonly public DOMDocumentType $doctype ;
readonly public DOMElement $documentElement ;
public string $documentURI ;
public string $encoding ;
public bool $formatOutput ;
readonly public DOMImplementation $implementation ;
public bool $preserveWhiteSpace = true ;
public bool $recover ;
public bool $resolveExternals ;
public bool $standalone ;
public bool $strictErrorChecking = true ;
public bool $substituteEntities ;
public bool $validateOnParse = false ;
public string $version ;
readonly public string $xmlEncoding ;
public bool $xmlStandalone ;
public string $xmlVersion ;
/* Методы */
__construct ([ string $version [, string $encoding ]] )
DOMAttr createAttribute ( string $name )
DOMAttr createAttributeNS ( string $namespaceURI , string $qualifiedName )
DOMCDATASection createCDATASection ( string $data )
DOMComment createComment ( string $data )
DOMDocumentFragment createDocumentFragment ( void )
DOMElement createElement ( string $name [, string $value ] )
DOMElement createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] )
DOMEntityReference createEntityReference ( string $name )
DOMProcessingInstruction createProcessingInstruction ( string $target [, string $data ] )
DOMText createTextNode ( string $content )
DOMElement getElementById ( string $elementId )
DOMNodeList getElementsByTagName ( string $name )
DOMNodeList getElementsByTagNameNS ( string $namespaceURI , string $localName )
DOMNode importNode ( DOMNode $importedNode [, bool $deep ] )
mixed load ( string $filename [, int $options = 0 ] )
bool loadHTML ( string $source )
bool loadHTMLFile ( string $filename )
mixed loadXML ( string $source [, int $options = 0 ] )
void normalizeDocument ( void )
bool registerNodeClass ( string $baseclass , string $extendedclass )
bool relaxNGValidate ( string $filename )
bool relaxNGValidateSource ( string $source )
int save ( string $filename [, int $options ] )
string saveHTML ([ DOMNode $node = NULL ] )
int saveHTMLFile ( string $filename )
string saveXML ([ DOMNode $node [, int $options ]] )
bool schemaValidate ( string $filename )
bool schemaValidateSource ( string $source )
bool validate ( void )
int xinclude ([ int $options ] )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

actualEncoding

Устарело. Кодировка документа, доступный только для чтения аналог encoding.

config

Устарело. Конфигурация использованная при вызове DOMDocument::normalizeDocument().

doctype

Объявление типа документа, соответствующее этому документу.

documentElement

Удобный атрибут, предоставляющий прямой доступ к узлу-потомку, как к элементу документа.

documentURI

Расположение документа или NULL, если не определено.

encoding

Кодировка документа, как она задана в объявлении XML. Этот атрибут отсутствует в итоговой DOM Level 3 спецификации, но это единственный путь для управления кодировкой XML документа в данной реализации.

formatOutput

Форматирует вывод, добавляя отступы и дополнительные пробелы.

implementation

Объект класса DOMImplementation, обрабатывающий этот документ.

preserveWhiteSpace

Указание не убирать лишние пробелы и отступы. По умолчанию TRUE.

recover

Патентованное свойство. Включает режим восстановления, то есть пытается разобрать некорректно составленные документы. Этот атрибут не входит в спецификацию DOM и является особенностью libxml.

resolveExternals

Установите в TRUE для загрузки внешних элементов из объявления типа документа. Может быть полезным при включении элементов с символьными данными в XML документ.

standalone

Устарело. Указание, что документ не зависит от других XML документов. Это можно определить из XML объявления. Свойство связано с xmlStandalone.

strictErrorChecking

Выбрасывает исключение DOMException при ошибке. По умолчанию TRUE.

substituteEntities

Патентованное свойство. Указывает, заменять или нет элементы документа. Этот атрибут не входит в спецификацию DOM и является особенностью libxml.

validateOnParse

Загружает DTD и проверяет документ на соответствие. По умолчанию FALSE.

version

Устарело. Версия XML, связанная с xmlVersion.

xmlEncoding

Атрибут задает, равно как и XML объявление, кодировку документа. Имеет значение NULL в случаях, когда атрибут не задан, либо значение неизвестно, если, например, документ создан в памяти.

xmlStandalone

Атрибут указывает, равно как и XML объявление, на то, что документ не зависит от других документов. Принимает значение FALSE, если не задан.

xmlVersion

Атрибут задает, равно как и XML объявление, версию документа. Если XML объявления в документе нет, но есть поддержка всех особенностей "XML", значение атрибута принимается равным "1.0".

Примечания

Замечание:

Расширение DOM использует кодировку UTF-8. Используйте функции utf8_encode() и utf8_decode() для работы с текстами в кодировке ISO-8859-1, либо Iconv в других кодировках.

Смотрите также

  • » W3C спецификация для Document

Содержание

  • DOMDocument::__construct — Создание нового DOMDocument объекта
  • DOMDocument::createAttribute — Создает новый атрибут
  • DOMDocument::createAttributeNS — Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection — Создает новый cdata узел
  • DOMDocument::createComment — Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment — Создание фрагмента докуента
  • DOMDocument::createElement — Создает новый узел-элемент
  • DOMDocument::createElementNS — Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference — Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction — Создает новый PI-узел
  • DOMDocument::createTextNode — Создает новый текстовый узел
  • DOMDocument::getElementById — Ищет элемент с заданным id
  • DOMDocument::getElementsByTagName — Ищет все элементы с заданным локальным именем
  • DOMDocument::getElementsByTagNameNS — Ищет элементы с заданным именем в определенном пространстве имен
  • DOMDocument::importNode — Импорт узла в текущий документ
  • DOMDocument::load — Загрузка XML из файла
  • DOMDocument::loadHTML — Загрузка HTML из строки
  • DOMDocument::loadHTMLFile — Загрузка HTML из файла
  • DOMDocument::loadXML — Загрузка XML из строки
  • DOMDocument::normalizeDocument — Нормализует документ
  • DOMDocument::registerNodeClass — Регистрация расширенного класса, используемого для создания базового типа узлов
  • DOMDocument::relaxNGValidate — Производит проверку документа на правильность построения посредством relaxNG
  • DOMDocument::relaxNGValidateSource — Проверяет документ посредством relaxNG
  • DOMDocument::save — Сохраняет XML дерево из внутреннего представления в файл
  • DOMDocument::saveHTML — Сохраняет документ из внутреннего представления в строку, используя HTML форматирование
  • DOMDocument::saveHTMLFile — Сохраняет документ из внутреннего представления в файл, используя HTML форматирование
  • DOMDocument::saveXML — Сохраняет XML дерево из внутреннего представления в виде строки
  • DOMDocument::schemaValidate — Проверяет действительности документа, основываясь на заданной схеме
  • DOMDocument::schemaValidateSource — Проверяет действительность документа, основываясь на схеме
  • DOMDocument::validate — Проверяет документ на соответствие его DTD
  • DOMDocument::xinclude — Проводит вставку XInclude разделов в объектах DOMDocument

User Contributed Notes

Nick M 01-Jun-2011 10:16
You may need to save all or part of a DOMDocument as an XHTML-friendly string, something compliant with both XML and HTML 4. Here's the DOMDocument class extended with a saveXHTML method:

<?php

/**
 * XHTML Document
 *
 * Represents an entire XHTML DOM document; serves as the root of the document tree.
 */
class XHTMLDocument extends DOMDocument {

  /**
   * These tags must always self-terminate. Anything else must never self-terminate.
   *
   * @var array
   */
  public $selfTerminate = array(
      'area','base','basefont','br','col','frame','hr','img','input','link','meta','param'
  );

  /**
   * saveXHTML
   *
   * Dumps the internal XML tree back into an XHTML-friendly string.
   *
   * @param DOMNode $node
   *         Use this parameter to output only a specific node rather than the entire document.
   */
  public function saveXHTML(DOMNode $node=null) {

    if (!$node) $node = $this->firstChild;

    $doc = new DOMDocument('1.0');
    $clone = $doc->importNode($node->cloneNode(false), true);
    $term = in_array(strtolower($clone->nodeName), $this->selfTerminate);
    $inner='';

    if (!$term) {
      $clone->appendChild(new DOMText(''));
      if ($node->childNodes) foreach ($node->childNodes as $child) {
        $inner .= $this->saveXHTML($child);
      }
    }

    $doc->appendChild($clone);
    $out = $doc->saveXML($clone);

    return $term ? substr($out, 0, -2) . ' />' : str_replace('><', ">$inner<", $out);

  }

}

?>

This hasn't been benchmarked, but is probably significantly slower than saveXML or saveHTML and should be used sparingly.
evert at er dot nl 20-Nov-2010 02:17
A nice and simple node 2 array I wrote, worth a try ;)

<?php
function getArray($node)
{
    $array = false;

    if ($node->hasAttributes())
    {
        foreach ($node->attributes as $attr)
        {
            $array[$attr->nodeName] = $attr->nodeValue;
        }
    }

    if ($node->hasChildNodes())
    {
        if ($node->childNodes->length == 1)
        {
            $array[$node->firstChild->nodeName] = $node->firstChild->nodeValue;
        }
        else
        {
            foreach ($node->childNodes as $childNode)
            {
                if ($childNode->nodeType != XML_TEXT_NODE)
                {
                    $array[$childNode->nodeName][] = $this->getArray($childNode);
                }
            }
        }
    }

    return $array;
}
?>
nathan at crause dot name 30-Jul-2010 09:35
Be careful with any assumptions you may have about this library. Unlike XML parsers in other languages (such as Java), when parsing an XML Schema constrained XML document, defaults you may define (such as for attributes) will NOT be correctly represented in the DOMDocument.
hutch one two zero at gmail dot com 25-Apr-2010 10:47
If you're using AJAX, make sure you put a header directive like the following at the top of your php file.

<?php header( "content-type: application/xml; charset=ISO-8859-15" ); ?>

If you don't add this header then your javascript downloadURL function will not work because the content type will not be recognised to be XML.
me at richardsnazell dot com 29-Mar-2010 06:34
After running into a problem with DomDocument and a UTF-8 encoded input string, a simple work-around was to convert the input string to ISO-8859-1, run my DOM queries, then convert back to UTF-8:

<?php
$xhtml = 'a UTF-8 encoded string';
$xhtml = utf8_decode($xhtml); // convert UTF-8 string to ISO-8859-1

// doing some DOM manipulation here on $xhtml

$xhtml = utf8_encode($xhtml); // convert ISO-8859-1 string back to UTF-8
?>

Not ideal - but it worked for me.
admin at beerpla dot net 12-Mar-2010 02:12
After seeing many complaints about certain DOMDocument shortcomings, such as bad handling of encodings and always saving HTML fragments with <html>, <head>, and DOCTYPE, I decided that a better solution is needed.

So here it is: SmartDOMDocument. You can find it at http://beerpla.net/projects/smartdomdocument/

Currently, the main highlights are:

- SmartDOMDocument inherits from DOMDocument, so it's very easy to use - just declare an object of type SmartDOMDocument instead of DOMDocument and enjoy the new behavior on top of all existing functionality (see example below).

- saveHTMLExact() - DOMDocument has an extremely badly designed "feature" where if the HTML code you are loading does not contain <html> and <body> tags, it adds them automatically (yup, there are no flags to turn this behavior off).
Thus, when you call $doc->saveHTML(), your newly saved content now has <html><body> and DOCTYPE in it. Not very handy when trying to work with code fragments (XML has a similar problem).
SmartDOMDocument contains a new function called saveHTMLExact() which does exactly what you would want - it saves HTML without adding that extra garbage that DOMDocument does.

- encoding fix - DOMDocument notoriously doesn't handle encoding (at least UTF-8) correctly and garbles the output.
SmartDOMDocument tries to work around this problem by enhancing loadHTML() to deal with encoding correctly. This behavior is transparent to you - just use loadHTML() as you would normally.

- SmartDOMDocument Object As String - you can use a SmartDOMDocument object as a string which will print out its contents.
For example:
<?php
echo "Here is the HTML: $smart_dom_doc";
?>

I'm going to maintain this code and try to fix bugs as they come in.

Enjoy.
tloach at gmail dot com 05-Feb-2010 10:01
For anyone else who has been having issues with formatOuput not working, here is a work-around:

rather than just doing something like:

<?php
$outXML = $xml->saveXML();
?>

force it to reload the XML from scratch, then it will format correctly:

<?php
$outXML = $xml->saveXML();
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML($outXML);
$outXML = $xml->saveXML();
?>
jay at jaygilford dot com 27-Jan-2010 08:46
Here's a small function I wrote to get all page links using the DOMDocument which will hopefully be of use to others

<?php
/**
 * @author Jay Gilford
 */

/**
 * get_links()
 *
 * @param string $url
 * @return array
 */
function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <a> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) {
        $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
    }

    //Return the links
    return $links;
}
?>
fcartegnie 31-Oct-2009 01:30
Be careful with formatOutput().

Creating an empty node like this:
createElement('foo','')
instead of
createElement('foo')
will break formatOutput.
Yarg Dahc 05-Oct-2009 05:08
Child class of DOMDocument which has a toArray() method. Enjoy and/or improve
<?php
class MyDOMDocument extends DOMDocument
{
    public function toArray(DOMNode $oDomNode = null)
    {
        // return empty array if dom is blank
        if (is_null($oDomNode) && !$this->hasChildNodes()) {
            return array();
        }
        $oDomNode = (is_null($oDomNode)) ? $this->documentElement : $oDomNode;
        if (!$oDomNode->hasChildNodes()) {
            $mResult = $oDomNode->nodeValue;
        } else {
            $mResult = array();
            foreach ($oDomNode->childNodes as $oChildNode) {
                // how many of these child nodes do we have?
                // this will give us a clue as to what the result structure should be
                $oChildNodeList = $oDomNode->getElementsByTagName($oChildNode->nodeName);
                $iChildCount = 0;
                // there are x number of childs in this node that have the same tag name
                // however, we are only interested in the # of siblings with the same tag name
                foreach ($oChildNodeList as $oNode) {
                    if ($oNode->parentNode->isSameNode($oChildNode->parentNode)) {
                        $iChildCount++;
                    }
                }
                $mValue = $this->toArray($oChildNode);
                $sKey   = ($oChildNode->nodeName{0} == '#') ? 0 : $oChildNode->nodeName;
                $mValue = is_array($mValue) ? $mValue[$oChildNode->nodeName] : $mValue;
                // how many of thse child nodes do we have?
                if ($iChildCount > 1) {  // more than 1 child - make numeric array
                    $mResult[$sKey][] = $mValue;
                } else {
                    $mResult[$sKey] = $mValue;
                }
            }
            // if the child is <foo>bar</foo>, the result will be array(bar)
            // make the result just 'bar'
            if (count($mResult) == 1 && isset($mResult[0]) && !is_array($mResult[0])) {
                $mResult = $mResult[0];
            }
        }
        // get our attributes if we have any
        $arAttributes = array();
        if ($oDomNode->hasAttributes()) {
            foreach ($oDomNode->attributes as $sAttrName=>$oAttrNode) {
                // retain namespace prefixes
                $arAttributes["@{$oAttrNode->nodeName}"] = $oAttrNode->nodeValue;
            }
        }
        // check for namespace attribute - Namespaces will not show up in the attributes list
        if ($oDomNode instanceof DOMElement && $oDomNode->getAttribute('xmlns')) {
            $arAttributes["@xmlns"] = $oDomNode->getAttribute('xmlns');
        }
        if (count($arAttributes)) {
            if (!is_array($mResult)) {
                $mResult = (trim($mResult)) ? array($mResult) : array();
            }
            $mResult = array_merge($mResult, $arAttributes);
        }
        $arResult = array($oDomNode->nodeName=>$mResult);
        return $arResult;
    }
}

$sXml = <<<XML
<nodes>
    <node>text<node>
    <node>
        <field>hello<field>
        <field>world<field>
    <node>
<nodes>
XML;
$dom = new MyDOMDocument;
$dom->loadXml($sXml);
var_dump($dom->toArray());
?>
Output:

array (
    "nodes" => array (
        "node" => array (
            0 => "text",
            1 => array (
            "field" => array (
                0 => "hello",
                1 => "world"
            )
        )
    )
 )
PhilipWayneRollins at gmail dot com 15-Aug-2009 01:32
If you want to use the DOMDocument to create xHTML documents here is a simple class

Note this is designed for creating xHTML documents from scratch but could be easily extended to work with xHTML documents. Also this is for xHTML not XML.

<?php
    class Document
    {
        public $doctype;
        public $head;
        public $title = 'Sensei Ninja';
        public $body;
        private $styles;
        private $metas;
        private $scripts;
        private $document;

        function __construct (  )
        {
            $this->document = new DOMDocument( );
            $this->head = $this->document->createElement( 'head', ' ' );
            $this->body = $this->document->createElement( 'body', ' ' );
        }

        public function addStyleSheet ( $url, $media='all' )
        {
            $element = $this->document->createElement( 'link' );
            $element->setAttribute( 'type', 'text/css' );
            $element->setAttribute( 'href', $url );
            $element->setAttribute( 'media', $media );
            $this->styles[] = $element;
        }

        public function addScript ( $url )
        {
            $element = $this->document->createElement( 'script', ' ' );
            $element->setAttribute( 'type', 'text/javascript' );
            $element->setAttribute( 'src', $url );
            $this->scripts[] = $element;
        }

        public function addMetaTag ( $name, $content )
        {
            $element = $this->document->createElement( 'meta' );
            $element->setAttribute( 'name', $name );
            $element->setAttribute( 'content', $content );
            $this->metas[] = $element;
        }

        public function setDescription ( $dec )
        {
            $this->addMetaTag( 'description', $dec );
        }

        public function setKeywords ( $keywords )
        {
            $this->addMetaTag( 'keywords', $keywords );
        }

        public function createElement ( $nodeName, $nodeValue=null )
        {
          return $this->document->createElement( $nodeName, $nodeValue );
        }

        public function assemble ( )
        {
            // Doctype creation
            $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML TRANSITIONAL 1.0//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

            // Create the head element
            $title = $this->document->createElement( 'title', $this->title );
            // Add stylesheets if needed
            if ( is_array( $this->styles ))
                foreach ( $this->styles as $element )
                    $this->head->appendChild( $element );
            // Add scripts if needed
            if(  is_array( $this->scripts ))
                foreach ( $this->scripts as $element )
                    $this->head->appendChild( $element );
            // Add meta tags if needed
            if ( is_array( $this->metas ))
                foreach ( $this->metas as $element )
                    $this->head->appendChild( $element );
            $this->head->appendChild( $title );

            // Create the document
            $html = $this->document->createElement( 'html' );
            $html->setAttribute( 'xmlns', 'http://www.w3.org/1999/xhtml' );
            $html->setAttribute( 'xml:lang', 'en' );
            $html->setAttribute( 'lang', 'en' );
            $html->appendChild( $this->head );
            $html->appendChild( $this->body );

            $this->document->appendChild( $html );
            return $doctype . $this->document->saveXML( );
        }

    }

?>

Small example

<?php
        $document = new Document( );
    $document->title = 'Hello';
    $document->addStyleSheet( 'StyleSheets/main.css' );
    $div = $document->createElement( 'div' );
    $div->nodeValue = 'Hello, world!';
    $div->setAttribute( 'style', 'color: red;' );
    $document->body->appendChild( $div );
    printf( '%s', $document->assemble( ) );
?>
e dot sand at elisand dot com 19-Jun-2009 09:19
It should be pointed out that DOMDocument extends DOMNode in every way... that means that you even have access to the DOMNode properties (even though the documentation here does not mention them as being inherited).

I used to use an XPath query to access nodes from a DOMDocument (when getElementById or getElementsByTagName weren't usable), as I believed this to be the only way.  However, since DOMDocument fully extends DOMNode, you can use DOMDocument->firstChild for example to get the first child node.

This simplifies things quite a bit when using an XPath query may seem a bit excessive to get access to something as simple as the child nodes.
cmyk777 at gmail dot com 23-May-2009 12:31
This function may help to debug current dom element:

<?php
function dom_dump($obj) {
    if ($classname = get_class($obj)) {
        $retval = "Instance of $classname, node list: \n";
        switch (true) {
            case ($obj instanceof DOMDocument):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->saveXML($obj);
                break;
            case ($obj instanceof DOMElement):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMAttr):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                //$retval .= $obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMNodeList):
                for ($i = 0; $i < $obj->length; $i++) {
                    $retval .= "Item #$i, XPath: {$obj->item($i)->getNodePath()}\n".
"{$obj->item($i)->ownerDocument->saveXML($obj->item($i))}\n";
                }
                break;
            default:
                return "Instance of unknown class";
        }
    } else {
        return 'no elements...';
    }
    return htmlspecialchars($retval);
}
?>

Example usage:

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$body = $dom->documentElement->getElementsByTagName('book');
echo '<pre>'.dom_dump($body).'<pre>';
?>

Output:

Instance of DOMNodeList, node list:
Item #0, XPath: /library/book[1]
<book isbn="0345342968">
<title>Fahrenheit 451</title>
<author>R. Bradbury</author>
<publisher>Del Rey</publisher>
</book>
Item #1, XPath: /library/book[2]
<book isbn="0048231398">
<title>The Silmarillion</title>
<author>J.R.R. Tolkien</author>
<publisher>G. Allen &amp; Unwin</publisher>
</book>
Item #2, XPath: /library/book[3]
<book isbn="0451524934">
<title>1984</title>
<author>G. Orwell</author>
<publisher>Signet</publisher>
</book>
Item #3, XPath: /library/book[4]
<book isbn="031219126X">
<title>Frankenstein</title>
<author>M. Shelley</author>
<publisher>Bedford</publisher>
</book>
Item #4, XPath: /library/book[5]
<book isbn="0312863551">
<title>The Moon Is a Harsh Mistress</title>
<author>R. A. Heinlein</author>
<publisher>Orb</publisher>
</book>
Atanas Markov (dreamer79bg at gmail dot com) 29-Nov-2008 11:59
Here is a simple web scraping example using the PHP DOM that tries to get the largest text body of a HTML document. I needed it for a spider that had to show a short description for a page. It assumes that document annotation can be the largest <div>, <td> or <p> element in the page.
In the example I show a way to prevent a bug in the DOM as it sometimes just doesn't recognize html encoding. It seems to work if you put charset meta tag right after the head tag of the document.

<?php
$ch= curl_init();
curl_setopt ($ch, CURLOPT_URL, '...put url here...' );
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_VERBOSE,1);
curl_setopt($ch, CURLOPT_USERAGENT, 'set sth...');
curl_setopt ($ch, CURLOPT_REFERER, '...set sth...'); //just a fake referer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POST,0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 20);

$html= curl_exec($ch);
$html1= curl_getinfo($ch);

//try to get page encoding as it was sent from server
if ($html1['content_type']){
    $arr= explode('charset=',$html1['content_type']);
    $csethdr= strtolower(trim($arr[1]));
} else {
    $csethdr= false;
}

$cset= false;
$arr= array();

//This has to replace page meta tags for charset with utf-8, but it doesn't actually help(see the bug info).
if (preg_match_all(
'/(<meta\s*http-equiv="Content-Type"\s*content="[^;]*;
\s*charset=([^"]*?)(?:"|\;)[^>]*>)/' //merge this line
,$html,$arr,PREG_PATTERN_ORDER)){
    $cset= strtolower(trim($arr[2][0]));
    if ($cset!='utf-8'||$cset!=$csethdr){
        $new= str_replace($arr[2][0],'utf-8',$arr[1][0]);
        $html= str_replace($arr[1][0],$new,$html);
        $cset= $csethdr;
    } else {
        $cset= false;
    }

    if ($cset=='utf-8'){
        $cset= false;
    }
}
unset($arr);
if ($cset){
    $html= iconv($cset,'utf-8',$html);
}
unset($cset);

//solve dom bug
$html=preg_replace('/<head[^>]*>/','<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
',$html);

$dom= new DOMDocument();
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;

function getMaxTextBody($dom){
    $content = $dom->getElementsByTagname('div');
    $content2= $dom->getElementsByTagname('td');
    $content3= $dom->getElementsByTagname('p');

    $new= array();
    foreach ($content as $value) {
        $new[]= $value;
        unset($value);
    }
    unset($content);

    foreach ($content2 as $value) {
        $new[]= $value;
        unset($value);
    }
    unset($content2);

    foreach ($content3 as $value) {
        $new[]= $value;
        unset($value);
    }
    unset($content3);

    $maxlen= 0;
    $result= '';
    foreach ($new as $item)
    {
        $str= $item->nodeValue;
        if (strlen($str)>$maxlen){
            $content1= $item->getElementsByTagName('div');
            $content2= $item->getElementsByTagname('td');
                        $content3= $item->getElementsByTagname('p');
            $contentnew= array();
            foreach ($content1 as $value) {
                $contentnew[]= $value;
                unset($value);
            }
            unset($content1);
            foreach ($content2 as $value) {
                $contentnew[]= $value;
                unset($value);
            }
            unset($content2);
            foreach ($content3 as $value) {
                $contentnew[]= $value;
                unset($value);
            }
            unset($content3);

            if (count($contentnew)==0){
                $result= $str;
            } else {
                foreach ($contentnew as $value) {
                    $str1= getMaxTextBody($value);
                    $str2= $value->nodeValue;
                        //let's say largest body has more than 50% of the text in its parent
                                    if (strlen($str1)*2<strlen($str2)){
                        $str1= $str2;
                    }
                    if (strlen($str1)*2>strlen($str)&&strlen($str1)>$maxlen){
                        $result= $str1;
                    } elseif (strlen($str1)>$maxlen){
                        $result= $str1;
                    }
                    $maxlen= strlen($result);
                }
            }
            $maxlen= strlen($result);
            unset($contnentnew);
        }
    }

    unset($new);
    return $result;
}
print getMaxTextBody($dom);

?>
Jochem Blok 15-May-2008 06:58
To indent a XML in a pretty way I use:

<?
$sXML = '<root><element><key>a</key><value>b</value></element></root>';
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput   = true;
$doc->loadXML($sXML);
echo $doc->saveXML();
?>
Fernando H 11-Apr-2008 12:48
Showing a quick example of how to use this class, just so that new users can get a quick start without having to figure it all out by themself. ( At the day of posting, this documentation just got added and is lacking examples. )

<?php

// Set the content type to be XML, so that the browser will   recognise it as XML.
header( "content-type: application/xml; charset=ISO-8859-15" );

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

// Create some elements.
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track", "The ninth symphony" );

// Set the attributes.
$xml_track->setAttribute( "length", "0:01:15" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );

// Create another element, just to show you can add any (realistic to computer) number of sublevels.
$xml_note = $xml->createElement( "Note", "The last symphony composed by Ludwig van Beethoven." );

// Append the whole bunch.
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );

// Repeat the above with some different values..
$xml_track = $xml->createElement( "Track", "Highway Blues" );

$xml_track->setAttribute( "length", "0:01:33" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
$xml_album->appendChild( $xml_track );

$xml->appendChild( $xml_album );

// Parse the XML.
print $xml->saveXML();

?>

Output:
<Album>
  <Track length="0:01:15" bitrate="64kb/s" channels="2">
    The ninth symphony
    <Note>
      The last symphony composed by Ludwig van Beethoven.
    </Note>
  </Track>
  <Track length="0:01:33" bitrate="64kb/s" channels="2">Highway Blues</Track>
</Album>

If you want your PHP->DOM code to run under the .xml extension, you should set your webserver up to run the .xml extension with PHP ( Refer to the installation/configuration configuration for PHP on how to do this ).

Note that this:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

is NOT the same as this:
<?php
// Will NOT work.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml_track = new DOMElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

although this will work:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml->appendChild( $xml_album );
?>
DOMComment::__construct
DOMDocument::__construct
DOM


Создание нового DOMDocument объекта

DOMDocument
DOMDocument::createAttribute
DOMDocument
PHP Manual

DOMDocument::__construct

(PHP 5)

DOMDocument::__construct — Создание нового DOMDocument объекта

Описание

DOMDocument::__construct ([ string $version [, string $encoding ]] )

Создание нового DOMDocument объекта.

Список параметров

version

Номер версии документа как часть XML объявления.

encoding

Кодировка документа как часть XML объявления.

Примеры

Пример #1 Создание объекта DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

Смотрите также

  • DOMImplementation::createDocument() - Создает объект класса DOMDocument заданного типа с элементом document

User Contributed Notes

_ michael 01-Jun-2010 07:23
The constuctor arguments are useful if you want to build a new document using createElement, appendChild etc.

By contrast, these arguments are overriden as soon as you load a document from source by calling load() or loadXML().

* If the source contains an XML declaration specifying an encoding, that encoding is used.
* If the XML declaration does not specify an encoding, or if the source does not contain a declaration at all, UTF-8 is assumed.

This behaviour applies no matter what you declared when you called new DOMDocument().
blackhailang at gmail dot com 09-Oct-2008 07:54
domdocument::domdocument() expects at least
At the least, I found that It due to ZEND optimizer, uninstall it,working well, but the speeds will be slowlly :-(.

Comment :
item 1 : 2008-10-03 17:10:58, gkrong said:
"Warning: domdocument::domdocument() expects at least 1
 parameter"
If you use PHP 5 in windows, you don't need to declare
php_domxml.dll in your php.ini file.
so u can give comment in the line php_domxml.dll in your
php.ini file.
you only need to comment it out, but do not delete the
php_domxml.dll file in the ext directory.
steve at mrclay dot org 08-Oct-2008 09:45
To expand on bholbrook's comment, if you receive this: "Warning: domdocument::domdocument() expects at least 1 parameter", it is due to the old domxml extension, which you need to disable.

domxml overwrites DOMDocument::_construct with an alias to domxml_open_mem, so this code:
<?php
$doc = new DOMDocument();
?>
...essentially does this:
<?php
$dom = domxml_open_mem();
?>
...which is why PHP complains about expecting at least 1 parameter (it expects a string of XML).
christian dot reinecke at web dot de 15-Jul-2008 07:09
If you get the error message "domdocument::domdocument() expects parameter 2 to be long, string given"  for a code sample like this:

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

which is obviously correct if you compare the constructor signature:

__construct  ([ string $version  [, string $encoding  ]] )

make sure you're not overwritting this dom library by another (f.e. extension=php_domxml.dll in php.ini). XAMPP f.e. delivers its standard version with php_domxml.dll which ends up in this error message
dave at revlob dot com 14-Feb-2008 02:07
@Jarl

Not sure if this is what you meant when you said "The constructor example clearly shows that version and encoding only end up in the XML header", but you can also affect other parameters in the generated XML header, by accessing the DOMDocument's properties, for example:

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
bholbrook at servillian dot com 05-Dec-2007 02:25
Make sure that php_domxml.dll on windows is removed before using the domdocument class as they cannot coexist.
jarl kringelding skim punt com 24-Sep-2007 02:22
Be aware using the encoding parameter in the constructor.
It does not mean that all data is automatically encoded for you in the supplied encoding. You need to do that yourself once you choose an encoding other than the default UTF-8. See the note on DOM Functions on how to properly work with other encodings...

The constructor example clearly shows that version and encoding only end up in the XML header.
DOMDocument
DOMDocument::createAttribute
DOMDocument


Создает новый атрибут

DOMDocument::__construct
DOMDocument::createAttributeNS
DOMDocument
PHP Manual

DOMDocument::createAttribute

(PHP 5)

DOMDocument::createAttribute — Создает новый атрибут

Описание

DOMAttr DOMDocument::createAttribute ( string $name )

Эта функция создает новый объект класса DOMAttr. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

name

Имя атрибута.

Возвращаемые значения

Новый объект DOMAttr либо FALSE в случае возникновения ошибки.

Ошибки

DOM_INVALID_CHARACTER_ERR

Возникает, если name содержит недопустимые символы.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

Beerkeeper 09-Nov-2011 07:19
Just in case it isn't clear (like I had), an example:

<?php

$domDocument = new DOMDocument('1.0', "UTF-8");
$domElement = $domDocument->createElement('field','some random data');
$domAttribute = $domDocument->createAttribute('name');

// Value for the created attribute
$domAttribute->value = 'attributevalue';

// Don't forget to append it to the element
$domElement->appendChild($domAttribute);

// Append it to the document itself
$domDocument->appendChild($domElement);

?>

Will output:
<?xml version="1.0" encoding="UTF-8"?>
<field name="attributevalue">some random data</field>
DOMDocument::__construct
DOMDocument::createAttributeNS
DOMDocument


Создает новый узел-атрибут с соответствующим ему пространством имен

DOMDocument::createAttribute
DOMDocument::createCDATASection
DOMDocument
PHP Manual

DOMDocument::createAttributeNS

(PHP 5)

DOMDocument::createAttributeNS — Создает новый узел-атрибут с соответствующим ему пространством имен

Описание

DOMAttr DOMDocument::createAttributeNS ( string $namespaceURI , string $qualifiedName )

Эта функция создает новый объект класса DOMAttr. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

namespaceURI

URI пространства имен.

qualifiedName

Имя и префикс атрибута в виде prefix:tagname.

Возвращаемые значения

Новый экземпляр класса DOMAttr либо FALSE в случае ошибки.

Ошибки

DOM_INVALID_CHARACTER_ERR

Возникает, если qualifiedName содержит недопустимые символы.

DOM_NAMESPACE_ERR

Возникает, если qualifiedName неправильно сформировано, либо если qualifiedName имеет префикс, а namespaceURI имеет значение NULL.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

_ michael 01-Jun-2010 07:35
If a new namespace is introduced while creating and inserting an attribute, createAttributeNS() does not behave in the same way as createElementNS().

(1) Location: With createAttributeNS(), the new namespace is declared at the level of the document element. By contrast, createElementNS() declares the new namespace at the level of the affected element itself.

(2) Timing: With createAttributeNS(), the new namespace is declared in the document as soon as the attribute is created - the attribute does not actually have to be inserted. createElementNS() doesn't affect the document as long as the element is not inserted.

An example:

<?php

    $source = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root><tag></tag></root>
XML;

    /*

     I. createAttributeNS:
     * a new namespace shows up immediately, even without insertion of the attribute
     * the new namespace is declared at the level of the document element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We just create a "namespace'd" attribute without appending it to any element.
    $attr_ns = $doc->createAttributeNS( '{namespace_uri_here}', 'example:attr' );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, having been added to the document element. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag/></root>

    */

    // (2) Next, we give the attribute a value and insert it.
    $attr_ns->value = 'value';
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $attr_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The "namespace'd" attribute shows up as well. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag example:attr="value"/></root>

    */

    /*

     II. createElementNS:
     * a new namespace shows up only when the element is inserted
     * the new namespace is declared at the level of the inserted element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We create a "namespace'd" element without inserting it into the document.
    $elem_ns = $doc->createElementNS( '{namespace_uri_here}', 'example:newtag' );

    print $doc->saveXML() . "\n";

    /*
      Result: The document remains unchanged. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root><tag/></root>

    */

    // (2) Next, we insert the new element.
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $elem_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, and it is embedded in the element using it. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root><tag><example:newtag xmlns:example="{namespace_uri_here}"/></tag></root>

    */

?>
DOMDocument::createAttribute
DOMDocument::createCDATASection
DOMDocument


Создает новый cdata узел

DOMDocument::createAttributeNS
DOMDocument::createComment
DOMDocument
PHP Manual

DOMDocument::createCDATASection

(PHP 5)

DOMDocument::createCDATASection — Создает новый cdata узел

Описание

DOMCDATASection DOMDocument::createCDATASection ( string $data )

Эта функция создает новый объект класса DOMCDATASection. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

data

Содержимое cdata.

Возвращаемые значения

Новый объект класса DOMCDATASection либо FALSE в случае ошибки.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

Marc info[at]braincast.nl 08-Mar-2011 01:55
Here's some code that takes an associative array and prints it asXML() but creates CDATA sections for each string

<?php
class SimpleXMLExtended extends SimpleXMLElement{
    public function addCData($string){
        $dom = dom_import_simplexml($this);
        $cdata = $dom->ownerDocument->createCDATASection($string);
        $dom->appendChild($cdata);
    }
}
function assocArrayToXML($root_element_name,$ar){
    $xml = new SimpleXMLExtended("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    if (!is_numeric($k))$ch=$c->addChild($k);
                    else $ch = $c->addChild(substr($c->getName(),0,-1));
                    $f($f,$ch,$v);
                } else {
                    if (is_numeric($v)){ $c->addChild($k, $v);
                    }else{$n = $c->addChild($k); $n->addCData($v);}
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}

/* sample */
$result = array("title"=>"CDATA Sample");
$result['items'] = array();
$result['items'][] = array('title'=>'Some string', 'number' => 1);
$result['items'][] = array('title'=>'Some string', 'number' => 2);
$result['items'][] = array('title'=>'Some string', 'number' => 3);

echo assocArrayToXML('result',$result);
?>

The is_numeric check could be changed by a more elaborate regular expression to check if the string is actually xml unsafe but this worked for me.
jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:44
If you would like to refer to the documentation for the class of the returned object, see http://www.php.net/manual/en/class.domcharacterdata.php
info at troptoek dot com 24-Mar-2008 09:40
A common issue seems to be adding javascript to CDATA and the browser throwing a javascript error. To ensure the javascript works use the following code when adding CDATA:

<?php
/**
 * Append Caracter Data to a node and check for a javascript node
 *
 * @param DOMElement $appendToNode
 * @param string $text
 */
function appendCdata($appendToNode, $text)
{
    if (strtolower($appendToNode->nodeName) == 'script') {  // Javascript hack
        $cm = $appendToNode->ownerDocument->createTextNode("\n//");
        $ct = $appendToNode->ownerDocument->createCDATASection("\n" . $text . "\n//");
        $appendToNode->appendChild($cm);
        $appendToNode->appendChild($ct);
    } else {  // Normal CDATA node
        $ct = $appendToNode->ownerDocument->createCDATASection($text);
        $appendToNode->appendChild($ct);
    }
}
?>
The result should be:

<script type="text/javascript">
//<![CDATA[
function someJsText() {
   document.write('Some js with <a href="#">HTML</a> content');
}
//]]></script>
loathsome 04-Aug-2007 02:28
Here's a function that will create a CDATA-section around a string coming from SimpleXML.

<?php
function sxml_cdata($path, $string){
  $dom = dom_import_simplexml($path);
  $cdata = $dom->ownerDocument->createCDATASection($string);
  $dom->appendChild($cdata);
}
?>
DOMDocument::createAttributeNS
DOMDocument::createComment
DOMDocument


Создает новый узел-комментарий

DOMDocument::createCDATASection
DOMDocument::createDocumentFragment
DOMDocument
PHP Manual

DOMDocument::createComment

(PHP 5)

DOMDocument::createComment — Создает новый узел-комментарий

Описание

DOMComment DOMDocument::createComment ( string $data )

Эта функция создает новый экземпляр класса DOMComment. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

data

Содержимое комментария.

Возвращаемые значения

Новый объект класса DOMComment лиюо FALSE в случае ошибки.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

php dot sirlancelot at spamgourmet dot com 25-Nov-2009 12:10
To prevent a parser error when the comment string would contain the character sequence "--", do this:

<?php

$CommentString = 'This contains -- some weird -- characters.';

$CommentNode = $DomDocument->createComment(
        str_replace('--', '-'.chr(194).chr(173).'-', $CommentString)
);
?>

This will insert a Soft Hyphen in between the two hyphens which will not cause the parser to error out.
capps at solareclipse dot net 29-Mar-2007 03:55
Use caution: this function does NOT escape, encode, or otherwise change the contents of the string.

This means that if your string contains two hyphens in a row (--), that will *end* the comment, which can easily create invalid XML when the document is serialized.
DOMDocument::createCDATASection
DOMDocument::createDocumentFragment
DOMDocument


Создание фрагмента докуента

DOMDocument::createComment
DOMDocument::createElement
DOMDocument
PHP Manual

DOMDocument::createDocumentFragment

(PHP 5)

DOMDocument::createDocumentFragment — Создание фрагмента докуента

Описание

DOMDocumentFragment DOMDocument::createDocumentFragment ( void )

Эта функция создает новый экземпляр класса DOMDocumentFragment. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Возвращаемые значения

Новый объект класса DOMDocumentFragment либо FALSE в случае ошибки.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

There are no user contributed notes for this page.
DOMDocument::createComment
DOMDocument::createElement
DOMDocument


Создает новый узел-элемент

DOMDocument::createDocumentFragment
DOMDocument::createElementNS
DOMDocument
PHP Manual

DOMDocument::createElement

(PHP 5)

DOMDocument::createElement — Создает новый узел-элемент

Описание

DOMElement DOMDocument::createElement ( string $name [, string $value ] )

Эта функция создает экземпляр класса DOMElement. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

name

Имя элемента.

value

Значение элемента. По умолчанию будет создан пустой элемент. Значение может быть установлено позднее с помощью функции DOMElement::$nodeValue.

Возвращаемые значения

Возвращает новый объект класса DOMElement либо FALSE в случае ошибки.

Ошибки

DOM_INVALID_CHARACTER_ERR

Возникает, если name содержит недопустимые символы.

Примеры

Пример #1 Создание нового элемента и вставка его в качестве корневого

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// Вставляем новый элемент как корень (потомок документа)
$dom->appendChild($element);

echo $dom->saveXML();
?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="utf-8"?>
<test>Это корневой элемент!</test>

Примечания

Замечание:

Значение value не будет экранировано. Используйте функцию DOMDocument::createTextNode() для создания узла с текстовым содержимым с поддержкой экранирования.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

funkathustra 04-Mar-2012 08:44
Although the built-in DOM functions are great, since they're designed to support generic XML, generating HTML DOMs becomes particularly verbose. I ended up writing this function to drastically speed things up.
Instead of calling something like
<?php
  $div = $dom->createElement("div");
  $div->setAttribute("class","MyClass");
  $div->setAttribute("id","MyID");
  $someOtherDiv->appendChild($div);
?>
you can accomplish the same thing with:
<?php
  $div = newElement("div", $someOtherDiv, "class=MyClass;id=MyID");
?>
The "key1=value;key2=value" syntax is really fast to use, but obviously doesn't hold up if your content has those characters in it. So, you can also pass it an array:
<?php
  $div = newElement("div", $someOtherDiv, array("class","MyClass"));
?>
Or an array of arrays, representing different attributes:
<?php
  $div = newElement("form", $someOtherDiv, array(array("method","get"), array("action","/refer/?id=5");
?>

Here's the function:

<?php
function newElement($type, $insertInto = NULL, $params=NULL, $content="")
    {
        $tempEl =  $this->dom->createElement($type, $content);
        if(gettype($params) == "string" && strlen($params) > 0)
        {
            $attributesCollection =split(";", $params);
            foreach($attributesCollection  as $attribute)
            {
                $keyvalue = split("=", $attribute);
                $tempEl->setAttribute($keyvalue[0], $keyvalue[1]);
            }
        }
        if(gettype($params) == "array")
        {
            if(gettype($params[0]) == "array")
            {
                foreach($params as $attribute)
                {
                    $tempEl->setAttribute($attribute[0], $attribute[1]);
                }
            } else {
                $tempEl->setAttribute($params[0], $params[1]);
            }
        }
?>
lars dot c dot magnusson at gmail dot com 26-Nov-2010 01:56
You may think insertBefore and insertAfter is a direct alternative for appendChild, this is not the case.

<?php
$dom = new DOMDocument();
$dom->load($file);

$dom->appendChild($newNode); //Works fine
$dom->insertBefore($newNode, $refNode); //Will fail

$refNode->parentNode->insertBefore($newNode, $refNode); // thanx to yasindagli (first post)
?>
yasindagli at gmail dot com 17-Jun-2009 02:01
To create elements with attributes,

<?php

function createElement($domObj, $tag_name, $value = NULL, $attributes = NULL)
{
    $element = ($value != NULL ) ? $domObj->createElement($tag_name, $value) : $domObj->createElement($tag_name);

    if( $attributes != NULL )
    {
        foreach ($attributes as $attr=>$val)
        {
            $element->setAttribute($attr, $val);
        }
    }

    return $element;
}

$dom = new DOMDocument('1.0', 'utf-8');

$elm = createElement($dom, 'foo', 'bar', array('attr_name'=>'attr_value'));

$dom->appendChild($elm);

echo $dom->saveXML();

?>

outputs :
<?xml version="1.0" encoding="utf-8"?>
<foo attr_name="attr_value">bar</foo>
chris AT cmbuckley DOT co DOT uk 26-May-2009 07:45
Note that the NUL character "\0" is not in the list of invalid characters for $name, so no error is triggered, but the tag name will be truncated at the null byte:

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$el = $dom->createElement('foo' . "\0" . 'bar', 'Hello World');
echo $el->tagName; // outputs "foo"

?>
poison 05-Jul-2007 10:11
In response to 'mikek dot nospam at nospam dot muonics dot com', here is a more correct version, as values have to be UTF-8 encoded, and there's absolutely no reason to create an extra DOMElement class.

<?php
class ADOMDocument extends DOMDocument {

    function __construct($version = null, $encoding = null) {
        parent::__construct($version, $encoding);
    }

    public function createElement($tagName, $value=null) {
        $node=parent::createElement($tagName);
        if (!is_null($value)) {
            $node->appendChild(
                $this->createTextNode(utf8_encode($value))
            );
        }
        return $node;
    }

    public function createElementNS($namespaceURI, $qualifiedName, $value=null) {
        $node=parent::createElementNS($namespaceURI, $qualifiedName);
        if (!is_null($value)) {
            $node->appendChild(
                $this->createTextNode(utf8_encode($value))
            );
        }
        return $node;
    }
}
?>
estill at gvtc dot com 12-Jun-2007 02:38
Note that the second parameter (value), although convenient, is non-standard. You should create elements like this instead:

<?php
$doc = new DOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElement('test');
$doc->appendChild($root);

$root_text = $doc->createTextNode('This is the root element!');
$root->appendChild($root_text);

print $doc->saveXML();
?>

Or, alternatively, extend the DOMDocument class and add your own custom, convenience method to avoid intruding on the standard:

<?php
class CustomDOMDocument extends DOMDocument {
  function createElementWithText($name, $child_text) {
    // Creates an element with a child text node

    // @param  string  $name        element tag name
    // @param  string  $child_text  child node text

    // @return  object  new element

    $element = $this->createElement($name);

    $element_text = $this->createTextNode($child_text);
    $element->appendChild($element_text);

    return $element;
  }
}

$doc = new CustomDOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElementWithText('test', 'This is the root element!');
$doc->appendChild($root);

print $doc->saveXML();
?>

Also use caution with (or avoid) the 'DOMElement->nodeValue' property. It can return some unexpected values and changing its value will replace (remove) all descendants of the element with a single text node. It's also non-standard; according to the DOM spec it should return NULL.
mikek dot nospam at nospam dot muonics dot com 03-Mar-2007 05:24
With regard to the note below about needing htmlentities to avoid warnings about unterminated entity references, I thought it worthwhile to mention that that you don't need to with createTextNode and DOMText::__construct.  If you mix both methods of setting text nodes and do (or don't) apply htmlentities consistently to all data to be displayed, you'll get &amp;s (or warnings and badly-formed xml).

It's probably in one's best interest to extend DOMElement and DOMDocument so that it creates a DOMText node and appends it, rather than passing it up to the DOMElement constructor.  Otherwise, good luck using (or not using) htmlentities in all the right places in your code, especially as code changes get made.

<?php

class XDOMElement extends DOMElement {
    function __construct($name, $value = null, $namespaceURI = null) {
        parent::__construct($name, null, $namespaceURI);
    }
}

class XDOMDocument extends DOMDocument {
    function __construct($version = null, $encoding = null) {
        parent::__construct($version, $encoding);
        $this->registerNodeClass('DOMElement', 'XDOMElement');
    }

    function createElement($name, $value = null, $namespaceURI = null) {
        $element = new XDOMElement($name, $value, $namespaceURI);
        $element = $this->importNode($element);
        if (!empty($value)) {
            $element->appendChild(new DOMText($value));
        }
        return $element;
    }
}

$doc1 = new XDOMDocument();
$doc1_e1 = $doc1->createElement('foo', 'bar & baz');
$doc1->appendChild($doc1_e1);
echo $doc1->saveXML();

$doc2 = new XDOMDocument();
$doc2_e1 = $doc2->createElement('foo');
$doc2->appendChild($doc2_e1);
$doc2_e1->appendChild($doc2->createTextNode('bar & baz'));
echo $doc2->saveXML();

?>

Text specified in createElement:
<?xml version=""?>
<foo>bar &amp; baz</foo>

Text added via createTextNode:
<?xml version=""?>
<foo>bar &amp; baz</foo>
sergsokolenko at gmail dot com 30-Jan-2007 04:11
To avoid warning message "unterminated entity reference" you may use htmlentities() for escaping supplied value:
<?php
//...
$dom->createElement('name', htmlentities($text))
//...
?>
DOMDocument::createDocumentFragment
DOMDocument::createElementNS
DOMDocument


Создание нового узла-элемента с соответствующим пространством имен

DOMDocument::createElement
DOMDocument::createEntityReference
DOMDocument
PHP Manual

DOMDocument::createElementNS

(PHP 5)

DOMDocument::createElementNS — Создание нового узла-элемента с соответствующим пространством имен

Описание

DOMElement DOMDocument::createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] )

Эта функция создает новый узел-элемент с соответствующим пространством имен. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

namespaceURI

URI пространства имен.

qualifiedName

Сформированное имя элемента в виде prefix:tagname.

value

Значение элемента. По умолчанию будет создан пустой элемент. Задать значение можно позднее с помощью DOMElement::$nodeValue.

Возвращаемые значения

Новый объект класса DOMElement либо FALSE в случае ошибки.

Ошибки

DOM_INVALID_CHARACTER_ERR

Возникает, если qualifiedName содержит недопустимые символы.

DOM_NAMESPACE_ERR

Возникает, если qualifiedName не верно сформировано.

Примеры

Пример #1 Создание элемента и вставка в документ в качестве корневого

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// Вставляем новый элемент как корень (потомок документа)
$dom->appendChild($element);

echo $dom->saveXML();
?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">Это корневой элемент!</xfoo:test>

Пример #2 Пример префикса пространства имен

<?php
$doc  = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);

echo $doc->saveXML(), "\n";

echo $item->namespaceURI, "\n"; // Выведет: http://base.google.com/ns/1.0
echo $item->prefix, "\n";       // Выведет: g
echo $item->localName, "\n";    // Выведет: item_type
?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="utf-8"?>
<element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
  <g:item_type>house</g:item_type>
</element>

http://base.google.com/ns/1.0
g
item_type

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

Martin 27-Dec-2011 09:39
To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).
DOMDocument::createElement
DOMDocument::createEntityReference
DOMDocument


Создание нового узла-ссылки на сущность

DOMDocument::createElementNS
DOMDocument::createProcessingInstruction
DOMDocument
PHP Manual

DOMDocument::createEntityReference

(PHP 5)

DOMDocument::createEntityReference — Создание нового узла-ссылки на сущность

Описание

DOMEntityReference DOMDocument::createEntityReference ( string $name )

Эта функция создает экземпляр класса DOMEntityReference. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

name

Содержимое ссылки на сущность, то есть ссылка на сущность без & в начале и ; в конце.

Возвращаемые значения

Новый объект класса DOMEntityReference либо FALSE в случае ошибки.

Ошибки

DOM_INVALID_CHARACTER_ERR

Возникает, если name содержит недопустимые символы.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

There are no user contributed notes for this page.
DOMDocument::createElementNS
DOMDocument::createProcessingInstruction
DOMDocument


Создает новый PI-узел

DOMDocument::createEntityReference
DOMDocument::createTextNode
DOMDocument
PHP Manual

DOMDocument::createProcessingInstruction

(PHP 5)

DOMDocument::createProcessingInstruction — Создает новый PI-узел

Описание

DOMProcessingInstruction DOMDocument::createProcessingInstruction ( string $target [, string $data ] )

Эта функция создает экземпляр класса DOMProcessingInstruction. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

target

Цель инструкций для обработчика документа.

data

Содержимое инструкций обработчика.

Возвращаемые значения

Новый объект класса DOMProcessingInstruction либо FALSE в случае ошибки.

Ошибки

DOM_INVALID_CHARACTER_ERR

Возникает, если target содержит недопустимы символы.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

romain at supinfo dot com 03-Feb-2009 11:57
A use exemple of this method :

Usefull for generating an XML linked with a XSLT !

<?php

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

//to have indented output, not just a line
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;

// ------------- Interresting part here ------------

//creating an xslt adding processing line
$xslt = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="base.xsl"');

//adding it to the xml
$xml->appendChild($xslt);

// ----------- / Interresting part here -------------

//adding some elements
$root = $xml->createElement("list");
$node = $xml->createElement("contact", "John Doe");
$root-> appendChild($node);
$xml-> appendChild($root);

//creating the file
$xml-> save("output.xml");

?>

output.xml :

<?xml version="1.0" encoding="ISO-8859-15"?>
<?xml-stylesheet type="text/xsl" href="base.xsl"?> //the line has been created successfully
<list>
  <contact>John Doe</contact>
</list>
DOMDocument::createEntityReference
DOMDocument::createTextNode
DOMDocument


Создает новый текстовый узел

DOMDocument::createProcessingInstruction
DOMDocument::getElementById
DOMDocument
PHP Manual

DOMDocument::createTextNode

(PHP 5)

DOMDocument::createTextNode — Создает новый текстовый узел

Описание

DOMText DOMDocument::createTextNode ( string $content )

Эта функция создает экземпляр класса DOMText. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().

Список параметров

content

Содержимое узла.

Возвращаемые значения

Новый объект класса DOMText либо FALSE в случае ошибки.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMDocument::createAttribute() - Создает новый атрибут
  • DOMDocument::createAttributeNS() - Создает новый узел-атрибут с соответствующим ему пространством имен
  • DOMDocument::createCDATASection() - Создает новый cdata узел
  • DOMDocument::createComment() - Создает новый узел-комментарий
  • DOMDocument::createDocumentFragment() - Создание фрагмента докуента
  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен
  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность
  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел

User Contributed Notes

Alex Kaye 25-Jul-2009 07:04
A quick note to anyone who is using character entities (e.g. &copy;) in this, and finding them automatically escaped. The correct thing to do here is to use the createEntityReference method (e.g. createEntityReference("copy");), and then appendChild this entity between text nodes.

Example:

<?php
$copyright_text_1 = $this->document->createTextNode("Copyright ");
$copyright_text_2 = $this->document->createTextNode(" Alex Kaye 2009");
$copyright_symbol = $this->document->createEntityReference("copy");
$copyright->appendChild($copyright_text_1);
$copyright->appendChild($copyright_symbol);
$copyright->appendChild($copyright_text_2);
?>
anton dot vakulchik at gmail dot com 12-Mar-2008 08:23
//For PHP5
$Doc = new DOMDocument('1.0');
$Dom = $Doc->appendChild(new domelement('log'));
$Dom->setAttribute('class','something');
$Dom->appendChild($Doc->createTextNode('something'));
jon at websandbox dot net 03-Aug-2005 04:01
About escaping characters:
This is standard behavior.  brackets, ampersans, and maybe even quoted will be "escaped" if you output your XML as a string.

This should not, however, happen if you append your text node to a CDATA section.
DOMDocument::createProcessingInstruction
DOMDocument::getElementById
DOMDocument


Ищет элемент с заданным id

DOMDocument::createTextNode
DOMDocument::getElementsByTagName
DOMDocument
PHP Manual

DOMDocument::getElementById

(PHP 5)

DOMDocument::getElementById — Ищет элемент с заданным id

Описание

DOMElement DOMDocument::getElementById ( string $elementId )

Эта функция является аналогом DOMDocument::getElementsByTagName, но ищет элемент по его id.

Для работы этой функции необходимо либо задать ID атрибуты элементов посредством DOMElement::setIdAttribute, либо понадобится DTD, которая определяет атрибут как имеющий тип ID. В последнем случае перед использованием этой функции потребуется проверять документ на действительность посредством DOMDocument::validate или DOMDocument::$validateOnParse.

Список параметров

elementId

Уникальный id элемента.

Возвращаемые значения

Returns the DOMElement or NULL if the element is not found.

Примеры

Пример #1 Пример использования DOMDocument::getElementById()

<?php

$doc = new DomDocument;

// Необходимо проверить документ на действительность перед тем как
// ссылаться на id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "Элемент с id 'books': " . $doc->getElementById('books')->tagName . "\n";

?>

Результат выполнения данного примера:

Элемент с id 'books': chapter

Смотрите также

  • DOMDocument::getElementsByTagName() - Ищет все элементы с заданным локальным именем

User Contributed Notes

ed at edgiardina dot com 13-Oct-2010 11:41
Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null.
paradox_haze at live dot de 02-Mar-2010 10:53
Had some issues with getElementById() while searching for a specific element in a XHTML document.
I wrote a small function what was solving my problem:

<?php
function getElementById($id)
{
    $xpath = new DOMXPath($this->domDocument);
    return $xpath->query("//*[@id='$id']")->item(0);
}
?>
gurmukh24 at gmail dot com 03-May-2009 09:40
See example how multiple attributes and childs are parsed using php in a perfect way. coder : gurmukh singh Bhatti
<?php
$xml =<<<EOT
<?xml version="1.0"?>
<root>
<section name="Section1">
  <category id="Category1" name="google">
   <arti name="article1">
   <p>any html code here</p>
   <b>my name is so so</b>
    </arti>
   <arti name="article2">value2</arti>
   <arti name="article3">value3</arti>
   <arti name="article4">value4</arti>
  </category>
    <category id="Category2" name="yahoo">
   <arti name="articleSection2">Test value</arti>
  </category>
</section>
<section name="Section2">
  <category id="category1_of_section2" name="msn">
   <arti name="article2">value1</arti>
   <arti name="article3">value2</arti>
  </category>
    <category id="Category2_of_section2" name="webcare">
    <arti name="param3">value4</arti>
   </category>
</section>
</root>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('section'); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
         echo "Section Attribute :-> ".$params->item($k)->getAttribute('name')."<br>";   //get section attribute
         $params2 = $params->item($k)->getElementsByTagName('category'); //digg categories with in Section
      $i=0; // values is used to iterate categories
        foreach ($params2 as $p) {
           echo "&nbsp;&nbsp;- Category Attribute Name :-> ".$params2->item($i)->getAttribute('name')."<br>"; //get Category attributes
            $params3 = $params2->item($i)->getElementsByTagName('arti'); //dig Arti into Categories
                 $j=0;//values used to interate Arti
                     foreach ($params3 as $p2)
                   {
                    echo "&nbsp;&nbsp;&nbsp;- Article Attribute Name : ".$params3->item($j)->getAttribute('name').""; //get arti atributes
echo "&nbsp;&nbsp; Value : ".$params3->item($j)->nodeValue."<br>"; //get Node value ;
                              $j++;
                   }
         $i++;
      }
$k++;

}
?>

output :
 Section Attribute :-> Section1
  - Category Attribute Name :-> google
            - Article Attribute Name : article1   Value : any html code heremy name is so so
            - Article Attribute Name : article2   Value : value2
            - Article Attribute Name : article3   Value : value3
            - Article Attribute Name : article4   Value : value4
  - Category Attribute Name :-> yahoo
            - Article Attribute Name : articleSection2   Value : Test value
Section Attribute :-> Section2
  - Category Attribute Name :-> msn
            - Article Attribute Name : article2   Value : value1
            - Article Attribute Name : article3   Value : value2
  - Category Attribute Name :-> webcare
            - Article Attribute Name : param3   Value : value4
carl2088 at gmail dot com 11-Apr-2009 12:41
From my experience, getElementById seem to work fine without any setups if you have loaded a HTML document. But in order for getElementById to work with a simple XML document that you've "constructed", you have to set up the id with "xml:" prefix and use setIdAttribute on the element you created or it won't work. See following example, hope this will save someone's frustration. If you have loaded the xml file, then all you have to make sure is the ID has a xml: prefix for the attribute.  But if you start to append the XML document, don't forget to setIdAttribute on the id name or those elements or getElementById will return null when you try to find them.

<?php

    /* test.xml
    <?xml version="1.0" encoding="utf-8"?>
    <root>
        <child xml:id="id_xxxxxx" status="partial">
            <sub_child>Some Data</sub_child>
        </child>
    </root>
    */

    $xmlDom = new DOMDocument('1.0', 'utf-8');
    $xmlDom->formatOutput = true;                        // we want a nice output

    // create a root
    $eltRoot = $xmlDom->createElement("root");
    $xmlDom->appendChild($eltRoot);

    $eltChild = $xmlDom->createElement("child");
    $eltRoot->appendChild($eltChild);

    // add a id attribute
    $attr = $xmlDom->createAttribute("xml:id");    // needs xml prefix or getElementById won't work
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("id_8120528");
    $attr->appendChild($tNode);
    $eltChild->setIdAttribute("xml:id", true);    // VERY IMPORT or getElementById won't work

    // add a id attribute
    $attr = $xmlDom->createAttribute("status");
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("partial");
    $attr->appendChild($tNode);

    // add a subchild
    $eltSub = $xmlDom->createElement("sub_child");
    $eltChild->appendChild($eltSub);

    $tNode = $xmlDom->createTextNode("Some Data");
    $eltSub->appendChild($tNode);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // bug? empty
    $strStatus = $id->getAttribute("status"); // this works!

    assert ($id !=null);

    $xmlDom->save("./_data/test.xml");

    $xmlDom->load("./_data/test.xml"); // reloading fixes the problem

    $nodeRoot = $xmlDom->getElementsByTagName("root");
    if ($nodeRoot->length > 0) {
        $eltRoot = $nodeRoot->item(0);
    }

    assert($eltRoot != null);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // this works now!
    $strStatus = $id->getAttribute("status"); // this works!

?>
guillaume dot crico at gmail dot com 01-Oct-2008 07:55
You don't want to use "xml:id" ?
Here is the relaxNG trick (with a generic schema):
(tested with libxml 2.6.26)

<?php
$doc = new DOMDocument();
$doc->load(...);

$rng = '
<grammar xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
    <start>
        <element>
            <anyName/>
            <ref name="anythingID"/>
        </element>
    </start>
    <define name="anythingID">
        <zeroOrMore>
            <choice>
                <element>
                    <anyName/>
                    <ref name="anythingID"/>
                </element>
                <attribute name="id">
                    <data type="ID"/>
                </attribute>
                <zeroOrMore>
                    <attribute><anyName/></attribute>
                </zeroOrMore>
                <text/>
            </choice>
        </zeroOrMore>
    </define>
</grammar>
';

$doc->relaxNGValidateSource($rng);
var_dump($doc->getElementById('id1'));
?>

Note that ID values must be valid ones :
  - integers do no work!
  - @see http://www.w3.org/TR/REC-xml/#id
  - => (Letter | '_' | ':') ( Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender  )*
simon at somewhere dot com 29-Jan-2007 08:07
SAVE YOURSELF A MAJOR HEADACHE AND A LOT OF SEARCHING THROUGH DOCUMENTATION -

Instead of using $object->setAttribute('id', 'id_name_here')
USE THIS: $object->setAttribute('xml:id', 'id_name_here')

Then, to get the node value: $domDocumentObject->getElementById('id_name_here');

The xml:id attribute should AUTOMATICALLY be defined!!

Woohoo!  That was easy......
jonbarnett at gmail dot com 01-Nov-2006 08:36
If your XML document does not have a DTD that defines the "id" attribute as an ID, then the easiest thing to do is to use XPath->query() to find an element that matches "//[@id='x']"
Tangui dot Le-Pense at laposte dot net 08-Apr-2006 06:00
Validating a document from a DTD so as to use getElementById is sometimes impossible (for example when the head and body elements are not included yet in a XHtml document : the validation failed).
Fortunately, xml:id is supported by this function :)
That may be useful.
http://www.w3.org/TR/xml-id/
20-Dec-2005 07:04
If you're trying to use getElementById with a xml file validated on a xsd file you must first use the schemaValidate function or getElementById will return null
Example:

  $dom = new DomDocument();
  $dom->load("users.xml");
  $dom->schemaValidate("users.xsd");

  $curruser = $dom->getElementById($user->name);
bart at mediawave dot nl 11-Sep-2005 04:46
It seems getElementById works fine without setting validateOnParse to true. Which is nice since setting this to true caused some performance problems with my script.
DOMDocument::createTextNode
DOMDocument::getElementsByTagName
DOMDocument


Ищет все элементы с заданным локальным именем

DOMDocument::getElementById
DOMDocument::getElementsByTagNameNS
DOMDocument
PHP Manual

DOMDocument::getElementsByTagName

(PHP 5)

DOMDocument::getElementsByTagName — Ищет все элементы с заданным локальным именем

Описание

DOMNodeList DOMDocument::getElementsByTagName ( string $name )

Эта функция возвращает новый объект класса DOMNodeList, содержащий элементы с заданным локальным именем.

Список параметров

name

Локальное имя тэга (без указания пространства имен), по которому будет проводиться поиск. Специальное значение * означает, что поиск будет произведен по всем тэгам.

Возвращаемые значения

Новый объект класса DOMNodeList содержащий все найденные элементы.

Примеры

Пример #1 Простой пример использования

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
 <book>Patterns of Enterprise Application Architecture</book>
 <book>Design Patterns: Elements of Reusable Software Design</book>
 <book>Clean Code</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}
?>

Результат выполнения данного примера:

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

Смотрите также

  • DOMDocument::getElementsByTagNameNS() - Ищет элементы с заданным именем в определенном пространстве имен

User Contributed Notes

metron at underhive-planet dot com 08-Oct-2010 05:28
My first try to get a stable solution with this function, failed with this Exception:

"Fatal error: Call to undefined method DOMNodeList::getElementsByTagName()"
This is the xml snipplet:
<?xml version="1.0" encoding="UTF-8"?>
<root>
 <component>
  <properties>
    ....<any element>
  </properties>
 </component>
</root>

So the php code to climb along the elements is:
<?php

$src = new DOMDocument('1.0', 'utf-8');
$src->formatOutput = true;
$src->preserveWhiteSpace = false;

//Loading extern file
$src->load('../xml/Item_component.xml');

//Check each child of first indexed branch node of: <component>
//First get element after root element: <component>

//1st level
$component = $src->getElementsByTagName('component')->item(0);

//2nd level, get next element after component, here it fails!!
$properties = $component->getElementsByTagName('properties')->item(0);
...
?>

I realised, that there is a different when using different libxml2 versions on Apache2. This code will fail with libxml2 version 2.6.23 and PHP version 5.2.6
--
->It works fine with libxml2 version 2.6.32 and PHP version 5.2.6-3ubuntu4.6
->...and finally it also works with libxml2 2.7.7 and PHP >= 5.3

So if you bored to search for solutions with DOM like I did, please ensure that your www environment has the correct libxml2 / PHP Version installed on your apache2 server.
calvin at g mail 02-Oct-2010 04:41
My first post!
And this is how I get elements by attribute and its value.
For an example, if I want to grab all DIV tags with class name 'className', then...

<?php
$some_link = 'some website';
$tagName = 'div';
$attrName = 'class';
$attrValue = 'className';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile($some_link);

$html = getTags( $dom, $tagName, $attrName, $attrValue );
echo $html;

function getTags( $dom, $tagName, $attrName, $attrValue ){
    $html = '';
    $domxpath = new DOMXPath($dom);
    $newDom = new DOMDocument;
    $newDom->formatOutput = true;

    $filtered = $domxpath->query("//$tagName" . '[@' . $attrName . "='$attrValue']");
    // $filtered =  $domxpath->query('//div[@class="className"]');
    // '//' when you don't know 'absolute' path

    // since above returns DomNodeList Object
    // I use following routine to convert it to string(html); copied it from someone's post in this site. Thank you.
    $i = 0;
    while( $myItem = $filtered->item($i++) ){
        $node = $newDom->importNode( $myItem, true );    // import node
        $newDom->appendChild($node);                    // append node
    }
    $html = $newDom->saveHTML();
    return $html;
}

?>

Please, improve it, and share it.
Philip N 01-Sep-2010 03:17
Note that when using getElementsByTagName that it is a dynamic list. Thus if you have code which adjusts the DOM structure it will change the results of the getElementsByTagName results list.

The following code iterates through a complete set of results and changes them all to a new tag:

<?php
 $nodes = $xml->getElementsByTagName ("oldtag");

 $nodeListLength = $nodes->length; // this value will also change
 for ($i = 0; $i < $nodeListLength; $i ++)
 {
    $node = $nodes->item(0);

    // some code to change the tag name from "oldtag" to something else
    // e.g. encrypting a tag element
 }
?>

Since the list is dynamically updating, $nodes->item(0) is the next "unchanged" tag.
Marco Maranao 27-Apr-2010 10:22
The following takes a list of news items from an XML file (or an RSS feed), assigning it to an array first for a name value pair and then generating an HTML list.

<?php

$xml  =<<<EOT
<?xml version="1.0" encoding="ISO-8859-1"?>
<news>
    <item>
        <title>News 1</title>
        <created>04/2/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 2</title>
        <created>04/25/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 3</title>
        <created>04/27/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
</news>
EOT;

$doc = new DOMDocument();

if ($doc->loadXML($xml)) {
    $items = $doc->getElementsByTagName('item');
    $headlines = array();

    foreach($items as $item) {
        $headline = array();

        if($item->childNodes->length) {
            foreach($item->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }

        $headlines[] = $headline;
    }

    if(!empty($headlines)) {
        $hc = 0;

        echo '<ul>';

        foreach($headlines as $headline) {
            if(++$hc <= 3) {
                echo '<li>'
                    .'<a href="'.$headline['url'].'" target="_blank">'
                        .'<span>'.date('F j, Y', strtotime($headline['created'])).'</span><br />'
                        .$headline['title']
                    .'</a>'
                .'</li>';
            }
        }

        echo '</ul>';
    }
}

?>
james 01-Feb-2010 07:03
Problem:
You have an XML document that contains filename references to, say, images. Each filename reference is defined by <file>filename.ext</file> tag. You'd like to perform perform additional validation, say, after running the XML document through XSD validation. The additional validation can be any of your choice, in this example, it would be ideal to convert the PHP code to a function. The function would then determine if the images exist and return either an integer value or a boolean.

<?xml version="1.0"?>
<root>
<box>
<file>example.png</file>
</box>
<content>
<item>
<image><file>example2.png</file></image>
<caption>The above image is an example</caption>
</item>
</content>
</root>

Solution:
<?php

$dom = new DomDocument();
$dom->prevservWhiteSpace = false;

if (!@$dom->load("example.xml")) {
    echo "example.xml doesn't exist!\n";
    return;
}

$imageList = $dom->getElementsByTagName('file');
$imageCnt  = $imageList->length;

for ($idx = 0; $idx < $imageCnt; $idx++) {
    print $imageList->item($idx)->nodeValue . "\n";
}

?>

The above PHP code could easily be turned into a function that returns an array of image filenames, an integer value relative to the number of images found, etc.

Hope this is helpful.
gurmukh24 at gmail dot com 03-Mar-2009 04:06
Following Example is of multiple attributes and multiple child nodes. this is being used to make joomla plugin for bulk upload of articles. Gurmukh Singh Bhatti

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<root>
<section name="Section1">
  <category id="Category1" name="google">
   <arti name="article1">
   <p>any html code here</p>
   <b>my name is so so</b>
    </arti>
   <arti name="article2">value2</arti>
   <arti name="article3">value3</arti>
   <arti name="article4">value4</arti>
  </category>
    <category id="Category2" name="yahoo">
   <arti name="articleSection2">Test value</arti>
  </category>
</section>
<section name="Section2">
  <category id="category1_of_section2" name="msn">
   <arti name="article2">value1</arti>
   <arti name="article3">value2</arti>
  </category>
    <category id="Category2_of_section2" name="webcare">
    <arti name="param3">value4</arti>
   </category>
</section>
</root>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('section'); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
         echo "Section Attribute :-> ".$params->item($k)->getAttribute('name')."<br>";   //get section attribute
         $params2 = $params->item($k)->getElementsByTagName('category'); //digg categories with in Section
      $i=0; // values is used to iterate categories
        foreach ($params2 as $p) {
           echo "&nbsp;&nbsp;- Category Attribute Name :-> ".$params2->item($i)->getAttribute('name')."<br>"; //get Category attributes
            $params3 = $params2->item($i)->getElementsByTagName('arti'); //dig Arti into Categories
                 $j=0;//values used to interate Arti
                     foreach ($params3 as $p2)
                   {
                    echo "&nbsp;&nbsp;&nbsp;- Article Attribute Name : ".$params3->item($j)->getAttribute('name').""; //get arti atributes
echo "&nbsp;&nbsp; Value : ".$params3->item($j)->nodeValue."<br>"; //get Node value ;
                              $j++;
                   }
         $i++;
      }
$k++;

}
?>

output :
 Section Attribute :-> Section1
  - Category Attribute Name :-> google
            - Article Attribute Name : article1   Value : any html code heremy name is so so
            - Article Attribute Name : article2   Value : value2
            - Article Attribute Name : article3   Value : value3
            - Article Attribute Name : article4   Value : value4
  - Category Attribute Name :-> yahoo
            - Article Attribute Name : articleSection2   Value : Test value
Section Attribute :-> Section2
  - Category Attribute Name :-> msn
            - Article Attribute Name : article2   Value : value1
            - Article Attribute Name : article3   Value : value2
  - Category Attribute Name :-> webcare
            - Article Attribute Name : param3   Value : value4
StudioAMK.com 09-Oct-2008 08:09
<?php

$doc = new DOMDocument();
$doc->load( 'Users.xml' );

$dataset = $doc->getElementsByTagName( "dataUser" );
foreach( $dataset as $row )
{
    $xmlUserNames = $row->getElementsByTagName( "UserName" );
    $xmlUserName = $xmlUserNames->item(0)->nodeValue;

    $xmlEmails = $row->getElementsByTagName( "Email" );
    $xmlEmail = $xmlEmails->item(0)->nodeValue;

    $xmlDisplayNames = $row->getElementsByTagName( "DisplayName" );
    $xmlDisplayName = $xmlDisplayNames->item(0)->nodeValue;

    echo "$xmlUserName - $xmlEmail - $xmlDisplayName\n";
}
?>

Contents in Users.xml

<NewDataSet>
    <dataUser>
        <UserName>StudioAMK</UserName>
        <Email>user1@mail.com</Email>
        <DisplayName>StudioAMK.com</DisplayName>
    </dataUser>
    <dataUser>
        <UserName>User2</UserName>
        <Email>user2@mail.com</Email>
        <DisplayName>UserTwo</DisplayName>
    </dataUser>
</NewDataSet>
James L 19-Aug-2008 04:04
Return if there are no matches is an empty DOMNodeList. Check using length property, e.g.:

<?php
$nodes=$domDocument->getElementsByTagName('book') ;
if ($nodes->length==0) {
   // no results
}
?>
jason at shaped dot ca 11-Feb-2008 04:59
in response to tildy at pr dot hu

my preferred way is (in example to gather country data from an iso 3166 xml flie)

$countries = new DOMDocument();
$countries->load("./lib/iso_3166.xml");

$countriesList = $countries->getElementsByTagName("ISO_3166-1_Entry");

foreach($countriesList as $country) {
    $values = $country->getElementsByTagName("*");
    foreach($values as $node) {
      echo $node->nodeName."=".$node->nodeValue;
    }
}
tildy at pr dot hu 13-Dec-2007 04:51
If you want to list the nodename and value of one item(node)  this is an example:

$itemnodes = $doc->getElementsByTagName( "item" );
$nodes = $itemnodes->item(0)->getElementsByTagName( "*" );
for ( $i = 0; $i < $nodes->length; $i++ ) {
    print "nodename=".$nodes->item( $i )->nodeName;
    print "\t";
    print "nodevalue : ".$nodes->item( $i )->nodeValue;
    print "\r\n";
}

It will be list all children name and value of item.
Francois Hill 30-Jul-2007 07:36
Careful : getElementsByTagName will yield all elements with the given tag name under the present node, at any sub-level (i.e. among child nodes and all other descendant nodes)
Finding values of a node 14-Mar-2007 02:01
I don't know if this is that obvious but it was not for me, so in addition to gem at rellim dot com's posting:
adding

<?php
echo $param -> nodeValue.'<br>';
?>

to the loop will output
value1
value2
value3
gem at rellim dot com 29-Sep-2004 04:20
Here is an example of getElementsByTagName():

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<config>
  <section id="section1">
   <param name="param1">value1</param>
   <param name="param2">value2</param>
  </section>
  <section id="section2">
   <param name="param3">value3</param>
  </section>
</config>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('param');

foreach ($params as $param) {
       echo $param -> getAttribute('name').'<br>';
}
?>

Expected result:
--------------
param1
param2
param3
DOMDocument::getElementById
DOMDocument::getElementsByTagNameNS
DOMDocument


Ищет элементы с заданным именем в определенном пространстве имен

DOMDocument::getElementsByTagName
DOMDocument::importNode
DOMDocument
PHP Manual

DOMDocument::getElementsByTagNameNS

(PHP 5)

DOMDocument::getElementsByTagNameNS — Ищет элементы с заданным именем в определенном пространстве имен

Описание

DOMNodeList DOMDocument::getElementsByTagNameNS ( string $namespaceURI , string $localName )

Возвращает объект DOMNodeList со всеми элементами с заданным локальным именем и URI пространства имен.

Список параметров

namespaceURI

URI пространства имен. Специальное значение * означает, что поиск будет произведен по всем пространствам имен.

localName

Локальное имя искомых элементов. Специальное значение * означает, что поиск будет произведен по всем локальным именам.

Возвращаемые значения

Новый объект класса DOMNodeList содержащий все найденные элементы.

Примеры

Пример #1 Получение всех XInclude элементов

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
 <xi:include href="book.xml">
  <xi:fallback>
   <error>xinclude: book.xml not found</error>
  </xi:fallback>
 </xi:include>
 <include>
  This is another namespace
 </include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// загрузка XML строки, определенной выше
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

Результат выполнения данного примера:

local name: include, prefix: xi
local name: fallback, prefix: xi

Смотрите также

  • DOMDocument::getElementsByTagName() - Ищет все элементы с заданным локальным именем

User Contributed Notes

There are no user contributed notes for this page.
DOMDocument::getElementsByTagName
DOMDocument::importNode
DOMDocument


Импорт узла в текущий документ

DOMDocument::getElementsByTagNameNS
DOMDocument::load
DOMDocument
PHP Manual

DOMDocument::importNode

(PHP 5)

DOMDocument::importNode — Импорт узла в текущий документ

Описание

DOMNode DOMDocument::importNode ( DOMNode $importedNode [, bool $deep ] )

Эта функция возвращает копию импортируемого узла и присоединяет ее к текущему документу.

Список параметров

importedNode

Импортируемый узел.

deep

Если установлен в TRUE, этот метод рекурсивно импортирует поддерево узла importedNode.

Замечание:

Чтобы скопировались атрибуты узла, deep должен быть установлен в TRUE.

Возвращаемые значения

Скопированный узел или FALSE, если он не может быть скопирован.

Ошибки

Если узел не может быть импортирован, будет выброшено исключение DOMException.

Примеры

Пример #1 Пример использования DOMDocument::importNode()

Копирование узлов между документами.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// Узел, который будет импортирован в новый документ
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Создание нового документа
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Добавление разметки
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo "Новый документ перед добавлением в него узлов:\n";
echo $newdoc->saveXML();

// Импорт узла и всех его потомков в документ
$node = $newdoc->importNode($node, true);
// И затем добавление узла в корень элемента
$newdoc->documentElement->appendChild($node);

echo "\nНовый документ после добавления в него узлов:\n";
echo $newdoc->saveXML();
?>

Результат выполнения данного примера:

Новый документ перед добавлением в него узлов:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
</root>

Новый документ после добавления в него узлов:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
  <element>
    <child>text in child</child>
  </element>
</root>

User Contributed Notes

c dot 1 at smithies dot org 19-Oct-2009 06:40
Assume that $source and $dest are instances of DOMDocument. Assume that $sourcedoc contains an element with ID 'sourceID' and that $destdoc contains an element with ID 'destID'. Assume that we have already set up source and destination element variables thus:

<?php
 $src = $sourcedoc->getElementById('sourceID');
 $dst = $destdoc->getElementById('destID');
?>

Finally, assume that $sel has more than one child node.

In order to import the child elements of $src as children of $dst, you might do something like this:

<?php
$src = $dest->importNode($src, TRUE);

foreach ($src->childNodes as $el) $dst->appendChild($el);
?>

But this does not work. foreach gets confused, because (as noted below) appending an imported element to another existing element in the same document causes it to be removed from its current parent element.

Therefore, the following technique should be used:

<?php
foreach ($src->childNodes as $el) $dst->appendChild($destdoc->importNode($el, TRUE));
?>
p dot reisinger at gmail dot com 29-Dec-2008 03:43
When you use function/method below, php automaticaly inserts namespaces (if you have some). If you want to join xml files exactly, then you can just use placeholders and treat xml as a string.
<?php
function joinXMLStrings($file1, $file2)
{
    //remove xml declaration
    $file2 = trim(preg_replace('/<\?xml.*\?>/', '', $file2, 1));

    //insert file2 in the place of placeholder in the first file
    $file1 = trim(preg_replace('/<\?file2\s\?>/', $file2, $file1, 1));
}
?>

so function looks like this and you insert two xml files. First file has to have placeholder (where you insert file2). Placeholder in this case will be <?file2 ?>

!!!this is only for ilustration - test before you use it
p dot reisinger at gmail dot com 23-Dec-2008 07:32
method (can be used as a function as well) that joins two xml files. first argument is parent xml (the one to be inserted into), second child (the one to be inserted) and third is optional argument that specifies the parent's tag where to insert children xml. If not specified then children is inserted as the last element, just before end of the root
<?php
    protected function joinXML($parent, $child, $tag = null)
    {
        $DOMChild = new DOMDocument;
        $DOMChild->loadXML($child);
        $node = $DOMChild->documentElement;

        $DOMParent = new DOMDocument;
        $DOMParent->formatOutput = true;
        $DOMParent->loadXML($parent);

        $node = $DOMParent->importNode($node, true);

        if ($tag !== null) {
            $tag = $DOMParent->getElementsByTagName($tag)->item(0);
            $tag->appendChild($node);
        } else {
            $DOMParent->documentElement->appendChild($node);
        }

        return $DOMParent->saveXML();
    }
?>
mailme at sove dot nl 11-Jun-2008 05:29
DOMDocument->importNode with seconds argument false will leave attributes behind. To fix this:

$__DOM->importNode
   (
      $__INPUT->cloneNode(false), true
   );

$__DOM (DOMDocument) will import the $__INPUT node (DOMElement) INCLUDING attributes.
mark at 4inloop dot de 05-Apr-2007 05:51
When you left out the second argument or enter false, not only the child nodes are ommited. The attributes of the node are also cut off.
adjwilli 05-Oct-2006 01:08
Editing XML with PHP can be a pain in the Secretary of State Powell, so here's a script to replace an XML node with a user-provided one through the POST. It's usually a good idea to run the $_POST['xml'] through a validation check and clean it for other thing before running this.

Pretty much this script expects a user-provided node called $_POST['xml'] and the XPath of the node in the original document that you want to replace called $_POST['XPath']. It also loads the original XML document from $xml. The function nodeRunner begins with the root node of the document you're editting and the XPath for the root element (these are more to make recursion easy than anything else).

$doc = new DOMDocument();
$doc->loadXML($xml); // $xml expects an XML string

function nodeRunner ($node,$xpath) {
    global $doc;
    if ($xpath == $_POST['XPath']) {

        $xmlPost = new DOMDocument();
        $xmlPost->loadXML($_POST['xml']);

        $newNode = $doc->importNode($xmlPost->firstChild,true);

        $node->parentNode->replaceChild($newNode,$node);
    } else {

        $page = 1;
        $section = 1;

        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $nodling) {
                $nodeName = $nodling->nodeName;
                if ($nodeName == 'page' || $nodeName == 'section') {
                    nodeRunner ($nodling,$xpath."/".$nodeName."[".$$nodeName."]");
                    $$nodeName++;
                }
            }
        }
    }
}

nodeRunner ($doc->documentElement,"/root[1]"); // /root should be explicit name of the root  element of the XPath

$doc->saveXML();
stomas 19-Sep-2006 06:14
I think this should do the same:

<?
 // Import $b into $a's document
 function myimport($a, $b)
 {
   if ($a->ownerDocument->isSameNode($b->ownerDocument))
   {
    return $b->cloneNode(TRUE);
   }
   else
   {
    return $a->ownerDocument->importNode($b, TRUE);
   }
 }
 ?>
Colin 12-Sep-2006 09:11
As of PHP 5.1.6 with libxml 2.6.26 and DOM/XML API version 20031129, importNode() does nothing if attempting to import from the same document.  Meaning, if you do an $ret = importNode and then appendChild($ret) or insertBefore($ret, ...) then you will end up *moving* the node instead of ending up with a copy.

If you expect importNode to give you a copy of the source (in this case, a deep copy) then you must account for them being from the same document.  This function addresses this:

<?
// Import $b into $a's document
function myimport($a, $b)
{
  if ($a->ownerDocument->isSameNode($b->ownerDocument))
  {
    $temp = new DOMDocument();
    $ret = $temp->importNode($b, TRUE);
    return $a->ownerDocument->importNode($ret, TRUE);
  }
  else
  {
    return $a->ownerDocument->importNode($b, TRUE);
  }
}
?>

(Function was freshly coded for this note but I based it off another, working function of mine.)

This function checks if the documents are the same and uses a new document (guaranteed to be different this way) to force a copy into $temp and then force a copy back into $a->ownerDocument.

Obviously, no error checking has been done.
andy dot clark at dial dot pipex dot com 15-Aug-2006 08:20
One useful use of importNode is to copy one node onto another.

function CopyXMLNode($SourceNode,$DestNode)
 {
  if ($SourceNode->nodeName != '#text')
   {
     //Copy this node
    $node = $DestNode->ownerDocument->importNode($SourceNode, true);
    $node = $DestNode->appendChild($node);
    //Now copy the child nodes
    foreach ($SourceNode->childNodes AS $item)
     {
     $this->CopyXMLNode($item,$node);
     }
    }
  }
Fitopaldi 03-Aug-2005 11:29
importNode returns a copy of the node to import and associates it with the current document, but not import the node to the current DOMDocument. Use appendChild for import the copy of the node to current DOMDocument.

<?
 $domNode = $dom->importNode($aDomNode, true);
 $currentDomDocument->appendChild($domNode);
?>
DOMDocument::getElementsByTagNameNS
DOMDocument::load
DOMDocument


Загрузка XML из файла

DOMDocument::importNode
DOMDocument::loadHTML
DOMDocument
PHP Manual

DOMDocument::load

(PHP 5)

DOMDocument::load — Загрузка XML из файла

Описание

mixed DOMDocument::load ( string $filename [, int $options = 0 ] )

Загружает XML документ из файла.

Внимание

Пути к файлам в стиле Unix с прямыми слешами могут отрицательно сказаться на работоспособности скриптов в среде Windows; используйте функцию realpath() для исключения подобных ситуаций.

Список параметров

filename

Путь к XML документу.

options

Побитовое ИЛИ констант настройки libxml.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. При статическом вызове возвращает объект класса DOMDocument или FALSE в случае возникновения ошибки.

Ошибки

Если через аргумент filename передана пустая строка или файл ничего не содержит, будет сгенерировано предупреждение. Это предупреждение генерируется не libxml, поэтому оно не может быть обработано обработчиками ошибок библиотеки libxml.

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Примеры

Пример #1 Создание документа

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

Смотрите также

  • DOMDocument::loadXML() - Загрузка XML из строки
  • DOMDocument::save() - Сохраняет XML дерево из внутреннего представления в файл
  • DOMDocument::saveXML() - Сохраняет XML дерево из внутреннего представления в виде строки

User Contributed Notes

sainthyoga2003 at gmail dot com 09-Feb-2012 03:37
in the default example:

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

you must enter the absolute path for book.xml due for get a false result in load function.
sainthyoga2003 at gmail dot com 25-Feb-2011 05:38
i've found the partial solution for xml:id warning,is explained at this address: https://fosswiki.liip.ch/display/BLOG/GetElementById+Pitfalls

there explains that:
The ID does have to be a valid NCName, which for example means, that the first letter can't be a number.

and in my xml:id i had a number. :D
sainthyoga2003 at gmail dot com 16-Feb-2011 09:31
adding an id for a child, when i use abstract mode i get the following warning:

[quote]Warning: DOMDocument::load() [domdocument.load]: xml:id : attribute value xx is not an NCName in /fake/path/to/xmlfile[/quote]
_ michael 01-Jun-2010 08:34
load() will handle non-ASCII characters depending on the details of the XML declaration, but in a somewhat surprising way. One would assume that the declarations '<?xml version="1.0" encoding="UTF-8"?>' and '<?xml version="1.0"?>' are treated in the same way because UTF-8 is the default encoding anyway. But not so.

* If there is an XML declaration defining the encoding *explicitly*, the non-ASCII characters remain unchanged.
* If the XML declaration does not define the encoding explicitly, or if the XML declaration is missing, non-ASCII characters are converted into numeric entities.

So the document

    <?xml version="1.0"?>
    <root><nonascii>ä</nonascii></root>

will be converted to

    <?xml version="1.0"?>
    <root><nonascii>&#xE4;</nonascii></root>

The same happens if there is no XML declaration at all. On the other hand, the document

    <?xml version="1.0" encoding="UTF-8"?>
    <root><nonascii>ä</nonascii></root>

will remain as it is.

This behaviour applies to loadXML() as well.
_ michael 19-Apr-2010 07:50
XHTML and entities: The solution proposed below by zachatwork at gmail dot com didn't work for me. I checked on a number of servers (both LAMPP and WAMPP) - on each of them, calling loadXML() with the LIBXML_DTDLOAD option triggered an external request for the DTD. And that's bad news.

If allow_url_fopen is turned off, the request for the DTD fails with a warning. If it is turned on, the request fails because these w3c URLs return a 503 Service Unavailable.

HTML entities still generate a warning in either case.

The best solution, as far as I can tell, is simply to ignore the warnings and suppress them using '@'. I can't recommend parsing XHTML with loadHTML() instead of loadXML() - yes, you get rid of the entity problem, but loadHTML() changes the source while parsing it (tries to 'fix' it even though there is nothing to fix).
zachatwork at gmail dot com 30-Jun-2009 11:28
You can easily avoid the warning about &nbsp; references by using the LIBXML_DTDLOAD option.

<?php

$html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  </head>
  <body>
    <p>&nbsp;</p>
  </body>
</html>
EOF;

// This one works perfectly.
$dom = new DOMDocument();
$dom->loadXML($html, LIBXML_DTDLOAD);
print $dom->saveXML();

// This one produces a warning.
$dom = new DOMDocument();
$dom->loadXML($html);
print $dom->saveXML();

?>

See also: http://www.php.net/manual/en/libxml.constants.php

Note that libxml will detect that your DTD is locally available via /etc/xml/catalog. So there is no worry about this causing your DOM loads to make external network requests.
Jonas Due Vesterheden 09-Jun-2009 08:18
I had a problem with loading documents over HTTP. I would get errors looking like this:

Warning: DOMDocument::load(http://external/document.xml): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

The document would load fine in browsers and using wget. The problem is that DOMDocument::load() on my systems (both OS X and Linux) didn't send any User-Agent header which for some weird reason made Microsoft-IIS/6.0 respond with the 500 error.

The solution is found on http://php.net/manual/en/function.libxml-set-streams-context.php :

<?php
$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');
?>
syntaxiko 04-Apr-2009 10:16
Function will not work if using XML DOM PECL module
darren at viamedia dot co dot za 05-Aug-2008 07:17
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
the_N_Channel 15-Jul-2008 04:53
NOTE, will not load successfully if there is a comment at the beginning of the file before the <?xml version="1.0" ?> declaration!
hh dot lohmann at yahoo dot de 30-Aug-2007 03:48
BadGuy´s note may be confusing since what he depicts is no special property of the relevant method. PHP works always in and on a local file system which means that if you want to use resources from other systems or - what is, indeed, BadGuy´s problem - need resources that have been dealt with by other programs or processes, you have to state and manage that explicitly in your code. PHP is just a quite normal program in that.

BadGuy´s solution is using the "http wrapper" to get output from another process (see "wrappers" in the PHP manual). Doing this, the appropriate syntax for http calls has to be respected.
admin at tijnema dot tijnema dot info 02-Jun-2007 04:39
In reply to BadGuy [at] BadGuy [dot] nl

When the news.php file is located on the same server, like you said in the first example then http://my.beautiful-website.com/xmlsource/news.php wouldn't work, but you should use http://localhost/xmlsource/news.php or http://127.0.0.1/xmlsource/news.php
BadGuy [at] BadGuy [dot] nl 18-Jan-2007 08:50
Note that this method uses the local file system before doing anything remote. The 'disadvantage' would be that if you would do the following:
<?php
$xml = new DOMDocument;
$xml->load("xmlsource/news.php");
?>

This would not make the method read the actual output of the news.php file --presumably valid xml data--, but the file contents --obviously this would be php code. So this will return an error saying news.php is missing the xml declaration and maybe the xml start-tag

What would work is the following:

<?php
$xml = new DOMDocument;
$xml->load("http://my.beautiful-website.com/xmlsource/news.php");
?>

This will force a http request to be used to get this file instead of just locally reading it and the file just returning code
daevid at daevid dot com 18-Oct-2005 05:08
Suppose you wanted to dynamically load an array from an .XSD file. This method is your guy. just remember to use the actual xs: portion in xpaths and such.

All the other "load" methods will error out.

<?php
$attributes = array();
$xsdstring = "/htdocs/api/xsd/common.xsd";
$XSDDOC = new DOMDocument();
$XSDDOC->preserveWhiteSpace = false;
if ($XSDDOC->load($xsdstring))
{
    $xsdpath = new DOMXPath($XSDDOC);
    $attributeNodes =
              $xsdpath->
              query('//xs:simpleType[@name="attributeType"]')
              ->item(0);
    foreach ($attributeNodes->childNodes as $attr)
    {
        $attributes[ $attr->getAttribute('value') ] = $attr->getAttribute('name');
    }
    unset($xsdpath);
}
print_r($attributes);
?>
DOMDocument::importNode
DOMDocument::loadHTML
DOMDocument


Загрузка HTML из строки

DOMDocument::load
DOMDocument::loadHTMLFile
DOMDocument
PHP Manual

DOMDocument::loadHTML

(PHP 5)

DOMDocument::loadHTML — Загрузка HTML из строки

Описание

bool DOMDocument::loadHTML ( string $source )

Функция разбирает HTML содержащийся в строке source. В отличие от XML, HTML не обязан быть правильно построенным документом. Эта функция также может быть вызвана статически для загрузки и создания объекта класса DOMDocument. Статический вызов может использоваться в случаях, когда нет необходимости устанавливать значения параметров объекта DOMDocument до загрузки документа.

Список параметров

source

HTML строка.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. В случае статического вызова возвращает объект класса DOMDocument или FALSE в случае возникновения ошибки.

Ошибки

Если через аргумент source передана пустая строка, будет сгенерировано предупреждение. Это предупреждение генерируется не libxml, поэтому оно не может быть обработано библиотечными обработчиками ошибок.

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Несмотря на то, что некорректный HTML обычно успешно загружается, данная функция может генерировать ошибки уровня E_WARNING при обнаружении плохой разметки. Для обработки данных ошибок можно воспользоваться функциями обработки ошибок libxml.

Примеры

Пример #1 Создание документа

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

Смотрите также

  • DOMDocument::loadHTMLFile() - Загрузка HTML из файла
  • DOMDocument::saveHTML() - Сохраняет документ из внутреннего представления в строку, используя HTML форматирование
  • DOMDocument::saveHTMLFile() - Сохраняет документ из внутреннего представления в файл, используя HTML форматирование

User Contributed Notes

Alex 10-Apr-2010 08:45
Beware of the "gotcha" (works as designed but not as expected): if you use loadHTML, you cannot validate the document. Validation is only for XML. Details here: http://bugs.php.net/bug.php?id=43771&edit=1
Shane Harter 04-Jan-2010 08:42
DOMDocument is very good at dealing with imperfect markup, but it throws warnings all over the place when it does.

This isn't well documented here. The solution to this is to implement a separate aparatus for dealing with just these errors.

Set libxml_use_internal_errors(true) before calling loadHTML. This will prevent errors from bubbling up to your default error handler. And you can then get at them (if you desire) using other libxml error functions.

You can find more info here http://www.php.net/manual/en/ref.libxml.php
mdmitry at gmail dot com 21-Dec-2009 09:02
You can also load HTML as UTF-8 using this simple hack:

<?php

$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="UTF-8">' . $html);

// dirty fix
foreach ($doc->childNodes as $item)
    if ($item->nodeType == XML_PI_NODE)
        $doc->removeChild($item); // remove hack
$doc->encoding = 'UTF-8'; // insert proper

?>
piopier 14-Jun-2009 08:29
Here is a function I wrote to capitalize the previous remarks about charset problems (UTF-8...) when using loadHTML and then DOM functions.
It adds the charset meta tag just after <head> to improve automatic encoding detection, converts any specific character to an html entity, thus PHP DOM functions/attributes will return correct values.

<?php
mb_detect_order("ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
function loadNprepare($url,$encod='') {
        $content        = file_get_contents($url);
        if (!empty($content)) {
                if (empty($encod))
                        $encod  = mb_detect_encoding($content);
                $headpos        = mb_strpos($content,'<head>');
                if (FALSE=== $headpos)
                        $headpos= mb_strpos($content,'<HEAD>');
                if (FALSE!== $headpos) {
                        $headpos+=6;
                        $content = mb_substr($content,0,$headpos) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr($content,$headpos);
                }
                $content=mb_convert_encoding($content, 'HTML-ENTITIES', $encod);
        }
        $dom = new DomDocument;
        $res = $dom->loadHTML($content);
        if (!$res) return FALSE;
        return $dom;
}
?>

NB: it uses mb_strpos/mb_substr instead of mb_ereg_replace because that seemed more efficient with huge html pages.
Errol 11-Feb-2009 08:05
It should be noted that when any text is provided within the body tag
outside of a containing element, the DOMDocument will encapsulate that
text into a paragraph tag (<p>).

For example:
<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>Test<br></p>
<div>Text</div>
</body></html>

while:
<?php
$doc = new DOMDocument();
$doc->loadHTML(
    "<html><body><i>Test</i><br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<i>Test</i><br><div>Text</div>
</body></html>
jamesedwardcooke+php at gmail dot com 19-Oct-2008 11:37
Using loadHTML() automagically sets the doctype property of your DOMDocument instance(to the doctype in the html, or defaults to 4.0 Transitional). If you set the doctype with DOMImplementation it will be overridden.

I assumed it was possible to set it and then load html with the doctype I defined(in order to decide the doctype at runtime), and ran into a huge headache trying to find out where my doctype was going. Hopefully this helps someone else.
xuanbn at yahoo dot com 04-Oct-2007 01:38
If you use loadHTML() to process utf HTML string (eg in Vietnamese), you may experience result in garbage text, while some files were OK. Even your HTML already have meta charset  like

  <meta http-equiv="content-type" content="text/html; charset=utf-8">

I have discovered that, to help loadHTML() process utf file correctly, the meta tag should come first, before any utf string appear. For example, this HTML file

<html>
 <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title> Vietnamese - Tiếng Việt</title>
  </head>
<body></body>
</html>

will be OK with loadHTML() when <meta> tag appear <title> tag.

But the file below will not regcornize by loadHTML() because <title> tag contains utf string appear before <meta> tag.

<html>
 <head>
    <title> Vietnamese - Tiếng Việt</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
  </head>
<body></body>
</html>
hanhvansu at yahoo dot com 26-Apr-2007 08:50
When using loadHTML() to process UTF-8 pages, you may meet the problem that the output of dom functions are not like the input. For example, if you want to get "Cạnh tranh", you will receive "Cáº¡nh tranh".  I suggest we use mb_convert_encoding before load UTF-8 page :
<?php
    $pageDom = new DomDocument();
    $searchPage = mb_convert_encoding($htmlUTF8Page, 'HTML-ENTITIES', "UTF-8");
    @$pageDom->loadHTML($htmlUTF8Page);

?>
romain dot lalaut at laposte dot net 15-Feb-2007 08:31
Note that the elements of such document will have no namespace even with <html xmlns="http://www.w3.org/1999/xhtml">
bigtree at DONTSPAM dot 29a dot nl 26-Apr-2005 02:15
Pay attention when loading html that has a different charset than iso-8859-1. Since this method does not actively try to figure out what the html you are trying to load is encoded in (like most browsers do), you have to specify it in the html head. If, for instance, your html is in utf-8, make sure you have a meta tag in the html's head section:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>

If you do not specify the charset like this, all high-ascii bytes will be html-encoded. It is not enough to set the dom document you are loading the html in to UTF-8.
DOMDocument::load
DOMDocument::loadHTMLFile
DOMDocument


Загрузка HTML из файла

DOMDocument::loadHTML
DOMDocument::loadXML
DOMDocument
PHP Manual

DOMDocument::loadHTMLFile

(PHP 5)

DOMDocument::loadHTMLFile — Загрузка HTML из файла

Описание

bool DOMDocument::loadHTMLFile ( string $filename )

Функция разбирает HTML документ из файла filename. В отличие от загрузки XML, HTML документ не обязан быть правильно построенным.

Список параметров

filename

Путь к HTML файлу.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. Если вызвана статически, возвращает объект класса DOMDocument или FALSE в случае возникновения ошибки.

Ошибки

Если через аргумент filename передана пустая строка или файл ничего не содержит, будет сгенерировано предупреждение. Это предупреждение генерируется не libxml, поэтому оно не может быть обработано обработчиками ошибок библиотеки libxml.

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Несмотря на то, что некорректный HTML обычно успешно загружается, данная функция может генерировать ошибки уровня E_WARNING при обнаружении плохой разметки. Для обработки данных ошибок можно воспользоваться функциями обработки ошибок libxml.

Примеры

Пример #1 Создание документа

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Смотрите также

  • DOMDocument::loadHTML() - Загрузка HTML из строки
  • DOMDocument::saveHTML() - Сохраняет документ из внутреннего представления в строку, используя HTML форматирование
  • DOMDocument::saveHTMLFile() - Сохраняет документ из внутреннего представления в файл, используя HTML форматирование

User Contributed Notes

Mark Omohundro, ajamyajax dot com 28-Nov-2008 06:32
<?php
// try this html listing example for all nodes / includes a few getElementsByTagName options:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

// example 1:
$elements = $doc->getElementsByTagName('*');
// example 2:
$elements = $doc->getElementsByTagName('html');
// example 3:
//$elements = $doc->getElementsByTagName('body');
// example 4:
//$elements = $doc->getElementsByTagName('table');
// example 5:
//$elements = $doc->getElementsByTagName('div');

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>". $element->nodeName. ": ";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>
gzech at SPAMFILTER dot eso dot org 21-Feb-2007 02:09
If you want to suppress output warnings from loadHTMLFile($url), put an @ sign in front. This even works in:
<?php
$load = @$dom->loadHTMLFile($url);
?>
Lachlan Hunt 26-Sep-2005 11:15
Andy, the code you gave should not give that result.  In your code, $tag is an <a> element and the nodeValue of elements is null, according to the DOM2 spec.  You need to get at the text node first, before getting the node value.
<?
...
foreach ($tags as $tag) {
       echo $tag->getAttribute('href').' | '.$tag->childNodes->item(0)->nodeValue."\n";
}
?>

This should output:

/mypage1 | Hello World!
/mypage2 | Another Hello World!
andy at carobert dot com 25-May-2005 01:24
This puts the HTML into a DOM object which can be parsed by individual tags, attributes, etc..  Here is an example of getting all the 'href' attributes and corresponding node values out of the 'a' tag. Very cool....

<?php
$myhtml = <<<EOF
<html>
<head>
<title>My Page</title>
</head>
<body>
<p><a href="/mypage1">Hello World!</a></p>
<p><a href="/mypage2">Another Hello World!</a></p>
</body>
</html>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($myhtml);

$tags = $doc->getElementsByTagName('a');

foreach ($tags as $tag) {
       echo $tag->getAttribute('href').' | '.$tag->nodeValue."\n";
}
?>

This should output:

/mypage1 | Hello World!
/mypage2 | Another Hello World!
bens at effortlessis dot com 08-Apr-2005 05:11
Note that this function doesn't parse the individual tags WITHIN the html file - it's all loaded as a "black box", and you end up with an XML widget that comprises nothing but the complete chunk of HTML.

I was hoping it would function as a sort of HTML-validator/parser, but that doesn't seem to be the case.
DOMDocument::loadHTML
DOMDocument::loadXML
DOMDocument


Загрузка XML из строки

DOMDocument::loadHTMLFile
DOMDocument::normalizeDocument
DOMDocument
PHP Manual

DOMDocument::loadXML

(PHP 5)

DOMDocument::loadXML — Загрузка XML из строки

Описание

mixed DOMDocument::loadXML ( string $source [, int $options = 0 ] )

Загружает XML документ из строки.

Список параметров

source

Содержащая XML строка.

options

Побитовое ИЛИ констант настройки libxml.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. Если вызвана статически, возвращает объект класса DOMDocument или FALSE в случае возникновения ошибки.

Ошибки

Если через аргумент source передана пустая строка, будет сгенерировано предупреждение. Это предупреждение генерируется не libxml, поэтому оно не может быть обработано библиотечными обработчиками ошибок.

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Примеры

Пример #1 Создание документа

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Пример #2 Статический вызов loadXML

<?php
// Вызывает ошибку E_STRICT
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Смотрите также

  • DOMDocument::load() - Загрузка XML из файла
  • DOMDocument::save() - Сохраняет XML дерево из внутреннего представления в файл
  • DOMDocument::saveXML() - Сохраняет XML дерево из внутреннего представления в виде строки

User Contributed Notes

szalma dot laszlo at zengo dot eu 27-Oct-2009 08:14
Loading from a string works fine without the <?xml version="1.0" encoding="utf-8"?> header, but in this case the xmlEncoding won't be set, and this makes the utf-8 characters (international, and special characters) to be encoded as hexa entities when saved with saveXML()!
remacg 26-Feb-2009 07:33
Instead of doing this:

<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

simply use:

loadHTML() rather than loadXML().
olalonde at NOSPAM dot gmail dot com 21-Mar-2008 05:00
For some reason, when you set DOMDocument's property 'recover' to true, using '@' to mask errors thrown by loadXml() won't work.

Here's my workaround:

function maskErrors() {}
set_error_handler('maskErrors');
$dom->loadXml($xml);
restore_error_handler();

You could also simply do this: error_reporting(0); and then set back error_reporting to its original state.
Stuart Grimshaw 26-Jun-2007 01:57
Possible values for the options parameter can be found here:

http://us3.php.net/manual/en/ref.libxml.php#libxml.constants
Marc Liyanage 18-Jun-2007 07:08
The documentation states that loadXML can be called statically, but this is misleading. This feature seems to be a special case hack and its use seems to be discouraged according to http://bugs.php.net/bug.php?id=41398.

Calling the method statically will fail with an error if the code runs with E_STRICT error reporting enabled.

The documentation should be changed to make it clear that a static call is against recommended practice and won't work with E_STRICT.
gabriel dot birke at web dot de 03-May-2007 08:44
If you want to preserve greater-than and lower-than signs inside CDATA sections with XSL processing you have to use the LIBXML_NOCDATA option:

Given this XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output omit-xml-declaration="yes" />
<xsl:template match="/">
<script type="text/javascript">
<xsl:text disable-output-escaping="yes">
// Decorative Brackets:
<![CDATA[// <<<<>>>> ]]>
</xsl:text>
</script>
</xsl:template>
</xsl:stylesheet>

and this PHP:

<?php

$xml = new DOMDocument;
$xml->load('dummy.xml');

$xsl1 = new DOMDocument;
$xsl1->load('scripttest.xsl');

$xsl2 = new DOMDocument;
$xsl2->load('scripttest.xsl', LIBXML_NOCDATA);

$proc = new XSLTProcessor;

echo "Normal Load:\n";
$proc->importStyleSheet($xsl1);
echo $proc->transformToXML($xml);

echo "LIBXML_NOCDATA Load:\n";
$proc->importStyleSheet($xsl2);
echo $proc->transformToXML($xml);

?>

You get the following output:
Normal Load:
<script type="text/javascript">
// Decorative Brackets:
// &lt;&lt;&lt;&lt;&gt;&gt;&gt;&gt;
</script>
LIBXML_NOCDATA Load:
<script type="text/javascript">
// Decorative Brackets:
// <<<<>>>>
</script>
jazzslider at hotmail dot com 30-Apr-2007 01:14
When using loadXML() to parse a string that contains entity references (e.g., &nbsp;), be sure that those entity references are properly declared through the use of a DOCTYPE declaration; otherwise, loadXML() will not be able to interpret the string.

Example:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd1 = new DOMDocument();
$dd1->loadXML($str);

echo $dd1->saveXML();
?>

Given the above code, PHP will issue a Warning about the entity 'nbsp' not being properly declared.  Also, the call to saveXML() will return nothing but a trimmed-down version of the original processing instruction...everything else is gone, and all because of the undeclared entity.

Instead, explicitly declare the entity first:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

Since the 'nbsp' entity is defined in the DOCTYPE, PHP no longer issues that Warning; the string is now well-formed, and loadXML() understands it perfectly.

You can also use references to external DTDs in the same way (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">), which is particularly important if you need to do this for many different documents with many different possible entities.

Also, as a sidenote...entity references created by createEntityReference() do not need this kind of explicit declaration.
shaoyu73 at gmail dot com 15-Mar-2007 08:53
earth at anonymous dot com,

preserveWhiteSpace property needs to be set to false for formatOutput to work properly, for some reason.

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xmlStr);
...
$element->appendChild(...);
...
$dom->formatOutput = true;
$xmlStr = $dom->saveXML();
echo $xmlStr;

This would format the output nicely.
Gavin Sinai gsinai at gmx dot net 30-Aug-2006 07:34
loadXml reports an error instead of throwing an exception when the xml is not well formed. This is annoying if you are trying to to loadXml() in a try...catch statement. Apparently its a feature, not a bug, because this conforms to a spefication.

If you want to catch an exception instead of generating a report, you could do something like

<?php
function HandleXmlError($errno, $errstr, $errfile, $errline)
{
    if ($errno==E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0))
    {
        throw new DOMException($errstr);
    }
    else
        return false;
}

function XmlLoader($strXml)
{
    set_error_handler('HandleXmlError');
    $dom = new DOMDocument();
    $dom->loadXml($strXml);
    restore_error_handler();
    return $dom;
 }

?>

Returning false in function HandleXmlError() causes a fallback to the default error handler.
mp at webfactory dot de 08-Aug-2006 08:26
While loadXML() expects its input to have a leading XML processing instruction to deduce the encoding used, there's no such concept in (non-XML) HTML documents. Thus, the libxml library underlying the DOM functions peeks at the <META> tags to figure out the encoding used.

See http://xmlsoft.org/encoding.html.
earth at anonymous dot com 12-Apr-2006 02:28
Note that loadXML crops off beginning and trailing whitespace and linebreaks.

When using loadXML and appendChild to add a chunk of XML to an existing document, you may want to force a linebreak between the end of the XML chunk and the next line (usually a close tag) in the output file:

$childDocument = new DOMDocument;
$childDocument>preserveWhiteSpace = true;
$childDocument->loadXML(..XML-Chunk..);
$mNewNode = $mainDOcument->importNode($childDocument->documentElement, true);
$ParentNode->appendChild($mNewNode);
$ParentNode->appendChild($mainDocument->createTextNode("\\n  ");

Although it is said that DOM should not be used to make 'pretty' XML output, it is something I struggled with to get something that was readable for testing.  Another solution is to use the createDocumentFragment()->appendXML(..XML-Chunk..) instead, which seems not to trim off linebreaks like DOMDocument->loadXML() does.
primaryspace at hotmail dot com 09-Aug-2005 01:42
This method replaces any existing document tree already in the object with the document tree contained in the source argument.
DOMDocument::loadHTMLFile
DOMDocument::normalizeDocument
DOMDocument


Нормализует документ

DOMDocument::loadXML
DOMDocument::registerNodeClass
DOMDocument
PHP Manual

DOMDocument::normalizeDocument

(PHP 5)

DOMDocument::normalizeDocument — Нормализует документ

Описание

void DOMDocument::normalizeDocument ( void )

Этот метод выполняет те же действия, как если бы Вы сохранили и затем загрузили документ, приводит документ к "нормальной" форме.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • » Спецификация DOM
  • DOMNode::normalize() - Нормализует узел

User Contributed Notes

There are no user contributed notes for this page.
DOMDocument::loadXML
DOMDocument::registerNodeClass
DOMDocument


Регистрация расширенного класса, используемого для создания базового типа узлов

DOMDocument::normalizeDocument
DOMDocument::relaxNGValidate
DOMDocument
PHP Manual

DOMDocument::registerNodeClass

(PHP 5 >= 5.2.0)

DOMDocument::registerNodeClass — Регистрация расширенного класса, используемого для создания базового типа узлов

Описание

bool DOMDocument::registerNodeClass ( string $baseclass , string $extendedclass )

Этот метод позволяет зарегистрировать свой собственный расширенный DOM класс, чтобы впоследствии использовать его в PHP DOM расширении.

Этот метод не входит в стандарт DOM.

Список параметров

baseclass

DOM класс, который будет расширен. Список таких классов можно увидеть во введении.

extendedclass

Имя расширенного класса. Если передать NULL, будут удалены все ранее зарегистрированные классы, расширяющие данный базовый класс baseclass.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
PHP 5.2.2 | В версиях до 5.2.2 ранее зарегистрированный расширенный класс extendedclass должен быть исключен из регистрации, прежде чем регистрировать новый класс, расширяющий тот же базовый класс baseclass.

Примеры

Пример #1 Добавление нового метода в класс DOMElement для упрощения кода

<?php

class myElement extends DOMElement {
   function appendElement($name) {
      return $this->appendChild(new myElement($name));
   }
}

class myDocument extends DOMDocument {
   function setRoot($name) {
      return $this->appendChild(new myElement($name));
   }
}

$doc = new myDocument();
$doc->registerNodeClass('DOMElement', 'myElement');

// С этих пор добавление одного элемента к другому
// требует всего одного вызова метода!
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

Результат выполнения данного примера:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Пример #2 Извлечение элементов в виде пользовательского класса

<?php
class myElement extends DOMElement {
    public function __toString() {
        return $this->nodeValue;
    }
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// Воспользуемся __toString методом..
echo $element;
?>

Результат выполнения данного примера:

string(9) "myElement"
text in child

Пример #3 Получение имени документа-владельца узла

Когда создается экземпляр расширенного класса DOMDocument, свойство ownerDocument будет ссылаться на создаваемый объект. Это значит, что нет необходимости (а фактически это невозможно) использовать DOMDocument::registerNodeClass() применительно к DOMDocument.

<?php
class myDOMDocument extends DOMDocument {
}

class myOtherDOMDocument extends DOMDocument {
}

// Создаем myDOMDocument с некоторым XML содержимым
$doc = new myDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// Текущий владелец узла - myDOMDocument
var_dump(get_class($child->ownerDocument));

// Импортируем узел из myDOMDocument
$newdoc = new myOtherDOMDocument;
$child = $newdoc->importNode($child);

// Новый владелец узла изменился на myOtherDOMDocument
var_dump(get_class($child->ownerDocument));
?>

Результат выполнения данного примера:

string(13) "myDOMDocument"
string(18) "myOtherDOMDocument"

User Contributed Notes

crh3675 at gmail dot com 25-Sep-2009 08:23
Creating innerHTML and outerHTML

<?php

class DOMHTMLElement extends DOMElement
{
    function __construct() { parent::__construct();}

    public function innerHTML()
    {
        $doc = new DOMDocument();
      foreach ($this->childNodes as $child){
          $doc->appendChild($doc->importNode($child, true));
        }
        $content = $doc->saveHTML();
        return $content;
    }

    public function outerHTML()
    {
        $doc = new DOMDocument();
        $doc->appendChild($doc->importNode($this, true));
        $content = $doc->saveHTML();
        return $content;
    }
}

$dom = DOMDocument::loadHTMLFile($file);
$dom->registerNodeClass('DOMElement','DOMHTMLElement');

if($dom)
{
    $xpath = new DOMXpath($dom);
    $regions = $xpath->query("//*[contains(@class, 'editable')]");
    $content = '';

    foreach($regions as $region){
        $content .= $region->outerHTML();
    }

    return $content;

}else{
    throw new Exception('Cannot parse HTML.  Please verify the syntax is correct.');
}
?>
arnold at adaniels dot nl 22-Jul-2009 03:10
Note than save and saveXML are not affected by __toString().
DOMDocument::normalizeDocument
DOMDocument::relaxNGValidate
DOMDocument


Производит проверку документа на правильность построения посредством relaxNG

DOMDocument::registerNodeClass
DOMDocument::relaxNGValidateSource
DOMDocument
PHP Manual

DOMDocument::relaxNGValidate

(PHP 5)

DOMDocument::relaxNGValidate — Производит проверку документа на правильность построения посредством relaxNG

Описание

bool DOMDocument::relaxNGValidate ( string $filename )

Производит » relaxNG проверку документа, основываясь на заданной RNG схеме.

Список параметров

filename

RNG файл.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMDocument::relaxNGValidateSource() - Проверяет документ посредством relaxNG
  • DOMDocument::schemaValidate() - Проверяет действительности документа, основываясь на заданной схеме
  • DOMDocument::schemaValidateSource() - Проверяет действительность документа, основываясь на схеме
  • DOMDocument::validate() - Проверяет документ на соответствие его DTD

User Contributed Notes

mitchell dot beaumont at mitchellbeaumont dot com 26-Aug-2007 07:28
It's worth noting that when validation fails this function also triggers a warning.

You can suppress the warning using the set_error_handler and restore_error_handler functions.
DOMDocument::registerNodeClass
DOMDocument::relaxNGValidateSource
DOMDocument


Проверяет документ посредством relaxNG

DOMDocument::relaxNGValidate
DOMDocument::save
DOMDocument
PHP Manual

DOMDocument::relaxNGValidateSource

(PHP 5)

DOMDocument::relaxNGValidateSource — Проверяет документ посредством relaxNG

Описание

bool DOMDocument::relaxNGValidateSource ( string $source )

Применяет » relaxNG проверку документа на соответствие заданному RNG источнику.

Список параметров

source

Строка содержащая RNG схему.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMDocument::relaxNGValidate() - Производит проверку документа на правильность построения посредством relaxNG
  • DOMDocument::schemaValidate() - Проверяет действительности документа, основываясь на заданной схеме
  • DOMDocument::schemaValidateSource() - Проверяет действительность документа, основываясь на схеме
  • DOMDocument::validate() - Проверяет документ на соответствие его DTD

User Contributed Notes

gem at rellim dot com 12-Oct-2004 04:47
Took me a while to get a working example.  Here it is:

<?php

# enable warnings
ini_set( 'track_errors', 1);
ini_set('error_reporting', E_ALL | E_STRICT);

# this is a sample relaxNG definition
$rng = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<grammar ns="" xmlns="http://relaxng.org/ns/structure/1.0"
  datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
  <start>
    <element name="apple">
      <element name="pear">
        <data type="NCName"/>
      </element>
    </element>
  </start>
</grammar>
EOT;

# well formed xml, but invalid per schema
# too many pears
$bad_xml =<<<EOT
<?xml version="1.0"?>
<apple>
  <pear>Pear</pear>
  <pear>Pear</pear>
</apple>
EOT;

# well formed xml and valid per schema
$good_xml =<<<EOT
<?xml version="1.0"?>
<apple>
  <pear>Pear</pear>
</apple>
EOT;

# this function does the work, it tests the relaxNG in the string $rng
# against the xml in string $xml
Function relaxNG ( $xml, $rng ) {
        $dom_xml = new DomDocument;
        $dom_xml->loadXML($xml);

        if ( $dom_xml->relaxNGValidateSource ( $rng ) ) {
                echo "Good\n";
        } else {
                echo $php_errormsg . "\n";
        }
}

# test the good xml, will echo:
#    Good
relaxNG ($good_xml, $rng);

# test the bad xml, will echo:
#    Did not expect element pear there
relaxNG ($bad_xml, $rng);

?>

results:

Good
Did not expect element pear there
DOMDocument::relaxNGValidate
DOMDocument::save
DOMDocument


Сохраняет XML дерево из внутреннего представления в файл

DOMDocument::relaxNGValidateSource
DOMDocument::saveHTML
DOMDocument
PHP Manual

DOMDocument::save

(PHP 5)

DOMDocument::save — Сохраняет XML дерево из внутреннего представления в файл

Описание

int DOMDocument::save ( string $filename [, int $options ] )

Создает XML документ из DOM представления. Эту функцию обычно вызывают после построения нового DOM документа, как показано в примере ниже.

Список параметров

filename

Путь к файлу в который будет сохранен XML доумент.

options

Дополнительные настройки. На данный момент поддерживается только LIBXML_NOEMPTYTAG.

Возвращаемые значения

Возвращает число записанных байт или FALSE в случае ошибки.

Список изменений

Версия | Описание
5.1.0 | Добавлен аргумент options

Примеры

Пример #1 Сохранение DOM дерева в файл

<?php

$doc = new DOMDocument('1.0');
// мы хотим красивый вывод
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Записано: ' . $doc->save("/tmp/test.xml") . ' байт'; // Записано: 72 байт

?>

Смотрите также

  • DOMDocument::saveXML() - Сохраняет XML дерево из внутреннего представления в виде строки
  • DOMDocument::load() - Загрузка XML из файла
  • DOMDocument::loadXML() - Загрузка XML из строки

User Contributed Notes

ss at littlerain dot com 01-Feb-2009 12:05
In addition to:
DOMDocument->formatOutput = true
DOMDocument->preserveWhiteSpace = false

...you also have to ensure you don't add text nodes as siblings of element nodes, or formatOutput won't work.
chenel324 at gmail dot com 19-Oct-2008 06:38
It took me forever to discover that
DOMDocument->formatOutput = true
will only have an effect on documents that are loaded from disk if one also sets
DOMDocument->preserveWhiteSpace = false ....

Hope this saves somebody a headache.
jon at mysql dot com 02-Nov-2007 02:38
If you're working with an existing XML file that contains an entity definition with an external reference like this one:

[
  <!ENTITY % all.entities SYSTEM "all-entities.ent">
  %all.entities;
]>

Be warned that DOMDocument->save() will expand this to include all definitions in all referenced entities file(s) when it writes the file. In other words, the same section of your saved file would now look something like this:

<!ENTITY % all.entities SYSTEM "all-entities.ent">
<!--
  This file names all the entity files needed by .xml files in the
  current directory.  All ENTITY declarations should be given
  first, followed by references to the those entities.
--><!ENTITY % fixedchars.entities SYSTEM "../common/fixedchars.ent">
<!ENTITY % urls.entities SYSTEM "../refman-common/urls.ent">
<!ENTITY % phrases.entities SYSTEM "../common/phrases.ent">
<!ENTITY % ndb.entities SYSTEM "ndb.en.ent">
<!ENTITY minus "&#x2013;"><!-- 2013 is actually Unicode for ndash -->
<!ENTITY Oslash "&#216;">
<!ENTITY macr "&#175;">
<!ENTITY auml "&#228;">
[etc.]

I've not found a way to keep this from occurring.
siegparr at NOSPAM dot web dot de 07-Jul-2006 08:00
The XML parser converts the text of an XML document into UTF-8, even if you have set the character encoding of the XML, for example as a second parameter of the DOMDocument constructor. After parsing the XML with the load() command all its texts have been converted to UTF-8.

In case you append text nodes with special characters (e. g. Umlaut) to your XML document you should therefore use utf8_encode() with your text to convert it into UTF-8 before you append the text to the document. Otherwise you will get an error message like "output conversion failed due to conv error" at the save() command. See example below:

<?php
// Text to insert into XML below
$txt = "a text with special characters like 'ä', 'ß', 'Ü' etc.";

// Create Instance of DOMDocument
$dom =  new DOMDocument;
// Load XML file
// Was created before with DOMDocument('1.0', 'iso-8859-1')
$dom = $dom->load("file.xml");
// Find the parent node
$parent = $dom->documentElement;
// Create Instance of DomXPath
$xpath = new DomXPath($dom);
// new node will be inserted before this node
$next = $xpath->query("//parentnode/childnode");
// Create the new element
$new_elem = $dom->createElement('new_elem');
// Insert the new element
$parent->insertBefore($new_elem, $next->item(0));
// DOMXML = utf-8! (will be converted to iso-8859-1 only at 'save()')
// prevents error message "output conversion failed due to conv error" at 'save()'
$txt = utf8_encode($txt);
// Create new text node with utf-8 encoded string
$nodetext = $dom->createTextNode("$txt");
// Append text node to new element
$nodetext = $new_elem->appendChild($nodetext);
// save
$dom->save("file.xml");
?>

Hope this helps someone.

siegparr
DOMDocument::relaxNGValidateSource
DOMDocument::saveHTML
DOMDocument


Сохраняет документ из внутреннего представления в строку, используя HTML форматирование

DOMDocument::save
DOMDocument::saveHTMLFile
DOMDocument
PHP Manual

DOMDocument::saveHTML

(PHP 5)

DOMDocument::saveHTML — Сохраняет документ из внутреннего представления в строку, используя HTML форматирование

Описание

string DOMDocument::saveHTML ([ DOMNode $node = NULL ] )

Создает HTML документ из DOM представления. Эту функцию обычно вызывают после построения нового DOM документа, как показано в примере ниже.

Список параметров

node

Необязательный аргумент для вывода некоторого подмножества документа.

Возвращаемые значения

Возвращает HTML или FALSE в случае ошибки.

Список изменений

Версия | Описание
5.3.6 | Добавлен аргумент node.

Примеры

Пример #1 Сохранение HTML дерева в виде строки

<?php

$doc = new DOMDocument('1.0');

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('Это заголовок');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

Смотрите также

  • DOMDocument::saveHTMLFile() - Сохраняет документ из внутреннего представления в файл, используя HTML форматирование
  • DOMDocument::loadHTML() - Загрузка HTML из строки
  • DOMDocument::loadHTMLFile() - Загрузка HTML из файла

User Contributed Notes

mpeters at domblogger dot net 03-Nov-2011 12:27
There is not a <script /> problem.

When a script node does not have a child and it is dumped as XML, a self closing script node is proper. Any browser with XML support will do the right thing IF you send your document with the right mime type -- application/xhtml+xml

When you dump it via saveHTML() - the script node will not be self closing.

There is however a <source /> problem.

With the new html5 media tags, <source src="whatever"> is not closed in html - so when sending as html, do a preg_replace on the output of saveHTML() to get rid of the </source> tags which are invalid.
alvaro at demogracia dot com 29-Mar-2011 11:04
Since PHP/5.3.6, DOMDocument->saveHTML() accepts an optional DOMNode parameter similarly to DOMDocument->saveXML():

http://bugs.php.net/bug.php?id=39771
Yajo 24-Nov-2010 07:21
Another way to workaround the <script/> problem is putting a semicolon (;) inside the script element.
Anonymous 09-Feb-2010 07:52
If you want a simpler way to get around the <script> tag problem try:

<?php

  $script = $doc->createElement ('script');\
  // Creating an empty text node forces <script></script>
  $script->appendChild ($doc->createTextNode (''));
  $head->appendChild ($script);

?>
Anonymous 12-May-2009 07:35
To avoid script tags from being output as <script />, you can use the DOMDocumentFragment class:

<?php

$doc = new DOMDocument();
$doc -> loadXML($xmlstring);
$fragment = $doc->createDocumentFragment();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */
if($fragment->appendXML("<script type='text/javascript' src='$source'></script>") {
  $xpath = new DOMXpath($doc);
  $resultlist = $xpath->query("//*[local-name() = 'html']/*[local-name() = 'head']"); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
  foreach($resultlist as $headnode)  // insert the script tag
     $headnode->appendChild($fragment);
}
$doc->saveXML(); /* and our script tags will still be <script></script> */

?>
Bart Feenstra 18-Jan-2009 10:17
I am using this solution to prevent tags and the doctype from being added to the HTML string automatically:

<?php
$html = '<h1>Hello world!</h1>';
$html = '<div>' . $html . '</div>';
$doc = new DOMDocument;
$doc->loadHTML($html);
echo substr($doc->saveXML($doc->getElementsByTagName('div')->item(0)), 5, -6)

// Outputs: "<h1>Hello world!</h1>"
?>
m at hbblogs daught calm 18-Aug-2008 08:41
This method, as of 5.2.6, will automatically add <html><body> and <!DOCTYPE> tags to the document if they are missing, without asking whether you want them. In my application, I needed to use the DOM methods to manipulate just a fragment of html, so these tags were rather unhelpful.

Here's a simple hack to remove them in case, like me, all you wanted to do was perform a few operations on an HTML fragment.

$html_fragment = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
Anonymous 25-Apr-2008 08:15
<?php
function getDOMString($retNode) {
  if (!$retNode) return null;
  $retval = strtr($retNode-->ownerDocument->saveXML($retNode),
  array(
    '></area>' => ' />',
    '></base>' => ' />',
    '></basefont>' => ' />',
    '></br>' => ' />',
    '></col>' => ' />',
    '></frame>' => ' />',
    '></hr>' => ' />',
    '></img>' => ' />',
    '></input>' => ' />',
    '></isindex>' => ' />',
    '></link>' => ' />',
    '></meta>' => ' />',
    '></param>' => ' />',
    'default:' => '',
    // sometimes, you have to decode entities too...
    '&quot;' => '&#34;',
    '&amp;' =>  '&#38;',
    '&apos;' => '&#39;',
    '&lt;' =>   '&#60;',
    '&gt;' =>   '&#62;',
    '&nbsp;' => '&#160;',
    '&copy;' => '&#169;',
    '&laquo;' => '&#171;',
    '&reg;' =>   '&#174;',
    '&raquo;' => '&#187;',
    '&trade;' => '&#8482;'
  ));
  return $retval;
}
?>
mjaque at ilkebenson dot com 19-Feb-2008 11:34
DOMDocument->saveXML() doesn't generate a proper XHTML format either.

There is a problem with "script" empty elements. For example:

This will be the code generated by saveXML, with an empty script tag.

<html>
  <head>
    <script type="text/JavaScript" src="myScript.js"/>
  </head>
  <body>
    <p>I will not appear</p>
    <script type="text/JavaScript">
    alert("Not working");
    </script>
  </body>
</html>

I don't know if this is valid XHTML (W3C Validator doesn't complain), but both FF 2.0 and IE 6 will not render it properly. Both will use </script> as the closing tag for the first script causing js errors and ignoring in between elements.

You can post-process saveXML string in order to close empty tags with the following function:

<?php
    function cerrarTag($tag, $xml){
        $indice = 0;
        while ($indice< strlen($xml)){
            $pos = strpos($xml, "<$tag ", $indice);
            if ($pos){
                $posCierre = strpos($xml, ">", $pos);
                if ($xml[$posCierre-1] == "/"){
                    $xml = substr_replace($xml, "></$tag>", $posCierre-1, 2);
                }
                $indice = $posCierre;
            }
            else break;
        }
        return $xml;
    }
?>

At least script and select empty elements should be closed. This example shows how it can be used:

<?php
    define("CABECERA_XHTML", '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');

  $xhtml = $docXML->saveXML($docXML->documentElement);
  $xhtml = cerrarTag("script", $xhtml);
  $xhtml = cerrarTag("select", $xhtml);
  $xhtml = CABECERA_XHTML."\n".$xhtml;
  echo $xhtml;
?>
archanglmr at yahoo dot com 27-Nov-2007 03:28
If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you're reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

<?php
header('Content-Type: text/html; charset=iso-8859-1');
?>
xoplqox 20-Nov-2007 11:07
XHTML:

If the output is XHTML use the function saveXML().

Output example for saveHTML:

<select name="pet" size="3" multiple>
    <option selected>mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>

XHTML conform output using saveXML:

<select name="pet" size="3" multiple="multiple">
    <option selected="selected">mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>
tyson at clugg dot net 21-Apr-2005 05:44
<?php
// Using DOM to fix sloppy HTML.
// An example by Tyson Clugg <tyson@clugg.net>
//
// vim: syntax=php expandtab tabstop=2

function tidyHTML($buffer)
{
  // load our document into a DOM object
  $dom = @DOMDocument::loadHTML($buffer);
  // we want nice output
  $dom->formatOutput = true;
  return($dom->saveHTML());
}

// start output buffering, using our nice
// callback funtion to format the output.
ob_start("tidyHTML");

?>
<html>
<p>It's like comparing apples to oranges.
</html>
<?php

// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();

?>

The above code takes out sloppy HTML:
 <html>
 <p>It's like comparing apples to oranges.
 </html>

And cleans it up to the following:
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
 <html><body><p>It's like comparing apples to oranges.
 </p></body></html>
DOMDocument::save
DOMDocument::saveHTMLFile
DOMDocument


Сохраняет документ из внутреннего представления в файл, используя HTML форматирование

DOMDocument::saveHTML
DOMDocument::saveXML
DOMDocument
PHP Manual

DOMDocument::saveHTMLFile

(PHP 5)

DOMDocument::saveHTMLFile — Сохраняет документ из внутреннего представления в файл, используя HTML форматирование

Описание

int DOMDocument::saveHTMLFile ( string $filename )

Создает HTML документ из DOM представления. Эту функцию обычно вызывают после построения нового DOM документа, как показано в примере ниже.

Список параметров

filename

Путь к файлу, в который сохранится HTML документ.

Возвращаемые значения

Возвращает число записанных байт или FALSE в случае ошибки.

Примеры

Пример #1 Сохранение HTML дерева в файл

<?php

$doc = new DOMDocument('1.0');
// мы хотим красивый вывод
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('Это заголовок');
$text = $title->appendChild($text);

echo 'Записано: ' . $doc->saveHTMLFile("/tmp/test.html") . ' байт; // Записано: 129 байт

?>

Смотрите также

  • DOMDocument::saveHTML() - Сохраняет документ из внутреннего представления в строку, используя HTML форматирование
  • DOMDocument::loadHTML() - Загрузка HTML из строки
  • DOMDocument::loadHTMLFile() - Загрузка HTML из файла

User Contributed Notes

deep42thouSPAMght42 at y_a_h_o_o dot com 14-Jan-2011 03:46
I foolishly assumed that this function was equivalent to
<?php
file_put_contents($filename, $document->saveHTML());
?>
but there are differences in the generated HTML:
<?php
$doc = new DOMDocument();
$doc->loadHTML(
    '<html><head><title>Test</title></head><body></body></html>'
);
$doc->encoding = 'iso-8859-1';

echo $doc->saveHTML();
#<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#<html>
#<head><title>Test</title></head>
#<body></body>
#</html>

$doc->saveHTMLFile('output.html');
#<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Test</title></head><body></body></html>

?>
Note that saveHTMLFile() adds a UTF-8 meta tag despite the ISO-8859-1 document encoding.
DOMDocument::saveHTML
DOMDocument::saveXML
DOMDocument


Сохраняет XML дерево из внутреннего представления в виде строки

DOMDocument::saveHTMLFile
DOMDocument::schemaValidate
DOMDocument
PHP Manual

DOMDocument::saveXML

(PHP 5)

DOMDocument::saveXML — Сохраняет XML дерево из внутреннего представления в виде строки

Описание

string DOMDocument::saveXML ([ DOMNode $node [, int $options ]] )

Создает XML документ из DOM представления. Эту функцию обычно вызывают после построения нового DOM документа, как показано в примере ниже.

Список параметров

node

Используйте этот аргумент для вывода только определенного узла без XML объявления вместо вывода документа целиком.

options

Дополнительные настройки. На данный момент поддерживается только LIBXML_NOEMPTYTAG.

Возвращаемые значения

Возвращает XML или FALSE в случае ошибки.

Ошибки

DOM_WRONG_DOCUMENT_ERR

Возникает, если node принадлежит другому документу.

Список изменений

Версия | Описание
5.1.0 | Добавлен аргумент options

Примеры

Пример #1 Сохранение DOM дерева в виде строки

<?php

$doc = new DOMDocument('1.0');
// мы хотим красивый вывод
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('Это заголовок');
$text = $title->appendChild($text);

echo "Сохранение всего документа:\n";
echo $doc->saveXML() . "\n";

echo "Сохранение только заголовка:\n";
echo $doc->saveXML($title);

?>

Результат выполнения данного примера:

Сохранение всего документа:
<?xml version="1.0"?>
<book>
  <title>Это заголовок</title>
</book>

Сохранение только заголовка:
<title>Это заголовок</title>

Смотрите также

  • DOMDocument::save() - Сохраняет XML дерево из внутреннего представления в файл
  • DOMDocument::load() - Загрузка XML из файла
  • DOMDocument::loadXML() - Загрузка XML из строки

User Contributed Notes

_ michael 19-Apr-2010 11:30
If your data is UTF-8-encoded and you discover that saveXML() turned all non-ASCII characters into numeric entities (e.g. ä -> &#xF6;):

Chances are that the XML declaration has been missing when you loaded the source data. Try adding <?xml version="1.0" encoding="UTF-8"?> to the beginning of the document before you read it with load() or loadXML(). Then the non-ASCII characters should remain untouched. Worked for me.
samstah at gmail dot com 19-Mar-2010 03:56
We discovered using DOMDocument::saveHTML() that it converts to HTML 4.01 compatible markup; rather than XHTML. The simple answer is to use saveXML() instead, although this adds the XML declaration to the top.

To qjerry.com at gmail.com, thanks for the pointer below - but I think that the simplest way seems to be using:
<?php $domDocument->saveXML($domDocument->documentElement); ?>

Of course, if you're dealing with XHTML, this will strip any <!DOCTYPE> declarations in the document too.
mdmitry at gmail dot com 21-Dec-2009 09:21
If you use saveXML($node) to save a part of an HTML document, you may want to use this function to make empty tags more HTML-compatible:

<?php

function xml2xhtml($xml) {
    return preg_replace_callback('#<(\w+)([^>]*)\s*/>#s', create_function('$m', '
        $xhtml_tags = array("br", "hr", "input", "frame", "img", "area", "link", "col", "base", "basefont", "param");
        return in_array($m[1], $xhtml_tags) ? "<$m[1]$m[2] />" : "<$m[1]$m[2]></$m[1]>";
    '), $xml);
}

?>

example:

<?php

$doc = new DOMDocument();
$doc->loadHTML('<div class="clear"></div><br><p></p>');
$output = $doc->saveXML($doc->documentElement);

echo $output;
// output: <html><body><div class="clear"/><br/><p/></body></html>
echo xml2xhtml($output);
// output: <html><body><div class="clear"></div><br /><p></p></body></html>

?>
qjerry.com at gmail.com 04-May-2009 04:24
The simpliest (and probably the fastest) way to strip an XML declaration (<?xml version="1.0" ... ?>) out of output document, is to output child nodes of DOMDocument separately:

<?php

$document = new DOMDocument();
$document->load('/some/file.xml');

// this will also output doctype and comments at top level
foreach($document->childNodes as $node)
    $result .= $document->saveXML($node)."\n";

echo $result;

?>

This might be userful when dealing with browser compatibility issues, for example, well known problem with valid XHTML in IE6.
vikramvmalhotra at hotmail dot com 27-Jan-2009 03:49
if you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. It will spit out the characters converted in encoded format.

<?php
$str = domdoc->saveXML(); // gives "&x#1245;" some encoded data
?>

Instead do the following

<?php
$str = domdoc->saveXML(domdoc->documentElement); // gives "保存しました" correct multi-byte data
?>
php_dev at cyane dot nl 04-Nov-2008 02:28
Since PHP Version 5.2.6, this function spits out an utf-8 encoded string, regardless of the xml encoding, in my case Latin1.
I had to alter my class with
 $str=utf8_decode($doc->saveXML())
to fix a huge problem with all the sites on my server that make use of DOM.

These things did NOT fix it:
$encoding="Latin1"; // or ISO... whatever
$doc = new DOMDocument("1.0",$encoding);
$doc->encoding=$encoding;
shinsh at shinmugen dot net 23-May-2008 07:57
Be careful, this function has been changed in 5.2.6 version. Adding a required parameter which is not that required wasn't the most intelligent idea ever, especially for a function which is often used.

To fix your programs if you have an error, fill the first parameter like this:

$dom->saveXML($dom->documentElement);

Why didn't the devs simply implement this as optional parameter, fixing the default parameter as documentElement?
Kriogen 26-Dec-2007 12:57
Create before test.xml with:
<?xml version="1.0" encoding="utf-8"?>
<Photos>
</Photos>

and past after in your php-file:

<?php
$simp = simplexml_load_file('test.xml');
$node = $simp->addChild('home');
$node->addChild('mychild', 'insert text');
$s = simplexml_import_dom($simp);
$s->saveXML('test.xml');
?>

This code creating a child-nod in the root.
Owner http://www.mensfashion.ru
JITR 02-Aug-2007 05:10
Comment to `devin at SPAMISBAD dot tritarget dot com''s post:

Thanks for pointing out the pitfalls of `formatOutput' vs. `load*()'. This has certainly saved me from some possible surprises.

I think the seemingly strange behaviour can be explained. Warning: The following stuff is mostly based on deductions and experiments. Much less on studying the sources and specs (I'm not sure some of these would provide answer anyway, at least not easily).

As you point out, `preserveWhiteSpace' must be set before loading the DOM from the source string (I'm working with `loadXML()' but I believe the situation should be the same with `load()' you used). This looks logical, as this property seems to control the parsing and DOM creation process during which text nodes containing the whitespace are either included or dropped. This can be proven by dumping the DOM structure and comparing the results based on the value of `preserveWhiteSpace'. With `preserveWhiteSpace' set to `FALSE', no text nodes containing whitespace will be present in the returned DOM. When this property is `TRUE', these nodes will be present.

Note: When speaking about the whitespace in the previous paragraph, we're most certainly speaking about so called `whitespace in element content' or `element content whitespace', if I'm not mistaken. See also my comment in the notes of `DOMText->isWhitespaceInElementContent()' method.

As for the mysterious effect on the output of `saveXLM()', I think the explanation lies in the presence or absence of the above mentioned whitespace text nodes. This was also proven by experiments: After adding such a node into a DOM which contained none (the DOM was created using `loadXML()' with `preserveWhiteSpace' set to `FALSE'), the output formatting got affected in a such a way, the formatting got lost for the rest of the document after the added node. I think the presence of whitespace text nodes forces such rendering, that the content of these nodes is used to separate adjoining nodes thus disabling default formatting. Only when there are no such text nodes present, the ouput formatting takes effect (provided the `formatOutput' is set to `TRUE', of course).

Well, the thing I don't really understand is how you did get an output of a signle line with `formatOutput' set to `TRUE'. This has happened to me when no whitespace text nodes were present (ie. when loading the XML with `preserveWhiteSpace' set to `FALSE') *and* with `formatOutput' set to *`FALSE'* (with the opposite value of `formatOutput', the formatting should do it's work and you should not end up with just one line). But I haven't seen your source. Perhaps you had whitespace nodes containing no new-lines in your DOM?

As for the CAUTION about root element, I didn't see any problems with empty root element neither in shortened nor full form. What did you have in mind, when you said it `WORKS' or `DOES NOT WORK'?
Sander 25-Apr-2007 05:35
Note that for large DOM trees (tens of thousands of elements nested at least a few levels deep), setting formatOutput to true drives up memory usage to rather insane levels when you call saveXML(). (Tested with PHP 5.2.1) Pretty output is not worth that cost.
nevyn at NOSPAM dot email dot PLEASE dot it 27-Dec-2006 01:41
A little function to get the full xml contents of a Xml node.

function innerXml($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<(\\w*)(?:\\s*\\w+=(?:\"[^\"]*\"|\'[^\']*\'))*\\s*>(.*)</\\1>$}";
    preg_match($re, $out, $mat);
    return $mat[2];
}
devin at SPAMISBAD dot tritarget dot com 14-Aug-2006 10:52
It took some searching to figure this one out. I didn't see much in the way of explaining this glitch in the manual thus far. (For PHP5 I believe)

formatOutput = true; appears to fail when the origin of the DOM came from a file via load(). EX:

<?php
    $dom = new DOMDocument();
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

Will not indent the output and will display the modified nodes all in one long line. Makes for editing a config.xml a bit difficult when saving to a file.

By adding the preserveWhiteSpace = false; BEFORE the load() the formatOutput works as expected. EX:

<?php
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

CAUTION: If your loaded xml file (test.xml) has an empty root node that is not shortened or has no children this will NOT work.

Example:

DOES NOT WORK:
<?xml version="1.0"?>
<root>
</root>

WORKS:
<?xml version="1.0"?>
<root/>

WORKS:
<?xml version="1.0"?>
<root>
  <!-- comment -->
</root>

WORKS:
<?xml version="1.0"?>
<root>
  <child/>
</root>
26-Mar-2006 04:20
I used the function posted by "joe" but the following works to me for get the innerXML
<?php
$itemLeido = $XMLRespuesta->getElementsByTagName("articulos");
foreach($itemLeido as $node) {
    echo($node->ownerDocument->saveXML($node));
}
?>
mswiercz at mwerk dot com 10-Sep-2004 03:43
Quick tip to minimize memory when generating documents with DOM.

Rather than using
   $xmlStr = DOMDocument->saveXML();
   echo $xmlStr;

to dump a large DOM to the output buffer, use a PHP output stream, as in

   DOMDocument->save('php://output');

A lot of memory will be saved when generating large DOMs.
padys at tlen dot pl 05-Aug-2004 07:36
When you save whole document:
DOMDocument->saveXML() produces string in encoding defined in property DOMDocument->encoding.

When you save only one node:
DOMDocument->saveXML(DOMNode) produces always string in UTF-8.
DOMDocument::saveHTMLFile
DOMDocument::schemaValidate
DOMDocument


Проверяет действительности документа, основываясь на заданной схеме

DOMDocument::saveXML
DOMDocument::schemaValidateSource
DOMDocument
PHP Manual

DOMDocument::schemaValidate

(PHP 5)

DOMDocument::schemaValidate — Проверяет действительности документа, основываясь на заданной схеме

Описание

bool DOMDocument::schemaValidate ( string $filename )

Проверяет документ на действительность, основываясь на заданной схеме.

Список параметров

filename

Путь к файлу со схемой.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMDocument::schemaValidateSource() - Проверяет действительность документа, основываясь на схеме
  • DOMDocument::relaxNGValidate() - Производит проверку документа на правильность построения посредством relaxNG
  • DOMDocument::relaxNGValidateSource() - Проверяет документ посредством relaxNG
  • DOMDocument::validate() - Проверяет документ на соответствие его DTD

User Contributed Notes

charles at stickyid dot com 13-Jan-2011 12:35
If you prefer to load an XML string rather than an XML file, use $dom->loadXML($tempFile) instead of $tempDom->load($tempFile)

Reference:
http://www.php.net/manual/en/domdocument.loadxml.php
wkoehler at ce-gmbh dot com 11-Jan-2011 02:37
In older versions of PHP5 this function might cause error messages when dealing with namespaces. I had problems with PHP 5.2.14 which comes with libXML V2.6.16. After switching to PHP 5.3.5 with libXML V2.7.7 I no longer had problems. Took me only about 30 hrs to figure that one out.
NetPanther 27-Mar-2009 01:42
Initial situation:
- Debian Lenny
- Apache 2 with PHP 5.2.6
- libxml 2.6.32

Problem: While trying to validate a manually created (!) DOMDocument against an existing XML Schema, I ran into a warning like the one below. Validation fails, even though the document IS valid and the command line tool xmllint confirms this (even with libxml 2.6.32, so this must be a problem with DOM). The validation works fine with libxml 2.7.3.

Warning: DOMDocument::schemaValidate() [domdocument.schemavalidate]: Element 'YourRootElementName': No matching global declaration available for the validation root. in /var/www/YourFile.php on line X

Solution: As libxml 2.7.3 is not provided for Debian Lenny yet and this problem seems to be caused by DOM (s.o.), I currently use the following workaround on my machines. DOM obviously has some namespace problems with documents, that have been created manually (i.e. they were not loaded from a file).

So my workaround is saving the DOMDocument temporarily, re-loading it and then validating the temporary DOMDocument. Strangely enough the validation of the same document (= same content) now works. Sure, creating a temporary file is not a nice solution, but unless this bug is fixed, this workaround should do just fine.

<?php

// Works with libxml 2.7.3 and higher.
public function isValid()
{
  return $this->dom->schemaValidate('schema.xsd');
}

// Workaround for prior libxml versions, e.g. 2.6.32.
public function isValid()
{
  // Create temporary file and save manually created DOMDocument.
  $tempFile = time() . '-' . rand() . '-document.tmp';
  $this->dom->save($tempFile);

  // Create temporary DOMDocument and re-load content from file.
  $tempDom = new DOMDocument();
  $tempDom->load($tempFile);

  // Delete temporary file.
  if (is_file($tempFile))
  {
    unlink($tempFile);
  }

  // Validate temporary DOMDocument.
  return $tempDom->schemaValidate('schema.xsd');
}

?>
poletto at jeuxvideo dot com 13-Feb-2008 12:32
I had a tricky issue using this method, i thought it was bug but i realized i misundestood something about namespaces.
When you want to use a schema to describe an xml document, you basically put the default namespace to a personnal namespace (and you refer to this namespace in the targetNamespace attribute of your schema).

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://my.uri.net">
  <elt>
    <x>blabla</x>
    <y>blabla</y>
  </elt>
</root>

That xmlns attribute specifies a "default namespace" and means that the root element and its children are in this namespace.
What i misunderstood is that, there's no way with the DOM api to specify a "default namespace" for each children of the root element.
Thus you may need to use createElementNS() and createAttributeNS() methods for each created element or attribute in the document specifying the URI of your namespace each time ("http://my.uri.net").

This only applies if you want to validate a document built with the API, not with a document loaded from an xml file or stream.
nevyn at NOSPAM dot email dot it 18-Dec-2006 05:41
I've seen that trying to validate an XML with a schema containing keys, they were ignored, and the XML was considered still valid altough it contained duplicate keys.
justin at redwiredesign dot com 08-Nov-2006 03:32
In his previous comment, Mike A wrote about validating documents using an XSD. However, you can validate without one. In my case, I needed to ensure that the content entered was just valid XML or not, and I couldn't find an XSD to support that. So I wrote this:

public static function validate($xml)
{
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();
    if (empty($errors))
    {
        return true;
    }

    $error = $errors[0];
    if ($error->level < 3)
    {
        return true;
    }

    $lines = explode("\r", $xml);
    $line = $lines[($error->line)-1];

    $message = $error->message.' at line '.$error->line.':<br />'.htmlentities($line);

    return $message;
}

The catch here is that the function only checks for the first error is LIBXML_ERR_FATAL, which would break XSL/XML compilation.

In my experience, the errors are returned by libxml_get_errors in descending severity, so this may be an OK thing to do.
Mike A. 17-Feb-2006 12:03
For more detailed feedback from DOMDocument::schemaValidate, disable libxml errors and fetch error information yourself.  See http://php.net/manual/en/ref.libxml.php for more info.

example.xml
<?xml version="1.0"?>
<example>
    <child_string>This is an example.</child_string>
    <child_integer>Error condition.</child_integer>
</example>

example.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
    <xs:element name="example">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child_string" type="xs:string"/>
                <xs:element name="child_integer" type="xs:integer"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

<?php

function libxml_display_error($error)
{
    $return = "<br/>\n";
    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "<b>Warning $error->code</b>: ";
            break;
        case LIBXML_ERR_ERROR:
            $return .= "<b>Error $error->code</b>: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "<b>Fatal Error $error->code</b>: ";
            break;
    }
    $return .= trim($error->message);
    if ($error->file) {
        $return .=    " in <b>$error->file</b>";
    }
    $return .= " on line <b>$error->line</b>\n";

    return $return;
}

function libxml_display_errors() {
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        print libxml_display_error($error);
    }
    libxml_clear_errors();
}

// Enable user error handling
libxml_use_internal_errors(true);

$xml = new DOMDocument();
$xml->load('example.xml');

if (!$xml->schemaValidate('example.xsd')) {
    print '<b>DOMDocument::schemaValidate() Generated Errors!</b>';
    libxml_display_errors();
}

?>

Old error message:
Warning: DOMDocument::schemaValidate() [function.schemaValidate]: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.php on line 40

New error message:
DOMDocument::schemaValidate() Generated Errors!
Error 1824: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.xml on line 4
DOMDocument::saveXML
DOMDocument::schemaValidateSource
DOMDocument


Проверяет действительность документа, основываясь на схеме

DOMDocument::schemaValidate
DOMDocument::validate
DOMDocument
PHP Manual

DOMDocument::schemaValidateSource

(PHP 5)

DOMDocument::schemaValidateSource — Проверяет действительность документа, основываясь на схеме

Описание

bool DOMDocument::schemaValidateSource ( string $source )

Проверяет соответствие документа переданной через строку схеме.

Список параметров

source

Строка содержащая схему.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMDocument::schemaValidate() - Проверяет действительности документа, основываясь на заданной схеме
  • DOMDocument::relaxNGValidate() - Производит проверку документа на правильность построения посредством relaxNG
  • DOMDocument::relaxNGValidateSource() - Проверяет документ посредством relaxNG
  • DOMDocument::validate() - Проверяет документ на соответствие его DTD

User Contributed Notes

There are no user contributed notes for this page.
DOMDocument::schemaValidate
DOMDocument::validate
DOMDocument


Проверяет документ на соответствие его DTD

DOMDocument::schemaValidateSource
DOMDocument::xinclude
DOMDocument
PHP Manual

DOMDocument::validate

(PHP 5)

DOMDocument::validate — Проверяет документ на соответствие его DTD

Описание

bool DOMDocument::validate ( void )

Проверяет документ на действительность, основываясь на его DTD.

Также можно использовать свойство validateOnParse класса DOMDocument для проведения DTD проверки.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. Если нет DTD, присоединенных к документу, этот метод вернет FALSE.

Примеры

Пример #1 Пример DTD проверки

<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
    echo "Документ является действительным!\n";
}
?>

Также можно проверять XML файл на этапе его загрузки:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->Load('book.xml');
?>

Смотрите также

  • DOMDocument::schemaValidate() - Проверяет действительности документа, основываясь на заданной схеме
  • DOMDocument::schemaValidateSource() - Проверяет действительность документа, основываясь на схеме
  • DOMDocument::relaxNGValidate() - Производит проверку документа на правильность построения посредством relaxNG
  • DOMDocument::relaxNGValidateSource() - Проверяет документ посредством relaxNG

User Contributed Notes

cabral dot brc at gmail dot com 08-Sep-2010 12:46
I was trying to validate my SVG file just to get the IDs with getElementById(),

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text id="text_titulo" x="150" y="20" font-family="Arial" font-size="15px" style="font-weight:bold;">Title</text>
<text id="text_subtitulo" x="200" y="35" font-family="Arial" font-size="10px">Sub Title</text>
<g transform="translate(0,50) scale(0.1)">
  <a id="a_AC" ...... >
    <polygon id="polygon_AC" ....... />
  </a>
</g>
</svg>

but when calling $dom->load(), it was getting the errors "failed to open stream" and "Validation failed: no DTD found !I/O warning : failed to load external entity"
so I created my own validation wrapper (I just want to find the IDs with getElementById() )

<?php
  $docSVG = new DOMDocument();
  $docSVG->load(realpath($filepath));
  setAllId($docSVG);

function setAllId($DOMNode){
  if($DOMNode->hasChildNodes()){
    foreach ($DOMNode->childNodes as $DOMElement) {
      if($DOMElement->hasAttributes()){
        $id=$DOMElement->getAttribute("id");
        if($id){
          $DOMElement->setIdAttribute("id",$id);
        }
      }
      setAllId($DOMElement);
    }
  }
}
?>
a dot schaffhirt at sedna-soft dot de 17-Sep-2008 02:22
When validating documents with this method there are two issues I don't like about it. First, it creates a bunch of warnings, which one would not expect, as the plot of calling this method is preventing any warnings that could occur when erroneously relying on the document's validity. Second, it only returns a boolean with no chance of getting additional details about the reasons for rendering invalid.

That's the reason for me to use a little wrapper, which I post here in case anyone finds it useful.

Please note that it only works with PHP5 or later.

<?php
    class MyDOMDocument {
        private $_delegate;
        private $_validationErrors;

        public function __construct (DOMDocument $pDocument) {
            $this->_delegate = $pDocument;
            $this->_validationErrors = array();
        }

        public function __call ($pMethodName, $pArgs) {
            if ($pMethodName == "validate") {
                $eh = set_error_handler(array($this, "onValidateError"));
                $rv = $this->_delegate->validate();
                if ($eh) {
                    set_error_handler($eh);
                }
                return $rv;
            }
            else {
                return call_user_func_array(array($this->_delegate, $pMethodName), $pArgs);
            }
        }
        public function __get ($pMemberName) {
            if ($pMemberName == "errors") {
                return $this->_validationErrors;
            }
            else {
                return $this->_delegate->$pMemberName;
            }
        }
        public function __set ($pMemberName, $pValue) {
            $this->_delegate->$pMemberName = $pValue;
        }
        public function onValidateError ($pNo, $pString, $pFile = null, $pLine = null, $pContext = null) {
            $this->_validationErrors[] = preg_replace("/^.+: */", "", $pString);
        }
    }
?>

<?php
    // $doc is a DOMDocument object
    $myDoc = new MyDOMDocument($doc); // copy constructor

    // do anything with $myDoc that you would with $doc

    $isValid = $myDoc->validate(); // won't create warnings
    if (!$isValid) {
        print_r($myDoc->errors); // the array all warnings are collected in
    }
?>

Maybe you need to change the the part
preg_replace("/^.+: */", "", $pString)
to something different depending on your system's error reporting settings (HTML or plain text), whatsoever

Best Regards,

Anja
darren at viamedia dot co dot za 05-Aug-2008 07:19
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
DOMDocument::schemaValidateSource
DOMDocument::xinclude
DOMDocument


Проводит вставку XInclude разделов в объектах DOMDocument

DOMDocument::validate
DOMDocumentFragment
DOMDocument
PHP Manual

DOMDocument::xinclude

(PHP 5)

DOMDocument::xinclude — Проводит вставку XInclude разделов в объектах DOMDocument

Описание

int DOMDocument::xinclude ([ int $options ] )

Этот метод вставляет » XInclude блоки в объекте класса DOMDocument.

Замечание:

Вследствие того, что libxml2 автоматически разрешает сущности, вызов этого метода приведет к неожидаемым результатам в случае, когда XML файл содержит прикрепленную схему DTD.

Список параметров

options

параметры libxml. Доступно, начиная с PHP 5.1.0 и Libxml 2.6.7.

Возвращаемые значения

Возвращает количество блоков XInclude в документе, -1 если при обработке произошла ошибка, либо FALSE, если не было произведено ни одной замены.

Примеры

Пример #1 Пример использования DOMDocument::xinclude()

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
 <title>Books of the other guy..</title>
 <para>
  <xi:include href="book.xml">
   <xi:fallback>
    <error>xinclude: book.xml not found</error>
   </xi:fallback>
  </xi:include>
 </para>
</chapter>
EOD;

$dom = new DOMDocument;

// Оформим вывод красиво
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// загрузка XML строки, определенной выше
$dom->loadXML($xml);

// вставка блока xinclude
$dom->xinclude();

echo $dom->saveXML();

?>

Результатом выполнения данного примера будет что-то подобное:

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

User Contributed Notes

nicolas_rainardNOSPAM at yahoo dot fr 12-Jul-2007 04:56
If you use the loadXML() method instead of the load() one (let's say, to process the XML string before loading and parsing it), you will have problems with xinclude(), because the parser will not know where to find the files to include.
Using chdir() before xinclude() will not help.

The solution is to set the documentURI property of the DOMDocument object accordingly to it's original filename, and everything will work fine !

<?php

$xml = file_get_contents($file);
$xml = do_something_with($xml);

$doc = new DOMDocument;
$doc->documentURI = $file;
$doc->loadXML($xml);
$doc->xinclude();

?>
DOMDocument::validate
DOMDocumentFragment
DOMDocument


Класс DOMDocumentFragment

(PHP 5)

Обзор классов

DOMDocumentFragment extends DOMNode {
/* Свойства */
/* Методы */
bool appendXML ( string $data )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Содержание

  • DOMDocumentFragment::appendXML — Добавление необработанных XML данных

User Contributed Notes

Ricki 29-Mar-2011 06:00
DOMDocumentFragment only appears useful if created from a parent DOMDocument eg.

1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = $dom->createDocumentFragment();
3. Now append items to $docFrag
4. Graft $docFrag contents back onto $dom at the desired location

Conversely taking this approach:
1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = new DOMDocumentFragment();
3. Now append items to $docFrag

...will fail on step 3 with a "read only" error as $docFrag is not created as a child of  DOMDocument.

I'm not sure of the reason for this: on the web people have cited security, and others have cited poor design however whatever the reason, it is really limiting when wanting to encapsulating generic independent DocumentFragments into classes for easy grafting to the desired tree. The only workarounds i have seen look expensive from a performance perspective and cumbersome from a coding perspective ie. create a  dummy $dom for temporary use.

(This is valid as of PHP 5.3) I've put this here as i've wasted a lot of time finding it out - I hope this saves others some heartache.

Using new DOMDocumentFramt
matthijs at stdin dot nl 29-Mar-2011 03:06
Note that DOMDocumentFragment is a bit special when it's added to another node. When that happens, not the fragment itself is added as a child, but all of the children of the fragment are moved over to the new parent node.

For example, consider this script:

<?php

/* Create a document and a fragment containing a single node */
$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement('foo'));

/* Now, the foo node is a child of the fragment */
var_dump($fragment->firstChild);

/* After appending the fragment to another node, the children of the
 * fragment will have been transfered to that node (and the fragment is
 * not present in the children list!) */
$doc->appendChild($fragment);
/* So the fragment has no children anymore */
var_dump($fragment->firstChild);
/* But $doc has a single child, which is the foo element, not the
 * fragment */
var_dump($doc->childNodes->length);
var_dump($doc->firstChild);

?>

This produces the following output:

object(DOMElement)#3 (0) {
}
NULL
int(1)
object(DOMElement)#3 (0) {
}
mary dot kalinosky at thieme dot com 12-Aug-2009 03:43
I found DOMDocument very useful for extracting raw XML from a field in a MySQL database.

The following always gave me character entities for the XML tag brackets (&lt; &gt;) in the output (whether I used the utf8_encode function or htmlspecialchars function or neither of them on $row['text']):

<?php
$next_elem = $doc->createElement( $row['node_type'], utf8_encode($row['text']) );
$section_elem->appendChild($next_elem);
?>

I changed the code to use a DOMDocumentFragment and now the XML I stored in my database comes out as XML in my output with proper tag brackets instead of html character entities:

<?php
$next_elem = $doc->createDocumentFragment();
$next_elem->appendXML($row['text']);
$section_elem->appendChild($next_elem);
?>
DOMDocument::xinclude
DOMDocumentFragment::appendXML
DOM


Добавление необработанных XML данных

DOMDocumentFragment
DOMDocumentType
DOMDocumentFragment
PHP Manual

DOMDocumentFragment::appendXML

(PHP 5 >= 5.1.0)

DOMDocumentFragment::appendXML — Добавление необработанных XML данных

Описание

bool DOMDocumentFragment::appendXML ( string $data )

Добавляет необработанные XML данные в объект класса DOMDocumentFragment.

Это метод не входит в стандарт DOM. Он был разработан для упрощения процедуры добавления XML DocumentFragment в DOMDocument.

Если следовать стандарту, необходимо создавать временный DOMDocument с фиктивным корнем, а затем проходить по всем узлам потомкам корневого узла XML документа и добавлять их по очереди.

Список параметров

data

XML для добавления.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Добавление XML данных в документ

<?php
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
?>

Результат выполнения данного примера:

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

User Contributed Notes

lpetrov(AT)axisvista.com 20-Jul-2007 05:45
Here is (maybe) a better example:
/**
* Helper function for replacing $node (DOMNode)
* with an XML code (string)
*
* @var DOMNode $node
* @var string $xml
*/
public function replaceNodeXML(&$node,$xml) {
 $f = $this->dom->createDocumentFragment();
 $f->appendXML($xml);
 $node->parentNode->replaceChild($f,$node);
}

Copied from the "PHP5 Dom Based Template" article at:
http://blog.axisvista.com/?p=35
DOMDocumentFragment
DOMDocumentType
DOMDocumentFragment


Класс DOMDocumentType

(PHP 5)

Введение

Каждый объект DOMDocument имеет атрибут doctype, значение которого либо NULL, либо объект класса DOMDocumentType.

Обзор классов

DOMDocumentType extends DOMNode {
/* Свойства */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $name ;
readonly public DOMNamedNodeMap $entities ;
readonly public DOMNamedNodeMap $notations ;
readonly public string $internalSubset ;
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

publicId

Общедоступный идентификатор внешнего подмножества типов.

systemId

Системный идентификатор внешнего подмножества типов. Это может быть абсолютный URI.

name

Имя DTD, то есть имя, следующее сразу за ключевым словом DOCTYPE.

entities

Объект класса DOMNamedNodeMap содержащий основные элементы, внутренние и внешние, объявленные в DTD.

notations

Объект класса DOMNamedNodeMap содержащий условные обозначения, объявленные в DTD.

internalSubset

Внутреннее подмножество в виде строки или NULL, если такового нет. Оно не должно содержать квадратных скобок.

User Contributed Notes

There are no user contributed notes for this page.
DOMDocumentFragment::appendXML
DOMElement
DOM


Класс DOMElement

(PHP 5)

Обзор классов

DOMElement extends DOMNode {
/* Свойства */
readonly public bool $schemaTypeInfo ;
readonly public string $tagName ;
/* Методы */
__construct ( string $name [, string $value [, string $namespaceURI ]] )
string getAttribute ( string $name )
DOMAttr getAttributeNode ( string $name )
DOMAttr getAttributeNodeNS ( string $namespaceURI , string $localName )
string getAttributeNS ( string $namespaceURI , string $localName )
DOMNodeList getElementsByTagName ( string $name )
DOMNodeList getElementsByTagNameNS ( string $namespaceURI , string $localName )
bool hasAttribute ( string $name )
bool hasAttributeNS ( string $namespaceURI , string $localName )
bool removeAttribute ( string $name )
bool removeAttributeNode ( DOMAttr $oldnode )
bool removeAttributeNS ( string $namespaceURI , string $localName )
DOMAttr setAttribute ( string $name , string $value )
DOMAttr setAttributeNode ( DOMAttr $attr )
DOMAttr setAttributeNodeNS ( DOMAttr $attr )
void setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value )
void setIdAttribute ( string $name , bool $isId )
void setIdAttributeNode ( DOMAttr $attr , bool $isId )
void setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

schemaTypeInfo

Пока не реализовано, всегда возвращает NULL

tagName

Имя элемента

Примечания

Замечание:

Расширение DOM использует кодировку UTF-8. Используйте функции utf8_encode() и utf8_decode() для работы с текстами в кодировке ISO-8859-1, либо Iconv в других кодировках.

Содержание

  • DOMElement::__construct — Создание нового объекта класса DOMElement
  • DOMElement::getAttribute — Возвращает значение атрибута
  • DOMElement::getAttributeNode — Возвращает узел атрибута
  • DOMElement::getAttributeNodeNS — Возвращает узел атрибута
  • DOMElement::getAttributeNS — Возвращает значение атрибута
  • DOMElement::getElementsByTagName — Возвращает элементы по имени тэга
  • DOMElement::getElementsByTagNameNS — Получение элементов по локальному имени в заданном пространстве имен
  • DOMElement::hasAttribute — Проверяет наличие атрибута
  • DOMElement::hasAttributeNS — Проверяет, существует ли заданный атрибут
  • DOMElement::removeAttribute — Удаляет атрибут
  • DOMElement::removeAttributeNode — Удаляет атрибут
  • DOMElement::removeAttributeNS — Удаляет атрибут
  • DOMElement::setAttribute — Устанавливает значение атрибута
  • DOMElement::setAttributeNode — Добавляет новый узел атрибута к элементу
  • DOMElement::setAttributeNodeNS — Добавляет новый атрибут к элементу
  • DOMElement::setAttributeNS — Добавляет новый атрибут
  • DOMElement::setIdAttribute — Объявляет атрибут с заданным именем ключевым атрибутом
  • DOMElement::setIdAttributeNode — Объявляет заданный узал атрибута ключевым
  • DOMElement::setIdAttributeNS — Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим

User Contributed Notes

loopduplicate at burningtoken dot com 22-Apr-2011 02:34
This works perfect for me as well:

<?php $xml = $domElement->ownerDocument->saveXML($domElement); ?>
cannedmeat at spamulike dot com 28-Mar-2011 04:49
You want to change the tag name of an element in a DOM tree, preserving the structure of its hierarchy of children? Well for applications like translating custom tags to "real" html I've found the following quickest:

<?php
$Document; // The DOM Document
$Element; // The troublesome element of the document requiring translation

$NewElement = $Document->createElement('newtagname');

// Clone the attributes:
foreach($Element->attributes as $attribute)
$NewElement->setAttribute($attribute->name, $attribute->value);

// Add clones of the old element's children to the replacement
foreach($Element->childNodes as $child)
$NewElement->appendChild($child->cloneNode(true));

// Replace the old node
$Element->parentNode->replaceChild($NewElement, $Element);
?>
Anonymous 24-Dec-2010 08:22
you can use DOMNode::nodeValue
DOMElement inherits this public property.

$elem->nodeValue
dpetroff ( at ) gmail.com 04-Dec-2010 11:24
Hi!

Combining all th comments, the easiest way to get inner HTML of the node is to use this function:

<?php
function get_inner_html( $node ) {
    $innerHTML= '';
    $children = $node->childNodes;
    foreach ($children as $child) {
        $innerHTML .= $child->ownerDocument->saveXML( $child );
    }

    return $innerHTML;
}
?>
php at fishpig dot co dot uk 11-Jul-2010 09:53
A quick an easy way to get a string representation of any XML value is as follows:

<?php

 echo $elem->property->__toString();

?>
adam dot clements at gmail dot com 26-Apr-2010 11:29
I spent ages figuring out how to get a string representation of a DOMElement (that wasn't the entire DOMDocument), finally I came across this snippet:

<?php $string = $domDocument->saveXML($node); ?>

where $domDocument is the entire document, and $node is the particular node/element/whatever you want a string XML representation of.
nawaman at gmail dot com 03-Sep-2009 08:08
The following code shows can text-only content be extracted from a document.

<?php
function getTextFromNode($Node, $Text = "") {
    if ($Node->tagName == null)
        return $Text.$Node->textContent;

    $Node = $Node->firstChild;
    if ($Node != null)
        $Text = getTextFromNode($Node, $Text);

    while($Node->nextSibling != null) {
        $Text = getTextFromNode($Node->nextSibling, $Text);
        $Node = $Node->nextSibling;
    }
    return $Text;
}

function getTextFromDocument($DOMDoc) {
    return getTextFromNode($DOMDoc->documentElement);
}

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");
echo getTextFromDocument($Doc)."\n";
?>
Daniel Morlock 07-May-2009 09:22
It would be nice to have a function which converts a document/node/element into a string.

Anyways, I use the following code snippet to get the innerHTML value of a DOMNode:

<?php
function getInnerHTML($Node)
{
     $Body = $Node->ownerDocument->documentElement->firstChild->firstChild;
     $Document = new DOMDocument();
     $Document->appendChild($Document->importNode($Body,true));
     return $Document->saveHTML();
}
?>
patrick smith 04-Nov-2008 08:14
Although it may be preferable to use the dom to manipulate elements, sometimes it's useful to actually get the innerHTML from a document element (e.g. to load into a client-side editor).

To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath):

<?php
$innerHTML = '';
$doc = new DOMDocument();
$doc->loadHTMLFile($filepath);
$elem = $doc->getElementById($elem_id);

// loop through all childNodes, getting html
$children = $elem->childNodes;
foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $innerHTML .= $tmp_doc->saveHTML();
}
?>
Pinochet 25-Oct-2008 05:33
Hi to get the value of DOMElement just get the nodeValue public parameter (it is inherited from DOMNode):
<?php
echo $domElement->nodeValue;
?>
Everything is obvious if you now about this thing ;-)
j DOT wagner ( AT ) medieninnovation.com 08-Oct-2008 09:11
Caveat!
It took me almost an hour to figure this out, so I hope it saves at least one of you some time.

If you want to debug your DOM tree and try var_dump() or similar you will be fooled into thinking the DOMElement that you are looking at is empty, because var_dump() says: object(DOMElement)#1 (0) { }

After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.

The solution is simple (if you know it):
$xml = $domElement->ownerDocument->saveXML($domElement);

This will give you an XML representation of $domElement.
Severin 14-Sep-2008 06:18
I wanted to find similar Elements - thats why I built an Xpath-String like this - maybe somebody needs it... its not very pretty - but neither is domdocument :)

<?php

$dom->load($xmlFile))

$xpathQuery = '//*';
$xmlNodes = $xpath->query($xpathQuery);

$pathlist = array();
$attrlist = array();
foreach ($xmlNodes as $node) {

  $depth = $this->_getDomDepth($node);   //get Path-Depth (for array key)
  $pathlist[$depth] = $node->tagName;     // tagname

  $attrs = $node->attributes;
  $attr='';
  $a=0;
  foreach ($attrs as $attrName => $attrNode)  // attributes
            {
              if ($attrName !='reg')
              {
                if ($a++!=0) $attr .= ' and ';
                $attr .= '@'.$attrName.'='."'".$attrNode->value."'";
              }
            }

          $attrlist[$depth] = $attr?'['.$attr.']':'';

          $path = ''; for ($i=0;$i<=$depth;$i++) $path .= '/'.$pathlist[$i].$attrlist[$i];  // the xpath of the actual Element

    // ... now you can go on and user $path to find similar elements
    }
  }
}

 private function _getDomDepth(DomNode $node)
   {
     $r = -2;
     while ($node) {
       $r++;
       $node = $node->parentNode;
     }
     return  $r;
   }
?>
ae.fxx 18-Jul-2008 01:49
Hi there.

Remember to append a DOMNode (or any of its descendants) to a DOMDocument __BEFORE__ you try to append a child to it.

I don't know why it has to be this way but it can't be done without it.

bye
DOMDocumentType
DOMElement::__construct
DOM


Создание нового объекта класса DOMElement

DOMElement
DOMElement::getAttribute
DOMElement
PHP Manual

DOMElement::__construct

(PHP 5)

DOMElement::__construct — Создание нового объекта класса DOMElement

Описание

DOMElement::__construct ( string $name [, string $value [, string $namespaceURI ]] )

Создает новый объект класса DOMElement. Этот объект доступен только для чтения. Он может быть добавлен в документ, но в него нельзя добавить дочерние узлы пока данный узел связан с документом. Для того чтобы создавать узлы, которые могут быть изменены, воспользуйтесь следующими методами: DOMDocument::createElement or DOMDocument::createElementNS.

Список параметров

name

Имя тэга создаваемого элемента. Если передан параметр namespaceURI, имя элемента может получить префикс для связи с URI.

value

Значение элемента.

namespaceURI

Пространство имен URI, передается для создания элемента со отдельным пространством имен.

Примеры

Пример #1 Создание DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

Смотрите также

  • DOMDocument::createElement() - Создает новый узел-элемент
  • DOMDocument::createElementNS() - Создание нового узла-элемента с соответствующим пространством имен

User Contributed Notes

Fabian dot Blech at gmx dot de 22-Jul-2010 08:30
Remember, Dom-Nodes mustn't start with a number:

allowed:
<t12345t4>Value</t12345t4>

Not allowed:
<12345t4>VALUE</12345t4>
troelskn at gmail dot com 03-Jun-2008 07:46
Note that this function is buggy. You have to manually escape the $value argument with htmlspecialchars.
See: http://bugs.php.net/bug.php?id=31191
adar at darkpoetry dot de 07-May-2007 01:27
If you like to view an element simply do:

<?php
echo htmlentities($element->C14N());
?>

Undocumented but found ;)
DOMElement
DOMElement::getAttribute
DOMElement


Возвращает значение атрибута

DOMElement::__construct
DOMElement::getAttributeNode
DOMElement
PHP Manual

DOMElement::getAttribute

(PHP 5)

DOMElement::getAttribute — Возвращает значение атрибута

Описание

string DOMElement::getAttribute ( string $name )

Возвращает значение атрибута с именем name для текущего узла.

Список параметров

name

Имя атрибута.

Возвращаемые значения

Значение атрибута или пустое значение, если атрибут с указанным именем name не найден.

Смотрите также

  • DOMElement::hasAttribute() - Проверяет наличие атрибута
  • DOMElement::setAttribute() - Устанавливает значение атрибута
  • DOMElement::removeAttribute() - Удаляет атрибут

User Contributed Notes

metron at underhive-planet dot com 24-Mar-2011 08:45
You can also use DOMXPath objects to interleave foreach() in this way is slightly shorter. If you need a special element or attribute value. The variable $xquery needs xpath expression. This example filters all group elements as described in xpath query ($xquery), then it filters again the results by last if condition and stores all attribute names in an object variable of type array ($this->menu).

Benefit: Using class array variable $menu in other class methods. Whenever you need those fields.

XML:
<xml>
  <category menu="products">
    <groups>
      <group menu="vegetables">...</group>
    </groups>
  </category>
</xml>

<?php
public class example {

public $menu;

function _construct(){}

public function getGroupValueByCategory($xpath_object,$category) {
$xquery = '//category[normalize-space(@menu)="'.$category.'"]/groups/group';
             if($elements = $xpobject->evaluate($xquery)){
                 $this->menu = array();
             }
             foreach ($elements as $element) {
                 if($element->hasAttributes()){
                     $attributes = $element->attributes;
                     if(!is_null($attributes)){
                         foreach ($attributes as $index=>$attr){
                             if($attr->name == 'menu'){
                                 $this->menu[] = $attr->value;
                             }
                         }
                     }
                 }
             }
}

}
?>

I used this to implement simple menu structure.
info at kevinfilteau dot com 17-Jul-2009 10:25
I want to retrieve value of name in my current language, or the default, or anything set if none of the above are true.

There is a sample XML file:

<product>
   <name lang="en">Candy</name>
   <name lang="fr">Bonbon</name>
   <name>Bonbon (no lang)</name>
</product>

There is my function, hope this can help. And if anybody want's to improve it, your welcom. The input elements are DOMNodeList returned from a previous DomXPath Query.

<?php
    private function getValueByLang($elements) {

        $a = array();

        if (!is_null($elements)) {

            foreach ($elements as $element) {

                if( !is_null($element->attributes)) {

                    $is_lang = false;

                    foreach ($element->attributes as $attrName => $attrNode) {

                        if( 'lang' == $attrName ) {
                            $a[$attrNode->value] = $element->nodeValue;
                            $is_lang = true;
                        }
                    }

                    if( !$is_lang ) {
                        $a[] = $element->nodeValue;
                    }
                }

            }

            // Returns current language if set.
            if( array_key_exists($this->lang, $a)) {
                $result = $a[$this->lang];
            // Returns default language if set.
            } elseif( array_key_exists($this->default_lang, $a)) {
                $result = $a[$this->default_lang];
            // Returns first result with no language attribute.
            } elseif( isset($a[0])) {
                $result = $a[0];
            // Return anything set.
            } elseif( $result = reset($a) ) {
            // Return nothing,  Doh!
            } else {
                $result = false;

            }

            return($result);

        } else {
            throw new Exception(printf("No elements defined."));
        }
    }
?>
mpalmer at cybersource dot com 09-Nov-2007 03:32
- - - - - - - - - - - - - -

XML Data:
<data>
<Report ID="1">
    <Date>REVIEW</Date>
    <AuthorID>1</AuthorID>
</Report>
<Report ID="2">
    <Date>REVIEW</Date>
    <AuthorID>2</AuthorID>
</Report>
</data>

- - - - - - - - - - - - - -

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load( 'data.xml' );

$searchNode = $xmlDoc->getElementsByTagName( "Report" );

foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('ID');

    $xmlDate = $searchNode->getElementsByTagName( "Date" );
    $valueDate = $xmlDate->item(0)->nodeValue;

    $xmlAuthorID = $searchNode->getElementsByTagName( "AuthorID" );
    $valueAuthorID = $xmlAuthorID->item(0)->nodeValue;

    echo "$valueID - $valueDate - $valueAuthorID\n";
}
?>

- - - - - - - - - - - - - -

Output:

1 - REVIEW - 1
2 - REVIEW - 2

- - - - - - - - - - - - - -
DOMElement::__construct
DOMElement::getAttributeNode
DOMElement


Возвращает узел атрибута

DOMElement::getAttribute
DOMElement::getAttributeNodeNS
DOMElement
PHP Manual

DOMElement::getAttributeNode

(PHP 5)

DOMElement::getAttributeNode — Возвращает узел атрибута

Описание

DOMAttr DOMElement::getAttributeNode ( string $name )

Возвращает атрибут с именем name текущего элемента в виде узла.

Список параметров

name

Имя атрибута.

Возвращаемые значения

Узел атрибута.

Смотрите также

  • DOMElement::hasAttribute() - Проверяет наличие атрибута
  • DOMElement::setAttributeNode() - Добавляет новый узел атрибута к элементу
  • DOMElement::removeAttributeNode() - Удаляет атрибут

User Contributed Notes

lowezar at gmail dot com 28-Feb-2011 08:22
It may also return DOMNameSpaceNode if you`re requesting 'xmlns:_prefix_'. So you`re unable to remove it with removeAttributeNode() which requires DOMAttr as parameter.
Alex 18-Feb-2009 08:33
Just trying to add some clarification: this function will return boolean "false" when there is not a $name attribute :)

Cheers, Alex
DOMElement::getAttribute
DOMElement::getAttributeNodeNS
DOMElement


Возвращает узел атрибута

DOMElement::getAttributeNode
DOMElement::getAttributeNS
DOMElement
PHP Manual

DOMElement::getAttributeNodeNS

(PHP 5)

DOMElement::getAttributeNodeNS — Возвращает узел атрибута

Описание

DOMAttr DOMElement::getAttributeNodeNS ( string $namespaceURI , string $localName )

Возвращает атрибут в пространстве имен namespaceURI с локальным именем localName для текущего элемента в виде узла.

Список параметров

namespaceURI

URI пространства имен.

localName

Локальное имя.

Возвращаемые значения

Узел атрибута.

Смотрите также

  • DOMElement::hasAttributeNS() - Проверяет, существует ли заданный атрибут
  • DOMElement::setAttributeNodeNS() - Добавляет новый атрибут к элементу
  • DOMElement::removeAttributeNode() - Удаляет атрибут

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::getAttributeNode
DOMElement::getAttributeNS
DOMElement


Возвращает значение атрибута

DOMElement::getAttributeNodeNS
DOMElement::getElementsByTagName
DOMElement
PHP Manual

DOMElement::getAttributeNS

(PHP 5)

DOMElement::getAttributeNS — Возвращает значение атрибута

Описание

string DOMElement::getAttributeNS ( string $namespaceURI , string $localName )

Получает значение атрибута в пространстве имен namespaceURI с локальным именем localName текущего элемента.

Список параметров

namespaceURI

URI пространства имен.

localName

Локальное имя.

Возвращаемые значения

Значение атрибута либо пустая строка, если атрибутов с заданным локальным именем localName в пространстве имен namespaceURI не найдено.

Смотрите также

  • DOMElement::hasAttributeNS() - Проверяет, существует ли заданный атрибут
  • DOMElement::setAttributeNS() - Добавляет новый атрибут
  • DOMElement::removeAttributeNS() - Удаляет атрибут

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::getAttributeNodeNS
DOMElement::getElementsByTagName
DOMElement


Возвращает элементы по имени тэга

DOMElement::getAttributeNS
DOMElement::getElementsByTagNameNS
DOMElement
PHP Manual

DOMElement::getElementsByTagName

(PHP 5)

DOMElement::getElementsByTagName — Возвращает элементы по имени тэга

Описание

DOMNodeList DOMElement::getElementsByTagName ( string $name )

Эта функция возвращает объект класса DOMNodeList - список всех элементов-потомков текущего узла с указанным именем тэга name, в порядке, в котором они встречаются при обходе дерева.

Список параметров

name

Имя тэга. Используйте символ * для выборки всех элементов дерева.

Возвращаемые значения

Эта функция возвращает новый объект класса DOMNodeList - список всех подходящих элементов.

Смотрите также

  • DOMElement::getElementsByTagNameNS() - Получение элементов по локальному имени в заданном пространстве имен

User Contributed Notes

ddkkdd twenty twenty at gmail dot com 08-Sep-2010 03:15
A simple function that uses this method to print the nodes it finds in an xml document. Improvements welcomed.

<?php
function printTags($tag){

  $node = $this->doc->getElementsByTagName($tag);
   for($c = 0; $c<$node->length; $c++){
     $text[$c] =$this->doc->saveXML($node->item($c));
     echo $text[$c];

   }

}
?>
DOMElement::getAttributeNS
DOMElement::getElementsByTagNameNS
DOMElement


Получение элементов по локальному имени в заданном пространстве имен

DOMElement::getElementsByTagName
DOMElement::hasAttribute
DOMElement
PHP Manual

DOMElement::getElementsByTagNameNS

(PHP 5)

DOMElement::getElementsByTagNameNS — Получение элементов по локальному имени в заданном пространстве имен

Описание

DOMNodeList DOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName )

Эта функция выбирает все элементы-потомки с заданным именем localName и пространством имен namespaceURI.

Список параметров

namespaceURI

URI пространства имен.

localName

Локальное имя. Используйте * для выбора всех элементов из дерева.

Возвращаемые значения

Эта функция возвращает новый объект класса DOMNodeList содержащий все подошедшие под шаблон выбора элементы в том порядке, в котором они появляются при прямом обходе дерева.

Смотрите также

  • DOMElement::getElementsByTagName() - Возвращает элементы по имени тэга

User Contributed Notes

spam at chovy dot com 03-Jun-2009 05:36
I had some difficulty stripping all default NS attributes for an ns-uri in one shot, the following will work though...first strip the documentElement namespace, then getElementsByTagNameNS() -- the documentation should reflect that the 2nd argument is actually the name of the tag, not the local namespace prefix as I first expected:

<?php

function strip_default_ns( $xml = null, $ns_uri = 'http://example.com/XML-Foo' ) {
    $ns_local = '';
    $ns_tag = '*';

    if ( empty($xml) ) return false;

    //remove document namespace
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $dom->documentElement->removeAttributeNS($ns_uri, $ns_local);

    //strip element namespaces
    foreach ( $dom->getElementsByTagNameNS($ns_uri, $ns_tag) as $elem ) {
        $elem->removeAttributeNS($ns_uri, $ns_local);
    }

    return $dom->saveXML();
}

$stripped_xml = strip_default_ns($the_xml);

?>

$stripped_xml can now take advantage of running XPath queries on it for the NULL namespace.
DOMElement::getElementsByTagName
DOMElement::hasAttribute
DOMElement


Проверяет наличие атрибута

DOMElement::getElementsByTagNameNS
DOMElement::hasAttributeNS
DOMElement
PHP Manual

DOMElement::hasAttribute

(PHP 5)

DOMElement::hasAttribute — Проверяет наличие атрибута

Описание

bool DOMElement::hasAttribute ( string $name )

Проверяет наличие атрибута с именем, указанным в параметре name текущего элемента.

Список параметров

name

Имя атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMElement::hasAttributeNS() - Проверяет, существует ли заданный атрибут
  • DOMElement::getAttribute() - Возвращает значение атрибута
  • DOMElement::setAttribute() - Устанавливает значение атрибута
  • DOMElement::removeAttribute() - Удаляет атрибут

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::getElementsByTagNameNS
DOMElement::hasAttributeNS
DOMElement


Проверяет, существует ли заданный атрибут

DOMElement::hasAttribute
DOMElement::removeAttribute
DOMElement
PHP Manual

DOMElement::hasAttributeNS

(PHP 5)

DOMElement::hasAttributeNS — Проверяет, существует ли заданный атрибут

Описание

bool DOMElement::hasAttributeNS ( string $namespaceURI , string $localName )

Показывает, существует ли атрибут в пространстве имен namespaceURI с именем localName в составе элемента.

Список параметров

namespaceURI

URI пространства имен.

localName

Локальное имя.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMElement::hasAttribute() - Проверяет наличие атрибута
  • DOMElement::getAttributeNS() - Возвращает значение атрибута
  • DOMElement::setAttributeNS() - Добавляет новый атрибут
  • DOMElement::removeAttributeNS() - Удаляет атрибут

User Contributed Notes

chad dot retz at gmail dot com 11-May-2008 12:38
This does not work as expected (at least on 5.2.5) with attributes in the default namespace. For instance:

<?php
$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><element xmlns="testns" attr="testval" />');
var_dump($dom->documentElement->hasAttributeNS('testns', 'attr'));
?>

returns bool(false) whereas:

<?php
$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><element xmlns:ns1="testns" ns1:attr="testval" />');
var_dump($dom->documentElement->hasAttributeNS('testns', 'attr'));
?>

returns bool(true). NULL does work properly in the namespaceURI parameter, so changing my initial example to:

<?php
$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><element xmlns="testns" attr="testval" />');
var_dump($dom->documentElement->hasAttributeNS(NULL, 'attr'));
?>

returns bool(true) as expected. Or even better for when you don't know whether the NS will be default:

<?php
$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><element xmlns="testns" attr="testval" />');
var_dump($dom->documentElement->hasAttributeNS(
    is_null($dom->documentElement->lookupPrefix('testns')) ? NULL : 'testns', 'attr'));
?>
DOMElement::hasAttribute
DOMElement::removeAttribute
DOMElement


Удаляет атрибут

DOMElement::hasAttributeNS
DOMElement::removeAttributeNode
DOMElement
PHP Manual

DOMElement::removeAttribute

(PHP 5)

DOMElement::removeAttribute — Удаляет атрибут

Описание

bool DOMElement::removeAttribute ( string $name )

Удаляет атрибут с именем name из элемента.

Список параметров

name

Имя атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если атрибут доступен только для чтения.

Смотрите также

  • DOMElement::hasAttribute() - Проверяет наличие атрибута
  • DOMElement::getAttribute() - Возвращает значение атрибута
  • DOMElement::setAttribute() - Устанавливает значение атрибута

User Contributed Notes

suwayan at mail dot ru 30-Mar-2012 12:19
<?php
/*When I try to get a some attribute from not validated HTML or XML document, PHP dies with no errors in logs or output:
*/
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
//And this check helped to me:
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj->attributes)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
?>
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:38
<?php

//Store your html into $html variable.

$html="<html>
<head>
<title>Rakesh Verma</title>
</head>

<body>
    <a href='http://example.com'>Example</a>
    <a href='http://google.com'>Google</a>
    <a href='http://www.yahoo.com'>Yahoo</a>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url.".au";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>
DOMElement::hasAttributeNS
DOMElement::removeAttributeNode
DOMElement


Удаляет атрибут

DOMElement::removeAttribute
DOMElement::removeAttributeNS
DOMElement
PHP Manual

DOMElement::removeAttributeNode

(PHP 5)

DOMElement::removeAttributeNode — Удаляет атрибут

Описание

bool DOMElement::removeAttributeNode ( DOMAttr $oldnode )

Удаляет узел атрибута oldnode из элемента.

Список параметров

oldnode

Узел атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

DOM_NOT_FOUND_ERROR

Возникает, если oldnode не является атрибутом элемента.

Смотрите также

  • DOMElement::hasAttribute() - Проверяет наличие атрибута
  • DOMElement::getAttributeNode() - Возвращает узел атрибута
  • DOMElement::setAttributeNode() - Добавляет новый узел атрибута к элементу

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::removeAttribute
DOMElement::removeAttributeNS
DOMElement


Удаляет атрибут

DOMElement::removeAttributeNode
DOMElement::setAttribute
DOMElement
PHP Manual

DOMElement::removeAttributeNS

(PHP 5)

DOMElement::removeAttributeNS — Удаляет атрибут

Описание

bool DOMElement::removeAttributeNS ( string $namespaceURI , string $localName )

Удаляет атрибут с пространством имен namespaceURI и локальным именем localName из элемента.

Список параметров

namespaceURI

URI пространства имен.

localName

Локальное имя.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

Смотрите также

  • DOMElement::hasAttributeNS() - Проверяет, существует ли заданный атрибут
  • DOMElement::getAttributeNS() - Возвращает значение атрибута
  • DOMElement::setAttributeNS() - Добавляет новый атрибут

User Contributed Notes

primaryspace at hotmail dot com 10-Aug-2005 12:56
This method can be used to remove a namespace declaration from an element, even though the declaration is not considered an attribute by the DOM.  The prefix will be removed from any element or attribute using it.

<?php

$dom = DOMDocument::loadXML('<foo:root xmlns:foo="http:bar"/>');
$element = $dom->childNodes->item(0);

// prints '0':
echo (int) $element->hasAttributeNS('http:bar', 'foo');

$element->removeAttributeNS('http:bar', 'foo');

/* prints '<?xml version="1.0"?> <root/>': */
print htmlentities($dom->saveXML());

?>
DOMElement::removeAttributeNode
DOMElement::setAttribute
DOMElement


Устанавливает значение атрибута

DOMElement::removeAttributeNS
DOMElement::setAttributeNode
DOMElement
PHP Manual

DOMElement::setAttribute

(PHP 5)

DOMElement::setAttribute — Устанавливает значение атрибута

Описание

DOMAttr DOMElement::setAttribute ( string $name , string $value )

Устанавливает значение атрибута с именем name. Если атрибут не существует, то он будет создан.

Список параметров

name

Имя атрибута.

value

Значение атрибута.

Возвращаемые значения

Новый объект класса DOMAttr или FALSE в случае ошибки.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

Примеры

Пример #1 Установка значения атрибута

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

Смотрите также

  • DOMElement::hasAttribute() - Проверяет наличие атрибута
  • DOMElement::getAttribute() - Возвращает значение атрибута
  • DOMElement::removeAttribute() - Удаляет атрибут

User Contributed Notes

Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:27
<?php
//Store your html into $html variable.
$html="
<html>
<head>
<title>Untitled Document</title>
</head>

<body>
    <a href='http://example.com'>Example</a><br>
    <a href='http://google.com'>Google</a><br>

    <a href='http://www.yahoo.com'>Yahoo</a><br>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url."/newurl";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>
address at gmail dot com 03-Jul-2008 07:25
If wanting to set an attribute of an element with unique id of "1"

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$xp = new DomXPath($dom);
$res = $xp->query("//*[@id = '1']");
$res->item(0)->setAttribute('title','2');
$dom->save('test.xml');
?>
Vasil Rangelov 31-Jul-2007 04:44
@karvjorm,
Using this method is not exactly a good practice. Infact, I think it may be a bug.
Names beginning with "xml" are reserved (for namespaces in this case).
setAttribute() should return false in this case I think, but I suppose it doesn't.

Still, the right way to do it is with createElementNS().
It lets you specify the namespace when creating the element node.

So the equivalent to yours ($html added to allow word wrapping) is:

$dom = new DomDocument('1.0','iso-8859-15');
$html = $dom->createElementNS('http://www.w3.org/1999/xhtml', 'html');
$ht_ml = $dom->appendChild($html);
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');
karvjorm at users.sourceforge.net 02-Mar-2007 03:05
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));
$ht_ml->setAttribute('xmlns','http://www.w3.org/1999/xhtml');
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi" lang="fi">
DOMElement::removeAttributeNS
DOMElement::setAttributeNode
DOMElement


Добавляет новый узел атрибута к элементу

DOMElement::setAttribute
DOMElement::setAttributeNodeNS
DOMElement
PHP Manual

DOMElement::setAttributeNode

(PHP 5)

DOMElement::setAttributeNode — Добавляет новый узел атрибута к элементу

Описание

DOMAttr DOMElement::setAttributeNode ( DOMAttr $attr )

Добавляет новый узел атрибута attr в элемент.

Список параметров

attr

Узел атрибута.

Возвращаемые значения

Возвращает старый узел, если атрибут был заменен, или NULL.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

Смотрите также

  • DOMElement::hasAttribute() - Проверяет наличие атрибута
  • DOMElement::getAttributeNode() - Возвращает узел атрибута
  • DOMElement::removeAttributeNode() - Удаляет атрибут

User Contributed Notes

karvjorm at users.sourceforge.net 02-Mar-2007 04:01
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));

$he_ad = $ht_ml->appendChild($dom->createElement('head'));

$tit_le= $he_ad->appendChild($dom->createElement('title'));
$tit_le->appendChild($dom->createTextNode('DOMAttr test'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Description'));
$me_ta->setAttributeNode(new DOMAttr('content', 'example'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Author'));
$me_ta->setAttributeNode(new DOMAttr('content', 'karvjorm'));

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html>
  <head>
    <title>DOMAttr test</title>
    <meta name="Description" content="example"/>
    <meta name="Author" content="karvjorm"/>
  </head>
DOMElement::setAttribute
DOMElement::setAttributeNodeNS
DOMElement


Добавляет новый атрибут к элементу

DOMElement::setAttributeNode
DOMElement::setAttributeNS
DOMElement
PHP Manual

DOMElement::setAttributeNodeNS

(PHP 5)

DOMElement::setAttributeNodeNS — Добавляет новый атрибут к элементу

Описание

DOMAttr DOMElement::setAttributeNodeNS ( DOMAttr $attr )

Добавляет новый узел атрибута attr в элемент.

Список параметров

attr

Узел атрибута.

Возвращаемые значения

Возвращает старый узел, если атрибут был заменен.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

Смотрите также

  • DOMElement::hasAttributeNS() - Проверяет, существует ли заданный атрибут
  • DOMElement::getAttributeNodeNS() - Возвращает узел атрибута
  • DOMElement::removeAttributeNode() - Удаляет атрибут

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::setAttributeNode
DOMElement::setAttributeNS
DOMElement


Добавляет новый атрибут

DOMElement::setAttributeNodeNS
DOMElement::setIdAttribute
DOMElement
PHP Manual

DOMElement::setAttributeNS

(PHP 5)

DOMElement::setAttributeNS — Добавляет новый атрибут

Описание

void DOMElement::setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value )

Устанавливает значение атрибута с пространстве имен namespaceURI и локальным именем name. Если атрибут не существует, он будет создан.

Список параметров

namespaceURI

URI пространства имен.

qualifiedName

Стандартизованное имя атрибута в виде prefix:tagname.

value

Значение атрибута.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

DOM_NAMESPACE_ERR

Возникает, если значение qualifiedName построено неправильно или если qualifiedName имеет префикс, а namespaceURI имеет значение NULL.

Смотрите также

  • DOMElement::hasAttributeNS() - Проверяет, существует ли заданный атрибут
  • DOMElement::getAttributeNS() - Возвращает значение атрибута
  • DOMElement::removeAttributeNS() - Удаляет атрибут

User Contributed Notes

catalinenache78 at gmail dot com 18-May-2011 07:39
To add new brand xml namespace use:

<?php
    $element->setAttributeNS(
        'http://www.w3.org/2000/xmlns/', // xmlns namespace URI
        'xmlns:mynamespace',
        'example.com/mynamespace'
    );
?>

'http://www.w3.org/2000/xmlns/' URI is important
to be able to add  new namespaces !!!

Later you can use your namespace like:

<?php
    $element->setAttributeNS(
        'example.com/mynamespace',
        'mynamespace:something',
        'value'
    );
?>
DOMElement::setAttributeNodeNS
DOMElement::setIdAttribute
DOMElement


Объявляет атрибут с заданным именем ключевым атрибутом

DOMElement::setAttributeNS
DOMElement::setIdAttributeNode
DOMElement
PHP Manual

DOMElement::setIdAttribute

(PHP 5)

DOMElement::setIdAttribute — Объявляет атрибут с заданным именем ключевым атрибутом

Описание

void DOMElement::setIdAttribute ( string $name , bool $isId )

Объявляет атрибут name ключевым.

Список параметров

name

Имя атрибута.

isId

Установите значение в TRUE если требуется сделать name идентифицирующим, в противном случае ставьте FALSE.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

DOM_NOT_FOUND

Возникает, если name не является атрибутом элемента.

Смотрите также

  • DOMDocument::getElementById() - Ищет элемент с заданным id
  • DOMElement::setIdAttributeNode() - Объявляет заданный узал атрибута ключевым
  • DOMElement::setIdAttributeNS() - Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::setAttributeNS
DOMElement::setIdAttributeNode
DOMElement


Объявляет заданный узал атрибута ключевым

DOMElement::setIdAttribute
DOMElement::setIdAttributeNS
DOMElement
PHP Manual

DOMElement::setIdAttributeNode

(PHP 5)

DOMElement::setIdAttributeNode — Объявляет заданный узал атрибута ключевым

Описание

void DOMElement::setIdAttributeNode ( DOMAttr $attr , bool $isId )

Объявляет атрибут, определяемый узлом attr идентифицирующим элемент атрибутом.

Список параметров

attr

Узел атрибута.

isId

Установите значение в TRUE если требуется сделать name идентифицирующим, в противном случае ставьте FALSE.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

DOM_NOT_FOUND

Возникает, если name не является атрибутом элемента.

Смотрите также

  • DOMDocument::getElementById() - Ищет элемент с заданным id
  • DOMElement::setIdAttribute() - Объявляет атрибут с заданным именем ключевым атрибутом
  • DOMElement::setIdAttributeNS() - Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::setIdAttribute
DOMElement::setIdAttributeNS
DOMElement


Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим

DOMElement::setIdAttributeNode
DOMEntity
DOMElement
PHP Manual

DOMElement::setIdAttributeNS

(PHP 5)

DOMElement::setIdAttributeNS — Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим

Описание

void DOMElement::setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId )

Объявляет атрибут с заданным локальным именем localName и пространством имен namespaceURI идентифицирующим элемент атрибутом.

Список параметров

namespaceURI

URI пространства имен атрибута.

localName

Локальное имя атрибута в виде prefix:tagname.

isId

Установите значение в TRUE если требуется сделать name идентифицирующим, в противном случае ставьте FALSE.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

DOM_NOT_FOUND

Возникает, если name не является атрибутом элемента.

Смотрите также

  • DOMDocument::getElementById() - Ищет элемент с заданным id
  • DOMElement::setIdAttribute() - Объявляет атрибут с заданным именем ключевым атрибутом
  • DOMElement::setIdAttributeNode() - Объявляет заданный узал атрибута ключевым

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::setIdAttributeNode
DOMEntity
DOMElement


Класс DOMEntity

(PHP 5)

Введение

Этот интерфейс представляет заведомо известную сущность, уже разобранную или нет, в документе XML.

Обзор классов

DOMEntity extends DOMNode {
/* Свойства */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $notationName ;
public string $actualEncoding ;
readonly public string $encoding ;
readonly public string $version ;
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

publicId

Общедоступный идентификатор соответствующий сущности или NULL, если не задан.

systemId

Системный идентификатор соответствующий сущности или NULL, если не задан. Это может быть абсолютный URI.

notationName

Для неразобранных объектов - наименование условного обозначения для сущности. Для разобранных - NULL.

actualEncoding

Атрибут, задающий кодировку, которая использовалась при разборе сущности, для случаев, когда разбор производился внешними методами. Атрибут имеет значение NULL, если сущность находится во внутреннем подмножестве или этот факт не известен.

encoding

Атрибут, задающий кодировку сущности, равно как и в объявлении, когда сущность разобрана внешними средствами. В противном случае атрибут имеет значение NULL.

version

Атрибут, задающий версию элемента, если он был разобран внешними средствами. В противном случае NULL.

User Contributed Notes

There are no user contributed notes for this page.
DOMElement::setIdAttributeNS
DOMEntityReference
DOM


Класс DOMEntityReference

(PHP 5)

Обзор классов

DOMEntityReference extends DOMNode {
/* Свойства */
/* Методы */
__construct ( string $name )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Содержание

  • DOMEntityReference::__construct — Создает новый объект класса DOMEntityReference

User Contributed Notes

Anonymous 11-Jun-2010 03:22
These can only appear if document->resolveExternals = true
DOMEntity
DOMEntityReference::__construct
DOM


Создает новый объект класса DOMEntityReference

DOMEntityReference
DOMException
DOMEntityReference
PHP Manual

DOMEntityReference::__construct

(PHP 5)

DOMEntityReference::__construct — Создает новый объект класса DOMEntityReference

Описание

DOMEntityReference::__construct ( string $name )

Создает новый объект класса DOMEntityReference.

Список параметров

name

Имя ссылки на сущность.

Примеры

Пример #1 Создание нового объекта DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root></root> */

?>

Смотрите также

  • DOMDocument::createEntityReference() - Создание нового узла-ссылки на сущность

User Contributed Notes

There are no user contributed notes for this page.
DOMEntityReference
DOMException
DOMEntityReference


Класс DOMException

(PHP 5)

Введение

Методы объектов DOM в редких случаях выбрасывают исключения, например, когда выполнение операции невозможно по понятным логичным причинам.

См. также Исключения.

Обзор классов

DOMException extends Exception {
/* Свойства */
readonly public int $code ;
/* Наследуемые методы */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Свойства

code

Целое число (integer) характеризующее тип произошедшей ошибки

User Contributed Notes

There are no user contributed notes for this page.
DOMEntityReference::__construct
DOMImplementation
DOM


Класс DOMImplementation

(PHP 5)

Введение

Интерфейс DOMImplementation предоставляет несколько методов для осуществления операций зависящих от некоторых особенностей реализации объектной модели документа.

Обзор классов

DOMImplementation {
/* Свойства */
/* Методы */
__construct ( void )
DOMDocument createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] )
DOMDocumentType createDocumentType ([ string $qualifiedName = NULL [, string $publicId = NULL [, string $systemId = NULL ]]] )
bool hasFeature ( string $feature , string $version )
}

Содержание

  • DOMImplementation::__construct — Создает новый объект класса DOMImplementation
  • DOMImplementation::createDocument — Создает объект класса DOMDocument заданного типа с элементом document
  • DOMImplementation::createDocumentType — Создает пустой объект класса DOMDocumentType
  • DOMImplementation::hasFeature — Тестирует реализацию специфичных возможностей объекта DOMImplementation

User Contributed Notes

giorgio dot liscio at email dot it 20-Jul-2010 06:26
officially, the w3 specifies that the way to access dom interfaces is through this class

so if you use

$doc = new DOMDocument("1.0", "UTF-8");

use instead:

$x = new DOMImplementation();
$doc = $x->createDocument(NULL,"rootElementName");
$doc->xmlVersion="1.0";
$doc->xmlEncoding="UTF-8";

it is not required by php's implementation, but, probably, it is a good practice

see:

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementation

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationList

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationSource
DOMException
DOMImplementation::__construct
DOM


Создает новый объект класса DOMImplementation

DOMImplementation
DOMImplementation::createDocument
DOMImplementation
PHP Manual

DOMImplementation::__construct

(PHP 5)

DOMImplementation::__construct — Создает новый объект класса DOMImplementation

Описание

DOMImplementation::__construct ( void )

Создает экземпляр класса DOMImplementation.

User Contributed Notes

There are no user contributed notes for this page.
DOMImplementation
DOMImplementation::createDocument
DOMImplementation


Создает объект класса DOMDocument заданного типа с элементом document

DOMImplementation::__construct
DOMImplementation::createDocumentType
DOMImplementation
PHP Manual

DOMImplementation::createDocument

(PHP 5)

DOMImplementation::createDocument — Создает объект класса DOMDocument заданного типа с элементом document

Описание

DOMDocument DOMImplementation::createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] )

Создает объект класса DOMDocument заданного типа с элементом document.

Список параметров

namespaceURI

URI пространства имен элемента document.

qualifiedName

Имя элемента document.

doctype

Тип элемента document или NULL.

Возвращаемые значения

Новый объект класса DOMDocument. Если аргументы namespaceURI, qualifiedName, и doctype имеют значение null, возвращаемый объект DOMDocument будет пустым, без элементов document.

Ошибки

DOM_WRONG_DOCUMENT_ERR

Возникает, если аргумент doctype уже был использован с другим документом или был создан в другой реализации.

DOM_NAMESPACE_ERR

Возникает, если обнаружена ошибка в строках namespaceURI и qualifiedName.

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Смотрите также

  • DOMDocument::__construct() - Создание нового DOMDocument объекта
  • DOMImplementation::createDocumentType() - Создает пустой объект класса DOMDocumentType

User Contributed Notes

eboyjr 22-Jul-2010 12:48
To add on to the other example, here's how to create an XHTML 1.0 transitional document with head, title, and body elements.

<?php

$document = DOMImplementation::createDocument(null, 'html',
    DOMImplementation::createDocumentType("html",
        "-//W3C//DTD XHTML 1.0 Transitional//EN",
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"));
$document->formatOutput = true;

$html = $document->documentElement;
$head = $document->createElement('head');
$title = $document->createElement('title');
$text = $document->createTextNode('Title of Page');
$body = $document->createElement('body');

$title->appendChild($text);
$head->appendChild($title);
$html->appendChild($head);
$html->appendChild($body);

echo $document->saveXML();
?>

This outputs: (http links removed due to spam)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "doctype.dtd">
<html xmlns="w3org1999xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Title of Page</title>
  </head>
  <body></body>
</html>

Note the saveXML function. If saveHTML was used instead, you get the output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "doctype.dtd">
<html>
<head><title>Title of Page</title></head>
<body></body>
</html>
arturm at union dot com dot pl 06-May-2006 10:23
To create HTML document with doctype:

<?php
$doctype = DOMImplementation::createDocumentType("html",
                "-//W3C//DTD HTML 4.01//EN",
                "http://www.w3.org/TR/html4/strict.dtd");
$doc = DOMImplementation::createDocument(null, 'html', $doctype);
?>
DOMImplementation::__construct
DOMImplementation::createDocumentType
DOMImplementation


Создает пустой объект класса DOMDocumentType

DOMImplementation::createDocument
DOMImplementation::hasFeature
DOMImplementation
PHP Manual

DOMImplementation::createDocumentType

(PHP 5)

DOMImplementation::createDocumentType — Создает пустой объект класса DOMDocumentType

Описание

DOMDocumentType DOMImplementation::createDocumentType ([ string $qualifiedName = NULL [, string $publicId = NULL [, string $systemId = NULL ]]] )

Создает пустой объект класса DOMDocumentType. Объявления сущностей и условных обозначений будет недоступно. Ссылки на сущности не будут заменяться, и умолчания значений атрибутов не будут применены.

Список параметров

qualifiedName

Стандартизованное имя типа документа для создания.

publicId

Общедоступный идентификатор внешнего подмножества.

systemId

Системный идентификатор внешнего подмножества.

Возвращаемые значения

Новый объект класса DOMDocumentType с атрибутом ownerDocument установленным в NULL.

Ошибки

DOM_NAMESPACE_ERR

Возникает, если обнаружена ошибка в строке qualifiedName.

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Примеры

Пример #1 Создание документа с прикрепленной DTD

<?php

// Создает экземпляр класса DOMImplementation
$imp = new DOMImplementation;

// Создает экземпляр класса DOMDocumentType
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Создает объект DOMDocument
$dom = $imp->createDocument("", "", $dtd);

// установка других параметров
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// создание пустого элемента
$element = $dom->createElement('graph');

// присоединение элемента
$dom->appendChild($element);

// извлечение и печать документа
echo $dom->saveXML();

?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Смотрите также

  • DOMImplementation::createDocument() - Создает объект класса DOMDocument заданного типа с элементом document

User Contributed Notes

until-all-bytes-are-free at example dot org 09-Apr-2011 04:28
I had problems to use a DTD from a file. It needed to be resolved relatively and it contained characters that made DomDocument failed to resolve the file.

Encoding and an absolute filename did not help much. So I used the data:// streamwrapper ( http://php.net/manual/en/wrappers.data.php ) as a work-around:

<?php

// relative or absolute filename
$path = '...';

// convert file contents into a filename
$data = file_get_contents($path);
$systemId = 'data://text/plain;base64,'.base64_encode($data);

// ...

// Creates a DOMDocumentType instance
$dtd = $aImp->createDocumentType('qualified name', '', $systemId);

?>

Works like a charm.
DOMImplementation::createDocument
DOMImplementation::hasFeature
DOMImplementation


Тестирует реализацию специфичных возможностей объекта DOMImplementation

DOMImplementation::createDocumentType
DOMNamedNodeMap
DOMImplementation
PHP Manual

DOMImplementation::hasFeature

(PHP 5)

DOMImplementation::hasFeature — Тестирует реализацию специфичных возможностей объекта DOMImplementation

Описание

bool DOMImplementation::hasFeature ( string $feature , string $version )

Тестирует реализацию специфичной возможности feature объекта DOMImplementation.

Вы можете найти список всех возможностей в разделе » Согласование стандарта DOM.

Список параметров

feature

Тестируемая возможность.

version

Номер версии тестируемой возможности feature. В DOM level 2 это может быть либо 2.0, либо 1.0.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Ошибки

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Примеры

Пример #1 Тестирование Вашей реализации DOM

<?php

$features = array(
  'Core'           => 'Core module',
  'XML'            => 'XML module',
  'HTML'           => 'HTML module',
  'Views'          => 'Views module',
  'Stylesheets'    => 'Style Sheets module',
  'CSS'            => 'CSS module',
  'CSS2'           => 'CSS2 module',
  'Events'         => 'Events module',
  'UIEvents'       => 'User interface Events module',
  'MouseEvents'    => 'Mouse Events module',
  'MutationEvents' => 'Mutation Events module',
  'HTMLEvents'     => 'HTML Events module',
  'Range'          => 'Range module',
  'Traversal'      => 'Traversal module'
);

foreach ($features as $key => $name) {
  if (DOMImplementation::hasFeature($key, '2.0')) {
    echo "Реализует возможность $name\n";
  } else {
    echo "Возможность $name отсутствует\n";
  }
}

?>

Смотрите также

  • DOMNode::isSupported() - Проверяет, поддерживается ли заданное свойство в определенной версии

User Contributed Notes

There are no user contributed notes for this page.
DOMImplementation::createDocumentType
DOMNamedNodeMap
DOMImplementation


Класс DOMNamedNodeMap

(PHP 5)

Обзор классов

DOMNamedNodeMap {
/* Свойства */
readonly public int $length ;
/* Методы */
DOMNode getNamedItem ( string $name )
DOMNode getNamedItemNS ( string $namespaceURI , string $localName )
DOMNode item ( int $index )
}

Свойства

length

Количество узлов в отображении. Диапазон допустимых индексов узлов-потомков от 0 до length - 1 включительно.

Содержание

  • DOMNamedNodeMap::getNamedItem — Извлекает узел с заданным именем
  • DOMNamedNodeMap::getNamedItemNS — Извлекает узел с заданным локальным именем и URI пространства имен
  • DOMNamedNodeMap::item — Извлекает узел с заданным индексом

User Contributed Notes

kendsnyder at gmail dot com 29-Oct-2009 07:55
To add to xafford's comment. When iterating a named node map collection using ->item() or using foreach, removing a attribute with DOMNode->removeAttribute() or DOMNode->removeAttributeNode() alters the collection as if it were a stack. To illustrate, the code below tries to remove all attributes from each element but only removes the first. One work around is to copy the named node map into an array before removing attributes. Using PHP 5.2.9 on Windows XP.

<?php
error_reporting(E_ALL);
$html  = '<h1 id="h1test" class="h1test">Heading</h1>';
$html .= '<p align="left" class="ptest">Hello World</p>';

$doc = new DOMDocument();
$doc->loadHTML($html);

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; ++$i) {
    $name = $h1->attributes->item($i)->name;
    $h1->removeAttribute($name);
    echo "h1: removed attribute `$name`<br>";
}
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
foreach ($p->attributes as $name => $attrNode) {
    $p->removeAttribute($name);
    echo "p: removed attribute `$name`<br>";
}

?>

OUTPUT:
-------
h1: removed attribute `id`

Notice: Trying to get property of non-object in nodemap.php on line 13
h1: removed attribute ``
p: removed attribute `align`
xafford 15-Oct-2009 03:16
I stumbled upon a problem with DOMNamedNodeMap. If you iterate over a DOMNamedNodeMap, representing the attributes of a DOMElement with foreach and you use DOMElement::removeAttributeNode only the first attribute will be handled.

Example (not complete):

<?php

/*
 * Imagine you got a node like this:
 * <a onclick="alert('evil')" href="http://example.com">evil</a>
 * and onclick should be removed, href would not be tested.
 */

foreach ( $node->attributes as $attribute )
{

    echo 'checking attribute ', $attribute->name, '<br />';

    if ( ! in_array ( $attribute->name, $allowed_attributes ) )
    {
        $node->removeAttributeNode ( $attribute );
    }

}

?>

The output would be:

checking attribute onclick
jtaal at eljakim dot nl 18-Aug-2008 06:14
You can iterate over an instance of DOMNamedNodeMap:
<?php
// suppose $node is a valid DOMElement object
// $node->attributes will be NULL or a valid DOMNamedNodeMap object
foreach ($node->attributes as $attrName => $attrNode) {
}
?>
DOMImplementation::hasFeature
DOMNamedNodeMap::getNamedItem
DOM


Извлекает узел с заданным именем

DOMNamedNodeMap
DOMNamedNodeMap::getNamedItemNS
DOMNamedNodeMap
PHP Manual

DOMNamedNodeMap::getNamedItem

(PHP 5)

DOMNamedNodeMap::getNamedItem — Извлекает узел с заданным именем

Описание

DOMNode DOMNamedNodeMap::getNamedItem ( string $name )

Извлекает узел с заданным значением тэга nodeName.

Список параметров

name

Значение тэга nodeName искомого узла.

Возвращаемые значения

Узел (любого типа) с заданным значением тэга nodeName или NULL, если таковых не найдено.

Смотрите также

  • DOMNamedNodeMap::getNamedItemNS() - Извлекает узел с заданным локальным именем и URI пространства имен

User Contributed Notes

franp at free dot fr 03-Mar-2006 07:28
Basic example of use :

<?xml version="1.0" encoding="UTF-8"?>
<racine version="2.0a">
  <article/>
</racine>

<?php
(...)
 echo $doc->documentElement->attributes->getNamedItem("version")->nodeValue;

// returns "2.0a"
?>
DOMNamedNodeMap
DOMNamedNodeMap::getNamedItemNS
DOMNamedNodeMap


Извлекает узел с заданным локальным именем и URI пространства имен

DOMNamedNodeMap::getNamedItem
DOMNamedNodeMap::item
DOMNamedNodeMap
PHP Manual

DOMNamedNodeMap::getNamedItemNS

(PHP 5)

DOMNamedNodeMap::getNamedItemNS — Извлекает узел с заданным локальным именем и URI пространства имен

Описание

DOMNode DOMNamedNodeMap::getNamedItemNS ( string $namespaceURI , string $localName )

Извлекает узел с заданным локальным именем localName и URI пространства имен namespaceURI.

Список параметров

namespaceURI

URI пространства имен искомого узла.

localName

Локальное имя искомого узла.

Возвращаемые значения

Узел (любого типа) с заданным локальным именем и URI пространства имен или NULL, если таковых не найдено.

Смотрите также

  • DOMNamedNodeMap::getNamedItem() - Извлекает узел с заданным именем

User Contributed Notes

There are no user contributed notes for this page.
DOMNamedNodeMap::getNamedItem
DOMNamedNodeMap::item
DOMNamedNodeMap


Извлекает узел с заданным индексом

DOMNamedNodeMap::getNamedItemNS
DOMNode
DOMNamedNodeMap
PHP Manual

DOMNamedNodeMap::item

(PHP 5)

DOMNamedNodeMap::item — Извлекает узел с заданным индексом

Описание

DOMNode DOMNamedNodeMap::item ( int $index )

Извлекает узел с заданным индексом index из объекта класса DOMNamedNodeMap.

Список параметров

index

Индекс узла в отображении.

Возвращаемые значения

Узел с индексом index в отображении или NULL, если индекс имеет недопустимое значение (больше или равен количеству узлов в отображении).

User Contributed Notes

reyjacobs at yahoo dot com 07-Mar-2008 11:24
Nevermind: I got it, and here it is:

<?php
if($element->hasAttributes())
{
    $attributes = $element->attributes;
    if(!is_null($attributes))
    {
        foreach ($attributes as $index=>$attr)
        {
            echo $attr->name."=\"".$attr->value."\"";
        }
    }
}
?>
DOMNamedNodeMap::getNamedItemNS
DOMNode
DOMNamedNodeMap


Класс DOMNode

(PHP 5)

Обзор классов

DOMNode {
/* Свойства */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Методы */
public DOMNode appendChild ( DOMNode $newnode )
public string C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode cloneNode ([ bool $deep ] )
public int getLineNo ( void )
public string getNodePath ( void )
public bool hasAttributes ( void )
public bool hasChildNodes ( void )
public DOMNode insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool isDefaultNamespace ( string $namespaceURI )
public bool isSameNode ( DOMNode $node )
public bool isSupported ( string $feature , string $version )
public string lookupNamespaceURI ( string $prefix )
public string lookupPrefix ( string $namespaceURI )
public void normalize ( void )
public DOMNode removeChild ( DOMNode $oldnode )
public DOMNode replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

nodeName

Возвращает имя текущего узла

nodeValue

Возращает значение текущего узла

nodeType

Возвращает тип текущего узла. Возможные варианты возвращаемых значений nodeType перечисленны в разделе констатнты XML_xxx_NODE

parentNode

Возвращает родительский узел текущего узла

childNodes

Возвращает список DOMNodeList, содержащий всех потомков текущего узла. Если у узла нет потомков, возвращает пустой список DOMNodeList.

firstChild

Возвращает первый дочерний узел текущего узла. Если у узла нет потомков, возвращает NULL.

lastChild

Возвращает последний дочерний узел текущего узла. Если у узла нет потомков, возвращает NULL.

previousSibling

Возвращает предыдущий узел непосредственно от текущего узла. Если такого узла нет, возвращает NULL.

nextSibling

Возвращает следующий узел после текущего узла. Если такого узла нет, возвращает NULL.

attributes

Возвращает объект DOMNamedNodeMap, содержащий атрибуты текущего узла (только если это DOMElement), иначе вернёт NULL.

ownerDocument

Возвращает корневой узел DOMDocument текущего узла.

namespaceURI

Вернёт пространство имён текущего узла или NULL если оно не установленно.

prefix

Вернёт префикс текущего узла или NULL если оно не установленно.

localName

Возвращает локальное имя текущего узла.

baseURI

Возвращает универсальный код ресурса (URI) текущего узела или NULL, если не удалось получить URI.

textContent

Этот атрибут возвращает текстовое содержимое текущего узла и его потомков

Примечания

Замечание:

Расширение DOM использует кодировку UTF-8. Используйте функции utf8_encode() и utf8_decode() для работы с текстами в кодировке ISO-8859-1 или функцию Iconv для других кодировок.

Смотрите также

  • » Спецификация W3C элемента Node

Содержание

  • DOMNode::appendChild — Добавляет новый дочерний узел в конец списка потомков
  • DOMNode::C14N — Canonicalize nodes to a string
  • DOMNode::C14NFile — Canonicalize nodes to a file
  • DOMNode::cloneNode — Клонирует узел
  • DOMNode::getLineNo — Возвращает номер строки узла
  • DOMNode::getNodePath — Получение XPath пути к узлу
  • DOMNode::hasAttributes — Проверяет, содержит ли данный узел атрибуты
  • DOMNode::hasChildNodes — Проверяет, содержит ли данный узел потомков
  • DOMNode::insertBefore — Добавляет новый дочерний узел перед опорным узлом
  • DOMNode::isDefaultNamespace — Проверяет, совпадает ли URI пространства имен узла с пространством имен по умолчанию
  • DOMNode::isSameNode — Проверяет, являются ли два узла одним и тем же узлом
  • DOMNode::isSupported — Проверяет, поддерживается ли заданное свойство в определенной версии
  • DOMNode::lookupNamespaceURI — Получает URI пространства имен узла по префиксу
  • DOMNode::lookupPrefix — Возвращает префикс пространства имен узла из URI пространства имен
  • DOMNode::normalize — Нормализует узел
  • DOMNode::removeChild — Удаляет дочерний узел из списка потомков
  • DOMNode::replaceChild — Заменяет дочерний узел

User Contributed Notes

alastair dot dallas at gmail dot com 25-Sep-2011 08:44
The issues around mixed content took me some experimentation to remember, so I thought I'd add this note to save others time.

When your markup is something like: <div><p>First text.</p><ul><li><p>First bullet</p></li></ul></div>, you'll get XML_ELEMENT_NODEs that are quite regular. The <div> has children <p> and <ul> and the nodeValue for both <p>s yields the text you expect.

But when your markup is more like <p>This is <b>bold</b> and this is <i>italic</i>.</p>, you realize that the nodeValue for XML_ELEMENT_NODEs is not reliable. In this case, you need to look at the <p>'s child nodes. For this example, the <p> has children: #text, <b>, #text, <i>, #text.

In this example, the nodeValue of <b> and <i> is the same as their #text children. But you could have markup like: <p>This <b>is bold and <i>bold italic</i></b>, you see?</p>. In this case, you need to look at the children of <b>, which will be #text, <i>, because the nodeValue of <b> will not be sufficient.

XML_TEXT_NODEs have no children and are always named '#text'. Depending on how whitespace is handled, your tree may have "empty" #text nodes as children of <body> and elsewhere.

Attributes are nodes, but I had forgotten that they are not in the tree expressed by childNodes. Walking the full tree using childNodes will not visit any attribute nodes.
mjpelmear at gmail dot com 03-Jun-2011 01:33
getAttribute() returns an empty string if the requested attribute doesn't exist in the node.
stilgar at gilevski dot fakepart dot name 21-May-2011 01:17
If you have empty $node->textContent and $node->textValue, check if document that is loaded have UTF-8 encoding.
imranomar at gmail dot com 20-Mar-2011 06:10
Just discovered that node->nodeValue strips out all the tags
I. Cook 19-Apr-2010 02:43
For a reference with more information about the XML DOM node types, see http://www.w3schools.com/dom/dom_nodetype.asp

(When using PHP DOMNode, these constants need to be prefaced with "XML_")
R. Studer 13-Jan-2010 09:03
For clarification:
The assumingly 'discoverd' by previous posters and seemingly undocumented methods (.getElementsByTagName and .getAttribute) on this class (DOMNode) are in fact methods of the class DOMElement, which inherits from DOMNode.

See: http://www.php.net/manual/en/class.domelement.php
David Rekowski 08-Jan-2010 01:54
You cannot simply overwrite $textContent, to replace the text content of a DOMNode, as the missing readonly flag suggests. Instead you have to do something like this:

<?php

$node->removeChild($node->firstChild);
$node->appendChild(new DOMText('new text content'));

?>

This example shows what happens:

<?php

$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
echo "Content 1: ".$node->textContent."\n";

$node->textContent = 'new content';
echo "Content 2: ".$node->textContent."\n";

$newText = new DOMText('new content');

$node->appendChild($newText);
echo "Content 3: ".$node->textContent."\n";

$node->removeChild($node->firstChild);
$node->appendChild($newText);
echo "Content 4: ".$node->textContent."\n";

?>

The output is:

Content 1: old content // starting content
Content 2: old content // trying to replace overwriting $node->textContent
Content 3: old contentnew content // simply appending the new text node
Content 4: new content // removing firstchild before appending the new text node

If you want to have a CDATA section, use this:

<?php
$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
$node->removeChild($node->firstChild);
$newText = $doc->createCDATASection('new cdata content');
$node->appendChild($newText);
echo "Content withCDATA: ".$doc->saveXML($node)."\n";
?>
Steve K 03-Nov-2009 11:47
This class apparently also has a getElementsByTagName method.

I was able to confirm this by evaluating the output from DOMNodeList->item() against various tests with the is_a() function.
marc at ermshaus dot org 05-May-2009 08:36
It took me forever to find a mapping for the XML_*_NODE constants. So I thought, it'd be handy to paste it here:

 1 XML_ELEMENT_NODE
 2 XML_ATTRIBUTE_NODE
 3 XML_TEXT_NODE
 4 XML_CDATA_SECTION_NODE
 5 XML_ENTITY_REFERENCE_NODE
 6 XML_ENTITY_NODE
 7 XML_PROCESSING_INSTRUCTION_NODE
 8 XML_COMMENT_NODE
 9 XML_DOCUMENT_NODE
10 XML_DOCUMENT_TYPE_NODE
11 XML_DOCUMENT_FRAGMENT_NODE
12 XML_NOTATION_NODE
matt at lamplightdb dot co dot uk 06-Apr-2009 05:39
And apparently also a setAttribute method too:

$node->setAttribute( 'attrName' , 'value' );
jorge dot hebrard at gmail dot com 23-Jan-2009 05:29
Try canonicalization:
<?php
$dom = new DOMDocument;
$dom->loadHTMLFile('http://www.example.com/');
echo $dom->documentElement->C14N();
?>

Or output it to a file, using C14NFile()

Undocumented stuff ;)
brian wildwoodassociates.info 07-Dec-2008 11:27
This class has a getAttribute method.

Assume that a DOMNode object $ref contained an anchor taken out of a DOMNode List.  Then

    $url = $ref->getAttribute('href');

would isolate the url associated with the href part of the anchor.
DOMNamedNodeMap::item
DOMNode::appendChild
DOM


Добавляет новый дочерний узел в конец списка потомков

DOMNode
DOMNode::C14N
DOMNode
PHP Manual

DOMNode::appendChild

(PHP 5)

DOMNode::appendChild — Добавляет новый дочерний узел в конец списка потомков

Описание

public DOMNode DOMNode::appendChild ( DOMNode $newnode )

Функция добавляет дочерний узел к существующему списку потомков или создает новый список. Дочерний узел может быть создан с помощью DOMDocument::createElement(), DOMDocument::createTextNode() и т.д., или может быть использован любой другой узел.

Список параметров

newnode

Добавляемый дочерний узел.

Возвращаемые значения

Добавленный узел.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения или предыдущий родитель вставляемого узла доступен только для чтения.

DOM_HIERARCHY_REQUEST_ERR

Возникает, если тип узла не поддерживает потомков типа, который имеет узел newnode, или же если добавляемый узел является предком целевого узла или им самим.

DOM_WRONG_DOCUMENT_ERR

Возникает, если newnode создан в другом документе, отличном от того, в котором был создан этот узел.

Примеры

Следующий пример добавляет новый узел в только что созданный документ.

Пример #1 Добавление дочернего узла

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Смотрите также

  • DOMNode::removeChild() - Удаляет дочерний узел из списка потомков
  • DOMNode::replaceChild() - Заменяет дочерний узел

User Contributed Notes

frame at dynamiccreated dot de 01-Dec-2010 04:14
Aware dealing with DOMNodeList and appendChild() on the same Node.

If you want to replace only the children not the DOMElement itself you probably foreach childNodes-property or get the DOMElements with a for-loop and item()-method of the DOMNodeList.

You will fail if you not clone the received single DOMElement. Actually the count of the DOMNodelist will be decreased on appendChild count but appendChild seems to refer to the old Nodelist and nothing visible will happen. Cloning will help.
krisdover at hotmail dot com 31-May-2008 08:49
What's not mentioned here is that DOMNode::appendChild() can also be used to move an existing node to another part of the DOMDocument, e.g.

<?php
$doc = new DOMDocument();
$doc->loadXML("<foobar><bar/><foo/></foobar>");
$bar = $doc->documentElement->firstChild;
$foo = $doc->documentElement->lastChild;
$foo->appendChild($bar);
print $doc->saveXML();
?>

This produces:

<?xml version="1.0"?>
<foobar><foo><bar/></foo></foobar>

Note that the nodes "<foo/>" and "<bar/>" were siblings, i.e. the first and last child of "<foobar>" but using appendChild() we were able to move "<bar/>" so that it is a child of "<foo/>".

This saves you the trouble of doing a DOMNode::removeChild($bar) to remove "<bar/>" before appending it as a child of "<foo/>".

Kris Dover
jrtayloriv at gmail dot com 30-Mar-2008 04:56
If you want to create nested DOM elements:

<?php
    $doc = new DOMDocument();

    $foo = $doc->createElement("foo");
    $doc->appendChild($foo);

    $bar = $doc->createElement("bar");
    $foo->appendChild($bar);

    $bazz = $doc->createElement("bazz");
    $foo->appendChild($bazz);

    echo $doc->saveXML();
?>

Is equivalent to:

<foo>
  <bar></bar>
  <bazz></bazz>
</foo>
DOMNode
DOMNode::C14N
DOMNode


Canonicalize nodes to a string

DOMNode::appendChild
DOMNode::C14NFile
DOMNode
PHP Manual

DOMNode::C14N

(PHP 5 >= 5.2.0)

DOMNode::C14N — Canonicalize nodes to a string

Описание

public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )

Canonicalize nodes to a string

Список параметров

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

with_comments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

ns_prefixes

An array of namespace prefixes to filter the nodes by.

Возвращаемые значения

Returns canonicalized nodes as a string или FALSE в случае возникновения ошибки

Смотрите также

  • DOMNode::C14NFile() - Canonicalize nodes to a file

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::appendChild
DOMNode::C14NFile
DOMNode


Canonicalize nodes to a file

DOMNode::C14N
DOMNode::cloneNode
DOMNode
PHP Manual

DOMNode::C14NFile

(PHP 5 >= 5.2.0)

DOMNode::C14NFile — Canonicalize nodes to a file

Описание

public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )

Canonicalize nodes to a file.

Список параметров

uri

Path to write the output to.

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

with_comments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

ns_prefixes

An array of namespace prefixes to filter the nodes by.

Возвращаемые значения

Number of bytes written или FALSE в случае возникновения ошибки

Смотрите также

  • DOMNode::C14N() - Canonicalize nodes to a string

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::C14N
DOMNode::cloneNode
DOMNode


Клонирует узел

DOMNode::C14NFile
DOMNode::getLineNo
DOMNode
PHP Manual

DOMNode::cloneNode

(PHP 5)

DOMNode::cloneNode — Клонирует узел

Описание

public DOMNode DOMNode::cloneNode ([ bool $deep ] )

Создает копию узла.

Список параметров

deep

Указывает, нужно ли копировать всех потомков. Этот параметр по умолчанию имеет значение FALSE.

Возвращаемые значения

Копия узла.

User Contributed Notes

cemkalyoncu at gmail dot com 28-Apr-2009 03:04
If you need some function to clone a node without touching namespaces you can use the following.

<?php
private function cloneNode($node,$doc){
    $nd=$doc->createElement($node->nodeName);

    foreach($node->attributes as $value)
        $nd->setAttribute($value->nodeName,$value->value);

    if(!$node->childNodes)
        return $nd;

    foreach($node->childNodes as $child) {
        if($child->nodeName=="#text")
            $nd->appendChild($doc->createTextNode($child->nodeValue));
        else
            $nd->appendChild(cloneNode($child,$doc));
    }

    return $nd;
}
?>
[montana] at [percepticon] dot [com] 16-Feb-2009 02:23
<?php

//@oliver thanks for example source...

/*
 cloneNode(false) does not omit
 Attributes of cloned node,
 to achieve this an iteration is required.
 this is probably less efficient
 than merely creating a new
 node from the desired nodeName
 but in some cases could be useful.

use case:

omit subnodes and attributes of
secured portions of an xml document
without altering expected general structure;
*/
//xml to use

$file="<?xml version='1.0'?>
<book type='paperback'>
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first='Robert' middle='E' last='Howard'/>
        <birthdate disco='false' nirvana='definitely'>
            9/21/1977
            <month title='september' />
        </birthdate>
    </author>
    <author>
        <name first='Arthur' middle='Mc' last='Kayn'/>
    </author>
</book>";

$doc = new domDocument;

$doc->loadXML($file);

$xpath = new domXPath($doc);

$query = "//author/birthdate";
$xpathQuery = $xpath->query($query);

//would be a loop in production code...
$child = $xpathQuery->item(0);

$parent = $child->parentNode;

$doppel = $child->cloneNode(false);

$limit = $doppel->attributes->length;

for ($a=0;$a<$limit;$a++) {
    $doppel->removeAttributeNode($doppel->attributes->item(0));
}
//swap for now empty node
$parent->replaceChild( $doppel, $child);

print $doc->saveXML();

?>
oliver dot christen at camptocamp dot com 19-Nov-2004 08:48
simple exemple of node cloning

<?xml version="1.0"?>

<book type="paperback">
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first="Robert" middle="E" last="Howard"/>
        <birthdate>9/21/1977</birthdate>
    </author>
    <author>
        <name first="Arthur" middle="Mc" last="Kayn"/>
    </author>
</book>

<?php

//filename xml file to use
$file = 'book.xml';

$doc = new domDocument;

if (file_exists($file)) {
    $doc->load($file);
} else {
    exit('Erreur !.');
}

$xpath = new domXPath($doc);

$query = "//author/*";
$xpathQuery = $xpath->query($query);

$size = $xpathQuery->length;
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if ($node->nodeName == 'birthdate' && $node->hasChildNodes() && $node->firstChild->textContent != ''){
        $clonenode = $node->cloneNode(true);
        $refnode = $node;
    }
}
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if (!$node->isSameNode($refnode)){
        $newnode = $node->appendChild($clonenode);
    }
}

print $doc->saveXML();

?>
dtorop932 at hotmail dot com 18-Oct-2004 10:44
For those converting from PHP 4 DOM XML to PHP 5 DOM extension:

In the old days, DOM XML's clone_node() was the way to copy nodes from one DOM to another, as well as to perform intra-DOM copies.  Nowadays, DOM's cloneNode() is the intra-DOM solution, but see importNode() (http://php.net/dom-domdocument-importnode) to copy nodes from one DOM to another.

So to append root node of $dom2 and all its children into root node of $dom1:

PHP 4 (DOM XML):

<?php
$root1 = $dom1->document_element();
$other_node = $dom2->document_element();
$root1->append_child($other_node->clone_node(true));
?>

PHP 5 (DOM):

<?php
$dom1->documentElement->appendChild(
  $dom1->importNode($dom2->documentElement, true));
?>
DOMNode::C14NFile
DOMNode::getLineNo
DOMNode


Возвращает номер строки узла

DOMNode::cloneNode
DOMNode::getNodePath
DOMNode
PHP Manual

DOMNode::getLineNo

(PHP 5 >= 5.3.0)

DOMNode::getLineNo — Возвращает номер строки узла

Описание

public int DOMNode::getLineNo ( void )

Возвращает номер строки, в которой определен узел.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Всегда возращает номер строки, в которой был определен узел.

Примеры

Пример #1 Пример использования DOMNode::getLineNo()

<?php
// Определяем необходимый для примера XML
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node />
</root>
XML;

// Создаем новый экземпляр DOMDocument
$dom = new DOMDocument;

// Загружаем XML
$dom->loadXML($xml);

// Выводим номер строки, в которой определен элемент 'node'
printf('Тег <node> определен в строке %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

Результат выполнения данного примера:

Тег <node> определен в строке 3

User Contributed Notes

Anonymous 19-May-2012 02:21
The DOMNode::getLineNo() method doesn't work properly due to a libxml2 bug.

https://bugzilla.gnome.org/show_bug.cgi?id=676026
luke dot NOREPLY at webconnex dot com 04-Mar-2011 06:28
This function is buggy. It doesn't always return the correct line number, especially for text elements. As an alternative you can do something like this:

<?php
$text = $node->ownerDocument->saveXML($node);
$line += substr_count($text, "\n");
?>

You'll want to keep a reference to $line (starting at 0) and add to it as you parse over the document recursively.

In order for this to work you have to tell DOMDocument to preserve white space before loading the document.
DOMNode::cloneNode
DOMNode::getNodePath
DOMNode


Получение XPath пути к узлу

DOMNode::getLineNo
DOMNode::hasAttributes
DOMNode
PHP Manual

DOMNode::getNodePath

(PHP 5 >= 5.2.0)

DOMNode::getNodePath — Получение XPath пути к узлу

Описание

public string DOMNode::getNodePath ( void )

Получает путь XPath по которому расположен узел.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает строку (string) содержащую XPath либо NULL в случае ошибки.

Примеры

Пример #1 Пример использования DOMNode::getNodePath()

<?php
// Создание объекта DOMDocument
$dom = new DOMDocument;

// Загрузка XML
$dom->loadXML('
<fruits>
 <apples>
  <apple>braeburn</apple>
  <apple>granny smith</apple>
 </apples>
 <pears>
  <pear>conference</pear>
 </pears>
</fruits>
');

// Вывод XPath для каждого элемента
foreach ($dom->getElementsByTagName('*') as $node) {
    echo $node->getNodePath() . "\n";
}
?>

Результат выполнения данного примера:

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

Смотрите также

  • DOMXPath

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::getLineNo
DOMNode::hasAttributes
DOMNode


Проверяет, содержит ли данный узел атрибуты

DOMNode::getNodePath
DOMNode::hasChildNodes
DOMNode
PHP Manual

DOMNode::hasAttributes

(PHP 5)

DOMNode::hasAttributes — Проверяет, содержит ли данный узел атрибуты

Описание

public bool DOMNode::hasAttributes ( void )

Этот метод проверяет, содержит ли данный узел атрибуты. Проверяемый узел должен быть XML_ELEMENT_NODE.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMNode::hasChildNodes() - Проверяет, содержит ли данный узел потомков

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::getNodePath
DOMNode::hasChildNodes
DOMNode


Проверяет, содержит ли данный узел потомков

DOMNode::hasAttributes
DOMNode::insertBefore
DOMNode
PHP Manual

DOMNode::hasChildNodes

(PHP 5)

DOMNode::hasChildNodes — Проверяет, содержит ли данный узел потомков

Описание

public bool DOMNode::hasChildNodes ( void )

Эта функция проверяет, содержит ли данный узел потомков.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMNode::hasAttributes() - Проверяет, содержит ли данный узел атрибуты

User Contributed Notes

sansana 14-Oct-2010 07:04
Personally I think using a simple:[code]if($DOMNode->childNodes <>0){}[/code] works better.
syngcw at syncgw.com 04-Jan-2010 05:53
This function is a bit tricky. If you want to find XML childnodes it is useless. You need to create a work-around:

<?php

$x = new DOMDocument();
$x->loadXML('
<A>
 <B>b-text</B>
 <C>
  <D>d-text</D>
 </C>
 <E/>
</A>');

shownode($x->getElementsByTagName('A')->item(0));
function shownode($x) {
 foreach ($x->childNodes as $p)
  if (hasChild($p)) {
      echo $p->nodeName.' -> CHILDNODES<br>';
      shownode($p);
  } elseif ($p->nodeType == XML_ELEMENT_NODE)
   echo $p->nodeName.' '.$p->nodeValue.'<br>';
}
function hasChild($p) {
 if ($p->hasChildNodes()) {
  foreach ($p->childNodes as $c) {
   if ($c->nodeType == XML_ELEMENT_NODE)
    return true;
  }
 }
 return false;
}

?>

shows:
B b-text
C -> CHILDNODES
D d-text
E
jintoppy at gmail dot com 28-Apr-2009 04:13
<?php

$doc = new DOMDocument;
$node = $doc->createElement("FirstMain", "First Main Node. This have child");
$doc->appendChild($node);
$childnode = $doc->createElement("childnode", "child node");
$node->appendChild($childnode);
$secondnode = $doc->createElement("SecondMain", "First Main Node. This don't have child");
$doc->appendChild($secondnode);
$doc->saveXML();
$nodeElmt = $doc->getElementsByTagName("FirstMain");
/*
if given as $nodeElmt = $doc->getElementsByTagName("childnode");
the output would be "This node has childnodes"

if given as $nodeElmt = $doc->getElementsByTagName("SecondMain");
the output would be "This node has no childnodes"

*/

foreach($nodeElmt as $nodeElmt)
{
if($nodeElmt->hasChildNodes())
{
echo "This node has childnodes";
}
else
{
echo "This node has no childnodes";
}
}

  ?>

- - - - - - - - - - - - - -

Output:

This node has childnodes

- - - - - - - - - - - - - -
DOMNode::hasAttributes
DOMNode::insertBefore
DOMNode


Добавляет новый дочерний узел перед опорным узлом

DOMNode::hasChildNodes
DOMNode::isDefaultNamespace
DOMNode
PHP Manual

DOMNode::insertBefore

(PHP 5)

DOMNode::insertBefore — Добавляет новый дочерний узел перед опорным узлом

Описание

public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )

Данная функция вставляет новый узел перед опорным узлом. Чтобы дальше модифицировать добавляемый узел, необходимо использовать возвращаемый узел

Список параметров

newnode

Новый узел.

refnode

Опорный узел. Если отсутствует, то newnode добавляется в конец списка потомков.

Возвращаемые значения

Добавленный узел.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения или предыдущий родитель вставляемого узла доступен только для чтения.

DOM_HIERARCHY_REQUEST_ERR

Возникает, если тип узла не поддерживает потомков типа, который имеет узел newnode, или же если добавляемый узел является предком целевого узла или им самим.

DOM_WRONG_DOCUMENT_ERR

Возникает, если newnode создан в другом документе, отличном от того, в котором был создан этот узел.

DOM_NOT_FOUND

Возникает, если refnode не является дочерним узлом данного узла.

User Contributed Notes

felixsigl at gmail dot com 12-May-2009 03:17
I wrote a function for me to handle several insert modes (including insertAfter)

<?php

    public function myInsertNode($newNode, $refNode, $insertMode=null) {

        if(!$insertMode || $insertMode == "inside") {

            $refNode->appendChild($newNode);

        } else if($insertMode == "before") {

            $refNode->parentNode->insertBefore($newNode, $refNode);

        } else if($insertMode == "after") {

            if($refNode->nextSibling) {
                $refNode->parentNode->insertBefore($newNode, $refNode->nextSibling);
            } else {
                $refNode->parentNode->appendChild($newNode);
            }

        }

    }

?>
naholyr at yahoo dot fr 08-Feb-2009 03:52
A very usual needed function is "appendSibling" to insert a node just before another one :

<?php
/**
 * @param DOMNode $newnode Node to insert next to $ref
 * @param DOMNode $ref Reference node
 * @requires $ref has a parent node
 * @return DOMNode the real node inserted
 */
function appendSibling(DOMNode $newnode, DOMNode $ref)
{
  if ($ref->nextSibling) {
    // $ref has an immediate brother : insert newnode before this one
    return $ref->parentNode->insertBefore($newnode, $ref->nextSibling);
  } else {
    // $ref has no brother next to him : insert newnode as last child of his parent
    return $ref->parentNode->appendChild($newnode);
  }
}
?>
odonnell dot NOSPAM at ideaengineinc dot com 06-May-2008 01:57
Here's a usage example.

If you try this, you'll get an error message.

$refNode->insertBefore($newNode, $refNode);

Try this instead...

$refNode->parentNode->insertBefore($newNode, $refNode);
DrTebi at Yahoo 03-Oct-2007 05:54
Sorry, my previous posting worked only for the top node. Here the corrected version, which will work for any node:

XML
----
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person>
  <person>Thomas</person>
</contacts>

PHP
---
<?php
// load XML, create XPath object
$xml = new DomDocument();
$xml->preserveWhitespace = false;
$xml->load('contacts.xml');
$xpath = new DOMXPath($xml);

// get node eva, which we will append to
$eva = $xpath->query('/contacts/person[.="Eva"]')->item(0);

// create node john
$john = $xml->createElement('person', 'John');

// insert john after eva
//   "in eva's parent node (=contacts) insert
//   john before eva's next node"
// this also works if eva would be the last node
$eva->parentNode->insertBefore($john, $eva->nextSibling);

// show result
header('Content-Type: text/plain');
print $xml->saveXML();
?>

Result
------
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person><person>John</person>
  <person>Thomas</person>
</contacts>
justin at redwiredesign dot com 07-Feb-2007 08:20
The previous example is incorrect, and causes a DOM_NOT_FOUND error, as the child nodes are not direct descendants of the root node.

Therefore, the line:

$parent_path = "/root";

needs to change to:

$parent_path = "/root/parent";

or

$parent_path = "//parent";

for this example to work
25-Aug-2005 11:34
moving an existing node within the DomDocument:
<root>
  <parent>
    <child><name>Bob</name></child>
    <child><name>Sue</name></child>
  </parent>
</root>

$dom = new DomDocument();
$dom->load("sample.xml");

$parent_path = "/root";
$query = "//child[position() = 2]";
$query2 = "//child[position() = 1]";

$xpath = new DomXPath($dom);

$parent = $xpath->query($parent_path);

$under = $xpath->query($query);

$above = $xpath->query($query2);

$parent->item(0)->insertBefore($under->item(0), $above->item(0));

$dom->save("sample.xml");

Should produce:

<root>
  <parent>
    <child><name>Sue</name></child>
    <child><name>Bob</name></child>
  </parent>
</root>
jg at handcode dot de 18-Aug-2005 12:18
example to insert <newnode/> between <chid1/> and <child2/>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
  <parent>
    <child nr="1"/>
    <child nr="2"/>
  </parent>
</root>

<?php

$xml_src = 'test.xml';

// XPath-Querys
$parent_path = "//parent";
$next_path = "//parent/child[@nr='2']";

// Create a new DOM document
$dom = new DomDocument();
$dom->load($xml_src);

// Find the parent node
$xpath = new DomXPath($dom);

// Find parent node
$parent = $xpath->query($parent_path);

// new node will be inserted before this node
$next = $xpath->query($next_path);

// Create the new element
$element = $dom->createElement('newnode');

// Insert the new element
$parent->item(0)->insertBefore($element, $next->item(0));

echo $dom->saveXML();

?>
Jerry Ellis 03-Jun-2005 12:45
1st argument) a node to insert
2nd argument) a reference node - this is the node that the new node will be inserted before

The trick to using this method is that the OBJECT on which you actually CALL the insertBefore() method is actually the PARENT node of the reference node!

INCORRECT:
$DOMNode_refNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);

CORRECT:
$DOMNode_refNode->parentNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);
DOMNode::hasChildNodes
DOMNode::isDefaultNamespace
DOMNode


Проверяет, совпадает ли URI пространства имен узла с пространством имен по умолчанию

DOMNode::insertBefore
DOMNode::isSameNode
DOMNode
PHP Manual

DOMNode::isDefaultNamespace

(PHP 5)

DOMNode::isDefaultNamespace — Проверяет, совпадает ли URI пространства имен узла с пространством имен по умолчанию

Описание

public bool DOMNode::isDefaultNamespace ( string $namespaceURI )

Сообщает, является ли namespaceURI пространством имен по умолчанию.

Список параметров

namespaceURI

URI пространства имен.

Возвращаемые значения

Возвращает TRUE если namespaceURI является пространством имен по умолчанию или FALSE в противном случае.

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::insertBefore
DOMNode::isSameNode
DOMNode


Проверяет, являются ли два узла одним и тем же узлом

DOMNode::isDefaultNamespace
DOMNode::isSupported
DOMNode
PHP Manual

DOMNode::isSameNode

(PHP 5)

DOMNode::isSameNode — Проверяет, являются ли два узла одним и тем же узлом

Описание

public bool DOMNode::isSameNode ( DOMNode $node )

Эта функция проверяет, являются ли два узла одним и тем же узлом. Данное сравнение происходит не на основе содержимого узлов.

Список параметров

node

Сравниваемый узел.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::isDefaultNamespace
DOMNode::isSupported
DOMNode


Проверяет, поддерживается ли заданное свойство в определенной версии

DOMNode::isSameNode
DOMNode::lookupNamespaceURI
DOMNode
PHP Manual

DOMNode::isSupported

(PHP 5)

DOMNode::isSupported — Проверяет, поддерживается ли заданное свойство в определенной версии

Описание

public bool DOMNode::isSupported ( string $feature , string $version )

Проверяет, поддерживается ли заданное свойство feature в определенной версии version.

Список параметров

feature

Название свойства для проверки. Список названий модулей приведен в примере к DOMImplementation::hasFeature().

version

Номер версии модуля (feature) для проверки.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • DOMImplementation::hasFeature() - Тестирует реализацию специфичных возможностей объекта DOMImplementation

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::isSameNode
DOMNode::lookupNamespaceURI
DOMNode


Получает URI пространства имен узла по префиксу

DOMNode::isSupported
DOMNode::lookupPrefix
DOMNode
PHP Manual

DOMNode::lookupNamespaceURI

(PHP 5)

DOMNode::lookupNamespaceURI — Получает URI пространства имен узла по префиксу

Описание

public string DOMNode::lookupNamespaceURI ( string $prefix )

Получает URI пространства имен узла по префиксу prefix.

Список параметров

prefix

Префикс пространства имен.

Возвращаемые значения

URI пространства имен узла.

Смотрите также

  • DOMNode::lookupPrefix() - Возвращает префикс пространства имен узла из URI пространства имен

User Contributed Notes

_ michael 30-Apr-2010 02:22
You have to pass *null* to lookupNamespaceURI if you want to read the default namespace. Passing an empty string doesn't work - even though the documentation says that lookupNamespaceURI takes a string as argument (and null would just be converted to an empty string).
lewar 05-Jun-2007 05:20
Simple way to get the URI of the default namespace:

<?php
    $document = new DOMDocument();
    $document->load($xml_file);
    $uri = $document->documentElement->lookupnamespaceURI(NULL);
?>
DOMNode::isSupported
DOMNode::lookupPrefix
DOMNode


Возвращает префикс пространства имен узла из URI пространства имен

DOMNode::lookupNamespaceURI
DOMNode::normalize
DOMNode
PHP Manual

DOMNode::lookupPrefix

(PHP 5)

DOMNode::lookupPrefix — Возвращает префикс пространства имен узла из URI пространства имен

Описание

public string DOMNode::lookupPrefix ( string $namespaceURI )

Возвращает префикс пространства имен узла из URI пространства имен.

Список параметров

namespaceURI

URI пространства имен.

Возвращаемые значения

Префикс пространства имен.

Смотрите также

  • DOMNode::lookupNamespaceURI() - Получает URI пространства имен узла по префиксу

User Contributed Notes

There are no user contributed notes for this page.
DOMNode::lookupNamespaceURI
DOMNode::normalize
DOMNode


Нормализует узел

DOMNode::lookupPrefix
DOMNode::removeChild
DOMNode
PHP Manual

DOMNode::normalize

(PHP 5)

DOMNode::normalize — Нормализует узел

Описание

public void DOMNode::normalize ( void )

Нормализует узел.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • » Спецификация DOM
  • DOMDocument::normalizeDocument() - Нормализует документ

User Contributed Notes

Amir Laher 22-Aug-2005 04:45
This is a quote from the DOM level 2 spec, explaining the normalize() function.
----
normalize
Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer [XPointer] lookups) that depend on a particular document tree structure are to be used.
----
(source: http://www.w3.org/TR/DOM-Level-2-Core/core.html)

i.e. the idea of normalize is to make text nodes the same as they would be if the xml document was re-loaded into DOM. It's handy if you want to compare DOM nodes.
DOMNode::lookupPrefix
DOMNode::removeChild
DOMNode


Удаляет дочерний узел из списка потомков

DOMNode::normalize
DOMNode::replaceChild
DOMNode
PHP Manual

DOMNode::removeChild

(PHP 5)

DOMNode::removeChild — Удаляет дочерний узел из списка потомков

Описание

public DOMNode DOMNode::removeChild ( DOMNode $oldnode )

Эта функция удаляет дочерний узел из списка потомков.

Список параметров

oldnode

Удаляемый дочерний узел.

Возвращаемые значения

Функция возращает удаляемый дочерний узел, если он может быть удален.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения.

DOM_NOT_FOUND

Возникает, если oldnode не является дочерним узлом данного узла.

Примеры

Следующий пример удаляет элемент chapter (глава) из XML-документа.

Пример #1 Удаление дочернего узла

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// находим главу (chapter) и удалям из книги (book)
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>

</book>

Пример #2 Сохраняем URI пространства имен родительского узла

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// находим главу (chapter) и удалям из книги (book)
$chapter = $book->getElementsByTagName('chapter')->item(0);

// копируем URI пространства имен
$nsuri = $book->namespaceURI;

// удаляем дочерний узел
$book->removeChild($chapter);

// вставляем URI пространства имен обратно в родительский узел
$book->namespaceURI = $nsuri;
?>

Примечания

Замечание:

После вызова этого метода свойство DOMNode::$namespaceURI родительского узла сбрасывается в NULL. В примере выше показано, как это обойти.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMNode::replaceChild() - Заменяет дочерний узел

User Contributed Notes

julien dot mulac at gmail dot com 14-Dec-2010 02:56
For the loop bug, you have to use the parent node of the node itself :

<?php
$nodeList = $doc->getElementsByTagName('p');

for ($i = 0; $i < $nodeList->length; $i++) {
    try {
        $old_child = $nodeList->item($i)->parentNode->removeChild($nodeList->item($i));
    } catch (DOMException $e) {
        echo $e->getMessage();
    }
}
?>
drimsun at gmail dot com 11-Feb-2010 03:37
If you try to remove children of a nested node (e.g. a <ul> list that contains another <ul>) and only remove the first level of child nodes, you'll get a messed-up node object.

Upon re-use of the messed-up node you'll get an error message that says: "Fatal error: Call to a member function blahblah() on a non-object".

To remove ALL child nodes, use this recursive function instead:
<?php
/**
 * Helper function that removes all child nodes of $node recursively
 * (i.e. including child nodes of the child nodes and so forth).
 */
function remove_children(&$node) {
  while ($node->firstChild) {
    while ($node->firstChild->firstChild) {
      remove_children($node->firstChild);
    }
    $node->removeChild($node->firstChild);
  }
}
?>
Justin Carlson 05-Nov-2009 11:46
Just a note, if you remove a node the whitespace it occupied will remain if you save the file.

To avoid this, use $document->preserveWhiteSpace = false;

For Example:

<?php
$document = new DomDocument();
$document->preserveWhiteSpace = false;
?>
crazy888s at hotmail dot com 15-Apr-2009 01:50
You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
foreach ( $domNodeList as $domElement ) {
  //  ...do stuff with $domElement...
  $domElement->parentNode->removeChild($domElement);
}
?>

... will seemingly leave the internal iterator on the foreach out of wack and results will be quite strange. Though, making a queue of items to remove seems to work. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
  // ...do stuff with $domElement...
  $domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
  $domElement->parentNode->removeChild($domElement);
}
?>
Justin Sheckler 30-Jan-2009 08:44
These two functions might be helpful to anyone trying to delete a node and all of its children:

<?php
function deleteNode($node) {
    deleteChildren($node);
    $parent = $node->parentNode;
    $oldnode = $parent->removeChild($node);
}

function deleteChildren($node) {
    while (isset($node->firstChild)) {
        deleteChildren($node->firstChild);
        $node->removeChild($node->firstChild);
    }
}
?>
tim cameron ryan 19-Jul-2008 01:00
Or something like:

<?php

while ($node->childNodes->length)
     $node->removeChild($node->firstChild);

?>
Michael D (DigitalGemstones.com) 05-Jul-2008 04:15
Note that iterating through the childNodes array and removing those children will stop the iteration.

For example:
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
     $child->parentNode->removeChild($child);
}

Will not work.  Note that in removing the node, the childNodes array gets rebuilt (it seems) and so only the first item will be removed.  In order to properly remove all the children you want to remove, you will need to do something like the following:

$nodesToDelete = array();
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
    $nodesToDelete[] = $child;
}
foreach($nodesToDelete as $node)
{
  $node->parentNode->removeChild($node);
}

I believe this is actually more efficient than the first snippet would be (if it worked) but obviously I cannot benchmark it.
Wala 04-Apr-2008 10:57
I used the following to delete an entire node using the child element:

<?php
$childElement->parentNode->parentNode-> removeChild($childElement->parentNode);
?>

I could not have thought of it without the help of everyone who contributed to this thread.

Thanks!

(I had to introduce the extra space between parentNode->removeChild to get rid of the wordwrap() warning while posting this note)
Vasil Rangelov 06-Oct-2007 10:14
At the time of writing, I suppose rightfully, removeChild() removes only the selected node, but when you remove an element, it's child elements are not removed. If you want to achieve that, replaceChild() is the solution.

The following should remove all descendants of the $node DOMNode, regardless of it's name:
<?php
$node->replaceChild(new DOMElement($node->nodeName), $node);
?>
If you're replacing the root element, you must explicitly state that with $node->documentElement as the second argument.
lsoethout at hotmail dot com 11-Mar-2007 09:08
The previous example is not correct; it only works when the tags are direct childs of the top-level node.
Better is:

while($elem = $dom->getElementsByTagName("name")->item(0)) {
   $elem->parentNode->removeChild($elem);
}
dave at dgx dot cz 27-Aug-2006 06:10
remove all children of a given node (simple way):

$node->nodeValue = '';
mytto at openxtrem dot com 07-Sep-2005 02:20
Back again on removing childs and iterators robustness.

Things get a bit more complicated when you only want to remove 'some' nodes according to a certain condition. Then you can't just remove the first one repeatedly.

The trick is to copy the content of the node list into a more robust collection than DOMNodeList, I name array!

The following piece of code will, for instance, remove all empty child nodes:

<?php
// Copy childNodes array
$childNodes = array();
foreach($node->childNodes as $childNode) {
  $childNodes[] = $childNode;
}

// Browse with the copy
foreach ($childNodes as $childNode) {
  if (!$childNode->hasChildNodes()); {
    $childNode->parentNode->removeChild($childNode);
  }
}
?>
karan 28-Aug-2005 02:48
can we directly remove a node which has some children or do we need to remove the children first.

 while($mytn->hasChildNodes())
    {
     $mytn->removeChild($mytn->childNodes->item(0));
    }

echo $j;//this shows correct no of children

echo $mytn->childNodes->length;//after removing it
                                         // shows 0..correct

$dom->save(net.xml);

but the changes r not reflected in the xml file
blaine (at) blainegarrett (dot com) 23-Aug-2005 10:10
This might be obvious, but might help someone as well...

If you simply have a node that you need to remove (perhaps from an xpath) and don't know the parent node offhand (the examples seem to assume you have the parent in a variable), then you can do something easy like this...

$node->parentNode->removeChild($node);

parentNode is a scalar property of the Element.

Hope that helps.

--
Blaine Garrett
Executive Director of the Art Attack
http://theartattack.org
pedro at leb dot usp dot br 30-May-2005 04:24
You may also use the hasChild function:
<?php

while($node->hasChildNodes()) {
  $node->removeChild($node->childNodes->item(0));
}

?>

When you remove a childNode, the next node becomes the first one!
vsematika at centrum dot cz 13-Feb-2005 03:35
For those who don't understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07< 'hack', here's a little discussion:

First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
   $parent->removeChild($child);
?>
This doesn't work because DOM tree id modified on-the-fly and this confuses foreach loop.

The idea behind sbeam's trick is that after removing the first item in the first iteration, the second item in childNodes nodelist immediately becomes the first item. That's why we must _always_ remove the first child. Here's another implementation:

<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
   $oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>
sbeam at onsetcorps dot net 02-Feb-2005 09:07
remove all children of a given node:

while ($parent->childNodes->length) {
      $parent->removeChild($parent->childNodes->item(0));
}
DOMNode::normalize
DOMNode::replaceChild
DOMNode


Заменяет дочерний узел

DOMNode::removeChild
DOMNodeList
DOMNode
PHP Manual

DOMNode::replaceChild

(PHP 5)

DOMNode::replaceChild — Заменяет дочерний узел

Описание

public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )

Функция заменяет дочерний узел oldnode новым узлом. Если новый узел уже является дочерним, то не будет добавлен во второй раз. Если замена прошла успешно, то будет возвращен старый (заменяемый) узел.

Список параметров

newnode

Новый узел. Должен быть частью целевого документа, то есть создан посредством одного из методов DOMDocument->createXXX() или импортирован в документ через DOMDocument::importNode.

oldnode

Старый узел.

Возвращаемые значения

Старый узел или FALSE в случае возникновения ошибки.

Ошибки

DOM_NO_MODIFICATION_ALLOWED_ERR

Возникает, если узел доступен только для чтения или предыдущий родитель вставляемого узла доступен только для чтения.

DOM_HIERARCHY_REQUEST_ERR

Возникает, если тип узла не поддерживает потомков типа, который имеет узел newnode, или же если добавляемый узел является предком целевого узла или им самим.

DOM_WRONG_DOCUMENT_ERR

Возникает, если newnode создан в другом документе, отличном от того, в котором был создан этот узел.

DOM_NOT_FOUND

Возникает, если oldnode не является дочерним узлом данного узла.

Смотрите также

  • DOMNode::appendChild() - Добавляет новый дочерний узел в конец списка потомков
  • DOMNode::removeChild() - Удаляет дочерний узел из списка потомков

User Contributed Notes

jb at jbpros dot com 01-Mar-2005 08:08
If you are trying to replace more than one node at once, you have to be careful about iterating over the DOMNodeList.  If the old node has a different name from the new node, it will be removed from the list once it has been replaced.  Use a regressive loop:

<?php

$xml = new DOMDocument;
$xml->load('docfile.xml');

$elements = $xml->getElementsByTagNameNS('http://www.example.com/NS/', '*');
$i = $elements->length - 1;
while ($i > -1) {
    $element = $elements->item($i);
    $ignore = false;

    $newelement = $xml>createTextNode('Some new node!');
    $element->parentNode->replaceChild($newelement, $element);
    $i--;
}

?>

The loop counter ($i) will always be in the list's interval as removed elements indexes are above the counter.
aidan at php dot net 26-Dec-2004 02:17
Here is a simple example for replacing a node:

Let's define our XML like so:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<root>
  <parent>
     <child>bar</child>
     <child>foo</child>
  </parent>
</root>
XML;
?>

If we wanted to replace the entire <parent> node, we could do something like this:

<?php
// Create a new document fragment to hold the new <parent> node
$parent = new DomDocument;
$parent_node = $parent ->createElement('parent');

// Add some children
$parent_node->appendChild($parent->createElement('child', 'somevalue'));
$parent_node->appendChild($parent->createElement('child', 'anothervalue'));

// Add the keywordset into the new document
// The $parent variable now holds the new node as a document fragment
$parent->appendChild($parent_node);
?>

Next, we need to locate the old node:

<?php
// Load the XML
$dom = new DomDocument;
$dom->loadXML($xml);

// Locate the old parent node
$xpath = new DOMXpath($dom);
$nodelist = $xpath->query('/root/parent');
$oldnode = $nodelist->item(0);
?>

We then import and replace the new node:

<?php
// Load the $parent document fragment into the current document
$newnode = $dom->importNode($parent->documentElement, true);

// Replace
$oldnode->parentNode->replaceChild($newnode, $oldnode);

// Display
echo $dom->saveXML();
?>

Our new node is successfully imported:

<?xml version="1.0"?>
<root>
<parent><child>somevalue</child><child>anothervalue</child></parent>
</root>
franp at free dot fr 23-Sep-2004 08:39
1) If your XPath query returns a NodeList including a unique item, or if you know for sure the order of the items returned, you can use the "item(n)" syntax instead of the "foreach" syntax.
This can greatly improve you code lisibility.
s the method name implies, replaceChild cannot replace a node itself but a child of a node.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
 <actionGlobal>
  <actionGlobalFR>sometext</actionGlobalFR>
 <actionGlobal>
</action>

$frag = $doc->createElement("actionGlobalFR");
$fragA = $doc->createTextNode("anothertext");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/actionGlobal/actionGlobalFR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($ajout, $xpResult->item(0));

2) Also, as the method name implies, replaceChild cannot replace a node itself but a child of a node.
Still it is possible to replace a node pointed by XPath istead of its child.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
  <FR>French Text</FR>
</action>

<?php
$frag = $doc->createElement("EN");
$fragA = $doc->createTextNode("English Text");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/FR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($fragA, $xpResult->item(0));
?>

Et voil� !

This produces :
<?xml version="1.0" ?>
<action>
  <EN>English Text</EN>
</action>

....................................................

3) Also, be carefull, you CANNOT replace a node that doesn't exist.
While this may seems obvious, it is easy to forget.

Consider this :
<?xml version="1.0" ?>
<action>
  <EN></EN>
</action>

You cannot use replaceChild() to turn this into :
<?xml version="1.0" ?>
<action>
  <EN>Some text</EN>
</action>

The reason is that since the <EN></EN> element is empty, it has no child (this is clearer to understand if you consider that <EN></EN> can be written <EN />).
The fact that you intend to put some text inbetween <EN> and </EN> does not change the fact that it has no text yet, thus no child yet.
When dealing with DOM, do not take your dream for the reality. The DOM parser doen't care about your dreams. If an element is currently empty, it has no child, whatever you intend to fill in.

Thus, the solution to teh problem is to use appendChild intead of replaceChild :

<?php
$fragA = $doc->createTextNode("Some Text");
$xpResult = $xp->query("/action/EN");
$blipblip = $xpResult->item(0)->appendChild($fragA);
?>

This produces the awaited :
<?xml version="1.0" ?>
<action>
  <EN>Some Text</EN>
</action>

....................................................

4) Note that the description of replaceChild in the doc is wrong. Arguments have been inverted.
The correct description is :
object DOMNode->replaceChild (object newnode, object oldnode)
DOMNode::removeChild
DOMNodeList
DOMNode


Класс DOMNodeList

(PHP 5)

Обзор классов

Traversable
DOMNodeList {
/* Свойства */
readonly public int $length ;
/* Методы */
DOMNode DOMNodelist::item ( int $index )
}

Свойства

length

Количество узлов, вошедших в список. Индексы в узлов списке лежат в промежутке от 0 до length - 1 включительно.

Содержание

  • DOMNodelist::item — Извлекает узел с заданным индексом

User Contributed Notes

geompse at gmail dot com 19-May-2010 08:39
Note that $length is calculated (php5.3.2).
Iterating over a large NodeList may be time expensive.

Prefer :
$nb = $nodelist->length;
for($pos=0; $pos<$nb; $pos++)

Than:
for($pos=0; $pos<$nodelist->length; $pos++)

I had a hard time figuring that out...
walt at brookhouse dot co dot uk 16-Oct-2009 09:53
Below a.lepe says, "Using NodeLists to store results of an XQuery..."

To clarify, this should say, "...the results of an XPath query...".

XQuery contains XPath but has additional functionality such as FLOWR expressions. PHP does not directly support XQuery (yet!).
A dot Lepe dev+php at alepe dot com 01-Oct-2009 10:53
Using NodeLists to store results of an XQuery is not very functional if you are planning to do some operations with those Nodes. Instead, you can use an array in this way:

<?php
$nodelist = $xpath->query($xpath, $DOMdoc);
foreach ($nodelist as $node) {
    // you can add here a special conditions, as searching for
    // regular expression matches in your nodes names/values/attributes
    // which can not be achieved with XSLT 1.0
    if( .... )  $nodearr[] = $node;
}
?>

This way, you can access nodes like (for example):

<?php
$nodearr[0]->nodeValue;
?>

solving the problem described by "saad0105050" (06-Jul-2008)

Even more, you can perform other operations in your results
as removing elements, reversing order, randomize, callbacks, etc.
nascoedu 18-Sep-2008 03:44
Get some nodes from an existing xml file and add them to a new file:

<?php
$dom = new DOMDocument;
$dom->load($xmlsource);

/*create the xPath object _after_  loading the xml source, otherwise the query won't work:*/
$xPath = new DOMXPath($dom);

/*now get the nodes in a DOMNodeList:*/
$nodeList = $xPath->query($anXPathExpr);

/*create a new DOMDocument and add a root element:*/
$newDom = new DOMDocument('1.0','UTF-8');
$root = $newDom->createElement('root');
$root = $newDom->appendChild($root);

/* append all nodes from $nodeList to the new dom, as children of $root:*/
foreach ($nodeList as $domElement){
   $domNode = $newDom->importNode($domElement, true);
   $root->appendChild($domNode);
}
/*please note: importNode does not cast a DOMElement to a DOMNode!*/

/*save the new dom */
echo 'Wrote: ' . $newDom->save('newDOM.xml') . ' bytes';
?>

the following won't work and you'll end up with a DOMException: 'Wrong Document Error' (at least I did):

<?php
foreach ($nodeList as $element){
   $root->appendChild($element);
}
?>

Cheers! ;-)
---
WindowsXP, WAMP5 (appache 2.2.6), PHP 5.2.5, DOM/XML API Version 20031129, libxml 2.6.26
---
c dot 1 at smithies dot org 27-Aug-2008 03:26
I doubt the accuracy of what saad105050 wrote below. In particular, in his example, he seems to assume that $element->getElementsByTagName() will return NULL if there are no matching nodes. This is not what happens; as per the documentation, a DOMNodeList is returned with the length property zero.
bobvandell at hotmail dot com 26-Aug-2008 09:12
That's actually incorrect. You can use function results as objects. It makes building an API for your database very clean and neat. For example:

Our code:

$articles = Node::screate('tags', 123456)->assets('like:title:test')->articles;

We use the above code to get articles that are linked to assets that are linked to a specific tag in our database.
rohypnol 14-Jul-2008 12:28
That's simply because up to and including PHP 5 (latest version at this time) you can't use a function result as an object even if it is an object.

Work:
1) $obj->sub_obj->method();
2) $sub_obj = $obj->get_sub_obj();
   $sub_obj->method();

Don't work:
1) $obj->get_sub_obj()->method();
2) echo $obj->get_sub_obj()->property;
saad0105050 at gmail dot com 06-Jul-2008 10:10
Problem with accessing return value of DOMNodeList::item() method.

When using the following code segment:
---------------------

$messageNodes = $doc->getElementsByTagName( "message" );
if( $messageNodes != NULL )
{
     $messageStr = $messageNodes->item( 0 )->firstChild->nodeValue;
}
---------------------
PHP gives an error: "syntax error, unexpected T_OBJECT_OPERATOR"

But if I modify it like the following:
---------------------
$messageNodes = $doc->getElementsByTagName( "message" );
if( $messageNodes != NULL )
{
    $messageNode = $messageNodes->item( 0 );
    $messageStr =  messageNode->firstChild->nodeValue;
}
---------------------
There is no error.

I guess, the return element of DOMNodeList::item() function can not be readily accessed via "->" operator.
mark at codedesigner dot nl 05-Jun-2008 03:14
$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as $node) {
  echo $node->nodeValue ;
  $newNode->appendChild($node) ;
}

the problem lies with the fact that foreach works on a copy of your object. The solution is simple, add & to $node

$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as &$node) {
  echo $node->nodeValue ;
  $newNode->appendChild($node) ;
}
a dot buffa at sns dot it 29-May-2008 04:28
I agree with drichter at muvicom dot de.

For istance, in order to delete each child node of a particular parent node,
<?php

while ($parentNode->hasChildNodes()){
  $domNodeList = $parentNode->childNodes;
  $parentNode->removeChild($domNodeList->item(0));
}

?>

In other word you have to uptade the DomNodeList on every iteration.

In my opinion, the DomNodeList class is useless.
c dot 1 at smithies dot org 23-May-2008 05:43
You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards:

$els = $document->getElementsByTagName('input');
for ($i = $els->length; --$i >= 0; ) {
  $el = $els->item($i);
  switch ($el->getAttribute('name')) {
    case 'MAX_FILE_SIZE' :
      $el->parentNode->removeChild($el);
    break;
    case 'inputfile' :
      $el->setAttribute('type', 'text');
    //break;
  }
}
drichter at muvicom dot de 14-May-2008 06:11
Addition to my first note:

An traditional for-loop does not allow you to change the DOM-tree while looping - the effects are the nearly the same as with foreach. So you have to collect the nodes in an array and do the tree-altering stuff within a second loop (looping the array this time ...)
drichter at muvicom dot de 14-May-2008 04:56
I have done some testing and have found 2 results:
(My System: Win XP with PHP 5.2.1)

1) Iteration with foreach does function correctly as "james dot j dot hackett at gmail dot com" writes, _if_ you only do readonly stuff with foreach or minor writings of some attributes.

2) foreach does not function, if you are doing some DOM-Operations while iterating. In my situation it was adding the iterated $node as an child to an new node:

$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as $node) {
  echo $node->nodeValue ;
  $newNode->appendChild($node) ;
}

This only gives you the first element ...

I'm interpreting it as an confusing but correct behavior because of the changes within the $dom-object while appending the node at an additional place ...

So, if you want to do something like 2) use for, length and item() :)
james dot j dot hackett at gmail dot com 08-May-2008 09:47
In Response to 'kassah at gmail'

You don't need to convert a DOMNodeList to an array in order iterate through it using 'foreach'.  You can use foreach directly with the DOMNodeList.

$nodeList = $someDomDocument->getElementsbytagname('user');

foreach ($nodeList as $node) {
    echo $node->nodeValue;
}
kassah at gmail dot com 04-May-2008 05:06
// Converts a DOMNodeList to an Array that can be easily foreached
function dnl2array($domnodelist) {
    $return = array();
    for ($i = 0; $i < $domnodelist->length; ++$i) {
        $return[] = $domnodelist->item($i);
    }
    return $return;
}
brack at wjp dot de 21-Apr-2008 02:35
In PHP 5.2.5 (Windows) it is not possible to iterate correctly over the DOMNodeList object returned by DOMNode->childNodes using foreach. Instead I had to use the for loop in conjunction with the item() method of DOMNodeList for iterating over all child nodes correctly.

I don't know whether this is really a bug, but apparently it is.
DOMNode::replaceChild
DOMNodelist::item
DOM


Извлекает узел с заданным индексом

DOMNodeList
DOMNotation
DOMNodeList
PHP Manual

DOMNodelist::item

(PHP 5)

DOMNodelist::item — Извлекает узел с заданным индексом

Описание

DOMNode DOMNodelist::item ( int $index )

Извлекает узел с заданным индексом index из объекта класса DOMNodeList.

Подсказка

Если требуется узнать количество узлов в коллекции, используйте свойство length объекта класса DOMNodeList.

Список параметров

index

Индекс узла в коллекции.

Возвращаемые значения

Узел, находящийся в позиции index объекта DOMNodeList, или NULL, если этот индекс недопустим.

Примеры

Пример #1 Вывод содержимого таблицы

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}

?>

Также можно воспользоваться оператором foreach; в данном случае этот вариант является более удобным и предпочтительным:

<?php

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}

?>

Результат выполнения данного примера:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

User Contributed Notes

Nagy Attila 06-Jan-2011 09:02
DOMNodeList::item does not return in constant time!

If you need to iterate over large nodelist then you'd better use standard navigation.

Instead of:

<?php
foreach ($nodelist as $node) {
    // do something
}
?>

you could do:

<?php
$node = $parentnode->firstChild;

do {
    // do something
} while ($node = $node->nextSibling);
?>
olivier dot berger at it-sudparis dot eu 21-Aug-2008 02:56
It seems that with zend.ze1_compatibility_mode on, the only way to iterate over the items list is with :
for ($i = 0; $i < $nodeList->length; ++$i) {
    $nodeName = $nodeList->item($i)->nodeName;
    $nodeValue = $nodeList->item($i)->nodeValue;
}

As other attemps failed :

for ($i = 0; $i < $nodeList->length; ++$i) {
    $node = &$nodeList->item($i);
    $nodeName = $node->nodeName;
    $nodeValue = $node->nodeValue;
}

or :
foreach ($nodeList as $node) {
    echo $node->nodeName;
    echo $node->nodeValue;
}
vinyanov at poczta dot onet dot pl 05-Jan-2008 10:12
SimpleXML has its own SPL iterator. See http://www.php.net/~helly/php/ext/spl/classSimpleXMLIterator.html . But I guess that there are none for DOM nodes. By the way, two out of three implementations I found over the Net were not recursive, so I wrote my own. Here is the snippet:

<?php

class DOMNodeListIterator implements RecursiveIterator
{
    private
        $nodes,
        $offset;

    function __construct(DOMNodeList $nodes)
    {
        return $this -> nodes = $nodes;
    }

    function rewind()
    {
        return $this -> offset = 0;
    }

    function current()
    {
        return $this -> nodes -> item($this -> offset);
    }

    function key()
    {
        return $this -> current() -> nodeName;
    }

    function next()
    {
        return $this -> offset++;
    }

    function valid()
    {
        return $this -> offset < $this -> nodes -> length;
    }

    function hasChildren()
    {
        return isset($this -> current() -> childNodes -> length) && $this -> current() -> childNodes -> length > 0;
    }

    function getChildren()
    {
        return new self($this -> current() -> childNodes);
    }
}

?>

Remember to use RecursiveIteratorIterator::SELF_FIRST flag when you create your iterator iterator.

<?php

$iterator = new DOMNodeListIterator($document -> childNodes);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

?>

Should work, has just few minutes though. :)
Hayley Watson 29-Oct-2007 02:14
Keep in mind that DOMNodelists are "live" - changes to the document or node that the DOMNodelist was derived from will be reflected in the DOMNodelist. In other words, a list of a parent node's children will change if you change the parent's children!
james dot dunmore at gmai dot com 27-Jul-2007 08:57
tfg_allardyce at gmail dot com

I have had exactly this problem.

To rectify I've had to do this:
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0);
$new_element = $doc->createElement('NewElement1');

$old_element_childNodes = $old_element->childNodes;
$length = $old_element_childNodes->length;

for($i = 0; $i < $length; $i++)
{
    $oldChildren_array[] = $old_element_childNodes->item($i);
}

foreach($oldChildren_array as $old_c)
{
    $new_element->appendChild($old_c);
}
?>

Rather than this:
(which I will bug report)
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0):
$new_element = $doc->createElement('NewElement1');

foreach($old_element->childNode as $node)
{
     $new_element->appendChild($node);
}

?>

Using the latter, randomally removes the children!
Geoffrey Thubron 26-May-2007 02:47
@ tfg_allardyce at gmail dot com

You could loop through the list backwards, that way, you are only ever taking off the last item from the list, and hence wont have disrupted the order.
oliver dot christen at camptocamp dot com 13-Feb-2007 07:27
NodeList are something annoying because you can't output the content with a simple print_r, so I did a little function that add all the node to a new empty DOMDocument and output it as a string.
Have fun.

<?php

public function domNodeList_to_string($DomNodeList) {
    $output = '';
    $doc = new DOMDocument;
    while ( $node = $DomNodeList->item($i) ) {
        // import node
        $domNode = $doc->importNode($node, true);
        // append node
        $doc->appendChild($domNode);
        $i++;
    }
    $output = $doc->saveXML();
    $output = print_r($output, 1);
    // I added this because xml output and ajax do not like each others
    $output = htmlspecialchars($output);
    return $output;
}

?>
tfg_allardyce at gmail dot com 10-Jan-2007 03:57
Be careful when looping through a DOMNodeList and moving its nodes around, sometimes this will take that node off the DOMNodeList and sometimes it wont!

<?php
// let $nodes be node list and $parent be some other node

foreach($nodes as $node) {
   $parent->appendChild($node);
}

?>

In some cases the $node will be taken off the list and the next iteration of the loop will be corrupted, skipping every other node in the list! In other cases the node will remain in the list and everything will be fine.

Generally if you've created the node list using a getElementsByTagName call or an XPath query then the nodes will stay on the list. If the node list comes from another nodes' childNodes property those child nodes will be shifted off the list whenever you call appendChild.
DOMNodeList
DOMNotation
DOMNodeList


Класс DOMNotation

(PHP 5)

Обзор классов

DOMNotation extends DOMNode {
/* Свойства */
readonly public string $publicId ;
readonly public string $systemId ;
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

publicId

Требуется описание

systemId

Требуется описание

User Contributed Notes

There are no user contributed notes for this page.
DOMNodelist::item
DOMProcessingInstruction
DOM


Класс DOMProcessingInstruction

(PHP 5)

Обзор классов

DOMProcessingInstruction extends DOMNode {
/* Свойства */
readonly public string $target ;
public string $data ;
/* Методы */
__construct ( string $name [, string $value ] )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

target

Требуется описание

data

Требуется описание

Содержание

  • DOMProcessingInstruction::__construct — Создает новый объект классаDOMProcessingInstruction

User Contributed Notes

There are no user contributed notes for this page.
DOMNotation
DOMProcessingInstruction::__construct
DOM


Создает новый объект классаDOMProcessingInstruction

DOMProcessingInstruction
DOMText
DOMProcessingInstruction
PHP Manual

DOMProcessingInstruction::__construct

(PHP 5)

DOMProcessingInstruction::__construct — Создает новый объект классаDOMProcessingInstruction

Описание

DOMProcessingInstruction::__construct ( string $name [, string $value ] )

Создает новый объект класса DOMProcessingInstruction. Этот объект будет доступен только для чтения. Он может быть добавлен в документ. Дополнительные узлы нельзя прикрепить к этому объекту, пока он присоединен к какому-либо документу. Для создания модифицируемого узла используйте DOMDocument::createProcessingInstruction.

Список параметров

name

Имя инструкции для обработчика.

value

Значение инструкции для обработчика.

Примеры

Пример #1 Создание объекта класса DOMProcessingInstruction

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

Результат выполнения данного примера:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

Смотрите также

  • DOMDocument::createProcessingInstruction() - Создает новый PI-узел

User Contributed Notes

There are no user contributed notes for this page.
DOMProcessingInstruction
DOMText
DOMProcessingInstruction


The DOMText class

(PHP 5)

Введение

Класс DOMText - это потомок класса DOMCharacterData и он содержит текстовой контент узлов, представленных объектами классов DOMElement или DOMAttr.

Обзор классов

DOMText extends DOMCharacterData {
/* Свойства */
readonly public string $wholeText ;
/* Методы */
public __construct ([ string $value ] )
public bool isWhitespaceInElementContent ( void )
public DOMText splitText ( int $offset )
/* Наследуемые методы */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Свойства

wholeText

Содержит все смежные (не разделенные другими элементами, комментариями или инструкциями) текстовые узлы элемента.

Содержание

  • DOMText::__construct — Создает объект класса DOMText
  • DOMText::isWhitespaceInElementContent — Определяет, содержит ли текстовый узел пробел в содержимом
  • DOMText::splitText — Разделяет узел на два, начиная с заданной позиции

User Contributed Notes

There are no user contributed notes for this page.
DOMProcessingInstruction::__construct
DOMText::__construct
DOM


Создает объект класса DOMText

DOMText
DOMText::isWhitespaceInElementContent
DOMText
PHP Manual

DOMText::__construct

(PHP 5)

DOMText::__construct — Создает объект класса DOMText

Описание

public DOMText::__construct() ([ string $value ] )

Создает новый экземпляр класса DOMText.

Список параметров

value

Значение текстового узла. Если значение не передано, будет создан пустой текстовый узел.

Примеры

Пример #1 Создание нового узла DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

Смотрите также

  • DOMDocument::createTextNode() - Создает новый текстовый узел

User Contributed Notes

Thomas 27-Apr-2012 01:54
I experinced that DOMText, given a integer as only value to the constructor failed to return valid data. I had to typecast the input to a string first:

$intValue = 3252; // Post/Zip-code
$some_element->appendChild( new DOMText( (string) $intValue) );

When not typecasting using "(string)" the XML output from $root->saveXML() would not validate.
DOMText
DOMText::isWhitespaceInElementContent
DOMText


Определяет, содержит ли текстовый узел пробел в содержимом

DOMText::__construct
DOMText::splitText
DOMText
PHP Manual

DOMText::isWhitespaceInElementContent

(PHP 5)

DOMText::isWhitespaceInElementContent — Определяет, содержит ли текстовый узел пробел в содержимом

Описание

public bool DOMText::isWhitespaceInElementContent ( void )

Определяет, содержит ли текстовый узел пробел в содержимом. Текстовые узлы могут содержать пробелы в своем содержимом в течение загрузки документа.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

JITR 07-Jul-2007 03:36
To add to `permidion at yahoo dot com''s comment:

Quite true. According to DOM Level 3 Core, the `isWhitespaceInElementContent()' method indicates, whether the node contains `whitespace in element content' (or `element content whitespace' according to the newer spec), see [1].

Btw, it seems the `isWhitespaceInElementContent()' method was replaced with the `isElementContentWhitespace' attribute in the current W3C recommendation, see [2].

I have the feeling, though, it would be more precise with the word `only' added, like: `... indicates, whether the node contains *only* element content whitespace.' This would better correspond with the fact the result is false, when there are any non-whitespace characters present (in addition to the whitespace ones), as already noted.

[1] (please concatenate the following two lines)
http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html
#core-Text3-isWhitespaceInElementContent
[2] (please concatenate the following two lines)
http://www.w3.org/TR/DOM-Level-3-Core/core.html
#Text3-isElementContentWhitespace
permidion at yahoo dot com 28-Oct-2004 08:30
if you have an xml element such as <name>Foo Bar</name> (note the space), isWhitespaceInElementContent will return false.
However it will return true for <name><name> or <name/>
so, that function can be used to determine if the element has a text content or not
DOMText::__construct
DOMText::splitText
DOMText


Разделяет узел на два, начиная с заданной позиции

DOMText::isWhitespaceInElementContent
DOMXPath
DOMText
PHP Manual

DOMText::splitText

(PHP 5)

DOMText::splitText — Разделяет узел на два, начиная с заданной позиции

Описание

public DOMText DOMText::splitText ( int $offset )

Разделяет узел на два, вторая часть начинается с позиции offset, полученные узлы становятся братьями.

После разделения исходный узел будет содержать данные до позиции offset. Если исходный узел имеет родителя, то второй, созданный, узел станет следующим братом исходного узла. Если offset равно длине содержимого узла, новый узел все равно будет создан, но не будет содержать данных.

Список параметров

offset

Позиция, с которой узле будет разделен, начиная с 0.

Возвращаемые значения

Новый узел того же типа содержащий данные после offset.

User Contributed Notes

There are no user contributed notes for this page.
DOMText::isWhitespaceInElementContent
DOMXPath
DOMText


Класс DOMXPath

(PHP 5)

Введение

Поддерживает XPath 1.0

Обзор классов

DOMXPath {
/* Свойства */
public DOMDocument $document ;
/* Методы */
public __construct ( DOMDocument $doc )
public mixed evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )
public DOMNodeList query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )
public bool registerNamespace ( string $prefix , string $namespaceURI )
public void registerPhpFunctions ([ mixed $restrict ] )
}

Свойства

document

Требуется описание

Содержание

  • DOMXPath::__construct — Создает новый объект класса DOMXPath
  • DOMXPath::evaluate — Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно
  • DOMXPath::query — Выполняет заданное XPath выражение
  • DOMXPath::registerNamespace — Ассоциирует пространство имен с объектом DOMXPath
  • DOMXPath::registerPhpFunctions — Регистрация функций PHP как XPath функций

User Contributed Notes

dhz 05-Jan-2011 10:47
I just spent far too much time chasing this one....

When running an xpath query on a table be careful about table internal nodes (ie: <tr></tr>, and <td></td>).  If the master <table> tag is missing, then query() (and likely evaluate() also) will return unexpected results.

I had a DOMNode with a structure like this:

<td>
    <table></table>
    <table>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
</td>

Upon which I was trying to do a relative query (ie: <?php $xpath_obj->query('my/x/path', $relative_node); ?>).

But because of the lone outer <td></td> tags, the inner tags were being invalidated, while the nodes were still recognized.  Meaning that the following query would work:

<?php $xpath_obj->query('*[2]/*[*[2]]', $relative_node); ?>

But when replacing any of the "*" tokens with the corresponding (and valid) "table", "tr", or "td" tokens the query would inexplicably break.
david at lionhead dot nl 11-Aug-2009 06:33
When using DOMXPath and having a default namespace. Consider using an intermediate function to add the default namespace to all queries:

<?php
// The default namespace: x:xmlns="http://..."
$path="/Book/Title";
$path=preg_replace("\/([a-zA-Z])","/x:$1",$path);

// Result: /x:Book/x:Title
?>
Mark Omohundro, ajamyajax dot com 14-Dec-2008 09:15
<?php
// to retrieve selected html data, try these DomXPath examples:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);

// example 1: for everything with an id
//$elements = $xpath->query("//*[@id]");

// example 2: for node data in a selected id
//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");

// example 3: same as above with wildcard
$elements = $xpath->query("*/div[@id='yourTagIdHere']");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>
DOMText::splitText
DOMXPath::__construct
DOM


Создает новый объект класса DOMXPath

DOMXPath
DOMXPath::evaluate
DOMXPath
PHP Manual

DOMXPath::__construct

(PHP 5)

DOMXPath::__construct — Создает новый объект класса DOMXPath

Описание

public DOMXPath::__construct ( DOMDocument $doc )

Создает новый объект класса DOMXPath.

Список параметров

doc

Объект класса DOMDocument связанный с DOMXPath.

User Contributed Notes

thsoft at vipmail dot hu 04-Jul-2007 04:57
As of PHP 5.2.0, DOMXPath object implements XPath 1.0.
Saulo Vallory 26-Jun-2007 03:23
The DOMXPath object doesn't create a reference to the document. If you load a new xml using either load, loadXML or loadHTML functions the DOMXPath object will still query and evaluate over the source in the DOMDocument when it was created.
DOMXPath
DOMXPath::evaluate
DOMXPath


Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно

DOMXPath::__construct
DOMXPath::query
DOMXPath
PHP Manual

DOMXPath::evaluate

(PHP 5 >= 5.1.0)

DOMXPath::evaluate — Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно

Описание

public mixed DOMXPath::evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )

Выполняет переданное XPath выражение expression и возвращает типизированный результат, если это возможно.

Список параметров

expression

XPath выражение для выполнения.

contextnode

Дополнительный параметр contextnode может быть использован для указания обрабатывать относительные XPath запросы. По умолчанию запросы выполняются относительно корневого элемента.

registerNodeNS

Посредством необязательного аргумента registerNodeNS можно отключить автоматическую регистрацию контекста узла.

Возвращаемые значения

Возвращает типизированный результат, если это возможно, либо объект DOMNodeList содержащий все узлы, соответствующие заданному XPath выражению expression.

Если значение аргумента expression построено неправильно или contextnode имеет неверное значение, DOMXPath::evaluate() вернет FALSE.

Список изменений

Версия | Описание
5.3.3 | Добавлен аргумент registerNodeNS.

Примеры

Пример #1 Определение количества всех английских книг

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// запрос информации относительно узла tbody
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "Всего английских книг $entries\n";

?>

Результат выполнения данного примера:

Всего английских книг 2

Смотрите также

  • DOMXPath::query() - Выполняет заданное XPath выражение

User Contributed Notes

daniel at danielnorton dot com 25-Jun-2011 09:56
Note that this method does not provide any means to distinguish between a successful result that returns FALSE and an error.

For example, this will succeed and return FALSE:

<?php $xpath->evaluate("1 = 0"); ?>

One workaround when you know you are expecting a Boolean is to wrap the result with string(). e.g.

<?php $xpath->evaluate("string(1 = 0)"); ?>

This will return a string "false" on success, or the Boolean FALSE on error.
Damien Bezborodov 28-Mar-2011 06:13
If your expression returns a node set, you will get a DOMNodeList instead of a typed result. Instead, try modifying your expression from "//node[1]" to "string(//node[1])".
daniel ad demus dk 16-Jun-2008 03:02
It seems this method is only included from PHP 5.1.
yuriucsal at NOSPAM dot yahoo dot com dot br 06-Mar-2005 12:55
this class can substitute the method evaluate while it is not validated. Made for Yuri Bastos and Jo�o Gilberto Magalh�es.

<?php

    class XPtahQuery
    {
        // function returns a DOMNodeList from a relative xPath
        public static function selectNodes($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNodeList = $domXPath->query($xPathQueryFull);

                return $rNodeList;
        }
        // function returns a DOMNode from a xPath from other DOMNode
        public static function selectSingleNode($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNode = $domXPath->query($xPathQueryFull)->item(0);

                return $rNode;
        }
        //utilitaries functions off selectSingleNode
        private function getNodePos($pNode, $nodeName)
        {
            if($pNode == null)
                {
                        return 0;
            }
            else
            {
                $var = 0;
                    if ($pNode->previousSibling != null)
                    {
                    if ($pNode->previousSibling->nodeName == $nodeName)
                    {
                        $var = 1;
                    }
                    }
                    return self::getNodePos($pNode->previousSibling, $nodeName) + $var;
            }
        }
        //utilitaries functions off selectSingleNode
        private function getFullXpath($pNode)
        {
            if($pNode == null)
                {
                        return "";
            }
            else
            {

                return self::getFullXpath($pNode->parentNode) . "/" . $pNode->nodeName . "[" .strval(self::getNodePos($pNode, $pNode->nodeName)+1) . "]";//+1 to get the real xPath index

            }
        }
    }
?>
DOMXPath::__construct
DOMXPath::query
DOMXPath


Выполняет заданное XPath выражение

DOMXPath::evaluate
DOMXPath::registerNamespace
DOMXPath
PHP Manual

DOMXPath::query

(PHP 5)

DOMXPath::query — Выполняет заданное XPath выражение

Описание

public DOMNodeList DOMXPath::query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )

Выполняет заданный XPath запрос expression.

Список параметров

expression

XPath запрос.

contextnode

Дополнительный параметр contextnode может быть использован для указания обрабатывать относительные XPath запросы. По умолчанию запросы выполняются относительно корневого элемента.

registerNodeNS

Посредством необязательного аргумента registerNodeNS можно отключить автоматическую регистрацию контекста узла.

Возвращаемые значения

Возвращает объект DOMNodeList содержащий узлы, отвечающие условиям отбора в XPath expression. Любой запрос, не возвращающий узлов, вернет пустой объект DOMNodeList.

Если значение аргумента expression построено неправильно или contextnode имеет неверное значение, DOMXPath::query() вернет FALSE.

Список изменений

Версия | Описание
5.3.3 | Добавлен аргумент registerNodeNS.

Примеры

Пример #1 Получение списка всех книг на английском

<?php

$doc = new DOMDocument;

// нам не нужны проблемы с пробелами
$doc->preserveWhiteSpace = false;

$doc->Load('book.xml');

$xpath = new DOMXPath($doc);

// начинаем с корневого элемента
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    echo "Найдена книга {$entry->previousSibling->previousSibling->nodeValue}," .
         " автор {$entry->previousSibling->nodeValue}\n";
}
?>

Результат выполнения данного примера:

Найдена книга The Grapes of Wrath, автор John Steinbeck
Найдена книга The Pearl, автор John Steinbeck

Можно также использовать аргумент contextnode для более короткой записи выражения:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// запрос относительно узла tbody
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
    echo "Найдена книга {$entry->previousSibling->previousSibling->nodeValue}," .
         " автор {$entry->previousSibling->nodeValue}\n";
}
?>

Смотрите также

  • DOMXPath::evaluate() - Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно

User Contributed Notes

imoore76 at yahoo dot com 17-Nov-2011 10:17
One-liner concat type escape:

<?php

function xpathConcatEscape($string) {

   return "concat(".str_replace(array("'',",",''"), "", "'".implode("',\"'\",'",explode("'",$string))."'") .")";

}

?>

I hate xpath :( This should not be needed.
info at syncgw dot com 22-Sep-2011 09:05
A warning to all PHP programmer using this function PHP 5.0.0.0: We needed an equivalent to upper-case() function (is not available in XPath 1.0).

XML-Document:

<Rec>
<SourceRef>./c:calendar2</SourceRef>
<SourceRef>./c:calendar</SourceRef>
</Rec>

using

query('//DataStore[translate(SourceRef,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ")="./C:CALENDAR"]/.')

returns ZERO matches.

If you change XML-Source to

<Rec>
<SourceRef>./c:calendar</SourceRef>
<SourceRef>./c:calendar2</SourceRef>
</Rec>

everything works fine
yuriscom at gmail dot com 07-Sep-2011 10:29
I hope it will be helpful for someone:

I spent some time to solve the problem when you query a string with quotes inside.

Suppose you have:
$parameter = "aaa \"bbb\"";
$domxpath->query("//path[text()=\"".$parameter."\""];

In versions > 5.3.0 there is registerPhpFunctions where you can put an addslashes. But in older version you cannot do it in simple way.

So the solution is to use a concat function. So when you have a substring with " inside, wrap it with '. And when you have a substring with ', then wrap with in ".

The code is:

<?php
$dom = new DOMDocument;
$dom->loadXML("<name>'bla' \"bla\" bla</name>");
$xpath = new DOMXPath($dom);
$nodeList = $xpath->query("//name[text()=concat(\"'bla' \" ,'\"bla\"' ,\" bla\")]");
?>

Below is the function that receives a string and returns a concat pattern for the xpath query.

<?php
    function getPattern_MQ($pattern) {
        // initiating an array of substrings
        $ar = array();
        // points to the current position in a string
        $offset = 0;
        $strlen = strlen($pattern);
        while (true) {
            // find a position of quotes
            $qPos = strpos($pattern, "\"", $offset);

            if (!$qPos) {
                // no more quotes
                $leftOver = $offset - $strlen;
                if ($leftOver < 0) {
                    $string = substr($pattern, $leftOver);
                    $ar[] = "\"" . $string . "\"";
                }
                break;
            }
            // add the whole substring before the quotes into the array
            $ar[] = "\"" . substr($pattern, $offset, ($qPos - $offset)) . "\"";
            // add the quotes wrapped with single quot
            $ar[] = "'" . substr($pattern, $qPos, 1) . "'";
            $offset = $qPos + 1;
        }
        // join the array to get: concat("aaa",'"',"bbb",'"');
        $pattern = "concat(''," . join(",", $dynamicPatternsAr) . ")";
        return $pattern;
    }
?>
chris AT cmbuckley DOT co DOT uk 14-Apr-2011 07:31
To help with the problem where the default namespace is not registered with the DOMXPath object, you can use the following replacement to update your paths accordingly:

<?php

$xml = <<<EOS
<root xmlns="urn:test">
    <foo>bar</foo>
</root>
EOS;

$expression = '//foo';
$prefix = 'fakeprefix';

$doc = new DOMDocument();
$doc->loadXML($xml);

$context = $doc->documentElement; // or whichever element you choose
$xpath = new DOMXPath($doc);

// register namespace as below, and apply a regex to the expression
if (null !== $context->namespaceURI) {
    $xpath->registerNamespace($prefix, $context->namespaceURI);
    $expression = preg_replace('#(::|/\s*|\A)(?![/@].+?|[a-z\-]+::)#', '$1' . $prefix . ':$2', $expression);
    var_dump($expression); // string(16) "//fakeprefix:foo"
}

$foo = $xpath->query($expression, $context)->item(0);
var_dump($doc->saveXML($foo)); // string(14) "<foo>bar</foo>"

?>
kkez at example dot com 03-Sep-2010 07:51
If the query() function seems to ignore your $contextnode, and instead returns all the tags in the document, try to use a relative path (use a . in front of the query):

<?php
    $xml = "<?xml version='1.0' encoding='UTF-8'?>
        <test>
            <tag1>
                <uselesstag>
                    <tag2>test</tag2>
                </uselesstag>
            </tag1>
            <tag2>test2</tag2>
        </test>";

    $dom = new DomDocument();
    $dom->loadXML($xml);
    $xpath = new DomXPath($dom);

    $tag1 = $dom->getElementsByTagName("tag1")->item(0);

    echo $xpath->query("//tag2")->length; //output 2 -> correct
    echo $xpath->query("//tag2", $tag1)->length; //output 2 -> wrong, the query is not relative
    echo $xpath->query(".//tag2", $tag1)->length; //output 1 -> correct (note the dot in front of //)
?>

See that i couldn't use $xpath->query("tag2", $tag1) as per the documentation, since "tag2" is not a direct child of "tag1".
I don't know why this note was deleted, i just tested it and it's correct.
It's not a bug, it's simply not written in the documentation.
Anonymous 27-Nov-2009 12:26
I found this useful for building page templates

<?php
$xsl = new DOMDocument;
$xsl->load('layout.xsl');

// Set the <xsl:include> href attribute, the inner stylesheet to include in this layout
$xpath = new DomXPath($xsl);
$res = $xpath->query('//xsl:include');
$res->item(0)->setAttribute('href','page.xsl');
$xsl->save('media/xsl/layout.xsl');
?>
Niklas 27-Aug-2008 02:36
For XPath escaping use the following method (of course it could be more efficient).
<?php
public function xpathescape($string)
{
$result = 'concat(';

for($i=0, $j=strlen($string); $i<$j; ++$i)
{
if($i > 0)
$result .= ",";

if($string[$i] == '\'')
$result .= "\"".$string[$i]."\"";
else
$result .= '\''.$string[$i].'\'';
}

$result .= ')';

return $result;
}
?>

Use it this way:
<php
$xpath->query('//example[sub='.xpathescape($acomplexstring).']');

?>
adam dot prall at thinkingman dot com 19-Jul-2008 09:01
If you're wondering, like I was, why your XPath queries are not returning any of the new DOMElements you create in your (X)HTML documents, and only the ones originally loaded in with (for example) loadXML(), this is why; if you're doing things right, you have registered the nameSpace 'html' after creating your DOMXPath object thus:

<?php

class XPathQueryLength {
     private $nameSpace = '';
     function __construct(DOMDocument $doc) {
          $this->xpath = new DOMXPath($this->doc);
          $this->xpath->registerNamespace(
                 'html','http://www.w3.org/1999/xhtml' );
     }
     function queryLength($query) {
          return $this->xpath->query($query)->length;
     }
}

?>

...but don't forget that when adding new elements to the above DOMDocument $doc, to use createElementNS() instead of createElement(), otherwise you'll have this problem:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElement('p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 0

print $xPath->queryLength('//p');

output: 1

?>

So do this instead:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElementNS('http://www.w3.org/1999/xhtml','p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 2

print $xPath->queryLength('//p');

output: 0

?>

The resulting XHTML file from both example scripts looks much like this:

<html>
  <head></head>
  <body>
     <p>This is a hardcoded paragraph.</p>
     <p>This is a new paragraph!</p>
  </body>
</html>

...so you would think that a paragraph is a paragraph is a paragraph, since you never see the prefix, as in "<html:p>This is a new paragraph!</html:p>".

This may seem glaringly obvious, but I was writing a class that converts CSS queries into XPath queries, and the fact that a namespace had been registered was rather buried in the code.

We love the DOM, the DOM is good to us.
Nibinaear 03-Mar-2008 06:15
I've searched the entire web looking for a way to update / modify/ change/ alter the elements of an xml file and found NOTHING!

So here it is, the defninitive way to "Change XML elements with PHP" rather than adding / appending new ones. This uses XPATH:

<?php

// Create a DOMDocument instance
$xml = new DOMDocument;

// Ignore whitespace between nodes (default: true)
$xml->preserveWhiteSpace = false;

$file='about.xml';

// Load the XML data source
$xml->Load($file);

$xpath = new DOMXPath($xml);

$query='/regions/branch';

$entries = $xpath->query($query);

foreach ($entries as $entry)
{
  $entry->firstChild->nodeValue="like this!";
  echo $entry->firstChild->nodeValue;
}

$xml->save($file);

?>
ondrej dot fischer at 4internet dot cz 25-Oct-2007 06:46
Unfortunately PHP's DOM extension doesn't support use of:
<?xml-stylesheet type="text/xsl" ... ?>
processing instruction.
Here is an example, how to implement it using XPath query and extending DOMDocument by a method output().

<?php

// This simple function adds missing direct usage of anonymous instances
// in PHP5's reference model
function a($var) {
   return $var;
}

// Extended DOMDocument class
class MyDOMDocument extends DOMDocument
{

   public function output()
   {
      $stylesheets = array();
      $PIs = a(new DOMXPath($this))
                  ->query('/processing-instruction("xml-stylesheet")');

      foreach($PIs as $PI)
      {
         // This might be implemented cleaner by regular parsing
         // of DOMProcessingInstruction::data property
         if(ereg('type *= *"text/xsl" +href *= *"([^"]+)"', $PI->data, $mem))
         {
            // Here should be verified, that XSL file exists.
            a($stylesheets[] = new DOMDocument())->load($mem[1]);
         }
      }

      if($stylesheets)
      {
         $processor = new XSLTProcessor();
         foreach($stylesheets as $stylesheet)
            $processor->importStylesheet($stylesheet);
         return $processor->transformToDoc($this);
      }
      // If no stylesheet instructions present, return self directly
      else return $this;

   }
}

?>

Usage:

<?php

$document = new MyDOMDocument();
$document->load('my.xml');
echo $document->output()->saveXML();

?>

With following file my.xml:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="my.xsl" ?>
<my-root />

and existing file my.xsl that code will transform the xml file using my.xsl and output the result.
jbarnett at flowershopnetwork dot com 11-Sep-2007 01:46
The order of nodes in the return value is not guaranteed.

When my code was on an old server, the returned DOMNodeList was in document order.  On the new server, the returned DOMNodeList is in a consistent order, but it is not in document order.

PHP passes this function call off to the xmlXPathEvalExpression() function in libxml.  That function in libxml only accepts two arguments - the same two this PHP function accepts.  There must have been a change in the libxml version from the old server to the new server, and that libxml behaves differently.

This would be okay if PHP had a way to compare nodes so I can resort the nodes manually, but there is not.

So, there is no guaranteed way to get an ordered list of nodes like DOM 3 XPath provides.
Hayley Watson 12-Aug-2007 05:43
Note that if your DOMDocument was loaded from HTML, where element and attribute names are case-insensitive, the DOM parser converts them all to lower-case, so your XPath queries will have to as well; '//A/@HREF' won't find anything even if the original HTML contained "<A HREF='example.com'>".
nicolas_rainardNOSPAM at yahoo dot fr 10-Jul-2007 02:04
Please note that what clochix says is valid for *any* document which has a default namespace (as it is the case for XHTML).

This document :

<?xml version="1.0" encoding="UTF-8" ?>

<root xmlns="http://www.exemple.org/namespace">

    <element id="1">
    ...
    </element>

    <element id="2">
    ...
    </element>

</element>

must be accessed this way :

$document = new DOMDocument();
$document->load('document.xml');

$xpath = new DOMXPath($document);
$xpath->registerNameSpace('fakeprefix', 'http://www.exemple.org/namespace');

$elements = $xpath->query('//fakeprefix:element');

Of course, there is no prefix in the original document, but the DOMXPath class *needs* one, whatever it is, if you use a default namespace. It *doesn't work* if you specify an empty prefix like this :

$xpath->registerNameSpace('', 'http://www.exemple.org/namespace');

Hope this help to spare some time...
clochix at clochix dot net 01-Mar-2007 04:05
If you want to perform queries on XHTML documents, you must fix a default namespace:

$doc = new DOMDocument;
$doc->preserveWhiteSpace = true;
$doc->resolveExternals = true; // for character entities
$doc->load("http://www.w3.org/");
$xpath = new DOMXPath($doc);
// won't work
$entries = $xpath->query("//div");
// you should use :
$xpath->registerNamespace("html", "http://www.w3.org/1999/xhtml");
$entries = $xpath->query("//html:div");
ckrack at i-z dot de 22-Dec-2005 07:27
tried finding a node by it's text content?

// Get all elements that equal the string "test"
$query = "//*[.='test']";
jakob dot voss at nichtich dot de 14-Nov-2005 12:33
You can transform the result nodes into new DOMDocument objects this way:

<?php
$result = $xpath->query($query);
$resultNode = $result->item(0);
$newDom = new DOMDocument;
$newDom->appendChild($newDom->importNode($resultNode,1));

print "<pre>" . htmlspecialchars($newDom->saveXML()) . "</pre>";
?>
Eric Hanson 12-Jul-2005 05:40
Two great XPath references follow.

XPath in Five Paragraphs (finally!):
http://www.rpbourret.com/xml/XPathIn5.htm

The w3c spec actually has a bunch of helpful examples:
http://www.w3.org/TR/xpath#location-paths
DOMXPath::evaluate
DOMXPath::registerNamespace
DOMXPath


Ассоциирует пространство имен с объектом DOMXPath

DOMXPath::query
DOMXPath::registerPhpFunctions
DOMXPath
PHP Manual

DOMXPath::registerNamespace

(PHP 5)

DOMXPath::registerNamespace — Ассоциирует пространство имен с объектом DOMXPath

Описание

public bool DOMXPath::registerNamespace ( string $prefix , string $namespaceURI )

Ассоциирует URI пространства имен namespaceURI и префикс prefix с объектом DOMXPath.

Список параметров

prefix

Префикс.

namespaceURI

URI пространства имен.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

xmedeko at gmail dot com 20-Sep-2011 04:58
A general way to register the root default namespace:

<?php
$xml = new DomDocument();
$xml->load('data.xml');
$xpath = new DOMXPath($xml);
$rootNamespace = $xml->lookupNamespaceUri($xml->namespaceURI);
$xpath->registerNamespace('x', $rootNamespace);
?>

And then just query:

<?php $elementList = $xpath->query('//x:items/x:name'); ?>
dulao5 at gmail dot com 16-Jun-2009 12:01
The following code can work for XML default namespace.
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:other="http://other.w3.org/other" >
        <id>uYG7-sPwjFg</id>
        <published>2009-05-17T18:29:31.000Z</published>
</entry>
EOT;

$doc = new DOMDocument;
$doc->loadXML($xml);
$xpath =  DOMXPath($doc);

$xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");

$xpath_str = '//atom:entry/atom:published/text()';

$entries = $xpath->evaluate($xpath_str);

print $entries->item(0)->nodeValue ."\n";

?>
agent009 31-Mar-2009 04:55
Ok, here's a function that extends XPath syntax with the following special characters:

~ inserts default namespace prefix if defined

# shorthand for text()

% shorthand for comment()

$ shorthand for node()

?* shorthand for processing-instruction()

?foo shorthand for processing-instruction("foo")

? shorthand for processing-instruction("")

^ escapes following character (with literal or SGML entity as needed)

All of the above except ^ are ignored within quoted strings

<?php
function extendXPath($str, $defns = NULL) {
   $quote = false;
   $map = array(
      '~' => isset($defns) ? "$defns:" : '',
      '#' => 'text()',
      '%' => 'comment()',
      '$' => 'node()'
   );
   $out = '';

   for ($i = 0, $len = strlen($str); $i < $len; $i++) {
      $c = $str[$i];
      if (!$quote && array_key_exists($c, $map)) {
         $out .= $map[$c];
      } else switch ($c) {
         case '^':
            $out .= htmlspecialchars($str[++$i], ENT_QUOTES);
            break;
         case '?':
            if ($quote) {
               $out .= $c;
            } elseif ($str[$i + 1] == '*') {
               $out .= 'processing-instruction()';
               $i++;
            } else {
               preg_match('/^\w+/', substr($str, $i + 1), $matches);
               $out .= 'processing-instruction("'.$matches[0].'")';
               $i += strlen($matches[0]);
            };
            break;
         case '"':
            $quote = !$quote;
         default:
            $out .= $c;
      };
   };

   return $out;
}
?>
adam dot prall at thinkingman dot com 08-Jun-2008 02:49
Just a quick "gotcha" that may sound stupid:

If you've registered your namespaces, loaded your XHTML, etc., into your XPath's DOMDocument object and <i>still</i> can't get it to work, check to make sure you haven't used the DOMDocument's loadHTML() or loadHTMLFile() function. For XHTML <i>always use the XML versions</i>, otherwise your XPath will never, ever work. Save yourself a couple hours of frustration...
cameron kellough 14-Apr-2007 10:33
This is called prefix mapping and it is necessary to use xpath to handle documents which have default namespaces. //root/item will search for items with no namespace, not items with the namespace described as the default in the xmlns declaration.  This problem is maddening as it just looks on the surface like xpath isn't working.
spam at spam dot spam 31-Mar-2005 12:46
It is mentioned in a few places on the web, but it wasn't mentioned here. You need to use this function to set up a prefix for the default namespace of a document.

For instance, if you are trying to parse a Microsoft Spreadsheet XML file, which has the default namespace of "urn:schemas-microsoft-com:office:spreadsheet":

$doc = DOMDocument::load("my_spreadsheet.xml);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace("m",
        "urn:schemas-microsoft-com:office:spreadsheet");
$query = '/m:Workbook/m:Worksheet[1]/m:Table';
$result = $xpath->query($query, $doc);

You can use anything in place of the 'm', but you have to specify something! Just asking for "/Workbook/Worksheet/Table" doesn't work.
DOMXPath::query
DOMXPath::registerPhpFunctions
DOMXPath


Регистрация функций PHP как XPath функций

DOMXPath::registerNamespace
DOM Функции
DOMXPath
PHP Manual

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0)

DOMXPath::registerPhpFunctions — Регистрация функций PHP как XPath функций

Описание

public void DOMXPath::registerPhpFunctions ([ mixed $restrict ] )

Этот метод включает возможность использовать PHP функции в XPath выражениях.

Список параметров

restrict

Используйте этот аргумент для включения возможности вызывать из XPath выражений только определенные функции.

Этот аргумент может иметь тип string (имя функции) или array (массив имен функций).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Дальнейшие примеры используют файл book.xml, содержимое которого следующее:

Пример #1 book.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
 <book>
  <title>PHP Basics</title>
  <author>Jim Smith</author>
  <author>Jane Smith</author>
 </book>
 <book>
  <title>PHP Secrets</title>
  <author>Jenny Smythe</author>
 </book>
 <book>
  <title>XML basics</title>
  <author>Joe Black</author>
 </book>
</books>

Пример #2 DOMXPath::registerPHPFunctions() с php:functionString

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Регистрация PHP: пространство имен (необходимо)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Регистрация PHP функций (без ограничений)
$xpath->registerPHPFunctions();

// Вызов функции substr применительно к названию книги
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "Найдены книги {$nodes->length} начинающиеся со слова 'PHP':\n";
foreach ($nodes as $node) {
    $title  = $node->getElementsByTagName("title")->item(0)->nodeValue;
    $author = $node->getElementsByTagName("author")->item(0)->nodeValue;
    echo "$title автора $author\n";
}

?>

Результатом выполнения данного примера будет что-то подобное:

Найдены книги (2) начинающиеся со слова 'PHP':
PHP Basics автора Jim Smith
PHP Secrets автора Jenny Smythe

Пример #3 DOMXPath::registerPHPFunctions() с php:function

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Регистрация PHP: пространство имен (необходимо)
$xpath->registerNamespace("php", "http://php.net/xpath");

// регистрация PHP функций (только has_multiple)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
    // возвращает true, если более одного автора
    return count($nodes) > 1;
}
// Отбор книг с двумя и более авторами
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Книги с двумя и более авторами:\n";
foreach ($books as $book) {
    echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

Результатом выполнения данного примера будет что-то подобное:

Книги с двумя и более авторами:
PHP Basics

Смотрите также

  • DOMXPath::registerNamespace() - Ассоциирует пространство имен с объектом DOMXPath
  • DOMXPath::query() - Выполняет заданное XPath выражение
  • DOMXPath::evaluate() - Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно

User Contributed Notes

There are no user contributed notes for this page.
DOMXPath::registerNamespace
DOM Функции
DOMXPath


DOM Функции

Содержание

  • dom_import_simplexml — Получает объект класса DOMElement из объекта класса SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.
DOMXPath::registerPhpFunctions
dom_import_simplexml
DOM


Получает объект класса DOMElement из объекта класса SimpleXMLElement

DOM Функции
DOM XML (PHP 4)
DOM Функции
PHP Manual

dom_import_simplexml

(PHP 5)

dom_import_simplexml — Получает объект класса DOMElement из объекта класса SimpleXMLElement

Описание

DOMElement dom_import_simplexml ( SimpleXMLElement $node )

Эта функция берет узел node класса SimpleXML и превращает его в узел DOMElement. Затем этот новый объект может быть использован как нативный узел DOMElement.

Список параметров

node

Узел SimpleXMLElement.

Возвращаемые значения

Добавленный узел DOMElement или FALSE в случае возникновения любых ошибок.

Примеры

Пример #1 Импорт SimpleXML в DOM с помощью функции dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>чепуха</title></book></books>');

if ($sxe === false) {
    echo 'Ошибка при разборе документа';
    exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Ошибка при преобразовании XML';
    exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

Смотрите также

  • simplexml_import_dom() - Получает объект класса SimpleXMLElement из узла DOM.

User Contributed Notes

Jeff M 06-Mar-2009 01:09
SimpleXML is an 'Object Mapping XML API'. It is not DOM, per se. SimpleXML converts the XML elements into PHP's native data types.

The dom_import_simplexml and simplexml_import_dom functions do *not* create separate copies of the original object. You are free to use the methods of either or both interchangeably, since the underlying instance is the same.

<?php
    // initialize a simplexml object
    $sxe = simplexml_load_string('<root/>');

    // get a dom interface on the simplexml object
    $dom = dom_import_simplexml($sxe);

    // dom adds a new element under the root
    $element = $dom->appendChild(new DOMElement('dom_element'));

    // dom adds an attribute on the new element
    $element->setAttribute('creator', 'dom');

    // simplexml adds an attribute on the dom element
    $sxe->dom_element['sxe_attribute'] = 'added by simplexml';

    // simplexml adds a new element under the root
    $element = $sxe->addChild('sxe_element');

    // simplexml adds an attribute on the new element
    $element['creator'] = 'simplexml';

    // dom finds the simplexml element (via DOMNodeList->index)
    $element = $dom->getElementsByTagName('sxe_element')->item(0);

    // dom adds an attribute on the simplexml element
    $element->setAttribute('dom_attribute', 'added by dom');

    echo ('<pre>');
    print_r($sxe);
    echo ('</pre>');
?>

Outputs:

SimpleXMLElement Object
(
    [dom_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => dom
                    [sxe_attribute] => added by simplexml
                )

        )

    [sxe_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => simplexml
                    [dom_attribute] => added by dom
                )

        )

)

What this illustrates is that both interfaces are operating on the same underlying object instance. Also, when you dom_import_simplexml, you can create and add new elements without reference to an ownerDocument (or documentElement).

So passing a SimpleXMLElement to another method does not mean the recipient is limited to using SimpleXML methods.

Hey Presto! Your telescope has become a pair of binoculars!
crescentfreshpot at yahoo dot com 12-Dec-2007 12:22
justinpatrin at php dot net:
> To get a proper DOM document (which you need to do most things) you need...

No you don't. Just do:
<?php
$dom = dom_import_simplexml($xml)->ownerDocument;
?>
justinpatrin at php dot net 01-Jun-2006 09:44
I've found that newer versions of PHP5 require some special syntax in order to properly convert between SimpleXML and DOM. It's not as easy as calling dom_import_simplexml() with a SimpleXML node. To get a proper DOM document (which you need to do most things) you need:
<?php
//$xml is a SimpleXML instance
$domnode = dom_import_simplexml($xml);
$dom = new DOMDocument();
$domnode = $dom->importNode($domnode, true);
$dom->appendChild($domnode);
?>

Switching back, though, is, well...simple.

<?php
//$dom is a DOMDocument instance
$xml = simplexml_import_dom($dom);
?>
DOM Функции
DOM XML (PHP 4)
DOM Функции


DOM XML (PHP 4)

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • DOM XML (PHP 4) Функции
    • DomAttribute::name — Возвращает имя атрибута
    • DomAttribute::set_value — Устанавливает значение атрибута
    • DomAttribute::specified — Проверяет, задан ли атрибут
    • DomAttribute::value — Возвращает значение атрибута
    • DomDocument::add_root — Добавляет корневой узел [устаревший метод]
    • DomDocument::create_attribute — Создает новый атрибут
    • DomDocument::create_cdata_section — Создает новый узел типа cdata
    • DomDocument::create_comment — Создает новый узел-комментарий
    • DomDocument::create_element_ns — Создает новый элемент с соответствующим пространством имен
    • DomDocument::create_element — Создает новый узел-элемент
    • DomDocument::create_entity_reference — Создает ссылку на сущность
    • DomDocument::create_processing_instruction — Создает новый PI узел
    • DomDocument::create_text_node — Создает новый текстовый узел
    • DomDocument::doctype — Возвращает тип документа
    • DomDocument::document_element — Возвращает узел корневого элемента
    • DomDocument::dump_file — Сохраняет XML дерево в файл
    • DomDocument::dump_mem — Представляет XML дерево в виде строки
    • DomDocument::get_element_by_id — Ищет элемент с заданным id
    • DomDocument::get_elements_by_tagname — Возвращает массив узлов с заданным тэгом в документе или пустой массив, если таких элементов не найдено
    • DomDocument::html_dump_mem — Преобразует дерево XML в HTML строку
    • DomDocument::xinclude — Подстановка XIncludes в объекте DomDocument
    • DomDocumentType::entities — Возвращает список сущностей
    • DomDocumentType::internal_subset — Возвращает подмножество внутренней структуры dom документа
    • DomDocumentType::name — Возвращает имя типа документа
    • DomDocumentType::notations — Возвращает список обозначений
    • DomDocumentType::public_id — Возвращает общедоступный (public) идентификатор типа документа
    • DomDocumentType::system_id — Возвращает системный идентификатор типа документа
    • DomElement::get_attribute_node — Возвращает узел заданного атрибута
    • DomElement::get_attribute — Возвращает значение заданного атрибута
    • DomElement::get_elements_by_tagname — Получает элементы по имени
    • DomElement::has_attribute — Проверяет, есть ли атрибут в текущем узле
    • DomElement::remove_attribute — Удаляет атрибут
    • DomElement::set_attribute_node — Добавляет новый атрибут
    • DomElement::set_attribute — Устанавливает значение атрибута
    • DomElement::tagname — Возвращает имя текущего элемента
    • DomNode::add_namespace — Добавляет узлу объявление пространства имен
    • DomNode::append_child — Добавляет нового сына в конец списка сыновей
    • DomNode::append_sibling — Добавляет к узлу нового брата
    • DomNode::attributes — Возвращает список атрибутов
    • DomNode::child_nodes — Возвращает сыновей узла
    • DomNode::clone_node — Копирует узел
    • DomNode::dump_node — Представляет одиночный узел в виде строки
    • DomNode::first_child — Возвращает первого сына узла
    • DomNode::get_content — Получает содержимое узла
    • DomNode::has_attributes — Проверяет, есть ли в узле атрибуты
    • DomNode::has_child_nodes — Проверяет, есть ли у узла потомки
    • DomNode::insert_before — Вставляет новый узел в качестве сына
    • DomNode::is_blank_node — Проверяет, есть ли содержимое в узле
    • DomNode::last_child — Возвращает последнего сына узла
    • DomNode::next_sibling — Возвращает следующего брата узла
    • DomNode::node_name — Возвращает имя узла
    • DomNode::node_type — Возвращает тип узла
    • DomNode::node_value — Возвращает значение узла
    • DomNode::owner_document — Возвращает документ, которому принадлежит этот узел
    • DomNode::parent_node — Возвращает родителя узла
    • DomNode::prefix — Возвращает префикс пространства имен узла
    • DomNode::previous_sibling — Возвращает предыдущего брата узла
    • DomNode::remove_child — Удаляет сына из списка сыновей
    • DomNode::replace_child — Замена сына
    • DomNode::replace_node — Заменяет узел
    • DomNode::set_content — Устанавливает содержимое узла
    • DomNode::set_name — Устанавливает имя узла
    • DomNode::set_namespace — Устанавливает пространство имен узла
    • DomNode::unlink_node — Удаляет узел
    • DomProcessingInstruction::data — Возвращает данные узла ProcessingInstruction
    • DomProcessingInstruction::target — Возвращает цель узла ProcessingInstruction
    • DomXsltStylesheet::process — Применяет XSLT-преобразование к объекту DomDocument
    • DomXsltStylesheet::result_dump_file — Сохраняет результат XSLT-Преобразования в файл
    • DomXsltStylesheet::result_dump_mem — Представляет результат XSLT-Преобразования в виде строки
    • domxml_new_doc — Создает новый пустой XML документ
    • domxml_open_file — Создает объект DOM из XML файла
    • domxml_open_mem — Создает объект DOM XML документа
    • domxml_version — Получает номер версии XML библиотеки
    • domxml_xmltree — Создает дерево объектов PHP из XML документа
    • domxml_xslt_stylesheet_doc — Создает объект класса DomXsltStylesheet из объекта DomDocument
    • domxml_xslt_stylesheet_file — Создает объект DomXsltStylesheet из XML файла
    • domxml_xslt_stylesheet — Создает объект DomXsltStylesheet из строки XSL
    • domxml_xslt_version — Получает версию XSLT библиотеки
    • xpath_eval_expression — Вычисляет XPath Location Path в переданной строке
    • xpath_eval — Вычисляет XPath Location Path в переданной строке
    • xpath_new_context — Создает новый xpath контекст
    • xpath_register_ns_auto — Регистрация заданного пространства имен в определенном XPath контексте
    • xpath_register_ns — Регистрирует пространство имен в переданном XPath контексте
    • xptr_eval — Вычисляет XPtr Location Path в заданной строке
    • xptr_new_context — Создает новый контекст XPath

User Contributed Notes

There are no user contributed notes for this page.
dom_import_simplexml
Введение
Обработка XML


Введение

Расширение DOM XML было доработано в PHP 4.3.0 для лучшей совместимости со стандартом DOM. Оно до сих пор содержит множество старых функций, поддержка которых вскоре прекратится. В частности, следует избегать использования не объектно-ориентированных функций.

Расширение позволяет работать с XML документами с использованием DOM API. Оно также предоставляет функцию domxml_xmltree() для преобразования XML документа в дерево объектов PHP. На данный момент, дерево, построенное этой функцией, обладает свойством только для чтения - можно его изменять, но эти изменения не сохраняются с тех пор, как стало невозможным применение функции DomDocument_dump_mem() к подобным объектам. Следовательно, если требуется читать XML файл и записывать его измененный вариант, необходимо пользоваться функциями DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), и т.д. и в завершении DomDocument_dump_mem().

Замечание:

Это расширение было перемещено в репозиторий » PECL и больше не поставляется с PHP 5.0.0.

Замечание: Это расширение более не отмечено как экспериментальное. Тем не менее, оно не будет реализовано в PHP 5 и будет поставляться только с PHP 4. Если требуется поддержка DOM XML в PHP 5, можно использовать расширение DOM. Расширение domxml не совместимо с расширением DOM.

User Contributed Notes

There are no user contributed notes for this page.
DOM XML (PHP 4)
Установка и настройка
DOM XML (PHP 4)


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
DOM XML (PHP 4)


Требования

Это расширение использует » XML библиотеку GNOME. Скачайте и установите ее. Вам потребуется по меньшей мере libxml-2.4.14. Для использования возможностей DOM XSLT установите » библиотеку libxslt, а также » http://www.exslt.org/. Вам потребуется по меньшей мере libxslt-1.0.18.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Это расширение » PECL не поставляется вместе с PHP. Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pecl.php.net/package/domxml.

В PHP 4 исходные файлы этого расширения PECL могут быть найдены в директории ext/ внутри исходных файлов PHP или по ссылке PECL выше. Это расширение доступно только если PHP сконфигурирован с настройкой --with-dom[=DIR] . Добавление настройки --with-dom-xslt[=DIR] включает поддержку XSLT. DIR - директория установленной libxslt. Для включения поддержки DOM EXSLT нужно добавить настройку --with-dom-exslt[=DIR] , где DIR - директория установленной libexslt.

Для использования функций в среде Windows необходимо включить php_domxml.dll в файле php.ini. В PHP 4 эта DLL находится в директории extensions/ внутри директории бинарного дистрибутива PHP для Windows. DLL для этого расширения PECL в данный момент недоступна. См. также раздел сборка на Windows. Также, есть одна DLL библиотека, которая должна быть доступна через системную переменную окружения PATH. В PHP 4 эта библиотека хранится в директории dlls/. Ее название: Для PHP <= 4.2.0 - libxml2.dll. Для PHP >= 4.3.0 - iconv.dll. В версии 5.0.0 iconv уже встроена в Windows PHP, и никакой дополнительной библиотеки не требуется.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

Константы XML
Константа | Значение | Описание
XML_ELEMENT_NODE (integer) | 1 | Узел является элементом
XML_ATTRIBUTE_NODE (integer) | 2 | Узел является атрибутом
XML_TEXT_NODE (integer) | 3 | Узел является отрывком текста
XML_CDATA_SECTION_NODE (integer) | 4 |
XML_ENTITY_REF_NODE (integer) | 5 |
XML_ENTITY_NODE (integer) | 6 | Узел является сущностью, как &nbsp;
XML_PI_NODE (integer) | 7 | Узел является инструкцией
XML_COMMENT_NODE (integer) | 8 | Узел является комментарием
XML_DOCUMENT_NODE (integer) | 9 | Узел является документом
XML_DOCUMENT_TYPE_NODE (integer) | 10 |
XML_DOCUMENT_FRAG_NODE (integer) | 11 |
XML_NOTATION_NODE (integer) | 12 |
XML_GLOBAL_NAMESPACE (integer) | 1 |
XML_LOCAL_NAMESPACE (integer) | 2 |
XML_HTML_DOCUMENT_NODE (integer) |  |
XML_DTD_NODE (integer) |  |
XML_ELEMENT_DECL_NODE (integer) |  |
XML_ATTRIBUTE_DECL_NODE (integer) |  |
XML_ENTITY_DECL_NODE (integer) |  |
XML_NAMESPACE_DECL_NODE (integer) |  |
XML_ATTRIBUTE_CDATA (integer) |  |
XML_ATTRIBUTE_ID (integer) |  |
XML_ATTRIBUTE_IDREF (integer) |  |
XML_ATTRIBUTE_IDREFS (integer) |  |
XML_ATTRIBUTE_ENTITY (integer) |  |
XML_ATTRIBUTE_NMTOKEN (integer) |  |
XML_ATTRIBUTE_NMTOKENS (integer) |  |
XML_ATTRIBUTE_ENUMERATION (integer) |  |
XML_ATTRIBUTE_NOTATION (integer) |  |
XPATH_UNDEFINED (integer) |  |
XPATH_NODESET (integer) |  |
XPATH_BOOLEAN (integer) |  |
XPATH_NUMBER (integer) |  |
XPATH_STRING (integer) |  |
XPATH_POINT (integer) |  |
XPATH_RANGE (integer) |  |
XPATH_LOCATIONSET (integer) |  |
XPATH_USERS (integer) |  |

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
DOM XML (PHP 4) Функции
DOM XML (PHP 4)


DOM XML (PHP 4) Функции

Устаревшие функции

Довольно много функций в расширении не вписываются в стандарт DOM и не будут в дальнейшем использоваться. Эти функции представлены в приведенном ниже списке. Функция DomNode_append_child() изменила свое поведение. Теперь она добавляет только сына узла и не добавляет брата. Если это поведение неприемлемо для вашего приложения, используйте не-DOM функцию DomNode_append_sibling().

Устаревшие и их заменяющие функции
Устаревшая функция | Новая функция
xmldoc | domxml_open_mem()
xmldocfile | domxml_open_file()
domxml_new_xmldoc | domxml_new_doc()
domxml_dump_mem | DomDocument_dump_mem()
domxml_dump_mem_file | DomDocument_dump_file()
DomDocument_dump_mem_file | DomDocument_dump_file()
DomDocument_add_root | DomDocument_create_element() followed by DomNode_append_child()
DomDocument_dtd | DomDocument_doctype()
DomDocument_root | DomDocument_document_element()
DomDocument_children | DomNode_child_nodes()
DomDocument_imported_node | No replacement.
DomNode_add_child | Создает новый узел, например функцией DomDocument_create_element(), и добавляет его функцией DomNode_append_child().
DomNode_children | DomNode_child_nodes()
DomNode_parent | DomNode_parent_node()
DomNode_new_child | Создает новый узел, например функцией DomDocument_create_element(), и добавляет его функцией DomNode_append_child().
DomNode_set_content | Создает новый узел, например функцией DomDocument_create_text_node(), и добавляет его функцией DomNode_append_child().
DomNode_get_content | Контент - это просто текстовый узел, доступ к которому можно получить посредством DomNode_child_nodes().
DomNode_set_content | Контент - это просто текстовый узел, который можно добавить посредством DomNode_append_child().

Классы

API этого модуля соответствует стандарту DOM Level 2 настолько, насколько это возможно. В частности, API полностью объектно-ориентированный. Было бы неплохой идеей иметь под рукой стандарт DOM при работе с этим модулем. Несмотря на то, что API объектно-ориентирован, есть множество функций, которые могут вызываться в процедурном стиле посредством передачи объекта обработки первым аргументом функции. Эти функции предназначены для сохранения совместимости со старыми версиями расширения и не должны применяться в новых создаваемых скриптах.

Этот API отличается от официального DOM API по двум направлениям. Во-первых, все свойства класса представлены в виде одноименных функций. Во-вторых, имена функций соответствуют правилам именования функций в PHP. Это означает, что DOM-функция lastChild() будет записана как last_child().

В модуле определены классы, которые приведены в списке ниже, включая свои методы. Классы, являющиеся аналогом классов в стандарте DOM, имеют название вида DOMxxx.

Список классов
Имя класса | Родительские классы
DomAttribute | DomNode
DomCData | DomNode
DomComment | DomCData : DomNode
DomDocument | DomNode
DomDocumentType | DomNode
DomElement | DomNode
DomEntity | DomNode
DomEntityReference | DomNode
DomProcessingInstruction | DomNode
DomText | DomCData : DomNode
Parser | На данный момент все еще именуется, как DomParser
XPathContext |

Класс DomDocument (DomDocument : DomNode)
Имя метода | Имя функции | Замечание
doctype | DomDocument_doctype() |
document_element | DomDocument_document_element() |
create_element | DomDocument_create_element() |
create_text_node | DomDocument_create_text_node() |
create_comment | DomDocument_create_comment() |
create_cdata_section | DomDocument_create_cdata_section() |
create_processing_instruction | DomDocument_create_processing_instruction() |
create_attribute | DomDocument_create_attribute() |
create_entity_reference | DomDocument_create_entity_reference() |
get_elements_by_tagname | DomDocument_get_elements_by_tagname() |
get_element_by_id | DomDocument_get_element_by_id() |
dump_mem | DomDocument_dump_mem() | отсутствует в стандарте DOM
dump_file | DomDocument_dump_file() | отсутствует в стандарте DOM
html_dump_mem | DomDocument_html_dump_mem() | отсутствует в стандарте DOM
xpath_init | xpath_init | отсутствует в стандарте DOM
xpath_new_context | xpath_new_context | отсутствует в стандарте DOM
xptr_new_context | xptr_new_context | отсутствует в стандарте DOM

Класс DomElement (DomElement : DomNode)
Имя метода | Имя функции | Замечание
tagname | DomElement_tagname() |
get_attribute | DomElement_get_attribute() |
set_attribute | DomElement_set_attribute() |
remove_attribute | DomElement_remove_attribute() |
get_attribute_node | DomElement_get_attribute_node() |
set_attribute_node | DomElement_set_attribute_node() |
get_elements_by_tagname | DomElement_get_elements_by_tagname() |
has_attribute | DomElement_has_attribute() |

Класс DomNode
Имя метода | Замечание
DomNode_node_name() |
DomNode_node_value() |
DomNode_node_type() |
DomNode_last_child() |
DomNode_first_child() |
DomNode_child_nodes() |
DomNode_previous_sibling() |
DomNode_next_sibling() |
DomNode_parent_node() |
DomNode_owner_document() |
DomNode_insert_before() |
DomNode_append_child() |
DomNode_append_sibling() | Отсутствует в стандарте DOM. Эта функция эмулирует поведение DomNode_append_child(), касающееся создания узла.
DomNode_remove_child() |
DomNode_has_child_nodes() |
DomNode_has_attributes() |
DomNode_clone_node() |
DomNode_attributes() |
DomNode_unlink_node() | Отсутствует в стандарте DOM
DomNode_replace_node() | Отсутствует в стандарте DOM
DomNode_set_content() | Отсутствует в стандарте DOM, устарела
DomNode_get_content() | Отсутствует в стандарте DOM, устарела
DomNode_dump_node() | Отсутствует в стандарте DOM
DomNode_is_blank_node() | Отсутствует в стандарте DOM

Класс DomAttribute (DomAttribute : DomNode)
Имя метода |  | Замечание
name | DomAttribute_name() |
value | DomAttribute_value() |
specified | DomAttribute_specified() |

Класс DomProcessingInstruction (DomProcessingInstruction : DomNode)
Имя метода | Имя функции | Замечание
target | DomProcessingInstruction_target() |
data | DomProcessingInstruction_data() |

Класс Parser
Имя метода | Имя функции | Замечание
add_chunk | Parser_add_chunk() |
end | Parser_end() |

Класс XPathContext
Имя метода | Имя функции | Замечание
eval | XPathContext_eval() |
eval_expression | XPathContext_eval_expression() |
register_ns | XPathContext_register_ns() |

Класс DomDocumentType (DomDocumentType : DomNode)
Имя метода | Имя функции | Замечание
name | DomDocumentType_name() |
entities | DomDocumentType_entities() |
notations | DomDocumentType_notations() |
public_id | DomDocumentType_public_id() |
system_id | DomDocumentType_system_id() |
internal_subset | DomDocumentType_internal_subset() |

Класс DomDtd исключен из DomNode. DomComment исключен из DomCData.

Примеры

Многие примеры в этом разделе требуют наличия строки XML. Вместо повторения этой строки в каждом примере, она помещена в файл, который будет добавляться в примерах. Содержимое этого файла приведено ниже в подразделе примеров. С другой стороны, ничего не мешает вам создать собственный XML документ и прочитать его функцией DomDocument_open_file().

Пример #1 Включаемый файл example.inc c XML-строкой

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &sp;
  <!-- comment -->
  <informaltable ID='findme' language='&sp;'>
   <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>
</chapter>";
?>

Содержание

  • DomAttribute::name — Возвращает имя атрибута
  • DomAttribute::set_value — Устанавливает значение атрибута
  • DomAttribute::specified — Проверяет, задан ли атрибут
  • DomAttribute::value — Возвращает значение атрибута
  • DomDocument::add_root — Добавляет корневой узел [устаревший метод]
  • DomDocument::create_attribute — Создает новый атрибут
  • DomDocument::create_cdata_section — Создает новый узел типа cdata
  • DomDocument::create_comment — Создает новый узел-комментарий
  • DomDocument::create_element_ns — Создает новый элемент с соответствующим пространством имен
  • DomDocument::create_element — Создает новый узел-элемент
  • DomDocument::create_entity_reference — Создает ссылку на сущность
  • DomDocument::create_processing_instruction — Создает новый PI узел
  • DomDocument::create_text_node — Создает новый текстовый узел
  • DomDocument::doctype — Возвращает тип документа
  • DomDocument::document_element — Возвращает узел корневого элемента
  • DomDocument::dump_file — Сохраняет XML дерево в файл
  • DomDocument::dump_mem — Представляет XML дерево в виде строки
  • DomDocument::get_element_by_id — Ищет элемент с заданным id
  • DomDocument::get_elements_by_tagname — Возвращает массив узлов с заданным тэгом в документе или пустой массив, если таких элементов не найдено
  • DomDocument::html_dump_mem — Преобразует дерево XML в HTML строку
  • DomDocument::xinclude — Подстановка XIncludes в объекте DomDocument
  • DomDocumentType::entities — Возвращает список сущностей
  • DomDocumentType::internal_subset — Возвращает подмножество внутренней структуры dom документа
  • DomDocumentType::name — Возвращает имя типа документа
  • DomDocumentType::notations — Возвращает список обозначений
  • DomDocumentType::public_id — Возвращает общедоступный (public) идентификатор типа документа
  • DomDocumentType::system_id — Возвращает системный идентификатор типа документа
  • DomElement::get_attribute_node — Возвращает узел заданного атрибута
  • DomElement::get_attribute — Возвращает значение заданного атрибута
  • DomElement::get_elements_by_tagname — Получает элементы по имени
  • DomElement::has_attribute — Проверяет, есть ли атрибут в текущем узле
  • DomElement::remove_attribute — Удаляет атрибут
  • DomElement::set_attribute_node — Добавляет новый атрибут
  • DomElement::set_attribute — Устанавливает значение атрибута
  • DomElement::tagname — Возвращает имя текущего элемента
  • DomNode::add_namespace — Добавляет узлу объявление пространства имен
  • DomNode::append_child — Добавляет нового сына в конец списка сыновей
  • DomNode::append_sibling — Добавляет к узлу нового брата
  • DomNode::attributes — Возвращает список атрибутов
  • DomNode::child_nodes — Возвращает сыновей узла
  • DomNode::clone_node — Копирует узел
  • DomNode::dump_node — Представляет одиночный узел в виде строки
  • DomNode::first_child — Возвращает первого сына узла
  • DomNode::get_content — Получает содержимое узла
  • DomNode::has_attributes — Проверяет, есть ли в узле атрибуты
  • DomNode::has_child_nodes — Проверяет, есть ли у узла потомки
  • DomNode::insert_before — Вставляет новый узел в качестве сына
  • DomNode::is_blank_node — Проверяет, есть ли содержимое в узле
  • DomNode::last_child — Возвращает последнего сына узла
  • DomNode::next_sibling — Возвращает следующего брата узла
  • DomNode::node_name — Возвращает имя узла
  • DomNode::node_type — Возвращает тип узла
  • DomNode::node_value — Возвращает значение узла
  • DomNode::owner_document — Возвращает документ, которому принадлежит этот узел
  • DomNode::parent_node — Возвращает родителя узла
  • DomNode::prefix — Возвращает префикс пространства имен узла
  • DomNode::previous_sibling — Возвращает предыдущего брата узла
  • DomNode::remove_child — Удаляет сына из списка сыновей
  • DomNode::replace_child — Замена сына
  • DomNode::replace_node — Заменяет узел
  • DomNode::set_content — Устанавливает содержимое узла
  • DomNode::set_name — Устанавливает имя узла
  • DomNode::set_namespace — Устанавливает пространство имен узла
  • DomNode::unlink_node — Удаляет узел
  • DomProcessingInstruction::data — Возвращает данные узла ProcessingInstruction
  • DomProcessingInstruction::target — Возвращает цель узла ProcessingInstruction
  • DomXsltStylesheet::process — Применяет XSLT-преобразование к объекту DomDocument
  • DomXsltStylesheet::result_dump_file — Сохраняет результат XSLT-Преобразования в файл
  • DomXsltStylesheet::result_dump_mem — Представляет результат XSLT-Преобразования в виде строки
  • domxml_new_doc — Создает новый пустой XML документ
  • domxml_open_file — Создает объект DOM из XML файла
  • domxml_open_mem — Создает объект DOM XML документа
  • domxml_version — Получает номер версии XML библиотеки
  • domxml_xmltree — Создает дерево объектов PHP из XML документа
  • domxml_xslt_stylesheet_doc — Создает объект класса DomXsltStylesheet из объекта DomDocument
  • domxml_xslt_stylesheet_file — Создает объект DomXsltStylesheet из XML файла
  • domxml_xslt_stylesheet — Создает объект DomXsltStylesheet из строки XSL
  • domxml_xslt_version — Получает версию XSLT библиотеки
  • xpath_eval_expression — Вычисляет XPath Location Path в переданной строке
  • xpath_eval — Вычисляет XPath Location Path в переданной строке
  • xpath_new_context — Создает новый xpath контекст
  • xpath_register_ns_auto — Регистрация заданного пространства имен в определенном XPath контексте
  • xpath_register_ns — Регистрирует пространство имен в переданном XPath контексте
  • xptr_eval — Вычисляет XPtr Location Path в заданной строке
  • xptr_new_context — Создает новый контекст XPath

User Contributed Notes

joaschi at gmx dot net 18-Jul-2008 04:55
The PHP 5.0 DOM is very powerful to create and work on valid RSS Feeds. I found a easy to follow step-by-step-tutorial here:
http://xml-rss.de/xml-rss-feed-mit-php.htm
(in german language but the code can be understand in every language i think) maybe it helps someone to understand the DOM-Thing better. But beware it don´t work on PHP 4!
gue-gue at gmx dot de 04-Apr-2007 07:46
Hi at All,

if you use xpath_eval() you get a xpathobject with a type-member-variable, which tells you about the type of the found content. Here are the values and the corresponding types:
1 = XPATH_NODESET (integer)
2 = XPATH_BOOLEAN (integer)
3 = XPATH_NUMBER (integer)
4 = XPATH_STRING (integer)

I think, but don't know, that the rest of the constants are:
0 = XPATH_UNDEFINED (integer)
5 = XPATH_POINT (integer)
6 = XPATH_RANGE (integer)
7 = XPATH_LOCATIONSET (integer)

I hope i could help some people.

Greetz,
Chris
01-Dec-2006 08:05
Referenced array functions drive me crazy for one reason or another (personal issue I guess).  So for any others like me, here's my modification (thanks to the original posters below for the base to work on!)

I haven't tested this on much more than simple XML files, so there's probably a few ways to break this - I'm also thinking this could probably be rewritten to be more efficient also, but it's working quite well for me thus far.

<?php

function xml2array($domnode)
{
    $nodearray = array();
    $domnode = $domnode->firstChild;
    while (!is_null($domnode))
    {
        $currentnode = $domnode->nodeName;
        switch ($domnode->nodeType)
        {
            case XML_TEXT_NODE:
                if(!(trim($domnode->nodeValue) == "")) $nodearray['cdata'] = $domnode->nodeValue;
            break;
            case XML_ELEMENT_NODE:
                if ($domnode->hasAttributes() )
                {
                    $elementarray = array();
                    $attributes = $domnode->attributes;
                    foreach ($attributes as $index => $domobj)
                    {
                        $elementarray[$domobj->name] = $domobj->value;
                    }
                }
            break;
        }
        if ( $domnode->hasChildNodes() )
        {
            $nodearray[$currentnode][] = xml2array($domnode);
            if (isset($elementarray))
            {
                $currnodeindex = count($nodearray[$currentnode]) - 1;
                $nodearray[$currentnode][$currnodeindex]['@'] = $elementarray;
            }
        } else {
            if (isset($elementarray) && $domnode->nodeType != XML_TEXT_NODE)
            {
                $nodearray[$currentnode]['@'] = $elementarray;
            }
        }
        $domnode = $domnode->nextSibling;
    }
    return $nodearray;
}
?>
Palatinusz - karoly_szalkary at yahoo dot com 25-Jan-2006 04:05
My short way of parsing an XML document, for example displaying the document in a structured form:

<?php
$indent = "";
$file = "semi.xml";

$showfile = file_get_contents("c:/Program Files/Apache Group/apache/htdocs/phpxml" . "/" . $file);  // whatever path
   // maybe the whole path is not important, look it up in other posts

$newstring=utf8_encode($showfile);          // it's important!
if(!$domDocument = domxml_open_mem($newstring)) {
   echo "Couldn't load xml...";
   exit;
}

$rootDomNode = $domDocument->document_element();
print "<pre>";
printElements($rootDomNode);
print "</pre>";

function printElements($domNode)
{
  if($domNode)
  {
    global $indent;

    if($domNode->node_type() == XML_ELEMENT_NODE)
    {
      print "<br />".$indent."&lt;".$domNode->node_name();
      if($domNode->has_attributes())
      {
        $attributes = $domNode->attributes();
        foreach($attributes as $domAttribute)
        {
          print " $domAttribute->name=\"$domAttribute->value\"";
        }
      }
      print "&gt;";
      if($domNode->has_child_nodes())
      {
        $indent.="  ";
        $nextNode = $domNode->first_child();
        printElements($nextNode);
        $indent= substr($indent, 0, strlen($indent)-2);
        print "<br />".$indent."&lt;"."/".$domNode->node_name()."&gt;";
      }
      else
      {
        print "$domNode->node_value()&lt;/".$domNode->node_name()."&gt;";
      }
    }

    $nextNode = $domNode->next_sibling();
    printElements($nextNode);
  }
}
?>
Squiz 13-Dec-2005 11:04
Re: websiterepairguys...  Close but no cigar ;-)

As written it will not work if the repeated tags are somewhere other than the first node, i.e. the following will not work:
<nodes>
  <node>onething</node>
  <node>something</node>
  <node>something</node>
</nodes>

You must store the new node name when you get a new sibling that doesn't match the previous and then it will work OK.  Amended code:

function dom_to_array($domnode, &$array) {
  $parent=$domnode;
  $domnode = $domnode->firstChild;
  $myname=$domnode->nodeName;
  $x=1;
  while (!is_null($domnode)) {
     switch ($domnode->nodeType) {
        case XML_ELEMENT_NODE: {
           if ( !$domnode->hasChildNodes()) {
              $array[$domnode->nodeName]='';
           } else if ( $domnode->hasChildNodes() && $domnode->firstChild->nodeType==XML_TEXT_NODE) {
              $array[$domnode->nodeName]=$domnode->firstChild->nodeValue;
           } else if ( $domnode->hasChildNodes() )  {
              $array_ptr = & $array[$domnode->nodeName];
              dom_to_array($domnode, $array_ptr);
           }
           break;
        }
     }
     $domnode = $domnode->nextSibling;
     if($domnode->nodeName == $myname)
     {
        $domnode->nodeName.=($x++);
     } else {
        $myname = $domnode->nodeName;
     }
  }
}
websiterepairguys at spamnot dot yahoo dot com 11-Nov-2005 09:43
I tried using the dom_to_simple_array that the user jas posted above, but it didnt work very well.

The problems were it didnt handle sibling nodes with the same name, such as:

<nodes>
  <node>something</node>
   <node>something</node>
</nodes>

Also, when it built child arrays from child nodes, it always interjected an wrapping array around the child, which isnt necessary.  Here is the patched code:

function dom_to_array($domnode, &$array) {
  $parent=$domnode;
  $domnode = $domnode->firstChild;
  $myname=$domnode->nodeName;
  $x=1;
  while (!is_null($domnode)) {
     switch ($domnode->nodeType) {

       case XML_ELEMENT_NODE: {

             if ( !$domnode->hasChildNodes()) {
                 $array[$domnode->nodeName]='';
             } else if ( $domnode->hasChildNodes() && $domnode->firstChild->nodeType==XML_TEXT_NODE) {
                 $array[$domnode->nodeName]=$domnode->firstChild->nodeValue;
             } else if ( $domnode->hasChildNodes() )  {

         $array_ptr = & $array[$domnode->nodeName];
           dom_to_array($domnode, $array_ptr);
         break;
       }
    }
    }
         $domnode = $domnode->nextSibling;
       if($domnode->nodeName==$myname)
       {
              $domnode->nodeName.=($x++);
       }
  }
}

snippet of array produced by this:

[admin] => Array
        (
            [menu] => Array
                (
                    [title] => Page Manager
                    [view] => list
                )

            [files] => Array
                (
                    [filename] => modules/testmodule/testmodule.php
                    [filename1] => modules/testmodule/testmodule.xml
                    [filename2] => media/lang/en-us/templates/testmodule.tpl
                )

        )
timo dot hummel at 4fb dot de 07-Jul-2005 12:57
If you want to subclass the domxml-classes, you have to use PHP5. It doesn't work with PHP4, and never will.
steve at find-information-on dot com 11-Feb-2005 04:33
If you are using apache, instead of copying files around (iconv.dll for instance) you can use this in your httpd.conf for apache:

LoadFile "d:/php/dlls/iconv.dll"

I placed this line before

LoadModule php4_module "d:/php/sapi/php4apache2.dll"

and it worked, no copying of files or anything therefore helps when updating php, don't have to mess around searching for files and other stuff.
ndaniel at bsi-scs dot com 22-Dec-2004 05:54
I recently developed a script for parsing DHL XML transaction responses - finding it a pain in the rear to actually parse the XML and set my variables - it actually wasn't that hard once I figured it out - and it goes something like this...

<?php

// Use with a class containing functions set_attributes() and
// set_data().  Use the following to set variables from the
// resulting xml.  $node is a dom xml object - in the first call
// to loop, $node would be equal to the root document
// element.

function loop($node) {
 // set attribute tags here
 if ($node->has_attributes()) {
    $this->set_attributes($node);
 } // end if node has attributes

 if ($node->has_child_nodes()) {
    $this->loop($node->first_child());
 } // end if node has child
 else {
    $this->set_data($node);
 } // end if node has no child
 // get next sibling
 $node = $node->next_sibling();
 if ($node) {
    $this->loop($node);
 } // end if node
} // end function loop
?>

The code goes from the root element, if the element has attributes - it sets attribute variables.  Second, it recursively proceeds to the lowest level element (no more children).  Once that level has been reached, data variables are set.  The next step goes to the next sibling of the element, if it exists.  If the next sibling does not exists, the function is ended and the current element is returned to the parent element.  The parent element is then checked for siblings.  This process continues (as is with recursion) until the parent element is back at the root element, which is the end of the document.
deborah dot seidman at imc-fr dot com 10-Dec-2004 08:15
You can always use a sax parser (expat) which saves on memory storage (there is none as sax is event driven) and use this neat code to produce an array structure of you xml file :

see http://fr2.php.net/manual/fr/function.xml-parse.php

comment by
tgrabietz at bupnet dot de
22-Sep-2004 05:05
jas at uci dot edu 15-Nov-2004 03:56
i needed to have an easy way to create a multi-dimensional but EXTREMELY SIMPLE php array out of some XML text i'm receiving. NOT an object. just an ARRAY.

i found that as simple a request as this seemed to be, the new (php5) DOM functions do not provide this functionality.

even the SimpleXML functions are object-oriented, which doesn't work for some of my purposes (sending to a Smarty template variable for looping through, etc.) -- returning attributes as SimpleXMLElement objects instead of strings, etc.. i just wanted an ARRAY containing the data as STRINGS.

eli (http://www.hoktar.com) had submitted such code earlier, based on domxml/php4 calls. his function was called "domxml_xmlarray".

but when php5 came out, eli's comments at the bottom of the PHP site got erased. (fortunately, i had already saved his code.) no doubt, mine will too w/next version..

furthermore, as far as i can tell, no one has taken the cue to add something like eli's domxml_xmlarray function directly into the DOMDocument object (but it would be nice).

so i translated eli's code, now using the dom calls (instead of the older domxml calls), and renamed the function to "dom_to_simple_array()".

below is a script containing the function itself as well as an example of its use. just copy it to your server somewhere and execute it and it should work right off the bat if you are using php5.

thanks.
jeff stern

==================================================================
<?php

function dom_to_simple_array($domnode, &$array) {
  $array_ptr = &$array;
  $domnode = $domnode->firstChild;
  while (!is_null($domnode)) {
    if (! (trim($domnode->nodeValue) == "") ) {
      switch ($domnode->nodeType) {
        case XML_TEXT_NODE: {
          $array_ptr['cdata'] = $domnode->nodeValue;
          break;
        }
        case XML_ELEMENT_NODE: {
          $array_ptr = &$array[$domnode->nodeName][];
          if ($domnode->hasAttributes() ) {
            $attributes = $domnode->attributes;
            if (!is_array ($attributes)) {
              break;
            }
            foreach ($attributes as $index => $domobj) {
              $array_ptr[$index] = $array_ptr[$domobj->name] = $domobj->value;
            }
          }
          break;
        }
      }
      if ( $domnode->hasChildNodes() ) {
        dom_to_simple_array($domnode, $array_ptr);
      }
    }
    $domnode = $domnode->nextSibling;
  }
}

  # now, let's make a sample string containing some XML
  $strXMLData = "<contacts>
       <contact>
         <name>
           John Doe
         </name>
         <phone>
           123-456-7890
         </phone>
       </contact>
       <contact>
         <name>
           Mary Smiley
         </name>
         <phone>
           567-890-1234
         </phone>
       </contact>
     </contacts>";

  # create a DOM tree xml object (hierarchical array) from
  # this XML string
  $domdoc = new DOMDocument;
  $domdoc->loadXML($strXMLData);

  # now simplify the DOM array into a very simple array structure

  # first, create an empty array to be filled with your
  # simplified array result..
  $aData = array();

  # now, pass the dom document and your empty array to the
  # converter function.
  dom_to_simple_array($domdoc, $aData);

  # now $aData contains your simplified array, so print it out
?><html>
<body>
<p>there are <? echo count($aData['contacts'][0]['contact']); ?>
 contacts</p>
<p>the 2nd contact's phone number is
<?echo $aData['contacts'][0]['contact'][1]['phone'][0]['cdata']; ?>
</p>
<hr />
<p>Here is the raw array structure:</p>
<pre>
<? print_r($aData); ?>
</pre>
</body>
</html>
==================================================================
Alex 04-Jul-2004 09:48
PHP4/DOMXML code is not compatible with the new PHP5/dom extension. While the conversion is quite strait forward, it can take a long time if domxml has been broadly used. Moreover, it can be interesting to have old PHP4 scripts ready for PHP5 as soon as possible even if the server is still running PHP4. Since I have that kind of problem, if have written a small library to include in PHP4 scripts to enable them to be run on PHP5. http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/

It does not cover all the domxml functionality, but most of the main functions and can easily be extended. Tested with PHP4.3.7 and PHP5.0.0RC3 but I will try to keep it updated. I hope it can help.
SAM 22-Apr-2004 11:05
When installing PHP --with-dom and --with-dom-xslt on a Red Hat 9.0 remember to install the following packages:

libxml
libxml2
libxml2-devel
libxslt
libxslt-devel

Then you will be spared error messages when trying to configure.

regards
SAM
ngc(dontSpamMe)rapanden(SpamOFF)dk 28-Jan-2004 04:48
Sorry, a bug in my code... I made the first version late at night, sorry!

The bug was in the "if ($ChildDomNode->has_child_nodes())" block, I didn't save the data for the for the CildNode of the CildNodes. the bug has been fixed.

<?php
function getElementAttributes($DomNode,$elementName,$attriName)
{
   if ($ChildDomNode = $DomNode->first_child())
    {
       while($ChildDomNode)
        {
            if ($ChildDomNode->node_type() == XML_ELEMENT_NODE)
             {
               if($ChildDomNode->node_name() == $elementName)
                {

                 if ($ChildDomNode->has_attributes())
                  {
                   $Array = $ChildDomNode->attributes();
                   foreach ($Array AS $DomAttribute)
                    {
                       if($DomAttribute->name() == $attriName)
                        {
                         $nodeArray[] = $DomAttribute->value();
                        }
                    }// foreach ($Array AS $DomAttribute)

                 }//if ($ChildDomNode->has_attributes())

                }

              if ($ChildDomNode->has_child_nodes())
                {
                   $tmpArray = (getElementAttributes($ChildDomNode,$elementName,$attriName));
                   $nodeArray = array_merge($nodeArray, $tmpArray);
                   unset($tmpArray);
                }// if ($ChildDomNode->has_child_nodes())

           }//if ($ChildDomNode->node_type() == XML_ELEMENT_NODE)

           $ChildDomNode = $ChildDomNode->next_sibling();

       }//while($ChildDomNode)

   return $nodeArray;
  }//if ($ChildDomNode = $DomNode->first_child())

}
$file = "test3.xml";
$element = "pb";
$att = "id";
$DomDocument = domxml_open_file($file);
$RootDomNode = $DomDocument->document_element();
$array = getElementAttributes($RootDomNode,$element,$att);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
bradparks at bradparks dot com 17-Dec-2003 02:41
Hey;

If you need to parse XML on an older version of PHP (e.g. 4.0) or if you can't get the expat extension enabled on your server, you might want to check out the Saxy and DOMIT! xml parsers from Engage Interactive. They're opensource and pure php, so no extensions or changes to your server are required. I've been using them for over a month on some projects with no problems whatsoever!

Check em out at:

DOMIT!, a DOM based xml parser, uses Saxy (included)
http://www.engageinteractive.com/redir.php?resource=3&target=domit

or

Saxy, a sax based xml parser
http://www.engageinteractive.com/redir.php?resource=4&target=saxy

Brad
bart at mediawave dot nl 11-Nov-2003 11:46
This recursive function will iterate over a DOM object and display it as a nicely formatted XML structure. I used intuitive variable names to help learn more about the DOM functions and their return values.

<<?php

function PrintDomTree($DomNode)
{
    if ($ChildDomNode = $DomNode->first_child()) {
        static $depth = 0;

        $whitespace = "\n<br>".str_repeat(" ", ($depth * 2));

        while ($ChildDomNode) {
            if ($ChildDomNode->node_type() == XML_TEXT_NODE) {
                echo trim($ChildDomNode->node_value());
            } elseif ($ChildDomNode->node_type() == XML_ELEMENT_NODE) {
                $HasTag = 1;
                echo $whitespace;
                echo "<", $ChildDomNode->node_name();

                if ($ChildDomNode->has_attributes()) {
                    $Array = $ChildDomNode->attributes();
                    foreach ($Array AS $DomAttribute) {
                        echo " ", $DomAttribute->name(), "=\"", $DomAttribute->value(), "\"";
                    }
                }
                echo ">";

                if ($ChildDomNode->has_child_nodes()) {
                    $depth++;
                    if (PrintDomTree($ChildDomNode)) {
                        echo $whitespace;
                    }
                    $depth--;
                }
                echo "</", $ChildDomNode->node_name(), ">";
            }
            $ChildDomNode = $ChildDomNode->next_sibling();
        }
        return $HasTag;
    }
}

?>
nospam at phppatterns dot com 09-Apr-2003 01:51
If you're having trouble understanding how the the DOM XML extension fits together you may find the UML diagram here helps: http://www.phppatterns.com/index.php/article/articleview/38
sorn at dsl dot upc dot es 17-Mar-2003 03:38
When parsing "iso-8859-1" encoded XML files, use "utf8_decode" to recover node contents (libxml uses "UTF-8" internal encoding, so conversion needed).

--- BEGIN: mydata.xml ---
<?xml version="1.0" encoding="iso-8859-1"?>
...
--- END: mydata.xml---

--- BEGIN: myparser.php ---
<?php
...
$domxml = domxml_open_file("mydata.xml"));
...
$content = utf8_decode(trim($node->content));
echo $content;
...
?>
--- END: myparser.php

-eof-
Предопределенные константы
DomAttribute::name
DOM XML (PHP 4)


Возвращает имя атрибута

DOM XML (PHP 4) Функции
DomAttribute::set_value
DOM XML (PHP 4) Функции
PHP Manual

DomAttribute::name

(PHP 4 >= 4.1.0)

DomAttribute::name — Возвращает имя атрибута

Описание

string DomAttribute::name ( void )

Получает имя атрибута.

Возвращаемые значения

Возвращает имя атрибута.

Миграция на PHP 5

Используйте свойство name класса DOMAttr.

Смотрите также

  • Примеры смотрите на странице DomAttribute::value

User Contributed Notes

There are no user contributed notes for this page.
DOM XML (PHP 4) Функции
DomAttribute::set_value
DOM XML (PHP 4) Функции


Устанавливает значение атрибута

DomAttribute::name
DomAttribute::specified
DOM XML (PHP 4) Функции
PHP Manual

DomAttribute::set_value

(PHP 4 >= 4.1.0)

DomAttribute::set_value — Устанавливает значение атрибута

Описание

bool DomAttribute::set_value ( string $content )

Эта функция устанавливает значение атрибута.

Список параметров

content

Новое значение.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Миграция на PHP 5

Установите значение свойства value класса DOMAttr.

Смотрите также

  • DomAttribute::value

User Contributed Notes

There are no user contributed notes for this page.
DomAttribute::name
DomAttribute::specified
DOM XML (PHP 4) Функции


Проверяет, задан ли атрибут

DomAttribute::set_value
DomAttribute::value
DOM XML (PHP 4) Функции
PHP Manual

DomAttribute::specified

(PHP 4 >= 4.1.0)

DomAttribute::specified — Проверяет, задан ли атрибут

Описание

bool DomAttribute::specified ( void )

Проверяет, присвоено ли значение значение атрибуту в исходном документе.

Замечание:

Этот метод еще не реализован.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • Определение слов » заданный атрибут смотрите в рекомендациях к стандарту DOM

User Contributed Notes

There are no user contributed notes for this page.
DomAttribute::set_value
DomAttribute::value
DOM XML (PHP 4) Функции


Возвращает значение атрибута

DomAttribute::specified
DomDocument::add_root
DOM XML (PHP 4) Функции
PHP Manual

DomAttribute::value

(PHP 4 >= 4.1.0)

DomAttribute::value — Возвращает значение атрибута

Описание

string DomAttribute::value ( void )

Эта функция возвращает значение атрибута.

Примеры

Пример #1 Получение всех атрибутов узла

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
     echo "Ошибка при разборе документа\n";
     exit;
}

$root = $dom->document_element();
$attrs = $root->attributes();

echo 'Атрибуты узла ' . $root->node_name() . "\n";
foreach ($attrs as $attribute) {
     echo ' - ' . $attribute->name . ' : ' . $attribute->value . "\n";
}

?>

Результат выполнения данного примера:

Атрибуты узла chapter
 - language : en

Возвращаемые значения

Возвращает значение атрибута.

Миграция на PHP 5

Используйте свойство value класса DOMAttr.

Смотрите также

  • DomAttribute::set_value
  • DomAttribute::name

User Contributed Notes

There are no user contributed notes for this page.
DomAttribute::specified
DomDocument::add_root
DOM XML (PHP 4) Функции


Добавляет корневой узел [устаревший метод]

DomAttribute::value
DomDocument::create_attribute
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::add_root

(PHP 4 >= 4.1.0)

DomDocument::add_root — Добавляет корневой узел [устаревший метод]

Описание

domelement DomDocument::add_root ( string $name )

Добавляет корневой узел dom-документу и возвращает новый узел. Имя элемента берется из переданного аргумента.

Пример #1 Создание простого HTML заголовка

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("html");
$head = $root->new_child("head", "");
$head->new_child("title", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

User Contributed Notes

Jorrit Kronjee 05-Nov-2003 07:16
For those not closely reading the documentation (like me), this is an example of adding a root without add_root.

$new_dom = domxml_new_doc("1.0");
$new_element = $newdom->create_element("root_el");
$new_node = $newdom->append_child($new_element);
DomAttribute::value
DomDocument::create_attribute
DOM XML (PHP 4) Функции


Создает новый атрибут

DomDocument::add_root
DomDocument::create_cdata_section
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::create_attribute

(PHP 4 >= 4.1.0)

DomDocument::create_attribute — Создает новый атрибут

Описание

domattribute DomDocument::create_attribute ( string $name , string $value )

Эта функция возвращает новый экземпляр класса DomAttribute. Имя атрибута берется из первого аргумента. Значение атрибута берется из второго аргумента. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией domnode_append_child().

В случае ошибки метод вернет FALSE.

См. также domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_cdata_section(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference() и
domnode_insert_before().

User Contributed Notes

There are no user contributed notes for this page.
DomDocument::add_root
DomDocument::create_cdata_section
DOM XML (PHP 4) Функции


Создает новый узел типа cdata

DomDocument::create_attribute
DomDocument::create_comment
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::create_cdata_section

(PHP 4 >= 4.1.0)

DomDocument::create_cdata_section — Создает новый узел типа cdata

Описание

domcdata DomDocument::create_cdata_section ( string $content )

Эта функция возвращает новый экземпляр класса DomCData. Содержимое cdata берется из переданного аргумента. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией domnode_append_child().

В случае ошибки метод вернет FALSE.

См. также domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference() и
domnode_insert_before().

User Contributed Notes

barthelemy dot seb at gmail dot com 06-Jan-2009 04:55
Since php 5.2.7 release, this function work properly with empty content :

Function call : dom_document->createCDATASection("");

- php < 5.2.7 will return an empty node like : <MyNode></MyNode>
- php >= 5.2.7 will return an empty node with CDATA like : <MyNode><![CDATA[]]></MyNode>

it can make problem if you make a xsd validation after it with node cannot be empty
webmaster at freecaradverts dot com 01-Apr-2004 04:55
Beware if you're using the PEAR package XML_BEAUTIFIER. This causes the DOM processor to recognise any CDATA section nodes as text nodes. Better just to stick with the formatting option when using dump_file()......
laurent at rezoloco dot com 03-Sep-2003 10:05
add CDATA SECTION with xml content in a xml document

 $doc_in=domxml_open_mem('<?xml version="1.0"?><paragraphe></paragraphe>'));
    $root=$doc_in->document_element ();
    $node_txt_para=$root->new_child("txt_para","");
    $cdata=$doc_in->create_cdata_section("<root><child num=1></child></root>");
    $node_txt_para->append_child($cdata);
    $dump=$doc_in->dumpmem();
    print($dump);
DomDocument::create_attribute
DomDocument::create_comment
DOM XML (PHP 4) Функции


Создает новый узел-комментарий

DomDocument::create_cdata_section
DomDocument::create_element_ns
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::create_comment

(PHP 4 >= 4.1.0)

DomDocument::create_comment — Создает новый узел-комментарий

Описание

domcomment DomDocument::create_comment ( string $content )

Эта функция возвращает новый экземпляр класса DomComment. Содержимое комментария берется из переданного аргумента. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией domnode_append_child().

В случае ошибки метод вернет FALSE.

См. также domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference() и
domnode_insert_before().

User Contributed Notes

There are no user contributed notes for this page.
DomDocument::create_cdata_section
DomDocument::create_element_ns
DOM XML (PHP 4) Функции


Создает новый элемент с соответствующим пространством имен

DomDocument::create_comment
DomDocument::create_element
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::create_element_ns

(PHP 4 >= 4.1.0)

DomDocument::create_element_ns — Создает новый элемент с соответствующим пространством имен

Описание

domelement DomDocument::create_element_ns ( string $uri , string $name [, string $prefix ] )

Эта функция создает новый экземпляр класса DomElement. Имя тэга элемента берется из аргумента name. URI пространства имен берется из аргумента uri. Если пространство имен с таким же URI уже объявлено в корневом узле документа, префикс будет взят оттуда, в противном случае префикс будет взят из необязательного аргумента prefix, либо сгенерирован случайным образом. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией domnode_append_child().

В случае ошибки метод вернет FALSE.

См. также domdocument_create_element_ns(),
domnode_add_namespace(),
domnode_set_namespace(),
domnode_append_child(),
domdocument_create_text(),
domdocument_create_comment(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference() и
domnode_insert_before().

User Contributed Notes

There are no user contributed notes for this page.
DomDocument::create_comment
DomDocument::create_element
DOM XML (PHP 4) Функции


Создает новый узел-элемент

DomDocument::create_element_ns
DomDocument::create_entity_reference
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::create_element

(PHP 4 >= 4.1.0)

DomDocument::create_element — Создает новый узел-элемент

Описание

domelement DomDocument::create_element ( string $name )

Эта функция возвращает новый экземпляр класса DomElement. Тэг имени элемента берется из переданного аргумента. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией domnode_append_child().

В случае ошибки метод вернет FALSE.

См. также domdocument_create_element_ns(),
domnode_append_child(),
domdocument_create_text(),
domdocument_create_comment(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference() и
domnode_insert_before().

User Contributed Notes

arimbourg at ariworld dot eu 16-Mar-2009 01:59
It seem that the domDocument 'create_element' method don't work anymore in php 5.2.6.
We have to use the DOM 'createElement' instead.
Mikael Ljungberg 03-May-2005 10:46
When creating empty nodes like xhtml:link, the output misses the closing slash. This is what I got:

<link ...>
dk 24-Nov-2003 11:58
The first example on this page is also a bit verbose. Since the DomElement class inherits/extends the DomNode class, one does not, in fact, have to get another reference to the first node. The create_element method has already given you that reference. (Also, the last line passes a string to the append_child method, instead of a DomNode object) Simplified:

<?
$new_element = $dom->create_element("new_element");
$new_element->append_child($another_element);
$oldTag->append_child($new_element);
?>
Jorrit Kronjee 05-Nov-2003 07:15
The example done by Nico Almhoedi has a small error.

Since append_child only accepts DomElement (which is an object), it should've been:

$new_element = DomDocument->create_element("new_el");
$new_node = $existent_node->append_child($new_element);
Nico almhoedi at gmx dot de 04-Jan-2003 03:40
It's easier possible since DomNode->append_child($new_element) returns the new child as an object, so you can refer to it immediately.

To append a child to the node $existent_node:

$new_element = DomDocument->create_element("new_el");
$new_node = $existent_node->append_child("new_el");

see Manual DomNode->append_child()
greg@cabinetuk 13-Nov-2002 05:27
Its important to remember, when adding a created element to an existing node using append_child(), that if you want to then add another element to that node you have to go back and set up a DOMNode instance using DOMDocument_get_elements_by_tagname or similar before you can append another node onto it.

eg

<?
$new_element = $dom->create_element("new_element");
$oldTag->append_child($new_element);
//Go back and set up new element as DOMNode
$new_elementArray = $dom->get_elements_by_tagname("new_element");
$new_elementTag = $new_elementArray[0];//(if theres more than one use a for loop)

$new_elementTag->append_child("another_new_element");
?>
DomDocument::create_element_ns
DomDocument::create_entity_reference
DOM XML (PHP 4) Функции


Создает ссылку на сущность

DomDocument::create_element
DomDocument::create_processing_instruction
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::create_entity_reference

(PHP 4 >= 4.1.0)

DomDocument::create_entity_reference — Создает ссылку на сущность

Описание

domentityreference DomDocument::create_entity_reference ( string $content )

Эта функция возвращает новый экземпляр класса DomEntityReference. Содержимое для инициализации берется из переданного аргумента. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией domnode_append_child().

В случае ошибки метод вернет FALSE.

См. также domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_cdata_section(),
domdocument_create_processing_instruction(),
domdocument_create_attribute() и
domnode_insert_before().

User Contributed Notes

There are no user contributed notes for this page.
DomDocument::create_element
DomDocument::create_processing_instruction
DOM XML (PHP 4) Функции


Создает новый PI узел

DomDocument::create_entity_reference
DomDocument::create_text_node
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::create_processing_instruction

(PHP 4 >= 4.1.0)

DomDocument::create_processing_instruction — Создает новый PI узел

Описание

domprocessinginstruction DomDocument::create_processing_instruction ( string $content )

Эта функция возвращает новый экземпляр класса DomCData. Содержимое pi берется из переданного аргумента. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией domnode_append_child().

В случае ошибки метод вернет FALSE.

См. также domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_cdata_section(),
domdocument_create_attribute(),
domdocument_create_entity_reference() и
domnode_insert_before().

User Contributed Notes

fru at not dot spam dot com 03-Aug-2004 02:31
note that
string DomDocument->
   create_processing_instruction ( string contenido)
takes two arguments:
- first: the processing instruction,
- second: the arguments and values of
      the processing instruction
:::so must be:
string DomDocument->
    create_processing_instruction ( string prInst,
           string contenido)
AlanCanon 26-May-2004 02:20
There's an error in both the above examples: it's "xml-stylesheet," not "xsl-stylesheet.Corrected examples:

    $pi = $dom->create_processing_instruction
    (
      "xml-stylesheet",
      "type=\"text/xsl\" href=\"$stylesheet\""
    );
    $dom->append_child($pi);
apoco at cox dot net 01-Dec-2003 08:34
That prior user example creates an invalid processing insruction under 4.3.4.  The first parameter is the processing instruction, and the second can be used for the attributes of the PI.   Here's a code snippet I used to insert a stylesheet:

<?php

$pi = $doc->create_processing_instruction(
  "xsl-stylesheet",
  "type=\"text/xsl\" href=\"$stylesheet\"");
$doc->append_child($pi);

?>
rj.kamp at hccnet dot nl 20-Oct-2003 04:29
Please note that you have to use this function the following way to add a stylsheetr for client side processing.

$pi = $myDoc->create_processing_instruction('','xsl-stylesheet type="text/xsl" href="path_to_my_stylesheet"');

$myDoc->append_child($pi);

And note you have to add this to the document before the rootnode.
DomDocument::create_entity_reference
DomDocument::create_text_node
DOM XML (PHP 4) Функции


РЎРѕР·РґР°РµС‚ РЅРѕРІС‹Р№ С‚РµРєСЃС‚РѕРІС‹Р№ СѓР·РµР»

DomDocument::create_processing_instruction
DomDocument::doctype
DOM XML (PHP 4) Р¤СѓРЅРєС†РёРё
PHP Manual

DomDocument::create_text_node

(PHP 4 >= 4.1.0)

DomDocument::create_text_node — РЎРѕР·РґР°РµС‚ РЅРѕРІС‹Р№ С‚РµРєСЃС‚РѕРІС‹Р№ СѓР·РµР»

РћРїРёСЃР°РЅРёРµ

domtext DomDocument::create_text_node ( string $content )

РС‚Р° С„СѓРЅРєС†РёСЏ РІРѕР·РІСЂР°С‰Р°РµС‚ РЅРѕРІС‹Р№ СЌРєР·РµРјРїР»СЏСЂ РєР»Р°СЃСЃР° DomText. РЎРѕРґРµСЂР¶РёРјРѕРµ СѓР·Р»Р° Р±РµСЂРµС‚СЃСЏ РёР· РїРµСЂРµРґР°РЅРЅРѕРіРѕ Р°СЂРіСѓРјРµРЅС‚Р°. РС‚РѕС‚ СѓР·РµР» РЅРµ Р±СѓРґРµС‚ РѕС‚РѕР±СЂР°Р¶Р°С‚СЊСЃСЏ РІ РґРѕРєСѓРјРµРЅС‚Рµ РґРѕ С‚РµС… РїРѕСЂ, РїРѕРєР° РѕРЅ РЅРµ Р±СѓРґРµС‚ РІСЃС‚Р°РІР»РµРЅ, РЅР°РїСЂРёРјРµСЂ, С„СѓРЅРєС†РёРµР№ domnode_append_child().

Р’ СЃР»СѓС‡Р°Рµ РѕС€РёР±РєРё РјРµС‚РѕРґ РІРµСЂРЅРµС‚ FALSE.

РЎРј. С‚Р°РєР¶Рµ domnode_append_child(),
domdocument_create_element(),
domdocument_create_comment(),
domdocument_create_text(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference() Рё
domnode_insert_before().

User Contributed Notes

chregu at php dot net 12-Dec-2002 04:29
Or just use utf8_encode($text), at least if your input is iso-8859-1

all text methods in domxml expect utf-8 encoded strings as input.
hlubek at networkteam dot com 01-Jun-2002 09:15
Ever tried to insert special characters e.g. German д,ь,ц,Я with this function?
Or to mix normal text with entities?

In my scripts I use a function like this:

$translateSpecial = array(
"д" => "#228",
"ь" => "#252",
"ц" => "#246",
"Д" => "#196",
"Ь" => "#220",
"Ц" => "#214",
"Я" => "#223"
);

$buffer = "";
for($i = 0; $i < strlen($value); $i++)
{
  if(!$translateSpecial[$value{$i}])
    $buffer .= $value{$i};
  else
  {
    $node->append_child($xmldoc->create_text_node($buffer));
    $buffer = "";
    $node->append_child($xmldoc->
    create_entity_reference($translateSpecial[$value{$i}]));
  }
}
$node->append_child($xmldoc->create_text_node($buffer));
DomDocument::create_processing_instruction
DomDocument::doctype
DOM XML (PHP 4) Р¤СѓРЅРєС†РёРё


Возвращает тип документа

DomDocument::create_text_node
DomDocument::document_element
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::doctype

(PHP 4 >= 4.1.0)

DomDocument::doctype — Возвращает тип документа

Описание

domdocumenttype DomDocument::doctype ( void )

Эта функция возвращает объект класса DomDocumentType. В версиях PHP до 4.3 это был класс Dtd, однако в стандарте DOM такой класс не описан.

См. также методы класса DomDocumentType.

User Contributed Notes

There are no user contributed notes for this page.
DomDocument::create_text_node
DomDocument::document_element
DOM XML (PHP 4) Функции


Возвращает узел корневого элемента

DomDocument::doctype
DomDocument::dump_file
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::document_element

(PHP 4 >= 4.1.0)

DomDocument::document_element — Возвращает узел корневого элемента

Описание

domelement DomDocument::document_element ( void )

Эта функция возвращает узел корневого элемента документа.

Следующий пример возвращает только элемент с именем CHAPTER и выводит его. Другой узел -- комментарий -- не возвращается.

Пример #1 Извлечение корневого элемента

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Ошибка при разборе документа\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

Результат выполнения данного примера:

domelement Object
(
    [type] => 1
    [tagname] => chapter
    [0] => 6
    [1] => 137960648
)

User Contributed Notes

jaworskidaniel no at spam gmail dot com 14-Jul-2008 05:19
in php5

            $root = $dom->documentElement;
            $tag = $root->tagName;
misterffoeg at hotmail dot com 11-Dec-2007 03:03
The last note is incorrect. The class he is referring to is DOMDocument, not DomDocument. This page is for the PHP 4 extension. Doing "new DomDocument" would be a fatal error in PHP 5 unless you hacked the old extension into it which would be a very useless move.
rianfowler no at spam gmail dot com 01-Apr-2007 05:51
The domelement returned by this will function as a domnode object for things like ->append_child.

$nodeChild = myxmldoc->create_element('child');
$nodeRoot = $this->myxmldoc->document_element();
$nodeRoot->append_child($nodeChild);
filipp at mac dot com 30-Dec-2006 02:29
as of PHP 5 (tested with 5.1.4), remember to use documentElement instead. As in:
$dom = new DomDocument ();
$dom -> load ('file.xml');
$newEl = $dom -> createElement ('newEl');
$dom -> documentElement -> appendChild ($newEl);
DomDocument::doctype
DomDocument::dump_file
DOM XML (PHP 4) Функции


Сохраняет XML дерево в файл

DomDocument::document_element
DomDocument::dump_mem
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::dump_file

(PHP 4 >= 4.1.0)

DomDocument::dump_file — Сохраняет XML дерево в файл

Описание

string DomDocument::dump_file ( string $filename [, bool $compressionmode [, bool $format ]] )

Создает XML документ из dom представления. Эту функцию обычно вызывают после построения нового dom документа, как это показано ниже. Аргумент format указывает на то, требуется ли аккуратно форматировать вывод функции или нет. Первый аргумент отвечает за имя создаваемого файла, а второй указывает, требуется ли сжатие вывода или нет.

Пример #1 Создание простого HTML заголовка

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

См. также domdocument_dump_mem() и domdocument_html_dump_mem().

User Contributed Notes

wkshi 22-Jun-2007 08:39
<?php
header('Content-Type: text/xml');

$doc = domxml_new_doc("1.0");
$root = $doc->add_root("html");

$head = $root->new_child("head", "");
$head->new_child("title", "phpdom test");

echo $doc->dump_mem();
$doc->dump_file("phpdom.xml", false, true);
?>

Also, It works
Nushto 02-Aug-2006 08:06
The string you pass as a filename should be an absolute path.

For Example:

$doc->dump_file(realpath("test.xml"),false,true);
winghonghibernates at hotmail dot com 14-May-2003 06:37
Sometimes it maybe strange in the structure of the XML document when using false, true as the two boolean parameters. Using false, false can solve the problem.
tommy 20-Jul-2002 02:06
the return value contains the number of bytes, wich are written by this command
DomDocument::document_element
DomDocument::dump_mem
DOM XML (PHP 4) Функции


Представляет XML дерево в виде строки

DomDocument::dump_file
DomDocument::get_element_by_id
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::dump_mem

(PHP 4 >= 4.1.0)

DomDocument::dump_mem — Представляет XML дерево в виде строки

Описание

string DomDocument::dump_mem ([ bool $format [, string $encoding ]] )

Создает XML документ из dom представления. Эту функцию обычно вызывают после построения нового dom документа, как это показано ниже. Аргумент format указывает на то, требуется ли аккуратно форматировать вывод функции или нет.

Пример #1 Создание простого HTML заголовка

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

Замечание:

Первый аргумент был добавлен в PHP 4.3.0.

См. также domdocument_dump_file() и domdocument_html_dump_mem().

User Contributed Notes

jonathan at fluent dot ltd dot uk 30-Nov-2003 04:11
It seems that if you use $xslt->dump_mem(TRUE) IE: breaks and formats all the HTML Badly. Perhaps its a problem with CR's...
ross at dev-null dot accretivetg dot com 26-Sep-2003 10:11
Given the missing description of the encoding parameter, I had hoped it would automatically encode the document if I set the encoding type; this is not the case.

At least in PHP v4.3.3, it seems that setting the encoding type does NOTHING other than set the name displayed in the string:

<?xml version="1.0" encoding="UTF-8"?>

Thus if you want your values to be encoded, you need to manually encode them when you create your DOM object.  E.g. assume you have a simple setup like this:

<?php

  $text = '�Spanish exclamation!' ;

  $xml = domxml_new_doc( '1.0' );
  $node = $xml->create_element( 'example' );
  $cdata = $xml->create_cdata_section( $text );
  $node->append_child( $cdata );
  $xml->append_child( $node );

  echo $xml->dump_mem( true, 'UTF-8' ) ;

  ?>

This will output the following:

<?xml version="1.0" encoding="UTF-8"?>
<example>
<![CDATA[�Spanish exclamation!]]>
</example>

However, that is not what was intended, as the exclamation is not UTF-8-encoded.  To make $text be encoded correctly, you have to explicitly do so, as in:

<?php

  $cdata = $xml->create_cdata_section( utf8_encode( $text ) );

  ?>

This results in the output being correctly UTF-8-encoded, as follows:

<![CDATA[¡Spanish exclamation!]]>

Apparently MSIE's MSXML2.DOMDocument ActiveX control requires UTF-8 encoding for special characters, and it will invalidate the entire document if those chars are not appropriately encoded, so beware.
amaslov at pegasus dot rutgers dot edu 23-Oct-2002 02:29
<pre>
for xml file that goes like this:
<item>
<name>foo</name>
<desc>bar</desc>
</item>

Format ID's influence output in this manner:
case 0 :{
<item><name>foo</name><desc>bar</desc></item>
}
case 1 :{
<item>
    <name>foo</name>
    <desc>bar</desc>
</item>
}
case 2:{
<item>
    <name>
foo
    </name>
    <desc>
bar
    </desc>
</item>

If you use PHP SAX(Expat) XML engine, you should always stick to format "0". It reads any empty spaces as XML data.
</pre>
bruno dot rodrigues at litux dot org 15-Aug-2002 02:32
string dump_mem(int format, string encoding);

format=0,1 = <tag>text</tag>
format=2 =
<tag>
  text
</tag>

encoding set's the encoding attribute in line
<?xml version="1.0" encoding="iso-8859-1"?>
DomDocument::dump_file
DomDocument::get_element_by_id
DOM XML (PHP 4) Функции


Ищет элемент с заданным id

DomDocument::dump_mem
DomDocument::get_elements_by_tagname
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::get_element_by_id

(PHP 4 >= 4.1.0)

DomDocument::get_element_by_id — Ищет элемент с заданным id

Описание

domelement DomDocument::get_element_by_id ( string $id )

Эта функция аналогична domdocument_get_elements_by_tagname(), но ищет элемент по заданному id. В соответствии со стандартом DOM это требует наличия DTD, где определено, какой из атрибутов ключевой, не смотря на то, что текущая реализация просто задает адрес для поиска "//*[@ID = '%s']". Это не соответствует стандарту, который предписывает возвращать null, если нельзя определить, какой атрибут ключевой. Такое поведение функции надо бы исправить, поэтому не стоит на него полагаться.

См. также domdocument_get_elements_by_tagname()

User Contributed Notes

etienne dot anken at eivd dot ch 03-Dec-2002 07:51
This class is useful for people who haven't the latest release of PHP and would like to search an element with a known ID through a collection of nodes.

Example to use it :

$domDoc = xmldoc("<root><entity id='e1'></entity><entity id='e2'><titi id='e5'></titi></entity></root>");

$root = $domDoc->root();
$children = $root->child_nodes();

$researchObject = new searchElementById("e5", $children);
$resultElement = $researchObject->beginSearching();

The source of the class :

class searchElementById {

  //Class which can find and return an XML node with a specified ID
  var $numberElements=0;
  var $numberAttributes=0;
  var $idToFind;
  var $tabElements;

  //Initialization function which accept 2 parameters :
  //$paramIdToFind : value of the ID to find
  //$paramTabElements : array of nodes which contains the element to find
  function searchElementById($paramIdToFind, $paramTabElements) {
    //Initialization of class variables
    $this->idToFind = $paramIdToFind;
    $this->tabElements = $paramTabElements;
  }

  //Function starting the research
  function beginSearching() {
    //Search and return the element found
    return $this->searchID($this->tabElements);
  }

  //Recursive function searching the desired node
  function searchID($tabElements) {

    //Variable of the number of elements
    $i = 0;
    //Variable of the number of attributes
    $j = 0;

    //Number of nodes in the elements' array
    $nbreNoeuds = count($tabElements);

    //Loop on all elements
    for ($i=0;$i<$nbreNoeuds;$i++) {

      //Incrementation of the class variable couting the total number of elements
      $this->compteurElements++;

      //Extraction of the attributes of the current element
      $tabAttributs = $tabElements[$i]->attributes();
      //Number of attributes in the current element
      $nbreAttributs = count($tabAttributs);
      //Loop on all attributes
      for ($j=0;$j<$nbreAttributs;$j++) {

        //Incrementation of the class variable couting the total number of attributes
        $this->numberAttributes++;

        //Test if the current attribute is the attribute to find
        if ($tabAttributs[$j]->value==$this->idToFind) {
          //If yes, return the current element
          return $tabElements[$i];
        }

      }

      //Search children nodes of the current element
      $children = $tabElements[$i]->child_nodes();
      if (!is_bool($children)) {
        //If the current element has children, call recursively this function
        $result = $this->searchID($children);
        //If the result is not boolean, return the array
        if (!is_bool($result)) {
          return $result;
        }
      }
    }

    return false;

  }

}
DomDocument::dump_mem
DomDocument::get_elements_by_tagname
DOM XML (PHP 4) Функции


Возвращает массив узлов с заданным тэгом в документе или пустой массив, если таких элементов не найдено

DomDocument::get_element_by_id
DomDocument::html_dump_mem
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::get_elements_by_tagname

(PHP 4 >= 4.1.0)

DomDocument::get_elements_by_tagname — Возвращает массив узлов с заданным тэгом в документе или пустой массив, если таких элементов не найдено

Описание

array DomDocument::get_elements_by_tagname ( string $name )

См. также domdocument_add_root()

User Contributed Notes

jon at hiveminds dot net 05-Dec-2003 05:49
Warning to win32 users: It appears that use of the wildcard argument to this function (e.g.

<?php
  $alltags = $domdoc->get_elements_by_tagname("*");
?>

) to return a collection of all DomElements in a document, which worked in php4.3.0-4.3.3, is broken in php4.3.4 for Windows. Upgrading broke numerous scripts depending on this behaviour, which returned to normal as soon as I rolled back to 4.3.3-win32.

I had intended to offer a workaround using child_nodes(), but found problems with this also. Therefore my suggested workarounds are either (a) don't upgrade to 4.3.4 if you're running this extension on Windows and are depending on the wildcard behaviour or (b) rewrite your code so as to use actual tagnames

The wildcard usage is per the W3C DOM spec, so hopefully this will be fixed and available again in 4.3.5.
Salman 01-Oct-2003 04:23
Yes it does return an object; the object is of type DomElement. Hopefully this code will help:

$element = new DomElement();

if(!$dom = domxml_open_file($xml_file)) {
   die("Error opening xml file");
}

$tables = $dom->get_elements_by_tagname("table");
foreach($tables as $table) {
    $element = $table;
    echo "Attribute name: ", $element->get_attribute("name");
}

- Salman
http://wwww.setcomputing.com/
blah at pasher dot org 16-Jan-2003 11:56
Correction to my last note: DomElement (and DomDocument) have their own get_elements_by_tagname() method. It does not get it from DomNode.
blah at pasher dot org 16-Jan-2003 11:44
To clarify some confusion:

This function returns an integer-indexed array of DomElement objects. The DomElement class extends the DomNode class, so all DomNode methods are available to this new object. Additional notes can be found under the "DomElement->get_elements_by_tagname" manual section. DomElement uses the DomNode method (unless DomElement overrides this method, but I don't think that occurs).

Also note, if there are no nodes matching your criteria, it returns an empty array, not false.
KingGeoffrey at yahoo dot com 24-Aug-2002 03:21
The return looks like an integer indexed array of objects when i try it.

Versions
 php:4.2.1 domxml:2.4.9

Code fragment:
    $nodes = $doc->get_elements_by_tagname("user");
    reset($nodes);
    while (list($key, $value) = each($nodes)) {
        echo "$key = " . $value->get_attribute('username') . "<br />\n";

    }

Output fragment:
0 = a
1 = b
2 = c
scouture at courtweb dot com 15-Jul-2002 03:33
Seems that this function return an object instead of an array. I've tried this :

if(!$dom = domxml_open_file("g://program files/apache group/apache/htdocs/intranetcw/data/config_one.xml"))
{
  echo "Error while parsing the document\n";
  exit;
}

//array DomDocument->get_elements_by_tagname ( string name)

$array_element = $dom->get_elements_by_tagname("IP_ORACLE_CONFIG");
if ($array_element)
{
    echo count($array_element)." array count<br>";
    for ($i=0;$i<count($array_element);$i++)
    {
        echo $array_element[$i]." array content<br>";
    }
}
else
{
    echo "you get nothing";
}

and the result was :

1 array count
Object array content

Styve
DomDocument::get_element_by_id
DomDocument::html_dump_mem
DOM XML (PHP 4) Функции


Преобразует дерево XML в HTML строку

DomDocument::get_elements_by_tagname
DomDocument::xinclude
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::html_dump_mem

(PHP 4 >= 4.1.0)

DomDocument::html_dump_mem — Преобразует дерево XML в HTML строку

Описание

string DomDocument::html_dump_mem ( void )

Создает HTML документ из dom представления. Эту функцию обычно вызывают после построения нового dom документа, как в примере ниже.

Пример #1 Создание простого HTML заголовка

<?php

// Создает документ
$doc = domxml_new_doc("1.0");

$root = $doc->create_element("html");
$root = $doc->append_child($root);

$head = $doc->create_element("head");
$head = $root->append_child($head);

$title = $doc->create_element("title");
$title = $head->append_child($title);

$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);

echo $doc->html_dump_mem();
?>

Результат выполнения данного примера:

<html><head><title>This is the title</title></head></html>

См. также domdocument_dump_file() и domdocument_html_dump_mem().

User Contributed Notes

Sudrien 14-Nov-2005 09:17
Clarification: DomDocument->dump_mem adds the  <?xml version="1.0"?> header, with some additional options.

header("Content-Type: application/xhtml+xml");
 forces xml processing (this can also be a server setting). Idealy, both should be used for serving xhtml, though the <?xml version="1.0"?> may be dropped - on its own, it does not XML processing.
drew dot northup at maine dot edu 16-Aug-2005 05:34
Note that DomDocument->html_dump_mem does not allow you to output valid XHTML, as you need to have valid xml tags for it.  Use DomDocument->dump_mem to output valid XHTML instead.
DomDocument::get_elements_by_tagname
DomDocument::xinclude
DOM XML (PHP 4) Функции


Подстановка XIncludes в объекте DomDocument

DomDocument::html_dump_mem
DomDocumentType::entities
DOM XML (PHP 4) Функции
PHP Manual

DomDocument::xinclude

(PHP 5)

DomDocument::xinclude — Подстановка XIncludes в объекте DomDocument

Описание

int DomDocument::xinclude ( void )

Эта функция замещает » XIncludes в объекте DomDocument.

Пример #1 Подстановка Xincludes

<?php

// include.xml содержит:
// <child>test</child>

$xml = '<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="include.xml">
    <xi:fallback>
      <error>xinclude: include.xml не найден</error>
    </xi:fallback>
  </xi:include>
</root>';

$domxml = domxml_open_mem($xml);
$domxml->xinclude();

echo $domxml->dump_mem();

?>

Результат выполнения данного примера:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <child>test</child>
</root>

Если include.xml не существует, вы увидите:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <error>xinclude:dom.xml not found</error>
</root>

User Contributed Notes

peter at softcoded dot com 04-Jun-2011 10:11
The xinclude method is defined as: int DomDocument->xinclude ( void ). However you can pass options to this method. If your xincluded file contains entities, these entities will not be resolved simply by setting the substituteEntities property of the DomDocument to "true". You must pass in options to the xinclude function. For example:

<?php
$doc = new DOMDocument();
//doc has entities, substitute them
$doc->substituteEntities = true;
$source = "/path/to/file.xml";
$doc->load($source);
//do this to resolve entities in an xincluded file
$options = LIBXML_NOENT;
$doc->xinclude($options);
...
?>
collin at paperclipped dot com 19-Feb-2010 10:03
I had to do things a bit differently to use xincludes (also following the example above only included a part of the XML):

<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>
<site xmlns:xi="http://www.w3.org/2001/XInclude">
    <xi:include href="home.xml#xpointer(/site/*)">
        <xi:fallback>
            <error>Error: home.xml not found or invalid!</error>
        </xi:fallback>
    </xi:include>
    <xi:include href="services.xml#xpointer(/site/*)">
        <xi:fallback>
            <error>Error: services.xml not found or invalid!</error>
        </xi:fallback>
    </xi:include>
    <xi:include href="about.xml#xpointer(/site/*)">
        <xi:fallback>
            <error>Error: about.xml not found or invalid!</error>
        </xi:fallback>
    </xi:include>
    <xi:include href="contact.xml#xpointer(/site/*)">
        <xi:fallback>
            <error>Error: contact.xml not found or invalid!</error>
        </xi:fallback>
    </xi:include>
</site>';

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml);
$xmlDoc->xinclude();

echo $xmlDoc->saveXML();
?>
www dot spam at whoah dot net 20-Aug-2004 06:29
Tips for anyone trying to use nested <xi:include /> blocks:

- Multiple calls to DOMDocument::xinclude() are required to parse each level of include blocks, you can either call xinclude() a fixed amount of times (enough to cover your needs), or you can check for leftover <xi:include /> blocks after each call to DOMDocument::xinclude() to see if you need to call it again.

- If you are going to use an <xi:include /> block in an included file, you must define the "xi" namespace in the included file where another include block exists, the namespace definition will not carry through from the first xml file

eg.

==========
a.xml (xi definition needed)
----------
<?xml version="1.0"?>
<a xmlns:xi="http://www.w3.org/2001/XInclude">
    <xi:include href="includes/b.xml" />
</a>
==========

==========
b.xml (xi definition needed)
----------
<?xml version="1.0"?>
<b xmlns:xi="http://www.w3.org/2001/XInclude">
    <xi:include href="c.xml" />
</b>
==========

==========
c.xml (xi definition not needed)
----------
<?xml version="1.0"?>
<c>whatever</c>
==========

- Futher to my example above, if you are including an xml file that has another include inside it, the href "base" url will be taken from the 2nd file. In the above example, "c.xml" is actually in the same directory as "b.xml", whereas "a.xml" is in the directory above, but because b is calling c, the "base" directory is seen as "includes/"

Another tip not related to nested xincludes, but simply xinclude stuff in general:

I wanted to turn this...
<a>
    <b />
    <c />
    <d />
    <e />
</a>

...into this...
<a>
    <xi:include file="bcde.xml" />
</a>

...but then bcde.xml would have looked like this...
<b />
<c />
<d />
<e />

...which is not valid xml and was causing an error. So just remember that included files need to be valid and may still only have one root element.

These are from my experiences with PHP5.0.1, I'm not a DOMXML expert at all. Enjoy!
amm at remasys dot com 01-Jul-2004 09:14
xml Include using xpointer to include specific part of another xml doc

Main xml file (or string):
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
   <optional>
      <xi:include href="include.xml#xpointer(/parts/*)" parse="xml">
         <xi:fallback>
            <error>Error.</error>
         </xi:fallback>
      </xi:include>
   </optional>
   <blah>blah</blah>
   <blah>blah</blah>
</root>

Include.xml file (or string:
<?xml version="1.0" encoding="utf-8"?>
<parts>
   <part>part one</part>
   <part>part two</part>
   <part>part three</part>
</parts>

href="include.xml#xpointer(/parts/*)"
will include all <part> tags but NOT <parts>

href="include.xml#xpointer(/parts/part[1])"
will include <part>part one</part>

simple but very usefull.
DomDocument::html_dump_mem
DomDocumentType::entities
DOM XML (PHP 4) Функции


Возвращает список сущностей

DomDocument::xinclude
DomDocumentType::internal_subset
DOM XML (PHP 4) Функции
PHP Manual

DomDocumentType::entities

(PHP 4 >= 4.1.0)

DomDocumentType::entities — Возвращает список сущностей

Описание

array DomDocumentType::entities ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Миграция на PHP 5

Используйте свойство entities объекта DOMDocumentType.

User Contributed Notes

There are no user contributed notes for this page.
DomDocument::xinclude
DomDocumentType::internal_subset
DOM XML (PHP 4) Функции


Возвращает подмножество внутренней структуры dom документа

DomDocumentType::entities
DomDocumentType::name
DOM XML (PHP 4) Функции
PHP Manual

DomDocumentType::internal_subset

(PHP 4 >= 4.1.0)

DomDocumentType::internal_subset — Возвращает подмножество внутренней структуры dom документа

Описание

bool DomDocumentType::internal_subset ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Миграция на PHP 5

Используйте свойство internalSubset объекта DOMDocumentType.

User Contributed Notes

There are no user contributed notes for this page.
DomDocumentType::entities
DomDocumentType::name
DOM XML (PHP 4) Функции


Возвращает имя типа документа

DomDocumentType::internal_subset
DomDocumentType::notations
DOM XML (PHP 4) Функции
PHP Manual

DomDocumentType::name

(PHP 4 >= 4.1.0)

DomDocumentType::name — Возвращает имя типа документа

Описание

string DomDocumentType::name ( void )

Эта функция возвращает имя типа документа.

Возвращаемые значения

Возвращает имя объекта DomDocumentType в виде строки.

Примеры

Пример #1 Получение имени типа документа

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Ошибка при разборе файла\n";
    exit;
}

$doctype = $dom->doctype();
echo $doctype->name(); // chapter

?>

Переход на PHP 5

Используйте свойство name объекта DOMDocumentType.

User Contributed Notes

There are no user contributed notes for this page.
DomDocumentType::internal_subset
DomDocumentType::notations
DOM XML (PHP 4) Функции


Возвращает список обозначений

DomDocumentType::name
DomDocumentType::public_id
DOM XML (PHP 4) Функции
PHP Manual

DomDocumentType::notations

(PHP 4 >= 4.1.0)

DomDocumentType::notations — Возвращает список обозначений

Описание

array DomDocumentType::notations ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Переход на PHP 5

Используйте свойство notations объекта DOMDocumentType.

User Contributed Notes

There are no user contributed notes for this page.
DomDocumentType::name
DomDocumentType::public_id
DOM XML (PHP 4) Функции


Возвращает общедоступный (public) идентификатор типа документа

DomDocumentType::notations
DomDocumentType::system_id
DOM XML (PHP 4) Функции
PHP Manual

DomDocumentType::public_id

(PHP 4 >= 4.1.0)

DomDocumentType::public_id — Возвращает общедоступный (public) идентификатор типа документа

Описание

string DomDocumentType::public_id ( void )

Эта функция возвращает public-идентификатор типа документа.

Возвращаемые значения

Возвращает общедоступный идентификатор объекта класса DomDocumentType в виде строки.

Примеры

Следующий пример не выведет ничего.

Пример #1 Извлечение public id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Ошибка при разборе документа\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

Переход на PHP 5

Используйте свойство publicId объекта DOMDocumentType.

User Contributed Notes

There are no user contributed notes for this page.
DomDocumentType::notations
DomDocumentType::system_id
DOM XML (PHP 4) Функции


Возвращает системный идентификатор типа документа

DomDocumentType::public_id
DomElement::get_attribute_node
DOM XML (PHP 4) Функции
PHP Manual

DomDocumentType::system_id

(PHP 4 >= 4.1.0)

DomDocumentType::system_id — Возвращает системный идентификатор типа документа

Описание

string DomDocumentType::system_id ( void )

Возвращает системный идентификатор типа документа.

Возвращаемые значения

Возвращает системный идентификатор объекта DomDocumentType в виде строки.

Примеры

Пример #1 Извлечение системного идентификатора

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Ошибка при разборе документа\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

Результат выполнения данного примера:

/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd

Переход на PHP 5

Используйте свойство systemId объекта класса DOMDocumentType.

User Contributed Notes

There are no user contributed notes for this page.
DomDocumentType::public_id
DomElement::get_attribute_node
DOM XML (PHP 4) Функции


Возвращает узел заданного атрибута

DomDocumentType::system_id
DomElement::get_attribute
DOM XML (PHP 4) Функции
PHP Manual

DomElement::get_attribute_node

(PHP 4 >= 4.1.0)

DomElement::get_attribute_node — Возвращает узел заданного атрибута

Описание

DomAttribute DomElement::get_attribute_node ( string $name )

Возвращает узел заданного атрибута текущего элемента.

Список параметров

name

Имя искомого атрибута. Этот аргумент чувствителен к регистру.

Возвращаемые значения

Возвращает узел атрибута в виде объекта класса DomAttribute, либо FALSE, если атрибутов с именем name не найдено.

Примеры

Пример #1 Получение имени атрибута

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Ошибка при разборе документа\n";
    exit;
}

$root = $dom->document_element();
if ($attribute = $root->get_attribute_node('language')) {
    echo 'Язык: ' . $attribute->value() . "\n";
}

?>

Переход на PHP 5

Используйте DOMElement::getAttributeNode.

Смотрите также

  • DomElement::get_attribute
  • DomElement::set_attribute

User Contributed Notes

There are no user contributed notes for this page.
DomDocumentType::system_id
DomElement::get_attribute
DOM XML (PHP 4) Функции


Возвращает значение заданного атрибута

DomElement::get_attribute_node
DomElement::get_elements_by_tagname
DOM XML (PHP 4) Функции
PHP Manual

DomElement::get_attribute

(PHP 4 >= 4.1.0)

DomElement::get_attribute — Возвращает значение заданного атрибута

Описание

string DomElement::get_attribute ( string $name )

Возвращает значение заданного атрибута в текущем элементе.

Начиная с PHP 4.3, если атрибутов с именем name не найдено, будет возвращена пустая строка.

Список параметров

name

Имя искомого атрибута. Этот аргумент чувствителен к регистру.

Возвращаемые значения

Возвращает значение атрибута в виде строки или пустую строку, если атрибутов с именем name не найдено.

Примеры

Пример #1 Получение значения атрибута

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Ошибка при разборе документа\n";
    exit;
}

// get chapter
$root = $dom->document_element();
echo $root->get_attribute('language'); // en

?>

Переход на PHP 5

Используйте DOMElement::getAttribute.

Смотрите также

  • DomElement::get_attribute_node
  • DomElement::set_attribute

User Contributed Notes

There are no user contributed notes for this page.
DomElement::get_attribute_node
DomElement::get_elements_by_tagname
DOM XML (PHP 4) Функции


Получает элементы по имени

DomElement::get_attribute
DomElement::has_attribute
DOM XML (PHP 4) Функции
PHP Manual

DomElement::get_elements_by_tagname

(PHP 4 >= 4.1.0)

DomElement::get_elements_by_tagname — Получает элементы по имени

Описание

array DomElement::get_elements_by_tagname ( string $name )

Получает все элементы с именем name, входящие в состав текущего элемента.

Список параметров

name

Имя искомых элементов.

Возвращаемые значения

Возвращает массив объектов класса DomElement.

Примеры

Пример #1 Получение содержимого

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Ошибка при разборе документа\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname('element');

foreach ($node_array as $node) {
    echo ' - ' . $node->get_content() . "\n";
}

?>

Переход на PHP 5

Используйте DOMElement::getElementsByTagName.

User Contributed Notes

mikhail dot nemtsev at gmail dot com 23-Aug-2008 08:21
This example uses get_elements_by_tagname() and child_nodes() to output the contents of the xml file. The sample xml file and php code are below.

<?xml version="1.0" encoding="iso-8859-1"?>
<dictionary>
 <entry>
    <word>Hello</word>
    <meaning>used to express a greeting</meaning>
    <example>Hello World!</example>
 </entry>
</dictionary>

<?php
$xml_path = "/some/dir/dictionary.xml";
    if (!$dom = domxml_open_file($xml_path)) {
        //the above requires absolube path
        exit("Could not access the XML source.");
    }
    $root = $dom->document_element(); //obtain the root
    $array_entry = $root->get_elements_by_tagname("entry"); //gets all <entry> DomElems
    foreach ($array_entry as $entry_dom_elem) {
        $childnodes = $entry_dom_elem->child_nodes();
        foreach ($childnodes as $child) { //cycle thru <word>, <meaning>, <example>
            echo "node name: ".$child->tagname() . "; contains: " . $child->get_content()."<br>";

        }
    }
?>
The above code outputs:
node name: word; contains: Hello
node name: meaning; contains: used to express a greeting
node name: example; contains: Hello World!
php dot net dot 3 dot jdoe at spamgourmet dot com 30-Mar-2004 10:55
Function get_elements_by_tagname() is only defined for the DocumentRoot-Element rather than for any DocumentElement.
chregu at php dot net 30-Oct-2002 07:02
if you want to search for tagnames with namespaces, do it the following way:
(it's a work around, not a really proper solution..)

$dom = domxml_open_mem($xmlval);
$ctx=xpath_new_context($dom);
$ctx->xpath_register_ns("yns","http://your.name.space/uri");
$nodes = $dom->get_elements_by_tagname("yns:tagname",$ctx);
DomElement::get_attribute
DomElement::has_attribute
DOM XML (PHP 4) Функции


Проверяет, есть ли атрибут в текущем узле

DomElement::get_elements_by_tagname
DomElement::remove_attribute
DOM XML (PHP 4) Функции
PHP Manual

DomElement::has_attribute

(PHP 4 >= 4.1.0)

DomElement::has_attribute — Проверяет, есть ли атрибут в текущем узле

Описание

bool DomElement::has_attribute ( string $name )

Эта функция проверяет, существует ли атрибут с именем name в текущем узле.

Список параметров

name

Имя проверяемого атрибута.

Возвращаемые значения

Возвращает TRUE, если атрибут существует, FALSE в противном случае.

Примеры

Пример #1 Проверка существования атрибута

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Ошибка при разборе документа\n";
    exit;
}

$root = $dom->document_element();

$buffer = '<html';
if ($root->has_attribute('language')) {
    $buffer .= 'lang="' . $root->get_attribute('language') . '"';
}
$buffer .= '>';

?>

Переход на PHP 5

Используйте DOMElement::hasAttribute.

User Contributed Notes

There are no user contributed notes for this page.
DomElement::get_elements_by_tagname
DomElement::remove_attribute
DOM XML (PHP 4) Функции


Удаляет атрибут

DomElement::has_attribute
DomElement::set_attribute_node
DOM XML (PHP 4) Функции
PHP Manual

DomElement::remove_attribute

(PHP 4 >= 4.1.0)

DomElement::remove_attribute — Удаляет атрибут

Описание

bool DomElement::remove_attribute ( string $name )

Удаляет атрибут из текущего узла DomElement.

Список параметров

name

Имя удаляемого атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Переход на PHP 5

Используйте DOMElement::removeAttribute.

User Contributed Notes

fpiat / bigfoot com 18-Apr-2006 02:38
<?php
/* Remove all attribute from a node */
foreach ($node->attributes() as $attr)
        $node->remove_attribute($attr);
/* Then rename that tag */
$node->set_name('div');
/* And set appropriate "class" attribute */
$node->set_attribute('class','paragraphBox');
?>
DomElement::has_attribute
DomElement::set_attribute_node
DOM XML (PHP 4) Функции


Добавляет новый атрибут

DomElement::remove_attribute
DomElement::set_attribute
DOM XML (PHP 4) Функции
PHP Manual

DomElement::set_attribute_node

(PHP 4 >= 4.1.0)

DomElement::set_attribute_node — Добавляет новый атрибут

Описание

DomNode DomElement::set_attribute_node ( DomNode $attr )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
DomElement::remove_attribute
DomElement::set_attribute
DOM XML (PHP 4) Функции


Устанавливает значение атрибута

DomElement::set_attribute_node
DomElement::tagname
DOM XML (PHP 4) Функции
PHP Manual

DomElement::set_attribute

(PHP 4 >= 4.1.0)

DomElement::set_attribute — Устанавливает значение атрибута

Описание

DomAttribute DomElement::set_attribute ( string $name , string $value )

Устанавливает значение атрибута name равным value.

Список параметров

name

Имя атрибута. Если атрибута с этим именем нет, он будет создан.

value

Устанавливаемое значение атрибута.

Возвращаемые значения

Возвращает старый узел DomAttribute, либо новый, если атрибут создается впервые.

Примеры

Пример #1 Установка значения атрибута

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

Переход на PHP 5

Используйте DOMElement::setAttribute.

Смотрите также

  • DomElement::get_attribute_node
  • DomElement::get_attribute

User Contributed Notes

There are no user contributed notes for this page.
DomElement::set_attribute_node
DomElement::tagname
DOM XML (PHP 4) Функции


Возвращает имя текущего элемента

DomElement::set_attribute
DomNode::add_namespace
DOM XML (PHP 4) Функции
PHP Manual

DomElement::tagname

(PHP 4 >= 4.1.0)

DomElement::tagname — Возвращает имя текущего элемента

Описание

string DomElement::tagname ( void )

Возвращает имя текущего узла. Вызов этой функции дает тот же результат, что и доступ к свойству tagname или вызов функции DomNode::node_name для текущего узла.

Возвращаемые значения

Возвращает имя текущего узла DomElement.

Примеры

Пример #1 Получение имени узла

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {

    echo "Ошибка при разборе документа\n";
    exit;
}

$root = $dom->document_element();
echo $root->tagname();   // chapter
echo $root->tagname;     // chapter
echo $root->node_name(); // chapter

?>

Переход на PHP 5

Используйте свойство tagName объекта класса DOMElement.

User Contributed Notes

There are no user contributed notes for this page.
DomElement::set_attribute
DomNode::add_namespace
DOM XML (PHP 4) Функции


Добавляет узлу объявление пространства имен

DomElement::tagname
DomNode::append_child
DOM XML (PHP 4) Функции
PHP Manual

DomNode::add_namespace

(PHP 4 >= 4.3.0)

DomNode::add_namespace — Добавляет узлу объявление пространства имен

Описание

bool DOMNode::add_namespace ( string $uri , string $prefix )

Этот метод добавляет узлу объявление пространства имен.

Замечание:

Этот метод не входит в спецификацию DOM.

Список параметров

uri

URI пространства имен узла.

prefix

Префикс пространства имен узла.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Переход на PHP 5

Вы можете задать UTI и префикс пространства имен объектов DOMElement и DOMAttr во время их создания, используя DOMDocument::createElementNS или DOMDocument::createAttributeNS.

Замечание:

Помните, что атрибут не наследует пространство имен от элемента, к которому он относится.

Смотрите также

  • DomDocument::create_element_ns
  • DomNode::set_namespace

User Contributed Notes

vivekanandan8 at yahoo dot com 18-Mar-2009 10:01
Integer overflow for 64 bit platform

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float.
This above general rule differs depending on whether a 32 bit or 64 bit platform is used, which is described as follows.

Platform:32 bit,Range: -2^31-1 to 2^31-1,Numbers:-2147483647 to 2147483647
Platform:64 bit,Range: -2^63-1 and 2^63 -1,Numbers:-9223372036854775807 to 9223372036854775807

<?php
$large_number=9223372036854775807;
var_dump($large_number);
// output: int(9223372036854775807)
$large_number = 9223372036854775808;
var_dump($large_number);
// output: float(9.2233720368548E+18) as 9223372036854775808

//2^64-1 is 18446744073709551615
var_dump(0xffffffffffffffff);
// output: float(1.844674407371E+19) as 18446744073709551615
?>
tkearns at fastmail dot fm 17-Sep-2003 02:02
<?php
// EXAMPLE USING PHP 4.3.3
$objDoc = domxml_new_doc("1.0");
$ndRoot = $objDoc->create_element("root");
$ndRoot = $objDoc->append_child($ndRoot);

$ndRoot->set_namespace("foo/the/bar");
// using ramdom prefix, produces something like
// <a3767:root xmlns:a3767="foo/the/bar"/>

$ndRoot->set_namespace("yet/another/namespace","yan");
// modifies the existing prefix (again) produces something like
// <yan:root xmlns:a3767="foo/the/bar" xmlns:yan="yet/another/namespace"/>

$ndRoot->set_namespace("yet/another/namespace","foo");
// attempt to use the same ns id has again no effect. element is un-touched
// <yan:root xmlns:a3767="foo/the/bar" xmlns:yan="yet/another/namespace"/>

$ndRoot->set_namespace("new/ns/no/prefix");
// munges the existing element prefix again as well as adding declaration
// <a1757:root
//     xmlns:a3767="foo/the/bar"
//     xmlns:yan="yet/another/namespace"
//     xmlns:a1757="new/ns/no/prefix"
// />

/*
It seems that the only way to add a DEFAULT namespace to a node (without
affecting the current prefix), is to use set_attribute("xmlns",$ndId).
*/

$ndRoot->set_attribute("xmlns","default/ns/no/prefix");
// now we have
// <a1757:root
//     xmlns:a3767="foo/the/bar"
//     xmlns:yan="yet/another/namespace"
//     xmlns:a1757="new/ns/no/prefix"
//     xmlns="default/ns/no/prefix"
// />

/*
Note that namespace declarations inserted using set_namespace are not classed as
attributes, so they do not show up in an attribute list. Since we set our
default namespace using the set_attribute() method, it is the only one that will
show up.
*/
var_dump($ndRoot->attributes());
// see that only the defaul namespace is returned because it is of type
// "domattribute" because we set it with an attribute method.

$ndRoot->set_attribute("xmlns:pfx","non/default/with/prefix");
// now we have
// <a1757:root
//     xmlns:a3767="foo/the/bar"
//     xmlns:yan="yet/another/namespace"
//     xmlns:a1757="new/ns/no/prefix"
//     xmlns="default/ns/no/prefix"
//     xmlns:pfx="non/default/with/prefix"
// />

/*
Any XML processor still regards it as a namespace declaration the same way
they recognise the other namespaces we declared. Problem for us is that we
cannot ascertain the existing namespace declarations on any element if they are
not declared using set_attribute. Furthermore, external files imported into
DOMXML objects do NOT have their namespace declarations detected as attributes -
and rightly so. But the problem arises that now there is no way to detect these
declarations.
*/

var_dump($ndRoot->attributes());
// Our new "xmlns:pfx" *attribute* now shows up because we set it with an
// attribute method and it is of type "domattribute". So what of our namespace
// declarations using set_namespace() then? Do they have a type?

/*
Well there doesn't seem to be any other dom type where our declarations can
reside. This is problably the reason why we have no way of detecting them.
It's important to note that when parsing in external XML files, the prefixed
namespace declarations do NOT show up in the list of attribute nodes.
*/

/*
I would also argue that destroying the existing element prefix by forcing the
[re]population of it with a new one when using set_namespace() should be
considdered "unexpected behaviour". If the user doesn not supply a prefix, then
it should be added as the default namespace (with no prefix).
Using set_attribute() is a workaround to the "problem" and not a solution.
*/

/*
The behaviour of set_namespace() is not the biggest problem though.
Inability to detect existing namespace declarations is. How do I find out if
a namespace with id of "yet/another/namespace" has been declared in this
element? The answer is I can't. And if I could, I would also want to know what
prefix it is using.
*/

echo htmlentities($objDoc->dump_mem(true));
?>
DomElement::tagname
DomNode::append_child
DOM XML (PHP 4) Функции


Добавляет нового сына в конец списка сыновей

DomNode::add_namespace
DomNode::append_sibling
DOM XML (PHP 4) Функции
PHP Manual

DomNode::append_child

(PHP 4 >= 4.1.0)

DomNode::append_child — Добавляет нового сына в конец списка сыновей

Описание

DOMNode DOMNode::append_child ( DOMNode $newnode )

Эта функция добавляет сына к существующему списку сыновей, либо создает список.

Список параметров

newnode

Добавляемый узел. Может быть создан посредством например DomDocument::create_element, DomDocument::create_text_node и т.п. или просто используя другой узел.

Замечание:

Невозможно этом методом добавить узел DOMAttribute. Используйте вместо него функцию DomElement::set_attribute.

Возвращаемые значения

Возвращает добавленный узел или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
4.3.0 | Вставка узла из другого документа больше не поддерживается.
4.3.0 | В отличие от версий PHP раньше 4.3.0 новый сын дублируется до добавления. Таким образом новый сын является полной копией, которую можно модифицировать, не изменяя состояния узла, переданного в функцию в качестве аргумента. Если переданный узел имел сыновей, то они также будут дублированы, что сильно упрощает дублирование больших частей XML документа. Возвращаемым значением является добавленный сын. Если планируется дальнейшая модификация добавленного сына, необходимо использовать именно возвращенный узел.
4.3.0 и 4.3.1 | Если новый сын newnode уже является сыном DomNode, то он не включается в существующий контекст. Поэтому newnode перемещается и ничего не копирует. Это поведение соответствует спецификациям W3C. Если требуется старое поведение, используйте функцию DomNode::clone_node перед добавлением узла.
4.3.2 | Если новый сын newnode уже находится в дереве, он отсоединяется от своего контекста. Применяются те же правила.

Примеры

Следующий пример добавляет новый элемент в чистый документ и устанавливает атрибут align в значение left.

Пример #1 Добавление сына

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

Пример выше можно записать в следующем виде:

Пример #2 Добавление сына

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>

Ниже представлен более исчерпывающий пример. Вначале производится поиск определенного элемента, затем он дублируется вместе со всеми потомками и добавляется как брат. В итоге новый атрибут добавлен к одному из сыновей нового брата, и документ скопирован целиком.

Пример #3 Добавление сына

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {

  echo "Ошибка при разборе документа\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
?>

Пример выше также можно выполнить с помощью DomNode::insert_before вместо DomNode::append_child.

Переход на PHP 5

Необходимо использовать DOMNode::appendChild.

Смотрите также

  • DomNode::insert_before
  • DomNode::clone_node

User Contributed Notes

andrew at transitionmedia dot co dot uk 12-Feb-2006 07:03
As of version 4.3 PHP doesn't support Appending a child from another source document. If you are trying to  import information from multiple sources into a final document [for transformation using XSL as an example] then you can have problems. This technique can be used to do it though.

I am assuming you have two documents open, $xmldoc1 and $xmldoc2 and you have selected [via XPath or explicit searching] the nodes you want in each document. Thus $xmldoc1_appending_node is the node you would like to add $xmldoc2_importnode to.

<?

// first we create a temporary node within the document we want to add to.
$temp_importnode = $xmldoc1->create_element("import");

// now we have a node that is in the right document context we can clone the one we want into this one.
$temp_importnode = $xmldoc_importnode->clone_node(true);

// by using true in the above call to clone_node() we copy all of the child nodes as well. Use false or nothing if you just want the containing node with no children.

$xmldoc1_appending->append_child($importnode);

?>

Now your document contains the new nodes imported from a different document.
wackysalut at bourget dot cc 01-Nov-2002 12:46
Be careful of the order you append childs. (PHP <= 4.2)

If you create let's say:

$x_html = $x_doc->create_element('html');
$x_head, $x_title, $x_meta, $x_link and $x_body in the same way.

If you:

$x_head->append_child($x_title);
$x_head->append_child($x_meta);
$x_head->append_child($x_link);

$x_html->append_child($x_head);

$x_body_backup = $x_html->append_child($x_body);

/* here */

$x_doc->append_child($x_html);

If you now try to modify $x_body_backup.. it will no longer be able to modify the actualy XML tree, because you appended the HTML tree to the DomDocument.. and it has copied ALL the nodes at the end of the DomDocument, so the reference you now have in $x_body_backup is not valid anymore! If you had modified it where the /* here */ line is.. the $x_body_backup would still be valid.. but not after the $x_doc->append_child($x_html);

What you can do is, reverse the order of your appendings.. so that you append the highest level node at the end.. so that your reference is still valid after, or wait till you have filled all of the nodes you wanted to add before you append it to your parent node.
DomNode::add_namespace
DomNode::append_sibling
DOM XML (PHP 4) Функции


Добавляет к узлу нового брата

DomNode::append_child
DomNode::attributes
DOM XML (PHP 4) Функции
PHP Manual

DomNode::append_sibling

(PHP 4 >= 4.2.0)

DomNode::append_sibling — Добавляет к узлу нового брата

Описание

domelement DomNode::append_sibling ( domelement $newnode )

Эта функция добавляет брата к существующему узлу. Сын может быть создан функциями domdocument_create_element(), domdocument_create_text() и т.п. или просто используя другой узел.

Прежде чем новый брат будет добавлен, он дублируется. Таким образом новый сын является полной копией, которую можно модифицировать, не изменяя состояния переданного в функцию узла. Если переданный узел имеет сыновей, они все также будут дублированы, это позволяет довольно просто дублировать большие части XML документа. Функция возвращает добавленного брата. Если планируется дальнейшая модификация добавленного узла, необходимо пользоваться возвращаемым значением.

Эта функция добавлена с целью предоставить поведение функции domnode_append_child(), как она работала до версии PHP 4.2.

См. также domnode_append_before().

User Contributed Notes

s dot girard at pandora dot be 30-Apr-2004 11:06
Small example on the use of domnode->append_sibling()
This function creates a news.xml file, that will be later on parsed with XSLT.

$doc = domxml_new_doc("1.0");
$root = $doc->create_element("rt");
$root = $doc->append_child($root);
$page = $doc->create_element("page");
$page = $root->append_child($page);
$page->set_attribute("pageimage","images/news.jpg");

while($row = mysql_fetch_row($result))
{
    $news = $doc->create_element("news");
    $news = $page->append_child($news);

    $topic = $doc->create_element("topic");
    $topic = $news->append_child($topic);

    $topic_content = $doc->create_text_node($row[0]);
    $topic_content = $topic->append_child($topic_content);

    $user = $doc->create_element("user");
    $user = $topic->append_sibling($user);

    $user_content = $doc->create_text_node($row[3]);
    $user_content = $user->append_child($user_content);

    $date = $doc->create_element("date");
    $date = $topic->append_sibling($date);

    $date_content = $doc->create_text_node($row[2]);
    $date_content = $date->append_child($date_content);

    $body = $doc->create_element("body");
    $body = $topic->append_sibling($body);

             $body_content = $doc->create_text_node($row[1]);
    $body_content = $body->append_child($body_content);
}
unlink("./data/news.xml");
$doc->dump_file("./data/news.xml");
DomNode::append_child
DomNode::attributes
DOM XML (PHP 4) Функции


Возвращает список атрибутов

DomNode::append_sibling
DomNode::child_nodes
DOM XML (PHP 4) Функции
PHP Manual

DomNode::attributes

(PHP 4 >= 4.1.0)

DomNode::attributes — Возвращает список атрибутов

Описание

array DomNode::attributes ( void )

Эта функция возвращает список атрибутов только если узел имеет тип XML_ELEMENT_NODE.

(только для PHP >= 4.3) Если атрибутов не найдено, функция вернет NULL.

User Contributed Notes

Ian Monroe 29-Nov-2005 08:03
A function to get the value of an attribute given the name of the desired attribute and the results of attributes() to the second parameter.
<?php
function getAttribute($name, $att)
{
    foreach($att as $i)
    {
        if($i->name()==$name)
            return $i->value();
    }
}?>
steve at realappraiser dot net 05-Jan-2005 12:41
$xpath = $parseDoc->xpath_new_context($parseDoc);
$getResultSearch = $xpath->xpath_eval("//PROPERTY_INFORMATION_RESPONSE/_PRODUCT");
$nodesetResult = $getResultSearch->nodeset;
$var1=$getResultSearch->nodeset[0]->attributes() ;
implode($var1);
print_r ($var1 )  ;

// it prints something like this:::::

Array ( [0] => domattribute Object ( [type] => 2 [name] => _PrettyAttr [value] => Y [0] => 26 [1] => 161068800 ) )
DomNode::append_sibling
DomNode::child_nodes
DOM XML (PHP 4) Функции


Возвращает сыновей узла

DomNode::attributes
DomNode::clone_node
DOM XML (PHP 4) Функции
PHP Manual

DomNode::child_nodes

(PHP 4 >= 4.1.0)

DomNode::child_nodes — Возвращает сыновей узла

Описание

array DomNode::child_nodes ( void )

Возвращает всех сыновей узла.

См. также domnode_next_sibling() и domnode_previous_sibling().

User Contributed Notes

thibo1025 at hotmail dot fr 30-Apr-2008 02:57
to avoid the "#text" what you can simply do without changing your xml file, is:

if($item->nodeName != "#text"){
// do your code.
}
andrew at transitionkiteboarding dot com 26-May-2004 11:58
Sometimes unless you know exactly where elements are it can be time consuming to pick each thing up with get_element_by_tagname calls.

I used a quick little function that, given a structure such as:

<customer>
  <firstname>Joe</firstname>
  <surname>Bloggs</surname>
  <age>24</age>
  <sex>Male</sex>
  ...
</customer>

it will return an associative array with the tag names as keys and the content as values. During the load I strip whitespace as well so it isn't confused by \n's creating blank nodes

-- CODE --
$xmldoc = domxml_open_mem($xmlstring,
  DOMXML_LOAD_PARSING + //0
  DOMXML_LOAD_COMPLETE_ATTRS + //8
  DOMXML_LOAD_SUBSTITUTE_ENTITIES + //4
  DOMXML_LOAD_DONT_KEEP_BLANKS //16 ));

  // get the node root and then the children of it.
  $noderoot = $xmldoc->document_element();
  $childnodes = $noderoot->child_nodes();

  // build the array
  foreach ($childnodes as $value) {
      echo $value->tagname . " : " . $value->get_content() . "<br>";
      $nodeArray[$value->tagname] = $value->get_content();
  }

-- END CODE --

You can then return node array or start using it however you like in other functions just like a normal associative array then.

$nodeArray['firstname'] == "Joe"
grillen at abendstille dot at 25-Jan-2004 01:08
There were some comments about problems with whitespaces.
you can easily solve them by creating the dom-document as follows:

<?php
    $xmlDoc = @domxml_open_mem(
            $xmlString
        ,    DOMXML_LOAD_PARSING + //0
            DOMXML_LOAD_COMPLETE_ATTRS + //8
            DOMXML_LOAD_SUBSTITUTE_ENTITIES + //4
            DOMXML_LOAD_DONT_KEEP_BLANKS //16
        ,    $error
        );
?>

if you call child_nodes() on eg. the root-element whitespaces are ignored.
zombie(at)artattack(dot)to 04-Nov-2003 05:17
Here is a handy little function i started using at work and home quite a bit. It takes in an array of nodes, typically from DomNode->child_nodes() as well as a filter argument and returns an array of filtered out nodes.

If the $filter arg is a string, then the $boolean argument is used. If boolean is true, then only nodes named $filter will be returned. If boolean is false, then only nodes NOT named $filter will be returend.

Additionally, you can specify the filter as an assoc array in the form of $array[$node_name] = true|false and only nodes in the array with a true value are returend. Note that if it is an array, then $boolean is not used. I was planning on having the boolean act as a negation kinda like !in_array(), but it was more for completeness than need so i dropped it.

function get_filtered_children($children_array,$filter,$boolean = true){
    $total_children = count($children_array);
    for ($i = 0; $i < $total_children; $i++){
        $cur_child = $children_array[$i];
        $node_name = $cur_child->node_name();
        if (is_array($filter)){ //array in the form of [node_name] = true|false
            if ($filter[$node_name])
                $filtered_children_array[] = $cur_child;
        }
        else if(is_string($filter)){ //string hopefully...
            if ($boolean && $node_name == $filter)
                $filtered_children_array[] = $cur_child;
            elseif (!$boolean && $node_name != $filter)
                $filtered_children_array[] = $cur_child;
        }
        else
            user_error('filter is of type ' . gettype($filter) . '. Please only supply arrays or strings.', E_USER_ERROR);
    }
    return $filtered_children_array;
}

Blaine Garrett
Web Master of the Art Attack
http://artattack.to
arcana at yetta dot net 09-Mar-2003 05:32
A better way to check for Text Child nodes (PHP 4.3.0)

    if ($childnode->node_type() == XML_TEXT_NODE)
    {
        echo "<br/>This item is a text node.";
    }
    else
    {
        echo "<br/>This item is not a text node.";
    }

You may want to look at DomElement->is_blank_node() as well.
zombie)(at)(localm)(dor)(org 30-Dec-2002 10:34
Loop through children making sure that the children are not text nodes.
<pre>

$moduleDoc = domxml_open_file("main_module_defs.xml");
$moduleDefinitionXPath = xpath_new_context($moduleDoc);
$dConvsNodeSet = xpath_eval($moduleDefinitionXPath, "//modules/module[@name='search']/dConvs");
$children = $dConvsNodeSet->nodeset[0]-> child_nodes();
$dTotal = count($children);
for ($i=0;$i<$dTotal;$i++){
    $curNode = $children[$i];
    if($curNode->node_name() != "#text"){
        echo "This are probably TextNodes...";    }
}
</pre>

--
http://artattack.to
jon.sprague(AT)itgco.com 10-Sep-2002 04:54
To answer hrosas)at(linuxmail)dot(org.

<node>
<child/>
</node>

<node> has 3 children.
1. whitespace between <node> and <child/>
2. <child/>
3. whitespace between <child/> and </node>

The whitespace is treated like text. To avoid this remove all whitespace.

<node><child/></node>

This can get hard to read, but correct.

But, you can tell some programs to ignore the whitespace, so it remains easy to read.

Jon Sprague
hrosas)at(linuxmail)dot(org 27-Aug-2002 06:36
I was using child_nodes and if I have a node like this.
<node>
    <child/>
</node>

the node <node> have two children: one the "    " spaces that appear as #text on php and <child/>. Is that normal? I think node has just one child <child/>
j dot metzger at steptown dot com 26-Aug-2002 08:01
if no children present, method
returns
FALSE (bool)

you can check the return result like this:

$children = $domNode -> child_nodes();
if (is_bool($children))
   print "Sorry, no children present ...";
DomNode::attributes
DomNode::clone_node
DOM XML (PHP 4) Функции


Копирует узел

DomNode::child_nodes
DomNode::dump_node
DOM XML (PHP 4) Функции
PHP Manual

DomNode::clone_node

(PHP 4 >= 4.1.0)

DomNode::clone_node — Копирует узел

Описание

domelement DomNode::clone_node ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

sworley at dotster dot com 21-Nov-2006 02:00
A complete, executable, minimal example of how to copy between documents:

<?
$doc1 = domxml_open_mem('<one><onething/></one>');
$doc2 = domxml_open_mem('<two><twothing/></two>');
$root1 = $doc1->document_element();
$root2 = $doc2->document_element();
$root1->append_child($root2->clone_node(true));
echo $doc1->dump_mem();
?>

Emits: <one><onething/><two><twothing/></two></one>
krymsonwulf at gmail dot com 05-Jun-2006 02:41
It seems like this function is non-recursive: cloning a node will not clone it's child nodes in my experience
andrew at transitionmedia dot co dot uk 12-Feb-2006 07:04
As of version 4.3 PHP doesn't support Appending a child from another source document. If you are trying to  import information from multiple sources into a final document [for transformation using XSL as an example] then you can have problems. This technique can be used to do it though.

I am assuming you have two documents open, $xmldoc1 and $xmldoc2 and you have selected [via XPath or explicit searching] the nodes you want in each document. Thus $xmldoc1_appending_node is the node you would like to add $xmldoc2_importnode to.

<?

// first we create a temporary node within the document we want to add to.
$temp_importnode = $xmldoc1->create_element("import");

// now we have a node that is in the right document context we can clone the one we want into this one.
$temp_importnode = $xmldoc_importnode->clone_node(true);

// by using true in the above call to clone_node() we copy all of the child nodes as well. Use false or nothing if you just want the containing node with no children.

$xmldoc1_appending->append_child($importnode);

?>

Now your document contains the new nodes imported from a different document.
hrz at geodata dot soton dot ac dot uk 11-May-2005 08:28
Passing boolean 'true' as the argument to this function will result in all child nodes being cloned as well.
r dot kamstra at syntomax dot com 08-Nov-2002 08:06
if a DomNode is duplicated it's siblings and parent are not duplicated
DomNode::child_nodes
DomNode::dump_node
DOM XML (PHP 4) Функции


Представляет одиночный узел в виде строки

DomNode::clone_node
DomNode::first_child
DOM XML (PHP 4) Функции
PHP Manual

DomNode::dump_node

(PHP 4 >= 4.1.0)

DomNode::dump_node — Представляет одиночный узел в виде строки

Описание

string DomNode::dump_node ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

См. также domdocument_dump_mem().

User Contributed Notes

sofa77 at gmx dot de 14-Apr-2005 02:04
the function below to dump only the contents of a node looks as follows in php5. necessarry to say, that there is no dump_node() function in php5... it took me some time to find this out.

function dump_child_nodes($node)
{
  $output = '';
  $owner_document = $node->ownerDocument;

  foreach ($node->childNodes as $el){
    $output .= $owner_document->saveXML($el);
  }
  return $output;
}
zombie(at)artattack(dot)to 06-Nov-2003 02:19
Here is a handy little function for dumping the contents of a element node when you do not want the element itself yet you do not want the output escaped. For example, you have an HTML body tag and you want to dump the children, but you do not want all the children HTML tags escaped, which it seems like the get value/content functions do. There might be a better way of doing this, but this is pretty stable.

function dump_child_nodes($node){
    $owner_document = $node->owner_document();
    $children = $node->child_nodes();
    $total_children = count($children);
    for ($i = 0; $i < $total_children; $i++){
        $cur_child_node = $children[$i];
        $output .= $owner_document->dump_node($cur_child_node);
    }
    return $output;
}

Blaine Garrett
Webmaster of Art Attack
http://artattack.to
12-Mar-2003 11:47
The note above is exact :
dump_node is not a method of the DomNode class anymore but a method of DomDocument class.
Note that "$dom->dump_node($myNodeObject); " also works in PHP 4.2.
So I recommand to use it like this.

Last thing : you can't specified the encoding in the dump_node methode contrary to the dump_mem method.
So characters like '�' are always converted in UTF-8.
The function below does exactly the same work as dump_node but also take in argument the encoding :
(it's not elegant but it works)

function my_dump_node($node,$encoding){
    $domNode = domxml_new_doc("1.0");
    $clonedNode = $node->clone_node(true);
    $domNode->append_child($clonedNode);
    $result = $domNode->dump_mem(true,$encoding);
    $pos = strpos($result,"?>");
    return substr($result,$pos+2);
}
so
$dom->dump_node($myNodeObject);
becomes
my_dump_node($myNodeObject,"ISO-8859-1");
gerret at oneota dot net 06-Feb-2003 07:59
I migrated some code from PHP 4.2.1 to PHP 4.3.0. Platform was Apache 1.3.9 on Windows. My code kept crashing Apache until I saw the previous note. dump_node() now appears to be a member of DomDocument, and not of DomNode as it used to be. At least, when I changed my code

$node->dump_node($node)

to

$doc->dump_node($node)

Apache quit crashing and the dump_node() method worked as intended.
gk at proliberty dot com 10-Jan-2003 12:39
The first comment above is wrong, at least, now in PHP 4.3.0
Example:
<?php
$xml=<<<eot
<node attr="test"><test>hi</test>
</node>
eot;
$doc = domxml_open_mem($xml);
$root=$doc->document_element();
//This will NOT work:
//$nodeDump =$doc->dump_node($doc);
//This works:
$nodeDump =$doc->dump_node($root);
echo htmlentities($nodeDump);
?>
lukeN~O at S~P~A~Mbenoire dot com 30-Oct-2002 05:43
I'm running PHP 4.2.3 and there is a second parameter which defines the format of the output, as with dump_mem() - see the notes for dump_mem() for usage of this.
KDan 22-Aug-2002 06:22
Note: This also dumps the tag that defines the node you are trying to dump. It is useful because it is the only way I could find to get a node's content including the tags in it.

Example:
From this xml bit of file:
<block>
          Blah blah blah <some_stuff/>
</block>

doing a dump_node on this block node will return exactly all of the xml typed above, including the <block> tags. Trying to get the value or content of the node, however, will only return "Blah blah blah" as <some_stuff> is considered a child, not part of the /text() xpath.
dan at mojavelinux dot com 27-Apr-2002 06:37
As of right now, php 4.2.0 this function requires that the first parameter be the node, so it would require

DomNode->dump_node(DomNode)
DomNode::clone_node
DomNode::first_child
DOM XML (PHP 4) Функции


Возвращает первого сына узла

DomNode::dump_node
DomNode::get_content
DOM XML (PHP 4) Функции
PHP Manual

DomNode::first_child

(PHP 4 >= 4.1.0)

DomNode::first_child — Возвращает первого сына узла

Описание

domelement DomNode::first_child ( void )

Возвращает первого сына узла.

(только для PHP >= 4.3) Если первый сын не найден, функция вернет NULL.

См. также domnode_last_child() и
domnode_next_sibling(),
domnode_previous_sibling().

User Contributed Notes

20-May-2007 06:52
in PHP5's DOM (Not DOM-XML) class use firstChild variable instead of first_child() function.
DomNode::dump_node
DomNode::get_content
DOM XML (PHP 4) Функции


Получает содержимое узла

DomNode::first_child
DomNode::has_attributes
DOM XML (PHP 4) Функции
PHP Manual

DomNode::get_content

(PHP 4 >= 4.2.0)

DomNode::get_content — Получает содержимое узла

Описание

string DomNode::get_content ( void )

Эта функция возвращает содержимое узла.

Пример #1 Получение содержимого

<?php
if (!$dom = domxml_open_mem($xmlstr)) {

  echo "Ошибка при разборе документа\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
    $node = $node_array[$i];
    echo "The element[$i] is: " . $node->get_content();
}

?>

User Contributed Notes

kris {at} linked {dot} com {dot} mt 01-Sep-2010 11:04
To print the node simply create a new document import the node and save it to html or whatever you need

e.g.:

<?php
$temp = new DOMDocument('1.0', 'UTF-8');
$temp_node = $temp->importNode($mynode, TRUE);
$temp->appendChild($temp_node);
$temp->saveHTML();
?>
d dot cicognani at ciconet dot it 23-Dec-2005 11:43
Only to correct a very small error, but maybe difficult to find in che function GetContentAsString posted by someone in April 2005.
There was $anode-node_value() instead of $anode->node_value().
This is the right version:

<?php

function GetContentAsString($node) {
  $st = "";
  foreach ($node->child_nodes() as $cnode)
   if ($cnode->node_type()==XML_TEXT_NODE)
     $st .= $cnode->node_value();
   else if ($cnode->node_type()==XML_ELEMENT_NODE) {
     $st .= "<" . $cnode->node_name();
     if ($attribnodes=$cnode->attributes()) {
       $st .= " ";
       foreach ($attribnodes as $anode)
         $st .= $anode->node_name() . "='" .
           $anode->node_value() . "'";
       }
     $nodeText = GetContentAsString($cnode);
     if (empty($nodeText) && !$attribnodes)
       $st .= " />";        // unary
     else
       $st .= ">" . $nodeText . "</" .
         $cnode->node_name() . ">";
     }
  return $st;
  }

?>
krautman at gmx dot net 06-Dec-2005 07:14
get_content() always returns UTF-8 (as should be!).
To get the content right just code it like

$myContent = utf8_decode($myNode->get_content());

Works fine!
sysadmin at webnow dot com dot br 26-Jul-2005 05:43
Seems that get_content() always returns utf-8.
Opening document with something like

$dom->dump_mem(true,"ISO-8859-1")

makes no difference!
11-Apr-2005 09:41
Here's a routine I wrote that acts like get_content() but returns embedded XHTML in the string returned.  I needed this as I was wanting to embed HTML formatting codes in my HTML (e.g., "<br />") and converting them to HTML entities or using CDATA was a huge hassle.

<?php

function GetContentAsString($node) {
  $st = "";
  foreach ($node->child_nodes() as $cnode)
    if ($cnode->node_type()==XML_TEXT_NODE)
      $st .= $cnode->node_value();
    else if ($cnode->node_type()==XML_ELEMENT_NODE) {
      $st .= "<" . $cnode->node_name();
      if ($attribnodes=$cnode->attributes()) {
        $st .= " ";
        foreach ($attribnodes as $anode)
          $st .= $anode->node_name() . "='" .
            $anode-node_value() . "'";
        }
      $nodeText = GetContentAsString($cnode);
      if (empty($nodeText) && !$attribnodes)
        $st .= " />";        // unary
      else
        $st .= ">" . $nodeText . "</" .
          $cnode->node_name() . ">";
      }
  return $st;
  }

?>
DomNode::first_child
DomNode::has_attributes
DOM XML (PHP 4) Функции


Проверяет, есть ли в узле атрибуты

DomNode::get_content
DomNode::has_child_nodes
DOM XML (PHP 4) Функции
PHP Manual

DomNode::has_attributes

(PHP 4 >= 4.1.0)

DomNode::has_attributes — Проверяет, есть ли в узле атрибуты

Описание

bool DomNode::has_attributes ( void )

Эта функция проверяет, имеет ли узел атрибуты.

См. также domnode_has_child_nodes().

User Contributed Notes

There are no user contributed notes for this page.
DomNode::get_content
DomNode::has_child_nodes
DOM XML (PHP 4) Функции


Проверяет, есть ли у узла потомки

DomNode::has_attributes
DomNode::insert_before
DOM XML (PHP 4) Функции
PHP Manual

DomNode::has_child_nodes

(PHP 4 >= 4.1.0)

DomNode::has_child_nodes — Проверяет, есть ли у узла потомки

Описание

bool DomNode::has_child_nodes ( void )

Эта функция проверяет, имеет ли узел потомков.

См. также domnode_child_nodes().

User Contributed Notes

There are no user contributed notes for this page.
DomNode::has_attributes
DomNode::insert_before
DOM XML (PHP 4) Функции


Вставляет новый узел в качестве сына

DomNode::has_child_nodes
DomNode::is_blank_node
DOM XML (PHP 4) Функции
PHP Manual

DomNode::insert_before

(PHP 4 >= 4.1.0)

DomNode::insert_before — Вставляет новый узел в качестве сына

Описание

domelement DomNode::insert_before ( domelement $newnode , domelement $refnode )

Эта функция вставляет новый узел newnode перед узлом refnode. Возвращаемым значением является вставленный узел. Если планируется его изменять, необходимо использовать для этого возвращаемый из функции узел.

(Только для PHP >= 4.3) Если newnode является частью документа, он будет отсоединен от своего прежнего контекста. Если refnode NULL, то newnode будет вставлен в конец списка сыновей.

domnode_insert_before() очень похожа на domnode_append_child(), что подтверждает пример ниже, который делает то же самое, что и пример в описании к domnode_append_child().

Пример #1 Добавление сына

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {

  echo "Ошибка при разборе документа\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";
?>

См. также domnode_append_child().

User Contributed Notes

captainbajoo at juno dot com 11-May-2006 08:40
In a numbered ordering of the document's nodes, insertBefore() will place newNode at the index held by refNode, and increment refNode's index and all subsequent nodes' indices. This is instead of maintaining refNode's index, placing newNode at refNode's position minus one, and shifting all previous nodes' indices down by one.

The base case of refNode.index = 0 demonstrates why this must be the case, but it is good to know this explicitly, as it affects methods that deal with iteration such as getElementsByTagName().
DomNode::has_child_nodes
DomNode::is_blank_node
DOM XML (PHP 4) Функции


Проверяет, есть ли содержимое в узле

DomNode::insert_before
DomNode::last_child
DOM XML (PHP 4) Функции
PHP Manual

DomNode::is_blank_node

(PHP 4 >= 4.1.0)

DomNode::is_blank_node — Проверяет, есть ли содержимое в узле

Описание

bool DomNode::is_blank_node ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
DomNode::insert_before
DomNode::last_child
DOM XML (PHP 4) Функции


Возвращает последнего сына узла

DomNode::is_blank_node
DomNode::next_sibling
DOM XML (PHP 4) Функции
PHP Manual

DomNode::last_child

(PHP 4 >= 4.1.0)

DomNode::last_child — Возвращает последнего сына узла

Описание

domelement DomNode::last_child ( void )

Возвращает последнего сына узла.

(только для PHP >= 4.3) Если последний сын не найден, функция вернет NULL.

См. также domnode_first_child() и
domnode_next_sibling(),
domnode_previous_sibling().

User Contributed Notes

There are no user contributed notes for this page.
DomNode::is_blank_node
DomNode::next_sibling
DOM XML (PHP 4) Функции


Возвращает следующего брата узла

DomNode::last_child
DomNode::node_name
DOM XML (PHP 4) Функции
PHP Manual

DomNode::next_sibling

(PHP 4 >= 4.1.0)

DomNode::next_sibling — Возвращает следующего брата узла

Описание

domelement DomNode::next_sibling ( void )

Эта функция возвращает следующего брата текущего узла. Если следующих братьев больше нет, функция возвращает FALSE (< 4.3) или null (>= 4.3). Можно использовать эту функцию для перебора сыновей узла как показана в примере ниже.

Пример #1 Перебор сыновей узла

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {

  echo "Ошибка при разборе документа\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while ($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

См. также domnode_previous_sibling().

User Contributed Notes

There are no user contributed notes for this page.
DomNode::last_child
DomNode::node_name
DOM XML (PHP 4) Функции


Возвращает имя узла

DomNode::next_sibling
DomNode::node_type
DOM XML (PHP 4) Функции
PHP Manual

DomNode::node_name

(PHP 4 >= 4.1.0)

DomNode::node_name — Возвращает имя узла

Описание

string DomNode::node_name ( void )

Возвращает имя узла. Имя может отличаться для различных типов узлов, как показано в следующей таблице.

Значение имени
Тип | Значение
DomAttribute | значение атрибута
DomAttribute |
DomCDataSection | #cdata-раздел
DomComment | #comment
DomDocument | #document
DomDocumentType | имя типа документа
DomElement | значение тэга имени элемента
DomEntity | имя сущности
DomEntityReference | имя ссылки на сущность
DomNotation | имя обозначения
DomProcessingInstruction | цель
DomText | #text

User Contributed Notes

zombie)(at)(localm)(dot)(.org 30-Dec-2002 10:33
Loop through children making sure that the children are not text nodes.
<pre>

$moduleDoc = domxml_open_file("main_module_defs.xml");
$moduleDefinitionXPath = xpath_new_context($moduleDoc);
$dConvsNodeSet = xpath_eval($moduleDefinitionXPath, "//modules/module[@name='search']/dConvs");
$children = $dConvsNodeSet->nodeset[0]-> child_nodes();
$dTotal = count($children);
for ($i=0;$i<$dTotal;$i++){
    $curNode = $children[$i];
    if($curNode->node_name() != "#text"){
        echo "This are probably TextNodes...";    }
}
</pre>

--
http://artattack.to
DomNode::next_sibling
DomNode::node_type
DOM XML (PHP 4) Функции


Возвращает тип узла

DomNode::node_name
DomNode::node_value
DOM XML (PHP 4) Функции
PHP Manual

DomNode::node_type

(PHP 4 >= 4.1.0)

DomNode::node_type — Возвращает тип узла

Описание

int DomNode::node_type ( void )

Возвращает тип узла. Все возможные типы приведены в таблице во введении.

<?php

include 'example.inc';

$dom = domxml_open_mem($xmlstr);

$chapter = $dom->document_element();

// Посмотрим, какие элементы содержатся в узле chapter
foreach($chapter->child_nodes() as $node) {
  if ($node->node_type() == XML_ELEMENT_NODE) {
    echo $node->node_name() . "\n";
  }
}

?>

Результат выполнения данного примера:

title
para

User Contributed Notes

dysmann 13-Apr-2008 04:14
node_type return one of the constants listed in the chapter "predefined constants"
wasti dot redl at gmx dot net 23-May-2005 01:40
That's not a parser issue, that's according to the DOM specification.

> Attr objects inherit the Node interface, but since they are not
> actually child nodes of the element they describe, the DOM does
> not consider them part of the document tree.

They are not child nodes, so they shouldn't be in the child_nodes collection.
17-Jun-2003 12:37
Doesn't pick up nodes of type XML_ATTRIBUTE_NODE (attributes)

Use DomNode->has_attributes() then DomNode->attributes() to retrieve a list (NameNodeMap object) of Attr objects for current node.

Is likely to be a parser issue, I'm using version 2.4.19-4 of libxml2.

Pete.
DomNode::node_name
DomNode::node_value
DOM XML (PHP 4) Функции


Возвращает значение узла

DomNode::node_type
DomNode::owner_document
DOM XML (PHP 4) Функции
PHP Manual

DomNode::node_value

(PHP 4 >= 4.1.0)

DomNode::node_value — Возвращает значение узла

Описание

string DomNode::node_value ( void )

Возвращает значение узла. Значения имеют различный смысл для разных типов узлов, как показано в следующей таблице.

Семантика значения
Тип | Семантика
DomAttribute | значение атрибута
DomAttribute |
DomCDataSection | содержимое
DomComment | содержимое комментария
DomDocument | null
DomDocumentType | null
DomElement | null
DomEntity | null
DomEntityReference | null
DomNotation | null
DomProcessingInstruction | внутреннее содержимое без цели
DomText | содержимое текстового блока

User Contributed Notes

erlend at nymedia dot no 07-Apr-2008 08:05
In response to rsl at zonapersonal dot com

Or just make sure you set the right page encoding before you start hot fixing.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Using anything else than Unicode is not really a good strategy anyway.
rsl at zonapersonal dot com 27-Jan-2006 04:18
Inmost work with HTML and browsers you may need to use

$text=utf8_decode($domnode->nodeValue);
or
$text=htmlentities(utf8_decode($domnode->nodeValue));

insted of

$text=$domnode->nodeValue;

To have a browser readable output spetialy if you deal with things like �����& etc or &amp;&aacute;&aacute; etc.
Salman 01-Oct-2003 05:42
To get the contents of the node, which is for instance:

<a>this is a test</a>

To get the string: "this is a test" use:

// assuming dom is an actual xml-dom
$temp = $dom->get_elements_by_tagname("a");
foreach($temp as $nexta) {
   echo $nexta->get_content();
}

- Salman
http://www.setcomputing.com/
DomNode::node_type
DomNode::owner_document
DOM XML (PHP 4) Функции


Возвращает документ, которому принадлежит этот узел

DomNode::node_value
DomNode::parent_node
DOM XML (PHP 4) Функции
PHP Manual

DomNode::owner_document

(PHP 4 >= 4.1.0)

DomNode::owner_document — Возвращает документ, которому принадлежит этот узел

Описание

domdocument DomNode::owner_document ( void )

Эта функция возвращает документ, которому принадлежит текущий узел.

Следующий пример создаст 2 идентичных списка сыновей.

Пример #1 Обнаружение документа узла

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

См. также domnode_insert_before().

User Contributed Notes

There are no user contributed notes for this page.
DomNode::node_value
DomNode::parent_node
DOM XML (PHP 4) Функции


Возвращает родителя узла

DomNode::owner_document
DomNode::prefix
DOM XML (PHP 4) Функции
PHP Manual

DomNode::parent_node

(PHP 4 >= 4.1.0)

DomNode::parent_node — Возвращает родителя узла

Описание

domnode DomNode::parent_node ( void )

Эта функция возвращает родительский узел.

(только для PHP >= 4.3) Если родительский узел не найден, функция вернет NULL.

Следующий пример покажет 2 идентичных списка сыновей.

Пример #1 Обнаружение документа узла

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

User Contributed Notes

There are no user contributed notes for this page.
DomNode::owner_document
DomNode::prefix
DOM XML (PHP 4) Функции


Возвращает префикс пространства имен узла

DomNode::parent_node
DomNode::previous_sibling
DOM XML (PHP 4) Функции
PHP Manual

DomNode::prefix

(PHP 4 >= 4.1.0)

DomNode::prefix — Возвращает префикс пространства имен узла

Описание

string DomNode::prefix ( void )

Возвращает префикс пространства имен узла.

User Contributed Notes

There are no user contributed notes for this page.
DomNode::parent_node
DomNode::previous_sibling
DOM XML (PHP 4) Функции


Возвращает предыдущего брата узла

DomNode::prefix
DomNode::remove_child
DOM XML (PHP 4) Функции
PHP Manual

DomNode::previous_sibling

(PHP 4 >= 4.1.0)

DomNode::previous_sibling — Возвращает предыдущего брата узла

Описание

domelement DomNode::previous_sibling ( void )

Эта функция возвращает предыдущего брата текущего узла. Если предыдущих братьев больше нет, она вернет FALSE (< 4.3) или NULL (>= 4.3). Можно использовать эту функцию для перебора сыновей узла как показано в примере.

См. также domnode_next_sibling().

User Contributed Notes

There are no user contributed notes for this page.
DomNode::prefix
DomNode::remove_child
DOM XML (PHP 4) Функции


Удаляет сына из списка сыновей

DomNode::previous_sibling
DomNode::replace_child
DOM XML (PHP 4) Функции
PHP Manual

DomNode::remove_child

(PHP 4 >= 4.2.0)

DomNode::remove_child — Удаляет сына из списка сыновей

Описание

domtext DomNode::remove_child ( domtext $oldchild )

Эта функция удаляет сына из списка сыновей. Если сына нельзя удалить или аргумент не является сыном, функция вернет FALSE. Если сын может быть удален, функция вернет старого сына.

Пример #1 Удаление сына

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {

  echo "Ошибка при разборе документа\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

См. также domnode_append_child().

User Contributed Notes

iloveitaly at gmail.com 04-Dec-2004 06:28
The remove_child() function seems to have a bug. if the parent node  of the node you are trying to delete is the same as the root node it will give you unexpected errors. I fixed this by checking if the parent node of the node i was deleting was the same as the document node. take a look at the function below if you are running into the same problem. $this->xmlData reffers to the domxml object inside the class i was using.
<?php
    function deleteNode($ref, $levels) {
        $parent = $ref->parent_node();
        $root = $this->xmlData->document_element();
        if($parent->node_name()==$root->node_name()) {
            $parent = $this->xmlData->document_element();
        }
        if($parent->remove_child($ref)) {
            return true;
        } else {
            exit("error removing node");
        }
    }
?>
DomNode::previous_sibling
DomNode::replace_child
DOM XML (PHP 4) Функции


Замена сына

DomNode::remove_child
DomNode::replace_node
DOM XML (PHP 4) Функции
PHP Manual

DomNode::replace_child

(PHP 4 >= 4.2.0)

DomNode::replace_child — Замена сына

Описание

domelement DomNode::replace_child ( domelement $newnode , domelement $oldnode )

(PHP 4.2) Эта функция заменяет сына oldnode новым переданным функции узлом. Если новый узел уже является сыном, то второе добавление не производится. Если старый узел найти не удается, функция вернет FALSE. Если замена прошла успешна, функция возвращает старый узел.

(PHP 4.3) Эта функция заменяет сына oldnode новым переданным функции узлом newnode, даже если новый узел уже является сыном DomNode. Если newnode уже был вставленным в документ, он отсоединяется от своего предыдущего контекста. Если заменяемый узел не удалось найти, функция вернет FALSE. Если замена завершилась успешно, будет возвращен старый узел. (Это поведение отвечает требованиям W3C спецификации.)

См. также domnode_append_child()

User Contributed Notes

Beat 25-Nov-2010 02:32
This function behaves differently depending on PHP version:

- It forgets attributes of the new node in PHP 5.2,
- but copies them in PHP 5.3.

(at least when looking at the SimpleXMLElement mirror of the DOM being changed in DOM (by lack of equivalent methods in SimpleXMLElement).

Annoying different behavior / bug, but good to know. Would be good to update the doc about what the wanted behavor is

In both versions, children nodes are not coming together with the new node and need to be added one by one recursively. Just good to know too.
nospam at fivetide dot com 26-Feb-2004 06:25
There's a bug in the docs here. The order of arguments is the other way round i.e.
object DomNode->replace_child ( object newnode, object oldnode)

Here's an example of it working:

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$doc->append_child($root);
$head = $doc->create_element("HEAD");
$root->append_child($head);
$title = $doc->create_element("TITLE");
$head->append_child($title);
$text = $doc->create_text_node("This is the title");
$title->append_child($text);

echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";

$newtitle = $doc->create_text_node("No, this is the title");
// object DomNode->replace_child ( object newnode, object oldnode)
$title->replace_child($newtitle,$title->first_child());

echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>
DomNode::remove_child
DomNode::replace_node
DOM XML (PHP 4) Функции


Заменяет узел

DomNode::replace_child
DomNode::set_content
DOM XML (PHP 4) Функции
PHP Manual

DomNode::replace_node

(PHP 4 >= 4.2.0)

DomNode::replace_node — Заменяет узел

Описание

domelement DomNode::replace_node ( domelement $newnode )

(PHP 4.2) Эта функция заменяет существующий узел на новый переданный в качестве аргумента. Перед заменой newnode копируется, если у него есть родитель, чтобы быть уверенными, что уже существующий узел не будет вставлен повторно. Такое поведение функции вынуждает делать все изменения в узле до замены, либо выбирать уже добавленный узел после замены такими функциями, как domnode_first_child(), domnode_child_nodes() и т.п.

(PHP 4.3) Эта функция заменяет существующий узел на новый переданный в качестве аргумента. Если newnode уже был добавлен в документ, он будет отсоединен от своего прежнего контекста. В случае успешной замены функция вернет старый узел.

См. также domnode_append_child()

User Contributed Notes

There are no user contributed notes for this page.
DomNode::replace_child
DomNode::set_content
DOM XML (PHP 4) Функции


Устанавливает содержимое узла

DomNode::replace_node
DomNode::set_name
DOM XML (PHP 4) Функции
PHP Manual

DomNode::set_content

(PHP 4 >= 4.1.0)

DomNode::set_content — Устанавливает содержимое узла

Описание

bool DomNode::set_content ( string $content )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

blah at pasher dot org 13-Jul-2006 03:42
For those transitioning to PHP5 DOM XML code, there is a gotcha with this function.

In PHP4, when you call $node->set_content($string), the $string must have special HTML characters encoded. The method does not properly handle the "&" character, so this is required to properly set the content

In PHP5, when you call $node->appendChild($dom->createTextNode($string)), PHP will properly encode the "&" character without the need for HTML encoding.

Because of this, older code that is currently using htmlspecialchars() in the set_content() call will potentially double-encode the "&" character if you keep the call to htmlspecialchars() in the createTextNode() call.
dh at victory-sa dot com 28-Sep-2004 06:00
function replace_content( &$node, $new_content )
{
    $dom = &$node->owner_document();
    $kids = &$node->child_nodes();
    foreach ( $kids as $kid )
        if ( $kid->node_type() == XML_TEXT_NODE )
            $node->remove_child ($kid);
    $node->set_content($new_content);
}
robinson at rsl dot com dot tw 05-Nov-2003 12:18
If you want to set_content which is not in Alphabet, such as big5 charset, you have to use the iconv() to convert your codeset from big5 to something else, such as UTF-8. Here is a example:

$node->set_content(iconv("big5","UTF-8","This is a test.");
$node->set_content(iconv("big5","UTF-8","[Chinese Chars]");

These works find that won't dump garbage chars when your use dump_mem to file.

Ps. don't forget to include the php_iconv.dll
27-Jun-2003 05:00
As of 4.3.2:

$names = $contact->get_elements_by_tagname("name");
$name = $names[0];
$name_text_node = $name->first_child();
$name_text_node->set_content("Joe");

does not work.  Currently it looks like dom text nodes are implemented as "domtext", not "domelement" and therefore lack the set_content method.  As far as I've been able to tell, replacing is the best solution.
fivebull at 163 dot com 27-Mar-2003 07:02
if you had used set_name() to change the node's tag name :

 $newnode =& $dom->create_element( $node->tagname );
should be:
 $newnode =& $dom->create_element(  $node->node_name());
ericb at computer dot org 13-Mar-2003 10:18
Actually, don't forget that the text is actually a child node of the given element. The domxml coders decided to append to the content in the case that this function is called on a node which has children (to avoid a crash), but you shouldn't normally call it that way.

For example, if your document had:

<contact>
<name>Eric</name>
</contact>

and you wanted to change the content of the name element and $contact is the contact node, then you would use:

$names = $contact->get_elements_by_tagname("name");
$name = $names[0];
$name_text_node = $name->first_child();
$name_text_node->set_content("Joe");

Hope this clarifies things. Removing nodes, and inserting new ones is not an efficient solution :)

Cheers,

Eric
KDan 23-Sep-2002 06:21
/**
 * Replace node contents
 *
 * Needed as a workaround for bug/feature of set_content
 * This version puts the content
 * as the first child of the new node.
 * If you need it somewhere else, simply
 * move $newnode->set_content() where
 * you want it.
 */
function replace_content( &$node, &$new_content )
{
    $dom =& $node->owner_document();

    $newnode =& $dom->create_element( $node->tagname );

    $newnode->set_content( $new_content );

    $atts =& $node->attributes();
    foreach ( $atts as $att )
    {
        $newnode->set_attribute( $att->name, $att->value );
    }

    $kids =& $node->child_nodes();
    foreach ( $kids as $kid )
    {
        if ( $kid->node_type() != XML_TEXT_NODE )
        {
            $newnode->append_child( $kid );
        }
    }

    $node->replace_node( $newnode );
}
KDan 05-Sep-2002 07:34
As of v4.2.2 of PHP, with libxml version 2.4.19, set_content does not replace the content of the node, but only appends to it. Bug, feature, who knows!

To replace the content of a node, create a new node, copy the properties and children of the old node to the new one, then set the content of the new one and use replace_node to put it back into the DoM.

Daniel
DomNode::replace_node
DomNode::set_name
DOM XML (PHP 4) Функции


Устанавливает имя узла

DomNode::set_content
DomNode::set_namespace
DOM XML (PHP 4) Функции
PHP Manual

DomNode::set_name

(PHP 4 >= 4.1.0)

DomNode::set_name — Устанавливает имя узла

Описание

bool DomNode::set_name ( void )

Устанавливает имя узла.

См. также domnode_node_name().

User Contributed Notes

There are no user contributed notes for this page.
DomNode::set_content
DomNode::set_namespace
DOM XML (PHP 4) Функции


Устанавливает пространство имен узла

DomNode::set_name
DomNode::unlink_node
DOM XML (PHP 4) Функции
PHP Manual

DomNode::set_namespace

(PHP 4 >= 4.3.0)

DomNode::set_namespace — Устанавливает пространство имен узла

Описание

void DomNode::set_namespace ( string $uri [, string $prefix ] )

Устанавливает пространство имен узла в значение uri. Если объявление пространства имен с этим URI уже есть в одном из родительских узлов, префикс будет взят оттуда, в противном случае префикс будет взят из необязательного аргумента prefix или сгенерирован случайным образом.

См. также domdocument_create_element_ns() и domnode_add_namespace()

User Contributed Notes

There are no user contributed notes for this page.
DomNode::set_name
DomNode::unlink_node
DOM XML (PHP 4) Функции


Удаляет узел

DomNode::set_namespace
DomProcessingInstruction::data
DOM XML (PHP 4) Функции
PHP Manual

DomNode::unlink_node

(PHP 4 >= 4.1.0)

DomNode::unlink_node — Удаляет узел

Описание

void DomNode::unlink_node ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

dajohny at gmail dot com 03-Nov-2008 01:00
<?xml version="1.0"?>
<galleries>
  <gallery title="test" intro="">
    <image/>
    <image/>
  </gallery>
  <gallery title="test1" intro="">
    <image/>
    <image/>
    <image/>
    <image/>
   </gallery>
  <gallery title="test2" intro="">
    <image/>
    <image/>
    <image/>
    <image/>
  </gallery>
</galleries>

<?php
$dom = domxml_open_file($xmlfilename, DOMXML_LOAD_DONT_KEEP_BLANKS)
$x = $dom->get_elements_by_tagname('youtagname');

for($i=0;$i<count($x);$i++)
{
    // to remove a particular node by finding the
    if($x[$i]->get_attribute('title')=="test1")
    {
        $remnode =  $x[$i]->node_name();
        $x[$i]->unlink_node($remnode);
        $dom->dump_file($xmlfilename, false, true);
    }
}

// Final xml will be like this:
?>

<?xml version="1.0"?>
<galleries>
  <gallery title="test" intro="">
    <image/>
    <image/>
  </gallery>
  <gallery title="test2" intro="">
    <image/>
    <image/>
    <image/>
    <image/>
  </gallery>
</galleries>

Njoi :)
starloran at hotmail dot com 01-Oct-2004 06:46
I tried to use unlink_node to delete a node, but it never worked.
However, you can delete a node with this:

function delNode($node){
                   $nud=$node->parent_node();
                   $nud->remove_child($node);
}
phpnotes AT no Spam dot phillfox.net 22-Nov-2002 02:07
Just like dump_node*, this method requres the node as an argument.
Like this:
      $removeThis = $dom->get_element_by_id ('26');
      $unlinked = $removeThis->unlink_node($removeThis);

In the example above, $unlinked seems to be NULL.

I'm using 4.3.0-dev (build: Nov 14 2002 10:13:12) in Module mode on Apache/1.3.24 - Win2000.

* see: http://www.php.net/manual/en/function.domnode-dump-node.php
DomNode::set_namespace
DomProcessingInstruction::data
DOM XML (PHP 4) Функции


Возвращает данные узла ProcessingInstruction

DomNode::unlink_node
DomProcessingInstruction::target
DOM XML (PHP 4) Функции
PHP Manual

DomProcessingInstruction::data

(PHP 4 >= 4.1.0)

DomProcessingInstruction::data — Возвращает данные узла ProcessingInstruction

Описание

string DomProcessingInstruction::data ( void )

Этот метод получает данные узла ProcessingInstruction.

Возвращаемые значения

Возвращает данные ProcessingInstruction.

Переход на PHP 5

Используйте свойство data объекта класса DOMProcessingInstruction.

User Contributed Notes

There are no user contributed notes for this page.
DomNode::unlink_node
DomProcessingInstruction::target
DOM XML (PHP 4) Функции


Возвращает цель узла ProcessingInstruction

DomProcessingInstruction::data
DomXsltStylesheet::process
DOM XML (PHP 4) Функции
PHP Manual

DomProcessingInstruction::target

(PHP 4 >= 4.1.0)

DomProcessingInstruction::target — Возвращает цель узла ProcessingInstruction

Описание

string DomProcessingInstruction::target ( void )

Этот метод получает цель узла ProcessingInstruction.

Возвращаемые значения

Возвращает цель ProcessingInstruction.

Переход на PHP 5

Используйте свойство target объекта класса DOMProcessingInstruction.

User Contributed Notes

There are no user contributed notes for this page.
DomProcessingInstruction::data
DomXsltStylesheet::process
DOM XML (PHP 4) Функции


Применяет XSLT-преобразование к объекту DomDocument

DomProcessingInstruction::target
DomXsltStylesheet::result_dump_file
DOM XML (PHP 4) Функции
PHP Manual

DomXsltStylesheet::process

(PHP 4 >= 4.1.0)

DomXsltStylesheet::process — Применяет XSLT-преобразование к объекту DomDocument

Описание

DomDocument DomXsltStylesheet::process ( DomDocument $xml_doc [, array $xslt_params [, bool $is_xpath_param [, string $profile_filename ]]] )

Применяет XSLT-преобразование к заданному объекту класса DomDocument.

Список параметров

xml_doc

XML документ для преобразования в виде объекта класса DomDocument.

xslt_params

Ассоциативный массив содержащий имена и значения параметров.

is_xpath_param

Если установлен в FALSE, значения массива xslt_params будут заключаться в кавычки. Это поведение по умолчанию. Оно позволяет передать значения в виде PHP строк.

Замечание:

Если строки содержат одновременно и одинарные, и двойные кавычки, необходимо самостоятельно заключить все значения в кавычки и установить значение этого аргумента в TRUE.

profile_filename

Задайте путь к файлу, если требуется сведения профилирования.

Возвращаемые значения

Возвращает результат обработки в виде объекта класса DomDocument.

Переход на PHP 5

Используйте XSLTProcessor::setParameter() и XSLTProcessor::transform-to-doc().

Список изменений

Версия | Описание
4.3.0 | Добавлен аргумент profile_filename.

Смотрите также

  • domxml_xslt_stylesheet() - Создает объект DomXsltStylesheet из строки XSL
  • domxml_xslt_stylesheet_file() - Создает объект DomXsltStylesheet из XML файла
  • domxml_xslt_stylesheet_doc() - Создает объект класса DomXsltStylesheet из объекта DomDocument

User Contributed Notes

msh at 247ms dot com 29-Oct-2006 11:36
Seems that the transformer is not handling "namespace-alias" correctly. I have been trying to generate XSL with my XML/XSL using this nice feature as described here:

http://www.topxml.com/xsl/examplegenss.asp
http://www.w3schools.com/xsl/el_namespace-alias.asp

Not sure if this is "correct" or "wrong" depending on how you look at it - but just make a note of it so you dont spend an entire Sunday trying to figure out what you did wrong since the basic examples aren't working :-)
Thomas Broyer 23-Aug-2005 12:54
Within LibXML/LibXSLT, the values of the parameters passed in to the XSLT stylesheet for processing are treated as being XPath expressions to be applied to the source document. This allows you to pass parameters of type "node-set".

This is actually the same as if you modified your XSLT stylesheet to change the default value of the top-level xsl:param to <xsl:param name="param-name" select="param-value" />

As this behavior might be a bit misleading, the PHP/DOMXML binding defaults to "converting" every parameter value to a string, as if you modified your XSLT stylesheet to change the default value of the top-level xsl:param to <xsl:param name="param-name" select="'param-value'" /> (note the single-quotes around the value and enclosed in double-quotes).

If you want to turn back to the original LibXML/LibXSLT behavior, just pass TRUE as the "is_param_xpath" argument.
regis at nvision dot lu 10-Jun-2004 02:48
Needless to say that xslt_parameters is an associative array. So for instance:

<?php
$document = new DOMDocument('/path/to/xmldata');
// Unfortunately there's no such method for DomXsltStylesheet
$stylesheet = domxml_xslt_stylesheet_file('/path/to/stylesheet');
$params = array(
   'param1' => 'value1'
   ...
   , 'paramN' => 'valueN' );
$result = $stylesheet->process($document, $params);
?>

As far as the param_is_xpath argument is concerned, XPath W3REC doesn't mention any parameter at any time ! That must be a DOM feature, which I'm not keen with yet...

Bye
DomProcessingInstruction::target
DomXsltStylesheet::result_dump_file
DOM XML (PHP 4) Функции


Сохраняет результат XSLT-Преобразования в файл

DomXsltStylesheet::process
DomXsltStylesheet::result_dump_mem
DOM XML (PHP 4) Функции
PHP Manual

DomXsltStylesheet::result_dump_file

(PHP 4 >= 4.1.0)

DomXsltStylesheet::result_dump_file — Сохраняет результат XSLT-Преобразования в файл

Описание

string DomXsltStylesheet::result_dump_file ( DomDocument $xmldoc , string $filename )

С тех пор как DomXsltStylesheet::process стала всегда возвращать достоверный XML DomDocument, не важно, какой метод вывода объявлен в

<xsl:output>
и подобных атрибутах/элементах, от этой функции мало толку, если требуется вывести HTML 4 или текстовые данные.

Эта функция принимает на обработку

<xsl:output method="html|text">
и другие директивы контроля вывода. Смотрите примеры для понимания, как она работает.

Примеры

Пример #1 Сохранение результата XSLT-преобразования в файл

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_file($result, "filename");
?>

Смотрите также

  • DomXsltStylesheet::result_dump_mem
  • DomXsltStylesheet::process

User Contributed Notes

There are no user contributed notes for this page.
DomXsltStylesheet::process
DomXsltStylesheet::result_dump_mem
DOM XML (PHP 4) Функции


Представляет результат XSLT-Преобразования в виде строки

DomXsltStylesheet::result_dump_file
domxml_new_doc
DOM XML (PHP 4) Функции
PHP Manual

DomXsltStylesheet::result_dump_mem

(PHP 4 >= 4.1.0)

DomXsltStylesheet::result_dump_mem — Представляет результат XSLT-Преобразования в виде строки

Описание

string DomXsltStylesheet::result_dump_mem ( DomDocument $xmldoc )

С тех пор как DomXsltStylesheet::process стала всегда возвращать достоверный XML DomDocument, не важно, какой метод вывода объявлен в

<xsl:output>
и подобных атрибутах/элементах, от этой функции мало толку, если требуется вывести HTML 4 или текстовые данные.

Эта функция принимает на обработку

<xsl:output method="html|text">
и другие директивы контроля вывода. Смотрите примеры для понимания, как она работает.

Примеры

Пример #1 Вывод результата XSLT преобразования

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_mem($result);
?>

Смотрите также

  • DomXsltStylesheet::result_dump_file
  • DomXsltStylesheet::process

User Contributed Notes

lsoethout at hotmail dot com 19-Feb-2006 02:43
The function result_dump_mem has a problem with the meta content type tag. It outputs it like this:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

which is not correct X(HT)ML, because it closes with '>' instead of with '/>'.

A way to get the output correct is to use instead of result_dump_mem :

    $domHtmlText = $domTranObj->html_dump_mem();

or, as a second alternative:

    $domHtmlText = $domTranObj->dump_mem(true);
DomXsltStylesheet::result_dump_file
domxml_new_doc
DOM XML (PHP 4) Функции


Создает новый пустой XML документ

DomXsltStylesheet::result_dump_mem
domxml_open_file
DOM XML (PHP 4) Функции
PHP Manual

domxml_new_doc

(PHP 4 >= 4.2.0)

domxml_new_doc — Создает новый пустой XML документ

Описание

DomDocument domxml_new_doc ( string $version )

Создает и возвращает новый пустой DOM документ.

Список параметров

version

Номер XML версии документа.

Возвращаемые значения

Возвращает новый экземпляр класса DomDocument.

User Contributed Notes

There are no user contributed notes for this page.
DomXsltStylesheet::result_dump_mem
domxml_open_file
DOM XML (PHP 4) Функции


Создает объект DOM из XML файла

domxml_new_doc
domxml_open_mem
DOM XML (PHP 4) Функции
PHP Manual

domxml_open_file

(PHP 4 >= 4.2.0)

domxml_open_file — Создает объект DOM из XML файла

Описание

DomDocument domxml_open_file ( string $filename [, int $mode = DOMXML_LOAD_PARSING [, array &$error ]] )

Функция разбирает XML документ из заданного файла.

Список параметров

filename

Путь к XML файлу. Файл доступен только для чтения.

mode

Этот необязательный аргумент можно использовать для переключения поведения функции.

В этом аргументе можно использовать одну из следующих констант: DOMXML_LOAD_PARSING (по умолчанию), DOMXML_LOAD_VALIDATING или DOMXML_LOAD_RECOVERING. Также к нему можно добавить DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES и DOMXML_LOAD_COMPLETE_ATTRS с помощью побитового или.

error

Если используется, может содержать сообщения об ошибках. error должен передаваться по ссылке.

Возвращаемые значения

Возвращает объект класса DomDocument.

Примеры

Пример #1 Открытие XML документа из файла

<?php

if (!$dom = domxml_open_file("example.xml")) {
  echo "Ошибка при разборе документа\n";
  exit;
}

$root = $dom->document_element();
?>

Список изменений

Версия | Описание
4.3.0 | Добавлены аргументы mode и error.

Смотрите также

  • domxml_open_mem() - Создает объект DOM XML документа
  • domxml_new_doc() - Создает новый пустой XML документ

User Contributed Notes

koms at koms dot ru 03-Mar-2009 11:18
The way to order the nodes in XML-files by an attribute (desc or asc):

<?php
// open the XML-file
$xml = domxml_open_file("our_file.xml");

// get the root element
$root = $xml->document_element();
// get the list of the nodes
$nodes = $root->child_nodes();

// create the array 'messages' of the nodes
foreach($nodes as $node)
{
 if ($node->node_name() == 'photo')
 {
     $currentMessage['thumbnail'] = $node->get_attribute('thumbnail');
     $currentMessage['filename'] = $node->get_attribute('filename');
     $currentMessage['idnum'] = $picnum[md5($node->get_attribute('filename'))];
     $messages[] = $currentMessage;
 }
}

// sort all the nodes by idnum (asc/desc is "1: -1" or "-1: 1")
$compare_func = create_function('$a, $b', 'return ($a[\'idnum\']==$b[\'idnum\'])? 0: (($a[\'idnum\']>$b[\'idnum\'])? 1: -1);');
usort($messages, $compare_func);

// create the new XML-data
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("photos");
$root = $doc->append_child($root);
for($ee=0;$ee<count($messages);$ee++)
{
    $msgNode = $root->new_child('photo');
    foreach($messages[$ee] as $description => $result)
    {
        $msgNode->set_attribute($description,$result);
    }
}

// write down the XML-file
$text = $doc->dump_mem(true);
$fp = fopen("our_file.xml","w");
fwrite($fp,$text);
fclose($fp);
?>
A-Wing (info at a-wing dot co dot uk) 16-May-2006 11:23
A very useful undocumented feature if you are opening hundreds of xml docs (my script processes 20,000) is DomDocument->free.
This clears the allocated the memory used by the xml file which is not done automatically by just opening a new file on the same variable.

Example:

<?
$dir="/path/to/xml/files/";
if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
        if(is_file($dir.$file))
        {
            echo $file . "\\n";
            $dom=domxml_open_file($dir.$file);

            #...
            #You xml processor here
            #...
            $dom->free();
        }
    }
    closedir($dh);
}

?>
noyanoya at tin dot it 28-Dec-2005 09:47
another way to resolve path's problem is to use  realpath() function
for example:

<?php
$file=$_REQUEST['file'];
$xmlPath = realpath("../xml/");
$fileXML ="$file";
  if(!$dom = domxml_open_file($xmlPath."/".$fileXML)) {
    echo "error opening the file";
    exit;
}
?>

N.B. you have to put the final slash ( / ) beetween path and file name!
php at gungfu [dot] de 19-Mar-2005 08:13
For me, on Windows XP, the solution with  file_get_contents works, the one with domxml_open_file does not. It seems the latter caches the loaded file. Quite confusing.
contact at richardleggett dot co dot uk 14-Feb-2005 02:00
If you want to work on both Windows and Linux, I found appending the following to the front of your file path works:

$xmlPath = dirname(__FILE__) . "/";
$xmlDOM = domxml_open_file($xmlPath . "file.xml");

(rather than the "\\" in a previous post on this page which only works on Windows).

This should get around the I/O errors.
info at sgonda dot de 30-Oct-2003 01:02
You can load your own DTD's within your XML Doc like this:

<?php
$domxml = domxml_open_file('test.xml',DOMXML_LOAD_VALIDATING,$error);
?>

I hope this helps....

The DocumentType Definition (must/have) to be in the Doc root of your Server...
kevin at ieqdev dot com 15-Jun-2003 04:30
If you're working on a windows machine and don't want to use full paths , just use...

$showfile = file_get_contents($path . "/" . $fileName);

if(!$domDoc = domxml_open_mem($showfile)) {
    echo "Couldn't load xml...";
    exit;
}

Because file_get_contents() can use relative paths on Win, it keeps your code more portable...

twist
et at wkv dot at 24-Feb-2003 08:49
domxml documentation is a moving target, for 4.2.3 a working example is:

<?
$xmlpath = dirname(__FILE__) . "\\";
$xmldoc = domxml_open_file( $xmlpath . "test.xml");
$xsldoc = domxml_xslt_stylesheet_file ( $xmlpath . "test.xsl");
$result = $xsldoc->process($xmldoc);
print $result->dump_mem();
?>

RTFS is a working method in this case (lucky guesses work also from time tor time) :-)
andrew at boxuk dot com 07-Feb-2003 05:32
Using PHP 4.2.3 and Win2K.

The XML file needs to be referenced using the full filesystem path name, even if its in the same directory.
rudolfnospam at redshift dot co dot no dot spam dot za 29-Apr-2002 06:12
Using PHP 4.1.2, Win2K, IIS.
I found that if the path to the XML source file is too long then the file isn't picked up. I haven't tested it to see how long the path can be or whether this is still an issue in PHP 4.2
domxml_new_doc
domxml_open_mem
DOM XML (PHP 4) Функции


Создает объект DOM XML документа

domxml_open_file
domxml_version
DOM XML (PHP 4) Функции
PHP Manual

domxml_open_mem

(PHP 4 >= 4.2.0)

domxml_open_mem — Создает объект DOM XML документа

Описание

DomDocument domxml_open_mem ( string $str [, int $mode [, array &$error ]] )

Функция разбирает XML документ из переданной строки.

Список параметров

str

Содержимое XML файла.

mode

Этот необязательный аргумент может использоваться для изменения режима работы функции.

В качестве аргумента может быть передана одна из констант: DOMXML_LOAD_PARSING (по умолчанию), DOMXML_LOAD_VALIDATING или DOMXML_LOAD_RECOVERING. Также можно добавить константы DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES и DOMXML_LOAD_COMPLETE_ATTRS посредством побитового или.

error

Если используется, может содержать сообщения об ошибках. error должен быть передан по ссылке.

Возвращаемые значения

Возвращает объект класса DomDocument, содержащий данные XML строки.

Список изменений

Версия | Описание
4.3.0 | Добавлены аргументы mode и error.

Примеры

Пример #1 Открытие XML документа из строки

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Ошибка при разборе документа\n";
  exit;
}

$root = $dom->document_element();
?>

Смотрите также

  • domxml_open_file() - Создает объект DOM из XML файла
  • domxml_new_doc() - Создает новый пустой XML документ

User Contributed Notes

msh at onliners dot dk 28-Feb-2005 09:51
It's always nice to see just where in the XML the error is so I've enhanced the error message example above to this:

// Read and parse dynamic PHP/XML document.
ob_start();
require($_REQUEST['page'].'.php');
$xml = ob_get_contents();
ob_end_clean();
$xmldoc = domxml_open_mem("<?xml version='1.0'  encoding='ISO-8859-1'?>".$xml, DOMXML_LOAD_PARSING, $error);
// Show error.
if(!$xmldoc) {
    // Assign each line to array.
    $arXML = explode("\n", $xml);

    echo "<pre>";

    foreach ($error as $errorline) {
        echo $errorline['errormessage'].
        "Node: ".$errorline['nodename']."\n".
        "Line: ".$errorline['line']."\n".
        "Column: ".$errorline['col']."\n";

        // Locate actual line number.
        $arErrorMessage = explode(' line ', $errorline['errormessage']);
        $arErrorMessage = explode(' ', $arErrorMessage[1]);
        $errorLineNumber = $arErrorMessage[0];

        // Show +/- 10 lines around error.
        $minErrorLineNumber = max(0, $errorLineNumber-10);
        $maxErrorLineNumber = min(sizeof($arXML), $errorLineNumber+10);
        echo "XML snip (linies: ".$minErrorLineNumber." to ".$maxErrorLineNumber."):\n";
        for($n = $minErrorLineNumber; $n < $maxErrorLineNumber; $n++)
            if($n == $errorLineNumber)
                echo "<B>".htmlentities($arXML[$n])."</B>\n";
            else
                echo htmlentities($arXML[$n])."\n";
        echo "\n\n";
    }

    echo "</pre>";
}

This will actually render +/- 10 lines around the actual error. Hope others will find this usefull aswell.
Lian Yuen Chi <yuenqi at hotmail dot com> 08-Oct-2004 07:40
Regarding the 'magic_quotes_runtime = On' issue in XML parsing, I will suggest using the method below, for those who do not want to turn off the setting in the configuration file.

<?php

$original-magic-quotes-runtime-value = get_magic_quotes_runtime();

set_magic_quotes_runtime(0);

your-xml-parsing-codes();

set_magic_quotes_runtime($original-magic-quotes-runtime-value);

?>
heiko[dot]weber[at]softwareag[dot]com 19-Aug-2004 02:28
Careful, this function will not work with XML documents which are in UTF-16 or UTF-32 encoding and include a BOM at the beginning, so your code will need a special handling for these encodings.
Carl Wurtz 13-Jul-2004 01:01
A recursive function that parses XML into objects:

<?php

    $xmlstg = '<?xml version="1.0"?';
    $xmlstg .= '><candy><anatomically_shaped><head_to_bite_off>chocolate bunnies</head_to_bite_off><headless>gummi worms</headless></anatomically_shaped></candy>';

    $dom = domxml_open_mem($xmlstg);
    $root = $dom->document_element();
    $root->name = '$candy';
    function parse_node($node) {
        global $candy;
        if ($node->has_child_nodes()) {
            foreach($node->child_nodes() as $n) {
                if ($n->node_name() == '#text') {
                    eval("$node->name=\"" . $n->node_value() . "\";");
                }
                else {
                    $n->name = $node->name . '->' . $n->node_name();
                    parse_node($n);
                }
            }
        }
    }

    parse_node($root);
    echo $candy->anatomically_shaped->head_to_bite_off;
// echos "chocolate bunnies"

?>
voituk [on] asg [dot] kiev [dot] ua 07-Jul-2004 05:48
There is some interesting feature with "magic_quotes_runtime" ini directive and "domxml_open_mem" function.
If we have "magic_quotes_runtime=on" in out php.ini file, this code generates many warning

$xml_str = file_get_contents($xml_file));
$Document = domxml_open_mem($xml_str));

if "magic_quotes_runtime=off" all is good.
ej at campbell *dot* name 30-Nov-2003 07:54
The DOM XML parser does not automatically free memory when a DomDocument goes out of scope.

If you're using the DOM parser to parse several XML files as part of a long running script, you must free the DomDocument manually or a memory leak will occur.

To free a DOM document allocated by domxml_open_mem, do the following:

$doc = domxml_open_mem("$contents");

$doc->free();
chris at schaake dot nu 01-Nov-2003 10:20
Finally figured out the error handling. The sample below will give a nice error message. Should also work for domxml_open_file.

<?
# Small sample xml file with 2 errors
#     1. root tag not closed
#    2. Missing ; in &amp;
$xml = "<root>&amp";

$xmldoc = @domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error);

echo "<pre>";    # Just for nice layout
foreach ($error as $errorline) {    # Loop through all errors
    echo $errorline['errormessage'];
    echo " Node   : " . $errorline['nodename'] . "\n";
    echo " Line   : " . $errorline['line'] . "\n";
    echo " Column : " . $errorline['col'] . "\n\n";
}

?>
jon at hiveminds dot net 16-Oct-2003 10:10
You can also create a new DomDocument instance by calling its constructor:

<?php
  $doc = new DomDocument($xml);
?>

where $xml is any string of well-formed XML.
domxml_open_file
domxml_version
DOM XML (PHP 4) Функции


Получает номер версии XML библиотеки

domxml_open_mem
domxml_xmltree
DOM XML (PHP 4) Функции
PHP Manual

domxml_version

(PHP 4 >= 4.1.0)

domxml_version — Получает номер версии XML библиотеки

Описание

string domxml_version ( void )

Получает версию текущей XML библиотеки.

Возвращаемые значения

Версия XML библиотеки в виде строки.

Примеры

Пример #1 Пример использования domxml_version()

<?php

echo domxml_version();

?>

Результатом выполнения данного примера будет что-то подобное:

20607

User Contributed Notes

There are no user contributed notes for this page.
domxml_open_mem
domxml_xmltree
DOM XML (PHP 4) Функции


Создает дерево объектов PHP из XML документа

domxml_version
domxml_xslt_stylesheet_doc
DOM XML (PHP 4) Функции
PHP Manual

domxml_xmltree

(PHP 4 >= 4.2.0)

domxml_xmltree — Создает дерево объектов PHP из XML документа

Описание

DomDocument domxml_xmltree ( string $str )

Функция разбирает XML документ из строки str и возвращает соответствующее дерево объектов PHP.

Эта функция изолирована от остальных, это означает, что невозможно получить доступ к дереву, используя другие функции. Изменение дерева, например добавление к нему узлов, не имеет смысла, потому как на данный момент нет способа получить из этого дерева обратно XML файл.

Тем не менее, эта функция может оказаться полезной, если требуется только прочитать файл и исследовать содержимое.

Список параметров

str

Содержимое XML файла.

Возвращаемые значения

Возвращает дерево DOM объектов, начиная с DomDocument.

User Contributed Notes

MediaHound 20-Dec-2007 08:49
And, arguably more important:
    Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

    Note: This extension is no longer marked experimental. It will, however, never be released with PHP 5, and will only be distributed with PHP 4. If you need DOM XML support with PHP 5 you can use the DOM extension. This domxml extension is not compatible with the DOM extension.

http://www.php.net/domxml
jeroen dot s at zonnet dot nl 16-May-2006 01:36
You can modify the returned DomDocument, and dump it as an XML file
by using DomDocument->dump_mem() or DomDocument->dump_file().
23-Feb-2005 06:38
Replacing line 10 works well, but replacing line 15 causes some errors. I have a tree like:

<admin>

<user level="0">
<username>admin</username>
<password>admin_pass</password>
</user>
<user level="1">
<username>moder</username>
<password>moder_pass</password>
</user>

</admin>

when I remove those brackets only the last <user> is included into array. In this example it would be
<user level="1">
<username>moder</username>
<password>juozux</password>
</user>

no user name admin, etc.

p.s. I don't store passwords in plain text in xml, that was just an example :))
Alan71 07-Feb-2004 10:05
In the function of nutbar, try to  replace line 10 by
$objptr = $branch->node_value();
and line 15 by :
$objptr = &$object[$branch->node_name()]; //without the '[]'

it makes an array much more easier to read.
Previously, it produces an array like $MyArray[ROOT][0][BRANCH1][0][BRANCH2][0][5], and now $MyArray[ROOT][BRANCH1][BRANCH2][5]. There isn't bugs in the example I use, and I haven't tested with arguments. I think that an implementation of a part of nospam's code is enough.

I hope this will help!
samc a t rampantlabs dot net 27-Dec-2002 12:36
Forgive me if I am mistaken, but the whole point of including the "useless white space" is because of the existence of mixed types, for example:

the schema def:

<xsd:element name="paragraph">
        <xsd:complexType mixed="true">
                <xsd:choice>
                        <xsd:element ref="link" />
                        <xsd:element ref="emphasisText" />
                </xsd:choice>
        </xsd:complexType>
</xsd:element>

and an example:

<paragraph>This here is a paragraph.  You'll notice that it has within it a bunch of text punctuated by other <emphasisText>tags</emphasisText> and it is <link target="me.html>my</url> understanding that the only way to read this text is by reading the tagless nodes that your functions strip.</paragraph>

I could be way off though...
colin at omenmedia dot com 12-Dec-2002 07:03
This is a genuinely useful function, however, as with any DOM-based markup parser, be mindful of the size of the XML document you are parsing.  Representing very large XML files as object structures requires *a lot* of memory and processing, and may even crash your server (which is what happened to my Apache when I tried parsing a 2MB XML file using this function, just for fun... ;).
nospam at candlefire dot org 15-Oct-2002 08:03
Consider the following revisions for including attributes into the array.

function domxml_xmlarray ($branch)
{
    $object = Array ();
    $objptr =& $object;
    $branch = $branch->first_child ();

    while ($branch)
    {
        if (!($branch->is_blank_node()))
        {
            switch ($branch->node_type())
            {
                case XML_TEXT_NODE:
                {
                    $objptr['cdata'] = $branch->node_value ();
                    break;
                }
                case XML_ELEMENT_NODE:
                {
                    $objptr =& $object[$branch->node_name ()][];
                    if ($branch->has_attributes ())
                    {
                        $attributes = $branch->attributes ();
                        if (!is_array ($attributes)) { break; }
                        foreach ($attributes as $index => $domobj)
                        {
                            $objptr[$index] = $objptr[$domobj->name] = $domobj->value;
                        }
                    }
                    break;
                }
            }
            if ($branch->has_child_nodes ()) { $objptr = array_merge ($objptr, domxml_xmlarray ($branch)); }
        }
        $branch = $branch->next_sibling ();
    }

    return $object;
}
nutbar at innocent dot com 13-Oct-2002 12:18
Same concept as previous function, except uses node names as key items in the arrays.  This function may prove a bit more useful than the previous one:

    function domxml_xmlarray($branch) {
        $object = array();
        $objptr = &$object;
        $branch = $branch->first_child();

        while ($branch) {
            if (!($branch->is_blank_node())) {
                switch ($branch->node_type()) {
                    case XML_TEXT_NODE: {
                        $objptr['cdata'] = $branch->node_value();

                        break;
                    }
                    case XML_ELEMENT_NODE: {
                        $objptr = &$object[$branch->node_name()][];

                        break;
                    }
                }

                if ($branch->has_child_nodes()) {
                    $objptr = array_merge($objptr, domxml_xmlarray($branch));
                }
            }

            $branch = $branch->next_sibling();
        }

        return $object;
    }

Usage is identical to the previous function.
domxml_version
domxml_xslt_stylesheet_doc
DOM XML (PHP 4) Функции


Создает объект класса DomXsltStylesheet из объекта DomDocument

domxml_xmltree
domxml_xslt_stylesheet_file
DOM XML (PHP 4) Функции
PHP Manual

domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_doc — Создает объект класса DomXsltStylesheet из объекта DomDocument

Описание

DomXsltStylesheet domxml_xslt_stylesheet_doc ( DomDocument $xsl_doc )

Создает объект класса DomXsltStylesheet из переданного XSL документа.

Список параметров

xsl_doc

XSL документ в виде объекта класса DomDocument.

Возвращаемые значения

Возвращает новый экземпляр класса DomXsltStylesheet.

Переход на PHP 5

Вызывайте XSLTProcessor::importStylesheet() с аргументом xsl_doc.

Смотрите также

  • DomXsltStylesheet::process
  • domxml_xslt_stylesheet() - Создает объект DomXsltStylesheet из строки XSL
  • domxml_xslt_stylesheet_file() - Создает объект DomXsltStylesheet из XML файла

User Contributed Notes

There are no user contributed notes for this page.
domxml_xmltree
domxml_xslt_stylesheet_file
DOM XML (PHP 4) Функции


Создает объект DomXsltStylesheet из XML файла

domxml_xslt_stylesheet_doc
domxml_xslt_stylesheet
DOM XML (PHP 4) Функции
PHP Manual

domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_file — Создает объект DomXsltStylesheet из XML файла

Описание

DomXsltStylesheet domxml_xslt_stylesheet_file ( string $xsl_file )

Создает объект класса DomXsltStylesheet из заданного XML файла.

Список параметров

xsl_file

Путь к XML файлу в виде строки.

Возвращаемые значения

Возвращает новый экземпляр класса DomXsltStylesheet.

Переход на PHP 5

Вызывайте XSLTProcessor::importStylesheet() с аргументом DOMDocument::load($xsl_file).

Смотрите также

  • DomXsltStylesheet::process
  • domxml_xslt_stylesheet() - Создает объект DomXsltStylesheet из строки XSL
  • domxml_xslt_stylesheet_doc() - Создает объект класса DomXsltStylesheet из объекта DomDocument

User Contributed Notes

info at sgonda dot de 29-Oct-2003 11:38
Here's is a example for use:

<?php

$xmldoc = domxml_open_file("dom.xml");
$xsldoc  = domxml_xslt_stylesheet_file ("dom.xsl");
$result   = $xsldoc->process($xmldoc);
 print $result->dump_mem();

?>
domxml_xslt_stylesheet_doc
domxml_xslt_stylesheet
DOM XML (PHP 4) Функции


Создает объект DomXsltStylesheet из строки XSL

domxml_xslt_stylesheet_file
domxml_xslt_version
DOM XML (PHP 4) Функции
PHP Manual

domxml_xslt_stylesheet

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet — Создает объект DomXsltStylesheet из строки XSL

Описание

DomXsltStylesheet domxml_xslt_stylesheet ( string $xsl_buf )

Создает объект класса DomXsltStylesheet из переданного XSL буфера.

Список параметров

xsl_buf

XSL документ в виде строки.

Возвращаемые значения

Возвращает новый экземпляр класса DomXsltStylesheet.

Переход на PHP 5

Вызывайте XSLTProcessor::importStylesheet() с аргументом DOMDocument::loadXML($xsl_buf).

Смотрите также

  • DomXsltStylesheet::process
  • domxml_xslt_stylesheet_file() - Создает объект DomXsltStylesheet из XML файла
  • domxml_xslt_stylesheet_doc() - Создает объект класса DomXsltStylesheet из объекта DomDocument

User Contributed Notes

mdn at heokieng dot com 16-Feb-2003 03:04
This is an exemple to change from XML to HTML by XSL utilising XML_DOM

File XML : Reunions.xml
<?xml version="1.0"?>
<reunions prev_id_reunion="2">
    <reunion id_reunion="0">
        <organisateur>Organisateur 1</organisateur>
        <date>Date 1</date>
        <heure>Heure 1</heure>
        <lieu>Lieu 1</lieu>
        <sujets>
            <sujet>Sujet 11</sujet>
            <sujet>Sujet 12</sujet>
        </sujets>
        <participants>
            <participant>Participant11</participant>
            <participant>Participant12</participant>
        </participants>
    </reunion>
    <reunion id_reunion="1">
        <organisateur>Organisateur 2</organisateur>
        <date>Date 2</date>
        <heure>Heure 2</heure>
        <lieu>Lieu 2</lieu>
        <sujets>
            <sujet>Sujet21</sujet>
            <sujet>Sujet22</sujet>
        </sujets>
        <participants>
            <participant>Participant21</participant>
            <participant>Participant22</participant>
        </participants>
    </reunion>
</reunions>

File PHP : Reunions.PhP
<?php
$StrXsl =    '<?xml version="1.0" encoding="ISO-8859-1"?>'.
            '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">'.
            '<xsl:template match="/">'.
            '<html>'.
                '<head>'.
                    '<title></title>'.
                '</head>'.

                '<body bgcolor="white" text="black" link="blue" vlink="purple" alink="red">'.
                '<div align="center">'.
                    '<font face="Verdana" color="#4682b4" size="+2">La liste des reunions</font>'.
                    '<table border="0" cellpadding="0" cellspacing="0" width="300" bgcolor="#f5fffa">'.
                        '<tr>'.
                            '<th>'.
                                '<div align="center">'.
                                    '<font face="Verdana" color="#4682b4" size="-1">Organisateur</font>'.
                                '</div>'.
                               '</th>'.

                               '<th>'.
                                '<div align="center">'.
                                    '<font face="Verdana" color="#4682b4" size="-1">Date</font>'.
                                '</div>'.
                               '</th>'.

                               '<th>'.
                                '<div align="center">'.
                                    '<font face="Verdana" color="#4682b4" size="-1">Heure</font>'.
                                '</div>'.
                               '</th>'.

                               '<th>'.
                                '<div align="center">'.
                                    '<font face="Verdana" color="#4682b4" size="-1">Lieu</font>'.
                                '</div>'.
                               '</th>'.
                        '</tr>'.
                        '<xsl:apply-templates select="reunions/reunion">'.
                               '<xsl:sort select="organisateur" order="ascending"/>'.
                         '</xsl:apply-templates>'.
                    '</table>'.
                '</div>'.
                '</body>'.

            '</html>'.
            '</xsl:template>'.
            '<xsl:template match="reunion">'.
                '<tr>'.
                       '<td bgcolor="white">'.
                        '<font face="Verdana" color="#4682b4" size="-1"><xsl:value-of select="organisateur"/></font>'.
                       '</td>'.
                       '<td bgcolor="white">'.
                        '<font face="Verdana" color="#4682b4" size="-1"><xsl:value-of select="date"/></font>'.
                       '</td>'.
                       '<td bgcolor="white">'.
                        '<font face="Verdana" color="#4682b4" size="-1"><xsl:value-of select="heure"/></font>'.
                       '</td>'.
                       '<td bgcolor="white">'.
                        '<font face="Verdana" color="#4682b4" size="-1"><xsl:value-of select="lieu"/></font>'.
                       '</td>'.
                 '</tr>'.
            '</xsl:template>'.
            '</xsl:stylesheet>';

//Transformer XML -> HTML par XSL
$CurrentDir = dirname(__FILE__);
$xmldoc = domxml_open_file("$CurrentDir\\Reunions.xml");
$xsldoc = domxml_xslt_stylesheet ($StrXsl);
$result =  $xsldoc->process($xmldoc);
print $xsldoc->result_dump_mem($result);
?>
domxml_xslt_stylesheet_file
domxml_xslt_version
DOM XML (PHP 4) Функции


Получает версию XSLT библиотеки

domxml_xslt_stylesheet
xpath_eval_expression
DOM XML (PHP 4) Функции
PHP Manual

domxml_xslt_version

(PHP 4 >= 4.2.0)

domxml_xslt_version — Получает версию XSLT библиотеки

Описание

int domxml_xslt_version ( void )

Получает версию XSLT библиотеки.

Возвращаемые значения

Возвращает версию XSLT библиотеки в виде числа.

Примеры

Пример #1 Пример использования domxml_xslt_version()

<?php

echo domxml_xslt_version();

?>

Результатом выполнения данного примера будет что-то подобное:

10112

Смотрите также

  • domxml_version() - Получает номер версии XML библиотеки

User Contributed Notes

There are no user contributed notes for this page.
domxml_xslt_stylesheet
xpath_eval_expression
DOM XML (PHP 4) Функции


Вычисляет XPath Location Path в переданной строке

domxml_xslt_version
xpath_eval
DOM XML (PHP 4) Функции
PHP Manual

xpath_eval_expression

(PHP 4)

xpath_eval_expression — Вычисляет XPath Location Path в переданной строке

Описание

XPathObject XPathContext::xpath_eval_expression ( string $expression [, domnode $contextnode ] )
XPathObject xpath_eval_expression ( XPathContext $xpath_context , string $expression [, domnode $contextnode ] )

Пример #1 Пример использования xpath_eval_expression()

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Ошибка при разборе документа\n";
    exit;
}

$xpath = xpath_new_context($dom);
var_dump(xpath_eval_expression($xpath, '/chapter/@language'));

?>

Результат выполнения данного примера:

object(XPathObject)(2) {
   ["type"]=>
   int(1)
   ["nodeset"]=>
   array(1) {
     [0]=>
     object(domattribute)(5) {
       ["type"]=>
       int(2)
       ["name"]=>
       string(8) "language"
       ["value"]=>
       string(2) "en"
       [0]=>
       int(7)
       [1]=>
       int(138004256)
     }
  }
}

См. также xpath_eval().

User Contributed Notes

trotters213 at msn dot com 15-Jan-2009 02:42
For those who use PHP5 and the domxml module of PECL : this function doesn't return the same thing if the result is "empty".

Look at this example using the code and the XML file  :
<?php
/* ...
... code to get a xpath ...
... */
$ret = xpath_eval_expression($xPath, "/some/thing | /other/thing");
var_dump($ret);
?>

If the xpath doesn't match anything :
- In PHP4, this code displays
bool(false)

- In PHP5 (with PECL domxml module) , this code displays
object(XPathObject)#25 (2) {
  ["type"]=>
  int(1)
  ["nodeset"]=>
  array(0) {
  }

which is NOT false !!!
domxml_xslt_version
xpath_eval
DOM XML (PHP 4) Функции


Вычисляет XPath Location Path в переданной строке

xpath_eval_expression
xpath_new_context
DOM XML (PHP 4) Функции
PHP Manual

xpath_eval

(PHP 4)

xpath_eval — Вычисляет XPath Location Path в переданной строке

Описание

XPathObject XPathContext::xpath_eval ( string $xpath_expression [, domnode $contextnode ] )
XPathObject xpath_eval ( XPathContext $xpath_context , string $xpath_expression [, domnode $contextnode ] )

Необязательный аргумент contextnode можно использовать для указания относительных адресов XPath.

См. также xpath_new_context().

User Contributed Notes

marius kreis (email to mariuskreis . de) 08-Jul-2005 07:26
If the namespace is subject to change you can write even more portable code if you extend brandon dot whitehead at orst dot edu's solution like this:

$doc = domxml_open_mem($xml);

$xpath = $doc->xpath_new_context();
$namespace = $xpath->xpath_eval('namespace-uri(//*)')->value; // returns the namespace uri

xpath_register_ns($xpath, "pre", $namespace); // sets the prefix "pre" for the namespace
$obj = $xpath->xpath_eval('//pre:Offer'); // finds all Offer tags

$nodeset = $obj->nodeset;

print_r($nodeset);

This code will determine the namespace of the root element and set a prefix for XPath queries. Thus it doesn't matter if the namespace is changing in your XML (like some webservices do...)
patrikG at home dot net 16-Mar-2004 08:42
Just an example of how to grab XML attributes with xpath - which took me a while to figure out. I'm filtering the returned object function node_content() which is a somewhat quick'n dirty solution, but I don't always need XML's child-parent relationships.

<?php
$xml='<MY_SERVICE>
    <MERCHANDISE>
        <SERVICE TYPE="books">
            <NAME>Ulysses</NAME>
        </SERVICE>
        <SERVICE TYPE="books">
            <NAME>The Poisonwood Bible</NAME>
        </SERVICE>
        <SERVICE TYPE="cars">
            <NAME>Van</NAME>
        </SERVICE>
        <SERVICE TYPE="vehicle sans wheels">
            <NAME>UFO</NAME>
        </SERVICE>
    </MERCHANDISE>
</MY_SERVICE>';

echo "<h4>XML</h4><xmp>";print_r(parse_XML($xml));echo"</xmp>";

function node_content($node,$attribute="content"){
    foreach($node->nodeset as $content){
        $return[]    =    $content->{$attribute};
    }
    return $return;
}

function parse_XML($xml){
    //needs PHP's xPath extension installed
    $dom    =domxml_open_mem($xml);
    $calcX = &$dom->xpath_new_context();
$xml_parsed["merchandise"]=node_content(
        $calcX->xpath_eval("//MERCHANDISE/SERVICE/NAME/text()")
        );
$xml_parsed["service"]=node_content(
        $calcX->xpath_eval("//MERCHANDISE/SERVICE/attribute::TYPE",$calcX)
        ,"value");
    return $xml_parsed;
}
?>

The code above returns:

XML
Array
(
    [merchandise] => Array
        (
            [0] => Ulysses

            [1] => The Poisonwood Bible
            [2] => Van
            [3] => UFO
        )

    [service] => Array
        (
            [0] => books
            [1] => books
            [2] => cars
            [3] => vehicle sans wheels
        )

)
brandon dot whitehead at orst dot edu 06-Sep-2003 01:52
In order to use the default namespace you must understand
how namespace prefixes work.  Prefixes are simply convenient mappies to the namespace URI.

For example, if you set the namespace:

xmlns:xm="http://www.someurl.org"

and you have the following document fragment:

<rootnode><xm:childnode>Text</xm:childnode></rootnode>

this is essentially equivalent to:

<rootnode>
   <http://www.someurl.org:childnode>
      Text
   </http://www.someurl.org:childnode>
</rootnode>

because the namespace URI is what matters, not the namespace prefix.

Unfortuantly, if you have a default namespace:

xmlns="http://www.anotherurl.org"

then all elements without a prefix belong to that namespace, and yet, it appears that PHP, and the underlying LIBXML2 don't let you register a default namespace with

"xpath_register_ns(context, prefix, uri)"

i.e. by leaving the prefix = "".  Therefore, to get around the problem, simply give the default prefix a simple name, such as "pre".

For example, if you have a default namespace declaration such as the following document:

<?xml version="1.0" encoding="UTF-8"?>
<rootname xmlns="http://www.some.org" xml:lang="en-US">
   <childnode>Some text</childnode>
</rootname>

And you want to evaluate the xpath expression:

"/rootname/childnode"

then you need to register the default namespace in PHP like this:

xpath_register_ns(context, "pre", "http://www.some.org");

and then use the following xpath expression:

"/pre:rootname/pre:childnode"

As you can see this is a lot prettier and more intuititive than using the local-name() function.  In addition, it makes your code more portable, because you are guaranteed to always be working on nodes that belong to your explicitly stated namespace, uniquely identified by your URI.
fabiostt[X_AT_X]libero[X_DOT_X].it 06-Sep-2003 10:05
Querying documents closed inside a namespace can be tricky

http://bugs.php.net/bug.php?id=11903
tuxo at gmx dot net 21-May-2003 11:47
PHP Version: 4.3.1

I tried out how to get a part of a xml document with the xpath functions in domxml.
Try the following solution:

<?php
// get dom object
$xmldoc = domxml_open_mem($xml);

// init xpath
$xpath = xpath_new_context($xmldoc);
$xpresult = xpath_eval($xpath, "/root/info");

// dump all nodes directly in plain text
foreach ($xpresult->nodeset as $node)
{
    $newxml .= $node->dump_node($node);
}
?>

If you wanna get a new dom object of the result just add

$newxmldoc = domxml_open_mem($newxml);
tk dot lists at fastmail dot fm 19-Jan-2003 05:46
You can indeed use the result object of xpath_eval(). You just have to be careful to pass the result by reference! (note the ampersand's position).

$objXP = xpath_new_context($objDom)
$objTest = &xpath_eval($objXP,"//lalala");
$objTest->nodeset[0]->set_attribute("test","test data");
echo htlentities($objDom->dump_mem());

just be careful that is you pass around values from $objTest then they also need to be passed by reference.
chregu at php dot net 29-Nov-2002 02:32
If you want to apply an XPath-Expression to a particular node:

$ctx->xpath_eval("xpath",$node);
arthur at ischium dot net 08-Nov-2002 03:54
If you want to get the XPath for a particular node:

function getXPath($node) {
    /* node id is held in a property named '1', this is
    illegal in php so we use a workaround */
    $one = '1';
    $xpath = '';
    while ($parent = $node->parent_node()) {
        $siblings = $parent->child_nodes();
        $index = 1;
        foreach ($siblings as $sibling) {
            if ($sibling->type != XML_ELEMENT_NODE || $sibling->tagname != $node->tagname) continue;
            if ($sibling->$one == $node->$one) {
                $xpath = '/' . $node->tagname . '[' . $index . ']' . $xpath;
                break;
                   }
            $index++;
            }
        $node = $parent;
        }
    return $xpath;
    }
bate at php dot net 04-Oct-2002 04:58
<?
$xml = xmldocfile('file.xml');
$xpath = $xml->xpath_new_context();

/**
* object access
*/
$ret = $xpath->xpath_eval('//tag');

/**
* function access
*/
$ret2 = xpath_eval($xpath, '//tag');

print_r($ret);
print_r($ret2);
?>
sbarnum@pointsystems com 20-Mar-2002 06:33
This function has come in handy for recursively viewing the results of xpath searches.  It iterates through a node and converts it to a big associative array:

/**
* Recursive function to convert xml root node to big assoc array
*/
function xmlnode2array($node) {
    if ($node->type==XML_ELEMENT_NODE) {
        if ($attrArray = $node->attributes()) {
            // parse attributes //
            foreach($attrArray AS $attr) {
                $out['ATTRIBUTE'][$attr->name] = $attr->value;
            }
        }
        if ($childArray = $node->children()) {
            // add child nodes //
            foreach($childArray AS $child) {
                if ($child->type==XML_ELEMENT_NODE) {
                    $out[$child->tagname][] = xmlnode2array($child);
                } else {
                    if ($content = xmlnode2array($child))
                        $out['CONTENT'] = $content;
                }
            }
        }

    } else {
        // this is a CONTENT NODE //
        $out = trim($node->content);
        if (!$out) return false;
    }
    return $out;
}
ziw at ifirst dot ru 22-Oct-2001 05:34
it seems that namespaces are not yet (PHP 4.06) implemented - xpath_eval($cnx,"/ns:tag") does work on w2k and does NOT on linux
sofnology at xtra dot co dot nz 25-Aug-2001 06:45
I hope this little example helps someone out. If the XML data doesn't come thru in the post feel free to contact me via email.

<?
    $p = xslt_create();

    $o += 0;
    $s =  '';
    $s .= "<query type='create'>";
    $s .=     "<resourceClass id='12345678901234567890' displayName='DAISY'>";
    $s .=         "<group family='global' id='kind'>";
    $s .=             "<node id='NODE_A' displayName='Red Ferrari' description='Red always goes faster'/>";
    $s .=         "</group>";
    $s .=     "</resourceClass>";
    $s .=     "<resourceClass id='12345678901234567890' displayName='BETTY'>";
    $s .=         "<group family='global' id='kind'>";
    $s .=             "<node id='NODE_B' displayName='Blue Porsche' description='But Porsches are a drivers car'/>";
    $s .=         "</group>";
    $s .=     "</resourceClass>";
    $s .= "</query>";

    $dom=xmldoc($s);
    $ctx=xpath_new_context($dom);

    $query_xo = xpath_eval($ctx,"count(/query/resourceClass)");
    $num_rc = $query_xo->value;
    echo("<BR>There are $num_rc classes in this list");

    for($x=1; $x <= $num_rc; $x++){
        $query_xo = xpath_eval($ctx,"/query/resourceClass[position()=$x]");
        $query_ns = $query_xo->nodeset;
        $resourceClass_dn = $query_ns[0];

//        echo("<PRE>");
//        print_r( $query_xo );
//        echo("<PRE><HR>");
//        print_r( $query_ns );
//        echo("<PRE><HR>");
//        print_r( $rc_dn );
        echo("<BR>[id::".$resourceClass_dn->get_attribute('id')."][displayName::".$resourceClass_dn->get_attribute('displayName')."]");

    }
?>
mfkahn2_NOSPAM at yahoo dot com 24-Jun-2001 02:35
$ctx = xpath_new_context($doc);
$xpath_nodes = xpath_eval($ctx, "//some_element");

$xpath_nodes->nodeset[i]->set_content($string) allows you to set the node content.  Try it and then do a $doc->dumpmem, you'll see the nodes in the original document are indeed updated properly.

I've used this feature lots.  It does work.
newsforsam at bigfoot dot de 24-May-2001 08:46
xpath_eval() returns only a copy of your document. So you cant for example change the $foo->nodeset[id]->content's of the resulting matches. If you want to, you have to do it yourself by going recursive through your doc, which makes xpath_eval at least useless except for checking if you have to ;).
pking at hoovers dot com 06-Mar-2001 05:22
This is a very (very) minor point, but there is a comma missing in the function definition for xpath_eval.  This being my first experience with xpath, I thought "object xpath context" was refering to a single parameter produced by a previous call to xpath_new_context().  Then I couldn't see where you would add the query (which is actually the context parameter)

So the proper definition should be
array xpath_eval (object xpath, context)

Additionally an example would be nice.  I found one from a post to phpbuilder.com:
-------------------------------
http://www.phpbuilder.com/annotate/message.php3?id=1002772
-------------------------------
Message # 1002772:
Date: 01/02/01 06:40
By: Luis Argerich
Subject: new DOM features im 4.0.4

Just wanted to add that PHP 4.0.4 has improved DOM support including Xpath and
Xpointer support:

Try this:

$xml='SOME XML ....';
$doc=xmldoc($xml);
$ctx=xpath_new_context($doc);
$foo=xpath_eval($ctx,"//title");
print_r($foo);

It returns an object that contains a property called Nodeset with an array of DomNodes with the result of the Xpath expression. print_r($foo) to see the full structure.

4.0.4 has also added Xpointer support, so with Xpath and Xpointer support we can really do a lot of things from PHP to XML files.

Luis.
xpath_eval_expression
xpath_new_context
DOM XML (PHP 4) Функции


Создает новый xpath контекст

xpath_eval
xpath_register_ns_auto
DOM XML (PHP 4) Функции
PHP Manual

xpath_new_context

(PHP 4)

xpath_new_context — Создает новый xpath контекст

Описание

XPathContext xpath_new_context ( domdocument $dom_document )

Создает новый xpath контекст.

Смотрите также

  • xpath_eval() - Вычисляет XPath Location Path в переданной строке

User Contributed Notes

David 09-Aug-2006 03:46
WARNING FOR PHP5 USERS! (if you are having xpath problems)

There seem to be several versions of the DOM library/extension arround, it would appear that the one in this page is for PHP4 only, while this is the one in PHP5:

http://us2.php.net/manual/en/ref.dom.php

See the DOMXPath class for xpath functions.
webmaster at ebinformatique dot com 07-Feb-2006 10:32
Should that not be placed as:
DomDocument->xpath_new_context as it seems to be a method used from a DomDocument object.
augusto at omnitec dot it 22-Jun-2004 10:52
Split easily XPath result into associative array:

function xpath_parser($xml_file, $xpath_query) {

    $xml_file = realpath($xml_file);

    if (file_exists($xml_file)) {

        $doc = domxml_open_file($xml_file);

        $ctx = $doc->xpath_new_context();

        if ($xpathObj = @$ctx->xpath_eval($xpath_query)) {

            $return = array();

            foreach($xpathObj->nodeset as $risultato) {

                $tagName = $risultato->tagname();
                $content = $risultato->get_content();

                if (array_key_exists($tagName, $return)) {

                    $return[$tagName][] = $content;

                }else {

                    if (count($doc->get_elements_by_tagname($tagName)) > 1) {

                        $return[$tagName] = array($content);

                    }else {

                        $return[$tagName] = $content;

                    }
                }
            }

        }else {  return("<b>Error :</b> Wrong XPath query");  }
    }else {  return("<b>Errore :</b> File not exist or wrong filepath!");  }

    return $return;
}

usage:

$xml_file = "./listaCD.xml";
$query = "/listacd/*";

echo "<pre>";
print_r(xpath_parser($xml_file, $query));
echo "</pre>";
27-May-2003 10:16
I found a nice function in XML_sql2xml. With it, you can get, easily,  the result of a xpath expression.

function getXpathValues(&$dom, $expr) {
    $xpth = $dom->xpath_new_context();
        $xnode = xpath_eval($xpth,$expr);
        if (isset ($xnode->nodeset[0])) {
            $firstnode = $xnode->nodeset[0];
            $children = $firstnode->children();
            $value = $children[0]->content;
        return $value;
    }
        else return Null;
}

Usage :

$dom = domxml_open_file('pear.rss');
echo $this->getXpathValues($dom, "//channel/title");
xpath_eval
xpath_register_ns_auto
DOM XML (PHP 4) Функции


Регистрация заданного пространства имен в определенном XPath контексте

xpath_new_context
xpath_register_ns
DOM XML (PHP 4) Функции
PHP Manual

xpath_register_ns_auto

(PHP 4 >= 4.3.0)

xpath_register_ns_auto — Регистрация заданного пространства имен в определенном XPath контексте

Описание

bool xpath_register_ns_auto ( XPathContext $xpath_context [, object $context_node ] )
Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • xpath_register_ns() - Регистрирует пространство имен в переданном XPath контексте

User Contributed Notes

There are no user contributed notes for this page.
xpath_new_context
xpath_register_ns
DOM XML (PHP 4) Функции


Регистрирует пространство имен в переданном XPath контексте

xpath_register_ns_auto
xptr_eval
DOM XML (PHP 4) Функции
PHP Manual

xpath_register_ns

(PHP 4 >= 4.2.0)

xpath_register_ns — Регистрирует пространство имен в переданном XPath контексте

Описание

bool xpath_register_ns ( XPathContext $xpath_context , string $prefix , string $uri )
Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • xpath_register_ns_auto() - Регистрация заданного пространства имен в определенном XPath контексте

User Contributed Notes

There are no user contributed notes for this page.
xpath_register_ns_auto
xptr_eval
DOM XML (PHP 4) Функции


Вычисляет XPtr Location Path в заданной строке

xpath_register_ns
xptr_new_context
DOM XML (PHP 4) Функции
PHP Manual

xptr_eval

(PHP 4)

xptr_eval — Вычисляет XPtr Location Path в заданной строке

Описание

int XPathContext::xptr_eval ( string $eval_str [, domnode $contextnode ] )
int xptr_eval ( XPathContext $xpath_context , string $eval_str [, domnode $contextnode ] )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

Jorrit Kronjee 19-Nov-2003 10:48
Actually xptr_eval works exactly the same as xpath_eval and doesn't return an integer as suggested. I haven't tried anything with it and PHP (4.3.0 for me now) doesn't seem to be any help either. Even simple examples (from http://www.zvon.org/xxl/XPointerTutorial/Output/index.html) don't work, just because half of XPointer is not implemented. XPointer expressions like /1/1 do work.

Let's face it, this is all experimental, folks!
xpath_register_ns
xptr_new_context
DOM XML (PHP 4) Функции


Создает новый контекст XPath

xptr_eval
libxml
DOM XML (PHP 4) Функции
PHP Manual

xptr_new_context

(PHP 4)

xptr_new_context — Создает новый контекст XPath

Описание

XPathContext xptr_new_context ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
xptr_eval
libxml
DOM XML (PHP 4) Функции


libxml

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • libXMLError — Класс libXMLError
  • libxml Функции
    • libxml_clear_errors — Очистка буфера ошибок libxml
    • libxml_disable_entity_loader — Отключение возможности загрузки сущностей из внешних источников
    • libxml_get_errors — Получение массива произошедших ошибок
    • libxml_get_last_error — Извлечение последней ошибки из libxml
    • libxml_set_external_entity_loader — Changes the default external entity loader
    • libxml_set_streams_context — Установка контекста потока для следующей загрузки или записи документа посредством libxml
    • libxml_use_internal_errors — Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю

User Contributed Notes

There are no user contributed notes for this page.
xptr_new_context
Введение
Обработка XML


Введение

Эти функции/константы доступны, начиная с PHP 5.1.0, указанные ниже расширения ядра ссылаются на это libxml расширение: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XSLT, XML, XMLReader, XMLRPC и XMLWriter.

User Contributed Notes

There are no user contributed notes for this page.
libxml
Установка и настройка
libxml


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
libxml


Требования

Это расширение требует для работы » libxml >= 2.6.0.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Расширение libxml включено по умолчанию, но может быть отключено посредством директивы --disable-libxml .

Необязательная директива --with-libxml-dir используется для задания расположения libxml в системах, на которых PHP скомпилирован, если не директива не используется, поиск будет производиться только по стандартным путям. configure процесс производит поиск libxml (особенно, xml2-config) по путям в следующем порядке:

  1. Расположение ([DIR]) заданное с помощью директивы --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

Если configure не найдет xml2-config в директории, заданной директивой --with-libxml-dir , он продолжит поиск по стандартным путям.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

LIBXML_COMPACT (integer)
Активирует оптимизацию выделения памяти для небольших узлов. Это может повысить быстродействие приложения без внесения изменений в коде.

Замечание:

Доступно только в Libxml >= 2.6.21

LIBXML_DTDATTR (integer)
DTD-атрибуты по умолчанию
LIBXML_DTDLOAD (integer)
Загрузка внешнего подмножества
LIBXML_DTDVALID (integer)
Проверка корректности документа с помощью DTD
LIBXML_NOBLANKS (integer)
Удаление пустых узлов
LIBXML_NOCDATA (integer)
Объединить CDATA как текстовые узлы
LIBXML_NOEMPTYTAG (integer)
Разворачивать пустые тэги (например <br/> в <br></br>)

Замечание:

Эта настройка доступна на данный момент только в функциях DOMDocument::save и DOMDocument::saveXML.

LIBXML_NOENT (integer)
Замещение сущностей
LIBXML_NOERROR (integer)
Запретить отчеты об ошибках
LIBXML_NONET (integer)
Отключить доступ к сети во время загрузки документов
LIBXML_NOWARNING (integer)
Запретить предупреждения
LIBXML_NOXMLDECL (integer)
Убрать XML объявление при сохранении документа

Замечание:

Доступна только в Libxml >= 2.6.21

LIBXML_NSCLEAN (integer)
Удалить лишние объявления пространств имен
LIBXML_PARSEHUGE (integer)
Установить флаг XML_PARSE_HUGE, который отключает жестко заданный лимит в парсере. Это затрагивает как лимиты максимальной глубины документа или рекурсии элементов, так и лимиты размеров текстовых элементов.

Замечание:

Доступно только в Libxml >= 2.7.0 (начиная с PHP >= 5.3.2 и PHP >= 5.2.12)

LIBXML_XINCLUDE (integer)
Реализовать XInclude замещение
LIBXML_ERR_ERROR (integer)
Устранимая ошибка
LIBXML_ERR_FATAL (integer)
Фатальная ошибка
LIBXML_ERR_NONE (integer)
Нет ошибок
LIBXML_ERR_WARNING (integer)
Простое предупреждение
LIBXML_VERSION (integer)
Версия libxml в виде 20605 или 20617
LIBXML_DOTTED_VERSION (string)
Версия libxml в виде 2.6.5 или 2.6.17

User Contributed Notes

@oneseventeen 05-Feb-2011 11:51
When inserting XML DOM Elements inside existing XML DOM Elements that I loaded from an XML file using the following code, none of my new elements were formatted correctly, they just showed up on one line:

<?php
$dom = DOMDocument::load('file.xml');
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks normal but the new nodes are all on one line.
?>

I found I could pass LIBXML_NOBLANKS to the load method and it would reformat the whole document, including my added stuff:
<?php
$dom = DOMDocument::load('file.xml', LIBXML_NOBLANKS);
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks newly formatted, including new nodes
?>

Hope this helps, took me hours of trial and error to figure this out!
zachatwork at gmail dot com 09-Feb-2010 11:30
Note: The LIBXML_NOXMLDECL constant is defined in this library but is not supported by DOMDocument (yet).

See also: http://bugs.php.net/bug.php?id=47137

<?php

print "PHP_VERSION:      ".PHP_VERSION."\n";
print "LIBXML_VERSION:   ".LIBXML_VERSION."\n";
print "LIBXML_NOXMLDECL: ".LIBXML_NOXMLDECL."\n";

$dom = new DomDocument();
$dom->loadXML("<foo />");

# This should work but doesn't.

print "DOMDocument doesn't honor LIBXML_NOXMLDECL:\n";
print $dom->saveXML(null,LIBXML_NOXMLDECL);

# This works, and will still work after the above is fixed.

print "Forwards compatible workaround:\n";
$lines = explode("\n", $dom->saveXML(null, LIBXML_NOXMLDECL), 2);
if(!preg_match('/^\<\?xml/', $lines[0]))
    print $lines[0];
print $lines[1];

?>

PHP_VERSION:      5.3.1-0.dotdeb.1
LIBXML_VERSION:   20632
LIBXML_NOXMLDECL: 2
DOMDocument doesn't honor LIBXML_NOXMLDECL:
<?xml version="1.0"?>
<foo/>
Forwards compatible workaround:
<foo/>
Типы ресурсов
libXMLError
libxml


Класс libXMLError

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Содержит различную информацию об ошибках, выбрасываемых libxml. Коды ошибок описаны в официальной » xmlError API документации.

Обзор классов

libXMLError {
/* Свойства */
public int $level ;
public int $code ;
public int $column ;
public string $message ;
public string $file ;
public int $line ;
}

Свойства

level

Важность ошибки (одна из следующих констант: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR или LIBXML_ERR_FATAL)

code

Код ошибки

column

Столбец, в котором произошла ошибка.

Замечание:

Это свойство реализовано в libxml не до конца, поэтому в большинстве случаев будет возвращаться 0.

message

Сообщение об ошибке, если есть.

file

Имя файла либо пустая строка, если XML загружался из строки.

line

Строка, в которой произошла ошибка.

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
libxml Функции
libxml


libxml Функции

Содержание

  • libxml_clear_errors — Очистка буфера ошибок libxml
  • libxml_disable_entity_loader — Отключение возможности загрузки сущностей из внешних источников
  • libxml_get_errors — Получение массива произошедших ошибок
  • libxml_get_last_error — Извлечение последней ошибки из libxml
  • libxml_set_external_entity_loader — Changes the default external entity loader
  • libxml_set_streams_context — Установка контекста потока для следующей загрузки или записи документа посредством libxml
  • libxml_use_internal_errors — Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю

User Contributed Notes

There are no user contributed notes for this page.
libXMLError
libxml_clear_errors
libxml


Очистка буфера ошибок libxml

libxml Функции
libxml_disable_entity_loader
libxml Функции
PHP Manual

libxml_clear_errors

(PHP 5 >= 5.1.0)

libxml_clear_errors — Очистка буфера ошибок libxml

Описание

void libxml_clear_errors ( void )

libxml_clear_errors() очищает буфер ошибок libxml.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • libxml_get_errors() - Получение массива произошедших ошибок
  • libxml_get_last_error() - Извлечение последней ошибки из libxml

User Contributed Notes

There are no user contributed notes for this page.
libxml Функции
libxml_disable_entity_loader
libxml Функции


Отключение возможности загрузки сущностей из внешних источников

libxml_clear_errors
libxml_get_errors
libxml Функции
PHP Manual

libxml_disable_entity_loader

(PHP 5 >= 5.2.11)

libxml_disable_entity_loader — Отключение возможности загрузки сущностей из внешних источников

Описание

bool libxml_disable_entity_loader ([ bool $disable = true ] )

Отключение/включение возможности загружать внешние сущности.

Список параметров

disable

Отключение (TRUE) или включение (FALSE) libxml расширений (также как в DOM, XMLWriter и XMLReader) для загрузки внешних сущностей.

Возвращаемые значения

Возвращает предыдущее значение.

Смотрите также

  • libxml_use_internal_errors() - Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю
  • Константа LIBXML_NONET

User Contributed Notes

simonsimcity 29-Feb-2012 06:23
Using this function you can prevent a vulnerable to Local and Remote File Inclusion attacks.

You'll see it in an example where I load and validate the following string:

<!DOCTYPE scan [<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=/etc/passwd">]>
<scan>&test;</scan>

One way to prevent that the file in given back is to set this value to 0.
Please take a closer look at the release of symfony 2.0.11
libxml_clear_errors
libxml_get_errors
libxml Функции


Получение массива произошедших ошибок

libxml_disable_entity_loader
libxml_get_last_error
libxml Функции
PHP Manual

libxml_get_errors

(PHP 5 >= 5.1.0)

libxml_get_errors — Получение массива произошедших ошибок

Описание

array libxml_get_errors ( void )

Получение массива произошедших ошибок.

Возвращаемые значения

Возвращает массив объектов LibXMLError, если в буфере есть ошибки, либо пустой массив в противном случае.

Примеры

Пример #1 Пример использования libxml_get_errors()

Этот пример демонстрирует, как создать простой обработчик ошибок libxml.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <titles>PHP: Behind the Parser</title>
 </movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if (!$doc) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
    $return  = $xml[$error->line - 1] . "\n";
    $return .= str_repeat('-', $error->column) . "^\n";

    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "Warning $error->code: ";
            break;
         case LIBXML_ERR_ERROR:
            $return .= "Error $error->code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "Fatal Error $error->code: ";
            break;
    }

    $return .= trim($error->message) .
               "\n  Line: $error->line" .
               "\n  Column: $error->column";

    if ($error->file) {
        $return .= "\n  File: $error->file";
    }

    return "$return\n\n--------------------------------------------\n\n";
}

?>

Результат выполнения данного примера:

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

Смотрите также

  • libxml_get_last_error() - Извлечение последней ошибки из libxml
  • libxml_clear_errors() - Очистка буфера ошибок libxml

User Contributed Notes

There are no user contributed notes for this page.
libxml_disable_entity_loader
libxml_get_last_error
libxml Функции


Извлечение последней ошибки из libxml

libxml_get_errors
libxml_set_external_entity_loader
libxml Функции
PHP Manual

libxml_get_last_error

(PHP 5 >= 5.1.0)

libxml_get_last_error — Извлечение последней ошибки из libxml

Описание

LibXMLError libxml_get_last_error ( void )

Извлечение последней ошибки из libxml.

Возвращаемые значения

Возвращает объект LibXMLError, если в буфере есть ошибки, либо FALSE в противном случае.

Смотрите также

  • libxml_get_errors() - Получение массива произошедших ошибок
  • libxml_clear_errors() - Очистка буфера ошибок libxml

User Contributed Notes

There are no user contributed notes for this page.
libxml_get_errors
libxml_set_external_entity_loader
libxml Функции


Changes the default external entity loader

libxml_get_last_error
libxml_set_streams_context
libxml Функции
PHP Manual

libxml_set_external_entity_loader

(PHP 5 >= 5.4.0)

libxml_set_external_entity_loader — Changes the default external entity loader

Описание

void libxml_set_external_entity_loader ( callable $resolver_function )

Changes the default external entity loader.

Список параметров

resolver_function

A callable that takes three arguments. Two strings, a public id and system id, and a context (an array with four keys) as the third argument. This callback should return a resource, a string from which a resource can be opened, or NULL.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 libxml_set_external_entity_loader() example

<?php
$xml = <<<XML
<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar">
<foo>bar</foo>
XML;

$dtd = <<<DTD
<!ELEMENT foo (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
    function ($public, $system, $context) use($dtd) {
        var_dump($public);
        var_dump($system);
        var_dump($context);
        $f = fopen("php://temp", "r+");
        fwrite($f, $dtd);
        rewind($f);
        return $f;
    }
);

$dd = new DOMDocument;
$r  = $dd->loadXML($xml);

var_dump($dd->validate());
?>

Результат выполнения данного примера:

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

Смотрите также

  • libxml_disable_entity_loader() - Отключение возможности загрузки сущностей из внешних источников

User Contributed Notes

There are no user contributed notes for this page.
libxml_get_last_error
libxml_set_streams_context
libxml Функции


Установка контекста потока для следующей загрузки или записи документа посредством libxml

libxml_set_external_entity_loader
libxml_use_internal_errors
libxml Функции
PHP Manual

libxml_set_streams_context

(PHP 5)

libxml_set_streams_context — Установка контекста потока для следующей загрузки или записи документа посредством libxml

Описание

void libxml_set_streams_context ( resource $streams_context )

Установка контекста потока для следующей загрузки или записи документа посредством libxml.

Список параметров

streams_context

Ресурс контекста потока (созданный функцией stream_context_create())

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования libxml_set_streams_context()

<?php

$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

Смотрите также

  • stream_context_create() - Создаёт контекст потока

User Contributed Notes

There are no user contributed notes for this page.
libxml_set_external_entity_loader
libxml_use_internal_errors
libxml Функции


Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю

libxml_set_streams_context
qtdom
libxml Функции
PHP Manual

libxml_use_internal_errors

(PHP 5 >= 5.1.0)

libxml_use_internal_errors — Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю

Описание

bool libxml_use_internal_errors ([ bool $use_errors = false ] )

libxml_use_internal_errors() позволяет отключить стандартные ошибки libxml и включить пользовательскую обработку ошибок.

Список параметров

use_errors

Включает (TRUE) пользовательскую обработку ошибок или отключает ее (FALSE). Отключение также очищает все текущие ошибки libxml.

Возвращаемые значения

Эта функция возвращает предыдущее значение параметра use_errors.

Примеры

Пример #1 Пример использования libxml_use_internal_errors()

Этот пример демонстрирует основное использование ошибок libxml и значение, которое возвращает эта функция.

<?php

// включение обработки ошибок пользователем
var_dump(libxml_use_internal_errors(true));

// загрузка документа
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
    foreach (libxml_get_errors() as $error) {
        // handle errors here
    }

    libxml_clear_errors();
}

?>

Результат выполнения данного примера:

bool(false)

Смотрите также

  • libxml_clear_errors() - Очистка буфера ошибок libxml
  • libxml_get_errors() - Получение массива произошедших ошибок

User Contributed Notes

james at dunmore dot me dot uk 21-Aug-2008 03:03
We use a custom error handler using  set_error_handler()  I found that after I call

libxml_use_internal_errors(false);

It resets my error_handler - not sure if this is a bug or not, I will report it as a bug - however, I needed to repeat my call to set_error_handler

(did confuse me for a while)
B Crawford 03-Oct-2007 06:22
When using this funtion, be sure to clear your internal error buffer. If you dn't and you are using this in a long running process, you may find that all your memory is used up.
libxml_set_streams_context
qtdom
libxml Функции


qtdom

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • qtdom
    • qdom_error — Возвращает строку ошибки из последней операции QDOM или FALSE, если ошибок не было
    • qdom_tree — Создает дерево XML-строки

User Contributed Notes

There are no user contributed notes for this page.
libxml_use_internal_errors
Введение
Обработка XML


Введение

Внимание

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и любую другую относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

Замечание: Для Windows-платформ это расширение недоступно.

Замечание:

Это расширение было перемещено в репозиторий » PECL и больше не поставляется с PHP 5.0.0.

User Contributed Notes

There are no user contributed notes for this page.
qtdom
Установка и настройка
qtdom


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
qtdom


Требования

Необходима библиотека Qt >=2.2.0

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Это расширение не поддерживается и считается умершим. Однако, его исходный код все еще доступен в PECL SVN вот здесь: » http://svn.php.net/viewvc/pecl/qtdom.

Это расширение было перемещено в репозиторий » PECL и больше не поставляется с PHP 5.0.0

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
qtdom
qtdom


qtdom
PHP Manual

qtdom

Содержание

  • qdom_error — Возвращает строку ошибки из последней операции QDOM или FALSE, если ошибок не было
  • qdom_tree — Создает дерево XML-строки

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
qdom_error
qtdom
PHP Manual


Возвращает строку ошибки из последней операции QDOM или FALSE, если ошибок не было

qtdom
qdom_tree
qtdom
PHP Manual

qdom_error

(PHP 4 >= 4.0.5)

qdom_error — Возвращает строку ошибки из последней операции QDOM или FALSE, если ошибок не было

Описание

string qdom_error ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
qtdom
qdom_tree
qtdom


Создает дерево XML-строки

qdom_error
SDO
qtdom
PHP Manual

qdom_tree

(PHP 4 >= 4.0.4)

qdom_tree — Создает дерево XML-строки

Описание

QDomDocument qdom_tree ( string $doc )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

User Contributed Notes

There are no user contributed notes for this page.
qdom_error
SDO
qtdom


Service Data Objects

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Limitations
  • Примеры
    • Basic usage
    • Setting and Getting Property Values
    • Working with Sequenced Data Objects
    • Reflecting on Service Data Objects
  • SDO Функции
    • SDO_DAS_ChangeSummary::beginLogging — Begin change logging
    • SDO_DAS_ChangeSummary::endLogging — End change logging
    • SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject
    • SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary
    • SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject
    • SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on
    • SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type
    • SDO_DAS_DataFactory::addType — Add a new type to a model
    • SDO_DAS_DataFactory::getDataFactory — Get a data factory instance
    • SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary
    • SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property
    • SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property
    • SDO_DAS_Setting::getPropertyName — Get the property name for a changed property
    • SDO_DAS_Setting::getValue — Get the old value for the changed property
    • SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified
    • SDO_DataFactory::create — Create an SDO_DataObject
    • SDO_DataObject::clear — Clear an SDO_DataObject's properties
    • SDO_DataObject::createDataObject — Create a child SDO_DataObject
    • SDO_DataObject::getContainer — Get a data object's container
    • SDO_DataObject::getSequence — Get the sequence for a data object
    • SDO_DataObject::getTypeName — Return the name of the type for a data object.
    • SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object.
    • SDO_Exception::getCause — Get the cause of the exception.
    • SDO_List::insert — Insert into a list
    • SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property
    • SDO_Model_Property::getDefault — Get the default value for the property
    • SDO_Model_Property::getName — Get the name of the SDO_Model_Property
    • SDO_Model_Property::getType — Get the SDO_Model_Type of the property
    • SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship
    • SDO_Model_Property::isMany — Test to see if the property is many-valued
    • SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject
    • SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject.
    • SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object
    • SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject
    • SDO_Model_Type::getBaseType — Get the base type for this type
    • SDO_Model_Type::getName — Get the name of the type
    • SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type
    • SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type
    • SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type
    • SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type
    • SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type
    • SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type
    • SDO_Model_Type::isOpenType — Test to see if this type is an open type
    • SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type
    • SDO_Sequence::getProperty — Return the property for the specified sequence index.
    • SDO_Sequence::insert — Insert into a sequence
    • SDO_Sequence::move — Move an item to another sequence position

User Contributed Notes

There are no user contributed notes for this page.
qdom_tree
Введение
Обработка XML


Введение

Service Data Objects (SDOs) enable PHP applications to work with data from different sources (like a database query, an XML file, and a spreadsheet) using a single interface.

Each different kind of data source requires a Data Access Service (DAS) to provide access to the data in the data source. In your PHP application, you use a DAS to create an SDO instance that represents some data in the data source. You can then set and get values in the SDO instance using the standard SDO interface. Finally, you use a DAS to write the modified data back to a data source, typically the same one.

See the list of Data Access Services for details on those currently available. In addition to the provided DASs, SDO also provides interfaces to enable others to be implemented (see the section on SDO Data Access Services Interface for more details).

This extension is derived from concepts taken from the » Service Data Objects specification. It includes a version of the » Apache Tuscany SDO for C++ project.

The Structure of a Service Data Object

A Service Data Object instance is made up of a tree of data objects. The tree is defined by containment relationships between the data objects. For example, a Company data object might consist of a number of Department data objects and therefore the Company would have a containment relationship to the Departments.

An SDO may also have non-containment references between data objects in the tree. For example, one Employee data object might reference another Employee to identify a career mentor.

As well as data objects referencing each other, they can also have primitive properties. For example, the Company data object might have a property called "name" of type string, for holding the name of the company (for example, "Acme").

Each of these properties of a data object - containment relationships, non-containment references, or primitive properties - may be many-valued or single-valued. In the above examples, Departments is many-valued and the Company name is single-valued.

In PHP, each SDO data object is represented as a PHP object. The properties of the data object can be accessed using either object syntax or associative array syntax. We'll see some examples of this later.

User Contributed Notes

There are no user contributed notes for this page.
SDO
Установка и настройка
SDO


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
SDO


Требования

The SDO extension requires PHP 5.1.0 or higher. It also requires the libxml2 library. Normally libxml2 will already be installed, but if not, it can be downloaded from » http://www.xmlsoft.org/.

User Contributed Notes

jerrywilborn at gmail dot com 21-Apr-2011 09:57
The extension does not compile against PHP 5.3.  Additionally, it uses SoapServer::setObject() which has only been available since PHP 5.2.
Установка и настройка
Установка
Установка и настройка


Установка

Информация по установке этого расширения PECL может быть найдена в главе руководства Установка PECL расширений. Дополнительная информация, такая как новые версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, может быть найдена здесь: » http://pecl.php.net/package/sca_sdo.

Замечание:

Earlier versions of the SDO extension required a separate shared library for the XML DAS. This is now obsolete and any references to php_sdo_das_xml.dll or sdo_das_xml.so should be removed from your php.ini.

Unix systems

  1. The three SDO components - the SDO core, the XML DAS and the Relational DAS - are packaged together with Service Component Architecture (SCA) into one PECL project, SCA_SDO, so you can download SCA and all three parts of SDO with the command:

    pecl install SCA_SDO

    This command will build the SDO shared library as well as installing the PHP files that make up SCA and the SDO Relational DAS.

    If you want to use the latest beta version, then instead run:

    pecl install SCA_SDO-beta

  2. The pecl command automatically installs the SDO module into your PHP extensions directory. To enable the SDO extension you must add the following line to php.ini:

    extension=sdo.so

    For more information about building PECL packages, consult the PECL installation section of the manual.

Building SDO on Linux

This section describes how to build the SDO core and XML DAS on Linux. You would only need to know how to do this if you wish to build a recent version that you have checked out of SVN.

  1. Change to the main extension directory: cd < wherever your sdo code is >

  2. Run phpize, which will set up the environment to compile SDO.

  3. Next, run ./configure; make; make install. Please note, you may need to login as root to install the extension.

  4. Make sure that the module is loaded by PHP, by adding extension=sdo.so to your php.ini file.

User Contributed Notes

Daniel Alvarez Arribas 11-Sep-2010 06:34
The link provided is wrong.

The PECL package is named SCA_SDO, not SCA_SCO.

The correct link is http://pecl.php.net/package/SCA_SDO
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

SDO_DAS_ChangeSummary::NONE=0 (integer)
Represents a change type of 'none'.
SDO_DAS_ChangeSummary::MODIFICATION=1 (integer)
Represents a change type of 'modification'.
SDO_DAS_ChangeSummary::ADDITION=2 (integer)
Represents a change type of 'addition'.
SDO_DAS_ChangeSummary::DELETION=3 (integer)
Represents a change type of 'deletion'.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Limitations
SDO


Limitations

Implementation Limitations

The following are limitations in the current SDO implementation:

  1. There is no support for multi-byte character sets. This will be considered, depending on community requirements, in a Unicode-enabled version of PHP.

SDO Limitations

The following SDO 2.0 concepts are not supported in the current PHP implementation. It is not necessarily the case that these will all be added over time. Their inclusion will depend on community requirements.

  1. Bi-directional relationships.

  2. Type and property alias names.

  3. Read-only properties.

  4. The Helper classes defined in SDO 2.0 are not directly implemented. However equivalent function is provided in a more natural way for PHP. For example the function of CopyHelper::copy() is provided by applying the PHP clone keyword to a data object.

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Примеры
SDO


Примеры

Содержание

  • Basic usage
  • Setting and Getting Property Values
  • Working with Sequenced Data Objects
  • Reflecting on Service Data Objects

User Contributed Notes

There are no user contributed notes for this page.
Limitations
Basic usage
SDO


Basic usage

The examples below assume an SDO created with the schema and instance information shown below, using the XML Data Access Service.

The instance document below describes a single company, called 'MegaCorp', which contains a single department, called 'Advanced Technologies'. The Advanced Technologies department contains three employees. The company employeeOfTheMonth is referencing the second employee, 'Jane Doe'.

<?xml version="1.0" encoding="UTF-8" ?>
<company xmlns="companyNS" name="MegaCorp"
  employeeOfTheMonth="E0003">
  <departments name="Advanced Technologies" location="NY" number="123">
    <employees name="John Jones" SN="E0001"/>
    <employees name="Jane Doe" SN="E0003"/>
    <employees name="Al Smith" SN="E0004" manager="true"/>
  </departments>
</company>

The root element of the schema is a company. The company contains departments, and each department contains employees. Each element has a number of attributes to store things like name, serial number, and so on. Finally, the company also has an IDREF attribute which identifies one of the employees as the 'employeeOfTheMonth'.

<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:sdo="commonj.sdo"
  xmlns:sdoxml="commonj.sdo/xml"
  xmlns:company="companyNS"
  targetNamespace="companyNS">
  <xsd:element name="company" type="company:CompanyType"/>
  <xsd:complexType name="CompanyType">
    <xsd:sequence>
      <xsd:element name="departments" type="company:DepartmentType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="employeeOfTheMonth" type="xsd:IDREF"
      sdoxml:propertyType="company:EmployeeType"/>
  </xsd:complexType>
  <xsd:complexType name="DepartmentType">
    <xsd:sequence>
      <xsd:element name="employees" type="company:EmployeeType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="location" type="xsd:string"/>
    <xsd:attribute name="number" type="xsd:int"/>
  </xsd:complexType>
  <xsd:complexType name="EmployeeType">
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="SN" type="xsd:ID"/>
    <xsd:attribute name="manager" type="xsd:boolean"/>
  </xsd:complexType>
</xsd:schema>

The XML Data Access Service maps the schema to an SDO. Attributes such as "name" become primitive properties, the sequence of employees becomes a many-valued containment relationship, and so on. Note that the containment relationships are expressed as one complex type within another, whereas non-containment references are expressed in terms of ID and IDREF, with a special sdoxml:propertyType attribute specifying the type of the non-containment reference.

User Contributed Notes

There are no user contributed notes for this page.
Примеры
Setting and Getting Property Values
Примеры


Setting and Getting Property Values

The following examples assume $company is the root of a tree of data objects created from the schema and instance document shown above.

Пример #1 Access via property name

Data object properties can be accessed using the object property access syntax. The following sets the company name to 'Acme'.

<?php
$company->name = 'Acme';
?>

Пример #2 Access via property name as array index

We can also access properties using associative array syntax. The simplest form of this uses the property name as the array index. For example, the following sets the company name and gets the employeeOfTheMonth.

<?php
$company['name'] = 'UltraCorp';
$eotm = $company['employeeOfTheMonth'];
?>

Пример #3 Data Object iteration

We can iterate over the properties of a data object using foreach. The following iterates over the properties of the employee of the month.

<?php
  $eotm = $company->employeeOfTheMonth;
  foreach ($eotm as $name => $value) {
      echo "$name: $value\n";
  }
?>

which will output:

name: Jane Doe
SN: E0003

The 'manager' property is not output, because it has not been set.

Пример #4 Access many-valued property by name

Many-valued data object properties can also be accessed using the object property name syntax. The following gets the list of departments.

<?php
$departments = $company->departments;
?>

Пример #5 Many-valued element access

We can access individual elements of many-valued properties using array syntax. The following accesses the first department in the company.

<?php
$ad_tech_dept = $company->departments[0];
?>

Пример #6 Many-valued property iteration

Many-valued properties can also be iterated over using foreach. The following iterates over the company's departments.

<?php
  foreach ($company->departments as $department) {
    // ...
  }
?>

Each iteration will assign the next department in the list to the variable $department.

Пример #7 Chained property access

We can chain property references on a single line. The following sets and gets the name of the first department.

<?php
  $company->departments[0]->name = 'Emerging Technologies';
  $dept_name = $company->departments[0]->name;
?>

Using the associative array syntax, this is equivalent to

<?php
  $company['departments'][0]['name'] = 'Emerging Technologies';
  $dept_name = $company['departments'][0]['name'];
?>

In either case, the dept_name variable is set to 'Emerging Technologies'.

Пример #8 XPath navigation

The associative array index can be an XPath-like expression. Valid expressions are defined by an augmented sub-set of XPath.

Two forms of indexing into many-valued properties are supported. The first is the standard XPath array syntax with the indexing starting at one, the second is an SDO extension to XPath with an index starting at zero. The standard syntax is:

<?php
  $jane_doe = $company["departments[1]/employees[2]"];
?>

and the SDO XPath extension syntax is:

<?php
  $jane_doe = $company["departments.0/employees.1"];
?>

Both these examples get the second employee from the first department.

Пример #9 XPath querying

We can use XPath to query and identify parts of a data object based on instance data. The following retrieves the manager from the 'Advanced Technologies' department.

<?php
 $ad_tech_mgr =
  $company["departments[name='Advanced Technologies']/employees[manager=true]"];
?>

Пример #10 Creating child data objects

A data object can be a factory for its child data objects. A child data object is automatically part of the data graph. The following add a new employee to the 'Advanced Technologies' department.

<?php
  $ad_tech_dept = $company["departments[name='Advanced Technologies']"];
  $new_hire = $ad_tech_dept->createDataObject('employees');
  $new_hire->name = 'John Johnson';
  $new_hire->SN = 'E0005';
  $new_hire->manager = false;
?>

Пример #11 Unset a primitive property

We can use the isset() and unset() functions to test and remove items from the data object.

The following clears the name of the first department.

<?php
  unset($company->departments[0]->name);
?>

Пример #12 Unset a data object

unset can also be used to remove a data object from the tree. The following example shows John Jones leaving the company.

<?php
  unset($company->departments[0]->employees[0]);
?>

Пример #13 Unset a referenced data object

The following removes the 'employeeOfTheMonth' from the company. If this were a containment relationship then the employee would be removed from the company (probably not a good idea to sack your best employee each month!), but since this is a non-containment reference, the employee being referenced will remain in the department in the company, but will no longer be accessible via the employeeOfTheMonth property.

<?php
  if (isset($company->employeeOfTheMonth)) {
    unset($company->employeeOfTheMonth);
  }
?>

Пример #14 Access via property index

Data object properties can be accessed via their property index using array syntax. The property index is the position at which the property's definition appears in the model (in this case the xml schema). We can see from the schema listing above that the company name attribute is the second company property (the SDO interface makes no distinction between XML attributes and elements). The following sets the company name to 'Acme', with the same result as Access via property name

<?php
  $company[1] = 'Acme';
?>

Using the index directly in this way is likely to be fragile. Normally the property name syntax should be preferred, but the property index may be required in special cases.

User Contributed Notes

There are no user contributed notes for this page.
Basic usage
Working with Sequenced Data Objects
Примеры


Working with Sequenced Data Objects

Sequenced data objects are SDOs which can track property ordering across the properties of a data object. They can also contain unstructured text elements (text element which do not belong to any of the SDO's properties). Sequenced data objects are useful for working with XML documents which allow unstructured text (i.e. mixed=true) or if the elements can be interleaved (

<A/><B/><A/>
). This can occur for example when the schema defines maxOccurs>1 on a element which is a complexType with a choice order indicator.

The examples below assume an SDO created with the following schema and instance information, using the XML Data Access Service.

The schema below describes the format of a letter. The letter can optionally contain three properties; date, firstName, and lastName. The schema states mixed="true" which means that unstructured text can be interspersed between the three properties.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

The following is an instance letter document. It contains the three letter properties; date, firstName and lastName, and has unstructured text elements for the address and letter body.

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

When loaded, the letter data object will have the sequence and property indices shown in the table below:

Sequence Index | Property Index:Name | Value
0 | 0:date | March 1, 2005
1 | - | Mutual of Omaha
2 | - | Wild Kingdom, USA
3 | - | Dear
4 | 1:firstName | Casy
5 | 2:lastName | Crocodile
6 | - | Please buy more shark repellent.
7 | - | Your premium is past due.

To ensure sequence indices are maintained, sequenced data objects should be manipulated through the SDO_Sequence interface. This allows the data object's instance data to be manipulated in terms of the sequence index as opposed to the property index (shown in the table above). The following examples assume the letter instance has been loaded into a data object referenced by the variable $letter.

Пример #1 Getting the SDO_Sequence interface

We obtain a data object's sequence using the getSequence() method. The follow gets the sequence for the letter data object.

<?php
  $letter_seq = $letter->getSequence();
?>

All subsequent examples assume that the $letter_seq variable has been assigned the sequence for the letter data object.

Пример #2 Get/set sequence values

We can get and set individual values (including unstructured text) using the sequence index. The following sets the firstName to 'Snappy' and gets the last sequence values (the unstructured text, 'Your premium is past due.').

<?php
  $letter_seq[4] = 'Snappy';
  $text = $letter_seq[count($letter_seq) - 1];
?>

Пример #3 Sequence iteration

We can iterate through the individual sequence values using foreach. The following runs through the individual values in sequence order.

<?php
foreach ($letter->getSequence() as $value) {
    // ...
}
?>

Пример #4 Sequence versus Data Object

Setting values through the data object interface may result in the value not being part of the sequence. A value set through the data object will only be accessible through the sequence if the property was already part of the sequence. The following example sets the lastName through the data object and gets it through the sequence. This is fine because lastName already exists in the sequence. If it had not previously been set, then lastName would be set to 'Smith', but would not be part of the sequence.

<?php
  $letter[2] = 'Smith';
  $last_name = $letter_seq[5];
?>

Пример #5 Adding to a sequence

We can add new values to a sequence using the SDO_Sequence::insert() method. The following examples assume that the 'firstName' and 'lastName' properties are initially unset.

<?php
  // Append a firstName value to the sequence
  // value: 'Smith'
  // sequence index: NULL (append)
  // propertyIdentifier: 1 (firtName property index)
  $letter_seq->insert('Smith', NULL, 1);

  // Append a lastName value to the sequence
  // value: 'Jones'
  // sequence index: NULL (append)
  // propertyIdentifier: 'lastName' (lastName property name)
  $letter_seq->insert('Jones', NULL, 'lastName');

  // Append unstructured text
  // value: 'Cancel Subscription.'
  // sequence index: absent (append)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq->insert('Cancel Subscription.');

  // Insert new unstructured text.  Subsequent sequence values
  // are shifted up.
  // value: 'Care of:'
  // sequence index: 1 (insert as second element)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq->insert('Care of:', 1);
?>

Пример #6 Removing from a sequence

We can use the isset() and unset() functions to test and remove items from the sequence (Note: unset() currently leaves the values in the data object, but this behaviour is likely to change to also remove the data from the data object). A sequence behaves like a contiguous list; therefore, removing items from the middle will shift entries at higher indices down. The following example tests to see if the first sequence element is set and unsets it if is.

<?php
  if (isset($letter_seq[0])) {
    unset($letter_seq[0]);
  }
?>

User Contributed Notes

There are no user contributed notes for this page.
Setting and Getting Property Values
Reflecting on Service Data Objects
Примеры


Reflecting on Service Data Objects

SDOs have a knowledge of the structure they have been created to represent (the model). For example, a Company SDO created using the Company XML schema above would only be permitted to contain DepartmentType data objects which in turn could only contain EmployeeType data objects.

Sometimes it is useful to be able to access this model information at runtime. For example, this could be used to automatically generate a user interface for populating a data object. The model information is accessed using reflection.

Пример #1 Reflecting on a Data Object

The following example shows how we can reflect on an empty Employee data object.

<?php
  // Create the employee data object (e.g. from an XML Data Access Service)
  $employee = ...;
  $reflection = new SDO_Model_ReflectionDataObject($employee);
  print($reflection);
?>

Результат выполнения данного примера:

object(SDO_Model_ReflectionDataObject)#4 { - ROOT OBJECT - Type {
companyNS:EmployeeType[3] { commonj.sdo:String $name;
commonj.sdo:String $SN; commonj.sdo:Boolean $manager; } }

Using print on the SDO_Model_ReflectionDataObject writes out the data object's model. We can see from the output how the type companyNS:EmployeeType has three properties and we can see the names of the properties along with their types. Note, the primitive types are listed as SDO types (e.g. commonj.sdo namespace, String type). It is worth noting that this is the SDO model and when these are surfaced to an application they can be treated as the PHP equivalent types (e.g. string and boolean).

Пример #2 Accessing the type information

We can query the type information of a data object using reflection. The following example checks the type corresponds to a data object rather than a primitive and then iterates through the properties of the type, writing out the name of each property ($type and $property are SDO_Model_Type and SDO_Model_Property objects, respectively).

<?php
    // Create the employee data object (e.g. from an XML Data Access Service)
    $employee = ...;
    $reflection = new SDO_Model_ReflectionDataObject($employee);
    $type = $reflection->getType();
    if (! $type->isDataType()) {
        foreach ($type->getProperties() as $property) {
            print $property->getName() . "\n";
        }
    }
?>

Результат выполнения данного примера:

name
SN
manager

User Contributed Notes

There are no user contributed notes for this page.
Working with Sequenced Data Objects
SDO Функции
Примеры


SDO Функции

Data Access Services

The table below lists the currently provided SDO Data Access Services:

DAS Name | Description
SDO_DAS_XML | An XML Data Access Service supporting reading/writing SDOs as XML documents.
SDO_DAS_Relational | A PDO-based Data Access Service supporting reading/writing SDO to relational databases. Implements an optimistic concurrency policy for updates.

Предопределенные классы

SDO consists of three sets of interfaces. The first set covers those interfaces for use by typical SDO applications. These are identified by the package prefix 'SDO_'. The second set is those used to reflect on, and work with, the model of a data object. These are identified by the package prefix 'SDO_Model_'. Finally, the third set are those use by Data Access Service implementations and are identified by the package prefix 'SDO_DAS_'. The majority of SDO users will not need to use or understand the 'SDO_Model_' and 'SDO_DAS_' interfaces.

SDO Application Programmer Interface

SDO_DataObject

The main interface through which data objects are manipulated. In addition to the methods below, SDO_DataObject extends the ArrayAccess, SDO_PropertyAccess (defines __get() / __set() methods for property access overloading), Iterator, and Countable interfaces.

Методы

  • getSequence - get the sequence for the data object

  • createDataObject - create a child data object

  • clear - unset the properties of a data object

  • getContainer - get the container (also known as 'parent') of this data object

  • getTypeName - get the name of the type for this data object

  • getTypeNamespaceURI - get the namespace URI of the type for this data object

SDO_Sequence

The interface through which sequenced data objects can be accessed to preserve ordering across a data object's properties and to allow unstructured text. SDO_Sequence preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down. In addition to the methods below, SDO_Sequence extends the ArrayAccess, Iterator and Countable interface.

Методы

  • getProperty - get the property for a given sequence index

  • move - move an element from one property index to another

  • insert - insert a new value into the sequence

SDO_List

The interface through which many-valued properties are manipulated. In addition to the method defined below, SDO_List extends ArrayAccess, Iterator and Countable. SDO_List preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down.

Методы

  • insert - insert a new value into the list

SDO_DataFactory

The interface through which data objects can be created. A Data Access Service is responsible for populating the model (i.e. configuring the data factory with the type and structure information for the data objects it can create.) for the factory and can then optionally return an instance of, or implement, the SDO_DataFactory interface.

Методы

  • create - create a new data object

SDO_Exception

An SDO_Exception is thrown when the caller's request cannot be completed. The subclasses of SDO_Exception are:

  • SDO_PropertyNotSetException - the property specified exists but has not been set or does not have a default value

  • SDO_PropertyNotFoundException - the property specified is not part of the data object's type

  • SDO_TypeNotFoundException - the specified namespace URI or type name is unknown

  • SDO_InvalidConversionException - conversion between the types of the assignment is not possible

  • SDO_IndexOutOfBoundsException - the numeric index into a data object, sequence or list is not in the valid range

  • SDO_UnsupportedOperationException - the request cannot be completed because it is not allowed, for example an attempt to set a read-only property.

Методы

One method is added to those inherited from the built in Exception class:

  • getCause - get the cause of this SDO_Exception

SDO Reflection Application Programmer Interfaces

SDO_Model_ReflectionDataObject

The main interface used to reflect on a data object instance to obtain its model type and property information. It is designed to follow the reflection pattern introduced in PHP 5.

Конструктор

  • __construct - construct a new SDO_Model_ReflectionDataObject.

Методы

  • export - get a string describing the data object.

  • getType - get the SDO_Model_Type for the data object.

  • getInstanceProperties - get the instance properties of the data object.

  • getContainmentProperty - get the property which defines the containment relationship to the data object.

SDO_Model_Type

The interface through which a data object's type information can be retrieved. This interface can be used to find out the type name and namespace URI of the type, whether the type allow open content, and so on.

Методы

  • getName - get the name of the type.

  • getNamespaceURI - get the namespace URI of the type.

  • isInstance - test for a data object being an instance of the type.

  • getProperties - get the properties of the type.

  • getProperty - get a property of the type.

  • isDataType - test to see if this type is a primitive scalar type.

  • isSequencedType - test to see if this is a sequenced type.

  • isOpenType - test to see if this is an open type.

  • isAbstractType - test to see if this is an abstract type.

  • getBaseType - get the base type of this type (if one exists).

SDO_Model_Property

The interface through which a data object's property information can be retrieved. This interface can be used to find out the type of a property, whether a property has a default value, whether the property is contained or reference by its parent, its cardinality, and so on.

Методы

  • getName - get the name of the property.

  • getType - get the type of the property.

  • isMany - test to see if the property is many-valued.

  • isContainment - test to see if the property describes a containment relationship.

  • getContainingType - get the type which contains this property.

  • getDefault - get the default value for a property.

SDO Data Access Service Developer Interfaces

SDO_DAS_DataObject

The interface through which a Data Access Service can access a data object's SDO_DAS_ChangeSummary. The change summary is used by the Data Access Service to check for conflicts when applying changes back to a data source.

Методы

  • getChangeSummary - get the change summary for a data object

SDO_DAS_ChangeSummary

The interface through which the change history of a data object is accessed. The change summary holds information for any modifications on a data object which occurred since logging was activated. In the case of deletions and modifications, the old values are also held in the change summary.

If logging is no longer active then the change summary only holds changes made up to the point when logging was deactivated. Reactivating logging clears the change summary. This is useful when a set of changes have been written out by a DAS and the data object is to be reused.

Методы

  • beginLogging - begin logging changes made to a data object

  • endLogging - end logging changes made to a data object

  • isLogging - test to see if change logging is on

  • getChangedDataObjects - get a list of the data objects which have been changed

  • getChangeType - get the type of change which has been made to a data object

  • getOldValues - get a list of old values for a data object

  • getOldContainer - get the old container data object for a deleted data object

SDO_DAS_Setting

The interface through which the old value for a property is accessed. A list of settings is returned by the change summary method getOldValues.

Методы

  • getPropertyIndex - get the property index for the changed property

  • getPropertyName - get the property name for the changed property

  • getValue - get the old value for the changed property

  • getListIndex - get the list index for the old value if it was part of a many-valued property

  • isSet - test to see if the property was set prior to being modified

SDO_DAS_DataFactory

The interface for constructing the model for an SDO_DataObject. The SDO_DAS_DataFactory is an abstract class providing a static method which returns a concrete data factory implementation. The implementation is used by Data Access Services to create an SDO model from their model. For example, a Relational Data Access Service might create and populate an SDO_DAS_DataFactory model based on a schema for a relational database.

Методы

  • getDataFactory - static methods for getting a concrete data factory instance

  • addType - add a new type to the SDO model

  • addPropertyToType - add a new property to a type definition in the SDO model

Содержание

  • SDO_DAS_ChangeSummary::beginLogging — Begin change logging
  • SDO_DAS_ChangeSummary::endLogging — End change logging
  • SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject
  • SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary
  • SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject
  • SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject
  • SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on
  • SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type
  • SDO_DAS_DataFactory::addType — Add a new type to a model
  • SDO_DAS_DataFactory::getDataFactory — Get a data factory instance
  • SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary
  • SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property
  • SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property
  • SDO_DAS_Setting::getPropertyName — Get the property name for a changed property
  • SDO_DAS_Setting::getValue — Get the old value for the changed property
  • SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified
  • SDO_DataFactory::create — Create an SDO_DataObject
  • SDO_DataObject::clear — Clear an SDO_DataObject's properties
  • SDO_DataObject::createDataObject — Create a child SDO_DataObject
  • SDO_DataObject::getContainer — Get a data object's container
  • SDO_DataObject::getSequence — Get the sequence for a data object
  • SDO_DataObject::getTypeName — Return the name of the type for a data object.
  • SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object.
  • SDO_Exception::getCause — Get the cause of the exception.
  • SDO_List::insert — Insert into a list
  • SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property
  • SDO_Model_Property::getDefault — Get the default value for the property
  • SDO_Model_Property::getName — Get the name of the SDO_Model_Property
  • SDO_Model_Property::getType — Get the SDO_Model_Type of the property
  • SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship
  • SDO_Model_Property::isMany — Test to see if the property is many-valued
  • SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject
  • SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject.
  • SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object
  • SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject
  • SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject
  • SDO_Model_Type::getBaseType — Get the base type for this type
  • SDO_Model_Type::getName — Get the name of the type
  • SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type
  • SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type
  • SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type
  • SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type
  • SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type
  • SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type
  • SDO_Model_Type::isOpenType — Test to see if this type is an open type
  • SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type
  • SDO_Sequence::getProperty — Return the property for the specified sequence index.
  • SDO_Sequence::insert — Insert into a sequence
  • SDO_Sequence::move — Move an item to another sequence position

User Contributed Notes

ng4rrjanbiah at rediffmail dot com 17-Mar-2006 10:07
Some useful links on SDO:
1. Quick intro ( http://www.obalweb.net/wppro/?p=19 )
2. SDO for Zend Conf 2005 ( http://www.ibm.com/developerworks/forums/weblogs/data/SDOforZendConf2005.pdf ), Presentation, [481 KB], Graham Charters, 2005-10-18
3. Introducing Service Data Objects for PHP ( http://www.zend.com/pecl/tutorials/sdo.php ), 2005-08-05
4. Service Data Objects specification ( http://www.ibm.com/developerworks/library/specification/j-commonj-sdowmt/ ), 2003-2005

HTH,
R. Rajesh Jeba Anbiah
Reflecting on Service Data Objects
SDO_DAS_ChangeSummary::beginLogging
SDO


Begin change logging

SDO Функции
SDO_DAS_ChangeSummary::endLogging
SDO Функции
PHP Manual

SDO_DAS_ChangeSummary::beginLogging

(^)

SDO_DAS_ChangeSummary::beginLogging — Begin change logging

Описание

void SDO_DAS_ChangeSummary::beginLogging ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Begin logging changes made to the SDO_DataObject.

Список параметров

None.

Возвращаемые значения

None.

User Contributed Notes

There are no user contributed notes for this page.
SDO Функции
SDO_DAS_ChangeSummary::endLogging
SDO Функции


End change logging

SDO_DAS_ChangeSummary::beginLogging
SDO_DAS_ChangeSummary::getChangeType
SDO Функции
PHP Manual

SDO_DAS_ChangeSummary::endLogging

(^)

SDO_DAS_ChangeSummary::endLogging — End change logging

Описание

void SDO_DAS_ChangeSummary::endLogging ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

End logging changes made to an SDO_DataObject.

Список параметров

None.

Возвращаемые значения

None.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_ChangeSummary::beginLogging
SDO_DAS_ChangeSummary::getChangeType
SDO Функции


Get the type of change made to an SDO_DataObject

SDO_DAS_ChangeSummary::endLogging
SDO_DAS_ChangeSummary::getChangedDataObjects
SDO Функции
PHP Manual

SDO_DAS_ChangeSummary::getChangeType

(^)

SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject

Описание

int SDO_DAS_ChangeSummary::getChangeType ( SDO_DataObject $dataObject )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the type of change which has been made to the supplied SDO_DataObject.

Список параметров

dataObject

The SDO_DataObject which has been changed.

Возвращаемые значения

The type of change which has been made. The change type is expressed as an enumeration and will be one of the following four values:

  • SDO_DAS_ChangeSummary::NONE

  • SDO_DAS_ChangeSummary::MODIFICATION

  • SDO_DAS_ChangeSummary::ADDITION

  • SDO_DAS_ChangeSummary::DELETION

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_ChangeSummary::endLogging
SDO_DAS_ChangeSummary::getChangedDataObjects
SDO Функции


Get the changed data objects from a change summary

SDO_DAS_ChangeSummary::getChangeType
SDO_DAS_ChangeSummary::getOldContainer
SDO Функции
PHP Manual

SDO_DAS_ChangeSummary::getChangedDataObjects

(^)

SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary

Описание

SDO_List SDO_DAS_ChangeSummary::getChangedDataObjects ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get an SDO_List of the SDO_DataObjects which have been changed. These data objects can then be used to identify the types of change made to each, along with the old values.

Список параметров

None.

Возвращаемые значения

Returns an SDO_List of SDO_DataObjects.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_ChangeSummary::getChangeType
SDO_DAS_ChangeSummary::getOldContainer
SDO Функции


Get the old container for a deleted SDO_DataObject

SDO_DAS_ChangeSummary::getChangedDataObjects
SDO_DAS_ChangeSummary::getOldValues
SDO Функции
PHP Manual

SDO_DAS_ChangeSummary::getOldContainer

(^)

SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject

Описание

SDO_DataObject SDO_DAS_ChangeSummary::getOldContainer ( SDO_DataObject $data_object )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the old container (SDO_DataObject) for a deleted SDO_DataObject.

Список параметров

data_object

The SDO_DataObject which has been deleted and whose container we wish to identify.

Возвращаемые значения

The old containing data object of the deleted SDO_DataObject.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_ChangeSummary::getChangedDataObjects
SDO_DAS_ChangeSummary::getOldValues
SDO Функции


Get the old values for a given changed SDO_DataObject

SDO_DAS_ChangeSummary::getOldContainer
SDO_DAS_ChangeSummary::isLogging
SDO Функции
PHP Manual

SDO_DAS_ChangeSummary::getOldValues

(^)

SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject

Описание

SDO_List SDO_DAS_ChangeSummary::getOldValues ( SDO_DataObject $data_object )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get a list of the old values for a given changed SDO_DataObject. Returns a list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject.

Список параметров

data_object

The data object which has been changed.

Возвращаемые значения

A list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject. If the change type is SDO_DAS_ChangeSummary::ADDITION, this list is empty.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_ChangeSummary::getOldContainer
SDO_DAS_ChangeSummary::isLogging
SDO Функции


Test to see whether change logging is switched on

SDO_DAS_ChangeSummary::getOldValues
SDO_DAS_DataFactory::addPropertyToType
SDO Функции
PHP Manual

SDO_DAS_ChangeSummary::isLogging

(^)

SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on

Описание

bool SDO_DAS_ChangeSummary::isLogging ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test to see whether change logging is switched on.

Список параметров

None.

Возвращаемые значения

Returns TRUE if change logging is on, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_ChangeSummary::getOldValues
SDO_DAS_DataFactory::addPropertyToType
SDO Функции


Adds a property to a type

SDO_DAS_ChangeSummary::isLogging
SDO_DAS_DataFactory::addType
SDO Функции
PHP Manual

SDO_DAS_DataFactory::addPropertyToType

(^)

SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type

Описание

void SDO_DAS_DataFactory::addPropertyToType ( string $parent_type_namespace_uri , string $parent_type_name , string $property_name , string $type_namespace_uri , string $type_name [, array $options ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Adds a property to a type. The type must already be known to the SDO_DAS_DataFactory (i.e. have been added using addType()). The property becomes a property of the type. This is how the graph model for the structure of an SDO_DataObject is built.

Список параметров

parent_type_namespace_uri

The namespace URI for the parent type.

parent_type_name

The type name for the parent type.

property_name

The name by which the property will be known in the parent type.

type_namespace_uri

The namespace URI for the type of the property.

type_name

The type name for the type of the property

options

This array holds one or more key=>value pairs to set attribute values for the property. The optional keywords are:

many

A flag to say whether the property is many-valued. A value of 'true' adds the property as a many-valued property (default is 'false').

readOnly

A flag to say whether the property is read-only. A value of 'true' means the property value cannot be modified through the SDO application APIs (default is 'false').

containment

A flag to say whether the property is contained by the parent. A value of 'true' means the property is contained by the parent. A value of 'false' results in a non-containment reference (default is 'true'). This flag is only interpreted when adding properties which are data object types, otherwise it is ignored.

default

A default value for the property. Omitting this key means that the property does not have a default value. A property can only have a default value if it is a single-valued data type (primitive).

Возвращаемые значения

None.

Список изменений

Версия | Описание
0.5.2 | Optional parameters many, readOnly, and containment deprecated in favour of the options array.

Примеры

Пример #1 A SDO_DAS_DataFactory::addPropertyToType() example

The following adds an 'addressline' property to a Person type. The person type is identified by its namespace, 'PersonNS', and type name, 'PersonType'. The type of the 'addressline' property is a many-valued SDO data type (primitive) with namespace 'commonj.sdo' and type name 'String'.

<?php
  $df->addPropertyToType('PersonNS', 'PersonType',
    'addressline', 'commonj.sdo', 'String', array('many'=>true));
?>

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_ChangeSummary::isLogging
SDO_DAS_DataFactory::addType
SDO Функции


Add a new type to a model

SDO_DAS_DataFactory::addPropertyToType
SDO_DAS_DataFactory::getDataFactory
SDO Функции
PHP Manual

SDO_DAS_DataFactory::addType

(^)

SDO_DAS_DataFactory::addType — Add a new type to a model

Описание

void SDO_DAS_DataFactory::addType ( string $type_namespace_uri , string $type_name [, array $options ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Add a new type to the SDO_DAS_DataFactory, defined by its namespace and type name. The type becomes part of the model of data objects that the data factory can create.

Список параметров

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

options

This array holds one or more key=>value pairs to set attribute values for the type. The optional keywords are:

open

A flag to say whether the type is open. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content such as that described by an <xsd:any> element. The default value is 'false'.

sequenced

A flag to say whether the type is sequenced. Sequenced types can have the ordering across properties preserved and can contain unstructured text. The default value is 'false'. For more information on sequenced types see the section on Working with Sequenced Data Objects.

basetype

If specified, an array of namespace URI and type name strings for the type from which this type is derived. An example of the use of base types is when a type derived in an XML schema inherits from another type by using <extension base="...">.

Возвращаемые значения

None.

Примеры

Пример #1 A SDO_DAS_DataFactory::addType() example

The following adds a new data object type of 'CompanyType' where that type belongs to the namespace 'CompanyNS'.

<?php
  $df->addType('CompanyNS', 'CompanyType');
?>

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_DataFactory::addPropertyToType
SDO_DAS_DataFactory::getDataFactory
SDO Функции


Get a data factory instance

SDO_DAS_DataFactory::addType
SDO_DAS_DataObject::getChangeSummary
SDO Функции
PHP Manual

SDO_DAS_DataFactory::getDataFactory

(^)

SDO_DAS_DataFactory::getDataFactory — Get a data factory instance

Описание

SDO_DAS_DataFactory SDO_DAS_DataFactory::getDataFactory ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Static method to get an instance of an SDO_DAS_DataFactory. This instance is initially only configured with the basic SDO types. A Data Access Service is responsible for populating the data factory model and then allowing PHP applications to create SDOs based on the model through the SDO_DataFactory interface. PHP applications should always obtain a data factory from a configured Data Access Service, not through this interface.

Список параметров

None.

Возвращаемые значения

Returns an SDO_DAS_DataFactory.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_DataFactory::addType
SDO_DAS_DataObject::getChangeSummary
SDO Функции


Get a data object's change summary

SDO_DAS_DataFactory::getDataFactory
SDO_DAS_Setting::getListIndex
SDO Функции
PHP Manual

SDO_DAS_DataObject::getChangeSummary

(^)

SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary

Описание

SDO_DAS_ChangeSummary SDO_DAS_DataObject::getChangeSummary ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

Список параметров

None.

Возвращаемые значения

Returns the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_DataFactory::getDataFactory
SDO_DAS_Setting::getListIndex
SDO Функции


Get the list index for a changed many-valued property

SDO_DAS_DataObject::getChangeSummary
SDO_DAS_Setting::getPropertyIndex
SDO Функции
PHP Manual

SDO_DAS_Setting::getListIndex

(^)

SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property

Описание

int SDO_DAS_Setting::getListIndex ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the list index for a modification made to an element of a many-valued property. For example, if we modified the third element of a many-valued property we could obtain an SDO_DAS_Setting from the change summary corresponding to that modification. A call to getListIndex() on that setting would return the value 2 (lists are indexed from zero).

Список параметров

None.

Возвращаемые значения

The list index for the element of the many-valued property which has been changed.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_DataObject::getChangeSummary
SDO_DAS_Setting::getPropertyIndex
SDO Функции


Get the property index for a changed property

SDO_DAS_Setting::getListIndex
SDO_DAS_Setting::getPropertyName
SDO Функции
PHP Manual

SDO_DAS_Setting::getPropertyIndex

(^)

SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property

Описание

int SDO_DAS_Setting::getPropertyIndex ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the property index for the changed property. This index identifies the property which was modified in data object.

Список параметров

None.

Возвращаемые значения

The property index for a changed property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Setting::getListIndex
SDO_DAS_Setting::getPropertyName
SDO Функции


Get the property name for a changed property

SDO_DAS_Setting::getPropertyIndex
SDO_DAS_Setting::getValue
SDO Функции
PHP Manual

SDO_DAS_Setting::getPropertyName

(^)

SDO_DAS_Setting::getPropertyName — Get the property name for a changed property

Описание

string SDO_DAS_Setting::getPropertyName ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the property name for the changed property. This name identifies the property which was modified in data object.

Список параметров

None.

Возвращаемые значения

The property name for a changed property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Setting::getPropertyIndex
SDO_DAS_Setting::getValue
SDO Функции


Get the old value for the changed property

SDO_DAS_Setting::getPropertyName
SDO_DAS_Setting::isSet
SDO Функции
PHP Manual

SDO_DAS_Setting::getValue

(^)

SDO_DAS_Setting::getValue — Get the old value for the changed property

Описание

mixed SDO_DAS_Setting::getValue ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the old value for the changed property. This can be used by a Data Access Service when writing updates to a data source. The DAS uses the old value to detect conflicts by comparing it with the current value in the data source. If they do not match, then the data source has been updated since the data object was originally populated, and therefore writing any new updates risks compromising the integrity of the data.

Список параметров

None.

Возвращаемые значения

Returns the old value of the changed property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Setting::getPropertyName
SDO_DAS_Setting::isSet
SDO Функции


Test whether a property was set prior to being modified

SDO_DAS_Setting::getValue
SDO_DataFactory::create
SDO Функции
PHP Manual

SDO_DAS_Setting::isSet

(^)

SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified

Описание

bool SDO_DAS_Setting::isSet ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test whether a property was set prior to being modified. If it was set prior to being modified then the SDO_DAS_Setting will also contain the old value.

Список параметров

None.

Возвращаемые значения

Returns TRUE if the property was set prior to being modified, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Setting::getValue
SDO_DataFactory::create
SDO Функции


Create an SDO_DataObject

SDO_DAS_Setting::isSet
SDO_DataObject::clear
SDO Функции
PHP Manual

SDO_DataFactory::create

(^)

SDO_DataFactory::create — Create an SDO_DataObject

Описание

void SDO_DataFactory::create ( string $type_namespace_uri , string $type_name )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Create a new SDO_DataObject given the data object's namespace URI and type name.

Список параметров

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Возвращаемые значения

Returns the newly created SDO_DataObject.

Ошибки

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type known to this data factory.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Setting::isSet
SDO_DataObject::clear
SDO Функции


Clear an SDO_DataObject's properties

SDO_DataFactory::create
SDO_DataObject::createDataObject
SDO Функции
PHP Manual

SDO_DataObject::clear

(^)

SDO_DataObject::clear — Clear an SDO_DataObject's properties

Описание

void SDO_DataObject::clear ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Clear an SDO_DataObject's properties. Read-only properties are unaffected. Subsequent calls to isset() for the data object will return FALSE.

Список параметров

None.

Возвращаемые значения

No return values.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DataFactory::create
SDO_DataObject::createDataObject
SDO Функции


Create a child SDO_DataObject

SDO_DataObject::clear
SDO_DataObject::getContainer
SDO Функции
PHP Manual

SDO_DataObject::createDataObject

(^)

SDO_DataObject::createDataObject — Create a child SDO_DataObject

Описание

SDO_DataObject SDO_DataObject::createDataObject ( mixed $identifier )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Create a child SDO_DataObject of the default type for the property identified. The data object is automatically inserted into the tree and a reference to it is returned.

Список параметров

identifier

Identifies the property for the data object type to be created. Can be either a property name (string), a property index (int), or an SDO_Model_Property.

Возвращаемые значения

Returns the newly created SDO_DataObject.

Ошибки

SDO_PropertyNotFoundException

Thrown if the identifier does not correspond to a property of the data object.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DataObject::clear
SDO_DataObject::getContainer
SDO Функции


Get a data object's container

SDO_DataObject::createDataObject
SDO_DataObject::getSequence
SDO Функции
PHP Manual

SDO_DataObject::getContainer

(^)

SDO_DataObject::getContainer — Get a data object's container

Описание

SDO_DataObject SDO_DataObject::getContainer ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the data object which contains this data object.

Список параметров

None.

Возвращаемые значения

Returns the SDO_DataObject which contains this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).

User Contributed Notes

There are no user contributed notes for this page.
SDO_DataObject::createDataObject
SDO_DataObject::getSequence
SDO Функции


Get the sequence for a data object

SDO_DataObject::getContainer
SDO_DataObject::getTypeName
SDO Функции
PHP Manual

SDO_DataObject::getSequence

(^)

SDO_DataObject::getSequence — Get the sequence for a data object

Описание

SDO_Sequence SDO_DataObject::getSequence ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Return the SDO_Sequence for this SDO_DataObject. Accessing the SDO_DataObject through the SDO_Sequence interface acts on the same SDO_DataObject instance data, but preserves ordering across properties.

Список параметров

None.

Возвращаемые значения

The SDO_Sequence for this SDO_DataObject, or returns NULL if the SDO_DataObject is not of a type which can have a sequence.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DataObject::getContainer
SDO_DataObject::getTypeName
SDO Функции


Return the name of the type for a data object.

SDO_DataObject::getSequence
SDO_DataObject::getTypeNamespaceURI
SDO Функции
PHP Manual

SDO_DataObject::getTypeName

(^)

SDO_DataObject::getTypeName — Return the name of the type for a data object.

Описание

string SDO_DataObject::getTypeName ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Return the name of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getName().

Список параметров

None.

Возвращаемые значения

The name of the type for the data object.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DataObject::getSequence
SDO_DataObject::getTypeNamespaceURI
SDO Функции


Return the namespace URI of the type for a data object.

SDO_DataObject::getTypeName
SDO_Exception::getCause
SDO Функции
PHP Manual

SDO_DataObject::getTypeNamespaceURI

(^)

SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object.

Описание

string SDO_DataObject::getTypeNamespaceURI ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Return the namespace URI of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getNamespaceURI().

Список параметров

None.

Возвращаемые значения

The namespace URI of the type for the data object.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DataObject::getTypeName
SDO_Exception::getCause
SDO Функции


Get the cause of the exception.

SDO_DataObject::getTypeNamespaceURI
SDO_List::insert
SDO Функции
PHP Manual

SDO_Exception::getCause

(^)

SDO_Exception::getCause — Get the cause of the exception.

Описание

mixed SDO_Exception::getCause ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the cause of this exception or NULL if the cause is nonexistent or unknown. Typically the cause will be an SDO_CPPException object, which may be used to obtain additional diagnostic information.

Список параметров

None.

Возвращаемые значения

Returns the cause of this exception or NULL if the cause is nonexistent or unknown.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DataObject::getTypeNamespaceURI
SDO_List::insert
SDO Функции


Insert into a list

SDO_Exception::getCause
SDO_Model_Property::getContainingType
SDO Функции
PHP Manual

SDO_List::insert

(^)

SDO_List::insert — Insert into a list

Описание

void SDO_List::insert ( mixed $value [, int $index ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Insert a new element at a specified position in the list. All subsequent list items are moved up.

Список параметров

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

index

The position at which to insert the new element. If this argument is not specified then the new value will be appended.

Возвращаемые значения

None.

Ошибки

SDO_IndexOutOfBoundsException

Thrown if the list index is less than zero or greater than the size of the list.

SDO_InvalidConversionException

Thrown if the type of the new value does not match the type for the list (e.g. the type of the many-valued property that the list represents).

User Contributed Notes

There are no user contributed notes for this page.
SDO_Exception::getCause
SDO_Model_Property::getContainingType
SDO Функции


Get the SDO_Model_Type which contains this property

SDO_List::insert
SDO_Model_Property::getDefault
SDO Функции
PHP Manual

SDO_Model_Property::getContainingType

(^)

SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property

Описание

SDO_Model_Type SDO_Model_Property::getContainingType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the SDO_Model_Type which contains this property.

Список параметров

None.

Возвращаемые значения

Returns the SDO_Model_Type which contains this property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_List::insert
SDO_Model_Property::getDefault
SDO Функции


Get the default value for the property

SDO_Model_Property::getContainingType
SDO_Model_Property::getName
SDO Функции
PHP Manual

SDO_Model_Property::getDefault

(^)

SDO_Model_Property::getDefault — Get the default value for the property

Описание

mixed SDO_Model_Property::getDefault ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the default value for the property. Only primitive data type properties can have default values.

Список параметров

None.

Возвращаемые значения

Returns the default value for the property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Property::getContainingType
SDO_Model_Property::getName
SDO Функции


Get the name of the SDO_Model_Property

SDO_Model_Property::getDefault
SDO_Model_Property::getType
SDO Функции
PHP Manual

SDO_Model_Property::getName

(^)

SDO_Model_Property::getName — Get the name of the SDO_Model_Property

Описание

string SDO_Model_Property::getName ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the name of the SDO_Model_Property.

Список параметров

None.

Возвращаемые значения

Returns the name of the SDO_Model_Property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Property::getDefault
SDO_Model_Property::getType
SDO Функции


Get the SDO_Model_Type of the property

SDO_Model_Property::getName
SDO_Model_Property::isContainment
SDO Функции
PHP Manual

SDO_Model_Property::getType

(^)

SDO_Model_Property::getType — Get the SDO_Model_Type of the property

Описание

SDO_Model_Type SDO_Model_Property::getType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the SDO_Model_Type of the property. The SDO_Model_Type describes the type information for the property, such as its type name, namespace URI, whether it is a primitive data type, and so on.

Список параметров

None.

Возвращаемые значения

Returns the SDO_Model_Type describing the property's type information.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Property::getName
SDO_Model_Property::isContainment
SDO Функции


Test to see if the property defines a containment relationship

SDO_Model_Property::getType
SDO_Model_Property::isMany
SDO Функции
PHP Manual

SDO_Model_Property::isContainment

(^)

SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship

Описание

bool SDO_Model_Property::isContainment ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test to see if the property corresponds to a containment relationship. Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

Список параметров

None.

Возвращаемые значения

Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Property::getType
SDO_Model_Property::isMany
SDO Функции


Test to see if the property is many-valued

SDO_Model_Property::isContainment
SDO_Model_ReflectionDataObject::__construct
SDO Функции
PHP Manual

SDO_Model_Property::isMany

(^)

SDO_Model_Property::isMany — Test to see if the property is many-valued

Описание

bool SDO_Model_Property::isMany ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test to see if the property is many-valued. Returns TRUE if this is a many-valued property, otherwise returns FALSE.

Список параметров

None.

Возвращаемые значения

Returns TRUE if this is a many-valued property, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Property::isContainment
SDO_Model_ReflectionDataObject::__construct
SDO Функции


Construct an SDO_Model_ReflectionDataObject

SDO_Model_Property::isMany
SDO_Model_ReflectionDataObject::export
SDO Функции
PHP Manual

SDO_Model_ReflectionDataObject::__construct

(^)

SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject

Описание

SDO_Model_ReflectionDataObject::__construct ( SDO_DataObject $data_object )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Construct an SDO_Model_ReflectionDataObject to reflect on an SDO_DataObject. Reflecting on an SDO_DataObject gives access to information about its model. The model contains information such as the data object's type, and whether that type is sequenced (preserves ordering across properties) or open (each instance can have its model extended). The model also holds information about the data object's properties, any default values they may have, and so on.

Список параметров

data_object

The SDO_DataObject being reflected upon.

Возвращаемые значения

None.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Property::isMany
SDO_Model_ReflectionDataObject::export
SDO Функции


Get a string describing the SDO_DataObject.

SDO_Model_ReflectionDataObject::__construct
SDO_Model_ReflectionDataObject::getContainmentProperty
SDO Функции
PHP Manual

SDO_Model_ReflectionDataObject::export

(^)

SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject.

Описание

mixed SDO_Model_ReflectionDataObject::export ( SDO_Model_ReflectionDataObject $rdo [, bool $return ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get a string describing the SDO_DataObject. The default behaviour is to print the output, but if TRUE is specified for return, it is returned as a string.

Список параметров

rdo

An SDO_Model_ReflectionDataObject.

return

If TRUE, return the output as a string, otherwise print it.

Возвращаемые значения

Returns the output if TRUE is specified for return, otherwise NULL.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_ReflectionDataObject::__construct
SDO_Model_ReflectionDataObject::getContainmentProperty
SDO Функции


Get the property which defines the containment relationship to the data object

SDO_Model_ReflectionDataObject::export
SDO_Model_ReflectionDataObject::getInstanceProperties
SDO Функции
PHP Manual

SDO_Model_ReflectionDataObject::getContainmentProperty

(^)

SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object

Описание

SDO_Model_Property SDO_Model_ReflectionDataObject::getContainmentProperty ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the SDO_Model_Property that contains the SDO_DataObject. This method is used to navigate up to the parent's property which contains the data object which has been reflected upon.

Список параметров

None.

Возвращаемые значения

Returns the container's SDO_Model_Property which references the SDO_DataObject, or NULL if it is a root SDO_DataObject.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_ReflectionDataObject::export
SDO_Model_ReflectionDataObject::getInstanceProperties
SDO Функции


Get the instance properties of the SDO_DataObject

SDO_Model_ReflectionDataObject::getContainmentProperty
SDO_Model_ReflectionDataObject::getType
SDO Функции
PHP Manual

SDO_Model_ReflectionDataObject::getInstanceProperties

(^)

SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject

Описание

array SDO_Model_ReflectionDataObject::getInstanceProperties ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the instance properties for the SDO_DataObject. The instance properties consist of all the properties defined on the data object's type, plus any instance properties from open content (if the data object is an open type).

Список параметров

None.

Возвращаемые значения

An array of SDO_Model_Property objects.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_ReflectionDataObject::getContainmentProperty
SDO_Model_ReflectionDataObject::getType
SDO Функции


Get the SDO_Model_Type for the SDO_DataObject

SDO_Model_ReflectionDataObject::getInstanceProperties
SDO_Model_Type::getBaseType
SDO Функции
PHP Manual

SDO_Model_ReflectionDataObject::getType

(^)

SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject

Описание

SDO_Model_Type SDO_Model_ReflectionDataObject::getType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the SDO_Model_Type for the SDO_DataObject. The SDO_Model_Type holds all the information about the data object's type, such as namespace URI, type name, whether it is a primitive data type, and so on.

Список параметров

None.

Возвращаемые значения

Returns the SDO_Model_Type for the SDO_DataObject.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_ReflectionDataObject::getInstanceProperties
SDO_Model_Type::getBaseType
SDO Функции


Get the base type for this type

SDO_Model_ReflectionDataObject::getType
SDO_Model_Type::getName
SDO Функции
PHP Manual

SDO_Model_Type::getBaseType

(^)

SDO_Model_Type::getBaseType — Get the base type for this type

Описание

SDO_Model_Type SDO_Model_Type::getBaseType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get the base type for this type. Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL. An example of when base types occur is when a type defined in XML schema inherits from another type by using

<extension base="...">
.

Список параметров

None.

Возвращаемые значения

Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_ReflectionDataObject::getType
SDO_Model_Type::getName
SDO Функции


Get the name of the type

SDO_Model_Type::getBaseType
SDO_Model_Type::getNamespaceURI
SDO Функции
PHP Manual

SDO_Model_Type::getName

(^)

SDO_Model_Type::getName — Get the name of the type

Описание

string SDO_Model_Type::getName ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the name of the type. The combination of type name and namespace URI is used to uniquely identify the type.

Список параметров

None.

Возвращаемые значения

Returns the name of the type.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::getBaseType
SDO_Model_Type::getNamespaceURI
SDO Функции


Get the namespace URI of the type

SDO_Model_Type::getName
SDO_Model_Type::getProperties
SDO Функции
PHP Manual

SDO_Model_Type::getNamespaceURI

(^)

SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type

Описание

string SDO_Model_Type::getNamespaceURI ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the namespace URI of the type. The combination of namespace URI and type name is used to uniquely identify the type.

Список параметров

None.

Возвращаемые значения

Returns the namespace URI of the type.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::getName
SDO_Model_Type::getProperties
SDO Функции


Get the SDO_Model_Property objects defined for the type

SDO_Model_Type::getNamespaceURI
SDO_Model_Type::getProperty
SDO Функции
PHP Manual

SDO_Model_Type::getProperties

(^)

SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type

Описание

array SDO_Model_Type::getProperties ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get an array of SDO_Model_Property objects describing the properties defined for the SDO_Model_Type. Each SDO_Model_Property holds information such as the property name, default value, and so on.

Список параметров

None.

Возвращаемые значения

Returns an array of SDO_Model_Property objects.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::getNamespaceURI
SDO_Model_Type::getProperty
SDO Функции


Get an SDO_Model_Property of the type

SDO_Model_Type::getProperties
SDO_Model_Type::isAbstractType
SDO Функции
PHP Manual

SDO_Model_Type::getProperty

(^)

SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type

Описание

SDO_Model_Property SDO_Model_Type::getProperty ( mixed $identifier )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Get an SDO_Model_Property of the type, identified by its property index or property name.

Список параметров

identifier

The property index or property name.

Возвращаемые значения

Returns the SDO_Model_Property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::getProperties
SDO_Model_Type::isAbstractType
SDO Функции


Test to see if this SDO_Model_Type is an abstract data type

SDO_Model_Type::getProperty
SDO_Model_Type::isDataType
SDO Функции
PHP Manual

SDO_Model_Type::isAbstractType

(^)

SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type

Описание

bool SDO_Model_Type::isAbstractType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test to see if this SDO_Model_Type is an abstract data type. Returns TRUE if this type is abstract, that is, no SDO_DataObject of this type can be instantiated, though other types may inherit from it.

Список параметров

None.

Возвращаемые значения

Returns TRUE if this type is an abstract data type, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::getProperty
SDO_Model_Type::isDataType
SDO Функции


Test to see if this SDO_Model_Type is a primitive data type

SDO_Model_Type::isAbstractType
SDO_Model_Type::isInstance
SDO Функции
PHP Manual

SDO_Model_Type::isDataType

(^)

SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type

Описание

bool SDO_Model_Type::isDataType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test to see if this SDO_Model_Type is a primitive data type. Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

Список параметров

None.

Возвращаемые значения

Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::isAbstractType
SDO_Model_Type::isInstance
SDO Функции


Test for an SDO_DataObject being an instance of this SDO_Model_Type

SDO_Model_Type::isDataType
SDO_Model_Type::isOpenType
SDO Функции
PHP Manual

SDO_Model_Type::isInstance

(^)

SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type

Описание

bool SDO_Model_Type::isInstance ( SDO_DataObject $data_object )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test for an SDO_DataObject being an instance of this SDO_Model_Type. Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.

Список параметров

data_object

The SDO_DataObject to be tested.

Возвращаемые значения

Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::isDataType
SDO_Model_Type::isOpenType
SDO Функции


Test to see if this type is an open type

SDO_Model_Type::isInstance
SDO_Model_Type::isSequencedType
SDO Функции
PHP Manual

SDO_Model_Type::isOpenType

(^)

SDO_Model_Type::isOpenType — Test to see if this type is an open type

Описание

bool SDO_Model_Type::isOpenType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test to see if this type is open. Returns TRUE if this type is open, otherwise returns FALSE. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content, such as that defined by an

<xsd:any>
element.

Список параметров

None.

Возвращаемые значения

Returns TRUE if this type is open, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::isInstance
SDO_Model_Type::isSequencedType
SDO Функции


Test to see if this is a sequenced type

SDO_Model_Type::isOpenType
SDO_Sequence::getProperty
SDO Функции
PHP Manual

SDO_Model_Type::isSequencedType

(^)

SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type

Описание

bool SDO_Model_Type::isSequencedType ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Test to see if this is a sequenced type. Returns TRUE if this type is sequence, otherwise returns FALSE. Sequenced types can have the ordering across properties preserved and can contain unstructured text. For more information on sequenced types see the section on Working with Sequenced Data Objects.

Список параметров

None.

Возвращаемые значения

Returns TRUE if this type is sequence, otherwise return FALSE.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::isOpenType
SDO_Sequence::getProperty
SDO Функции


Return the property for the specified sequence index.

SDO_Model_Type::isSequencedType
SDO_Sequence::insert
SDO Функции
PHP Manual

SDO_Sequence::getProperty

(^)

SDO_Sequence::getProperty — Return the property for the specified sequence index.

Описание

SDO_Model_Property SDO_Sequence::getProperty ( int $sequence_index )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Return the property for the specified sequence index.

Список параметров

sequence_index

The position of the element in the sequence.

Возвращаемые значения

An SDO_Model_Property. A return value of NULL means the sequence element does not belong to a property and must therefore be unstructured text.

Ошибки

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Model_Type::isSequencedType
SDO_Sequence::insert
SDO Функции


Insert into a sequence

SDO_Sequence::getProperty
SDO_Sequence::move
SDO Функции
PHP Manual

SDO_Sequence::insert

(^)

SDO_Sequence::insert — Insert into a sequence

Описание

void SDO_Sequence::insert ( mixed $value [, int $sequenceIndex [, mixed $propertyIdentifier ]] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Insert a new element at a specified position in the sequence. All subsequent sequence items are moved up.

Список параметров

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

sequenceIndex

The position at which to insert the new element. Default is NULL, which results in the new value being appended to the sequence.

propertyIdentifier

Either a property index, a property name, or an SDO_Model_Property, used to identify a property in the sequence's corresponding SDO_DataObject. A value of NULL signifies unstructured text.

Возвращаемые значения

None.

Ошибки

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_InvalidConversionException

Thrown if the type of the new value cannot be juggled to match the type for the specified data object property.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Sequence::getProperty
SDO_Sequence::move
SDO Функции


Move an item to another sequence position

SDO_Sequence::insert
SDO-DAS-Relational
SDO Функции
PHP Manual

SDO_Sequence::move

(^)

SDO_Sequence::move — Move an item to another sequence position

Описание

void SDO_Sequence::move ( int $toIndex, int $fromIndex )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Modify the position of the item in the sequence, without altering the value of the property in the SDO_DataObject.

Список параметров

toIndex

The destination sequence index. If this index is less than zero or greater than the size of the sequence then the value is appended.

fromIndex

The source sequence index.

Возвращаемые значения

None.

Ошибки

SDO_IndexOutOfBoundsException

Thrown if the fromIndex sequence index is less than zero or greater than the size of the sequence.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Sequence::insert
SDO-DAS-Relational
SDO Функции


SDO Relational Data Access Service

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • Creating, retrieving, updating and deleting data
    • Specifying the metadata
    • One-table examples
    • Two-table examples
    • Three-table example
  • Limitations
  • SDO-DAS-Relational Функции
    • SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database.
    • SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service
    • SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
    • SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
    • SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph.

User Contributed Notes

There are no user contributed notes for this page.
SDO_Sequence::move
Введение
Обработка XML


Введение

Внимание

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и любую другую относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

In order to use the Relational Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, the disconnected way of working, the change summary, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO. In addition, the Relational DAS makes use of the PDO extension to isolate itself from specifics of different back-end relational databases. In order to use the Relational DAS you will need to be able to create and pass a PDO database connection; for this reason you might also want to take a look at the section on PDO.

The job of the Relational DAS is to move data between the application and a relational database. In order to do this it needs to be told the mapping between the database entities - tables, columns, primary keys and foreign keys - and the elements of the SDO model - types, properties, containment relationships and so on. You specify this information as metadata when you construct the Relational DAS.

Overview of Operation

  1. The first step is to call the Relational DAS's constructor, passing the metadata that defines the mapping between database and SDO model. There are examples of this below.

  2. The next step might be to call the executeQuery() or executePreparedQuery() methods on the Relational DAS, passing either a literal SQL statement for the DAS to prepare and execute, or a prepared statement with placeholders and a list of values to be inserted. You may also need to specify a small amount of metadata about the query itself, so that the Relational DAS knows exactly what columns will be returned from the database and in what order. You will also need to pass a PDO database connection.

    The return value from executeQuery() or executePreparedQuery() is a normalised data graph containing all the data from the result set. For a query that returns data obtained from a number of tables, this graph will contain a number of data objects, linked by SDO containment relationships. There may also be SDO non-containment references within the data.

    Once the query has been executed and the data graph constructed, there is no need for either that instance of the Relational DAS or the database connection. There are no locks held on the database. Both the Relational DAS and the PDO database connection can be garbage collected.

  3. Quite possibly the data in the data graph will go through a number of modifications. The data graph can be serialised into the PHP session and so may have a lifetime beyond just one client-server interaction. Data objects can be created and added to the graph, the data objects already in the graph can be deleted, and data objects in the graph can be modified.

  4. Finally, the changes made to the data graph can be applied back to the database using the applyChanges() method of the Relational DAS. For this, another instance of the Relational DAS must be constructed, using the same metadata, and another connection to the database obtained. The connection and the data graph are passed to applyChanges(). At this point the Relational DAS examines the change summary and generates the necessary INSERT, UPDATE and DELETE SQL statements to apply the changes. Any UPDATE and DELETE statements are qualified with the original values of the data so that should the data have changed in the database in the meantime this will be detected. Assuming no such collisions have occurred the changes will be committed to the database. The application can then continue to work with the data graph, make more changes and apply them, or can discard it.

There are other ways of working with the data in the database: it is possible to just create data objects and write them to the database without a preliminary call to executeQuery(), for example. This scenario and others are explored in the Examples section below.

User Contributed Notes

There are no user contributed notes for this page.
SDO-DAS-Relational
Установка и настройка
SDO-DAS-Relational


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
SDO-DAS-Relational


Требования

The Relational DAS requires that the SDO extension be installed. The SDO extension requires a version of PHP 5.1, and the Relational DAS requires a recent version that contains an important fix for PDO. The most up-to-date information about required levels of PHP should be found in the changelog for the package on PECL. At the time of writing, though, the Relational DAS requires the most recent beta level of PHP 5.1, that is PHP 5.1.0.

The Relational DAS uses PDO to access the relational database, and so should run with a variety of different relational databases. At the time of writing it has been tested in the following configurations

  • MySQL 4.1.14, on Windows. The Relational DAS operates correctly with the php_pdo_mysql driver that comes with the pre-built binaries for PHP 5.1.0.

  • MySQL 4.1.13, on Linux. It is necessary to have the most up-to-date PDO driver for MySQL, which comes built in to PHP 5.1.0. It may be necessary to uninstall the usual driver that would have come from PECL using pear uninstall pdo_mysql. You will need to configure PHP with the --with-pdo-mysql option.

  • DB2 8.2 Personal Edition, on Windows. The Relational DAS operates correctly with the php_pdo_odbc driver that comes with the pre-built binaries for PHP 5.1.0.

  • DB2 8.2 Personal Developer's Edition, on Linux. The Developer's Edition is needed because it contains the include files needed when PHP is configured and built. You will need to configure PHP with the --with-pdo-odbc=ibm-db2 option.

The Relational DAS applies changes to the database within a user-delimited transaction: that is, it issues a call to PDO::beginTransaction() before beginning to apply changes, and PDO::commit() or PDO::rollback() on completion. Whichever database is chosen, the database and the PDO driver for the database must support these calls.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

The installation instructions for all the SDO components are in the SDO install section of the SDO documentation.

In any case, the essential facts are that the Relational DAS is written in PHP and it should be placed somewhere on the PHP include_path.

Your application will of course need to include the Relational DAS with a statement like this:

<?php
require_once 'SDO/DAS/Relational.php';
?>

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Настройка во время выполнения

Данное расширение не определяет никакие директивы конфигурации в php.ini.

Tracing

You may be interested in seeing the SQL statements that are generated in order to apply changes back to the database. At the top of the SDO/DAS/Relational.php you will find a number of constants which control whether the process of constructing and executing the SQL statements is to be traced. Try setting DEBUG_EXECUTE_PLAN to TRUE to see the generated SQL statements.

User Contributed Notes

There are no user contributed notes for this page.
Установка
Типы ресурсов
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

The Relational DAS introduces no predefined constants.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
SDO-DAS-Relational


Примеры

Содержание

  • Creating, retrieving, updating and deleting data
  • Specifying the metadata
  • One-table examples
  • Two-table examples
  • Three-table example

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Creating, retrieving, updating and deleting data
SDO-DAS-Relational


Creating, retrieving, updating and deleting data

This section illustrates how the Relational DAS can be used to create, retrieve, update and delete data in a relational database. Many of the examples are illustrated with a three-table database that contains companies, departments within those companies, and employees that work in those departments. This example is used in a number of places within the SDO literature. See the examples section of the » Service Data Objects specification or the Examples section of the documentation for the SDO extension.

The Relational DAS is constructed with metadata that defines the relational database and how it should be mapped to SDO. The long section that follows describes this metadata and how to construct the Relational DAS. The examples that follow it all assume that this metadata is in an included php file.

The examples below and others can all be found in the Scenarios directory in the Relational DAS package.

The Relational DAS throws exceptions in the event that it finds errors in the metadata or errors when executing SQL statements against the database. For brevity the examples below all omit the use of try/catch blocks around the calls to the Relational DAS.

These examples all differ from the expected use of SDO in two important respects.

First, they show all interactions with the database completed within one script. In this respect these scenarios are not realistic but are chosen to illustrate just the use of the Relational DAS. It is expected that interactions with the database will be separated in time and the data graph serialized and deserialized into the PHP session one or more times as the application interacts with an end user.

Second, all queries executed against the database use hard-coded queries with no variables substituted. In this case it is safe to use the simple executeQuery() call, and this is what the examples illustrate. In practice, though, it is unlikely that the SQL statement is known entirely ahead of time. In order to allow variables to be safely substituted into the SQL queries, without running the risk of injecting SQL with unknown effects, it is safer to use the executePreparedQuery() which takes a prepared SQL statement containing placeholders and a list of values to be substituted.

User Contributed Notes

There are no user contributed notes for this page.
Примеры
Specifying the metadata
Примеры


Specifying the metadata

This first long section describes in detail how the metadata describing the database and the required SDO model is supplied to the Relational DAS.

When the constructor for the Relational DAS is invoked, it needs to be passed several pieces of information. The bulk of the information, passed as an associative array in the first argument to the constructor, tells the Relational DAS what it needs to know about the relational database. It describes the names of the tables, columns, primary keys and foreign keys. It should be fairly easy to understand what is required, and once written it can be placed in a php file and included when needed. The remainder of the information, passed in the second and third arguments to the constructor, tells the Relational DAS what it needs to know about the relationships between objects and the shape of the data graph; it ultimately determines how the data from the database is to be normalized into a graph.

Database metadata

The first argument to the constructor describes the target relational database.

Each table is described by an associative array with up to four keys.

Key | Value
name | The name of the table.
columns | An array listing the names of the columns, in any order.
PK | The name of the column containing the primary key.
FK | An array with two entries, 'from' and 'to', which define a column containing a foreign key, and a table to which the foreign key points. If there are no foreign keys in the table then the 'FK' entry does not need to be specified. Only one foreign key can be specified. Only a foreign key pointing to the primary key of a table can be specified.

<?php
/*****************************************************************
* METADATA DEFINING THE DATABASE
******************************************************************/
$company_table = array (
  'name' => 'company',
  'columns' => array('id', 'name',  'employee_of_the_month'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'employee_of_the_month',
      'to' => 'employee',
      ),
  );
$department_table = array (
  'name' => 'department',
  'columns' => array('id', 'name', 'location', 'number', 'co_id'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'co_id',
      'to' => 'company',
      )
  );
$employee_table = array (
  'name' => 'employee',
  'columns' => array('id', 'name', 'SN', 'manager', 'dept_id'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'dept_id',
      'to' => 'department',
      )
  );
$database_metadata = array($company_table, $department_table, $employee_table);
?>

This metadata corresponds to a relational database that might have been defined to MySQL as:

create table company (
 id integer auto_increment,
 name char(20),
 employee_of_the_month integer,
 primary key(id)
);
create table department (
 id integer auto_increment,
 name char(20),
 location char(10),
 number integer(3),
 co_id integer,
 primary key(id)
);
create table employee (
 id integer auto_increment,
 name char(20),
 SN char(4),
 manager tinyint(1),
 dept_id integer,
 primary key(id)
);

or to DB2 as:

create table company ( \
  id integer not null generated by default as identity,  \
  name varchar(20), \
  employee_of_the_month integer, \
  primary key(id) )
create table department ( \
  id integer not null generated by default as identity, \
  name varchar(20), \
  location varchar(10), \
  number integer, \
  co_id integer, \
  primary key(id) )
create table employee ( \
  id integer not null generated by default as identity, \
  name varchar(20), \
  SN char(4), \
  manager smallint, \
  dept_id integer, \
  primary key(id) )

Note that although in this example there are no foreign keys specified to the database and so the database is not expected to enforce referential integrity, the intention behind the co_id column on the department table and the dept_id column on the employee table is they should contain the primary key of their containing company or department record, respectively. So these two columns are acting as foreign keys.

There is a third foreign key in this example, that from the employee_of_the_month column of the company record to a single row of the employee table. Note the difference in intent between this foreign key and the other two. The employee_of_the_month column represents a single-valued relationship: there can be only one employee of the month for a given company. The co_id and dept_id columns represent multi-valued relationships: a company can contain many departments and a department can contain many employees. This distinction will become evident when the remainder of the metadata picks out the company-department and department-employee relationships as containment relationships.

There are a few simple rules to be followed when constructing the database metadata:

  • All tables must have primary keys, and the primary keys must be specified in the metadata. Without primary keys it is not possible to keep track of object identities. As you can see from the SQL statements that create the tables, primary keys can be auto-generated, that is, generated and assigned by the database when a record is inserted. In this case the auto-generated primary key is obtained from the database and inserted into the data object immediately after the row is inserted into the database.

  • It is not necessary to specify in the metadata all the columns that exist in the database, only those that will be used. For example, if the company table had another column that the application did not want to access with SDO, this need not be specified in the metadata. On the other hand it would have done no harm to specify it: if specified in the metadata but never retrieved, or assigned to by the application, then the unused column will not affect anything.

  • In the database metadata note that the foreign key definitions identify not the destination column in the table which is pointed to, but the table name itself. Strictly, the relational model permits the destination of a foreign key to be a non-primary key. Only foreign keys that point to a primary key are useful for constructing the SDO model, so the metadata specifies the table name. It is understood that the foreign key points to the primary key of the given table.

Given these rules, and given the SQL statements that define the database, the database metadata should be easy to construct.

What the Relational DAS does with the metadata

The Relational DAS uses the database metadata to form most of the SDO model. For each table in the database metadata, an SDO type is defined. Each column which can represent a primitive value (columns which are not defined as foreign keys) are added as properties to the SDO type.

All primitive properties are given a type of string in the SDO model, regardless of their SQL type. When writing values back to the database the Relational DAS will create SQL statements that treat the values as strings, and the database will convert them to the appropriate type.

Foreign keys are interpreted in one of two ways, depending on the metadata in the third argument to the constructor that defines the SDO containment relationships. A discussion of this is therefore deferred until the section on SDO containment relationships below.

Specifying the application root type

The second argument to the constructor is the application root type. The true root of each data graph is an object of a special root type and all application data objects come somewhere below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, the application root type can be inferred, and this argument can be omitted.

Specifying the SDO containment relationships

The third argument to the constructor defines how the types in the model are to be linked together to form a graph. It identifies the parent-child relationships between the types which collectively form a graph. The relationships need to be supported by foreign keys to be found in the data, in a way shortly to be described.

The metadata is an array containing one or more associative arrays, each of which identifies a parent and a child. The example below shows a parent-child relationship from company to department, and another from department to employee. Each of these will become an SDO property defining a multi-valued containment relationship in the SDO model.

<?php
$department_containment = array( 'parent' => 'company', 'child' => 'department');
$employee_containment = array( 'parent' => 'department', 'child' => 'employee');

$SDO_containment_metadata = array($department_containment, $employee_containment);
?>

Foreign keys in the database metadata are interpreted as properties with either multi-valued containment relationships or single-valued non-containment references, depending on whether they have a corresponding SDO containment relationship specified in the metadata. In the example here, the foreign keys from department to company (the co_id column in the department table) and from employee to department (the dept_id column in the employee table) are interpreted as supporting the SDO containment relationships. Each containment relationship mentioned in the SDO containment relationships metadata must have a corresponding foreign key present in the database and defined in the database metadata. The values of the foreign key columns for containment relationships do not appear in the data objects, instead each is represented by a containment relationship from the parent to the child. So the co_id column in the department row in the database, for example, does not appear as a property on the department type, but instead as a containment relationship called department on the company type. Note that the foreign key and the parent-child relationship appear to have opposite senses: the foreign key points from the department to the company, but the parent-child relationship points from company to department.

The third foreign key in this example, the employee_of_the_month , is handled differently. This is not mentioned in the SDO containment relationships metadata. As a consequence this is interpreted in the second way: it becomes a single-valued non-containment reference on the company object, to which can be assigned references to SDO data objects of the employee type. It does appear as a property on the company type. The way to assign a value to it in the SDO data graph is to have a graph that contains an employee object through the containment relationships, and to assign the object to it. This is illustrated in the later examples below.

User Contributed Notes

There are no user contributed notes for this page.
Creating, retrieving, updating and deleting data
One-table examples
Примеры


One-table examples

The following set of examples all use the Relational DAS to work with a data graph containing just one application data object, a single company and the data just to be found the company table. These examples do not exercise the power of SDO or the Relational DAS and of course the same result could be achieved more economically with direct SQL statements but they are intended to illustrate how to work with the Relational DAS.

For this very simple scenario it would be possible to simplify the database metadata to include just the company table - if that were done the second and third arguments to the constructor and the column specifier used in the query example would become optional.

Пример #1 Creating a data object

The simplest example is that of creating a single data object and writing it to the database. In this example a single company object is created, its name is set to 'Acme', and the Relational DAS is called to write the changes to the database. The company name is set here using the property name method. See the Examples section on the SDO extension for other ways of accessing the properties of an object.

Data objects can only be created when you have a data object to start with, however. It is for that reason that the first call to the Relational DAS here is to obtain a root object. This is in effect how to ask for an empty data graph - the special root object is the true root of the tree. The company data object is then created with a call to createDataObject() on the root object. This creates the company data object and inserts it in the graph by inserting into a multi-valued containment property on the root object called 'company'.

When the Relational DAS is called to apply the changes a simple insert statement 'INSERT INTO company (name) VALUES ("Acme");' will be constructed and executed. The auto-generated primary key will be set into the data object and the change summary will be reset, so that it would be possible to continue working with the same data object, modify it, and apply the newer changes a second time.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Obtain a root object and create a company object underneath.
* Make a simple change to the data object.
***************************************************************/
$root = $das  -> createRootDataObject();
$acme = $root -> createDataObject('company');

$acme->name = "Acme";

/**************************************************************
* Get a database connection and write the object to the database
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das -> applyChanges($dbh, $root);
?>

Пример #2 Retrieving a data object

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

In this example the third argument to executeQuery(), the column specifier is needed as there are other tables in the metadata with column names of name and id. If there were no possible ambiguity it could be omitted.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
         'select name, id from company where name="Acme"',
          array('company.name', 'company.id') );

/**************************************************************
* Echo name and id
***************************************************************/
foreach ($root['company'] as $company) {
  echo "Company obtained from the database has name = " .
  $company['name'] . " and id " . $company['id'] . "\n";
}
?>

Пример #3 Updating a data object

This example combines the previous two, in the sense that in order to be updated the object must first be retrieved. The application code reverses the company name (so 'Acme' becomes 'emcA') and then the changes are written back to the database in the same way that they were when the object was created. Because the query searches for the name both ways round the program can be run repeatedly to find the company and reverse its name each time.

In this example the same instance of the Relational DAS is reused for the applyChanges(), as is the PDO database handle. This is quite alright; it also alright to allow the previous instances to be garbage collected and to obtain new instances. No state data regarding the graph is held the Relational DAS once it has returned a data graph to the application. All necessary data is either within the graph itself, or can be reconstructed from the metadata.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
  'select name, id from company where name="Acme" or name="emcA"',
  array('company.name', 'company.id') );

/**************************************************************
* Alter the name of just the first company
***************************************************************/
$company = $root['company'][0];
echo "obtained a company with name of " . $company->name . "\n";
$company->name = strrev($company->name);

/**************************************************************
* Write the change back
***************************************************************/
$das->applyChanges($dbh,$root);
?>

Пример #4 Deleting a data object

Any companies called 'Acme' or its reverse 'emcA' are retrieved. They are then all deleted from the graph with unset.

In this example they are all deleted in one go by unsetting the containing property (the property defining the containment relationship). It is also possible to delete them individually.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
  'select name, id from company where name="Acme" or name="emcA"',
  array('company.name', 'company.id') );

/**************************************************************
* Delete any companies found from the data graph
***************************************************************/
unset($root['company']);

/**************************************************************
* Write the change(s) back
***************************************************************/
$das->applyChanges($dbh,$root);
?>

User Contributed Notes

There are no user contributed notes for this page.
Specifying the metadata
Two-table examples
Примеры


Two-table examples

The following set of examples all use two tables from the company database: the company and department tables. These examples exercise more of the function of the Relational DAS.

In this series of examples a company and department are created, retrieved, updated, and finally deleted. This illustrates the lifecycle for a data graph containing more than one object. Note that this example clears out the company and department tables at the start so that the exact results of the queries can be known.

You can find these examples combined into one script called 1cd-CRUD in the Scenarios directory in the Relational DAS package.

Пример #1 One company, one department - Create

As in the earlier example of creating just one company data object, the first action after constructing the Relational DAS is to call createRootDataObject() to obtain the special root object of the otherwise empty data graph. The company object is then created as a child of the root object, and the department object as a child of the company object.

When it comes to applying the changes, the Relational DAS has to perform special processing to maintain the foreign keys that support the containment relationships, especially if auto-generated primary keys are involved. In this example, the relationship between the auto-generated primary key id in the company table and the co_id column in the department table must be maintained. When inserting a company and department for the first time the Relational DAS has to first insert the company row, then call PDO's getLastInsertId() method to obtain the auto-generated primary key, then add that as the value of the co_id column when inserting the department row.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the two tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();

/**************************************************************
* Create a company with name Acme and one department, the Shoe department
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das -> createRootDataObject();

$acme = $root -> createDataObject('company');
$acme -> name = "Acme";

$shoe = $acme->createDataObject('department');
$shoe->name = 'Shoe';

$das -> applyChanges($dbh, $root);

?>

Пример #2 One company, one department - Retrieve and Update

In this case the SQL query passed to executeQuery() performs an inner join to join the data from the company and department tables. Primary keys for both the company and department tables must be included in the query. The result set is re-normalised to form a normalised data graph. Note that a column specifier is passed as the third argument to the executeQuery() call enabling the Relational DAS to know which column is which in the result set.

Note that the co_id column although used in the query is not needed in the result set. In order to understand what the Relational DAS is doing when it builds the data graph it may be helpful to visualise what the result set looks like. Although the data in the database is normalised, so that multiple department rows can point through their foreign key to one company row, the data in the result set is non-normalised: that is, if there is one company and multiple departments, the values for the company are repeated in each row. The Relational DAS has to reverse this process and turn the result set back into a normalised data graph, with just one company object.

In this example the Relational DAS will examine the result set and column specifier, find data for both the company and department tables, find primary keys for both, and interpret each row as containing data for a department and its parent company. If it has not seen data for that company before (it uses the primary key to check) it creates a company object and then a department object underneath it. If it has seen data for that company before and has already created the company object it just creates the department object underneath.

In this way the Relational DAS can retrieve and renormalise data for multiple companies and multiple departments underneath them.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Retrieve the company and Shoe department, then delete Shoe and add IT
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];            // get the first company - will be 'Acme'
$shoe = $acme['department'][0];         // get the first department underneath - will be 'Shoe'

unset($acme['department'][0]);

$it = $acme->createDataObject('department');
$it->name = 'IT';

$das -> applyChanges($dbh, $root);
?>

Пример #3 One company, two departments - Retrieve and Delete

In this example the company and department are retrieved and then deleted. It is not necessary to delete them individually (although that would be possible) - deleting the company object from the data graph also deletes any departments underneath it.

Note the way that the company object is actually deleted using the PHP unset call. The unset has to be performed on the containing property which in this case is the company property on the special root object. You must use:

<?php
unset($root['company'][0]);
?>
and not:
<?php
unset($acme); //WRONG
?>
Simply unsetting $acme would destroy the variable but leave the data in the data graph untouched.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Retrieve the company and IT department, then delete the whole company
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];
$it = $acme['department'][0];

unset($root['company'][0]);

$das -> applyChanges($dbh, $root);

?>

User Contributed Notes

There are no user contributed notes for this page.
One-table examples
Three-table example
Примеры


Three-table example

The following examples use all three tables from the company database: the company, department, and employee tables. These introduce the final piece of function not exercised by the examples above: the non-containment reference employee_of_the_month.

Like the examples above for company and department, this set of examples is intended to illustrate the full lifecycle of such a data graph.

Пример #1 One company, one department, one employee - Create

In this example a company is created containing one department and just one employee. Note that this example clears out all three tables at the start so that the exact results of the queries can be known.

Note how once the company, department and employee have been created, the employee_of_the_month property of the company can be made to point at the new employee. As this is a non-containment reference, this cannot be done until the employee object has been created within the graph. Non-containment references need to be managed carefully. For example if the employee were now deleted from under the department, it would not be correct to try to save the graph without first clearing or re-assigning the employee_of_the_month property. The closure rule for SDO data graphs requires that any object pointed at by a non-containment reference must also be reachable by containment relationships.

When it comes to inserting the graph into the database, the procedure is similar to the example of inserting the company and department, but employee_of_the_month introduces an extra complexity. The Relational DAS needs to insert the objects working down the tree formed by containment relationships, so company, then department, then employee. This is necessary so that it always has the auto-generated primary key of a parent on hand to include in a child row. But when the company row is inserted the employee who is employee of the month has not yet been inserted and the primary key is not known. The procedure is that after the employee record is inserted and its primary key known, a final step is performed in which the company record is updated with the employee's primary key.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the three tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM EMPLOYEE;');
$rows_affected = $pdo_stmt->execute();

/*************************************************************************************
* Create a tiny but complete company.
* The company name is Acme.
* There is one department, Shoe.
* There is one employee, Sue.
* The employee of the month is Sue.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root             = $das  -> createRootDataObject();
$acme             = $root -> createDataObject('company');
$acme -> name     = "Acme";
$shoe             = $acme -> createDataObject('department');
$shoe -> name     = 'Shoe';
$shoe -> location = 'A-block';
$sue              = $shoe -> createDataObject('employee');
$sue -> name      = 'Sue';
$acme -> employee_of_the_month = $sue;

$das -> applyChanges($dbh, $root);

echo "Wrote back Acme with one department and one employee\n";
?>

Пример #2 One company, one department, one employee - Retrieve and update

The SQL statement passed to the Relational DAS is this time an inner join that retrieves data from all three tables. Otherwise this example introduces nothing that has not appeared in a previous example.

The graph is updated by the addition of a new department and employee and some alterations to the name properties of the existing objects in the graph. The combined changes are then written back. The Relational DAS will process and apply an arbitrary mixture of additions, modifications and deletions to and from the data graph.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Find the company again and change various aspects.
* Change the name of the company, department and employee.
* Add a second department and a new employee.
* Change the employee of the month.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
  "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
  "from company c, department d, employee e " .
  "where e.dept_id = d.id and d.co_id = c.id and c.name='Acme'",
   array('company.id','company.name','company.employee_of_the_month',
   'department.id','department.name','employee.id','employee.name'));
$acme         = $root['company'][0];

$shoe         = $acme->department[0];
$sue          = $shoe -> employee[0];

$it           = $acme->createDataObject('department');
$it->name     = 'IT';
$it->location = 'G-block';
$billy        = $it->createDataObject('employee');
$billy->name  = 'Billy';

$acme->name   = 'MegaCorp';
$shoe->name   = 'Footwear';
$sue->name    = 'Susan';

$acme->employee_of_the_month = $billy;
$das -> applyChanges($dbh, $root);
echo "Wrote back company with extra department and employee and all the names changed (Megacorp/Footwear/Susan)\n";

?>

Пример #3 One company, two departments, two employees - Retrieve and delete

The company is retrieved as a complete data graph containing five data objects - the company, two departments and two employees. They are all deleted by deleting the company object. Deleting an object from the graph deletes all the object beneath it in the graph. Five SQL DELETE statements will be generated and executed. As always they will be qualified with a WHERE clause that contains all of the fields that were retrieved, so that any updates to the data in the database in the meantime by another process will be detected.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Now read it one more time and delete it.
* You can delete part, apply the changes, then carry on working with the same graph but
* care is needed to keep closure - you cannot delete the employee who is eotm without
* reassigning. For safety here we delete the company all in one go.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
  "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
  "from company c, department d, employee e " .
  "where e.dept_id = d.id and d.co_id = c.id and c.name='MegaCorp';",
   array('company.id','company.name','company.employee_of_the_month',
   'department.id','department.name','employee.id','employee.name'));
$megacorp = $root['company'][0];

unset($root['company']);
$das -> applyChanges($dbh, $root);

echo "Deleted the company, departments and employees all in one go.\n";

?>

User Contributed Notes

There are no user contributed notes for this page.
Two-table examples
Limitations
Примеры


Limitations

There are the following limitations in the current release of the Relational DAS:

  • No support for nulls. There is no support for SQL NULL type. It is not legal to assign PHP NULL to a data object property and the Relational DAS will not write that back as a NULL to the database. If nulls are found in the database on a query, the property will remain unset.

  • Only two types of SDO relationship. The metadata described below allows the Relational DAS to model just two types of SDO relationship: multi-valued containment relationships and single-valued non-containment references. In SDO, whether a property describes a single- or multi-valued relationship, and whether it is containment or non-containment, are independent. The full range of possibilities that SDO allows cannot all be defined. There may be relationships that it would be useful to model but which the current implementation cannot manage. One example is a single-valued containment relationship.

  • No support for the full range of SDO data types. The Relational DAS defines all primitive properties in the SDO model as being of type string. SDO defines a richer set of types containing various integer, float, boolean and data and time types. String is adequate for the purposes of the Relational DAS since the combination of PHP, PDO and the database will ensure that values passed as strings will be converted to the proper type before being put in the database. This does affect some scenarios in which the Relational DAS has to work with a data graph that has come from or will go to a different DAS.

  • Only one foreign key per table. The metadata only provides the means to specify one foreign key per table. This foreign key may be mapped to one of the two types of SDO relationship supported. Obviously there are some scenarios that cannot be described under this limitation - it is not possible to have two non-containment references from one table to another for example.

User Contributed Notes

There are no user contributed notes for this page.
Three-table example
SDO-DAS-Relational Функции
SDO-DAS-Relational


SDO-DAS-Relational Функции

Предопределенные классы

The Relational DAS provides two classes: the Relational DAS itself and the subclass of Exception that can be thrown. The Relational DAS has four publicly useful calls: the constructor, the createRootDataObject() call to obtain the root object of an empty data graph, the executeQuery() call to obtain a data graph containing data from a relational database, and the applyChanges() call to write changes made to a data graph back to the relational database.

SDO_DAS_Relational

The only object other than an SDO_DAS_Relational_Exception with which the application is expected to interact.

Методы

  • __construct - construct the Relational DAS with a model derived from the passed metadata

  • createRootDataObject - obtain an otherwise empty data graph containing just the special root object

  • executeQuery - execute an SQL query passed as a literal string and return the results as a normalised data graph

  • executePreparedQuery - execute an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

  • applyChanges - examine the change summary in the data graph and apply those changes back to the database, subject to an assumption of optimistic concurrency

SDO_DAS_Relational_Exception

Is a subclass of PHP's Exception. It adds no behaviour to Exception. Thrown, with useful descriptive text, to signal errors in the metadata or unexpected failures to perform SQL operations.

Содержание

  • SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database.
  • SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service
  • SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
  • SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
  • SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph.

User Contributed Notes

There are no user contributed notes for this page.
Limitations
SDO_DAS_Relational::applyChanges
SDO-DAS-Relational


Applies the changes made to a data graph back to the database.

SDO-DAS-Relational Функции
SDO_DAS_Relational::__construct
SDO-DAS-Relational Функции
PHP Manual

SDO_DAS_Relational::applyChanges

(^)

SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database.

Описание

void SDO_DAS_Relational::applyChanges ( PDO $database_handle , SDODataObject $root_data_object )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Given a PDO database handle and the special root object of a data graph, examine the change summary in the datagraph and applies the changes to the database. The changes that it can apply can be creations of data objects, deletes of data objects, and modifications to properties of data objects.

Список параметров

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

root_data_object

The special root object which is at the top of every SDO data graph.

Возвращаемые значения

None. Note however that the datagraph that was passed is still intact and usable. Furthermore, if data objects were created and written back to a table with autogenerated primary keys, then those primary keys will now be set in the data objects. If the changes were successfully written, then the change summary associated with the datagraph will have been cleared, so that it is possible to now make further changes to the data graph and apply those changes in turn. In this way it is possible to work with the same data graph and apply changes repeatedly.

Ошибки

SDO_DAS_Relational::applyChanges() can throw an SDO_DAS_Relational_Exception if it is unable to apply all the changes correctly.

The Relational DAS starts a database transaction before beginning to apply the changes and will commit the transaction only if they are all successful. The Relational DAS generates qualified update and delete statements which contain a where clause that specifies that the row to be updated or deleted must contain the same values that it did when the data was first retrieved. This is how the optimistic concurrency is implemented. If any of the qualified update or delete statements fails to update or delete their target row, it may be because the data has been altered in the database in the meantime. In any event, if any update fails for any reason, the transaction is rolled back and an exception thrown. The exception will contain the generated SQL statement that failed.

The Relational DAS also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Примеры

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method. Please see also the section on Tracing to see how you can see what SQL statements are generated by the Relational DAS.

User Contributed Notes

There are no user contributed notes for this page.
SDO-DAS-Relational Функции
SDO_DAS_Relational::__construct
SDO-DAS-Relational Функции


Creates an instance of a Relational Data Access Service

SDO_DAS_Relational::applyChanges
SDO_DAS_Relational::createRootDataObject
SDO-DAS-Relational Функции
PHP Manual

SDO_DAS_Relational::__construct

(^)

SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service

Описание

SDO_DAS_Relational::__construct ( array $database_metadata [, string $application_root_type [, array $SDO_containment_references_metadata ]] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Constructs an instance of a Relational Data Access Service from the passed metadata.

Список параметров

database_metadata

An array containing one or more table definitions, each of which is an associative array containing the keys name, columns, PK, and optionally, FK. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

application_root_type

The root of each data graph is an object of a special root type and the application data objects come below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, so the application root type can be inferred, this argument can be omitted.

SDO_containment_references_metadata

An array containing one or more definitions of a containment relation, each of which is an associative array containing the keys parent and child. The containment relations describe how the types in the model are connected to form a tree. The type specified as the application root type must be present as one of the parent types in the containment references. If the application only needs to work with one table at a time, and there are no containment relations in the model, this argument can be omitted. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

Возвращаемые значения

Returns an SDO_DAS_Relational object on success.

Ошибки

SDO_DAS_Relational::__construct() throws a SDO_DAS_Relational_Exception if any problems are found in the metadata.

Примеры

For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Relational::applyChanges
SDO_DAS_Relational::createRootDataObject
SDO-DAS-Relational Функции


Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.

SDO_DAS_Relational::__construct
SDO_DAS_Relational::executePreparedQuery
SDO-DAS-Relational Функции
PHP Manual

SDO_DAS_Relational::createRootDataObject

(^)

SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.

Описание

SDODataObject SDO_DAS_Relational::createRootDataObject ( void )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Returns the special root object at the top of an otherwise empty data graph. This call is used when the application wants to create a data graph from scratch, without having called executeQuery() to create a data graph.

The special root object has one multi-valued containment property, with a name of the application root type that was passed when the Relational DAS was constructed. The property can take values of only that type. The only thing that the application can usefully do with the root type is to call createDataObject() on it, passing the name of the application root type, in order to create a data object of their own application type.

Список параметров

None.

Возвращаемые значения

The root object.

Ошибки

None.

Примеры

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Relational::__construct
SDO_DAS_Relational::executePreparedQuery
SDO-DAS-Relational Функции


Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.

SDO_DAS_Relational::createRootDataObject
SDO_DAS_Relational::executeQuery
SDO-DAS-Relational Функции
PHP Manual

SDO_DAS_Relational::executePreparedQuery

(^)

SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.

Описание

SDODataObject SDO_DAS_Relational::executePreparedQuery ( PDO $database_handle , PDOStatement $prepared_statement , array $value_list [, array $column_specifier ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Executes a given query against the relational database, using the supplied PDO database handle. Differs from the simpler executeQuery() in that it takes a prepared statement and a list of values. This is the appropriate call to use either when the statement is to executed a number of times with different arguments, and there is therefore a performance benefit to be had from preparing the statement only once, or when the SQL statement is to contain varying values taken from a source that cannot be completely trusted. In this latter case it may be unsafe to construct the SQL statement by simply concatenating the parts of the statement together, since the values may contain pieces of SQL. To guard against this, a so-called SQL injection attack, it is safer to prepare the SQL statement with placeholders (also known as parameter markers, denoted by '?') and supply a list of the values to be substituted as a separate argument. Otherwise this function is the same as executeQuery() in that it uses the model that it built from the metadata to interpret the result set and returns a data graph.

Список параметров

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

prepared_statement

A prepared SQL statement to be executed against the database. This will have been prepared by PDO's prepare() method.

value_list

An array of the values to be substituted into the SQL statement in place of the placeholders. In the event that there are no placeholders or parameter markers in the SQL statement then this argument can be specified as NULL or as an empty array;

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata, For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Возвращаемые значения

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Ошибки

SDO_DAS_Relational::executePreparedQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Примеры

Пример #1 Retrieving a data object using executePreparedQuery()

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

Other examples of the use of executePreparedQuery() can be found in the example code supplied in sdo/DAS/Relational/Scenarios.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 * Use a prepared query with a placeholder.
 ***************************************************************/
$name = 'Acme';
$pdo_stmt = $dbh->prepare('select name, id from company where name=?');
$root = $das->executePreparedQuery(
    $dbh,
    $pdo_stmt,
    array($name),
    array('company.name', 'company.id'));

/**************************************************************
 * Echo name and id
 ***************************************************************/
foreach ($root['company'] as $company) {
    echo "Company obtained from the database has name = " .
    $company['name'] . " and id " . $company['id'] . "\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Relational::createRootDataObject
SDO_DAS_Relational::executeQuery
SDO-DAS-Relational Функции


Executes a given SQL query against a relational database and returns the results as a normalised data graph.

SDO_DAS_Relational::executePreparedQuery
SDO DAS XML
SDO-DAS-Relational Функции
PHP Manual

SDO_DAS_Relational::executeQuery

(^)

SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph.

Описание

SDODataObject SDO_DAS_Relational::executeQuery ( PDO $database_handle , string $SQL_statement [, array $column_specifier ] )
Внимание

Эта функция является ЭКСПЕРИМЕНТАЛЬНОЙ. Поведение этой функции, ее имя и относящаяся к ней документация могут измениться в последующих версиях PHP без уведомления. Используйте эту функцию на свой страх и риск.

Executes a given query against the relational database, using the supplied PDO database handle. Uses the model that it built from the metadata to interpret the result set. Returns a data graph.

Список параметров

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

SQL_statement

The SQL statement to be executed against the database.

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata. For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Возвращаемые значения

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Ошибки

SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Примеры

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Relational::executePreparedQuery
SDO DAS XML
SDO-DAS-Relational Функции


SDO XML Data Access Service

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
  • SDO DAS XML Функции
    • SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object
    • SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file
    • SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name
    • SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string.
    • SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document
    • SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string
    • SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file
    • SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string
    • SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject
    • SDO_DAS_XML_Document::getRootElementName — Returns root element's name
    • SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string
    • SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding
    • SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration
    • SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_Relational::executeQuery
Введение
Обработка XML


Введение

In order to use the XML Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO.

The job of the XML DAS is to move data between the application and an XML data source, which can be either a file or a URL. SDOs are always created and maintained according to a model which defines type names and what property names each type may have. For data which is from XML, this SDO model is built from a schema file written in XML schema language (an xsd file). This schema file is usually passed to the create method when the XMLDAS is initialised. The » SDO 2.0 specification defines the mapping between XML types and SDO types. There are a number of small limitations in the PHP support - not everything which is in the specification can be done - and these limitations are summarised in a later section.

User Contributed Notes

There are no user contributed notes for this page.
SDO DAS XML
Установка и настройка
SDO DAS XML


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
SDO DAS XML


Требования

The SDO XML Data Access Service requires PHP 5.1.0 or higher. It is packaged with the SDO extension and requires SDO to have been installed. See the SDO installation instructions for the details of how to do this.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

The XML Data Access Service is packaged and installed as part of the SDO extension. Please Refer SDO installation instructions.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
SDO DAS XML


Примеры

Several of the following examples are based on the letter example described in the SDO documentation. The examples assume the XML Schema for the letter is contained in a file letter.xsd and the letter instance is in the file letter.xml. These two files are reproduced here:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

Пример #1 Loading, altering, and saving an XML document

The following example shows how an XML document can be loaded from a file, altered, and written back.

<?php
/**
 * Load, update, and save an XML document
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas->loadFile("letter.xml");
   $root_data_object = $document->getRootDataObject();
   $root_data_object->date = "September 03, 2004";
   $root_data_object->firstName = "Anantoju";
   $root_data_object->lastName = "Madhu";
   $xmldas->saveFile($document, "letter-out.xml");
   echo "New file has been written:\n";
   print file_get_contents("letter-out.xml");
} catch (SDO_Exception $e) {
   print($e->getMessage());
}
?>

An instance of the XML DAS is first obtained from the SDO_DAS_XML::create() method, which is a static method of the SDO_DAS_XML class. The location of the xsd is passed as a parameter. Once we have an instance of the XML DAS initialised with a given schema, we can use it to load the instance document using the loadFile() method. There is also a loadString() method if you want to load an XML instance document from a string. If the instance document loads successfully, you will be returned an object of type SDO_DAS_XML_Document, on which you can call the getRootDataObject() method to get the SDO data object which is the root of the SDO data graph. You can then use SDO operations to change the graph. In this example we alter the date, firstName, and lastName properties. Then we use the saveFile() method to write the changed document back to the file system. The saveFile method has an optional extra integer argument which if specified will cause the XML DAS to format the XML, using the integer as the amount to indent by at each change in level on the document.

This will write the following to letter-out.xml.

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <date>September 03, 2004</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Anantoju</firstName>
  <lastName>Madhu</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</FormLetter>

Пример #2 Creating a new XML document

The previous example loaded the document from a file. This example shows how to create an SDO data graph in memory. In this example it is then saved to an XML string. Furthermore, because the letter contains both structured and unstructured content, it uses the Sequence API as well assignments to properties to construct the data graph.

<?php
/**
 * Create an XML document from scratch
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   try {
       $doc = $xmldas->createDocument();
       $rdo = $doc->getRootDataObject();
       $seq = $rdo->getSequence();
       $seq->insert("April 09, 2005", NULL, 'date');
       $seq->insert("Acme Inc. ", NULL, NULL);
       $seq->insert("United Kingdom. ");
       $seq->insert("Dear", NULL, NULL);
       $seq->insert("Tarun", NULL, "firstName");
       $seq->insert("Nayaraaa", NULL, "lastName");
       $rdo->lastName = "Nayar";
       $seq->insert("Please note that your order number ");
       $seq->insert(12345);
       $seq->insert(" has been dispatched today. Thanks for your business with us.");
       print($xmldas->saveString($doc));
   } catch (SDO_Exception $e) {
       print($e);
   }
} catch (SDO_Exception $e) {
   print("Problem creating an XML document: " . $e->getMessage());
}
?>

The createDocument() method on the XML DAS returns a document object with a single root data object corresponding to an empty document element. The element name of the document element is known from the schema file. If there is any ambiguity about what the document element is, as there can be when more than one schema has been loaded into the same XML DAS, the element name and the namespace URI can be passed to the createDocument() method.

This will emit the following output (line breaks have been inserted for readability):

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>April 09, 2005</date>
Acme Inc. United Kingdom.
Dear
<firstName>Tarun</firstName>
<lastName>Nayar</lastName>
Please note that your order number 12345 has been
dispatched today. Thanks for your business with us.
</FormLetter>

Пример #3 Setting XML document properties

This third example shows you how to set the XML version and encoding on the document object. These will be used when the XML is written out. If no XML declaration is wanted at all (perhaps you want to generate the XML as a string to embed in something) then you can use the setXMLDeclaration() method to suppress it.

<?php
/**
 * Illustrate the calls that control the XML declaration
 */
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas->loadFile("letter.xml");
   $document->setXMLVersion("1.1");
   $document->setEncoding("ISO-8859-1");
   print($xmldas->saveString($document));
?>

The XML version and encoding are set in the XML declaration at the top of the XML document.

<?xml version="1.1" encoding="utf-8"?>
.../...

Пример #4 Using an open type

This fourth example illustrates the use of an SDO open type and the use of the createDataObject() method. For this example we use the following two schema:

<schema
  xmlns="http://www.w3.org/2001/XMLSchema">

  <element name="jungle">
    <complexType>
      <sequence>
        <any minOccurs="0" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>

</schema>

Note the presence of the any element in the definition. This first schema defines the jungle complex type as containing a sequence of any other type. The other types that the example will use are defined in a second schema file:

<schema xmlns= "http://www.w3.org/2001/XMLSchema">

   <complexType name="snakeType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "length" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="bearType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "weight" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="pantherType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "colour" type="string" />
     </sequence>
   </complexType>

</schema>

Here is the example PHP code that uses these two schema files:

<?php

/**
 * Illustrate open types and the use of the addTypes() method
 */

$xmldas = SDO_DAS_XML::create();
$xmldas->addTypes("jungle.xsd"); // this is an open type i.e. the xsd specifies it can contain "any" type
$xmldas->addTypes('animalTypes.xsd');

$baloo            = $xmldas->createDataObject('','bearType');
$baloo->name      = "Baloo";
$baloo->weight    = 800;

$bagheera         = $xmldas->createDataObject('','pantherType');
$bagheera->name   = "Bagheera";
$bagheera->colour = 'inky black';

$kaa              = $xmldas->createDataObject('','snakeType');
$kaa->name        = "Kaa";
$kaa->length      = 25;

$document         = $xmldas->createDocument();
$do               = $document->getRootDataObject();
$do->bear         = $baloo;
$do->panther      = $bagheera;
$do->snake        = $kaa;

print($xmldas->saveString($document,2));

?>

These two schema files are loaded into the XML DAS with first the create() and addTypes() methods. The createDataObject() method is used to create three separate data objects. In each case the namespaceURI and typename of the type are passed to the createDataObject() method: in this example the namespace URI is blank because no namespace is used in the schema. Once the three data objects - representing a bear, a panther and a snake - have been created, a document object is created with the createDocument() method. In this case there is no ambiguity about what the document element of the document should be - as the second schema file only defines complex types, the document element can only be the global jungle element defined in the first schema. This document will have a single root data object corresponding to an empty document element jungle. As this is an open type, properties can be added at will. When the first assignment is made to $do->bear, a property bear is added to the root data object: likewise for the next two assignments. When the document is written out by the saveString() method, the resulting document is:

<?xml version="1.0" encoding="UTF-8"?>
<jungle xsi:type="jungle" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <bear xsi:type="bearType">
    <name>Baloo</name>
    <weight>800</weight>
  </bear>
  <panther xsi:type="pantherType">
    <name>Bagheera</name>
    <colour>inky black</colour>
  </panther>
  <snake xsi:type="snakeType">
    <name>Kaa</name>
    <length>25</length>
  </snake>
</jungle>

Пример #5 Finding out what you can from the document

This example is intended to illustrate how you can find the element name and namespace of the document element from the XML Document object, and the SDO type and namespace from the root data object of the XML data object, and how they relate to one another. This can be difficult to understand because there are four method calls: two can be made against the Document object, and two that can be made against any data object including the root data object. Because of the rules that define how the SDO model is derived from the XML model, when the data object concerned is the root object that represents the document object for the document, only three possible values can come back from these four method calls.

The two method calls that can be made against the document are getRootElementName() and getRootEelementURI(). These return the element name and namespace of the document element, respectively.

The two method calls that can be made against any data object are getTypeName() and getTypeNamespaceURI(). These return the SDO type name and type namespace of the data object, respectively.

Always, calling getRootElementURI() on the document object will return the same value as calling getNamespaceURI() on the root data object. Essentially, the information is all derived from the first few lines of the schema file, where there are three distinct pieces of information. For illustration, here again are the first few lines of the letter.xsd that we used above.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:letter="http://letterSchema"
            targetNamespace="http://letterSchema">

  <xsd:element name="letters" type="letter:FormLetter"/>

  <xsd:complexType name="FormLetter" mixed="true">
    .../...

The three important values are:

  • letters, the name of the document element

  • FormLetter, the name of the complex type of the document element. This is also the name of the SDO type of the root data object.

  • http://letterSchema, the namespace to which the document element belongs. This is also the namespaceURI of the SDO type of the root data object.

It is part of the XML-SDO mapping rules that when the SDO model is built from the schema file, the typename and namespaceURI of the SDO types for the root element are taken from those of the complex type of the document element, where it exists. Hence in this example the typename of the root data object is FormLetter. In the event that there is no separate complex type definition for the document element, when the type is defined inline and is anonymous, the SDO type name will be the same as the element name.

The following program loads the letter document and checks the return values from each of the four calls.

<?php
/**
 * Finding out what you can about the document and document element
 * This can be quite hard to understand because there are four calls
 * Two calls are made against the document
 * Two calls are made against the root data object and its model
 * Because of the SDO-XML mapping rules and how the SDO model is derived
 * from the XML model, only three possible values can come back from these four calls.
 * Always, $document->getRootElementURI() == (type of root data object)->namespaceURI
 * Essentially, it all comes form the first few lines of the xsd:
 * <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 *   xmlns:letter="http://letterSchema"
 *   targetNamespace="http://letterSchema">
 *   <xsd:element name="letters" type="letter:FormLetter"/>
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
$document = $xmldas->loadFile("letter.xml");
$root_do = $document->getRootDataObject();

/**
 * The "root element name" is the element name of the document element
 * in this case 'letters'
 * This matches the 'name' attribute of the document element in the xsd and matches
 * the element name from the xml
 */
echo "The document element name is " . $document->getRootElementName() . "\n";
assert($document->getRootElementName() == 'letters'); // a property of the document

/**
 * The "root element URI" is the namespace part of the element name of the document element
 * in this case 'http://letterSchema' since 'letters' is in that namespace
 * This is taken from the xsd and matches the namespace picked up from the xml
 */
echo "The document element is in the namespace " . $document->getRootElementURI() . "\n";
assert($document->getRootElementURI() == 'http://letterSchema'); // a property of the document

/**
 * The type name is taken from the SDO model
 * The XML-SDO mapping rules make this either:
 *   The name of the complexType if there is one (in this case there is)
 *   The document element name if there no complexType
 * This is taken from the xsd
 */
echo "The type name of the root data object is " . $root_do->getTypeName() . "\n";
assert($root_do->getTypeName() == 'FormLetter');

/**
 * The type's namespaceURI is taken from the SDO model
 * The XML-SDO mapping rules ensure that this will always be the same as
 * the namepace URI of the document element
 */
echo "The namespaceURI of the root data object is " . $root_do->getTypeNamespaceURI() . "\n";
assert($root_do->getTypeNamespaceURI() == 'http://letterSchema');

?>

The output from this program is as follows:

The document element name is letters
The document element is in the namespace http://letterSchema
The type name of the root data object is FormLetter
The namespaceURI of the root data object is http://letterSchema

Пример #6 Printing the SDO model

The XML DAS provides a simple means to see what types and properties have been loaded. The php "print" or "echo" instruction will print out the types and properties.

<?php
/**
 * Illustrate printing out the model
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
print $xmldas;

?>

The output from this program is as follows:

object(SDO_XML_DAS)#1 {
18 types have been defined. The types and their properties are::
1. commonj.sdo:BigDecimal
2. commonj.sdo:BigInteger
3. commonj.sdo:Boolean
4. commonj.sdo:Byte
5. commonj.sdo:Bytes
6. commonj.sdo:ChangeSummary
7. commonj.sdo:Character
8. commonj.sdo:DataObject
9. commonj.sdo:Date
10. commonj.sdo:Double
11. commonj.sdo:Float
12. commonj.sdo:Integer
13. commonj.sdo:Long
14. commonj.sdo:Short
15. commonj.sdo:String
16. commonj.sdo:URI
17. http://letterSchema:FormLetter
    - date (commonj.sdo:String)
    - firstName (commonj.sdo:String)
    - lastName (commonj.sdo:String)
18. http://letterSchema:RootType
    - letters (http://letterSchema:FormLetter)

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
SDO DAS XML Функции
SDO DAS XML


SDO DAS XML Функции

Предопределенные классы

The XML DAS provides two main classes. The first is SDO_DAS_XML which is the main class used to fetch the data from the XML source and used to write the data back. The second is the SDO_DAS_XML_Document class, which represents the data in the XML document.

There are also some exception classes which can be thrown if errors are found when looking for or parsing the xsd or xml files.

SDO_DAS_XML

This is the main class of the XML DAS, which is used fetch the data from the xml source and also used to write the data back. Other than the methods to load and save xml files,

Методы

  • create This is a static method available in the SDO_DAS_XML class. Used to construct an SDO_DAS_XML object.

  • addTypes Works in much the same way as create() but used to add the contents of a second or subsequent schema file to an XML DAS that has already been created.

  • createDataObject Can be used to construct an SDO data object of a given type.

  • createDocument Can be used to construct an XML Document object from scratch.

  • loadFile Loads the xml instance document from a file. This file can be at local file system or it can be on a remote host.

  • loadString same as the above method. Loads the xml instance which is available as string.

  • saveFile save SDO_DAS_XML_Document object as a xml file.

  • saveString save SDO_DAS_XML_Document object as a xml string.

SDO_DAS_XML_Document

This class can be used to get to the name and namespace of the document element, and to get to the root data object of the document. Lastly, it can also be used to set the XML version and encoding of a document on output.

Методы

  • getRootDataObject gets the root DataObject.

  • getRootElementName gets the root DataObject's name.

  • getRootElementURI gets the root DataObject's URI.

  • setEncoding sets the encoding string with the given value.

  • setXMLDeclaraion to set/unset the xml declaration.

  • setXMLVersion sets the xml version with the given value.

SDO_DAS_XML_ParserException

Is a subclass of SDO_Exception. Thrown for any parser errors while loading the xsd/xml file.

SDO_DAS_XML_FileException

Is a subclass of SDO_Exception. Thrown by any of the methods that load data from a file, when the file cannot be found.

Limitations compared with SDO 2.0 specification

The » SDO 2.0 specification defines the mapping between XML types and SDO types. With Java SDO, this mapping is implemented by the XMLHelper. With SDO for PHP, this mapping is implemented by the XML Data Access Service. The XML DAS implements the mapping described in the SDO 2.0 specification with some restrictions. A detailed list is of the limitations is:

XML Simple Types

  1. Simple Type with sdoJava:instanceClass - no PHP equivalent provided.

  2. Simple Type with sdoJava:extendedInstanceClass - no PHP equivalent provided.

  3. Simple Type with list of itemType.

  4. Simple Type with union.

XML Complex Types

  1. Complex Type with sdo:aliasName - no PHP support for SDO Type aliases.

XSD Attribute

  1. Attribute with sdo:aliasName - no PHP support for SDO property aliases.

  2. Attribute with default value - no PHP support for SDO property defaults.

  3. Attribute with fixed value - no PHP support for SDO read-only properties or default values.

  4. Attribute referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="...".

  5. Attribute with bi-directional property to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

XSD Elements

  1. Element with sdo:aliasName - no PHP support for SDO property aliases.

  2. Element with substitution group.

XSD Elements with Simple Type

  1. Element of SimpleType with default - no PHP support for SDO defaults

  2. Element of SimpleType with fixed value - no PHP support for SDO read-only properties or default values.

  3. Element of SimpleType with sdo:string - no support for sdo:string="true".

  4. Element referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="..."

  5. Element with bi-directional reference to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

Содержание

  • SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object
  • SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file
  • SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name
  • SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string.
  • SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document
  • SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string
  • SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file
  • SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string
  • SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject
  • SDO_DAS_XML_Document::getRootElementName — Returns root element's name
  • SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string
  • SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding
  • SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration
  • SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version

User Contributed Notes

There are no user contributed notes for this page.
Примеры
SDO_DAS_XML::addTypes
SDO DAS XML


To load a second or subsequent schema file to a SDO_DAS_XML object

SDO DAS XML Функции
SDO_DAS_XML::create
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::addTypes

(^)

SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object

Описание

void SDO_DAS_XML::addTypes ( string $xsd_file )

Load a second or subsequent schema file to an XML DAS that has already been created with the static method create(). Although the file may be any valid schema file, a likely reason for using this method is to add a schema file containing definitions of extra complex types, hence the name. See Example 4 of the parent document for an example.

Список параметров

xsd_file

Path to XSD Schema file.

Возвращаемые значения

None if successful, otherwise throws an exception as described below.

Ошибки

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

User Contributed Notes

There are no user contributed notes for this page.
SDO DAS XML Функции
SDO_DAS_XML::create
SDO DAS XML Функции


To create SDO_DAS_XML object for a given schema file

SDO_DAS_XML::addTypes
SDO_DAS_XML::createDataObject
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::create

(^)

SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file

Описание

SDO_DAS_XML SDO_DAS_XML::create ([ mixed $xsd_file [, string $key ]] )

This is the only static method of SDO_DAS_XML class. Used to instantiate SDO_DAS_XML object.

Список параметров

xsd_file

Path to XSD Schema file. This is optional. If omitted a DAS will be created that only has the SDO base types defined. Schema files can then be loaded with the addTypes() method. Can be string or array of values.

key

Возвращаемые значения

Returns SDO_DAS_XML object on success otherwise throws an exception as described below.

Ошибки

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::addTypes
SDO_DAS_XML::createDataObject
SDO DAS XML Функции


Creates SDO_DataObject for a given namespace URI and type name

SDO_DAS_XML::create
SDO_DAS_XML::createDocument
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::createDataObject

(^)

SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name

Описание

SDO_DataObject SDO_DAS_XML::createDataObject ( string $namespace_uri , string $type_name )

Creates SDO_DataObject for a given namespace URI and type name. The type should be defined in the underlying model otherwise SDO_TypeNotFoundException will be thrown.

Список параметров

namespace_uri

Namespace URI of the type name.

type_name

Type Name.

Возвращаемые значения

Returns SDO_DataObject on success.

Ошибки

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::create
SDO_DAS_XML::createDocument
SDO DAS XML Функции


Creates an XML Document object from scratch, without the need to load a document from a file or string.

SDO_DAS_XML::createDataObject
SDO_DAS_XML::loadFile
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::createDocument

(^)

SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string.

Описание

SDO_DAS_XML_Document SDO_DAS_XML::createDocument ([ string $document_element_name ] )
SDO_DAS_XML_Document SDO_DAS_XML::createDocument ( string $document_element_namespace_URI , string $document_element_name [, SDO_DataObject $dataobject ] )

Creates an XML Document object. This will contain just one empty root element on which none of the properties will have been set. The purpose of this call is to allow an application to create an XML document from scratch without the need to load a document from a file or string. The document that is created will be as if a document had been loaded that contained just a single empty document element with no attributes set or elements within it.

createDocument() may need to be told what the document element is. This will not be necessary in simple cases. When there is no ambiguity then no parameter need be passed to the method. However it is possible to load more than one schema file into the same XML DAS and in this case there may be more than one possible document element defined: furthermore it is even possible that there are two possible document elements that differ only in the namespace. To cope with these cases it is possible to specify either the document element name, or both the document element name and namespace to the method.

Список параметров

document_element_name

The name of the document element. Only needed if there is more than one possibility.

document_element_namespace_URI

The namespace part of the document element name. Only needed if there is more than one possible document element with the same name.

dataobject

Возвращаемые значения

Returns an SDO_XML_DAS_Document object on success.

Ошибки

SDO_UnsupportedOperationException

Thrown if an element name or element name and namespace URI is passed, but not found in the underlying model.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::createDataObject
SDO_DAS_XML::loadFile
SDO DAS XML Функции


Returns SDO_DAS_XML_Document object for a given path to xml instance document

SDO_DAS_XML::createDocument
SDO_DAS_XML::loadString
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::loadFile

(^)

SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document

Описание

SDO_XMLDocument SDO_DAS_XML::loadFile ( string $xml_file )

Constructs the tree of SDO_DataObjects from the given address to xml instance document. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Список параметров

xml_file

Path to Instance document. This can be a path to a local file or it can be a URL.

Возвращаемые значения

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Ошибки

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::createDocument
SDO_DAS_XML::loadString
SDO DAS XML Функции


Returns SDO_DAS_XML_Document for a given xml instance string

SDO_DAS_XML::loadFile
SDO_DAS_XML::saveFile
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::loadString

(^)

SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string

Описание

SDO_DAS_XML_Document SDO_DAS_XML::loadString ( string $xml_string )

Constructs the tree of SDO_DataObjects from the given xml instance string. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Список параметров

xml_string

xml string.

Возвращаемые значения

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Ошибки

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if the a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::loadFile
SDO_DAS_XML::saveFile
SDO DAS XML Функции


Saves the SDO_DAS_XML_Document object to a file

SDO_DAS_XML::loadString
SDO_DAS_XML::saveString
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::saveFile

(^)

SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file

Описание

void SDO_DAS_XML::saveFile ( SDO_XMLDocument $xdoc , string $xml_file [, int $indent ] )

Saves the SDO_DAS_XML_Document object to a file.

Список параметров

xdoc

SDO_DAS_XML_Document object.

xml_file

xml file.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Возвращаемые значения

None.

Ошибки

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::loadString
SDO_DAS_XML::saveString
SDO DAS XML Функции


Saves the SDO_DAS_XML_Document object to a string

SDO_DAS_XML::saveFile
SDO_DAS_XML_Document::getRootDataObject
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML::saveString

(^)

SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string

Описание

string SDO_DAS_XML::saveString ( SDO_XMLDocument $xdoc [, int $indent ] )

Saves the SDO_DAS_XML_Document object to string.

Список параметров

xdoc

SDO_DAS_XML_Document object.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Возвращаемые значения

xml string.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::saveFile
SDO_DAS_XML_Document::getRootDataObject
SDO DAS XML Функции


Returns the root SDO_DataObject

SDO_DAS_XML::saveString
SDO_DAS_XML_Document::getRootElementName
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML_Document::getRootDataObject

(^)

SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject

Описание

SDO_DataObject SDO_DAS_XML_Document::getRootDataObject ( void )

Returns the root SDO_DataObject.

Список параметров

Возвращаемые значения

Returns the root SDO_DataObject.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML::saveString
SDO_DAS_XML_Document::getRootElementName
SDO DAS XML Функции


Returns root element's name

SDO_DAS_XML_Document::getRootDataObject
SDO_DAS_XML_Document::getRootElementURI
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML_Document::getRootElementName

(^)

SDO_DAS_XML_Document::getRootElementName — Returns root element's name

Описание

string SDO_DAS_XML_Document::getRootElementName ( void )

Returns root element's name.

Список параметров

Возвращаемые значения

Returns root element's name.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML_Document::getRootDataObject
SDO_DAS_XML_Document::getRootElementURI
SDO DAS XML Функции


Returns root element's URI string

SDO_DAS_XML_Document::getRootElementName
SDO_DAS_XML_Document::setEncoding
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML_Document::getRootElementURI

(^)

SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string

Описание

string SDO_DAS_XML_Document::getRootElementURI ( void )

Returns root element's URI string.

Список параметров

Возвращаемые значения

Returns root element's URI string.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML_Document::getRootElementName
SDO_DAS_XML_Document::setEncoding
SDO DAS XML Функции


Sets the given string as encoding

SDO_DAS_XML_Document::getRootElementURI
SDO_DAS_XML_Document::setXMLDeclaration
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML_Document::setEncoding

(^)

SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding

Описание

void SDO_DAS_XML_Document::setEncoding ( string $encoding )

Sets the given string as encoding.

Список параметров

encoding

Encoding string.

Возвращаемые значения

None.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML_Document::getRootElementURI
SDO_DAS_XML_Document::setXMLDeclaration
SDO DAS XML Функции


Sets the xml declaration

SDO_DAS_XML_Document::setEncoding
SDO_DAS_XML_Document::setXMLVersion
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML_Document::setXMLDeclaration

(^)

SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration

Описание

void SDO_DAS_XML_Document::setXMLDeclaration ( bool $xmlDeclatation )

Controls whether an XML declaration will be generated at the start of the XML document. Set to TRUE to generate the XML declaration, or FALSE to suppress it.

Список параметров

xmlDeclatation

Boolean value to set the XML declaration.

Возвращаемые значения

None.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML_Document::setEncoding
SDO_DAS_XML_Document::setXMLVersion
SDO DAS XML Функции


Sets the given string as xml version

SDO_DAS_XML_Document::setXMLDeclaration
SimpleXML
SDO DAS XML Функции
PHP Manual

SDO_DAS_XML_Document::setXMLVersion

(^)

SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version

Описание

void SDO_DAS_XML_Document::setXMLVersion ( string $xmlVersion )

Sets the given string as xml version.

Список параметров

xmlVersion

xml version string.

Возвращаемые значения

None.

User Contributed Notes

There are no user contributed notes for this page.
SDO_DAS_XML_Document::setXMLDeclaration
SimpleXML
SDO DAS XML Функции


SimpleXML

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • Базовое использование SimpleXML
    • Работа с ошибками XML
  • SimpleXMLElement — Класс SimpleXMLElement
    • SimpleXMLElement::addAttribute — Добавляет атрибут к SimpleXML-элементу
    • SimpleXMLElement::addChild — Добавляет дочерний элемент к узлу XML
    • SimpleXMLElement::asXML — Возвращает сформированный XML документ в виде строки используя SimpleXML элемент
    • SimpleXMLElement::attributes — Возвращает атрибуты элемента
    • SimpleXMLElement::children — Поиск дочерних элементов данного узла
    • SimpleXMLElement::__construct — Создание нового SimpleXMLElement объекта
    • SimpleXMLElement::count — Считает количество дочерних элементов у текущего элемента
    • SimpleXMLElement::getDocNamespaces — Возвращает объявленное пространство имен в документе
    • SimpleXMLElement::getName — Получение имени XML элемента
    • SimpleXMLElement::getNamespaces — Получение пространств имен, используемых в документе
    • SimpleXMLElement::registerXPathNamespace — Создает префикс/пространство имен контекста для следующего XPath запроса
    • SimpleXMLElement::saveXML — Псевдоним SimpleXMLElement::asXML
    • SimpleXMLElement::xpath — Запускает XPath запрос к XML данным
  • SimpleXMLIterator — Класс SimpleXMLIterator
    • SimpleXMLIterator::current — Возвращает текущий элемент
    • SimpleXMLIterator::getChildren — Возвращает вложенные элементы текущего элемента
    • SimpleXMLIterator::hasChildren — Проверяет, имеет ли текущий элемент вложенные элементы
    • SimpleXMLIterator::key — Возвращает текущий ключ
    • SimpleXMLIterator::next — Перемещает итератор к следующему элементу
    • SimpleXMLIterator::rewind — Возвращает итератор к первому элементу
    • SimpleXMLIterator::valid — Проверяет, является ли текущий элемент допустимым
  • SimpleXML
    • simplexml_import_dom — Получает объект класса SimpleXMLElement из узла DOM.
    • simplexml_load_file — Интерпретирует XML-файл в объект
    • simplexml_load_string — Интерпретирует строку с XML в объект

User Contributed Notes

xaviered at gmail dot com 17-May-2012 07:00
Here is a recursive function that will convert a given SimpleXMLElement object into an array, preserving namespaces and attributes.

<?php
function xmlObjToArr($obj) {
        $namespace = $obj->getDocNamespaces(true);
        $namespace[NULL] = NULL;

        $children = array();
        $attributes = array();
        $name = strtolower((string)$obj->getName());

        $text = trim((string)$obj);
        if( strlen($text) <= 0 ) {
            $text = NULL;
        }

        // get info for all namespaces
        if(is_object($obj)) {
            foreach( $namespace as $ns=>$nsUrl ) {
                // atributes
                $objAttributes = $obj->attributes($ns, true);
                foreach( $objAttributes as $attributeName => $attributeValue ) {
                    $attribName = strtolower(trim((string)$attributeName));
                    $attribVal = trim((string)$attributeValue);
                    if (!empty($ns)) {
                        $attribName = $ns . ':' . $attribName;
                    }
                    $attributes[$attribName] = $attribVal;
                }

                // children
                $objChildren = $obj->children($ns, true);
                foreach( $objChildren as $childName=>$child ) {
                    $childName = strtolower((string)$childName);
                    if( !empty($ns) ) {
                        $childName = $ns.':'.$childName;
                    }
                    $children[$childName][] = xmlObjToArr($child);
                }
            }
        }

        return array(
            'name'=>$name,
            'text'=>$text,
            'attributes'=>$attributes,
            'children'=>$children
        );
    }
?>
andrew at andrewluecke dot com 01-Apr-2012 12:00
In many situations, the methods of supporting CDATA in comments above may inappropriate (especially if an external library is using simplexml).

Instead, you may simply cast CDATA elements to a string, such as:
print (string)$xml->cdataelement or (string)$xml->{'cdataelement'}

In my case, it eliminated the need for me to edit an external library file every time an upgrade for the file was released.
thedoc8786 at gmail dot com 23-Mar-2012 07:42
FAIL! This function works better than the one I posted below:

<?php
    function toArray($xml) {
        $array = json_decode(json_encode($xml), TRUE);

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( empty($value) ) $array[$key] = NULL;
            elseif ( is_array($value) ) $array[$key] = toArray($value);
        }

        return $array;
    }
thedoc8786 at gmail dot com 23-Mar-2012 04:19
I know it is over-done, but the following is a super-short example of a XML to Array conversion function (recursive):

<?php
    function toArray(SimpleXMLElement $xml) {
        $array = (array)$xml;

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( $value instanceof SimpleXMLElement ) {
                $array[$key] = empty($value) ? NULL : toArray($value);
            }
        }
        return $array;
    }
salvocucinella at gmail dot com 30-Sep-2011 01:59
Here is a snippet to convert a simple object to XML.
A class that does the job and an example how to use it

<?php
class Obj2xml {

    var $xmlResult;

    function __construct($rootNode){
        $this->xmlResult = new SimpleXMLElement("<$rootNode></$rootNode>");
    }

    private function iteratechildren($object,$xml){
        foreach ($object as $name=>$value) {
            if (is_string($value) || is_numeric($value)) {
                $xml->$name=$value;
            } else {
                $xml->$name=null;
                $this->iteratechildren($value,$xml->$name);
            }
        }
    }

    function toXml($object) {
        $this->iteratechildren($object,$this->xmlResult);
        return $this->xmlResult->asXML();
    }
}

    //----test object----
    $ob->field1=10;
    $ob->field2->field21="textA";
    $ob->field2->field22="textB";
    //----test object----

    $converter=new Obj2xml("root");

    header("Content-Type:text/xml");

    echo $converter->toXml($ob);

?>
xananax at yelostudio dot com 07-Sep-2011 06:25
None of the XML2Array functions that I found satisfied me completely; Their results did not always fit the project I was working on, and I found none that would account for repeating XML elements (such as
<fields><field/><field/><field/></fields>)
So I rolled out my own; hope it helps someone.
<?php
/**
 * Converts a simpleXML element into an array. Preserves attributes.<br/>
 * You can choose to get your elements either flattened, or stored in a custom
 * index that you define.<br/>
 * For example, for a given element
 * <code>
 * <field name="someName" type="someType"/>
 * </code>
 * <br>
 * if you choose to flatten attributes, you would get:
 * <code>
 * $array['field']['name'] = 'someName';
 * $array['field']['type'] = 'someType';
 * </code>
 * If you choose not to flatten, you get:
 * <code>
 * $array['field']['@attributes']['name'] = 'someName';
 * </code>
 * <br>__________________________________________________________<br>
 * Repeating fields are stored in indexed arrays. so for a markup such as:
 * <code>
 * <parent>
 *     <child>a</child>
 *     <child>b</child>
 *     <child>c</child>
 * ...
 * </code>
 * you array would be:
 * <code>
 * $array['parent']['child'][0] = 'a';
 * $array['parent']['child'][1] = 'b';
 * ...And so on.
 * </code>
 * @param simpleXMLElement    $xml            the XML to convert
 * @param boolean|string    $attributesKey    if you pass TRUE, all values will be
 *                                            stored under an '@attributes' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $childrenKey    if you pass TRUE, all values will be
 *                                            stored under an '@children' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $valueKey        if you pass TRUE, all values will be
 *                                            stored under an '@values' index. Note
 *                                            that you can also pass a string to
 *                                            change the default index.<br/>
 *                                            defaults to null.
 * @return array the resulting array.
 */
function simpleXMLToArray(SimpleXMLElement $xml,$attributesKey=null,$childrenKey=null,$valueKey=null){

    if($childrenKey && !is_string($childrenKey)){$childrenKey = '@children';}
    if($attributesKey && !is_string($attributesKey)){$attributesKey = '@attributes';}
    if($valueKey && !is_string($valueKey)){$valueKey = '@values';}

    $return = array();
    $name = $xml->getName();
    $_value = trim((string)$xml);
    if(!strlen($_value)){$_value = null;};

    if($_value!==null){
        if($valueKey){$return[$valueKey] = $_value;}
        else{$return = $_value;}
    }

    $children = array();
    $first = true;
    foreach($xml->children() as $elementName => $child){
        $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
        if(isset($children[$elementName])){
            if(is_array($children[$elementName])){
                if($first){
                    $temp = $children[$elementName];
                    unset($children[$elementName]);
                    $children[$elementName][] = $temp;
                    $first=false;
                }
                $children[$elementName][] = $value;
            }else{
                $children[$elementName] = array($children[$elementName],$value);
            }
        }
        else{
            $children[$elementName] = $value;
        }
    }
    if($children){
        if($childrenKey){$return[$childrenKey] = $children;}
        else{$return = array_merge($return,$children);}
    }

    $attributes = array();
    foreach($xml->attributes() as $name=>$value){
        $attributes[$name] = trim($value);
    }
    if($attributes){
        if($attributesKey){$return[$attributesKey] = $attributes;}
        else{$return = array_merge($return, $attributes);}
    }

    return $return;
}
?>
soloman at textgrid dot com 09-Aug-2011 05:06
Three line xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

?>

Ta da!
james at esilogix dot com 21-Jul-2011 07:55
Here is a function I wrote that converts an associative array into an xml output.  It also includes tabs to ensure the xml output is easy to read.

<?php
 /*
  * James Earlywine - July 20th 2011
  *
  * Translates a jagged associative array
  * to XML
  *
  * @param : $theArray - The jagged Associative Array
  * @param : $tabCount - for persisting tab count across recursive function calls
  */
function assocToXML ($theArray, $tabCount=2) {
    //echo "The Array: ";
    //var_dump($theArray);
    // variables for making the XML output easier to read
    // with human eyes, with tabs delineating nested relationships, etc.

    $tabCount++;
    $tabSpace = "";
    $extraTabSpace = "";
     for ($i = 0; $i<$tabCount; $i++) {
        $tabSpace .= "\t";
     }

     for ($i = 0; $i<$tabCount+1; $i++) {
        $extraTabSpace .= "\t";
     }

    // parse the array for data and output xml
    foreach($theArray as $tag => $val) {
        if (!is_array($val)) {
            $theXML .= PHP_EOL.$tabSpace.'<'.$tag.'>'.htmlentities($val).'</'.$tag.'>';
        } else {
            $tabCount++;
            $theXML .= PHP_EOL.$extraTabSpace.'<'.$tag.'>'.assocToXML($val, $tabCount);
            $theXML .= PHP_EOL.$extraTabSpace.'</'.$tag.'>';
        }
    }

return $theXML;
}
?>
streaver91 at gmail dot com 04-May-2011 08:49
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different.

I think the array structure developed by svdmeer can fit for XML, and fits well.

here is an example array converted from an xml file:
array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@text"=>"some text",
)

or if it has childrens, that can be:

array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@items"=>array(
    0=>array(
        "@tag"=>"name","@text"=>"some text"
    )
)

Also, I wrote a function that can change that array back to XML.

<?php
function array2XML($arr,$root) {
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>");
$f = create_function('$f,$c,$a','
        foreach($a as $v) {
            if(isset($v["@text"])) {
                $ch = $c->addChild($v["@tag"],$v["@text"]);
            } else {
                $ch = $c->addChild($v["@tag"]);
                if(isset($v["@items"])) {
                    $f($f,$ch,$v["@items"]);
                }
            }
            if(isset($v["@attr"])) {
                foreach($v["@attr"] as $attr => $val) {
                    $ch->addAttribute($attr,$val);
                }
            }
        }');
$f($f,$xml,$arr);
return $xml->asXML();
}
?>
info at kevinbelanger dot com 20-Jan-2011 09:07
An easer way to get the text node if you can't access to [0] property of the simpleXMLElement is to use the sprintf function.

As gwhitescarver at yahoo dot com said, in some version of php 5 it is hard to access to text node of an element, but when you print the element, the [0] property is automaticaly returned.

Like if you echo() the element, the text node is return.

The sprintf function do the same:

<?php
$a = array();

foreach ($xml->children() as $child) {
 $a[$child->getName()] = sprintf("%s", $child);
}
?>
phil at dier dot us 19-Jan-2011 11:37
Here's a function I came up with to convert an associative array to XML.  Works for multidimensional arrays as well.

<?php
function assocArrayToXML($root_element_name,$ar)
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    $ch=$c->addChild($k);
                    $f($f,$ch,$v);
                } else {
                    $c->addChild($k,$v);
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}
?>
philipp at strazny dot com 23-Nov-2010 05:33
Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn't know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.

<?php
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
    $children = array();
    if ($xml instanceof SimpleXMLElement) {
        $children = $xml->children();
        if ($root){ // we're at root
            $path .= '/'.$xml->getName();
        }
    }
    if ( count($children) == 0 ){
        $return[$path] = (string)$xml;
        return;
    }
    $seen=array();
    foreach ($children as $child => $value) {
        $childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
        if ( !isset($seen[$childname])){
            $seen[$childname]=0;
        }
        $seen[$childname]++;
        XMLToArrayFlat($value, $return, $path.'/'.$child.'['.$seen[$childname].']');
    }
}
?>

Use like this:

<?php
$xml = simplexml_load_string(...some xml string...);
$xmlarray = array(); // this will hold the flattened data
XMLToArrayFlat($xml, $xmlarray, '', true);
?>

You can also pull multiple files in one array:

<?php
foreach($files as $file){
    $xml = simplexml_load_file($file);
    XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
?>
The respective filename/path is thus prefixed to each key.
kristof at viewranger dot com 18-Nov-2010 05:14
If you tried to load an XML file with this, but the CDATA parts were not loaded for some reason, is because you should do it this way:

$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);

This converts CDATA to String in the returning object.
sherwinterunez at yahoo dot com 01-Sep-2010 11:15
<?php

// Sherwin R. Terunez
//
// This is my own version of XML Object to Array
//

function amstore_xmlobj2array($obj, $level=0) {

    $items = array();

    if(!is_object($obj)) return $items;

    $child = (array)$obj;

    if(sizeof($child)>1) {
        foreach($child as $aa=>$bb) {
            if(is_array($bb)) {
                foreach($bb as $ee=>$ff) {
                    if(!is_object($ff)) {
                        $items[$aa][$ee] = $ff;
                    } else
                    if(get_class($ff)=='SimpleXMLElement') {
                        $items[$aa][$ee] = amstore_xmlobj2array($ff,$level+1);
                    }
                }
            } else
            if(!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(get_class($bb)=='SimpleXMLElement') {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            }
        }
    } else
    if(sizeof($child)>0) {
        foreach($child as $aa=>$bb) {
            if(!is_array($bb)&&!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(is_object($bb)) {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            } else {
                foreach($bb as $cc=>$dd) {
                    if(!is_object($dd)) {
                        $items[$obj->getName()][$cc] = $dd;
                    } else
                    if(get_class($dd)=='SimpleXMLElement') {
                        $items[$obj->getName()][$cc] = amstore_xmlobj2array($dd,$level+1);
                    }
                }
            }
        }
    }

    return $items;
}

?>
svdmeer at xs4all dot nl 23-May-2010 11:57
Simple XML in an array of strings without objects:

<?php
function xml2array($xml) {
    $arXML=array();
    $arXML['name']=trim($xml->getName());
    $arXML['value']=trim((string)$xml);
    $t=array();
    foreach($xml->attributes() as $name => $value){
        $t[$name]=trim($value);
    }
    $arXML['attr']=$t;
    $t=array();
    foreach($xml->children() as $name => $xmlchild) {
        $t[$name][]=xml2array($xmlchild); //FIX : For multivalued node
    }
    $arXML['children']=$t;
    return($arXML);
}
?>
[EDITOR thiago NOTE: Function has fixes and improvements by n dot dhuygelaere at oieau dot fr]
Ashok dot 893 at gmail dot com 25-Apr-2010 10:48
This is very simple way to convert all applicable objects into associative array.  This works with not only SimpleXML but any kind of object. The input can be either array or object. This function also takes an options parameter as array of indices to be excluded in the return array. And keep in mind, this returns only the array of non-static and accessible variables of the object since using the function get_object_vars().

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();

    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }

    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}
?>

Usage:

<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
?>
michael dot allen at emp dot shentel dot com 15-Apr-2010 11:06
Here is a very robust SimpleXML parser.  Can be used to load files, strings, or DOM into SimpleXML, or can be used to perform the reverse when handed SimpleXML.

<?php
/**
 * XMLParser Class File
 *
 * This class loads an XML document into a SimpleXMLElement that can
 * be processed by the calling application.  This accepts xml strings,
 * files, and DOM objects.  It can also perform the reverse, converting
 * an SimpleXMLElement back into a string, file, or DOM object.
 */
class XMLParser {
    /**
     * While parsing, parse the supplied XML document.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML document file.
     *
     * @param string $doc the xml document location path
     * @return object
     */
    public static function loadFile($doc) {
        if (file_exists($doc)) {
            return simplexml_load_file($doc);
        } else {
            throw new Exception ("Unable to load the xml file " .
                                 "using: \"$doc\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML string.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML string.
     *
     * @param string $string the xml document string
     * @return object
     */
    public static function loadString($string) {
        if (isset($string)) {
            return simplexml_load_string($string);
        } else {
            throw new Exception ("Unable to load the xml string " .
                                 "using: \"$string\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML DOM node.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML DOM node.
     *
     * @param object $dom the xml DOM node
     * @return object
     */
    public static function loadDOM($dom) {
        if (isset($dom)) {
            return simplexml_import_dom($dom);
        } else {
            throw new Exception ("Unable to load the xml DOM node " .
                                 "using: \"$dom\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the SimpleXMLElement.
     *
     * Sets up a XML file, string, or DOM object based on success of
     * parsing the XML DOM node.
     *
     * @param object $path the xml document location path
     * @param string $type the return type (string, file, dom)
     * @param object $simplexml the simple xml element
     * @return mixed
     */
    public static function loadSXML($simplexml, $type, $path) {
        if (isset($simplexml) && isset($type)) {
        switch ($type) {
            case 'string':
                return $simplexml->asXML();
            break;
            case 'file':
                if (isset($path)) {
                    return $simplexml->asXML($path);
                } else {
                    throw new Exception ("Unable to create the XML file. Path is missing or" .
                                         "is invalid: \"$path\"", E_USER_ERROR);
                }
            break;
            case 'dom':
                return dom_import_simplexml($simplexml);
            break;
        }
        } else {
            throw new Exception ("Unable to load the simple XML element " .
                                 "using: \"$simplexml\"", E_USER_ERROR);
        }
    }
}
?>
emmanuel 17-Feb-2010 10:21
dynamic sql in php using xml:

test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<sql>
    <statement>
        SELECT * FROM USERS
        <call criteria="byId">WHERE id = %d</call>
        <call criteria="byUsername">WHERE username = "%s"</call>;
    </statement>
</sql>

index.php:
<?php
function callMe($param) {
    $search = array('byUsername' => 'dynsql');

    if (isset($search[$param[1]])) {
        return sprintf($param[2], $search[$param[1]]);
    }

    return "";
}

$xml = simplexml_load_file("test.xml");
$string = $xml->statement->asXML();
$string = preg_replace_callback('/<call criteria="(\w+)">(.*?)<\/call>/', 'callMe', $string);
$node = simplexml_load_string($string);
echo $node;
?>

obviously, this example can be improved [in your own code.]
jakep at insperia dot com 28-Jan-2010 01:44
If you decide to include a hyphen or a dash in the name of your attribute things get a bit interesting. The code has to be adjusted since the name of a class method cannot contain "-". To make it work, the attribute name has to include braces and single quotes (e.g. "{'name'}").

Credit http://aaronz-sakai.blogspot.com
mahmutta at gmail dot com 20-Jan-2010 12:58
while using simple xml and get double or float int value from xml object for using math operations (+ * - / ) some errors happens on the operation, this is because of simple xml returns everythings to objects.
exmple;

<?php

$name = "somestring";
$size = 11.45;
$xml = '
<xml>
 <name>somestring</name>
 <size>11.45</size>
</xml>';

$xmlget = simplexml_load_string($xml)

echo $xml->size*2;    // 20  its false
// ($xml->size is an object (int)11 and  (45) )

// this is true
echo $size*2;            // 22.90
echo (float)$size*2;   // 22.90
?>
Danny from holland 03-Dec-2009 05:58
I tested all the scripts ive found on this page but none of them wasnt working.

ive made an new script that will work and wont get any memory errors with big xml feeds

<?php
print "<pre>";

$root = simplexml_load_string($XML_URL);
$data = get_object_vars($root);

$producten = array();

foreach ($data['product'] as $keys => $values) {
    $producten['product'][$keys] = get_object_vars($data['product']);

    foreach ($values as $key => $value) {
        $value = str_replace("\r\n", '<br />', $value);
        $value = str_replace("\r", '<br />', $value);
        $value = str_replace("\n", '<br />', $value);
        $producten['product'][$keys][$key] = $value;
    }

}
print_R($producten);

print "</pre>";
?>
antoine dot rabanes at gmail dot com 16-Oct-2009 07:22
if for some reasons you need the string value instead of the simpleXML Object you can cast the return value as a string.

exemple:

<?php
$all_api_call = simplexml_load_file($url);
$all_api = array();
$all_api = $all_api_call->result;
$list_all_api_name = array();
$i = 0;
foreach ($all_api->children() as $funcky_function)
{
    $string_tmp = (string )$funcky_function->function;
    $list_all_api_name[$i++] = $putain;
}
?>

...
spcmky at gmail dot com 14-Oct-2009 10:49
There are issues with most examples of converting a simplexml object into an array recursively.  The situation that fails is when you have a value for an element and attributes.  For example:

<results found="yes">
  <warehouse>
    <name>WH3</name>
    <phone>2-1121</phone>
  </warehouse>
  <items count="3">
    <item id="E1120" bin="AA21">Desk</item>
    <item id="E1121" bin="FG03">Chair</item>
    <item id="E1122" bin="CD00">Table</item>
  </items>
</results>

If you :

<?php
$obj = simplexml_load_string($xml);
print_r($obj);
?>

You will get:

(
    [@attributes] => Array
        (
            [found] => yes
        )

    [warehouse] => SimpleXMLElement Object
        (
            [name] => WH3
            [phone] => 2-1121
        )

    [items] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [count] => 3
                )

            [item] => Array
                (
                    [0] => Desk
                    [1] => Chair
                    [2] => Table
                )

        )

)

Where is the rest of the data for the items?  If you were to traverse recursively through the object the item information is in fact there.  The problem is how to represent an element as an array that has a value and attributes.  Most of the solution's just ignore the attributes.

print_r, var_dump, and get_object_vars ignore the attributes in this special case from what I've found.

Here is a simple function to convert the object into an array but it still fails to deal with the attributes.
<?php
function ToArray ( $data )
{
  if (is_object($data)) $data = get_object_vars($data);
  return (is_array($data)) ? array_map(__FUNCTION__,$data) : $data;
}
?>

So why even bother trying to convert the object to an array?  Simply because of serialization for caching the object.

One solution would be to create an index called "value" and assign that the element's value.  This way the attributes could coexist.
walter 12-Jun-2009 07:58
Working fix for the infamous SimpleXML + memcache bug.

Improves code at http://tinyurl.com/bmoon-simplexml to actually work for arbitrary-depth structures.  (Because neither the function nor the json_decode(json_encode($obj)) hack listed there worked for me.)

There's probably some superfluous code in here that could be improved on -- but it works!

<?php
 # convert a structure that may include objects to a pure
 # array-based structure (that can be stored in memcache)
 #  ... includes support for simplexml!
 # (nb: may have problems with infinite recursive structs)
 function enforce_array($obj) {
  $array = (array)$obj;
  if(empty($array)) {
   $array = '';
  }
  else {
   foreach($array as $key=>$value) {
    if(!is_scalar($value)) {
     if(is_a($value,'SimpleXMLElement')) {
      $tmp = memcache_objects_to_array($value);
      if(!is_array($tmp)) {
       $tmp = ''.$value;
      }
      $array[$key] = $tmp;
     }
     else {
      $array[$key] = enforce_array($value);
     }
    }
    else {
     $array[$key] = $value;
    }
   }
  }
  return $array;
 }
?>
mail at kleineedv dot de 28-Apr-2009 12:37
I had a problem with simplexml reading nodes from an xml file. It always return an SimpleXML-Object but not the text inside the node.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <Id>123</Id>
</Test>

Reading this xml into a variable called $xml and then doing the following
<?php
$myId = $xml->Id;
?>
Did not return 123 in $myId, but instead I got a SimpleXMLElement Object.

The solution is simple, when you know it. Use explicit string conversion.
<?php
$myId = (string)$xml->Id;
?>
oscargodson at gmail dot com 25-Jan-2009 03:05
To add to what others have said, you can't directly put a $_GET or $_POST value into a variable then into an attribute using SimpleXML. You must first convert it to an integer.

This will NOT work

<?php
      $page_id = $_GET['id'];
      echo $xml->page[$page_id]
?>

You will get something like:
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/mysite/index.php on line 10

However, this WILL work and is much simpler then using (string) or other methods.
<?php
   $page_id = intval($_GET['id']);
   echo $xml->page[$page_id]
?>
bxt at die-optimisten dot net 26-Nov-2008 07:47
Addition to QLeap's post:
SimpleXML will return a reference to an object containing the node value and you can't use references in session variables as there is no feasible way to restore a reference to another variable.

This won't work too:
$val=$this->xml->node->attributes()->name;
echo $array[$val]; // will cause a warning because of the wrong index type.

You have to convert/cast to a String first:
echo $array[(string)$val];

This will work as expected, because converting will call the __toString() method. Therefor echo works too:
echo $val; // will display the name
QLeap 18-Nov-2008 02:27
Storing SimpleXMLElement values in $_SESSION does not work. Saving the results as an object or individual elements of the object will result in the dreaded "Warning: session_start() [function.session-start]: Node no longer exists" error.

For example, this does not work:

    $xml  = new SimpleXMLElement($page);
    $country  = $xml->Response->Placemark->AddressDetails->Country->CountryNameCode;
    $_SESSION['country'] = $country;

This will work:

    $_SESSION['country'] = (string) $country;
gwhitescarver at yahoo dot com 11-Sep-2008 01:02
Moving some code from a PHP 5.2.6 / Windows environment to a 5.2.0 / Linux environment, I somehow lost access to a plain text node within a SimpleXML Object.  On a var_dump of $xml_node, a [0] element was shown as the string '12'.  However, $xml_node[0] was evaluating NULL in 5.2.0.  You can see below the code change I made, pulling my data out of the raw XML with a regular expression.  Hope this is useful to someone.

//In some versions of PHP it seems we cannot access the [0] element of a SimpleXML Object.  Doesn't work in 5.2.0:
//$count = $xml_node[0];
//grab the raw XML:
$count = ($xml_node->asXML());
//pull out the number between the closing and opening brace of the xml:
$count = preg_replace('/.*>(\d*)<.*/', '$1', $count);
charlie at blankcanvasstudios dot com 14-Aug-2008 11:21
Optimizing aalaap at gmail dot com's php

<?php
function is_rss($feedxml) {
    @$feed = simplexml_load_string($feedxml);

    return ($feed->channel->item)?true:false;
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);
    ($feed->entry):true:false;
}
?>
aalaap at gmail dot com 30-Jun-2008 06:58
Here are two quick and dirty functions that use SimpleXML to detect if a feed xml is RSS or ATOM:

<?php
function is_rss($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->channel->item) {
        return true;
    } else {
        return false;
    }
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->entry) {
        return true;
    } else {
        return false;
    }
}
?>

The functions take in the full text feed (retrieved via cURL, for example) and return a true or a false based on the result.
SDO_DAS_XML_Document::setXMLVersion
Введение
Обработка XML


Введение

Расширение SimpleXML предоставляет очень простой и легкий в использовании набор инструментов для преобразования XML в объект, с которым можно затем работать через его свойства и с помощью итераторов.

User Contributed Notes

SL 24-Mar-2009 03:09
SimpleXML has a beautiful simplicity. The following is one example of how it may be used with namespaces.

Note, I use the XML that made Paul Reinheimer experience hair loss; for that XML see

http://blog.preinheimer.com/index.php?/archives/172-SimpleXML,-Namespaces-Hair-loss.html

<?php
$dom = new DOMDocument();
$dom->loadXML( $response );

$ns='urn:ebay:apis:eBLBaseComponents';
$domlist=$dom->getElementsByTagNameNS($ns,'*');
$sxe=simplexml_import_dom($domlist->item(0));
echo 'Ebay Timestamp ',$sxe->Timestamp;
?>

Running the above code left my own hair uneffected. :)
alvaro at demogracia dot com 30-Sep-2008 01:30
SimpleXML is simple, unless your XML document has namespaces (e.g., tags withs "colons" like <rs:data>). In this case, most code examples in this section will not work at all: namespaces imply that you need to do further processing with functions that are often undocumented.

Look for "namespace" in user notes.
SimpleXML
Установка и настройка
SimpleXML


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
SimpleXML


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

Модуль SimpleXML требует PHP 5.

User Contributed Notes

crazyone at crazycoders dot net 24-Dec-2009 07:17
You don't NEED "allow_url_fopen = On". This is only if you query for external xml feeds such as:

<?php $data = simplexml_load_file('http://www.example.com/myfeed.xml"); ?>

In many other cases you WONT need allow_url_fopen because files will be local or you will use posted XML data...
Установка и настройка
Установка
Установка и настройка


Установка

Это расширение включено по умолчанию. Оно может быть отключено во время выполнения с помощью следующей опции: --disable-simplexml

Примечание: До PHP 5.1.2 необходима опция --enable-simplexml для работы этого расширения.

User Contributed Notes

alvaro at digdib dot com 02-Jan-2009 02:40
Gentoo users: emerge does not compile dev-lang/php with simplexml by default. To enable this option, add the flag simplexml to your USE variable and recompile php.
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
SimpleXML


Примеры

Содержание

  • Базовое использование SimpleXML
  • Работа с ошибками XML

User Contributed Notes

Juan Herrera 19-Dec-2009 12:49
When using simplexml to access a element the returned object may be a SimpleXMLElement instead of a string.

Example:

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
    <cmd>login</cmd>
    <login>Richard</login>
</document>
XML;

$xml = simplexml_load_string($string);
print_r($xml);
$login = $xml->login;
print_r($login);
$login = (string) $xml->login;
print_r($login);
?>

Expected result:
----------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
Richard
Richard

Actual result:
--------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
SimpleXMLElement Object
(
    [0] => Richard
)
Richard

But this is an intended behavior. See http://bugs.php.net/bug.php?id=29500
info at accountr dot eu 05-May-2009 08:35
Instead of using  <?php eval($code) ?>

you can use this method,

<?php

$node = "node";

$XML = simplexml_load_file($file);

$text = (string)$XML->nodes->{$node}; // works
// or
$text2 = (string)$XML->{$node}->child; // also works fine

?>

I think it is much more easier instead of eval().
Edward Rudd 14-Nov-2008 08:46
If you need to updated the content of a node selected via Xpath use [0].  Example.
<?php
$x = new SimpleXMLElement(<<<EOXML
<root>
   <node>Some Text</node>
</root>
EOXML
);

$nodes = $x->xpath('/root/node');

// This does not work
// $nodes[0] = "My New Text";
$nodes[0][0] = "My New Text";

echo $x->asXML();
?>

Note that this for some reason doesn't work.
<?php
$node = $nodes[0];
$nodes[0] = "My New Text";
?>
It throw an exception "Object ($node) don't support array access operators"
Kari P. 15-Aug-2008 02:17
To take care of proper error checking, one must use try-catch blocks:

<?php
try {
  $sxe = new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>

To get rid of warnings, use @ in front of new:

<?php
try {
  $sxe = @new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>
dipl dot paed dot thomas dot schaefer at web dot de 03-May-2008 09:57
<?php
class QXML {
  ...
  protected function _toXML(
    $xmlArray,
    $elmName='graph',
    $elmCloseTag="",
    $level=0)
  {
    $xmlString = "";
    if(is_array($xmlArray)){
      $strXmlAttributes = "";
      $key_xml = "";
      $keysXmlArray = array_keys($xmlArray);
      $curLevel = $level + 1;
      if(in_array(self::attribute,$keysXmlArray)){
        if(isset($xmlArray[self::attribute])){
          if(is_array($xmlArray[self::attribute])){
            foreach($xmlArray[self::attribute]
              as $xmlArrayKey => $xmlArrayValue)
            {
              $strXmlAttributes .= sprintf(' %s="%s"',
                                    $xmlArrayKey,
                                    addslashes($xmlArrayValue));
            }
          }
        }
        unset($xmlArray[self::attribute]);
      }
      if(in_array(self::textNode,$keysXmlArray)){
        if(isset($xmlArray[self::textNode])){
          if($xmlArray[self::textNode]){
            $key_xml = $xmlArray[self::textNode];
          }
          if(strlen($ky_xml)){
            $key_xml = sprintf("<![CDATA[%s]]>",$key_xml);
          } else {
            $key_xml = "";
          }
        }
        unset($xmlArray[self::textNode]);
      }
      $keysXmlArray=array_keys($xmlArray);
      if($elmCloseTag){
        $indent=str_repeat(" ",$level * 5);
        $xmlString  .="\n".$indent.
                    "<".$elmCloseTag.$strXmlAttributes.">".
                    $key_xml;
      }
      if(is_array($xmlArray) && count($xmlArray)>0
        && count($keysXmlArray)>0)
      {
        reset($xmlArray);
        foreach($keysXmlArray as $key){
          $altKey = $altKeyXml = $xmlArray[$key];
          $check = false;
          foreach(array_keys($altKeyXml) as $j=>$p){
            if(is_numeric($j)){
              $check=true;
              $xmlString.= $this->_toXML(
                $altKeyXml[$j],
                "",
                $key,
                $curLevel
              );
              unset($altKeyXml[$j]);
            }
          }
          if($check){
            $altKey = $altKeyXml;
          }
          if($altKey){
            $xmlString .= $this->_toXML($altKey,"",$key,$curLevel);
          }
        }
      }
      if($elmCloseTag){
        $xmlString.= (count($xmlArray)>0?"\n".$indent:"").
                     "</".$elmCloseTag.">";
      }
    }

    if($elmName) {
      $xmlString = "<?xml version='1.0' encoding='UTF-8'?>\n$xmlString\n";
    }
    return $xmlString;
  }

...
}
?>
Honeymonster 30-Apr-2008 06:52
@david b
@Fabi W

Why can't you use the ->{} operators?

e.g

$xml->{$node}

I've not tested this, but see no reason why it would not work.
Fabi W 23-Apr-2008 12:34
@david b's approach of dynamically accessing xml-elements:

You can explode the dynamic var with '->' as seperator and thus build a simple function to get the element

function simplexml_get_node_by_query($sxml_obj, $query)
{
      $nodes = explode("->", $query);
      $currTree = $sxml_obj;

      foreach($nodes as $node)
      {
        $currTree = $currTree->$node;
      }
      return $currTree;
}
mike at mike-griffiths dot co dot uk 18-Apr-2008 09:11
It is important that you select the correct method of loading the XML in depending on the format of your XML file.

If you use the wrong function to load it in you will get some strange errors.
david b 12-Apr-2008 03:04
Use eval() when using variable variables to access SimpleXML nodes.
e.g.

<?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

$s = 'movie[0]->plot' ;

echo "\n1: OK   " . $xml->movie[0]->plot ;   // OK
echo "\n2: FAIL " . $xml->$s ;               // FAIL
echo "\n3: OK   " . eval( "return  \$xml->$s ;" ) ;    // OK

?>
Предопределенные константы
Базовое использование SimpleXML
SimpleXML


Базовое использование SimpleXML

Некоторые примеры этого руководства включают XML-строку. Вместо того, чтобы повторять ее в каждом примере, положите эту строку в файл, который и включайте в каждом примере. Эта строка приведена в следующем примере. Помимо этого можно создать XML-документ и считывать его функцией simplexml_load_file().

Пример #1 Файл example.php с XML строкой

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Появление Парсера</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   Таким образом, это язык. Это все равно язык программирования. Или
   это скриптовый язык? Все раскрывается в этом документальном фильме,
   похожем на фильм ужасов.
  </plot>
  <great-lines>
   <line>PHP решает все мои проблемы в web</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

SimpleXML пользоваться очень просто! Попробуйте получить какую-нибудь строку или число из базового XML документа.

Пример #2 Получение части документа <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

Результат выполнения данного примера:

   Таким образом, это язык. Это все равно язык программирования. Или
   это скриптовый язык? Все раскрывается в этом документальном фильме,
   похожем на фильм ужасов.

В PHP получить доступ к элементу в XML документе, содержащим в названии недопустимые символы (например, дефис), можно путем заключения данного имени элемента в фигурные скобки и апострофы.

Пример #3 Получение строки <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

Результат выполнения данного примера:

PHP решает все мои проблемы в web

Пример #4 Доступ к не уникальным элементам в SimpleXML

В том случае, если существует несколько экземпляров дочерних элементов в одном родительском элементе, то нужно применять стандартные методы итерации.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Для каждого узла <character>, мы отдельно выведем имя <name>. */
foreach ($movies->movie->characters->character as $character) {
   echo $character->name, ' играет ', $character->actor, PHP_EOL;
}

?>

Результат выполнения данного примера:

Ms. Coder играет Onlivia Actora
Mr. Coder играет El ActÓr

Замечание:

Свойства ($movies->movie в предыдущем примере) не являются массивами. Это итеративный объект в виде массива.

Пример #5 Использование атрибутов

До сих пор мы только читали названия и значения элементов. SimpleXML может так же получать доступ к атрибутам элемента. Получить доступ к атрибуту элемента можно так же, как к элементам массива array.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Доступ к узлу <rating> первого фильма.
 * Так же выведем шкалу оценок. */
foreach ($movies->movie[0]->rating as $rating) {
    switch((string) $rating['type']) { // Получение атрибутов элемента по индексу
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?>

Результат выполнения данного примера:

7 thumbs up5 stars

Пример #6 Сравнение элементов и атрибутов с текстом

Для сравнения элемента или атрибута со строкой или для передачи в функцию в качестве текста, необходимо привести его к строке, используя (string). В противном случае, PHP будет рассматривать элемент как объект.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Появление Парсера') {
    print 'Мой любимый фильм.';
}

echo htmlentities((string) $movies->movie->title);
?>

Результат выполнения данного примера:

Мой любимый фильм.PHP: Появление Парсера

Пример #7 Сравнение двух элементов

Два элемента SimpleXMLElements считаются различными, даже если они указывают на один и тот же объект начиная с PHP 5.2.0.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2); // false начиная с PHP 5.2.0
?>

Результат выполнения данного примера:

bool(false)

Пример #8 Использование XPath

SimpleXML включает в себя встроенную поддержку XPath. Поиск всех элементов <character>:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
    echo $character->name, ' играет ', $character->actor, PHP_EOL;
}
?>

'//' служит в качестве шаблона. Для указания абсолютного пути, опустите одну из косых черт.

Результат выполнения данного примера:

Ms. Coder играет Onlivia Actora
Mr. Coder играет by El ActÓr

Пример #9 Установка значений

Данные в SimpleXML не могут быть постоянными. Объект позволяет манипулировать всеми элементами.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

Результат выполнения данного примера:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Появление Парсера</title>
  <characters>
   <character>
    <name>Miss Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   Таким образом, это язык. Это все равно язык программирования. Или
   это скриптовый язык? Все раскрывается в этом документальном фильме,
   похожем на фильм ужасов.
  </plot>
  <great-lines>
   <line>PHP решает все мои задачи в web</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>

Пример #10 Добавление элементов и атрибутов

Начиная с PHP 5.1.3, SimpleXML имеет возможность легко добавлять дочерние элементы и атрибуты.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

Результат выполнения данного примера:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Появление Парсера</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  <character><name>Mr. Parser</name><actor>John Doe</actor></character></characters>
  <plot>
   Таким образом, это язык. Это все равно язык программирования. Или
   это скриптовый язык? Все раскрывается в этом документальном фильме,
   похожем на фильм ужасов.
  </plot>
  <great-lines>
   <line>PHP решает все мои задачи в web</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 <rating type="mpaa">PG</rating></movie>
</movies>

Пример #11 Взаимодействие с DOM

PHP может преобразовывать XML узлы из SimpleXML в формат DOM и наоборот. Этот пример показывает, как можно изменить DOM элемент в SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>бред</title></book></books>');
if (!$dom) {
    echo 'Ошибка при разборе документа';
    exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

Результат выполнения данного примера:

blah

User Contributed Notes

gkokmdam at zonnet dot nl 23-Feb-2011 01:54
A quick tip on xpath queries and default namespaces. It looks like the XML-system behind SimpleXML has the same workings as I believe the XML-system .NET uses: when one needs to address something in the default namespace, one will have to declare the namespace using registerXPathNamespace and then use its prefix to address the otherwise in the default namespace living element.

<?php
$string = <<<XML
<?xml version='1.0'?>
<document xmlns="http://www.w3.org/2005/Atom">
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("def", "http://www.w3.org/2005/Atom");

$nodes = $xml->xpath("//def:document/def:title");

?>
kdos 31-Jan-2011 05:32
Using stuff like: is_object($xml->module->admin) to check if there actually is a node called "admin", doesn't seem to work as expected, since simplexml always returns an object- in that case an empty one  - even if a particular node does not exist.
For me good old empty() function seems to work just fine in such cases.

Cheers
Max K. 20-Jun-2010 02:38
From the README file:

SimpleXML is meant to be an easy way to access XML data.

SimpleXML objects follow four basic rules:

1) properties denote element iterators
2) numeric indices denote elements
3) non numeric indices denote attributes
4) string conversion allows to access TEXT data

When iterating properties then the extension always iterates over
all nodes with that element name. Thus method children() must be
called to iterate over subnodes. But also doing the following:
foreach ($obj->node_name as $elem) {
  // do something with $elem
}
always results in iteration of 'node_name' elements. So no further
check is needed to distinguish the number of nodes of that type.

When an elements TEXT data is being accessed through a property
then the result does not include the TEXT data of subelements.

Known issues
============

Due to engine problems it is currently not possible to access
a subelement by index 0: $object->property[0].
ie dot raymond at gmail dot com 01-Apr-2010 03:07
If you need to output valid xml in your response, don't forget to set your header content type to xml in addition to echoing out the result of asXML():

<?php

$xml=simplexml_load_file('...');
...
...xml stuff
...

//output xml in your response:
header('Content-Type: text/xml');
echo $xml->asXML();
?>
php at keith tyler dot com 23-Dec-2009 12:57
[Editor's Note: The SimpleXMLIterator class, however, does implement these methods.]

While SimpleXMLElement claims to be iterable, it does not seem to implement the standard Iterator interface functions like ::next and ::reset properly. Therefore while foreach() works, functions like next(), current(), or each() don't seem to work as you would expect -- the pointer never seems to move or keeps getting reset.
bjorn at xQmail dot eu 31-Aug-2009 07:48
If you're not sure the XML will be valid you'd better use:

<?php
$xmlObject = simplexml_load_string($xml);
// or
$xmlObject = simplexml_load_file(xml);
?>

Both of these return a SimpleXMLElement Object or a libXMLError Object.
radams at circlepix com 24-Apr-2009 10:52
To test whether an element exists:

<?php

    $xml = <<<EOT
<?xml version='1.0' standalone='yes'?>
<root>
    <test1></test1>
    <test2 />
    <test4> </test4>
</root>
EOT;

    $xmlDoc = new SimpleXMLElement($xml);

echo "Test1: \n";
var_dump($xmlDoc->test1);
echo "\n(" . (bool)$xmlDoc->test1 . ")";
echo "\n\n";

echo "Test2: \n";
var_dump($xmlDoc->test2);
echo "\n(" . (bool)$xmlDoc->test2 . ")";
echo "\n\n";

echo "Test3: \n";
var_dump($xmlDoc->test3);
echo "\n(" . (bool)$xmlDoc->test3 . ")";
echo "\n\n";

echo "Test4: \n";
var_dump($xmlDoc->test4);
echo "\n(" . (bool)$xmlDoc->test4 . ")";
echo "\n\n";

?>

The var_dumps for test1, test2, and test3 are identical, but the (bool) test gives a '1' for test1 and test2, and a '' for test3.
Примеры
Работа с ошибками XML
Примеры


Работа с ошибками XML

Работа с ошибками XML при загрузке документов является очень простой задачей. Использование функциональности libxml позволяет подавить все XML ошибки при загрузке документа и затем обработать их.

Объект libXMLError, возвращаемый libxml_get_errors(), содержит несколько свойств, в том числе сообщение, номер строки и колонку (позицию) этой ошибки.

Пример #1 Загрузка синтаксически неправильной XML строки

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (!$sxe) {
    echo "Ошибка загрузки XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}
?>

Результат выполнения данного примера:

Ошибка загрузки XML
    Blank needed here
    parsing XML declaration: '?>' expected
    Opening and ending tag mismatch: xml line 1 and broken
    Premature end of data in tag broken line 1

Смотрите также

  • libxml_use_internal_errors()
  • libxml_get_errors()
  • libXMLError

User Contributed Notes

openbip at gmail dot com 25-Feb-2010 08:20
Note that "if (! $sxe) {" may give you a false-negative if the XML document was empty (e.g. "<root />").  In that case, $sxe will be:

object(SimpleXMLElement)#1 (0) {
}

which will evaluate to false, even though nothing technically went wrong.

Consider instead: "if ($sxe === false) {"
Jacob Tabak 15-Feb-2010 01:17
If you are trying to load an XML string with some escaped and some unescaped ampersands, you can pre-parse the string to ecsape the unescaped ampersands without modifying the already escaped ones:
<?php
$s = preg_replace('/&[^; ]{0,6}.?/e', "((substr('\\0',-1) == ';') ? '\\0' : '&amp;'.substr('\\0',1))", $s);
?>
Базовое использование SimpleXML
SimpleXMLElement
Примеры


Класс SimpleXMLElement

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Представляет собой элемент в XML-документе.

Обзор классов

SimpleXMLElement implements Traversable {
/* Методы */
final public __construct ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )
public void addAttribute ( string $name [, string $value [, string $namespace ]] )
public SimpleXMLElement addChild ( string $name [, string $value [, string $namespace ]] )
public mixed asXML ([ string $filename ] )
public SimpleXMLElement attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )
public SimpleXMLElement children ([ string $ns [, bool $is_prefix = false ]] )
public int count ( void )
public array getDocNamespaces ([ bool $recursive = false ] )
public string getName ( void )
public array getNamespaces ([ bool $recursive = false ] )
public bool registerXPathNamespace ( string $prefix , string $ns )
public array xpath ( string $path )
}

Содержание

  • SimpleXMLElement::addAttribute — Добавляет атрибут к SimpleXML-элементу
  • SimpleXMLElement::addChild — Добавляет дочерний элемент к узлу XML
  • SimpleXMLElement::asXML — Возвращает сформированный XML документ в виде строки используя SimpleXML элемент
  • SimpleXMLElement::attributes — Возвращает атрибуты элемента
  • SimpleXMLElement::children — Поиск дочерних элементов данного узла
  • SimpleXMLElement::__construct — Создание нового SimpleXMLElement объекта
  • SimpleXMLElement::count — Считает количество дочерних элементов у текущего элемента
  • SimpleXMLElement::getDocNamespaces — Возвращает объявленное пространство имен в документе
  • SimpleXMLElement::getName — Получение имени XML элемента
  • SimpleXMLElement::getNamespaces — Получение пространств имен, используемых в документе
  • SimpleXMLElement::registerXPathNamespace — Создает префикс/пространство имен контекста для следующего XPath запроса
  • SimpleXMLElement::saveXML — Псевдоним SimpleXMLElement::asXML
  • SimpleXMLElement::xpath — Запускает XPath запрос к XML данным

User Contributed Notes

heaver 31-May-2012 07:33
XML to JSON conversion without '@attributes'
<?php
function XML2JSON($xml) {

        function normalizeSimpleXML($obj, &$result) {
            $data = $obj;
            if (is_object($data)) {
                $data = get_object_vars($data);
            }
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $res = null;
                    normalizeSimpleXML($value, $res);
                    if (($key == '@attributes') && ($key)) {
                        $result = $res;
                    } else {
                        $result[$key] = $res;
                    }
                }
            } else {
                $result = $data;
            }
        }
        normalizeSimpleXML(simplexml_load_string($xml), $result);
        return json_encode($result);
    }
?>
demian dot katz at villanova dot edu 29-Mar-2012 05:50
Here is a more namespace-aware version of the earlier function for attaching one SimpleXMLElement to another.  I'm sure it could still be further improved (right now it generates some redundant xmlns definitions), but it seems to be working well enough for my purposes so far.

function SimpleXMLElement_append($parent, $child)
{
    // get all namespaces for document
    $namespaces = $child->getNamespaces(true);

    // check if there is a default namespace for the current node
    $currentNs = $child->getNamespaces();
    $defaultNs = count($currentNs) > 0 ? current($currentNs) : null;
    $prefix = (count($currentNs) > 0) ? current(array_keys($currentNs)) : '';
    $childName = strlen($prefix) > 1
        ? $prefix . ':' . $child->getName() : $child->getName();

    // check if the value is string value / data
    if (trim((string) $child) == '') {
        $element = $parent->addChild($childName, null, $defaultNs);
    } else {
        $element = $parent->addChild(
            $childName, htmlspecialchars((string)$child), $defaultNs
        );
    }

    foreach ($child->attributes() as $attKey => $attValue) {
        $element->addAttribute($attKey, $attValue);
    }
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->attributes($nsurl) as $attKey => $attValue) {
            $element->addAttribute($nskey . ':' . $attKey, $attValue, $nsurl);
        }
    }

    // add children -- try with namespaces first, but default to all children
    // if no namespaced children are found.
    $children = 0;
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->children($nsurl) as $currChild) {
            SimpleXMLElement_append($element, $currChild);
            $children++;
        }
    }
    if ($children == 0) {
        foreach ($child->children() as $currChild) {
            SimpleXMLElement_append($element, $currChild);
        }
    }
}
saganmarketing.com 12-Mar-2012 12:27
Parsing an invalid XML string through SimpleXML causes the script to crash completely (usually) therefore it is best to make sure the XML is valid before parsing with something like this:

// Must be tested with ===, as in if(isXML($xml) === true){}
// Returns the error message on improper XML
function isXML($xml){
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();

    if(empty($errors)){
        return true;
    }

    $error = $errors[0];
    if($error->level < 3){
        return true;
    }

    $explodedxml = explode("r", $xml);
    $badxml = $explodedxml[($error->line)-1];

    $message = $error->message . ' at line ' . $error->line . '. Bad XML: ' . htmlentities($badxml);
    return $message;
}
Anonymous 14-Nov-2011 12:34
Warning to anyone trying to parse XML with a key name that includes a hyphen ie.)
<subscribe>
    <callback-url>example url</callback-url>
</subscribe>

In order to access the callback-url you will need to do something like the following:
<?php
$xml = simplexml_load_string($input);
$callback = $xml->{"callback-url"};
?>
If you attempt to do it without the curly braces and quotes you will find out that you are returned a 0 instead of what you want.
juanfhj at gmail dot spam dot me dot not dot com 13-Aug-2011 11:01
To access the underlying element as a string, it's necessary to make the cast $x = (string)$my_xml_element.
dans at dansheps dot com 22-Apr-2011 12:06
I created a little function to parse the simple XML into a structure which is easier to iterate(I believe anyways) than the simpleXML node structure.

<?php
function parseSimpleXML($xmldata)
    {
        $childNames = array();
        $children = array();

        if( $xmldata->count() !== 0 )
        {
            foreach( $xmldata->children() AS $child )
            {
                $name = $child->getName();

                if( !isset($childNames[$name]) )
                {
                    $childNames[$name] = 0;
                }

                $childNames[$name]++;
                $children[$name][] = $this->parseSimpleXML($child);
            }
        }

        $returndata = new XMLNode();
        if( $xmldata->attributes()->count() > 0 )
        {
            $returndata->{'@attributes'} = new XMLAttribute();
            foreach( $xmldata->attributes() AS $name => $attrib )
            {
                $returndata->{'@attributes'}->{$name} = (string)$attrib;
            }
        }

        if( count($childNames) > 0 )
        {
            foreach( $childNames AS $name => $count )
            {
                if( $count === 1 )
                {
                    $returndata->{$name} = $children[$name][0];
                }
                else
                {
                    $returndata->{$name} = new XMLMultiNode();
                    $counter = 0;
                    foreach( $children[$name] AS $data )
                    {
                        $returndata->{$name}->{$counter} = $data;
                        $counter++;
                    }
                }
            }
        }
        else
        {
            if( (string)$xmldata !== '' )
            {
                $returndata->{'@innerXML'} = (string)$xmldata;
            }
        }
        return $returndata;
    }
?>
ms dot n at 163 dot com 11-Feb-2011 10:50
Adds a new function for SimpleXMLElement class, in order to output HTML code.

<?php
class CeiXML extends SimpleXMLElement{
public function asHTML(){
$ele=dom_import_simplexml($this);
$dom = new DOMDocument('1.0', 'utf-8');
$element=$dom->importNode($ele,true);
$dom->appendChild($element);
return $dom->saveHTML();
}
}
?>
Pavel Musil pavel dot musil at gmail dot com 10-Feb-2011 03:18
Simple recursive function to append XML object into SimpleXMLElement node:

<?php
// root: parent element - SimpleXMLElement instance
// append: XML object from simplexml_load_string

function xml_join($root, $append) {
    if ($append) {
        if (strlen(trim((string) $append))==0) {
            $xml = $root->addChild($append->getName());
            foreach($append->children() as $child) {
                xml_join($xml, $child);
            }
        } else {
            $xml = $root->addChild($append->getName(), (string) $append);
        }
        foreach($append->attributes() as $n => $v) {
            $xml->addAttribute($n, $v);
        }
    }
}

$xml_append = simplexml_load_string('<data><items><item id="1">value</item></items></data>');
$xml_root = new SimpleXMLElement('<result></result>');

$cxml = $xml_root->addChild('clone');
xml_join($cxml, $xml_append->items->item[0]);

print $xml_root->asXML();
?>

Result:
<?xml version="1.0"?>
<result>
    <clone>
        <item id="1">
            value
        </item>
    </clone>
</result>
rmirabelle 08-Nov-2010 09:42
To further previous comments and drive the point home:

What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE,  (specifically a libxml resource).

That's why you can't store a SimpleXMLElement to $_SESSION or perform straight comparison operations on node values without first casting them to some type of object.  $_SESSION expects to store 'an object' and comparison operators expect to compare 2 'objects' and SimpleXMLElements are not objects.

When you echo or print a node's value, PHP converts the value (a resource) into a string object for you.  It's a time saver for sure, but can fool you into thinking that your SimpleXMLElement is an object.

Hope this helps clarify
joshduck at gmail dot com 28-Sep-2010 05:00
You should cast elements to a float (or even string) if you plan on using them in addition, multiplication, etc. If you don't then PHP will incorrectly treat the node values as an integer.

<?php
$obj = new SimpleXMLElement('<root>
    <a>1.9</a>
    <b>1.9</b>
</root>');

var_dump($obj->a + $obj->b);
var_dump((float)$obj->a + (float)$obj->b);
var_dump((string)$obj->a + (string)$obj->b);
?>

The first line gives: int(2)
The second and third give the expected result: float(3.8)
francs at seznam dot cz 23-Sep-2010 05:28
Be aware when you trying to cast some attribute to boolean.

(boolean)$xml->attributes()->someAtt;

returns TRUE if attribute is array([0] => 0);

use (boolean)(int) instead.
kweij at lsg dot nl 26-Jul-2010 04:47
I'm using SimpleXML for, ofcourse, it's simplicity, however I did wanted to manipulate the xml and combining one SimpleXMLElement with any other, so I wrote this function to add a SimpleXMLElement-child.

<?php
function SimpleXMLElement_append($key, $value) {
    // check class
    if ((get_class($key) == 'SimpleXMLElement') && (get_class($value) == 'SimpleXMLElement')) {
        // check if the value is string value / data
        if (trim((string) $value) == '') {
            // add element and attributes
            $element = $key->addChild($value->getName());
            foreach ($value->attributes() as $attKey => $attValue) {
                $element->addAttribute($attKey, $attValue);
            }
            // add children
            foreach ($value->children() as $child) {
                SimpleXMLElement_append($element, $child);
            }
        } else {
            // set the value of this item
            $element = $key->addChild($value->getName(), trim((string) $value));
        }
    } else {
        // throw an error
        throw new Exception('Wrong type of input parameters, expected SimpleXMLElement');
    }
}
?>

I'd recommend SimpleXMLElement to extend it's addChild() function with the functionalitity above.
cherubangel at gmail dot com 02-Jul-2010 04:28
Note that changing attributes from within a foreach loop, especially namespaced attributes, can be very tricky.

For example, when trying to change the value of an existing xlink:href attribute:
<?php
foreach($xmlelement -> attributes('xlink', true) as $attribute => $attribvalue){
    $attribvalue[0] = 'value'; // Throws an error
    $attribvalue = 'value'; // Does not change your XML
    $xmlelement -> addAttribute($attribute, 'value', 'http://www.w3.org/1999/xlink'); // Adds an attribute, does not change existing one.
    $xmlelement[$attribute] = 'value'; // Adds an attribute, does not change existing one.
}
?>

Instead, you should access the array returned by the attributes() function directly, like this:
<?php
    $xmlelement -> attributes('xlink', true) -> href = 'value'; // Works!
?>
php at keith tyler dot com 19-Feb-2010 06:23
The root node element of your input XML string is not retrievable as a property.

<?php
$xml="<foo>bar</foo>";
$sxe=new SimpleXMLElement($xml);
print $sxe->foo;
?>

prints nothing. You can only get to the root element via the array index method ($sxe[0]).

Also, you may not have two (or more) root elements -- that is apparently not well-formed XML.

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement($xml);
?>

throws an exception. A Q&D is to append an arbitraty root node structure to both ends of the input:

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement("<z>".$xml."</z>");
?>

Doing this also solves the above problem of root node property accessibility. (It may not work if your XML string includes a declaration.)
triplepoint at gmail dot com 19-Dec-2009 04:19
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating it as if it were a full document).
<?php
class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addProcessingInstruction( $name, $value )
    {
        // Create a DomElement from this simpleXML object
        $dom_sxe = dom_import_simplexml($this);

        // Create a handle to the owner doc of this xml
        $dom_parent = $dom_sxe->ownerDocument;

        // Find the topmost element of the domDocument
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);

        // Add the processing instruction before the topmost element
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}
?>

For example, if you had a simpleXMLElement_Plus object made out of the xml fragment:
<xml><content /></xml>

And you needed the output to be:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>
<xml><content/></xml>

you could do (using the class above):
<?php
$xml = new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/xsl.xsl"');
echo $xml->asXML();
?>
ivandosreisandrade at gmail dot com 19-Nov-2009 06:55
Hello,

here goes my contribution for those whom are struggling to understand how SimpleXMLElement works.

After some time trying to figure out how this works, I've came up to this small example:

<?php
    $xmlstr = "<?xml version='1.0' ?>\n".
              // optionally you can specify a xml-stylesheet for presenting the results. just uncoment the following line and change the stylesheet name.
              /* "<?xml-stylesheet type='text/xsl' href='xml_style.xsl' ?>\n". */
              "<book></book>";

    // create the SimpleXMLElement object with an empty <book> element
    $xml = new SimpleXMLElement($xmlstr);

    // add some child nodes
    $xml->addChild("title", "Title of my book");
    $xml->addChild("abstract", "My book is about learning to work with SimpleXMLElement");

    // add some more child nodes
    $chapter1 = $xml->addChild("chapter_1");
    // add an attribute to child chapter_1
    $chapter1->addAttribute("chapter_title", "Introduction to my book");

    $chapter2 = $xml->addChild("chapter_2");
    $chapter2->addAttribute("chapter_title", "Development of my book");

    $chapter3 = $xml->addChild("chapter_3");
    $chapter3->addAttribute("chapter_title", "Another chapter of my book");

    $conclusion = $xml->addChild("conclusion", "The ending of my book");

    // insert the header to tell the browser how to read the document
    header("Content-type: text/xml");
    // print the SimpleXMLElement as a XML well-formed string
    echo $xml->asXML();
?>

With this script you can just copy-paste and try to understand how it works.
I hope it can help somebody :)
brett at brettbrewer dot com 27-Oct-2009 04:53
Figuring out how to access the properties of a SimpleXmlElement object was a little tricky for me. In particular, it took a while to discover that I needed to cast my SimpleXmlElement properties to be of type "string" to print them or do comparisons on them. For instance, assuming you already have a string of xml in $xmlstr...

<?php
$sxml= new SimpleXmlElement($xmlstr);

if ((string) $sxml->property== "somevalue") {
    echo (string) $sxml->property;
}
?>
The properties of a SimpleXmlElement object are objects themselves, so you need to put "(string)" before them, which casts their values to a string instead of an object. I assume if you were doing a numeric comparison you'd want to cast to an (int) or something numeric instead.
Работа с ошибками XML
SimpleXMLElement::addAttribute
SimpleXML


Добавляет атрибут к SimpleXML-элементу

SimpleXMLElement
SimpleXMLElement::addChild
SimpleXMLElement
PHP Manual

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3)

SimpleXMLElement::addAttribute — Добавляет атрибут к SimpleXML-элементу

Описание

public void SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] )

Добавляет атрибут к SimpleXML-элементу.

Список параметров

name

Название добавляемого атрибута.

value

Значение атрибута.

namespace

Необязательный параметр указывает на пространство имен, к которому принадлежит атрибут.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Замечание:

Перечисленные примеры могут включать example.php, в котором определяется XML-строка, расположенная в первом примере руководства по базовому использованию.

Пример #1 Добавление атрибутов и потомков к SimpleXML-элементу

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: Истории парсера');
$movie->addChild('plot', 'Все о людях, создававших его.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

Результатом выполнения данного примера будет что-то подобное:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Появление Парсера</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   Итак, этот язык. Типа, язык программирования. Или
   это скриптовый язык? Все раскрывается в этом документальном фильме,
   похожем на фильм ужасов.
  </plot>
  <great-lines>
   <line>PHP решает все мои задачи в web</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: Истории парсера</title>
  <plot>Все о людях, создававших его.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

Смотрите также

  • SimpleXMLElement::addChild() - Добавляет дочерний элемент к узлу XML
  • Базовое использование SimpleXML

User Contributed Notes

p.servus 18-Nov-2011 05:42
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml = new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo $xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
sarlak 07-May-2011 07:49
You can access a node child with his name this way :

<?php
$root = new SimpleXMLElement($filePath);
echo $root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
booleer at yahoo dot it 16-Dec-2010 09:44
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo $xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
SimpleXMLElement
SimpleXMLElement::addChild
SimpleXMLElement


Добавляет дочерний элемент к узлу XML

SimpleXMLElement::addAttribute
SimpleXMLElement::asXML
SimpleXMLElement
PHP Manual

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3)

SimpleXMLElement::addChild — Добавляет дочерний элемент к узлу XML

Описание

public SimpleXMLElement SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )

Добавляет дочерний элемент к узлу и возвращает потомка SimpleXMLElement.

Список параметров

name

Имя добавляемого дочернего элемента.

value

Если указано, то значение (содержимое) дочернего элемента.

namespace

Если указано, то пространсто имен, к которому принадлежит дочерний элемент.

Возвращаемые значения

Метод addChild возвращает объект SimpleXMLElement, представляющий добавленного потомка к узлу XML.

Примеры

Замечание:

Перечисленные примеры могут включать example.php, в котором определяется XML строка, расположенная в первом примере руководства по базовому использованию.

Пример #1 Добавление атрибутов и потомков к SimpleXML элементу

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: Истории парсера');
$movie->addChild('plot', 'Все о людях, создававших его.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

Результатом выполнения данного примера будет что-то подобное:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Появление Парсера</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   Таким образом, это язык. Это все равно язык программирования. Или
   это скриптовый язык? Все раскрывается в этом документальном фильме,
   похожем на фильм ужасов.
  </plot>
  <great-lines>
   <line>PHP решает все мои задачи в web</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: Истории парсера</title>
  <plot>Все о людях, создававших его.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

Смотрите также

  • SimpleXMLElement::addAttribute() - Добавляет атрибут к SimpleXML-элементу
  • Базовое использование SimpleXML

User Contributed Notes

jerikojerk 31-Jul-2011 07:32
If you're looking for a way to append children you may be interested in this:

<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');

$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
    var_dump($foo);
}

?>
alex dot feraud at gmail dot com 16-Jun-2011 02:52
Here is a class with more functions for SimpleXMLElement :

<?php
/**
 *
 * Extension for SimpleXMLElement
 * @author Alexandre FERAUD
 *
 */
class ExSimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
  private function addCData($cdata_text)
  {
   $node= dom_import_simplexml($this);
   $no = $node->ownerDocument;
   $node->appendChild($no->createCDATASection($cdata_text));
  }

  /**
   * Create a child with CDATA value
   * @param string $name The name of the child element to add.
   * @param string $cdata_text The CDATA value of the child element.
   */
    public function addChildCData($name,$cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string) $append))==0) {
                $xml = $this->addChild($append->getName());
                foreach($append->children() as $child) {
                    $xml->appendXML($child);
                }
            } else {
                $xml = $this->addChild($append->getName(), (string) $append);
            }
            foreach($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
Volker Grabsch 21-Apr-2011 06:17
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
felipenmoura at gmail dot com 11-Apr-2011 06:06
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
    $xml= new SimpleXMLElement('<root></root>');
    $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
    $son= $xml->father->addChild('son'); // uses the first father tag
    $son['name']= 'first son';
    $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
    $otherSon['name']= 'second son';

    echo htmlentities($xml->asXML());
?>

The result will be
<root>
    <father>
        <son name='first son' />
        <son name='second son' />
    </father>
</root>

So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.
Dmitry Dulepov 02-Sep-2009 05:53
addChild will automatically escape all XML characters as necessary. You do not have to do any magic when adding values like "if a > b then...".
SimpleXMLElement::addAttribute
SimpleXMLElement::asXML
SimpleXMLElement


Возвращает сформированный XML документ в виде строки используя SimpleXML элемент

SimpleXMLElement::addChild
SimpleXMLElement::attributes
SimpleXMLElement
PHP Manual

SimpleXMLElement::asXML

(PHP 5 >= 5.0.1)

SimpleXMLElement::asXML — Возвращает сформированный XML документ в виде строки используя SimpleXML элемент

Описание

public mixed SimpleXMLElement::asXML ([ string $filename ] )

Метод asXML задает формат данных родительских объектов в версии XML 1.0.

Список параметров

filename

Если указан, то функция запишет данные в файл, а не вернет их.

Возвращаемые значения

Если filename не указан, то функция вернет string в случае успеха и FALSE в случае ошибки. Если параметр указан, то функция вернет TRUE если файл будет успешно записан и FALSE в противном случае.

Примеры

Пример #1 Получение XML

<?php
$string = <<<XML
<a>
 <b>
  <c>текст</c>
  <c>штучка</c>
 </b>
 <d>
  <c>код</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

Результат выполнения данного примера:

<?xml version="1.0"?>
<a>
 <b>
  <c>текст</c>
  <c>штучка</c>
 </b>
 <d>
  <c>код</c>
 </d>
</a>

asXML также работает с результатами Xpath:

Пример #2 Использование asXML() с результатами SimpleXMLElement::xpath()

<?php
// Продолжение XML примера выше.

/* Поиск <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo $node->asXML();
}
?>

Результат выполнения данного примера:

<c>текст</c><c>штучка</c>

Смотрите также

  • Базовое использование SimpleXML

User Contributed Notes

oleg dot pavlin at gmail dot com 10-Jan-2012 04:17
Function asXML decodes special chars like ø, æ and others to &#xE6;, &#xF8;

To get normal output use without quoting:

$xml = html_entity_decode($xml, ENT_NOQUOTES, 'UTF-8');
jcr at di dot uminho dot pt 25-Jan-2011 02:32
Code snippet to load a XML document, increment an attribute and store it again.
My XML looks like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<doctypes counter="16">
    <doctype id="d1">
        <name>Carta</name>
        <acro>CA</acro>
    </doctype>
...
</doctypes>

I want to retrieve the counter attribute, increment it, and store the new document at the end:

<?php
  $document = simplexml_load_file("mydoc.xml");
  $cont = (integer) $document['counter'];
  $document['counter'] = $cont+1;
  $document->asXML("mydoc.xml");
?>
SimpleXMLElement::addChild
SimpleXMLElement::attributes
SimpleXMLElement


Возвращает атрибуты элемента

SimpleXMLElement::asXML
SimpleXMLElement::children
SimpleXMLElement
PHP Manual

SimpleXMLElement::attributes

(PHP 5 >= 5.0.1)

SimpleXMLElement::attributes — Возвращает атрибуты элемента

Описание

public SimpleXMLElement SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )

Эта функция возвращает названия и значения атрибутов установленные в xml теге.

Замечание: SimpleXML содержит правило добавления итеративных свойств к большинству методов. Они не могут быть просмотрены с использованием var_dump() или каких-либо других средств анализа объектов.

Список параметров

ns

Не обязательное пространство имен для извлеченных атрибутов

is_prefix

По умолчанию FALSE

Возвращаемые значения

Возвращает итеративный объект SimpleXMLElement, по которому можно перемещаться для перебора всех атрибутов тега.

Вернет NULL если вызванный объект SimpleXMLElement уже представляет собой атрибуты, а не тег.

Примеры

Пример #1 Интерпретация XML строки

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

Результат выполнения данного примера:

name="one"
game="lonely"

Смотрите также

  • Базовое использование SimpleXML

User Contributed Notes

chris at chlab dot ch 23-Mar-2012 10:16
Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Table Foo="Bar" ss:ExpandedColumnCount="7">
 </Table>
</Workbook>
XML;

$sxml = new SimpleXMLElement($xml);

/**
 * Access attribute of default namespace
 */
var_dump((string) $sxml->Table[0]['Foo']);
// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */
var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);
// outputs: 0

var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);
// outputs: '7'
?>
Andrei 16-May-2011 04:46
Reading the attributes of the root element with name space prefixes as in an Atom feed

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;Ck4EQXYzeCp7ImA9WhZWFE4.&quot;">

<?php
$xml =  @simplexml_load_file($feed);
$att_gd = $xml->attributes("gd",1);
$Etag = $att_gd["etag"];
?>
sarlak 27-Apr-2011 01:12
<?php
$att = 'attribueName';

// You can access an element's attribute just like this :
$attribute = $element->attributes()->$att;

// This will save the value of the attribute, and not the objet
$attribute = (string)$element->attributes()->$att;

// You also can edit it this way :
$element->attributes()->$att = 'New value of the attribute';
?>
leap 02-Apr-2011 09:07
If you want to save the value of an attribute into an array, typecast it to a string.

<?php
// stores an xml-element-object
$dataStore['value'] = $attributes->myValue

// stores the value of the attribute
$dataStore['value'] = (string)$attributes->myValue
?>
alan at performantsystems dot com 23-May-2010 10:26
So lets say you have database type data in an XML string called $xmlstring with the key or item ID as an XML Attribute and all content data as regular XML Elements, as above. SimpleXML processes the Attributes as an array, so we can play along and push the Attributes into an array. Then we can get the value of any specific Attribute we want by addressing it by name, such as "ID".

Considering this data:

<?xml version="1.0" encoding="utf-8"?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company>Digital Showcase</Company>
   </item>
</data>

Example of listing both the ID Attribute and Company Element values:

<?php
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node) {
        $arr = $node->attributes();   // returns an array
        print ("ID=".$arr["ID"]);     // get the value of this attribute
        print ("  Company=".$node->Company);
        print ("<p><hr>");
}
?>
Xeoncross 10-Apr-2010 07:46
It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

<?php
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 55555
        )

    [text] => "hello world"
)
?>

Then using a function

<?php
function xml_attribute($object, $attribute)
{
    if(isset($object[$attribute]))
        return (string) $object[$attribute];
}
?>

I can get the "id" like this

<?php
print xml_attribute($xml, 'id'); //prints "55555"
?>
gillllberg at gmail dot com 04-Nov-2009 02:21
To get an attribute in the node, use node->attributes()->attributeName
skerr at mojavi dot org 09-Dec-2004 10:55
You can also access the node as an array to get attributes:

<?php

$xml = simplexml_load_file('file.xml');

echo 'Attribute: ' . $xml['attribute'];

?>
inge at elektronaut dot no 26-May-2004 10:53
here's a simple function to get an attribute by name, based on the example

<?php
function findAttribute($object, $attribute) {
  foreach($object->attributes() as $a => $b) {
    if ($a == $attribute) {
      $return = $b;
    }
  }
  if($return) {
    return $return;
  }
}
?>
SimpleXMLElement::asXML
SimpleXMLElement::children
SimpleXMLElement


Поиск дочерних элементов данного узла

SimpleXMLElement::attributes
SimpleXMLElement::__construct
SimpleXMLElement
PHP Manual

SimpleXMLElement::children

(PHP 5 >= 5.0.1)

SimpleXMLElement::children — Поиск дочерних элементов данного узла

Описание

public SimpleXMLElement SimpleXMLElement::children ([ string $ns [, bool $is_prefix = false ]] )

Этот метод находит всех дочерних элементов узла. Результат подчиняется стандартным правилам итерации.

Замечание: SimpleXML содержит правило добавления итеративных свойств к большинству методов. Они не могут быть просмотрены с использованием var_dump() или каких-либо других средств анализа объектов.

Список параметров

ns

Не обязательное пространство имен XML.

is_prefix

Если is_prefix установлен в TRUE, ns будет рассмотрен как префикс. Если FALSE, ns будет рассмотрен как пространство имен URL.

Возвращаемые значения

Возвращает SimpleXMLElement элемент, даже если узел не имеет дочерних элементов.

Список изменений

Версия | Описание
5.2.0 | Добавлен не обязательный параметр is_prefix.

Примеры

Пример #1 Обход псевдо-массива children()

<?php
$xml = new SimpleXMLElement(
'<person>
 <child role="сын">
  <child role="дочь"/>
 </child>
 <child role="дочь">
  <child role="сын">
   <child role="сын"/>
  </child>
 </child>
</person>');

foreach ($xml->children() as $second_gen) {
    echo ' У человека родился(-ась) ' . $second_gen['role'];

    foreach ($second_gen->children() as $third_gen) {
        echo ' у которого родился(-ась) ' . $third_gen['role'] . ';';

        foreach ($third_gen->children() as $fourth_gen) {
            echo ' и у ' . $third_gen['role'] .
                ' родился(-ась) ' . $fourth_gen['role'];
        }
    }
}
?>

Результат выполнения данного примера:

У человека родился(-ась) сын у которого родился(-ась) дочь; У человека
родился(-ась) дочь у которого родился(-ась) сын; и у сын родился(-ась) сын

Пример #2 Использование пространства имен

<?php
$xml = '<example xmlns:foo="my.foo.urn">
  <foo:a>Яблоко</foo:a>
  <foo:b>Банан</foo:b>
  <c>Cherry</c>
</example>';

$sxe = new SimpleXMLElement($xml);

$kids = $sxe->children('foo');
var_dump(count($kids));

$kids = $sxe->children('foo', TRUE);
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn');
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn', TRUE);
var_dump(count($kids));

$kids = $sxe->children();
var_dump(count($kids));
?>
int(0)
int(2)
int(2)
int(0)
int(1)

Примечания

SimpleXMLElement::children() вернет узел объекта в любом случае, даже если текущий узел не имеет потомков. Используя count() для возвращенного значения, можно узнать о существовании потомков. В PHP 5.3.0 вместо этого можно использовать SimpleXMLElement::count().

Смотрите также

  • SimpleXMLElement::count() - Считает количество дочерних элементов у текущего элемента
  • count() - Подсчитывает количество элементов массива или что-то в объекте

User Contributed Notes

thetazzbot at gmail dot com 08-Sep-2011 06:56
Ok so say you have this xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE nitf
PUBLIC "-//IPTC-NAA//DTD NITF 3.1//EN"
       "http://www.nitf.org/site/nitf-documentation/nitf-3-1.dtd">
<nitf>
  <head>
    <docdata management-status="embargoed">
      <!--data/2011/08/23/parties/doc4e53aa5783cca930694817.txt-->
      <doc-id id-string="doc4e53aa5783cca930694817"/>
      <date.release norm="20110823T000000"/>
      <key-list/>
    </docdata>
    <pubdata type="web" position.section="parties" position.sequence="0"/>
  </head>

-- snip --

If you need to access the nodes named "like.this" such as the date.release above, here is how I did it:

$xml = new SimpleXMLElement($xhtml);
 echo (string)$xml->head->docdata->{"date.release"}["norm"];

Took me a while to figure that one out ;)
coldshine1 at rambler dot ru 10-Dec-2010 02:37
This is my recursive simple function to parse XML with attributes.

<?php
function ParseXML($node, &$parent=array(), $only_child=true) {

        //Current node name
        $node_name = $node->getName();

        //Let's count children
        $only_child = true;
        if($node->count() > 1 ) $only_child = false;

        //If there is no child, then there may be text data
        if($only_child){
            $content="$node";
            if (strlen($content)>0) $parent['content']=$content;
        }

        //Get attributes of current node
        foreach ($node->attributes() as $k=>$v) {
            $parent['@attributes'][$k]="$v";
        }

        //Get children
        $count = 0;
        foreach ($node->children() as $child_name=>$child_node) {
            if(!$only_child) //If there are siblings then we'll add node to the end of the array
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name][$count], $only_child);
            else
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name], $only_child);
            $count++;
        }

        return $parent;
        //(c) c01d[s]h!nE 10.12.2010
    }

?>
Anonymous 26-Oct-2010 05:19
Here's my xml-to-array routine. Unlike many of the other comments here, this one takes namespaces into account.

<?php

class XmlArray {

  public function load_dom ($xml) {
    $node=simplexml_import_dom($xml);
    return $this->add_node($node);
  }

  public function load_string ($s) {
    $node=simplexml_load_string($s);
    return $this->add_node($node);
  }

  private function add_node ($node, &$parent=null, $namespace='', $recursive=false) {

    $namespaces = $node->getNameSpaces(true);
    $content="$node";

    $r['name']=$node->getName();
    if (!$recursive) {
      $tmp=array_keys($node->getNameSpaces(false));
      $r['namespace']=$tmp[0];
      $r['namespaces']=$namespaces;
    }
    if ($namespace) $r['namespace']=$namespace;
    if ($content) $r['content']=$content;

    foreach ($namespaces as $pre=>$ns) {
      foreach ($node->children($ns) as $k=>$v) {
        $this->add_node($v, $r['children'], $pre, true);
      }
      foreach ($node->attributes($ns) as $k=>$v) {
        $r['attributes'][$k]="$pre:$v";
      }
    }
    foreach ($node->children() as $k=>$v) {
      $this->add_node($v, $r['children'], '', true);
    }
    foreach ($node->attributes() as $k=>$v) {
      $r['attributes'][$k]="$v";
    }

    $parent[]=&$r;
    return $parent[0];

  }

}

?>
alan at performantsystems dot com 11-Aug-2010 02:40
As I have occasion to retrieve a single data item rather than a list, I wanted a way to just grab and parse one data item from XML.  Here is one way to do that:

<?php
echo "\n";
$XML =
'<data>
   <USERS>
      <ID>alang</ID>
      <NAME>Alan Gruskoff</NAME>
      <ROLE>mgr</ROLE>
   </USERS>
</data>';

$xmlObject = new SimpleXMLElement($XML);

$node = $xmlObject->children();
echo "var_dump node\n";
var_dump($node);
echo "\n";

echo "\nnode ID=". $node[0]->ID;
echo "\nnode NAME=". $node[0]->NAME;
echo "\nnode ROLE=". $node[0]->ROLE;

echo "\n";
?>

This will show the contents of the $node child of the $xmlObject and then the specific element values.
php at shiinaringo dot se 18-Feb-2010 02:42
Most examples on this page do not take namespaces into account, rendering them useless in many cases. Here is a function to convert xml to array. You have to feed it the list of namespaces to use. Watch the example at the bottom.

<?php

function xml2phpArray($xml, $namespaces, $arr) {
    $iter = 0;

    foreach ($namespaces as $namespace => $namespaceUrl) {
        foreach ($xml->children($namespaceUrl) as $b) {
            $a = $b->getName();

            if ($b->children($namespaceUrl)) {
                $arr[$a][$iter] = array();
                $arr[$a][$iter] = xml2phpArray($b, $namespaces, $arr[$a][$iter]);
            }
            else {
                $arr[$a] = trim($b[0]);
            }

            $iter++;
        }
    }

    return $arr;
}

$xml = simplexml_load_file('http://urltosomexmlfile.xml');

$namespaces = array_merge(array('' => ''), $xml->getDocNamespaces(true));
$myArray = array();
$myArray = xml2phpArray($xml, $namespaces, $myArray);

?>
mrdaniellee at live dot com 10-Jan-2010 09:11
use this If you want to view the HTML as well as data.

normal dumps display the parsed versions of HTML.
This code displays the HTML as Text in a Text Area, and also display all other a data along side as an array

perfect for debugging (xml with html).

Try This Code:

<?php
$xml  = simplexml_load_file($url);

function xml2array_parse($xml){
     foreach ($xml->children() as $parent => $child){
         $return["$parent"] = xml2array_parse($child)?xml2array_parse($child):"$child";
     }
     return $return;
 }

 print "<pre><textarea style=\"width:200%;height:100%;\">";
 print_r(xml2array_parse($xml));
 print "</textarea></pre>";
?>
rodmen at gmail dot com 21-May-2009 08:32
Transform xml to array php

<?php
function xml2phpArray($xml,$arr){
    $iter = 0;
        foreach($xml->children() as $b){
                $a = $b->getName();
                if(!$b->children()){
                        $arr[$a] = trim($b[0]);
                }
                else{
                        $arr[$a][$iter] = array();
                        $arr[$a][$iter] = xml2phpArray($b,$arr[$a][$iter]);
                }
        $iter++;
        }
        return $arr;
}

$Array = simplexml_load_string(file_get_contents('myfile.xml'));
print_r(xml2phpArray($Array,array()));
?>
G dot B dot Yahav at Gmail dot com 25-Mar-2009 10:26
I done a very nice function to run over the XML element recursivly with SimpleXML, and print it on the screen

here it is:

<?php

$xml_han = new SimpleXMLElement( "data.xml", null, true );

print RecursiveXML( $xml_han );
function RecursiveXML( SimpleXMLElement $han, $preffix = "")
{
    if( count( $han->children() ) < 1 )
    {
        return $preffix . "&lt;" . $han->getName() . warpAttributes( $han->attributes() ) . "&gt;&nbsp;" . $han . "&nbsp;&lt;/" . $han->getName() . "&gt;<br />";
    }

    $ret = $preffix . "&lt;" . $han->getName() . warpAttributes( $han->attributes() ) . "&gt;<br />";
    foreach( $han->children() as $key => $child )
    {
        $ret .= RecursiveXML($child , $preffix . "|--&nbsp;&nbsp;&nbsp;" );
    }
    return $ret;
}

?>

enjoy :)
hoseinnj at google&#39;s great mail dot com 19-Mar-2009 11:25
Quick easy way to turn objectified SimpleXMLElement data into an array.

<?php
function get_xml_from_some_source(){
//blah blah blah build cUrl
$data = @curl_exec($ch);
$newdata = new SimpleXMLElement($data);
$new = xml2array_parse($newdata);
}

function xml2array_parse($xml){
     foreach ($xml->children() as $parent => $child){
         $return["$parent"] = xml2array_parse($child)?xml2array_parse($child):"$child";
     }
     return $return;
 }
?>

My first post, be nice.  ;-)
Anonymous 06-Sep-2008 05:39
for XML namespaces such as <dc:creator> in RSS feeds use

<?php
    $xml = new SimpleXMLElement($string);
    $item = $xml->channel[0]->item[0];
    $dc = $item->children("http://purl.org/dc/elements/1.1/");
    echo $dc->creator;
?>
transglobe at gmx dot de 19-Mar-2008 02:37
I made a slightly differnt approch towards the RecurseXML function. Beeing hungry I had problems with the code, as it did just overwrite two <maincourse>s. So here is what I did:

<?php

$xml = new SimpleXMLElement(
'<meal>
   <type>Lunch</type>
   <time>12:30</time>
   <menu>
     <entree>salad</entree>
     <maincourse>
        <part>ships</part>
        <part>steak</part>
     </maincourse>
     <maincourse>
        <part>fisch</part>
        <part>rice</part>
     </maincourse>
     <maincourse>
        <part>wine</part>
        <part>cheese</part>
     </maincourse>
   </menu>
</meal>');

$vals = array();
RecurseXML($xml,$vals);

foreach($vals as $key=>$value)
  print("{$key} = {$value}<BR>\n");

function RecurseXML($xml,&$vals,$parent="") {

  $childs=0;
  $child_count=-1; # Not realy needed.
  $arr=array();
        foreach ($xml->children() as $key=>$value) {
                if (in_array($key,$arr)) {
                        $child_count++;
                } else {
                        $child_count=0;
                }
                $arr[]=$key;
                $k=($parent == "") ? "$key.$child_count" : "$parent.$key.$child_count";
                $childs=RecurseXML($value,$vals,$k);
                if ($childs==0) {
                        $vals[$k]= (string)$value;
                }
        }

  return $childs;
}

?>
Output is like this:
type.0 = Lunch
time.0 = 12:30
menu.0.entree.0 = salad
menu.0.maincourse.0.part.0 = ships
menu.0.maincourse.0.part.1 = steak
menu.0.maincourse.0 =
menu.0.maincourse.1.part.0 = fisch
menu.0.maincourse.1.part.1 = rice
menu.0.maincourse.1 =
menu.0.maincourse.2.part.0 = wine
menu.0.maincourse.2.part.1 = cheese
menu.0.maincourse.2 =
menu.0 =

(Not beautiful, but it solved my case...)
crescentfreshpot at yahoo dot com 10-Dec-2007 08:16
Just a warning that the iterable returned from children() contains the '@attributes' key, which is "invisible" during a foreach but can be seen if using a different construct, such as list()=each() or casting to an array before iterating w/ foreach.
aero 23-May-2007 08:07
Here's a simple, recursive, function to transform XML data into pseudo E4X syntax ie. root.child.value = foobar

<?php
error_reporting(E_ALL);

$xml = new SimpleXMLElement(
'<Patriarch>
   <name>Bill</name>
   <wife>
     <name>Vi</name>
   </wife>
   <son>
     <name>Bill</name>
   </son>
   <daughter>
     <name>Jeri</name>
     <husband>
       <name>Mark</name>
     </husband>
     <son>
       <name>Greg</name>
     </son>
     <son>
       <name>Tim</name>
     </son>
     <son>
       <name>Mark</name>
     </son>
     <son>
       <name>Josh</name>
         <wife>
           <name>Kristine</name>
         </wife>
         <son>
           <name>Blake</name>
         </son>
         <daughter>
           <name>Liah</name>
         </daughter>
     </son>
   </daughter>
</Patriarch>');

RecurseXML($xml);

function RecurseXML($xml,$parent="")
{
   $child_count = 0;
   foreach($xml as $key=>$value)
   {
      $child_count++;
      if(RecurseXML($value,$parent.".".$key) == 0)  // no childern, aka "leaf node"
      {
         print($parent . "." . (string)$key . " = " . (string)$value . "<BR>\n");
      }
   }
   return $child_count;
}

?>

The output....

.name = Bill
.wife.name = Vi
.son.name = Bill
.daughter.name = Jeri
.daughter.husband.name = Mark
.daughter.son.name = Greg
.daughter.son.name = Tim
.daughter.son.name = Mark
.daughter.son.name = Josh
.daughter.son.wife.name = Kristine
.daughter.son.son.name = Blake
.daughter.son.daughter.name = Liah
taylorbarstow at that google mail thingy 21-Apr-2006 07:38
Sometimes you actually want an array, not a pseudo array.   This is especially true when you aren't dealing with attributes (i.e., you just want the array of child nodes).

Do like this:

<?php
$children = $sxml->xpath('child::node()');
?>

The reason you might want this is to be able to use array functions like array_shift, array_pop, etc.  This is especially true when you are writing recursive functions.  Simplexml works really well in iterative programming, but if you try to implement recursion it gets ugly.
Sebastian 27-Oct-2005 03:45
Just a quick addition:

If you need to access a child node which contains a dash, you need to encapsulate it with {""}.

For example:
<?php
foreach ($domain->domain-listing as $product) {
}
?>

The example above doesn't work because of the dash. But instead you need to use:
<?php
foreach ($domain->{"domain-listing"} as $product) {
}
?>

At least for me the second example works perfectly fine.
no-one 31-May-2005 06:05
For anyone who hasn't read Sterling Hughe's article (http://www.zend.com/php5/articles/php5-simplexml.php):

<?php
$xml_document =<<<EOT
<?xml version="1.0"?>
<root xmlns:foo="http://example.com">
  <foo:bar>baz</foo:bar>
</root>
EOT;

$xml_document = simplexml_load_xml($xml_document);

$foo_ns_bar = $xml_document->children('http://example.com');

echo $foo_ns_bar->bar[0]; // prints 'baz'
?>
Andrew Rose (rose dot andrew at gmail dot com) 16-Mar-2005 04:48
The example below shows the basic use of depth-first recursion to span the xml tree.

This is coded for the command line, and it prints out the original sentance above and then the copy cat sentence it creates itself for comparison, which as you will see; this example is slightly off from, I'll leave it upto you to resolve this issue.

All in all I personaly think xml and recursion go hand in hand, so if you don't understand recursion but know xml and want to use php to manipulate xml you will need to learn about recursion at some point.

<?php
$xml = simplexml_load_string(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

function recurse($child)
 {
   foreach($child->children() as $children) {
     echo ' who begot a '.$children['role'];
     recurse($children);
   }
    return;
 }

foreach($xml->children() as $children) {
 echo 'The person begot a '.$children['role'];
  recurse($children, 0);
 echo '; ';
}

echo "\n";
echo 'The person begot a son who begot a daughter; The person begot a daughter who begot a son; and that son begot a son'."\n";

?>
zyxwvu at users dot sourceforge dot net 15-Feb-2004 10:32
File:

<category>
  <item>text</item>
  <bold>text</bold>
  <item>text</item>
  <item>text</item>
  <mark>text</mark>
  <bold>text</bold>
</category>

If you want to get also names of the tags, you can use this loop layout:

<?php
foreach($category -> children() as $name => $node){
  echo $name.'<br/>';
}
?>
SimpleXMLElement::attributes
SimpleXMLElement::__construct
SimpleXMLElement


Создание нового SimpleXMLElement объекта

SimpleXMLElement::children
SimpleXMLElement::count
SimpleXMLElement
PHP Manual

SimpleXMLElement::__construct

(PHP 5 >= 5.0.1)

SimpleXMLElement::__construct — Создание нового SimpleXMLElement объекта

Описание

final public SimpleXMLElement::__construct() ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )

Создает новый SimpleXMLElement объект.

Список параметров

data

Правильно сформированная XML строка. Может быть путем или URL к XML документу, если параметр data_is_url установлен в TRUE.

options

Необязательный параметр, используется для указания дополнительных параметров Libxml.

data_is_url

По умолчанию, data_is_url установлен в FALSE. Используйте TRUE для указания того, что data является путем или URL к XML документу вместо string данных.

ns

Префикс пространства имен или URI.

is_prefix

TRUE если ns является префиксом, FALSE если это URI; по умолчанию FALSE.

Возвращаемые значения

Возвращает объект SimpleXMLElement представляющий data.

Ошибки

Выдает сообщение с ошибкой E_WARNING для каждой найденной ошибки в XML данных, и дополнительно генерирует исключение Exception, если XML данные не могут быть разобраны.

Подсказка

Используйте libxml_use_internal_errors() для подавления всех XML ошибок, и libxml_get_errors() для их переборки.

Примеры

Замечание:

Перечисленные примеры могут включать example.php, в котором определяется XML строка, расположенная в первом примере руководства по базовому использованию.

Пример #1 Создание объекта SimpleXMLElement

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

Результат выполнения данного примера:

PHP: Появление Парсера

Пример #2 Создание объекта SimpleXMLElement из URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

Смотрите также

  • Базовое использование SimpleXML
  • simplexml_load_string() - Интерпретирует строку с XML в объект
  • simplexml_load_file() - Интерпретирует XML-файл в объект
  • Работа с ошибками XML
  • libxml_use_internal_errors() - Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю

User Contributed Notes

kumarldh at gmail dot com 22-Mar-2011 10:50
Using libxml_use_internal_errors() may suppress errors but Exception still requires decent handling. I used following code snippet.

<?php
libxml_use_internal_errors(true);
try{
    $xmlToObject = new SimpleXMLElement($notSoWellFormedXML);
} catch (Exception $e){
    echo 'Please try again later...';
    exit();
}
?>
zwilson at gulosolutions dot com 19-Nov-2009 10:16
SimpleXML does not correctly parse SOAP XML results if the result comes back with colons ‘:’ in a tag, like <soap:Envelope>. Why? Because SimpleXML treats the colon character ‘:’ as an XML namespace, and places the entire contents of the SOAP XML result inside a namespace within the SimpleXML object. There is no real way to correct this using SimpleXML, but we can alter the raw XML result a little before we send it to SimpleXML to parse.

All we have to do is use the preg_replace function to get rid of the colons in the SOAP response tags BEFORE you hand it off to SimpleXML, like so:

<?php
// SimpleXML seems to have problems with the colon ":" in the <xxx:yyy> response tags, so take them out
$xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
?>
uramihsayibok, gmail, com 16-Aug-2009 06:52
As I was filling out a bug report, I realized why (speculation here) the constructor is final: so that functions like simplexml_load_file and simplexml_load_string can work. I imagine the PHP-ized code looks something like

<?php

function simplexml_load_file($filename, $class_name = "SimpleXMLElement", $options = 0, $ns = "", $is_prefix = false) {
    return new $class_name($filename, $options, true, $ns, $is_prefix);
}

?>

If we were to use a different $class_name and change the constructor's definition these functions wouldn't work.

There's no easy, sensible solution that keeps simplexml_load_file and simplexml_load_string.
tudor at culise dot net 20-Nov-2007 03:35
This class is extendable, but it's too bad that its constructor cannot be overriden (PHP says it's a final method). Thus the class should be wrapped using the delegation principle rather that extended.
SimpleXMLElement::children
SimpleXMLElement::count
SimpleXMLElement


Считает количество дочерних элементов у текущего элемента

SimpleXMLElement::__construct
SimpleXMLElement::getDocNamespaces
SimpleXMLElement
PHP Manual

SimpleXMLElement::count

(PHP 5 >= 5.3.0)

SimpleXMLElement::count — Считает количество дочерних элементов у текущего элемента

Описание

public int SimpleXMLElement::count ( void )

Этот метод подсчитывает количество дочерних элементов у текущего элемента.

Возвращаемые значения

Возвращает число элементов у текущего элемента.

Примеры

Пример #1 Подсчет количества дочерних элементов

<?php
$xml = <<<EOF
<people>
 <person name="Человек 1">
  <child/>
  <child/>
  <child/>
 </person>
 <person name="Человек 2">
  <child/>
  <child/>
  <child/>
  <child/>
  <child/>
 </person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
    printf("%s имеет %d детей.\n", $person['name'], $person->count());
}
?>

Результат выполнения данного примера:

Человек 1 имеет 3 детей.
Человек 2 имеет 5 детей.

Смотрите также

  • SimpleXMLElement::children() - Поиск дочерних элементов данного узла

User Contributed Notes

daniel dot erni at focusedpublishing dot com 22-Mar-2011 08:37
Alternative code for PHP < 5.3:
<?php
$count = $node->count(); // PHP > 5.3
$count = count($node->children()); // PHP < 5.3
?>
Jimmy New Tron 15-Jun-2010 08:17
I used the DOMNodeList $length property to simulate this function since my host had not yet implemented PHP 5.3.  The following code makes it portable and allows you to prepare for an upgrade path.

<?php
$url = "http://www.example.com/foo.xml";
$xml = simplexml_load_file($url);
// For debugging
// echo "<p>".phpversion()."</p>";
if(phpversion() >= '5.3.0'){
    $bar_count = $xml->foo->bar->count();
    }
else    {
    $doc = new DOMDocument();
    $str = $xml->asXML();
    $doc->loadXML($str);
    $bar_count = $doc->getElementsByTagName("bar")->length;
    }
echo "There are ".$bar_count." \"bar\" nodes in this document.<br />";
?>
SimpleXMLElement::__construct
SimpleXMLElement::getDocNamespaces
SimpleXMLElement


Возвращает объявленное пространство имен в документе

SimpleXMLElement::count
SimpleXMLElement::getName
SimpleXMLElement
PHP Manual

SimpleXMLElement::getDocNamespaces

(PHP 5 >= 5.1.2)

SimpleXMLElement::getDocNamespaces — Возвращает объявленное пространство имен в документе

Описание

public array SimpleXMLElement::getDocNamespaces ([ bool $recursive = false ] )

Возвращает объявленное пространство имен в документе

Список параметров

recursive

Если указано, то возвращает все объявленные пространства имен у родительского узла и его дочерних элементов. В противном случае, возвращает только объявленное пространство имен корневого узла.

Возвращаемые значения

Метод getDocNamespaces возвращает массив array с названиями пространств имен и связанными с ними URI.

Примеры

Пример #1 Получение пространства имен документа

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces();
var_dump($namespaces);

?>

Результат выполнения данного примера:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Пример #2 Работа с несколькими пространствами имен

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person t:id="1">John Doe</p:person>
    <p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
        Susie Q. Public
    </p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

Результат выполнения данного примера:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Смотрите также

  • SimpleXMLElement::getNamespaces() - Получение пространств имен, используемых в документе
  • SimpleXMLElement::registerXPathNamespace() - Создает префикс/пространство имен контекста для следующего XPath запроса

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLElement::count
SimpleXMLElement::getName
SimpleXMLElement


Получение имени XML элемента

SimpleXMLElement::getDocNamespaces
SimpleXMLElement::getNamespaces
SimpleXMLElement
PHP Manual

SimpleXMLElement::getName

(PHP 5 >= 5.1.3)

SimpleXMLElement::getName — Получение имени XML элемента

Описание

public string SimpleXMLElement::getName ( void )

Получает имя XML элемента.

Возвращаемые значения

Метод getName возвращает имя тега XML в виде строки string, на который ссылается SimpleXMLElement объект.

Примеры

Замечание:

Перечисленные примеры могут включать example.php, в котором определяется XML строка, расположенная в первом примере руководства по базовому использованию.

Пример #1 Получение имен XML элемента

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
    echo $child->getName() . "\n";
}

?>

Результат выполнения данного примера:

movies
movie

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLElement::getDocNamespaces
SimpleXMLElement::getNamespaces
SimpleXMLElement


Получение пространств имен, используемых в документе

SimpleXMLElement::getName
SimpleXMLElement::registerXPathNamespace
SimpleXMLElement
PHP Manual

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2)

SimpleXMLElement::getNamespaces — Получение пространств имен, используемых в документе

Описание

public array SimpleXMLElement::getNamespaces ([ bool $recursive = false ] )

Возвращает пространства имен, используемые в документе

Список параметров

recursive

Если указано, то возвращает все используемые пространства имен у родительского узла и его дочерних элементов. В противном случае, возвращает только используемое пространство имен корневого узла.

Возвращаемые значения

Метод getNamespaces возвращает массив array с названиями пространств имен и связанными с ними URI.

Примеры

Пример #1 Получение пространств имен, используемых в документе

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

Результат выполнения данного примера:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

Смотрите также

  • SimpleXMLElement::getDocNamespaces() - Возвращает объявленное пространство имен в документе
  • SimpleXMLElement::registerXPathNamespace() - Создает префикс/пространство имен контекста для следующего XPath запроса

User Contributed Notes

harry at nospam dot thestorm dot plus dot com 17-Feb-2012 02:21
If the namespace is nested in the xml, then you will have to loop over the nodes.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
 <people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
     <items>
           <title>This is a test of namespaces and my patience</title>
           <p:person id="1">John Doe</p:person>
           <p:person id="2">Susie Q. Public</p:person>
           <p:person id="1">Fish Man</p:person>
     </items>
 </people>
XML;

$sxe = new SimpleXMLElement($xml);

foreach ($sxe as $out_ns)
{
    $ns = $out_ns->getNamespaces(true);

    $child = $out_ns->children($ns['p']);
}

print_r($child);

foreach ($child as $out)
{
    echo $out ."<br />";
}

?>
harry at nospam dot thestorm dot plus dot com 16-Feb-2012 12:50
To read a namespace node you have to use the children method.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$ns = $sxe->getNamespaces(true);

$child = $sxe->children($ns['p']);

foreach ($child->person as $out_ns)
{
    echo $out_ns;
}

?>
SimpleXMLElement::getName
SimpleXMLElement::registerXPathNamespace
SimpleXMLElement


Создает префикс/пространство имен контекста для следующего XPath запроса

SimpleXMLElement::getNamespaces
SimpleXMLElement::saveXML
SimpleXMLElement
PHP Manual

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.2.0)

SimpleXMLElement::registerXPathNamespace — Создает префикс/пространство имен контекста для следующего XPath запроса

Описание

public bool SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns )

Создает префикс/пространство имен контекста для следующего XPath запроса. В частности это необходимо, если поставщик данного XML документа изменяет префикс пространства имен. registerXPathNamespace создаст префикс для связанного пространства имен, позволяя получить доступ к узлам в этом пространстве имен без необходимости изменения кода, учитывающего новые префиксы, предоставленные поставщиком.

Список параметров

prefix

Префикс используемого пространства имен в запросе XPath для получения пространства имен в ns.

ns

Используемое пространство имен для запроса XPath. Оно должно соответствовать пространству имен в используемом XML документе иначе запрос XPath использующий prefix не даст никаких результатов.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Установка префикса пространства имен для использования в запросе XPath

<?php

$xml = <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
    <title>My Book</title>
    <chapter id="1">
        <chap:title>Chapter 1</chap:title>
        <para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
            In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
            Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
            ultricies id, mauris.</para>
    </chapter>
    <chapter id="2">
        <chap:title>Chapter 2</chap:title>
        <para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
            gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
            vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
            tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
    </chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach ($result as $title) {
  echo $title . "\n";
}

?>

Результат выполнения данного примера:

Chapter 1
Chapter 2

Обратите внимание, на то, как в примере XML-документу задается пространство имен с префиксом chap. Представьте, что этот документ (или другой похожий) может использовать префикс c. Так как он изменится, то запрос XPath больше не будет возвращать необходимых результатов и придется изменить запрос. Использование registerXPathNamespace позволяет избежать будущих модификаций запросов, даже если поставщик изменит префикс прострнства имен.

Смотрите также

  • SimpleXMLElement::xpath() - Запускает XPath запрос к XML данным
  • SimpleXMLElement::getDocNamespaces() - Возвращает объявленное пространство имен в документе
  • SimpleXMLElement::getNamespaces() - Получение пространств имен, используемых в документе

User Contributed Notes

Lea Hayes 12-Jan-2011 09:56
Looks like you have to use registerXPathNamespace for each node when using XPath:

<?php
$xml = simplexml_load_file($filename);

$xml->registerXPathNamespace('test', 'http://example.com');

$shopping_element = $xml->xpath('test:shopping-list');

// Breaks with out the following line:

$shopping_element->registerXPathNamespace('test', 'http://example.com');

$fruit = $shopping_element->xpath('test:fruit');
?>
SimpleXMLElement::getNamespaces
SimpleXMLElement::saveXML
SimpleXMLElement


Псевдоним SimpleXMLElement::asXML

SimpleXMLElement::registerXPathNamespace
SimpleXMLElement::xpath
SimpleXMLElement
PHP Manual

SimpleXMLElement::saveXML

(PHP 5 >= 5.2.0)

SimpleXMLElement::saveXML — Псевдоним SimpleXMLElement::asXML()

Описание

Этот метод является псевдонимом: SimpleXMLElement::asXML()

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLElement::registerXPathNamespace
SimpleXMLElement::xpath
SimpleXMLElement


Запускает XPath запрос к XML данным

SimpleXMLElement::saveXML
SimpleXMLIterator
SimpleXMLElement
PHP Manual

SimpleXMLElement::xpath

(PHP 5 >= 5.2.0)

SimpleXMLElement::xpath — Запускает XPath запрос к XML данным

Описание

public array SimpleXMLElement::xpath ( string $path )

Метод xpath ищет узлы SimpleXML с дочерними элементами, совпадающими с XPath path.

Список параметров

path

Путь XPath

Возвращаемые значения

Возвращает массив array объектов SimpleXMLElement или FALSE в случае ошибки.

Примеры

Пример #1 Xpath

<?php
$string = <<<XML
<a>
 <b>
  <c>текст</c>
  <c>вещь</c>
 </b>
 <d>
  <c>код</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Поиск <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo '/a/b/c: ',$node,"\n";
}

/* Относительные пути также работают... */
$result = $xml->xpath('b/c');

while(list( , $node) = each($result)) {
    echo 'b/c: ',$node,"\n";
}
?>

Результат выполнения данного примера:

/a/b/c: текст
/a/b/c: вещь
b/c: текст
b/c: вещь

Обратите внимание, что оба результата одинаковы.

Смотрите также

  • SimpleXMLElement::registerXPathNamespace() - Создает префикс/пространство имен контекста для следующего XPath запроса
  • SimpleXMLElement::getDocNamespaces() - Возвращает объявленное пространство имен в документе
  • SimpleXMLElement::getNamespaces() - Получение пространств имен, используемых в документе
  • Базовое использование SimpleXML

User Contributed Notes

jan at ingoedebanen dot nl 30-Oct-2011 11:32
If you want to search for quoted values use the xpath concat function.
<?php
// see note "paul at pmtlogic dot com"
$xml->xpath('//zone[@country=concat("Cote d", \''\', "Ivoire")]');
?>
yetihehe at yetihehe dot com 12-Jan-2011 02:21
Xpath actually knows which element is root regardless of element on which you execute it. Example:

<?php

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <b>
  <c>code</c>
 </b>
</a>
XML;

header('content-type: text/plain');

$xml = new SimpleXMLElement($string);

//relative to root
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: //c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: //c: ',$node,"\n";
}

echo "\n";

//relative to current element
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: .//c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: .//c: ',$node,"\n";
}

?>

Will return:
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code

b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code
stefan at efectos dot nl 09-Nov-2010 02:33
Having problems selecting information through xpath when there are namespaces in the XML?

Try this quick and dirty solution, but it works:

<?php
$objImageXml = new SimpleXMLElement($objImageXml->asXML());
?>
eleg 10-May-2010 04:25
to be able to use the default namespace:

<?php
    $xml = simplexml_load_file('test.xfdf');
    $namespaces = $xml->getDocNamespaces();
    $xml->registerXPathNamespace('__empty_ns', $namespaces['']);
    $result = $xml->xpath('//__empty_ns:field/@name');
?>
grummfy at gmail dot com 11-Feb-2010 04:08
On a xml that have namespace you need to do this before your xpath request (or empty array will be return) :

<?php
$string = str_replace('xmlns=', 'ns=', $string); //$string is a string that contains xml...
?>
DrupalFocus at earthlink dot net 02-Dec-2009 12:27
Looks like the relative path is relative to the SimpleXMLElement object that you call the Xpath() method on.  Basically chopping off the root element.

<?php
$string = <<<XML
<foo>
  <bar>
    <a>
     <b>
      <c>text</c>
      <c>stuff</c>
     </b>
     <d>
      <c>code</c>
     </d>
    </a>
  </bar>
</foo>
XML;

$xml = new SimpleXMLElement($string);
/* Search for children using 2nds level relative <bar><a><b><c> */
$result = $xml->xpath('a/b/c');
if ($result)
foreach($result as $node) {
    drupal_set_message(t('a/b/c: @node.', array('@node' => $node)));
}
else
  drupal_set_message(t('a/b/c: failed.'));

/* it relative to the SimpleXMLElement Search for 2nds level relative <bar><a><b><c> but where is foo */
$bar = $xml->bar;
$result = $bar->xpath('a/b/c');
foreach($result as $node) {
    drupal_set_message(t('bar->a/b/c: @node.', array('@node' => $node)));
}
?>

results in :
#
# a/b/c: failed.
# bar->a/b/c: text.
# bar->a/b/c: stuff.
behnam@zwnj 24-Sep-2009 01:34
Seems like this function cannot return the result of XPath string() [1] function.  For example if you query xpath("string(a/@b)") you will get bool(false) although the node "a" may have the attribute "b" set to a non-empty string.

[1] http://www.w3.org/TR/xpath#section-String-Functions
Anti Veeranna 17-Jun-2009 03:50
Whether it returns a false or empty array for a non-existing path seems to depend on libxml version.

I tried the following code:

<?php
$data = '<foo><bar></bar></foo>';
$xml = simplexml_load_string($data);
print gettype($xml->xpath('/first/second'));
?>

On a machine with libxml 2.6.16 and PHP 5.2.8 I got back boolean. On a different machine with libxml 2.7.3 and PHP 5.2.8/5.2.9 I got back empty array.

You can check the libxml version from command line by executing: php --ri libxml

or simply look at phpinfo() output
arealzone-czernobyl at yahoo dot de 11-Jun-2009 03:23
The simplest way to count nodes in a XML doc:

<?php
$xml = new SimpleXMLElement($xmlstr);

$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);

echo $nodeCount;
?>
anemik 02-Jul-2008 03:46
If you want to find easly all records satisfying some condition in XML data like

....
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
...

try example below

<?php

$xmlStr = file_get_contents('data/books.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find all book records with price higher than 40$
$res = $xml->xpath("book/price[.>'40']/parent::*");
print_r($res);

?>

You will see response like:
Array (
[0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => bk101
                )

            [author] => Gambardella, Matthew
            [title] => XML Developer's Guide
            [genre] => Computer
            [price] => 44.95
            [publish_date] => 2000-10-01
            [description] => An in-depth look at creating applications
      with XML.
        )
...
paul at pmtlogic dot com 18-Jun-2008 12:17
xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.

xml snippet:

<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>

The following code does not work:

<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");

foreach ( $result[0]->attributes() as $key => $val ) {
    print "<div class='coords'>$key: $val</div>\n";
}
?>

I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.

In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:

<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
canuemail at gmail dot com 05-May-2008 05:05
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
brettz9 through yah 13-Sep-2006 07:31
I was looking to find all of a given element type with attributes which were not of a particular value (including null items).

I tried this...
<?php
   $xml->xpath("//pg[@show!='none']");
?>
...But that only worked if there was in fact some attribute.

I thought this should work (shouldn't it?), but it didn't:
<?php
   $xml->xpath("//pg[@show!='none' or !@show]");
?>

The solution is to use the not() function:

<?php
   $xml->xpath("//pg[not(@show='none')]");
?>
ron @ rotflol dot cx 29-Mar-2006 09:07
xpath returning references to the parent simplexml object can bite you performance wise when processing large trees.
this bit me big time so looking for a solution I came up with a simple way to speed up the code.

'dereferencing' will yield instant results, code will be lighting fast.
sacrifice is losing the reference to the parent object, for simple read-only operation this should be ok.

<?php
$data = 'data.xml';
$rs = simplexml_load_file($data);
foreach($rs->xpath('//row') as $rsrow){
    // 'derefence' into a seperate xml tree for performance
    $row = simplexml_load_string($rsrow->asXML());
    $v = $row->xpath('//field[@name="id"]');

}
?>
drewish at katherinehouse dot com 09-Jan-2006 11:40
here's a simple work-around for the lack of support for default namespaces, just overwrite the xmlns attribute of the root element:
<?php
$xml = simplexml_load_file('http://example.com/atom_feed.xml');
// hack to work around php 5.0's problems with default namespaces and xpath()
$xml['xmlns'] = '';
// now our queries work:
$titles = $xml->xpath('entry/title');
foreach ((array)$titles as $title) {
    print "$title\n";
}
?>
Hugh 18-Dec-2005 03:23
Note that this function does not ALWAYS return an array. It seems that if the specified path is not found in the document, it will return false. You need to check for the false value before using foreach, if you wish to avoid a warning (and often to handle errors or control program flow in this situation).
retardis at gmail dot com 24-Aug-2005 01:21
Xpath actually returns an array full of references to elements in the parent SimpleXML object. Therefore, in addition to preserving attributes, you can actually modify them and the result will be reflected in the parent.

Example:

<?php

$xml_str = <<<END
<a>
    <b attr="foo"/>
</a>
END;

$xml = simplexml_load_string ($xml_str);
$result = $xml->xpath ('/a/b'); // returns an array with one element
$result[0]['attr'] = 'bar';
print $xml->asXML ();
?>

Outputs:
<a>
    <b attr="bar"/>
</a>
drewish at katherinehouse dot com 10-Jul-2005 06:16
xpath() can also be used to select elements by their attributes. For a good XPath reference check out: http://www.w3schools.com/xpath/xpath_syntax.asp

<?php
$string = <<<XML
<sizes>
    <size label="Square" width="75" height="75" />
    <size label="Thumbnail" width="100" height="62" />
    <size label="Small" width="112" height="69" />
    <size label="Large" width="112" height="69" />
</sizes>
XML;

$xml = simplexml_load_string($string);
$result = $xml->xpath("//size[@label='Large']");

// print the first (and only) member of the array
echo $result[0]->asXml();
?>

The script would print:
<size label="Large" width="112" height="69"/>
matt@roughest[d0t]net 03-Sep-2004 12:17
This may be obvious, but in case you're wondering, the array resulting from the xpath() operation doesn't retain any of the nodes' attributes.

In other words, it won't return any of the tags' attributes
SimpleXMLElement::saveXML
SimpleXMLIterator
SimpleXMLElement


Класс SimpleXMLIterator

(PHP 5 >= 5.1.0)

Введение

SimpleXMLIterator обеспечивает рекурсивную итерацию по всем узлам объекта SimpleXMLElement.

Обзор классов

SimpleXMLIterator extends SimpleXMLElement implements RecursiveIterator , Traversable , Iterator , Countable {
/* Методы */
public mixed current ( void )
SimpleXMLIterator getChildren ( void )
bool hasChildren ( void )
mixed key ( void )
void next ( void )
void rewind ( void )
bool valid ( void )
/* Наследуемые методы */
final public SimpleXMLElement::__construct ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )
public void SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] )
public SimpleXMLElement SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )
public mixed SimpleXMLElement::asXML ([ string $filename ] )
public SimpleXMLElement SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )
public SimpleXMLElement SimpleXMLElement::children ([ string $ns [, bool $is_prefix = false ]] )
public int SimpleXMLElement::count ( void )
public array SimpleXMLElement::getDocNamespaces ([ bool $recursive = false ] )
public string SimpleXMLElement::getName ( void )
public array SimpleXMLElement::getNamespaces ([ bool $recursive = false ] )
public bool SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns )
public array SimpleXMLElement::xpath ( string $path )
}

Содержание

  • SimpleXMLIterator::current — Возвращает текущий элемент
  • SimpleXMLIterator::getChildren — Возвращает вложенные элементы текущего элемента
  • SimpleXMLIterator::hasChildren — Проверяет, имеет ли текущий элемент вложенные элементы
  • SimpleXMLIterator::key — Возвращает текущий ключ
  • SimpleXMLIterator::next — Перемещает итератор к следующему элементу
  • SimpleXMLIterator::rewind — Возвращает итератор к первому элементу
  • SimpleXMLIterator::valid — Проверяет, является ли текущий элемент допустимым

User Contributed Notes

ajnsit dot NOSPAM at gmail dot com 17-Mar-2011 10:14
Here's a simple function to convert an XML string to an array -

<?php
// PHP5.3 and above only
function parse($str) {
    $f = function($iter) {
      foreach($iter as $key=>$val)
        $arr[$key][] = ($iter->hasChildren())?
          call_user_func (__FUNCTION__, $val)
          : strval($val);
      return $arr;
    };
    return $f(new SimpleXmlIterator($str, null));
}
?>

PHP 5.2 and below do not have anonymous functions.
But you can create a helper function to achieve the same thing -

<?php
  function parse($str) {
    return parseHelper(new SimpleXmlIterator($str, null));
  }
  function parseHelper($iter) {
    foreach($iter as $key=>$val)
      $arr[$key][] = ($iter->hasChildren())?
        call_user_func (__FUNCTION__, $val)
        : strval($val);
    return $arr;
  }
?>

Using it is straightforward enough -

<?php

$xml = '
<movies>
  <movie>abcd</movie>
  <movie>efgh</movie>
  <movie>hijk</movie>
</movies>';
var_dump(parse($xml));

?>

This will output -

array
  'movie' =>
    array
      0 => string 'abcd' (length=4)
      1 => string 'efgh' (length=4)
      2 => string 'hijk' (length=4)
ratfactor at gmail dot com 19-Jul-2009 05:08
The documentation is a bit sparse for SimpleXmlIterator.  Here is an example showing the use of its methods. xml2Array and sxiToArray work together to convert an XML document to an associative array structure.

The contents of cats.xml:
======================================
<cats>
  <cat>
      <name>Jack</name>
      <age>2</age>
      <color>grey</color>
      <color>white</color>
  </cat>
  <cat>
      <name>Maxwell</name>
      <age>12</age>
      <color>orange</color>
      <color>black</color>
  </cat>
</cats>
======================================

<?php
function xml2array($fname){
  $sxi = new SimpleXmlIterator($fname, null, true);
  return sxiToArray($sxi);
}

function sxiToArray($sxi){
  $a = array();
  for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
    if(!array_key_exists($sxi->key(), $a)){
      $a[$sxi->key()] = array();
    }
    if($sxi->hasChildren()){
      $a[$sxi->key()][] = sxiToArray($sxi->current());
    }
    else{
      $a[$sxi->key()][] = strval($sxi->current());
    }
  }
  return $a;
}

// Read cats.xml and print the results:
$catArray = xml2array('cats.xml');
print_r($catArray);
?>

Results (reformatted a bit for compactness and clarity):
======================================
Array(
  [cat] => Array(
    [0] => Array(
      [name] => Array(  [0] => Jack    )
      [age] => Array(   [0] => 2       )
      [color] => Array( [0] => grey,
                        [1] => white   )
    )
    [1] => Array(
      [name] => Array(  [0] => Maxwell )
      [age] => Array(   [0] => 12      )
      [color] => Array( [0] => orange
                        [1] => black   )
    )
  )
)
David Lanstein 17-Jan-2009 06:40
Unlike the DirectoryIterator, for one, you'll need to call $it->rewind() before using the iterator in a for() or while() loop.  Calling foreach() does rewind the iterator before iteration.
SimpleXMLElement::xpath
SimpleXMLIterator::current
SimpleXML


Возвращает текущий элемент

SimpleXMLIterator
SimpleXMLIterator::getChildren
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::current

(PHP 5 >= 5.1.0)

SimpleXMLIterator::current — Возвращает текущий элемент

Описание

public mixed SimpleXMLIterator::current ( void )

Этот метод возвращает текущий элемент как объект класса SimpleXMLIterator или NULL.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает текущий элемент как объект класса SimpleXMLIterator или NULL в случае ошибки.

Примеры

Пример #1 Возвращение текущего элемента

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>Основы PHP</book><book>Основы XML</book></books>');
var_dump($xmlIterator->current());

$xmlIterator->rewind(); // сбрасывает курсор к первому элементу
var_dump($xmlIterator->current());
?>

Результат выполнения данного примера:

NULL
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "Основы PHP"
}

Смотрите также

  • SimpleXMLIterator::key() - Возвращает текущий ключ
  • SimpleXMLIterator::next() - Перемещает итератор к следующему элементу
  • SimpleXMLIterator::rewind() - Возвращает итератор к первому элементу
  • SimpleXMLIterator::valid() - Проверяет, является ли текущий элемент допустимым
  • SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLIterator
SimpleXMLIterator::getChildren
SimpleXMLIterator


Возвращает вложенные элементы текущего элемента

SimpleXMLIterator::current
SimpleXMLIterator::hasChildren
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::getChildren

(PHP 5 >= 5.1.0)

SimpleXMLIterator::getChildren — Возвращает вложенные элементы текущего элемента

Описание

SimpleXMLIterator SimpleXMLIterator::getChildren ( void )

Этот метод возвращает объект SimpleXMLIterator, содержащий вложенные элементы текущего элемента SimpleXMLIterator.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает объект SimpleXMLIterator, содержащий вложенные элементы текущего элемента.

Примеры

Пример #1 Возвращает вложенные элементы текущего элемента

$xml = <<<XML
<books>
    <book>
        <title>Основы PHP</title>
        <author>Джим Смит</author>
    </book>
    <book>Основы XML</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator($xml);
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    foreach($xmlIterator->getChildren() as $name => $data) {
    echo "$name: '$data' из класса " . get_class($data) . "\n";
    }
}
?>

Результат выполнения данного примера:

title: 'Основы PHP' из класса SimpleXMLIterator
author: 'Джим Смит' из класса SimpleXMLIterator

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLIterator::current
SimpleXMLIterator::hasChildren
SimpleXMLIterator


Проверяет, имеет ли текущий элемент вложенные элементы

SimpleXMLIterator::getChildren
SimpleXMLIterator::key
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::hasChildren

(PHP 5 >= 5.1.0)

SimpleXMLIterator::hasChildren — Проверяет, имеет ли текущий элемент вложенные элементы

Описание

bool SimpleXMLIterator::hasChildren ( void )

Этот метод проверяет, имеет ли текущий элемент SimpleXMLIterator вложенные элементы.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

TRUE если у текущего элемента есть вложенные элементы; в противном случае FALSE

Примеры

Пример #1 Проверяет, имеет ли текущий элемент вложенные элементы

<?php
$xml = <<<XML
<books>
    <book>
        <title>Основы PHP</title>
        <author>Джим Смит</author>
    </book>
    <book>Основы XML</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator( $xml );
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    if($xmlIterator->hasChildren()) {
        var_dump($xmlIterator->current());
    }
}
?>

Результат выполнения данного примера:

object(SimpleXMLIterator)#2 (2) {
  ["title"]=>
  string(10) "Основы PHP"
  ["author"]=>
  string(9) "Джим Смит"
}

User Contributed Notes

grummfy at gmail dot com 12-Feb-2010 01:01
Hello,

just a note for people like me who encounter the problems :

<?php
foreach($xmlIterator as $x)
{
    if($x->hasChildren())
    {
        //never reach
        echo 'x : ';
        var_dump($x->current());
    }
    if($xmlIterator->hasChildren())
    {
        echo 'iterator : ';
        var_dump($x->current()); //all time null
        var_dump($xmlIterator->current());
    }
}
?>
SimpleXMLIterator::getChildren
SimpleXMLIterator::key
SimpleXMLIterator


Возвращает текущий ключ

SimpleXMLIterator::hasChildren
SimpleXMLIterator::next
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::key

(PHP 5 >= 5.1.0)

SimpleXMLIterator::key — Возвращает текущий ключ

Описание

mixed SimpleXMLIterator::key ( void )

Этот метод получает имя XML-тега текущего элемента.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает имя XML-тега элемента, на который ссылается текущий объект SimpleXMLIterator, или FALSE

Примеры

Пример #1 Получает имя текущего XML-тега

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>Основы PHP</book><book>Основы XML</book></books>');

echo var_dump($xmlIterator->key());
$xmlIterator->rewind(); // возврат к первому элементу
echo var_dump($xmlIterator->key());

?>

Результат выполнения данного примера:

bool(false)
string(4) "book"

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLIterator::hasChildren
SimpleXMLIterator::next
SimpleXMLIterator


Перемещает итератор к следующему элементу

SimpleXMLIterator::key
SimpleXMLIterator::rewind
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::next

(PHP 5 >= 5.1.0)

SimpleXMLIterator::next — Перемещает итератор к следующему элементу

Описание

void SimpleXMLIterator::next ( void )

Этот метод перемещает SimpleXMLIterator к следующему элементу.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Перемещение к следующему элементу

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>Основы PHP</book><book>Основы XML</book></books>');
$xmlIterator->rewind(); // возврат к первому элементу
$xmlIterator->next();

var_dump($xmlIterator->current());
?>

Результат выполнения данного примера:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "Основы XML"
}

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLIterator::key
SimpleXMLIterator::rewind
SimpleXMLIterator


Возвращает итератор к первому элементу

SimpleXMLIterator::next
SimpleXMLIterator::valid
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::rewind

(PHP 5 >= 5.1.0)

SimpleXMLIterator::rewind — Возвращает итератор к первому элементу

Описание

void SimpleXMLIterator::rewind ( void )

Этот метод возвращает SimpleXMLIterator к первому элементу.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Возврат к первому элементу

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>Основы PHP</book><book>Основы XML</book></books>');
$xmlIterator->rewind();

var_dump($xmlIterator->current());
?>

Результат выполнения данного примера:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "Основы PHP"
}

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLIterator::next
SimpleXMLIterator::valid
SimpleXMLIterator


Проверяет, является ли текущий элемент допустимым

SimpleXMLIterator::rewind
SimpleXML
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::valid

(PHP 5 >= 5.1.0)

SimpleXMLIterator::valid — Проверяет, является ли текущий элемент допустимым

Описание

bool SimpleXMLIterator::valid ( void )

Этот метод проверяет, является ли текущий элемент допустимым после вызова SimpleXMLIterator::rewind() или SimpleXMLIterator::next().

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает TRUE если текущий элемент допустим; в противном случае FALSE

Примеры

Пример #1 Проверяет, является ли текущий элемент допустимым

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>Основы SQL</book></books>');

$xmlIterator->rewind(); // возврат к первому элементу
echo var_dump($xmlIterator->valid()); // bool(true)

$xmlIterator->next(); // перейти к следующему элементу
echo var_dump($xmlIterator->valid()); // bool(false), поскольку есть только один элемент
?>

User Contributed Notes

There are no user contributed notes for this page.
SimpleXMLIterator::rewind
SimpleXML
SimpleXMLIterator


SimpleXML
PHP Manual

SimpleXML

Содержание

  • simplexml_import_dom — Получает объект класса SimpleXMLElement из узла DOM.
  • simplexml_load_file — Интерпретирует XML-файл в объект
  • simplexml_load_string — Интерпретирует строку с XML в объект

User Contributed Notes

thomas at guenneguez dot com 14-Dec-2011 02:36
Merge two xml only with SimpleXML :
Function corrected if note containe only value.

<?php
function mergeXML(&$base, $add)
{
    if ( $add->count() != 0 )
        $new = $base->addChild($add->getName());
    else
        $new = $base->addChild($add->getName(), $add);
    foreach ($add->attributes() as $a => $b)
    {
        $new->addAttribute($a, $b);
    }
    if ( $add->count() != 0 )
    {
        foreach ($add->children() as $child)
        {
            mergeXML($new, $child);
        }
    }
}
?>

Use : <?php mergeXML($xmlElement, simplexml_load_string($toMerge)) ?>
julien dot breiner at laposte dot net 09-Dec-2011 10:31
Merge two xml only with SimpleXML :

<?php
private function mergeXML(&$base, $add)
{
    $new = $base->addChild($add->getName());
    foreach ($add->attributes() as $a => $b) {
        $new[$a] = $b;
    }
    foreach ($add->children() as $child) {
        $this->mergeXML($new, $child);
    }
}?>

Use : <?php mergeXML($xmlElement, simplexml_load_string($toMerge)) ?>
k dot antczak at livedata dot pl 22-Apr-2011 01:08
A quick snippet which converts XML Object into array:

<?php
function xml2array ( $xmlObject, $out = array () )
{
        foreach ( (array) $xmlObject as $index => $node )
            $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

        return $out;
}
?>

Have fun! ;-)
help :-) @ theapotek :-) com 08-Apr-2011 12:54
If you are having trouble accessing CDATA in your simplexml document, you don't need to str_replace/preg_replace the CDATA out before loading it with simplexml.

You can do this instead, and all your CDATA contents will be merged into the element contents as strings.

$xml = simplexml_load_file($xmlfile,
'SimpleXMLElement', LIBXML_NOCDATA);
Andrez zenarter at hotmail dot com 16-Jul-2009 10:56
I just wanna add an additional to
"Append/combine/merge one simplexml to another"
The parent should has attributes too.

<?php

function append_simplexml(&$simplexml_to, &$simplexml_from)
{

static $firstLoop=true;

//Here adding attributes to parent
if( $firstLoop )
            {
                foreach( $simplexml_from->attributes() as $attr_key => $attr_value )
                {
                    $simplexml_to->addAttribute($attr_key, $attr_value);
                }
            }

foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

       $firstLoop=false;

        append_simplexml($simplexml_temp, $simplexml_child);
    }

unset( $firstLoop=false );
}

?>

I have aproblem to assign an object into a variable used as an object later, Then i found the code above, it solve half of my problem. I have it should have the parent name assign too but it didnt. Any better code?
Douglas Marsh 06-Jul-2009 08:53
SimpleXML is really nice for loading/converting XML data into native PHP data structures. I was considering crude searching of SVG for the width/height and since it really is an XML file... I found a SUPER easy method for parsing out the information I wanted:

<?php
// putting incomplete SVG data inline for readability
$RawXML = <<< XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://www.example.com/dc"
   xmlns:cc="http://www.example.com/cc"
   xmlns:rdf="http://www.example.com/rdf"
   xmlns:svg="http://www.example.com/svg"
   xmlns="http://www.example.com/"
   xmlns:sodipodi="http://www.example.com/sodipodi"
   xmlns:inkscape="http://www.example.com/inkscape"
   id="svg2"
   sodipodi:version="0.32"
   inkscape:version="0.46"
   width="586.25"
   height="743.75"
   xml:space="preserve"
   sodipodi:docname="some_svg_file.svg"
   inkscape:output_extension="org.inkscape.output.svg.inkscape">
 <!-- portions removed to keep this short -->
</svg>
XML;

$svg = new SimpleXMLElement($RawXML);

$height = $svg['height'];
$width = $svg['width'];

echo "The width x height is: ${width} x ${height} \n";

?>
info at ajaxforum dot ru 17-Jun-2009 12:32
Append/combine/merge one simplexml to another:

<?php
include 'example.php';
$el1 = new SimpleXMLElement($xmlstr);
$el2 = new SimpleXMLElement($xmlstr);

// wrong way!
// php convert $el2->movie[0] to string silently
$el1->addChild('movie', $el2->movie[0]);

// wrong way!
// php 5.1 convert $el2->movie[0] to string and generate Warning: It is not yet possible to assign complex types to properties. It is not possible to assign complex types to nodes
// php 5.2 convert $el2->movie[0] to string silently
$el1->addChild('movie');
$el1->movie[2] = $el2->movie[0];

// right way!
$el1_movie = $el1->addChild('movie');
append_simplexml($el1_movie, $el2->movie[0]);

echo "<pre>"; print_r($el1); echo "</pre>";

/**
 * Add one simplexml to another
 *
 * @param object $simplexml_to
 * @param object $simplexml_from
 * @author Boris Korobkov
 * @link http://www.ajaxforum.ru/
 */
function append_simplexml(&$simplexml_to, &$simplexml_from)
{
    foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

        append_simplexml($simplexml_temp, $simplexml_child);
    }
}
?>
codejunky32 at NOSPAM dot com 22-May-2009 08:45
Just wanted to add a post as to how you can extract the value from a SimpleXMLElement. Its not as straightforward as you think. Because its a complex object you can't just access the element directly. Here is a sample of data that represents a var_dump of a SimpleXmlElement

array(1) {
  [0]=>
  object(SimpleXMLElement)#13 (2) {
    ["@attributes"]=>
    array(1) {
      ["name"]=>
      string(5) "title"
    }
    [0]=>
    string(19) "PHP Tech Book"
  }
}

If you want to extract the title of the book you have to cast the specified element to a string like so.
$newTitle = (string) $title[0];

The $title variable is the SimpleXMLElement that you have extracted from the xml document using simplexml_load_string for instance.  To initially access the title element from the xml document you can do like so, using xpath.
$title = $doc->xpath('str[@name="title"]');

Hope this helps someone out there.
james dot ellis at gmail dot com 28-Aug-2008 06:55
While SimpleXML is a powerful tool, developers using it to process and handle large XML documents & strings should take into careful consideration its memory usage requirements.
SimpleXML requires the entire XML tree to be available prior to any processing actions on that tree -- this requires the entire tree to be in memory. Ok for a 40kb XML file but when dealing with > 100MB files you will see performance degradation, especially if you have a busy server.

An alternative to processing large XML files is the XMLReader class, which operates in streaming mode, of which an excellent tutorial is presented here:
http://www.ibm.com/developerworks/library/x-pullparsingphp.html

XML is an incredibly verbose format. If you are dealing with large data structures, especially in web services, do you you actually need to represent the data as an XML tree? - other serialisation formats such as JSON, Serialised PHP, Google Protocol Buffers (http://code.google.com/p/protobuf/) and even CSV can remarkably reduce processing time, bandwidth and load  when dealing with large files. A 110MB XML file can become a 65MB CSV file, with the same data in it, simply because the data identifiers (tags) are only represented once in the entire document.
m0sh3 at hotmail dot com 22-May-2008 03:24
Be aware of quirks like this one:

<?php

$a = new SimpleXMLElement('<a><b/></a>');

$a->b = 'test &amp; test';
$a->c = 'test &amp; test';

print_r($a);
/*
OUTPUT:

SimpleXMLElement Object
(
    [b] => test & test
    [c] => test &amp; test
)
*/
nathan at gimpstraw dot com 05-Apr-2008 09:43
I'm using SimpleXML to process data sent back from an API request, and I ran into the CDATA problem and the error you get from html entities, and here is a solution i came up with, don't know if it's the most practical, but it's working.

<?php
$str = <<< XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
    <item>
        <title><![CDATA[Caf&eacute;]]></title>
        <description><![CDATA[Some description.]]></description>
    </item>
</menu>
XML;

$str = preg_replace("/\<\!\[CDATA\[(.*?)\]\]\>/ies", "'[CDATA]'.base64_encode('$1').'[/CDATA]'", $str);
$xml = new SimpleXMLElement($str);

// Return item title's
foreach ($xml->item as $item) {
    $tmp = (string) $item->title;
    $tmp = preg_replace("/\[CDATA\](.*?)\[\/CDATA\]/ies", "base64_decode('$1')", $tmp);
    echo $tmp;
}
?>
ngkongs at gmail dot com 19-Mar-2008 10:44
fix the function i posted before, have a wrong quote placement

function implode2($glue="", $var){
    if ($var){
        foreach ($var as $value){
            $array[]=strval($value);
        }
        return implode($glue, $array);
    }
    else return false;
}
philippe_marc_--a---t--_novartis_com 12-Feb-2008 09:46
TIP: if you run into memory issue using simpleXML.
You may want to use PHP>5.2.5 in order to avoid that: http://bugs.php.net/bug.php?id=38604
If not possible, avoid "foreach ( $xmldata->node as $node )" like calls.
andrvm 02-Jan-2008 03:01
<?php
/**
    * Remove node/nodes xml with xpath
    *
    * @param SimpleXMLElement                 $xml
    * @param string XPath                     $path
    * @param string ('one'|'child'|'all')     $multi
    *
    * Use:
    *
    * Example xml file - http://ru2.php.net/manual/ru/ref.simplexml.php
    *
    * $xml = simplexml_load_file($xmlfile);
    *
    * //1. remove only 1 node (without child nodes)
    * //   $path must return only 1 (unique) node without child nodes
    * removeNode($xml, '//movie/rating[@type="thumbs"]');
    *
    * //2. remove 1 node (with 1 child nodes)
    * //    $path can return any nodes - will be removed only first node
    * //   with all child nodes
    * removeNode($xml, '//characters', 'child')
    *
    * //3. remove all nodes (with child nodes)
    * //   $path can return any nodes - will be removed all
    * //   with child nodes
    * removeNode($xml, '//rating', 'all')
    *
    * $xml->asXML($xmlfile);
    *
    */
   function removeNode($xml, $path, $multi='one')
   {
       $result = $xml->xpath($path);

          # for wrong $path
          if (!isset($result[0])) return false;

          switch ($multi) {
              case 'all':
                    $errlevel = error_reporting(E_ALL & ~E_WARNING);
                    foreach ($result as $r) unset ($r[0]);
                    error_reporting($errlevel);
                    return true;

                case 'child':
                   unset($result[0][0]);
                   return true;

                case 'one':
                   if (count($result[0]->children())==0 && count($result)==1) {
                       unset($result[0][0]);
                       return true;
                   }

                default:
                      return false;
          }
 }
?>

p.s. after use (if deleted all nodes):
<?php

   function trimXml($xmlfile)
   {
       $dom = new DOMDocument();

          $dom->preserveWhiteSpace = false;

         if (!$dom->load($xmlfile)) return false;

         $dom->formatOutput = true;

         if (!$dom->save($xmlfile)) return false;

         return true;
   }
?>
onPHP5.com 17-Nov-2007 04:37
It does not say in the docs, but SimpleXML will convert all text into UTF-8, if the source XML declaration has another encoding. Eg, if the source has the following XML decl:

<?xml version="1.0" encoding="windows-1251" ?>

all the text in the resulting SimpleXMLElement will be in UTF-8 automatically.
lordi at msdi dot ca 23-Oct-2007 05:35
If you need to do math calculations on values extracted from simplexml document, you might need to cast the value as float to prevent precision loss. Here is an example:

<?php
    $objXML = new SimpleXMLElement('<test x="-123.45"></test>');

    //Shows correctly
    echo $objXML['x']."\n";

    //We loose the decimals
    echo $objXML['x'] + $objXML['x']."\n";

    $x = $objXML['x'];

    //This works if we cast the amounts
    echo (float)$objXML['x'] + (float)$objXML['x']."\n";

    //Calculated on a string, no problem
    echo "-123.45" + "-123.45";

?>

This is due to the fact that $objXML['x'] is not a string (php would cast it automatically) neither a float, but a SimpleXMLElement object.

"echo var_dump($x);" will output this
~~
object(SimpleXMLElement)#3 (1) {
  [0]=>
  string(7) "-123.45"
}
~~

I opened a bug request on php but here is the answer they gave me:

~~
Status: Won't fix

The behavior is defined by the engine not the extension. When performing mathematical operations on objects, they are treated as integers. It is up to the user to cast the object to the appropriate type to maintain proper precision.
~~
cmsa at gmx dot de 27-Aug-2007 05:07
I had a problem with entities.

My first solution:
I saved Data that way:
$ENTRY_->
addchild('Nachricht',htmlentities($_POST["blog"]));

Had Entities in the XML-File like:
<!ENTITY auml "&amp;auml">

And I loaded the Data that way:
html_entity_decode($ENTRY->Nachname);

But after saving and
loading the xml-file the entity-entry
<!ENTITY auml "&amp;auml">
disappeared. strange...

My second solution:
With saving the Data this way:
$ENTRY_->
addchild('Nachricht',htmlentities(htmlentities($_POST["blog"])));

I can now load it with html_entity_decode without the
 entity-entry in the XML-file!
I tested it with äöü.

Hope it helpes.
karsten dot bruch at bms-verlage dot de 16-Aug-2007 08:28
When creating a new XML document and adding text with umlauts and such

<?php $SimpleXMLElement->asXML(); ?>

will silently NOT output any content with umlauts.

Use htmlentities () while adding Umlauts & co to solve the "problem"
anthony dot parsons at manx dot net 03-Aug-2007 07:40
If you're handling lots of HTML or mixed-content XML you'll probably want to use the DOM functions instead of SimpleXML. Take this for example:
<?php
$html = new SimpleXMLElement('<div><p>Some text, <a href="#">a link,</a> more text</p></div>');

echo $html->p->a,"<br>\n"; // "a link,"
echo $html->p;             // "Some text, more text" (!)
?>
In the above example reconstructing the original markup is impossible because of the way SimpleXML represents the data.
php at werner dash ott dot de 28-Mar-2007 06:03
Concerning SimpleXML and sessions:

When creating a SimpleXML object (to be precise: a SimpleXMLElement object) in the context of a session and storing it in $_SESSION['XMLobject'], this object does not "survive" the session!

By the time re-entering the session, print_r($_SESSION['XMLobject']) says:

['XMLobject'] => SimpleXMLElement Object
Warning:  Node no longer exists in /your_php_file.php on line xyz
   (
   )

(Message simplified for the sake of better readability.)
codje2 at lboro dot ac dot uk 11-Mar-2007 01:46
Sometimes it's nice to mix up data storage types. This is a very simple SQL to XML converter. Feed it a SQL query and it outputs the result in XML.

The first paramater should be a mysql_query result
(optional)The second is the xml name for each row (i.e the second depth of XML)
(optional)The third is the name of the XML document, the root name

<?php
$result=mysql_query("SELECT * FROM users");
sql_to_xml($result,"users","members");

function sql_to_xml($mysql_result,$row_name="row",$doc_name="root")
{

    $xml= new SimpleXMLElement("<$doc_name></$doc_name>");
    while($line=mysql_fetch_assoc($mysql_result))
    {
        $row=$xml->addChild($row_name);
        foreach($line as $column => $value)
        {
            $row->$column="$value";
        }
    }
    return $xml->asXML();
}

?>
php at NOSPAM dot coutch dot com 21-Feb-2007 02:04
Memory leak when setting attributes as in example (#Example 2134. Setting values)

This probably goes unnoticed in web scripts (unless you do a LOT of xml manipulations), but I ran into this in my standalone script that processes a large number of XML files.

The following code will eat up memory quite fast:

<?php
include 'example.php';

while (true) {
  $xml = new SimpleXMLElement($xmlstr);
  $xml->movie[0]->characters->character[0]->name = 'Miss Coder';
}
?>

while this seems to behave correctly:

<?php
include 'example.php';

while (true) {
  $xml = new SimpleXMLElement($xmlstr);
  $c = $xml->xpath("//character");
  $c[0]->name = 'Miss Coder';
}
?>

This looks like bug #38604, and I just confirmed that in 6.0.0-dev (on Windows at least) it is fixed.  It is NOT fixed in 5.2.1 or  5.2.2-dev (2/21 build), so for 5.2 users, use the second form to avoid leaks.
joel [from the website] purerave.com 19-Feb-2007 05:57
It doesn't mention this anywhere, but creationg a new SimpleXMLElement object from a non-valid string throws an exception. It looks ugly in the php log as it dumps the stack in multiple lines.

The correct way to create a new SimpleXMLElement object is like so:
<?php
$xmlstr = ''; // empty to throw an exception
try {
   $xml = new SimpleXMLElement($xmlstr);
} catch (Exception $e) {
   // handle the error
   echo '$xmlstr is not a valid xml string';
}
?>
matt at mattbostock dot com 05-Nov-2006 11:40
Be careful when using var_export to debug element attributes - it won't work! Always use print() or similar for checking the contents of element attributes.
Arnaud Bienvenu 19-Oct-2006 07:35
As of PHP 5.1.4, trying to iterate on a non-existent node will actually create that node.

<?
$xml = simplexml_load_string('<root></root>');
foreach($xml->b as $dummy);
echo $xml->asXML();
?>

Gives :

<?xml version="1.0"?>
<root><b/></root>

You might think it is a bug, but PHP developers seam to consider it as a feature : http://bugs.php.net/bug.php?id=39164
Jason Sheets <jsheets at shadonet dot com> 31-May-2006 10:31
Here is my Simple XML to array function, it is recursive and has the benefit of maintaining key value relationships and has worked well for me.

<?php
function XMLToArray($xml)
{
  if ($xml instanceof SimpleXMLElement) {
    $children = $xml->children();
    $return = null;
  }

  foreach ($children as $element => $value) {
    if ($value instanceof SimpleXMLElement) {
      $values = (array)$value->children();

      if (count($values) > 0) {
        $return[$element] = XMLToArray($value);
      } else {
        if (!isset($return[$element])) {
          $return[$element] = (string)$value;
        } else {
          if (!is_array($return[$element])) {
            $return[$element] = array($return[$element], (string)$value);
          } else {
            $return[$element][] = (string)$value;
          }
        }
      }
    }
  }

  if (is_array($return)) {
    return $return;
  } else {
    return $false;
  }
}
?>
daniel dot oconnor at gmail dot com 17-May-2006 06:21
SimpleXML handles namespaces, but it's not documented very well here at all.

If you wanted to parse, say, an open office manifest file or a piece of RDF/XML, you have to get elements and attributes by the namespace url.

Example:
<?php
function display($in) {
    if (file_exists($in)) {
        $xml = simplexml_load_file($in);
    } else {
        throw new Exception($in . " does not exist");
    }

    $manifest = $xml->children('http://openoffice.org/2001/manifest');

    foreach ($manifest->xpath('//manifest:file-entry') as $file) {
        foreach ($file->attributes('http://openoffice.org/2001/manifest') as $key => $value) {
            print "Key:" . $key . "\n";
            print "Value:" . $value . "\n";
        }
    }

}
?>

File: manifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
 <manifest:file-entry manifest:media-type="application/vnd.sun.xml.writer" manifest:full-path="/"/>
 <manifest:file-entry manifest:media-type="application/vnd.sun.xml.ui.configuration" manifest:full-path="Configurations2/"/>
 <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="layout-cache"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/thumbnail.png"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
</manifest:manifest>
paul at preinheimer dot com 06-May-2005 05:11
Hi,

If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently.

You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result.
eg.

<?php
$xml->xpath('/data/time-layout/start-valid-time');
?>

You can also choose just to encapsulate the element names containing a dash:
<?php $xml->data->{'time-layout'}->{'start-valid-time'} ?>

--

On a only partially related note, dealing with SimpleXML is one of the only times I have employed casting with PHP. While iterating (foreach) through the valid times, echo'ing the element worked great (it merely echo'ed the apropriate time), assigning it to another variable resulted in a SimpleXML object containing the time to be assigned, rather than just the time itself. This was resolved by casting the time to a string:

<?php
foreach($xml->data->{'time-layout'}->{'start-valid-time'} AS $time)
{
 $weatherDates[] = (string) $time;
}
?>
T CHASSAGNETTE t_chassagnette at yahoo dot fr 04-May-2005 01:57
Another method to parse an XML Document into a PHP array with SIMPLEXML inspired from Daniel FAIVRE !

<?php
function xml2php($xml)
{
    $fils = 0;
    $tab = false;
    $array = array();
    foreach($xml->children() as $key => $value)
    {
        $child = xml2php($value);

        //To deal with the attributes
        foreach($node->attributes() as $ak=>$av)
        {
            $child[$ak] = (string)$av;

        }

        //Let see if the new child is not in the array
        if($tab==false && in_array($key,array_keys($array)))
        {
            //If this element is already in the array we will create an indexed array
            $tmp = $array[$key];
            $array[$key] = NULL;
            $array[$key][] = $tmp;
            $array[$key][] = $child;
            $tab = true;
        }
        elseif($tab == true)
        {
            //Add an element in an existing array
            $array[$key][] = $child;
        }
        else
        {
            //Add a simple element
            $array[$key] = $child;
        }

        $fils++;
      }

    if($fils==0)
    {
        return (string)$xml;
    }

    return $array;

}
?>
nelson_menezes at yahoo dot co dot uk 01-Mar-2005 05:05
Note that SimpleXML expects to both read and output XML in UTF-8 encoding. You'll need to add a line such as this at the top of your input XML file if it isn't saved in UTF-8 (adjust to whatever encoding used):

<?xml version="1.0" encoding="ISO-8859-1" ?>

On the output side of things, if you're not serving/handling UTF-8, you'll need to use utf8_decode() [red. but that will only work for ISO-8859-1, not other encodings]. Common mistake: http://bugs.php.net/bug.php?id=28154
brcavanagh AT NO SPAM hotmail.com 02-Jan-2005 09:18
If you are looking to use SimpleXML for anything but reading XML documents, you should really reconsider, and use the XML DOM library.  By the time you get enough utilities implemented in DOM to handle all the set backs in SimpleXML, you will have defeated the purpose of using SimpleXML.  There are a few reasons for this, and there are already many workrounds, but the primairy issues are this

1) No complex node assignment.  You cannot switch nodes or replace them.

2) No appending new child nodes

3) Whenever you do something like $new_node = $xml_doc->node you will always get a reference even if you use a clone method, which will crash the script.

Other than that, its a great tool for reading docs.
SimpleXMLIterator::valid
simplexml_import_dom
SimpleXML
PHP Manual


Получает объект класса SimpleXMLElement из узла DOM.

SimpleXML
simplexml_load_file
SimpleXML
PHP Manual

simplexml_import_dom

(PHP 5)

simplexml_import_dom — Получает объект класса SimpleXMLElement из узла DOM.

Описание

SimpleXMLElement simplexml_import_dom ( DOMNode $node [, string $class_name = "SimpleXMLElement" ] )

Эта функция берет узел документа DOM и превращает его в узел SimpleXML. Затем этот новый объект может быть использован как первичный элемент SimpleXML.

Список параметров

node

Узел-элемент DOM

class_name

Вы можете использовать этот дополнительный параметр для того, чтобы функция simplexml_import_dom() возвращала объект указанного класса. Этот класс должен расширять класс SimpleXMLElement.

Возвращаемые значения

Возвращает SimpleXMLElement или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Импорт DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>чепуха</title></book></books>');
if (!$dom) {
    echo 'Ошибка при разборе документа';
    exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

Результат выполнения данного примера:

чепуха

Смотрите также

  • dom_import_simplexml() - Получает объект класса DOMElement из объекта класса SimpleXMLElement
  • Базовое использование SimpleXML

User Contributed Notes

peter-SPAMrubbish-ATveridon.com 05-Mar-2008 11:06
Something that surprised me, any changes made to the SimpleXML object obtained from the imported DOMDocument also change the original DOMDocument.

e.g.

<?php

$string = '<root><foo>abc</foo></root>';
$domxml = DOMDocument::loadXML($string);
$simplexml = simplexml_import_dom($domxml);
$simplexml->foo = "xyz";
$simplexml->bar = "123";
echo $domxml->saveXML();

?>
Outputs:

--START--
<?xml version="1.0"?>
<root><foo>xyz</foo><bar>123</bar></root>
spam AT media MINUS soma DOT de 26-Jul-2006 09:27
Please note that a valid SimpleXMLElement is typecasted to false.

<?php

    $string = '<root><foo>abc</foo></root>';
    $xml = DOMDocument::loadXML($string);
    $xml = simplexml_import_dom($xml);
    echo 'simplexml_import_dom';
    var_dump($xml);
    var_dump((bool)$xml);

    $xml = simplexml_load_string('<root><foo>abc</foo></root>');
    echo 'simplexml_load_string';
    var_dump($xml);
    var_dump((bool)$xml);

    $xml = simplexml_load_file('test.xml');
    echo 'simplexml_load_file';
    var_dump($xml);
    var_dump((bool)$xml);

?>

Outputs:

--START--
simplexml_import_dom

object(SimpleXMLElement)[2]
  public 'foo' => 'abc'

false

simplexml_load_string

object(SimpleXMLElement)[1]
  public 'foo' => 'abc'

false

simplexml_load_file

object(SimpleXMLElement)[2]
  public 'foo' => 'abc'

false
--END--
SimpleXML
simplexml_load_file
SimpleXML


Интерпретирует XML-файл в объект

simplexml_import_dom
simplexml_load_string
SimpleXML
PHP Manual

simplexml_load_file

(PHP 5)

simplexml_load_file — Интерпретирует XML-файл в объект

Описание

SimpleXMLElement simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

Преобразует правильно сформированный XML-документ в указанном файле в объект.

Список параметров

filename

Путь к XML-файлу

Замечание:

Libxml 2 декодирует URI, так что если вы хотите передать, например, b&c как параметр URI a, вы должны вызвать simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Начиная с PHP 5.1.0 этого не требуется, потому, что PHP сделает это за вас.

class_name

Вы можете использовать этот необязательный параметр для того, чтобы функция simplexml_load_file() возвращала объект указанного класса. Этот класс должен расширять класс SimpleXMLElement.

options

Начиная с PHP 5.1.0 и Libxml 2.6.0, вы также можете использовать параметр options чтобы указать дополнительные параметры Libxml.

ns

Префикс пространства имен или URI.

is_prefix

TRUE если ns является префиксом, и FALSE если URI; по умолчанию равен FALSE.

Возвращаемые значения

Возвращает объект (object) класса SimpleXMLElement со свойствами, содержащими данные, которые хранятся внутри XML-документа или FALSE в случае возникновения ошибки.

Ошибки

Генерирует сообщение об ошибке уровня E_WARNING для каждой ошибки, найденной в XML-данных.

Подсказка

Используйте функцию libxml_use_internal_errors() для того, чтобы подавить все ошибки XML, и функцию libxml_get_errors() для прохода по ним впоследствии.

Примеры

Пример #1 Интерпретация XML-документа

<?php
//Файл test.xml содержит XML-документ с корневым элементом
//и, по крайней мере, элемент /[root]/title.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');

    print_r($xml);
} else {
    exit('Не удалось открыть файл test.xml.');
}
?>

Этот скрипт выведет, в случае успешного завершения, следующее:

SimpleXMLElement Object
(
  [title] => Пример заголовка
  ...
)

Здесь вы можете использовать $xml->body и любые другие элементы.

Смотрите также

  • simplexml_load_string() - Интерпретирует строку с XML в объект
  • SimpleXMLElement::__construct() - Создание нового SimpleXMLElement объекта
  • Работа с ошибками XML
  • libxml_use_internal_errors() - Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю
  • Базовое использование SimpleXML

User Contributed Notes

fusionstream at gmail dot com 05-Apr-2012 04:15
If you are loading many files, this may slow down your page load time.

To set a timeout, use file_get_context and then simplexml_load_string

<?php

$fp = fopen('http://www.example.com/rss', false, stream_create_context(array('http' => array('timeout', '1.5'))));

if ($fp) {
    print_r( simplexml_load_string($fp) );
} else {
    echo "The request timed out";
}
?>
sean at aliencreations dot com 17-Mar-2011 10:59
If you find that you are receiving 500 errors with simplexml_load_file() but you can access the xml/rss feed manually through a browser, your script is probably being blocked by a user agent sniffer.

Add this code before your xml call to remedy this issue

<?php

ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ini_set("max_execution_time", 0);
ini_set("memory_limit", "10000M");

$rss = simplexml_load_file($feed_url);

?>
Nanuit at ossi dot at 08-Feb-2011 01:51
A little function very helpfull in using simplexml_load_file behind a proxy

<?php
function getXMLfromURL($url) {
      $Proxy = getenv("HTTP_PROXY");

      if (strlen($Proxy) > 1) {
        $r_default_context = stream_context_get_default ( array
                    ('http' => array(
                        'proxy' => $Proxy,
                        'request_fulluri' => True,
                    ),
                )
            );
        libxml_set_streams_context($r_default_context);
      }
      $daten = simplexml_load_file($url);
      return ($daten);
    }
?>

where HTTP_PROXY is set to e.g.: tcp://proxy:8080
guego dot ol at ig dot com dot br 12-Nov-2010 03:26
Analyze fully XML.

<?php
$xml = simplexml_load_file('file.xml');

foreach($xml as $key0 => $value){
echo "..1..[$key0] => $value";
foreach($value->attributes() as $attributeskey0 => $attributesvalue1){
echo "________[$attributeskey0] = $attributesvalue1";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value as $key => $value2){
echo "....2.....[$key] => $value2";
foreach($value2->attributes() as $attributeskey => $attributesvalue2){
echo "________[$attributeskey] = $attributesvalue2";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value2 as $key2 => $value3){
echo ".........3..........[$key2] => $value3";
foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){
echo "________[$attributeskey2] = $attributesvalue3";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value3 as $key3 => $value4){
echo "...................4....................[$key3] => $value4";
foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){
echo "________[$attributeskey3] = $attributesvalue4";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value4 as $key4 => $value5){
echo ".....................5......................[$key4] => $value5";
foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){
echo "________[$attributeskey4] = $attributesvalue5";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value5 as $key5 => $value6){
echo "......................6.......................[$key5] => $value6";
foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){
echo "________[$attributeskey5] = $attributesvalue6";
}
echo '<br />';
}}}}}
echo '<br />';
}
?>
raduispas at gmail dot com 21-Oct-2010 06:12
if you want to check when this function fails,make sure to compare the return value with ===  instead of == :

<?php
$url = 'http://www.example.com';
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
if($xml ===  FALSE)
{
   //deal with error
}
else { //do stuff }
?>

Otherwise you may end up with FALSE all the time even if the document is ok. Hope this helps someone ;)
jamie at splooshmedia dot co dot uk 31-Mar-2010 06:17
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

<?php
function loadXML2($domain, $path, $timeout = 30) {

    /*
        Usage:

        $xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
        if($xml) {
            // xml doc loaded
        } else {
            // failed. show friendly error message.
        }
    */

    $fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
    if($fp) {
        // make request
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $domain\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);

        // get response
        $resp = "";
        while (!feof($fp)) {
            $resp .= fgets($fp, 128);
        }
        fclose($fp);
        // check status is 200
        $status_regex = "/HTTP\/1\.\d\s(\d+)/";
        if(preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {
            // load xml as object
            $parts = explode("\r\n\r\n", $resp);
            return simplexml_load_string($parts[1]);
        }
    }
    return false;

}
?>
Smokey 14-Mar-2010 10:16
for nested and same name values i'v made up this little bit for getting and displaying multiable values from google's geocode when a exact match is not found it returns all close matches in the following format(this is an abriged version of there output)

<Response>
  <Placemark id="1">
    <address> New York 24, NY, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.5850086,40.7207442,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="2">
    <address>New York 27, NY, USA</address>
    <AddressDetails>
      ...................
    </AddressDetails>
    <Point>
      <coordinates>-72.8987835,40.8003588,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="3">
    <address>Cedar Place School, 20 Cedar Pl, Yonkers, NY 10705, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.8966320,40.9256520,0</coordinates>
    </Point>
  </Placemark>
</Response>

<?php
// get and breakdown the results then store them in $var's
$Address = "99999 parkplace, new york, NY";
$urladdress = urlencode($Address);
$Base_url = "http://maps.google.com/maps/geo?q=";
$urlParts = "&output=xml";
$urlrequest = $Base_url . $urladdress . $urlParts;
$xml = simplexml_load_file($urlrequest);
$num = "0";
foreach ($xml->Response->Placemark as $value){
    $num++;
    $GeoFindAdd{$num} = $value->address;
    $GeoFindCords{$num} = $value->Point->coordinates;
}

// a simple display for the results
echo "Found ",$num," Possable Geo Data Sets <br>";
$CountNumResults = "0";
for ( ; $num > 0; $num--){
    $CountNumResults++;
    echo $countnum,"<br> Address = ",$GeoFindAdd{$num},"<br> Coordinates = ",$GeoFindCords{$num},"<br>";
}
echo "END";
?>
knl at bitflop dot com 11-Sep-2009 12:02
If you need to parse the data from SimpleXML into a session variable remember to define the data as a string first.

If you don't you will get warnings of "Node no longer exists" pointing to your session_start() function.

This will work:

<?php

    $new_version = simplexml_load_file('http://example.com/version.xml');
    $_SESSION['current_version'] = (string)$new_version->version;

?>
neil art neilanddeb dort com 17-Aug-2009 06:00
Because the encoding of my XML file is UTF-8 and the
encoding of my web page is iso-8859-1 I was getting strange characters such as â€™ instead of a right single quote.

The solution to this turned out to be hard to find, but really easy to implement.

http://uk3.php.net/manual/en/function.iconv.php

Using the iconv() function you can convert from one encodign to another, the TRANSLIT option seems to work best for what I needed.  Here's my example:

<?php
// convert string from utf-8 to iso8859-1
$horoscope = iconv( "UTF-8", "ISO-8859-1//TRANSLIT", $horoscope );
?>

I found the solution on this page...
http://tinyurl.com/lm39xc
Hope this helps
christoph dot burgdorfer at gmail dot com 31-Jan-2009 12:30
This function gets RSS Items of a Wordpress blog from a search and fills the respective elements  into an array:

<?php

function get_rss_items($searchkeywords) {
    // define url
    $url = "http://some.wordpress.blog.com/feed/?s=" . urlencode($searchkeywords) . "&submit=";

    // retrieve search results
    if($xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA)) {
        $result["title"]   = $xml->xpath("/rss/channel/item/title");
        $result["link"]    = $xml->xpath("/rss/channel/item/link");
        $result["content"] = $xml->xpath("/rss/channel/item/content:encoded/text()");

        foreach($result as $key => $attribute) {
            $i=0;
            foreach($attribute as $element) {
                $ret[$i][$key] = (string)$element;
                $i++;
            }
        }
        return $ret;
    } else
        return false;
}

?>
cryonyx at cerebrate dot ru 21-Oct-2008 03:34
In case you have a XML file with a series of equally named elements on one level simplexml incorrectly processes them and doesn't allow to walk through the array using foreach(). As far as I'm concerned, it is the problem caused by PHP xml_parser (see: http://ru2.php.net/manual/ru/function.xml-parser-create.php#53188).

To avoid this, just use count() and walk through the array using for().

Example:

<params>
  <param>
    <name>version.shell</name>
    <value>1.0</value>
  </param>
  <param>
      <name>version.core</name>
      <value>1.0</value>
  </param>
  <param>
      <name>file.lang</name>
      <value>vc.lang</value>
  </param>
  ...
</params>

<?php
$filename = '...';
$xml = simplexml_load_file($filename);
$p_cnt = count($xml->param);
for($i = 0; $i < $p_cnt; $i++) {
  $param = $xml->param[$i];
  ...;
}
?>
mario 02-Sep-2008 02:08
If you want CDATA in your object you should use LIBXML_NOCDATA

<?php
$xml = simplexml_load_file($file_xml, 'SimpleXMLElement',LIBXML_NOCDATA);

    print_r($xml);
?>
clarke DOT chris at googley mail DOT com 25-Jul-2008 08:33
For clarification, finding attributes seems easier this way, hope I'm not being redundant.

Source XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body type="small" important="low">Don't forget me this weekend!</body>
</note>

Code Example:
<?php
$xml = simplexml_load_file("test.xml");
print $xml->body['type'];
?>

Output:
small
pc_storm at abv dot bg 20-May-2008 05:16
You can avoid easily, the unpredictable destruction of $_SESSION when loading a simple_xml object (which occurs under _some_ PHP versions) by serializing and unserializing it:

<?php
$oldsession=serialize($_SESSION);
$myxml=@simplexml_load_file('my.xml');
$_SESSION=unserialize($oldsession);
unset ($oldsession);
?>

This worked for me under PHP 5.2.5 while on 5.1.6 there was no need for such workaround at all.

Same workaround should help if there are other superglobals affected by this bug...
l [DOT] anzinger [AT] gmail [DOT] com 26-Mar-2008 09:03
If you don't want that the CDATA values get escaped, just load the XML with LIBXML_NOCDATA as an 3rd argument.

Note: A PHP version >= 5.1.0 is required for this to work.

Example:

<?php simplexml_load_file('xmldatei.xml', null, LIBXML_NOCDATA); ?>
php at werner dash ott dot de 29-Mar-2007 01:13
Making SimpleXMLElement objects session save.

Besides the effect of not surviving sessions, the SimpleXMLElement object may even crash the session_start() function when trying to re-enter the session!

To come up with a solution for this, I used a pattern as follows. The core idea is to transform the SimpleXMLElement between session calls to and from a string representation which of course is session save.

<?php
  //
  // session save handling of SimpleXMLElement objects
  // (applies to/ tested with PHP 5.1.5 and PHP 5.2.1)
  // The myClass pattern allows for conveniently accessing
  // XML structures while being session save
  //
  class myClass
  {
    private $o_XMLconfig = null;
    private $s_XMLconfig = '';

    public function __construct($args_configfile)
    {
      $this->o_XMLconfig = simplexml_load_file($args_configfile);
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
    } // __construct()

    public function __destruct()
    {
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
      unset($this->o_XMLconfig); // this object would otherwise crash
                                 // the subsequent call of
                                 // session_start()!
    } // __destruct()

    public function __wakeup()
    {
      $this->o_XMLconfig = simplexml_load_string($this->s_XMLconfig);
    } // __wakeup()

  } // class myClass
?>
wouter at code-b dot nl 20-Feb-2007 02:08
To correctly extract a value from a CDATA just make sure you cast the SimpleXML Element to a string value by using the cast operator:

<?php
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<rss>
    <channel>
        <item>
            <title><![CDATA[Tom & Jerry]]></title>
        </item>
    </channel>
</rss>';

$xml = simplexml_load_string($xml);

// echo does the casting for you
echo $xml->channel->item->title;

// but vardump (or print_r) not!
var_dump($xml->channel->item->title);

// so cast the SimpleXML Element to 'string' solve this issue
var_dump((string) $xml->channel->item->title);
?>

Above will output:

Tom & Jerry

object(SimpleXMLElement)#4 (0) {}

string(11) "Tom & Jerry"
Kyle 10-Dec-2006 02:35
In regards to Anonymous on 7th April 2006

There is a way to get back HTML tags. For example:

<?xml version="1.0"?>
<intro>
    Welcome to <b>Example.com</b>!
</intro>

<?php
// I use @ so that it doesn't spit out content of my XML in an error message if the load fails. The content could be passwords so this is just to be safe.
$xml = @simplexml_load_file('content_intro.xml');
if ($xml) {
    // asXML() will keep the HTML tags but it will also keep the parent tag <intro> so I strip them out with a str_replace. You could obviously also use a preg_replace if you have lots of tags.
    $intro = str_replace(array('<intro>', '</intro>'), '', $xml->asXML());
} else {
    $error = "Could not load intro XML file.";
}
?>

With this method someone can change the intro in content_intro.xml and ensure that the HTML is well formed and not ruin the whole site design.
Anonymous 06-Apr-2006 09:21
What has been found when using the script is that simplexml_load_file() will remove any HTML formating inside the XML file, and will also only load so many layers deep. If your XML file is to deap, it will return a boolean false.
fdouteaud at gmail dot com 09-Mar-2006 05:21
Be careful if you are using simplexml data directly to feed your MySQL database using MYSQLi and bind parameters.

The data coming from simplexml are Objects and the bind parameters functions of MySQLi do NOT like that! (it causes some memory leak and can crash Apache/PHP)

In order to do this properly you MUST cast your values to the right type (string, integer...) before passing them to the binding methods of MySQLi.
I did not find that in the documentation and it caused me a lot of headache.
info at evasion dot cc 06-Feb-2006 08:26
Sorry there's a mistake in the previous function :
<?php
   function &getXMLnode($object, $param) {
       foreach($object as $key => $value) {
           if(isset($object->$key->$param)) {
               return $object->$key->$param;
           }
           if(is_object($object->$key)&&!empty($object->$key)) {
               $new_obj = $object->$key;
               // Must use getXMLnode function there (recursive)
               $ret = getXMLnode($new_obj, $param);

           }
       }
       if($ret) return (string) $ret;
       return false;
   }
?>
skutter at imprecision dot net 03-Feb-2006 09:11
So it seems SimpleXML doesn't support CDATA... I bashed together this little regex function to sort out the CDATA before trying to parse XML with the likes of simplexml_load_file / simplexml_load_string. Hope it might help somebody and would be very interested to hear of better solutions. (Other than *not* using SimpleXML of course! ;)

It looks for any <![CDATA [Text and HTML etc in here]]> elements, htmlspecialchar()'s the encapsulated data and then strips the "<![CDATA [" and "]]>" tags out.

<?php
function simplexml_unCDATAise($xml) {
    $new_xml = NULL;
    preg_match_all("/\<\!\[CDATA \[(.*)\]\]\>/U", $xml, $args);

    if (is_array($args)) {
        if (isset($args[0]) && isset($args[1])) {
            $new_xml = $xml;
            for ($i=0; $i<count($args[0]); $i++) {
                $old_text = $args[0][$i];
                $new_text = htmlspecialchars($args[1][$i]);
                $new_xml = str_replace($old_text, $new_text, $new_xml);
            }
        }
    }

    return $new_xml;
}

//Usage:
$xml = 'Your XML with CDATA...';
$xml = simplexml_unCDATAise($xml);
$xml_object = simplexml_load_string($xml);
?>
info at evasion dot cc 03-Feb-2006 03:37
Suppose you have loaded a XML file into $simpleXML_obj.
The structure is like below :

SimpleXMLElement Object
(

    [node1] => SimpleXMLElement Object
        (
            [subnode1] => value1
            [subnode2] => value2
            [subnode3] => value3
        )

    [node2] => SimpleXMLElement Object
        (
            [subnode4] => value4
            [subnode5] => value5
            [subnode6] => value6
        )

)

When searching a specific node in the object, you may use this function :

<?php

    function &getXMLnode($object, $param) {
        foreach($object as $key => $value) {
            if(isset($object->$key->$param)) {
                return $object->$key->$param;
            }
            if(is_object($object->$key)&&!empty($object->$key)) {
                $new_obj = $object->$key;
                $ret = getCfgParam($new_obj, $param);
            }
        }
        if($ret) return (string) $ret;
        return false;
    }
?>

So if you want to get subnode4 value you may use this function like this :

<?php
$result = getXMLnode($simpleXML_obj, 'subnode4');
echo $result;
?>

It display "value4"
patrick at procurios dot nl 12-Jan-2006 06:46
simplexml_load_file creates an xml-tree with values that are UTF-8 strings. To convert them to the more common encoding
ISO-8859-1 (Latin-1), use "utf8_decode".
genialbrainmachine at NOSPAM dot tiscali dot it 30-Sep-2005 08:52
Micro$oft Word uses non-standard characters and they create problems in using simplexml_load_file.
Many systems include non-standard Word character in their implementation of ISO-8859-1. So an XML document containing that characters can appear well-formed (i.e.) to many browsers. But if you try to load this kind of documents with simplexml_load_file you'll have a little bunch of troubles..
I believe that this is exactly the same question discussed in htmlentites. Following notes to htmlentitles are interesting here too (given in the reverse order, to grant the history):
http://it.php.net/manual/en/function.htmlentities.php#26379
http://it.php.net/manual/en/function.htmlentities.php#41152
http://it.php.net/manual/en/function.htmlentities.php#42126
http://it.php.net/manual/en/function.htmlentities.php#42511
mark 12-Sep-2005 11:06
If the property of an object is empty the array is not created. Here is a version object2array that transfers properly.

<?php
function object2array($object)
{
    $return = NULL;

    if(is_array($object))
    {
        foreach($object as $key => $value)
            $return[$key] = object2array($value);
    }
    else
    {
        $var = get_object_vars($object);

        if($var)
        {
            foreach($var as $key => $value)
                $return[$key] = ($key && !$value) ? NULL : object2array($value);
        }
        else return $object;
    }

    return $return;
}
?>
simplexml_import_dom
simplexml_load_string
SimpleXML


Интерпретирует строку с XML в объект

simplexml_load_file
WDDX
SimpleXML
PHP Manual

simplexml_load_string

(PHP 5)

simplexml_load_string — Интерпретирует строку с XML в объект

Описание

SimpleXMLElement simplexml_load_string ( string $data [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

Получает правильно сформированную XML-строку и возвращает ее как объект.

Список параметров

data

Правильно сформированная XML-строка

class_name

Вы можете использовать этот необязательный параметр для того, чтобы функция simplexml_load_string() возвращала объект указанного класса. Этот класс должен расширять класс SimpleXMLElement.

options

Начиная с PHP 5.1.0 и Libxml 2.6.0, вы также можете использовать параметр options чтобы указать дополнительные параметры Libxml.

ns

Префикс пространства имен или URI.

is_prefix

TRUE если ns является префиксом, и FALSE если URI; по умолчанию равен FALSE.

Возвращаемые значения

Возвращает объект (object) класса SimpleXMLElement со свойствами, содержащими данные, которые хранятся внутри XML-документа или FALSE в случае возникновения ошибки.

Ошибки

Генерирует сообщение об ошибке уровня E_WARNING для каждой ошибки, найденной в XML-данных.

Подсказка

Используйте функцию libxml_use_internal_errors() для того, чтобы подавить все ошибки XML, и функцию libxml_get_errors() для прохода по ним впоследствии.

Примеры

Пример #1 Интерпретация XML-строки

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
 <title>Что 40?</title>
 <from>Джо</from>
 <to>Джейн</to>
 <body>
  Я знаю, что это - ответ. В чем заключается вопрос?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

Результат выполнения данного примера:

SimpleXMLElement Object
(
  [title] => Что 40?
  [from] => Джо
  [to] => Джейн
  [body] =>
   Я знаю, что это - ответ. В чем заключается вопрос?
)

Здесь вы можете использовать $xml->body и проч.

Смотрите также

  • simplexml_load_file() - Интерпретирует XML-файл в объект
  • SimpleXMLElement::__construct() - Создание нового SimpleXMLElement объекта
  • Работа с ошибками XML
  • libxml_use_internal_errors() - Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю
  • Базовое использование SimpleXML

User Contributed Notes

Anonymous 29-Feb-2012 08:54
Use libxml_disable_entity_loader() to restrict loading of external files.  See http://www.idontplaydarts.com/2011/02/scanning-the-internal-network-using-simplexml/
chris at willowsconsulting dot ie 15-Nov-2011 04:20
There is NO NEED to convert to an array, an Object is more powerful than an array...

To access the data, simply do (using the example set above):

<?php

echo $xml->title;
echo $xml->from;
// etc to access the relevant data~~

?>
lb at bostontech dot net 07-Nov-2011 10:40
please note that:

<?
$data_array = (array) simplexml_load_string($xml_string);
?>

will only convert the root element to an array, where as the child elements remain XML objects.

To prove this, try returning a value N objects deep by association.  Then try the same exercise using something like the object2array example below. (Which works great).
tomas at rds dot lt 13-Sep-2011 08:57
The most simple way to get assoc array from xml string:
<?
$data_array = (array) simplexml_load_string($xml_string);
?>
Diego Araos, diego at klapmedia dot com 05-Feb-2011 12:57
A simpler way to transform the result into an array (requires json module).

<?php
function object2array($object) { return @json_decode(@json_encode($object),1); }
?>

Example:
<?php
$xml_object=simplexml_load_string('<SOME XML DATA');
$xml_array=object2array($xml_object);
?>
ascammon at hotmail dot com 28-Dec-2010 01:04
I had a hard time finding this documented, so posting it here in case it helps someone:

If you want to use multiple libxml options, separate them with a pipe, like so:

<?php
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
?>
thejhereg at gmail dot com 30-Aug-2010 11:24
"simplexml_load_string() : Entity: line #: parser error : Comment not terminated"

On the off chance you see this error and you're pulling your hair out over it, simplexml can't seem to correctly parse XML comment tags if the comment contains "--".

Is silly and likely won't happen very often -- but sometimes it does. ;-)
jeff at creabilis dot com 17-Nov-2009 02:28
If you want to set the charset of the outputed xml, simply set the encoding attribute like this :

<?php simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><xml/>'); ?>

The generated xml outputed by $xml->asXML will containt accentuated characters like 'é' instead of &#xE9;.

Hope this help
spcmky at gmail dot com 13-Oct-2009 01:50
Most of the xml 2 array functions listed here fail when they encounter the following xml:

<something code="231" type="open">Value</something>

The attributes get dropped.
Bob 17-Jun-2009 02:16
Here is my simple SimpleXML wrapper function.
As far as I can tell, it does the same as Julio Cesar Oliveira's (above).
It parses an XML string into a multi-dimensional associative array.
The second argument is a callback that is run on all data (so for example, if you want all data trimmed, like Julio does in his function, just pass 'trim' as the second arg).
<?php
function unserialize_xml($input, $callback = null, $recurse = false)
/* bool/array unserialize_xml ( string $input [ , callback $callback ] )
 * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
 * Returns false on all failure
 * Notes:
    * Root XML tags are stripped
    * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
    * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
 */
{
    // Get input, loading an xml string with simplexml if its the top level of recursion
    $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
    // Convert SimpleXMLElements to array
    if ($data instanceof SimpleXMLElement) $data = (array) $data;
    // Recurse into arrays
    if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
    // Run callback and return
    return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
?>
tiznull 06-Apr-2009 10:16
SimpleXMLElement - Warning: unserialize() [function.unserialize]: Node no longer exists in … .php

If you get this error from storing serialized SimpleXMLElement data then this is your fix…

<?php

function sxml_unserialze($str) {
return unserialize(str_replace(array('O:16:"SimpleXMLElement":0:{}', 'O:16:"SimpleXMLElement":'), array('s:0:"";', 'O:8:"stdClass":'), $str));
}

?>
Julio Cesar Oliveira 30-Mar-2009 07:14
The XML2Array func now Recursive!

<?php
function XML2Array ( $xml , $recursive = false )
{
    if ( ! $recursive )
    {
        $array = simplexml_load_string ( $xml ) ;
    }
    else
    {
        $array = $xml ;
    }

    $newArray = array () ;
    $array = ( array ) $array ;
    foreach ( $array as $key => $value )
    {
        $value = ( array ) $value ;
        if ( isset ( $value [ 0 ] ) )
        {
            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
        }
        else
        {
            $newArray [ $key ] = XML2Array ( $value , true ) ;
        }
    }
    return $newArray ;
}
?>
Julio Cesar Oliveira 26-Mar-2009 08:57
<?php
function XML2Array ( $xml )
{
    $array = simplexml_load_string ( $xml );
    $newArray = array ( ) ;
    $array = ( array ) $array ;
    foreach ( $array as $key => $value )
    {
        $value = ( array ) $value ;
        $newArray [ $key] = $value [ 0 ] ;
    }
    $newArray = array_map("trim", $newArray);
  return $newArray ;
}
?>
supzero at phparts dot net 07-Mar-2009 10:04
if we don't know children number. How many loop. How many key.

<?php
class XML {
    protected $pointer;
    public    $degerler=array();

    function loadString($string){
        $this->pointer = simplexml_load_string($string);
                return $this->pointer;
    }

    function loadFile($file){
        $this->pointer = simplexml_load_file($file);
        return $this->pointer;
    }

    function getname(){
        return $this->pointer->getName();
    }
    function child(){
        return $this->pointer->children();
    }
    function att(){
        return $this->pointer->attributes();
    }
    function toArray(){
        foreach ($this->child() as $sq){
            $this->degerler[$this->getname()][$sq->getname()][][] = $sq; // How many key
        }
        return;
    }

}
?>
Mark Omohundro, ajamyajax.com 04-Nov-2008 10:33
How about a recursive function to reduce the xml hard-coding in your apps?  Here is my simple listing routine as an example:

<?php
function list_xml($str) {
  $root = simplexml_load_string($str);
  list_node($root);
}

function list_node($node) {
  foreach ($node as $element) {
    echo $element. "\n";
    if ($element->children()) {
      echo "<br/>";
      list_node($element);
    }
  }
}
?>
javalc6 at gmail dot com 18-Oct-2008 06:25
I wanted to convert an array containing strings and other arrays of the same type into a simplexml object.

Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks.

<?php
function array2xml($array, $tag) {

    function ia2xml($array) {
        $xml="";
        foreach ($array as $key=>$value) {
            if (is_array($value)) {
                $xml.="<$key>".ia2xml($value)."</$key>";
            } else {
                $xml.="<$key>".$value."</$key>";
            }
        }
        return $xml;
    }

    return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}

$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

echo array2xml($test,"meal")->asXML();
?>
rowan dot collins at gmail dot com 10-Jul-2008 07:07
There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine under PHP 5.2.6

The key is noted above example #6 here:
http://uk2.php.net/manual/en/simplexml.examples.php

"To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object."

If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the string content of the element. So some functions, including print_r(), might not show what you expect. But if you explicitly cast to a string, you get the whole content.

<?php
$xml = simplexml_load_string('<foo>Text1 &amp; XML entities</foo>');
print_r($xml);
/*
SimpleXMLElement Object
(
    [0] => Text1 & XML entities
)
*/

$xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw data]]></foo>');
print_r($xml2);
/*
SimpleXMLElement Object
(
)
*/
// Where's my CDATA?

// Let's try explicit casts
print_r( (string)$xml );
print_r( (string)$xml2 );
/*
Text1 & XML entities
Text2 & raw data
*/
// Much better
?>
SmartD 11-Jun-2008 08:40
A small 'n nice function to extract an XML and return it as an array. If there is a bug, please let me know here. I testet it for my purposes and it works.

<?php

public function extractXML($xml) {

if (!($xml->children())) {
    return (string) $xml;
}

foreach ($xml->children() as $child) {
    $name=$child->getName();
    if (count($xml->$name)==1) {
        $element[$name] = $this->extractXML($child);
    } else {
        $element[][$name] = $this->extractXML($child);
    }
}

return $element;
}

// you can call it this way

$xml = false;

$xml = @simplexml_load_string($xmlstring);

// 1)

if ($xml) {
  $array = extractXML($xml);
}  else {
  $array = false;
}

// 2)

if ($xml) {
  $array[$xml->getName()] = extractXML($xml);
}  else {
  $array = false;
}

?>
nospam at qool dot com 05-Jun-2008 11:45
simplexml doesn't appear to like long attributes. I have tried passing it a valid xhtml document but the url in the anchor tag was causing simplexml to generate an error.
kyle at codeincarnate dot com 21-Apr-2008 05:28
A looked through a lot of the sample code for reading XML files with CDATA, but they didn't work out that well for me.  However, I found that the following piece of code worked perfectly for reading through a file using lots of CDATA.

<?php
$article_string = file_get_contents($path);
$article_string = preg_replace_callback('/<!\[CDATA\[(.*)\]\]>/', 'filter_xml', $article_string);
$article_xml = simplexml_load_string($article_string);

function filter_xml($matches) {
    return trim(htmlspecialchars($matches[1]));
}

?>
paulyg76 at NOSPAM dot gmail dot com 18-Feb-2008 06:39
Be careful using nested SimpleXML objects in double quoted strings.

<?php
$xmlstring = '<root><node>123</node><foo><bar>456</bar></foo></root>';

$root = simplexml_load_string($xmlstring);

echo "Node is: $root->node"; // Works: Node is 123
echo "Bar is: $root->foo->bar"; // Doesn't work, outputs: Bar is: ->bar
// use curly brackets to fix
echo "Bar is: {$root->foo->bar}"; // Works: Bar is 456

?>
amir_abiri at ipcmedia dot com 08-Feb-2008 08:47
It doesn't seem to be documented anywhere, but you can refer to an element "value" for the purpose of changing it like so:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} = $xml->number->{0} + 1;

echo $xml->asXml();
?>

echos:
<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>2</number></root>

However, this only works with a direct assignment, not with any of the other operators:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} += 1;
// Or:
$xml->number->{0}++;

echo $xml->asXml();
?>

Both of the above cases would result in:

<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>1<0/></number></root>
bojan 04-Feb-2008 04:38
As was said before don't use var_dump() or print_r() to see SimpleXML object structure as they do not returns always what you expect.
Consider the following:

<?php

// data in xml
$xml_txt = '
<root>
  <folder ID="65" active="1" permission="1"><![CDATA[aaaa]]></folder>
  <folder ID="65" active="1" permission="1"><![CDATA[bbbb]]></folder>
</root>';

// load xml into SimpleXML object
$xml = simplexml_load_string($xml_txt, 'SimpleXMLElement', LIBXML_NOCDATA);//LIBXML_NOCDATA LIBXML_NOWARNING

// see object structure
print_r($xml);

/* this prints
SimpleXMLElement Object
(
    [folder] => Array
        (
            [0] => aaaa
            [1] => bbbb
        )

)
*/

// but...
foreach ($xml->folder as $value){
    print_r($value);
}
/* prints complete structure of each folder element:
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => aaaa
)

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => bbbb
)

*/
?>
hattori at hanso dot com 15-Oct-2007 03:19
Theres a problem with the below workaround when serializing fields containing html CDATA. For any other content type then HTML try to modfiy function parseCDATA.
Just add these lines before serializing.
This is also a workaround for this bug http://bugs.php.net/bug.php?id=42001

<?PHP
if(strpos($content, '<![CDATA[')) {
   function parseCDATA($data) {
      return htmlentities($data[1]);
   }
   $content = preg_replace_callback(
      '#<!\[CDATA\[(.*)\]\]>#',
      'parseCDATA',
      str_replace("\n", " ", $content)
   );
}
?>
hattori at hanso dot com 17-Sep-2007 02:15
If you want to serialize and unserialize SimpleXMLElement objects for caching, you need to transform the SimpleXMLElement object into a standard class object before unserializing.
This is only if you want to cache converted data, the functionallity of the SimpleXMLElement will not be held.

$content = '<SomeXML....'

$serialized = str_replace(
  array('O:16:"SimpleXMLElement":0:{}', 'O:16:"SimpleXMLElement":'),
  array('s:0:"";', 'O:8:"stdClass":'),
  serialize(simplexml_load_string($content))
);

$unserialized = unserialize($serialized);
nbijnens at servs dot eu 10-Sep-2007 05:17
Please note that not all LIBXML options are supported with the options argument.

For instance LIBXML_XINCLUDE does not work. But there is however a work around:

<?php
$xml = new DOMDocument();
$xml->loadXML ($XMLString);

$xml->xinclude();
$xml = simplexml_import_dom($xml);

?>
Pedro 06-Jul-2007 01:28
Attention:

simplexml_load_string has a problem with entities other than (&lt;, &gt;, &amp;, &quot; and &apos;).

Use numeric character references instead!
youx_free_fr 23-May-2007 09:52
While needing to add an xml subtree to an existing simplexml object, I noticed that simplexml_load_string fails with strings like
<emptynode></emptynode>

I needed to use dom instead of simplexml to bypass this problem and work with any kind of xml strings.
David Somerset 08-May-2007 11:39
Another option for having simplexml convert CDATA into plain text is to simply type cast the result to string. Here's an example:

$xmlRoot = simplexml_load_string('<?xml version="1.0"?>

<tvshows>
    <show>
        <name>The Simpsons</name>
    </show>
     <show>
        <name><![CDATA[Lois & Clark]]></name>
    </show>
</tvshows>');

$show = array();

foreach($xmlRoot as $val){
    $show[] = (string) $val->name;
    }
php at teamhirsch dot com 24-Apr-2007 02:46
It's worth noting that in the example above, $xml->body will actually return an object of type SimpleXMLElement, not a string, e.g.

 SimpleXMLElement Object (
       [0] => this is the text in the body tag
  )

If you want to get a string out of it you must explicitly cast it using (string) or double quotes, or pass $xml->body (or whatever attribute you want to access) to any function that returns a string, such as urldecode() or trim().
m dot ament at mailcity dot com 06-Mar-2007 06:51
Warning:

The parsing of XML-data will stop when reaching character 0.
Please avoid this character in your XML-data.
mindpower 30-Jan-2007 03:03
A simple extension that adds a method for retrieving a specific attribute:

<?php
class simple_xml_extended extends SimpleXMLElement
{
    public    function    Attribute($name)
    {
        foreach($this->Attributes() as $key=>$val)
        {
            if($key == $name)
                return (string)$val;
        }
    }

}

$xml = simplexml_load_string('
<xml>
  <dog type="poodle" owner="Mrs Smith">Rover</dog>
</xml>', 'simple_xml_extended');

echo $xml->dog->Attribute('type');

?>

outputs 'poodle'

I prefer to use this technique rather than typecasting attributes.
h 15-Nov-2006 10:44
seems like simplexml has a line-length restriction - fails if a largeish XML doc with no linebreaks is passed as a string or file.

h
roy dot walter at nospam dot brookhouse dot co dot uk 16-Oct-2006 09:15
simplexml provides a neat way to do 'ini' files. Preferences for any number of users can be held in a single XML file having elements for each user name with user specific preferences as attributes of child elements. The separate <pref/>'s could of course be combined as multiple attributes of a single <pref/> element but this could get unwieldy.

In the sample code below the makeXML() function uses the simplexml_load_string function to generate some XML to play with and the readPrefs() function parses the requested users preferences into an array.

<?php
function makeXML() {

$xmlString = <<<XML
<preferences>
    <johndoe>
        <pref color="#FFFFFF"/>
        <pref size="14"/>
        <pref font="Verdana"/>
    </johndoe>
    <janedoe>
        <pref color="#000000"/>
        <pref size="16"/>
        <pref font="Georgia"/>
    </janedoe>
</preferences>
XML;

return simplexml_load_string($xmlString);

}
function readPrefs($user, $xml) {

    foreach($xml->$user as $arr);
        $n = count($arr);

    for($i=0;$i<$n;$i++) {
        foreach($xml->$user->pref[$i]->attributes() as $a=>$b) {
            $prefs[$a] = (string)$b;
        }
    }

    print_r($prefs);
}

readPrefs('johndoe', makeXML());

?>
paul at santasoft dot com 25-Jul-2006 08:22
If you have PHP > 5.1 and LibXML > 2.6, use this function call to have simplexml convert CDATA into plain text.

simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA);

Too bad, so sad with PHP < 5.1.
lists at cyberlot dot net 07-Sep-2005 12:51
While you can't add new elements to a SimpleXML object you can however add new attributes
<?php
$string = '<doc channel="chat"><test1>Hello</test1></doc>';
$xml = simplexml_load_string($string);
$xml->test1['sub'] = 'No';
echo $xml->asXML();
?>

Will return output
<doc channel="chat"><test1 sub="No">Hello</test1></doc>
Maciek Ruckgaber <maciekrb at gmai dot com> 07-Jun-2005 05:07
after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P

when you have something like:

<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://foosite.foo/">2328</double>
XML;
?>

you will have the simpleXML object "transformed" to the text() content:

<?php
$xml = simplexml_load_string($xmlstr);
echo $xml; // this will echo 2328  (string)
?>
igor kraus 07-Jan-2005 10:37
A simple way to merge two SimpleXML objects.

<?php
/**
* Pumps all child elements of second SimpleXML object into first one.
*
* @param    object      $xml1   SimpleXML object
* @param    object      $xml2   SimpleXML object
* @return   void
*/
function simplexml_merge (SimpleXMLElement &$xml1, SimpleXMLElement $xml2)
{
    // convert SimpleXML objects into DOM ones
    $dom1 = new DomDocument();
    $dom2 = new DomDocument();
    $dom1->loadXML($xml1->asXML());
    $dom2->loadXML($xml2->asXML());

    // pull all child elements of second XML
    $xpath = new domXPath($dom2);
    $xpathQuery = $xpath->query('/*/*');
    for ($i = 0; $i < $xpathQuery->length; $i++)
    {
        // and pump them into first one
        $dom1->documentElement->appendChild(
            $dom1->importNode($xpathQuery->item($i), true));
    }
    $xml1 = simplexml_import_dom($dom1);
}

$xml1 = simplexml_load_string('<root><child>child 1</child></root>');
$xml2 = simplexml_load_string('<root><child>child 2</child></root>');
simplexml_merge($xml1, $xml2);
echo($xml1->asXml());
?>

Will output:
<?xml version="1.0"?>
<root>
    <child>child 1</child>
    <child>child 2</child>
</root>
cellog at php dot net 31-Aug-2004 04:11
simplexml does not simply handle CDATA sections in a foreach loop.

<?php
$sx = simplexml_load_string('
<test>
 <one>hi</one>
 <two><![CDATA[stuff]]></two>
 <t>
  <for>two</for>
 </t>
 <multi>one</multi>
 <multi>two</multi>
</test>');
foreach((array) $sx as $tagname => $val) {
    if (is_string($val)) {
       // <one> will go here
    } elseif (is_array($val)) {
       // <multi> will go here because it happens multiple times
    } elseif (is_object($val)) {
      // <t> will go here because it contains tags
      // <two> will go here because it contains CDATA!
    }
}
?>

To test in the loop, do this

<?php
if (count((array) $val) == 0) {
    // this is not a tag that contains other tags
    $val = '' . $val;
    // now the CDATA is revealed magically.
}
?>
greg dot steffensen at spamless dot richmond dot edu 19-Feb-2004 03:04
Simplexml's simplicity can be deceptive.  Simplexml elements behave either as objects or strings, depending on the context in which they're used (through overloading of the __toString() method, I assume).  Statements implying conversion to string treat them as strings, while assignment operations treat them as objects.  This can lead to unexpected behavior if, for example, you are trying to compare the values of two Simplexml elements.  The expected syntax will not work.  To force conversion to strings, just "typecast' whatever Simplexml element you're using.  For example:

<?php
$s = simplexml_load_string('<foo>43</foo> <bar>43</bar>');

// Evaluates to false by comparing object IDs instead of strings
($s->foo == $s->bar);

// Evaluates to true
((string)$s->foo == (string)$s->bar);
?>

[Ed. Note: Changed from quotes to casts because casts provide a quicker and more explicit conversion than do double quotes.]
simplexml_load_file
WDDX
SimpleXML


WDDX

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • wddx examples
  • WDDX Функции
    • wddx_add_vars — Add variables to a WDDX packet with the specified ID
    • wddx_deserialize — Unserializes a WDDX packet
    • wddx_packet_end — Ends a WDDX packet with the specified ID
    • wddx_packet_start — Starts a new WDDX packet with structure inside it
    • wddx_serialize_value — Serialize a single value into a WDDX packet
    • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

There are no user contributed notes for this page.
simplexml_load_string
Введение
Обработка XML


Введение

These functions are intended for work with » WDDX.

User Contributed Notes

alvaro at demogracia dot com 29-Sep-2008 08:49
From OpenWDDX.Org:

"The Web Distributed Data Exchange, or WDDX, is a free, open XML-based technology that allows Web applications created with any platform to easily exchange data with one another over the Web."

"WDDX is an XML-based technology that enables the exchange of complex data between Web programming languages, creating what some refer to as 'Web syndicate networks'. WDDX consists of a language-independent representation of data based on an XML 1.0 DTD, and a set of modules for a wide variety of languages that use WDDX. WDDX can be used with HTTP, SMTP, POP, FTP and other Internet protocols that support transferring textual data."
WDDX
Установка и настройка
WDDX


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
WDDX


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

After installing the required expat library, compile PHP with --enable-wddx , and use --with-libexpat-dir for expat.

Версия PHP для Windows имеет встроенную поддержку данного расширения. Это означает, что для использования данных функций не требуется загрузка никаких дополнительных расширений.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Типы ресурсов

This extension defines a WDDX packet identifier returned by wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
WDDX


Примеры

Содержание

  • wddx examples

User Contributed Notes

dormilich at netscape dot net 27-Nov-2008 06:37
If you want to use the WDDX 1.0 DTD for validation (http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt) check that you define the comment as element, not as attribute.

<?xml version="1.0" encoding="iso-8859-1" ?>
<wddxPacket version='1.0'>
    <header>
        <comment>PHP</comment>
    </header>
    <data><!-- WDDX serialized data --></data>
</wddxPacket>
Предопределенные константы
wddx examples
WDDX


wddx examples

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Пример #1 Serializing a single value with WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Пример #2 Using incremental packets with WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Замечание:

If you want to serialize non-ASCII characters you have to convert your data to UTF-8 first (see utf8_encode() and iconv()).

User Contributed Notes

There are no user contributed notes for this page.
Примеры
WDDX Функции
Примеры


WDDX Функции

Содержание

  • wddx_add_vars — Add variables to a WDDX packet with the specified ID
  • wddx_deserialize — Unserializes a WDDX packet
  • wddx_packet_end — Ends a WDDX packet with the specified ID
  • wddx_packet_start — Starts a new WDDX packet with structure inside it
  • wddx_serialize_value — Serialize a single value into a WDDX packet
  • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

iGEL 14-Mar-2008 02:03
As of version 5.2.5, this is wrong:

> Note: If you want to serialize non-ASCII characters you
> have to convert your data to UTF-8 first (see utf8_encode()
> and iconv()).

Serializing a string with WDDX will always convert it from ISO-8859-1 to UTF-8, no matter what the original encoding is. So if your data already are UTF-8, you get just gibberish.

You can restore the original encoding by using utf8_decode on the serialized wddx data, even though your original data may use chars not included in ISO-8859-1:

<?php
header("Content-Type: text/xml;encoding=utf-8");
echo utf8_decode(wddx_serialize_value("안녕 하세요"));
?>

(This is why I dislike PHP, sorry)
egbert teeselink 23-Feb-2008 10:50
I'm horrible, forgot to include a helper function:

function getchild($node)
{
    if(count($node) > 1) echo "warning: node $node has more than 1 child";
    foreach($node->children() as $name => $subnode) {}
    return array($subnode, $name);
}
egbert teeselink 23-Feb-2008 10:49
If your PHP doesn't have wddx support installed, and you need it, and you don't want to install PEAR just for wddx, try this short piece of code, based on SimpleXML:

//can read any wddx file generated from php arrays. assumes var elements are only inside struct elements and that only one packet exists.
function wddx_read_node($node, $type)
{
    switch($type)
    {
    case "boolean":
        return (string)$node;
    case "number":
    case "binary":
    case "string":
        return (string)$node;
    case "null":
        return null;
    case "array":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            $a[] = wddx_read_node($subnode, $subtype);
        }
        return $a;
    case "struct":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            list($key, $value) = wddx_read_node($subnode, $subtype); //must be a var element
            $a[$key] = $value;
        }
        return $a;
    case "var":
        list($subnode, $subtype) = getchild($node);
        return array((string)$node["name"], wddx_read_node($subnode, $subtype));
    case "data":
        list($subnode, $subtype) = getchild($node);
        return wddx_read_node($subnode, $subtype);
    }
}

function wddx_read($string)
{
    $xml = simplexml_load_string($string);
    $d = wddx_read_node($xml->data, "data");
    return $d;
}

important notice: this one may not work with all wddx input. multiple packets or variables outside a "struct" are not supported. basically, you always get a PHP (associative) array, never something else. feel free to make additions.
no at spam dot thx 12-Aug-2007 02:09
To bradburn at kiwi dot de:

PHP is only capable of serializing properly variables which match one of its native (scalar) types (See http://php.net/types). Which means that only variables of type booleans, integers, floating point numbers, string and NULL will be serialized properly.

I think there are two exceptions though:
- arrays are serialized by processing them recursively, so if its only composed of the above mentioned types, you should be fine.
- floating point numbers and integers may use the same representation while serialized in WDDX (I don't know much about WDDX, so I'm not 100% sure about this statement).

An interesting case would be whether objects can be serialized or not...
Jimmy Wimenta 15-Jul-2004 05:53
PHP's WDDX is useful only for exchanging data between PHP applications, but definetly not for exchanging data between different languages (which actually defeats the purpose of WDDX).

For example:

$hash1 = array ("2" => "Two", "4" => "Four", "5" => "Five");
$hash2 = array ("0" => "Zero", "1" => "One", "2" => "Two");

$hash1 will be serialized as hash, but
$hash2 will be serialized as array/list, because the key happen to be a sequence starting from 0.

Unless the library provide a way for users to specify the type, it can never be used for cross-platform data exchange.
Q1tum at hotmail dot com 21-Nov-2003 05:08
To insert arrays into a wddx variable here is a fine way to do it:

<?php

$sql = 'SELECT * FROM example';
$query = mysql_query($sql, $db) or die(mysql_error());

while($result = mysql_fetch_array($query)) {
    $id[] = $result[ 'id'];
    $name[] = $result['name'];
    $description[] = $result[$prefix . 'description'];
}

mysql_free_result($query);

wddx_add_vars($packet_id, "id");
wddx_add_vars($packet_id, "name");
wddx_add_vars($packet_id, "description");

$wddxSerializeValue = wddx_packet_end($packet_id);

?>
11-Sep-2003 07:29
wddx isn't 100% perl compatible .. I have an wddx file infront of me and it only works with php so better don't use it
bradburn at kiwi dot de 30-Jul-2002 07:02
With ref to the above comment about typing, I have found that -- oddly enough -- PHP's WDDX supports the following WDDX types: null, boolean (true/false), number and string, *but* not date-time.

as an example, use the following values in an array that you then serialize:

$number = 5,
$null = NULL,
$bool = true,
$string = 'this is a string'.

they will all serialize correctly, e.g. the third entry comes out as:

<var name='bool'><boolean value='true'/></var>

i have tried with the 'official' format for WDDX 'datetime', e.g. '1998-9-15T09:05:32+4:0' (from the DTD @ http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt)  but have only succeeded in getting this encoded as a 'string' type.

if anyone else has any more information on this, it would be welcome. i would like to store the variables in 'appropriate' fields in a database, and the fact that only datetime is not supported is slightly irritating -- otherwise it would be a very useful function.
djm at web dot us dot uu dot net 18-Oct-1999 08:45
Since there aren't any examples of reversing the process, here's one. If you had the packet produced by the above example (without the htmlentities() call), you could retrieve the values like this:

<?php
$value = wddx_deserialize($packet);
print "pi is:<br>" . $value["pi"] . "<p>\n";
print "cities is:<br>\n";
while (list($key, $val) = each($value["cities"])) {
    print "$key => $val<br>\n";
}
?>

which outputs:

<pre>
pi is:
3.1415926

cities is:
0 => Austin
1 => Novato
2 => Seattle
</pre>
wddx examples
wddx_add_vars
WDDX


Add variables to a WDDX packet with the specified ID

WDDX Функции
wddx_deserialize
WDDX Функции
PHP Manual

wddx_add_vars

(PHP 4, PHP 5)

wddx_add_vars — Add variables to a WDDX packet with the specified ID

Описание

bool wddx_add_vars ( resource $packet_id , mixed $var_name [, mixed $... ] )

Serializes the passed variables and add the result to the given packet.

Список параметров

This function takes a variable number of parameters.

packet_id

A WDDX packet, returned by wddx_packet_start().

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

maciek at webenlinea dot com 05-Sep-2004 11:20
Here is a simple way of serializing dynamic values from an array:

<?PHP
//a unix timestamp
$date    = "1094095513";

//some data to be included
$books   = array('programming'   => array('php','perl','java'),
                'markup'        => array('UML','XML','HTML')
                );

//stick data to an array to iterate over
$data_to_serialize = array($date,$books);

//create the packet
$packet = wddx_packet_start("SOME DATA ARRAY");

//loop through the data
foreach($data_to_serialize as $key => $data)
{
  //create a var whith the name of the content of $key
  $$key = $data;
  wddx_add_vars($packet,$key);
}

echo wddx_packet_end($packet);

?>

Have fun !
WDDX Функции
wddx_deserialize
WDDX Функции


Unserializes a WDDX packet

wddx_add_vars
wddx_packet_end
WDDX Р¤СѓРЅРєС†РёРё
PHP Manual

wddx_deserialize

(PHP 4, PHP 5)

wddx_deserialize — Unserializes a WDDX packet

РћРїРёСЃР°РЅРёРµ

mixed wddx_deserialize ( string $packet )

Unserializes a WDDX packet.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

packet

A WDDX packet, as a string or stream.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Returns the deserialized value which can be a string, a number or an array. Note that structures are deserialized into associative arrays.

User Contributed Notes

valer underscore crisan at yahoo 01-Apr-2009 02:03
In PHP 5.2.9, we noticed that wddx serialize and deserialize seems to use UTF-8 encoding for XML input and the output data. There are some posts below that talk about fixing the input XML data so deserialize would work fine on special chars in ISO-8859-1 encoding, but none of the posts talks about the output encoding.

Consider this test:
$text = "JГјr";
$packet = wddx_serialize_value($text);
$header = '<?xml version="1.0" encoding="iso-8859-1"?>';
$newText = wddx_deserialize($header . $packet);
echo "WDDX Packet: $packet\n";
echo "Deserialized Object: $newText\n";

The output is:

WDDX Packet: <wddxPacket version='1.0'><header/><data><string>JГјr</string></data></wddxPacket>
Deserialized Object: JГѓВјr

The deserialized string is not in ISO-8859-1 encoding. It is in UTF-8 encoding. So we need to run utf8_decode() on the deserialized data to convert it back to ISO-8859-1 encoding which is what our application expects.

Hope this helps.
Magnus Deininger, dma05 at web dot de 12-Feb-2009 05:57
When writing your wddx file manually with an UTF-8 aware editor and saving it in utf-8, if your data gets its special characters mysteriously scrambled, try to add an xml header that marks the output as iso-8859-1, like this one:

<?xml version="1.1" encoding="iso-8859-1" ?>

This makes the wddx decode function treat the input as iso-8859-1, so it will not try to treat it as utf-8 and do an implicit decode to iso-8859-1. You will then have read all string data in the wddx packet in their original utf-8 encoding, so that 'echo' and other output functions will produce the intended result if you have set the output encoding to utf-8.

(Bugs reports on this behaviour seem to be treated as bogus, so it would seem in order to point out this incorrect and highly confusing side-effect.)
dormilich at netscape dot net 28-Nov-2008 05:13
When deserializing objects make sure you have the class definition loaded. wddx_deserialize() doesn't call the class itself, so you will receive a fatal error.
Nevertheless you can look for the class manually and delegate it to __autoload().

<?php
// $wddx_string needs to be valid XML to be loaded by SimpleXML.
// class_exists() will call the __autoload() function. if you don't
// want to use __autoloload(), use require_once()

function loadClassesFromWDDX($wddx_string)
{
    $xml = new SimpleXMLElement($wddx_string);

    foreach ($xml->xpath('//var') as $var)
    {
        if ($var['name'] == 'php_class_name')
        {
            if (!class_exists($var->string))
            {
                throw new Exception('Class '" . $var->string . "'not available.');
                // trigger_error('Class '" . $var->string . "'not available.', E_USER_ERROR);
            }
        }
    }
}
?>
dave at codexweb dot co dot za 21-Jan-2006 04:40
Here's a handy wddx_deserialize clone I wrote a while back. It uses PHP5 SimpleXML and recursion to do pretty much the same task as wddx_deserialize. Hope it comes in handy for someone.

<?php

if (!function_exists('wddx_deserialize'))
{
    /**
     * Clone implementation of wddx_deserialize
     */
    function wddx_deserialize($xmlpacket)
    {
        if ($xmlpacket instanceof SimpleXMLElement)
        {
            if (!empty($xmlpacket->struct))
            {
                $struct = array();
                foreach ($xmlpacket->xpath("struct/var") as $var)
                {
                    if (!empty($var["name"]))
                    {
                        $key = (string) $var["name"];
                        $struct[$key] = wddx_deserialize($var);
                    }
                }
                return $struct;
            }
            else if (!empty($xmlpacket->array))
            {
                $array = array();
                foreach ($xmlpacket->xpath("array/*") as $var)
                {
                    array_push($array, wddx_deserialize($var));
                }
                return $array;
            }
            else if (!empty($xmlpacket->string))
            {
                return (string) $xmlpacket->string;
            }
            else if (!empty($xmlpacket->number))
            {
                return (int) $xmlpacket->number;
            }
            else
            {
                if (is_numeric((string) $xmlpacket))
                {
                    return (int) $xmlpacket;
                }
                else
                {
                    return (string) $xmlpacket;
                }
            }
        }
        else
        {
            $sxe = simplexml_load_string($xmlpacket);
            $datanode = $sxe->xpath("/wddxPacket[@version='1.0']/data");
            return wddx_deserialize($datanode[0]);
        }
    }
}

?>
php dot net at werner-ott dot de 24-Nov-2005 12:20
On migrating wddx_deserialize() from PHP 4.x to PHP 5.1 (5.1.0RC6):

While

  $buffer = wddx_serialize_vars($some_array);
  $some_array = wddx_deserialize($buffer);

worked fine with PHP 4.x, the deserialization failed with PHP 5.1. In the above example $some_array will just be an empty string under 5.1

While wddx_serialize_vars() seems to behave identical in 4.x and 5.1, wddx_deserialize() does NOT.

Prepending XML encoding information to the buffer turned out to be at least a workaround. So, the following works with PHP 5.1:

  $buffer = wddx_serialize_vars($some_array);
  $buffer = '<?xml version="1.0"
          encoding="ISO-8859-1"?>'.
          $buffer;
  $some_array = wddx_deserialize($buffer);

NB: It may well be, that the behavioural difference between 4.x and 5.1 described above can only be observed if the array contains certain characters, i.e. german Umlaute (дцьДЦЬ). So this workaround may not be necessary in each and every case.
mail_fidel at yahoo dot com 19-Nov-2004 12:11
To properly deserialize a wddx file it was to be utf8_encoded.

The following code will NOT work (PHP5.0.2 FreeBSD):

<?php
   $data = wddx_serialize_value(array("xyzедц","abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>

Even thought the serialization is done right, the deserialization will not work unless you encode the text using utf8.

This code WILL work:

<?php
   $data = wddx_serialize_value(array(utf8_encode("xyzедц"),"abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>
xavier at c-est-simple dot com 19-May-2004 04:09
JavaScript/PHP interroperability:

If you want to exchange wddx packets between a JavaScript application using the JS wddx library from openwddx (http://www.openwddx.org/downloads/), and a PHP script using wddx functions, be aware that the encoding of the classes of objects serialized in the wddx packet is not made the same way in both implementations.

The JS lib uses a 'type' attribute in the 'struct' tab and gives it the name of the class of the object serialized in the 'struct' element, while PHP uses a 'php_class_name' tag within the 'struct'.
NB : to get the type attribute with JS serialisation, you need to set the 'wddxSerializationType' member in your classes

Example with an object of class 'exemple' containing 2 members _attr1 and _attr2.
(NB : in french, 'example' is spelled 'exemple', okay ? :-)

JS serialization :
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct type="exemple">
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

php serialization:
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct>
   <var name='php_class_name'>
    <string>exemple</string>
   </var>
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

I like the JS approach better.
So if you need the compatibility, the workaround is quite simple:
- add a 'php_class_name' member in your JS objects, giving it the name of the class for value, and the JS generated packet will be correctly deserialized with PHP in classed objects.

- use a regexp on a PHP generated packet to add the 'type' attribute so that the JS deserialization instanciates objects of the right class:
      $pat = "/<struct><var name='php_class_name'><string>(\w+)<\/string>/" ;
      $rep = "<struct type='\$1'><var name='php_class_name'><string>\$1</string>" ;
      $serialised = preg_replace($pat, $rep, $serialised );
NB : this only works because the 'php_class_name' tag is just next to the 'struct' tag.
Who knows if this is going to be true in future releases... ?

This way, you can exchange JS and PHP objects (provided you define your JS and PHP classes the same way) smoothly...

It's worth saying that both implementations, as well as my interroperability workaround, handle correctly objects with members that are also objects.

NB : NB means Nota Bene.
xavier at c-est-simple.com 18-May-2004 10:19
Beware, although the deserialized objects are instanciated class objects (if the php_class_name tag is amongst the children of the struct tag and its text content is the name of a loaded class), the constructor of the class has not been called at all.
You can use the members and call the methods of the object all right, but any initialisation action that the constructor might be in charge of is missing.
php at mike2k dot com 10-Sep-2001 06:06
if you have WDDX data coming from a third party source and it isnt being parsed correctly in your php, try translating their WDDX. we have a third party sending us WDDX from cold fusion, and it uses a <recordset> element, which PHP seems to ignore (looking around the web we found some other people having trouble) so the (hopefully temporary) solution we found was to translate the WDDX midstream and then we were able to parse it:

$url = "http://somedomain.com/blah.wddx";
$fp = fopen($url,"r");
$page = fread($fp,10000);
fclose($fp);
$page = str_replace("<recordset","<struct",$page);
$page = str_replace("</recordset","</struct",$page);
$page = str_replace("<field","<var",$page);
$page = str_replace("</field","</var",$page);
$values = wddx_deserialize($page);
while(list($key,$val) = each($values)) {
        print "$key => $val<BR>";
}

this works for us. it's a hack, and hopefully php will support this in the future or something.
medvitz at medvitz dot net 14-Oct-2000 05:29
You can also serialize instantiated class objects with the wddx functions.
ie.

<?php
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "objvar");
$packet = wddx_packet_end($packet_id);

$a =  wddx_deserialize($packet);
$obj = $a[objvar];
?>

now $obj is a useable object, that looks like the original.

Note that with this method, you need to know what the variable name of the original object was.  You can use one of the array functions to get the object in the event that the original object's variable name was unknown.

*** only verified on linux with 4.0.2
djm at web dot us dot uu dot net 18-Oct-1999 09:58
The packet string you pass to this function doesn't have to be sanitized first; it searches for a WDDX packet within the string.  So the string can contain HTML markup and random text outside of the packet, and that is all ignored.
This means you can get a packet from another web page like this:
<?php
$fhandle = fopen("http://myserver.com/packet.php", "r");
if ($fhandle) {
        $page = fread($fhandle,10000);
        fclose($fhandle);
        $value = wddx_deserialize($page);
        print "pi is:<br>" . $value["pi"] . "<p>\n";
} else {
        print "could not get packet.php<p>";
}
?>
wddx_add_vars
wddx_packet_end
WDDX Р¤СѓРЅРєС†РёРё


Ends a WDDX packet with the specified ID

wddx_deserialize
wddx_packet_start
WDDX Функции
PHP Manual

wddx_packet_end

(PHP 4, PHP 5)

wddx_packet_end — Ends a WDDX packet with the specified ID

Описание

string wddx_packet_end ( resource $packet_id )

Ends and returns the given WDDX packet.

Список параметров

packet_id

A WDDX packet, returned by wddx_packet_start().

Возвращаемые значения

Returns the string containing the WDDX packet.

User Contributed Notes

There are no user contributed notes for this page.
wddx_deserialize
wddx_packet_start
WDDX Функции


Starts a new WDDX packet with structure inside it

wddx_packet_end
wddx_serialize_value
WDDX Функции
PHP Manual

wddx_packet_start

(PHP 4, PHP 5)

wddx_packet_start — Starts a new WDDX packet with structure inside it

Описание

resource wddx_packet_start ([ string $comment ] )

Start a new WDDX packet for incremental addition of variables. It automatically creates a structure definition inside the packet to contain the variables.

Список параметров

comment

An optional comment string.

Возвращаемые значения

Returns a packet ID for use in later functions, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.
wddx_packet_end
wddx_serialize_value
WDDX Функции


Serialize a single value into a WDDX packet

wddx_packet_start
wddx_serialize_vars
WDDX Функции
PHP Manual

wddx_serialize_value

(PHP 4, PHP 5)

wddx_serialize_value — Serialize a single value into a WDDX packet

Описание

string wddx_serialize_value ( mixed $var [, string $comment ] )

Creates a WDDX packet from a single given value.

Список параметров

var

The value to be serialized

comment

An optional comment string that appears in the packet header.

Возвращаемые значения

Returns the WDDX packet, or FALSE on error.

User Contributed Notes

chris at digitalbase dot com 04-Jan-2002 04:36
When serializing JavaScript objects to interact with PHP objects, you should make the JavaScript object's first entry a php_class_name.

PHP:
class myclass {
    var $name;
    var $age;
    var $ssn;
    ...

    function myclass() {
        $this->name = "";
        $this->age = "";
        $this->ssn = "";
        ...
    }
}

JavaScript:
// serialization example code is from the
// WDDX SDK http://www.openwddx.org
function SerializeMsg(name, age, ssn, ...) {
    var MyObj = new Object;

    // the following line is necessary in order
    // to deserialize back to a PHP object
    MyObj.php_class_name = "myclass";

    MyObj.name = name;
    MyObj.age = age;
    MyObj.ssn = ssn;
    ...

    // Create a new serializer "object" to do our work for us
    MySer = new WddxSerializer;

    // Serialize the Message variable into a WDDX Packet
    MyWDDXPacket = MySer.serialize(MyObj);

    // Output WDDX Packet so we can see what it looks like
    return MyWDDXPacket;
}

Now you can use this in a page which is its own form action:
<?php
// don't forget to include the class definition from above!
if (!isSet($wddx_packet))
    $MyObj = new myclass();
else
    $MyObj = wddx_deserialize($wddx_packet);
?>

<html>
<head>
<script language="JavaScript">
<!--
function Init() {
    // sets the form's text-elements
    tmp = document.MyForm;

    tmp.name.value = "<? echo $MyObj->name ?>";
    tmp.age.value = "<? echo $MyObj->age ?>";
    tmp.ssn.value = "<? echo $MyObj->ssn ?>";
    ...
}

function SerializeMsg(name, age, ssn, ...) {
// see above!
}

function SubmitForm() {
    // sumbits the form
    tmp = document.MyForm;

    tmp.wddx_packet.value =
    SerializeMsg(tmp.name.value, tmp.age.value, tmp.ssn.value,...);
    document.submit();
}
// -->
</script>
</head>
<body>
...
<form name="MyForm"
action="<? echo $PHP_SELF ?>" method="post">
<input name="wddx_packet" type="hidden">
<input name="name" type="text">
<input name="age" type="text">
<input name="ssn" type="text">
...
<input name="SubmitBtn" type="button" onclick="SumbitForm()">
</form>
</body>
</html>

---------------------------------
If you don't provide that first 'php_class_name' in the JavaScript function, then when PHP deserializes it will deserialize into an associative array and not an object instance.

Note that this provides a way to maintain state without
using sessions or cookies - just good old HTML!

Hope this helps!
--
Chris Hansen
wddx_packet_start
wddx_serialize_vars
WDDX Функции


Serialize variables into a WDDX packet

wddx_serialize_value
XML-анализатор
WDDX Функции
PHP Manual

wddx_serialize_vars

(PHP 4, PHP 5)

wddx_serialize_vars — Serialize variables into a WDDX packet

Описание

string wddx_serialize_vars ( mixed $var_name [, mixed $... ] )

Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.

Список параметров

This function takes a variable number of parameters.

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Возвращаемые значения

Returns the WDDX packet, or FALSE on error.

Примеры

Пример #1 wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

Результат выполнения данного примера:

<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

User Contributed Notes

kangus at jaga dot us 13-Oct-2003 03:57
A function to use for dates with PHP & WDDX
getdate()

$ta="<FORM><TEXTAREA rows=15 cols=80>" ;
$te="</TEXTAREA></FORM>";
$packet_id=wddx_packet_start("Date Example--");
$myDate=getdate();
wddx_add_vars($packet_id,'myDate');
$package=wddx_packet_end($packet_id);
print($ta.$package.$te);

Produces:

<wddxPacket version='1.0'><header><comment>Date Example--</comment></header>
<data><struct><var name='myDate'>
<struct><var name='seconds'><number>12</number></var>
<var name='minutes'><number>55</number></var>
<var name='hours'><number>1</number></var>
<var name='mday'><number>13</number></var>
<var name='wday'><number>1</number></var>
<var name='mon'><number>10</number></var>
<var name='year'><number>2003</number></var>
<var name='yday'><number>285</number></var>
<var name='weekday'><string>Monday</string></var>
<var name='month'><string>October</string></var>
<var name='0'><number>1066031712</number>
</var></struct></var></struct></data></wddxPacket>
tychay at alumni dot caltech dot edu 31-Mar-2002 12:15
The above feature will cause a slight trouble since the name of the variable will always be "wddxtemp" but you can use preg_replace to fix that.

Also, a better approach is to serialize the entire class. WDDX will that write a reserved "php_class_name" variable which can be used to reconstruct the class during a deserialize.
tychay at alumni dot caltech dot edu 30-Mar-2002 10:49
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
tychay at alumni dot caltech dot edu 30-Mar-2002 10:45
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
christian dot knoflach at gmx dot at 21-May-2001 03:56
Be careful using WDDX - functions on object variables. As I just had to find out the following won't work:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx = wddx_serialize_vars("this->str");
    print(htmlentities($this->wddx));
  }
}

new Test();
?>

That's what you'll get:
<wddxPacket version='1.0'><header/><data><struct></struct></data></wddxPacket>
wddx_serialize_value
XML-анализатор
WDDX Функции


XML-анализатор

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Обработчики событий
  • Приведение к одному регистру
  • Коды ошибок
  • Кодировка символов
  • Примеры
    • Пример Структуры Элемента XML
    • Пример отображения XML тегов
    • Пример использования внешних сущностей XML
  • Функции парсера XML
    • utf8_decode — Преобразует строку с ISO-8859-1 символами кодированную в UTF-8 в однобайтную ISO-8859-1
    • utf8_encode — Кодирует строку ISO-8859-1 в кодировке UTF-8
    • xml_error_string — Получение строки ошибки XML анализатора
    • xml_get_current_byte_index — Получает текущий для XML анализатора байтовый индекс
    • xml_get_current_column_number — Получает от XML парсера номер текущего столбца
    • xml_get_current_line_number — Получает от XML-парсера номер текущей строки
    • xml_get_error_code — Получает код ошибки XML-парсера
    • xml_parse_into_struct — Разбор XML данных и помещение в массив
    • xml_parse — Запускает разбор XML документа
    • xml_parser_create_ns — Создание XML анализатора с поддержкой пространств имен
    • xml_parser_create — Создание XML анализатора
    • xml_parser_free — Освобождение XML анализатора
    • xml_parser_get_option — Получение значения настройки XML анализатора
    • xml_parser_set_option — Установка значения настройки XML анализатора
    • xml_set_character_data_handler — Установка обработчика символьных данных
    • xml_set_default_handler — Установка обработчика по умолчанию
    • xml_set_element_handler — Установка обработчика начального и конечного элементов
    • xml_set_end_namespace_decl_handler — Установка обработчика выхода за пределы пространства имен
    • xml_set_external_entity_ref_handler — Установка обработчика внешних сущностей
    • xml_set_notation_decl_handler — Установка обработчика объявления условных обозначений
    • xml_set_object — Использование XML анализатора внутри объекта
    • xml_set_processing_instruction_handler — Установка обработчика инструкций препроцессора (PI)
    • xml_set_start_namespace_decl_handler — Установка обработчика входа в пределы пространства имен
    • xml_set_unparsed_entity_decl_handler — Установка обработчика неразобранных объявлений сущностей

User Contributed Notes

marcgear at gmail dot com 04-Aug-2010 10:12
While this SAX event based parser is better for memory management than the tree based parsers of SimpleXML and DOM, the pull-based parser XMLReader is much easier to use than the xml_parser_* functions, and still doesn't require loading the file into memory.
nat 04-Sep-2009 12:19
An event-based parser such XML Parser is preferable for large files, because tree-based parsers must fully load the file into memory in order to parse the XML. Event-based parsers do not need to load the entire file into memory to begin parsing.
pavel dot lishin at gmail dot com 28-Jul-2009 09:33
If you're wanting to actually work with XML data as it was intended, treating it as a tree, try http://us2.php.net/manual/en/book.simplexml.php .
wddx_serialize_vars
Введение
Обработка XML


Введение

XML (eXtensible Markup Language - расширяемый язык разметки) - это формат данных для обмена структурированными документами в всемирной сети. Данный стандарт определён Консорциумом Всемирной паутины (W3C). Информация об XML и связанных технологиях может быть найдена на » http://www.w3.org/XML/.

Данное PHP-расширение реализует поддержку библиотеки expat Джеймса Кларка в PHP. Данный инструментарий позволяет Вам анализировать, но не проверять XML-документы. Он поддерживает три кодировки символов исходного текста также поддерживаемых PHP: US-ASCII, ISO-8859-1 и UTF-8. UTF-16 не поддерживается.

Данное расширение позволит вам создавать XML-анализаторы и далее определить обработчики для различных событий. Каждый XML-анализатор также имеет несколько параметров, которые вы можете настраивать.

User Contributed Notes

There are no user contributed notes for this page.
XML-анализатор
Установка и настройка
XML-анализатор


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
XML-анализатор


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

Это расширение использует expat-совместимый слой по умолчанию. Также может быть использован expat, который может быть найден здесь: » http://www.jclark.com/xml/expat.html. Makefile, поставляемый с expat не создает библиотеку по умолчанию, вы можете использовать следующее правило для этого:

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
Исходный RPM пакет expat может быть найден здесь:» http://sourceforge.net/projects/expat/.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

Это расширение включено по умолчанию. Оно может быть отключено во время выполнения с помощью следующей опции: --disable-xml

Эти функции включены по умолчанию при использовании стандартной библиотеки expat. Вы можете отключить поддержку XML с помощью --disable-xml . Если вы собрали PHP как модуль для Apache 1.3.9 или более поздней версии, PHP будет автоматически использовать стандартну библиотеку expat из Apache. В случае, если вы не хотите использовать стандартную библиотеку expat, то вам необходимо настроить PHP опцию --with-expat-dir=DIR , где DIR - путь до установочной директории библиотеки expat.

Версия PHP для Windows имеет встроенную поддержку данного расширения. Это означает, что для использования данных функций не требуется загрузка никаких дополнительных расширений.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Типы ресурсов

XML-ресурс, возвращаемый xml_parser_create() и xml_parser_create_ns(), ссылается на сущность xml-парсера, чтобы иметь возможность использовать функции этого расширения.

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

XML_ERROR_NONE (integer)
XML_ERROR_NO_MEMORY (integer)
XML_ERROR_SYNTAX (integer)
XML_ERROR_NO_ELEMENTS (integer)
XML_ERROR_INVALID_TOKEN (integer)
XML_ERROR_UNCLOSED_TOKEN (integer)
XML_ERROR_PARTIAL_CHAR (integer)
XML_ERROR_TAG_MISMATCH (integer)
XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)
XML_ERROR_PARAM_ENTITY_REF (integer)
XML_ERROR_UNDEFINED_ENTITY (integer)
XML_ERROR_RECURSIVE_ENTITY_REF (integer)
XML_ERROR_ASYNC_ENTITY (integer)
XML_ERROR_BAD_CHAR_REF (integer)
XML_ERROR_BINARY_ENTITY_REF (integer)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)
XML_ERROR_MISPLACED_XML_PI (integer)
XML_ERROR_UNKNOWN_ENCODING (integer)
XML_ERROR_INCORRECT_ENCODING (integer)
XML_ERROR_UNCLOSED_CDATA_SECTION (integer)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)
XML_OPTION_CASE_FOLDING (integer)
XML_OPTION_TARGET_ENCODING (integer)
XML_OPTION_SKIP_TAGSTART (integer)
XML_OPTION_SKIP_WHITE (integer)
XML_SAX_IMPL (string)
Устанвливает стандарт обработки SAX. Может быть libxml или expat.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Обработчики событий
XML-анализатор


Обработчики событий

Список обработчиков событий XML:

Поддерживаемые XML обработчики
Функции PHP для установки обработчика | Описание события
xml_set_element_handler() | События элементов выдаются каждый раз, когда XML парсер встречает начальный или конечный тэги. Есть разные обработчики для начальных и конечных тэгов.
xml_set_character_data_handler() | Символьные данные это примерно всё неразмеченное содержимое XML документов, включая непечатные символы между тэгами. Отметим, что XML анализатор не добавляет или удаляет никаких непечатных символов, так как это приложение (то есть пользователь) решает где непечатные символы значительны.
xml_set_processing_instruction_handler() | PHP программисты должны быть уже знакомы с инструкциями обработки (PIs). <?php ?> является обрабатывающей инструкцией, где php является вызываемой "PI целью". Обработка этих инструкций зависит от программы, за исключением того, что все цели PI начинаются с зарезервированного слова "XML".
xml_set_default_handler() | Если нет специального обработчика, то вызывается обработчик по умолчанию. Вы получите XML и объявления типов документа при помощи обработчика по умолчанию.
xml_set_unparsed_entity_decl_handler() | Этот обработчик будет вызываться для декларирования непроанализированных (NDATA) сущностей.
xml_set_notation_decl_handler() | Этот обработчик вызывается при объявлении нотации.
xml_set_external_entity_ref_handler() | Этот обработчик вызывается когда анализатор XML находит ссылку на внешнюю сущность. Например, это может быть ссылка на файл или URL. Смотрите пример внешней сущности.
xml_set_start_namespace_decl_handler() | Этот обработчик вызывается в начале объявления пространства имён.
xml_set_end_namespace_decl_handler() | Этот обработчик вызывается в конце объявления пространства имён. Отметим, что это событие НЕ входит в состав LibXML.

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Приведение к одному регистру
XML-анализатор


Приведение к одному регистру

Функции обработчиков элементов могут получать имена своих элементов приведенными к одному регистру. Приведение к одному регистру определяется как "процесс, применяемый к последовательности символов, когда символы, идентифицируемые как "не в верхнем регистре", заменяются своими эквивалентами верхнего регистра". Иначе говоря, когда речь идёт о XML, приведение к одному регистру означает перевод символов в верхний регистр.

По умолчанию имена всех элементов, передаваемые функциям обработчиков, передаются с выравниванием регистра. Такой режим может запрашиваться и контролироваться XML-парсером с помощью функций xml_parser_get_option() и xml_parser_set_option() соответственно.

User Contributed Notes

There are no user contributed notes for this page.
Обработчики событий
Коды ошибок
XML-анализатор


Коды ошибок

Следующие константы определены для кодов ошибок XML (возвращаемых функцией 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

User Contributed Notes

djmaze 14-Aug-2010 08:29
Here's the full list of all 733 error codes
http://www.xmlsoft.org/html/libxml-xmlerror.html#xmlParserErrors
Michael 19-Aug-2009 03:33
XML_ERR_NAME_REQUIRED - Means you have an entity that isn't valid in XML.

For example: & < and > all have to be escaped as &amp; &lt; and &gt; respectively.
Приведение к одному регистру
Кодировка символов
XML-анализатор


Кодировка символов

Модуль XML в PHP поддерживает набор символов » Unicode через разные кодировки символов. Есть два типа кодировок символов в этом модуле, исходная кодировка и целевая кодировка. Внутреннее представление документа в PHP всегда кодировано в UTF-8.

Исходное кодирование происходит, когда XML документ разбирается. При создании анализатора XML может быть определена исходная кодировка (эта кодировка не может быть изменена позже, во время работы XML анализатора). Поддерживаются исходные кодировки ISO-8859-1, US-ASCII и UTF-8. Первые две являются однобайтными кодировками,что означает, что каждый символ представлен одним байтом. UTF-8 может кодировать символы, представленные переменным числом бит (вплоть до 21) в байты (от одного до четырёх). По умолчанию в PHP исходной кодировкой является ISO-8859-1.

Целевое кодирование происходит, когда PHP передаёт данные обрабатывающим XML функциям. Когда создаётся XML анализатор, целевая кодировка устанавливается такой же, как исходная кодировка, затем она может быть изменена в любой момент. Целевая кодировка повлияет на символьные данные, а также имена тегов и цели обрабатывающих команд.

Если XML анализатор встречает символы за пределами диапазона, которые их исходная кодировкам может предоставить, он возвращает ошибку.

Если PHP встречает символы в разбираемом XML документе, которые не могут быть представлены в выбранной целевой кодировке, проблемные символы будут "понижены". В данном случае это означает, что такие символы будут замещены вопросительным знаком.

User Contributed Notes

There are no user contributed notes for this page.
Коды ошибок
Примеры
XML-анализатор


Примеры

Содержание

  • Пример Структуры Элемента XML
  • Пример отображения XML тегов
  • Пример использования внешних сущностей XML

User Contributed Notes

There are no user contributed notes for this page.
Кодировка символов
Пример Структуры Элемента XML
XML-анализатор


Пример Структуры Элемента XML

Первый пример отображает структуру начальных элементов в документе с отступом.

Пример #1 Показать структуру элемента XML

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs)
{
    global $depth;
    for ($i = 0; $i < $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name)
{
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("Невозможно произвести чтение XML");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("Ошибка XML: %s на строке %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>

User Contributed Notes

roan at horning dot us 30-Oct-2009 09:07
The following example will echo back an xml file using the basic event based parser.  Currently, (at least in the version of PHP5 I'm using) it will skip The XML declaration and the Doctype declaration--they don't seem to be captured by the default handler.

<?php
echo "<pre>";

$file = "test.xml";
echo $file."\n";
global $inTag;

$inTag = "";
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_set_processing_instruction_handler($xml_parser, "pi_handler");
xml_set_default_handler($xml_parser, "parseDEFAULT");
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents");

if (!($fp = fopen($file, "r"))) {
    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)));
    }
}
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);

function startElement($parser, $name, $attrs) {

    global $inTag;
    global $depth;

    $padTag = str_repeat(str_pad(" ", 3), $depth);

    if (!($inTag == "")) {
        echo "&gt;";
    }
    echo "\n$padTag&lt;$name";
    foreach ($attrs as $key => $value) {
        echo "\n$padTag".str_pad(" ", 3);
        echo " $key=\"$value\"";
    }
    $inTag = $name;
    $depth++;
}

function endElement($parser, $name) {

    global $depth;
   global $inTag;
    global $closeTag;

    $depth--;

   if ($closeTag == TRUE) {
       echo "&lt/$name&gt;";
       $inTag = "";
   } elseif ($inTag == $name) {
       echo " /&gt;";
       $inTag = "";
   } else {
         $padTag = str_repeat(str_pad(" ", 3), $depth);
       echo "\n$padTag&lt/$name&gt;";
    }
}

function contents($parser, $data) {

    global $closeTag;

    $data = preg_replace("/^\s+/", "", $data);
    $data = preg_replace("/\s+$/", "", $data);

    if (!($data == ""))  {
        echo "&gt;$data";
        $closeTag = TRUE;
    } else {
        $closeTag = FALSE;
     }
}

function parseDEFAULT($parser, $data) {

    $data = preg_replace("/</", "&lt;", $data);
    $data = preg_replace("/>/", "&gt;", $data);
    echo $data;
}

function pi_handler($parser, $target, $data) {

    echo "&lt;?$target $data?&gt;\n";
}
echo "</pre>";
?>
Примеры
Пример отображения XML тегов
Примеры


Пример отображения XML тегов

Пример #1 Отображение XML в HTML

Этот пример отображает теги XML документа непосредственно в HTML тегах. Элементы не найденные в "массиве отображения" игнорируются. Конечно, этот пример будет работать только с определенным типом документа XML.

<?php
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";
    }
}

function endElement($parser, $name)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";
    }
}

function characterData($parser, $data)
{
    echo $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("Невозможно произвести чтение XML");
}

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

User Contributed Notes

There are no user contributed notes for this page.
Пример Структуры Элемента XML
Пример использования внешних сущностей XML
Примеры


Пример использования внешних сущностей XML

Этот пример подсвечивает код XML. Он иллюстрирует то, как необходимо использовать обработчик ссылки на внешнюю сущность для подключения и разбора содержимого внешних файлов, так же как может быть обработан PI, и путь для определения "доверия" к коду, содержащемуся в PI.

XML документы, которые используются в примере расположены под самим примером (xmltest.xml и xmltest2.xml.)

Пример #1 Пример использования внешней сущности

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
    // доверять только нашим собственным локальным файлам
    if (!preg_match("@^([a-z]+)\:\/\/@i", $file)
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs)
{
    echo "&lt;<font color=\"#0000cc\">$name</font>";
    if (count($attribs)) {
        foreach ($attribs as $k => $v) {
            echo " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    echo "&gt;";
}

function endElement($parser, $name)
{
    echo "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data)
{
    echo "<b>$data</b>";
}

function PIHandler($parser, $target, $data)
{
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // Если обработанный документ является "доверенным", то можно сказать,
            // что запуск расположенного в нем кода является безопасным. Если нет,
            // то вместо запуска отобразить сам код.
            if (trustedFile($parser_file[$parser])) {
                eval($data);
            } else {
                printf("Небезопасный код PHP: <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("Невозможно открыть сущность %s в %s\n", $openEntityNames,
                   $systemId);
            return false;
        }
        while ($data = fread($fp, 4096)) {
            if (!xml_parse($parser, $data, feof($fp))) {
                printf("Ошибка XML: %s в строке %d в процессе разбора сущности %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("Чтение XML-файла невозможно");
}

echo "<pre>";
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("Ошибка XML: %s в строке %d\n",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
echo "</pre>";
echo "разбор завершен\n";
xml_parser_free($xml_parser);

?>

Пример #2 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;
 <section id="about">
  <title>About this Document</title>
  <para>
   <!-- this is a comment -->
   <?php echo 'Hi!  This is PHP version ' . phpversion(); ?>
  </para>
 </section>
</chapter>

Этот файл подключен из xmltest.xml:

Пример #3 xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "Здесь запущен некий код PHP"; ?>
</foo>

User Contributed Notes

There are no user contributed notes for this page.
Пример отображения XML тегов
Функции парсера XML
Примеры


Функции парсера XML

Содержание

  • utf8_decode — Преобразует строку с ISO-8859-1 символами кодированную в UTF-8 в однобайтную ISO-8859-1
  • utf8_encode — Кодирует строку ISO-8859-1 в кодировке UTF-8
  • xml_error_string — Получение строки ошибки XML анализатора
  • xml_get_current_byte_index — Получает текущий для XML анализатора байтовый индекс
  • xml_get_current_column_number — Получает от XML парсера номер текущего столбца
  • xml_get_current_line_number — Получает от XML-парсера номер текущей строки
  • xml_get_error_code — Получает код ошибки XML-парсера
  • xml_parse_into_struct — Разбор XML данных и помещение в массив
  • xml_parse — Запускает разбор XML документа
  • xml_parser_create_ns — Создание XML анализатора с поддержкой пространств имен
  • xml_parser_create — Создание XML анализатора
  • xml_parser_free — Освобождение XML анализатора
  • xml_parser_get_option — Получение значения настройки XML анализатора
  • xml_parser_set_option — Установка значения настройки XML анализатора
  • xml_set_character_data_handler — Установка обработчика символьных данных
  • xml_set_default_handler — Установка обработчика по умолчанию
  • xml_set_element_handler — Установка обработчика начального и конечного элементов
  • xml_set_end_namespace_decl_handler — Установка обработчика выхода за пределы пространства имен
  • xml_set_external_entity_ref_handler — Установка обработчика внешних сущностей
  • xml_set_notation_decl_handler — Установка обработчика объявления условных обозначений
  • xml_set_object — Использование XML анализатора внутри объекта
  • xml_set_processing_instruction_handler — Установка обработчика инструкций препроцессора (PI)
  • xml_set_start_namespace_decl_handler — Установка обработчика входа в пределы пространства имен
  • xml_set_unparsed_entity_decl_handler — Установка обработчика неразобранных объявлений сущностей

User Contributed Notes

Glen at ITIStudios dot ca 02-Dec-2011 03:37
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  2.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);

    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag][$item])) {
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>

This is supplimental information for the "class xmlToArrayParser".
This is a fully functional error free, extensively tested php class unlike the posts that follow it.

Key phrase: Fully functional, fully tested, error free XML To Array parser.

<?php
/**
 * class xmlToArrayParser
 *
  Notes:
  1. 'attrib' and 'cdata' are keys added to the array when the element contains both attributes and content.
  2. Ignores content that is not in between it's own set of tags.
  3. Don't know if it recognizes processing instructions nor do I know about processing instructions.
     <\?some_pi some_attr="some_value"?>  This is the same as a document declaration.
  4. Empty elements are not included unless they have attributes.
  5. Version 2.0, Dec. 2, 2011, added xml error reporting.

  Usage:
    $domObj = new xmlToArrayParser($xml);
    $elemVal = $domObj->array['element']
    Or assign the entire array to its own variable:
    $domArr = $domObj->array;
    $elemVal = $domArr['element']

  Example:
    $xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <top>
      <element1>element content 1</element1>
      <element2 var2="val2" />
      <element3 var3="val3" var4="val4">element content 3</element3>
      <element3 var5="val5">element content 4</element3>
      <element3 var6="val6" />
      <element3>element content 7</element3>
    </top>';

    $domObj = new xmlToArrayParser($xml);
    $domArr = $domObj->array;

    if($domObj->parse_error) echo $domObj->get_xml_error();
    else print_r($domArr);

    On Success:
    $domArr['top']['element1'] => element content 1
    $domArr['top']['element2']['attrib']['var2'] => val2
    $domArr['top']['element3']['0']['attrib']['var3'] => val3
    $domArr['top']['element3']['0']['attrib']['var4'] => val4
    $domArr['top']['element3']['0']['cdata'] => element content 3
    $domArr['top']['element3']['1']['attrib']['var5'] => val5
    $domArr['top']['element3']['1']['cdata'] => element content 4
    $domArr['top']['element3']['2']['attrib']['var6'] => val6
    $domArr['top']['element3']['3'] => element content 7

    On Error:
    Error Code [76] "Mismatched tag", at char 58 on line 3
 *
 */
?>
wolfon.AT-DoG.inbox.ru 28-Jul-2008 03:09
Finally a simple xml => array class.
Functioning like SimpleXML library.

<?php
class xml  {
    private $parser;
    private $pointer;
    public $dom;

    public function __construct($data) {
        $this->pointer =& $this->dom;
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
        xml_parse($this->parser, $data);
    }

    private function tag_open($parser, $tag, $attributes) {
        if (isset($this->pointer[$tag]['@attributes'])) {
            $content = $this->pointer[$tag];
            $this->pointer[$tag] = array(0 => $content);
            $idx = 1;
        } else if (isset($this->pointer[$tag]))
            $idx = count($this->pointer[$tag]);

        if (isset($idx)) {
            $this->pointer[$tag][$idx] = Array(
                '@idx' => $idx,
                '@parent' => &$this->pointer);
               $this->pointer =& $this->pointer[$tag][$idx];
        } else {
            $this->pointer[$tag] = Array(
                '@parent' => &$this->pointer);
            $this->pointer =& $this->pointer[$tag];
        }
        if (!empty($attributes))
            $this->pointer['@attributes'] = $attributes;
    }

    private function cdata($parser, $cdata) {
           $this->pointer['@data'] = $cdata;
    }

    private function tag_close($parser, $tag) {
        $current = & $this->pointer;
        if (isset($this->pointer['@idx']))
            unset($current['@idx']);

        $this->pointer = & $this->pointer['@parent'];

          unset($current['@parent']);
           if (isset($current['@data']) && count($current) == 1)
               $current = $current['@data'];
           else if (empty($current['@data'])||$current['@data']==0)
               unset($current['@data']);
    }
}
?>

maybe I'll do some explanations on habr
geoff at spacevs dot com 07-Nov-2007 09:13
Reading xml into a class:

<?PHP
        class XmlData {}
        $elements = array();
        $elements[] =& new XmlData();
        function startElement($parser, $name, $attrs) {
                global $elements;
                $element =& new XMLData();
                $elements[count($elements)-1]->$name =& $element;
                $elements[] =& $element;
        }
        function endElement($parser, $name) {
                global $elements;
                array_pop($elements);
        }
        function characterData($parser, $data) {
                global $elements;
                $elements[count($elements)-1]->data = $data;
        }
        $xml_parser     = xml_parser_create();
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_set_character_data_handler($xml_parser, "characterData");
        xml_parse($xml_parser, $xml, true);
        xml_parser_free($xml_parser);
        $request =& array_pop($elements);

        echo $request->LOGIN->USER->data;
?>
demonpants at gmail dot com 22-Oct-2007 08:59
I wanted to access the ISBN database, and was previously parsing the HTML string generated from their main page, that is until I discovered they have an API that returns XML.

So, if anyone wants to get some information from the ISBN database, all you need to do is the following.

<?php
//Search the ISBN database for the book.
            $url = "http://www.isbndb.com/api/books.xml? access_key=KEY&index1=isbn&value1=$_GET[ISBN]";
            $p = xml_parser_create();
            xml_parse_into_struct($p,file_get_contents($url),$results,$index);
            xml_parser_free($p);

            $title = $results[$index[TITLELONG][0]][value];
            $author = $results[$index[AUTHORSTEXT][0]][value];
            $publisher = $results[$index[PUBLISHERTEXT][0]][value];
?>

You will need to get an access key from isbndb.com, but it takes two seconds and is free. When you get it, replace KEY in the URL with your own key. Also, my code above will search for the book that fits the ISBN number stored in the GET variable ISBN - you can search by other parameters and return more than one result, but my example is  for a simple ISBN search.
Zvjezdan Patz 09-Sep-2007 08:22
The problem I had was I needed to generate xml on the screen for users to actually see and copy to a file.

I'm generating the xml manually from a php file and the browser kept interpreting the xml...not very helpful.

This is how you get around it:

<?php

$file  = file_get_contents("http://example.com/xml.php?whatever=$whatever");
print nl2br(htmlentities($file));

?>

Prints all my xml quite nicely.
v9 at fakehalo dot us 13-Jul-2007 08:04
I needed this for work/personal use.  Sometimes you'll have a XML string generated as one long string and no line breaks...nusoap in the case of today/work, but there are any other number of possible things that will generate these.  Anyways, this simply takes a long XML string and returns an indented/line-breaked version of the string for display/readability.

<?php
function xmlIndent($str){
    $ret = "";
    $indent = 0;
    $indentInc = 3;
    $noIndent = false;
    while(($l = strpos($str,"<",$i))!==false){
        if($l!=$r && $indent>0){ $ret .= "\n" . str_repeat(" ",$indent) . substr($str,$r,($l-$r)); }
        $i = $l+1;
        $r = strpos($str,">",$i)+1;
        $t = substr($str,$l,($r-$l));
        if(strpos($t,"/")==1){
            $indent -= $indentInc;
            $noIndent = true;
        }
        else if(($r-$l-strpos($t,"/"))==2 || substr($t,0,2)=="<?"){ $noIndent = true; }
        if($indent<0){ $indent = 0; }
        if($ret){ $ret .= "\n"; }
        $ret .= str_repeat(" ",$indent);
        $ret .= $t;
        if(!$noIndent){ $indent += $indentInc; }
        $noIndent = false;
    }
    $ret .= "\n";
    return($ret);
}
?>

(...this was only tested for what i needed at work, could POSSIBLY need additions)
geoffers [at] gmail [dot] com 30-Dec-2006 03:27
Time to add my attempt at a very simple script that parses XML into a structure:

<?php

class Simple_Parser
{
    var $parser;
    var $error_code;
    var $error_string;
    var $current_line;
    var $current_column;
    var $data = array();
    var $datas = array();

    function parse($data)
    {
        $this->parser = xml_parser_create('UTF-8');
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
        xml_set_element_handler($this->parser, 'tag_open', 'tag_close');
        xml_set_character_data_handler($this->parser, 'cdata');
        if (!xml_parse($this->parser, $data))
        {
            $this->data = array();
            $this->error_code = xml_get_error_code($this->parser);
            $this->error_string = xml_error_string($this->error_code);
            $this->current_line = xml_get_current_line_number($this->parser);
            $this->current_column = xml_get_current_column_number($this->parser);
        }
        else
        {
            $this->data = $this->data['child'];
        }
        xml_parser_free($this->parser);
    }

    function tag_open($parser, $tag, $attribs)
    {
        $this->data['child'][$tag][] = array('data' => '', 'attribs' => $attribs, 'child' => array());
        $this->datas[] =& $this->data;
        $this->data =& $this->data['child'][$tag][count($this->data['child'][$tag])-1];
    }

    function cdata($parser, $cdata)
    {
        $this->data['data'] .= $cdata;
    }

    function tag_close($parser, $tag)
    {
        $this->data =& $this->datas[count($this->datas)-1];
        array_pop($this->datas);
    }
}

$xml_parser = new Simple_Parser;
$xml_parser->parse('<foo><bar>test</bar></foo>');

?>
Didier: dlvb ** free * fr 24-Dec-2006 09:53
Hi !

After parsing the XML and modifying it, I just add a method to rebuild the XML form the internal structure (xmlp->document).
The method xmlp->toXML writes into xmlp->XML attributes. Then, you just have to output it.
I hope it helps.

<?php
class XMLParser {

var $parser;
var $filePath;
var $document;
var $currTag;
var $tagStack;
var $XML;
var $_tag_to_close = false;
var $TAG_ATTRIBUT = 'attr';
var $TAG_DATA = 'data';

function XMLParser($path) {
    $this->parser = xml_parser_create();
    $this->filePath = $path;
    $this->document = array();
    $this->currTag =& $this->document;
    $this->tagStack = array();
    $this->XML = "";
}

function parse() {
    xml_set_object($this->parser, $this);
    xml_set_character_data_handler($this->parser, 'dataHandler');
    xml_set_element_handler($this->parser, 'startHandler', 'endHandler');

   if(!($fp = fopen($this->filePath, "r"))) {
       die("Cannot open XML data file: $this->filePath");
       return false;
     }

    while($data = fread($fp, 4096)) {
        if(!xml_parse($this->parser, $data, feof($fp))) {
            die(sprintf("XML error: %s at line %d",
                xml_error_string(xml_get_error_code($this->parser)),
             xml_get_current_line_number($this->parser)));
      }
    }

    fclose($fp);
    xml_parser_free($this->parser);

    return true;
}

function startHandler($parser, $name, $attribs) {
     if(!isset($this->currTag[$name]))
          $this->currTag[$name] = array();

     $newTag = array();
     if(!empty($attribs))
          $newTag[$this->TAG_ATTRIBUT] = $attribs;
     array_push($this->currTag[$name], $newTag);

     $t =& $this->currTag[$name];
     $this->currTag =& $t[count($t)-1];
     array_push($this->tagStack, $name);
}

function dataHandler($parser, $data) {
    $data = trim($data);

    if(!empty($data)) {
      if(isset($this->currTag[$this->TAG_DATA]))
            $this->currTag[$this->TAG_DATA] .= $data;
      else
            $this->currTag[$this->TAG_DATA] = $data;
    }
}

function endHandler($parser, $name) {
     $this->currTag =& $this->document;
     array_pop($this->tagStack);

     for($i = 0; $i < count($this->tagStack); $i++) {
          $t =& $this->currTag[$this->tagStack[$i]];
          $this->currTag =& $t[count($t)-1];
     }
}

function clearOutput () {
    $this->XML = "";
}

function openTag ($tag) {
    $this->XML.="<".strtolower ($tag);
    $this->_tag_to_close = true;
}

function closeTag () {
    if ($this->_tag_to_close) {
        $this->XML.=">";
        $this->_tag_to_close = false;
    }
}

function closingTag ($tag) {
    $this->XML.="</".strtolower ($tag).">";
}

function output_attributes ($contenu_fils) {
    foreach ($contenu_fils[$this->TAG_ATTRIBUT] as $nomAttribut => $valeur) {
        $this->XML.= " ".strtolower($nomAttribut)."=\"".$valeur."\"";
    }
}

function addData ($texte) {
// to be completed
    $ca  = array ("é", "è", "ê", "à");
    $par = array ("&eacute;", "&egrave;", "&ecirc;", "agrave;");
    return htmlspecialchars(str_replace ($ca, $par, $texte), ENT_NOQUOTES);
}

function toXML ($tags="") {
    if ($tags=="") {
        $tags = $this->document;
      $this->clearOutput ();
    }

    foreach ($tags as $tag => $contenu) {
        $this->process ($tag, $contenu);
    }
}

function process ($tag, $contenu) {
     // Pour tous les TAGs
    foreach ($contenu as $indice => $contenu_fils) {
         $this->openTag ($tag);

         // Pour tous les fils (non attribut et non data)
         foreach ($contenu_fils as $tagFils => $fils) {
             switch ($tagFils) {
                 case $this->TAG_ATTRIBUT:
                         $this->output_attributes ($contenu_fils);
                        $this->closeTag ();
                         break;
                 case $this->TAG_DATA:
                        $this->closeTag ();
                         $this->XML.= $this->addData ($contenu_fils [$this->TAG_DATA]);
                         break;
                 default:
                         $this->closeTag ();
                         $this->process ($tagFils, $fils);
                         break;
             }
         }

        $this->closingTag ($tag);
    }
}

}
?>
forquan 28-Jan-2006 03:45
Here's code that will create an associative array from an xml file.  Keys are the tag data and subarrays are formed from attributes and child tags

<?php
$p =& new xmlParser();
$p->parse('/*xml file*/');
print_r($p->output);
?>

<?php
class xmlParser{
   var $xml_obj = null;
   var $output = array();
   var $attrs;

   function xmlParser(){
       $this->xml_obj = xml_parser_create();
       xml_set_object($this->xml_obj,$this);
       xml_set_character_data_handler($this->xml_obj, 'dataHandler');
       xml_set_element_handler($this->xml_obj, "startHandler", "endHandler");
   }

   function parse($path){
       if (!($fp = fopen($path, "r"))) {
           die("Cannot open XML data file: $path");
           return false;
       }

       while ($data = fread($fp, 4096)) {
           if (!xml_parse($this->xml_obj, $data, feof($fp))) {
               die(sprintf("XML error: %s at line %d",
               xml_error_string(xml_get_error_code($this->xml_obj)),
               xml_get_current_line_number($this->xml_obj)));
               xml_parser_free($this->xml_obj);
           }
       }

       return true;
   }

   function startHandler($parser, $name, $attribs){
       $_content = array();
       if(!empty($attribs))
         $_content['attrs'] = $attribs;
       array_push($this->output, $_content);
   }

   function dataHandler($parser, $data){
       if(!empty($data) && $data!="\n") {
           $_output_idx = count($this->output) - 1;
           $this->output[$_output_idx]['content'] .= $data;
       }
   }

   function endHandler($parser, $name){
       if(count($this->output) > 1) {
           $_data = array_pop($this->output);
           $_output_idx = count($this->output) - 1;
           $add = array();
           if ($_data['attrs'])
                $add['attrs'] = $_data['attrs'];
           if ($_data['child'])
                $add['child'] = $_data['child'];
           $this->output[$_output_idx]['child'][$_data['content']] = $add;
       }
   }
}
?>
Greg S 17-Nov-2005 08:56
If you need utf8_encode support and configure PHP with --disable-all you will have some trouble. Unfortunately the configure options aren't completely documented. If you need utf8 functions and have everything disabled just recompile PHP with --enable-xml and you should be good to go.
compu_global_hyper_mega_net_2 at yahoo dot com 19-Sep-2004 01:35
The documentation regarding white space was never complete I think.

The XML_OPTION_SKIP_WHITE doesn't appear to do anything.  I want to preserve the newlines in a cdata section.  Setting XML_OPTION_SKIP_WHITE to 0 or false doesn't appear to help.  My character_data_handler is getting called once for each line.  This obviously should be reflected in the documentation as well.  When/how often does the handler get called exactly?  Having to build separate test cases is very time consuming.

Inserting newlines myself in my cdata handler is no good either.  For non actual CDATA sections that cause my handler to get called, long lines are split up in multiple calls.  My handler would not be able to tell the difference whether or not the subsequent calls would be due to the fact that the data is coming from the next line or the fact that some internal buffer is long enough for it to 'flush' out and call the handler.
This behaviour also needs to be properly documented.
odders 18-Mar-2004 10:36
I wrote a simple xml parser mainly to deal with rss version 2. I found lots of examples on the net, but they were all masive and bloated and hard to manipulate.

Output is sent to an array, which holds arrays containg data for each item.

Obviously, you will have to make modifications to the code to suit your needs, but there isnt a lot of code there, so that shouldnt be a problem.

<?php

   $currentElements = array();
   $newsArray = array();

   readXml("./news.xml");

   echo("<pre>");
   print_r($newsArray);
   echo("</pre>");

   // Reads XML file into formatted html
   function readXML($xmlFile)
   {

      $xmlParser = xml_parser_create();

      xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
      xml_set_element_handler($xmlParser, startElement, endElement);
      xml_set_character_data_handler($xmlParser, characterData);

      $fp = fopen($xmlFile, "r");

      while($data = fread($fp, filesize($xmlFile))){
         xml_parse($xmlParser, $data, feof($fp));}

      xml_parser_free($xmlParser);

   }

   // Sets the current XML element, and pushes itself onto the element hierarchy
   function startElement($parser, $name, $attrs)
   {

      global $currentElements, $itemCount;

      array_push($currentElements, $name);

      if($name == "item"){$itemCount += 1;}

   }

   // Prints XML data; finds highlights and links
   function characterData($parser, $data)
   {

      global $currentElements, $newsArray, $itemCount;

      $currentCount = count($currentElements);
      $parentElement = $currentElements[$currentCount-2];
      $thisElement = $currentElements[$currentCount-1];

      if($parentElement == "item"){
         $newsArray[$itemCount-1][$thisElement] = $data;}
      else{
         switch($name){
            case "title":
               break;
            case "link":
               break;
            case "description":
               break;
            case "language":
               break;
            case "item":
               break;}}

   }

   // If the XML element has ended, it is poped off the hierarchy
   function endElement($parser, $name)
   {

      global $currentElements;

      $currentCount = count($currentElements);
      if($currentElements[$currentCount-1] == $name){
         array_pop($currentElements);}

   }

?>
software at serv-a-com dot com 22-Jan-2003 02:08
use:

<?php
while ($data = str_replace("\n","",fread($fp, 4096))){
 // ...
}
?>

instead of:

<?php
while ($data = fread($fp, 4096)) {
  // ...
}
?>

[UPDATE 17-FEB-2003: This post] resulted in some of the visitors e-mailg me on the carriage return stripping issue with questions. I'll try to make the following mumble as brief and easy to understand as possible.

1. Overview of the 4096 fragmentation issue
As you know the following freads the file 4096 bytes at a time (that is 4KB) this is perhaps ok for testing expat and figuring out how things work, but it it rather dangerous in the production environment. Data may not be fully understandable due to fread fragmentation and improperly formatted due to numerous sources(formats) of data contained within (i.e. end of line delimited CDATA).

<?php
while ($data = fread($fp, 4096)) {
  if (!xml_parse($xml_parser, $data, feof($fp))) {
    // ...
  }
}
?>

Sometimes to save time one may want to load it all up into a one big variable and leave all the worries to expat. I think anything under 500 KB is ok (as long as nobody knows about it). Some may argue that larger variables are acceptable or even necessary because of the magic that take place while parsing using xml_parse. Our XML parser(expat) works and can be successfully implemented only when we know what type of XML data we are dealing with, it's average size and structure of general layout and data contained within tags. For example if the tags are followed by a line delimiter like a new line we can read it with fgets in and with minimal effort make sure that no data will be sent to the function that does not end with a end tag. But this require a fair knowledge of the file's preference for storing XML data and tags (and a bit of code between reading data and xml_parse'ing it).
It will save you a headache.

2. Pre Parser Strings and New Line Delimited Data
One important thing to note at this point is that the xml_parse function requires a string variable. You can manipulate the content of any string variable easily as we all know.

A better approach to removing newlines than:

<?php
while ($data = fread($fp, 4096)) {
$data = preg_replace("/\n|\r/","",$data); //flarp
if (!xml_parse($xml_parser, $data, feof($fp))) {...
?>

Above works across all 3 line-delimited text files  (\n, \r, \r\n). But this could potentially (or will most likely) damage or scramble data contained in for example CDATA areas. As far as I am concerned end of line characters should not be used _within_ XML tags. What seems to be the ultimate solution is to pre-parse the loaded data this would require checking the position within the XML document and adding or subtracting (using a in-between fread temporary variable) data based on conditions like: "Is within tag", "Is within CDATA" etc. before fedding it to the parser. This of course opens up a new can of worms (as in parse data for the parser...). (above procedure would take place between fread and xml_parser calls this method would be compatible with the general usage examples on top of the page)

3. The Answer to parsing arbitrary XML and Preprocessor Revisited
You can't just feed any XML document to the parser you constructed and assuming that it will work! You have to know what kind of methods for storing data are used, for example is there a end of line delimited data in the  file ?, Are there any carriage returns in the tags etc... XML files come formatted in different ways some are just a one long string of characters with out any end of line markers others have newlines, carriage returns or both (Microsloth Windows). May or may not contain space and other whitespace between tags. For this reason it is important to what I call Normalize the data before feeding it to the parser. You can perform this with regular expressions or plain old str_replace and concatenation. In many cases this can be done to the file it self sometimes to string data on the fly( as shown in the example above). But I feel it is important to normalize the data before even calling the function to call xml_parse. If you have the ability to access all data before that call you can convert it to what you fell the data should have been in the first place and omit many surprises and expensive regular expression substitution (in a tight spot) while fread'ing the data.
guy at bhaktiandvedanta dot com 27-Sep-2002 12:01
For a simple XML parser you can use this function. It doesn't require any extensions to run.

<?php
// Extracts content from XML tag

function GetElementByName ($xml, $start, $end) {

    global $pos;
    $startpos = strpos($xml, $start);
    if ($startpos === false) {
        return false;
    }
    $endpos = strpos($xml, $end);
    $endpos = $endpos+strlen($end);
    $pos = $endpos;
    $endpos = $endpos-$startpos;
    $endpos = $endpos - strlen($end);
    $tag = substr ($xml, $startpos, $endpos);
    $tag = substr ($tag, strlen($start));

    return $tag;

}

// Open and read xml file. You can replace this with your xml data.

$file = "data.xml";
$pos = 0;
$Nodes = array();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}
while ($getline = fread($fp, 4096)) {
    $data = $data . $getline;
}

$count = 0;
$pos = 0;

// Goes throw XML file and creates an array of all <XML_TAG> tags.
while ($node = GetElementByName($data, "<XML_TAG>", "</XML_TAG>")) {
    $Nodes[$count] = $node;
    $count++;
    $data = substr($data, $pos);
}

// Gets infomation from tag siblings.
for ($i=0; $i<$count; $i++) {
$code = GetElementByName($Nodes[$i], "<Code>", "</Code>");
$desc = GetElementByName($Nodes[$i], "<Description>", "</Description>");
$price = GetElementByName($Nodes[$i], "<BasePrice>", "</BasePrice>");
}
?>

Hope this helps! :)
Guy Laor
dmarsh dot NO dot SPAM dot PLEASE at spscc dot ctc dot edu 18-Sep-2002 12:27
Some reference code I am working on as "XML Library" of which I am folding it info an object. Notice the use of the DEFINE:

Mainly Example 1 and parts of 2 & 3 re-written as an object:
--- MyXMLWalk.lib.php ---
<?php

if (!defined("PHPXMLWalk")) {
define("PHPXMLWalk",TRUE);

class XMLWalk {
 var $p; //short for xml parser;
 var $e; //short for element stack/array

  function prl($x,$i=0) {
    ob_start();
    print_r($x);
    $buf=ob_get_contents();
    ob_end_clean();
    return join("\n".str_repeat(" ",$i),split("\n",$buf));
  }

 function XMLWalk() {
  $this->p = xml_parser_create();
  $this->e = array();
  xml_parser_set_option($this->p, XML_OPTION_CASE_FOLDING, true);
  xml_set_element_handler($this->p, array(&$this, "startElement"), array(&$this, "endElement"));
  xml_set_character_data_handler($this->p, array(&$this, "dataElement"));
  register_shutdown_function(array(&$this, "free")); // make a destructor
  }

  function startElement($parser, $name, $attrs) {
    if (count($attrs)>=1) {
      $x = $this->prl($attrs, $this->e[$parser]+6);
    } else {
      $x = "";
    }

    print str_repeat(" ",$this->e[$parser]+0). "$name $x\n";
    $this->e[$parser]++;
    $this->e[$parser]++;
  }

  function dataElement($parser, $data) {
    print str_repeat(" ",$this->e[$parser]+0). htmlspecialchars($data, ENT_QUOTES) ."\n";
  }

  function endElement($parser, $name) {
    $this->e[$parser]--;
    $this->e[$parser]--;
  }
  function parse($data, $fp) {
    if (!xml_parse($this->p, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($this->p)),
                    xml_get_current_line_number($this->p)));
    }
  }

  function free() {
    xml_parser_free($this->p);
  }

} // end of class

} // end of define

?>

--- end of file ---

Calling code:
<?php

...

require("MyXMLWalk.lib.php");

$file = "x.xml";

$xme = new XMLWalk;

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
  $xme->parse($data, $fp);
}

...
?>
jon at gettys dot org 14-Aug-2002 01:59
[Editor's note: see also xml_parse_into_struct().]

Very simple routine to convert an XML file into a PHP structure. $obj->xml contains the resulting PHP structure. I would be interested if someone could suggest a cleaner method than the evals I am using.

<?php
$filename = 'sample.xml';
$obj->tree = '$obj->xml';
$obj->xml = '';

function startElement($parser, $name, $attrs) {
    global $obj;

    // If var already defined, make array
    eval('$test=isset('.$obj->tree.'->'.$name.');');
    if ($test) {
      eval('$tmp='.$obj->tree.'->'.$name.';');
      eval('$arr=is_array('.$obj->tree.'->'.$name.');');
      if (!$arr) {
        eval('unset('.$obj->tree.'->'.$name.');');
        eval($obj->tree.'->'.$name.'[0]=$tmp;');
        $cnt = 1;
      }
      else {
        eval('$cnt=count('.$obj->tree.'->'.$name.');');
      }

      $obj->tree .= '->'.$name."[$cnt]";
    }
    else {
      $obj->tree .= '->'.$name;
    }
    if (count($attrs)) {
        eval($obj->tree.'->attr=$attrs;');
    }
}

function endElement($parser, $name) {
    global $obj;
    // Strip off last ->
    for($a=strlen($obj->tree);$a>0;$a--) {
        if (substr($obj->tree, $a, 2) == '->') {
            $obj->tree = substr($obj->tree, 0, $a);
            break;
        }
    }
}

function characterData($parser, $data) {
    global $obj;

    eval($obj->tree.'->data=\''.$data.'\';');
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($filename, "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);
print_r($obj->xml);
return 0;

?>
hans dot schneider at bbdo-interone dot de 24-Jan-2002 08:43
I had to TRIM the data when I passed one large String containig a wellformed XML-File to xml_parse. The String was read by CURL, which aparently put a BLANK at the end of the String. This BLANK produced a "XML not wellformed"-Error in xml_parse!
sam at cwa dot co dot nz 28-Sep-2000 07:39
I've discovered some unusual behaviour in this API when ampersand entities are parsed in cdata; for some reason the parser breaks up the section around the entities, and calls the handler repeated times for each of the sections. If you don't allow for this oddity and you are trying to put the cdata into a variable, only the last part will be stored.

You can get around this with a line like:

$foo .= $cdata;

If the handler is called several times from the same tag, it will append them, rather than rewriting the variable each time. If the entire cdata section is returned, it doesn't matter.

May happen for other entities, but I haven't investigated.

Took me a while to figure out what was happening; hope this saves someone else the trouble.
Daniel dot Rendall at btinternet dot com 07-Jul-1999 10:21
When using the XML parser, make sure you're not using the magic quotes option (e.g. use set_magic_quotes_runtime(0) if it's not the compiled default), otherwise you'll get 'not well-formed' errors when dealing with tags with attributes set in them.
Пример использования внешних сущностей XML
utf8_decode
XML-анализатор


РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ СЃ ISO-8859-1 СЃРёРјРІРѕР»Р°РјРё РєРѕРґРёСЂРѕРІР°РЅРЅСѓСЋ РІ UTF-8 РІ РѕРґРЅРѕР±Р°Р№С‚РЅСѓСЋ ISO-8859-1

Р¤СѓРЅРєС†РёРё РїР°СЂСЃРµСЂР° XML
utf8_encode
Р¤СѓРЅРєС†РёРё РїР°СЂСЃРµСЂР° XML
PHP Manual

utf8_decode

(PHP 4, PHP 5)

utf8_decode — РџСЂРµРѕР±СЂР°Р·СѓРµС‚ СЃС‚СЂРѕРєСѓ СЃ ISO-8859-1 СЃРёРјРІРѕР»Р°РјРё РєРѕРґРёСЂРѕРІР°РЅРЅСѓСЋ РІ UTF-8 РІ РѕРґРЅРѕР±Р°Р№С‚РЅСѓСЋ ISO-8859-1

РћРїРёСЃР°РЅРёРµ

string utf8_decode ( string $data )

РС‚Р° С„СѓРЅРєС†РёСЏ РґРµРєРѕРґРёСЂСѓРµС‚ data, РїСЂРµРґРїРѕР»РѕР¶РёС‚РµР»СЊРЅРѕ Р·Р°РєРѕРґРёСЂРѕРІР°РЅРЅС‹Рµ РІ UTF-8, РІ ISO-8859-1.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

data

РЎС‚СЂРѕРєР° Р·Р°РєРѕРґРёСЂРѕРІР°РЅРЅР°СЏ РІ UTF-8.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ РґР°РЅРЅС‹Рµ data, РїРµСЂРµРІРµРґРµРЅРЅС‹Рµ РІ ISO-8859-1.

РЎРјРѕС‚СЂРёС‚Рµ С‚Р°РєР¶Рµ

  • utf8_encode() - РљРѕРґРёСЂСѓРµС‚ СЃС‚СЂРѕРєСѓ ISO-8859-1 РІ РєРѕРґРёСЂРѕРІРєРµ UTF-8 (СЃРѕРґРµСЂР¶РёС‚ РѕРїРёСЃР°РЅРёРµ UTF-8)

User Contributed Notes

chris at deliens dot be 18-Apr-2012 12:37
I didn't see any post showing a way to recursively utf8_decode an array.
So here's one I've just built for this purpose:

function utf8DecodeArray($array) {
    $utf8DecodedArray = array();

    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $utf8DecodedArray[$key] = utf8DecodeArray($value);
            continue;
        }

        $utf8DecodedArray[$key] = utf8_decode($value);
    }

    return $utf8DecodedArray;
}
deceze at gmail dot com 14-Jul-2011 07:01
Please note that utf8_decode simply converts a string encoded in UTF-8 to ISO-8859-1. A more appropriate name for it would be utf8_to_iso88591. If your text is already encoded in ISO-8859-1, you do not need this function. If you don't want to use ISO-8859-1, you do not need this function.

Note that UTF-8 can represent many more characters than ISO-8859-1. Trying to convert a UTF-8 string that contains characters that can't be represented in ISO-8859-1 to ISO-8859-1 will garble your text and/or cause characters to go missing. Trying to convert text that is not encoded in UTF-8 using this function will most likely garble the text.

If you need to convert any text from any encoding to any other encoding, look at iconv() instead.
gabriel arobase gabsoftware dot com 12-Jun-2011 08:41
If you want to retrieve some UTF-8 data from your database, you don't need utf8_decode().

Simply do the following query before any SELECT :

$result = mysql_query("SET NAMES utf8");
vidthekid at live dot com 18-Oct-2010 07:30
Got around to some very basic testing of my modified UTF-8 to HTML Entities function.  Apparently preg_replace doesn't like null-characters in its patterns.  That was the only glaring error (actually a warning, but it caused the returned string to be empty) I've encountered.  That's been fixed.  Also, support for four-byte UTF-8 sequences has been added.  Finally, arithmetic operators have been replaced with bitwise operators, which should make the conversion slightly faster and less prone to wild results given invalid input вЂ” even though the invalid input should have been filtered out already.

<?PHP
function UTF8ToEntities ($string) {
    /* note: apply htmlspecialchars if desired /before/ applying this function
    /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;

    // reject too-short sequences
    $string = preg_replace("/[\302-\375]([\001-\177])/", "&#65533;\\1", $string);
    $string = preg_replace("/[\340-\375].([\001-\177])/", "&#65533;\\1", $string);
    $string = preg_replace("/[\360-\375]..([\001-\177])/", "&#65533;\\1", $string);
    $string = preg_replace("/[\370-\375]...([\001-\177])/", "&#65533;\\1", $string);
    $string = preg_replace("/[\374-\375]....([\001-\177])/", "&#65533;\\1", $string);

    // reject illegal bytes & sequences
        // 2-byte characters in ASCII range
    $string = preg_replace("/[\300-\301]./", "&#65533;", $string);
        // 4-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/\364[\220-\277]../", "&#65533;", $string);
        // 4-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/[\365-\367].../", "&#65533;", $string);
        // 5-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/[\370-\373]..../", "&#65533;", $string);
        // 6-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/[\374-\375]...../", "&#65533;", $string);
        // undefined bytes
    $string = preg_replace("/[\376-\377]/", "&#65533;", $string);

    // reject consecutive start-bytes
    $string = preg_replace("/[\302-\364]{2,}/", "&#65533;", $string);

    // decode four byte unicode characters
    $string = preg_replace(
        "/([\360-\364])([\200-\277])([\200-\277])([\200-\277])/e",
        "'&#'.((ord('\\1')&7)<<18 | (ord('\\2')&63)<<12 |" .
        " (ord('\\3')&63)<<6 | (ord('\\4')&63)).';'",
    $string);

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
"'&#'.((ord('\\1')&15)<<12 | (ord('\\2')&63)<<6 | (ord('\\3')&63)).';'",
    $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
    "'&#'.((ord('\\1')&31)<<6 | (ord('\\2')&63)).';'",
    $string);

    // reject leftover continuation bytes
    $string = preg_replace("/[\200-\277]/", "&#65533;", $string);

    return $string;
}
?>

Warning: only a bit of accidental testing was done with invalid UTF-8 input, and the result wasn't closely analyzed.  But valid UTF-8 doesn't seem to be mangled at all.
mkluczka at gmail dot com 16-Sep-2010 04:36
In jQuery AJAX requests, latin2 specific chars have 2B length, and common chars have 1B length.

PHP functions for UTF8->latin2 conversion didn't work for me, so I wrote this simple function
to convert from jQuery AJAX encoding to ISO-8859-2 (latin2).

<?php
function jquery2iso($in)
{
  $CONV = array();
  $CONV['c4']['85'] = 'Д…';
  $CONV['c4']['84'] = 'Д„';
  $CONV['c4']['87'] = 'Д‡';
  $CONV['c4']['86'] = 'Д†';
  $CONV['c4']['99'] = 'Д™';
  $CONV['c4']['98'] = 'Д';
  $CONV['c5']['82'] = 'Е‚';
  $CONV['c5']['81'] = 'ЕЃ';
  $CONV['c4']['84'] = 'Е„';
  $CONV['c4']['83'] = 'Еѓ';
  $CONV['c3']['b3'] = 'Гі';
  $CONV['c3']['93'] = 'Г“';
  $CONV['c5']['9b'] = 'Е›';
  $CONV['c5']['9a'] = 'Ељ';
  $CONV['c5']['ba'] = 'Еє';
  $CONV['c5']['b9'] = 'Е№';
  $CONV['c5']['bc'] = 'Еј';
  $CONV['c5']['bb'] = 'Е»';

  $i=0;
  $out = '';
  while($i<strlen($in))
  {
    if(array_key_exists(bin2hex($in[$i]), $CONV))
    {
      $out .= $CONV[bin2hex($in[$i])][bin2hex($in[$i+1])];
      $i += 2;
    }
    else
    {
      $out .= $in[$i];
      $i += 1;
    }
  }

  return $out;
}

?>
andrew 25-Nov-2009 08:13
a simple function to convert encoding that appears mixed.

<?php
$trans = new Latin1UTF8();

$mixed = "MIXED TEXT INPUT";

print "Original: ".$mixed;
print "Latin1:   ".$trans->mixed_to_latin1($mixed);
print "UTF-8:    ".$trans->mixed_to_utf8($mixed);

class Latin1UTF8 {

    private $latin1_to_utf8;
    private $utf8_to_latin1;
    public function __construct() {
        for($i=32; $i<=255; $i++) {
            $this->latin1_to_utf8[chr($i)] = utf8_encode(chr($i));
            $this->utf8_to_latin1[utf8_encode(chr($i))] = chr($i);
        }
    }

    public function mixed_to_latin1($text) {
        foreach( $this->utf8_to_latin1 as $key => $val ) {
            $text = str_replace($key, $val, $text);
        }
        return $text;
    }

    public function mixed_to_utf8($text) {
        return utf8_encode($this->mixed_to_latin1($text));
    }
}
?>
Anonymous 08-Aug-2009 02:25
In addition to Blackbit's note below, here's my shot at converting UTF-8 strings to HTML entities.

<?php $encoded = preg_replace('/([\200-\277])/e', "'&#'.(ord('\\1')).';'", $utf8str); ?>

This code converts one byte UTF-8 to HTML entities while below you'll find conversions for two byte and three byte UTF-8.
Johan K 27-Jul-2009 07:53
If you simply need to decode a previously numerically escaped string (for example "This is \xC3encoded\xAF - now what?") into its literal (unencoded) representation:

<?php
preg_replace("#(\\\x[0-9A-F]{2})#e", "chr(hexdec('\\1'))", $string);
?>

PS: note the miraculous escaping of \x in the regex as \\\x (!)
pedro at pontonet dot com 05-May-2009 03:25
I've modified above utf8_array_decode to utf8_array_encode. The main difference is the later encodes a multi-dimension array.

Here goes the code:

<?php
function utf8_array_encode($input)
{
    $return = array();

    foreach ($input as $key => $val)
    {
        if( is_array($val) )
        {
            $return[$key] = utf8_array_encode($val);
        }
        else
        {
            $return[$key] = utf8_encode($val);
        }
    }
    return $return;
}
?>

Enjoy it!

Pedro Bastos
ytak at gmx dot net 30-Jan-2009 09:35
If you running Gentoo Linux and encounter problems with some PHP5 applications saying:
Call to undefined function: utf8_decode()
Try reemerge PHP4 with 'xml' flag enabled.
info at vanylla dot it 26-Jan-2009 12:21
IMPORTANT: when converting UTF8 data that contains the EURO sign DON'T USE utf_decode function.

utf_decode converts the data into ISO-8859-1 charset. But ISO-8859-1 charset does not contain the EURO sign, therefor the EURO sign will be converted into a question mark character '?'

In order to convert properly UTF8 data with EURO sign you must use:

iconv("UTF-8", "CP1252", $data)
Blackbit 12-Aug-2008 04:40
Squirrelmail contains a nice function in the sources to convert unicode to entities:

<?php
function charset_decode_utf_8 ($string) {
      /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",        \
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",    \
    $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e", \
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'", \
    $string);

    return $string;
}
?>
punchivan at gmail dot com 24-Jun-2008 02:13
EY! the bug is not in the function 'utf8_decode'. The bug is in the function 'mb_detect_encoding'. If you put a word with a special char at the end like this 'accentuГ©', that will lead to a wrong result (UTF-8) but if you put another char at the end like this 'accentuГ©e' you will get it right. So you should always add a ISO-8859-1 character to your string for this check. My advise is to use a blank space.
IВґve tried it and it works!

function ISO_convert($array)
{
    $array_temp = array();

    foreach($array as $name => $value)
    {
        if(is_array($value))
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = ISO_convert($value);
        else
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = (mb_detect_encoding($value." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($value) : $value );
    }

    return $array_temp;
}
webmaster at lapstore dot de 19-Jun-2008 08:11
[EDITED BY cataphract AT php DOT net - NOTE: This has been fixed
in PHP 5.3.4 and 5.2.15.]

Warning!
This function contains a possible security risk when you try to convert escaped strings (see addslashes() and related functions).
It reacts nasty on broken multibyte sequences. In UTF-8, follow-up bytes ALWAYS have the binary pattern 10xxxxxx, but this fact is not handled by utf8_decode in the way you would expect: If you pass a start byte (110xxxxx, 1110xxxx, 11110xxx - or even invalid sequences like 11111100), followed by one or more non-multibyte chars (0xxxxxxx), the start sequence "char" will be replaced by '?' (0x3F) and up to three following chars will disappear even if they are single-byte-chars (0xxxxxxx). So if you escape a string with a typical escape char like backslash, you would expect that your escaping would always survive a call to utf8decode because the escape char is in the assumed safe ascii range 0-127, but that is NOT the case!
Try things like utf8_decode("test: Гј\\\"123456") to check it out.
To avoid problems take care that string-escaping always is the last step of data manipulation when you depend on leak-proof escaping.
juantxito at example dot com 28-May-2008 01:26
To decode the values and the keys, i think this would work

 function utf8_array_decode($input){

    $return = array();

        foreach ($input as $key => $val) {
        $k = utf8_decode($key);
                $return[$k] = utf8_decode($val);
            }
            return $return;
        }
phpnet at freshsite dot de 09-May-2008 01:08
I didn't find an utf8_array_decode. This one only decodes the values, not the keys.

        function utf8_array_decode($input){
            foreach ($input as $key => $val) {
                $input[$key] = utf8_decode($val);
            }
            return $input;
        }
haugas at gmail dot com 08-May-2008 02:11
If you don't know exactly, how many times your string is encoded, you can use this function:

<?php

function _utf8_decode($string)
{
  $tmp = $string;
  $count = 0;
  while (mb_detect_encoding($tmp)=="UTF-8")
  {
    $tmp = utf8_decode($tmp);
    $count++;
  }

  for ($i = 0; $i < $count-1 ; $i++)
  {
    $string = utf8_decode($string);

  }
  return $string;

}

?>
lukasz dot mlodzik at gmail dot com 05-Mar-2008 04:46
Update to MARC13 function utf2iso()
I'm using it to handle AJAX POST calls.
Despite using
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'; charset='utf-8');
it still code Polish letters using UTF-16

This is only for Polish letters:

<?php
function utf16_2_utf8 ($nowytekst) {
        $nowytekst = str_replace('%u0104','Д„',$nowytekst);    //Д„
        $nowytekst = str_replace('%u0106','Д†',$nowytekst);    //Д†
        $nowytekst = str_replace('%u0118','Д',$nowytekst);    //Д
        $nowytekst = str_replace('%u0141','ЕЃ',$nowytekst);    //ЕЃ
        $nowytekst = str_replace('%u0143','Еѓ',$nowytekst);    //Еѓ
        $nowytekst = str_replace('%u00D3','Г“',$nowytekst);    //Г“
        $nowytekst = str_replace('%u015A','Ељ',$nowytekst);    //Ељ
        $nowytekst = str_replace('%u0179','Е№',$nowytekst);    //Е№
        $nowytekst = str_replace('%u017B','Е»',$nowytekst);    //Е»

        $nowytekst = str_replace('%u0105','Д…',$nowytekst);    //Д…
        $nowytekst = str_replace('%u0107','Д‡',$nowytekst);    //Д‡
        $nowytekst = str_replace('%u0119','Д™',$nowytekst);    //Д™
        $nowytekst = str_replace('%u0142','Е‚',$nowytekst);    //Е‚
        $nowytekst = str_replace('%u0144','Е„',$nowytekst);    //Е„
        $nowytekst = str_replace('%u00F3','Гі',$nowytekst);    //Гі
        $nowytekst = str_replace('%u015B','Е›',$nowytekst);    //Е›
        $nowytekst = str_replace('%u017A','Еє',$nowytekst);    //Еє
        $nowytekst = str_replace('%u017C','Еј',$nowytekst);    //Еј
   return ($nowytekst);
   }
?>

Everything goes smooth, but it doesn't change '%u00D3','Г“' and '%u00F3','Гі'. I dont have idea what to do with that.

Remember! File must be saved in UTF-8 coding.
tacchete at gmail dot com 13-Dec-2007 04:36
Known problem with Byte Order Mark (BOM) and header() in pages of a site.

For example at sending headings or to a dynamic conclusion in other coding distinct from UTF-8 by means of XSLT (<xsl:output encoding="windows-1251"/>).

To clean all symbols BOM from the text of page:

1. exclude BOM from the main file;
2. write down function of a return call for the buffer

<?php
header('content-type: text/html; charset: utf-8');
ob_start('ob');
function ob($buffer)
{
    return str_replace("\xef\xbb\xbf", '', $buffer);
}
?>

it will exclude BOM from a code of the connected files;
3. do not experience for BOM in connected files;
4. be pleased.
ludvig dot ericson at gmail dot com 15-Jul-2007 10:52
A better way to convert would be to use iconv, see http://www.php.net/iconv -- example:

<?php
$myUnicodeString = "Г…Г¤Г¶";
echo iconv("UTF-8", "ISO-8859-1", $myUnicodeString);
?>

Above would echo out the given variable in ISO-8859-1 encoding, you may replace it with whatever you prefer.

Another solution to the issue of misdisplayed glyphs is to simply send the document as UTF-8, and of course send UTF-8 data:

<?php
# Replace text/html with whatever MIME-type you prefer.
header("Content-Type: text/html; charset=utf-8");
?>
MARC13 07-Jul-2007 07:50
I did this function to convert data from AJAX call to insert to my database.
It converts UTF-8 from XMLHttpRequest() to ISO-8859-2 that I use in LATIN2 MySQL database.

<?php
function utf2iso($tekst)
{
        $nowytekst = str_replace("%u0104","\xA1",$tekst);    //Д„
        $nowytekst = str_replace("%u0106","\xC6",$nowytekst);    //Д†
        $nowytekst = str_replace("%u0118","\xCA",$nowytekst);    //Д
        $nowytekst = str_replace("%u0141","\xA3",$nowytekst);    //ЕЃ
        $nowytekst = str_replace("%u0143","\xD1",$nowytekst);    //Еѓ
        $nowytekst = str_replace("%u00D3","\xD3",$nowytekst);    //Г“
        $nowytekst = str_replace("%u015A","\xA6",$nowytekst);    //Ељ
        $nowytekst = str_replace("%u0179","\xAC",$nowytekst);    //Е№
        $nowytekst = str_replace("%u017B","\xAF",$nowytekst);    //Е»

        $nowytekst = str_replace("%u0105","\xB1",$nowytekst);    //Д…
        $nowytekst = str_replace("%u0107","\xE6",$nowytekst);    //Д‡
        $nowytekst = str_replace("%u0119","\xEA",$nowytekst);    //Д™
        $nowytekst = str_replace("%u0142","\xB3",$nowytekst);    //Е‚
        $nowytekst = str_replace("%u0144","\xF1",$nowytekst);    //Е„
        $nowytekst = str_replace("%u00D4","\xF3",$nowytekst);    //Гі
        $nowytekst = str_replace("%u015B","\xB6",$nowytekst);    //Е›
        $nowytekst = str_replace("%u017A","\xBC",$nowytekst);    //Еє
        $nowytekst = str_replace("%u017C","\xBF",$nowytekst);    //Еј

    return ($nowytekst);
}
?>

In my case also the code file that deals with AJAX calls must be in UTF-8 coding.
visus at portsonline dot net 23-Jun-2007 09:08
Following code helped me with mixed (UTF8+ISO-8859-1(x)) encodings. In this case, I have template files made and maintained by designers who do not care about encoding and MySQL data in utf8_binary_ci encoded tables.

<?php

class Helper
{
    function strSplit($text, $split = 1)
    {
        if (!is_string($text)) return false;
        if (!is_numeric($split) && $split < 1) return false;

        $len = strlen($text);

        $array = array();

        $i = 0;

        while ($i < $len)
        {
            $key = NULL;

            for ($j = 0; $j < $split; $j += 1)
            {
                $key .= $text{$i};

                $i += 1;
            }

            $array[] = $key;
        }

        return $array;
    }

    function UTF8ToHTML($str)
    {
        $search = array();
        $search[] = "/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e";
        $search[] = "/&#228;/";
        $search[] = "/&#246;/";
        $search[] = "/&#252;/";
        $search[] = "/&#196;/";
        $search[] = "/&#214;/";
        $search[] = "/&#220;/";
        $search[] = "/&#223;/";

        $replace = array();
        $replace[] = 'Helper::_UTF8ToHTML("\\1")';
        $replace[] = "Г¤";
        $replace[] = "Г¶";
        $replace[] = "Гј";
        $replace[] = "Г„";
        $replace[] = "Г–";
        $replace[] = "Гј";
        $replace[] = "Гџ";

        $str = preg_replace($search, $replace, $str);

        return $str;
    }

    function _UTF8ToHTML($str)
    {
        $ret = 0;

        foreach((Helper::strSplit(strrev(chr((ord($str{0}) % 252 % 248 % 240 % 224 % 192) + 128).substr($str, 1)))) as $k => $v)
            $ret += (ord($v) % 128) * pow(64, $k);
        return "&#".$ret.";";
    }
}

// Usage example:

$tpl = file_get_contents("template.tpl");
/* ... */
$row = mysql_fetch_assoc($result);

print(Helper::UTF8ToHTML(str_replace("{VAR}", $row['var'], $tpl)));

?>
luka8088 at gmail dot com 22-Jun-2007 07:03
simple UTF-8 to HTML conversion:

function utf8_to_html ($data)
    {
    return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '_utf8_to_html("\\1")', $data);
    }

function _utf8_to_html ($data)
    {
    $ret = 0;
    foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)
        $ret += (ord($v) % 128) * pow(64, $k);
    return "&#$ret;";
    }

Example:
echo utf8_to_html("a b ДЌ Д‡ Еѕ гЃ“ гЃ« гЃЎ г‚Џ ()[]{}!#$?*");

Output:
a b &#269; &#263; &#382; &#12371; &#12395; &#12385; &#12431; ()[]{}!#$?*
Sadi 13-Jun-2007 03:38
Once again about polish letters. If you use fananf's solution, make sure that PHP file is coded with cp1250 or else it won't work. It's quite obvious, however I spent some time before I finally figured that out, so I thought I post it here.
alexlevin at kvadro dot net 20-May-2007 08:20
If you running Gentoo Linux and encounter problems with some PHP4 applications saying:
Call to undefined function: utf8_decode()
Try reemerge PHP4 with 'expat' flag enabled.
ahmed dot adaileh at gmail dot com 08-Mar-2007 03:32
I searched a lot everywhere to find a suitable function which converts my UTF8 characters to the windows-1250 charset for Polish language, but couldn't find anything :(

Following is a function which does that:

function show_polish ($text) {
 $text = str_replace("Г„вЂћ", '&#260;', $text); //Д„
 $text = str_replace("Г„вЂ ", '&#262;', $text); //Д†
 $text = str_replace("Г„Лњ", '&#280;', $text); //Д
 $text = str_replace("Г…ВЃ", '&#321;', $text); //ЕЃ
 $text = str_replace("Г…Ж’", '&#323;', $text); //Еѓ
 $text = str_replace("ГѓвЂњ", '&#211;', $text); //Г“
 $text = str_replace("Г…ЕЎ", '&#346;', $text); //Ељ
 $text = str_replace("Г…В№", '&#377;', $text); //Е№
 $text = str_replace("Г…В»", '&#379;', $text); //Е»
 $text = str_replace("Г„вЂ¦", '&#261;', $text); //Д…
 $text = str_replace("Г„вЂЎ", '&#263;', $text); //Д‡
 $text = str_replace("Г„в„ў", '&#281;', $text); //Д™
 $text = str_replace("Г…вЂљ", '&#322;', $text); //Е‚
 $text = str_replace("Г…вЂћ", '&#324;', $text); //Е„
 $text = str_replace("ГѓВі", '&#243;', $text); //Гі
 $text = str_replace("Г…вЂє", '&#347;', $text); //Е›
 $text = str_replace("Г…Вє", '&#378;', $text); //Еє
 $text = str_replace("Г…Вј", '&#380;', $text); //Еј

return $text;
}

You can refer to http://hermes.umcs.lublin.pl/~awmarcz/awm/info/pl-codes.htm
if you want to use HTML hex. code rather than HTML dec. code which I used in my function.
fananf at nerdshack dot com 05-Mar-2007 07:22
Comment to AJGORS reply from 28-Dec-2006 02:38:

You have used twice "Еј" instead of "Еє".

Correct code should be:

ISO version:

function utf82iso88592($text) {
 $text = str_replace("\xC4\x85", 'В±', $text);
 $text = str_replace("\xC4\x84", 'Л‡', $text);
 $text = str_replace("\xC4\x87", 'Д‡', $text);
 $text = str_replace("\xC4\x86", 'Д†', $text);
 $text = str_replace("\xC4\x99", 'Д™', $text);
 $text = str_replace("\xC4\x98", 'Д', $text);
 $text = str_replace("\xC5\x82", 'Е‚', $text);
 $text = str_replace("\xC5\x81", 'ЕЃ', $text);
 $text = str_replace("\xC3\xB3", 'Гі', $text);
 $text = str_replace("\xC3\x93", 'Г“', $text);
 $text = str_replace("\xC5\x9B", 'В¶', $text);
 $text = str_replace("\xC5\x9A", 'В¦', $text);
 $text = str_replace("\xC5\xBC", 'Еј', $text);
 $text = str_replace("\xC5\xBB", 'Е»', $text);
 $text = str_replace("\xC5\xBA", 'ДЅ', $text);
 $text = str_replace("\xC5\xB9", 'В¬', $text);
 $text = str_replace("\xc5\x84", 'Е„', $text);
 $text = str_replace("\xc5\x83", 'Еѓ', $text);

return $text;
}

CP version:

function utf82iso88592($text) {
 $text = str_replace("\xC4\x85", 'Д…', $text);
 $text = str_replace("\xC4\x84", 'Д„', $text);
 $text = str_replace("\xC4\x87", 'Д‡', $text);
 $text = str_replace("\xC4\x86", 'Д†', $text);
 $text = str_replace("\xC4\x99", 'Д™', $text);
 $text = str_replace("\xC4\x98", 'Д', $text);
 $text = str_replace("\xC5\x82", 'Е‚', $text);
 $text = str_replace("\xC5\x81", 'ЕЃ', $text);
 $text = str_replace("\xC3\xB3", 'Гі', $text);
 $text = str_replace("\xC3\x93", 'Г“', $text);
 $text = str_replace("\xC5\x9B", 'Е›', $text);
 $text = str_replace("\xC5\x9A", 'Ељ', $text);
 $text = str_replace("\xC5\xBC", 'Еј', $text);
 $text = str_replace("\xC5\xBB", 'Е»', $text);
 $text = str_replace("\xC5\xBA", 'Еє', $text);
 $text = str_replace("\xC5\xB9", 'Е№', $text);
 $text = str_replace("\xc5\x84", 'Е„', $text);
 $text = str_replace("\xc5\x83", 'Еѓ', $text);

return $text;
}
sam 06-Feb-2007 08:20
In addition to yannikh's note, to convert a hex utf8 string

<?php

echo utf8_decode("\x61\xc3\xb6\x61");
// works as expected

$abc="61c3b661";
$newstr = "";
$l = strlen($abc);
for ($i=0;$i<$l;$i+=2){
    $newstr .= "\x".$abc[$i].$abc[$i+1];
}
echo utf8_decode($newstr);
// or varieties  of "\x": "\\x" etc does NOT output what you want

echo utf8_decode(pack('H*',$abc));
// this outputs the correct string, like the first line.

?>
Ajgor 28-Dec-2006 05:38
small upgrade for polish decoding:

function utf82iso88592($text) {
 $text = str_replace("\xC4\x85", 'Д…', $text);
 $text = str_replace("\xC4\x84", 'Д„', $text);
 $text = str_replace("\xC4\x87", 'Д‡', $text);
 $text = str_replace("\xC4\x86", 'Д†', $text);
 $text = str_replace("\xC4\x99", 'Д™', $text);
 $text = str_replace("\xC4\x98", 'Д', $text);
 $text = str_replace("\xC5\x82", 'Е‚', $text);
 $text = str_replace("\xC5\x81", 'ЕЃ', $text);
 $text = str_replace("\xC3\xB3", 'Гі', $text);
 $text = str_replace("\xC3\x93", 'Г“', $text);
 $text = str_replace("\xC5\x9B", 'Е›', $text);
 $text = str_replace("\xC5\x9A", 'Ељ', $text);
 $text = str_replace("\xC5\xBC", 'Еј', $text);
 $text = str_replace("\xC5\xBB", 'Е»', $text);
 $text = str_replace("\xC5\xBA", 'Еј', $text);
 $text = str_replace("\xC5\xB9", 'Е»', $text);
 $text = str_replace("\xc5\x84", 'Е„', $text);
 $text = str_replace("\xc5\x83", 'Еѓ', $text);

return $text;
} // utf82iso88592
paul.hayes at entropedia.co.uk 27-Oct-2006 07:10
I noticed that the utf-8 to html functions below are only for 2 byte long codes. Well I wanted 3 byte support (sorry haven't done 4, 5 or 6). Also I noticed the concatination of the character codes did have the hex prefix 0x and so failed with the large 2 byte codes)

<?
  public function utf2html (&$str) {

    $ret = "";
    $max = strlen($str);
    $last = 0;  // keeps the index of the last regular character
    for ($i=0; $i<$max; $i++) {
        $c = $str{$i};
        $c1 = ord($c);
        if ($c1>>5 == 6) {  // 110x xxxx, 110 prefix for 2 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c1 &= 31; // remove the 3 bit two bytes prefix
            $c2 = ord($str{++$i}); // the next byte
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
            $c1 >>= 2; // c1 shifts 2 to the right
            $ret .= "&#" . ($c1 * 0x100 + $c2) . ";"; // this is the fastest string concatenation
            $last = $i+1;
        }
        elseif ($c1>>4 == 14) {  // 1110 xxxx, 110 prefix for 3 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c2 = ord($str{++$i}); // the next byte
            $c3 = ord($str{++$i}); // the third byte
            $c1 &= 15; // remove the 4 bit three bytes prefix
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 |= (($c2 & 3) << 6); // last 2 bits of c2 become first 2 of c3
            $c2 >>=2; //c2 shifts 2 to the right
            $c2 |= (($c1 & 15) << 4); // last 4 bits of c1 become first 4 of c2
            $c1 >>= 4; // c1 shifts 4 to the right
            $ret .= '&#' . (($c1 * 0x10000) + ($c2 * 0x100) + $c3) . ';'; // this is the fastest string concatenation
            $last = $i+1;
        }
    }
    $str=$ret . substr($str, $last, $i); // append the last batch of regular characters
}
?>
tobias at code-x dot de 20-Oct-2006 05:13
converting uft8-html sign &#301; to uft8

<?
function uft8html2utf8( $s ) {
        if ( !function_exists('uft8html2utf8_callback') ) {
             function uft8html2utf8_callback($t) {
                     $dec = $t[1];
            if ($dec < 128) {
              $utf = chr($dec);
            } else if ($dec < 2048) {
              $utf = chr(192 + (($dec - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            } else {
              $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
              $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            }
            return $utf;
             }
        }
        return preg_replace_callback('|&#([0-9]{1,});|', 'uft8html2utf8_callback', $s );
}
echo uft8html2utf8('test: &#301;');
?>
e dot panzyk at panzyk dot net 04-Oct-2006 02:38
enhanced UTF8-Decoder

After recognising that UTF8-Decode converts some French Characters to "?" i end with that Function.

The space will be need when a String ends with a converted Char ( a buggy Php Function will fit a /hex00 char at the End )

function utf8dec ( $s_String )
    {
    $s_String = html_entity_decode(htmlentities($s_String." ", ENT_COMPAT, 'UTF-8'));
    return substr($s_String, 0, strlen($s_String)-1);
    }

Hope it helps ... cost me a lot of time ...
michael at calwell-computing dot co dot uk 04-Oct-2006 01:15
I found that trying to put Javascript strings into a pre MySQL 4.0 database was creating problems with strange chars in the database. Closer inspection revealed that utf8 is the default character set for Javascript, which cannot be handled by the db. This function was invaluable.
ethaizone [AT] hotmail [DOT] com 01-Aug-2006 10:11
This function I use convert UTF-8 to Thai font (iso-8859-11).
It from iso8859_11toUTF8 function [Suttichai Mesaard-www.ceforce.com] at utf8_encode page.

It useful for translate string from mod_rewrite to real url.
I makes SEO Url In Thai language.

<?php
function UTF8toiso8859_11($string) {

     if ( ! ereg("[\241-\377]", $string) )
         return $string;

     $UTF8 = array(
"\xe0\xb8\x81" => "\xa1",
"\xe0\xb8\x82" => "\xa2",
"\xe0\xb8\x83" => "\xa3",
"\xe0\xb8\x84" => "\xa4",
"\xe0\xb8\x85" => "\xa5",
"\xe0\xb8\x86" => "\xa6",
"\xe0\xb8\x87" => "\xa7",
"\xe0\xb8\x88" => "\xa8",
"\xe0\xb8\x89" => "\xa9",
"\xe0\xb8\x8a" => "\xaa",
"\xe0\xb8\x8b" => "\xab",
"\xe0\xb8\x8c" => "\xac",
"\xe0\xb8\x8d" => "\xad",
"\xe0\xb8\x8e" => "\xae",
"\xe0\xb8\x8f" => "\xaf",
"\xe0\xb8\x90" => "\xb0",
"\xe0\xb8\x91" => "\xb1",
"\xe0\xb8\x92" => "\xb2",
"\xe0\xb8\x93" => "\xb3",
"\xe0\xb8\x94" => "\xb4",
"\xe0\xb8\x95" => "\xb5",
"\xe0\xb8\x96" => "\xb6",
"\xe0\xb8\x97" => "\xb7",
"\xe0\xb8\x98" => "\xb8",
"\xe0\xb8\x99" => "\xb9",
"\xe0\xb8\x9a" => "\xba",
"\xe0\xb8\x9b" => "\xbb",
"\xe0\xb8\x9c" => "\xbc",
"\xe0\xb8\x9d" => "\xbd",
"\xe0\xb8\x9e" => "\xbe",
"\xe0\xb8\x9f" => "\xbf",
"\xe0\xb8\xa0" => "\xc0",
"\xe0\xb8\xa1" => "\xc1",
"\xe0\xb8\xa2" => "\xc2",
"\xe0\xb8\xa3" => "\xc3",
"\xe0\xb8\xa4" => "\xc4",
"\xe0\xb8\xa5" => "\xc5",
"\xe0\xb8\xa6" => "\xc6",
"\xe0\xb8\xa7" => "\xc7",
"\xe0\xb8\xa8" => "\xc8",
"\xe0\xb8\xa9" => "\xc9",
"\xe0\xb8\xaa" => "\xca",
"\xe0\xb8\xab" => "\xcb",
"\xe0\xb8\xac" => "\xcc",
"\xe0\xb8\xad" => "\xcd",
"\xe0\xb8\xae" => "\xce",
"\xe0\xb8\xaf" => "\xcf",
"\xe0\xb8\xb0" => "\xd0",
"\xe0\xb8\xb1" => "\xd1",
"\xe0\xb8\xb2" => "\xd2",
"\xe0\xb8\xb3" => "\xd3",
"\xe0\xb8\xb4" => "\xd4",
"\xe0\xb8\xb5" => "\xd5",
"\xe0\xb8\xb6" => "\xd6",
"\xe0\xb8\xb7" => "\xd7",
"\xe0\xb8\xb8" => "\xd8",
"\xe0\xb8\xb9" => "\xd9",
"\xe0\xb8\xba" => "\xda",
"\xe0\xb8\xbf" => "\xdf",
"\xe0\xb9\x80" => "\xe0",
"\xe0\xb9\x81" => "\xe1",
"\xe0\xb9\x82" => "\xe2",
"\xe0\xb9\x83" => "\xe3",
"\xe0\xb9\x84" => "\xe4",
"\xe0\xb9\x85" => "\xe5",
"\xe0\xb9\x86" => "\xe6",
"\xe0\xb9\x87" => "\xe7",
"\xe0\xb9\x88" => "\xe8",
"\xe0\xb9\x89" => "\xe9",
"\xe0\xb9\x8a" => "\xea",
"\xe0\xb9\x8b" => "\xeb",
"\xe0\xb9\x8c" => "\xec",
"\xe0\xb9\x8d" => "\xed",
"\xe0\xb9\x8e" => "\xee",
"\xe0\xb9\x8f" => "\xef",
"\xe0\xb9\x90" => "\xf0",
"\xe0\xb9\x91" => "\xf1",
"\xe0\xb9\x92" => "\xf2",
"\xe0\xb9\x93" => "\xf3",
"\xe0\xb9\x94" => "\xf4",
"\xe0\xb9\x95" => "\xf5",
"\xe0\xb9\x96" => "\xf6",
"\xe0\xb9\x97" => "\xf7",
"\xe0\xb9\x98" => "\xf8",
"\xe0\xb9\x99" => "\xf9",
"\xe0\xb9\x9a" => "\xfa",
"\xe0\xb9\x9b" => "\xfb",
 );

     $string=strtr($string,$UTF8);
     return $string;
 }
?>

Jo, EThaiZone.Com
2ge at NO2geSPAM dot us 26-Jan-2006 01:00
Hello all,

I like to use COOL (nice) URIs, example: http://example.com/try-something
I'm using UTF8 as input, so I have to write a function UTF8toASCII to have nice URI. Here is what I come with:

<?php
function urlize($url) {
 $search = array('/[^a-z0-9]/', '/--+/', '/^-+/', '/-+$/' );
 $replace = array( '-', '-', '', '');
 return preg_replace($search, $replace, utf2ascii($url));
}

function utf2ascii($string) {
 $iso88591  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7";
 $iso88591 .= "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
 $iso88591 .= "\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF7";
 $iso88591 .= "\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF";
 $ascii = "aaaaaaaceeeeiiiidnooooooouuuuyyy";
 return strtr(mb_strtolower(utf8_decode($string), 'ISO-8859-1'),$iso88591,$ascii);
}

echo urlize("Fucking дmдl");

?>

I hope this helps someone.
peter dot mescalchin at geemail dot com 26-Dec-2005 09:43
Adding to below I have a few more MS word characters that need replacing. Found this was required when "fixing" some phpmyadmin export scripts from a live server where MS word characters were all through the content - before importing them back into my local mySQL database.

The code I wrote for this process also does a strpos for any extra "\\xe2\\x80" strings - which are the tell-tale sign of any funny characters I want removed.

Here are my updated arrays()

<?php
$badchr = array(
    "\\xe2\\x80\\xa6",        // ellipsis
    "\\xe2\\x80\\x93",        // long dash
    "\\xe2\\x80\\x94",        // long dash
    "\\xe2\\x80\\x98",        // single quote opening
    "\\xe2\\x80\\x99",        // single quote closing
    "\\xe2\\x80\\x9c",        // double quote opening
    "\\xe2\\x80\\x9d",        // double quote closing
    "\\xe2\\x80\\xa2"        // dot used for bullet points
    );

$goodchr = array(
    '...',
    '-',
    '-',
    '\\'',
    '\\'',
    '"',
    '"',
    '*'
    );
?>
php-net at ---NOSPAM---lc dot yi dot org 08-Dec-2005 12:04
I've just created this code snippet to improve the user-customizable emails sent by one of my websites.

The goal was to use UTF-8 (Unicode) so that non-english users have all the Unicode benefits, BUT also make life seamless for English (or specifically, English MS-Outlook users).  The niggle: Outlook prior to 2003 (?)  does not properly detect unicode emails.  When "smart quotes" from MS Word were pasted into a rich text area and saved in Unicode, then sent by email to an Outlook user, more often than not, these characters were wrongly rendered as "greek".

So, the following code snippet replaces a few strategic characters into html entities which Outlook XP (and possibly earlier) will render as expected.  [Code based on bits of code from previous posts on this and the htmlenties page]
<?php
    $badwordchars=array(
        "\xe2\x80\x98", // left single quote
        "\xe2\x80\x99", // right single quote
        "\xe2\x80\x9c", // left double quote
        "\xe2\x80\x9d", // right double quote
        "\xe2\x80\x94", // em dash
        "\xe2\x80\xa6" // elipses
    );
    $fixedwordchars=array(
        "&#8216;",
        "&#8217;",
        '&#8220;',
        '&#8221;',
        '&mdash;',
        '&#8230;'
    );
    $html=str_replace($badwordchars,$fixedwordchars,$html);
?>
yannikh at gmeil dot com 07-Dec-2005 11:34
I had to tackle a very interesting problem:

I wanted to replace all \xXX in a text by it's letters. Unfortunatelly XX were ASCII and not utf8. I solved my problem that way:
<?php preg_replace ('/\\\\x([0-9a-fA-F]{2})/e', "pack('H*',utf8_decode('\\1'))",$v); ?>
thierry.bo # netcourrier point com 01-Oct-2005 12:53
to complete my previous test, here is the summarize with :

- if ($string == utf8_decode($string))
- if ($string == iconv('UTF-8', 'UTF-8', $string)

201 lines are valid UTF8 strings using phpnote regexp
203 lines are valid UTF8 strings using j.dittmer regexp
200 lines are valid UTF8 strings using fhoech regexp
239 lines are valid  UTF8 strings using using mb_detect_encoding
203 lines are valid  UTF 8 strings using using utf8_decode
224 lines are valid  UTF 8strings using using iconv

If we trust the file used for this test, no need to use a regexp, use XML::utf8_decode() to test your strings, you get the same detection chance as the three regexp tested, and XML Parser extension is almost always available, unlike Iconv and Multibyte String functions.
thierry.bo # netcourrier point com 30-Sep-2005 12:38
In response to fhoech (22-Sep-2005 11:55), I just tried a simultaneous test with the file UTF-8-test.txt using your regexp, 'j dot dittmer' (20-Sep-2005 06:30) regexp (message #56962), `php-note-2005` (17-Feb-2005 08:57) regexp in his message on `mb-detect-encoding` page (http://us3.php.net/manual/en/function.mb-detect-encoding.php#50087) who is using a regexp from the W3C (http://w3.org/International/questions/qa-forms-utf-8.html), and PHP mb_detect_encoding function.

Here are a summarize of the results :

201 lines are valid UTF8 strings using phpnote regexp
203 lines are valid UTF8 strings using j.dittmer regexp
200 lines are valid UTF8 strings using fhoech regexp
239 lines are valid  UTF8 strings using using mb_detect_encoding

Here are the lines with differences (left to right, phpnote, j.dittmer and fhoech) :

Line #70 : NOT UTF8|IS UTF8!|IS UTF8! :2.1.1 1 byte (U-00000000): ""
Line #79 : NOT UTF8|IS UTF8!|IS UTF8! :2.2.1 1 byte (U-0000007F): ""
Line #81 : IS UTF8!|IS UTF8!|NOT UTF8 :2.2.3 3 bytes (U-0000FFFF): "&#65535;" |
Line #267 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.1 U+FFFE = ef bf be = "&#65534;" |
Line #268 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.2 U+FFFF = ef bf bf = "&#65535;" |

Interesting is that you said that your regexp corrected j.dittmer regexp that failed on 5.3 section, but it my test I have the opposite result ?!

I ran this test on windows XP with PHP 4.3.11dev. Maybe these differences come from operating system, or PHP version.

For mb_detect_encoding I used the command :

mb_detect_encoding($line, 'UTF-8, ISO-8859-1, ASCII');
fhoech 22-Sep-2005 10:55
Sorry, I had a typo in my last comment. Corrected regexp:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbd]|
\\xee[\\x80-\\xbf]{2}|
\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$
fhoech 22-Sep-2005 10:12
JF Sebastian's regex is almost perfect as far as I'm concerned. I found one error (it failed section 5.3 "Other illegal code positions" from http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt) which I corrected as follows:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbc]|
\\xee[\\x80-\\xbf]{2}|
\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$

(Again, concatenate to one single line to make it work)
j dot dittmer at portrix dot net 20-Sep-2005 05:30
The regex in the last comment has some typos. This is a
syntactically valid one, don't know if it's correct though.
You've to concat the expression in one long line.

^(
[\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
[\xe0][\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
[\xed][\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
[\xf0][\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
[\xf4][\x80-\x8f][\x80-\xbf]{2}
)*$
chris at mrwsp dot com 09-Aug-2005 03:54
A small improvement.

JF Sebastian's regex for UTF-8 is not quite correct.  Because code points could otherwise be coded in more than one way using UTF-8, the Standard stipulates that the shortest possible representation for a character should be used.  So some 'duplicate' combinations his regex accepts are not valid UTF-8.  Additionally, his regex accepts characters beyond the valid Unicode code space.

The regex should be:

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
[\xe0][\xa0-\xbf][\x80-xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
[\xed][\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
[\xf0][\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
[\xf4][\x80-\x8f][\x80-\xbf]{2}*$)
miracle at balkansys dot com 14-Jun-2005 02:24
The best multilanguage library I have found is a part of a CMS system - typo3

http://www.typo3.org

It can convert from and to any charset + it does it by three methods - mbstring, iconv, or the raw way by scripts. It uses only one of these techniques - the fastest if available.

That was the only way I could make mysql 3.23 contain letters in almost any language, while maintaining my website in utf-8 only.
Vladimir Stwora, vlad4321 at fastmail dot fm 08-May-2005 03:41
If you want to convert utf-8 to ascii, you can use the following procedure:

<?php
function utf2ascii($string) {
   $string=iconv('utf-8','windows-1250',$string);
   $win  ='ћэбнйъ...';  // I was unable to paste here all set of characters, but you get the point
   $ascii='zyaieuu...';
   $string = StrTr($string,$win,$ascii);
   return $string;
  }
?>
This works based on the assumption that you know what language text (and thus what charset) you want to convert from. In the above example I am converting from an eastern European language, so I know I can safely use windows-1250 charset as an intermediem charset. You will have to adjust the charset based on your language.

Please remember that you have to save this file separately and it must be coded in the charset, which you will call within function iconv. Otherwise it will not work.
JF Sebastian 30-Mar-2005 07:09
The following Perl regular expression tests if a string is well-formed Unicode UTF-8 (Broken up after each | since long lines are not permitted here. Please join as a single line, no spaces, before use.):

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
\xe0[\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
\xed[\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
f0[\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
\xf4[\x80-\x8f][\x80-\xbf]{2})*$

NOTE: This strictly follows the Unicode standard 4.0, as described in chapter 3.9, table 3-6, "Well-formed UTF-8 byte sequences" ( http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G31703 ).

ISO-10646, a super-set of Unicode, uses UTF-8 (there called "UCS", see http://www.unicode.org/faq/utf_bom.html#1 ) in a relaxed variant that supports a 31-bit space encoded into up to six bytes instead of Unicode's 21 bits in up to four bytes. To check for ISO-10646 UTF-8, use the following Perl regular expression (again, broken up, see above):

^([\x00-\x7f]|
[\xc0-\xdf][\x80-\xbf]|
[\xe0-\xef][\x80-\xbf]{2}|
[\xf0-\xf7][\x80-\xbf]{3}|
[\xf8-\xfb][\x80-\xbf]{4}|
[\xfc-\xfd][\x80-\xbf]{5})*$

The following function may be used with above expressions for a quick UTF-8 test, e.g. to distinguish ISO-8859-1-data from UTF-8-data if submitted from a <form accept-charset="utf-8,iso-8859-1" method=..>.

function is_utf8($string) {
    return (preg_match('/[insert regular expression here]/', $string) === 1);
}
ivanmaz(remove) at mech dot math dot msu dot su 15-Mar-2005 03:50
Here is my variant of UTF8 to Cyrillic Win-1251 encoding convertor that replaces all characters but latin and Russian ones with &#...; entities:

function utf2win1251 ($s)
{
 $out = "";

 for ($i=0; $i<strlen($s); $i++)
 {
  $c1 = substr ($s, $i, 1);
  $byte1 = ord ($c1);
  if ($byte1>>5 == 6) // 110x xxxx, 110 prefix for 2 bytes unicode
  {
   $i++;
   $c2 = substr ($s, $i, 1);
   $byte2 = ord ($c2);
   $byte1 &= 31; // remove the 3 bit two bytes prefix
   $byte2 &= 63; // remove the 2 bit trailing byte prefix
   $byte2 |= (($byte1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
   $byte1 >>= 2; // c1 shifts 2 to the right

   $word = ($byte1<<8) + $byte2;
   if ($word==1025) $out .= chr(168);                    // Ё
   elseif ($word==1105) $out .= chr(184);                // ё
   elseif ($word>=0x0410 && $word<=0x044F) $out .= chr($word-848); // А-Я а-я
   else
   {
     $a = dechex($byte1);
     $a = str_pad($a, 2, "0", STR_PAD_LEFT);
     $b = dechex($byte2);
     $b = str_pad($b, 2, "0", STR_PAD_LEFT);
     $out .= "&#x".$a.$b.";";
   }
  }
  else
  {
   $out .= $c1;
  }
 }

 return $out;
}

The function is based on 2 other functions posted below.
I hope it will help those who convert UTF8-encoded text to Win-1251 to use it safely on Russian web pages (works fine in all browsers).
marcelo at maccoy dot com dot br 14-Feb-2005 10:24
function decode_utf8($str){
       # erase null signs in string
          $str=eregi_replace("^.{10,13}q\?","",$str);
       # paterns
           $pat = "/=([0-9A-F]{2})/";
           $cha="'.chr(hexdec(";
       # to decode with eval and replace
          eval("\$str='".
                  preg_replace($pat,$cha."'$1')).'",$str).
                  "';");
        # return
           return $str;
        }

Note:
It's possible put it in 3 lines, but I don't got in this first code submition.
husamb at maksimum dot net 27-Jan-2005 01:16
Hi, I collected the some scripts in this page and I written a new customizable script. You can switch easily iso type to convert. There are definitions in unicode.org page at http://www.unicode.org/Public/MAPPINGS/ISO8859/.

<?php
# GLOBAL VARIABLES
$url = "http://www.unicode.org/Public/MAPPINGS/ISO8859/8859-9.TXT";
//$url = "8859-9.txt";
$iso2utf = array();
$utf2iso = array();

# UNICODE MAPPING TABLE PARSING
function create_map($url){
    global $iso2utf, $utf2iso;
    $fl = @(file($url)) OR (die("cannot open file : $url\n"));
    for ($i=0; $i<count($fl); $i++){
        if($fl[$i][0] != '#' && trim($fl[$i])){
            list($iso, $uni, $s, $desc) = split("\t",$fl[$i]);
            $iso2utf[$iso] = $uni;
            $utf2iso[$uni] = $iso;
        }
    }
}

# FINDING UNICODE LETTER'S DECIMAL ASCII VALUE
function uniord($c){
    $ud = 0;
    if (ord($c{0})>=0 && ord($c{0})<=127)   $ud = $c{0};
    if (ord($c{0})>=192 && ord($c{0})<=223) $ud = (ord($c{0})-192)*64 + (ord($c{1})-128);
    if (ord($c{0})>=224 && ord($c{0})<=239) $ud = (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128);
    if (ord($c{0})>=240 && ord($c{0})<=247) $ud = (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128);
    if (ord($c{0})>=248 && ord($c{0})<=251) $ud = (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128);
    if (ord($c{0})>=252 && ord($c{0})<=253) $ud = (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128);
    if (ord($c{0})>=254 && ord($c{0})<=255) $ud = false; //error
    return $ud;
}

# PARSING UNICODE STRING
function utf2iso($source) {
    global $utf2iso;
    $pos = 0;
    $len = strlen ($source);
    $encodedString = '';

    while ($pos < $len) {
        $is_ascii = false;
        $asciiPos = ord (substr ($source, $pos, 1));
        if(($asciiPos >= 240) && ($asciiPos <= 255)) {
            // 4 chars representing one unicode character
            $thisLetter = substr ($source, $pos, 4);
            $thisLetterOrd = uniord($thisLetter);
            $pos += 4;
        }
        else if(($asciiPos >= 224) && ($asciiPos <= 239)) {
            // 3 chars representing one unicode character
            $thisLetter = substr ($source, $pos, 3);
            $thisLetterOrd = uniord($thisLetter);
            $pos += 3;
        }
        else if(($asciiPos >= 192) && ($asciiPos <= 223)) {
            // 2 chars representing one unicode character
            $thisLetter = substr ($source, $pos, 2);
            $thisLetterOrd = uniord($thisLetter);
            $pos += 2;
        }
        else{
            // 1 char (lower ascii)
            $thisLetter = substr ($source, $pos, 1);
            $thisLetterOrd = uniord($thisLetter);
            $pos += 1;
            $encodedString .= $thisLetterOrd;
            $is_ascii = true;
        }
        if(!$is_ascii){
            $hex = sprintf("%X", $thisLetterOrd);
            if(strlen($hex)<4) for($t=strlen($hex);$t<4;$t++)$hex = "0".$hex;
            $hex = "0x".$hex;
            $hex = $utf2iso[$hex];
            $hex = str_replace('0x','',$hex);
            $dec = hexdec($hex);
            $encodedString .= sprintf("%c", $dec);
        }
    }
    return $encodedString;
}

# CREATING ISO2UTF & UTF2ISO MAPS
create_map($url);

# TESTING
$unicode_string = "Ekonomi_ve_\xc4\xb0\xc5\x9f_D\xc3\xbcnyas\xc4\xb1";

echo "unicode string : <b>" . $unicode_string . "</b>";
echo "<br><br>";
echo "ISO8859 (latin5 / turkish) converted string : <b>" . utf2iso($unicode_string) . "</b>";
?>

The unicode string is turkish. ITs mean in english is 'Economy and Business World' :)

Husam
rasmus at flajm dot se 19-Jan-2005 02:57
If you don't have the multibyte extension installed, here's a function to decode UTF-16 encoded strings. It support both BOM-less and BOM'ed strings, (big- and little-endian byte order.)

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 *
 * @param   string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode( $str ) {
    if( strlen($str) < 2 ) return $str;
    $bom_be = true;
    $c0 = ord($str{0});
    $c1 = ord($str{1});
    if( $c0 == 0xfe && $c1 == 0xff ) { $str = substr($str,2); }
    elseif( $c0 == 0xff && $c1 == 0xfe ) { $str = substr($str,2); $bom_be = false; }
    $len = strlen($str);
    $newstr = '';
    for($i=0;$i<$len;$i+=2) {
        if( $bom_be ) { $val = ord($str{$i})   << 4; $val += ord($str{$i+1}); }
        else {        $val = ord($str{$i+1}) << 4; $val += ord($str{$i}); }
        $newstr .= ($val == 0x228) ? "\n" : chr($val);
    }
    return $newstr;
}
?>
dobersch at gmx dot net 04-Nov-2004 06:11
Sorry, there's an error in my previous comment, my error_reporting was not set to E_ALL ... so the notices disappeared...

It seems that those Google URLs are not only UTF-8 encoded, but after encoding, several values also get replaced. (cp1252 ?)

Just the way as described in following comments on the utf8_encode() page:
http://de3.php.net/manual/de/function.utf8-encode.php#44843 and
http://de3.php.net/manual/de/function.utf8-encode.php#45226

Below I post a solution for getting back the ISO-8859-1 encoded string from the encoded data, by turning the function from Aidan the other way around.

hope this time, everything is alright...

<?PHP
ini_set('error_reporting', E_ALL);
// map taken from http://de3.php.net/manual/de/function.utf8-encode.php#45226
$cp1252_map = array(
   "\xc2\x80" => "\xe2\x82\xac", /* EURO SIGN */
   "\xc2\x82" => "\xe2\x80\x9a", /* SINGLE LOW-9 QUOTATION MARK */
   "\xc2\x83" => "\xc6\x92",    /* LATIN SMALL LETTER F WITH HOOK */
   "\xc2\x84" => "\xe2\x80\x9e", /* DOUBLE LOW-9 QUOTATION MARK */
   "\xc2\x85" => "\xe2\x80\xa6", /* HORIZONTAL ELLIPSIS */
   "\xc2\x86" => "\xe2\x80\xa0", /* DAGGER */
   "\xc2\x87" => "\xe2\x80\xa1", /* DOUBLE DAGGER */
   "\xc2\x88" => "\xcb\x86",    /* MODIFIER LETTER CIRCUMFLEX ACCENT */
   "\xc2\x89" => "\xe2\x80\xb0", /* PER MILLE SIGN */
   "\xc2\x8a" => "\xc5\xa0",    /* LATIN CAPITAL LETTER S WITH CARON */
   "\xc2\x8b" => "\xe2\x80\xb9", /* SINGLE LEFT-POINTING ANGLE QUOTATION */
   "\xc2\x8c" => "\xc5\x92",    /* LATIN CAPITAL LIGATURE OE */
   "\xc2\x8e" => "\xc5\xbd",    /* LATIN CAPITAL LETTER Z WITH CARON */
   "\xc2\x91" => "\xe2\x80\x98", /* LEFT SINGLE QUOTATION MARK */
   "\xc2\x92" => "\xe2\x80\x99", /* RIGHT SINGLE QUOTATION MARK */
   "\xc2\x93" => "\xe2\x80\x9c", /* LEFT DOUBLE QUOTATION MARK */
   "\xc2\x94" => "\xe2\x80\x9d", /* RIGHT DOUBLE QUOTATION MARK */
   "\xc2\x95" => "\xe2\x80\xa2", /* BULLET */
   "\xc2\x96" => "\xe2\x80\x93", /* EN DASH */
   "\xc2\x97" => "\xe2\x80\x94", /* EM DASH */

   "\xc2\x98" => "\xcb\x9c",    /* SMALL TILDE */
   "\xc2\x99" => "\xe2\x84\xa2", /* TRADE MARK SIGN */
   "\xc2\x9a" => "\xc5\xa1",    /* LATIN SMALL LETTER S WITH CARON */
   "\xc2\x9b" => "\xe2\x80\xba", /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
   "\xc2\x9c" => "\xc5\x93",    /* LATIN SMALL LIGATURE OE */
   "\xc2\x9e" => "\xc5\xbe",    /* LATIN SMALL LETTER Z WITH CARON */
   "\xc2\x9f" => "\xc5\xb8"      /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
);

// I find this name a little misleading because the result won't be valid UTF8 data
function cp1252_to_utf8($str) {
   global $cp1252_map;
   return  strtr(utf8_encode($str), $cp1252_map);
}

function cp1252_utf8_to_iso($str) { // the other way around...
  global $cp1252_map;
  return  utf8_decode( strtr($str, array_flip($cp1252_map)) );
}

$euro = "\xe2\x82\xac";  // "google encoded" euro sign
$str = cp1252_utf8_to_iso($euro);

for($i=0; $i<strlen($str); $i++) {
  print '&quot;' . $str[$i] . '&quot; - ' . ord($str[$i]) . ' (decimal)<br />';
}
?>
vpribish at shopping dot com 10-Sep-2004 11:55
big thanks to wielspm and mittag for the function to convert wide utf to html.  I have altered your function to output decimal html entities which i hear are more widely supported.  Also I've optimized it, it is now twice as fast.

<?php
function utf2html ($str) {
$ret = "";
$max = strlen($str);
$last = 0;  // keeps the index of the last regular character
for ($i=0; $i<$max; $i++) {
 $c = $str{$i};
 $c1 = ord($c);
 if ($c1>>5 == 6) {   // 110x xxxx, 110 prefix for 2 bytes unicode
    $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
    $c1 &= 31; // remove the 3 bit two bytes prefix
    $c2 = ord($str{++$i}); // the next byte
    $c2 &= 63;  // remove the 2 bit trailing byte prefix
    $c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
    $c1 >>= 2; // c1 shifts 2 to the right
    $ret .= "&#" . ($c1 * 100 + $c2) . ";"; // this is the fastest string concatenation
    $last = $i+1;
 }
}
return $ret . substr($str, $last, $i); // append the last batch of regular characters
}
?>
Aidan Kehoe <php-manual at parhasard dot net> 31-Jan-2004 05:35
The fastest way I've found to check if something is valid UTF-8 is
<?php
if (iconv('UTF-8', 'UTF-8', $input) != $input) {
        /* It's not UTF-8--for me, it's probably CP1252, the Windows
           version of Latin 1, with directed quotation marks and
           the Euro sign.  */
}
 ?>.
The iconv() C library fails if it's told a string is UTF-8 and it isn't; the PHP one doesn't, it just returns the conversion up to the point of failure, so you have to compare the result to the input to find out if the conversion succeeded.
lg83news at free dot fr 28-Dec-2003 09:40
Here are some functions for converting UTF-8 to and from Latin 9 (aka ISO-8859-15), if your PHP file is encoded as UTF-8.

<?php
function latin9_to_utf8($latin9str) { // replaces utf8_encode()
    $trans = array("¤"=>"Ђ", "¦"=>"Љ", "Ё"=>"љ", "ґ"=>"Ћ", "ё"=>"ћ", "ј"=>"Њ", "Ѕ"=>"њ", "ѕ"=>"џ");
    $wrong_utf8str = utf8_encode($latin9str);
    $utf8str = strtr($wrong_utf8str, $trans);
    return $utf8str;
}
function utf8_to_latin9($utf8str) { // replaces utf8_decode()
    $trans = array("Ђ"=>"¤", "Љ"=>"¦", "љ"=>"Ё", "Ћ"=>"ґ", "ћ"=>"ё", "Њ"=>"ј", "њ"=>"Ѕ", "џ"=>"ѕ");
    $wrong_utf8str = strtr($utf8str, $trans);
    $latin9str = utf8_decode($wrong_utf8str);
    return $latin9str;
}
?>

Note: the above functions will not work if your PHP file is not encoded in UTF-8.

You can copy this binary data to your PHP file instead, it'll work with any encoding (including UTF-8) as long as you copy it as bytes, not characters:

<?php
function latin9_to_utf8($latin9str) { // replaces utf8_encode()
    $trans = array("В¤"=>"в‚¬", "В¦"=>"Е ", "ВЁ"=>"ЕЎ", "Вґ"=>"ЕЅ", "Вё"=>"Еѕ", "Вј"=>"Е’", "ВЅ"=>"Е“", "Вѕ"=>"Её");
    $wrong_utf8str = utf8_encode($latin9str);
    $utf8str = strtr($wrong_utf8str, $trans);
    return $utf8str;
}
function utf8_to_latin9($utf8str) { // replaces utf8_decode()
    $trans = array("в‚¬"=>"В¤", "Е "=>"В¦", "ЕЎ"=>"ВЁ", "ЕЅ"=>"Вґ", "Еѕ"=>"Вё", "Е’"=>"Вј", "Е“"=>"ВЅ", "Её"=>"Вѕ");
    $wrong_utf8str = strtr($utf8str, $trans);
    $latin9str = utf8_decode($wrong_utf8str);
    return $latin9str;
}
?>

(Note: the PHP manual is served as ISO-8859-1, but many of the bytes used here have no meaning in ISO-8859-1, so they'll probably be displayed as Windows-1252 if your using Windows, or garbage otherwise. Just copy the bytes!)
gto at interia dot pl 25-Nov-2003 07:12
Correction to function converting utf82iso88592 and iso88592tutf8.
Janusz forgot about "&#324;", and "&#380;" exchanged from "&#378;" here and there.

GTo

function utf82iso88592($tekscik) {
     $tekscik = str_replace("\xC4\x85", "&#261;", $tekscik);
     $tekscik = str_replace("\xC4\x84", '&#260;', $tekscik);
     $tekscik = str_replace("\xC4\x87", '&#263;', $tekscik);
     $tekscik = str_replace("\xC4\x86", '&#262;', $tekscik);
     $tekscik = str_replace("\xC4\x99", '&#281;', $tekscik);
     $tekscik = str_replace("\xC4\x98", '&#280;', $tekscik);
     $tekscik = str_replace("\xC5\x82", '&#322;', $tekscik);
     $tekscik = str_replace("\xC5\x81", '&#321;', $tekscik);
     $tekscik = str_replace("\xC5\x84", '&#324;', $tekscik);
     $tekscik = str_replace("\xC5\x83", '&#323;', $tekscik);
     $tekscik = str_replace("\xC3\xB3", 'у', $tekscik);
     $tekscik = str_replace("\xC3\x93", 'У', $tekscik);
     $tekscik = str_replace("\xC5\x9B", '&#347;', $tekscik);
     $tekscik = str_replace("\xC5\x9A", '&#346;', $tekscik);
     $tekscik = str_replace("\xC5\xBC", '&#380;', $tekscik);
     $tekscik = str_replace("\xC5\xBB", '&#379;', $tekscik);
     $tekscik = str_replace("\xC5\xBA", '&#378;', $tekscik);
     $tekscik = str_replace("\xC5\xB9", '&#377;', $tekscik);
     return $tekscik;
} // utf82iso88592

function iso885922utf8($tekscik) {
     $tekscik = str_replace("&#261;", "\xC4\x85", $tekscik);
     $tekscik = str_replace('&#260;', "\xC4\x84", $tekscik);
     $tekscik = str_replace('&#263;', "\xC4\x87", $tekscik);
     $tekscik = str_replace('&#262;', "\xC4\x86", $tekscik);
     $tekscik = str_replace('&#281;', "\xC4\x99", $tekscik);
     $tekscik = str_replace('&#280;', "\xC4\x98", $tekscik);
     $tekscik = str_replace('&#322;', "\xC5\x82", $tekscik);
     $tekscik = str_replace('&#321;', "\xC5\x81", $tekscik);
     $tekscik = str_replace('&#324;', "\xC5\x84", $tekscik);
     $tekscik = str_replace('&#323;',"\xC5\x83", $tekscik);
     $tekscik = str_replace('у', "\xC3\xB3", $tekscik);
     $tekscik = str_replace('У', "\xC3\x93", $tekscik);
     $tekscik = str_replace('&#347;', "\xC5\x9B", $tekscik);
     $tekscik = str_replace('&#346;', "\xC5\x9A", $tekscik);
     $tekscik = str_replace('&#380;', "\xC5\xBC", $tekscik);
     $tekscik = str_replace('&#379;', "\xC5\xBB", $tekscik);
     $tekscik = str_replace('&#378;', "\xC5\xBA", $tekscik);
     $tekscik = str_replace('&#377;', "\xC5\xB9", $tekscik);
     return $tekscik;
} // iso885922utf8
nospam at jra dot nu 23-Nov-2003 03:48
There is an error in the 'smart_utf8_decode' function posted by ' goran_johansson' below. It should look like this:

function smart_utf8_decode($in_str)
{
    // Replace ? with a unique string
    $new_str = str_replace("?", "q0u0e0s0t0i0o0n", $in_str);

    // Try the utf8_decode
    $new_str=utf8_decode($new_str);

    // if it contains ? marks
    if (strpos($new_str,"?") !== false)
    {
        // Something went wrong, set new_str to the original string.
        $new_str=$in_str;
    }
    else
    {
        // If not then all is well, put the ?-marks back where is belongs
        $new_str = str_replace("q0u0e0s0t0i0o0n", "?", $new_str);
    }

    return $new_str;
}
janusz dot s at remove_this dot and_this dot poczta dot fm 25-Oct-2003 08:54
Here are functions to PROPERLY de/encode Unicode (UTF-8) string to/from ISO-8859-2 (Polish character set).

Regards,
Janusz

function utf82iso88592($tekscik) {
 $tekscik = str_replace("\xC4\x85", "±", $tekscik);
 $tekscik = str_replace("\xC4\x84", 'Ў', $tekscik);
 $tekscik = str_replace("\xC4\x87", 'ж', $tekscik);
 $tekscik = str_replace("\xC4\x86", 'Ж', $tekscik);
 $tekscik = str_replace("\xC4\x99", 'к', $tekscik);
 $tekscik = str_replace("\xC4\x98", 'К', $tekscik);
 $tekscik = str_replace("\xC5\x82", 'і', $tekscik);
 $tekscik = str_replace("\xC5\x81", 'Ј', $tekscik);
 $tekscik = str_replace("\xC3\xB3", 'у', $tekscik);
 $tekscik = str_replace("\xC3\x93", 'У', $tekscik);
 $tekscik = str_replace("\xC5\x9B", '¶', $tekscik);
 $tekscik = str_replace("\xC5\x9A", '¦', $tekscik);
 $tekscik = str_replace("\xC5\xBC", 'ј', $tekscik);
 $tekscik = str_replace("\xC5\xBB", '¬', $tekscik);
 $tekscik = str_replace("\xC5\xBA", 'ї', $tekscik);
 $tekscik = str_replace("\xC5\xB9", 'Ї', $tekscik);
 return $tekscik;
} // utf82iso88592

function iso885922utf8($tekscik) {
 $tekscik = str_replace("±", "\xC4\x85", $tekscik);
 $tekscik = str_replace('Ў', "\xC4\x84", $tekscik);
 $tekscik = str_replace('ж', "\xC4\x87", $tekscik);
 $tekscik = str_replace('Ж', "\xC4\x86", $tekscik);
 $tekscik = str_replace('к', "\xC4\x99", $tekscik);
 $tekscik = str_replace('К', "\xC4\x98", $tekscik);
 $tekscik = str_replace('і', "\xC5\x82", $tekscik);
 $tekscik = str_replace('Ј', "\xC5\x81", $tekscik);
 $tekscik = str_replace('у', "\xC3\xB3", $tekscik);
 $tekscik = str_replace('У', "\xC3\x93", $tekscik);
 $tekscik = str_replace('¶', "\xC5\x9B", $tekscik);
 $tekscik = str_replace('¦', "\xC5\x9A", $tekscik);
 $tekscik = str_replace('ј', "\xC5\xBC", $tekscik);
 $tekscik = str_replace('¬', "\xC5\xBB", $tekscik);
 $tekscik = str_replace('ї', "\xC5\xBA", $tekscik);
 $tekscik = str_replace('Ї', "\xC5\xB9", $tekscik);
 return $tekscik;
} // iso885922utf8
bn2 (bn2 at ukr dot net) 01-Sep-2003 08:56
Function to decode uft8 to win-1251 (russian) charset. Don't support ukrainian letters. Support only 2-byte coding.

function utf8win1251($s){
$out="";$c1="";$byte2=false;
for ($c=0;$c<strlen($s);$c++){
$i=ord($s[$c]);
if ($i<=127) $out.=$s[$c];
if ($byte2){
$new_c2=($c1&3)*64+($i&63);
$new_c1=($c1>>2)&5;
$new_i=$new_c1*256+$new_c2;
if ($new_i==1025) $out_i=168; else
if ($new_i==1105) $out_i=184; else $out_i=$new_i-848;
$out.=chr($out_i);
$byte2=false;}
if (($i>>5)==6) {$c1=$i;$byte2=true;}
}
return $out;}
morris_hirsch at hotmail dot com 18-Aug-2003 09:43
Be aware that utf8_decode can not properly store ''wide'' code entities which have a numeric value too big for a byte.

This function may help you.  It converts utf8 to strict ASCII with no high-bit codes, they are all written as numerics.

// 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.

// input CANNOT have single byte upper half extended ascii codes

function numeric_entify_utf8 ($utf8_string) {

  $out = "";
  $ns = strlen ($utf8_string);
  for ($nn = 0; $nn < $ns; $nn++) {
    $ch = $utf8_string [$nn];
    $ii = ord ($ch);

//1 7 0bbbbbbb (127)

    if ($ii < 128) $out .= $ch;

//2 11 110bbbbb 10bbbbbb (2047)

   else if ($ii >>5 == 6) {
  $b1 = ($ii & 31);

  $nn++;
   $ch = $utf8_string [$nn];
    $ii = ord ($ch);
  $b2 = ($ii & 63);

  $ii = ($b1 * 64) + $b2;

      $ent = sprintf ("&#%d;", $ii);
      $out .= $ent;
    }

//3 16 1110bbbb 10bbbbbb 10bbbbbb

   else if ($ii >>4 == 14) {
  $b1 = ($ii & 31);

  $nn++;
   $ch = $utf8_string [$nn];
    $ii = ord ($ch);
  $b2 = ($ii & 63);

  $nn++;
   $ch = $utf8_string [$nn];
    $ii = ord ($ch);
  $b3 = ($ii & 63);

  $ii = ((($b1 * 64) + $b2) * 64) + $b3;

      $ent = sprintf ("&#%d;", $ii);
      $out .= $ent;
    }

//4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb

   else if ($ii >>3 == 30) {
  $b1 = ($ii & 31);

  $nn++;
   $ch = $utf8_string [$nn];
    $ii = ord ($ch);
  $b2 = ($ii & 63);

  $nn++;
   $ch = $utf8_string [$nn];
    $ii = ord ($ch);
  $b3 = ($ii & 63);

  $nn++;
   $ch = $utf8_string [$nn];
    $ii = ord ($ch);
  $b4 = ($ii & 63);

  $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;

      $ent = sprintf ("&#%d;", $ii);
      $out .= $ent;
    }

  }
  return $out;
}
johan dot andersson at strateg dot se 05-May-2003 01:25
A simple way to convert utf-8 encoded strings...
(PHP 4 >= 4.3.0)

<?php
$newstring = html_entity_decode(htmlentities($utf8_string, ENT_COMPAT, 'UTF-8'));
?>

(For 4.1.0 >= PHP < 4.3.0 use this function instead of html_entity_decode)

<?php
function unhtmlentities ($string)
{
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    return strtr ($string, $trans_tbl);
}

$newstring = unhtmlentities(htmlentities($utf8_string, ENT_COMPAT, 'UTF-8'));
?>

//Johan
24-Feb-2003 06:10
Oups, this is the non bugged version :)

Well sometimes you need to store a utf-8 string in a database table column with a fixed size.
Here is a function that fix a string which has been broken (by a substr for example) in a middle of a utf-8 char sequence.

function FixUtf8BrokenString($Desc)
{
 // UTF-8 encoding
 // bytes : representation
 // 1     : 0bbbbbbb
 // 2    : 110bbbbb 10bbbbbb
 // 3     : 1110bbbb 10bbbbbb 10bbbbbb
 // 4     : 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
 // to see if a string is broken in middle of a utf8 char
 // we search for last byte encoding size of utf-8 char
 // if number of last bytes in string is lower than encoding size
 // we remove those last bytes

 // if last byte is ord < 128, ok. we return !
 if (ord($Desc[strlen($Desc) - 1]) < (0x80))
   return $Desc

 // loop for finding byte encoding size
 $nbbytes = 1;
 while (ord($Desc[strlen($Desc) - $nbbytes]) > 0x7F)
 {
   if (ord($Desc[strlen($Desc) - $nbbytes]) > 0xBF)
     break;
   $nbbytes++;
 }

  // check if byte encoding size is encoding a size of 4 bytes
  if ((ord($Desc[strlen($Desc) - $nbbytes]) > 0xF0) && ($nbbytes == 4))
    return $Desc;
  // check if byte encoding size is encoding a size of 3 bytes
  if ((ord($Desc[strlen($Desc) - $nbbytes]) > 0xE0) && ($nbbytes == 3))
    return $Desc;
  // check if byte encoding size is encoding a size of 2 bytes
  if ((ord($Desc[strlen($Desc) - $nbbytes]) > 0xC0) && ($nbbytes == 2))
    return $Desc;
  // then this is the case where string is badly broken, we remove last bytes
  return substr($Desc, 0, -$nbbytes);
}

$str = "Ekonomi_ve_\xc4\xb0\xc5\x9f_D\xc3\xbcnyas\xc4\xb1";
$broken = substr($str, 0, 12);
$fixed = FixUtf8BrokenString($broken);

echo "$str<hr>$fixed<hr>$broken<hr>";

Sebastien Meudec.
18-Dec-2002 09:08
addition to above entrie:

it does not mean "when it comes to a '='" but when it comes to a "0"
mittag - -add- -marcmittag- -dot- -de 18-Dec-2002 08:56
The above function does not work entirely correct. It comes to problems, if there is a leading "=" in one of the two Strings it produces and glues out of the two bytes of the unicode letter.

The following works:

<?php
//Convert Unicode to ASCII + Entities
$fp = fopen($DOCUMENT_ROOT."/your_unicode_text.txt", "r");
while ( !feof($fp) )
{ $string = fgets($fp, 1000);

 $utf2html_string .= $string;
}
$string2 = $utf2html_string;
fclose ( $fp);

function utf2html ()
{
global $utf2html_string;

$utf2html_retstr = "";
 for ($utf2html_p=0; $utf2html_p<strlen($utf2html_string); $utf2html_p++) {
 $utf2html_c = substr ($utf2html_string, $utf2html_p, 1);
 $utf2html_c1 = ord ($utf2html_c);
  if ($utf2html_c1>>5 == 6) {// 110x xxxx, 110 prefix for 2 bytes unicode
    $utf2html_p++;
   $utf2html_t = substr ($utf2html_string, $utf2html_p, 1);
  $utf2html_c2 = ord ($utf2html_t);
   $utf2html_c1 &= 31; // remove the 3 bit two bytes prefix
   $utf2html_c2 &= 63; // remove the 2 bit trailing byte prefix
   $utf2html_c2 |= (($utf2html_c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
   $utf2html_c1 >>= 2; // c1 shifts 2 to the right
   $a = dechex($utf2html_c1);
   $a = str_pad($a, 2, "0", STR_PAD_LEFT);
   $b = dechex($utf2html_c2);
   $b = str_pad($b, 2, "0", STR_PAD_LEFT);

   $utf2html_n_neu = $a.$b;
   $utf2html_n_neu_speicher = $utf2html_n_neu;
   $utf2html_n_neu = "&#x".$utf2html_n_neu.";";

 $utf2html_retstr .= $utf2html_n_neu;

  }
  else {
   $utf2html_retstr .= $utf2html_c;
  }
 }
 echo $utf2html_retstr;
 //return $utf2html_retstr;

}

utf2html();

?>
wielspm at xs4all dot nl 05-Dec-2002 09:44
Here is a function I made to convert all 2 byte utf in a &#xxx; form:

function utf2html ($utf2html_string)
{
  $utf2html_retstr = "";
  for ($utf2html_p=0; $utf2html_p<strlen($utf2html_string); $utf2html_p++):
    $utf2html_c = substr ($utf2html_string, $utf2html_p, 1);
    $utf2html_c1 = ord ($utf2html_c);
    if ($utf2html_c1>>5 == 6): // 110x xxxx, 110 prefix for 2 bytes unicode
      $utf2html_p++;
       $utf2html_t = substr ($utf2html_string, $utf2html_p, 1);
      $utf2html_c2 = ord ($utf2html_t);
      $utf2html_c1 &= 31; // remove the 3 bit two bytes prefix
      $utf2html_c2 &= 63; // remove the 2 bit trailing byte prefix
      $utf2html_c2 |= (($utf2html_c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
      $utf2html_c1 >>= 2; // c1 shifts 2 to the right
       $utf2html_n = dechex($utf2html_c1).dechex($utf2html_c2);
      $utf2html_retstr .= sprintf ("&#%03d;", hexdec($utf2html_n));
    else:
      $utf2html_retstr .= $utf2html_c;
    endif;
  endfor;
  return $utf2html_retstr;
}
27-Aug-2002 12:22
echo utf8_decode(
"Ekonomi_ve_\xc4\xb0\xc5\x9f_D\xc3xbcnyas\xc4\xb1");

Outputs: Ekonomi_ve_??_Dьnyas?

This is not a bug. For example "\xc4\xb0" is decoded like this:
0xC4 = 110 00100 (110 prefix for 2 bytes)
0xB0 = 10 110000 (10 for trailing byte)
Character = 001 0011 0000 = 0x130

This U+0130 Unicode character is not defined in ISO-8859-1
(where all codes are below 0x100), so the utf8_decode() function
cannot represent it, and inserts a '?' replacement character
in the result string...

There's no alternative in the utf8_decode() function
which returns a string made of
single-byte characters.

PHP really lacks a datatype for UTF-16 (a.k.a. Unicode) strings,
unlike Java whose strings are always natively encoded
with UTF-16...

The alternative for PHP would be that it allows inserting SGML
character entities. In the above example, it could return
"&#x130;" when decoding "\xc4\xb0".

May be a future version of PHP could make strings using
double-byte UTF-16 encoding, so that Unicode could be natively
supported, but this would require adding new functions to
define the behavior of I/O functions to provide external
encode/decode capabilities when sending Unicode strings to
a file stream, or with echo and print builtins for the
standard input and output streams:

- What would be the semantic of fwrite($fp, $string)
if $string can contain any UTF-16 characters ?
- Should fwrite() truncate the highest byte of each UTF-16
character, letting the user anticipating this truncation by
performing the conversion to UTF-8 or character entities himself ?
- Should the user be able to specify an encoder/decoder object
used by all I/O operations performed on a file ?

For example:
- set_encoder($fp, 'utf8_encode') would define the PHP function
to call to encode a string.
- set_encoder($fp) or set_encoder($fp, null) would restore the
default (stripping) encoder...
- then fwrite($fp, $string) would return the number of bytes
written to the stream, which may be larger than the length of
$string...
ronen at greyzone dot com 01-Mar-2002 05:37
The following function will take a utf-8 encoded string and convert it to Unicode entities (the format is &#nnn; or &#nnnnn; with n={0..9} ).  Most browsers will display Unicode entities regardless of the encoding of the page.  Otherwise try charset=utf-8 to make sure the entities display correctly.  This works well with IE and Mozilla (tested with Mozilla 0.9.8 for X-Windos).

<?php
/**
* takes a string of utf-8 encoded characters and converts it to a string of unicode entities
* each unicode entitiy has the form &#nnnnn; n={0..9} and can be displayed by utf-8 supporting
* browsers
* @param $source string encoded using utf-8 [STRING]
* @return string of unicode entities [STRING]
* @access public
*/
function utf8ToUnicodeEntities ($source) {
    // array used to figure what number to decrement from character order value
    // according to number of characters used to map unicode to ascii by utf-8
    $decrement[4] = 240;
    $decrement[3] = 224;
    $decrement[2] = 192;
    $decrement[1] = 0;

    // the number of bits to shift each charNum by
    $shift[1][0] = 0;
    $shift[2][0] = 6;
    $shift[2][1] = 0;
    $shift[3][0] = 12;
    $shift[3][1] = 6;
    $shift[3][2] = 0;
    $shift[4][0] = 18;
    $shift[4][1] = 12;
    $shift[4][2] = 6;
    $shift[4][3] = 0;

    $pos = 0;
    $len = strlen ($source);
    $encodedString = '';
    while ($pos < $len) {
        $asciiPos = ord (substr ($source, $pos, 1));
        if (($asciiPos >= 240) && ($asciiPos <= 255)) {
            // 4 chars representing one unicode character
            $thisLetter = substr ($source, $pos, 4);
            $pos += 4;
        }
        else if (($asciiPos >= 224) && ($asciiPos <= 239)) {
            // 3 chars representing one unicode character
            $thisLetter = substr ($source, $pos, 3);
            $pos += 3;
        }
        else if (($asciiPos >= 192) && ($asciiPos <= 223)) {
            // 2 chars representing one unicode character
            $thisLetter = substr ($source, $pos, 2);
            $pos += 2;
        }
        else {
            // 1 char (lower ascii)
            $thisLetter = substr ($source, $pos, 1);
            $pos += 1;
        }

        // process the string representing the letter to a unicode entity
        $thisLen = strlen ($thisLetter);
        $thisPos = 0;
        $decimalCode = 0;
        while ($thisPos < $thisLen) {
            $thisCharOrd = ord (substr ($thisLetter, $thisPos, 1));
            if ($thisPos == 0) {
                $charNum = intval ($thisCharOrd - $decrement[$thisLen]);
                $decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
            }
            else {
                $charNum = intval ($thisCharOrd - 128);
                $decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
            }

            $thisPos++;
        }

        if ($thisLen == 1)
            $encodedLetter = "&#". str_pad($decimalCode, 3, "0", STR_PAD_LEFT) . ';';
        else
            $encodedLetter = "&#". str_pad($decimalCode, 5, "0", STR_PAD_LEFT) . ';';

        $encodedString .= $encodedLetter;
    }

    return $encodedString;
}
?>

Ronen.
Р¤СѓРЅРєС†РёРё РїР°СЂСЃРµСЂР° XML
utf8_encode
Р¤СѓРЅРєС†РёРё РїР°СЂСЃРµСЂР° XML


РљРѕРґРёСЂСѓРµС‚ СЃС‚СЂРѕРєСѓ ISO-8859-1 РІ РєРѕРґРёСЂРѕРІРєРµ UTF-8

utf8_decode
xml_error_string
Р¤СѓРЅРєС†РёРё РїР°СЂСЃРµСЂР° XML
PHP Manual

utf8_encode

(PHP 4, PHP 5)

utf8_encode — РљРѕРґРёСЂСѓРµС‚ СЃС‚СЂРѕРєСѓ ISO-8859-1 РІ РєРѕРґРёСЂРѕРІРєРµ UTF-8

РћРїРёСЃР°РЅРёРµ

string utf8_encode ( string $data )

РС‚Р° С„СѓРЅРєС†РёСЏ РєРѕРґРёСЂСѓРµС‚ СЃС‚СЂРѕРєСѓ data РєРѕРґРёСЂРѕРІРєРѕР№ UTF-8, Рё РІРѕР·РІСЂР°С‰Р°РµС‚ Р·Р°РєРѕРґРёСЂРѕРІР°РЅРЅС‹Р№ РІР°СЂРёР°РЅС‚. UTF-8 - СЃС‚Р°РЅРґР°СЂС‚РЅС‹Р№ РјРµС…Р°РЅРёР·Рј, РёСЃРїРѕР»СЊР·СѓРµРјС‹Р№ РІ Unicode РґР»СЏ РєРѕРґРёСЂРѕРІР°РЅРёСЏ wide character Р·РЅР°С‡РµРЅРёР№ РІ РїРѕС‚РѕРє Р±Р°Р№С‚РѕРІ. UTF-8 РЅРµ РѕРєР°Р·С‹РІР°РµС‚ РІР»РёСЏРЅРёСЏ РЅР° РЅРµР·Р°С€РёС„СЂРѕРІР°РЅРЅС‹Рµ ASCII СЃРёРјРІРѕР»С‹, РѕРЅ СЃР°РјРѕСЃРёРЅС…СЂРѕРЅРёР·РёСЂСѓСЋС‰РёР№СЃСЏ (СЌС‚Рѕ Р·РЅР°С‡РёС‚, С‡С‚Рѕ РїСЂРѕРіСЂР°РјРјРЅРѕ РјРѕР¶РЅРѕ РІС‹С‡РёСЃР»РёС‚СЊ, РіРґРµ РІ РїРѕС‚РѕРєРµ Р±Р°Р№С‚ РЅР°С‡РёРЅР°СЋС‚СЃСЏ СЃРёРјРІРѕР»С‹) Рё РјРѕР¶РµС‚ РёСЃРїРѕР»СЊР·РѕРІР°С‚СЊСЃСЏ С„СѓРЅРєС†РёСЏРјРё СЃСЂР°РІРЅРµРЅРёСЏ СЃС‚СЂРѕРє РґР»СЏ СЃРѕСЂС‚РёСЂРѕРІРєРё Рё РїРѕРґРѕР±РЅС‹С… Р·Р°РґР°С‡. PHP РєРѕРґРёСЂСѓРµС‚ UTF-8 СЃРёРјРІРѕР»С‹ РІ 4 Р±Р°Р№С‚Р°, РєР°Рє РїРѕРєР°Р·Р°РЅРѕ РЅРёР¶Рµ:

UTF-8 encoding
Р±Р°Р№С‚С‹ | Р±РёС‚С‹ | РїСЂРµРґСЃС‚Р°РІР»РµРЅРёРµ
1 | 7 | 0bbbbbbb
2 | 11 | 110bbbbb 10bbbbbb
3 | 16 | 1110bbbb 10bbbbbb 10bbbbbb
4 | 21 | 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
РљР°Р¶РґР°СЏ b РїСЂРµРґСЃС‚Р°РІР»СЏРµС‚ Р±РёС‚, РєРѕС‚РѕСЂС‹Р№ РјРѕР¶РµС‚ Р±С‹С‚СЊ РёСЃРїРѕР»СЊР·РѕРІР°РЅ РґР»СЏ С…СЂР°РЅРµРЅРёСЏ РґР°РЅРЅС‹С… СЃРёРјРІРѕР»Р°.

РЎРїРёСЃРѕРє РїР°СЂР°РјРµС‚СЂРѕРІ

data

ISO-8859-1 СЃС‚СЂРѕРєР°.

Р’РѕР·РІСЂР°С‰Р°РµРјС‹Рµ Р·РЅР°С‡РµРЅРёСЏ

Р’РѕР·РІСЂР°С‰Р°РµС‚ UTF-8 РїРµСЂРµРІРѕРґ РґР°РЅРЅС‹С… data.

User Contributed Notes

deceze at gmail dot com 14-Jul-2011 06:51
Please note that utf8_encode only converts a string encoded in ISO-8859-1 to UTF-8. A more appropriate name for it would be "iso88591_to_utf8". If your text is not encoded in  ISO-8859-1, you do not need this function. If your text is already in UTF-8, you do not need this function. In fact, applying this function to text that is not encoded in ISO-8859-1 will most likely simply garble that text.

If you need to convert text from any encoding to any other encoding, look at iconv() instead.
ivan dot jelenic42 at NOBOTSPAMPLZ dot gmail dot com 06-Jul-2011 01:12
Conversion for Croatian characters:

<?php
function croURLtoCHAR($text)
{
$url=array(
    "%C5%A0","%C5%A1",
    "%C4%90","%C4%91",
    "%C4%8C","%C4%8D",
    "%C4%86","%C4%87",
    "%C5%BD","%C5%BE"
);
$char=array(
    "Е ","ЕЎ",
    "Дђ","Д‘",
    "ДЊ","ДЌ",
    "Д†","Д‡",
    "ЕЅ","Еѕ"
);

return str_replace($url,$char,$text);
}

function croCHARtoURL($text)
{
$char=array(
    "Е ","ЕЎ",
    "Дђ","Д‘",
    "ДЊ","ДЌ",
    "Д†","Д‡",
    "ЕЅ","Еѕ"
);
$url=array(
    "%C5%A0","%C5%A1",
    "%C4%90","%C4%91",
    "%C4%8C","%C4%8D",
    "%C4%86","%C4%87",
    "%C5%BD","%C5%BE"
);

return str_replace($char,$url,$text);
}

?>

NOTE:
Obviously, you'll have to use other functions to replace/encode/decode the rest of the characters/code.
bastianschwarz t live punkt de 13-May-2011 08:25
My version for converting ISO array keys to utf8:

<?php
function convertArrayKeysToUtf8(array $array) {
    $convertedArray = array();
    foreach($array as $key => $value) {
      if(!mb_check_encoding($key, 'UTF-8')) $key = utf8_encode($key);
      if(is_array($value)) $value = $this->convertArrayKeysToUtf8($value);

      $convertedArray[$key] = $value;
    }
    return $convertedArray;
  }
?>
mike at eastghost dot com 12-Apr-2011 01:59
Lots of problems with conversions.  Is UTF-8 even necessary?  Wouldn't it be better for everyone to learn English and type only ASCII ??

<chuckle>

Look at iconv() function, which offers a way to convert from 8859 and dreaded 1252 into UTF8 (or else simply discard any untranslatable chars without error).  A script to fixup text of unknown type works well with iconv()
Anonymous 27-Mar-2011 01:33
Although this seems to break german Umlaute [Г¤Г¶Гј] if the document is already UTF-8.
powtac 4t gmx d0t de 11-Feb-2011 01:11
I tried a lot of things, but this seems to be the final fail save method to convert any string to proper UTF-8.

<?php
function _convert($content) {
    if(!mb_check_encoding($content, 'UTF-8')
        OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {

        $content = mb_convert_encoding($content, 'UTF-8');

        if (mb_check_encoding($content, 'UTF-8')) {
            // log('Converted to UTF-8');
        } else {
            // log('Could not converted to UTF-8');
        }
    }
    return $content;
}
?>
One of you 17-Sep-2010 12:49
Reason: Mysql prior 5.5 very strict in parsing UTF-8, it does not understand 4-byte and more UTF-8 chars and truncates such strings.

Solution:

<?php
function get_correct_utf8_mysql_string($s)
{
    if(empty($s)) return $s;
    $s = preg_match_all("#[\x09\x0A\x0D\x20-\x7E]|
[\xC2-\xDF][\x80-\xBF]|
\xE0[\xA0-\xBF][\x80-\xBF]|
[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|
\xED[\x80-\x9F][\x80-\xBF]#x", $s, $m );
    return implode("",$m[0]);
}
?>

Function cleans string from everything except correct ASCII & UTF-8 characters (excluding 4-byte+ UTF-8 sequences).
Ready to insert into utf-8 mysql database.

Fast, clean and easy to understand.You can easily convert it to 4-byte sequences using example below.
Disadvantage: it can make mess from incorrect UTF-8 string, but this mess will be valid UTF-8
Yumok 15-Sep-2010 04:26
Avoiding use of preg_match to detect if utf8_encode is needed:

<?php
                $string = $string_input; // avoid being destructive

                $string = preg_replace("#[\x09\x0A\x0D\x20-\x7E]#"        ,"",$string);         // ASCII
                $string = preg_replace("#[\xC2-\xDF][\x80-\xBF]#"            ,"",$string);             // non-overlong 2-byte
                $string = preg_replace("#\xE0[\xA0-\xBF][\x80-\xBF]#"    ,"",$string);     // excluding overlongs
                $string = preg_replace("#[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}#","",$string);     // straight 3-byte
                $string = preg_replace("#\xED[\x80-\x9F][\x80-\xBF]#"    ,"",$string);     // excluding surrogates
                $string = preg_replace("#\xF0[\x90-\xBF][\x80-\xBF]{2}#","",$string);     // planes 1-3
                $string = preg_replace("#[\xF1-\xF3][\x80-\xBF]{3}#"    ,"",$string);     //  planes 4-15
                $string = preg_replace("#\xF4[\x80-\x8F][\x80-\xBF]{2}#","",$string);     // plane 16

                $rc = ($string == ""?true:false);
?>
darkenergy at hispeed dot ch 10-Aug-2010 06:15
to encode a string only if it is not yet UTF-8, the most elegant solution i found is:

<?php
//$s is a string from whatever source
mb_detect_encoding($s, "UTF-8") == "UTF-8" ? : $s = utf8_encode($s);
?>

hope it helps
rhill at raymondhill dot net 26-Jun-2010 07:17
utf8_[encode|decode] will actually translate windows-1252 characters as well, not just from/to ISO-8859-1 as the documentation says. I assumed it didn't and was puzzled that the output was mangled due to some characters going through a two-pass conversion to/from UTF8 (mine and that of utf8_* functions.)

Well, that's how it behaves on Linux flavor of PHP, I didn't check with Windows version.
rodrigo at overflow dot biz 24-Apr-2010 11:16
I've been working on a is_utf8 function and wanted to post it here, in addition to others i also took in consideration the 5000 char bug:

<?php
define('_is_utf8_split',5000);

function is_utf8($string) { // v1.01
    if (strlen($string) > _is_utf8_split) {
        // Based on: http://mobile-website.mobi/php-utf8-vs-iso-8859-1-59
        for ($i=0,$s=_is_utf8_split,$j=ceil(strlen($string)/_is_utf8_split);$i < $j;$i++,$s+=_is_utf8_split) {
            if (is_utf8(substr($string,$s,_is_utf8_split)))
                return true;
        }
        return false;
    } else {
        // From http://w3.org/International/questions/qa-forms-utf-8.html
        return preg_match('%^(?:
                [\x09\x0A\x0D\x20-\x7E]            # ASCII
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
            |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
            |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
            |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
            |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
        )*$%xs', $string);
    }
}
?>
nico at mein-sachsen dot net 05-Jan-2010 12:21
in function fix_latin you should replace $input with $instr when calling preg_match
squeegee 26-Aug-2009 06:20
I think this is a reasonable port of Perl's Encoding::FixLatin by Grant McLean, which converts a string with mixed encodings (ASCII, ISO-8859-1, CP1252, and UTF-8) to UTF-8.

<?php

function init_byte_map(){
  global $byte_map;
  for($x=128;$x<256;++$x){
    $byte_map[chr($x)]=utf8_encode(chr($x));
  }
  $cp1252_map=array(
    "\x80"=>"\xE2\x82\xAC",    // EURO SIGN
    "\x82" => "\xE2\x80\x9A",  // SINGLE LOW-9 QUOTATION MARK
    "\x83" => "\xC6\x92",      // LATIN SMALL LETTER F WITH HOOK
    "\x84" => "\xE2\x80\x9E",  // DOUBLE LOW-9 QUOTATION MARK
    "\x85" => "\xE2\x80\xA6",  // HORIZONTAL ELLIPSIS
    "\x86" => "\xE2\x80\xA0",  // DAGGER
    "\x87" => "\xE2\x80\xA1",  // DOUBLE DAGGER
    "\x88" => "\xCB\x86",      // MODIFIER LETTER CIRCUMFLEX ACCENT
    "\x89" => "\xE2\x80\xB0",  // PER MILLE SIGN
    "\x8A" => "\xC5\xA0",      // LATIN CAPITAL LETTER S WITH CARON
    "\x8B" => "\xE2\x80\xB9",  // SINGLE LEFT-POINTING ANGLE QUOTATION MARK
    "\x8C" => "\xC5\x92",      // LATIN CAPITAL LIGATURE OE
    "\x8E" => "\xC5\xBD",      // LATIN CAPITAL LETTER Z WITH CARON
    "\x91" => "\xE2\x80\x98",  // LEFT SINGLE QUOTATION MARK
    "\x92" => "\xE2\x80\x99",  // RIGHT SINGLE QUOTATION MARK
    "\x93" => "\xE2\x80\x9C",  // LEFT DOUBLE QUOTATION MARK
    "\x94" => "\xE2\x80\x9D",  // RIGHT DOUBLE QUOTATION MARK
    "\x95" => "\xE2\x80\xA2",  // BULLET
    "\x96" => "\xE2\x80\x93",  // EN DASH
    "\x97" => "\xE2\x80\x94",  // EM DASH
    "\x98" => "\xCB\x9C",      // SMALL TILDE
    "\x99" => "\xE2\x84\xA2",  // TRADE MARK SIGN
    "\x9A" => "\xC5\xA1",      // LATIN SMALL LETTER S WITH CARON
    "\x9B" => "\xE2\x80\xBA",  // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
    "\x9C" => "\xC5\x93",      // LATIN SMALL LIGATURE OE
    "\x9E" => "\xC5\xBE",      // LATIN SMALL LETTER Z WITH CARON
    "\x9F" => "\xC5\xB8"       // LATIN CAPITAL LETTER Y WITH DIAERESIS
  );
  foreach($cp1252_map as $k=>$v){
    $byte_map[$k]=$v;
  }
}

function fix_latin($instr){
  if(mb_check_encoding($instr,'UTF-8'))return $instr; // no need for the rest if it's all valid UTF-8 already
  global $nibble_good_chars,$byte_map;
  $outstr='';
  $char='';
  $rest='';
  while((strlen($instr))>0){
    if(1==preg_match($nibble_good_chars,$input,$match)){
      $char=$match[1];
      $rest=$match[2];
      $outstr.=$char;
    }elseif(1==preg_match('@^(.)(.*)$@s',$input,$match)){
      $char=$match[1];
      $rest=$match[2];
      $outstr.=$byte_map[$char];
    }
    $instr=$rest;
  }
  return $outstr;
}

$byte_map=array();
init_byte_map();
$ascii_char='[\x00-\x7F]';
$cont_byte='[\x80-\xBF]';
$utf8_2='[\xC0-\xDF]'.$cont_byte;
$utf8_3='[\xE0-\xEF]'.$cont_byte.'{2}';
$utf8_4='[\xF0-\xF7]'.$cont_byte.'{3}';
$utf8_5='[\xF8-\xFB]'.$cont_byte.'{4}';
$nibble_good_chars = "@^($ascii_char+|$utf8_2|$utf8_3|$utf8_4|$utf8_5)(.*)$@s";

?>

Then just call fix_latin wherever you need it.
rabby 28-Apr-2009 07:59
there is a little auto-detect script for encodings which decides if it is necessary to utf8_encode or not. it can simply be modified to work with iso-8859-1 scripts, too, and decide if utf8_decode or not.
            preg_match('%^(?:
                [\x09\x0A\x0D\x20-\x7E]              # ASCII
                | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
                |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
                | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
                |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
                |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
                | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
                |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
                )*$%xs',
                $s)
As preg_match is a bit tricky with bigger strings $s, let me share the fixed function called autoencode: http://mobile-website.mobi/php-utf8-vs-iso-8859-1-59
bassam at saprinna dot com 27-Apr-2009 02:47
you can convert any encode to utf and save it to mysql from this function :

<?php
    function convert_charset($item)
    {
        if ($unserialize = unserialize($item))
        {
            foreach ($unserialize as $key => $value)
            {
                $unserialize[$key] = @iconv('windows-1256', 'UTF-8', $value);
            }
            $serialize = serialize($unserialize);
            return $serialize;
        }
        else
        {
            return @iconv('windows-1256', 'UTF-8', $item);
        }
    }
?>
mrezair at azarbod dot com 23-Mar-2009 10:19
I found this little function very useful in fixing strings that are not in utf-8 but need be converted

<?php
// Fixes the encoding to uf8
function fixEncoding($in_str)
{
  $cur_encoding = mb_detect_encoding($in_str) ;
  if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8"))
    return $in_str;
  else
    return utf8_encode($in_str);
} // fixEncoding
?>
dan at birminghampr dot co dot uk 19-Mar-2009 05:01
I use a function like this, rather than utf8_encode() alone, for fixing the encoding of unknown data, for example the contents of get_meta_tags():

<?php
function FixEncoding($x){
  if(mb_detect_encoding($x)=='UTF-8'){
    return $x;
  }else{
    return utf8_encode($x);
  }
}
?>
rogeriogirodo at gmail dot com 19-Mar-2009 04:24
This function may be useful do encode array keys and values [and checks first to see if it's already in UTF format]:

<?php
public static function to_utf8($in)
{
        if (is_array($in)) {
            foreach ($in as $key => $value) {
                $out[to_utf8($key)] = to_utf8($value);
            }
        } elseif(is_string($in)) {
            if(mb_detect_encoding($in) != "UTF-8")
                return utf8_encode($in);
            else
                return $in;
        } else {
            return $in;
        }
        return $out;
}
?>

Hope this may help.

[NOTE BY danbrown AT php DOT net: Original function written by (cmyk777 AT gmail DOT com) on 28-JAN-09.]
Julio Cesar 20-Jan-2009 05:08
With This Script you can convert a lot of files in
subfolders and convert to UTF8 without problems!

I thought about that when I was converting an eclipse
Project to UTF-8 and I loose all the Accentuation O.o

But with this script YOU WILL NOT! ;-)

I Make this based on Aidan Kehoe's Script and webmaster at
asylum-et dot com of http://www.php.net/scandir:

<?php
ini_set("implicit_flush", "on");
ini_set("max_execution_time", 0);
ini_set("register_argc_argv", "on");
ini_set("html_errors", "Off");

function cp1252_to_utf8($str) {
    $cp1252_map = array ("\xc2\x80" => "\xe2\x82\xac",
    "\xc2\x82" => "\xe2\x80\x9a",
    "\xc2\x83" => "\xc6\x92",
    "\xc2\x84" => "\xe2\x80\x9e",
    "\xc2\x85" => "\xe2\x80\xa6",
    "\xc2\x86" => "\xe2\x80\xa0",
    "\xc2\x87" => "\xe2\x80\xa1",
    "\xc2\x88" => "\xcb\x86",
    "\xc2\x89" => "\xe2\x80\xb0",
    "\xc2\x8a" => "\xc5\xa0",
    "\xc2\x8b" => "\xe2\x80\xb9",
    "\xc2\x8c" => "\xc5\x92",
    "\xc2\x8e" => "\xc5\xbd",
    "\xc2\x91" => "\xe2\x80\x98",
    "\xc2\x92" => "\xe2\x80\x99",
    "\xc2\x93" => "\xe2\x80\x9c",
    "\xc2\x94" => "\xe2\x80\x9d",
    "\xc2\x95" => "\xe2\x80\xa2",
    "\xc2\x96" => "\xe2\x80\x93",
    "\xc2\x97" => "\xe2\x80\x94",

    "\xc2\x98" => "\xcb\x9c",
    "\xc2\x99" => "\xe2\x84\xa2",
    "\xc2\x9a" => "\xc5\xa1",
    "\xc2\x9b" => "\xe2\x80\xba",
    "\xc2\x9c" => "\xc5\x93",
    "\xc2\x9e" => "\xc5\xbe",
    "\xc2\x9f" => "\xc5\xb8"
);
    return strtr ( utf8_encode ( $str ), $cp1252_map );
}
function rscandir($base="", &$data=array()) {

  $array = array_diff(scandir($base), array(".", ".."));

  foreach($array as $value) :

    if (is_dir($base.$value)) :
      //$data[] = $base.$value."/";
      $data = rscandir($base.$value."/", $data);

    elseif (is_file($base.$value) &&
!eregi(".jpg|.gif|.png|.ttf|.dataModel|.wsdlDataModel
|.project|.jsdtscope|.prefs|.name|.container|
.exe|.bat|.cmd|.src|.dll|.ini|.swf|.fla|.bmp\$",
$value)) : /* where you put the unwanted extensions  */
    echo "Converting to UTF8 " . $base.$value . "\r\n";

file_put_contents(
        $base.$value,
            cp1252_to_utf8(
            file_get_contents($base.$value)));

    endif;

  endforeach;

  return $data;

}
echo "Type a Folder (With a Slash in end): ";
$folder = trim(fgets(STDIN));

rscandir($folder);

?>

You can put this on windows Dir and put a Batch like this:

@echo off
php -n C:\windows\ConvertUTF8.php
pause

So you can convert your files from any where, just type on
Execute Command Like: ConvertFilesToUTF8

I think this will help everyone! Enjoy ;-)

P.s: I remove the comments becouse the wordwrap
bitseeker 22-Sep-2008 02:07
...or just use this simple piece of code to check valid utf-8 string:

<?php
    /**
     * Returns true if $string is valid UTF-8 and false otherwise.
     *
     * @since        1.14
     * @param [mixed] $string     string to be tested
     * @subpackage
     */
    function is_utf8($string) {

        // From http://w3.org/International/questions/qa-forms-utf-8.html
        return preg_match('%^(?:
              [\x09\x0A\x0D\x20-\x7E]            # ASCII
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
            |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
            |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
            |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
            |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
        )*$%xs', $string);

    }
?>
hmdker at gmail dot com 23-Aug-2008 09:49
Here's my is_utf8 function, to detect valid UTF-8 text.

<?php
function is_utf8($str) {
    $c=0; $b=0;
    $bits=0;
    $len=strlen($str);
    for($i=0; $i<$len; $i++){
        $c=ord($str[$i]);
        if ($c >= 128) {
            if(($c >= 254)) return false;
            elseif($c >= 252) $bits=6;
            elseif($c >= 248) $bits=5;
            elseif($c >= 240) $bits=4;
            elseif($c >= 224) $bits=3;
            elseif($c >= 192) $bits=2;
            else return false;
            if(($i+$bits) > $len) return false;
            while($bits > 1){
                $i++;
                $b=ord($str[$i]);
                if($b < 128 || $b > 191) return false;
                $bits--;
            }
        }
    }
    return true;
}

?>

[NOTE BY danbrown AT php DOT net: Contains a bugfix supplied by "svenmika" on 09-JUL-09 with the following note: "A value of exactly 128 (binary 10000000) in the first byte of a character is invalid."]
akam 30-Jun-2008 07:14
<?php
// Author akam at akameng dot com
// Support 6 bit
function UTF_to_Unicode($input, $array=False) {

 $bit1  = pow(64, 0);
 $bit2  = pow(64, 1);
 $bit3  = pow(64, 2);
 $bit4  = pow(64, 3);
 $bit5  = pow(64, 4);
 $bit6  = pow(64, 5);

 $value = '';
 $val   = array();

 for($i=0; $i< strlen( $input ); $i++){

     $ints = ord ( $input[$i] );

     $z     = ord ( $input[$i] );
     $y     = ord ( $input[$i+1] ) - 128;
     $x     = ord ( $input[$i+2] ) - 128;
     $w     = ord ( $input[$i+3] ) - 128;
     $v     = ord ( $input[$i+4] ) - 128;
     $u     = ord ( $input[$i+5] ) - 128;

     if( $ints >= 0 && $ints <= 127 ){
        // 1 bit
        $value .= '&#'.($z * $bit1).';';
        $val[]  = $value;
     }
     if( $ints >= 192 && $ints <= 223 ){
        // 2 bit
        $value .= '&#'.(($z-192) * $bit2 + $y * $bit1).';';
        $val[]  = $value;
     }
     if( $ints >= 224 && $ints <= 239 ){
        // 3 bit
        $value .= '&#'.(($z-224) * $bit3 + $y * $bit2 + $x * $bit1).';';
        $val[]  = $value;
     }
     if( $ints >= 240 && $ints <= 247 ){
        // 4 bit
        $value .= '&#'.(($z-240) * $bit4 + $y * $bit3 +
$x * $bit2 + $w * $bit1).';';
        $val[]  = $value;
     }
     if( $ints >= 248 && $ints <= 251 ){
        // 5 bit
        $value .= '&#'.(($z-248) * $bit5 + $y * $bit4
+ $x * $bit3 + $w * $bit2 + $v * $bit1).';';
        $val[]  = $value;
     }
     if( $ints == 252 && $ints == 253 ){
        // 6 bit
        $value .= '&#'.(($z-252) * $bit6 + $y * $bit5
+ $x * $bit4 + $w * $bit3 + $v * $bit2 + $u * $bit1).';';
        $val[]  = $value;
     }
     if( $ints == 254 || $ints == 255 ){
       echo 'Wrong Result!<br>';
     }

 }

 if( $array === False ){
    return $unicode = $value;
 }
 if($array === True ){
     $val     = str_replace('&#', '', $value);
     $val     = explode(';', $val);
     $len = count($val);
     unset($val[$len-1]);

     return $unicode = $val;
 }

}

function Unicode_to_UTF( $input, $array=TRUE){

     $utf = '';
    if(!is_array($input)){
       $input     = str_replace('&#', '', $input);
       $input     = explode(';', $input);
       $len = count($input);
       unset($input[$len-1]);
    }
    for($i=0; $i < count($input); $i++){

    if ( $input[$i] <128 ){
       $byte1 = $input[$i];
       $utf  .= chr($byte1);
    }
    if ( $input[$i] >=128 && $input[$i] <=2047 ){

       $byte1 = 192 + (int)($input[$i] / 64);
       $byte2 = 128 + ($input[$i] % 64);
       $utf  .= chr($byte1).chr($byte2);
    }
    if ( $input[$i] >=2048 && $input[$i] <=65535){

       $byte1 = 224 + (int)($input[$i] / 4096);
       $byte2 = 128 + ((int)($input[$i] / 64) % 64);
       $byte3 = 128 + ($input[$i] % 64);

       $utf  .= chr($byte1).chr($byte2).chr($byte3);
    }
    if ( $input[$i] >=65536 && $input[$i] <=2097151){

       $byte1 = 240 + (int)($input[$i] / 262144);
       $byte2 = 128 + ((int)($input[$i] / 4096) % 64);
       $byte3 = 128 + ((int)($input[$i] / 64) % 64);
       $byte4 = 128 + ($input[$i] % 64);
       $utf  .= chr($byte1).chr($byte2).chr($byte3).
chr($byte4);
    }
    if ( $input[$i] >=2097152 && $input[$i] <=67108863){

       $byte1 = 248 + (int)($input[$i] / 16777216);
       $byte2 = 128 + ((int)($input[$i] / 262144) % 64);
       $byte3 = 128 + ((int)($input[$i] / 4096) % 64);
       $byte4 = 128 + ((int)($input[$i] / 64) % 64);
       $byte5 = 128 + ($input[$i] % 64);
       $utf  .= chr($byte1).chr($byte2).chr($byte3).
chr($byte4).chr($byte5);
    }
    if ( $input[$i] >=67108864 && $input[$i] <=2147483647){

       $byte1 = 252 + ($input[$i] / 1073741824);
       $byte2 = 128 + (($input[$i] / 16777216) % 64);
       $byte3 = 128 + (($input[$i] / 262144) % 64);
       $byte4 = 128 + (($input[$i] / 4096) % 64);
       $byte5 = 128 + (($input[$i] / 64) % 64);
       $byte6 = 128 + ($input[$i] % 64);
       $utf  .= chr($byte1).chr($byte2).chr($byte3).
chr($byte4).chr($byte5).chr($byte6);
    }
   }
   return $utf;
}
?>
www.tricinty.com 11-Jun-2008 03:43
<?php
    /**
    * Encodes an ISO-8859-1 mixed variable to UTF-8 (PHP 4, PHP 5 compat)
    * @param    mixed    $input An array, associative or simple
    * @param    boolean  $encode_keys optional
    * @return    mixed     ( utf-8 encoded $input)
    */

    function utf8_encode_mix($input, $encode_keys=false)
    {
        if(is_array($input))
        {
            $result = array();
            foreach($input as $k => $v)
            {
                $key = ($encode_keys)? utf8_encode($k) : $k;
                $result[$key] = utf8_encode_mix( $v, $encode_keys);
            }
        }
        else
        {
            $result = utf8_encode($input);
        }

        return $result;
    }
?>
klein at buchung-24 dot de 04-Jun-2008 04:22
IF you donВґt use the function from ethan dot nelson at ltd dot org in a class, youВґll get an error, so please try

function utf_prepare(&$array)
{
    foreach($array AS $key => &$value)
    {
        if (is_array($value))
        {
            utf_prepare($value);
        } else
        {
            $value = utf8_encode($value);
        }
    }
}
www.qaiser.net 17-Apr-2008 07:56
that isUTF8 function is a killer...

wouldn't something like

if ( preg_match( "~(\x00[\x80-\xff]|[\x00-\x07][\x00-\xff]~", $string ) ) { /* is utf */ };

be a lot more efficient? it doesn't take into account all the ranges, but it has to be a better method and a simple start since it'll quit on the first successful match. think of encoding and decoding a 1mb string--not good. i'm having to work with +20 meg xml files.
renardo13 at free dot fr 01-Apr-2008 04:56
another nice way to implement an isUTF8 function ...

<?php

function isUTF8($string)
{
    return (utf8_encode(utf8_decode($string)) == $string);
}

?>
tacchete at gmail dot com 13-Dec-2007 04:35
Known problem with Byte Order Mark (BOM) and header() in pages of a site.

For example at sending headings or to a dynamic conclusion in other coding distinct from UTF-8 by means of XSLT (<xsl:output encoding="windows-1251"/>).

To clean all symbols BOM from the text of page:

1. exclude BOM from the main file;
2. write down function of a return call for the buffer

<?php
header('content-type: text/html; charset: utf-8');
ob_start('ob');
function ob($buffer)
{
    return str_replace("\xef\xbb\xbf", '', $buffer);
}
?>

it will exclude BOM from a code of the connected files;
3. do not experience for BOM in connected files;
4. be pleased.
ethan dot nelson at ltd dot org 06-Nov-2007 05:41
This does the same thing as some of the posts below (minus the keys), but I thought I'd share anyway cause it is slightly more elegant.  Also, its a good example using references such that this could be used as a callback function.

  function utf_prepare(&$array) {

    foreach($array AS $key => &$value) {

      if (is_array($value)) {
        $this->utf_prepare($value);
      } else {
        $value = utf8_encode($value);
      }

    }

  }
luka8088 at gmail dot com 22-Jun-2007 07:19
simple HTML to UTF-8 conversion:

function html_to_utf8 ($data)
    {
    return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data);
    }

function _html_to_utf8 ($data)
    {
    if ($data > 127)
        {
        $i = 5;
        while (($i--) > 0)
            {
            if ($data != ($a = $data % ($p = pow(64, $i))))
                {
                $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
                for ($i; $i > 0; $i--)
                    $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
                break;
                }
            }
        }
        else
        $ret = "&#$data;";
    return $ret;
    }

Example:
echo html_to_utf8("a b &#269; &#263; &#382; &#12371; &#12395; &#12385; &#12431; ()[]{}!#$?* &lt; &#62;");

Output:
a b ДЌ Д‡ Еѕ гЃ“ гЃ« гЃЎ г‚Џ ()[]{}!#$?* &lt; &#62;
hillar dot petersen at gmail dot com 29-May-2007 10:59
In addition to my previous post. If your values are already in utf-8 maybe you want to utf8_encode array keys only. This will do it:

<?php
/**
 * (Recursively) utf8_encode all array keys.
 *
 * @param array $array
 * @return array with utf8_encoded keys
 */

function utf8_encode_array_keys($array)
{
  $array_type = array_type($array);

  if ($array_type == "map")
  {
    $result_array = array();

    foreach($array as $key => $value)
    {
      if (is_array($value))
      {
        // recursion
        $result_array[utf8_encode($key)] = utf8_encode_array_keys($value);
      }
      else
      {
        // value is not an array, no recursion
        $result_array[utf8_encode($key)] = $value;
      }
    }

    return $result_array;
  }

  else if ($array_type == "vector")
  {
    // do not encode anything, just follow the value if it is an array
    $result_array = array();

    foreach ($array as $key => $value)
    {
      if (is_array($value))
      {
        // recursion
        $result_array[$key] = utf8_encode_array_keys($value);
      }
      else
      {
        // value is not an array, no recursion
        $result_array[$key] = $value;
      }
    }

    return $result_array;
  }

  return false;     // argument is not an array, return false
}
?>

Also note that both this operation (with keys only) and the operation with both keys and values can be reversed by replacing "encode" by "decode".
hillar dot petersen at gmail dot com 29-May-2007 07:06
If you are interested in recursively converting ISO-8859-1-encoded arrays into UTF-8, then this is one way to do it. Could use a small refactor though. (I used it to prepare some ISO-8859-1 arrays for json_encode. Note that for this to work your values and for associative arrays also your keys must be ISO-8859-1-encoded.)

<?php
/**
 * (Recursively) utf8_encode each value in an array.
 *
 * @param array $array
 * @return array utf8_encoded
 */

function utf8_encode_array($array)
{
  if (is_array($array))
  {
    $result_array = array();

    foreach($array as $key => $value)
    {

      if (array_type($array) == "map")
      {
        // encode both key and value

        if (is_array($value))
        {
          // recursion
          $result_array[utf8_encode($key)] = utf8_encode_array($value);
        }
        else
        {
          // no recursion
          if (is_string($value))
          {
            $result_array[utf8_encode($key)] = utf8_encode($value);
          }
          else
          {
            // do not re-encode non-strings, just copy data
            $result_array[utf8_encode($key)] = $value;
          }

        }

      }

      else if (array_type($array) == "vector")
      {
        // encode value only

        if (is_array($value))
        {
          // recursion
          $result_array[$key] = utf8_encode_array($value);
        }
        else
        {
          // no recursion

          if (is_string($value))
          {
            $result_array[$key] = utf8_encode($value);
          }
          else
          {
            // do not re-encode non-strings, just copy data
            $result_array[$key] = $value;
          }

        }

      }

    }

    return $result_array;
  }

  return false;     // argument is not an array, return false
}

/**
 * Determines array type ("vector" or "map"). Returns false if not an array at all.
 * (I hope a native function will be introduced in some future release of PHP, because
 * this check is inefficient and quite costly in worst case scenario.)
 *
 * @param array $array The array to analyze
 * @return string array type ("vector" or "map") or false if not an array
 */

function array_type($array)
{
  if (is_array($array))
  {
    $next = 0;

    $return_value = "vector";  // we have a vector until proved otherwise

    foreach ($array as $key => $value)
    {

      if ($key != $next)
      {
        $return_value = "map";  // we have a map
        break;
      }

      $next++;
    }

    return $return_value;
  }

  return false;    // not array
}
?>
nikooo adog bk adot ru - Nickolaz 03-May-2007 07:02
You can use this simple code to convert win-1251 into Unicode.

    function rus2uni($str,$isTo = true)
    {
        $arr = array('С‘'=>'&#x451;','РЃ'=>'&#x401;');
        for($i=192;$i<256;$i++)
            $arr[chr($i)] = '&#x4'.dechex($i-176).';';
        $str =preg_replace(array('@([Р°-СЏ]) @i','@ ([Р°-СЏ])@i'),array('$1&#x0a0;','&#x0a0;$1'),$str);
        return strtr($str,$isTo?$arr:array_flip($arr));
    }

That is useful for xml_parser (to parse windows-1251 files like utf-8).
18-Apr-2007 09:06
I just read what I wrote, sorry for the typos it was a long day:

here's the rewritten code:

xml_tpl.php
<?php
    header("Content-Type: text/html;charset=ISO-8859-1");
    print "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
    $names=array('jack','bob','vanessa','catherine','valerie');
?>
<parent>
<?php foreach($names as $name) {?>
    <child name="<?php print $name?>" />
<?php } ?>
</parent>

<?php
function create_xml(){
    ob_start();
    include "xml_tpl.php";
    $trapped_content=ob_get_contents();
    ob_end_clean();
    $file_path= "./somefile.xml";
    $file_handle=fopen($file_path,'w');
    fwrite($file_handle,utf8_encode($trapped_content));
}

?>
penda ekoka 17-Apr-2007 11:15
creating utf-8 xml files:
this is something that has wasted a lot of my time, I hope this will spare you the headaches:

my method consists of creating an xml template that will look like this (this is probably optional, I'm sure you can use good ol' print or echo statements):

xml_tpl.php
<?php
header("Content-Type: text/html;charset=ISO-8859-1");
print "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
$names=array('jack','bob','vanessa','catherine','valerie');
?>
<parent>
<?php foreach($names as $name) {?>
    <child name="<?php print $name?>" />
<?php } ?>
</parent>
?>

from a function or a method I include the previous template and trap the outputted content in an output buffer. The buffured content is then inserted into a file:

<?php
function create_xml(){
    ob_start();
    include "xml_php.php";
    $trapped_content=ob_get_contents();
    ob_end_clean();
    $file_path= "./somefile.xml";
    $file_handle=fopen($somefile,'w');
    fwrite($file_handle,utf8_encode($trapped_content));
}

?>

Some side notes:
- note that the utf8_encode function goes inside the fwrite() function.
- when troubleshooting, make sure to transfer text file (xml included) and scripts in ascii mode when using ftp. For some unknown reason my ftp client did not have xml set as an ascii transfer candidate and was automatically tranfering them in binary. That little "feature" ended up costing me hours of frustration, as the encoding information would just "vanish" between transfer and I kept scratching my head as to why manually created utf8 files were not behaving as they should.
28-Mar-2007 02:07
<?php

function unicon($str, $to_uni = true) {
    $cp = Array (
        "Рђ" => "&#x410;", "Р°" => "&#x430;",
        "Р‘" => "&#x411;", "Р±" => "&#x431;",
        "Р’" => "&#x412;", "РІ" => "&#x432;",
        "Р“" => "&#x413;", "Рі" => "&#x433;",
        "Р”" => "&#x414;", "Рґ" => "&#x434;",
        "Р•" => "&#x415;", "Рµ" => "&#x435;",
        "РЃ" => "&#x401;", "С‘" => "&#x451;",
        "Р–" => "&#x416;", "Р¶" => "&#x436;",
        "Р—" => "&#x417;", "Р·" => "&#x437;",
        "Р" => "&#x418;", "Рё" => "&#x438;",
        "Р™" => "&#x419;", "Р№" => "&#x439;",
        "Рљ" => "&#x41A;", "Рє" => "&#x43A;",
        "Р›" => "&#x41B;", "Р»" => "&#x43B;",
        "Рњ" => "&#x41C;", "Рј" => "&#x43C;",
        "Рќ" => "&#x41D;", "РЅ" => "&#x43D;",
        "Рћ" => "&#x41E;", "Рѕ" => "&#x43E;",
        "Рџ" => "&#x41F;", "Рї" => "&#x43F;",
        "Р " => "&#x420;", "СЂ" => "&#x440;",
        "РЎ" => "&#x421;", "СЃ" => "&#x441;",
        "Рў" => "&#x422;", "С‚" => "&#x442;",
        "РЈ" => "&#x423;", "Сѓ" => "&#x443;",
        "Р¤" => "&#x424;", "С„" => "&#x444;",
        "РҐ" => "&#x425;", "С…" => "&#x445;",
        "Р¦" => "&#x426;", "С†" => "&#x446;",
        "Р§" => "&#x427;", "С‡" => "&#x447;",
        "РЁ" => "&#x428;", "С€" => "&#x448;",
        "Р©" => "&#x429;", "С‰" => "&#x449;",
        "РЄ" => "&#x42A;", "СЉ" => "&#x44A;",
        "Р«" => "&#x42B;", "С‹" => "&#x44B;",
        "Р¬" => "&#x42C;", "СЊ" => "&#x44C;",
        "Р" => "&#x42D;", "СЌ" => "&#x44D;",
        "Р®" => "&#x42E;", "СЋ" => "&#x44E;",
        "РЇ" => "&#x42F;", "СЏ" => "&#x44F;"
    );

    if ($to_uni) {
        $str = strtr($str, $cp);
    } else {
        foreach ($cp as $c) {
            $cpp[$c] = array_search($c, $cp);
        }
        $str = strtr($str, $cpp);
    }

    return $str;
}

?>
emze at donazga dot net 17-Dec-2006 09:42
/*
Every function seen so far is incomplete or resource consumpting. Here are two -- integer 2 utf sequence (i3u) and utf sequence to integer (u3i). Below is a code snippet that checks well behavior at the range boundaries.

Someday they might be hardcoded into PHP...
*/

function i3u($i) { // returns UCS-16 or UCS-32 to UTF-8 from an integer
  $i=(int)$i; // integer?
  if ($i<0) return false; // positive?
  if ($i<=0x7f) return chr($i); // range 0
  if (($i & 0x7fffffff) <> $i) return '?'; // 31 bit?
  if ($i<=0x7ff) return chr(0xc0 | ($i >> 6)) . chr(0x80 | ($i & 0x3f));
  if ($i<=0xffff) return chr(0xe0 | ($i >> 12)) . chr(0x80 | ($i >> 6) & 0x3f)
      . chr(0x80  | $i & 0x3f);
  if ($i<=0x1fffff) return chr(0xf0 | ($i >> 18)) . chr(0x80 | ($i >> 12) & 0x3f)
      . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  if ($i<=0x3ffffff) return chr(0xf8 | ($i >> 24)) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  return chr(0xfc | ($i >> 30)) . chr(0x80 | ($i >> 24) & 0x3f) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
}

function u3i($s,$strict=1) { // returns integer on valid UTF-8 seq, NULL on empty, else FALSE
  // NOT strict: takes only DATA bits, present or not; strict: length and bits checking
  if ($s=='') return NULL;
  $l=strlen($s); $o=ord($s{0});
  if ($o <= 0x7f && $l==1) return $o;
  if ($l>6 && $strict) return false;
  if ($strict) for ($i=1;$i<$l;$i++) if (ord($s{$i}) > 0xbf || ord($s{$i})< 0x80) return false;
  if ($o < 0xc2) return false; // no-go even if strict=0
  if ($o <= 0xdf && ($l=2 && $strict)) return (($o & 0x1f) << 6 | (ord($s{1}) & 0x3f));
  if ($o <= 0xef && ($l=3 && $strict)) return (($o & 0x0f) << 12 | (ord($s{1}) & 0x3f) << 6
     |  (ord($s{2}) & 0x3f));
  if ($o <= 0xf7 && ($l=4 && $strict)) return (($o & 0x07) << 18 | (ord($s{1}) & 0x3f) << 12
     | (ord($s{2}) & 0x3f) << 6 |  (ord($s{3}) & 0x3f));
  if ($o <= 0xfb && ($l=5 && $strict)) return (($o & 0x03) << 24 | (ord($s{1}) & 0x3f) << 18
     | (ord($s{2}) & 0x3f) << 12 | (ord($s{3}) & 0x3f) << 6 |  (ord($s{4}) & 0x3f));
  if ($o <= 0xfd && ($l=6 && $strict)) return (($o & 0x01) << 30 | (ord($s{1}) & 0x3f) << 24
     | (ord($s{2}) & 0x3f) << 18 | (ord($s{3}) & 0x3f) << 12
     | (ord($s{4}) & 0x3f) << 6 |  (ord($s{5}) & 0x3f));
  return false;
}

// boundary behavior checking
$do=array(0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff);
foreach ($do as $ii) for ($i=$ii;$i<=$ii+1; $i++) {
  $o=i3u($i);
  for ($j=0;$j<strlen($o);$j++) print "O[$j]=" . sprintf('%08b',ord($o{$j})) . ", ";
  print "c=$i, o=[$o].\n";
  print "Back: [$o] => [" . u3i($o) . "]\n";
}
sadikkeskin at hotmail dot com 21-Nov-2006 02:49
i wrote a function to convert encoding utf8 to iso-8859-9. This function is very useful if you want to use this for ajax.
you can apply same way for other languages.
<?
function str_encode ($string,$to="iso-8859-9",$from="utf8") {
    if($to=="iso-8859-9" && $from=="utf8"){
        $str_array = array(
       chr(196).chr(177) => chr(253),
       chr(196).chr(176) => chr(221),
       chr(195).chr(182) => chr(246),
       chr(195).chr(150) => chr(214),
       chr(195).chr(167) => chr(231),
       chr(195).chr(135) => chr(199),
       chr(197).chr(159) => chr(254),
       chr(197).chr(158) => chr(222),
       chr(196).chr(159) => chr(240),
       chr(196).chr(158) => chr(208),
       chr(195).chr(188) => chr(252),
       chr(195).chr(156) => chr(220)
       );
       return str_replace(array_keys($str_array), array_values($str_array), $string);

    }
    return $string;
}
?>
genert at adsuk dot com 01-Oct-2006 10:23
If you encoded data with utf8_encode function and you would like to decode it in javascript use library found here: http://www.webtoolkit.info/. There is encoder too.
27-Sep-2006 01:30
In reply to Cundle:

Note: The BOM is completely unnecessary in UTF-8. UTF-8 is interpreted the same way regardless of endianness, e.g. О› (U+039B, GREEK CAPITAL LETTER LAMDA) is represented as the octets 0xCE, 0x9B, always in that order.

Extra note: UTF-16 and UCS-2 are different. The same letter would be encoded as 0x03 0x9B on big-endian (e.g. Motorola) architecture, but 0x9B 0x03 on little-endian (e.g Intel) architecture.

But in any case, there's nothing wrong with putting a BOM at the beginning of a UTF-8 encoded file. It is just treated as U+FEFF Zero Width No-Break Space.
James Cundle 18-Jul-2006 07:33
I had some difficulty finding a way to easily write UTF-8 files with the byte order mark included. This is the simple solution I have come up with:

<?php
function writeUTF8File($filename,$content) {
        $dhandle=fopen($filename,"w");
        # Now UTF-8 - Add byte order mark
        fwrite($dhandle, pack("CCC",0xef,0xbb,0xbf));
        fwrite($dhandle,$content);
        fclose($dhandle);
}
?>

When you read the file back in using fopen, the BOM will also be there. To remove it, I also wrote the following function:

<?php
function removeBOM($str=""){
        if(substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
                $str=substr($str, 3);
        }
        return $str;
}
?>
rocketman 16-Mar-2006 04:46
If you are looking for a function to replace special characters with the hex-utf-8 value (e.g. fГјr Webservice-Security/WSS4J compliancy) you might use this:

$textstart = "GrГ¶Гџe";
$utf8 ='';
$max = strlen($txt);

for ($i = 0; $i < $max; $i++) {

if ($txt{i} == "&"){
$neu = "&x26;";
}
elseif ((ord($txt{$i}) < 32) or (ord($txt{$i}) > 127)){
$neu = urlencode(utf8_encode($txt{$i}));
$neu = preg_replace('#\%(..)\%(..)\%(..)#','&#x\1;&#x\2;&#x\3;',$neu);
$neu = preg_replace('#\%(..)\%(..)#','&#x\1;&#x\2;',$neu);
$neu = preg_replace('#\%(..)#','&#x\1;',$neu);
}
else {
$neu = $txt{$i};
}

$utf8 .= $neu;
} // for $i

$textnew = $utf8;

In this example $textnew will be "Gr&#xC3;&#xB6;&#xC3;&#x9F;e"
mailing at jcn50 dot com 20-Jan-2006 10:40
I recommend using this alternative for every language:

$new=mb_convert_encoding($s,"UTF-8","auto");

Don't forget to set all your pages to "utf-8" encoding, otherwise just use HTML entities.

jcn50.
migueldiaz at gennio dot com 13-Dec-2005 09:23
Here's my function to know if one string is encoded in UTF8.

If we encode in UTF8 a string or text file that is already encoded in UTF8, it's expected to find the character 'ѓ' ( ALT+159)  in the final string.

<?php

function isUTF8($string)
{
    $string_utf8 = utf8_encode($string);
    if( strpos($string_utf8,"ѓ",0) !== false ) // "ѓ" is ALT+159
         return true;  // the original string was utf8
    else
         return false; // otherwise
}

?>

regards
Miguel Dнaz
04-Nov-2005 02:34
// Reads a file story.txt ascii (as typed on keyboard)
// converts it to Georgian character using utf8 encoding
// if I am correct(?) just as it should be when typed on Georgian computer
// it outputs it as an html file
//
// http://www.comweb.nl/keys_to_georgian.html
// http://www.comweb.nl/keys_to_georgian.php
// http://www.comweb.nl/story.txt

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<HTML>
<HEAD>
<TITLE>keys to unicode code</TITLE>

// this meta tag is needed
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

// note the sylfean font seems to be standard installed on Windows XP
// It supports Georgian

<style TYPE="text/css">
<!--
body {font-family:sylfaen; }
-->
</style>
</HEAD>

<BODY>

<?
$eng=array(97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,87,82,84,83,
67,74,90);
$geo=array(4304,4305,4330,4307,4308,4324,4306,4336,4312,4335,4313,
4314,4315,4316,4317,4318,4325,4320,4321,4322,4323,4309,
4332,4334,4327,4310,4333,4326,4311,4328,4329,4319,4331,
91,93,59,39,44,46,96);

$fc=file("story.txt");
foreach($fc as $line)
{
   $spacestart=1;
   for ($i=0; $i<strlen($line); $i+=1)
   {
      $character=ord(substr($line,$i,1));
      $found=0;
      for ($k=0; $k<count($eng); $k+=1)
      {
         if ($eng[$k]==$character)
         {
             print code2utf( $geo[$k] );
             $found=1;
         }
      }
      if ($found==0)
      {
         if ($character==126 || $character==32 || $character==10 || $character==9)
         {
            if ($character==9)  { print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; }
            if ($character==10) { print "<BR>\n"; }
            if ($character==32)
            {
               if ($spacestart==1) {print '&nbsp;'; } else { print " "; }
            }
            if ($character==126){ print "~";      }
         } else
         {
            print substr($line,$i,1);
         }
      }
      if ($character!=32) { $spacestart=0; }
   }
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
*/
function code2utf($num)
{
   if($num<128)return chr($num);
   if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
   if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
   if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
   return '';
}
?>

</BODY>
</HTML>
Janci 04-Nov-2005 04:00
I was searching for a function similar to Javascript's unescape(). In most cases it is OK to use url_decode() function but not if you've got UTF characters in the strings. They are converted into %uXXXX entities that url_decode() cannot handle.
I googled the net and found a function which actualy converts these entities into HTML entities (&#xxx;) that your browser can show correctly. If you're OK with that, the function can be found here: http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps

But it was not OK with me because I needed a string in my charset to make some comparations and other stuff. So I have modified the above function and in conjuction with code2utf() function mentioned in some other note here, I have managed to achieve my goal:

<?php
/**
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8).
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
 *
 * @param string $source escaped with Javascript's escape() function
 * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
 * @return string
 */
function unescape($source, $iconv_to = 'UTF-8') {
    $decodedStr = '';
    $pos = 0;
    $len = strlen ($source);
    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == '%') {
            $pos++;
            $charAt = substr ($source, $pos, 1);
            if ($charAt == 'u') {
                // we got a unicode character
                $pos++;
                $unicodeHexVal = substr ($source, $pos, 4);
                $unicode = hexdec ($unicodeHexVal);
                $decodedStr .= code2utf($unicode);
                $pos += 4;
            }
            else {
                // we have an escaped ascii character
                $hexVal = substr ($source, $pos, 2);
                $decodedStr .= chr (hexdec ($hexVal));
                $pos += 2;
            }
        }
        else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }

    if ($iconv_to != "UTF-8") {
        $decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
    }

    return $decodedStr;
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
 */
function code2utf($num){
    if($num<128)return chr($num);
    if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
    if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
    if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
    return '';
}
?>
aktionimskript at gmx dot net 01-Sep-2005 08:52
if you want to put variables as parameter in a flashfile, i prefer using to convert the string with utf8_encode() [or preg_replace, or iconv] and after this i encode it with urlencode();

<?php
     $yourstring="yourstring";
     $str_utf8=utf8_encode($yourstring);
     $str_encoded=urlencode($str_utf8);
     echo "<script language='javascript'>";
     echo "parameterForFlash='".$str_encoded."';";
     echo "</script>";
?>

now you can use the variable (parameterForFlash) in your javascript (plugindetection), that writes the flash object/embed.
suttichai at ceforce dot com 28-May-2005 12:26
This function I use convert Thai font (iso-8859-11) to UTF-8. For my case, It work properly. Please try to use this function if you have a problem to convert charset iso-8859-11 to UTF-8.

function iso8859_11toUTF8($string) {

     if ( ! ereg("[\241-\377]", $string) )
         return $string;

     $iso8859_11 = array(
"\xa1" => "\xe0\xb8\x81",
"\xa2" => "\xe0\xb8\x82",
"\xa3" => "\xe0\xb8\x83",
"\xa4" => "\xe0\xb8\x84",
"\xa5" => "\xe0\xb8\x85",
"\xa6" => "\xe0\xb8\x86",
"\xa7" => "\xe0\xb8\x87",
"\xa8" => "\xe0\xb8\x88",
"\xa9" => "\xe0\xb8\x89",
"\xaa" => "\xe0\xb8\x8a",
"\xab" => "\xe0\xb8\x8b",
"\xac" => "\xe0\xb8\x8c",
"\xad" => "\xe0\xb8\x8d",
"\xae" => "\xe0\xb8\x8e",
"\xaf" => "\xe0\xb8\x8f",
"\xb0" => "\xe0\xb8\x90",
"\xb1" => "\xe0\xb8\x91",
"\xb2" => "\xe0\xb8\x92",
"\xb3" => "\xe0\xb8\x93",
"\xb4" => "\xe0\xb8\x94",
"\xb5" => "\xe0\xb8\x95",
"\xb6" => "\xe0\xb8\x96",
"\xb7" => "\xe0\xb8\x97",
"\xb8" => "\xe0\xb8\x98",
"\xb9" => "\xe0\xb8\x99",
"\xba" => "\xe0\xb8\x9a",
"\xbb" => "\xe0\xb8\x9b",
"\xbc" => "\xe0\xb8\x9c",
"\xbd" => "\xe0\xb8\x9d",
"\xbe" => "\xe0\xb8\x9e",
"\xbf" => "\xe0\xb8\x9f",
"\xc0" => "\xe0\xb8\xa0",
"\xc1" => "\xe0\xb8\xa1",
"\xc2" => "\xe0\xb8\xa2",
"\xc3" => "\xe0\xb8\xa3",
"\xc4" => "\xe0\xb8\xa4",
"\xc5" => "\xe0\xb8\xa5",
"\xc6" => "\xe0\xb8\xa6",
"\xc7" => "\xe0\xb8\xa7",
"\xc8" => "\xe0\xb8\xa8",
"\xc9" => "\xe0\xb8\xa9",
"\xca" => "\xe0\xb8\xaa",
"\xcb" => "\xe0\xb8\xab",
"\xcc" => "\xe0\xb8\xac",
"\xcd" => "\xe0\xb8\xad",
"\xce" => "\xe0\xb8\xae",
"\xcf" => "\xe0\xb8\xaf",
"\xd0" => "\xe0\xb8\xb0",
"\xd1" => "\xe0\xb8\xb1",
"\xd2" => "\xe0\xb8\xb2",
"\xd3" => "\xe0\xb8\xb3",
"\xd4" => "\xe0\xb8\xb4",
"\xd5" => "\xe0\xb8\xb5",
"\xd6" => "\xe0\xb8\xb6",
"\xd7" => "\xe0\xb8\xb7",
"\xd8" => "\xe0\xb8\xb8",
"\xd9" => "\xe0\xb8\xb9",
"\xda" => "\xe0\xb8\xba",
"\xdf" => "\xe0\xb8\xbf",
"\xe0" => "\xe0\xb9\x80",
"\xe1" => "\xe0\xb9\x81",
"\xe2" => "\xe0\xb9\x82",
"\xe3" => "\xe0\xb9\x83",
"\xe4" => "\xe0\xb9\x84",
"\xe5" => "\xe0\xb9\x85",
"\xe6" => "\xe0\xb9\x86",
"\xe7" => "\xe0\xb9\x87",
"\xe8" => "\xe0\xb9\x88",
"\xe9" => "\xe0\xb9\x89",
"\xea" => "\xe0\xb9\x8a",
"\xeb" => "\xe0\xb9\x8b",
"\xec" => "\xe0\xb9\x8c",
"\xed" => "\xe0\xb9\x8d",
"\xee" => "\xe0\xb9\x8e",
"\xef" => "\xe0\xb9\x8f",
"\xf0" => "\xe0\xb9\x90",
"\xf1" => "\xe0\xb9\x91",
"\xf2" => "\xe0\xb9\x92",
"\xf3" => "\xe0\xb9\x93",
"\xf4" => "\xe0\xb9\x94",
"\xf5" => "\xe0\xb9\x95",
"\xf6" => "\xe0\xb9\x96",
"\xf7" => "\xe0\xb9\x97",
"\xf8" => "\xe0\xb9\x98",
"\xf9" => "\xe0\xb9\x99",
"\xfa" => "\xe0\xb9\x9a",
"\xfb" => "\xe0\xb9\x9b"
 );

     $string=strtr($string,$iso8859_11);
     return $string;
 }

Suttichai Mesaard-www.ceforce.com
bisqwit at iki dot fi 20-May-2005 01:15
For reference, it may be insightful to point out that:
  utf8_encode($s)
is actually identical to:
  recode_string('latin1..utf8', $s)
and:
  iconv('iso-8859-1', 'utf-8', $s)
That is, utf8_encode is a specialized case of character set conversions.

If your string to be converted to utf-8 is something other than iso-8859-1 (such as iso-8859-2 (Polish/Croatian)), you should use recode_string() or iconv() instead rather than trying to devise complex str_replace statements.
JF Sebastian 09-Apr-2005 03:54
The following Perl regular expression tests if a string is well-formed Unicode UTF-8 (Broken up after each | since long lines are not permitted here. Please join as a single line, no spaces, before use.):

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
\xe0[\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
\xed[\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
f0[\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
\xf4[\x80-\x8f][\x80-\xbf]{2})*$

NOTE: This strictly follows the Unicode standard 4.0, as described in chapter 3.9, table 3-6, "Well-formed UTF-8 byte sequences" ( http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G31703 ).

ISO-10646, a super-set of Unicode, uses UTF-8 (there called "UCS", see http://www.unicode.org/faq/utf_bom.html#1 ) in a relaxed variant that supports a 31-bit space encoded into up to six bytes instead of Unicode's 21 bits in up to four bytes. To check for ISO-10646 UTF-8, use the following Perl regular expression (again, broken up, see above):

^([\x00-\x7f]|
[\xc0-\xdf][\x80-\xbf]|
[\xe0-\xef][\x80-\xbf]{2}|
[\xf0-\xf7][\x80-\xbf]{3}|
[\xf8-\xfb][\x80-\xbf]{4}|
[\xfc-\xfd][\x80-\xbf]{5})*$

The following function may be used with above expressions for a quick UTF-8 test, e.g. to distinguish ISO-8859-1-data from UTF-8-data if submitted from a <form accept-charset="utf-8,iso-8859-1" method=..>.

function is_utf8($string) {
   return (preg_match('/[insert regular expression here]/', $string) === 1);
}
http://iubito.free.fr 09-Mar-2005 11:57
Here's a function I made to know if one string or textfile is already encoded in UTF8 :

<?php
/**
 * Returns <kbd>true</kbd> if the string or array of string is encoded in UTF8.
 *
 * Example of use. If you want to know if a file is saved in UTF8 format :
 * <code> $array = file('one file.txt');
 * $isUTF8 = isUTF8($array);
 * if (!$isUTF8) --> we need to apply utf8_encode() to be in UTF8
 * else --> we are in UTF8 :)
 * </code>
 * @param mixed A string, or an array from a file() function.
 * @return boolean
 */
function isUTF8($string)
{
    if (is_array($string))
    {
        $enc = implode('', $string);
        return @!((ord($enc[0]) != 239) && (ord($enc[1]) != 187) && (ord($enc[2]) != 191));
    }
    else
    {
        return (utf8_encode(utf8_decode($string)) == $string);
    }
}
?>
Denis G. 24-Feb-2005 05:32
Sniplet to convert ASCII coded text to UTF-8:

$text= preg_replace ('/([\x80-\xff])/se', "pack (\"C*\", (ord ($1) >> 6) | 0xc0, (ord ($1) & 0x3f) | 0x80)", $text);
anonymous at anonymous dot com 24-Jan-2005 02:49
A few bugs in your example code:

 function code2utf($num){
  if($num<128)return chr($num);
  if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
  if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
  if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
  return '';
 }
schofei at yahoo dot de 11-Jan-2005 03:23
regarding the above code2utf function...

> romans at void dot lv
> 02-Oct-2002 09:59
> Here is optimized function which converts
> binary UTF symbol code into unicoded string....

Thanks for providing your nice conversion code, however due to some missing parenthesis 4-byte utf-8 chars are not converted properly.

Here is a corrected version of the code2utf function:

 function code2utf($num){
  if($num<128)return chr($num);
  if($num<1024)return chr(($num>>6)+192).chr(($num&63)+128);
  if($num<32768)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
  if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
  return '';
 }

regards
Scho Fei
hrpeters (at) gmx (dot) net 13-Dec-2004 10:46
// Validate Unicode UTF-8 Version 4
// This function takes as reference the table 3.6 found at http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf
// It also flags overlong bytes as error

function is_validUTF8($str)
{
    // values of -1 represent disalloweded values for the first bytes in current UTF-8
    static $trailing_bytes = array (
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    );

    $ups = unpack('C*', $str);
    if (!($aCnt = count($ups))) return true; // Empty string *is* valid UTF-8
    for ($i = 1; $i <= $aCnt;)
    {
        if (!($tbytes = $trailing_bytes[($b1 = $ups[$i++])])) continue;
        if ($tbytes == -1) return false;

        $first = true;
        while ($tbytes > 0 && $i <= $aCnt)
        {
            $cbyte = $ups[$i++];
            if (($cbyte & 0xC0) != 0x80) return false;

            if ($first)
            {
                switch ($b1)
                {
                    case 0xE0:
                        if ($cbyte < 0xA0) return false;
                        break;
                    case 0xED:
                        if ($cbyte > 0x9F) return false;
                        break;
                    case 0xF0:
                        if ($cbyte < 0x90) return false;
                        break;
                    case 0xF4:
                        if ($cbyte > 0x8F) return false;
                        break;
                    default:
                        break;
                }
                $first = false;
            }
            $tbytes--;
        }
        if ($tbytes) return false; // incomplete sequence at EOS
    }
    return true;
}
Mark AT modernbill DOT com 09-Nov-2004 11:56
If you haven't guessed already: If the UTF-8 character has no representation in the ISO-8859-1 codepage, a ? will be returned. You might want to wrap a function around this to make sure you aren't saving a bunch of ???? into your database.
Aidan Kehoe <php-manual at parhasard dot net> 30-Aug-2004 07:05
Here's some code that addresses the issue that Steven describes in the previous comment;

<?php

/* This structure encodes the difference between ISO-8859-1 and Windows-1252,
   as a map from the UTF-8 encoding of some ISO-8859-1 control characters to
   the UTF-8 encoding of the non-control characters that Windows-1252 places
   at the equivalent code points. */

$cp1252_map = array(
    "\xc2\x80" => "\xe2\x82\xac", /* EURO SIGN */
    "\xc2\x82" => "\xe2\x80\x9a", /* SINGLE LOW-9 QUOTATION MARK */
    "\xc2\x83" => "\xc6\x92",     /* LATIN SMALL LETTER F WITH HOOK */
    "\xc2\x84" => "\xe2\x80\x9e", /* DOUBLE LOW-9 QUOTATION MARK */
    "\xc2\x85" => "\xe2\x80\xa6", /* HORIZONTAL ELLIPSIS */
    "\xc2\x86" => "\xe2\x80\xa0", /* DAGGER */
    "\xc2\x87" => "\xe2\x80\xa1", /* DOUBLE DAGGER */
    "\xc2\x88" => "\xcb\x86",     /* MODIFIER LETTER CIRCUMFLEX ACCENT */
    "\xc2\x89" => "\xe2\x80\xb0", /* PER MILLE SIGN */
    "\xc2\x8a" => "\xc5\xa0",     /* LATIN CAPITAL LETTER S WITH CARON */
    "\xc2\x8b" => "\xe2\x80\xb9", /* SINGLE LEFT-POINTING ANGLE QUOTATION */
    "\xc2\x8c" => "\xc5\x92",     /* LATIN CAPITAL LIGATURE OE */
    "\xc2\x8e" => "\xc5\xbd",     /* LATIN CAPITAL LETTER Z WITH CARON */
    "\xc2\x91" => "\xe2\x80\x98", /* LEFT SINGLE QUOTATION MARK */
    "\xc2\x92" => "\xe2\x80\x99", /* RIGHT SINGLE QUOTATION MARK */
    "\xc2\x93" => "\xe2\x80\x9c", /* LEFT DOUBLE QUOTATION MARK */
    "\xc2\x94" => "\xe2\x80\x9d", /* RIGHT DOUBLE QUOTATION MARK */
    "\xc2\x95" => "\xe2\x80\xa2", /* BULLET */
    "\xc2\x96" => "\xe2\x80\x93", /* EN DASH */
    "\xc2\x97" => "\xe2\x80\x94", /* EM DASH */

    "\xc2\x98" => "\xcb\x9c",     /* SMALL TILDE */
    "\xc2\x99" => "\xe2\x84\xa2", /* TRADE MARK SIGN */
    "\xc2\x9a" => "\xc5\xa1",     /* LATIN SMALL LETTER S WITH CARON */
    "\xc2\x9b" => "\xe2\x80\xba", /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
    "\xc2\x9c" => "\xc5\x93",     /* LATIN SMALL LIGATURE OE */
    "\xc2\x9e" => "\xc5\xbe",     /* LATIN SMALL LETTER Z WITH CARON */
    "\xc2\x9f" => "\xc5\xb8"      /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
);

function cp1252_to_utf8($str) {
        global $cp1252_map;
        return  strtr(utf8_encode($str), $cp1252_map);
}

?>
steven -at- acko -dot- net 17-Aug-2004 02:45
Note that you should only use utf8_encode() on ISO-8859-1 data, and not on data using the Windows-1252 codepage. Microsoft's Windows-1252 codepage contains ISO-8859-1, but it includes several characters in the range 0x80-0x9F whose codepoints in Unicode do not match the byte's value (in Unicode, codepoints U+80 - U+9F are unassigned).

utf8_encode() simply assumes the bytes integer value is the codepoint number in Unicode.

E.g. in 1252, byte 0x80 is the euro sign, which is U+20AC. The same goes for curly quotes, em dashes, etc.

utf8_encode() will convert 0x80 into U+0080 (an unassigned codepoint) rather than U+20AC.

To convert 1252 to UTF-8, use iconv, recode or mbstring.
Net Raven 24-Jun-2004 12:58
I often need to convert multi language text sent to me for use in websites and other apps into UTF8 encoded so I can insert it into source code and databases.

I knocked up a small web page with its charset set to UTF8 then set it up so I can paste from the original doc (eg word or excel) and have the page return the UTF8 encoded version.

Of course the browser will convert the unicode to UTF8 for you as part of the submit (I use IE5 or better for this) then all you have to do in the PHP is encode the UTF8 so the browser will show it in its raw form.

Its a bit bulky but I just convert ALL character to html numbered entities (brute force and ignorance does it again.)

I've used this to encode everything from Hebrew to Japanese without problems

<?
header("Content-Type: text/plain; charset=utf-8");
$code = (get_magic_quotes_gpc())?stripslashes($GLOBALS[code]):$GLOBALS[code];
?>
<html>
<head>
    <title>UTF8 ENCODER PAGE</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form method=post action="?seed=<?=time()?>">
    Original Unicode<br />
    <textarea name="code" cols="80" rows="10"><?=$code?></textarea><br />
    Encoded UTF8<br />
    <textarea name="encd" cols="80" rows="10"><?
        for ($i = 0; $i < strlen($code); $i++) {
            echo '&#'.ord(substr($code,$i,1));
        }
    ?></textarea><br />
    <input type="submit" value="encode">
</form>
</body>
</html>
lorro at lorro dot wigner dot bme dot hu 05-Apr-2004 07:12
Good news is that utf8_encode (like UTF-8) passes '<', '>', '/', '\'', '"', etc., so you are free to utf8_encode complete blocks of html text that includes tags.
Bad news is that UTF-8 is stupid enough so that utf8_encode(utf8_encode($str)) != utf8_encode($str) in most of the cases. What you can do is write utf8_ensure like:

function utf8_ensure($str) {
    return seems_utf8($str)? $str: utf8_encode($str);
}

Comes handy when your view library tries to encode the same text multiple times.
bmorel at ssi dot fr 17-Feb-2004 01:22
Here is an improved version of that function, compatible with 31-bit encoding scheme of Unicode 3.x :

<?php
function seems_utf8($Str) {
 for ($i=0; $i<strlen($Str); $i++) {
  if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
  elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
  elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
  elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
  elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
  elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
  else return false; # Does not match any model
  for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
   if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
    return false;
  }
 }
 return true;
}
?>
bmorel at ssi dot fr 16-Feb-2004 12:28
Here is a simple function that can help, if you want to know if a string could be UTF-8 or not :

<?php
function seems_utf8($Str) {
 for ($i=0; $i<strlen($Str); $i++) {
  if (ord($Str[$i]) < 0x80) $n=0; # 0bbbbbbb
  elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
  elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
  elseif ((ord($Str[$i]) & 0xF0) == 0xF0) $n=3; # 1111bbbb
  else return false; # Does not match any model
  for ($j=0; $j<$n; $j++) { # n octets that match 10bbbbbb follow ?
   if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80)) return false;
  }
 }
 return true;
}
?>
Karen 01-Oct-2003 12:33
Re the previous post about converting GB2312 code to Unicode code which displayed the following function:

<?
// Program by sadly (www.phpx.com)

function gb2unicode($gb)
{
   if(!trim($gb))
    return $gb;
   $filename="gb2312.txt";
   $tmp=file($filename);
   $codetable=array();
   while(list($key,$value)=each($tmp))
    $codetable[hexdec(substr($value,0,6))]=substr($value,9,4);
   $utf="";
   while($gb)
    {
      if (ord(substr($gb,0,1))>127)
     {
        $this=substr($gb,0,2);
        $gb=substr($gb,2,strlen($gb));
        $utf.="&#x".$codetable[hexdec(bin2hex($this))-0x8080].";";
      }
     else
     {
      $gb=substr($gb,1,strlen($gb));
      $utf.=substr($gb,0,1);
     }
     }
  return $utf;
}
?>

I found that a small change was needed in the code to properly handle latin characters embedded in the middle of gb2312 text, as when the text includes a URL or email address. Just reverse the two lines in the part of the statement above that handles ord vals !>127.

Change:

$gb=substr($gb,1,strlen($gb));
$utf.=substr($gb,0,1);

to:

$utf.=substr($gb,0,1);
$gb=substr($gb,1,strlen($gb));

In the original function, the first latin chacter was dropped and it was not converting the first non-latin character after the latin text (everything was shifted one character too far to the right). Reversing those two lines makes it work correctly in every example I have tried.

Also, the source of the gb2312.txt file needed for this to work has changed. You can find it a couple places:

http://tcl.apache.org/sources/tcl/tools/encoding/gb2312.txt
ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/GB/GB2312.TXT
artem at w510 dot tm dot odessa dot ua 02-Jun-2003 07:10
Loading variables in flash

you can lost a lot of hours if your charset is not iso-88951 and you cant' see your characters in flash

you must use iconv instead with your codepage
(for example windows-1251 for ukrainian, russian)

$fw = fopen("flash_input.txt", "w");
if( $fw )
{
    $utf = iconv("windows-1251","UTF-8",$variable_value);
    $out = 'variable_name='.$utf;
    fputs($fw, $out);
    fclose($fw);
}

and no urlecode is needed if you save data in file!
mualem_i at hotmail dot com 21-May-2003 06:12
Hebrew!! What a language. I had some trouble placing the Hebrew in a javascript based drop down menu, the text appeared as UTF8 so I made this function to overcome the problem (Not talking about efficiency)

function rtf_heb($string)
    {
    $array = split (" ",$string) ;
    foreach ($array as $VAL)
        {
        $VAL = str_replace("&#1488","а",$VAL);
        $VAL = str_replace("&#1489","б",$VAL);
        $VAL = str_replace("&#1490","в",$VAL);
        $VAL = str_replace("&#1491","г",$VAL);
        $VAL = str_replace("&#1492","д",$VAL);
        $VAL = str_replace("&#1493","е",$VAL);
        $VAL = str_replace("&#1494","ж",$VAL);
        $VAL = str_replace("&#1495","з",$VAL);
        $VAL = str_replace("&#1496","и",$VAL);
        $VAL = str_replace("&#1497","й",$VAL);
        $VAL = str_replace("&#1499","л",$VAL);
        $VAL = str_replace("&#1500","м",$VAL);
        $VAL = str_replace("&#1502","о",$VAL);
        $VAL = str_replace("&#1504","р",$VAL);
        $VAL = str_replace("&#1505","с",$VAL);
        $VAL = str_replace("&#1506","т",$VAL);
        $VAL = str_replace("&#1508","ф",$VAL);
        $VAL = str_replace("&#1510","ц",$VAL);
        $VAL = str_replace("&#1511","ч",$VAL);
        $VAL = str_replace("&#1512","ш",$VAL);
        $VAL = str_replace("&#1513","щ",$VAL);
        $VAL = str_replace("&#1514","ъ",$VAL);
        $VAL = str_replace("&#1498","к",$VAL);
        $VAL = str_replace("&#1507","у",$VAL);
        $VAL = str_replace("&#1503","п",$VAL);
        $VAL = str_replace("&#1501","н",$VAL);
        $VAL = str_replace("&#1509","х",$VAL);
        $VAL = str_replace(";","",$VAL);
        $send_VAR .= $VAL." ";

        }
        return $send_VAR;
    }
RoyLaw at 263 dot Net 19-May-2003 04:16
There is a function for converting GB2312 code to Unicode code.It maybe useful for programming on XML/WML in non-English lanaguages.

<?
// Program by sadly (www.phpx.com)

function gb2unicode($gb)
{
   if(!trim($gb))
    return $gb;
   $filename="gb2312.txt";
   $tmp=file($filename);
   $codetable=array();
   while(list($key,$value)=each($tmp))
    $codetable[hexdec(substr($value,0,6))]=substr($value,9,4);
   $utf="";
   while($gb)
    {
      if (ord(substr($gb,0,1))>127)
     {
        $this=substr($gb,0,2);
        $gb=substr($gb,2,strlen($gb));
        $utf.="&#x".$codetable[hexdec(bin2hex($this))-0x8080].";";
      }
     else
     {
      $gb=substr($gb,1,strlen($gb));
      $utf.=substr($gb,0,1);
     }
     }
  return $utf;
}
?>

This function requires a code list of gb2312,you can download it at
ftp://ftp.unicode.org/Public/MAPPINGS/EASTASIA/GB/GB2312.TXT
sunish_mv at rediffmail dot com 03-Apr-2003 10:50
/*Here I have a class that will convert ISCII (Indian Standard Code for Information Interchange) devnagiri (Hindi) string to unicode string. /*

<?php

  class iscii2utf8 {

      var $map;

      function iscii2utf8() {

          $this->map = array (
                   "a0" =>  '63'  ,
                 "a1" => '2305' ,
                 "a2" => '2306' ,
                 "a3" => '2307' ,
                 "a4" => '2309' ,
                 "a5" => '2310' ,
                 "a6" => '2311' ,
                 "a7" => '2312' ,
                 "a8" => '2313' ,
                 "a9" => '2314' ,
                 "aa" => '2315' ,
                 "ab" => '2318' ,
                 "ac" => '2319' ,
                 "ad" => '2320' ,
                 "ae" => '2317' ,
                 "af" => '2322' ,
                 "b0" => '2323' ,
                 "b1" => '2324' ,
                 "b2" => '2321' ,
                 "b3" => '2325' ,
                 "b4" => '2326' ,
                 "b5" => '2327' ,
                 "b6" => '2328' ,
                 "b7" => '2329' ,
                 "b8" => '2330' ,
                 "b9" => '2331' ,
                 "ba" => '2332' ,
                 "bb" => '2333' ,
                 "bc" => '2334' ,
                 "bd" => '2335' ,
                 "be" => '2336' ,
                 "bf" => '2337' ,
                 "c0" => '2338' ,
                 "c1" => '2339' ,
                 "c2" => '2340' ,
                 "c3" => '2341' ,
                 "c4" => '2342' ,
                 "c5" => '2343' ,
                 "c6" => '2344' ,
                 "c7" => '2345' ,
                 "c8" => '2346' ,
                 "c9" => '2347' ,
                 "ca" => '2348' ,
                 "cb" => '2349' ,
                 "cc" => '2350' ,
                 "cd" => '2351' ,
                 "ce" => '2399' ,
                 "cf" => '2352' ,
                 "d0" => '2353' ,
                 "d1" => '2354' ,
                 "d2" => '2355' ,
                 "d3" => '2356' ,
                 "d4" => '2357' ,
                 "d5" => '2358' ,
                 "d6" => '2359' ,
                 "d7" => '2360' ,
                 "d8" => '2361' ,
                 "d9" =>  '63'  ,
                 "da" => '2366' ,
                 "db" => '2367' ,
                 "dc" => '2368' ,
                 "dd" => '2369' ,
                 "de" => '2370' ,
                 "df" => '2371' ,
                 "e0" => '2374' ,
                 "e1" => '2375' ,
                 "e2" => '2376' ,
                 "e3" => '2373' ,
                 "e4" => '2378' ,
                 "e5" => '2379' ,
                 "e6" => '2380' ,
                 "e7" => '2377' ,
                 "e8" => '2381' ,
                 "e9" =>  '63'  ,
                 "ea" => '2404' ,
                 "eb" =>  '63'  ,
                 "ec" =>  '63'  ,
                 "ed" =>  '63'  ,
                 "ee" =>  '63'  ,
                 "ef" =>  '63'  ,
                 "f0" =>  '63'  ,
                 "f1" => '2406' ,
                 "f2" => '2407' ,
                 "f3" => '2408' ,
                 "f4" => '2409' ,
                 "f5" => '2410' ,
                 "f6" => '2411' ,
                 "f7" => '2412' ,
                 "f8" => '2413' ,
                 "f9" => '2414' ,
                 "fa" => '2415' ,
                 "fb" =>  '63'  ,
                 "fc" =>  '63'  ,
                 "fd" =>  '63'  ,
                 "fe" =>  '63'  ,
                 "ff" =>  '63'  ,);
        }

        function code2utf($num){

             //Returns the utf string corresponding to the unicode value
             //courtesy - romans@void.lv

             if($num<128)return chr($num);
             if($num<1024)return chr(($num>>6)+192).chr(($num&63)+128);
             if($num<32768)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
             if($num<2097152)return chr($num>>18+240).chr((($num>>12)&63)+128).chr(($num>>6)&63+128). chr($num&63+128);
             return '';

        }

        function convertstring($iscii) {
            //Returs utf8 string equibalent of given iscii string

            $str = "";
            for($i = 0; $i<strlen($iscii); $i++) {

                $c = dechex(ord(substr($iscii,$i,1)));
                if (isset($this->map[$c] )) {
                    $s = $this->code2utf($this->map[$c]);
                    $str .= ($s == "?")?"":$s;
                    }
                else {
                   $str .= substr($iscii,$i,1);
                   }

            }

            return $str;
        }

    }

?>
rbotzer at yahoo dot com 01-Apr-2003 01:25
BTW, the 21-bit range is pretty old news.  Unicode 3.x uses a 31bit encoding scheme that allows for 2 billion characters.

I'll post an enhanced encoder soon.  In the meanwhile here's the current encoding scheme: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8

Ronen
webmaster at swisswebgroup dot com 31-Mar-2003 05:54
if you try to pass data to a flash movie with the
actionscripts functions loadVars or sendAndLoad give this a try,
if you have problems with special chars like &auml; &ouml; ....

echo "&data1=".urlencode(utf8_encode("дць"))
    ."&data2=".urlencode(utf8_encode("ДЦЬ"));

greets

js
romans at void dot lv 02-Oct-2002 06:59
Here is optimized function which converts binary UTF symbol code into unicoded string.

 function code2utf($num){
  if($num<128)return chr($num);
  if($num<1024)return chr(($num>>6)+192).chr(($num&63)+128);
  if($num<32768)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
  if($num<2097152)return chr($num>>18+240).chr((($num>>12)&63)+128).chr(($num>>6)&63+128). chr($num&63+128);
  return '';
 }
dimitrisATccfDOTauthDOTgr 28-Aug-2002 11:04
To make utf8_encode and utf8_decode support other than iso-8859-1 encodings, you can easily define your encoding in the PHP source.
In the file PHP_SOURCE/ext/xml/xml.c add the following code, for e.g. greek iso-8859-7:

DEFINE TWO NEW FUNCTIONS UP TOP:
inline static unsigned short xml_encode_iso_8859_7(unsigned char);
inline static char xml_decode_iso_8859_7(unsigned short);

AND THEN IMPLEMENT THEM BELOW:
/* {{{ xml_encode_iso_8859_7() - Dimitris Daskopoulos 28/8/02 */
/* map iso-8859-7 chars to Unicode chars */
inline static unsigned short xml_encode_iso_8859_7(unsigned char c)
{
        if (c < 0x80) { /* low-ASCII, leave as is */
                return (unsigned short)c;
        } else { /* Greek character in high-ASCII */
                /* map to UCS greek range (U+0310..03ff) */
                /* assume that c < 0xff */
                return (unsigned short)(c + 720);
        }
}
/* }}} */

/* {{{ xml_decode_iso_8859_7() - Dimitris Daskopoulos 28/8/02 */
/* map Unicode chars to iso-8859-7 chars */
inline static char xml_decode_iso_8859_7(unsigned short c)
{
        if (c < 0x100) { /* char in latin chart, leave as is */
                return (char)c;
        } else if (c > 0x030f && c < 0x0400) { /* char in greek chart */
                /* map back to ISO-8859-7 greek (high-ASCII) */
                return (char)(c - 720);
        } else { /* char not in latin or greek Unicode charts */
                /* return question mark character */
                return (char)('?');
        }
}
/* }}} */

These two work fine for greek iso-8859-7, but studying http://www.unicode.org/charts you
can implement mappings between unicode and other iso-8859-x quite easily.

In both functions (utf8_encode and utf8_decode), change the requested encoding to the one you prefer, e.g.

encoded = xml_utf8_encode(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &len, "ISO-8859-7");

decoded = xml_utf8_decode(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &len, "ISO-8859-7");

Make sure you add the new encoding
in the structure, by entering a new
row with the official name (ISO-8859-7), and the names of the
two functions you have just defined:
xml_encoding xml_encodings[] = {
        { "ISO-8859-1", xml_decode_iso_8859_1, xml_encode_iso_8859_1 },
        { "US-ASCII",   xml_decode_us_ascii,   xml_encode_us_ascii   },
        { "UTF-8",      NULL,                  NULL                  },
        { "ISO-8859-7", xml_decode_iso_8859_7, xml_encode_iso_8859_7 },
        { NULL,         NULL,                  NULL                  }
};

Finally, the following is probably not necessary, but I changed the default encoding (found in 2 spots in this file) to whatever encoding you prefer in your
pages, e.g.:
XML(default_encoding) = "ISO-8859-7";

This solution is a little messy,
since the utf8_encode function does not accept an argument for choosing the encoding method to use but hardwires the encoding method in the source code. Maybe PHP developers will provide this option in future releases. Until then, this is a quick and dirty solution that will work for
localized PHP pages.

Dimitris Daskopoulos
27-Aug-2002 11:30
For XML generation, if you want non-ASCII ISO-8859-1 characters within text and attributes, you don't absolutely need UTF-8 encoding:

The optional XML declaration can change the default encoding for characters from UTF-8 to ISO-8859-1:

<?xml version="1.0" encoding="iso-8859-1" ?>

This can save a lot of PHP code if you just want to generate ISO-8859-1 text and attribute values...

XML specification requires that all parsers support both the UTF-8 encoding (by default), and the ISO-8859-1 character set. Other character sets may be supported also by specifying them in the encoding attribute of the leading XML declaration (but the target parser must support this character set to allow automatic conversion of the source text into Unicode character entities.
dutoit at NOSPAM dot abonder dot com 01-Aug-2002 11:50
To write an XML element $title containing "exotic" (eg. non ASCII й & а с...) 2 solutions I found :
Fastest :
$xml .= "<title><![CDATA[" . $title ."]]></title>\n"

or cleanest :
$xml .= "<title>".utf8_encode(htmlspecialchars($title))."</title>\n"

After that, your xml can be parsed without errors.
sts at netempire dot de at nospam dot remove at this dot com 12-Apr-2002 08:18
if you want to encode/decode arrays, use these recursive functions

function utf8_encode_array (&$array, $key) {
    if(is_array($array)) {
      array_walk ($array, 'utf8_encode_array');
    } else {
      $array = utf8_encode($array);
    }
}

function utf8_decode_array (&$array, $key) {
    if(is_array($array)) {
      array_walk ($array, 'utf8_decode_array');
    } else {
      $array = utf8_decode($array);
    }
}

and call them with array_walk for e.g.
array_walk ($array_unencoded, 'utf8_decode_array');
lars(at)ioflux(dot)net 13-Mar-2002 08:29
This will also do the job for those who're interested:

<?

function utf8toiso8859($string)
{
  $returns = "";
  $UTF8len = array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6);
  $pos = 0;
  $antal = strlen($string);

  do
  {
    $c = ord($string[$pos]);
    $len = $UTF8len[($c >> 2) & 0x3F];
    switch ($len)
    {
      case 6:
        $u = $c & 0x01;
        break;
      case 5:
        $u = $c & 0x03;
        break;
      case 4:
        $u = $c & 0x07;
        break;
      case 3:
        $u = $c & 0x0F;
        break;
      case 2:
        $u = $c & 0x1F;
        break;
      case 1:
        $u = $c & 0x7F;
        break;
      case 0:  /* unexpected start of a new character */
        $u = $c & 0x3F;
        $len = 5;
        break;
    }
    while (--$len && (++$pos < $antal && $c =
ord($string[$pos])))
    {
      if (($c & 0xC0) == 0x80)
        $u = ($u << 6) | ($c & 0x3F);
      else
      { /* unexpected start of a new character */
        $pos--;
        break;
      }
    }
    if ($u <= 0xFF)
      $returns .= chr($u);
    else
      $returns .= '?';
  } while (++$pos < $antal);
  return $returns;
}

?>
ronen at greyzone dot com 07-Mar-2002 12:01
The following function will utf-8 encode unicode entities &#nnn(nn); with n={0..9}

/**
* takes a string of unicode entities and converts it to a utf-8 encoded string
* each unicode entitiy has the form &#nnn(nn); n={0..9} and can be displayed by utf-8 supporting
* browsers.  Ascii will not be modified.
* @param $source string of unicode entities [STRING]
* @return a utf-8 encoded string [STRING]
* @access public
*/
function utf8Encode ($source) {
    $utf8Str = '';
    $entityArray = explode ("&#", $source);
    $size = count ($entityArray);
    for ($i = 0; $i < $size; $i++) {
        $subStr = $entityArray[$i];
        $nonEntity = strstr ($subStr, ';');
        if ($nonEntity !== false) {
            $unicode = intval (substr ($subStr, 0, (strpos ($subStr, ';') + 1)));
            // determine how many chars are needed to reprsent this unicode char
            if ($unicode < 128) {
                $utf8Substring = chr ($unicode);
            }
            else if ($unicode >= 128 && $unicode < 2048) {
                $binVal = str_pad (decbin ($unicode), 11, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 5);
                $binPart2 = substr ($binVal, 5);

                $char1 = chr (192 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $utf8Substring = $char1 . $char2;
            }
            else if ($unicode >= 2048 && $unicode < 65536) {
                $binVal = str_pad (decbin ($unicode), 16, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 4);
                $binPart2 = substr ($binVal, 4, 6);
                $binPart3 = substr ($binVal, 10);

                $char1 = chr (224 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $utf8Substring = $char1 . $char2 . $char3;
            }
            else {
                $binVal = str_pad (decbin ($unicode), 21, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 3);
                $binPart2 = substr ($binVal, 3, 6);
                $binPart3 = substr ($binVal, 9, 6);
                $binPart4 = substr ($binVal, 15);

                $char1 = chr (240 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $char4 = chr (128 + bindec ($binPart4));
                $utf8Substring = $char1 . $char2 . $char3 . $char4;
            }

            if (strlen ($nonEntity) > 1)
                $nonEntity = substr ($nonEntity, 1); // chop the first char (';')
            else
                $nonEntity = '';

            $utf8Str .= $utf8Substring . $nonEntity;
        }
        else {
            $utf8Str .= $subStr;
        }
    }

    return $utf8Str;
}

Ronen.
utf8_decode
xml_error_string
Р¤СѓРЅРєС†РёРё РїР°СЂСЃРµСЂР° XML


Получение строки ошибки XML анализатора

utf8_encode
xml_get_current_byte_index
Функции парсера XML
PHP Manual

xml_error_string

(PHP 4, PHP 5)

xml_error_string — Получение строки ошибки XML анализатора

Описание

string xml_error_string ( int $code )

Получение строкового представления ошибки XML анализатора в соответствии с переданным кодом ошибки code.

Список параметров

code

Код ошибки, возвращаемый функцией xml_get_error_code().

Возвращаемые значения

Возвращает строку с текстовым описанием кода ошибки code или FALSE, если описания не найдено.

Смотрите также

  • xml_get_error_code() - Получает код ошибки XML-парсера

User Contributed Notes

There are no user contributed notes for this page.
utf8_encode
xml_get_current_byte_index
Функции парсера XML


Получает текущий для XML анализатора байтовый индекс

xml_error_string
xml_get_current_column_number
Функции парсера XML
PHP Manual

xml_get_current_byte_index

(PHP 4, PHP 5)

xml_get_current_byte_index — Получает текущий для XML анализатора байтовый индекс

Описание

int xml_get_current_byte_index ( resource $parser )

Получает текущий для заданного XML анализатора байтовый индекс.

Список параметров

parser

Ссылка на XML анализатор, из которого будет получен индекс байта.

Возвращаемые значения

Эта функция вернет FALSE, если аргумент parser не ссылается на допустимый анализатор, в противном случае она возвращает индекс байта в буфере данных анализатора, на котором он находится в данный момент (начиная с нуля).

Примечания

Внимание

Эта функция возвращает байтовый индекс, считая, что текст закодирован в UTF-8. Смена кодировки не повлияет на вывод функции.

Смотрите также

  • xml_get_current_column_number() - Получает от XML парсера номер текущего столбца
  • xml_get_current_line_number() - Получает от XML-парсера номер текущей строки

User Contributed Notes

turan dot yuksel at tcmb dot gov dot tr 20-Sep-2005 03:38
The outcome of this function is heavily dependent on the parser implementation used. For example, at the point where the start_element_ callback is called, libxml2 parser consumes the entire element name and attributes, however expat does not.
xml_error_string
xml_get_current_column_number
Функции парсера XML


Получает от XML парсера номер текущего столбца

xml_get_current_byte_index
xml_get_current_line_number
Функции парсера XML
PHP Manual

xml_get_current_column_number

(PHP 4, PHP 5)

xml_get_current_column_number — Получает от XML парсера номер текущего столбца

Описание

int xml_get_current_column_number ( resource $parser )

Получает текущий номер столбца заданного XML парсера.

Список параметров

parser

Ссылка на парсер XML для получения номера столбца.

Возвращаемые значения

Эта функция возвращает FALSE, если ссылка параметра parser не ведет к действующему парсеру, или же возвращает номер столбца на текущей строке (определенной с помощью xml_get_current_line_number()) согласно текущему положению указателя парсера.

Смотрите также

  • xml_get_current_byte_index() - Получает текущий для XML анализатора байтовый индекс
  • xml_get_current_line_number() - Получает от XML-парсера номер текущей строки

User Contributed Notes

shaun at 5810 dot com 05-Jul-2003 09:04
Column numbers apparently start at 0. So you may want to add 1.
javajohn at gulfbridge.net 22-Mar-2003 10:03
"Column number" refers to the current character position within the current line of the XML document.
xml_get_current_byte_index
xml_get_current_line_number
Функции парсера XML


Получает от XML-парсера номер текущей строки

xml_get_current_column_number
xml_get_error_code
Функции парсера XML
PHP Manual

xml_get_current_line_number

(PHP 4, PHP 5)

xml_get_current_line_number — Получает от XML-парсера номер текущей строки

Описание

int xml_get_current_line_number ( resource $parser )

Получает номер текущей строки для заданного XML-парсера.

Список параметров

parser

Ссылка на парсер XML для получения номера строки.

Возвращаемые значения

Эта функция возвращает FALSE, если ссылка параметра parser не ведет к действующему парсеру, или же возвращает номер строки согласно текущему положению указателя парсера.

Смотрите также

  • xml_get_current_column_number() - Получает от XML парсера номер текущего столбца
  • xml_get_current_byte_index() - Получает текущий для XML анализатора байтовый индекс

User Contributed Notes

There are no user contributed notes for this page.
xml_get_current_column_number
xml_get_error_code
Функции парсера XML


Получает код ошибки XML-парсера

xml_get_current_line_number
xml_parse_into_struct
Функции парсера XML
PHP Manual

xml_get_error_code

(PHP 4, PHP 5)

xml_get_error_code — Получает код ошибки XML-парсера

Описание

int xml_get_error_code ( resource $parser )

Получает код ошибки XML-парсера.

Список параметров

parser

Ссылка на парсер XML для получения кода ошибки.

Возвращаемые значения

Эта функция возвращает FALSE, если ссылка параметра parser не ведет к действующему парсеру, или же возвращает один из кодов ошибок из списка, расположенного в разделе кодов ошибок.

Смотрите также

  • xml_error_string() - Получение строки ошибки XML анализатора

User Contributed Notes

gmsundar at geotekhsolutions dot com 28-May-2008 10:38
error codes
    *  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
xml_get_current_line_number
xml_parse_into_struct
Функции парсера XML


Разбор XML данных и помещение в массив

xml_get_error_code
xml_parse
Функции парсера XML
PHP Manual

xml_parse_into_struct

(PHP 4, PHP 5)

xml_parse_into_struct — Разбор XML данных и помещение в массив

Описание

int xml_parse_into_struct ( resource $parser , string $data , array &$values [, array &$index ] )

Эта функция разбирает XML строку и помещает данные в 2 массива. Массив index содержит указатели на размещение значений в массиве values. Аргументы, задающие массивы, должны передаваться в функцию по ссылке.

Список параметров

parser

Ссылка на используемый XML анализатор.

data

Строка XML данных.

values

Массив значений XML данных.

index

Массив указателей на соответствующие значения в массиве $values.

Возвращаемые значения

xml_parse_into_struct() возвращает 0 при неудачном разборе строки и 1 при успешном. Это не тоже самое, что FALSE и TRUE, будьте осторожны с такими операторами, как ===.

Примеры

Ниже представлен пример, демонстрирующий внутреннее устройство массивов, генерируемых функцией. XML строка содержит простой тэг note вложенный в тэг para. Программа в примере разбирает эту строку и выводит построенные массивы:

Пример #1 Пример использования xml_parse_into_struct()

<?php
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nМассив Vals\n";
print_r($vals);
?>

После обработки программа выведет следующее:

Index array
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

Массив Vals
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => simple note
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

Управляемый событиями разбор (основанный на expat библиотеке) может дать труднообрабатываемый результат в случае, если разбирается составной XML документ. Эта функция не создает DOM объектов, но создаваемые ею массивы можно преобразовать в древовидную структуру впоследствии. Таким образом можно довольно просто создавать объекты, представляющие содержимое XML файла. Предположим, что следующий XML файл представляет небольшую базу данных с информацией об аминокислотах:

Пример #2 moldb.xml - небольшая база данных с информацией о молекулах

<?xml version="1.0"?>
<moldb>

  <molecule>
      <name>Alanine</name>
      <symbol>ala</symbol>
      <code>A</code>
      <type>hydrophobic</type>
  </molecule>

  <molecule>
      <name>Lysine</name>
      <symbol>lys</symbol>
      <code>K</code>
      <type>charged</type>
  </molecule>

</moldb>
Код, разбирающий документ и создающий подходящие объекты:

Пример #3 parsemoldb.php - разбирает moldb.xml и помещает данные в массив молекул

<?php

class AminoAcid {
    var $name;  // название аминокислоты
    var $symbol;    // трехбуквенное обозначение
    var $code;  // однобуквенный код
    var $type;  // гидрофобная, заряженная, нейтральная

    function AminoAcid ($aa)
    {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename)
{
    // чтение XML базы данных аминокислот
    $data = implode("", file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);

    // проход через структуры
    foreach ($tags as $key=>$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // каждая смежная пара значений массивов является верхней и
            // нижней границей определения молекулы
            for ($i=0; $i < count($molranges); $i+=2) {
                $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues)
{
    for ($i=0; $i < count($mvalues); $i++) {
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** База данных аминокислот:\n";
print_r($db);

?>
После выполнения parsemoldb.php переменная $db содержит массив объектов AminoAcid, а вывод соответственно следующий:
** База данных аминокислот:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

User Contributed Notes

sujithfem at gmail dot com 26-Oct-2009 01:46
following function use to get the value for given XML tag

<?php
function getXmlValueByTag($inXmlset,$needle){
        $resource    =    xml_parser_create();//Create an XML parser
        xml_parse_into_struct($resource, $inXmlset, $outArray);// Parse XML data into an array structure
        xml_parser_free($resource);//Free an XML parser

        for($i=0;$i<count($outArray);$i++){
            if($outArray[$i]['tag']==strtoupper($needle)){
                $tagValue    =    $outArray[$i]['value'];
            }
        }
        return $tagValue;
    }

    echo getXmlValueByTag($inXmlset,$needle);
?>
Adam Tylmad 30-Apr-2009 12:59
Thanx to jukea i've upgraded the characterData-function to allow the value 0. Here is the new complete code:

<?php

class XMLParser {
    var $path;
    var $result;

    function cleanString($string) {
        return trim(str_replace("'", "&#39;", $string));
    }

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

    function startElement($parser, $tag, $attributeList) {
        $this->path .= "->".$tag;
        eval("\$data = ".$this->path.";");
        if (is_array($data)) {
            $index = sizeof($data);
            $this->path .= "[".$index."]";
        } else if (is_object($data)) {
            eval($this->path." = array(".$this->path.");");
            $this->path .= "[1]";
        }

        foreach($attributeList as $name => $value)
            eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
    }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        if (strlen($data = XMLParser::cleanString($data)))
            eval($this->path." = '$data';");
    }
}

?>
Adam Tylmad 30-Apr-2009 12:58
Thanx to jukea i've upgraded the characterData-function to allow the value 0. Here is the new complete code:

<?php

class XMLParser {
    var $path;
    var $result;

    function cleanString($string) {
        return trim(str_replace("'", "&#39;", $string));
    }

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

    function startElement($parser, $tag, $attributeList) {
        $this->path .= "->".$tag;
        eval("\$data = ".$this->path.";");
        if (is_array($data)) {
            $index = sizeof($data);
            $this->path .= "[".$index."]";
        } else if (is_object($data)) {
            eval($this->path." = array(".$this->path.");");
            $this->path .= "[1]";
        }

        foreach($attributeList as $name => $value)
            eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
    }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        if (strlen($data = XMLParser::cleanString($data)))
            eval($this->path." = '$data';");
    }
}

?>
aerik at thesylvans dot com 28-Nov-2008 03:55
Here's another attempt at dealing with rebuilding the xml from the array.  I'm basically preventing certain tags from being self closing by just checking for them explicitly (sure wish expat didn't interpret <textarea /> and <textarea></textarea> the same way (as "complete" tags).

<?php
function array2xml($xmlary){
  $o='';
  foreach($xmlary as $tag ){
    if($tag['tag'] == 'textarea' && !isset($tag['value'])){
      //fake a value so it won't self close
      $tag['value']='';
    }
    //tab space:
    $t = '';
    for($i=1; $i < $tag['level'];$i++){
      $t.="\t";
    }
    switch($tag['type']){
      case 'complete':
      case 'open':
        $o.=$t.'<'.$tag['tag'];
        if(isset($tag['attributes'])){
          foreach($tag['attributes'] as $attr=>$aval){
            $o.=' '.$attr.'="'.$aval.'"';
          }//foreach
        }//attributes
        if($tag['type'] == 'complete'){
          if(!isset($tag['value'])){
            $o .= ' />'."\n";
          } else {
            $o .= '>'."\n".$t.$tag['value']."\n".$t.'</'.$tag['tag'].'>'."\n";
          }
        }else{
          $o .= '>'."\n";
        }
        break;
      case 'close':
        $o .= $t.'</'.$tag['tag'].'>'."\n";
        break;
      case 'cdata':
        $o .= $t.$tag['value']."\n";
        break;
    }//switch
  }//foreach
}
?>
lpatrick 03-Nov-2008 04:36
@ dale at ucsc dot edu
I modified your code for entries like <caption>Value</caption>
<?php
$o='';
foreach( $vals as $tag ){
    //tab space:
    for($i=1; $i < $tag['level'];$i++)
        $o.="\t";
    if($tag['type']!='close'){
        if($tag['type']!='cdata')
            $o.='<'.$tag['tag'];
        if(isset($tag['attributes'])){
            foreach($tag['attributes'] as $attr=>$aval){
                $o.=' '.$attr.'="'.$aval.'"';
            }
        }
        if($tag['type']!='cdata'){
            $o.=($tag['type']=='complete' && (!isset($tag['value']) || $tag['value']==''))?'/>':'>';
        }
        $o.=(isset($tag['value']))?$tag['value']:'';
        if($tag['type']!='cdata'){
            $o.=($tag['type']=='complete' && (isset($tag['value']) && $tag['value']<>''))?'</'.$tag['tag'].'>':'';
        }
        $o.="\n";
    }else{
        $o.='</'.$tag['tag'].'>'."\n";
    }
}
?>
dale at ucsc dot edu 25-Sep-2008 04:16
here you can [re]assemble xml from a xml_parse_into_struct generated array: ie array2xml

<?php
$xml_parser = xml_parser_create( 'UTF-8' ); // UTF-8 or ISO-8859-1
xml_parser_set_option( $xml_parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option( $xml_parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct( $xml_parser, $my_text_xml, $aryXML );
xml_parser_free($xml_parser);

//now use aryXML array to xml string:
        $o='';
        foreach( $aryXML as $tag ){
            //tab space:
            for($i=1; $i < $tag['level'];$i++)
                $o.="\t";
            if($tag['type']!='close'){
                if($tag['type']!='cdata')
                    $o.='<'.$tag['tag'];
                if(isset($tag['attributes'])){
                    foreach($tag['attributes'] as $attr=>$aval){
                        $o.=' '.$attr.'="'.$aval.'"';
                    }
                }
                if($tag['type']!='cdata'){
                    $o.=($tag['type']=='complete')?'/>'."\n":'>'."\n";
                }
                $o.=(isset($tag['value']))?$tag['value']:'';
            }else{
                $o.='</'.$tag['tag'].'>';
            }
        }
?>
Llorenc 09-Sep-2008 03:20
Sorry, forgot my last post below, I confused CDATA sections (<![CDATA[]]>) with the value type "cdata", which despite its name it's very different! The first allows adding markup (&,<,>) as regular text and the second is to indicate a not complete node between the open and close nodes. What is true is that the CDATA delimiters are lost after xml_parse_into_struct so it's not possible to revert the process.

Please, feel free to remove my comments or leave them if you think they can help anyone.
Llorenc 09-Sep-2008 06:08
Many examples below using this function check if a given tag returned is of type "cdata". It seems to me nowadays CDATA sections are not detected by all implementations, if any. In the servers I could test (FreeBSD 6.2 with PHP 5.2.6 and libxml 2.6.26 or PHP 4.4.8 and expat 2.0.0 - MacOSX 10.5.4 with PHP 5.2.6 and libxml 2.6.16) my CDATA sections were reported as being of type "complete".

This problem was reported earlier as a bug (#26188), but was discarded because "the behaviour is quite dependent on the backend XML parsing implementation" (sic).

So if you want to detect CDATA sections and not depend on a given implementation, you'll have to forget this function and use xml_parse and xml_set_character_data_handler instead.
POST at PSPAETH dot DE 14-Aug-2008 08:45
I wrote a simple function which totally flattens any xml structure. You can then directly get the data or use regular expression functions to fetch data from the output. E.g., if the input is
   <gallery xmlns='http://www.pspaeth.de/joomlaPlugins/psg'>
        <g imageDir='einsatzGallerie'></g>
          <caption for="f1.jpg"}This is picture number 1</caption>
          <caption for="f2.jpg"}This is picture number 2</caption>
        </g>
   </gallery>
the output will be an array:
   ['.gallery0@xmlns']=>
      ".gallery0@xmlns=http://www.pspaeth.de/joomlaPlugins/psg"
   ['.gallery0.g0@imageDir']=>
      ".gallery0.g0@imageDir=einsatzGallerie"
   ['.gallery0.g0.caption0@for']=>
      ".gallery0.g0.caption0@for=f1.jpg"
   ['.gallery0.g0.caption0']=>
      ".gallery0.g0.caption0=This is picture number 1"
   ['.gallery0.g0.caption1@for']=>
      ".gallery0.g0.caption1@for=f2.jpg"
   ['.gallery0.g0.caption1']=>
      ".gallery0.g0.caption1=This is picture number 2"

Here the code:
<?php
function _xmlToArray($xml) {
   $parser = xml_parser_create('UTF-8'); // UTF-8 or ISO-8859-1
   xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
   xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
   xml_parse_into_struct($parser, $xml, $values);
   xml_parser_free($parser);

   $return = array();
   $stack = '';
   $attrs = array();
   $levelCounters = array(0);
   foreach($values as $val) {
     if($val['type'] == "open") {
       $ind = array_pop($levelCounters);
       $stack = $stack . "." . $val['tag'] . $ind;
       if ($val['attributes']) {
           foreach($val['attributes'] as $attrKey => $attrVal)
             $return[$stack . '@' . $attrKey] = $stack . '@' . $attrKey . "=" .
                $attrVal;
       }
       array_push($levelCounters,$ind+1);
       array_push($levelCounters,0);
     } elseif($val['type'] == "close") {
       $stack = substr($stack,0,strrpos($stack,'.'));
     } elseif($val['type'] == "complete") {
       $ind = array_pop($levelCounters);
       $stack = $stack . "." . $val['tag'] . $ind;
       if ($val['attributes']) {
           foreach($val['attributes'] as $attrKey => $attrVal)
             $return[$stack . '@' . $attrKey] = $stack . '@' . $attrKey . "=" .
                $attrVal;
       }
       $return[$stack] = $stack . "=" . $val['value'];
       $stack = substr($stack,0,strrpos($stack,'.'));
       array_push($levelCounters,$ind+1);
     }
   }
   return $return;
}
?>
wickedfather at hotmail dot com 06-Jul-2008 12:33
Had a comment up that was removed saying I'd found drawbacks, but here's a class what I wrote which works fine for me.  Comments removed due to post restrictions.  Pass the xml into the parse method or in the constructor.  Php4 and 5 safe.

class XMLThing
{
    var $rawXML;
    var $valueArray = array();
    var $keyArray = array();
    var $parsed = array();
    var $index = 0;
    var $attribKey = 'attributes';
    var $valueKey = 'value';
    var $cdataKey = 'cdata';
    var $isError = false;
    var $error = '';

    function XMLThing($xml = NULL)
    {
        $this->rawXML = $xml;
    }

    function parse($xml = NULL)
    {
        if (!is_null($xml))
        {
            $this->rawXML = $xml;
        }

        $this->isError = false;

        if (!$this->parse_init())
        {
            return false;
        }

        $this->index = 0;
        $this->parsed = $this->parse_recurse();
        $this->status = 'parsing complete';

        return $this->parsed;
    }

    function parse_recurse()
    {
        $found = array();
        $tagCount = array();

        while (isset($this->valueArray[$this->index]))
        {
            $tag = $this->valueArray[$this->index];
            $this->index++;

            if ($tag['type'] == 'close')
            {
                return $found;
            }

            if ($tag['type'] == 'cdata')
            {
                $tag['tag'] = $this->cdataKey;
                $tag['type'] = 'complete';
            }

            $tagName = $tag['tag'];

            if (isset($tagCount[$tagName]))
            {
                if ($tagCount[$tagName] == 1)
                {
                    $found[$tagName] = array($found[$tagName]);
                }

                $tagRef =& $found[$tagName][$tagCount[$tagName]];
                $tagCount[$tagName]++;
            }
            else
            {
                $tagCount[$tagName] = 1;
                $tagRef =& $found[$tagName];
            }

            switch ($tag['type'])
            {
                case 'open':
                    $tagRef = $this->parse_recurse();

                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                    }

                    if (isset($tag['value']))
                    {
                        if (isset($tagRef[$this->cdataKey]))
                        {
                            $tagRef[$this->cdataKey] = (array)$tagRef[$this->cdataKey];
                            array_unshift($tagRef[$this->cdataKey], $tag['value']);
                        }
                        else
                        {
                            $tagRef[$this->cdataKey] = $tag['value'];
                        }
                    }
                    break;

                case 'complete':
                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                        $tagRef =& $tagRef[$this->valueKey];
                    }

                    if (isset($tag['value']))
                    {
                        $tagRef = $tag['value'];
                    }
                    break;
            }
        }

        return $found;
    }

    function parse_init()
    {
        $this->parser = xml_parser_create();

        $parser = $this->parser;
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        if (!$res = (bool)xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray))
        {
            $this->isError = true;
            $this->error = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
        }
        xml_parser_free($parser);

        return $res;
    }
}
Anonymous 02-Jul-2008 08:35
@jemptymethod:

I found only one downfall to your function. If you have duplicates, the first one cannot be accessed iteratively.

I added the following to fix the problem:

<?php
...
        else if (is_array($parent['children'][$tag])) {
            if(!isset($parent['children'][$tag][0])) {
                $oldSingle = $parent['children'][$tag];
                $parent['children'][$tag] = null;
                $parent['children'][$tag][] = $oldSingle;

            }
              $parent['children'][$tag][] = $pop['children'];
        }
...
?>
jemptymethod at gmail dot com 16-Jun-2008 01:39
@wickedfather, re: beaudurrant....I just cannot concur that the latter's class is "great"....First of all, it doesn't handle attributes.  Second of all, as my code below demonstrates, there is no need waste processing by determining duplicates within their own loop.  Thirdly, when there are duplicates, it collapses the layer in the array above the duplicates.

Here is some much more consise code, though not (yet) object oriented, and also not yet handling attributes; it maintains a stack for each level:

<?php
function xml_parse_into_assoc($file) {
  $data = implode("", file($file));
  $p = xml_parser_create();

  xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);

  xml_parse_into_struct($p, $data, $vals, $index);
  xml_parser_free($p);

  $levels = array(null);

  foreach ($vals as $val) {
    if ($val['type'] == 'open' || $val['type'] == 'complete') {
      if (!array_key_exists($val['level'], $levels)) {
        $levels[$val['level']] = array();
      }
    }

    $prevLevel =& $levels[$val['level'] - 1];
    $parent = $prevLevel[sizeof($prevLevel)-1];

    if ($val['type'] == 'open') {
      $val['children'] = array();
      array_push(&$levels[$val['level']], $val);
      continue;
    }

    else if ($val['type'] == 'complete') {
      $parent['children'][$val['tag']] = $val['value'];
    }

    else if ($val['type'] == 'close') {
      $pop = array_pop($levels[$val['level']]);
      $tag = $pop['tag'];

      if ($parent) {
        if (!array_key_exists($tag, $parent['children'])) {
          $parent['children'][$tag] = $pop['children'];
        }
        else if (is_array($parent['children'][$tag])) {
          $parent['children'][$tag][] = $pop['children'];
        }
      }
      else {
        return(array($pop['tag'] => $pop['children']));
      }
    }

    $prevLevel[sizeof($prevLevel)-1] = $parent;
  }
}
?>
jukea 18-Apr-2008 02:09
concerning Adam Tylmad's code, note that the line

 if ($data = xml::cleanString($data))

prevents 0 values to be considered, as this will evaluate to false. I just tracked down this bug in our system .. ouch
wickedfather at hotmail dot com 12-Apr-2008 08:36
To beaudurrant - that class is great and structures things in a very sensible way.  Only problem is that it raises an error if a tag is empty, so would suggest a simple mod to the parse method just to add an isset test.

if (isset($val['value']))
{
    $this->setArrayValue($this->output, $stack, $val['value']);
}
mathiasrav at gmail dot com 10-Mar-2008 08:42
In response to Anonymous' post at 26-Feb-2008 11:50:

Saying that you "don't understand everything" isn't going to get you very popular - you should understand the code you use.
foreach isn't *slow* in PHP, it is actually faster than the equivalent for-construct (which, in many cases, isn't available).

The reason your script is slow is simply your use of xml_parse_into_struct - it reads the whole XML-string and doesn't return until it has parsed and validated it all. If you're looking for efficiency, you'll have to use the more low-level xml_parser_create, xml_set_*_handler functions. Then make sure you don't keep everything in a huge array before outputting it (at least don't if you're going for efficiency).
Anonymous 26-Feb-2008 02:50
Hi, I actually use this parser without understanding everything. I read somewhere that using "foreach" is very slow, and I indeed noticed that this parser was slow, when getting a lot of data, so how should I edit it to make it faster ? (with the exact same output) thanks in advance

    $xml_parser = xml_parser_create();
    $data = $outputone;

    xml_parse_into_struct($xml_parser, $data, $vals, $index);
    xml_parser_free($xml_parser);

    $params = array();
    $level = array();
    $i="1";

    foreach ($vals as $xml_elem) {
        if ($xml_elem['type'] == 'open' && $xml_elem['level'] == '1') {
                $level[$xml_elem['level']] = $xml_elem['tag'];
        }
        if ($xml_elem['type'] == 'open' && $xml_elem['level'] == '2') {
                $level[$xml_elem['level']] = $xml_elem['tag']."".$i;
                $i++;
        }
        if ($xml_elem['type'] == 'complete') {
            $start_level = 1;
            $php_stmt = '$params';
            while($start_level < $xml_elem['level']) {
                $php_stmt .= '[$level['.$start_level.']]';
                $start_level++;
            }
            $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
                eval($php_stmt);
        }
    }
cesaralcaide at gmail dot com 10-Jan-2008 02:35
I didn't fount an appropiate xml2array translaction for my purpose, so I wrote this:

(convert an xml string to an associative array allowing multiple elements with the same name)

/////////////////////////////////// Inicio XML
//
//
//
// Convierte un XML en un array asociativo cuyos elementos son arrays
// (para permitir varios elementos del mismo nombre)
//
// Limitación: el elemento "attributos" no puede aparecer en el XML, pues corresponde al
// de attribs de un tag (un Tag empieza con "T",no "t")
//
////////////////////////////////////

function xml_analiza($xml) {
 global $xml_resul,$xml_n,$xml_cont,$xml_attr;
 $xml_n = 0;
 $xml_resul = array();
 $xml_cont = array();
 $xml_attr = array();
 $p = xml_parser_create();
 //Si quisiéramos distinguir Mayúsculas-Minúsculas en los nombres de etiquetas:
 xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
 xml_set_element_handler($p, "xml_inicio", "xml_fin");
 xml_set_character_data_handler($p, "xml_char");

 // Recorta hasta el primer tag del XML:
 $i = instr($xml,"<" . "?xml");
 if (!$i) return array();
 $j = instr($i,$xml,"?" . ">");
 if (!$j) return array();
 $xml = substr($xml,$j+2);

 if (!xml_parse($p, $xml))
  alarma("URG","xml_analiza","XML error: " . xml_error_string(xml_get_error_code($p))
   . " en la línea " . xml_get_current_line_number($p) . " ($xml)");
 xml_parser_free($p);
 if (!sizeof($xml_resul)) return array();
 return $xml_resul[0];
}

function xml_inicio($p, $nombre, $atributos) {
 global $xml_resul,$xml_n,$xml_cont,$xml_attr;
 $xml_n++;
 $xml_resul[] = array();
 $xml_cont[] = "";
 $xml_attr[] = $atributos;
}

function xml_fin($p, $nombre) {
 global $xml_resul,$xml_n,$xml_cont,$xml_attr;
 $xml_n--;
 $nuevo = array_pop($xml_resul);
 $nombre = $nombre;
 if ($nombre == "attributos") alarma("URG","xml_analiza","Tag con nombre no permitido (attributos)");
 $conte = array_pop($xml_cont);
 $attrib = array_pop($xml_attr);
 if ($conte) $xml_resul[$xml_n][$nombre][] = $conte;
 else {
  if ($nuevo) {
   if ($attrib) $nuevo["attributos"][] = $attrib;
   $xml_resul[$xml_n][$nombre][] = $nuevo;
  }
  else
   $xml_resul[$xml_n][$nombre][] = "";
 }
}

function xml_char($p, $data) {
 global $xml_cont;
 $xml_cont[sizeof($xml_cont)-1] .= trim(str_replace("\n","",$data));
}

function xml_a($a) {
 // Devuelve un elemento del array XML, p.e.: xml_a($v,"FichaCircuito","Red",0)
 $n = func_num_args();
 for ($i=1;$i<$n;$i++) {
  $b = func_get_arg($i);
  if (isset($a[$b]))
   $a = $a[$b];
  else {
   if (!isset($a[0][$b][0])) return "";
   $a = $a[0][$b];
  }
 }
 return $a;
}
beaudurrant at gmail dot com 19-Dec-2007 11:23
This is extending what Alf Marius Foss Olsen had posted above.

It takes into account array keys with the same name and uses an increment for them instead of overwriting the keys.

I am using it for SOAP requests (20K - 150K) and it parses very fast compared to PEAR.

<?

class XMLParser  {

    // raw xml
    private $rawXML;
    // xml parser
    private $parser = null;
    // array returned by the xml parser
    private $valueArray = array();
    private $keyArray = array();

    // arrays for dealing with duplicate keys
    private $duplicateKeys = array();

    // return data
    private $output = array();
    private $status;

    public function XMLParser($xml){
        $this->rawXML = $xml;
        $this->parser = xml_parser_create();
        return $this->parse();
    }

    private function parse(){

        $parser = $this->parser;

        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);     // Dont bother with empty info
        if(!xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray)){
            $this->status = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
            return false;
        }
        xml_parser_free($parser);

        $this->findDuplicateKeys();

        // tmp array used for stacking
        $stack = array();
        $increment = 0;

        foreach($this->valueArray as $val) {
            if($val['type'] == "open") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack, $val['tag']);
                }
            } elseif($val['type'] == "close") {
                array_pop($stack);
                // reset the increment if they tag does not exists in the stack
                if(array_key_exists($val['tag'], $stack)){
                    $this->duplicateKeys[$val['tag']] = 0;
                }
            } elseif($val['type'] == "complete") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack,  $val['tag']);
                }
                $this->setArrayValue($this->output, $stack, $val['value']);
                array_pop($stack);
            }
            $increment++;
        }

        $this->status = 'success: xml was parsed';
        return true;

    }

    private function findDuplicateKeys(){

        for($i=0;$i < count($this->valueArray); $i++) {
            // duplicate keys are when two complete tags are side by side
            if($this->valueArray[$i]['type'] == "complete"){
                if( $i+1 < count($this->valueArray) ){
                    if($this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'] && $this->valueArray[$i+1]['type'] == "complete"){
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                    }
                }
            }
            // also when a close tag is before an open tag and the tags are the same
            if($this->valueArray[$i]['type'] == "close"){
                if( $i+1 < count($this->valueArray) ){
                    if(    $this->valueArray[$i+1]['type'] == "open" && $this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'])
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                }
            }

        }

    }

    private function setArrayValue(&$array, $stack, $value){
        if ($stack) {
            $key = array_shift($stack);
            $this->setArrayValue($array[$key], $stack, $value);
            return $array;
        } else {
            $array = $value;
        }
    }

    public function getOutput(){
        return $this->output;
    }

    public function getStatus(){
        return $this->status;
    }

}

?>

Usage:

$p = new XMLParser($xml);
$p->getOutput();
php dot net at crazedsanity dot com 24-Oct-2007 07:32
There's an updated version of cs-phpxml (http://sf.net/projects/cs-phpxml, or https://cs-phpxml.svn.sourceforge.net/svnroot/cs-phpxml/releases for the latest out of subversion) which easily converts an XML string into a PHP array.  Using my previous example:::

<?php
/**
 *
 * *********** EXAMPLE ***********
 *
 * Original file contents:
 * <test xmlns="stuff">
 *         <indexOne>hello</indexOne>
 *         <my_single_index testAttribute="hello" />
 *         <multiple_items>
 *             <item>1</item>
 *             <item>2</item>
 *         </multiple_items>
 * </test>
 *
 * Would return:::
 *
 * array(
 *     TEST => array(
 *         indexOne => hello,
 *         my_single_index => NULL,
 *         multiple_items => array(
 *               items => array(
 *                   0 => 1,
 *                   1 => 2
 *               )
 *         ),
 *     ),
 * );
*/
?>

I've been using this in many production environments, and it's been very stable.  The syntax is pretty simple, too:::

<?php
require_once(dirname(__FILE__) ."/cs-phpxml/xmlParserClass.php");
$xmlParser = new xmlParser(file_get_contents("test.xml"));
$myArray = $xmlParser->get_tree(TRUE);

?>
Alf Marius Foss Olsen 12-Sep-2007 06:46
<?php
/*
  An easy lightweight (Array ->) XML -> Array algorithm..

  Typical case: You have an array you want to export to an external server,
                so you make XML out of it, exports it, and "on the other side"
                make it into an array again. These two functions will take care
                of that last part, ie XML -> Array

  NOTE! The function XMLToArray assumes that the XML _dont_ have nodes on the
        same level with the same name, then it just wont work. This is not a
        problem, as this case deals with Array -> XML -> Array, and an array
        cant have to identical indexes/keys.
*/

function XMLToArray($xml) {
  $parser = xml_parser_create('ISO-8859-1'); // For Latin-1 charset
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); // Dont bother with empty info
  xml_parse_into_struct($parser, $xml, $values);
  xml_parser_free($parser);

  $return = array(); // The returned array
  $stack = array(); // tmp array used for stacking
  foreach($values as $val) {
    if($val['type'] == "open") {
      array_push($stack, $val['tag']);
    } elseif($val['type'] == "close") {
      array_pop($stack);
    } elseif($val['type'] == "complete") {
      array_push($stack, $val['tag']);
      setArrayValue($return, $stack, $val['value']);
      array_pop($stack);
    }//if-elseif
  }//foreach
  return $return;
}//function XMLToArray

function setArrayValue(&$array, $stack, $value) {
  if ($stack) {
    $key = array_shift($stack);
    setArrayValue($array[$key], $stack, $value);
    return $array;
  } else {
    $array = $value;
  }//if-else
}//function setArrayValue

// USAGE:
$xml = <<<QQQ
<?xml version="1.0"?>
<root>
  <node1>Some text</node1>
  <node2a>
    <node2b>
      <node2c>Some text</node2c>
    </node2b>
  </node2a>
</root>\n
QQQ;
$array = XMLToArray($xml);
print "<pre>";
print_r($array);
print "</pre>";
//  Output:
//
//  Array
//  (
//      [root] => Array
//          (
//              [node1] => Some text
//              [node2a] => Array
//                  (
//                      [node2b] => Array
//                          (
//                              [node2c] => Some text
//                          )
//                  )
//          )
//  )
?>
vinod at citadel-soft dot com 01-Sep-2007 03:43
My previous code was having some bugs in, that is fixed now

<?php
class CSLXmlReader {
    private $tagstack;
    private $xmlvals;
    private  $xmlvarArrPos;
    private $xmlfile;
    function __construct($filename)  // constructor to intialize the stack and val array
    {

        $this->tagstack = array();   // contain the open tags till now
        $this->xmlvals = array();
        $this->xmlvarArrPos = $this->xmlvals;  // temporary variable to hold the current tag position
        $this->xmlfile = $filename;
    }
    function readDatabase()
    {
        // read the XML database
        $data = implode("", file($this->xmlfile));
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $data, $values, $tags);
        xml_parser_free($parser);

        foreach($values as $key => $val)  //
        {
            if($val['type'] == "open")
            {
                array_push($this->tagstack, $val['tag']);
                $this->getArrayPath();
                if(count($this->xmlvarArrPos) > 0 && (!array_key_exists(0,$this->xmlvarArrPos)))
                {
                    $temp1 = $this->xmlvarArrPos;
                    $this->xmlvarArrPos =  array();
                    $this->xmlvarArrPos[0] = $temp1;
                    array_push($this->tagstack, 1);
                }
                else if( array_key_exists(0,$this->xmlvarArrPos)){
                    $opncount = count($this->xmlvarArrPos);
                    array_push($this->tagstack, $opncount);
                }
                $tagStackPointer += 1;
            }else if($val['type'] == "close")
            {
                while( $val['tag'] != ($lastOpened = array_pop($this->tagstack))){}
            }else if($val['type'] ==  "complete")
            {
                $this->getArrayPath();
                if( array_key_exists($val['tag'],$this->xmlvarArrPos))
                {
                    if(array_key_exists(0,$this->xmlvarArrPos[$val['tag']]))
                    {
                        $elementCount = count($this->xmlvarArrPos[$val['tag']]);
                        $this->xmlvarArrPos[$val['tag']][$elementCount] = $val['value'];
                    }else
                    {
                        $temp1 = $this->xmlvarArrPos[$val['tag']];
                        $this->xmlvarArrPos[$val['tag']] =  array();
                        $this->xmlvarArrPos[$val['tag']][0] = $temp1;
                        $this->xmlvarArrPos[$val['tag']][1] = $val['value'];
                    }
                } else
                {
                    $this->xmlvarArrPos[$val['tag']] = $val['value'];
                }
            }
        }
        reset($this->xmlvals);
        return $this->xmlvals;
    }
    function getArrayPath()
    {

        reset($this->xmlvals);
        $this->xmlvarArrPos = &$this->xmlvals;
        foreach($this->tagstack as $key)
        {
            $this->xmlvarArrPos = &$this->xmlvarArrPos[$key];

        }
    }

}

$readerObj  = new CSLXmlReader("test.xml");
$xmlvals = $readerObj->readDatabase();

echo "########## XML Values In array as the multidimentional array  #############\n";
echo "<pre>";
print_r($xmlvals);
echo "</pre>";

?>
php dot net at crazedsanity dot com 13-Jul-2007 10:43
If you're interested in something that creates arrays in PHP, handles attributes well, and is easily transferrable back into XML, you may want to take a look at the cs-phpxml project at SourceForge.net (http://sf.net/projects/cs-phpxml).  It's not necessarily documented very well, but it will do something like this:

<?php
/**
 *
 * *********** EXAMPLE ***********
 *
 * Original file contents:
 * <test xmlns="stuff">
 *         <indexOne>hello</indexOne>
 *         <my_single_index testAttribute="hello" />
 *         <multiple_items>
 *             <item>1</item>
 *             <item>2</item>
 *         </multiple_items>
 * </test>
 *
 * Would return:
 *
 * array(
 *     TEST => array(
 *         type => 'open',
 *         attributes => array(
 *             xmlns => 'stuff'
 *         )
 *         INDEXONE => 'hello',
 *         MY_SINGLE_INDEX = array(
 *             type => 'complete',
 *
 *         )
 *     )
 * );
*/
?>

It's presently under development, but I'm using it in several production environments.  The XMLCreator is kinda clunky (builds XML within PHP code).  NOTE: it has a dependency on "cs-arraytopath", also available at sourceforge via http://sf.net/projects/cs-arraytopath .  The setup is a bit irritating, and it's fragile when handling quoting & formatting the data, but I think it's worth the hassle for most projects.
siteres at gmail dot com 07-Feb-2007 01:38
PHP: XML to Array and backwards:

Here the XML with PHP solution: XML->Array and Array->XML.
Work with it as with usual array.

Sources are here:
http://mysrc.blogspot.com/2007/02/php-xml-to-array-and-backwards.html
(leave me comments:)

Example #1 (1.xml):

<ddd>
 <onemore dd="55">
  <tt>333</tt>
  <tt ss="s1">555</tt>
  <tt>777</tt>
 </onemore>
 <two>sdf rr</two>
</ddd>

The code:

$xml=xml2ary(file_get_contents('1.xml'));
print_r($xml);

Here is the Array result:

Array
(
   [ddd] => Array (
           [_c] => Array (
                   [_p] => Array *RECURSION*
                   [onemore] => Array (
                           [_a] => Array (
                                   [dd] => 55
                               )
                           [_c] => Array (
                                   [_p] => Array  *RECURSION*
                                   [tt] => Array (
                                           [0] => Array (
                                                   [_v] => 333
                                               )
                                           [1] => Array (
                                                   [_a] => Array (
                                                           [ss] => s1
                                                       )
                                                   [_v] => 555
                                               )
                                           [2] => Array (
                                                   [_v] => 777
                                               )
                                       )
                               )
                       )
                   [two] => Array (
                           [_v] => sdf rr
                       )
               )
       )
)
amish 08-Jan-2007 09:21
Previous parser worked great for me, except a few issues. It did not work well if the element has attributes. I had a huge xml with so many elements, and attributes. Somehow, it mixed up my array, and messed up the keys. Hope following code help fix those issues....

$xml_response = "
<test>
   <item>
     <name att=\"this should show up\">Item1</name>
     <id>item_1</id>
     <description> This is Item 1</description>
     <quantity>10</quantity>
     <navigation website='site1'>test1</navigation>
     <navigation website='site2'>test2</navigation>
   </item>
</test>
"

$parser = xml_parser_create();
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
xml_parse_into_struct($parser,$xml_response,$values,$tags);
xml_parser_free($parser);

$params = array();
$level = array();

foreach ($values as $xml_elem) {
    $start_level = 1;
           if ($xml_elem['type'] == 'open') {
            if (array_key_exists('attributes',$xml_elem)) {
                 list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
             } else {
                 $level[$xml_elem['level']] = $xml_elem['tag'];
             }
               $name_array    =    array();
         $i=0;
           }

           if ($xml_elem['type'] == 'complete') {
           if(!in_array($xml_elem['tag'], $name_array)){
                 array_push($name_array, $xml_elem['tag']);
                   $i=0;
              }else{
            $i++;
             }
             $php_stmt = '$params';
             while($start_level < $xml_elem['level']) {
                      $php_stmt .= '[$level['.$start_level.']]';
                    $test    =    $php_stmt;
                    $start_level++;
             }
             $php_stmt .= '[$xml_elem[\'tag\']][$i] = $xml_elem[\'value\'];';
             if(isset($xml_elem['attributes'])){
                         foreach ($xml_elem['attributes'] as $key=>$va){
                     $attribute    =    '';
                     $new_stmt    =    '';
                     $attribute    =    "".$i."_attribute_".$key."";
                       $new_stmt .= $test.'[$xml_elem[\'tag\']][$attribute] = $va;';
                     eval($new_stmt);
                    }
              }
              eval($php_stmt);
              $start_level--;
           }
           if ($xml_elem['type'] == 'close') {
           array_pop($level);
           }
}
webmaster at after5webdesign dot com 30-Nov-2006 04:48
That parser also has a problem in which it will not parse more items than the current level it is on. That is, parsing this:  <1><2>A</2><2>B</2><2>C</2></1>
Will only result in this: A B
C is never processed.

It might be better with something like this:
          $file = get_url('http://news.search.yahoo.com/news/rss?p=current+events', URL_CONTENT);
          $data = $file['content'];
          $xml_parser = xml_parser_create();
          xml_parse_into_struct($xml_parser, $data, $vals, $index);
          xml_parser_free($xml_parser);
          //Uncomment the lines below to see the entire structure of your XML document
          //echo "<pre>INDEX: \n";
          //print_r ($index);
          //echo "\n \n \n VALUES:";
          //print_r ($vals);
          //echo "</pre>";
          $params = array();
          $level = array();
          $start_level = 1;
          foreach ($vals as $xml_elem) {
            if ($xml_elem['type'] == 'open') {
              if (array_key_exists('attributes',$xml_elem)) {
                list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
              } else {
                $level[$xml_elem['level']] = $xml_elem['tag'];
              }
            }
            if ($xml_elem['type'] == 'complete') {
              $php_stmt = '$params';
              while($start_level < $xml_elem['level']) {
                $php_stmt .= '[$level['.$start_level.']]';
                $start_level++;
              }
              $php_stmt .= '[$xml_elem[\'tag\']][] = $xml_elem[\'value\'];';
              eval($php_stmt);
              $start_level--;
            }
          }
          echo "<pre>";
          print_r ($params);
          echo "</pre>";

~Tim_Myth
tsivert 17-Nov-2006 03:06
To John.

The reason that you only get the last item is that you declare a array of one element that is constantly overwritten by the last element...

I don't know if you want to put the items as two different childarrays of the parent or if you want to put the items in one childarray with two elements.

To put the items in two different childarrays, change the line
$php_stmt .= '[$level['.$start_level.']]';
to
$php_stmt .= '[$level['.$start_level.']][]';

To put in same childarray change line
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
to
$php_stmt .= '[$xml_elem[\'tag\']][] = $xml_elem[\'value\'];';

Hope this helps you!

tsivert
john 10-Nov-2006 11:15
I'm currently using this parser and it's working the way I want it to, but it has a little glitch and I was hoping maybe someone can let me know why.

Here's the parser and use for example purposes the following input:

$xml_response = '<?xml version="1.0" encoding="UTF-8"?>
<test>
    <item>First Item</item>
    <item>Second Item</item>
</test>'

$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xml_response, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
   if (array_key_exists('attributes',$xml_elem)) {
     list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
   } else {
     $level[$xml_elem['level']] = $xml_elem['tag'];
   }
  }
  if ($xml_elem['type'] == 'complete') {
   $start_level = 1;
   $php_stmt = '$params';
   while($start_level < $xml_elem['level']) {
     $php_stmt .= '[$level['.$start_level.']]';
     $start_level++;
   }
   $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
   eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";

At the output, only the last <item> shows (i.e.Second Item). The first one is lost.

What should I change so it keeps ALL <item> tags.
A3 03-Nov-2006 05:28
XML -> Array
<?
    $data = '<root><a><b x="s" a="2">asdf</b><c></c></a></root>';

    $p = xml_parser_create();
    xml_parse_into_struct($p, $data, $vals);
    xml_parser_free($p);

    $key = $output = array();
   foreach ($vals as $id=>$item) {
      if ($item["type"]=="open" || $item["level"]>count($key)) {// && count($key)<=$item["level"])
          array_push($key, $id);
          $temp = array("tag"=>$item["tag"], "value"=>"", "attributes"=>array());
          eval("\$output[".implode("][", $key)."] = \$temp;");
      }
      if ($item["type"]=="close" || $item["level"]<count($key))// && $item["level"]>=count($key))
          array_pop($key);
      if (isset($item["attributes"]))
          eval("\$output[".implode("][", $key)."]['attributes'] = array_merge(\$output[".implode("][", $key)."]['attributes'], \$item['attributes']);");
      if (isset($item["value"]))
          eval("\$output[".implode("][", $key)."]['value'] .= \$item['value'];");
   }
?>
Elad Elrom 12-Sep-2006 02:14
This is a quick fix for parsing XML from remote URL, some of the example above will work when trying to parse on your local server without "http://" but not when trying to parse from remote server using "http://www.URL"...

<?
$file="http://www.URL.com/file.XML";

$xml_parser = xml_parser_create();

$handle = fopen($file, "rb");
$contents = '';
while (!feof($handle)) {
  $data .= fread($handle, 8192);
}
fclose($handle);

xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
   if (array_key_exists('attributes',$xml_elem)) {
     list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
   } else {
     $level[$xml_elem['level']] = $xml_elem['tag'];
   }
  }
  if ($xml_elem['type'] == 'complete') {
   $start_level = 1;
   $php_stmt = '$params';
   while($start_level < $xml_elem['level']) {
     $php_stmt .= '[$level['.$start_level.']]';
     $start_level++;
   }
   $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
   eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>
mad dot cat at mcmadcat dot com 06-Sep-2006 04:55
this my love function:
<?php
function mc_parse_xml($filename)
{
    $xml = file_get_contents($filename);
    $p = xml_parser_create();
    xml_parse_into_struct($p, $xml, $values, $index);
    xml_parser_free($p);
    for ($i=0;$i<count($values);$i++) {
        if (isset($values[$i]['attributes'])) {
            $parent = $values[$i]['tag'];
            $keys = array_keys($values[$i]['attributes']);
            for ($z=0;$z<count($keys);$z++)
            {
                $content[$parent][$i][$keys[$z]] = $values[$i]['attributes'][$keys[$z]];
                if (isset($content[$parent][$i]['VALUE'])) $content[$parent][$i]['VALUE'] = $values[$i]['value'];
            }
        }
    }
    foreach ($content as $key => $values) {
        $content[$key] = array_values($content[$key]);
    }
    if (is_array($content)) return $content;
    else return false;
}
?>
webmaster at unitedscripters dot com 16-Jul-2006 05:29
Ps keep in mind that some Rss feeds include spurious tags as... html entities (see Google news Rss feeds: they include tables as &lt;table blah blah!).

If so, in my rssSnapper below add this:

<?php
$input=preg_replace("/(<!\\[CDATA\\[)|(\\]\\]>)/", '', $input);
$input=html_entity_decode($input); //<-- added line
?>

You may play around with the code and make it perfect, testing it on various feeds. Not _all_ XML is worth of an XML parser and the sleepless nights it entails.
webmaster at unitedscripters dot com 16-Jul-2006 02:43
It may be not entirely immaterial to stress that when you are dealing with incoming XML files such as RSS feeds, and you are about to include several of them in some page of yours, resorting to the PHP XML oriented functions is neither _necessarily_ the best idea, nor it is _strictly_ indispensable.

I have in mind, here, also a note that time ago was on this documentation by some info at gramba dot tv:

QUOTE
I was working with the xml2array functions below and had big performance problems. I fired them on a 20MB XML file and had to quit since all approaches of parsing where just too slow (more than 20 Minute parsing etc..). The solution was parsing it manually with preg_match, which increased performance by more than 20 times (processing time about 1 minute).
UNQUOTE

Calling in a specific XML structure function, and arranging a whole class, when all you want from an incoming files may be the contents of a few tags, is not the only option you are left with, when you are at PHP.

Here is a simple function that parses a XML RSS feed using no XML oriented function: keeping this in mind may spare you the need to create extremely complex classes as the ones we see here when _all_ you may want is a few titles and descriptions from an RSS (if that's your goal, you don't need XML parsers):

<?php
function rssSnapper($input='', $limit=0, $feedChannel='Yahoo!News'){
$input=file_get_contents($input);
    if(!$input){return '';};
$input=preg_replace("/[\\n\\r\\t]+/", '', $input);
$input=preg_replace("/(<!\\[CDATA\\[)|(\\]\\]>)/", '', $input);
preg_match_all("/<item>(.*?)<\\/item>/", $input, $items, PREG_SET_ORDER);
$limit=(int)$limit;
$limit=($limit && is_numeric($limit) && abs($limit)<sizeof($items))? sizeof($items)-abs($limit): 0;
while(sizeof($items)>$limit){
    $item=array_shift($items);
    $item=$item[1];
    preg_match_all("/<link>(.*?)<\\/link>/", $item, $link, PREG_SET_ORDER);
    preg_match_all("/<title>(.*?)<\\/title>/", $item, $title, PREG_SET_ORDER);
    preg_match_all("/<author>(.*?)<\\/author>/", $item, $author, PREG_SET_ORDER);
    preg_match_all("/<pubDate>(.*?)<\\/pubDate>/", $item, $pubDate, PREG_SET_ORDER);
    preg_match_all("/<description>(.*?)<\\/description>/", $item, $description, PREG_SET_ORDER);
        if(sizeof($link)){ $link = strip_tags($link[0][1]); };
        if(sizeof($title)){ $title = strtoupper( strip_tags($title[0][1]) ); };
        if(sizeof($author)){ $author = strip_tags($author[0][1]); };
        if(sizeof($pubDate)){ $pubDate = strip_tags($pubDate[0][1]); };
        if(sizeof($description)){ $description = strip_tags($description[0][1]); };
    print <<<USAVIT

    <!-- ITEM STARTS -->
    <div class="news_bg_trick">
    <a href="$link" class="item" target="_blank">
    <span class="title">$title<span class="channel">$feedChannel</span></span>
    <span class="title_footer">
    by <span class="author">$author</span> -
    <span class="date">$pubDate</span>
    </span>
    <span class="description">$description</span>
    </a>
    </div>
    <!-- ITEM ENDS -->

USAVIT;
}//out of loop
/*unitedscripters.com*/}
?>

The printing phase assigns Css class names: the output is thus fully customizable by a mere style sheet.

The use of strip_tags is a reminder from Chris Shiflett: distrust incoming data, always, anyway.
I hope no typos slipped in in transcription. Arguably not perfect, but I hope a good alternative idea to spending three days on a full fledged XML parser just to grab... three tags from a RSS feed!
bye, ALberto
efredricksen at gmail dot com 24-May-2006 12:55
Perhaps the one true parser:? I modified xademax's fine code to tidy it up, codewise and style wise, rationalize some minor crazyness, and make names fit nomenclature from the XML spec. (There are no uses of eval, and shame on you people who do.)

<?php
class XmlElement {
  var $name;
  var $attributes;
  var $content;
  var $children;
};

function xml_to_object($xml) {
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $xml, $tags);
  xml_parser_free($parser);

  $elements = array();  // the currently filling [child] XmlElement array
  $stack = array();
  foreach ($tags as $tag) {
    $index = count($elements);
    if ($tag['type'] == "complete" || $tag['type'] == "open") {
      $elements[$index] = new XmlElement;
      $elements[$index]->name = $tag['tag'];
      $elements[$index]->attributes = $tag['attributes'];
      $elements[$index]->content = $tag['value'];
      if ($tag['type'] == "open") {  // push
        $elements[$index]->children = array();
        $stack[count($stack)] = &$elements;
        $elements = &$elements[$index]->children;
      }
    }
    if ($tag['type'] == "close") {  // pop
      $elements = &$stack[count($stack) - 1];
      unset($stack[count($stack) - 1]);
    }
  }
  return $elements[0];  // the single top-level element
}

// For example:
$xml = '
<parser>
   <name language="en-us">Fred Parser</name>
   <category>
       <name>Nomenclature</name>
       <note>Noteworthy</note>
   </category>
</parser>
';
print_r(xml_to_object($xml));
?>

will give:

xmlelement Object
(
    [name] => parser
    [attributes] =>
    [content] =>
    [children] => Array
        (
            [0] => xmlelement Object
                (
                    [name] => name
                    [attributes] => Array
                        (
                            [language] => en-us
                        )

                    [content] => Fred Parser
                    [children] =>
                )

            [1] => xmlelement Object
                (
                    [name] => category
                    [attributes] =>
                    [content] =>
                    [children] => Array
                        (
                            [0] => xmlelement Object
                                (
                                    [name] => name
                                    [attributes] =>
                                    [content] => Nomenclature
                                    [children] =>
                                )

                            [1] => xmlelement Object
                                (
                                    [name] => note
                                    [attributes] =>
                                    [content] => Noteworthy
                                    [children] =>
                                )

                        )

                )

        )

)
Stuart 23-May-2006 03:26
This is a great little function for a lot of XML work, but note that this function does not handle XML entities properly.

The basic XML entities &lt; &gt; &amp; &quot; are fine, just anything else will not work:

If the entity is defined in the XML header, the parser will drop it completely from the struct it creates.

If the entity is not defined in the XML then the parser will crash out with an undefined entity error.

You should be able to work around this limitation by using a preg_replace on your XML string before passing it to the parser.

(Further details in Bug #35271; this is just a warning to those thinking of using this function for parsing real XML documents not just trivial XML examples)
donna at coloma dot com 28-Apr-2006 12:15
I needed a very simple parser for a set of name-value pairs to be stored in a single database field. I started with the mold example, paired it down, picked up the "id" attributes. Perhaps it will be useful for someone else.

<?php
/* simple conversion for name-value fields */

$xmlInput = "<?xml version=\"1.0\"?>
<mcw_settings>
  <field id=\"imageAlign\">left</field>
  <field id=\"caption\">What a nice picture.</field>
</mcw_settings>";

$desiredResult = array (
    'imageAlign' => "left",
    'caption' => "What a nice picture."
);

function parseFields ($data)
{
    // read the XML database of fields
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);
    $fields = null;

    // loop through the structures
    $fieldIndices = $tags['field'];
    for ( $i=0; $i < count($fieldIndices); $i++ ) {
        $fieldInfo = $values[$fieldIndices[$i]];
        $fields[$fieldInfo['attributes']['id']] = $fieldInfo['value'];
    }
    return $fields;
}

$test = parseFields($xmlInput);
echo "** Result:\n";
print_r($test);
?>
matt at australiangamer dot com 02-Apr-2006 07:58
I liked VampBoy's code as it gave me structure pretty much as I wanted it. Just two notes, though:

There is a bug in this code. subdivide() checks for pre-existing values, but not in the case of a "complete" element.

In the following (appallingly bad) XML

<Names>
<Name>Matt</Name>
<Name>Stacy</Name>
<Names>

Only Stacy is added to Names in the array, wiping Matt in the process.

To fix this replace the following code
<?php
elseif ($dat[level] === $level && $dat[type] === "complete"){
   $newarray[$dat[tag]]=$dat[value];
}
?>
with
<?php
elseif ($dat[level] === $level && $dat[type] === "complete"){
     if (isset($newarray[$dat['tag']]) && is_array($newarray[$dat['tag']])){
          $newarray[$dat['tag']][] = $dat['value'];
     } elseif (isset($newarray[$dat['tag']]) && !is_array($newarray[$dat['tag']])){
          $newarray[$dat['tag']] = array($newarray[$dat['tag']], $dat['value']);
     } else {
          $newarray[$dat['tag']]=$dat['value'];
     }
}?>

Oh, also, note that the $dat[level], etc, WILL generate warnings, and should be more correctly written as $dat['level'].

The other thing I thought I should point out is that the array keys when created using xml_parse_into_struct will be an UPPERCASE version of your existing element names. If case is important, especially if you, like me, need mixedCase, do the following:

<?php
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
?>
29-Mar-2006 11:57
$simple = '<?xml version="1.0"?>
<moldb>
    <molecule>
        <name>Alanine</name>
        <symbol>ala</symbol>
        <code>A</code>
        <type>hydrophobic</type>
    </molecule>
    <molecule>
        <name>Lysine</name>
        <symbol>lys</symbol>
        <code>K</code>
        <type>charged</type>
    </molecule>
</moldb>';

$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "<pre>";
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

foreach ($vals as $k => $v) {
    $i = 0;
    if (trim($v['value']) != '') {
        if ($arr[$i][$v['tag']] != '') {
            $i ++;
        }
        $arr[$i][$v['tag']] = $v['value'];
    }
}
xademax at gmail dot com 08-Jan-2006 12:15
This is just another simple xml parser :)

<?php

class Xml
{
    var $tag;
    var $value;
    var $attributes;
    var $next;
}

function xml2array($xml_string)
{
    $Parser = xml_parser_create();
    xml_parser_set_option($Parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($Parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($Parser, $xml_string, $Xml_Values);
    xml_parser_free($Parser);
    $XmlClass = array();
    $LastObj = array();
    $NowObj = &$XmlClass;

    foreach($Xml_Values as $Xml_Key => $Xml_Value)
    {
        $Index = count($NowObj);
        if($Xml_Value["type"] == "complete")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
        }
        elseif($Xml_Value["type"] == "open")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
            $NowObj[$Index]->next = array();
            $LastObj[count($LastObj)] = &$NowObj;
            $NowObj = &$NowObj[$Index]->next;
        }
        elseif($Xml_Value["type"] == "close")
        {
            $NowObj = &$LastObj[count($LastObj) - 1];
            unset($LastObj[count($LastObj) - 1]);
        }

    }

    return $XmlClass;
}

$String = "
<parser>
    <parseur_name>MyParser</parseur_name>
    <category>
        <name>Name 1</name>
        <note>A note 1</note>
    </category>
</parser>
";
$Xml = xml2array($String);

print_r($Xml);
?>

This exemple will show :
Array
(
    [0] => Xml Object
        (
            [tag] => parser
            [value] =>
            [attributes] =>
            [next] => Array
                (
                    [0] => Xml Object
                        (
                            [tag] => parseur_name
                            [value] => MyParser
                            [attributes] =>
                            [next] =>
                        )

                    [1] => Xml Object
                        (
                            [tag] => category
                            [value] =>
                            [attributes] =>
                            [next] => Array
                                (
                                    [0] => Xml Object
                                        (
                                            [tag] => name
                                            [value] => Name 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                    [1] => Xml Object
                                        (
                                            [tag] => note
                                            [value] => A note 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                )

                        )

                )

        )

)
VampBoy 14-Dec-2005 02:45
WHUPS! that was a broken test version.here is the real one:

class xml2array{
/* This class parses XML tags into a recursive, associative array with the tags as the associative array elements names.

if it encounters multiples of the same tag within a stream, it enumerates them as a sub array under the tag thus:

Array (
    [Lvl1tag] => Array (
        [0] => Array(
            [Lvl2tag] = "foo")
        [1]=> Array(
            [Lvl2tag] = "bar")
    )
)

It tries to detect when there is only one copy of a tag under another, and concatinate properly.
*/

    function readxmlfile($xmlfile){ // reads XML file in and returns it
      $xmlstream =fopen($xmlfile,r);
      $xmlraw=fread($xmlstream,1000000);
      fclose($xmlstream);
      return $xmlraw;
    }

    function parseXMLintoarray ($xmldata){ // starts the process and returns the final array
      $xmlparser = xml_parser_create();
      xml_parse_into_struct($xmlparser, $xmldata, $arraydat);
      xml_parser_free($xmlparser);
      $semicomplete = $this->subdivide($arraydat);
      $complete = $this->correctentries($semicomplete);
      return $complete;
    }

    function subdivide ($dataarray, $level = 1){
      foreach ($dataarray as $key => $dat){
        if ($dat[level] === $level && $dat[type] === "open"){
          $toplvltag = $dat[tag];
        } elseif ($dat[level] === $level && $dat[type] === "close" && $dat[tag]=== $toplvltag){
          $newarray[$toplvltag][] = $this->subdivide($temparray,($level +1));

          unset($temparray,$nextlvl);
        } elseif ($dat[level] === $level && $dat[type] === "complete"){
          $newarray[$dat[tag]]=$dat[value];
        } elseif ($dat[type] === "complete"||$dat[type] === "close"||$dat[type] === "open"){
          $temparray[]=$dat;
        }
      }
      return $newarray;
    }
function correctentries($dataarray){

if (is_array($dataarray)){
  $keys =  array_keys($dataarray);
  if (count($keys)== 1 && is_int($keys[0])){
    $tmp = $dataarray[0];
    unset($dataarray[0]);
       $dataarray = $tmp;
  }
  $keys2 = array_keys($dataarray);
  foreach($keys2 as $key){
    $tmp2 = $dataarray[$key];
    unset($dataarray[$key]);
    $dataarray[$key] = $this->correctentries($tmp2);
    unset($tmp2);
  }
  }
return $dataarray;
}
}
p dot gasiorowski at axent dot pl 13-Dec-2005 06:31
Something similar to kieran's _xml2array, however much more faster.
------
class ObjectFromXML
{
    var $parser;
    var $iter = 0;
    var $path = array();
    var $xml = array();

    function ObjectFromXML($XML)
    {
        $this->parser = xml_parser_create();

        xml_set_object($this->parser, &$this);

        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);

        xml_set_element_handler($this->parser, "hanleTagStart", "hanleTagEnd");
        xml_set_character_data_handler($this->parser, "hanleTagCData");

        xml_parse($this->parser, $XML);
        xml_parser_free($this->parser);

        $this->xml = $this->xml['_children'][0];
    }

    function getEvalPath()
    {
        return '$this->xml[' . "'" . implode("']['", $this->path) . "'" . ']';
    }

    function hanleTagStart($parser, $tag, $attributes)
    {
        array_push($this->path, '_children');
        array_push($this->path, ($this->iter++));

        $e = $this->getEvalPath();
        eval ($e . "['_name'] = \$tag;");
        if ($attributes !== array())
        {
            eval ($e . "['_attributes'] = \$attributes;");
        }
    }

    function hanleTagCData($parser, $cdata)
    {
        $e = $this->getEvalPath();
        eval ($e . "['_value'] = \$cdata;");
    }

    function hanleTagEnd($parser, $tag)
    {
        array_pop($this->path);
        array_pop($this->path);
    }
}
mbirth at webwriters dot de 08-Nov-2005 03:48
Searching for a nice and working way to get a RSS feed into an array-structure, I found the solution posted by kieran but disliked those several eval()s. So I wrote my own using references/pointers.

<?php

class RSSParser {

  var $struct = array();  // holds final structure
  var $curptr;  // current branch on $struct
  var $parents = array();  // parent branches of current branch

  function RSSParser($url) {
    $this->curptr =& $this->struct;  // set ref to base
    $xmlparser = xml_parser_create();
    xml_set_object($xmlparser, $this);
    xml_set_element_handler($xmlparser, 'tag_open', 'tag_close');
    xml_set_character_data_handler($xmlparser, 'cdata');
    $fp = fopen($url, 'r');

    while ($data = fread($fp, 4096))
      xml_parse($xmlparser, $data, feof($fp))
      || die(sprintf("XML error: %s at line %d",
         xml_error_string(xml_get_error_code($xmlparser)),
         xml_get_current_line_number($xmlparser)));

    fclose($fp);
    xml_parser_free($xmlparser);
  }

  function tag_open($parser, $tag, $attr) {
    $i = count($this->curptr['children']);
    $j = count($this->parents);
    $this->curptr['children'][$i]=array();  // add new child element
    $this->parents[$j] =& $this->curptr;  // store current position as parent
    $this->curptr =& $this->curptr['children'][$i];  // submerge to newly created child element
    $this->curptr['name'] = $tag;
    if (count($attr)>0) $this->curptr['attr'] = $attr;
  }

  function tag_close($parser, $tag) {
    $i = count($this->parents);
    if ($i>0) $this->curptr =& $this->parents[$i-1];  // return to parent element
    unset($this->parents[$i-1]);  // clear from list of parents
  }

  function cdata($parser, $data) {
    $data = trim($data);
    if (!empty($data)) {
      $this->curptr['value'] .= $data;
    }
  }

}

$myparser = new RSSParser('getitems.xml');
$anotherparser = new RSSParser('http://johndoe:secret@myfeeds.com/getfeed.xml');

print_r($myparser->struct);
print_r($anotherparser->struct);

?>
kieran at kieran dot ca 20-Oct-2005 09:20
<?
/*
|
| _xml2array - another abstraction layer on xml_parse_into_struct
|              that returns a nice nested array.
|
|      @param: $xml is a string containing a full xml document
|
|     returns: a nested php array that looks like this:
|
|              array
|              (
|                  [_name] => the name of the tag
|                  [_attributes] => an array of 'attribute'=>'value' combos
|                  [_value] => the text contents of the node
|                  [_children] => an array of these arrays, one for each node.
|              )
|
|       notes: thanks to 'jeffg at activestate dot com' who inspired
|              me to essentially re-write his example code from php.net
|
|           me: Kieran Huggins < kieran[at]kieran[dot]ca >
|
*/
function _xml2array($xml){
    global $keys;
    global $level;
    if(!is_array($xml)){ // init on first run
        $raw_xml = $xml;
        $p = xml_parser_create();
        xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($p, $raw_xml, $xml, $idx);
        xml_parser_free($p);
    }
    for($i=0;$i<count($xml,1);$i++){
        // set the current level
        $level = $xml[$i]['level'];

        if($level<1)break;

        // mark this level's tag in the array
        $keys[$level] = '['.$i.']';

        // if we've come down a level, sort output and destroy the upper level
        if(count($keys)>$level) unset($keys[count($keys)]);

        // ignore close tags, they're useless
        if($xml[$i]['type']=="open" || $xml[$i]['type']=="complete"){

            // build the evalstring
            $e = '$output'.implode('[\'_children\']',$keys);

            // set the tag name
            eval($e.'[\'_name\'] = $xml[$i][\'tag\'];');

            // set the attributes
            if($xml[$i]['attributes']){
                eval($e.'[\'_attributes\'] = $xml[$i][\'attributes\'];');
            }

            // set the value
            if($xml[$i]['value']){
                eval($e.'[\'_value\'] = trim($xml[$i][\'value\']);');
            }

        }

    }

    return $output;
}
?>
info at gramba dot tv 23-Aug-2005 08:54
I was working with the xml2array functions below and had big performance problems. I fired them on a 20MB XML file and had to quit since all approaches of parsing where just too slow (more than 20 Minute parsing etc..). The solution was parsing it manually with preg_match, which increased performance by more than 20 times (processing time about 1 minute).

Rough example function with high performance:

<?php

function customXMLtoARRAY($xmlstring) {

    // get all nodes
    preg_match_all("#<node>(.*?)</node>#s",$xmlstring,$nodes);
    $xmlstring = NULL;

    $allnodes = array();

    // put subnodes into node
    while($nodes = array_pop($nodes[1])) {

        $nodecontent = array();

        // Content1
        preg_match("#<content1>(.*?)</content1>#",$eventreihe,$val);
        $nodecontent['content1'] = $val[1];

        $allnodes[] = $nodecontent;

    }
    return $allnodes;
}

?>
Chris Hester 28-Jul-2005 05:06
The array generated from XML stores not only the elements but also any spaces and linebreaks between the tags. This results in a much longer array. (I had 24 array fields instead of 10!) To cure this use the following code when creating the parser:

<?php
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
?>
grusin at gmail dot com 19-Jul-2005 11:54
Here is a simple patch to peter's xml2array function.

Replace:

<?
case 'open':
$tag_or_id = (array_key_exists ('attributes', xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
$ptrs[$level][$tag_or_id] = array ();
$ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
break;
?>

with:

<?
case 'open':
$tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
$ptrs[$level][$tag_or_id][] = array ();
$ptrs[$level+1] = & $ptrs[$level][$tag_or_id][count($ptrs[$level][$tag_or_id])-1];
break;
?>

and now code should handle multiple element case :)
Dustin 13-Jul-2005 08:39
If you happen to have problems with weird charaters, I added this code to the first line of dUDA's function:

$XML = utf8_decode($XML);
PhF at madmac dot fr 23-Jun-2005 01:11
The code previously posted by noob at noobsrule dot com doesn't work when the same tag name is used at different levels.
(but perhaps "$php_used_prefix" was intended for that ?)
For example:
<RatedShipment>
  <TransportationCharges>
    ...
  </TransportationCharges>
  <RatedPackage>
    <TransportationCharges>
      ...
    </TransportationCharges>
  </RatedPackage>
</RatedShipment>
<?php
    $p = xml_parser_create();
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($p, $UPSxml, $values, $idx);
    xml_parser_free($p);

    // tracking used keys
    $usedKeys = array();
    $deepLevel = -1;

    // start a php array string (evaluated later)
    $forEvalPrefix = '$xml_array';

    // loop throught the value array
    foreach ($values as $key => $val) {
        $tagName = $val['tag']; // pass the key tag into a more friendly looking variable
        $level = $val['level']; // idem
        if($val['type'] == 'open') {
            $deepLevel++; // increase deep level
            $forEvalPrefix .= '[\''. $tagName .'\']';

            // begin used keys checks to allow multidimensionatity under the same tag
            (isset($usedKeys[$level][$tagName])) ? $usedKeys[$level][$tagName]++ : $usedKeys[$level][$tagName] = 0;
            $forEvalPrefix .= '['. $usedKeys[$level][$tagName] .']';
        }
        if($val['type'] == 'complete') {
            ($level > $deepLevel) ? $deepLevel++ : ''; // increase $deepLevel only if current level is bigger
            $tagValue = addslashes($val['value'] ); // format the value for evaluation as a string
            $forEvalSuffix = '[\''. $tagName .'\'] = \''. $tagValue .'\';'; // create a string to append to the current prefix
            $forEval = $forEvalPrefix . $forEvalSuffix; // (without "$php_used_prefix"...)
            eval($forEval); // write the string to the array structure
        }
        if($val['type'] == 'close') {
            unset($usedKeys[$deepLevel]); // Suppress tagname's keys useless
            $deepLevel--;
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the used keys node
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the end level of the array string prefix
        }
    }
echo '<pre>';
print_r ($xml_array);
echo '</pre>';
?>

MADmac ;-)
peter at elemental dot org 15-Jun-2005 08:46
Quick addendum to my post below... The code does *not* handle cases where multiple elements are used without attribute IDs, as is the case with the moldb example.  (It is probably worth noting that some of the other code below doesn't do this either, and is still more complex.)

It is not difficult to add that functionality, but I have yet to find an elegant way to integrate that feature, and since I don't need that functionality at the moment, I'm going leave that as an exercise to the reader.  ;-)

-p.
peter at elemental dot org 14-Jun-2005 04:09
Some of the code posted previously seemed absurdly complex, so I thought I'd see if I could simplify things a bit. Here's what I came up with.  (I'm still a PHP newbie, so perhaps I simplified too much.  ;-)  Untested for speed, but it *should* be pretty quick since it uses references instead of lookups or (gack) evals.

Enjoy!

/*
 *  Convert a string containing XML into a nested array
 *
 *  Takes a raw XML string as input
 *  Returns a nested array
 */

function xml2array ($xml_data)
{
    // parse the XML datastring
    $xml_parser = xml_parser_create ();
    xml_parse_into_struct ($xml_parser, $xml_data, $vals, $index);
    xml_parser_free ($xml_parser);

    // convert the parsed data into a PHP datatype
    $params = array();
    $ptrs[0] = & $params;
    foreach ($vals as $xml_elem) {
        $level = $xml_elem['level'] - 1;
        switch ($xml_elem['type']) {
        case 'open':
            $tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
            $ptrs[$level][$tag_or_id] = array ();
            $ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
            break;
        case 'complete':
            $ptrs[$level][$xml_elem['tag']] = (isset ($xml_elem['value'])) ? $xml_elem['value'] : '';
            break;
        }
    }

    return ($params);

}
gleber at mapnet dot pl 26-Mar-2005 03:03
XMLtoArray created by dudus at onet dot pl was not good enough for me, that's why i decided to create my own version, and here's the result:

<?php

function &last(&$array) {
if (!count($array)) return null;
end($array);
return $array[key($array)];
}

function myParseXML(&$vals, &$dom, &$lev) {
    do {
        $curr = current($vals);
        $lev = $curr['level'];
        switch ($curr['type']) {
            case 'open':
                if (isset($dom[$curr['tag']])) {
                    $tmp = $dom[$curr['tag']];
                    if (!$tmp['__multi'])
                        $dom[$curr['tag']] = array('__multi' => true, $tmp);
                    array_push($dom[$curr['tag']], array());
                    $new =& last($dom[$curr['tag']]);
                } else {
                    $dom[$curr['tag']] = array();
                    $new =& $dom[$curr['tag']];
                }
                next($vals);
                myParseXML(&$vals, $new, $lev);
                break;
            case 'cdata':
                break;
            case 'complete':
                if (!isset($dom[$curr['tag']]))
                    $dom[$curr['tag']] = $curr['value'];
                else {
                    if (is_array($dom[$curr['tag']]))
                        array_push($dom[$curr['tag']] , $curr['value']);
                    else
                        array_push($dom[$curr['tag']] = array($dom[$curr['tag']]) , $curr['value']);
                }
                break;
            case 'close':
                return;
        }
    }
    while (next($vals)!==FALSE);
}

function MyXMLtoArray($XML) {
       $xml_parser = xml_parser_create();
       xml_parse_into_struct($xml_parser, $XML, $vals);
       xml_parser_free($xml_parser);
       reset($vals);
       $dom = array(); $lev = 0;
       myParseXML($vals, $dom, $lev);
       return $dom;
}

?>

MyXMLtoArray() is that function you should call, other are for "internal" use.

P.S. It's 4-5 time faster then dudus at onet dot pl 's code
noob at noobsrule dot com 24-Jan-2005 10:59
This is my first time contributing but I found all the examples either didn't work or were beyond my comprehension.  I also wanted to maintain the XML multi-dimensionality so I could do loops based on keys I was expecting rather than numbers or some other whatnot.  This script is probably way inefficient, but should give you a multidimensional array with a depth that will match the XML source.  Great for situations when you aren't sure what you'll be getting back.  Its also only based on the values array of xml_parse_into_str() using the 3 tag types (open, complete, and close) -- hopefully it will make more sense to other noobs.

Basically it just constructs a string ($php_prefix) that is tweaked if it hits an "open" or "close" tag and evaluated if it hits a "complete" tag.

Thanks.

<?php

# initiate curl session...
$ch = curl_init( "http://yourtargethost" ) or die ( "could not initialize curl" );

# set curl options...
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $request_str );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0 );
curl_setopt( $ch, CURLOPT_REFERER, https://foobar.com" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

# execute curl commands...
$curl_result = curl_exec( $ch ) or die ( "could not execute the post" );
curl_close( $ch ); // close curl session

# pass the XML result into 2 arrays ( index and values )...
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($p, $curl_result, $vals, $index);
xml_parser_free($p);

# create an empty used key tracker...
$used_keys = array();

# start a php array string (evaluated later)...
$php_prefix = "$"."my_array";

# loop through the values array...
foreach ($vals as $key => $val) {
    if( $val['type'] == "open" ) {
        $my_tag = $val['tag']; // pass the key tag into a more friendly looking variable...
        $php_prefix .= "['".$my_tag."']"; # add a new level to the array string...

        # begin used key checks to allow multidimensionality under the same tag, adds a number to the prefix if necessary...
        if( ! array_key_exists( $my_tag, $used_keys ) ) {
            $used_keys[$my_tag] = 0;
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }else {
            $used_keys[$my_tag]++; // increment the key tracker to avoid overwriting existing key...
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }
    } elseif( $val['type'] == "complete" ) {
        $my_value = addslashes( $val['value'] ); # format the value for evaluation as a string...
        $php_suffix = "['".$val['tag']."'] = \"".$my_value."\";"; # create a string with the tag and value to append to the current prefix (just used here)...
        $php_str = $php_prefix.$php_used_prefix.$php_suffix;
        eval( $php_str ); # write the string to the array structure...
    }
    if( $val['type'] == "close" ) {
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the used keys node...
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the end level of the array string prefix...
    }
}

echo "<pre>";
//print_r ($index);
//echo "<br><br><br>";
//print_r ($vals);
//echo "<br><br><br>";
print_r ($my_array);
echo "</pre>";

?>
dudus at onet dot pl 18-Jan-2005 06:33
This function return array from XML. Included attributes and tags in same level.
I wrote this function based on mmustafa code.

enjoy!
dUDA

-------------------------------

<?
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close')
        {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete')
        {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while($start_level < $x_level)
        {
              $php_stmt .= '[$level['.$start_level.']]';
              if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                  $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
              $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete'))
        {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
             $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes',$xml_elem))
        {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes',$xml_elem))
        {
            if (isset($xml_elem['value']))
            {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value)
            {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
     return $xml_array;
}    // END XMLtoArray
?>
memandeemail at gmail dot com 09-Dec-2004 07:09
a BREAK on right place, will be faster and bugprevent

    /**
    * @return bool
    * @param xml_array $values
    * @param xml_array[reference] $tags
    * @desc Reconstruct xml_parse_into_struct to open and close concept
    */
    function reconstruct_tag($values, &$tags) {
        unset($return);
        foreach ($tags as $tkey => $tvalue) {
            foreach ($tvalue as $vvalue) {
                if ($values[$vvalue]['type'] == 'open' or $values[$vvalue]['type'] == 'complete') {
                    $return[$tkey][] = $vvalue;
                }
                if ($values[$vvalue]['type'] == 'open') {
                    foreach ($tvalue as $tv_value) {
                        if ($values[$tv_value]['type'] == 'close'
                        and $values[$tv_value]['level'] == $values[$vvalue]['level']
                        and $tv_value > $vvalue) {
                            $return[$tkey][] = $tv_value;
                            break;
                        }
                    }
                }
            }
        }
        $tags = $return;
        return (bool) $tags;
    }
memandeemail at gmail dot com 03-Dec-2004 04:32
If you have de XML:
<?xml version="1.0" encoding="iso-8859-1"?>
<teste>
    <teste>
        <teste>
        </teste>
    </teste>
</teste>

this function will return this tags:
Array
(
    [teste] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
        )

)

With this function (right below) will convert the struc to OPEN and CLOSE concept.

The New Struct:
Array
(
    [teste] => Array
        (
            [0] => 0
            [1] => 4
            [2] => 1
            [3] => 3
            [4] => 2
        )

)
The Function:
/**
 * @return bool
 * @param xml_array $values
 * @param xml_array[reference] $tags
 * @desc Reconstruct xml_parse_into_struct
*/
function reconstruct_tag($values, &$tags) {
    unset($return);
    foreach ($tags as $tkey => $tvalue) {
        foreach ($tvalue as $vvalue) {
            if ($values[$vvalue]['type'] == 'open' or $values[$vvalue]['type'] == 'complete') {
                $return[$tkey][] = $vvalue;
            }
            if ($values[$vvalue]['type'] == 'open') {
                foreach ($tvalue as $tv_value) {
                    if ($values[$tv_value]['type'] == 'close'
                    and $values[$tv_value]['level'] == $values[$vvalue]['level']) {
                        $return[$tkey][] = $tv_value;
                    }
                }
            }
        }
    }
    $tags = $return;
    return (bool) $tags;
}

Ahh, DO NOT forget this comment:

jukkaho at mail dot student dot oulu dot fi
29-Jun-2004 12:17
Everyone seems to forget the return value of this function (including people making examples!), but it is there for a reason:
0 if failed (invalid XML), 1 if succeeded.

Return value really is an integer, be careful with those === operators.
rob at digital hyphen crocus dot com 03-Sep-2004 09:21
I wrote this function in a bad mood, to get some data you can loop through. sprint_r or var_dump its output to see what it does. It's not pretty, but at least you can loop through the data without a LOT of hassle.

This can also be done with handlers, but I couldn't be bothered with global variables.

<?php

$data = xml_parse_into_struct($somexml);

function xml_getmeaningfuldata($data) {
foreach($data as $element) {
        if ($element['type'] == "open") {
                if (!$elementnos[$parents.$element['tag']]) {
                        $elementnos[$parents.$element['tag']] = 1;
                }
                $elements[$parents.$element['tag'].":". $elementnos[$parents.$element['tag']]]['attributes'] = $element['attributes'];
                $elements[$parents.$element['tag'].":". $elementnos[$parents.$element['tag']]]['value'] = trim($element['value']);
                $parents .= $element['tag'].":".$elementnos[$parents.$element['tag']]."^";
        }
        if ($element['type'] == "cdata") {
                if (trim($element['value'])) {
                        $elements[$parents.$element['tag'].":". $elementnos[$parents.$element['tag']]]['values'] = $element['value'];
                }
        }
        if ($element['type'] == "complete") {
                if (!$elementnos[$parents.$element['tag']]) {
                        $elementnos[$parents.$element['tag']] = 1;
                }
                $elements[$parents.$element['tag'].":". $elementnos[$parents.$element['tag']]]['attributes'] = $element['attributes'];
                $elements[$parents.$element['tag'].":". $elementnos[$parents.$element['tag']]]['value'] = trim($element['value']);
                $elementnos[$parents.$element['tag']]++;
        }
        if ($element['type'] == "close") {
                $parents = substr($parents, 0, strrpos(substr($parents, 0, -1), "^")+1);
                $elementnos[$parents.$element['tag']]++;
//              if (sizeof($parents) == 1) unset($parents);
        }
}

return $elements;

}
happyseb at free dot fr 24-Aug-2004 08:51
I would just add something about the solution proposed by "gordon at kanazawa dot ac dot jp".

Something went wrong about the fact that "cdata" are treated the same way as "complete" in the xml_get_children first and in the xml_get_child then.

When ?
with this method, something like this :
<tagA>
  <tagB>valueB</tagB>
  valueA
  <tagC>valueC</tagC>
</tagA>
is considered as the same thing as
<tagA>
  <tagB>valueB</tagB>
  <tagA>valueA</tagA>
  <tagC>valueC</tagC>
</tagA>

The algorithm is nomore bijective.

Even if it might not be perfect :-) i propose a little modification of the xml_get_child function :

function xml_get_child(&$v, $children=NULL) {
      $c = array(); // the "child"
      if (isset($v['tag']) && $v['type'] != 'cdata') $c['tag'] = $v['tag'];
      if (isset($v['value'])) $c['value'] = $v['value'];
      if (isset($v['attributes'])) $c['attributes'] = $v['attributes'];
      if (is_array($children)) $c['children'] = $children;
      return $c;
}

moreover, the following function will take the tree (made from the xml_get_tree function) as a parameter and build the xml content back

    /*
    // setTree
    // set xml Tree from a well-formed array
    // manage indentation
    // Parameters are :
    // $1 (needed) : Tree to transform
    // $2 (optional) : Indentation type (default is one tabulation)
    // $3 (optional) : First indent (default is empty string)
    */

    function setTree($Atree, $indentType = '    ', $Sindent = '')
    {
      if (! isset ($Atree['tag']) && isset ($Atree['value'])) return ($Sindent.trim($Atree['value'])."\r\n") ;
      else {
        $Stemp = $Sindent.'<'.$Atree['tag'].' ' ;
        if (isset ($Atree['attributes']) && is_array ($Atree['attributes'])) {
          foreach ($Atree['attributes'] as $Aattribute => $Svalue) $Stemp .= $Aattribute.'="'.$Svalue.'" ' ;
        }
        if (! isset ($Atree['children']) && ! isset ($Atree['value'])) $Stemp .= '/>'."\r\n" ;
        else {
          $Stemp .= '>'."\r\n" ;
          if (isset ($Atree['value'])) $Stemp .= $Sindent.$indentType.trim($Atree['value'])."\r\n" ;
          if (isset ($Atree['children']) && is_array ($Atree['children']))
            foreach ($Atree['children'] as $Achild) $Stemp .= $this->setTree($Achild, $indentType, $Sindent.$indentType) ;
          $Stemp .= $Sindent.'</'.$Atree['tag'].'>'."\r\n" ;
        }
        return ($Stemp) ;
      }
    }
sdh33 at cornell dot edu 13-Jun-2004 10:12
(The previous post I wrote was incorrect.  I fix that herein)
I used the algorithm from stephane for writing back to a file, but ran into the following problem.  My original XML looks like

<ENTRY id="1"> ... </ENTRY><ENTRY id="2"> ... </ENTRY>

This got saved back as

<1> ... </1><2> ... </2>,

which expat doesn't like.  So I propose the following modification:

function writeXmlToFile($data, $f, $niv = 0) {
  foreach($data as $name => $elem) {
    if (preg_match("/\A[0-9]/",$name)) {
      $open = "ENTRY id=\"$name\""; $name = "ENTRY";
    } else {
      $open = $name;
    }
    if(is_array($elem)) {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    } else {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">".$elem."</".$name.">"."\n");
    }
  }
}
stephane dot dekeyzer at noemail dot com 08-Apr-2004 11:54
for writing the array of mmustafa back to a xml file, use this code:

function writeXmlFile($fileName, $struct){
  $f = fopen($fileName, "w");
  writeXmlToFile($struct, $f);
  fclose($f);
}

function writeXmlToFile($data, $f, $niv = 0){
  foreach($data as $name => $elem){
    if(is_array($elem)){
      fwrite($f, str_repeat("  ", $niv)."<".$name.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    }
    else{
      fwrite($f, str_repeat("  ", $niv)."<".$name.">".$elem."</".$name.">"."\n");
    }
  }
}
gordon at kanazawa dot ac dot jp 25-Jan-2004 08:36
Many thanks to "dave at ovumdesign dot com" for his excellent routines based on the fine work of "gdemartini at bol dot com". I offer a further refinement below, which removes the duplication of the code to create a child node. The resulting tree is the same as in Dave's earlier version and so can be compacted using his "xml_condense_tree"

function xml_get_child(&$v, $children=NULL) {
   $c = array(); // the "child"
   if (isset($v['tag'])) $c['tag'] = $v['tag'];
   if (isset($v['value'])) $c['value'] = $v['value'];
   if (isset($v['attributes'])) $c['attributes'] = $v['attributes'];
   if (is_array($children)) $c['children'] = $children;
   return $c;
}
function xml_get_children(&$values, &$i) {
   $children = array();
   while ($i < count($values)) {
      $v = &$values[$i++];
      switch ($v['type']) {
         case 'cdata':
         case 'complete':
            $children[] = xml_get_child($v);
            break;
         case 'open':
            $children[] = xml_get_child($v, xml_get_children($values, $i));
            break;
         case 'close':
            break 2; // leave "while" loop
      }
   }
   return $children;
}
function xml_get_tree($file) {
   $data = join('', file($file));

   $p = xml_parser_create();
   xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
   xml_parser_set_option($p, XML_OPTION_SKIP_WHITE,  1);
   xml_parse_into_struct($p, $data, $values);
   xml_parser_free($p);

   return xml_get_children($values, $i=0);
}
mmustafa at vsnl dot com 06-Jan-2004 12:19
A small and simple php code to convert the raw array returned by xml_parse_into_struct into a proper data structure ..

<?php
$file = "data.xml";
$xml_parser = xml_parser_create();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

$data = fread($fp, filesize($file));
fclose($fp);
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
    if (array_key_exists('attributes',$xml_elem)) {
      list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
    } else {
      $level[$xml_elem['level']] = $xml_elem['tag'];
    }
  }
  if ($xml_elem['type'] == 'complete') {
    $start_level = 1;
    $php_stmt = '$params';
    while($start_level < $xml_elem['level']) {
      $php_stmt .= '[$level['.$start_level.']]';
      $start_level++;
    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
    eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>

Converts an XML document like ..

<country id="ZZ">
<name>My Land</name>
<location>15E</location>
<area>40000</area>
<state1>
<name>Hi State</name>
<area>1000</area>
<population>2000</population>
<city1>
<location>13E</location>
<population>500</population>
<area>500</area>
</city1>
<city2>
<location>13E</location>
<population>500</population>
<area>5000</area>
</city2>
</state1>
<state2>
<name>Low State</name>
<area>3000</area>
<population>20000</population>
<city1>
<location>15E</location>
<population>5000</population>
<area>1500</area>
</city1>
</state2>
</country>

To a php datastructure like ..

Array
(
    [ZZ] => Array
        (
            [NAME] => My Land
            [LOCATION] => 15E
            [AREA] => 40000
            [STATE1] => Array
                (
                    [NAME] => Hi State
                    [AREA] => 1000
                    [POPULATION] => 2000
                    [CITY1] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 500
                        )

                    [CITY2] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 5000
                        )

                )

            [STATE2] => Array
                (
                    [NAME] => Low State
                    [AREA] => 3000
                    [POPULATION] => 20000
                    [CITY1] => Array
                        (
                            [LOCATION] => 15E
                            [POPULATION] => 5000
                            [AREA] => 1500
                        )

                )

        )

)
26-Sep-2003 03:43
actually, using the notation

$object->property is the right one

and you can use it always, preventing errors with arrays
Eric 22-Sep-2003 08:50
Yet another XML -> nested array converter.

This is based on http://www.devdump.com/phpxml.php, but adds features while reducing code complexity.

It can take several forms of input:
 - string (buffer)
 - file handle (pipe)
 - file name -or-
 - URL

It can optionally collapse arrays of same-named tags to a single element if there is only one tag with a given name.

It can optionally preserve tag order for XML applications where position is significant, such as CallXML.

XMLParser.obj at:
http://eric.pollmann.net/work/public_domain/

Corrections and suggestions enthusiastically welcomed.  :)
Adam Tylmad 12-Sep-2003 05:01
I've just debugged and optimized my xmlparser.

gdemartini's xml-example generates this structure:

stdClass Object
(
    [FORM] => stdClass Object
        (
            [SECTION] => stdClass Object
                (
                    [NAME] => Data
                    [EDITFIELD] => stdClass Object
                        (
                            [LABEL] => Text:
                            [NAME] => poll_text
                            [LENGTH] => 255
                            [SIZE] => 56
                            [REQUIRED] => T
                        )

                    [MEMOFIELD] => stdClass Object
                        (
                            [LABEL] => Options
                            [NAME] => options
                            [COLS] => 56
                            [ROWS] => 5
                            [REQUIRED] => T
                        )
                )
        )
)

the moldb example generates this structure:

stdClass Object
(
    [MOLDB] => stdClass Object
        (
            [MOLECULE] => Array
                (
                    [0] => stdClass Object
                        (
                            [NAME] => Alanine
                            [SYMBOL] => ala
                            [CODE] => A
                            [TYPE] => hydrophobic
                        )

                    [1] => stdClass Object
                        (
                            [NAME] => Lysine
                            [SYMBOL] => lys
                            [CODE] => K
                            [TYPE] => charged
                        )
                )
        )
)

here is the code. enjoy!

<?php

class XMLParser {
    var $path;
    var $result;

    function cleanString($string) {
        return trim(str_replace("'", "&#39;", $string));
    }

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

    function startElement($parser, $tag, $attributeList) {
        $this->path .= "->".$tag;
        eval("\$data = ".$this->path.";");
        if (is_array($data)) {
            $index = sizeof($data);
            $this->path .= "[".$index."]";
        } else if (is_object($data)) {
            eval($this->path." = array(".$this->path.");");
            $this->path .= "[1]";
        }

        foreach($attributeList as $name => $value)
            eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
    }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        if ($data = XMLParser::cleanString($data))
            eval($this->path." = '$data';");
    }
}

?>
plusplus7 at hotmail dot com 18-Jun-2003 06:40
Quick and dirty function to get original file from $vals array in manual example. Build on this for custom parsing of individual elements (something like this should be built-in IMO).

<pre>
function parseVals($vals){
    foreach($vals as $valobj){
        if($valobj['type']=='open' || $valobj['type']=='complete'){
            $retstr .= '<'.$valobj['tag'];
            if(is_array($valobj['attributes'])){
                foreach($valobj['attributes'] as $key=>$val){
                    $retstr .= " $key=\"$val\"";
                }
            }
        }
        if($valobj['type']=='open'){
            $retstr .= '>'.$valobj['value'];
        }elseif($valobj['type']=='complete' && $valobj['value']){
            $retstr .= '>'.$valobj['value'].'</'.$valobj['tag'].'>';
        }elseif($valobj['type']=='complete'){
            $retstr .= ' />';
        }elseif($valobj['type']=='cdata'){
            $retstr .= $valobj['value'];
        }elseif($valobj['type']=='close'){
            $retstr .= '</'.$valobj['tag'].'>';
        }

    }
    return $retstr;
}

</pre>
masuod_a at hotmail dot com 24-Nov-2002 04:32
wanna load object from xml file? this function take a tree returned by xml_get_tree() [dave@ovumdesign.com's version] and return an object.
it can't work with attributes, i hate attributes (except id), but may be useful for you.

- how to use :
------------------------- xml file -------------
<config>
   <images>
      <image id="1">
        <name>my pet</name>
        <file>pet001.jpg</file>
      </image>
      <image id="2">
        <name>harry's pet</name>
        <file>pet003.jpg</file>
      </image>
   </images>
   <library>lib_functions.php</library>
</config>
----------------------------------------------
$config=xml_to_object($xml_tree);
$config->library;    #return "lib_functions.php"
$config->images->image__1->name; #return "my pet"
----------------------------------------------
function xml_to_object($xml_tree,$root=false){
             $object_name=$xml_tree['tag'];
             foreach ($xml_tree['children'] as $children){
                          $child_id=$children['attributes']['id'];
                          $child_name=$children['tag'];
                          $child_name.=($child_id) ? "__".$child_id:'';

                          if (is_array($children['children'])) {
                                      $child_object=xml_to_object($children);
                                      $temp_object->$child_name=$child_object;
                          } else {
                                    $temp_object->$child_name=$children['value'];
                         }
             }

             if (!$root)
                          $xml_object=$temp_object;
             else       $xml_object->$object_name=$temp_object;

             return $xml_object;
}

also you can use this function for loading array from xml , but i suggest you to use kris@h3x.com's functions[ http://www.devdump.com/phpxml.php ].

function xml_to_array($xml_tree,$root=false){
   $array_name=$xml_tree['tag'];
   foreach ($xml_tree['children'] as $children){
       $child_id=$children['attributes']['id'];
       $child_name=$children['tag'];
       $child_name.=($child_id) ? "__".$child_id:'';
       if (is_array($children['children'])) {
            $child_array=xml_to_array($children);
            $temp_array[$child_name]=$child_array;
       } else {
            $temp_array[$child_name]=$children['value'];
       }
   }

   if (!$root)
      $xml_array=$temp_array;
   else
      $xml_array[$array_name]=$temp_array;

    return $xml_array;
}
bisqwit at iki dot fi dot not dot for dot ads dot invalid 20-Nov-2002 08:33
I made my own xml2tree()-function.
The difference to the previously suggested ones on this manual page is that this creates a tree where the tags are keys.

Example input:

<tree>
 <leaf name="gruu"> pl�� </leaf>
 <animal type="cat" />
</tree>

Example output:

Array
( 'tree' => Array
     ( 0 => Array
          ( 'children' => Array
               ( 'leaf' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('name' => 'gruu'),
                           'values' => Array(0 => ' pl�� ')
                    )    ),
                 'animal' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('type' => 'cat')
)    )   )    )    )   )

function xml2tree2($string)
{
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $string, $vals, $index);
  xml_parser_free($parser);

  $stack = array( array() );
  $stacktop = 0;
  $parent = array();
  foreach($vals as $val)
  {
    $type = $val['type'];
    if($type=='open' || $type=='complete')
    {
      // open tag
      $stack[$stacktop++] = $tagi;
      $tagi = array('tag' => $val['tag']);

      if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
      if(isset($val['value']))
        $tagi['values'][] = $val['value'];
    }
    if($type=='complete' || $type=='close')
    {
      // finish tag
      $tags[] = $oldtagi = $tagi;
      $tagi = $stack[--$stacktop];
      $oldtag = $oldtagi['tag'];
      unset($oldtagi['tag']);
      $tagi['children'][$oldtag][] = $oldtagi;
      $parent = $tagi;
    }
    if($type=='cdata')
    {
      $tagi['values'][] = $val['value'];
    }
  }
  return $parent['children'];
}

Ps: Note that the xml parsing for some reason chokes if the values contain <> (even inside ""). You need to escape them as &lt; and &gt;.
Same for & (for obvious reasons). Escape it as &amp;.
For example "&nbsp;" should be written as "&amp;nbsp;".
joeldegan at yahoo dot com 19-Nov-2002 04:40
Using one of the nice function above, I was able to get these two great structures below on nmap info for a machine and then the PID lists for each open port.. Very handy for my current project.

$test = `nmap -sU -sS localhost -oX -`;
$ret = xml2array($test);
$z=0;
while (list($key,$val)=each($ret["host"][0][3]["children"])){
    if ($val["tag"] == "PORT"){
        $new[$z]["PROTOCOL"] = $val["attributes"]["PROTOCOL"];
        $new[$z]["PORT"] = $val["attributes"]["PORTID"];

        //echo $val["attributes"]["PROTOCOL"]."\n";
        //echo $val["attributes"]["PORTID"]."\n";
        $z++;
    }//fi
}//wend

print_r($new);

function port_pids($portnum){
    $ret = `lsof -i :$portnum -F pc`;
    $ret = explode("\n", $ret);
    $z=0;
    for($a=0;$a<count($ret);$a++){
        $port = $ret[$a];
        $a++;
        $com = $ret[$a];
        $new[$z]["PID"]=substr($port, 1);
        $new[$z]["COMMAND"]=substr($com, 1);
        $z++;
    }//wend
    return $new;
}//end function

print_r(port_pids("3306"));
no at chance dot com 08-Nov-2002 10:38
Thanks to gdemartini's tree algorithm , I was able to create a variation that display's the information in a way that allows you to then easily parse the information with less code and process time. Here's the variation and I've also posted a quick function at the bottom that allows you to visually display complex arrays in human readable format. Hope this helps someone as much as gdemartini's functions helped me.

I decided to post it on my server as opposed to the forums as it was too large and needed some good html formatting.  It can found at http://www.devdump.com/phpxml.php .
ambi at gmx dot de 05-Oct-2002 03:59
Sorry.. unreachable and unneeded code in my posting above :-)
Here is the fixed version:
function xml_condense_tree($tree) {
    if ($tree["children"]) {
            unset($nodecounters);
            foreach ($tree['children'] as $index => $node) {
                if (!isset($nodecounters[$node['tag']]))
                $nodecounters[$node['tag']]=1;
                else $nodecounters[$node['tag']]++;
            }
        foreach ($tree['children'] as $index => $node) {
            if (isset($node['children'])) {
                $tree['children'][$index] = xml_condense_tree($node);
            } elseif (isset($node['value']) and !$node['attributes'] and $nodecounters[$node['tag']]==1) {
                $tree['values'][$node['tag']] = $node['value'];
                unset($tree['children'][$index]);
            }
        }
    }
    if (!$tree['children']) unset($tree['children']);

    return $tree;
}
09-Aug-2002 01:20
This is based on a comment above by mh@mainlab.de.  This version makes more sense to me and I included a few comments that might make it more usefull for specific purposes.

// Look through $vals and $index,
// generated by parse_xml_data(),
// for $location.  $location resembles a unix path.
// E.g. "my/xml/path/to/my/data".
// Note: This is NOT a full-feature xml utility.
// Your path must be unique in the xml data
// and the tags must not contain slashes.
//
// returns: cdata from last element of $location
//          or NULL.
function get_xml_values($vals, $index, $location) {
  $location = explode('/', $location);
  $location_level = count($location);
  for ($n=0; $n<$location_level; ++$n) {
    $val_indexes=$index[$location[$n]];
    $good=0;
    for ($i=0; $i<count($val_indexes); ++$i) {
      $v = $vals[$val_indexes[$i]];
      // level is 1 based, n is 0 based:
      if ($v['level']-1 == $n) {
        if ($v['type'] == 'open') {
          // We found an open tag at the correct level.
          $good=1;
          break; // Remove break to avoid 'open' hiding
                 // 'complete' at last $n. (Speed Vs. Robustness:
                 // For now, I'm going with speed).
        }
        if ($v['type'] == 'complete') {
          // We found it, after finding all the prior elements:
          // You may want to change this to
          // return $v
          // so you can call $v['value'] and $v['attributes']
          return $v['value'];
        }
      }
    }
    if (!$good) {
      return NULL;
    }
  }
}
farinspace-at-hotmail-dot-com 20-Jul-2002 06:41
Wow, took a while to consume all of this. I am a noobie at XML, in fact i just really started working with it today. I went ahead and added to the above code by gdemartini@bol.com.br. I also added the update by nyk@cowham.net.

Added 'value' => $vals[$i]['value'] to the open case, as some nodes have both cdata as well as a children node. In previous versions of the functions the cdata of a node(a) that also had children would get stored in the children's array of the parent node(a). Now only children values are in the children array and the cdata is in the value key of the parent node(a).

Added 'value' => $vals[$i]['value'] to tree array as the vals array produced by PHP includes a value to the top most node if no children exist (for completeness).

Also, using xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,1) will strip all white space from both around the XML tags as well as inside the cdata. I added a piece of code by waldo@wh-e.com to take care of this. All SPACE characters are now only stripped from around the XML tags and cdata spacing is retained.

CODE:
***************************************

function GetChildren($vals, &$i) {

    $children = array();

    while (++$i < sizeof($vals)) {

        // compair type
        switch ($vals[$i]['type']) {

            case 'cdata':
                $children[] = $vals[$i]['value'];
                break;
            case 'complete':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value']
                );
                break;
            case 'open':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value'],
                    'children' => GetChildren($vals, $i)
                );
                break;
            case 'close':
                return $children;
        }
    }
}

function GetXMLTree($file) {

    $data = implode('', file($file));

    // by: waldo@wh-e.com - trim space around tags not within
    $data = eregi_replace(">"."[[:space:]]+"."<","><",$data);

    // XML functions
    $p = xml_parser_create();

    // by: anony@mous.com - meets XML 1.0 specification
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parse_into_struct($p, $data, &$vals, &$index);
    xml_parser_free($p);

    $i = 0;
    $tree = array();
    $tree[] = array(
        'tag' => $vals[$i]['tag'],
        'attributes' => $vals[$i]['attributes'],
        'value' => $vals[$i]['value'],
        'children' => GetChildren($vals, $i)
    );

    return $tree;
}

***************************************
dave at ovumdesign dot com 03-Apr-2002 03:32
Here is another variation on gdemartini@bol.com.br's nice tree algorithm. I have included nyk@cowham.net's "cdata" suggestion. I made a few changes to suppress unitialized variable warnings with error_reporting(E_ALL), and made a few stylistic changes.

There are two functional modifications as well. The first is the added option to expat to turn off "case folding", since XML is technically a case-sensitive language. The second is the returned tree - instead of returning a single-element list (an array with index 0 pointing to the top node) like the original algorithm, it returns the top node itself. This saves you an unnecessary level of indirection.

function xml_get_children($vals, &$i) {
    $children = array();
    if (isset($vals[$i]['value'])) $children[] = $vals[$i]['value'];

    while (++$i < count($vals)) {
        switch ($vals[$i]['type']) {
        case 'cdata':
            $children[] = $vals[$i]['value'];
            break;

        case 'complete':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'value'      => $vals[$i]['value'],
            );
            break;

        case 'open':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'children'   => xml_get_children($vals, $i),
            );
            break;

        case 'close':
            return $children;
        }
    }
}

function xml_get_tree($file) {
    $data = join('', file($file));

    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,   1);
    xml_parse_into_struct($parser, $data, $vals, $index);
    xml_parser_free($parser);

    return array(
        'tag'        => $vals[0]['tag'],
        'attributes' => isset($vals[0]['attributes'])?
                        $vals[0]['attributes'] : null,
        'children'   => xml_get_children($vals, $i = 0),
    );
}

This function takes a tree returned by xml_get_tree() and simplifies it similarly to voncken@mailandnews.com and oknapp@soly.de's suggestions. It finds any nodes that expat considered "complete" (childless) and contain no attributes, and it moves the tag name (as the key) and value into an element in the parent node's "values" array.

For example:
$tree = xml_get_tree('moldb.xml');
$tree = xml_condense_tree($tree);
echo $tree['children'][1]['values']['name'];

Outputs:
Lysine

function xml_condense_tree($tree) {
    foreach ($tree['children'] as $index => $node) {
        if (isset($node['children'])) {
            $tree['children'][$index] = xml_condense_tree($node);

        } elseif (isset($node['value']) and !$node['attributes']) {
            $tree['values'][$node['tag']] = $node['value'];
            unset($tree['children'][$index]);
        }
    }

    if (!$tree['children']) unset($tree['children']);
    return $tree;
}

Enjoy,
Dave
voncken at mailandnews dot com 06-Jan-2002 05:24
I needed something a bit different:
this is the result of my xml2array function (from the moldb example)

Array
(
    [molecule] => Array
        (
            [0] => Array
                (
                    [name] => Alanine
                    [symbol] => ala
                    [code] => A
                    [type] => hydrophobic
                )

            [1] => Array
                (
                    [name] => Lysine
                    [symbol] => lys
                    [code] => K
                    [type] => charged
                )

        )

)

function xml2array($data)
  {
    //mvo voncken@mailandnews.com
    //original ripped from  on the php-manual:gdemartini@bol.com.br
    //to be used for data retrieval(result-structure is Data oriented)
    $p = xml_parser_create();
    xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($p, $data, &$vals, &$index);
    xml_parser_free($p);

    $tree = array();
    $i = 0;
    //array_push($tree, array('tag' => $vals[$i]['tag'], 'attributes'=> $vals[$i]['attributes'],                            'children' => ));
    $tree = GetChildren($vals, $i);
    return $tree;
  }

 function GetChildren($vals, &$i)
  {
    $children = array();
    if ($vals[$i]['value']) array_push($children, $vals[$i]['value']);

    $prevtag = "";
    while (++$i < count($vals)) // so pra nao botar while true ;-)
    {
      switch ($vals[$i]['type'])
      {
         case 'cdata':
           array_push($children, $vals[$i]['value']);
           break;
         case 'complete':
           $children[ strtolower($vals[$i]['tag']) ] = $vals[$i]['value'];
           break;

         case 'open':

           //restartindex on unique tag-name
           $j++;
           if ($prevtag <> $vals[$i]['tag']) {
                   $j = 0;
                   $prevtag = $vals[$i]['tag'];
            }
           $children[ strtolower($vals[$i]['tag']) ][$j] = GetChildren($vals,$i);
           break;

         case 'close':
           return $children;
      }
    }
  }
xml_get_error_code
xml_parse
Функции парсера XML


Запускает разбор XML документа

xml_parse_into_struct
xml_parser_create_ns
Функции парсера XML
PHP Manual

xml_parse

(PHP 4, PHP 5)

xml_parse — Запускает разбор XML документа

Описание

int xml_parse ( resource $parser , string $data [, bool $is_final = false ] )

xml_parse() разбирает XML документ. Обработчики запрограммированных событий вызываются столько раз, сколько необходимо.

Список параметров

parser

Ссылка на используемый XML анализатор.

data

Часть данных для разбора. Документ можно разбирать по частям, вызывая функцию xml_parse() несколько раз с новыми данными, пока аргумент is_final не будет установлен в TRUE, это сообщит анализатору, что разбирается последняя часть документа.

is_final

Если задан и установлен в TRUE, data считается последней частью в этом разборе.

Возвращаемые значения

Возвращает 1 при успешном завершении, 0 в противном случае.

В случае неудачного разбора информацию об ошибках можно получить с помощью
функций xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() и
xml_get_current_byte_index().

Замечание:

Ошибки при разборе сущностей выдаются в конце разбора, их можно получить только когда is_final установлен в TRUE.

User Contributed Notes

dr3w at gmail dot com 30-Jun-2010 04:16
interpreting xml into an object using simplexml_load_string is not a very good idea, as in cases like:
<item foo="bar">value here</item>
attributes would be lost
Ashok dot 893 at gmail dot com 25-Apr-2010 10:52
This is very simple way to convert all applicable objects into associative array.  This works with not only SimpleXML but any kind of object. The input can be either array or object. This function also takes an options parameter as array of indices to be excluded in the return array. And keep in mind, this returns only the array of non-static and accessible variables of the object since using the function get_object_vars().

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();

    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }

    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}
?>

Usage:

<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
?>
lz_speedy at web dot de 30-Dec-2008 10:20
Best seen xml2array function ever
<?php
function xml2array($url, $get_attributes = 1, $priority = 'tag')
{
    $contents = "";
    if (!function_exists('xml_parser_create'))
    {
        return array ();
    }
    $parser = xml_parser_create('');
    if (!($fp = @ fopen($url, 'rb')))
    {
        return array ();
    }
    while (!feof($fp))
    {
        $contents .= fread($fp, 8192);
    }
    fclose($fp);
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);
    if (!$xml_values)
        return; //Hmm...
    $xml_array = array ();
    $parents = array ();
    $opened_tags = array ();
    $arr = array ();
    $current = & $xml_array;
    $repeated_tag_index = array ();
    foreach ($xml_values as $data)
    {
        unset ($attributes, $value);
        extract($data);
        $result = array ();
        $attributes_data = array ();
        if (isset ($value))
        {
            if ($priority == 'tag')
                $result = $value;
            else
                $result['value'] = $value;
        }
        if (isset ($attributes) and $get_attributes)
        {
            foreach ($attributes as $attr => $val)
            {
                if ($priority == 'tag')
                    $attributes_data[$attr] = $val;
                else
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }
        if ($type == "open")
        {
            $parent[$level -1] = & $current;
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
            {
                $current[$tag] = $result;
                if ($attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                $current = & $current[$tag];
            }
            else
            {
                if (isset ($current[$tag][0]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    if (isset ($current[$tag . '_attr']))
                    {
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset ($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = & $current[$tag][$last_item_index];
            }
        }
        elseif ($type == "complete")
        {
            if (!isset ($current[$tag]))
            {
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            }
            else
            {
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes)
                    {
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                        if ($attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                }
            }
        }
        elseif ($type == 'close')
        {
            $current = & $parent[$level -1];
        }
    }
    return ($xml_array);
}
?>

Returns a well formed array like the structure of the xml-document

<root>
 <child1>
  <child1child1/>
 </child1>
</root>

create an array like
array[root][child1][child1child1]

lg
passionplay at hotmail dot com 12-Oct-2008 07:50
Why we continue to recode the same basic pieces, I'll never understand. And to not have a default xml parser class means I have to remember crap all the time. Here's my xmlBase class. Enjoy.

P.S. Excuse the spacing. When you put it into a text editor, it will all line up.

<?php
// Basic error functions
class errorBase
{
    function backtrace($provideObject=false)
    {
        foreach(debug_backtrace($provideObject) as $row)
        {
            if($last!=$row['file'])
                echo "File: $file<br>\n'";
      $last=$row['file'];
            echo " Line: $row[line]: ";
            if($row['class']!='')
                echo "$row[class]$row[type]$row[function]";
            else
                echo "$row[function]";
            echo "(";
            echo join("', '",$args);
            echo ")<br>\n";
        }
    }
    function error($msg,$fatal=false)
    {
        echo "<div align=\"center\"><font color=\"red\"><b>Error: $msg</b></font></div>";
        $last='';
        $this->backtrace();
        exit();
    }
    function fatalError($msg){return $this->error($msg,true);}
}

// Basic XML parser with all call-backs abstracted
class xmlBase  extends errorBase
{

    // Valuable resource
    var $_p;

    // Constructor/destructor
    function xmlBase($ns=false,$encoding=null,$separator=null)
    {
            $this->_p = $ns
                                                ?
                                                xml_parser_create_ns($encoding,$separator)
                                                :
                                                xml_parser_create($encoding);

            xml_set_object($this->_p, $this);
            xml_set_default_handler($this->_p,"_default");
            xml_set_element_handler($this->_p, "_tagOpen", "_tagClose");
            xml_set_character_data_handler($this->_p, "_cdata");
            xml_set_start_namespace_decl_handler($this->_p,"_nsStart");
            xml_set_end_namespace_decl_handler($this->_p,"_nsEnd");
            xml_set_external_entity_ref_handler($this->_p,"_entityRef");
            xml_set_processing_instruction_handler($this->_p,"_pi");
            xml_set_notation_decl_handler($this->_p,"_notation");
            xml_set_unparsed_entity_decl_handler($this->_p,"_unparsedEntity");
    }
    function _xmlBase()                                                {xml_parser_free($this->_p);$this->_p=null;}

    // All private abstract methods - override these
    function _default($parser,$data)            {}
    function _tagOpen($parser,$tag,
                                                                                $attribs){}
    function _tagClose($parser,$tag)        {}
    function _cdata($parser,$data)            {}
    function _nsStart($parser,
                                                            $userData,
                                                            $prefix,$uri)                {}
    function _nsEnd($parser,$userData,
                                                        $prefix)                                {}
    function _entityRef($parser,
                                  $openEntityNames,
                                                                $base,
                                                                $systemID,
                                                                $publicID)                    {}
    function _pi($parser,$target,$data){}
    function _notation($parser,
                                  $notationName,
                                                                $base,
                                                                $systemID,
                                                                $publicID)                    {}
    function _unparsedEntity($parser,
                                  $entityName,
                                                                $base,
                                                                $systemID,
                                                                $publicID,
                                                                $notationName){}

    function _parse($data,$final=false)
    {
        if(xml_parse($this->_p,$data,$final))
        {
            echo $data.'<br />';
            $this->fatalError(sprintf('XML error %d:"%s" at line %d column %d byte %d',
            xml_get_error_code($this->_p),
            xml_error_string($this->_p),
            xml_get_current_line_number($this->_p),
            xml_get_current_column_number($this->_p),
            xml_get_current_byte_index($this->_p)));
        }
    }

    // All the public functions you're meant to not override
    function setOption($option,$value)    {return xml_parser_set_option($this->_p,$option,$value);}
    function getOption($option)              {return xml_parser_get_option($this->_p,$option);}
    function parseFile($file)
    {
        if(($f=fopen($file,'r'))!=null)
        {
            while(!feof($f))
                $this->parse(fgets($f,1024));
            $this->parseEnd();
        }
        else
            $this->fatalError("Unable to open file $file");
    }
    function parseEnd()
    {
        $this->_parse(null,true);
    }
    function parse($data)
    {
        $this->_parse($data);
    }
}
?>
Frank 21-Feb-2008 09:09
And with that, why not use recursivity to get to all the CDATA...

<?php

function printCDATA($pItem)
{
  foreach($pItem as $value){
    if (isset($value[children])){
      printCDATA($value[children]);
    }else{
      if(isset($value[name])){
        echo $value[name].": ";
      }
      if(isset($value[cdata])){
        echo $value[cdata]."<br>";
      }
    }
  }
}

printCDATA($stack);
?>
neoyahuu at yahoo dot com 12-Dec-2007 08:18
Instead of passing a URL, we can pass the XML content to this class (either you
 want to use CURL, Socks or fopen to retrieve it first) and instead of using
 array, I'm using separator '|' to identify which data to get (in order to make
 it short to retrieve a complex XML data). Here is my class with built-in fopen
 which you can pass URL or you can pass the content instead :

p/s : thanks to this great help page.

<?php

class xx_xml {

    // XML parser variables
    var $parser;
    var $name;
    var $attr;
    var $data  = array();
    var $stack = array();
    var $keys;
    var $path;

    // either you pass url atau contents.
    // Use 'url' or 'contents' for the parameter
    var $type;

    // function with the default parameter value
    function xx_xml($url='http://www.example.com', $type='url') {
        $this->type = $type;
        $this->url  = $url;
        $this->parse();
    }

    // parse XML data
    function parse()
    {
        $data = '';
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, 'startXML', 'endXML');
        xml_set_character_data_handler($this->parser, 'charXML');

        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);

        if ($this->type == 'url') {
            // if use type = 'url' now we open the XML with fopen

            if (!($fp = @fopen($this->url, 'rb'))) {
                $this->error("Cannot open {$this->url}");
            }

            while (($data = fread($fp, 8192))) {
                if (!xml_parse($this->parser, $data, feof($fp))) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        } else if ($this->type == 'contents') {
            // Now we can pass the contents, maybe if you want
            // to use CURL, SOCK or other method.
            $lines = explode("\n",$this->url);
            foreach ($lines as $val) {
                if (trim($val) == '')
                    continue;
                $data = $val . "\n";
                if (!xml_parse($this->parser, $data)) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        }
    }

    function startXML($parser, $name, $attr)    {
        $this->stack[$name] = array();
        $keys = '';
        $total = count($this->stack)-1;
        $i=0;
        foreach ($this->stack as $key => $val)    {
            if (count($this->stack) > 1) {
                if ($total == $i)
                    $keys .= $key;
                else
                    $keys .= $key . '|'; // The saparator
            }
            else
                $keys .= $key;
            $i++;
        }
        if (array_key_exists($keys, $this->data))    {
            $this->data[$keys][] = $attr;
        }    else
            $this->data[$keys] = $attr;
        $this->keys = $keys;
    }

    function endXML($parser, $name)    {
        end($this->stack);
        if (key($this->stack) == $name)
            array_pop($this->stack);
    }

    function charXML($parser, $data)    {
        if (trim($data) != '')
            $this->data[$this->keys]['data'][] = trim(str_replace("\n", '', $data));
    }

    function error($msg)    {
        echo "<div align=\"center\">
            <font color=\"red\"><b>Error: $msg</b></font>
            </div>";
        exit();
    }
}

?>

And example of retrieving XML data:
p/s: example use to retrieve weather

<?php
include_once "xx_xml.class.php";

// Im using simple curl (the original is in class) to get the contents

$pageurl = "http://xml.weather.yahoo.com/forecastrss?p=MYXX0008&u=c";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $pageurl );
$thecontents = curl_exec ( $ch );
curl_close($ch);

// We want to pass only a ready XML content instead of URL
// But if you want to use URL , skip the curl functions above and use this
// $xx4 = new xx_xml("url here",'url');

$xx4 = new xx_xml($thecontents,'contents');
// As you can see, we use saparator '|' instead of long array
$Code = $xx4->data ['rss|channel|item|yweather:condition']['code'] ;
$Celcius = $xx4->data ['rss|channel|item|yweather:condition']['temp'] ;
$Text = $xx4->data ['rss|channel|item|yweather:condition']['text'] ;
$Cityname = $xx4->data ['rss|channel|yweather:location']['city'] ;

?>

Hope this helps.
joris dot landman at chello dot nl 28-Jul-2007 07:42
This page has been a great help! I've adapted the examples below to make a class to parse an X(HT)ML file to a multidimensional array.

Spaces, tabs, breaks, etc. are included in the array as TEXT_NODE, since in XHTML they may be functional. A function to trim them can easily be added if so desired.

I've written my class to store multiple tags with the same name. In order to do this I've used nested arrays with the key NODES to store the order in which tags and data were parsed. These NODES arrays can be used as a blueprint to reconstruct the X(HT)ML part of the document in it's entirity, including formatting. (Doctype will have to be added for validity).

<?php

class my_xml_object {

    var $xml_data; # raw xml data from file
    function parse_xml_file($my_uri) {
        $this->xml_data = null; # clear previously parsed file and related variables
        if (is_file($my_uri) && is_readable($my_uri)) { # existing and readable uri?
            $my_file = fopen($my_uri, "r");
            while($my_xml_input = fread($my_file, filesize($my_uri))) {
                $this->xml_data .= $my_xml_input; # add data to xml_data
            }
            fclose($my_file);
            $this->parse_xml_data($this->xml_data); # parse data
        } else {
            trigger_error("supplied argument is not a URI to a (readable) file", E_USER_ERROR);
        }
    }

    var $xml_array = Array(); # xml array from parsed data
    function parse_xml_data($my_data) { # adapted from class by randlem@gmail.com, tgrabietz@bupnet.de, bbellwfu@gmail.com, Kyle Bresin - see http://nl2.php.net/xml_parse
        $this->xml_array = Array(0 => Array()); # clear previously parsed file and related variables; populate first element
        $my_parser = xml_parser_create(); # set up parser
        xml_set_object($my_parser, $this); # enable parser within object
        xml_set_element_handler($my_parser, "xml_tag_open", "xml_tag_close");
        xml_set_character_data_handler($my_parser, "xml_tag_data");
        if (!xml_parse($my_parser, $my_data)) {
            trigger_error("data can not be parsed", E_USER_ERROR); # inspect problems #die(sprintf("<br />\n<b>Error</b>:  %s on line <b>%d</b><br />\n", xml_error_string(xml_get_error_code($my_parser)), xml_get_current_line_number($my_parser)));
        }
        xml_parser_free($my_parser); # free parser
        return $this->xml_array; # return xml array
    }

    var $my_branch = Array();
    function xml_tag_open($my_parser, $my_name, $my_attributes) {
        array_push($this->my_branch, $my_name); # add tag name to branch
        $this->xml_array[] = Array(); # nest array in xml array for data
        if (count($my_attributes)) {
            $this->xml_array[count($this->xml_array) - 1]["ATTRIBUTES"] = $my_attributes; # nest attributes array
        }
    }

    function xml_tag_data($my_parser, $my_data) {
        $this->xml_array[count($this->my_branch)]["TEXT_NODE"][] = $my_data; # add data to nested array
        $this->xml_array[count($this->my_branch)]["NODES"][] = "TEXT_NODE"; # add text node to nested NODES array
    }

    function xml_tag_close($my_parser, $my_name) {
        $this->xml_array[count($this->my_branch) - 1][$this->my_branch[count($this->my_branch) - 1]][] = $this->xml_array[count($this->xml_array) - 1]; # nest arrays to follow document structure
        array_pop($this->xml_array); # pop off element that was nested
        $this->xml_array[count($this->my_branch) - 1]["NODES"][] = $my_name; # add tag node to nested NODES array
        array_pop($this->my_branch); # update branch
    }

?>
dgrimes at scvl dot com 29-Jun-2007 06:14
One note about magic quotes: magic_quotes_runtime needs to be disabled before parsing XML. It can cause strange errors during parsing. Just add the following at the top of your program:

set_magic_quotes_runtime(0);

If you need magic quotes you can use stripslashes or save the current magic quotes setting with get_magic_quotes_runtime() then disable and parse your XML and then restore the previous magic quotes setting.
php at b635 dot com 23-Jun-2007 10:17
The suggestions below have been a great help, but there was one thing I really needed...

I'm parsing Amazon XML data, and I wanted to be able to index into the array using something like:

<?php
  print "<p>" . $strAXML->arrOutput[ITEMLOOKUPRESPONSE][ITEMS][ITEM][SMALLIMAGE][URL];
?>

To solve this, I had to push all of the open tags onto a separate stack, add any tag data to the tail end of an attributed multi-dimensional array, and then pop the tag name off of the stack once it was closed...

<?php

class xml2array {

  var $arrOutput = array();
  var $arrName = array();
  var $objParser;
  var $strXmlData;

  function parse($strInputXML) {

    // standard XML parse object setup

    $this->objParser = xml_parser_create ();
    xml_set_object($this->objParser,$this);
    xml_set_element_handler($this->objParser, "tagOpen", "tagClosed");

    xml_set_character_data_handler($this->objParser, "tagData");

    $this->strXmlData = xml_parse($this->objParser,$strInputXML );
    if(!$this->strXmlData) {
      die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->objParser)),
        xml_get_current_line_number($this->objParser)));
    }

    xml_parser_free($this->objParser);

    return $this->arrOutput;
  }

  function tagOpen($parser, $name, $attrs) {
    // push the current tag name to an array of still-open tag names
    array_push ($this->arrName, $name);

    // merge the array of current attributes to the open tag
    // NOTE: this does not currently handle multiple attributes with the same name
    // (i.e. it will overwrite them with the last values)

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }
    $strEval = $strEval . " = array_merge (" . $strEval . ",\$attrs);";

    eval ($strEval);
  }

  function tagData($parser, $tagData) {

    // set the latest open tag equal to the tag data

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }

    $strEval = $strEval . " = \$tagData;";

    eval ($strEval);
  }

  function tagClosed($parser, $name) {

    // pop this tag (and any subsequent tags) off the stack of open tag names

    for ($i = count ($this->arrName) - 1; $i > 0; $i--) {
      $currName = $this->arrName[$i];
      array_pop ($this->arrName);
      if ($currName == $name) {
        break;
      }
    }
  }

}

?>
edvardas at alderonas dot lt 17-Aug-2006 11:38
xml_parse() crashes when xml file contains chars \x00 - \x1f, so be careful! I solve this problem simple:
<?php
$bad_chr = array("\x00" => "chr(0)", "\x01" => "chr(1)", "\x02" => "chr(2)", "\x03" => "chr(3)", "\x04" => "chr(4)", "\x05" => "chr(5)", "\x06" => "chr(6)", "\x07" => "chr(7)", "\x08" => "chr(8)", "\x09" => "chr(9)", "\x0a" => "chr(10)", "\x0b" => "chr(11)", "\x0c" => "chr(12)", "\x0d" => "chr(13)", "\x0e" => "chr(14)", "\x0f" => "chr(15)", "\x10" => "chr(16)", "\x11" => "chr(17)", "\x12" => "chr(18)", "\x13" => "chr(19)", "\x14" => "chr(20)", "\x15" => "chr(21)", "\x16" => "chr(22)", "\x17" => "chr(23)", "\x18" => "chr(24)", "\x19" => "chr(25)", "\x1a" => "chr(26)", "\x1b" => "chr(27)", "\x1c" => "chr(28)", "\x1d" => "chr(29)", "\x1e" => "chr(30)", "\x1f" => "chr(31)");
xml_parse($xml_parser, strtr($data, $bad_chr), feof($fp));
//....
$parsed_data = strtr($parsed_data, array_flip($bad_chr));
?>
james @at@ mercstudio dot Com dot nospam 02-Apr-2006 12:10
hi,

i've modified bbellwfu at gmail dot com to as below:

features added:
  - toXML (convert back array to xml string)
  - changed name, according to macromedia flash xml concept : children -> childrens, tagdata -> nodevalue, name -> nodename,
  - added pointer firstchild to childrens[0] (if exists)

some findings that i would like to share:
 - <![cdata[my value here]]> (does not work on property value
 - xml file must be htmlentity based (if not using cdata)
 - xml line feed on node data seems to be double line feed on windows (still figuring why)
 - xml line feed on attribute value seems to be ignored...

here's my code below :)

class u007xml
{
   var $arrOutput = array();
   var $resParser;
   var $strXmlData;

    function u007xml($tfile = "")
    {
        if(trim($tfile) != "") { $this->loadFile($tfile);}
    }

    function loadFile($tfile)
    {
        $this->thefile = $tfile;

        $th = file($tfile);
        $tdata = implode("\n", $th);

        return $this->parse($tdata);
    }

   function parse($strInputXML)
   {
        $this->resParser = xml_parser_create ();
        xml_set_object($this->resParser,$this);
        xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

        xml_set_character_data_handler($this->resParser, "tagData");

        $this->strXmlData = xml_parse($this->resParser,$strInputXML );

        if(!$this->strXmlData) {
           die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->resParser)),
        xml_get_current_line_number($this->resParser)));
        }

        xml_parser_free($this->resParser);

        return $this->arrOutput;
   }

   //called on each xml tree
   function tagOpen($parser, $name, $attrs) {
       $tag=array("nodename"=>$name,"attributes"=>$attrs);
       array_push($this->arrOutput,$tag);
   }

  //called on data for xml
   function tagData($parser, $tagData) {
       if(trim($tagData)) {
           if(isset($this->arrOutput[count($this->arrOutput)-1]['nodevalue'])) {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] .= $this->parseXMLValue($tagData);
           }
           else {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] = $this->parseXMLValue($tagData);
           }
       }
   }

  //called when finished parsing
   function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['childrens'][] = $this->arrOutput[count($this->arrOutput)-1];

       if(count ($this->arrOutput[count($this->arrOutput)-2]['childrens'] ) == 1)
       {
            $this->arrOutput[count($this->arrOutput)-2]['firstchild'] =& $this->arrOutput[count($this->arrOutput)-2]['childrens'][0];
       }
       array_pop($this->arrOutput);
   }

    function toArray()
    {
        //not used, we can call loadString or loadFile instead...
    }

    function parseXMLValue($tvalue)
    {
        $tvalue = htmlentities($tvalue);
        return $tvalue;
    }

    function toXML($tob = null)
    {
        //return back xml
        $result = "";

        if( $tob == null)
        {
            $tob = $this->arrOutput;
        }

        if(!isset($tob))
        {
            echo "XML Array empty...";
            return null;
        }

        for($c = 0; $c < count($tob); $c++)
        {
            $result .="<" . $tob[$c]["nodename"];

            while (list($key, $value) = each($tob[$c]["attributes"]))
            {
                $result .=" " . $key."=\"" . $this->parseXMLValue($value) . "\"";
            }

            $result .= ">";

            //assign node value
            if( isset($tob[$c]["nodevalue"]) )
            {
                $result .= $tob[$c]["nodevalue"];
            }

            if( count($tob[$c]["childrens"]) > 0 )
            {
                $result .= "\r\n" . $this->toXML(&$tob[$c]["childrens"]) . "";
            }

            $result .= "</" . $tob[$c]["nodename"] . ">\r\n";

        }//end of each array...

        return $result;
    }

    function displayXML()
    {
        print_r($this->arrOutput);
    }

    function getXML($tob = null)
    {
        return "<?xml version='1.0'?>\r\n" . $this->toXML($tob);
    }

}//end of u007xml class

//examples below:

$xx = new u007xml();
$xx->loadFile("xml3.xml");

//$xx->displayXML();

print $xx->getXML();
ben at autonomic dot net 16-Mar-2006 05:12
bbellwfu's code does not handle 'text nodes' properly.
Consider the innards of a tag like <root>xxx<tag2/>yyy</root>
The 'tagData' for root will be "xxxyyy" and you have lost all information about where "tag2" was in that sequence.

Quick and dirty hack.

Replace tagData with this code :
   function tagData($parser, $tagData) {
          $last_element=count($this->arrOutput)-1;
        $this->arrOutput[$last_element]['children'][] = array("textnode",$tagData);
   }

What this does is adds 'textnodes' as children of its containing parent, *in the right sequence* (rather like the internet browsers do it). This then lets you do some more sensible secondary work like recursively looking up internal references within the document...
Kyle Bresin 19-Jan-2006 03:15
Just wanted to note a small bug in bbellwfu's class (which is really great btw).

It fails to capture any datums which are equal to numerical zero.

The problem lies in the function tagData, the first if statement should be:

if(trim($tagData) != '') {
tim at alloutinteraction dot com 01-Oct-2005 07:29
I wanted to create a really simple XML parser, but I found the array management in xml_parse a bit daunting. So I flattened my XML and parsed it using string matching. It wouldn't be difficult to add xml depth (of 2 plus levels) by modifying the parsedXML array.

<?
// here's the raw html
$xmlRaw="<order>Order data</order><label>Label data</label><control>123</control>";
// here are the xml field names
$xmlFieldNames=array("order", "label", "control");
// for each xml field...
foreach ($xmlFieldNames as $xmlField) {
    if(strpos($xmlRaw,$xmlField)!==false){
        // I've broken 1 single line into 4 for display purposes
        $parsedXML[$xmlField]=substr($xmlRaw,
        strpos($xmlRaw,"<$xmlField>")+strlen("<$xmlField>"),
        strpos($xmlRaw,"</$xmlField>")-strlen("<$xmlField>")
        -strpos($xmlRaw,"<$xmlField>"));
    }
}
print_r($parsedXML);
// prints: Array ( [order] => Order data [label] => Label data [control] => 123 )

?>

Hope you find this useful (coded it while ill in bed with streaming cold, but felt much better afterwards!)

Tim (a lazy coder)
bbellwfu at gmail dot com 05-May-2005 02:51
Just improving a little bit on the code examples from tgrabietz and randlem below... everything in one pretty class, plus some checks in place so that the element data doesnt get split up (thanks to flobee on the xml_set_character_data_handler page)

<?php

/* Usage
 Grab some XML data, either from a file, URL, etc. however you want. Assume storage in $strYourXML;

 $objXML = new xml2Array();
 $arrOutput = $objXML->parse($strYourXML);
 print_r($arrOutput); //print it out, or do whatever!

*/
class xml2Array {

    var $arrOutput = array();
    var $resParser;
    var $strXmlData;

    function parse($strInputXML) {

            $this->resParser = xml_parser_create ();
            xml_set_object($this->resParser,$this);
            xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

            xml_set_character_data_handler($this->resParser, "tagData");

            $this->strXmlData = xml_parse($this->resParser,$strInputXML );
            if(!$this->strXmlData) {
               die(sprintf("XML error: %s at line %d",
            xml_error_string(xml_get_error_code($this->resParser)),
            xml_get_current_line_number($this->resParser)));
            }

            xml_parser_free($this->resParser);

            return $this->arrOutput;
    }
    function tagOpen($parser, $name, $attrs) {
       $tag=array("name"=>$name,"attrs"=>$attrs);
       array_push($this->arrOutput,$tag);
    }

    function tagData($parser, $tagData) {
       if(trim($tagData)) {
            if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
            }
            else {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
            }
       }
    }

    function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1];
       array_pop($this->arrOutput);
    }
}
?>

Will output something like...

<snippet>
Array
(
    [0] => Array
        (
            [name] => GETMESSAGESRESPONSE
            [attrs] => Array
                (
                )

            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => STATUS
                            [attrs] => Array
                                (
                                )

                        )

</snippet>
alex dot garcia at noos dot fr 14-Mar-2005 01:47
Here is the inverse function which takes parsed xml array in entry and outputs xml string

enjoy !

function getXmlFromArray($root){

        if(count($root) > 0){

            $curr_name = $root['name'];
            $attribs = $root['attrs'];
            $curr_childs = $root['children'];
            $curr_data = $root['cdata'];

            $xml .= '<'.$curr_name;

            if(count($attribs) > 0){
                $i = 1;
                foreach($attribs as $key => $value){
                    $curr_attribs .= $key.'="'.$value.'"';
                    $i++;
                    if($i <= count($attribs)){
                        $curr_attribs .= ' ';
                    }
                }
                $xml .= ' '.$curr_attribs;
            }

            if($curr_data != ''){
                $xml .= '><![CDATA['.$curr_data.']]></'.$curr_name.'>';
            } else {
                if(count($curr_childs) > 0){
                    $xml .= '>';
                    foreach($curr_childs as $child){
                        $xml .= getXmlFromArray($child);
                    }
                    $xml .= '</'.$curr_name.'>';
                } else {
                    $xml .= '/>';
                }
            }

        }
        return $xml;
    }
tgrabietz at bupnet dot de 22-Sep-2004 08:05
it's like randlem at gmail dot com's great code, without using a "class container" but parsing cdata. The script returns the tree-structure in a single array.

<?php
$file = 'simple.xml';
$stack = array();

function startTag($parser, $name, $attrs)
{
   global $stack;
   $tag=array("name"=>$name,"attrs"=>$attrs);
   array_push($stack,$tag);

}

function cdata($parser, $cdata)
{
    global $stack,$i;

    if(trim($cdata))
    {
        $stack[count($stack)-1]['cdata']=$cdata;
    }
}

function endTag($parser, $name)
{
   global $stack;
   $stack[count($stack)-2]['children'][] = $stack[count($stack)-1];
   array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "cdata");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
   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);

print("<pre>\n");
print_r($stack);
print("</pre>\n");
?>
ByK 16-Sep-2004 08:12
modified from yours code. I think it's work!!.
class CXml
{
    var $xml_data;
    var $obj_data;
    var $pointer;

    function CXml() { }

    function Set_xml_data( &$xml_data )
    {
        $this->index = 0;
        $this->pointer[] = &$this->obj_data;

        //strip white space between tags
        $this->xml_data = eregi_replace(">"."[[:space:]]+"."<","><",$xml_data);
        $this->xml_parser = xml_parser_create( "UTF-8" );

        xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
        xml_set_object( $this->xml_parser, &$this );
        xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
        xml_set_character_data_handler( $this->xml_parser, "_cData" );

        xml_parse( $this->xml_parser, $this->xml_data, true );
        xml_parser_free( $this->xml_parser );
    }

    function _startElement( $parser, $tag, $attributeList )
    {
        foreach( $attributeList as $name => $value )
        {
            $value = $this->_cleanString( $value );
            $object->$name = $value;
        }
        //replaces the special characters with the underscore (_) in tag name
        $tag = preg_replace("/[:\-\. ]/", "_", $tag);
        eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
        eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
        eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

        $this->index++;
    }

    function _endElement( $parser, $tag )
    {
        array_pop( $this->pointer );
        $this->index--;
    }

    function _cData( $parser, $data )
    {
        if (empty($this->pointer[$this->index])) {
            if (rtrim($data, "\n"))
                $this->pointer[$this->index] = $data;
        } else {
            $this->pointer[$this->index] .= $data;
        }
    }

    function _cleanString( $string )
    {
        return utf8_decode( trim( $string ) );
    }
}

$m_xml = new CXml();
$xml_data = file_get_contents( $filename );

$m_xml->Set_XML_data( $xml_data );

$newsid = $m_xml->obj_data->root[0]->NewsID[0];
randlem at gmail dot com 15-Sep-2004 08:43
Here's a handy way to generate a tree that can be can be decended easily.

<?php
$file = 'xmltest.xml';

$tag_tree = array();
$stack = array();

class tag {
    var $name;
    var $attrs;
    var $children;
    function tag($name, $attrs, $children) {
        $this->name = $name;
        $this->attrs = $attrs;
        $this->children = $children;
    }
}

function startTag($parser, $name, $attrs) {
    global $tag_tree, $stack;
    $tag = new tag($name,$attrs,'');
    array_push($stack,$tag);
}

function endTag($parser, $name) {
    global $stack;
    $stack[count($stack)-2]->children[] = $stack[count($stack)-1];
    array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
    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);

print("\n");
print_r($stack);
print("\n");
?>
talraith at withouthonor dot com 08-Jul-2004 04:40
I have written a module that contains a class for use with XML documents.  The module is dual-purpose in that it will parse XML code into a native object tree structure and will generate XML code from the object tree structure.

The output produced from generating XML code is designed to be used by other applications and is not in human-readable form.

I would like to point out that the code does not use any eval() statements to create the tree.

I am posting my code for two purposes:

1) I am looking to refine it and make it more efficient
2) It may benefit someone that is looking for a module like this.

The code is too big to post in here, so I have uploaded it to a web site:  http://www.withouthonor.com/obj_xml.html

An example of parsing an XML document:

<?php

// Use the method of your choice to load the XML document
// into a variable...  (a very generic sample follows)
$XML = '<root><section>This is my sample XML code</section></root>';

$xml = new xml_doc($XML);
$xml->parse();

// Access root level object
$my_tag = $xml->getTag(0,$name,$attributes,$cdata,$children);

?>

It is then possible to loop through the children of the tag and process the data with your program.  The last variable above ($children) contains a list of tag reference ID's.  The object tree is created by assigning each tag a unique ID starting with zero.  The tree is created by using object references to relate parents and children.

If you wanted to create an XML document from scratch, the code would be similar to the following example:

<?php

$xml = new xml_doc();

// Create the root tag and retrieve reference ID #
$root_tag = $xml->createTag('root');

// The second parameter is for tag attributes
// This is done using an associative array
$xml->createTag('section',array(),'This is my sample XML code',$root_tag);

$my_output = $xml->generate();

print $my_output;

?>

The example above creates an XML document that is the same as the one used in my first example.  Another option available would be to load the XML code as in the first example, change it through PHP, and then generate the code and output it.
michelek 26-Oct-2003 10:42
its maybe not better, but me thinks its more stright-forward

--INPUT:

<?xml version="1.0" encoding="UTF-8"?>
<world>
    <country name="sweden">
        <city name="stockholm">
            <user>Adam</user>
            <user>Eva</user>
        </city>
        <city name="g�teborg">
            <user>God</user>
        </city>
    </country>
    <country name="usa">
        <city name="new york">
            <user>Clinton</user>
            <user>Bush</user>
        </city>
    </country>
</world>

--CODE:
<?
/**
 * m_i_h_k_e_l_AT_w_w_DOT_e_e
 * 26.10.2003
**/
$filename = "m.m.xml";
$xmlC = new XmlC();
$xml_data = file_get_contents( $filename );

$xmlC->Set_XML_data( $xml_data );

echo( "<pre>\n" );
print_r( $xmlC->obj_data );
echo( "</pre>\n" );

class XmlC
{
  var $xml_data;
  var $obj_data;
  var $pointer;

  function XmlC()
  {
  }

  function Set_xml_data( &$xml_data )
  {
    $this->index = 0;
    $this->pointer[] = &$this->obj_data;

    $this->xml_data = $xml_data;
    $this->xml_parser = xml_parser_create( "UTF-8" );

    xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
    xml_set_object( $this->xml_parser, &$this );
    xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
    xml_set_character_data_handler( $this->xml_parser, "_cData" );

    xml_parse( $this->xml_parser, $this->xml_data, true );
    xml_parser_free( $this->xml_parser );
  }

  function _startElement( $parser, $tag, $attributeList )
  {
    foreach( $attributeList as $name => $value )
    {
      $value = $this->_cleanString( $value );
      $object->$name = $value;
    }
    eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
    eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
    eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

    $this->index++;
  }

  function _endElement( $parser, $tag )
  {
    array_pop( $this->pointer );
    $this->index--;
  }

  function _cData( $parser, $data )
  {
    if( trim( $data ) )
    {
      $this->pointer[$this->index] = trim( $data );
    }
  }

  function _cleanString( $string )
  {
    return utf8_decode( trim( $string ) );
  }

}
?>
Adam Tylmad 11-Sep-2003 01:11
I've created a parser that returns an
object based on a xml document.

example:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<country name="sweden">
    <city name="stockholm">
        <user>Adam</user>
        <user>Eve</user>
    </city>
    <city name="g�teborg">
        <user>God</user>
    </city>
</country>
<country name="usa">
    <city name="new york">
        <user>Clinton</user>
        <user>Bush</user>
    </city>
</country>

generates the following object structure:
[country] => Array
(
    [0] => stdClass Object
        (
            [name] => sweden
            [city] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => stockholm
                            [user] => Array
                                (
                                    [0] => Adam
                                    [1] => Eve
                                )
                        )
                    [1] => stdClass Object
                        (
                            [name] => g�teborg
                            [user] => God
                        )
                )
        )
    [1] => stdClass Object
        (
            [name] => usa
            [city] => stdClass
                (
                    [name] => new york
                    [user] => Array
                        (
                            [0] => Clinton
                            [1] => Bush
                        )
                )
        )
)

Here is the code:

class XMLParser {
    var $path;
    var $result;

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

        function startElement($parser, $tag, $attributeList) {
            eval("\$vars = get_object_vars(".$this->path.");");
            $this->path .= "->".$tag;
            if ($vars and array_key_exists($tag, $vars)) {
                 eval("\$data = ".$this->path.";");
                     if (is_array($data)) {
                           $index = sizeof($data);
                           $this->path .= "[".$index."]";
                     } else if (is_object($data)) {
                           eval($this->path." = array(".$this->path.");");
                           $this->path .= "[1]";
                     }
            }
            eval($this->path." = null;");

            foreach($attributeList as $name => $value)
                eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
        }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        eval($this->path." = '".trim($data)."';");
    }
}

enjoy! And please make it better if you can ;-)
jacek <dot> prucia <at> 7bulls <dot> com 27-Aug-2002 09:03
don't underestimate is_final argument. If you ignore it (since it is optional) you can get strange results with non well-formed XML's, like no output from xml_parse at all. Also if you use feof($fp) as is_final make sure you don't use fgets, because there's a caveat with how feof is evaluated there.
06-Dec-2001 12:14
if you're using magic quotes by default, remember to turn them off for the XML parsing.
xml_parse_into_struct
xml_parser_create_ns
Функции парсера XML


Создание XML анализатора с поддержкой пространств имен

xml_parse
xml_parser_create
Функции парсера XML
PHP Manual

xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5)

xml_parser_create_ns — Создание XML анализатора с поддержкой пространств имен

Описание

resource xml_parser_create_ns ([ string $encoding [, string $separator = ':' ]] )

xml_parser_create_ns() создает новый XML анализатор с поддержкой пространств имен и возвращает ссылающийся на него ресурс, который можно использовать в других XML функциях.

Список параметров

encoding

Необязательный аргумент encoding задает кодировку символов для ввода/вывода в PHP 4. Начиная с PHP 5, кодировка входных данных определяется автоматически, а encoding задает кодировку только для выводимых данных. В PHP 4 кодировка по умолчанию для выходных данных та же, что и входных. Если передается пустая строка, анализатор попытается определить кодировку, просматривая первые 3 или 4 байта. В PHP 5.0.0 и 5.0.1 кодировка по умолчанию ISO-8859-1. Для версий PHP 5.0.2 и выше - UTF-8. Список поддерживаемых кодировок: ISO-8859-1, UTF-8 и US-ASCII.

separator

Если сообщить анализатору пространство имен, то параметры тэгов, передающиеся в различные обработчики будут состоять из пространства имен и локального имени, отделенных заданным в этом аргументе разделителем seperator.

Возвращаемые значения

Возвращает ресурс созданного XML анализатора.

Смотрите также

  • xml_parser_create() - Создание XML анализатора
  • xml_parser_free() - Освобождение XML анализатора

User Contributed Notes

jonnyNO at SPAM dot sanriowasteland dot net 11-Jun-2002 05:49
This is from the Expat Function Reference by Clark Cooper, which is a reference to the C api.

"XML_Parser XML_ParserCreateNS(const XML_Char*encoding, XML_Char sep)
Constructs a new parser that has namespace processing in effect. Namespace expanded element names and attribute names are returned as a concatenation of the namespace URI, sep, and the local part of the name. This means that you should pick a character for sep that can't be part of a legal URI."

(from http://www.xml.com/pub/a/1999/09/expat/reference.html)

So thats what this function is for.  Now you know.
xml_parse
xml_parser_create
Функции парсера XML


Создание XML анализатора

xml_parser_create_ns
xml_parser_free
Функции парсера XML
PHP Manual

xml_parser_create

(PHP 4, PHP 5)

xml_parser_create — Создание XML анализатора

Описание

resource xml_parser_create ([ string $encoding ] )

xml_parser_create() создает новый XML анализатор и возвращает ссылающийся на него ресурс, который можно использовать в других XML функциях.

Список параметров

encoding

Необязательный аргумент encoding задает кодировку символов для ввода/вывода в PHP 4. Начиная с PHP 5, кодировка входных данных определяется автоматически, а encoding задает кодировку только для выводимых данных. В PHP 4 кодировка по умолчанию для выходных данных та же, что и входных. Если передается пустая строка, анализатор попытается определить кодировку, просматривая первые 3 или 4 байта. В PHP 5.0.0 и 5.0.1 кодировка по умолчанию ISO-8859-1. Для версий PHP 5.0.2 и выше - UTF-8. Список поддерживаемых кодировок: ISO-8859-1, UTF-8 и US-ASCII.

Возвращаемые значения

Возвращает ресурс созданного XML анализатора.

Смотрите также

  • xml_parser_create_ns() - Создание XML анализатора с поддержкой пространств имен
  • xml_parser_free() - Освобождение XML анализатора

User Contributed Notes

marek995 at seznam dot cz 24-Sep-2010 11:46
I created a function, which combines xml_paresr_create and all functions around.

<?php
function html_parse($file)
     {
      $array = str_split($file, 1);
      $count = false;
      $text = "";
      $end = false;
      foreach($array as $temp)
       {
        switch($temp)
         {
          case "<":
           between($text);
           $text = "";
           $count = true;
           $end = false;
           break;
          case ">":
           if($end == true) {end_tag($text);}
           else {start_tag($text);}
           $text = "";
           break;
          case "/":
           if($count == true) {$end = true;}
           else {$text = $text . "/";}
           break;
          default:
           $count = false;
           $text = $text . $temp;
         }
       }
     }
?>
The input value is a string.
It calls functions start_tag() , between() and end_tag() just like the original xml parser.

But it has a few differences:
  - It does NOT check the code. Just resends values to that three functions, no matter, if they are right
  - It works with parameters. For example: from tag <sth b="42"> sends sth b="42"
  - It works wit diacritics. The original parser sometimes wrapped the text before the first diacritics appearance.
  - Works with all encoding. If the input is UTF-8, the output will be UTF-8 too
  - It works with strings. Not with file pointers.
  - No "Reserved XML name" error
  - No doctype needed
  - It does not work with commentaries, notes, programming instructions etc. Just the tags

definition of the handling functions is:

<?php
function between($stuff) {}
?>

No other attributes
juanhdv at NOSPAM dot divvol dot org 05-Dec-2007 12:08
In PHP 5, when including in your xml file the definition '<?xml version="1.0" encoding="ISO-8859-1" ?>',   I'd also recommend adding the option below:

xml_parser_set_option($xml_parser,XML_OPTION_TARGET_ENCODING, "ISO-8859-1").

It works fine!

If your enconding is 'UTF-8', just replace 'ISO-8859-1'.
19-Apr-2006 07:42
I'd also recommend adding the option below
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
Tobbe 25-May-2005 06:01
The above "XML to array" code does not work properly if you have several tags on the same level and with the same name, example:

<currenterrors>
<error>
<description>This is a real error...</description>
</error>
<error>
<description>This is a second error...</description>
</error>
<error>
<description>Lots of errors today...</description>
</error>
<error>
<description>This is the last error...</description>
</error>
</currenterrors>

It will then only display the first <error>-tag.
In this case you will need to number the tags automatically or maybe have several arrays for each new element.
dma05 at web dot de 27-Apr-2005 02:54
xml_parser_create () on php5 sometimes detects the wrong input format for me -- for example, sometimes when i try to parse data that has been fetched from a databse by my script and that only contains a handful of special ISO-8859-1 characters, it seems to think the input was something else and xml_parse() chokes on things like umlauts.

the only reason i was able to figure out so far would be that -- unlike my data files -- the xml data generated by my script doesn't contain the <?xml  [...] encoding="..." ?> definition. every data source with that definition seemed just fine; it's kinda odd that it worked *sometimes* without it *shrugs*.
no matter what the reason, using utf8_encode () on the string made it work, and prepending '<?xml version="1.0" encoding="ISO-8859-1" ?>' worked as well.

this problem shouldn't occur in php4, since there you would specify the input encoding along with the output encoding.
php at stock-consulting dot com 21-Feb-2005 02:47
Even though I passed "UTF-8" as encoding type PHP (Version 4.3.3) did *not* treat the input file as UTF-8. The input file was missing the BOM header bytes (which may indeed be omitted, according to RFC3629...but things are a bit unclear there. The RFC seems to make mere recommendations concering the BOM header). If you want to sure that PHP treats an UTF-8 encoded file correctly, make sure that it begins with the corresponding 3 byte BOM header (0xEF 0xBB 0xBF)
jcalvert at gmx dot net 03-Apr-2004 10:39
To maintain compatibility between PHP4 and PHP5 you should always pass a string argument to this function. PHP4 autodetects the format of the input if you leave it out whereas PHP5 will assume the format to be ISO-8859-1 (and choke on the byte order marker of UTF-8 files).

Calling the function as <?php $res = xml_parser_create('') ?> will cause both versions of PHP to autodetect the format.
mmustafa at vsnl dot com 05-Jan-2004 10:00
thought I'd share this small piece of PHP code that prepares a proper array from XML Data
(uses xml_parse_into_struct to get a raw array)
features : 1) can easily adjust to multiple levels 2) simple.

<code>

$file = "data.xml";
$xml_parser = xml_parser_create();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

$data = fread($fp, filesize($file));
fclose($fp);
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
    if (array_key_exists('attributes',$xml_elem)) {
      list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
    } else {
      $level[$xml_elem['level']] = $xml_elem['tag'];
    }
  }
  if ($xml_elem['type'] == 'complete') {
    $start_level = 1;
    $php_stmt = '$params';
    while($start_level < $xml_elem['level']) {
      $php_stmt .= '[$level['.$start_level.']]';
      $start_level++;
    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
    eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";

</code>

Example :
I/P XML ...

<country id="ZZ">
<name>My Land</name>
<location>15E</location>
<area>40000</area>

    <state1>
<name>Hi State</name>
<area>1000</area>
<population>2000</population>

    <city1>
<location>13E</location>
<population>500</population>
<area>500</area>
</city1>

    <city2>
<location>13E</location>
<population>500</population>
<area>5000</area>
</city2>
</state1>

    <state2>
<name>Low State</name>
<area>3000</area>
<population>20000</population>

    <city1>
<location>15E</location>
<population>5000</population>
<area>1500</area>
</city1>
</state2>
</country>

O/P Array :
Array
(
    [ZZ] => Array
        (
            [NAME] => My Land
            [LOCATION] => 15E
            [AREA] => 40000
            [STATE1] => Array
                (
                    [NAME] => Hi State
                    [AREA] => 1000
                    [POPULATION] => 2000
                    [CITY1] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 500
                        )

                    [CITY2] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 5000
                        )

                )

            [STATE2] => Array
                (
                    [NAME] => Low State
                    [AREA] => 3000
                    [POPULATION] => 20000
                    [CITY1] => Array
                        (
                            [LOCATION] => 15E
                            [POPULATION] => 5000
                            [AREA] => 1500
                        )

                )

        )

)
xml_parser_create_ns
xml_parser_free
Функции парсера XML


Освобождение XML анализатора

xml_parser_create
xml_parser_get_option
Функции парсера XML
PHP Manual

xml_parser_free

(PHP 4, PHP 5)

xml_parser_free — Освобождение XML анализатора

Описание

bool xml_parser_free ( resource $parser )

Освобождает память, занятую XML анализатором parser.

Список параметров

parser
Ссылка на очищаемый XML анализатор.

Возвращаемые значения

Эта функция возвращает FALSE, если parser ссылается на недопустимый анализатор, в остальных случаях она очищает анализатор и возвращает TRUE.

User Contributed Notes

alex_foe at yahoo dot de 09-Oct-2006 10:07
whitout throwing exceptions you could try these for clear parser shutdown:

xml_parse($this->p, null, 1);

full example-class (php4 compatible):

class XML_Parser
{
    var $file = null;
    var $p = null; #the resource xml-parser

    var $__parsing = false;

    function XML_Parser($file = null)
    {
        if (!empty($file)) { $this->file = $file; }

        $this->p = xml_parser_create();
        xml_set_element_handler($this->p, array(&$this, "element_start"));

        register_shutdown_function(array(&$this, "destructor"));
    }

    function element_start($parser, $name, $attrs) { die("here I die while parsing"); }

    function parse_file($file = null)
    {
        $this->__parsing = true;

        if (!empty($file)) { $this->file = $file; }

        if (!file_exists($this->file)) { die("file does not exists: $this->file"); return; }

        if (!($fp = fopen($this->file, "r"))) { die("could not open XML input"); }
        while ($data = fread($fp, 4096))
        {
            if (!xml_parse($this->p, $data, feof($fp)))
            {
                die(
                      xml_error_string(xml_get_error_code($this->p)
                    . xml_getcurrent_line_number($this->p)));
            }
        }

        $this->__parsing = false;
    }

    function destructor()
    {
        if ($this->__parsing) { xml_parse($this->p, null, 1); }
        xml_parser_free($this->p);
    }
}

#run_me
$o =& new XML_Parser "some_xml_file.xml";
$o->parse_file();
dio at edu dot uni-klu dot ac dot at 01-Oct-2005 09:56
If you try to free an XML parser while it is still parsing, strange things will happen - your script will "hang" and no output will be sent to the browser. Consider this pseudo-code example:

-------

...
if (!xml_parse($parser)) echo 'XML error';

xml_parser_free($parser);

...

function SomeCallbackWhichWasSetBefore(...)
{
global $parser;

...

if (some_error_happened) xml_parser_free($parser);  //problem!

...

}

------

It would be logical that xml_parse would return false if the parser was freed while parsing, right? Wrong! Instead, everything hangs and no output will be sent out (no matter whether output buffering is on or not). It took me more than an hour to figure out why: you cannot free a parser handle that is currently parsing. A simple solution:

-------

$xml_error = false;
if (!xml_parse($parser))
echo 'XML error (directly from parser)';
else if ($xml_error)
echo 'XML error (from some callback function);

xml_parser_free($parser);

...

function SomeCallbackWhichWasSetBefore(...)
{
global $parser;
global $xml_error;

if ($xml_error)
return;

...

if (some_error_occured)
{
$xml_error = false;
return;
}

...

}

-------

If you use this solution you will have to check for $xml_error in every callback function. Essentially what you're doing is that, in case you want to stop parsing because of an error, you continue until xml_parse() is finished (without actually doing anything) and then free the parser and act on the error.

Of course the underlying problem is that you cannot stop a parser while it is parsing. There should be some function like xml_throw_error() or xml_parser_stop() or whatever, but unfortunately there isn't.
php dot net at gwprogramming dot com (George Webb) 30-Oct-2003 06:56
I found that with PHP 4.3.4RC1, if you don't call xml_parser_free() before your script ends, some sort of ugliness occurs with the webserver; i.e. the HTTP connection is closed.  (The apache error_log says "exit signal Segmentation fault (11)".)

Usually PHP tends to clean up connections you don't explicitly close (e.g. database connections), but in this case apparently it doesn't.

Some web browsers (MSIE for one) do not actually show this problem, so you may not actually notice it.  Opera 7.11 does show it, which is how I discovered it.

So don't forget to call xml_parser_free() ... always!
xml_parser_create
xml_parser_get_option
Функции парсера XML


Получение значения настройки XML анализатора

xml_parser_free
xml_parser_set_option
Функции парсера XML
PHP Manual

xml_parser_get_option

(PHP 4, PHP 5)

xml_parser_get_option — Получение значения настройки XML анализатора

Описание

mixed xml_parser_get_option ( resource $parser , int $option )

Получает значение настройки XML анализатора.

Список параметров

parser
Ссылка на XML анализатор, настройку которого требуется получить.
option
Какую настройку получить. Доступны следующие настройки XML_OPTION_CASE_FOLDING и XML_OPTION_TARGET_ENCODING. Их описание смотрите в документации к функции xml_parser_set_option().

Возвращаемые значения

Эта функция возвращает FALSE, если parser ссылается на недопустимый анализатор или если option имеет недопустимое значение (в этом случает выбрасывается предупреждение E_WARNING). В остальных случаях возвращается значение настройки.

User Contributed Notes

There are no user contributed notes for this page.
xml_parser_free
xml_parser_set_option
Функции парсера XML


Установка значения настройки XML анализатора

xml_parser_get_option
xml_set_character_data_handler
Функции парсера XML
PHP Manual

xml_parser_set_option

(PHP 4, PHP 5)

xml_parser_set_option — Установка значения настройки XML анализатора

Описание

bool xml_parser_set_option ( resource $parser , int $option , mixed $value )

Устанавливает значение настройки XML анализатора.

Список параметров

parser

Ссылка на XML анализатор.

option

Какую настройку требуется установить. См. ниже.

Доступны следующие настройки:

Настройки XML анализатора
Константа | Тип данных | Описание
XML_OPTION_CASE_FOLDING | integer | Требуется ли включить case-folding для этого анализатора. Включено по умолчанию.
XML_OPTION_SKIP_TAGSTART | integer | Задает количество символов с начала имени тэга, которые следует пропустить.
XML_OPTION_SKIP_WHITE | integer | Требуется ли пропускать значения, состоящие из пробелов.
XML_OPTION_TARGET_ENCODING | string | Устанавливает кодировку, которая будет использоваться XML анализатором. По умолчанию используется кодировка заданная при вызове функции xml_parser_create(). Поддерживаются кодировки ISO-8859-1, US-ASCII и UTF-8.

value

Новое значение настройки.

Возвращаемые значения

Функция возвращает FALSE, если parser ссылается на недопустимый анализатор или если настройка не может быть установлена. В противном случае устанавливается новое значение настройки и возвращается значение TRUE.

User Contributed Notes

www.thomaskoch.it 31-Jul-2008 02:22
The option XML_OPTION_SKIP_WHITE has no effect in my PHP 5.2.6 (with expat-1.95.8-5). To skip cdata composed of white space only, simply check for that at the beginning of your cdata callback function:

<?php
function callback_cdata($parser, $cdata)
{
 if(!trim($cdata))
  return;

 // ... continue processing ...
}
?>
maschoen at pobox dot com 11-Oct-2007 12:19
I'm a little confused about using xml_parser_set_option and xml_parser_get_option with XML_OPTION_SKIP_WHITE and XML_OPTION_SKIP_TAGSTART.

Looking at the source code, ...set_option() accepts both ...SKIP_WHITE and ...SKIP_TAGSTART, and sets a program variables.  On the other hand, ...get_option() returns an error for both.   I'm not sure of the code actually uses the variables properly, although it does reference the set variables.  This does look like an oversite.
j[no_spam_please] at [thx]jessepearson dot net 08-Mar-2007 08:08
In the function below, you need to update two lines if you don't want php to throw warnings.

change these two:
           $elements[$index]['attributes'] = $tag['attributes'];
           $elements[$index]['content'] = $tag['value'];

to this:
      $elements[$index]['attributes'] = empty($tag['attributes']) ? "" : $tag['attributes'];
      $elements[$index]['content']    = empty($tag['value']) ? "" : $tag['value'];
06-Sep-2006 07:56
A little mod to a function posted here...

function xml_to_array( $file )
{
    $parser = xml_parser_create();
    xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
    xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
    xml_parse_into_struct( $parser, file_get_contents($file), $tags );
    xml_parser_free( $parser );

    $elements = array();
    $stack = array();
    foreach ( $tags as $tag )
    {
        $index = count( $elements );
        if ( $tag['type'] == "complete" || $tag['type'] == "open" )
        {
            $elements[$index] = array();
            $elements[$index]['name'] = $tag['tag'];
            $elements[$index]['attributes'] = $tag['attributes'];
            $elements[$index]['content'] = $tag['value'];

            if ( $tag['type'] == "open" )
            {    # push
                $elements[$index]['children'] = array();
                $stack[count($stack)] = &$elements;
                $elements = &$elements[$index]['children'];
            }
        }

        if ( $tag['type'] == "close" )
        {    # pop
            $elements = &$stack[count($stack) - 1];
            unset($stack[count($stack) - 1]);
        }
    }
    return $elements[0];
}
ksavage at achaean dot com 28-Mar-2005 01:25
Had one heck of a time getting curl to send my XML request.  Tried a lot of different things, FINALLY ended up with this.

Im making a curl request to paymentech / Orbital 's payment gateway.   Essentially, I took the same header i made for the fsockopen() request, and used it for this curl request. (Hostinc company didnt allow fsockopen().

You'll note that this specific gateway requires a custom content type header.  Thats what gave me the most trouble.  When using the CURLOPT_HTTPHEADER, and CURLOPT_POSTFIELDS together, it doesnt matter, it sends the default post header because of CURLOPT_POSTFIELDS.

<?php

$url = "https://example.com";
$page = "/proccessing_page.cgi";

$post_string = "<YourXML>All XML stuff Here</YourXML>";

       $header  = "POST ".$page." HTTP/1.0 \r\n";
        $header .= "MIME-Version: 1.0 \r\n";
        $header .= "Content-type: application/PTI26 \r\n";
        $header .= "Content-length: ".strlen($post_string)." \r\n";
        $header .= "Content-transfer-encoding: text \r\n";
        $header .= "Request-number: 1 \r\n";
        $header .= "Document-type: Request \r\n";
        $header .= "Interface-Version: Test 1.4 \r\n";
        $header .= "Connection: close \r\n\r\n";
        $header .= $post_string;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);

        $data = curl_exec($ch);         if (curl_errno($ch)) {
           print curl_error($ch);
        } else {
           curl_close($ch);
        }

// use XML Parser on $data, and your set!

        $xml_parser = xml_parser_create();
        xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
        xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
        xml_parse_into_struct($xml_parser, $data, $vals, $index);
        xml_parser_free($xml_parser);

// $vals = array of XML tags.  Go get em!

?>

Worked like a dream for me.  Enjoy!
matt at mcbridematt dot dhs dot org 16-Dec-2002 05:56
Re: anony at mous dot com
case folding is a violation of the XHTML specification. xhtml is all in lowercase to be inline with the DOM
pupeno at pupeno dot com 16-Nov-2002 01:14
XML is case sensitive, then, from my point of view, disabling case folding doesn't goes against xml 1.0 specifications but the contrary, disabling case folding allow us to distiguish between diferent cases of the same letter ('a' and 'A') which of XML are two diferent things.
From my point of view, disabling case folding is a good practice and I think it should be disabled by default.
More information on:
http://www.isacat.net/2001/xml/case.htm
and
http://www.w3.org/TR/REC-xml
Thank you.
ta at NOSPAM dot magicsquare dot info 09-Jul-2002 04:52
XML_OPTION_SKIP_WHITE works for me (linux, php 4.2.1)

phpinfo says :

XML Support active
XML Namespace Support active
EXPAT Version expat_1.95.2

i guess it depends on expat version/presence
chris at wildcharacters dot com 21-Oct-2001 07:32
The two 'skip' tags are not available to windows users using PHP 4.0.4.  The following:

$skipWhite = xml_parser_get_option ($xmlParser,XML_OPTION_SKIP_WHITE);
$skipTagStart = xml_parser_get_option ($xmlParser,XML_OPTION_SKIP_TAGSTART);

generates the following errors:
Warning: xml_parser_get_option: unknown option in c:/program files/abria merlin/apache/htdocs/xml/sax_test.php on line 230
anony at mous dot com 20-Apr-2000 05:26
Disable case folding or your code will be violating the XML 1.0 specification.
xml_parser_get_option
xml_set_character_data_handler
Функции парсера XML


Установка обработчика символьных данных

xml_parser_set_option
xml_set_default_handler
Функции парсера XML
PHP Manual

xml_set_character_data_handler

(PHP 4, PHP 5)

xml_set_character_data_handler — Установка обработчика символьных данных

Описание

bool xml_set_character_data_handler ( resource $parser , callable $handler )

Устанавливает обработчик символьных данных для заданного XML анализатора parser.

Список параметров

parser

Ссылка на XML анализатор.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать два аргумента:

handler ( resource $parser , string $data )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
data
Второй аргумент data должен содержать данные в виде текстовой строки.

Обработчик символьных данных вызывается для каждого фрагмента текста в XML документе. Он также может вызываться несколько раз внутри каждого фрагмента (например для не-ASCII строк).

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

pigeon at pigeonsnest dot co dot uk 03-Mar-2012 01:23
Another workaround for the problem of entities being eaten is to "hide" them from xml_parse(), so the callback is called only once, and then "un-hide" them afterwards...

<?php
$input_data = preg_replace('/&(#?[a-z0-9]+);/', 'SOME_UNIQUE_STRING_dhe74037_\1;', $input_data);
xml_parse($parser, $input_data);

# callback does stuff

$output_data = preg_replace('/SOME_UNIQUE_STRING_dhe74037_(#?[a-z0-9]+);/', '&\1;', $output_data);
?>
svanegmond at tinyplanet dot ca 08-Oct-2010 12:06
For those who are having their character entities eaten by this function (e.g. &amp; &lt; and so forth):

You will notice that your callback gets called several times.

input: Give me some beans &amp; rice. &#032;

call 1: Give me some beans
call 2: amp; and rice
call 3: #032;

There is an obvious workaround. This is not perfect:

<?php
        $text = preg_replace('/^([a-z]+;)/','&\1', $text);
        $text = preg_replace('/^(#[0-9]+;)/', '&\1', $text);
?>
jhill at live dot com 28-Aug-2008 07:11
To detect that concatenation of data is taking place, you can keep track of whether the last function call was to the data processing function.
e.g. using $this->inside_data variable below:

<?php
xml_set_element_handler($this->parser, "start_tag", "end_tag");
xml_set_character_data_handler($this->parser, "contents");

protected function contents($parser, $data)
{
    switch ($this->current_tag) {
            case "name":
                if ($this->inside_data)
                    $this->name .= $data; // need to concatenate data
                else
                    $this->name = $data;
                break;
         ...
    }
    $this->inside_data = true;
}

protected function start_tag($parser, $name)
{
    $this->current_tag = $name;
    $this->inside_data = false;
}

protected function end_tag() {
    $this->current_tag = '';
    $this->inside_data = false;
}
?>
unspammable-iain at iaindooley dot com 03-Jan-2006 01:41
re: jason at omegavortex dot com below, another way to deal with whitespace issues is:

        function charData($parser,$data)
        {
            $char_data = trim($data);

            if($char_data)
                $char_data = preg_replace('/  */',' ',$data);

            $this->cdata .= $char_data;
        }

This means that:

    <p>here is my text <a href="something">my text</a>
    and here is some more after some spaces at the
    beginning of the line</p>

comes out properly. You could do further replacements if you want to deal with tabs in your files. i only ever use spaces. if you only use trim() then you would lose the space before the <a> tag above, but trim() is a good way to check for completely empty char data, then just replace more than one space with a single space. this will preserve a single space at the beginning and end of the cdata.
jason at omegavortex dot com 06-Dec-2005 11:00
I don't believe the problem has been addressed, but if you're parsing an XML file and run into the line break (or tab) problem I believe this function may help:

if (!preg_match("/((\r|)\n)/i", $data) || preg_match("/\\t+/i", $data)) {
(Code Here)
}
wako057 at gmx dot fr 22-Aug-2005 09:39
That give an example about the note.
When you are creating a class and you need to use a method of your class to the function xml_set_character_data_handler that is the way to point give the method:

class example
{
   function example()
   {
   }

  function data($parseur, $texte)
  {
      switch ($this->derniereBaliseRencontree)
      {
         case "TITLE":
                     -----
          break;
         case "LINK"
                    -----
         break;
        case "DESCRIPTION":
                    -----
        break;
     }
  }

  function fetchOpen($parseur, $nomBalise, $tableauAttributs)
  {
     ----------------
  }

  function fetchClose($parseur, $nomBalise)
  {
     ----------------
  }

  function ZZZ()
  {
      $parseurXML = xml_parser_create();
       xml_set_element_handler($parseurXML, Array(&$this, 'fetchOpen'),   Array(&$this, 'fetchClose'));
         ---------------- <IMPORTANT> --------------------------
       xml_set_character_data_handler($parseurXML, Array(&$this, 'data'));
        ---------------- </IMPORTANT> --------------------------
}
ben at removethis emediastudios dotcom 05-Aug-2005 03:53
I too love the undocumented "splitting" functionality :-p.

Rather than concatinating the data based on whether or not the current tag name has changed from the previous tag name I suggest always concatinating like the following with the $catData variable being unset in the endElement function:

<?php

function endElement ($parser, $data) {
  global $catData;

  // Because we are at an element end we know any splitting is finished
  unset($GLOBALS['catData']);
}

function characterData ($parser, $data) {
  global $catData;

  // Concatinate data in case splitting is taking place
  $catData.=$data;

}

?>

This got me around a problem with data like the following where, because characterData is not called for empty tags, the previous and current tag names were the same even though splitting was not taking place.

<companydept>
<companydeptID></companydeptID>
<companyID>1</companyID>
<companydeptName></companydeptName>
</companydept>
<companydept>
<companydeptID></companydeptID>
<companyID>2</companyID>
<companydeptName></companydeptName>
</companydept>
<companydept>
<companydeptID></companydeptID>
<companyID>3</companyID>
<companydeptName></companydeptName>
</companydept>
yaroukh at email dot cz 25-Apr-2005 08:51
It would be nice if someone could complete documentation of this function. I think that the "splitting" behaviour should (at least) be mentioned within the documentation, if not explained (please!). I'm not quite sure whether the cut comes after each 1024bytes/chars of data.

My experience looks as follows:
[xmlFile]
...
    <label>slo|�ka</label>
    <comment>koment|�&#345; slo�ky</comment>
...
[/xmlFile]
(Places where the character-data got splitted are marked with pipes. Plus there was latin small letter 'r' with caron instead of &#345;.)

Since the splitting is not mentioned in documentation one could assume that it is a bug; especially when you work with UTF-8 and the cuts come right before some special characters.
(Should the concatenating of $cData be considered to be the proper & 'final' way of processing character-data?)

Also I'd suggest to add another line in "Description" when fc has an alternate usage (instead of hiding it within the "Note" :o); in this particular case I'd prefer this:

Description:
bool xml_set_character_data_handler ( resource parser, callback handler )
bool xml_set_character_data_handler ( resource parser, object reference, method name )

... there are dozens of functions ofcourse where documentation works this way (I mean not mentioning the alternate usage in the "Description" part).

Have a nice day
  Yaroukh
flobee 12-Feb-2005 09:53
re. to Philippe Marc , and  karuna_gadde examples

i found out that the xml_set_character_data_handler call back  function can be called more often for the same element in particular the content is just a few chars long (happen on windows)

so a check up can give you the answer an may be for long strings too.
eg:
<?php
xml_set_character_data_handler($this->parser, "cdata");
//...
function cdata($parser, $cdata) {
// ...
if(isset($this->data[$this->currentItem][$this->currentField])) {
    $this->data[$this->currentItem][$this->currentField] .= $cdata;
} else {
    $this->data[$this->currentItem][$this->currentField] = $cdata;
}
?>
Philippe Marc 28-Oct-2004 07:21
How to overide the 1024 characters limitation of xml_set_character_data_handler.
Took me some time to find out how to deal with that!

When calling a basic XML parser:
$parseurXML = xml_parser_create();
xml_set_element_handler($parseurXML, "opentagfunction", "closetagfunction");
xml_set_character_data_handler($parseurXML, "textfunction");

The textfunction only receive 1024 characters at once, even if the text is 4000 characters long. In facts, the parser seems to split the data in pieces of 1024 characters. The way to handle that is to concatenate them.

example:
If you have an XML tag called UNIPROT_ABSTRACT containing a 4000 characters protein description:
function textfunction($parser, $text)
    {
     if ($last_tag_read=='UNIPROT_ABSTRACT') $uniprot.=$text;
    }
The function is called 4 times and receives 1024+1024+1024+928 characters that will be concatenated in the $uniprot variable using the ".=" concatenation fonction.

Easy to do, but not documented!
Brad dot Harrison at griffith dot edu dot au 11-Jul-2004 10:23
If you need to trim the white space for HTML code and don't rely on spaces for formatting text (if you are then it is time to use Style Sheets) then this code will come in very useful.

 $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
 $data=eregi_replace(">"."[[:space:]]+",">",$data);
 $data=eregi_replace("[[:space:]]+"."<","<",$data);
karuna_gadde at yahoo dot com 27-May-2004 07:01
<?
class Parser {

var $att;
var $id;
var $title;
var $content;
var $index=-1;
var $xml_parser;
var $tagname;

function parser()
{
$file = "data.xml";
$this->xml_parser = xml_parser_create();
xml_set_object($this->xml_parser,$this);
xml_set_element_handler($this->xml_parser, "startElement", "endElement");
xml_set_character_data_handler($this->xml_parser, 'elementContent');
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
if (!xml_parse($this->xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->xml_parser)),
xml_get_current_line_number($this->xml_parser)));
}
}
xml_parser_free($this->xml_parser);
}

function startElement($parser, $name, $attrs) {
if (($name=="TREE") or ($name=="NODE") or ($name=="LEAFNODE"))
    {
         $this->index++;
         $this->att[$this->index]=$name;
    }
    $this->tagname=$name;
}

function elementContent($parser, $data) {
switch ($this->tagname)
{
     case 'ID':
                 $this->id[$this->index]=trim($data);
                 break;
     case 'TITLE' :
                 $this->title[$this->index]=trim($data);
                 //echo $data;
                 break;
     case 'CONTENT'    :
                 $this->content[$this->index]=trim($data);
                 break;

}
}
function endElement($parser, $name){
$this->tagname=="";
}
}
?>

I thought this class is more help full to know about xml_parser with no white spaces
michael dot stilson at wmich dot edu 04-Mar-2004 12:31
Hello,

This is an addition to the note posted by:
wiart at yahoo dot com
22-Aug-2003 05:31
Which is located below.

I had similar problems manually creating XML docs and adding new-lines within my node data, e.g.

<root>
    ...
    <node attribute="something">
        Here is some data. There is a lot of data, and I want to
        be able to read the data from a terminal window, so I add
        newlines to fit everything within 80 columns.
    </node>
    ...
</root>

So, given the above example, my data handler gets called 3 times and the result left in my variable is:

"newlines to fit everything within 80 columns."

Instead of all of the data within "node", which I was expecting.

By using the concatenation operator; however, as suggested by the mentioned note, I was able to get what I needed. Which is of course:

"Here is some data. There is a lot of data, and I want to be able to read the data from a terminal window, so I add newlines to fit everything within 80 columns."
dan30odd08 at hotmail dot com 01-Dec-2003 04:38
I just want to mention that i ran into a problem when parsing an xml file using the character data handler. If you happen to have a string which is also an internal php function stored in your xml data file and you want to output it as a string the parser dosent seem to recognize it.
   I found a way around this problem. In my case i was storing a string with the value read. This would not allow me to output the data so to work around this problem i added a backslash for every character in the data element.

   e.g.      <xml>
    from    <element>read</element>
    to       <element>////read</element>

i dont know if anyone has ran into this problem or not but i thought i would just put it here just so in case someone is getting stuck with this.
wiart at yahoo dot com 22-Aug-2003 05:31
WARNING !!!
Always use concatenation for getting the content of a XML tag when you write the function that will deal with the Character Data handling

Example:

$mycontent = '';
$xml_parser = xml_parser_create ();
xml_set_character_data_handler($xml_parser, "_characterdata");

function _characterdata($parser, $data){
  global $mycontent;
  //HERE: use .= and not =
  $mycontent .= $data;
}

...

while ($data = fread($fp, 4096)) {
    xml_parse($xml_parser, $data, feof($fp));
}

I had the following problem with the use of '=$data' :

In one of my XML documents, the parsing stopped in the middle of a character data :

In original document:
<prop name="nbres">100</prop>

What happened:
<prop name="nbres">10[parsing stopped here in chunck of 4096bytes]0</prop>

As I did not use the concatenation, when I displayed the value of the 'nbres' property, the value was 0 instead of 100 because the first time the function characterdata was called :
$mycontent = 10;

and the second time:
$mycontent = 0;      //!!!!!!!!!!!!! HO HO !! some problem occured ...

Instead of $mycontent = 100;

CONCLUSION:
IN YOUR CHARACTER DATA HANDLER FUNCTIONS, NEVER FORGET THE . (concatenation operator) !!!!! IF YOU DON'T WANT TO HAVE WEIRD BUGS SOME TIMES
morris_hirsch at hotmail dot com 18-Aug-2003 09:15
Thanks to Christian Stocker for clearing up my entity issues,  where some entities are parsed correctly and others not.

The problem is the ''wide'' entities that have a large numeric code simply can not fit in a single byte, which is the default encoding for both source input to the parser and data output from the parser.  So the parser puts out a ''?'' to say it could not store the code value. One could argue that if the input has a &1234; the output should simply copy it as &1234; instead of the ''?'' but that would still mean the  parser behaves two different ways according to the code values, and anyway they don't do it.

So, we need utf8 encoding for the output, and the slightly not obvious way to say so is

  $xml_parser = xml_parser_create ("UTF-8");

which means BOTH source input and data output are utf8.
Remember that utf8 is a superset of basic ASCII but not of extended ASCII, so your input can contain e.g. &eacute;
spelled out, but a native eacute character is wrong here.
Just utf8_encode your input to be sure.

That should do it, and thanks again for the help.
morris_hirsch at hotmail dot com 06-Aug-2003 12:23
Here are two ways to deal with named entities in the XML.

1. Put a list of named entities at the front so the parser knows what they all mean

  $decl = '<!DOCTYPE rootname [

<!ENTITY frac12  "&#x00BD;" >
<!ENTITY frac14  "&#x00BC;" >
<!ENTITY frac34  "&#x00BE;" >
<!ENTITY frac18  "&#x215B;" >
<!ENTITY frac38  "&#x215C;" >
<!ENTITY frac58  "&#x215D;" >
<!ENTITY frac78  "&#x215E;" >
<!ENTITY frac13  "&#x2153;" >
<!ENTITY frac23  "&#x2154;" >
<!ENTITY frac15  "&#x2155;" >
<!ENTITY frac25  "&#x2156;" >
<!ENTITY frac35  "&#x2157;" >
<!ENTITY frac45  "&#x2158;" >
<!ENTITY frac16  "&#x2159;" >
<!ENTITY frac56  "&#x215A;" >

<!ENTITY mdash  "&#x2014;" >

 ..... lots of others

<!ENTITY uuml    "&#252;" >
<!ENTITY yacute  "&#253;" >
<!ENTITY thorn   "&#254;" >
<!ENTITY yuml    "&#255;" >

]>';

$parseThis = $decl . "<rootname> ..... </rootname>";

This works fine for all the single-byte (European) codes,
but not the wide codes like emdash or frac18.
They seem to be trashed when the character data handler gets them.  They all echo as "?"

There may be a way to make them work, but until I find it,
or a newer release takes care of it, here is a work-around that does work.

2. Rewrite every ampersand as &amp; in the input stream

 $ampXML = str_replace ("&", "&amp;", $sourceXML);

Now the parser will see &amp;foo; instead of &foo;

It does not try to decode it, so wide (two byte) values are not a problem, and no list of names is needed.

When you write that to your output you have &foo;

which is usually fine for the next stage of your process.
www.PhoC.de 20-May-2003 07:39
In some cases it's better to avoid storing data which is not needed. In these cases the function

chop()  ( => Alias of function rtrim() )

could be usefull to prevent data like

"\t"
"\r"
"\o"
"\n"
"\x0B"
" "

to be stored in a array or a string or something like this.

Example: (storing data in a string)
________________
$filename="xyz.xml";

if(!($fp=fopen($filename,"r"))){
   die("Cannot open $filename ");
}

while (!feof($fp))
{
   $data .= chop(fgets($fp, 4096));
}

fclose($fp);
________________

Have a look at the documentation of rtrim() http://www.php.net/manual/en/function.rtrim.php.

Greetz
PhoC
waldo at wh-e dot com 06-Mar-2002 09:52
Here's a way to strip all the spaces between tags in an xml document.

//strip white space between tags
$data=eregi_replace(">"."[[:space:]]+"."<","><",$data);

So this:

<house>
  <garage>
    <car>Waldo</car>
  </garage>
</house>

would be changed to:

<house><garage><car>Waldo</car></garage></house>

It was useful to me. Maybe you too?
ken at positive-edge dot com 29-Jan-2002 08:20
the function handler is called several times when it parses the character data.  It doesn't return the entire string as it suggests.  There are special exceptions that will always force the parser to stop scanning and call the character data handler.  This is when:

- The parser runs into an Entity Declaration, such as &amp; (&) or &apos; (�)
- The parser finishes parsing an entity
- The parser runs into the new-line character (\n)
- The parser runs into a series of tab characters (\t)

And perhaps others.

For instance, if we have this xml content:

<mytag name=�Ken Egervari� title=�Chief Technology Officer�>
    Ken has been Positive Edge&apos;s Chief Technology Officer for 2 years.
</mytag>

The parser will call the character data handler 6 times.  This is what will happen:

1    \n
2    \t
3    Ken has been Positive Edge
4    �
5    s Chief Technology Officer for 2 years.
6    \n

I hope that helps people out.
mogmios at mlug dot missouri dot edu 24-Oct-2001 04:24
If you want to strip unwanted whitespace in an HTML-like manner then there are two steps.

The first you need to strip consecutive whitespaces from all you input data like this:  $data = eregi_replace ( "[[:space:]]+", " ", $data );

Then in your cdata handler make a check to see if it's blank space. An easy way is like this: if ( trim ( $cdata ) ) { work on cdata }

That should take care of any whitespace issues you might have.
annies at cs dot tu-berlin dot de 03-Aug-2001 10:43
The maximum size of the second parmeter $data seems to be 1024. Is there more character data  in the XML text the handler is called again immediately with the next portion.
xml_parser_set_option
xml_set_default_handler
Функции парсера XML


Установка обработчика по умолчанию

xml_set_character_data_handler
xml_set_element_handler
Функции парсера XML
PHP Manual

xml_set_default_handler

(PHP 4, PHP 5)

xml_set_default_handler — Установка обработчика по умолчанию

Описание

bool xml_set_default_handler ( resource $parser , callable $handler )

Задает обработчик по умолчанию для XML анализатора parser.

Список параметров

parser

Ссылка на XML анализатор.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать два аргумента:

handler ( resource $parser , string $data )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
data
Второй аргумент dataдолжен содержать символьные данные. Это может быть XML объявление, объявление типа документа, сущности или другие данные, для которых еще нет обработчика.

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

anoril at anoril dot com 13-Jul-2006 07:54
I have the same issue using two installation of PHP5: on accepts to use the default handler while the other only uses the character_data one.

Maybe a configuration problem...

;) Nonor.
phillip 26-Apr-2005 02:13
it seems to me that in PHP5 the function defined as default-handler (using xml_set_default_handler()) doesen't get passed the cdata anymore:

i.e.:
xml_set_element_handler($this->parser, 'parseSTART', 'parseEND');
xml_set_default_handler($this->parser, 'parseDEFAULT');
function parseSTART() { ... }
function parseEND() { ... }
function parseDEFAULT() { ... }

under PHP5, parseDEFAULT will NOT get passed any cdata, but unter PHP4 it will. at least that's my take on the strange stuff (not) happening after migrating to PHP5.

my solution was to add a xml_set_character_data_handler($parser, 'parseDEFAULT'). it worked for me.
xml_set_character_data_handler
xml_set_element_handler
Функции парсера XML


Установка обработчика начального и конечного элементов

xml_set_default_handler
xml_set_end_namespace_decl_handler
Функции парсера XML
PHP Manual

xml_set_element_handler

(PHP 4, PHP 5)

xml_set_element_handler — Установка обработчика начального и конечного элементов

Описание

bool xml_set_element_handler ( resource $parser , callable $start_element_handler , callable $end_element_handler )

Устанавливает функцию обработчик элементов для XML анализатора parser. start_element_handler и end_element_handler - строки, содержащие имена функций, которые должны быть определены на момент вызова функции xml_parse() из анализатора parser.

Список параметров

parser

Ссылка на XML анализатор.

start_element_handler

Функция с именем start_element_handler должна принимать три аргумента:

start_element_handler ( resource $parser , string $name , array $attribs )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
name
Второй аргумент name содержит имя элемента, для которого этот обработчик вызывается. Если настройка case-folding включена для этого анализатора, имя элемента будет в верхнем регистре.
attribs
Третий аргумент attribs содержит ассоциативный массив с атрибутами элемента (если есть). Индексами этого массива будут имена атрибутов, а значения массива будут соответствовать значениям атрибутов. Имена атрибутов должны быть приведены к регистру в соответствии с теми же критериями, что и имена элементов. Значения атрибутов не приводятся к какому-либо регистру. Атрибуты извлекаются из элемента в порядке прямого обхода по attribs, используя функцию each().Первый индекс в массиве соответствует первому атрибуту и так далее.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

end_element_handler

Функция с именем end_element_handler должна принимать два аргумента:

end_element_handler ( resource $parser , string $name )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
name
Второй аргумент name содержит имя элемента, для которого этот обработчик вызывается. Если настройка case-folding включена для этого анализатора, имя элемента будет в верхнем регистре.

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

kok at nachon dot nl 26-Sep-2008 06:44
Here is another example of detecting empty elements. I works with libxml2. Note that it handles buffer boundaries.

<?php

$depth = 0; //current depth, used for pretty printing
$empty = false; //whether the tag is empty
$offset = 0; //the index of the start of the current buffer within the stream

function tagStart($parser, $name, array $attribs) {
    global $depth, $empty, $data, $offset, $lastchar;
    $idx = xml_get_current_byte_index($parser);
    /* xml_get_current_byte_index returns index within the streams and not
       within the buffer.*/

    /* Check if the index is within the buffer. */
    if (isset($data[$idx - $offset])) {
        $c = $data[$idx - $offset];
    } else {
        /* If it isn't simple use the last character of the buffer. */
        $c = $lastchar;
    }
    $empty = $c == '/';
    echo str_repeat("\t", $depth), "<$name", ($empty ? '/>' : '>'), "\n";
    if (!$empty) ++$depth;
}

function tagEnd($parser, $name) {
    global $depth, $empty;
    if (!$empty) {
        --$depth;
        echo str_repeat("\t", $depth), "</$name>\n";
    } else {
        $empty = false;
    }
}

$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($parser, 'tagStart', 'tagEnd');

$data1 = '
<test>
    <empty att="3" />
    <nocontent></nocontent>
    <content>
        <empty/>
        <empty/>
    </content>
    <empty/';

$data2 = '>
    <empty att="5" />
</test>
';

$data = &$data1;
$length = strlen($data1);
$lastchar = $data[$length-1];
xml_parse($parser, $data1);
$offset .= $length;
$data = &$data2;
xml_parse($parser, $data2);
darien at etelos dot com 12-Feb-2007 10:48
This documentation is somewhat awry. I know it's been said many times before, but it bears repeating...

If using PHP4, you may be required to use xml_set_object() instead of calling any of the xml_set_*_handler() functions with a two-item array. It will work fine on PHP5, but move the same code to PHP4 and it will create one copie of $this (even if you use &$this) for each handler you set!

<?php
// This code will fail mysteriously on PHP4.
$this->parser = xml_parser_create();
xml_set_element_handler(
            $this->parser,
            array(&$this,"start_tag"),
            array(&$this,"end_tag")
        );
        xml_set_character_data_handler(
            $this->parser,
            array(&$this,"tag_data")
        );
?>

<?php
// This code will work on PHP4.
$this->parser = xml_parser_create();
xml_set_object($this->parser,&$this);
xml_set_element_handler(
            $this->parser,
            "start_tag",
            "end_tag"
        );
        xml_set_character_data_handler(
            $this->parser,
            "tag_data"
        );
?>
lloeki at gmail dot com 31-Oct-2006 03:07
I modified the previous script, so that it is associative. I find it more useful that way. BTW I prefer strtolower() things, but that's not mandatory at all.

<?php

$file = "data.xml";
$depth = 0;
$tree = array();
$tree['name'] = "root";
$stack[] = &$tree;

function startElement($parser, $name, $attrs) {
   global $depth;
   global $stack;
   global $tree;

   $element = array();
   foreach ($attrs as $key => $value) {
       $element[strtolower($key)]=$value;
   }

   end($stack);
   $stack[key($stack)][strtolower($name)] = &$element;
   $stack[strtolower($name)] = &$element;

   $depth++;
}

function endElement($parser, $name) {
   global $depth;
   global $stack;

   array_pop($stack);
   $depth--;
}

$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);
$tree = end(end($stack));
echo "<pre>";
print_r($tree);
echo "</pre>";

?>
rubentrancoso at gmail dot com 29-Aug-2006 01:44
My 25 cents. This example show how to parse a XML in a associative array tree.

<?php

$file = "flow/flow.xml";
$depth = 0;
$tree = array();
$tree['name'] = "root";
$stack[count($stack)] = &$tree;

function startElement($parser, $name, $attrs) {
   global $depth;
   global $stack;
   global $tree;

   $element = array();
   $element['name'] = $name;
   foreach ($attrs as $key => $value) {
        //echo $key."=".$value;
        $element[$key]=$value;
    }

   $last = &$stack[count($stack)-1];
   $last[count($last)-1] = &$element;
   $stack[count($stack)] = &$element;

   $depth++;
}

function endElement($parser, $name) {
   global $depth;
   global $stack;

   array_pop($stack);
   $depth--;
}

$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);
$tree = $stack[0][0];
echo "<pre>";
print_r($tree);
echo "</pre>";
redb 15-May-2006 05:48
Example below (BadParser) works fine with some changes.

xml_set_element_handler ( $parser, array ( &$this, 'tagStart' ), array ( &$this, 'tagEnd' ) );
xml_set_character_data_handler ( $parser, array ( &$this, 'tagContent' ) );
Anonymous Koward 06-Apr-2006 10:38
This has been mentioned before, but I just spent several days trying to figure out what was going on. Folks, if your XML parser is completely in a class, look at the documentation for xml_set_object(). The documentation above does say you can use functions inside classes as callbacks for xml_set_element_handler, but it doesn't tell you that if your entire XML parser is inside a class, then this is the _WRONG_ way to do things.

You should instead call xml_set_object with your parser variable and $this, which will then fix strange errors that can otherwise crop up and stop you having to pass an array of ( $this, 'tagStart' ) to this function.

e.g.

<?php

class BadParser
{

    function BadParser ()
    {

        $parser = xml_parser_create();

        //This is the WRONG WAY to set the functions inside your class for parsing the XML.
        xml_set_element_handler ( $parser, array ( $this, 'tagStart' ), array ( $this, 'tagEnd' ) );
        xml_set_character_data_handler ( $parser, array ( $this, 'tagContent' ) );

        xml_parse ( $parser, $this->XMLData );

    }

    function tagStart ( $parser, $tagName, $attributes = NULL )
    {

        $this->tag = $tagName;

    }

    function tagEnd ( $parser, $tagName )
    {

        $this->tag = NULL;

    }

    function tagContent ( $parser, $content )
    {

        //This WILL NOT work as you intended. $this->tag will do strange, mysterious things, but it won't be the tag name like you expected.
        echo ( "{$this->tag}: $content" );

    }

}

?>

Instead, you should change your constructor to do this as XML initalization instead:

<?php

class GoodParser
{

    function GoodParser ()
    {

        $parser = xml_parser_create();

        //This is the RIGHT WAY to set everything inside the object.
        xml_set_object ( $parser, $this );

        xml_set_element_handler ( $parser, 'tagStart', 'tagEnd' );
        xml_set_character_data_handler ( $parser, 'tagContent' );

        xml_parse ( $parser, $this->XMLData );

    }

    /* ... */

}

?>

I don't know if this problem exists in other versions of PHP. My version is 4.4.1. Hope I made sense, if this note had been around, it would've saved a lot of headaches for me (maybe I'm not observant enough).
vladimir-leontiev at uiowa dot edu 13-Dec-2005 09:44
It seems that characterData() gets characters in chuncks of 1024; therefore if you have string of characters between you tags that is longer than 1024 then characterData() will be called more that once for single pair of tags. I don't know if this feature(bug?) is documented anywhere, I just wanted to warn everyone about this; it had tripped me. I use php 4.3.10 on Linux.
hendra_g at hotmail dot com 19-Nov-2005 08:10
I ran into the same problem with 'ibjoel at hotmail dot com' in regards to self-closing tags, and found that the script that he/she wrote did not work as I expected.
I played around with some of php's functions and examples and compiled something, which may not be the neatest solution, but it works for the data that 'ibjoel at hotmail dot com' provided.
The data needs to be read from a file though, so the fp can be utilised. It still uses the xml_get_current_byte_index(resource parser) trick, but this time, I check for the last 2 character before the index and test if it's "/>".

<?php
/* myxmltest.xml:
<normal_tag>
  <self_close_tag />
     data
  <normal_tag>data
     <self_close_tag attr="value" />
  </normal_tag>
     data
  <normal_tag></normal_tag>
</normal_tag>
*/

//## Global Variables ##//
$file = "myxmltest.xml";
$character_data_on = false;
$tag_complete = true;

function startElement($parser, $name, $attrs)
{
    global $character_data_on;
    global $tag_complete;

    echo "&lt;<font color=\"#0000cc\">$name</font>";
    //## Print the attributes ##//
    if (sizeof($attrs)) {
        while (list($k, $v) = each($attrs)) {
            echo " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    //## Tag is still still incomplete,
    //## will be completed at either endElement or characterData ##//
    $tag_complete = false;
    $character_data_on = false;
}

function endElement($parser, $name)
{
    global $fp;
    global $character_data_on;
    global $tag_complete;

    //#### Test for self-closing tag ####//
    //## xml_get_current_byte_index(resource parser) when run in this
    //## function, gives the index at (indicated by *):
    //##   for self closing tag: <br />*
    //##   for individual closing tag: <div>character data*</div>
    //## So to test for self-closing tag, we can just test for the last 2
    //## characters from the index
    //###################################//

    if (!$character_data_on) {
        //## Record current fp position ##//
        $temp_fp = ftell($fp);

        //## Point fp to 2 bytes before the end element byte index ##//
        $end_element_byte_index = xml_get_current_byte_index($parser);
        fseek($fp,$end_element_byte_index-2);

        //## Gets the last 2 characters before the end element byte index ##//
        $validator = fgets($fp, 3);

        //## Restore fp position ##//
        fseek($fp,$temp_fp);

        //## If the last 2 character is "/>" ##//
        if ($validator=="/>") {
            //// Complete the self-closing tag ////
            echo " /&gt";
            //// Otherwise it is an individual closing tag ////
        } else echo "&gt&lt/<font color=\"#0000cc\">$name</font>&gt";
        $tag_complete = true;
    } else echo "&lt/<font color=\"#0000cc\">$name</font>&gt";

    $character_data_on = false;
}

function characterData($parser, $data)
{
    global $character_data_on;
    global $tag_complete;

    if ((!$character_data_on)&&(!$tag_complete)) {
        echo "&gt";
        $tag_complete = true;
    }
    echo "<b>$data</b>";
    $character_data_on = true;
}

$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
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");
}

echo "<pre>";
while ($file_content = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $file_content, 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)));
    }
}
echo "</pre>";
xml_parser_free($xml_parser);
?>
turan dot yuksel at tcmb dot gov dot tr 20-Sep-2005 03:41
The method that 'ibjoel at hotmail dot com' have described requires libxml2 as the xml parser, it does not work with expat. For a brief explanation, see xml_get_current_byte_index.
ibjoel at hotmail dot com 01-Aug-2005 03:49
I noticed that in the example below, and all the examples I've seen on this site for viewing xml in html, the look of self closing tags such as <br /> are not preserved. The parser cannot distinguish between <tag /> and <tag></tag>, and if your start and end element functions are like these examples, both instances will be output with both an indvidual start and end tag.  I needed to preserve self-closing tags and it took me a while to figure out this work around. Hope this helps someone...

The start tag is left open, and then completed by it's first child, the next start tag or its end tag.  The end tag will complete with " />", or </tag> depending on the number of bytes between the start and end tags in the parsed data.
<?php
//$data=filepath or string
$data=<<<DATA
<normal_tag>
  <self_close_tag />
      data
  <normal_tag>data
     <self_close_tag attr="value" />
  </normal_tag>
      data
  <normal_tag></normal_tag>
</normal_tag>
DATA;

function startElement($parser, $name, $attrs)
{
        xml_set_character_data_handler($parser, "characterData");
        global $first_child, $start_byte;
        if($first_child)          //close start tag if neccessary
                echo "><br />";
        $first_child=true;
        $start_byte=xml_get_current_byte_index ($parser);
        if(count($attrs)>=1){
                foreach($attrs as $x=>$y){
                        $attr_string .= " $x=\"$y\"";
                }
        }
        echo htmlentities("<{$name}{$attr_string}"); //unclosed starttag
}

function endElement($parser, $name)
{
        global $first_child, $start_byte;
        $byte=xml_get_current_byte_index ($parser);
        if($byte-$start_byte>2){           //if end tag is more than 2 bytes from start tag
                if($first_child)          //close start tag if neccessary
                        echo "><br />";
                echo htmlentities("</{$name}>")."<br />";  //individual end tag
        }else
                echo " /><br />";  // self closing tag
        $first_child=false;

}

function characterData($parser, $data)
{
        global $first_child;
        if($first_child)  //if $data is first child, close start tag
                echo "><br />";
        if($data=trim($data))
                echo "<font color='blue'>$data</font><br />";
        $first_child=false;
}

function ParseData($data)
{
        $xml_parser = xml_parser_create();
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
        if(is_file($data))
        {
                if (!($fp = fopen($file, "r"))) {
                        die("could not open XML input");
                }

                while ($data = fread($fp, 4096)) {
                        if (!xml_parse($xml_parser, $data, feof($fp))) {
                                $error=xml_error_string(xml_get_error_code($xml_parser));
                               $line=xml_get_current_line_number($xml_parser);
                                die(sprintf("XML error: %s at line %d",$error,$line));
                        }
                }
        }else{
                if (!xml_parse($xml_parser, $data, 1)) {
                                $error=xml_error_string(xml_get_error_code($xml_parser));
                                $line=xml_get_current_line_number($xml_parser);
                                die(sprintf("XML error: %s at line %d",$error,$line));
                }
        }

        xml_parser_free($xml_parser);
}

ParseData($data);
?>
youniforever at naver dot com 30-Apr-2005 03:41
<html>
  <head>
    <title>SAX Demonstration</title>
   <META HTTP-EQUIV='Content-type' CONTENT='text/html; charset=euc-kr'>
  </head>
  <body>
    <h1>RSS ������</h1>

      <?php

     $file = "data.xml";

      $currentTag = "";
      $currentAttribs = "";

      function startElement($parser, $name, $attribs)
      {
          global $currentTag, $currentAttribs;
          $currentTag = $name;

          $currentAttribs = $attribs;
          switch ($name) {

          default:
              echo("<b>&lt$name&gt</b><br>");
              break;
          }
      }

      function endElement($parser, $name)
      {
          global $currentTag;
          switch ($name) {
          default:
              echo("<br><b>&lt/$name&gt</b><br><br>");
              break;
          }
          $currentTag = "";
          $currentAttribs = "";
      }

      function characterData($parser, $data)
      {
          global $currentTag;
          switch ($currentTag) {
          case "link":
              echo("<a href=\"$data\">$data</a>\n");
              break;
          case "title":
              echo("title : $data");
              break;
          default:
              echo($data);
              break;
          }
      }

     $xmlParser = xml_parser_create();

      $caseFold = xml_parser_get_option($xmlParser,
                                        XML_OPTION_CASE_FOLDING);

      $targetEncoding = xml_parser_get_option($xmlParser,
                                              XML_OPTION_TARGET_ENCODING);

      if ($caseFold == 1) {
          xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
      }

      xml_set_element_handler($xmlParser, "startElement", "endElement");
      xml_set_character_data_handler($xmlParser, "characterData");

      if (!($fp = fopen($file, "r"))) {
          die("Cannot open XML data file: $file");
      }

     while ($data = fread($fp, 4096)) {
          if (!xml_parse($xmlParser, $data, feof($fp))) {
              die(sprintf("XML error: %s at line %d",
                          xml_error_string(xml_get_error_code($xmlParser)),
                          xml_get_current_line_number($xmlParser)));
              xml_parser_free($xmlParser);
          }
      }
      xml_parser_free($xmlParser);
      ?>
    </table>
  </body>
</html>
13-Mar-2005 01:34
In response to aw at avatartechnology dot com...
In response to landb at mail dot net...

When your functions are in an object:
Careful ! Don't forget to add: & (reference) to your parameters.

xml_set_element_handler($parser, array(&$this,"_startElement"), array(&$this,"_endElement"));
--> xmlparse will work on your object (good).

instead of:
xml_set_element_handler($parser, array($this,"_startElement"), array($this,"_endElement"));
---> xmlparse will work on a COPY of your object (often bad)

Vin-s
(sorry for my english)
aw at avatartechnology dot com 21-Oct-2004 08:40
In response to landb at mail dot net...

As the notes mention, you can pass an array that contains the reference to an object and a method name when you need... so you can call methods in your own class as handlers like this:

xml_set_element_handler($parser, array($this,"_startElement"), array($this,"_endElement"));

Hope it helps...
tj at tobyjoe dot com 31-Jan-2003 11:22
It seems that the tag handlers don't block on one another (the end handler is called whether or not the begin handler has finished). this can put you in a tight spot if you don't realize it while planning your app.
11-Oct-2001 04:09
You CAN use classes to parse XML. Just take a look at the following function:

xml_set_object
jg at jmkg dot net 07-May-2001 11:08
If you are using a class for xml parsing, and want to check the return value of xml_set_element_handler in case it  fails, you must do this outside of the class's constructor. Inside the constructor, PHP-4.0.5 will die.

Basically, put all your xml initialisation code in another function of the class, and keep it out of the constructor.
xml_set_default_handler
xml_set_end_namespace_decl_handler
Функции парсера XML


Установка обработчика выхода за пределы пространства имен

xml_set_element_handler
xml_set_external_entity_ref_handler
Функции парсера XML
PHP Manual

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_end_namespace_decl_handler — Установка обработчика выхода за пределы пространства имен

Описание

bool xml_set_end_namespace_decl_handler ( resource $parser , callable $handler )

Задает обработчик, который вызывается при выходе за пределы объявления пространства имен. Этот обработчик будет вызываться для каждого объявления пространства имен после того как отработает обработчик окончания элемента, в котором это пространство имен было объявлено.

Список параметров

parser

Ссылка на XML анализатор.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать два аргумента и возвращать целочисленный результат. Если обработчик вернет FALSE (равно как и ничего не вернет), XML анализатор прекратит работу, а функция xml_get_error_code() будет возвращать константу XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
prefix
Префикс - строка, используемая как ссылка на пространство имен в пределах XML объекта.

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примечания

Замечание:

Это событие не поддерживается LibXML.

Смотрите также

  • xml_set_start_namespace_decl_handler() - Установка обработчика входа в пределы пространства имен

User Contributed Notes

Aeden Jameson 19-Dec-2004 09:19
NOTE: The namespace end event is not supported under libxml.  This issue is formally addressed in the bug report at http://bugs.php.net/bug.php?id=30834
xml_set_element_handler
xml_set_external_entity_ref_handler
Функции парсера XML


Установка обработчика внешних сущностей

xml_set_end_namespace_decl_handler
xml_set_notation_decl_handler
Функции парсера XML
PHP Manual

xml_set_external_entity_ref_handler

(PHP 4, PHP 5)

xml_set_external_entity_ref_handler — Установка обработчика внешних сущностей

Описание

bool xml_set_external_entity_ref_handler ( resource $parser , callable $handler )

Задает функцию обработчик внешних сущностей для XML анализатора parser.

Список параметров

parser

Ссылка на XML анализатор.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать пять аргументов и возвращать целочисленный результат. Если обработчик вернет FALSE (равно как и ничего не вернет), XML анализатор прекратит работу, а функция xml_get_error_code() будет возвращать константу XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $open_entity_names , string $base , string $system_id , string $public_id )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
open_entity_names
Второй аргумент open_entity_names - список разделенных пробелами имен сущностей, которые могут участвовать в разборе текущей сущности (включая текущую сущность).
base
Это основа для разрешения системного идентификатора (system_id) внешней сущности. На данный момент в качестве этого аргумента всегда передается пустая строка.
system_id
Четвертый аргумент system_id - системный идентификатор в том виде, как он представлен в объявлении сущности.
public_id
Пятый аргумент public_id - общедоступный идентификатор в том виде, как он представлен в объявлении сущности, либо пустая строка, если такового нет; пробелы в идентификаторе будут нормализованы в соответствии с требованиями XML спецификации.

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
xml_set_end_namespace_decl_handler
xml_set_notation_decl_handler
Функции парсера XML


Установка обработчика объявления условных обозначений

xml_set_external_entity_ref_handler
xml_set_object
Функции парсера XML
PHP Manual

xml_set_notation_decl_handler

(PHP 4, PHP 5)

xml_set_notation_decl_handler — Установка обработчика объявления условных обозначений

Описание

bool xml_set_notation_decl_handler ( resource $parser , callable $handler )

Задает обработчик объявления обозначений для XML анализатора parser.

Раздел объявления обозначений является частью DTD документа и имеет следующий формат:

<!NOTATION <parameter>name</parameter>
{ <parameter>systemId</parameter> | <parameter>publicId</parameter>?>
См. » раздел 4.7 спецификации XML 1.0 для более полного описания обозначений (нотаций).

Список параметров

parser

Ссылка на XML анализатор.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать пять аргументов:

handler ( resource $parser , string $notation_name , string $base , string $system_id , string $public_id )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
notation_name
Имя обозначения name в том же виде, как описано выше.
base
Это основа для разрешения системного идентификатора (system_id) внешней сущности. На данный момент в качестве этого аргумента всегда передается пустая строка.
system_id
Системный идентификатор объявления внешнего обозначения.
public_id
Общедоступный идентификатор объявления внешнего обозначения.

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
xml_set_external_entity_ref_handler
xml_set_object
Функции парсера XML


Использование XML анализатора внутри объекта

xml_set_notation_decl_handler
xml_set_processing_instruction_handler
Функции парсера XML
PHP Manual

xml_set_object

(PHP 4, PHP 5)

xml_set_object — Использование XML анализатора внутри объекта

Описание

bool xml_set_object ( resource $parser , object &$object )

Эта функция позволяет использовать parser внутри объекта object. Все callback-функции могут быть установлены функциями xml_set_element_handler() и т.п. и использоваться как методы объекта object.

Список параметров

parser

Ссылка на XML анализатор.

object

Объект, в котором будет использоваться XML анализатор.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования xml_set_object()

<?php
class xml  {
    var $parser;

    function xml()
    {
        $this->parser = xml_parser_create();

        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
    }

    function parse($data)
    {
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($parser, $tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($parser, $cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($parser, $tag);
    }

} // окончание определения класса xml

$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

User Contributed Notes

wake dot shinigami at gmail dot com 23-Nov-2005 08:28
I finally managed to get xml_set_object() to work, after much documentation searching.  As the solution I found has been hinted at, the focus has been wrong.

There have been many problems getting class contained XML parsers to make changes to the members of an instance.  This is because, from what I'm guessing, the functions are using a either a new annonymous instance of the class or an uninstanced version of the class.

What we want to make sure it does it that the parser is accessing its handlers as member methods of a particular instance of a class.  This can be done using the array method for passing a callback, setting the object as a reference to this instance.  This way, you know that the parser is going to call the function properly.

Ex:
<?php
class Parser {

 private $parser;
 private $data;

 public function __construct() {
  $this->parser = NULL;
  $this->data = '';
 }

 private function ParseElementStart($parser, $name, $attrs) {
  // Code
 }
 private function ParseElementEnd($parser, $name) {
  // Code
 }

 public function Parse($XMLdata) {
  $this->parser = xml_parser_create();
  xml_set_object($this->parser, $this);
  xml_set_element_handler($this->parser,
                          array(&$this, 'ParseElementStart'),
                          array(&$this, 'ParseElementEnd'));
  xml_parse($this->parser, $XMLdata);
  xml_parser_free($this->parser);
 }
}
?>

With this, when you call the Parse method, the data in that instance can be modified.  I'm not sure if xml_set_object becomes unneccissary when using the array callbacks, but I leave it in just to make sure that the xml_parse function knows it's in the object.

As above, I'd recommend for memory sake, that the XML parser be created, used, and freed all in the same function, to ensure that everything is cleaned up correctly.
bettmenn at gmx dot de 16-Oct-2004 02:03
Adding to 'lmfe at mega dot ist dot utl dot pt' contribution below, I have to say that this behaviour is very usual for PHP if MemberVars of an Object arent initialized from the constructor.
What worked best for me so far was something like this:
<?php
class foo {
  var $bar
  // the constructor
  function foo() {
    unset($this->bar);  // with every instanciation, the variable is cleared for the object
  }
}
?>
lmfe at mega dot ist dot utl dot pt 29-Sep-2004 10:51
Using PHP 4.3.0, I got this strange behaviour:

<?php
class xml  {

     /* (as specified in the documentation above) */

} // end of class xml

/* This code works */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");

/* This code works */
$xml_parser2 = new xml();
$xml_parser2->parse("<A ID='hallo2'>PHP2</A>");

/* This code DON'T work */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo3'>PHP3</A>");
?>

In the third block of code, php complains it can't find the handlers it needs.
It seems this problem only happens if the variable is used more than once.
Calling xml_parser_free doesn't help
hwheinzen at t-online dot de 14-Aug-2004 03:38
(Adding to zitan's note)
It seems easy enough to provide output functions for callback handler classes too.

Example:

<?php
class CallBack {
    var $name = 'Callback';
    var $info = 'Information!';
    function toString() {
        return $this->name.': '.$this->info;
    }
}
class Main {
    var $name = 'Main';
    var $callBackObject;
    function setCallBack(&$cBIn) { $this->callBackObject = $cBIn; }
    function toString() {
        return $this->name.': '.$this->callBackObject->toString();
    }
}

$cb = & new CallBack;
$m = & new Main;
$m->setCallBack(&$cb);
echo $cb->toString();
echo $m->toString();
?>

So, after collecting information during the parse operation within the callback handler class, e.g. in tag_close(), retrieving them is possible.
zitan at mediasculpt dot net 01-Sep-2003 09:05
Just a note about creating abstract "call back handlers" as mentioned in some of the other notes.  In this case I recommend extending the base XML class and overwritting the handler methods.  The reason I wanted to do this, is that if you have a separate callback method class it causes problems, for example if you want to collect information out of the XML file and store it in an array.  You can get around it with global variables, but I prefer to use them only when required ;)

Example:

<?php
class xml_output extends xml{

  var $output = array();

   function xml_output(){
    $this->xml();
   }

    //overwrite base methods
    function tag_open($parser, $tag, $attributes)
    {
        array_push($this->output, "<$tag, attributes>");
    }

    function cdata($parser, $cdata)
    {
         array_push($this->output, "$cdata");
    }

    function tag_close($parser, $tag)
    {
         array_push($this->output, "</$tag>");
    }

}

$xml_parser = & new xml_output();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
echo("$xml_parser->output");
?>
sbeam at syxyz dot net 12-Nov-2002 09:34
passing the object as a call-time ref (&$this) as in the example will create a warning in php 4.1+. Pass xml_set_object($xp,$this); instead. This does not seem to break anything - but I dont know for sure.
chiefgeek at ecodedesign.com 04-Aug-2002 10:37
Just adding a little note about my above written example.  It needs some improvements.

Because PHP passes by VALUE by default, when you pass an array like this:
array($callback_handler, 'handler_method')
PHP makes a copy of the callback_handler object and uses the handler_method in the copy.

This is not an ideal situation for many reasons...which I will not get into here...but you should have an idea by now.

The best way to fix this is to change a few things. In the function declaration change the parameter from $callback_handler to &$callback_handler. So now your declaration should look like this

function set_callback_handler(&$callback_handler)
{
  ...
}

Now each time you reference $callback_handler change it to &$callback_handler.  For example:

xml_set_element_handler(
          $this->xml_parser,
          array(&$callback_handler, 'start_element'),
          array(&$callback_handler, 'close_Element' ));

This ensures that PHP will always use the same object.
chiefgeek at ecodedesign.com 03-Aug-2002 08:25
xml_set_object is great, if you want to hard code your start_element, end_element, etc functions within your xml class.

But what if you want to increase the modularity of your application?

Solution, create one generic XMLParser class that handles everything *except* the callback funtions.  Then create an abstract XMLCallbackHandler class which you can extend to provide any customization you want.

So how do you tell the php's xml_parser that you want to use this other class to handle the callback functions.

xml_set_object?  This only works if the functions are *within* the object you called this method from.

The solution lies in the xml_set_element_handler() function.
Take a look at this sample source...

class XMLParser
{

  ...

  function set_callback_handler($callback_handler)
  {
    // Assign the startElement endElement functions
    xml_set_element_handler(
          $this->xml_parser,
          array($callback_handler, 'start_element'),
          array($callback_handler, 'close_Element' ));

    /* By passing an array with this ($object, 'function_name') structure
       to the 2nd and 3rd parameters.  We are able to tell the parser to
       look in another object for these callback functions.
    */

    // Assign the character data function
    xml_set_character_data_handler(
          $this->xml_parser,
          array($callback_handler, 'character_data'));
    }
}

class myCallBackHandler
{
  function start_element(...)
  {
    //code goes here
  }

  function end_element(...)
  {
    //code goes here
  }

  function character_data(...)
  {
    //code goes here
  }
}

Now all thats left to do is use these classes..

$parser = new XMLParser();
$parser->set_callback_handler(new myCallbackHandler());
dfoesch at cs dot nmsu dot edu 12-Apr-2002 05:38
English explaination of why you do: $xml = & new xml();

Ok, when PHP executes "new xml()" it creates an anonymous variable (one that you can't reference with any name) which it then runs the constructor function on.  Ok, now once that's done, it then assigns by VALUE in the example above.  This means that that lovely pointer to your parser is pointing to the anonymous instance of your class, and not the used instance of your class... thus making a "shadow" of all your variables, where assignments inside the parser access different variables than outside the parser.  What PHP _SHOULD_ be doing (similar to C++) is have this statement execute such that the assignment is done by REFERENCE, so that you assign the new name to the class that actually got constructed, and not just a copy of the class that you constructed.

If they did it right, this code wouldn't be broken.
14-Feb-2002 11:10
Call-time pass-by-reference has been deprecated, so the example is buggy as was already mentionned. However since 4.04 (I think) "new" can return objects by reference. So the clean way to have both the parser initialised in the constructor, and to save the result in your object is to do

$xml_parser = & new xml();

see http://www.php.net/manual/en/language.oop.newref.php

Ivan
pete dot nelson at serverSXPYAZMsolved dot com 27-Aug-2001 10:15
<p>in reply to jon9mm's question, I have found the same problem (function 'startElement' does not exist).  I finally found the way around this, by re-reading this doc for xml_set_object.  You HAVE to use the xml_set_object($this->parser, &$this) within your parser function.</p> <p>When that function is called, your object temporarily becomes the parser object and shares scope (so it can see 'startElement', etc).   Once that function is done, the xml_set_object(...) call goes out of scope, and your object is no longer bound to the parser.  So the simplist solution is to call xml_set_object(...), do any parsing, and then call xml_parser_free(...) all within the same function.</p>
<p>And remember, don't call xml_set_object(...) in your object's constructor - your object will be forever bound to the parser object and you'll loose all access to your object's member functions.</p>
<p>This is all explained in the examples above, but it took me reading it a couple of times to grok how it all works.</p>
nick at category4 dot com 14-May-2001 01:45
If you're using the XML parser within an object, be careful not to accidentally call any methods that don't exist within the object. Instead of complaining that the missing method doesn't exist, PHP will say it's not able to find the handler routines, even if you've indicated them correctly. (PHP version 4.0.5 on FreeBSD).
williams at cse dot unl dot edu 06-Dec-2000 12:42
If xml_set_object is not called in the constructor of an object, the values that the parser modifies will be saved. Else, the values do not seem to be saved as stated by "i_sofer" above.
--- Start Example Code ---
class foo {
var xmlparser;
function foo() { \\the constructor
$this->xmlparser=xmlparser_create();
}
function parse() {
xml_set_object($this->xmlparser,&$this);
\\also include data handler
\\and element handlers here
}
}
--- End Example Code ---
i_sofer at yahoo dot com 18-Nov-2000 04:15
Using xml parser in objects seem to have a problem that values modified(even of the object itself) get lost as soon as parsing ends...
malcontent at msgto dot com 20-Aug-2000 12:11
The example will generate a warning unless allow_call_time_pass_reference is set to true in your INI file. It also will not accept a call by value.
robert at webmotion dot com 18-Apr-2000 10:58
While true that there is no automatic destructor for PHP class objects, it is quite simple to create a method called destroy and perform the destruction manually. In the example above it may not be necessary to free the xml parser immediately... it would appear from the example that the object is re-useable.
xml_set_notation_decl_handler
xml_set_processing_instruction_handler
Функции парсера XML


Установка обработчика инструкций препроцессора (PI)

xml_set_object
xml_set_start_namespace_decl_handler
Функции парсера XML
PHP Manual

xml_set_processing_instruction_handler

(PHP 4, PHP 5)

xml_set_processing_instruction_handler — Установка обработчика инструкций препроцессора (PI)

Описание

bool xml_set_processing_instruction_handler ( resource $parser , callable $handler )

Задает обработчик инструкций препроцессора (PI) для XML анализатора. parser.

Инструкции имеют следующий формат:

<?
target data
?>
Можно вставлять PHP код в тело тэга, но есть одно ограничение: завершающий тэг инструкций (?>) нельзя заключать в кавычки, таким образом эта последовательность символов не должна встречаться в PHP коде, который вы вставляете посредством PI в XML документы. Если это произойдет, остаток PHP кода будет воспринят как простые символьные данные.

Список параметров

parser

Ссылка на XML анализатор, для которого устанавливается обработчик.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать три аргумента:

handler ( resource $parser , string $target , string $data )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
target
Второй аргумент target содержит цель применения PI.
data
Третий аргумент data содержит PI данные.

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
xml_set_object
xml_set_start_namespace_decl_handler
Функции парсера XML


Установка обработчика входа в пределы пространства имен

xml_set_processing_instruction_handler
xml_set_unparsed_entity_decl_handler
Функции парсера XML
PHP Manual

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_start_namespace_decl_handler — Установка обработчика входа в пределы пространства имен

Описание

bool xml_set_start_namespace_decl_handler ( resource $parser , callable $handler )

Задает обработчик события входа в пространство имен. То есть обработчик вызывается анализатор находит объявление пространства имен. Подобные объявления находятся в открывающих тэгах элементов. Этот обработчик вызывается до обработчика начала тэга.

Список параметров

parser

Ссылка на XML анализатор.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать три аргумента и возвращать целочисленный результат. Если обработчик вернет FALSE (равно как и ничего не вернет), XML анализатор прекратит работу, а функция xml_get_error_code() будет возвращать константу XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix , string $uri )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
prefix
Префикс - строка, используемая как ссылка на пространство имен в пределах XML объекта.
uri
Универсальный идентификатор ресурса (URI) пространства имен.

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • xml_set_end_namespace_decl_handler() - Установка обработчика выхода за пределы пространства имен

User Contributed Notes

There are no user contributed notes for this page.
xml_set_processing_instruction_handler
xml_set_unparsed_entity_decl_handler
Функции парсера XML


Установка обработчика неразобранных объявлений сущностей

xml_set_start_namespace_decl_handler
XMLReader
Функции парсера XML
PHP Manual

xml_set_unparsed_entity_decl_handler

(PHP 4, PHP 5)

xml_set_unparsed_entity_decl_handler — Установка обработчика неразобранных объявлений сущностей

Описание

bool xml_set_unparsed_entity_decl_handler ( resource $parser , callable $handler )

Задает функцию обработчик неразобранных объявлений сущностей для XML анализатора parser.

Обработчик handler будет вызван, если XML анализатор обнаружит NDATA объявление внешней сущности вида:

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

См. » раздел 4.2.2 XML 1.0 спецификации, чтобы получить точное определение обозначений внешних сущностей.

Список параметров

parser

Ссылка на XML анализатор для которого задается обработчик.

handler

handler - строка содержащая имя функции, которая должна быть определена на момент вызова функции xml_parse() из анализатора parser.

Функция с именем handler должна принимать шесть аргументов:

handler ( resource $parser , string $entity_name , string $base , string $system_id , string $public_id , string $notation_name )
parser
Первый аргумент parser является ссылкой на XML анализатор вызывающий обработчик.
entity_name
Имя сущности, которой требуется дать определение.
base
Это основа для разрешения системного идентификатора (system_id) внешней сущности. На данный момент в качестве этого аргумента всегда передается пустая строка.
system_id
Системный идентификатор внешней сущности.
public_id
Общедоступный идентификатор внешней сущности.
notation_name
Имя обозначения этой сущности (см. xml_set_notation_decl_handler()).

Если в качестве обработчика передана пустая строка или FALSE, этот обработчик отключается.

Замечание: В качестве аргумента вместо имени функции может быть передан массив, содержащий ссылку на объект и имя метода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
xml_set_start_namespace_decl_handler
XMLReader
Функции парсера XML


XMLReader

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • XMLReader — Класс XMLReader
    • XMLReader::close — Закрыть ввод XMLReader
    • XMLReader::expand — Возвратить копию текущего узла в виде объекта DOM
    • XMLReader::getAttribute — Получить значение атрибута с определённым именем
    • XMLReader::getAttributeNo — Получить значение атрибута по индексу
    • XMLReader::getAttributeNs — Получить значение атрибута по localname и URI
    • XMLReader::getParserProperty — Указывает, было ли определенное свойство установлено
    • XMLReader::isValid — Показать, является ли разбираемый документ синтаксически правильным
    • XMLReader::lookupNamespace — Найти пространство имён для префикса
    • XMLReader::moveToAttribute — Переместить курсор к атрибуту с заданным именем
    • XMLReader::moveToAttributeNo — Переместить курсор на атрибут по индексу
    • XMLReader::moveToAttributeNs — Переместить курсор к именованному атрибуту
    • XMLReader::moveToElement — Позиционировать курсор на родительском элементе текущего атрибута
    • XMLReader::moveToFirstAttribute — Переместить позицию курсора на первый атрибут
    • XMLReader::moveToNextAttribute — Переместить позицию курсора на следующий атрибут
    • XMLReader::next — Переместить курсор на следующий узел, пропуская все поддеревья
    • XMLReader::open — Установить URI, содержащий XML-документ для разобора
    • XMLReader::read — Переместиться к следующему узлу в документе
    • XMLReader::readInnerXML — Извлечь XML из текущего узла
    • XMLReader::readOuterXML — Получить XML из текущего узла, включая сам узел
    • XMLReader::readString — Прочитать содержимое текущего узла как строку
    • XMLReader::setParserProperty — Устанавливает опцию парсера
    • XMLReader::setRelaxNGSchema — Устанавить имя файла или URI для схемы RelaxNG
    • XMLReader::setRelaxNGSchemaSource — Устанавливает данные, содержащие схему RelaxNG
    • XMLReader::setSchema — Проверить документ, используя XSD
    • XMLReader::XML — Установить данные, содержащие XML для разбора

User Contributed Notes

kraussInode at yahoo dot com 27-Mar-2010 12:54
See also XMLWriter: XMLReader and XMLWriter complement each other.
xml_set_unparsed_entity_decl_handler
Введение
Обработка XML


Введение

Расширение XMLReader - синтаксический анализатор XML. Класс-читатель выступает в качестве курсора, следует по потоку документа и останавливается на каждом узле на этом пути.

Кодировка

Важно отметить, что библиотека libxml внутри использует кодировку UTF-8 и, таким образом, кодировка извлекаемого содержимого всегда будет в кодировке UTF-8.

User Contributed Notes

There are no user contributed notes for this page.
XMLReader
Установка и настройка
XMLReader


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
XMLReader


Установка

Расширение XMLReader доступно в PECL с версии PHP 5.0.0 и начиная с PHP 5.1.0 доступно по умолчанию. Оно может быть включено добавлением опции --enable-xmlreader (или --with-xmlreader до 5.1.0) к конфигурационной строке.

Это расширение включено по умолчанию. Оно может быть отключено во время выполнения с помощью следующей опции: --disable-xmlreader

User Contributed Notes

s dot coletta at unidata dot it 27-May-2009 09:43
When you type:

pecl install XMLReader

and installation fails with this error:

Fatal error: Call to undefined function preg_match() in /usr/share/pear/PEAR/Frontend/CLI.php on line 57

You can temporarily fix it by removing the -n flag from the pecl script.

By removing the -n flag it will use your php.ini.
alvaro at digdib dot com 02-Jan-2009 02:33
Gentoo users: emerge does not compile dev-lang/php with --enable-xmlreader by default. To enable this option, add the flag xmlreader to your USE variable and recompile php.
Требования
Настройка во время выполнения
Установка и настройка


Типы ресурсов

Данное расширение не определяет никакие типы ресурсов.

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
XMLReader
Установка и настройка


Класс XMLReader

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Расширение XMLReader - синтаксический анализатор XML. Класс-читатель выступает в качестве курсора, следует по потоку документа и останавливается на каждом узле на этом пути.

Обзор классов

XMLReader {
/* Константы */
const int NONE = 0 ;
const int ELEMENT = 1 ;
const int ATTRIBUTE = 2 ;
const int TEXT = 3 ;
const int CDATA = 4 ;
const int ENTITY_REF = 5 ;
const int ENTITY = 6 ;
const int PI = 7 ;
const int COMMENT = 8 ;
const int DOC = 9 ;
const int DOC_TYPE = 10 ;
const int DOC_FRAGMENT = 11 ;
const int NOTATION = 12 ;
const int WHITESPACE = 13 ;
const int SIGNIFICANT_WHITESPACE = 14 ;
const int END_ELEMENT = 15 ;
const int END_ENTITY = 16 ;
const int XML_DECLARATION = 17 ;
const int LOADDTD = 1 ;
const int DEFAULTATTRS = 2 ;
const int VALIDATE = 3 ;
const int SUBST_ENTITIES = 4 ;
/* Свойства */
public readonly int $attributeCount ;
public readonly string $baseURI ;
public readonly int $depth ;
public readonly bool $hasAttributes ;
public readonly bool $hasValue ;
public readonly bool $isDefault ;
public readonly bool $isEmptyElement ;
public readonly string $localName ;
public readonly string $name ;
public readonly string $namespaceURI ;
public readonly int $nodeType ;
public readonly string $prefix ;
public readonly string $value ;
public readonly string $xmlLang ;
/* Методы */
bool close ( void )
DOMNode expand ([ DOMNode $basenode ] )
string getAttribute ( string $name )
string getAttributeNo ( int $index )
string getAttributeNs ( string $localName , string $namespaceURI )
bool getParserProperty ( int $property )
bool isValid ( void )
bool lookupNamespace ( string $prefix )
bool moveToAttribute ( string $name )
bool moveToAttributeNo ( int $index )
bool moveToAttributeNs ( string $localName , string $namespaceURI )
bool moveToElement ( void )
bool moveToFirstAttribute ( void )
bool moveToNextAttribute ( void )
bool next ([ string $localname ] )
bool open ( string $URI [, string $encoding [, int $options = 0 ]] )
bool read ( void )
string readInnerXML ( void )
string readOuterXML ( void )
string readString ( void )
bool setParserProperty ( int $property , bool $value )
bool setRelaxNGSchema ( string $filename )
bool setRelaxNGSchemaSource ( string $source )
bool setSchema ( string $filename )
bool xml ( string $source [, string $encoding [, int $options = 0 ]] )
}

Свойства

attributeCount

Количество атрибутов в узле

baseURI

Базовый URI узла

depth

Глубина узла в дереве, начиная с 0

hasAttributes

Показывает, есть ли у узла атрибуты

hasValue

Показывает, имеет ли узел текстовое значение

isDefault

Показывает, является ли атрибутом по умолчанию из DTD

isEmptyElement

Показывает, является ли узел пустым тегом

localName

Локальное имя узла

name

Полностью определенное имя узла

namespaceURI

URI пространства имён связанный с узлом

nodeType

Тип узла

prefix

Префикс пространства имён связанный с узлом

value

Текстовое значение узла

xmlLang

Контекст xml:lang, в котором находится узел

Предопределенные константы

Типы узлов XMLReader

XMLReader::NONE

Нет типа узла

XMLReader::ELEMENT

Начальный элемент

XMLReader::ATTRIBUTE

Узел атрибута

XMLReader::TEXT

Текстовый узел

XMLReader::CDATA

Узел CDATA

XMLReader::ENTITY_REF

Узел ссылки на сущность

XMLReader::ENTITY

Узел объявления объекта

XMLReader::PI

Узел инструкций обработки

XMLReader::COMMENT

Узел комментария

XMLReader::DOC

Узел документа

XMLReader::DOC_TYPE

Узел типа документа

XMLReader::DOC_FRAGMENT

Узел фрагмента документа

XMLReader::NOTATION

Узел нотации

XMLReader::WHITESPACE

Пробельный узел

XMLReader::SIGNIFICANT_WHITESPACE

Существенный пробельный узел

XMLReader::END_ELEMENT

Завершение элемента

XMLReader::END_ENTITY

Завершение объекта

XMLReader::XML_DECLARATION

Узел XML объявления

Опции анализатора XMLReader

XMLReader::LOADDTD

Загружать DTD, но не проверять

XMLReader::DEFAULTATTRS

Загружать DTD и атрибуты по умолчанию, но не проверять

XMLReader::VALIDATE

Загружать DTD и проверять при разборе

XMLReader::SUBST_ENTITIES

Заменять объекты и разворачивать ссылки

Содержание

  • XMLReader::close — Закрыть ввод XMLReader
  • XMLReader::expand — Возвратить копию текущего узла в виде объекта DOM
  • XMLReader::getAttribute — Получить значение атрибута с определённым именем
  • XMLReader::getAttributeNo — Получить значение атрибута по индексу
  • XMLReader::getAttributeNs — Получить значение атрибута по localname и URI
  • XMLReader::getParserProperty — Указывает, было ли определенное свойство установлено
  • XMLReader::isValid — Показать, является ли разбираемый документ синтаксически правильным
  • XMLReader::lookupNamespace — Найти пространство имён для префикса
  • XMLReader::moveToAttribute — Переместить курсор к атрибуту с заданным именем
  • XMLReader::moveToAttributeNo — Переместить курсор на атрибут по индексу
  • XMLReader::moveToAttributeNs — Переместить курсор к именованному атрибуту
  • XMLReader::moveToElement — Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToFirstAttribute — Переместить позицию курсора на первый атрибут
  • XMLReader::moveToNextAttribute — Переместить позицию курсора на следующий атрибут
  • XMLReader::next — Переместить курсор на следующий узел, пропуская все поддеревья
  • XMLReader::open — Установить URI, содержащий XML-документ для разобора
  • XMLReader::read — Переместиться к следующему узлу в документе
  • XMLReader::readInnerXML — Извлечь XML из текущего узла
  • XMLReader::readOuterXML — Получить XML из текущего узла, включая сам узел
  • XMLReader::readString — Прочитать содержимое текущего узла как строку
  • XMLReader::setParserProperty — Устанавливает опцию парсера
  • XMLReader::setRelaxNGSchema — Устанавить имя файла или URI для схемы RelaxNG
  • XMLReader::setRelaxNGSchemaSource — Устанавливает данные, содержащие схему RelaxNG
  • XMLReader::setSchema — Проверить документ, используя XSD
  • XMLReader::XML — Установить данные, содержащие XML для разбора

User Contributed Notes

lee8oi at gmail dot com 21-Mar-2012 01:54
Sometimes you have an unusual URL that doesn't actually point to an xml file but still returns xml as output (Like the Battlefield Heroes generated syndication urls). Using get_file_contents(url) you can retrieve the xml data from these urls and pass it as a variable for processing as an XML String.

Unfortunately simpleXML or xml DOM cannot process all xml strings. Some have error boxes added to the end of them (such as Battlefield Heroes syndicated news). These boxes cause an end of file sort of error and closes out the script. XMLReader grabs data from these strings without error.
japos dot trash at googlemail dot com 09-Oct-2010 02:17
Take care about how to use XMLReader::$isElementEmpty. I don't know if it is a bug or not, but $isElementEmpty is set for the current context and NOT just for the element. If you move your cursor to an attribute, $isElementEmpty will ALWAYS be false.

<?php
 $xml = new XMLReader();
 $xml->XML('<tag attr="value" />');
 $xml->read();
 var_dump($xml->isEmptyElement);
 $xml->moveToNextAttribute();
 var_dump($xml->isEmptyElement);
?>

will output

(bool) true
(bool) false

So be sure to store $isEmptyElement before moving the cursor.
jart (at) mail.ru 23-Sep-2010 06:59
Guys, I hope this example will help
you can erase prints showing the process-
and it will be a piece of nice code.

<?php
function xml2assoc($xml, $name)
{
    print "<ul>";

    $tree = null;
    print("I'm inside " . $name . "<br>");

    while($xml->read())
    {
        if($xml->nodeType == XMLReader::END_ELEMENT)
        {
            print "</ul>";
            return $tree;
        }

        else if($xml->nodeType == XMLReader::ELEMENT)
        {
            $node = array();

            print("Adding " . $xml->name ."<br>");
            $node['tag'] = $xml->name;

            if($xml->hasAttributes)
            {
                $attributes = array();
                while($xml->moveToNextAttribute())
                {
                    print("Adding attr " . $xml->name ." = " . $xml->value . "<br>");
                    $attributes[$xml->name] = $xml->value;
                }
                $node['attr'] = $attributes;
            }

            if(!$xml->isEmptyElement)
            {
                $childs = xml2assoc($xml, $node['tag']);
                $node['childs'] = $childs;
            }

            print($node['tag'] . " added <br>");
            $tree[] = $node;
        }

        else if($xml->nodeType == XMLReader::TEXT)
        {
            $node = array();
            $node['text'] = $xml->value;
            $tree[] = $node;
            print "text added = " . $node['text'] . "<br>";
        }
    }

    print "returning " . count($tree) . " childs<br>";
    print "</ul>";

    return $tree;
}

echo "<PRE>";

$xml = new XMLReader();
$xml->open('test.xml');
$assoc = xml2assoc($xml, "root");
$xml->close();

print_r($assoc);
echo "</PRE>";

?>

It reads this xml:

<test>
    <hallo volume="loud"> me <br/> lala </hallo>
    <hallo> me </hallo>
</test>
jnettles at inccrra dot org 02-Oct-2009 09:51
Just in case someone is confused, if you're wanting to simply pass a string of XML instead of an entire file, you would do this.

<?php
$foo = new XMLReader();
$foo->xml($STRING);
?>

.... where $STRING holds your XML. You cannot pass it like $foo = $STRING or $foo->xml = $STRING.
james dot ellis at example dot com 25-Mar-2009 03:16
The "XML2Assoc" functions noted here should be used with caution... basically they are duplicating the functionality already present in SimpleXML. They may work but they won't scale.

Their are two main uses cases for parsing XML, each suited to either XMLReader or SimpleXML.

1. SimpleXML is an excellent tool for easy access to an XML document tree using native PHP data types. It starts to flounder with massive (> 50M or so) XML documents, as it reads the entire document into memory before it can be processed. SimpleXML will just laugh at you then die when your server runs out of memory (or it will cause a load spike).

2. Aside from the reasoning behind massive XML documents, if you have to deal with massive XML documents, use XMLReader to process them. Don't try and gather an entire XML document into a PHP data structure using XMLReader and a PHP xml2assoc() function, you are reinventing the SimpleXML wheel.
When parsing massive XML documents using XMLReader, gather the data you need to perform an operation then perform it before skipping to the next node. Do not build massive data structures from a massive XML document, your server (and it's admins) will not like you.
PxL 23-Jan-2009 03:36
A basic parser

<?php
function xml2assoc($xml) {
    $arr = array();
    if (!preg_match_all('|\<\s*?(\w+).*?\>(.*)\<\/\s*\\1.*?\>|s', $xml, $m)) return $xml;
    if (is_array($m[1]))
        for ($i = 0;$i < sizeof($m[1]); $i++) $arr[$m[1][$i]] = xml2assoc($m[2][$i]);
    else $arr[$m[1]] = xml2assoc($m[2]);

    return $arr;
}
?>
boukeversteegh at gmail dot com 18-Jan-2009 02:06
XML to ASSOCIATIVE ARRAY

Improved algorithm based on Sergey Aikinkulov's. The problem was that it would overwrite nodes if they had the same tag name. Because of that <a><b/><b/><a> would be read as if <a><b/><a/>. This algorithm handles it better and outputs an easy to understand array:

<?php
function xml2assoc($xml) {
    $tree = null;
    while($xml->read())
        switch ($xml->nodeType) {
            case XMLReader::END_ELEMENT: return $tree;
            case XMLReader::ELEMENT:
                $node = array('tag' => $xml->name, 'value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
                if($xml->hasAttributes)
                    while($xml->moveToNextAttribute())
                        $node['attributes'][$xml->name] = $xml->value;
                $tree[] = $node;
            break;
            case XMLReader::TEXT:
            case XMLReader::CDATA:
                $tree .= $xml->value;
        }
    return $tree;
}

?>

Usage:

myxml.xml:
------
<PERSON>
    <NAME>John</NAME>
    <PHONE type="home">555-555-555</PHONE>
</PERSON>
----

<?
    $xml = new XMLReader();
    $xml->open('myxml.xml');
    $assoc = xml2assoc($xml);
    $xml->close();
    print_r($assoc);
?>

Outputs:
Array
(
    [0] => Array
        (
            [tag] => PERSON
            [value] => Array
                (
                    [0] => Array
                        (
                            [tag] => NAME
                            [value] => John
                        )

                    [1] => Array
                        (
                            [tag] => PHONE
                            [value] => 555-555-555
                            [attributes] => Array
                                (
                                    [type] => home
                                )

                        )

                )

        )

)

For reasons that have to do with recursion, it returns an array with the ROOT xml node as the first childNode, rather than to return only the ROOT node.
andrei_antal at yahoo dot com 08-Jan-2009 08:25
<?php
//Pull certain elements
 $reader = new XMLReader();
  $reader->open($xmlfile);
while ($reader->read()) {
 switch ($reader->nodeType) {
   case (XMLREADER::ELEMENT):

if ($reader->name == "Code")
     {
       $reader->read();
       $code = trim($reader->value);
       echo "$code\n";
       break;
     }

 if ($reader->name == "Name")
     {
       $reader->read();
       $customername = trim( $reader->value );
       echo "$name\n";
       break;
     }

 if ($reader->name == "Camp")
    {
      $camp = trim($reader->getAttribute("ID"));
       echo "$camp\n";
      break;
    }
  }
}
?>
godseth at o2 dot pl 28-Nov-2008 02:34
Thanks rein_baarsma33 AT hotmail DOT com for bugfixes.

This is my new child of XML parsing method  based on my and yours modification.

XML2ASSOC Is a complete solution for parsing ordinary XML

<?php
/**
 * XML2Assoc Class to creating
 * PHP Assoc Array from XML File
 *
 * @author godseth (AT) o2.pl & rein_baarsma33 (AT) hotmail.com (Bugfixes in parseXml Method)
 * @uses XMLReader
 *
 */

class Xml2Assoc {

    /**
     * Optimization Enabled / Disabled
     *
     * @var bool
     */
    protected $bOptimize = false;

    /**
     * Method for loading XML Data from String
     *
     * @param string $sXml
     * @param bool $bOptimize
     */

    public function parseString( $sXml , $bOptimize = false) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {

            // Set String Containing XML data
            $oXml->XML($sXml);

            // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * Method for loading Xml Data from file
     *
     * @param string $sXmlFilePath
     * @param bool $bOptimize
     */
    public function parseFile( $sXmlFilePath , $bOptimize = false ) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {
            // Open XML file
            $oXml->open($sXmlFilePath);

            // // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage(). ' | Try open file: '.$sXmlFilePath;
        }
    }

    /**
     * XML Parser
     *
     * @param XMLReader $oXml
     * @return array
     */
    protected function parseXml( XMLReader $oXml ) {

        $aAssocXML = null;
        $iDc = -1;

        while($oXml->read()){
            switch ($oXml->nodeType) {

                case XMLReader::END_ELEMENT:

                    if ($this->bOptimize) {
                        $this->optXml($aAssocXML);
                    }
                    return $aAssocXML;

                case XMLReader::ELEMENT:

                    if(!isset($aAssocXML[$oXml->name])) {
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name] = '';
                            } else {
                                $aAssocXML[$oXml->name] = $this->parseXML($oXml);
                            }
                        }
                    } elseif (is_array($aAssocXML[$oXml->name])) {
                        if (!isset($aAssocXML[$oXml->name][0]))
                        {
                            $temp = $aAssocXML[$oXml->name];
                            foreach ($temp as $sKey=>$sValue)
                            unset($aAssocXML[$oXml->name][$sKey]);
                            $aAssocXML[$oXml->name][] = $temp;
                        }

                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    } else {
                        $mOldVar = $aAssocXML[$oXml->name];
                        $aAssocXML[$oXml->name] = array($mOldVar);
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    }

                    if($oXml->hasAttributes) {
                        $mElement =& $aAssocXML[$oXml->name][count($aAssocXML[$oXml->name]) - 1];
                        while($oXml->moveToNextAttribute()) {
                            $mElement[$oXml->name] = $oXml->value;
                        }
                    }
                    break;
                case XMLReader::TEXT:
                case XMLReader::CDATA:

                    $aAssocXML[++$iDc] = $oXml->value;

            }
        }

        return $aAssocXML;
    }

    /**
     * Method to optimize assoc tree.
     * ( Deleting 0 index when element
     *  have one attribute / value )
     *
     * @param array $mData
     */
    public function optXml(&$mData) {
        if (is_array($mData)) {
            if (isset($mData[0]) && count($mData) == 1 ) {
                $mData = $mData[0];
                if (is_array($mData)) {
                    foreach ($mData as &$aSub) {
                        $this->optXml($aSub);
                    }
                }
            } else {
                foreach ($mData as &$aSub) {
                    $this->optXml($aSub);
                }
            }
        }
    }

}

?>

[EDIT BY danbrown AT php DOT net:  Fixes were also provided by "Alex" and (qdog AT qview DOT org) in user notes on this page (since removed).]
Sergey Aikinkulov 19-Jun-2008 03:51
Next version xml2assoc with some improve fixes:
 - no doubled data
 - no buffer arrays

<?php
/*
    Read XML structure to associative array
    --
    Using:
    $xml = new XMLReader();
    $xml->open([XML file]);
    $assoc = xml2assoc($xml);
    $xml->close();
*/
    function xml2assoc($xml) {
      $assoc = null;
      while($xml->read()){
        switch ($xml->nodeType) {
          case XMLReader::END_ELEMENT: return $assoc;
          case XMLReader::ELEMENT:
            $assoc[$xml->name][] = array('value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
            if($xml->hasAttributes){
              $el =& $assoc[$xml->name][count($assoc[$xml->name]) - 1];
              while($xml->moveToNextAttribute()) $el['attributes'][$xml->name] = $xml->value;
            }
            break;
          case XMLReader::TEXT:
          case XMLReader::CDATA: $assoc .= $xml->value;
        }
      }
      return $assoc;
    }
?>
desk_ocean at msn dot com 16-Mar-2008 10:03
make some modify from Sergey Aikinkulov's note

<?php
function xml2assoc(&$xml){
    $assoc = NULL;
    $n = 0;
    while($xml->read()){
        if($xml->nodeType == XMLReader::END_ELEMENT) break;
        if($xml->nodeType == XMLReader::ELEMENT and !$xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = xml2assoc($xml);
            $n++;
        }
        else if($xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = "";
            $n++;
        }
        else if($xml->nodeType == XMLReader::TEXT) $assoc = $xml->value;
    }
    return $assoc;
}
?>

add else if($xml->isEmptyElement)
may be some xml has emptyelement
itari 15-Feb-2008 08:30
<?php
function parseXML($node,$seq,$path) {
global $oldpath;
    if (!$node->read())
      return;
    if ($node->nodeType != 15) {
      print '<br/>'.$node->depth;
      print '-'.$seq++;
      print '  '.$path.'/'.($node->nodeType==3?'text() = ':$node->name);
      print $node->value;
      if ($node->hasAttributes) {
        print ' [hasAttributes: ';
        while ($node->moveToNextAttribute()) print '@'.$node->name.' = '.$node->value.' ';
        print ']';
        }
      if ($node->nodeType == 1) {
        $oldpath=$path;
        $path.='/'.$node->name;
        }
      parseXML($node,$seq,$path);
      }
    else parseXML($node,$seq,$oldpath);
}

$source = "<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>";
$xml = new XMLReader();
$xml->XML($source);
print htmlspecialchars($source).'<br/>';
parseXML($xml,0,'');
?>

Output:

<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>

0-0 /tag1
1-1 /tag1/text() = this
1-2 /tag1/tag2 [hasAttributes: @id = 4 @name = foo ]
2-3 /tag1/text() = is
1-4 /text() = a
1-5 /tag2 [hasAttributes: @id = 5 ]
2-6 /text() = common
1-7 /text() = record
orion at ftf-hq dot dk 15-Feb-2006 04:50
Some more documentation (i.e. examples) would be nice :-)

This is how I read some mysql parameters in an xml file:

<?php
    $xml = new XMLReader();
    $xml->open("config.xml");
    $xml->setParserProperty(2,true); // This seems a little unclear to me - but it worked :)

    while ($xml->read()) {
        switch ($xml->name) {
        case "mysql_host":
            $xml->read();
            $conf["mysql_host"] = $xml->value;
            $xml->read();
            break;
        case "mysql_username":
            $xml->read();
            $conf["mysql_user"] = $xml->value;
            $xml->read();
            break;
        case "mysql_password":
            $xml->read();
            $conf["mysql_pass"] = $xml->value;
            $xml->read();
            break;
        case "mysql_database":
            $xml->read();
            $conf["mysql_db"] = $xml->value;
            $xml->read();
            break;
        }
    }

    $xml->close();
?>

The XML file used:
<?xml version='1.0'?>
<MySQL_INIT>
   <mysql_host>localhost</mysql_host>
   <mysql_database>db_database</mysql_database>
   <mysql_username>root</mysql_username>
   <mysql_password>password</mysql_password>
</MySQL_INIT>
Типы ресурсов
XMLReader::close
XMLReader


Закрыть ввод XMLReader

XMLReader
XMLReader::expand
XMLReader
PHP Manual

XMLReader::close

(PHP 5 >= 5.1.2)

XMLReader::close — Закрыть ввод XMLReader

Описание

bool XMLReader::close ( void )

Закрывает ввод, который в настоящий момент анализирует объект XMLReader.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::open() - Установить URI, содержащий XML-документ для разобора
  • XMLReader::xml() - Установить данные, содержащие XML для разбора

User Contributed Notes

There are no user contributed notes for this page.
XMLReader
XMLReader::expand
XMLReader


Возвратить копию текущего узла в виде объекта DOM

XMLReader::close
XMLReader::getAttribute
XMLReader
PHP Manual

XMLReader::expand

(PHP 5 >= 5.1.2)

XMLReader::expand — Возвратить копию текущего узла в виде объекта DOM

Описание

DOMNode XMLReader::expand ([ DOMNode $basenode ] )

Этот метод копирует текущий узел и возвращает соответствующий объект DOM.

Возвращаемые значения

Результирующий DOMNode или FALSE в случае ошибки.

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::close
XMLReader::getAttribute
XMLReader


Получить значение атрибута с определённым именем

XMLReader::expand
XMLReader::getAttributeNo
XMLReader
PHP Manual

XMLReader::getAttribute

(PHP 5 >= 5.1.2)

XMLReader::getAttribute — Получить значение атрибута с определённым именем

Описание

string XMLReader::getAttribute ( string $name )

Возвращает значение именованного атрибута или NULL, если атрибут не существует или не находится в узле элемента.

Список параметров

name

Имя атрибута.

Возвращаемые значения

Значение атрибута или NULL, если атрибут с заданным параметром name не найден или нет позиции элемента.

Список изменений

Версия | Описание
5.1.3 | Возвращает NULL, если атрибут не найден. Ранее возвращалась пустая строка.

Смотрите также

  • XMLReader::getAttributeNo() - Получить значение атрибута по индексу
  • XMLReader::getAttributeNs() - Получить значение атрибута по localname и URI

User Contributed Notes

Anonymous 16-Feb-2011 09:02
Or use XMLReader::ELEMENT and XMLReader::END_ELEMENT rather than the numbers 1 and 15.
Gabi 02-Jul-2007 08:15
might be obvious, but not to everyone ;-) ... when reading attributes from a node that has sub-nodes (and creating an output from this node), the output will be issued twice, once on the <ELEMENT> tag and once on the end tag </ELEMENT>. To avoid this, you can test on which part of the node you are using the property nodeType.
It'll be 1 for the element, 15 for the end element.
XMLReader::expand
XMLReader::getAttributeNo
XMLReader


Получить значение атрибута по индексу

XMLReader::getAttribute
XMLReader::getAttributeNs
XMLReader
PHP Manual

XMLReader::getAttributeNo

(PHP 5 >= 5.1.2)

XMLReader::getAttributeNo — Получить значение атрибута по индексу

Описание

string XMLReader::getAttributeNo ( int $index )

Возвращает значение атрибута на основании позиции или пустую строку, если атрибут не существует или не расположен на узле элемента.

Список параметров

index

Позиция атрибута.

Возвращаемые значения

Значение атрибута или пустая строка, если атрибут с заданным параметром index не существует или нет позиции элемента.

Смотрите также

  • XMLReader::getAttribute() - Получить значение атрибута с определённым именем
  • XMLReader::getAttributeNs() - Получить значение атрибута по localname и URI

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::getAttribute
XMLReader::getAttributeNs
XMLReader


Получить значение атрибута по localname и URI

XMLReader::getAttributeNo
XMLReader::getParserProperty
XMLReader
PHP Manual

XMLReader::getAttributeNs

(PHP 5 >= 5.1.2)

XMLReader::getAttributeNs — Получить значение атрибута по localname и URI

Описание

string XMLReader::getAttributeNs ( string $localName , string $namespaceURI )

Возвращает значение атрибута по имени и URI пространства имен или пустую строку, если атрибут не существует или не расположен на узле элемента.

Список параметров

localName

Локальное имя.

namespaceURI

URI пространства имён.

Возвращаемые значения

Значение атрибута или пустая строка, если атрибут с заданным localName и namespaceURI не найден или нет позиции элемента.

Смотрите также

  • XMLReader::getAttribute() - Получить значение атрибута с определённым именем
  • XMLReader::getAttributeNo() - Получить значение атрибута по индексу

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::getAttributeNo
XMLReader::getParserProperty
XMLReader


Указывает, было ли определенное свойство установлено

XMLReader::getAttributeNs
XMLReader::isValid
XMLReader
PHP Manual

XMLReader::getParserProperty

(PHP 5 >= 5.1.2)

XMLReader::getParserProperty — Указывает, было ли определенное свойство установлено

Описание

bool XMLReader::getParserProperty ( int $property )

Указывает, было ли определенное свойство установлено.

Список параметров

property

Одна из констант анализатора.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::setParserProperty() - Устанавливает опцию парсера

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::getAttributeNs
XMLReader::isValid
XMLReader


Показать, является ли разбираемый документ синтаксически правильным

XMLReader::getParserProperty
XMLReader::lookupNamespace
XMLReader
PHP Manual

XMLReader::isValid

(PHP 5 >= 5.1.2)

XMLReader::isValid — Показать, является ли разбираемый документ синтаксически правильным

Описание

bool XMLReader::isValid ( void )

Возвращает логическое значение (boolean), которое является признаком того, что разбираемый документ является синтаксически правильным.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Проверка правильности XML

<?php
$xml = XMLReader::open('test.xml');

// Вы должны использовать это
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Смотрите также

  • XMLReader::setParserProperty() - Устанавливает опцию парсера
  • XMLReader::setRelaxNGSchema() - Устанавить имя файла или URI для схемы RelaxNG
  • XMLReader::setRelaxNGSchemaSource() - Устанавливает данные, содержащие схему RelaxNG
  • XMLReader::setSchema() - Проверить документ, используя XSD

User Contributed Notes

zubin at trattonuovo dot com 20-Jan-2010 03:00
I encountered some problems to use isValid method with xml2assoc function.
I use this way to validate the entire xml file and put it into an associative array.

$xml = new XMLReader();
if (!$xml->xml($xml_string, NULL, LIBXML_DTDVALID)) {
  echo "XML not valid: load error";
  exit();
}

libxml_use_internal_errors(TRUE);

$xml_array = xml2assoc($xml);

$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
  echo "XML not valid: ".$xml_errors;
  exit();
}

//all ok
remy dot damour at laposte dot net 31-Dec-2008 03:27
1. If you validate against relax-ng, no need to call $xml->setParserProperty(XMLReader::VALIDATE, true);

2. Be aware that $xml->isValid() will return validity for currently active node (ie. node currently positioned using $xml->read()). It won't check validity of your entire tree at once, but rather on a step by step basis
anzenews at volja dot net 22-Jan-2008 10:50
This comment is only partially correct:
"isValid() always returns false unless you enable checking for validity by $reader->setParserProperty(XMLReader::VALIDATE, true);"
This enables DTD checking, but you can also check by using RelaxNG (see setRelaxNGSchema() and setRelaxNGSchemaSource()).

And also, this is NOT correct:
"If you just need to check if XML file is well formed, successful loading into XMLReader object is usually enough."
It is not enough. Pull parsers operate on stream and if you have a large enough file they will not know it is well formed until it is read to the end. If you need to know if it is well formed or/and valid, read it till the end or validation error (you can use next() for fast reading if you don't care about contents).
patryk dot szczyglowski at gmail dot com 21-Dec-2007 06:10
isValid() always returns false unless you enable checking for validity by:

$reader->setParserProperty(XMLReader::VALIDATE, true);
where $reader is XMLReader object.

Beware, once you enable this check, PHP will search for DTD file and possibly produce warnings.

If you just need to check if XML file is well formed, successful loading into XMLReader object is usually enough.
XMLReader::getParserProperty
XMLReader::lookupNamespace
XMLReader


Найти пространство имён для префикса

XMLReader::isValid
XMLReader::moveToAttribute
XMLReader
PHP Manual

XMLReader::lookupNamespace

(PHP 5 >= 5.1.2)

XMLReader::lookupNamespace — Найти пространство имён для префикса

Описание

bool XMLReader::lookupNamespace ( string $prefix )

Поиск в контексте пространства имен для данного префикса.

Список параметров

prefix

Строка, содержащая префикс.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::isValid
XMLReader::moveToAttribute
XMLReader


Переместить курсор к атрибуту с заданным именем

XMLReader::lookupNamespace
XMLReader::moveToAttributeNo
XMLReader
PHP Manual

XMLReader::moveToAttribute

(PHP 5 >= 5.1.2)

XMLReader::moveToAttribute — Переместить курсор к атрибуту с заданным именем

Описание

bool XMLReader::moveToAttribute ( string $name )

Позиционирует курсор на атрибуте с заданным именем.

Список параметров

name

Имя атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::moveToElement() - Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToAttributeNo() - Переместить курсор на атрибут по индексу
  • XMLReader::moveToAttributeNs() - Переместить курсор к именованному атрибуту
  • XMLReader::moveToFirstAttribute() - Переместить позицию курсора на первый атрибут

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::lookupNamespace
XMLReader::moveToAttributeNo
XMLReader


Переместить курсор на атрибут по индексу

XMLReader::moveToAttribute
XMLReader::moveToAttributeNs
XMLReader
PHP Manual

XMLReader::moveToAttributeNo

(PHP 5 >= 5.1.2)

XMLReader::moveToAttributeNo — Переместить курсор на атрибут по индексу

Описание

bool XMLReader::moveToAttributeNo ( int $index )

Устанавливает курсор на атрибуте, основываясь на его позиции.

Список параметров

index

Позиция атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::moveToElement() - Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToAttribute() - Переместить курсор к атрибуту с заданным именем
  • XMLReader::moveToAttributeNs() - Переместить курсор к именованному атрибуту
  • XMLReader::moveToFirstAttribute() - Переместить позицию курсора на первый атрибут

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::moveToAttribute
XMLReader::moveToAttributeNs
XMLReader


Переместить курсор к именованному атрибуту

XMLReader::moveToAttributeNo
XMLReader::moveToElement
XMLReader
PHP Manual

XMLReader::moveToAttributeNs

(PHP 5 >= 5.1.2)

XMLReader::moveToAttributeNs — Переместить курсор к именованному атрибуту

Описание

bool XMLReader::moveToAttributeNs ( string $localName , string $namespaceURI )

Позиционирует курсор на именованном атрибуте в указанном пространстве имен.

Список параметров

localName

Локальное имя.

namespaceURI

URI пространства имён.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::moveToElement() - Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToAttribute() - Переместить курсор к атрибуту с заданным именем
  • XMLReader::moveToAttributeNo() - Переместить курсор на атрибут по индексу
  • XMLReader::moveToFirstAttribute() - Переместить позицию курсора на первый атрибут

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::moveToAttributeNo
XMLReader::moveToElement
XMLReader


Позиционировать курсор на родительском элементе текущего атрибута

XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute
XMLReader
PHP Manual

XMLReader::moveToElement

(PHP 5 >= 5.1.2)

XMLReader::moveToElement — Позиционировать курсор на родительском элементе текущего атрибута

Описание

bool XMLReader::moveToElement ( void )

Перемещает курсор на родительский элемент текущего атрибута.

Возвращаемые значения

Возвращает TRUE в случае успеха и FALSE в случае неудачи или если невозможно выполнить позиционирование курсора на атрибуте, когда этот метод вызывается.

Смотрите также

  • XMLReader::moveToAttribute() - Переместить курсор к атрибуту с заданным именем
  • XMLReader::moveToAttributeNo() - Переместить курсор на атрибут по индексу
  • XMLReader::moveToAttributeNs() - Переместить курсор к именованному атрибуту
  • XMLReader::moveToFirstAttribute() - Переместить позицию курсора на первый атрибут

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute
XMLReader


Переместить позицию курсора на первый атрибут

XMLReader::moveToElement
XMLReader::moveToNextAttribute
XMLReader
PHP Manual

XMLReader::moveToFirstAttribute

(PHP 5 >= 5.1.2)

XMLReader::moveToFirstAttribute — Переместить позицию курсора на первый атрибут

Описание

bool XMLReader::moveToFirstAttribute ( void )

Перемещает позицию курсора на первый атрибут.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::moveToElement() - Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToAttribute() - Переместить курсор к атрибуту с заданным именем
  • XMLReader::moveToAttributeNo() - Переместить курсор на атрибут по индексу
  • XMLReader::moveToAttributeNs() - Переместить курсор к именованному атрибуту
  • XMLReader::moveToNextAttribute() - Переместить позицию курсора на следующий атрибут

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::moveToElement
XMLReader::moveToNextAttribute
XMLReader


Переместить позицию курсора на следующий атрибут

XMLReader::moveToFirstAttribute
XMLReader::next
XMLReader
PHP Manual

XMLReader::moveToNextAttribute

(PHP 5 >= 5.1.2)

XMLReader::moveToNextAttribute — Переместить позицию курсора на следующий атрибут

Описание

bool XMLReader::moveToNextAttribute ( void )

Перемещает курсора к следующему атрибуту, если курсор спозиционирован на атрибуте или перемещает позицию на первый атрибут, если спозиционирован на элементе.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::moveToElement() - Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToAttribute() - Переместить курсор к атрибуту с заданным именем
  • XMLReader::moveToAttributeNo() - Переместить курсор на атрибут по индексу
  • XMLReader::moveToAttributeNs() - Переместить курсор к именованному атрибуту
  • XMLReader::moveToFirstAttribute() - Переместить позицию курсора на первый атрибут

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::moveToFirstAttribute
XMLReader::next
XMLReader


Переместить курсор на следующий узел, пропуская все поддеревья

XMLReader::moveToNextAttribute
XMLReader::open
XMLReader
PHP Manual

XMLReader::next

(PHP 5 >= 5.1.2)

XMLReader::next — Переместить курсор на следующий узел, пропуская все поддеревья

Описание

bool XMLReader::next ([ string $localname ] )

Позиционирует курсор на следующем узле, пропуская все поддеревья.

Список параметров

localname

Имя следующего узла для перехода.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::moveToNextAttribute() - Переместить позицию курсора на следующий атрибут
  • XMLReader::moveToElement() - Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToAttribute() - Переместить курсор к атрибуту с заданным именем

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::moveToNextAttribute
XMLReader::open
XMLReader


Установить URI, содержащий XML-документ для разобора

XMLReader::next
XMLReader::read
XMLReader
PHP Manual

XMLReader::open

(PHP 5 >= 5.1.2)

XMLReader::open — Установить URI, содержащий XML-документ для разобора

Описание

bool XMLReader::open ( string $URI [, string $encoding [, int $options = 0 ]] )

Установить URI, содержащий XML-документ, который будет разобран.

Список параметров

URI

URI, указывающий на документ.

encoding

Кодировка документа или NULL.

options

Битовая маска, состоящая из LIBXML_* констант.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. при статическом вызове, возвращается XMLReader или FALSE в случае возникновения ошибки.

Ошибки

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Список изменений

Версия | Описание
5.2.0 | Были добавлены параметры encoding и options.

Смотрите также

  • XMLReader::xml() - Установить данные, содержащие XML для разбора
  • XMLReader::close() - Закрыть ввод XMLReader

User Contributed Notes

crungmungus at gmail dot com 15-Sep-2008 05:11
Windows users remember to enable php_openssl.dll in your php.ini if you want to be able to use this function (and others) with a HTTPS URL.
XMLReader::next
XMLReader::read
XMLReader


Переместиться к следующему узлу в документе

XMLReader::open
XMLReader::readInnerXML
XMLReader
PHP Manual

XMLReader::read

(PHP 5 >= 5.1.2)

XMLReader::read — Переместиться к следующему узлу в документе

Описание

bool XMLReader::read ( void )

Перемещает курсор к следующему узлу в документе.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::moveToElement() - Позиционировать курсор на родительском элементе текущего атрибута
  • XMLReader::moveToAttribute() - Переместить курсор к атрибуту с заданным именем
  • XMLReader::next() - Переместить курсор на следующий узел, пропуская все поддеревья

User Contributed Notes

Nate 27-Jun-2011 10:49
It is interesting to note that this function will stop on closing tags as well.  I have an XML document similar to the following:

<root>
  <columns>
    <column>columnX</column>
    <column>columnY</column>
  </columns>
  <table>
    <row>
      <columnX>38</columnX>
      <columnY>50</columnY>
    </row>
    <row>
      <columnX>82</columnY>
      <columnY>28</columnY>
    </row>
    ...
  </table>
</root>

I need to parse the <columns> object to know what attributes to check for from each <row> node.  Therefore I was doing the following:

<?php
while ($xml->read()) {
  if ($xml->name === 'column') {
   //parse column node to into $columns array
  }
  elseif ($xml->name === 'row') {
    //parse row node, using constructed $columns array
  }
}
?>

This kind of worked in that I ended up with an array of all the data I wanted, but the array I constructed was twice as large as I expected and every other entry was empty.  Took me a while to debug, but finally figured out that checking <?php $xml->name === 'row' ?> matches both <row> and </row>, so the check should really be something more like:

<?php

if ($xml->name === 'row' && $xml->nodeType == XMLReader::ELEMENT) {
  // parse row node
}

?>

I would have liked to use the next() function instead, but as I needed to parse 2 different subtrees, I couldn't figure out how to find all the columns, reset the pointer, and then find all the rows.
andy at siliconrockstar dot com 16-May-2011 01:01
A very simple way to avoid typing $reader->read() multiple times when you want to skip some nodes:

<?php
class smartXMLReader extends XMLReader {
    public function readTimes($count) {
        $i = 0;
        while($i < $count){
            $this->read();
            $i++;
        }
    }
}
?>

Using this smartXMLReader,

<?php
$reader->readTimes(3);
?>

is equivalent to

<?php
$reader->read();
$reader->read();
$reader->read();
?>

Makes getting around in your XML document a bit easier :)
caddozzone at gmail dot com 01-Feb-2011 01:58
This class XMLReader2 is dangerous: charge all XML in memory, it can cause an out of memory error. It's the same that SimpleXML does.
Please take care.
Yannik 10-Nov-2009 03:38
If you have trouble parsing xml documents with text tags bigger than 10MB, this might help you:

<?php
$xmlreader = new XMLReader();
$xmlreader->open($uri, null, 1<<19);
?>

Since in libxml there is a constant
XML_PARSE_HUGE = 1<<19
which enables parsing xml documents with huge texts.

Please note that this option is not accessible using the setParserProperty method and that there is currently no constant to do the work, which will hopefully change soon:

http://bugs.php.net/bug.php?id=49660
jirka at kosek dot cz 08-Feb-2006 01:01
libxml2 contains much more useful method readString() that will read and return whole text content of element. You can call it after receiving start tag (XMLReader::ELEMENT). You can use this PHP code to emulate this method until PHP will directly call underlying libxml2 implementation.

<?php
class XMLReader2 extends XMLReader
{
  function readString()
  {
        $depth = 1;
        $text = "";

        while ($this->read() && $depth != 0)
        {
            if (in_array($this->nodeType, array(XMLReader::TEXT, XMLReader::CDATA, XMLReader::WHITESPACE, XMLReader::SIGNIFICANT_WHITESPACE)))
                $text .= $this->value;
            if ($this->nodeType == XMLReader::ELEMENT) $depth++;
            if ($this->nodeType == XMLReader::END_ELEMENT) $depth--;
        }
        return $text;
    }
}
?>

Just use XMLReader2 instead of XMLReader.
XMLReader::open
XMLReader::readInnerXML
XMLReader


Извлечь XML из текущего узла

XMLReader::read
XMLReader::readOuterXML
XMLReader
PHP Manual

XMLReader::readInnerXML

(PHP 5 >= 5.2.0)

XMLReader::readInnerXML — Извлечь XML из текущего узла

Описание

string XMLReader::readInnerXML ( void )

Читает содержимое текущего узла, включая дочерние узлы и разметку.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает содержимое текущего узла в виде строки. Пустая строка возвращается в случае ошибки.

Примечания

Предостережение

Эта функция доступна только если PHP скомпилирован с поддержкой libxml 20620 или старше.

Смотрите также

  • XMLReader::readString() - Прочитать содержимое текущего узла как строку
  • XMLReader::readOuterXML() - Получить XML из текущего узла, включая сам узел
  • XMLReader::expand() - Возвратить копию текущего узла в виде объекта DOM

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::read
XMLReader::readOuterXML
XMLReader


Получить XML из текущего узла, включая сам узел

XMLReader::readInnerXML
XMLReader::readString
XMLReader
PHP Manual

XMLReader::readOuterXML

(PHP 5 >= 5.2.0)

XMLReader::readOuterXML — Получить XML из текущего узла, включая сам узел

Описание

string XMLReader::readOuterXML ( void )

Читает содержимое текущего узла, включая сам узел.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает содержимое текущего узла, включая сам узел как строку. В случае ошибки строка будет пустой.

Примечания

Предостережение

Эта функция доступна только если PHP скомпилирован с поддержкой libxml 20620 или старше.

Смотрите также

  • XMLReader::readString() - Прочитать содержимое текущего узла как строку
  • XMLReader::readInnerXML() - Извлечь XML из текущего узла
  • XMLReader::expand() - Возвратить копию текущего узла в виде объекта DOM

User Contributed Notes

simon at avalon dot net dot nz 16-Mar-2011 04:35
Be aware that when you extract a piece of XML from a larger XML document using the readOuterXML() function, it tries to determine the namespaces (as defined in the original XML document) that apply to the new piece, and inserts them into the appropriate tags as xmlns attributes. This can be disconcerting, but it should be a benign alteration in most cases, and I understand that it causes the new chunk of XML to be correctly formatted so it is valid in it's own right.

As far as I'm aware it's not possible to change this behaviour.
XMLReader::readInnerXML
XMLReader::readString
XMLReader


Прочитать содержимое текущего узла как строку

XMLReader::readOuterXML
XMLReader::setParserProperty
XMLReader
PHP Manual

XMLReader::readString

(PHP 5 >= 5.2.0)

XMLReader::readString — Прочитать содержимое текущего узла как строку

Описание

string XMLReader::readString ( void )

Читает содержимое текущего узла как строку.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает содержимое текущего узла в виде строки. В случае ошибки строка будет пустой.

Примечания

Предостережение

Эта функция доступна только если PHP скомпилирован с поддержкой libxml 20620 или старше.

Смотрите также

  • XMLReader::readOuterXML() - Получить XML из текущего узла, включая сам узел
  • XMLReader::readInnerXML() - Извлечь XML из текущего узла
  • XMLReader::expand() - Возвратить копию текущего узла в виде объекта DOM

User Contributed Notes

Lea Hayes 07-Jun-2011 01:51
I would like to reiterate that this does not work when compiled with versions of libxml lower than 20620. I found that it just presents a blank page.

<?php $string = $reader->readString(); ?>

I worked around this issue by adding the following helper function:

<?php
function read_string($reader) {
    $node = $reader->expand();
    return $node->textContent;
}
?>

And then using:

<?php $string = read_string($reader); ?>
Michael Rusch 18-May-2009 10:27
For those who, like me, are having trouble figuring out the difference between getString() an getInnerXML(), the difference is that getString() does NOT include markup.  So, for:

<foo>bar<baz>Hello, world!</baz></foo>

getString() on the <foo> node would return

bar Hello, world!

whereas getInnerXML() would return

bar<baz>Hello, world!</baz>
XMLReader::readOuterXML
XMLReader::setParserProperty
XMLReader


Устанавливает опцию парсера

XMLReader::readString
XMLReader::setRelaxNGSchema
XMLReader
PHP Manual

XMLReader::setParserProperty

(PHP 5 >= 5.1.2)

XMLReader::setParserProperty — Устанавливает опцию парсера

Описание

bool XMLReader::setParserProperty ( int $property , bool $value )

Устанавливает опции для парсера. Опции должны быть установлены после вызова XMLReader::open() или XMLReader::xml() и до первого вызова XMLReader::read().

Список параметров

property

Одна из констант опций парсера.

value

Если установлено в TRUE, то опция будет включена, в противном случае опция будет выключена.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::readString
XMLReader::setRelaxNGSchema
XMLReader


Устанавить имя файла или URI для схемы RelaxNG

XMLReader::setParserProperty
XMLReader::setRelaxNGSchemaSource
XMLReader
PHP Manual

XMLReader::setRelaxNGSchema

(PHP 5 >= 5.2.0)

XMLReader::setRelaxNGSchema — Устанавить имя файла или URI для схемы RelaxNG

Описание

bool XMLReader::setRelaxNGSchema ( string $filename )

Устанавливает имя файла или URI для схемы RelaxNG, которые используются при проверке.

Список параметров

filename

Имя файла или URI, указывающий на схему RelaxNG.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::setRelaxNGSchemaSource() - Устанавливает данные, содержащие схему RelaxNG
  • XMLReader::setSchema() - Проверить документ, используя XSD
  • XMLReader::isValid() - Показать, является ли разбираемый документ синтаксически правильным

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:40
Make sure to load your data prior to calling ->setRelaxNGSchema() otherwise you will get an error.

<?php
$xml_reader = new XMLReader();
$xml_reader->setRelaxNGSchema($rng_schema);
$xml_reader->xml($xml_data);
?>
Above code generates the following warning: "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

whereas the following does not generate a warning:
<?php
$xml_reader = new XMLReader();
$xml_reader->xml($xml_data); // or $xml_reader->xml($xml_file);
$xml_reader->setRelaxNGSchema($rng_schema);
?>

cf. http://bugs.php.net/bug.php?id=46978
XMLReader::setParserProperty
XMLReader::setRelaxNGSchemaSource
XMLReader


Устанавливает данные, содержащие схему RelaxNG

XMLReader::setRelaxNGSchema
XMLReader::setSchema
XMLReader
PHP Manual

XMLReader::setRelaxNGSchemaSource

(PHP 5 >= 5.1.2)

XMLReader::setRelaxNGSchemaSource — Устанавливает данные, содержащие схему RelaxNG

Описание

bool XMLReader::setRelaxNGSchemaSource ( string $source )

Устанавливает данные, содержащие схему RelaxNG, используемую при проверке.

Список параметров

source

Строка, содержащая схему RelaxNG.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLReader::setRelaxNGSchema() - Устанавить имя файла или URI для схемы RelaxNG
  • XMLReader::setSchema() - Проверить документ, используя XSD
  • XMLReader::isValid() - Показать, является ли разбираемый документ синтаксически правильным

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:43
If you get the following warning message when calling ->setRelaxNGSchemaSource(): "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

Make sure to load data using XMLReader::open() or XMLReader::xml() prior to calling XMLReader::setRelaxNGSchemaSource().

Cf. comment on XMLReader::setRelaxNGSchema for more details.
anzenews at volja dot net 21-Jan-2008 12:18
This function and setRelaxNGSchema() seem picky about when they are called - right after the call to open(). For example:

<?php
  $schema="/path/to/schema.rng";
  $xmlfile="/path/to/xml.xml";

  $xml = new XMLReader();
  $xml->open($xmlfile);
  $xml->setRelaxNGSchemaSource(file_get_contents($schema));

  while ($xml->read()) {
   // ...
  }

  $xml->close();
?>
XMLReader::setRelaxNGSchema
XMLReader::setSchema
XMLReader


Проверить документ, используя XSD

XMLReader::setRelaxNGSchemaSource
XMLReader::XML
XMLReader
PHP Manual

XMLReader::setSchema

(PHP 5 >= 5.2.0)

XMLReader::setSchema — Проверить документ, используя XSD

Описание

bool XMLReader::setSchema ( string $filename )

Использует схему W3C XSD для проверки документов в процессе работы. Активация возможна только до первого вызова Read().

Список параметров

filename

Имя файла XSD схемы.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Ошибки

Предупреждение E_WARNING возникает, если libxml был собран без поддержки схем, схема содержит ошибки или если функция XMLReader::read() уже была вызвана.

Примечания

Предостережение

Эта функция доступна только если PHP скомпилирован с поддержкой libxml 20620 или старше.

Смотрите также

  • XMLReader::setRelaxNGSchema() - Устанавить имя файла или URI для схемы RelaxNG
  • XMLReader::setRelaxNGSchemaSource() - Устанавливает данные, содержащие схему RelaxNG
  • XMLReader::isValid() - Показать, является ли разбираемый документ синтаксически правильным

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::setRelaxNGSchemaSource
XMLReader::XML
XMLReader


Установить данные, содержащие XML для разбора

XMLReader::setSchema
XMLWriter
XMLReader
PHP Manual

XMLReader::XML

(PHP 5 >= 5.1.2)

XMLReader::XML — Установить данные, содержащие XML для разбора

Описание

bool XMLReader::xml ( string $source [, string $encoding [, int $options = 0 ]] )

Устанавливает данные, содержащие XML для разбора.

Список параметров

source

Строка, содержащая XML для разбора.

encoding

Кодировка документа или NULL.

options

Битовая маска констант LIBXML_*.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. в случае статического вызова либо возвращается XMLReader или FALSE в случае возникновения ошибки.

Ошибки

Этот метод может быть вызван статически, но при этом будет сгенерирована ошибка уровня E_STRICT.

Список изменений

Версия | Описание
5.2.0 | Были добавлены параметры encoding и options.

Смотрите также

  • XMLReader::open() - Установить URI, содержащий XML-документ для разобора
  • XMLReader::close() - Закрыть ввод XMLReader

User Contributed Notes

There are no user contributed notes for this page.
XMLReader::setSchema
XMLWriter
XMLReader


XMLWriter

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • XMLWriter
    • XMLWriter::endAttribute — Завершить атрибут
    • XMLWriter::endCData — Завершить текущую секцию CDATA
    • XMLWriter::endComment — Завершить комментарий
    • XMLWriter::endDocument — Завершить текущий документ
    • XMLWriter::endDTDAttlist — Завершить текущий DTD
    • XMLWriter::endDTDElement — Завершить текущий элемент DTD
    • XMLWriter::endDTDEntity — Завершить текущую запись DTD
    • XMLWriter::endDTD — Завершить текущий DTD
    • XMLWriter::endElement — Завершить текущий элемент
    • XMLWriter::endPI — Завершить текущую инструкцию обработки (PI)
    • XMLWriter::flush — Сбросить текущий буфер
    • XMLWriter::fullEndElement — Завершить текущий элемент
    • XMLWriter::openMemory — Создать новый объект XMLWriter, используя память для строкового вывода
    • XMLWriter::openURI — Создать новый объект XMLWriter, используя исходный URI для вывода
    • XMLWriter::outputMemory — Возвратить текущий буфер
    • XMLWriter::setIndentString — Установить строку, используемую для отступов
    • XMLWriter::setIndent — Включить или отключить отступы
    • XMLWriter::startAttributeNS — Создать стартовый атрибут пространства имен
    • XMLWriter::startAttribute — Создать начальный атрибут
    • XMLWriter::startCData — Создать начальный тэг CDATA
    • XMLWriter::startComment — Создает стартовый комментарий
    • XMLWriter::startDocument — Создать тэг документа
    • XMLWriter::startDTDAttlist — Создает стартовый список атрибутов DTD
    • XMLWriter::startDTDElement — Создать начальный элемент DTD
    • XMLWriter::startDTDEntity — Создать начальную запись DTD
    • XMLWriter::startDTD — Создать стартовый DTD тэг
    • XMLWriter::startElementNS — Создать начальный тег элемента пространства имен
    • XMLWriter::startElement — Создать стартовый тэг элемента
    • XMLWriter::startPI — Создать начальный тэг PI
    • XMLWriter::text — Записать текст
    • XMLWriter::writeAttributeNS — Записать полный атрибут пространства имен
    • XMLWriter::writeAttribute — Записать полный атрибут
    • XMLWriter::writeCData — Записать полный тэг CDATA
    • XMLWriter::writeComment — Записать полный тэг комментария
    • XMLWriter::writeDTDAttlist — Записать полный тэг DTD AttList
    • XMLWriter::writeDTDElement — Записать полный тэг элемента DTD
    • XMLWriter::writeDTDEntity — Записать полный тэг DTD записи
    • XMLWriter::writeDTD — Записать полный тэг DTD
    • XMLWriter::writeElementNS — Записать полное пространство имен тега элемента
    • XMLWriter::writeElement — Записать полный тег элемента
    • XMLWriter::writePI — Записать инструкцию обработки (PI)
    • XMLWriter::writeRaw — Пишет необработанный XML-текст

User Contributed Notes

Alexey Zakhlestin 09-Jun-2008 03:47
important: XMLWriter expects UTF-8 data from you. It can output xml in various encodings, but input should be strictly utf-8!
XMLReader::XML
Введение
Обработка XML


Введение

XMLWriter является расширением PHP. Оно создает XmlWriter API на основе библиотеки libxml.

Это расширение представляет собой класс-писатель, который является некэшируемым, однонаправленным средством генерирования потоков или файлов, содержащих данные XML.

Это расширение может быть использовано в объектно-ориентированном либо в процедурном стилях. Каждый документированный метод описывает альтернативные процедурные вызовы.

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter
Установка и настройка
XMLWriter


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
XMLWriter


Установка

Это расширение включено по умолчанию. Оно может быть отключено во время выполнения с помощью следующей опции: --disable-xmlwriter

User Contributed Notes

alvaro at digdib dot com 02-Jan-2009 02:37
Gentoo users: emerge does not compile dev-lang/php with --enable-xmlwriter by default. To enable this option, add the flag xmlwriter to your USE variable and recompile php.
Требования
Настройка во время выполнения
Установка и настройка


Типы ресурсов

Существует один resource, используемый процедурной версией расширения XMLWriter: его возвращает xmlwriter_open_memory() или xmlwriter_open_uri().

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Данное расширение не определяет никакие константы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
XMLWriter
XMLWriter


XMLWriter
PHP Manual

XMLWriter

Содержание

  • XMLWriter::endAttribute — Завершить атрибут
  • XMLWriter::endCData — Завершить текущую секцию CDATA
  • XMLWriter::endComment — Завершить комментарий
  • XMLWriter::endDocument — Завершить текущий документ
  • XMLWriter::endDTDAttlist — Завершить текущий DTD
  • XMLWriter::endDTDElement — Завершить текущий элемент DTD
  • XMLWriter::endDTDEntity — Завершить текущую запись DTD
  • XMLWriter::endDTD — Завершить текущий DTD
  • XMLWriter::endElement — Завершить текущий элемент
  • XMLWriter::endPI — Завершить текущую инструкцию обработки (PI)
  • XMLWriter::flush — Сбросить текущий буфер
  • XMLWriter::fullEndElement — Завершить текущий элемент
  • XMLWriter::openMemory — Создать новый объект XMLWriter, используя память для строкового вывода
  • XMLWriter::openURI — Создать новый объект XMLWriter, используя исходный URI для вывода
  • XMLWriter::outputMemory — Возвратить текущий буфер
  • XMLWriter::setIndentString — Установить строку, используемую для отступов
  • XMLWriter::setIndent — Включить или отключить отступы
  • XMLWriter::startAttributeNS — Создать стартовый атрибут пространства имен
  • XMLWriter::startAttribute — Создать начальный атрибут
  • XMLWriter::startCData — Создать начальный тэг CDATA
  • XMLWriter::startComment — Создает стартовый комментарий
  • XMLWriter::startDocument — Создать тэг документа
  • XMLWriter::startDTDAttlist — Создает стартовый список атрибутов DTD
  • XMLWriter::startDTDElement — Создать начальный элемент DTD
  • XMLWriter::startDTDEntity — Создать начальную запись DTD
  • XMLWriter::startDTD — Создать стартовый DTD тэг
  • XMLWriter::startElementNS — Создать начальный тег элемента пространства имен
  • XMLWriter::startElement — Создать стартовый тэг элемента
  • XMLWriter::startPI — Создать начальный тэг PI
  • XMLWriter::text — Записать текст
  • XMLWriter::writeAttributeNS — Записать полный атрибут пространства имен
  • XMLWriter::writeAttribute — Записать полный атрибут
  • XMLWriter::writeCData — Записать полный тэг CDATA
  • XMLWriter::writeComment — Записать полный тэг комментария
  • XMLWriter::writeDTDAttlist — Записать полный тэг DTD AttList
  • XMLWriter::writeDTDElement — Записать полный тэг элемента DTD
  • XMLWriter::writeDTDEntity — Записать полный тэг DTD записи
  • XMLWriter::writeDTD — Записать полный тэг DTD
  • XMLWriter::writeElementNS — Записать полное пространство имен тега элемента
  • XMLWriter::writeElement — Записать полный тег элемента
  • XMLWriter::writePI — Записать инструкцию обработки (PI)
  • XMLWriter::writeRaw — Пишет необработанный XML-текст

User Contributed Notes

neftali dot yagua at gmail dot com 02-Jun-2011 06:43
Inspired in the XmlConstruct.

<?php
class XLIFFConstruct extends XMLWriter
{

    /**
     * Constructor.
     * @param string $prm_rootElementName A root element's name of a current xml document
     * @param string $prm_xsltFilePath Path of a XSLT file.
     * @access public
     * @param null
     */
      var $_phrase_id=1;
    public function __construct(){
        $this->openMemory();
        $this->setIndent(true);
        $this->setIndentString(' ');
        $this->startDocument('1.0', 'UTF-8');

        if($prm_xsltFilePath){
            $this->writePi('xml-stylesheet', 'type="text/xsl" href="'.$prm_xsltFilePath.'"');
        }
        $this->startElement('xliff');
        $this->writeAttribute('version', '1.0');
        $this->startElement('file');
        $this->writeAttribute('original', 'global');
        $this->writeAttribute('source-language', 'es');
        $this->writeAttribute('datatype', 'plaintext');
        $this->writeAttribute('date', date('c'));
        $this->startElement('body');
    }
    public function addPhrase($source, $target){
        $this->startElement('trans-unit');
      $this->writeAttribute('id', $this->_phrase_id++);
        $this->startElement('source');
        $this->text($source);
      $this->endElement();
        $this->startElement('target');
      $this->text($target);
      $this->endElement();
      $this->endElement();
    }
    public function getDocument(){
        $this->endElement();
        $this->endElement();
        $this->endElement();
        $this->endDocument();
        return $this->outputMemory();
    }
    public function output(){
        header('Content-type: text/xml');
        echo $this->getDocument();
    }
}
?>

Example:

<?php
$xliff = new XLIFFConstruct();
$xliff->addPhrase('source','target');
$xliff->addPhrase('add','añadir');
$xliff->addPhrase('open','abrir');
$xliff->addPhrase('change','cambiar');
$xliff->addPhrase('new','nuevo');
$xliff->addPhrase('save','guardar');

echo $xliff->getDocument();

?>
darko at uvcms dot com 22-Feb-2010 07:30
setElement in the previous example does exactly the same thing as already existing writeElement.
massimo71 19-Feb-2009 02:24
I had a feature to the XmlConstruct class by Alexandre Aprica. Now you can use nested array to generate nested xml elements.

<?php
class XmlConstruct extends XMLWriter
{

    /**
     * Constructor.
     * @param string $prm_rootElementName A root element's name of a current xml document
     * @param string $prm_xsltFilePath Path of a XSLT file.
     * @access public
     * @param null
     */
    public function __construct($prm_rootElementName, $prm_xsltFilePath=''){
        $this->openMemory();
        $this->setIndent(true);
        $this->setIndentString(' ');
        $this->startDocument('1.0', 'UTF-8');

        if($prm_xsltFilePath){
            $this->writePi('xml-stylesheet', 'type="text/xsl" href="'.$prm_xsltFilePath.'"');
        }

        $this->startElement($prm_rootElementName);
    }

    /**
     * Set an element with a text to a current xml document.
     * @access public
     * @param string $prm_elementName An element's name
     * @param string $prm_ElementText An element's text
     * @return null
     */
    public function setElement($prm_elementName, $prm_ElementText){
        $this->startElement($prm_elementName);
        $this->text($prm_ElementText);
        $this->endElement();
    }

    /**
     * Construct elements and texts from an array.
     * The array should contain an attribute's name in index part
     * and a attribute's text in value part.
     * @access public
     * @param array $prm_array Contains attributes and texts
     * @return null
     */
    public function fromArray($prm_array){
      if(is_array($prm_array)){
        foreach ($prm_array as $index => $element){
          if(is_array($element)){
            $this->startElement($index);
            $this->fromArray($element);
            $this->endElement();
          }
          else
            $this->setElement($index, $element);

        }
      }
    }

    /**
     * Return the content of a current xml document.
     * @access public
     * @param null
     * @return string Xml document
     */
    public function getDocument(){
        $this->endElement();
        $this->endDocument();
        return $this->outputMemory();
    }

    /**
     * Output the content of a current xml document.
     * @access public
     * @param null
     */
    public function output(){
        header('Content-type: text/xml');
        echo $this->getDocument();
    }

}

Example:

$contents = array(
  'page_title' => 'Generate a XHTML page from XML+XSLT files',
  'welcome_msg' => 'Simple XHTML document from XML+XSLT files!',
  'prova' => array(
    "gino" => array(
      "innergino" => "gino inner value"
    ),
    "filo" => "filodata"
  ),
);

$XmlConstruct = new XmlConstruct('root');
$XmlConstruct->fromArray($contents);
$XmlConstruct->output();
?>
Yves Sucaet 25-Jul-2007 07:10
If you want your XML-output to be seen as XML by the browser, you need to modify your header. The XmlWriter does not do this for you! Therefore, the first line of your script should be:

<?php header("Content-type: text/xml"); ?>
Alexandre Arica 16-Apr-2006 05:25
How to generate a simple XML document for a XSL-Transformation purpose.

We have 3 files:
- 'index.php' : output a XML document
- 'XmlConstruct.class.php' : allow to construct a XML document with 'xmlwriter'
- 'index.xsl' : contains a XSLT document

Contents of the file 'index.php' :

<?php
$contents = array('page_title' => 'Generate a XHTML page from XML+XSLT files',
                    'welcome_msg' => 'Simple XHTML document from XML+XSLT files!');

require('XmlConstruct.class.php');
$XmlConstruct = new XmlConstruct('rootElement', 'index.xsl');
$XmlConstruct->fromArray($contents);
$XmlConstruct->output();
?>

Contents of the file  'XmlConstruct.class.php' :

<?php

/**
 * Construct a simple XML document.
 * This class inherits from the (PHP) class 'xmlwriter'.
 * You will need at least PHP 5.1.2
 *
 * @author Alexandre Arica
 * @since  16 April 2006
 * @version 1.0 modified the 16 April 2006
 */
class XmlConstruct extends XMLWriter
{

    /**
     * Constructor.
     * @param string $prm_rootElementName A root element's name of a current xml document
     * @param string $prm_xsltFilePath Path of a XSLT file.
     * @access public
     * @param null
     */
    public function __construct($prm_rootElementName, $prm_xsltFilePath=''){
        $this->openMemory();
        $this->setIndent(true);
        $this->setIndentString(' ');
        $this->startDocument('1.0', 'UTF-8');

        if($prm_xsltFilePath){
            $this->writePi('xml-stylesheet', 'type="text/xsl" href="'.$prm_xsltFilePath.'"');
        }

        $this->startElement($prm_rootElementName);
    }

    /**
     * Set an element with a text to a current xml document.
     * @access public
     * @param string $prm_elementName An element's name
     * @param string $prm_ElementText An element's text
     * @return null
     */
    public function setElement($prm_elementName, $prm_ElementText){
        $this->startElement($prm_elementName);
        $this->text($prm_ElementText);
        $this->endElement();
    }

    /**
     * Construct elements and texts from an array.
     * The array should contain an attribute's name in index part
     * and a attribute's text in value part.
     * @access public
     * @param array $prm_array Contains attributes and texts
     * @return null
     */
    public function fromArray($prm_array){
        if(is_array($prm_array)){
            foreach ($prm_array as $index => $text){
                $this->setElement($index, $text);
            }
        }
    }

    /**
     * Return the content of a current xml document.
     * @access public
     * @param null
     * @return string Xml document
     */
    public function getDocument(){
        $this->endElement();
        $this->endDocument();
        return $this->outputMemory();
    }

    /**
     * Output the content of a current xml document.
     * @access public
     * @param null
     */
    public function output(){
        header('Content-type: text/xml');
        echo $this->getDocument();
    }

}

?>

Contents of the file 'index.xsl' :

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet
 version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns="http://www.w3.org/TR/xhtml1/strict">

<xsl:output
    method="html"
    encoding="utf-8"
/>

<xsl:template match="rootElement">

<html xmlns="http://www.w3.org/1999/xhtml">

        <head>

            <title><xsl:value-of select="page_title" /></title>

        </head>

        <body>

            <xsl:value-of select="welcome_msg" />

        </body>

</html>

</xsl:template>

</xsl:stylesheet>
Carlos Averett 15-Apr-2006 10:49
Using XMLWriter to create a WAP page:

<?php
$memory = xmlwriter_open_memory();
xmlwriter_start_document($memory,'1.0','UTF-8');
xmlwriter_start_dtd($memory,'html','-//WAPFORUM//DTD XHTML Mobile 1.0//EN', 'http://www.wapforum.org/DTD/xhtml-mobile10.dtd');
xmlwriter_end_dtd($memory);
xmlwriter_start_element ($memory,'html'); // <html>
xmlwriter_write_attribute( $memory, 'xmlns', 'http://www.wapforum.org/DTD/xhtml-mobile10.dtd');
xmlwriter_write_attribute( $memory, 'xm:lang', 'en');

xmlwriter_start_element($memory,'head'); // <head>

xmlwriter_write_element ($memory,'title', 'Test WAP Document');

xmlwriter_end_element($memory); // </head>
xmlwriter_start_element($memory,'body'); // <body>
xmlwriter_start_element($memory,'ol'); // <ol>

xmlwriter_write_element ($memory,'li', 'One Item');
xmlwriter_write_element ($memory,'li', 'Another Item');
xmlwriter_write_element ($memory,'li', 'Another Item');

xmlwriter_end_element($memory); // </ol>
xmlwriter_end_element($memory); // </body>
xmlwriter_end_element($memory); // </html>

xmlwriter_end_dtd($memory);
$xml = xmlwriter_output_memory($memory,true);
?>

Output:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.wapforum.org/DTD/xhtml-mobile10.dtd" xm:lang="en">
<head>
<title>Test WAP Document</title>
</head>
<body>
<ol>
<li>One Item</li>
<li>Another Item</li>
<li>Another Item</li>
</ol>
</body>
</html>
Предопределенные константы
XMLWriter::endAttribute
XMLWriter
PHP Manual


Завершить атрибут

XMLWriter
XMLWriter::endCData
XMLWriter
PHP Manual

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — Завершить атрибут

Описание

Объектно-ориентированный стиль

bool XMLWriter::endAttribute ( void )

Процедурный стиль

bool xmlwriter_end_attribute ( resource $xmlwriter )

Завершает текущий атрибут.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startAttribute() - Создать начальный атрибут
  • XMLWriter::startAttributeNS() - Создать стартовый атрибут пространства имен
  • XMLWriter::writeAttribute() - Записать полный атрибут
  • XMLWriter::writeAttributeNS() - Записать полный атрибут пространства имен

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter
XMLWriter::endCData
XMLWriter


Завершить текущую секцию CDATA

XMLWriter::endAttribute
XMLWriter::endComment
XMLWriter
PHP Manual

XMLWriter::endCData

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endCData -- xmlwriter_end_cdata — Завершить текущую секцию CDATA

Описание

Объектно-ориентированный стиль

bool XMLWriter::endCData ( void )

Процедурный стиль

bool xmlwriter_end_cdata ( resource $xmlwriter )

Завершает текущую секцию CDATA.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startCData() - Создать начальный тэг CDATA
  • XMLWriter::writeCData() - Записать полный тэг CDATA

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endAttribute
XMLWriter::endComment
XMLWriter


Завершить комментарий

XMLWriter::endCData
XMLWriter::endDocument
XMLWriter
PHP Manual

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Завершить комментарий

Описание

Объектно-ориентированный стиль

bool XMLWriter::endComment ( void )

Процедурный стиль

bool xmlwriter_end_comment ( resource $xmlwriter )

Завершает текущий комметарий.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startComment() - Создает стартовый комментарий
  • XMLWriter::writeComment() - Записать полный тэг комментария

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endCData
XMLWriter::endDocument
XMLWriter


Завершить текущий документ

XMLWriter::endComment
XMLWriter::endDTDAttlist
XMLWriter
PHP Manual

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — Завершить текущий документ

Описание

Объектно-ориентированный стиль

bool XMLWriter::endDocument ( void )

Процедурный стиль

bool xmlwriter_end_document ( resource $xmlwriter )

Завершает текущий документ.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDocument() - Создать тэг документа

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endComment
XMLWriter::endDTDAttlist
XMLWriter


Завершить текущий DTD

XMLWriter::endDocument
XMLWriter::endDTDElement
XMLWriter
PHP Manual

XMLWriter::endDTDAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDAttlist -- xmlwriter_end_dtd_attlist — Завершить текущий DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::endDTDAttlist ( void )

Процедурный стиль

bool xmlwriter_end_dtd_attlist ( resource $xmlwriter )

Завершает текущий список атрибутов DTD для документа.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTDAttlist() - Создает стартовый список атрибутов DTD
  • XMLWriter::writeDTDAttlist() - Записать полный тэг DTD AttList

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endDocument
XMLWriter::endDTDElement
XMLWriter


Завершить текущий элемент DTD

XMLWriter::endDTDAttlist
XMLWriter::endDTDEntity
XMLWriter
PHP Manual

XMLWriter::endDTDElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDElement -- xmlwriter_end_dtd_element — Завершить текущий элемент DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::endDTDElement ( void )

Процедурный стиль

bool xmlwriter_end_dtd_element ( resource $xmlwriter )

Завершает текущий элемент DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTDElement() - Создать начальный элемент DTD
  • XMLWriter::writeDTDElement() - Записать полный тэг элемента DTD

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endDTDAttlist
XMLWriter::endDTDEntity
XMLWriter


Завершить текущую запись DTD

XMLWriter::endDTDElement
XMLWriter::endDTD
XMLWriter
PHP Manual

XMLWriter::endDTDEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDEntity -- xmlwriter_end_dtd_entity — Завершить текущую запись DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::endDTDEntity ( void )

Процедурный стиль

bool xmlwriter_end_dtd_entity ( resource $xmlwriter )

Завершает текущую запись DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTDEntity() - Создать начальную запись DTD
  • XMLWriter::writeDTDEntity() - Записать полный тэг DTD записи

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endDTDElement
XMLWriter::endDTD
XMLWriter


Завершить текущий DTD

XMLWriter::endDTDEntity
XMLWriter::endElement
XMLWriter
PHP Manual

XMLWriter::endDTD

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTD -- xmlwriter_end_dtd — Завершить текущий DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::endDTD ( void )

Процедурный стиль

bool xmlwriter_end_dtd ( resource $xmlwriter )

Завершает секцию определения типа документа (DTD).

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTD() - Создать стартовый DTD тэг
  • XMLWriter::writeDTD() - Записать полный тэг DTD

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endDTDEntity
XMLWriter::endElement
XMLWriter


Завершить текущий элемент

XMLWriter::endDTD
XMLWriter::endPI
XMLWriter
PHP Manual

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — Завершить текущий элемент

Описание

Объектно-ориентированный стиль

bool XMLWriter::endElement ( void )

Процедурный стиль

bool xmlwriter_end_element ( resource $xmlwriter )

Завершает текущий элемент.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startElement() - Создать стартовый тэг элемента
  • XMLWriter::writeElement() - Записать полный тег элемента

User Contributed Notes

contact at paulchaplin dot com 26-May-2012 12:32
Note that elements opened this way will *remain open* (i.e. the XML will be badly formed and thus invalid) unless *each element* is explicitly closed with XMLWriter::endElement.

If you have multiple elements open, and wish to simply close them all -- including the root element -- this snippet is what you want:

<?php

// Automatically close all remaining open elements.
while ($xml->endElement() !== false) { continue; }

?>

In some cases, XMLWriter::writeElement might serve you better: it writes complete elements, but isn't suitable when you need to loop to generate its contents, unless this is done beforehand.
XMLWriter::endDTD
XMLWriter::endPI
XMLWriter


Завершить текущую инструкцию обработки (PI)

XMLWriter::endElement
XMLWriter::flush
XMLWriter
PHP Manual

XMLWriter::endPI

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endPI -- xmlwriter_end_pi — Завершить текущую инструкцию обработки (PI)

Описание

Объектно-ориентированный стиль

bool XMLWriter::endPI ( void )

Процедурный стиль

bool xmlwriter_end_pi ( resource $xmlwriter )

Завершает текущую инструкцию обработки.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startPI() - Создать начальный тэг PI
  • XMLWriter::writePI() - Записать инструкцию обработки (PI)

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endElement
XMLWriter::flush
XMLWriter


Сбросить текущий буфер

XMLWriter::endPI
XMLWriter::fullEndElement
XMLWriter
PHP Manual

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Сбросить текущий буфер

Описание

Объектно-ориентированный стиль

mixed XMLWriter::flush ([ bool $empty = true ] )

Процедурный стиль

mixed xmlwriter_flush ( resource $xmlwriter [, bool $empty = true ] )

Сбрасывает текущий буфер.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

empty

Освободить ли буфер или нет. По умолчанию TRUE.

Возвращаемые значения

Если XML создается в памяти, то эта функция вернет сгенерированный буфер XML, иначе при использовании URI эта функция запишет буфер и возвратит количество записанных байт.

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::endPI
XMLWriter::fullEndElement
XMLWriter


Завершить текущий элемент

XMLWriter::flush
XMLWriter::openMemory
XMLWriter
PHP Manual

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — Завершить текущий элемент

Описание

Объектно-ориентированный стиль

bool XMLWriter::fullEndElement ( void )

Процедурный стиль

bool xmlwriter_full_end_element ( resource $xmlwriter )

Завершает текущий XML элемент. Записывает закрывающий тег, даже если элемент пустой.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endElement() - Завершить текущий элемент

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::flush
XMLWriter::openMemory
XMLWriter


Создать новый объект XMLWriter, используя память для строкового вывода

XMLWriter::fullEndElement
XMLWriter::openURI
XMLWriter
PHP Manual

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Создать новый объект XMLWriter, используя память для строкового вывода

Описание

Объектно-ориентированный стиль

bool XMLWriter::openMemory ( void )

Процедурный стиль

resource xmlwriter_open_memory ( void )

Создает новый объект XMLWriter, используя память для строкового вывода.

Список параметров

Возвращаемые значения

Объектно-ориентированный стиль: Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Процедурный стиль: возвращает новый xmlwriter resource для дальнейшего использования функциями xmlwriter в случае успеха либо FALSE в случае ошибки.

Смотрите также

  • XMLWriter::openURI() - Создать новый объект XMLWriter, используя исходный URI для вывода

User Contributed Notes

alvaro at demogracia dot com 16-Jun-2011 01:05
A simple usage example:

<?php
header('Content-type: text/xml; charset=UTF-8');

$oXMLWriter = new XMLWriter;
$oXMLWriter->openMemory();
$oXMLWriter->startDocument('1.0', 'UTF-8');

$oXMLWriter->startElement('test');
$oXMLWriter->text('Hello, World!');
$oXMLWriter->endElement();

$oXMLWriter->endDocument();
echo $oXMLWriter->outputMemory(TRUE);
?>
prashant at prashantpatil dot net 26-Apr-2010 06:40
Here is an simple example of using openMemory. This is particularly useful when you are handling a large amount of data and you want to split the xml creation in batches.

<?php
$batchSize = 25;
$xmlWriter = new XMLWriter();
$xmlWriter->openUri('php://output');
$xmlWriter->setIndent(true);
if($xmlWriter)
{
  $xmlWriter->startDocument('1.0','UTF-8');
  $xmlWriter->startElement('Books');

  $memXmlWriter = new XMLWriter();

  $memXmlWriter->openMemory();
  $memXmlWriter->setIndent(true);

  for($i=1;$i<=1000;$i++)
  {
    $memXmlWriter->startElement('book');
      $memXmlWriter->text('book_'.$i);
    $memXmlWriter->endElement();

    if($i%5 == 0)
    {
      $batchXmlString = $memXmlWriter->outputMemory(true);
      $xmlWriter->writeRaw($batchXmlString);
    }
  }
  $memXmlWriter->flush();
  unset($memXmlWriter);
  $xmlWriter->endElement();
  $xmlWriter->endDocument();
}
?>
XMLWriter::fullEndElement
XMLWriter::openURI
XMLWriter


Создать новый объект XMLWriter, используя исходный URI для вывода

XMLWriter::openMemory
XMLWriter::outputMemory
XMLWriter
PHP Manual

XMLWriter::openURI

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::openURI -- xmlwriter_open_uri — Создать новый объект XMLWriter, используя исходный URI для вывода

Описание

Объектно-ориентированный стиль

bool XMLWriter::openURI ( string $uri )

Процедурный стиль

resource xmlwriter_open_uri ( string $uri )

Создаёт новый объект XMLWriter, используя uri для вывода.

Список параметров

uri

URI ресурса для вывода.

Возвращаемые значения

Объектно-ориентированный стиль: Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Процедурный стиль: возвращает новый объект XmlWriter resource для дальнейшего использования функциями xmlwriter в случае успеха или FALSE в случае ошибки.

Смотрите также

  • XMLWriter::openMemory() - Создать новый объект XMLWriter, используя память для строкового вывода

User Contributed Notes

Lukas Knuth 07-May-2011 09:08
If you're facing problems on Windows Servers running PHP 5.3 and newer, where this function quits with an "Unable to resolve file path" Error, here is a Workaround which isn't posted on the Bug site yet:

Add this before you use the openURI()-function:

<?php
touch($uri);
$uri = realpath($uri);
?>

This Bug appears in the following cases:

$xml->openURI('file.xml'); -> ok!
$xml->openURI('../file.xml'); -> ok!
$xml->openURI('xml/file.xml'); -> DON'T WORK!
$xml->openURI('../xml/file.xml'); -> DON'T WORK!
icepick dot pt at hotmail dot com 16-Mar-2009 01:13
I wanted to stream a XML file directly to the user and having him prompted to save it without displaying the content, but when using

<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>

the user's browser was displaying the file contents instead of prompting the user with a filesave window.

To have the XML file stream saved directly to the user without being displayed by the browser, you shoud add:

<?php
header("Content-Type: text/html/force-download");
header("Content-Disposition: attachment; filename='file_name.xml'");
$out =new XMLWriter();
$out->openURI('php://output');
?>

This will prompt the user with a dialog box to save 'file_name.xml' on his disk, and will not display the content of the streamed XML.
yankee at ignorethis dot cipher DASH code dot de 19-Nov-2007 10:46
Want to write xml-data directly to the user instead of memory or file?
This will do:
<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>
XMLWriter::openMemory
XMLWriter::outputMemory
XMLWriter


Возвратить текущий буфер

XMLWriter::openURI
XMLWriter::setIndentString
XMLWriter
PHP Manual

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Возвратить текущий буфер

Описание

Объектно-ориентированный стиль

string XMLWriter::outputMemory ([ bool $flush = true ] )

Процедурный стиль

string xmlwriter_output_memory ( resource $xmlwriter [, bool $flush = true ] )

Возвращает текущий буфер.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

flush

Освободить буфер или нет. По умолчанию TRUE.

Возвращаемые значения

Возвращает текущий буфер в виде строки.

Смотрите также

  • XMLWriter::flush() - Сбросить текущий буфер

User Contributed Notes

dave at dtracorp dot com 22-Feb-2007 11:08
when writing xml with xmlwriter, there is no need to use htmlspecialchars or htmlentities for the text() method (this will only cause double encoding)
the xmlwriter takes care of entities for you after calling outputMemory
XMLWriter::openURI
XMLWriter::setIndentString
XMLWriter


Установить строку, используемую для отступов

XMLWriter::outputMemory
XMLWriter::setIndent
XMLWriter
PHP Manual

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Установить строку, используемую для отступов

Описание

Объектно-ориентированный стиль

bool XMLWriter::setIndentString ( string $indentString )

Процедурный стиль

bool xmlwriter_set_indent_string ( resource $xmlwriter , string $indentString )

Устанавливает строку, которая будет использоваться для отступа каждого элемента/атрибута в результирующем XML.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

indentString

Отступ строки.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::setIndent() - Включить или отключить отступы

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::outputMemory
XMLWriter::setIndent
XMLWriter


Включить или отключить отступы

XMLWriter::setIndentString
XMLWriter::startAttributeNS
XMLWriter
PHP Manual

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Включить или отключить отступы

Описание

Объектно-ориентированный стиль

bool XMLWriter::setIndent ( bool $indent )

Процедурный стиль

bool xmlwriter_set_indent ( resource $xmlwriter , bool $indent )

Включает или отключает отступы.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

indent

Включено ли добавление отступа.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::setIndentString() - Установить строку, используемую для отступов

User Contributed Notes

nemiga at gmail dot com 28-Jul-2011 12:05
This param should be used only after openMemory() call:

<?php
$version = '1.0';
$encoding = 'UTF-8';
$rootName = 'root';

$xml = new XMLWriter();

$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument($version, $encoding);
$xml->startElement($this->rootName);
// .. add more elements here
$xml->endElement();
echo $xml->outputMemory();
?>
XMLWriter::setIndentString
XMLWriter::startAttributeNS
XMLWriter


Создать стартовый атрибут пространства имен

XMLWriter::setIndent
XMLWriter::startAttribute
XMLWriter
PHP Manual

XMLWriter::startAttributeNS

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNS -- xmlwriter_start_attribute_ns — Создать стартовый атрибут пространства имен

Описание

Объектно-ориентированный стиль

bool XMLWriter::startAttributeNS ( string $prefix , string $name , string $uri )

Процедурный стиль

bool xmlwriter_start_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri )

Начинает атрибут пространства имен.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

prefix

Префикс пространства имен.

name

Имя атрибута.

uri

URI пространства имен.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startAttribute() - Создать начальный атрибут
  • XMLWriter::endAttribute() - Завершить атрибут
  • XMLWriter::writeAttribute() - Записать полный атрибут
  • XMLWriter::writeAttributeNS() - Записать полный атрибут пространства имен

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::setIndent
XMLWriter::startAttribute
XMLWriter


Создать начальный атрибут

XMLWriter::startAttributeNS
XMLWriter::startCData
XMLWriter
PHP Manual

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Создать начальный атрибут

Описание

Объектно-ориентированный стиль

bool XMLWriter::startAttribute ( string $name )

Процедурный стиль

bool xmlwriter_start_attribute ( resource $xmlwriter , string $name )

Начинает атрибут.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startAttributeNS() - Создать стартовый атрибут пространства имен
  • XMLWriter::endAttribute() - Завершить атрибут
  • XMLWriter::writeAttribute() - Записать полный атрибут
  • XMLWriter::writeAttributeNS() - Записать полный атрибут пространства имен

User Contributed Notes

alvaro at demogracia dot com 11-Apr-2011 03:08
The attribute value can be set with XMLWriter::text(), e.g.:

<?php
$writer = new XMLWriter;
$writer->openURI('php://output');
$writer->startDocument('1.0', 'UTF-8');

$writer->startElement('response');
    $writer->startElement('status');
        $writer->startAttribute('code');
            $writer->text('500');
        $writer->endAttribute();
    $writer->endElement();
$writer->endElement();

$writer->endDocument();
?>

... generates:

<?xml version="1.0" encoding="UTF-8"?>
<response><status code="500"/></response>
XMLWriter::startAttributeNS
XMLWriter::startCData
XMLWriter


Создать начальный тэг CDATA

XMLWriter::startAttribute
XMLWriter::startComment
XMLWriter
PHP Manual

XMLWriter::startCData

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startCData -- xmlwriter_start_cdata — Создать начальный тэг CDATA

Описание

Объектно-ориентированный стиль

bool XMLWriter::startCData ( void )

Процедурный стиль

bool xmlwriter_start_cdata ( resource $xmlwriter )

Начинает CDATA.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endCData() - Завершить текущую секцию CDATA
  • XMLWriter::writeCData() - Записать полный тэг CDATA

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::startAttribute
XMLWriter::startComment
XMLWriter


Создает стартовый комментарий

XMLWriter::startCData
XMLWriter::startDocument
XMLWriter
PHP Manual

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Создает стартовый комментарий

Описание

Объектно-ориентированный стиль

bool XMLWriter::startComment ( void )

Процедурный стиль

bool xmlwriter_start_comment ( resource $xmlwriter )

Начинает комментарий.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endComment() - Завершить комментарий
  • XMLWriter::writeComment() - Записать полный тэг комментария

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::startCData
XMLWriter::startDocument
XMLWriter


Создать тэг документа

XMLWriter::startComment
XMLWriter::startDTDAttlist
XMLWriter
PHP Manual

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Создать тэг документа

Описание

Объектно-ориентированный стиль

bool XMLWriter::startDocument ([ string $version = 1.0 [, string $encoding = NULL [, string $standalone ]]] )

Процедурный стиль

bool xmlwriter_start_document ( resource $xmlwriter [, string $version = 1.0 [, string $encoding = NULL [, string $standalone ]]] )

Начинает документ.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

version

Номер версии документа как часть объявления XML.

encoding

Кодировка документа как часть объявления XML.

standalone

yes или no.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endDocument() - Завершить текущий документ

User Contributed Notes

icepick dot pt at hotmail dot com 30-Mar-2009 01:25
I was having a very hard time triyng to use:

$writer->startDocument( '1.0' , 'Windows-1252' );

Somehow this caused the generation of an empty xml file, and I could not figure out why.
When all other efforts failed I asked for help to the team that developed the XMLwriter extension, and got a very quick reply as follows:

Quote:
==============================
Windows-1252 support is only available if libxml2 is link with iconv
support (it usually is, but there are exceptions). I know on my Mac, the
built in libxml2 doesnt provide iconv support - they go with some
Unicode hack which doesnt provide it, so I had to build my own. It is
built by default (and your code works) on my linux machines.

It is possible to create the XML without a declaration, which means you
could add it manually, but if you use any characters that are differnt
between UTF-8 and Windows-1252, the encoding would be wrong in the
document, so do not recommend.
==============================

Then light was made on my head: I am using a linux server distribution that by default is still running PHP 4.3. A few months ago I decided to force the upgrade of PHP to the newest version 5.1.6 at that time, and that has brougth me the XMLwriter extension that I am now using. But clearly there are compatibility issues betwen the rest of the server's defaults and PHP 5 wich is probably why it's development team has not upgraded yet.

Let's hope all the remaining environments catch up with this extension. It is in fact most handy.

And in the meantime, I have figured out a (not recomended, obviously) workaroud that works for me:

Instead of using two parameters, I used only the first one:

$writer->startDocument( '1.0" encoding="Windows-1252' );

this will output:

<?xml version="1.0" encoding="Windows-1252"?>
XMLWriter::startComment
XMLWriter::startDTDAttlist
XMLWriter


Создает стартовый список атрибутов DTD

XMLWriter::startDocument
XMLWriter::startDTDElement
XMLWriter
PHP Manual

XMLWriter::startDTDAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDAttlist -- xmlwriter_start_dtd_attlist — Создает стартовый список атрибутов DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::startDTDAttlist ( string $name )

Процедурный стиль

bool xmlwriter_start_dtd_attlist ( resource $xmlwriter , string $name )

Стартовый список атрибутов DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Название списка атрибутов.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endDTDAttlist() - Завершить текущий DTD
  • XMLWriter::writeDTDAttlist() - Записать полный тэг DTD AttList

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::startDocument
XMLWriter::startDTDElement
XMLWriter


Создать начальный элемент DTD

XMLWriter::startDTDAttlist
XMLWriter::startDTDEntity
XMLWriter
PHP Manual

XMLWriter::startDTDElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDElement -- xmlwriter_start_dtd_element — Создать начальный элемент DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::startDTDElement ( string $qualifiedName )

Процедурный стиль

bool xmlwriter_start_dtd_element ( resource $xmlwriter , string $qualifiedName )

Начинает элемент DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

qualifiedName

Полностью определенное имя типа документа для создания.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endDTDElement() - Завершить текущий элемент DTD
  • XMLWriter::writeDTDElement() - Записать полный тэг элемента DTD

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::startDTDAttlist
XMLWriter::startDTDEntity
XMLWriter


Создать начальную запись DTD

XMLWriter::startDTDElement
XMLWriter::startDTD
XMLWriter
PHP Manual

XMLWriter::startDTDEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDEntity -- xmlwriter_start_dtd_entity — Создать начальную запись DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::startDTDEntity ( string $name , bool $isparam )

Процедурный стиль

bool xmlwriter_start_dtd_entity ( resource $xmlwriter , string $name , bool $isparam )

Начинает запись DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя записи.

isparam

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endDTDEntity() - Завершить текущую запись DTD
  • XMLWriter::writeDTDEntity() - Записать полный тэг DTD записи

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::startDTDElement
XMLWriter::startDTD
XMLWriter


Создать стартовый DTD тэг

XMLWriter::startDTDEntity
XMLWriter::startElementNS
XMLWriter
PHP Manual

XMLWriter::startDTD

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTD -- xmlwriter_start_dtd — Создать стартовый DTD тэг

Описание

Объектно-ориентированный стиль

bool XMLWriter::startDTD ( string $qualifiedName [, string $publicId [, string $systemId ]] )

Процедурный стиль

bool xmlwriter_start_dtd ( resource $xmlwriter , string $qualifiedName [, string $publicId [, string $systemId ]] )

Начинает DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

qualifiedName

Полностью определенное имя типа документа для создания.

publicId

Идентификатор внешнего публичного подмножества.

systemId

Идентификатор внешнего системного подмножества.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endDTD() - Завершить текущий DTD
  • XMLWriter::writeDTD() - Записать полный тэг DTD

User Contributed Notes

joaner1206 at gmail dot com 04-Oct-2011 02:52
If you will write a HTML document :

 // $xml = new XMLWriter();  you know it and openURI()

<?php
 // for HTML 5
$xml->startDTD('html');
 // for XHTML 1.0
$xml->startDTD('html', '-//W3C//DTD XHTML 1.0 Strict//EN','http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); // standards compliant

$xml->endDTD();
?>
it will be :
<!DOCTYPE html>
or    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">

don't need to startDocument() .
XMLWriter::startDTDEntity
XMLWriter::startElementNS
XMLWriter


Создать начальный тег элемента пространства имен

XMLWriter::startDTD
XMLWriter::startElement
XMLWriter
PHP Manual

XMLWriter::startElementNS

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNS -- xmlwriter_start_element_ns — Создать начальный тег элемента пространства имен

Описание

Объектно-ориентированный стиль

bool XMLWriter::startElementNS ( string $prefix , string $name , string $uri )

Процедурный стиль

bool xmlwriter_start_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri )

Начинает элемент пространства имен.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

prefix

Префикс пространства имен.

name

Имя элемента.

uri

URI пространства имен.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endElement() - Завершить текущий элемент
  • XMLWriter::writeElementNS() - Записать полное пространство имен тега элемента

User Contributed Notes

pike-php at kw dot nl 07-Mar-2011 04:02
by default, the xmlns: definition is repeated on every element.

if you do want the prefix, but dont want the xmlns: declaration repeated, set the namespace to null. dont forget to declare the namespace prefix somewhere higher in your document, though:

<?php
$w->startElementNS('foo', 'bar', 'http://example.com/foo');
$w->startElementNS('foo', 'baz', null);
$w->endElement();
$w->endElement();
?>
anthony dot parsons at manx dot net 05-Aug-2007 10:27
If you don't want any namespace prefix at all but still want the xmlns attribute, set $prefix to null.
XMLWriter::startDTD
XMLWriter::startElement
XMLWriter


Создать стартовый тэг элемента

XMLWriter::startElementNS
XMLWriter::startPI
XMLWriter
PHP Manual

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Создать стартовый тэг элемента

Описание

Объектно-ориентированный стиль

bool XMLWriter::startElement ( string $name )

Процедурный стиль

bool xmlwriter_start_element ( resource $xmlwriter , string $name )

Начинает элемент.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя элемента.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endElement() - Завершить текущий элемент
  • XMLWriter::writeElement() - Записать полный тег элемента

User Contributed Notes

toby at php dot net 21-Oct-2010 11:01
Note that startElement() and startElementNS() naturally do not write the closing ">" of the tag, since you may add an arbitrary number of attributes after starting a tag.

However, in some cases you may want to have the starting element tag closed in the output buffer before writing any further elements or content (e.g. if you communicate via an XML stream). To achieve this, you can simply use the text() method with an empty string.
marcuslists at brightonart dot co dot uk 16-Oct-2009 05:10
Call trim on the tag as a trailing space breaks the end element.
XMLWriter::startElementNS
XMLWriter::startPI
XMLWriter


Создать начальный тэг PI

XMLWriter::startElement
XMLWriter::text
XMLWriter
PHP Manual

XMLWriter::startPI

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startPI -- xmlwriter_start_pi — Создать начальный тэг PI

Описание

Объектно-ориентированный стиль

bool XMLWriter::startPI ( string $target )

Процедурный стиль

bool xmlwriter_start_pi ( resource $xmlwriter , string $target )

Начинает тег инструкций обработки (PI).

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

target

Цель инструкций обработки.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::endPI() - Завершить текущую инструкцию обработки (PI)
  • XMLWriter::writePI() - Записать инструкцию обработки (PI)

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::startElement
XMLWriter::text
XMLWriter


Записать текст

XMLWriter::startPI
XMLWriter::writeAttributeNS
XMLWriter
PHP Manual

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Записать текст

Описание

Объектно-ориентированный стиль

bool XMLWriter::text ( string $content )

Процедурный стиль

bool xmlwriter_text ( resource $xmlwriter , string $content )

Записывает текст.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

content

Содержимое текста.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes

c dot 1 at smithies dot org 27-Nov-2011 10:55
There is no need to use htmlspecialchars() on your data: it is done automatically.
eikonomega at gmail dot com 16-Apr-2010 03:04
This method creates a text node (W3C type 3).
XMLWriter::startPI
XMLWriter::writeAttributeNS
XMLWriter


Записать полный атрибут пространства имен

XMLWriter::text
XMLWriter::writeAttribute
XMLWriter
PHP Manual

XMLWriter::writeAttributeNS

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNS -- xmlwriter_write_attribute_ns — Записать полный атрибут пространства имен

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeAttributeNS ( string $prefix , string $name , string $uri , string $content )

Процедурный стиль

bool xmlwriter_write_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri , string $content )

Записывает полный атрибут пространства имен.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

prefix

Префикс пространства имен.

name

Имя атрибута.

uri

URI пространства имен.

content

Значение атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::writeAttribute() - Записать полный атрибут
  • XMLWriter::startAttribute() - Создать начальный атрибут
  • XMLWriter::startAttributeNS() - Создать стартовый атрибут пространства имен
  • XMLWriter::endAttribute() - Завершить атрибут

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::text
XMLWriter::writeAttribute
XMLWriter


Записать полный атрибут

XMLWriter::writeAttributeNS
XMLWriter::writeCData
XMLWriter
PHP Manual

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Записать полный атрибут

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeAttribute ( string $name , string $value )

Процедурный стиль

bool xmlwriter_write_attribute ( resource $xmlwriter , string $name , string $value )

Записывает полный атрибут.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя атрибута.

value

Значение атрибута.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::writeAttributeNS() - Записать полный атрибут пространства имен
  • XMLWriter::startAttribute() - Создать начальный атрибут
  • XMLWriter::startAttributeNS() - Создать стартовый атрибут пространства имен
  • XMLWriter::endAttribute() - Завершить атрибут

User Contributed Notes

Maxim at inbox dot ru 12-Feb-2012 01:01
Be careful and dont write attributes after writing text() or any content into xml element, for example
<?php
xml->startelement("div");
xml->text("my text in div");
xml->writeattribute("id",1); // wont write because after adding text
xml->endelement();
?>
Jason Hughes 15-Apr-2011 01:37
If you intermix writing sub-elements and attributes, any attributes that are written after the first sub-element are ignored/discarded:

<?php
$xml->startElement('element');
  $xml->writeAttribute('attr1', 0);
  $xml->writeElement('subelem', 0);
  $xml->writeAttribute('attr2', 0);
$xml->endElement();
?>

Outputs:

<element attr1=0>
  <subelem>0</subelem>
</element>

This is stupid, but the way it works as of PHP 5.2.4.
XMLWriter::writeAttributeNS
XMLWriter::writeCData
XMLWriter


Записать полный тэг CDATA

XMLWriter::writeAttribute
XMLWriter::writeComment
XMLWriter
PHP Manual

XMLWriter::writeCData

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCData -- xmlwriter_write_cdata — Записать полный тэг CDATA

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeCData ( string $content )

Процедурный стиль

bool xmlwriter_write_cdata ( resource $xmlwriter , string $content )

Записывает полный тэг CDATA.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

content

Содержимое CDATA.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startCData() - Создать начальный тэг CDATA
  • XMLWriter::endCData() - Завершить текущую секцию CDATA

User Contributed Notes

t dot w dot natt at UNIVERSITY dot bath dot ac dot uk 09-Sep-2008 08:18
Seen a couple of bug reports and gotchas with this one but not a simple code example. Just in case someone finds it useful:

<?php

// serve xml doc as xml
header('Content-type: application/xml');

// set up the document
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('mydoc');
$xml->startElement('myele');

// CData output
$xml->startElement('mycdataelement');
$xml->writeCData("text for inclusion within CData tags");
$xml->endElement();

// end the document and output
$xml->endElement();
$xml->endElement();
echo $xml->outputMemory(true);
?>

Outputs:
<?xml version="1.0" encoding="UTF-8"?>
<mydoc>
    <myele>
        <mycdataelement><![CDATA[text for inclusion within CData tags]]>
        </mycdataelement>
    </myele>
</mydoc>
harvey dot robin at gmail dot com 08-Sep-2007 04:57
This function will not have any effect if the last node you output was a text node.  This includes whitespace.  Example:

<?php
/*
<html>
<![CDATA[ Summut nice ]]>
<p>something</p>
</html>
*/
$xw = new XMLWriter;
$xw->openMemory();
$xw->startDocument('1.0', 'ISO-8859-1');
$xw->startElement('html');
$xw->text('Comment out this line to get the CDATA back!!');
$xw->writeCData('Summut nice');
$xw->writeElement('p', 'something');
$xw->endElement();
$xw->endDocument();
echo $xw->outputMemory();
?>
thesoupdragon at hotmail dot com 21-Jun-2007 02:14
A rather strange effect with this.

UTF8 Mysql database

                            $xml->startElement('tablecolor2');
    $xml->writeCData( $tablecolor2 );
    $xml->endElement();

does not work !

but
                            $xml->startElement('tablecolor2');
    $tablecolor2 = utf8_decode ( $val['pcolor2']);
    $xml->writeCData( utf8_encode ($tablecolor2) );
    $xml->endElement();

cannot explain this - but it may help someone
dave at dtracorp dot com 06-Mar-2007 01:30
i don't know if this is a bug with the underlying c code or not, or this is by design (i'm not a big xml guy), but for me, running on fedora core 5, php 5.2.1
to get this to work, the cdata functions need to wrap the description (or whatever element the cdata should appear in)
for example.
// initiate xmlwriter object as $xw
// add header, titles, etc.

// start cdata
$xw->startCData();
// start description
$xw->startElement('description');
// write cdata
$xw->writeCData('<img src="http://php.net/images/php.gif" />');
// write the description contents
$xw->text('php logo');
// end the description element
$xw->endElement();
// end the cdata
$xw->endCData();

// end xml, and output

otherwise, i just got warnings about writing cdata in the wrong context, and no cdata would be written
XMLWriter::writeAttribute
XMLWriter::writeComment
XMLWriter


Записать полный тэг комментария

XMLWriter::writeCData
XMLWriter::writeDTDAttlist
XMLWriter
PHP Manual

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Записать полный тэг комментария

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeComment ( string $content )

Процедурный стиль

bool xmlwriter_write_comment ( resource $xmlwriter , string $content )

Записывает полный комментарий.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

content

Содержание комментария.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startComment() - Создает стартовый комментарий
  • XMLWriter::endComment() - Завершить комментарий

User Contributed Notes

thewrs at gmail dot com 05-Dec-2007 02:37
This will write a XML <!----> style comment to your XMLWriter resource.

Strings up to 50 characters long are displayed on a single line with no spacing between the tags.

Anything above 50 characters will show on multiple formatted lines. Using the \n metacharater inserts a newline and maintains indenting.
XMLWriter::writeCData
XMLWriter::writeDTDAttlist
XMLWriter


Записать полный тэг DTD AttList

XMLWriter::writeComment
XMLWriter::writeDTDElement
XMLWriter
PHP Manual

XMLWriter::writeDTDAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDAttlist -- xmlwriter_write_dtd_attlist — Записать полный тэг DTD AttList

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeDTDAttlist ( string $name , string $content )

Процедурный стиль

bool xmlwriter_write_dtd_attlist ( resource $xmlwriter , string $name , string $content )

Записывает список атрибутов DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя списка атрибутов DTD.

content

Содержимое списка атрибутов DTD.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTDAttlist() - Создает стартовый список атрибутов DTD
  • XMLWriter::endDTDAttlist() - Завершить текущий DTD

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::writeComment
XMLWriter::writeDTDElement
XMLWriter


Записать полный тэг элемента DTD

XMLWriter::writeDTDAttlist
XMLWriter::writeDTDEntity
XMLWriter
PHP Manual

XMLWriter::writeDTDElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDElement -- xmlwriter_write_dtd_element — Записать полный тэг элемента DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeDTDElement ( string $name , string $content )

Процедурный стиль

bool xmlwriter_write_dtd_element ( resource $xmlwriter , string $name , string $content )

Записывает полный тэг элемента DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя элемента DTD.

content

Содержимое элемента.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTDElement() - Создать начальный элемент DTD
  • XMLWriter::endDTDElement() - Завершить текущий элемент DTD

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::writeDTDAttlist
XMLWriter::writeDTDEntity
XMLWriter


Записать полный тэг DTD записи

XMLWriter::writeDTDElement
XMLWriter::writeDTD
XMLWriter
PHP Manual

XMLWriter::writeDTDEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDEntity -- xmlwriter_write_dtd_entity — Записать полный тэг DTD записи

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeDTDEntity ( string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid )

Процедурный стиль

bool xmlwriter_write_dtd_entity ( resource $xmlwriter , string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid )

Записывает полную DTD запись.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя записи.

content

Содержимое записи.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTDEntity() - Создать начальную запись DTD
  • XMLWriter::endDTDEntity() - Завершить текущую запись DTD

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::writeDTDElement
XMLWriter::writeDTD
XMLWriter


Записать полный тэг DTD

XMLWriter::writeDTDEntity
XMLWriter::writeElementNS
XMLWriter
PHP Manual

XMLWriter::writeDTD

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTD -- xmlwriter_write_dtd — Записать полный тэг DTD

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeDTD ( string $name [, string $publicId [, string $systemId [, string $subset ]]] )

Процедурный стиль

bool xmlwriter_write_dtd ( resource $xmlwriter , string $name [, string $publicId [, string $systemId [, string $subset ]]] )

Записывает полный тэг DTD.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя DTD.

publicId

Идентификатор внешнего публичного подмножества.

systemId

Идентификатор внешнего системного подмножества.

subset

Содержание DTD.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startDTD() - Создать стартовый DTD тэг
  • XMLWriter::endDTD() - Завершить текущий DTD

User Contributed Notes

test2 at twinmail dot de 01-Jul-2009 04:14
Use NULL for $publicId to force 'SYSTEM' instead of 'PUBLIC' output.
XMLWriter::writeDTDEntity
XMLWriter::writeElementNS
XMLWriter


Записать полное пространство имен тега элемента

XMLWriter::writeDTD
XMLWriter::writeElement
XMLWriter
PHP Manual

XMLWriter::writeElementNS

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNS -- xmlwriter_write_element_ns — Записать полное пространство имен тега элемента

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeElementNS ( string $prefix , string $name , string $uri [, string $content ] )

Процедурный стиль

bool xmlwriter_write_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri [, string $content ] )

Записывает полное пространство имен тега элемента.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

prefix

Префикс пространства имен.

name

Имя элемента.

uri

URI пространства имен.

content

Содержимое элемента.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
PHP 5.2.3 | Параметр content стал опциональным.

Смотрите также

  • XMLWriter::startElementNS() - Создать начальный тег элемента пространства имен
  • XMLWriter::endElement() - Завершить текущий элемент
  • XMLWriter::writeElement() - Записать полный тег элемента

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::writeDTD
XMLWriter::writeElement
XMLWriter


Записать полный тег элемента

XMLWriter::writeElementNS
XMLWriter::writePI
XMLWriter
PHP Manual

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Записать полный тег элемента

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeElement ( string $name [, string $content ] )

Процедурный стиль

bool xmlwriter_write_element ( resource $xmlwriter , string $name [, string $content ] )

Записывает полный тег элемента.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

name

Имя элемента.

content

Содержимое элемента.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия | Описание
PHP 5.2.3 | Параметр content стал опциональным.

Смотрите также

  • XMLWriter::startElement() - Создать стартовый тэг элемента
  • XMLWriter::endElement() - Завершить текущий элемент
  • XMLWriter::writeElementNS() - Записать полное пространство имен тега элемента

User Contributed Notes

rjb at robertjbrown dot com 24-Jan-2010 06:04
Quick note - writeElement also seems to decode any HTML entities during the write. For example, if you pass it "Me & You", it will write the output as "Me &amp; You".
googolplex at gmx dot net 09-Dec-2008 06:08
The function XMLWriter::writeElement is used to write an element (i.e. a XML tag, an [optional] content, and a closing XML tag) in one line without sub-elements:

<?php

$oXMLout = new XMLWriter();
$oXMLout->openMemory();
$oXMLout->writeElement("quantity", 8);
$oXMLout->writeElement("price_per_quantity", 110);
print $oXMLout->outputMemory();

// produces:
// <quantity>8</quantity>
// <price_per_quantity>110</price_per_quantity>

?>

whereas if you want to include sub-elements you have to use the XMLWriter::startElement / XMLWriter::endElement pair:

<?php

$oXMLout = new XMLWriter();
$oXMLout->openMemory();
$oXMLout->startElement("item");
$oXMLout->writeElement("quantity", 8);
$oXMLout->writeElement("price_per_quantity", 110);
$oXMLout->endElement();
print $oXMLout->outputMemory();

// produces:
// <item>
// <quantity>8</quantity>
// <price_per_quantity>110</price_per_quantity>
// </item>

?>
XMLWriter::writeElementNS
XMLWriter::writePI
XMLWriter


Записать инструкцию обработки (PI)

XMLWriter::writeElement
XMLWriter::writeRaw
XMLWriter
PHP Manual

XMLWriter::writePI

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writePI -- xmlwriter_write_pi — Записать инструкцию обработки (PI)

Описание

Объектно-ориентированный стиль

bool XMLWriter::writePI ( string $target , string $content )

Процедурный стиль

bool xmlwriter_write_pi ( resource $xmlwriter , string $target , string $content )

Записывает инструкцию обработки.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

target

Цель инструкций обработки.

content

Содержимое инструкций обработки.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::startPI() - Создать начальный тэг PI
  • XMLWriter::endPI() - Завершить текущую инструкцию обработки (PI)

User Contributed Notes

ghargoil at remove dot gmx dot this dot net 29-Jul-2006 10:13
Just wanted to point out that if you do the following code in php, you can generate a simple php page with a stylesheet.

<?php
        $res = xmlwriter_open_memory();
        xmlwriter_set_indent_string($res, "\t");
        xmlwriter_start_document($res);
        xmlwriter_write_pi($res, "xml-stylesheet", "type=\"text/xml\" href=\"yourstyle.xsl\"");
        xmlwriter_end_document($res);
        $string = xmlwriter_output_memory($res);
        echo $string;
?>

This results in the following:
X-Powered-By: PHP/5.1.4
Content-type: text/html

<?xml version="1.0"?>
<?xml-stylesheet type="text/xml" href="yourstyle.xsl"?>
XMLWriter::writeElement
XMLWriter::writeRaw
XMLWriter


Пишет необработанный XML-текст

XMLWriter::writePI
XSL
XMLWriter
PHP Manual

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Пишет необработанный XML-текст

Описание

Объектно-ориентированный стиль

bool XMLWriter::writeRaw ( string $content )

Процедурный стиль

bool xmlwriter_write_raw ( resource $xmlwriter , string $content )

Пишет необработанный XML-текст.

Список параметров

xmlwriter

Только для процедурных вызовов. Изменяемый resource XMLWriter. Этот ресурс может быть получен из xmlwriter_open_uri() или xmlwriter_open_memory().

content

Текстовая строка для записи.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XMLWriter::text() - Записать текст

User Contributed Notes

There are no user contributed notes for this page.
XMLWriter::writePI
XSL
XMLWriter


XSL

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • Примеры
    • Файлы collection.xml и collection.xsl для примеров
  • XSLTProcessor — Класс XSLTProcessor
    • XSLTProcessor::__construct — Создаёт новый экземпляр класса XSLTProcessor
    • XSLTProcessor::getParameter — Возвращает значение параметра
    • XsltProcessor::getSecurityPrefs — Get security preferences
    • XSLTProcessor::hasExsltSupport — Определяет имеет ли PHP поддержку EXSLT
    • XSLTProcessor::importStylesheet — Импортирует таблицу стилей
    • XSLTProcessor::registerPHPFunctions — Включает возможность использовать PHP функции в качестве функций XSLT
    • XSLTProcessor::removeParameter — Удаляет параметр
    • XSLTProcessor::setParameter — Устанавливает значение параметра
    • XSLTProcessor::setProfiling — Устанавливает файл для профилирования
    • XsltProcessor::setSecurityPrefs — Set security preferences
    • XSLTProcessor::transformToDoc — Преобразовует в DOMDocument
    • XSLTProcessor::transformToUri — Преобразует в URI
    • XSLTProcessor::transformToXML — Преобразует в XML

User Contributed Notes

Jaroslaw Zabiello 23-Jun-2011 07:10
This is more usefull, no files needed, it just takes XML and XSL strings as input parameters and returns transformed XML

<?php
/**
 * @param  $xml
 * @param  $xsl
 * @return string xml
 */
function transform($xml, $xsl) {
   $xslt = new XSLTProcessor();
   $xslt->importStylesheet(new  SimpleXMLElement($xsl));
   return $xslt->transformToXml(new SimpleXMLElement($xml));
}
?>
sudhir dot vis at gmail dot com 25-Apr-2009 11:40
Here is a simplest way to transform the xml from php

<?php
$sXml  = "<xml>";
$sXml .= "<sudhir>hello sudhir</sudhir>";
$sXml .= "</xml>";

# LOAD XML FILE
$XML = new DOMDocument();
$XML->loadXML( $sXml );

# START XSLT
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load( 'xsl/index.xsl', LIBXML_NOCDATA);
$xslt->importStylesheet( $XSL );
#PRINT
print $xslt->transformToXML( $XML );
?>
allens at nospam dot com 19-Apr-2009 08:45
Problem:
Getting Netbeans error message:
Fatal error: Class 'xsltprocessor' not found

Solution:
place copy of php.ini in the c:\windows directory!

by default the php.ini file has xsl disabled......search for the line

;extension=php_xsl.dll

to enable XSL....remove ; so that the extension gets included

Then if Netbeans gives you the following message:
PHP Startup: Unable to load dynamic library './php_xsl.dll'

then you need to run the php-5.2.9-1-win32-installer.msi again
this time selecting the XSL extension!
visual77 at gmail dot com 20-Sep-2008 04:35
The XSLTProcessor is kind of a pain to use to generate an entire website, mostly due to the tedious process of building an XML tree through DOMDocument's createElement and appendChild functions.

To get an entire website out of nothing but XML and XSL (which really is a superior system to just echoing out the HTML), you could use an object that does all the PHP data structure to XML data tree conversion, and combines with the XSLTProcessor for rendering. A good object like this is DOMi, which you can find at http://domi.sourceforge.net.
emilise dot victor at gmail dot com 12-Mar-2008 08:10
Here is a way to get an output without using <xml:message> : use the var_dump function of php :
- First bind the php functions with
<? $xslt->registerPHPFunctions() ?>
and xmlns:php="http://php.net/xsl" in the stylesheet
- Then you can call the var_dump function like this : <xsl:variable name="a" select="php:function('var_dump', $return)" />

I couldn't find a way to call the function and have it really print the result without creating a variable, but well, it's just for debugging...
shangxiao at php dot net 10-Jan-2008 05:38
When using the DOM api to add xsl commands to your stylesheet dynamically, be sure to use createElementNS() rather than createElement() otherwise the XSLTProcessor will not recognise these DOM nodes.

Eg:
$xsl->createElementNS('http://www.w3.org/1999/XSL/Transform', 'xsl:element');
pb at online-magazin dot at 11-Oct-2007 03:13
Calling the Saxon XSLT Processor is a very esay task to do!

You just need to do some simple task

1. Install the JavaBridge for PHP

2. Download the freeware (B) Saxon distribution from http://saxon.sourceforge.net/

3. Put the jar files in a directory whre you have access

4. Use this sample of code

// Directory where the jar files are located
define("SAXON_DIR", $_SERVER['DOCUMENT_ROOT']."/saxonb8.9.0/");

// include the jars
java_require(SAXON_DIR."saxon8.jar;".SAXON_DIR."saxon8-dom.jar");

$sXslFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xsl"; // The xsl file
$sXmlFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xml"; // The xml file

try
{
  $oXslSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXslFile);
  $oXmlSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXmlFile);

  $oFeatureKeys = new JavaClass("net.sf.saxon.FeatureKeys");

  // Create the Factory
  $oTransformerFactory = new java("net.sf.saxon.TransformerFactoryImpl");

  //Disable source document validation
  $oTransformerFactory->setAttribute($oFeatureKeys->SCHEMA_VALIDATION, 4);

  // Create a new Transformer
  $oTransFormer = $oTransformerFactory->newTransformer($oXslSource);

  // Create a StreamResult to store the output
  $oResultStringWriter = new java("java.io.StringWriter");
  $oResultStream = new java("javax.xml.transform.stream.StreamResult", $oResultStringWriter);

  // Transform
  $oTransFormer->transform($oXmlSource, $oResultStream);

  // Echo the output from the transformation
  echo java_cast($oResultStringWriter->toString(), "string");

}
catch(JavaException $e){
   echo java_cast($e->getCause()->toString(), "string");
   exit;
}

5. Enjoy

This is working quite well.
Vasil Rangelov 21-Aug-2007 07:31
@basslines at gmail dot com
"
As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).
"

Using SAXON or AltovaXML by using their JAVA bindings could prove to be a difficult task to do, and .NET seems to be buggy (at least for me). However, I've made a class that uses SAXON or AltovaXML from the command line. AltovaXML could also be used with COM, provided it's registered as a COM component.

You can download my wrapper from:
http://xslt2processor.sourceforge.net/

I still need to implement a more graceful error handling (the way the XSL extension uses the Libxml functions), and once the bug
http://bugs.php.net/bug.php?id=41577
is fixed, I'll implement the .NET interfaces too.

I'll appreciate any feedback.
geoffreyj dot lee at gmail dot com 01-Jul-2007 11:02
Here are a couple useful tips for those who care about cross-browser compatibility.

Given:

<script type="text/javascript" src="test.js"></script>

XSLT will automatically condense it to:

<script type="text/javascript" src="test.js"/>

While this is good, Internet Explorer breaks on empty script tags. So, the simple solution is to add something to prevent an empty tag. For example:

<script type="text/javascript" src="test.js"><xsl:comment/></script>

Produces:

<script type="text/javascript" src="test.js">

</script>

------------------------

Also, here is a way to use IE's conditional comments:

<xsl:comment>[if gte IE 5]&#62;
&#60;link rel="stylesheet" type="text/css" href="ie.css" /&#62;
&#60;![endif]</xsl:comment>

Produces:

<!--[if gte IE 5]>
<link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

This will let you isolate IE-related CSS without needing to use ugly CSS hacks.
gabriel dot birke at web dot de 10-May-2007 03:19
Each <xsl:message> tag will generate a PHP error (level Warning). If you want to collect and pretty-print them, you could use a custom error handling function that collects the warnings in a static variable.
mnot at mnot dot net 08-May-2007 08:59
You can set an HTTP proxy for the XSLT document() function to use (as well as DTD external references) by setting http_proxy in the environment.

E.g., in Apache configuration;

SetEnv http_proxy http://127.0.0.1:3128/
Ryan D. Hatch 02-May-2007 01:14
Looking for php_xsl.dll?

If you installed on Windows using the MSI Installer - you may not have it.

1.) Add/Remove Programs and Change PHP Installation.  Select XSL Extension.

OR

2.) Download complete .zip file of PHP and you can copy php_xsl.dll into your PHP/etc directory.

Just a note.

Ryan D. Hatch
adrian at foeder dot de 14-Sep-2006 02:45
If you want to use the document()-function inside your XSL stylesheet, please note that you have to use an absolute path there.
Important for windows users: the absolute path *has* to be with forward slashes, so subsitute windows-path-backslashes to forward slashes before you transform the document.

Examples:
This will NOT work:
<xsl:copy-of select="document('test.xml')" />

This will also NOT work:
<xsl:copy-of select="document('c:\temp\test.xml')" />

But this WILL work:
<xsl:copy-of select="document('c:/temp/test.xml')" />
27-Apr-2006 06:26
Enable libxslt library, PHP 5, under windows:

To Enable:
In your php.ini
1. Uncomment ;extension=php_xsl.dll
2. Change extension_dir to
     extension_dir = "./ext"

To Confirm:
1. In a test.php page:
<?php phpinfo() ?>
2. Run test.php
3. Search for "libxslt Version". It should return a version number in a XSL headed table.

Further info Google
"Configuring and Testing PHP Servers for XSL Support"
Fabrice Bonny 30-Mar-2006 01:34
In response to how to use entities from DTD (internal or external) in XSLT. It works if you do this way:

$xsl = new DOMDocument;
$xsl->resolveExternals = TRUE;
$xsl->substituteEntities = TRUE;
$xsl->load(...);

Hope this helps! ;-)
basslines at gmail dot com 29-Mar-2006 10:07
As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).
17-Mar-2006 09:14
In response to appletalk at gmail dot com
<snip>
As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:
Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...
There're many ways to solve this:
.....
b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
   <!DOCTYPE xsl:stylesheet [
   <!ENTITY nbsp "&#160;" >
   ]>
.......</snip>
Just wanted to let people know that option b does NOT work. I'm not sure why this isn't implemented correctly, but it isn't, so don't waste your time. It's unfortunate the DOMXSL transform is so much less capable than the old xslt function.
olivier dot sow at alias dot france 05-Aug-2005 06:27
if you have 'XML parser error 4: not well-formed (invalid token)' error without but your are sure to do no error at all, try this:
<?
function
XSL_transformation($XMLFile,$XSLFile,$ResultFile,$xsl_params){

        $Str = '';

        $xp = xslt_create() or trigger_error('Could not create XSLT process.', E_USER_ERROR);

        xslt_set_encoding($xp, 'ISO-8859-1');

        // read the files into memory
        $xsl_string = join('', file($XSLFile));
        $xml_string = join('', file($XMLFile));

        // set the argument buffer
        $arg_buffer = array('/xml' => $xml_string, '/xsl' => $xsl_string);

        // process the two files to get the desired output
        if (($Str = xslt_process($xp, 'arg:/xml', 'arg:/xsl', NULL, $arg_buffer, $xsl_params))){

            //Saves transformation result into '$ResultFile'
            $fp = fopen($ResultFile,"w+");
            fwrite($fp,$Str);
            fclose($fp);

            return true;
        }

        return false;

    }
?>

found here: http://bugs.php.net/bug.php?id=16193
venkatesh at lammersmedical dot com 01-Mar-2005 06:17
Here is function to read from the XSL sheet which is saved as a text file.

function ReadExcelSheet($filename){
             $test=file($filename);
             $ar1=str_replace("~[^\t]*\t","\t",$test);
             $ar2=str_replace("~","",$ar1);
             $ar=str_replace("�","",$ar2);
             $temp=array();
             for ($i=0; $i<count($ar); $i++) {
                       if((substr($ar[$i],0,1)!= "\t")){
                           if($ar[$i]!=="\r\n"){
                           array_push($temp,$ar[$i]);
            }
        }
    }
    $name=split("\t",$temp[0]);
    $ExcelList=array();
    for($i=1;$i<count($temp);$i++){
        $split_result=split("\t",$temp[$i]);
        array_push($ExcelList,$split_result);
    }
    $result=insert_into_array($ExcelList,0,$name);
    return($result);
}
appletalk at gmail dot com 04-Feb-2005 10:32
As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:

Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...

There're many ways to solve this:
a) The hard way
<xsl:text disable-output-escaping="yes"> &amp;nbsp;</xsl:text>

b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
   <!DOCTYPE xsl:stylesheet [
    <!ENTITY nbsp "&#160;" >
    ]>

c) External Doctype
Just in case you want need other HTML entities, you can call an external doctype with the proper definitions

<!DOCTYPE page SYSTEM "http://gv.ca/dtd/character-entities.dtd">

Of course, you can download the file and place it in your server.
kekoajs at yahoo dot com 22-Dec-2004 02:07
Wow, I spent the better part of a day looking for how one could pass an entire test expression to an XSL stylesheet.  It seems that the XSLT 1.0 specification doesn't support it but PHP 5 (and maybe 4s) inclusion of  EXSLT allows one to do exactly that...

simply add these lines...

xmlns:dyn="http://exslt.org/dynamic"
extension-element-prefixes="dyn"

to the <xsl:stylesheet> element and when using an expression stored in a <xsl:param> element write

<xsl:if test="dyn:evaluate($param-name)">

and viola!  you can now use expressions generated externally in your stylesheet!

EXSLT adds many useful functions that can be integrated into your XSL in a similar fashion.  You can go to http://exslt.org/ to learn more...
rd at jerntorget dot se 24-Sep-2004 03:58
If you get the following warning message:

xsltApplyOneTemplate: _if_ was not compiled in (if can for example be apply-template or some other method), i've found that the problem seems to be an &nbsp; directly before the <xsl:if> or what ever is causing the problem.

One way to get thru the problem is to use span tags around &nbsp;  like : <span>&nbsp;</span>
jw at jwscripts dot com 06-Sep-2004 02:23
The following code is a wrapper to support calls to some of the old xslt_* functions:

<?

if (PHP_VERSION >= 5) {
    // Emulate the old xslt library functions
    function xslt_create() {
        return new XsltProcessor();
    }

    function xslt_process($xsltproc,
                          $xml_arg,
                          $xsl_arg,
                          $xslcontainer = null,
                          $args = null,
                          $params = null) {
        // Start with preparing the arguments
        $xml_arg = str_replace('arg:', '', $xml_arg);
        $xsl_arg = str_replace('arg:', '', $xsl_arg);

        // Create instances of the DomDocument class
        $xml = new DomDocument;
        $xsl = new DomDocument;

        // Load the xml document and the xsl template
        $xml->loadXML($args[$xml_arg]);
        $xsl->loadXML($args[$xsl_arg]);

        // Load the xsl template
        $xsltproc->importStyleSheet($xsl);

        // Set parameters when defined
        if ($params) {
            foreach ($params as $param => $value) {
                $xsltproc->setParameter("", $param, $value);
            }
        }

        // Start the transformation
        $processed = $xsltproc->transformToXML($xml);

        // Put the result in a file when specified
        if ($xslcontainer) {
            return @file_put_contents($xslcontainer, $processed);
        } else {
            return $processed;
        }

    }

    function xslt_free($xsltproc) {
        unset($xsltproc);
    }
}

$arguments = array(
    '/_xml' => file_get_contents("newxslt.xml"),
    '/_xsl' => file_get_contents("newxslt.xslt")
);

$xsltproc = xslt_create();
$html = xslt_process(
    $xsltproc,
    'arg:/_xml',
    'arg:/_xsl',
    null,
    $arguments
);

xslt_free($xsltproc);
print $html;

?>
rojaro 23-Jun-2004 07:43
If you're want to use XML from a variable e.g. $xmldata but the XSLT-StyleSheet from a file, you can do it also the following way:

<?php
$xslt = new xsltProcessor;
$xslt->importStyleSheet(DomDocument::load('filename.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($xmldata));
?>
XMLWriter::writeRaw
Введение
Обработка XML


Введение

XSL расширение реализует XSL стандарты, поведение » XSLT трансформации при использовании » библиотеки libxslt

User Contributed Notes

There are no user contributed notes for this page.
XSL
Установка и настройка
XSL


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
XSL


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

Это расширение использует libxslt, который может быть найден на » http://xmlsoft.org/XSLT/. Необходима версия libxslt 1.1.0, или выше.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

PHP 5 содержит расширение XSL по умолчанию. Расширение может быть активировано добавлением аргумента --with-xsl[=DIR] в строку конфигурации. DIR - путь установки libxslt.

User Contributed Notes

Manu 26-Jul-2009 02:12
On Windows, if you chose "Custom" during installation; you will need to run the installation again, select "Change" in the second screen. And in the "Choose Items to Install" Screen select extensions and drop-down-select "Entire feature will be installed on local harddrive". This installs and activates xsl.
Michael 11-Jun-2009 02:26
On some linux systems you might be able to simply do this:

sudo apt-get install php5-xsl

or similar.
bit 06-Jun-2009 07:00
If you want to activate this extension on Windows, uncomment ";extension=php_xsl.dll" in your php.ini file, and direct it to its respective folder. e.g. "extension=ext/php_xsl.dll"
Требования
Настройка во время выполнения
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

XSL_CLONE_AUTO (integer)
XSL_CLONE_NEVER (integer)
XSL_CLONE_ALWAYS (integer)
LIBXSLT_VERSION (integer)
версия libxslt формата 10117. Доступна с PHP 5.1.2.
LIBXSLT_DOTTED_VERSION (string)
версия libxslt формата 1.1.17. Доступна с PHP 5.1.2.
LIBEXSLT_VERSION (integer)
версия libexslt формата 813. Доступна с PHP 5.1.2.
LIBEXSLT_DOTTED_VERSION (string)
версия libexslt формата 1.1.17. Доступна с PHP 5.1.2.
XSL_SECPREF_READ_FILE (integer)
XSL_SECPREF_WRITE_FILE (integer)
XSL_SECPREF_CREATE_DIRECTORY (integer)
XSL_SECPREF_READ_NETWORK (integer)
XSL_SECPREF_WRITE_NETWORK (integer)

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
XSL


Примеры

Содержание

  • Файлы collection.xml и collection.xsl для примеров

User Contributed Notes

hipertracker at gmail dot com 28-Mar-2011 05:49
This is more convenient, no files nor verbose variables needed:

<?php
  $xslt = new XSLTProcessor();
  $xslt->importStylesheet(new SimpleXMLElement($xslt_string));
  echo $xslt->transformToXml(new SimpleXMLElement($xml_string));
?>
contato at log dot blog dot br 15-Oct-2008 05:43
Here's a very simple example on how to use PHP5 to transform a XML file using a XSL file.

<?php

   $xslDoc = new DOMDocument();
   $xslDoc->load("collection.xsl");

   $xmlDoc = new DOMDocument();
   $xmlDoc->load("collection.xml");

   $proc = new XSLTProcessor();
   $proc->importStylesheet($xslDoc);
   echo $proc->transformToXML($xmlDoc);

?>

For the sake of simplicity there's no error handling on this code. I hope this helps.
Предопределенные константы
Файлы collection.xml и collection.xsl для примеров
XSL


Файлы collection.xml и collection.xsl для примеров

Многие примеры в этом разделе документации содержат оба файла: XML и XSL. Мы будем использовать collection.xml и collection.xsl со следующим содержанием:

Пример #1 collection.xml

<collection>
 <cd>
  <title>Fight for your mind</title>
  <artist>Ben Harper</artist>
  <year>1995</year>
 </cd>
 <cd>
  <title>Electric Ladyland</title>
  <artist>Jimi Hendrix</artist>
  <year>1997</year>
 </cd>
</collection>

Пример #2 collection.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
 <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
 <xsl:template match="collection">
  Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection!
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="cd">
  <h1><xsl:value-of select="title"/></h1>
  <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
  <hr />
 </xsl:template>
</xsl:stylesheet>

User Contributed Notes

There are no user contributed notes for this page.
Примеры
XSLTProcessor
Примеры


Класс XSLTProcessor

(Информация о версии неизвестна, возможно, только в SVN)

Введение

Обзор классов

XSLTProcessor {
/* Методы */
string getParameter ( string $namespaceURI , string $localName )
public int XsltProcessor::getSecurityPrefs ( void )
bool hasExsltSupport ( void )
void importStylesheet ( object $stylesheet )
void registerPHPFunctions ([ mixed $restrict ] )
bool removeParameter ( string $namespaceURI , string $localName )
bool setParameter ( string $namespace , string $name , string $value )
bool setProfiling ( string $filename )
public int XsltProcessor::setSecurityPrefs ( int $securityPrefs )
DOMDocument transformToDoc ( DOMNode $doc )
int transformToURI ( DOMDocument $doc , string $uri )
string transformToXML ( DOMDocument $doc )
}

Содержание

  • XSLTProcessor::__construct — Создаёт новый экземпляр класса XSLTProcessor
  • XSLTProcessor::getParameter — Возвращает значение параметра
  • XsltProcessor::getSecurityPrefs — Get security preferences
  • XSLTProcessor::hasExsltSupport — Определяет имеет ли PHP поддержку EXSLT
  • XSLTProcessor::importStylesheet — Импортирует таблицу стилей
  • XSLTProcessor::registerPHPFunctions — Включает возможность использовать PHP функции в качестве функций XSLT
  • XSLTProcessor::removeParameter — Удаляет параметр
  • XSLTProcessor::setParameter — Устанавливает значение параметра
  • XSLTProcessor::setProfiling — Устанавливает файл для профилирования
  • XsltProcessor::setSecurityPrefs — Set security preferences
  • XSLTProcessor::transformToDoc — Преобразовует в DOMDocument
  • XSLTProcessor::transformToUri — Преобразует в URI
  • XSLTProcessor::transformToXML — Преобразует в XML

User Contributed Notes

There are no user contributed notes for this page.
Файлы collection.xml и collection.xsl для примеров
XSLTProcessor::__construct
XSL


Создаёт новый экземпляр класса XSLTProcessor

XSLTProcessor
XSLTProcessor::getParameter
XSLTProcessor
PHP Manual

XSLTProcessor::__construct

(PHP 5)

XSLTProcessor::__construct — Создаёт новый экземпляр класса XSLTProcessor

Описание

XSLTProcessor::__construct() ( void )

Создаёт новый экземпляр класса XSLTProcessor.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Создаёт XSLTProcessor

<?php

$doc = new DOMDocument();
$xsl = new XSLTProcessor();

$doc->load($xsl_filename);
$xsl->importStyleSheet($doc);

$doc->load($xml_filename);
echo $xsl->transformToXML($doc);

?>

User Contributed Notes

Martin 04-Jun-2009 03:02
The example above is a bit confusing because it uses the same variable ($doc) for two different things. I would rather write

<?php

$xsl = new XSLTProcessor();
$xsldoc = new DOMDocument();
$xsldoc->load($xsl_filename);
$xsl->importStyleSheet($xsldoc);

$xmldoc = new DOMDocument();
$xmldoc->load($xml_filename);
echo $xsl->transformToXML($xmldoc);

?>

[ Editor's note - thiago AT php DOT net: This note has improvements from Matthieu ]
XSLTProcessor
XSLTProcessor::getParameter
XSLTProcessor


Возвращает значение параметра

XSLTProcessor::__construct
XsltProcessor::getSecurityPrefs
XSLTProcessor
PHP Manual

XSLTProcessor::getParameter

(PHP 5)

XSLTProcessor::getParameter — Возвращает значение параметра

Описание

string XSLTProcessor::getParameter ( string $namespaceURI , string $localName )

Возвращает параметр, если он раньше установлен с помощью XSLTProcessor::setParameter().

Список параметров

namespaceURI

Пространство имён URI параметра XSLT.

localName

Локальное имя параметра XSLT.

Возвращаемые значения

Значение параметра, или NULL, если оно не установлено.

Смотрите также

  • XSLTProcessor::setParameter() - Устанавливает значение параметра
  • XSLTProcessor::removeParameter() - Удаляет параметр

User Contributed Notes

There are no user contributed notes for this page.
XSLTProcessor::__construct
XsltProcessor::getSecurityPrefs
XSLTProcessor


Get security preferences

XSLTProcessor::getParameter
XSLTProcessor::hasExsltSupport
XSLTProcessor
PHP Manual

XsltProcessor::getSecurityPrefs

(PHP >= 5.4.0)

XsltProcessor::getSecurityPrefs — Get security preferences

Описание

public int XsltProcessor::getSecurityPrefs ( void )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
XSLTProcessor::getParameter
XSLTProcessor::hasExsltSupport
XSLTProcessor


Определяет имеет ли PHP поддержку EXSLT

XsltProcessor::getSecurityPrefs
XSLTProcessor::importStylesheet
XSLTProcessor
PHP Manual

XSLTProcessor::hasExsltSupport

(PHP 5 >= 5.0.4)

XSLTProcessor::hasExsltSupport — Определяет имеет ли PHP поддержку EXSLT

Описание

bool XSLTProcessor::hasExsltSupport ( void )

Этот метод определяет был ли PHP сконфигурирован с » библиотекой EXSLT.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Проверка поддержки EXSLT

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
    die('EXSLT support not available');
}

// выполнение некоторых действий EXSLT ..

?>

User Contributed Notes

There are no user contributed notes for this page.
XsltProcessor::getSecurityPrefs
XSLTProcessor::importStylesheet
XSLTProcessor


Импортирует таблицу стилей

XSLTProcessor::hasExsltSupport
XSLTProcessor::registerPHPFunctions
XSLTProcessor
PHP Manual

XSLTProcessor::importStylesheet

(PHP 5)

XSLTProcessor::importStylesheet — Импортирует таблицу стилей

Описание

void XSLTProcessor::importStylesheet ( object $stylesheet )

Этот метод импортирует таблицу стилей в XSLTProcessor для трансформации.

Список параметров

stylesheet

Импортируемая таблица стилей в виде объекта DOMDocument или SimpleXMLElement.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

Версия | Описание
5.2.8 | Принимает SimpleXMLElement вновь, что было невозможно в версии PHP 5.2.6 и более поздних.

User Contributed Notes

mishak@mishak 16-Jun-2011 05:09
actually return value is bool, returns true on success and false on error.
kevin at metalaxe dot com 17-Nov-2007 03:26
Just for reference, as of this writing, this function does not support importing multiple stylesheets. The following will output only the stylesheet transformation of the second imported sheet:

<?php

# LOAD XML FILE
$XML = new DOMDocument();
$XML->load( 'data.xml' );

# START XSLT
$xslt = new XSLTProcessor();

# IMPORT STYLESHEET 1
$XSL = new DOMDocument();
$XSL->load( 'template1.xsl' );
$xslt->importStylesheet( $XSL );

#IMPORT STYLESHEET 2
$XSL = new DOMDocument();
$XSL->load( 'template2.xsl' );
$xslt->importStylesheet( $XSL );

#PRINT
print $xslt->transformToXML( $XML );
?>

This wasn't documented and quite dissapointing.
fcartegnie 21-Jul-2007 06:11
PHP5 xsl processor has a different behaviour than PHP4's one with CDATA sections. (see http://bugs.php.net/bug.php?id=29837)
Loaded XSL sheet CDATA sections does not allow, by default, output-escaping handling (everything in the CDATA is escaped by default).

So in this case you can't build your XSL Dom the usual way:
    $xsldom = DomDocument::loadXML(file_get_contents('sheet.xsl'));

and must go through this one (allowing LIBXML_NOCDATA parameter):
    $xsldom = new DomDocument;
    $xsldom->load('sheet.xsl', LIBXML_NOCDATA);

Then the CDATA output-escaping behaviour will be correct.
diesel at spbnet dot ru 19-Mar-2007 09:07
This is not a problem. You may set DOMDocument's documentURI property.
Something like this

<?php
$xsl = new DOMDocument('1.0','UTF-8');

$xsl->loadXML(file_get_contents('/foo/bar/somefile.xsl');
$xsl->documentURI = '/foo/bar/somefile.xsl';

$xslProc = new XSLTProcessor();
$xslProc->importStylesheet($xsl);
?>

and document('other.xsl') will work fine!
bbrosseau at gmail 01-Mar-2005 08:46
For those who wants to use external documents, it is important not to use the DomDocument::loadXML because the processor will not have the path to look for other files

So if you want to transform some xml with a pre-generated stylesheet $f:

<?php
$f = 'somestylesheet.xsl';
$xsl = DomDocument::loadXML(file_get_contents($f));
?>

document('other.xml') will not work with relative path and <?php $xsl = DomDocument::load($f); ?> will!
XSLTProcessor::hasExsltSupport
XSLTProcessor::registerPHPFunctions
XSLTProcessor


Включает возможность использовать PHP функции в качестве функций XSLT

XSLTProcessor::importStylesheet
XSLTProcessor::removeParameter
XSLTProcessor
PHP Manual

XSLTProcessor::registerPHPFunctions

(PHP 5 >= 5.0.4)

XSLTProcessor::registerPHPFunctions — Включает возможность использовать PHP функции в качестве функций XSLT

Описание

void XSLTProcessor::registerPHPFunctions ([ mixed $restrict ] )

Этот метод позволяет использовать PHP функции как функции XSLT в XSL таблицах стилей.

Список параметров

restrict

Используйте этот параметр, если хотите вызывать из XSLT только некоторые функции из.

Этот параметр может принимать либо строковое значение - название функции, либо массив - список названий.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Простой вызов функции PHP из таблицы стилей

<?php
$xml = <<<EOB
<allusers>
 <user>
  <uid>bob</uid>
 </user>
 <user>
  <uid>joe</uid>
 </user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
 <xsl:template match="allusers">
  <html><body>
    <h2>Users</h2>
    <table>
    <xsl:for-each select="user">
      <tr><td>
        <xsl:value-of
             select="php:function('ucfirst',string(uid))"/>
      </td></tr>
    </xsl:for-each>
    </table>
  </body></html>
 </xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);

$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>

Список изменений

Версия | Описание
5.1.0 | Был добавлен параметр restrict.

User Contributed Notes

Matthew, info at mathias-schaefer dot de 25-Nov-2010 08:34
=> there is no instance of your class needed, you have to take care about the namespace (using 5.3).

<!-- xsl:
<xsl:value-of select="php:function ('My\Name\Space\MyClassName::methodName',1+2)"/>
--->

<?php
namespace My\Name\Space;

   class MyClassName
   {
      static public function methodName($someArgument)
      {
         return "resultis:".$someArgument;
      }
   }
?>

<!-- result:
resultis:3
-->

=> no to-string conversion of the argument needed
=> returning numbers is also possible (maybe DOM nodes too)

Keep on hackin'
Demerit 10-Aug-2010 07:58
Let's get the terminology correct here, folks.

If you are calling a function that is residing within a class, reference it by its INSTANCE name, NOT its class name.

class.my_class.php:

<?php
class class_name {
static function function_name($in){
return ($out);
}
}
?>

calling_document.php:

<?php
require_once('class.my_class.php');
$instance_name=new class_name();
?>

my_xslt.xsl:

<xsl:value-of select="php:function ('instance_name::function_name','garbage')" />

BTW, in 5.1.6 double-colon (::) is the only thing that works when calling a function that resides within a class. However, you must declare your function as static. Using -> as some have suggested (e.g., php:function ('instance_name->function_name','garbage')) doesn't work at all, no matter how you declare your function.
Nic Luciano 22-Jul-2009 11:09
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."

Also note that the class function must be declared as static.
Ariz Jacinto 08-Jul-2008 02:21
If you want to use replace() function similar to XPath 2.0[1]  and you want to avoid a long XSLT function similar to this one[2], you can use PHP's str_replace() instead:

   <xsl:value-of select="php:functionString('str_replace','pattern', 'replacement' , . )">

Links:
  [1] http://www.w3.org/TR/2004/WD-xpath-functions-20041029/#func-replace
  [2] http://aspn.activestate.com/ASPN/Cookbook/XSLT/Recipe/65426

_
thsoft at vipmail dot hu 27-Dec-2007 02:22
Unfortunately, you can't pass arrays to PHP from XLST.
But you can pass an arbitrary number of arguments to a PHP function and then get them with func_get_args() as an array.
[There's no sense writing a function that is identical to the array() construct, because a function's return value is converted to a string when passed as an argument to another function. This means deep arrays cannot be handled this way.]
thsoft at vipmail dot hu 31-Jan-2007 03:20
The correct way to receive DOM nodes (let it be element, document, document fragment etc.) returned from PHP is to use <xsl:copy-of select="php:function...

I found the idea and an example here: http://bugs.php.net/bug.php?id=29409

For the technical details about the reason, see http://www.w3.org/TR/xslt#copy-of
phil at worldpoolfederation dot com 01-Dec-2006 03:22
Not true

Use :: to call static functions
Use -> to call non static functions

You must define a function as static in php 5.1 to be able to call it statically.
mark at thirst dot org 10-Oct-2006 07:25
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."   This worked in 5.0.4 but no longer works in 5.1.6.
franp at free dot fr 02-Sep-2006 01:45
Note that if you want your output to validate against some xhtml dtd, you must add the following attribute to the xsl:stylesheet element of the xslt stylesheet :
exclude-result-prefixes="php".

Otherwise, you get an "invalid attribute xmlns:php" error.
taylorbarstow at that google mail thingy 26-May-2006 05:33
Add-on to my previous note (below) about returning nodesets to XSLT from PHP functions:

You don't have to return a DOMDocument, DOMElement works just as well.  Plus, retuning a DOMElement gets around the problem of discarding the root node which I discuss below and which is also touched on by "Ingram".
heinemann dot juergen at hjcms dot de 08-Mar-2006 02:23
You can find mor Examples at PHP Sources php-5.*/ext/xsl/tests
<?php

$xform = <<<EOT
<?xml version = '1.0' encoding = 'utf-8' ?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:php="http://php.net/xsl"
    xsl:extension-element-prefixes="php"
>
<xsl:output method="xml" indent="yes" encoding="utf-8" />
<xsl:namespace-alias stylesheet-prefix="php" result-prefix="xsl" />
<xsl:template match="root">
<html>
<head>
    <title>Dateformat</title>
</head>
<body>
<xsl:for-each select="datenode">
    <li>
        <xsl:value-of select="php:functionString('convertDate', . )" />
    </li>
    </xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
EOT;

function convertDate( $i )
{
    setlocale( LC_TIME, 'de_DE' );
    return utf8_encode( strftime( '%B %d %A %Y %H:%M:%S CET', $i ) );
}

$xsl = new XSLTProcessor;
$xsl->registerPHPFunctions();
$xsl->setParameter( 'DOCTYPE', 'PUBLIC', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' );
$xsl->setParameter( 'html', 'xmlns', 'http://www.w3.org/1999/xhtml' );

$xdom = new DomDocument( '1.0', 'utf-8' );
$xdom->loadXML( $xform );

$xsl->importStyleSheet( $xdom );
unset( $xdom );

$dom = new DomDocument( '1.0', 'utf-8' );
$r = $dom->appendChild( $dom->createElement( 'root' ) );
foreach ( range( 1, 12 ) AS $i ) {
    $r->appendChild( $dom->createElement( 'datenode', mktime( date('G'), date('i'), date('s'), $i, date('d'), date('Y') ) ) );
}

header( "Content-Type: text/html; charset=utf-8;" );
header( "Content-Encoding: utf-8" );
echo $xsl->transformToXML( $dom );

?>
Ingram 28-Feb-2006 12:33
Upon testing returning of a nodeset contributed by

taylorbarstow at that google mail thingy

(which works excellently, TY!)

I found that with using:

===
"Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" /> "
===

I could only output the text and not any of the tags after applying templates - i.e. it stripped all elements around text.

Instead using:

===
<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
     <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.
===

Worked fine and allowed me to apply-templates without problem on the returned nodeset.
hopeseekr at gmail dot com 01-Feb-2006 12:17
One of the peskiest things I had problems with was encoding URL parameters.  I mean, pretend you want to populate a link with "search+terms" instead of just "search terms".  I was including two seperate URLs in the XML and that was ludicrous.

Below is a far more elegant PHP+XSLT solution.  You will also see it uses two *undocumented* features of registerPHPFunctions(), namely php:functionString() and the passing of parameters to the function.  I figured this out by trial and error; I really hope this note helps you as it *greatly* expands the power of php functions in XSLT!

<?php
/* --- XML input --- */
<search_results>
   <query>concert tickets</query>
</search_results>

/* --- XSL code --- */
<!-- Display query -->
<xsl:template match="search_results">
   <!-- Get URL-encoded string via PHP -->
   <xsl:variable name="safeurl" as="xs:string" select="php:functionString('urlencode', query)" />
   <p>Your search for <em><xsl:value-of select="query"/></em> can be continued at <a href="http://www.tixtix.com/search.php?q={$safeurl}">our search engine</a></p>
</xsl:template>

/* --- XHTML output --- */
<p>Your search for <em>concert tickets</em> can be continued at <a href="http://www.tixtix.com/search.php?q=space+cowboy">our search engine</a></p>
?>

Cool, huh?
taylorbarstow at that google mail thingy 01-Dec-2005 07:14
From a PHP function, you can pass a nodeset back to XSL using a DOMDocument.  For example:

<?php

function getNodeSet() {
   $xml =
       "<test>" .
       "<a-node>This is a node</a-node>" .
       "<a-node>This is another node</a-node>" .
       "</test>";
   $doc = new DOMDocument;
   $doc->loadXml($xml);
   return $doc;
}

?>

The only problem I've found is that the root level node in your returned DOM document acts like the root level node of your original.   SO, it's easy to introduce an infinite loop like so:

<xsl:template match="/">
   <xsl:apply-templates select="php:function('getNodeSet')" />
</xsl:template>

To avoid this, I've been using a construct like:

<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
      <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.  Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" />
Ritch at Bugsoftware dot co dot uk 22-Jun-2005 03:18
If you wish to use a function from inside a class use the double colon (::) notation, for example;

php:functionString('classname::function')

The funtion is fired off as a static and as such acts like a function in the global namespace.
benbarnett 04-Mar-2005 04:34
You can use the php:functionString() in the XSL, which will automatically convert output to a string!
zac at zacbowling dot com 27-Oct-2004 01:48
One thing I have told a lot of people to do if they are having
issues with this function is to check for any 'xmlns' attributes
that get generated and added to your xml pages by some
types of popular software.

<?php
$file = "http://data.map***.net/m***ck.asmx/GetMessages?IMEI=$id";

$docxml = file_get_contents($file);

//You may have to do something like this where
//I remove any instance of xmlns tags that get
//returned by my ASP.NET SOAP responses.

$docxml =
 str_replace("xmlns=\"http://data.map***.net/m***ck.asmx?WSDL\"",
  "",$docxml);

$xslt = new xsltProcessor;

//You don't remove them then this function will blow up.
$xslt->registerPHPFunctions();
$xslt->importStyleSheet(DomDocument::load('../xsl/message.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($docxml));

?>

Also a few cool tricks with this function is that you can call
built in PHP functions. For example:

<xsl:value-of
  select="php:function('nl2br',string(MessageContent/Message))"
  disable-output-escaping="yes"/>

That XSL value will now return your normal string but replace
all your new line charactors in your xml with '<br />'s.

Also note the 'disable-output-escaping="yes"' statement. If
you don't call this, then the output of that bind will be ran
thru basicly a "htmlencode()" type function.

Last but not least, take a look at the 'string()' function I
called in XSL before passing it back. That is because without
calling that, when it runs it will try and pass the node object,
and not its value (which is what you most likely only want).

This function is very awsome and could lead to some very
interesting code development. Skins could be loaded
remotely. You could write an RSS viewer in PHP without much
code. You could parse XHTML pages into another view (either
localy or remotely). Then you can take that same XML
content and throw it against ASP.NET, Java, or even a
command line processing tool using that same exact XSL
style sheet and generate the front ends for you page without
much change. I'm very excited.

Happy codding.
junkmail at eighteyes dot com 08-Oct-2004 02:52
When writing a stylesheet that uses a callback function be sure to include a namespace declaration for php, as follows:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl" version='1.0'>
begemot at php dot com dot ua 28-Sep-2004 06:24
I think it help  your.
<?php

function dateLang () {
        return strftime("%A");
}

$xsl = new DomDocument();
$xsl->load("datetime.xsl");
$inputdom = new DomDocument();
$inputdom->load("today.xml");

$proc = new XsltProcessor();
$proc->registerPhpFunctions();

// Load the documents and process using $xslt
$xsl = $proc->importStylesheet($xsl);

/* transform and output the xml document */
$newdom = $proc->transformToDoc($inputdom);

print $newdom->saveXML();

?>

Here's the XSLT stylesheet, datetime.xsl, that will call that function:

<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<xsl:template match="/">
  <xsl:value-of select="php:function('dateLang')" />
</xsl:template>
</xsl:stylesheet>

And here's an absolute minimal XML file, today.xml, to pass through the stylesheet (although articles.xml would achieve the same result):

<?xml version="1.0" encoding="iso-8859-1" ?>
<today></today>
zac at zacbowling dot com 26-Aug-2004 09:48
One thing to note about this function. A lot of values need to be converted to a XSLT string using the "string()" function in XLS before you pass them to your functions, and when you return them make sure that if they are strings that you call the "strval()" in php before doing so. This saved me hours.

Hope that helps.

Zac Bowling
XSLTProcessor::importStylesheet
XSLTProcessor::removeParameter
XSLTProcessor


Удаляет параметр

XSLTProcessor::registerPHPFunctions
XSLTProcessor::setParameter
XSLTProcessor
PHP Manual

XSLTProcessor::removeParameter

(PHP 5)

XSLTProcessor::removeParameter — Удаляет параметр

Описание

bool XSLTProcessor::removeParameter ( string $namespaceURI , string $localName )

Удаляет параметр, если он установлен. Это позволяет процессору использовать значение в таблице стилей, установленное по умолчанию.

Список параметров

namespaceURI

Пространство имён URI параметра XSLT.

localName

Локальное название XSLT параметра.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Смотрите также

  • XSLTProcessor::setParameter() - Устанавливает значение параметра
  • XSLTProcessor::getParameter() - Возвращает значение параметра

User Contributed Notes

There are no user contributed notes for this page.
XSLTProcessor::registerPHPFunctions
XSLTProcessor::setParameter
XSLTProcessor


Устанавливает значение параметра

XSLTProcessor::removeParameter
XSLTProcessor::setProfiling
XSLTProcessor
PHP Manual

XSLTProcessor::setParameter

(PHP 5)

XSLTProcessor::setParameter — Устанавливает значение параметра

Описание

bool XSLTProcessor::setParameter ( string $namespace , string $name , string $value )
bool XSLTProcessor::setParameter ( string $namespace , array $options )

Устанавливает значение для одного или нескольких параметров, чтобы использовать в дальнейшем в преобразованиях XSLTProcessor. Если параметра нет в таблице стилей, то он будет проигнорирован.

Список параметров

namespace

Пространство имён URI параметра XSLT.

name

Локальное название параметра XSLT.

value

Новое значение параметра XSLT.

options

Массив пар name => value. Этот синтаксис доступен с PHP 5.1.0.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Изменение владельца перед преобразованием

<?php

$collections = array(
    'Marc Rutkowski' => 'marc',
    'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Настройка преобразования
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // добавление стилей xsl

foreach ($collections as $name => $file) {
    // Load the XML source
    $xml = new DOMDocument;
    $xml->load('collection_' . $file . '.xml');

    $proc->setParameter('', 'owner', $name);
    $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

Смотрите также

  • XSLTProcessor::getParameter() - Возвращает значение параметра
  • XSLTProcessor::removeParameter() - Удаляет параметр

User Contributed Notes

richard at aggmedia dot net 04-Mar-2009 07:47
Note that there is no way to remove a parameter from an XSLTProcessor unless you know its name, and there is no way (that I can find) to get a list of the current parameters.

This means that you cannot reuse an XSLTProcessor with different parameters unless you call XSLTProcessor->removeParameter() on every parameter, and to do that you need to know the names of all the currently set parameters.

I bumped into this because we were caching XSLTProcessors for reuse, and they were spitting out content based on phantom parameters (they were still there from previous uses).
Lennaert van der Linden 13-Feb-2008 06:28
The parameter will not be set if the value contains both single and double quotes. Instead a warning will be shown when transforming the document:

PHP Warning:  XSLTProcessor::transformToXml(): Cannot create XPath expression (string contains both quote and double-quotes)
brettz9 08-May-2007 08:27
It seems heinemann's usage is not correct and does not achieve the intended result.

This method's purpose is to change a global <xsl:param> value in the XSL stylesheet--not to change an attribute of any other element.  <xsl:param> basically lets you set up a stylesheet which can be customized (as from PHP) externally (without needing to tamper with the original XSL file).

Here's an example of usage (that will work):

Stylesheet:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="print_something" select="defaultstring"/>
    <xsl:template match="/mydoc">
        <p style="color:red;">Printed parameter: <xsl:value-of select="$print_something"/></p>
    </xsl:template>
</xsl:stylesheet>

Script:

<?php
$dom = new DOMDocument();
$xsl = new XSLTProcessor;
$xsl->setParameter( '', 'print_something', "Now I've overridden the default!");
$style = realpath( "./my_stylesheet.xslt" );
$dom->load($style);
$xsl->importStyleSheet($dom);
$dom->loadXML('<mydoc></mydoc>');

$out = $xsl->transformToXML( $dom );

var_dump( '<pre>',
    htmlentities( $out, ENT_QUOTES, 'utf-8' ),
    $xsl->getParameter('', 'print_something'),
'</pre>' );
?>

gives:

string(5) "

"
string(143) "<?xml version="1.0"?>
<p style="color:red;">Printed parameter: Now I've overridden the default!</p>
"
string(32) "Now I've overridden the default!"
string(6) "

"

Notice that at present adding a namespace will not work. The only option at present is to set the first parameter for namespace to an empty string (though you can add the prefix with colon to the second argument for name in order to set the parameter for a namespace-prefixed parameter name).

See http://bugs.php.net/bug.php?id=30622
OrionI 01-May-2007 07:19
After looking at this a little further (see http://bugs.php.net/bug.php?id=41248), it appears that it's a shortcoming of libxslt, not PHP, that prevents passing in DOMDocuments or DOMNodes as parameters.
Orion I 30-Apr-2007 08:46
I've been trying to pass in a DOMDocument object as a parameter so I can stuff a bunch of data into XML nodes, but it appears that this function is not capable of it. I was hoping to get it to work like it does in the .NET 2.0 framework. (See http://msdn2.microsoft.com/en-us/library/
system.xml.xsl.xsltargumentlist.addparam.aspx)
But after looking at the PHP 5.2.1 source code, /php-5.2.1/ext/xsl/xsltprocessor.c line 604-650, it appears that it's not possible to do so in PHP even though it appears that libxslt supports it (see http://xmlsoft.org/XSLT/html/libxslt-variables.html
#xsltParseGlobalParam)

In fact, if the parameters aren't exactly what's expected, you'll always get a warning like this:

Wrong parameter count for XSLTProcessor::setParameter()
heinemann dot juergen at hjcms dot de 07-Mar-2006 03:39
Example for how it works.

<?xml version = '1.0' encoding = 'utf-8' ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"
    indent="yes"
    encoding="ISO-8859-15"
    doctype-system = "-//W3C//DTD XHTML 1.0 Transitional//EN"
    doctype-public = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
/>
<xsl:template match="docs">
<html>
<head>
    <title>
        <xsl:text>Example</xsl:text>
    </title>
</head>
<body>
    <xsl:for-each select="block">
        <div>
            <xsl:value-of select="." />
        </div>
    </xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

------------------

<?php
$dom = new DomDocument( '1.0', 'utf-8' );
$xsl = new XSLTProcessor;
$xsl->setParameter( 'block', 'xmlns', 'http://www.w3.org/1999/xhtml' );

$style = realpath( "./my_stylesheet.xslt" );
$dom->load( $style );
$xsl->importStyleSheet( $dom );

$dom->loadXML( '<docs>
    <block>Howto set xhtml Transitional Namespaces width php</block>
    <block>see http://www.php.net</block>
</docs>' );

$out = $xsl->transformToXML( $dom );

var_dump( '<pre>',
    htmlentities( $out, ENT_QUOTES, 'utf-8' ),
    $xsl->getParameter( 'block', 'xmlns' ),
    $xsl->getParameter( 'docs', 'xmlns' ),
'</pre>' );

?>
Stoke A 11-Aug-2005 03:40
XSLTProcessor::removeParameter() won't work on parameters set via XSLTProcessor::setParameter(string namespace, array options) in 5.1+ -- they need to be set and removed one by one.
XSLTProcessor::removeParameter
XSLTProcessor::setProfiling
XSLTProcessor


Устанавливает файл для профилирования

XSLTProcessor::setParameter
XsltProcessor::setSecurityPrefs
XSLTProcessor
PHP Manual

XSLTProcessor::setProfiling

(PHP >= 5.3.0)

XSLTProcessor::setProfiling — Устанавливает файл для профилирования

Описание

bool XSLTProcessor::setProfiling ( string $filename )

Устанавливает файл для записи профилирующей информации во время обработки таблиц стилей.

Список параметров

filename

Путь к файлу, в который записывается профилирующая информация.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример вывода профилирующей информации

<?php
// Загрузка исходного XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Настройка преобразования
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // добавление стилей xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

Вышеприведенный код записывает следующую информацию в файл профилирования:

number               match                name      mode  Calls Tot 100us Avg

    0                   cd                                    2      3      1
    1           collection                                    1      1      1

                         Total                                3      4

User Contributed Notes

There are no user contributed notes for this page.
XSLTProcessor::setParameter
XsltProcessor::setSecurityPrefs
XSLTProcessor


Set security preferences

XSLTProcessor::setProfiling
XSLTProcessor::transformToDoc
XSLTProcessor
PHP Manual

XsltProcessor::setSecurityPrefs

(PHP >= 5.4.0)

XsltProcessor::setSecurityPrefs — Set security preferences

Описание

public int XsltProcessor::setSecurityPrefs ( int $securityPrefs )

Внимание

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

User Contributed Notes

There are no user contributed notes for this page.
XSLTProcessor::setProfiling
XSLTProcessor::transformToDoc
XSLTProcessor


Преобразовует в DOMDocument

XsltProcessor::setSecurityPrefs
XSLTProcessor::transformToUri
XSLTProcessor
PHP Manual

XSLTProcessor::transformToDoc

(PHP 5)

XSLTProcessor::transformToDoc — Преобразовует в DOMDocument

Описание

DOMDocument XSLTProcessor::transformToDoc ( DOMNode $doc )

Преобразовует исходный узел в DOMDocument применяя таблицу стилей, заданую с помощью метода XSLTProcessor::importStylesheet().

Список параметров

doc

Узел, который нужено преобразовать.

Возвращаемые значения

Возвращает DOMDocument или FALSE при ошибке.

Примеры

Пример #1 Преобразование в DOMDocument

<?php

// Загрузка исходного XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Настройка преобразования
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // добавление стилей xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

Результат выполнения данного примера:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

Смотрите также

  • XSLTProcessor::transformToUri() - Преобразует в URI
  • XSLTProcessor::transformToXml() - Преобразует в XML

User Contributed Notes

franp at free dot fr 30-Aug-2006 05:16
In most cases if you expect XML (or XHTML) as output you better use transformToXML() directly. You gain better control over xsl:output attributes, notably omit-xml-declaration.

Instead of :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$dom = $proc->transformToDoc($xml);
echo $dom->saveXML();

do use :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$newXml = $proc->transformToXML($xml);
echo $newXml;

In the first case, <?xml version="1.0" encoding="utf-8"?> is added whatever you set the omit-xml-declaration while transformToXML() take the attribute into account.
XsltProcessor::setSecurityPrefs
XSLTProcessor::transformToUri
XSLTProcessor


Преобразует в URI

XSLTProcessor::transformToDoc
XSLTProcessor::transformToXML
XSLTProcessor
PHP Manual

XSLTProcessor::transformToUri

(PHP 5)

XSLTProcessor::transformToUri — Преобразует в URI

Описание

int XSLTProcessor::transformToURI ( DOMDocument $doc , string $uri )

Преобразует исходный узел в URI, применяя таблицу стилей, которая установленна с помощью метода XSLTProcessor::importStylesheet().

Список параметров

doc

Документ для преобразоваия.

uri

Целевой URI для преобразования.

Возвращаемые значения

Возвращает количество записаных байтов, либо FALSE при ошибке.

Примеры

Пример #1 Преобразование в HTML файл

<?php

// Загрузка источника XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Настройка преобразования
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // добавление стилей xsl

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

Смотрите также

  • XSLTProcessor::transformToDoc() - Преобразовует в DOMDocument
  • XSLTProcessor::transformToXml() - Преобразует в XML

User Contributed Notes

jonbarnett at gmail dot com 13-Jul-2007 12:32
Sometimes you don't want to transform to a file, an XML string (because you're using text or html), or a DOMDocument.

To transform to standard output, you can use php://output

<?php
$proc->transformToURI($xml, 'php://output');
?>

To transform to a string (of HTML or text, instead of XML), you can use the above in conjunction with output buffering.
<?php
ob_start();
$proc->transformToURI($xml, 'php://output');
$outputString = ob_get_flush();
?>
XSLTProcessor::transformToDoc
XSLTProcessor::transformToXML
XSLTProcessor


Преобразует в XML

XSLTProcessor::transformToUri
XSLT (PHP 4)
XSLTProcessor
PHP Manual

XSLTProcessor::transformToXML

(PHP 5)

XSLTProcessor::transformToXML — Преобразует в XML

Описание

string XSLTProcessor::transformToXML ( DOMDocument $doc )

Преобразует исходный узел в строку, применяя таблицы стилей, которые установлены с помощью метода xsltprocessor::importStylesheet().

Список параметров

doc

Преобразуемый документ.

Возвращаемые значения

Результат преобразования, или FALSE при ошибке.

Примеры

Пример #1 Трансформация в строку

<?php

// Загрузка источника XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Настройка преобразования
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // добавление стилей xsl

echo $proc->transformToXML($xml);

?>

Результат выполнения данного примера:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

<h1>Fight for your mind</h1><h2>by Ben Harper - 1995</h2><hr>
<h1>Electric Ladyland</h1><h2>by Jimi Hendrix - 1997</h2><hr>

Смотрите также

  • XSLTProcessor::transformToDoc() - Преобразовует в DOMDocument
  • XSLTProcessor::transformToUri() - Преобразует в URI

User Contributed Notes

zweibieren at yahoo dot com 15-Sep-2010 11:15
Entities are omitted from the output with the code above.
The symptom was that &nbsp;
-- which should work with UTF-8 encoding --
did not even get to XSLTProcessor, let alone through it.
After too much hacking I discovered the simple fix:
set substituteEntities to true in the DOMDocument for the XSL file.
That is, replace the loading of the xsl document with

<?php
   $xsl = new DOMDocument;
   $xsl->substituteEntities = true;    // <===added line
   $xsl->load('collection.xsl');
?>

However, this fails when data entries have HTML entity references. (Some database entries may even contain user generated text.) libxml has the pedantic habit of throwing a FATAL error for any undefined entitiy. Solution: hide the entities so libxml doesn't see them.

<?php
function hideEntities($data) {
        return str_replace("&", "&amp;", $data);
}
?>

You could just add this to the example, but it is tidier to define a function to load data into a DOMDocument. This way you don't need entity declarations in catalog.xsl, either.

<?php
// Added function for  Example #1

/** Load an XML file and create a DOMDocument.
Handles arbitrary entities, even undefined ones.
*/
function fileToDOMDoc($filename) {
    $dom= new DOMDocument;
    $xmldata = file_get_contents($filename);
    $xmldata = str_replace("&", "&amp;", $xmldata);  // disguise &s going IN to loadXML()
    $dom->substituteEntities = true;  // collapse &s going OUT to transformToXML()
    $dom->loadXML($xmldata);
    return $dom;
}

// Compare with  Example #1 Transforming to a string

// Load the XML sources
$xml = fileToDOMDoc('collection.xml');
$xsl = fileToDOMDoc('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);

// transform $xml according to the stylesheet $xsl
echo $proc->transformToXML($xml); // transform the data
?>
michael dot weibel at tilllate dot com 03-Dec-2009 01:33
If you retrieve "false" from the transformToXML method, use libxml_get_last_error() or libxml_get_errors() to retrieve the errors.
Charlie Murder 29-Nov-2009 07:43
To prevent your xsl file from automatically prepending

<?xml version="1.0"?>

whilst keeping the output as xml, which is preferable for a validated strict xhtml file, rather specify output as

<xsl:output method="xml" omit-xml-declaration="yes" />
john 05-Feb-2008 11:09
If your xsl doesn't have <html> tags. The output will contain <?xml version="1.0"?>. To fix this you can add the following to your xsl stylesheet:

<xsl:output
method="html" />
smubldg4 at hotmail dot com 02-Oct-2007 08:58
How to fix:: *Fatal error: Call to undefined method domdocument::load()*

If you get this error, visit the php.ini file and try commenting out the following, like this:

;[PHP_DOMXML]
;extension=php_domxml.dll

Suddenly, the wonderfully simple example above works as advertised.
jeandenis dot boivin at gmail dot com 13-Mar-2007 04:59
$domTranObj = $xslProcessor->transformToDoc($domXmlObj);
$domHtmlText = $domTranObj->saveHTML();

Do fix the <meta> for valid XHTML but do not correctly end empty node like <br /> which ouput like this : <br></br>

Some browser note this as 2 different <br /> ...

To fix this use

$domTranObj = $xslProcessor->transformToDoc($domXmlObj);
$domHtmlText = $domTranObj->saveXML();
Thomas Praxl 22-Jan-2007 01:36
I noticed an incompatibility between libxslt (php4) and the transformation through XSLTProcessor.
Php5 and the XSLTProcessor seem to add implicit CDATA-Section-Elements.
If you have an xslt like

<script type="text/javascript">
foo('<xsl:value-of select="bar" />');
</script>

It will result in

<script type="text/javascript"><![CDATA[
foo('xpath-result-of-bar');
]]></script>

(at least for output method="xml" in order to produce strict xhtml with xslt1)

That brings up an error (at least) in Firefox 1.5 as it is no valid javascript.
It should look like that:

<script type="text/javascript">//<![CDATA[
foo('xpath-result-of-bar');
]]></script>

As the CDATA-Section is implicit, I was not able to disable the output or to put a '//' before it.

I tried everything about xsl:text disable-output-escaping="yes"

I also tried to disable implicit adding of CDATA with <output cdata-section-elements="" />
(I thought that would exclude script-tags. It didn't).

The solution:

<xsl:text disable-output-escaping="yes">&lt;script type="text/javascript"&gt;
  foo('</xsl:text><xsl:value-of select="bar" /><xsl:text disable-output-escaping="yes">');
            &lt;/script&gt;</xsl:text>

Simple, but it took me a while.
werner@mollentze 15-Aug-2006 01:53
The transformToXML function can produce valid XHTML output - it honours the <xsl:output> element's attributes, which defines the format of the output document.

For instance, if you want valid XHTML 1.0 Strict output, you can provide the following attribute values for the <xsl:output> element in your XSL stylesheet:

<xsl:output
method="xml"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" />
lsoethout at hotmail dot com 19-Feb-2006 02:35
The function transformToXML has a problem with the meta content type tag. It outputs it like this:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

which is not correct X(HT)ML, because it closes with '>' instead of with '/>'.

A way to get the output correct is to use instead of transformToXML first transformToDoc anf then saveHTML:

    $domTranObj = $xslProcessor->transformToDoc($domXmlObj);
    $domHtmlText = $domTranObj->saveHTML();
jlipps at mac 06-Jan-2005 08:05
transformToXML, if you have registered PHP functions previously, does indeed attempt to execute these functions when it finds them in a php:function() pseudo-XSL function. It even finds static functions within classes, for instance:

<xsl:value-of select="php:function('MyClass::MyFunction', string(@attr), string(.))" disable-output-escaping="yes"/>

However, in this situation transformToXML does not try to execute "MyClass::MyFunction()". Instead, it executes "myclass:myfunction()". In PHP, since classes and functions are (I think) case-insensitive, this causes no problems.

A problem arises when you are combining these features with the __autoload() feature. So, say I have MyClass.php which contains the MyFunction definition. Generally, if I call MyClass::MyFunction, PHP will pass "MyClass" to __autoload(), and __autoload() will open up "MyClass.php".

What we have just seen, however, means that transformToXML will pass "myclass" to __autoload(), not "MyClass", with the consequence that PHP will try to open "myclass.php", which doesn't exist, instead of "MyClass.php", which does. On case-insensitive operating systems, this is not significant, but on my RedHat server, it is--PHP will give a file not found error.

The only solution I have found is to edit the __autoload() function to look for class names which are used in my XSL files, and manually change them to the correct casing.

Another solution, obviously, is to use all-lowercase class and file names.
XSLTProcessor::transformToUri
XSLT (PHP 4)
XSLTProcessor


XSLT (PHP 4)

  • Введение
  • Установка и настройка
    • Требования
    • Установка
    • Настройка во время выполнения
    • Типы ресурсов
  • Предопределенные константы
  • XSLT (PHP 4) Функции
    • xslt_backend_info — Возвращает информацию о настройках, заданных при компиляции расширения (backend)
    • xslt_backend_name — Возвращает имя расширения
    • xslt_backend_version — Возвращает номер версии Sablotron
    • xslt_create — Создает новый XSLT-процессор
    • xslt_errno — Возвращает код ошибки
    • xslt_error — Возвращает сообщение об ошибке
    • xslt_free — Освобождение XSLT-процессора
    • xslt_getopt — Получение настроек заданного XSLT-процессора
    • xslt_process — Запуск XSLT преобразования
    • xslt_set_base — Установка базового URI для всех XSLT преобразований
    • xslt_set_encoding — Задание кодировки для разбора XML документов
    • xslt_set_error_handler — Задание обработчика ошибок для XSLT-процессора
    • xslt_set_log — Задание файла журнала для записи сообщений XSLT процессора
    • xslt_set_object — Задает объект, в котором будут реализованы callback-функции
    • xslt_set_sax_handler — Задает SAX обработчик для XSLT-процессора
    • xslt_set_sax_handlers — Задает SAX обработчики, которые будут вызваться после разбора XML докумнента
    • xslt_set_scheme_handler — Задает обработчики схемы для XSLT-процессора
    • xslt_set_scheme_handlers — Задает обработчики схемы для XSLT-процессора
    • xslt_setopt — Установка значений настроек XSLT-процессора

User Contributed Notes

There are no user contributed notes for this page.
XSLTProcessor::transformToXML
Введение
Обработка XML


Введение

Это PHP расширение предоставляет независимый от процессора API для XSLT преобразований. На данный момент поддерживается только библиотека Sablotron от Ginger Alliance. Планируется поддержка и других библиотек, таких как Xalan или libxslt.

XSLT (Extensible Stylesheet Language (XSL) Transformations) - язык для преобразований XML документов в другие XML документы. Это стандарт, описанный Консорциумом Всемирной Паутины (W3C). Информацию о XSLT и сопутствующих технологиях можно найти на » http://www.w3.org/TR/xslt.

Замечание: Это расширение отличается от sablotron расширения выпущенного для версий PHP ниже 4.1.0. На данный момент в PHP 4.1.0 поддерживается только новое расширение. Если нужна поддержка старых расширений, обращайтесь в списки рассылки PHP.

Замечание:

Это расширение было перемещено в репозиторий » PECL и больше не поставляется с PHP 5.0.0.

Замечание: Если требуется поддержка xslt в PHP 5, можно воспользоваться XSL расширением.

User Contributed Notes

There are no user contributed notes for this page.
XSLT (PHP 4)
Установка и настройка
XSLT (PHP 4)


Установка и настройка

Содержание

  • Требования
  • Установка
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
Введение
Требования
XSLT (PHP 4)


Требования

Для корректной работы этого расширения необходимо PHP расширение libxml. Это означает, что также необходима передача опции --enable-libxml , хотя неявно это уже сделано, так как поддержка libxml по умолчанию включена.

Это расширение использует библиотеки Sablotron и expat, которые можно найти по адресу » http://sablotron.sourceforge.net/. На ресурсе предоставлены исходные коды и двоичные файлы.

Для подключения добавьте в PHP 4 настройку --with-xslt .

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Установка
Установка и настройка


Установка

На Unix системах выполните configure с параметрами --enable-xslt --with-xslt-sablot . Sablotron библиотека должна быть установлена в директорию, в которой ваш компилятор сможет ее найти.

Убедитесь, что к Sablotron библиотеке подключены те же библиотеки, что и к PHP. Настройки конфигурации --with-expat-dir=DIR --with-iconv-dir=DIR могут вам помочь задать пути к этим библиотекам. Если будете обращаться за поддержкой, всегда упоминайте эти пути и есть ли другие установленные в системе версии этих библиотек. Естественно, указывайте все номера версий.

Предостережение

Убедитесь, что ваша Sablotron библиотека прилинкована к -lstdc++. В противном случае процедура конфигурирования потерпит неудачу, или PHP откажет при загрузке или запуске.

Замечание: Поддержка JavaScript E-XSLT
Если Sablotron библиотека скомпилирована с поддержкой JavaScript, необходимо задать еще один параметр: --with-sablot-js=DIR .

Замечание: Заметка для Win32 пользователей

Для работы этого расширения системной переменной Windows PATHдолжны быть доступны DLL-файлы. Чтобы узнать как этого достичь, обратитесь к разделу FAQ "Как добавить мою директорию с PHP в переменную Windows PATH". Хотя копирование DLL-файлов из директории PHP в системную папку Windows также решает проблему (потому что системная директория по умолчанию находится в переменной PATH), это не рекомендуется. Этому расширению требуются следующие файлы в переменной PATH: sablot.dll, expat.dll и iconv.dll

Для PHP <= 4.2.0, файл iconv.dll не требуется.

User Contributed Notes

There are no user contributed notes for this page.
Требования
Настройка во время выполнения
Установка и настройка


Типы ресурсов

Это расширение определяет ресурс XSLT процессора, возвращаемый функцией xslt_create().

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

XSLT_OPT_SILENT (integer)
Отключение всего протоколирования и сообщений об ошибках. Эта настройка относится ко всем серверам (backends) и, возможно, будет добавлена в будущем.
XSLT_SABOPT_PARSE_PUBLIC_ENTITIES (integer)

Дать указание Sablotron разбирать все общедоступные сущности. По умолчанию этого не делается.

XSLT_SABOPT_DISABLE_ADDING_META (integer)

Не добавлять мета-тэг "Content-Type" в HTML вывод. Умолчания для этой настройки задаются во время компиляции библиотеки Sablotron.

XSLT_SABOPT_DISABLE_STRIPPING (integer)
Запретить удаление пробелов (только для файлов с данными).
XSLT_SABOPT_IGNORE_DOC_NOT_FOUND (integer)
Не считать фатальными неразобранные документы (функция document()).
XSLT_SABOPT_FILES_TO_HANDLER (integer)
XSLT_ERR_UNSUPPORTED_SCHEME (integer)
Код возврата при ошибке обработчиков схемы.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
XSLT (PHP 4) Функции
XSLT (PHP 4)


XSLT (PHP 4) Функции

Содержание

  • xslt_backend_info — Возвращает информацию о настройках, заданных при компиляции расширения (backend)
  • xslt_backend_name — Возвращает имя расширения
  • xslt_backend_version — Возвращает номер версии Sablotron
  • xslt_create — Создает новый XSLT-процессор
  • xslt_errno — Возвращает код ошибки
  • xslt_error — Возвращает сообщение об ошибке
  • xslt_free — Освобождение XSLT-процессора
  • xslt_getopt — Получение настроек заданного XSLT-процессора
  • xslt_process — Запуск XSLT преобразования
  • xslt_set_base — Установка базового URI для всех XSLT преобразований
  • xslt_set_encoding — Задание кодировки для разбора XML документов
  • xslt_set_error_handler — Задание обработчика ошибок для XSLT-процессора
  • xslt_set_log — Задание файла журнала для записи сообщений XSLT процессора
  • xslt_set_object — Задает объект, в котором будут реализованы callback-функции
  • xslt_set_sax_handler — Задает SAX обработчик для XSLT-процессора
  • xslt_set_sax_handlers — Задает SAX обработчики, которые будут вызваться после разбора XML докумнента
  • xslt_set_scheme_handler — Задает обработчики схемы для XSLT-процессора
  • xslt_set_scheme_handlers — Задает обработчики схемы для XSLT-процессора
  • xslt_setopt — Установка значений настроек XSLT-процессора

User Contributed Notes

hentaidream at gmx dot de 07-Jul-2011 11:09
How to make a XSLT Side with function

<code>
<xsl:output method="xhtml"/>
  <xsl:template match="/">
    <html>
      <head><title>Ausgabe</title></head>
      <body>
        <xsl:apply-templates select="aktien/aktie"></xsl:apply-templates>
      </body>
    </html>

  </xsl:template>

  <xsl:template match="aktie">
     <xsl:if test="@isin">
       <xsl:value-of select="name" />
       <xsl:value-of select="fn:format-number(fn:sum(kurse/kurs/ausgabepreis) div fn:count(kurse/kurs), '##.00')" />
     </xsl:if>
  </xsl:template>

</xsl:stylesheet>
</code>
Jeroen 23-May-2008 11:51
In addition to the contibution of "tom at kornack dot com" about converting an Apple plist (iPhoto or iTunes library or other) into a more general XML format, I have tried to simplify his xsl file a little further:

<?xml version="1.0"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="no"/>
<!-- XSL file based on example on php.net by tom@kornack.com -->

<xsl:template match="dict">
  <xsl:for-each select="key">
    <xsl:variable name="n1" select="translate(.,' ','_')"/>
    <xsl:variable name="pName"><xsl:choose>
      <xsl:when test="string(number($n1))='NaN'">
        <xsl:value-of select="$n1"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="concat('_',$n1,'_')"/>
      </xsl:otherwise>
    </xsl:choose></xsl:variable>
    <xsl:element name="{$pName}">
      <xsl:apply-templates select="following-sibling::*[1]"/>
    </xsl:element>
  </xsl:for-each>
</xsl:template>

<xsl:template match="array">
  <xsl:for-each select="*"><xsl:element name="item">
    <xsl:attribute name="nr"><xsl:number/></xsl:attribute>
    <xsl:apply-templates select="."/>
  </xsl:element></xsl:for-each>
</xsl:template>

<xsl:template match="string|integer|real|date|data">
  <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="true|false">
  <xsl:value-of select="name()"/>
</xsl:template>

<xsl:template match="text()|@*">
</xsl:template>

</xsl:transform>
nicolas_rainardNOSPAM at yahoo dot fr 12-Jul-2007 10:27
The XSLTProcessor, when transforming a document, always resolves entities.
To avoid this (if you want to keep HTML entitities by ex.), you have two solutions:

- if you have full control over the input document, you can encapsulate every text element which contains entities in a CDATA section.

- the previous solution is the smarter and the less computing intensive, but it is not always possible. In other cases, what you can do is to replace every occurence of '&' (entity mark) by something which will be considered as normal text by the parser (let's say '[AMP]' by ex) in the input document before the transformation. After the transformation, you can get these entitites back in the output document by reversing the previous operation.

<?php

$xml = $input_dom->saveXML();
$xml = str_replace('&', '[AMP]', $xml);
$input_dom->loadXML($xml);

$xml = $xsl->transformToXML($input_dom);
$xml = str_replace('[AMP]', '&', $xml);
$output_dom->loadXML($xml);

?>

Warning : this second method "escapes" ALL entities, even those you wouldn't want to be escaped. This is a raw explanation, fine-tune it to your own situation.
armencho at gmail dot com 21-Dec-2006 07:34
I believe the xslt_process and its URI resolving behaviour, including the xslt_set_base function are violating the XSLT specification which states:

<blockquote>

3.2 Base URI

Every node also has an associated URI called its base URI, which is used for resolving attribute values that represent relative URIs into absolute URIs. If an element or processing instruction occurs in an external entity, the base URI of that element or processing instruction is the URI of the external entity; otherwise, the base URI is the base URI of the document. The base URI of the document node is the URI of the document entity. The base URI for a text node, a comment node, an attribute node or a namespace node is the base URI of the parent of the node.

</blockquote>

This implies that if stylesheet file A contains a <xsl:import href="../B.xsl" /> and stylesheet file B contains a <xsl:import href="../C.xsl" />, given that all physical paths are valid, no matter which base you set up for the XSLT extension (with xslt_set_base) the processor WILL FAIL. Simply because it uses a single base path for all its processing regardless of the context (importing file) which includes/imports. This is a violation of the above part of the specification quoted above.

And it makes it very difficult to program XSLT with PHP.
Roman 06-Aug-2006 03:18
bat at flurf, you said that Sablotron implements XSLT 1.1, but according to its makers, "Sablotron is ...implementing XSLT 1.0, DOM Level2 and XPath 1.0" [http://www.gingerall.org/sablotron.html]
bat at flurf dot net 27-Mar-2006 04:40
maurits says that libxslt should be preferred over Sablotron, but I disagree.  libxslt only implements a fraction of the capabilities of Sablotron; in particular, this doesn't work in libxslt:

    <xsl:variable name="x">
      <a>One</a>
      <a>Two</a>
      <a>Three</a>
    </xsl:variable>

    <xsl:for-each select="$x/a">
      <xsl:value-of select="."/>
    </xsl:for-each>

In Sablotron, which implements XSLT 1.1, this works fine.  In libxslt's version, XSLT 1.0, a variable is a "result tree fragment", not a nodeset, and you are arbitrarily not allowed to do as much with it.

Further, Sablotron allows callbacks via the document() function (see information on xslt_set_scheme_handler()) and appears to give /slightly/ more informative error messages -- they identify the line number in the XSLT file at least.

In general, I can't recommend libxslt, which appears very underpowered.  Sablotron is considerably more impressive.
gabriel a-t bumpt do-t net 04-Feb-2006 02:50
If you need to transform an XML document that specifies the URL of its own prefered stylesheet (using the processing instruction <?xml-stylesheet href="xyz.xsl"?>, you can start by parsing the XML data to retrieve that URL, and then call the xslt_process function using the specified stylesheet :

<?php

/* A small class for stylesheet URL extraction from an XML */

class XMLStylesheet
{
    var $hParser;
    var $xml;
    var $stylesheet;

    function XMLStylesheet($filename)
    {
        $this->hParser = xml_parser_create();
        xml_set_object($this->hParser, $this);
        xml_set_processing_instruction_handler($this->hParser, 'fnProcessingInstruction');
        $this->xml = file_get_contents($filename);
        xml_parse($this->hParser, $this->xml, true);
        xml_parser_free($this->hParser);
    }

    function getStylesheet()
    {
        return $this->stylesheet;
    }

    function fnProcessingInstruction($hParser, $target, $data)
    {
        if($target == 'xml-stylesheet')
        {
            ereg('href="([^"]+)"', $data, $regs);
            $this->stylesheet = $regs[1];
        }
    }
}

/* Now, instanciate an object of this class, given the filename of our XML data */
$xml = new XMLStylesheet('my_data.xml');

/* And finally, retrieve the URL of the stylesheet specified in the XML data. */
$xsl_url = $xml->getStylesheet());

/* Now you can xslt_process as usual. */

?>
maurits at example dot com 05-Dec-2005 03:47
I tried to get Sablotron runnning on a Windows XP - Apache 2 -PHP5 System which is my developement system. I have Sablotron running on a life Linux server. After spending lots of  effort I gave up on Sablotron on Windows.

Then I found out that there is Libxslt, and it is allready working!

I am missing a hint on this page, that Sablotron is not really recommended any more and that people should start to migrate their code to Libxslt.
Jon Dawson 15-Jun-2005 01:23
Getting XSLT running under Red Hat/Plesk 7.5

The PHP installation on my VPS came with '--enable-xslt=shared' '--with-xslt-sablot' '--with-sablot-js=/usr' in the config line. However could not get any transformations to run. Finally got there following these steps:

1. ran 'yum install php-xslt'
2. This installed 'xslt.so' to usr/lib/php4 and other dependencies.
3. Add 'dl('xslt.so');' to the top of your php files you want to perform a translation in. e.g.

dl('xslt.so');
// Allocate a new XSLT processor
$xh = xslt_create();
// Process the document, returning the result into the $result variable
$result = xslt_process($xh, 'test.xml', 'test.xsl');
// Output to browser
echo $result;
Pete Silvester 13-Apr-2005 08:50
When installing on debian using apt/binaries, after installing php4-xslt and sablotron, you may have to add this line to /etc/php4/apache/php.ini :

extension=xslt.so
arossato at istitutocolli dot org 28-Aug-2004 01:12
It is possible to create the xslt extension as a shared object module statically linked with salbot and expat (I needed it for a project hosted in sourceforge where the sablot library is available).
Compile the module as usual:
cd ext/xslt
phpize
./configure --enable-module=so --enable-xslt=shared --with-xslt-sablot --with-expat
make

Then create a statically linked module:
gcc -Wl,-Bstatic -shared  xslt.lo sablot.lo  -o xslt.so  /usr/local/lib/libsablot.a /usr/local/lib/libexpat.a --static-libgcc

change /usr/local/lib/libsablot.a and /usr/local/lib/libexpat.a according to the right path on your system.

You're done!
My xslt.so is 5.2M...
tom at kornack dot com 24-Aug-2004 03:09
If you're wrangling with a plist in Mac OS X: here a bit of code to convert the plist into xml using xslt and then accessing it using simplexml. This was modified from http://www.xmldatabases.org/WK/blog/1086?t=item . Please do post improvements. This has been tested against iPhoto's AlbumData as well as iTunes' data. Enjoy!

<?php
$xsl = new DomDocument();
$xsl->load("plistConvert.xsl");
$inputdom = new DomDocument();
$inputdom->load("iTunes Music Library.xml");
$proc = new XsltProcessor();
$proc->registerPhpFunctions();
$xsl = $proc->importStylesheet($xsl);
$newdom = $proc->transformToDoc($inputdom);
$sxe = simplexml_import_dom($newdom);
print('<pre>');
print_r($sxe->dict);
print('</pre>');
?>

Here's the plistConvert.sxl file:

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl  ="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/plist">
  <propertylist>
    <xsl:apply-templates/>
  </propertylist>
</xsl:template>

<xsl:template match="dict">
  <dict>
    <xsl:for-each select="key">
      <xsl:variable name='n1' select='translate(., " ", "_")'/>
      <xsl:variable name='pName'>
        <xsl:choose>
            <!-- Need to do this because number tags like <0> are not valid?! -->
          <xsl:when test='contains("0123456789", substring($n1, 1, 1))'>
            <xsl:value-of select='concat("number_", $n1)'/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select='$n1'/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:variable>

      <xsl:element name="{$pName}">
        <xsl:for-each select='following-sibling::*[1]'>
          <xsl:choose>
            <xsl:when test='name() = "dict"'>
              <xsl:apply-templates select='.'/>
            </xsl:when>

            <xsl:when test='name() = "array"'>
              <xsl:attribute name="array">collection</xsl:attribute>
              <xsl:apply-templates/>
            </xsl:when>

            <xsl:when test='name() = "string"'>
              <xsl:value-of select='.'/>
            </xsl:when>

            <xsl:when test='name() = "integer"'>
<!--              <xsl:attribute name="type">integer</xsl:attribute> -->
              <xsl:value-of select='.'/>
            </xsl:when>

            <xsl:when test='name() = "date"'>
<!--              <xsl:attribute name="type">date</xsl:attribute> -->
              <xsl:value-of select='.'/>
            </xsl:when>

            <xsl:when test='name() = "true"'>True</xsl:when>
            <xsl:when test='name() = "false"'>False</xsl:when>
            <xsl:when test='name() = "real"'>
              <xsl:value-of select='.'/>
            </xsl:when>
            <xsl:when test='name() = "data"'>
              <xsl:value-of select='.'/>
            </xsl:when>

            <xsl:otherwise>
              <xsl:message>pListConverter: <xsl:value-of select='name()'/> not implemented!
              </xsl:message>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:for-each>
      </xsl:element>
    </xsl:for-each>
  </dict>
</xsl:template>

<!-- don't pass text thru -->
<xsl:template match="text()|@*">
</xsl:template>

</xsl:stylesheet>
will at NOSPAM dot wdp dot ndo dot co dot uk 16-Nov-2003 02:09
As an update to the previous advice about the undefined references problem when installing PHP with Sablotron, PHP 4.3.4 has a new EXTRA_LDFLAGS_PROGRAM line added to the Makefile. Make sure to add -lstdc++ to this line as well as the EXTRA_LDFLAGS line.
crtn at users dot sourceforge dot net 07-Jun-2003 09:41
Another way to get around the EXPAT-SABLOTRON problems (seg faults) is supposedly to recompile apache with:
--disable-rule=EXPAT
d dot brotherstone at pobox dot com 27-May-2003 09:14
If you get problems with undefined references to gxx_s type stuff, UPDATE LIBTOOL!  I found 1.4.1 worked for some configurations, 1.4.3 worked for almost none, but 1.5 worked for every combination of Sablotron/gettext/sybase/zlib/postgres --with options I tried.

Make sure you follow the advice of adding -lstdc++ to EXTRA_LD_FLAGS in Makefile after you've run ./configure, and BEFORE you've run make (if you issue make, you'll need to do a make clean before you make again, after changing the Makefile, or it still won't work reliably).

Cheers, Dave.
DrTebi at NOSPAM dot yahoo dot NOSPAM dot com 12-May-2003 09:37
I would like to add that there is no problem to install PHP with Sablotron on a Gentoo Linux system (http://www.gentoo.org).

Just make sure you emerged the expat and sablotron packages like so:

emerge expat
emerge sablotron

After this, there should be no linking problem or whatsoever:

./configure --with-xslt --with-sablotron
make

and you should be set ;-)
ohlesbeauxjours at yahoo dot fr 20-Mar-2003 12:18
In reply to Jaron, who needed to evaluate PHP code inside the stylesheet, look at a post I sent about xslt_set_scheme_handlers().
Scheme handlers are very useful, since they allow the XSLT engine and PHP to fully interact (they will communicate through XML strings).

With xslt_set_scheme_handlers(), you can give the XSLT engine an advanced access to the file system (or even to the other I/O interfaces), and perform various tasks (checking the existence of a file, creating new files "on the fly", deleting, etc...)
... all that in only one stylesheet :)

baptiste
aargh at 44rgh dot net 14-Oct-2002 03:47
Compilation on RedHat 7.0 PHP-4.1.2-7.0.4.
Compilation failed when providing --enable-xslt --with-xslt-sablot --with-sablot-js.
Problem was that an additonal flag needed to be specified or the build would fail complaining that js-libs ... could not be found.

LIBS="-lttf -lpng -ljpeg -lz -lnsl -ljs"; export LIBS

The additional flag "-ljs" needed to be set.
jw at shapers dot nl 27-Sep-2002 08:09
In addition to "tk dot lists at fastmail dot fm"'s comment on Windows dependencies: You'll also need iconv.dll in your SYSTEM32 folder. At least, that's what I needed to get it working on my PHP4.2.3-Win install.
gbarattoKILLSPAMMERS at superb dot net 18-Sep-2002 10:55
Regarding the `__gxx_personality_v0' problem described by dennisNOSPAM@infoleak.com, you have to use LDFLAGS=-lstdc++  as well before configuring php (and not apache) when compiling php as a shared object.

Thank you Dennis
matthias-at-mlienau.de 29-Aug-2002 05:52
For those guys who mess up with compiling the current Sablotron 0.95 sources from gingerall.com:

Here is a patch which corrects a typo.
Or - go to src/engine/domprovider.cpp and change "voiD" to "void" in line 558 and compile again...

*** domprovider.cpp.diff        Thu Aug 29 23:32:59 2002
--- domprovider.cpp     Thu Aug 29 23:32:14 2002
***************
*** 555,561 ****
    if (external) cdelete(external);
  }

! void DOMProviderUniversal::setExtProvider(DOMHandler *domh, voiD *data)
  {
    if (external) cdelete(external);
    if (domh)
--- 555,561 ----
    if (external) cdelete(external);
  }

! void DOMProviderUniversal::setExtProvider(DOMHandler *domh, void *data)
  {
    if (external) cdelete(external);
    if (domh)
dennisNOSPAM at infoleak dot com 22-May-2002 09:23
Building Sablotron on Solaris with.
gcc 3.0.3 and native linker
libtool (sunfreeware)
apache 1.3.24
php-4.2.1
sablotron-0.90
expat-1.95.2

When configuring Apache you might experience this error..

libsablot.so: undefined reference to `operator new[](unsigned)'
libsablot.so: undefined reference to `__cxa_call_unexpected'
libsablot.so: undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
libsablot.so: undefined reference to `operator delete(void*)'
libsablot.so: undefined reference to `__gxx_personality_v0'
libsablot.so: undefined reference to `vtable for __cxxabiv1::__class_type_info'
libsablot.so: undefined reference to `operator delete[](void*)'
libsablot.so: undefined reference to `vtable for __cxxabiv1::__vmi_class_type_info'
libsablot.so: undefined reference to `operator new(unsigned)'

To cure it make sure that during the configure stage you feed configure LDFLAGS variable like so.

LDFLAGS=' -lstdc++' ./configure

Otherwise Apache's compiler sanity check will balk.
ken1138 at altavista dot com 11-Jan-2002 02:15
The XSLT functions may experience conflicts with Apache in some configurations, causing random segfaults in httpd.  Apache has included a 'lite' version of expat in their recent distributions, which can cause conflicts with expat.  Apache1.3.22 solves the problem by configuring itself to use the expat you have installed, instead of the built-in. If you compiled Apache before you installed expat, make sure you upgrade and/or recompile your Apache server with the same version of expat that PHP and Sablotron are using.
Jaron dot Schaeffer at jayweb dot de 09-Jan-2002 01:25
I extended the example of Daniel Unterberger even more. I had the problem to evaluate PHP code within my xml data files (e.g. to output database results) and after that apply a xsl stylesheet to the generated data.

When I tried Daniel's solution I found it quite useful but noticed that you can't "print out" from your PHP Code. You're bound to annoying return()-Statements, wich makes it impossible to loop outputs or concatenate strings and then return them. If you try to do so, you will notice that a statement like
...
<php:eval>
  for($i=0; $i<10; $i++)
    echo "This is number ".$i;
</php:eval>
...

will result in PHP to do the output right in the moment when the eval()-Statement is run.

Things do, at least, work fine if you keep it simple:

...
<php:eval>
  return("Hello World!");
</php:eval>
...

I tried to fix that and came to a solution. The following code is just a snippet from my XSLT-class. The uppercase letters are constants defined in a header file. (e.g. define('PHP_EVAL_START_TAG', '<php:eval>');

...
 function xmlString() {

    $fd = fopen($this->xmlFileLocation, 'r');
    $xmlString = fread($fd, filesize($this->xmlFileLocation));
    fclose($fd);

    if($this->contentType == DYNAMIC_CONTENT) {

      while(!(strpos($xmlString, PHP_EVAL_START_TAG) === false)) {

    $startPos = strpos($xmlString, PHP_EVAL_START_TAG);
    $endPos   = strpos($xmlString, PHP_EVAL_END_TAG);

    ob_start();
    eval(substr($xmlString, $startPos + strlen(PHP_EVAL_START_TAG), $endPos - $startPos - strlen(PHP_EVAL_START_TAG)));
    $evaluatedString = ob_get_contents();
    ob_end_clean();

    $xmlString =
       substr($xmlString, 0, $startPos).$evaluatedString.substr($xmlString, $endPos + 11);
      }
    }

    return($xmlString);
  }
...

Jaron.Schaeffer@jayweb.de
sandro_zic at web dot de 27-Aug-2001 06:57
[Editor's note: moved this note here where it belongs - jmcastagnetto@php.net]

This shows how you can use the XSLT functions to add dynamic content to the result tree, i.e. how to hand over parameters to the XSL stylesheet and write to Sablotron's document buffer.

First we assign the value of the parameter to an array in PHP:
-----------------------------------------
$xslt_params["test"] = "Run-time parameter.";
-----------------------------------------

The parameter is envoced in XSL by
-----------------------------------------
<h1>Value of run-time parameter:</h1>
<b><xsl:value-of select="$test" /></b>
<hr/>
-----------------------------------------

Don't forget to define the parameter at the beginning of your stylesheet:
-----------------------------------------
<xsl:param name="test"/>
-----------------------------------------

How can we add dynamic content from a database to the XSLT output? In Sablotron, this is done using the document buffer function.

Retrieve a table's content, store it in a XML structure assigned to an array in PHP:
-----------------------------------------
$xslt_args["buffer1"] =
"
<TestBuffer>
    <Message>
        <Content>
        This is message 1 of buffer 1.
        </Content>
    </Message>
    <Message>
        <Content>
        This is message 2 of buffer 1.
        </Content>
    </Message>
</TestBuffer>
";
-----------------------------------------

This is how you add the buffer to the result tree in your XSL document:
-----------------------------------------
<h1>Dynamic content from document buffer 1:</h1>
<xsl:for-each select="document('arg:/buffer1')/TestBuffer/Message">
    <b><xsl:value-of select="Content" /></b><br/>
</xsl:for-each>
<hr/>
-----------------------------------------

To get the whole thing running, following functions have to be executed:
-----------------------------------------
$processor = xslt_create();
xslt_run ($processor, "file://".$DOCUMENT_ROOT.$xsl_file, "file://".$DOCUMENT_ROOT.$xml_file, "arg:/_result", $xslt_params, $xslt_args);
$result = xslt_fetch_result ($processor);
echo $result;
-----------------------------------------

The complete XSL file looks like this:
-----------------------------------------
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" version="1.0" standalone="yes" indent="yes" />

<!-- define parameter -->
<xsl:param name="test"/>

<xsl:template match="/">

<!-- run-time parameter -->
<h1>Value of run-time parameter:</h1>
<b><xsl:value-of select="$test" /></b>
<hr/>

<!-- dynamic content -->
<h1>Dynamic content from document buffer 1:</h1>
<xsl:for-each select="document('arg:/buffer1')/TestBuffer/Message">
    <b><xsl:value-of select="Content" /></b><br/>
</xsl:for-each>
<hr/>

</xsl:template>

</xsl:stylesheet>
-----------------------------------------
d dot u at mail dot com 13-Jun-2001 12:19
... addition to last message

sorry shanx (miss-spelled).
having a full example you must call it like in the shanx-example. Hint dont use echo inside of <php:eval> but return, because it is only string concatenation.

<code>
<?php
##  require "xslt.inc.php";

$xslt = new xsltTransform("life.xsl", "life.xml");
print ($xslt->applyTransformation());

?>
</code>
d dot u at mail dot com 13-Jun-2001 11:43
I extended the example of shanks (very helpful for me tnx), so you can call php inside your xslt file, I had the problem to pass url-parameters and did not understand how to solve it, so I use php.

<code>
<?php

/**
 *
 * A class to transform XML through XSLT using PHP4 Sablotron extension
 *
 */

 #######################################################################
 ## file extended by Daniel Unterberger (d.u@mail.com)
 ## changes: some  php:eval's added

class xsltTransform
{

    var $xsl_file;
    var $xml_file;
    var $fileName;

    /**
     * Constructor to the xsl_transform ticket
     *
     * @param $xsl_file The XSLT file containing the transformation info
     * @param $xml_file The XML file containing the actual data
     * @see readFile()
     */
    function xsltTransform($xsl_file = '', $xml_file = '')
    {
        $this->xsl_string = $this->readFile($xsl_file,'php:eval');
        $this->xml_string = $this->readFile($xml_file);
    }

    /**
     * Function to read through the file
     *
     * @param $fileName Which file to read?
     *
     */
    function readFile($fileName,$php_eval="")
    {
        // get contents of a file into a string
        $fd = fopen( $fileName, "r" );
        $content = fread( $fd, filesize( $fileName ) );
        fclose( $fd );

        ##################################################
        ## extension by Daniel Unterberger (d.u@mail.com)

        while ( $php_eval and ( $pos_start=strpos($content,'<php:eval>') ))
        {
          $pos_end=strpos($content,'</php:eval>');
          $content=substr($content,0,$pos_start).
                   eval( substr($content,$pos_start+10,$pos_end-$pos_start-10) ).
                   substr($content,$pos_end+11);
        }

        if ($GLOBALS["debug"]=="ON") print "<xmp>$content</xmp>";
            ## see xslt-file for debuggin if you call page.php?debug=ON (remove on life-server)

        ###################################################
        ## end extension

        return $content;

    }

    /**
     * Function to apply the actual transformation
     *
     */
    function applyTransformation()
    {
        $this->result = '';
        $this->msg = xslt_process($this->xsl_string, $this->xml_string, $this->result);
        if(!$this->msg) print ("Transformation failed.");
        return $this->result;
    }

// End of class, do not remove
}

?>
</code>

in the xslt you can call it now with

...
<tag><php:eval> return $GLOBALS["filter"]; /* all php allowed */ </php:eval></tag>
...

-------------------------------
hope this gives new inspiration
(d.u)
maximo at migliari dot com 27-Apr-2001 09:31
COMPILING AND INSTALLING SABLOTRON AND EXPAT FOR PHP ON A FREEBSD iServer

0) Prepare your virtual server environment.  Telnet to your iserver and type:
    mkdir -p ~/usr/local/apache/1.3/bin
    ln /usr/bin/make ~/usr/bin/make
    ln /usr/local/apache/1.3/bin/apxs ~/usr/local/apache/1.3/bin/apxs
    ln /usr/local/apache/1.3/bin/httpd ~/usr/local/apache/1.3/bin/httpd

1) download the following files:
    expat-1.95.tar.gz - http://expat.sourceforge.com
    Sablot-0.52.tar.gz - http://www.gingerall.com
    php4-latest.tar.gz - http://snaps.php.net

2) copy these files to ~/usr/local

3) expand all these files uing tar -xvzf

4) go into expat directory and type:
    ./configure --prefix=/usr/home/your_iserver_login_name/usr/local
    make
    make install

   the files will be installed under ~/usr/local/lib and ~/usr/local/include

5) set the following environment variables:
    setenv LD_LIBRARY_PATH /usr/home/your_iserver_login_name/usr/local/lib
    setenv LD_RUN_PATH /usr/home/your_iserver_login_name/usr/local/
    setenv CPLUS_INCLUDE_PATH /usr/home/your_iserver_login_name/usr/local/include
    setenv LIBRARY_PATH /usr/home/your_iserver_login_name/usr/local/lib

6) go into the Sablotron directory and type:
    ./configure --prefix=/usr/home/your_iserver_login_name/usr/local
    make
    make install

7) go into the php directory and type:
    ./configure --with-apxs=/usr/local/apache/1.3/bin/apxs \
    --disable-debug \
    --enable-trans-sid \
    --enable-versioning \
    --enable-ftp \
    --with-mysql=/usr/home/your_iserver_login_name/usr/local/mysql \
    --with-xml \
    --enable-magic-quotes \
    --enable-track-vars \
    --enable-sablot-errors-descriptive \
    --with-sablot=/usr/home/your_iserver_login_name/usr/local \
    --with-expat=/usr/home/your_iserver_login_name/usr/local

    then

    make
    and
    make install

the final command - make install - should give an error about not being able to install pear.
This is normal, as pear tries to copy itself outside of your virtual server space.  Since pear
is not an essential part of PHP - you can ignore this. (maybe there is a command for ./configure
in php that allows us to specify the directory in which pear will be installed?

8) final steps:
   go to ~/usr/local/etc/httpd/conf
   edit httpd.conf
   comment out the LoadModule directive for the previous php .so module.
   not that you should see the new module you just compile already inserted in the httpd.conf as
   the last line of all LoadModule directives. (it should be called libphp4.so

   now just go back to the command prompt after you have edited httpd.conf and type:
   restart_apache

   now go to your httpd document root (usually htdocs), and create a php file with the following
   code in it:

   <?php
     phpinfo();
   ?>

   load the file in your browser, and you should see that everything has been installed properly :)
Предопределенные константы
xslt_backend_info
XSLT (PHP 4)


Возвращает информацию о настройках, заданных при компиляции расширения (backend)

XSLT (PHP 4) Функции
xslt_backend_name
XSLT (PHP 4) Функции
PHP Manual

xslt_backend_info

(PHP 4 >= 4.3.0)

xslt_backend_info — Возвращает информацию о настройках, заданных при компиляции расширения (backend)

Описание

string xslt_backend_info ( void )

xslt_backend_info() получает информацию о настройках, заданных при компиляции расширения (backend).

Возвращаемые значения

Возвращает строку с информацией о настройках, заданных при компиляции расширения (backend), либо сообщение об ошибке, если подобной информации нет.

Смотрите также

  • xslt_backend_name() - Возвращает имя расширения
  • xslt_backend_version() - Возвращает номер версии Sablotron

User Contributed Notes

There are no user contributed notes for this page.
XSLT (PHP 4) Функции
xslt_backend_name
XSLT (PHP 4) Функции


Возвращает имя расширения

xslt_backend_info
xslt_backend_version
XSLT (PHP 4) Функции
PHP Manual

xslt_backend_name

(PHP 4 >= 4.3.0)

xslt_backend_name — Возвращает имя расширения

Описание

string xslt_backend_name ( void )

xslt_backend_name() получает имя расширения (backend).

Возвращаемые значения

Возвращает Sablotron.

Примеры

Пример #1 Пример использования xslt_backend_name()

<?php

echo xslt_backend_name(); // Sablotron

?>

Смотрите также

  • xslt_backend_info() - Возвращает информацию о настройках, заданных при компиляции расширения (backend)
  • xslt_backend_version() - Возвращает номер версии Sablotron

User Contributed Notes

There are no user contributed notes for this page.
xslt_backend_info
xslt_backend_version
XSLT (PHP 4) Функции


Возвращает номер версии Sablotron

xslt_backend_name
xslt_create
XSLT (PHP 4) Функции
PHP Manual

xslt_backend_version

(PHP 4 >= 4.3.0)

xslt_backend_version — Возвращает номер версии Sablotron

Описание

string xslt_backend_version ( void )

xslt_backend_version() получает номер версии Sablotron.

Возвращаемые значения

Возвращает номер версии или FALSE, если он недоступен.

Примеры

Пример #1 Пример использования xslt_backend_version()

<?php

echo xslt_backend_version(); // 0.98 например
?>

Смотрите также

  • xslt_backend_info() - Возвращает информацию о настройках, заданных при компиляции расширения (backend)
  • xslt_backend_name() - Возвращает имя расширения

User Contributed Notes

There are no user contributed notes for this page.
xslt_backend_name
xslt_create
XSLT (PHP 4) Функции


Создает новый XSLT-процессор

xslt_backend_version
xslt_errno
XSLT (PHP 4) Функции
PHP Manual

xslt_create

(PHP 4 >= 4.0.3)

xslt_create — Создает новый XSLT-процессор

Описание

resource xslt_create ( void )

Создает новый XSLT-процессор, используемый другими XSLT функциями, и возвращает его ресурс.

Возвращаемые значения

Возвращает ресурс XSLT-процессора или FALSE в случае ошибки.

Примеры

Пример #1 Пример использования xslt_create()

<?php
function xml2html($xmldata, $xsl)
{
    /* $xmldata -> ваш XML */
    /* $xsl -> XSLT файл */

    $path = 'include';
    $arguments = array('/_xml' => $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', "$path/$xsl", NULL, $arguments);

    if (empty($html)) {
       die('Ошибка при XSLT обработке: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}
?>

Смотрите также

  • xslt_free() - Освобождение XSLT-процессора

User Contributed Notes

LW 28-Aug-2008 01:41
Hello,

I changed the function from myadzel (?) a little bit, so that it now correctly uses either a file OR a string as parameter - WITHOUT producing PHP warnings. See here:

<?php
function xslt ($xml, $xsl) {

    $xh = @xslt_create();

    $args['xml'] = ( file_exists( $xml ) )?join ('', file ($xml)):$xml;
    $args['xsl'] = ( file_exists( $xsl ) )?join ('', file ($xsl)):$xsl;

    // try with a string
    $result = @xslt_process ($xh, 'arg:/xml', 'arg:/xsl', NULL, $args);

    // try with resource
    if (!$result) { $result = @xslt_process ($xh, $xml, $xsl); }

    @xslt_free ($xh);
    return $result;

}
?>

Examples:
echo xslt ('./index.xml', './index.xsl');
echo xslt ('<test><example>An example!</example></test>', './index.xsl');
sxguard-1trail(At)yahoo dot com 05-Jun-2008 08:12
Hardly can I find this. But, those required dll is not included in the package and no link for download.

It's a pitty that no discussion about this within php.net

  Note   to   Win32   Users:     In   order   to   enable   this   module   on   a   Windows   environment,   you   must   copy   several   files   from   the   DLL   folder   of   the   PHP/Win32   binary   package   to   the   SYSTEM32   folder   of   your   windows   machine.   (Ex:   C:\WINNT\SYSTEM32   or   C:\WINDOWS\SYSTEM32).   For   PHP   <=   4.2.0   copy   sablot.dll     and   expat.dll   to   your   SYSTEM32   folder.   For   PHP   >=   4.2.1   copy   sablot.dll,   expat.dll   and   iconv.dll   to   your   SYSTEM32   folder.
myadzel at gmail dot com 20-Mar-2007 08:26
All for a long time know about a problem xslt-transformation in php.
We shall try a trivial way, knowing, that xslt_process () accepts string or resources in it's parameters.

function xslt ($xml, $xsl) {

    $xh = @xslt_create();

    $args['xml'] = join ('', file ($xml));
    $args['xsl'] = join ('', file ($xsl));

    // try with a string
    $result = @xslt_process ($xh, 'arg:/xml', 'arg:/xsl', NULL, $args);

    // try with resource
    if (!$result) { $result = @xslt_process ($xh, $xml, $xsl); }

    @xslt_free ($xh);
    return $result;

}

For example: echo xslt ('./index.xml', './index.xsl');
Kerry Kobashi 28-Mar-2005 07:29
It should be noted that xslt_create() will return FALSE in the case of failure (Sablotron processor could not be created).

This, obtained from looking at the source code extension.
garth at webconexion dot net 18-Sep-2003 05:23
In order to pass PHP variables into an XSL document you need to do the following:

Firstly I created the following function to use:

function GetXHTML($sXML, $sXSL, $aParameters)
{
    $hXML = xslt_create();
    $aArguments = array('/_xml' => $sXML, '/_xsl' => $sXSL);
    $sXHTML = xslt_process($hXML, 'arg:/_xml', 'arg:/_xsl', NULL, $aArguments, $aParameters);
    xslt_free($hXML);
    return $sXHTML;
}

Then call it like thus, passing the XML and XSL as a string with the final parameter being an array which can contain as many values as you wish to pass in:

$sXHTML = GetXHTML($sXML, $sXSL, array("age"=>"26"));

Then in the XSL document you need the following:

<xsl:param name="age" />

Then where you want to display the value of age you do this:

<xsl:value-of select="$age" />

Thanks now.
xslt_backend_version
xslt_errno
XSLT (PHP 4) Функции


Возвращает код ошибки

xslt_create
xslt_error
XSLT (PHP 4) Функции
PHP Manual

xslt_errno

(PHP 4 >= 4.0.3)

xslt_errno — Возвращает код ошибки

Описание

int xslt_errno ( resource $xh )

Возвращает код последней ошибки, произошедшей в работе заданного XSLT процессора.

Список параметров

xh

Ресурс XSLT процессора, возвращаемый функцией xslt_create().

Возвращаемые значения

Возвращает целое число, соответствующее коду ошибки.

Смотрите также

  • xslt_error() - Возвращает сообщение об ошибке

User Contributed Notes

There are no user contributed notes for this page.
xslt_create
xslt_error
XSLT (PHP 4) Функции


Возвращает сообщение об ошибке

xslt_errno
xslt_free
XSLT (PHP 4) Функции
PHP Manual

xslt_error

(PHP 4 >= 4.0.3)

xslt_error — Возвращает сообщение об ошибке

Описание

string xslt_error ( resource $xh )

Возвращает строку, содержащую описание последней ошибки, произошедшей в процессе работы XSLT-процессора.

Список параметров

xh

Ресурс XSLT-процессора, возвращаемый функцией xslt_create().

Возвращаемые значения

Возвращает сообщение об ошибке в виде строки.

Примеры

Пример #1 Обработка ошибок с использованием функций xslt_error() и xslt_errno().

<?php

$xh = xslt_create();
$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
if (!$result) {
    die(sprintf("Невозможно преобразовать XSLT документ [%d]: %s",
                xslt_errno($xh), xslt_error($xh)));
}

echo $result;

xslt_free($xh);
?>

Смотрите также

  • xslt_errno() - Возвращает код ошибки

User Contributed Notes

mikes at ayeltd dot biz 05-Jan-2004 05:18
There may be cases where a null $result is legitimate, in this case add a test for non-zero xlst_errno:

<?php

$xh = xslt_create();
$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
if (!$result && xslt_errno($xh) > 0) {
   die(sprintf("Cannot process XSLT document [%d]: %s",
               xslt_errno($xh), xslt_error($xh)));
}

echo $result;

xslt_free($xh);
?>
xslt_errno
xslt_free
XSLT (PHP 4) Функции


Освобождение XSLT-процессора

xslt_error
xslt_getopt
XSLT (PHP 4) Функции
PHP Manual

xslt_free

(PHP 4 >= 4.0.3)

xslt_free — Освобождение XSLT-процессора

Описание

void xslt_free ( resource $xh )

Освобождает ресурс, занятый XSLT-процессором.

Список параметров

xh

Ресурс XSLT-процессора, возвращаемый функцией xslt_create().

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Смотрите также

  • xslt_create() - Создает новый XSLT-процессор

User Contributed Notes

There are no user contributed notes for this page.
xslt_error
xslt_getopt
XSLT (PHP 4) Функции


Получение настроек заданного XSLT-процессора

xslt_free
xslt_process
XSLT (PHP 4) Функции
PHP Manual

xslt_getopt

(PHP 4 >= 4.3.0)

xslt_getopt — Получение настроек заданного XSLT-процессора

Описание

int xslt_getopt ( resource $processor )

xslt_getopt() возвращает значения настроек XSLT-процессора processor.

Список параметров

processor

Ресурс XSLT-процессора, возвращаемый функцией xslt_create().

Возвращаемые значения

Возвращает значения настроек в виде битовой маски, созданной с помощью констант XSLT_SABOPT_XXX.

Смотрите также

  • xslt_setopt() - Установка значений настроек XSLT-процессора

User Contributed Notes

There are no user contributed notes for this page.
xslt_free
xslt_process
XSLT (PHP 4) Функции


Запуск XSLT преобразования

xslt_getopt
xslt_set_base
XSLT (PHP 4) Функции
PHP Manual

xslt_process

(PHP 4 >= 4.0.3)

xslt_process — Запуск XSLT преобразования

Описание

mixed xslt_process ( resource $xh , string $xmlcontainer , string $xslcontainer [, string $resultcontainer [, array $arguments [, array $parameters ]]] )

xslt_process() - главная функция расширения XSLT. Она позволяет применить XSLT преобразование практически к любому типу входных данных - контейнеров. Это возможно, благодаря использованию буферов аргументов - концепция, взятая из Sablotron XSLT процессора (на данный момент это расширение поддерживает только XSLT процессор). По умолчанию, контейнеры - файлы содержащие документ для преобразования.

Список параметров

xh

Ресурс XSLT-процессора, возвращаемый функцией xslt_create().

xmlcontainer

Путь к XML файлу или псевдопеременная для XML аргумента.

xslcontainer

Путь к XSL файлу или псевдопеременная для XML аргумента.

resultcontainer

Контейнер для результата. По умолчанию, это имя файла для записи преобразованного документа. Если не задано - то есть NULL - то результат будет возвращен из функции.

arguments

Вместо явного указания аргументов XML и XSLT в функции xslt_process() можно задать "псевдопеременные", которые будут заменяться значениями из отдельного массива аргументов arguments.

parameters

Массив параметров, которые будут передаваться в XSLT-документ. Доступ к этим параметрам из XSL файлов можно получить, используя инструкцию <xsl:param name="имя_параметра">. Параметры должны быть закодированы в UTF-8, а их значения будут интерпретированы Sablotron процессором, как символьные строки. Другими словами, нельзя передавать узлы и поддеревья в качестве параметров в XSLT документ.

Контейнеры также могут быть заданы в виде массива arguments (см. ниже).

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. Если контейнер для результата не задан - т.е. NULL - будет возвращен результат преобразования.

Список изменений

Версия | Описание
4.0.6 | Эта функция больше не принимает XML строки в качестве значений xmlcontainer или xslcontainer. Передача строк с XML данными в качестве какого-либо из этих параметров приведет к ошибке распределения памяти в версиях Sablotron ранее 0.95 включительно.

Примеры

Простейший тип преобразования с помощью функции xslt_process() - это преобразование XML файла с файлом XSLT и помещение результата в третий файл, который будет содержать новый XML (или HTML) документ. Делать подобные преобразования с помощью Sablotron довольно просто...

Пример #1 Использование функции xslt_process() для преобразования XML и XSL файлов в новый XML файл

<?php

// Создание нового XSLT процессора
$xh = xslt_create();

// Преобразование документа
if (xslt_process($xh, 'sample.xml', 'sample.xsl', 'result.xml')) {
    echo "УСПЕХ, sample.xml преобразован в соответствии с sample.xsl в result.xml";
    echo ", содержимое result.xml:\n<br />\n";
    echo "<pre>\n";
    readfile('result.xml');
    echo "</pre>\n";
} else {
    echo "К сожалению, sample.xml не может быть преобразован в соответсвии с sample.xsl в";
    echo "  result.xml по следующей причине: " . xslt_error($xh) . ", код ошибки: ";
    echo xslt_errno($xh);
}

xslt_free($xh);

?>

Зачастую, особенно это относится к web окружению, требуется прямой вывод результата преобразования. Этого можно добиться, если опустить третий аргумент функции xslt_process() (или передать в качестве него NULL). В этом случае функция вернет результат XSLT преобразования без помещения его в файл...

Пример #2 Использование функции xslt_process() для преобразования XML и XSL файлов в переменную, содержащую результирующие XML данные

<?php

// Создание нового XSLT processor
$xh = xslt_create();

// Преобразование документа, возврат результата в переменную $result
$result = xslt_process($xh, 'sample.xml', 'sample.xsl');
if ($result) {
    echo " УСПЕХ, sample.xml преобразован в соответствии с sample.xsl в переменную \$result";
    echo ", содержимое переменной \$result следующее:\n<br />\n";
    echo "<pre>\n";
    echo $result;
    echo "</pre>\n";
} else {
    echo " К сожалению, sample.xml не может быть преобразован в соответсвии с sample.xsl в";
    echo " переменную \$result по следующей причине: " . xslt_error($xh);
    echo ". Код ошибки: " . xslt_errno($xh);
}

xslt_free($xh);

?>

Приведенные выше ситуации и примеры являются наиболее общими и используются чаще всего. Однако, в ряде случаев XML и XSLT может быть получен из внешних источников, таких как база данных или сокет. В этих случаях XML и/или XSLT данные хранятся в переменных, а помещение их в файлы создаст дополнительные временные затраты, что для некоторых приложений критично. В этих исключительных ситуациях на помощь придет особый синтаксис "аргументов" XSLT. Вместо XML и XSLT файлов в качестве аргументов в функции xslt_process() можно задать "псевдопеременные", на места которых будут подставлены значения отдельного массива аргументов (5й аргумент функции xslt_process()). Ниже представлен пример, в котором XML и XSLT преобразуются с сохранением результата в переменной и без использования файлов вообще.

Пример #3 Использование функции xslt_process() для преобразования XML и XSL данных, содержащихся в переменных и сохранения результата в другую переменную с XML кодом.

<?php
// $xml и $xsl содержат XML и XSL данные

$arguments = array(
     '/_xml' => $xml,
     '/_xsl' => $xsl
);

// Создаем новый XSLT-процессор
$xh = xslt_create();

// Преобразование документа
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
if ($result) {
    echo " УСПЕХ, sample.xml преобразован в соответствии с sample.xsl в переменную \$result";
    echo ", содержимое переменной \$result следующее:\n<br />\n";
    echo "<pre>\n";
    echo $result;
    echo "</pre>\n";
} else {
    echo " К сожалению, sample.xml не может быть преобразован в соответсвии с sample.xsl в";
    echo " переменную \$result по следующей причине: " . xslt_error($xh);
    echo ". Код ошибки: " . xslt_errno($xh);
}
xslt_free($xh);
?>

Пример #4 Передача PHP переменных в XSL файлы

<?php

// XML строка
$xml = '<?xml version="1.0"?>
<para>
 change me
</para>';

// XSL строка
$xsl = '
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no"
 omit-xml-declaration="yes"  media-type="text/html"/>
 <xsl:param name="myvar"/>
 <xsl:param name="mynode"/>
 <xsl:template match="/">
Моя PHP переменная : <xsl:value-of select="$myvar"/><br />
Мой набор узлов : <xsl:value-of select="$mynode"/>
 </xsl:template>
</xsl:stylesheet>';

$xh = xslt_create();

// второй параметр будет интерпретирован как строка
$parameters = array (
  'myvar' => 'test',
  'mynode' => '<foo>bar</foo>'
);

$arguments = array (
  '/_xml' => $xml,
  '/_xsl' => $xsl
);

echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments, $parameters);

?>

Результат выполнения данного примера:

Моя PHP переменная : test<br>
Мой набор узлов : &lt;foo&gt;bar&lt;/foo&gt;

Примечания

Замечание:

Учтите, что в случае использования Windows, вам нужно указать file:// в начале пути.

User Contributed Notes

anonymous 28-Jun-2007 08:05
It is possible that the xslt_process call can expose information about Apache's installation location if null values are passed to the signature.

for example:
<?php
$xslt = xslt_create();
$result = xslt_process($xslt, null, null);
echo $result;
?>

The error you will recieve is:
Warning:  Sablotron error on line none: cannot open file 'C:\Program Files\Apache Group\Apache2/' in C:\webroot\htdocs\projects\www\sales\test.php on line 4

Although trying to read a 'null' XML file and 'null' XSL stylesheet are rather silly, consider an attacker tries to upload an arbitrary file and execute it with similar code.

the user may then gain enough information to attack your site.
16-Aug-2006 04:30
To let xslt_process() work correctly, you have to set xslt_set_base()
Here is my example code (Tested on: Windows 2000/XAMPP 1.4.15/PHP 4.4.0/Sablotron 1.0.2):

<?php
$xh = xslt_create();
$filebase = 'file://' . getcwd () . '/test/';
xslt_set_base($xh,$filebase);

$xml = 'document.xml';
$xsl = 'document.xsl';
$resultdoc = 'result.html';

$parameters = array('mynode' => '<foo>bar</foo>','sample' => 'A sample value');

$result = xslt_process($xh,$xml,$xsl,$resultdoc,NULL,$parameters);
if (!$result)
{
    die(sprintf("Cannot process XSLT document [%d]: %s",xslt_errno($xh), xslt_error($xh)));
}
echo "Result: ".$result."<br />";
xslt_free($xh);
?><a href="test/<?=$resultdoc?>">The result document</a><?
?>
ken at guest dot ie 04-Apr-2006 04:46
After experiencing an ”xml declaration not at start of external entity” error with XML recieved from a remote server. The server now sends response headers back and these were getting in the way.

This fixed it:

$fp = fsockopen($queryhost, 80);
if($fp) {
    fputs($fp, $header);
    while(!feof($fp)) {
        $xml .= fgets($fp, 128);
    }
}
fclose($fp);

//ensure string starts with the XML declaration.
$xml = substr($xml, strpos($xml, “<?xml”) );

$xsltproc = xslt_create();
$result = xslt_process($xsltproc,‘arg:/_xml’, $xsltfile, NULL, array(‘/_xml’ => $xml));
08-Jul-2005 03:35
just to let you know an an apostrophe �  can generate a  "not well-formed (invalid token)" error message. I spent a couple of hours to find it, until i found another user with similar problem:
http://www.feedforall.com/forum/viewtopic.php?t=116&view=next
lets hope that hosting providers will soon adopt php5
csarven at gmail dot com 30-Mar-2005 07:17
I found using the output buffer to be efficient, when dealing with php scripts, with xml data.

<?
$xh = xslt_create();

ob_start();
include('main.php');          //main.php contains php and xml
$xml_file = ob_get_contents();
ob_end_clean();

$arguments = array('/_xml' => $xml_file);

$result = xslt_process($xh, 'arg:/_xml', 'index.xsl', NULL, $arguments);

if (!$result) echo 'XSLT processing error: ' .xslt_error($xh) ;
else echo $result;

xslt_free($xh);
?>
ppekaar at hotmail dot com 07-Aug-2004 05:19
In response to "twa at carlbro dot dk" above I have finally solved how to combine two XML sources and one XSL stylesheet.  The above comment was nearly right,

for the php

<?php

xh = xslt_create();
xslt_set_base($xh,"file://c:\inetpub\wwwroot\yourwebsite\");

$arguments = array('/_xml' => $xmlSingle, '/_xsl'=>$xsl, '/xml2'=>$xml_rates);
$xslResult = xslt_process($xh, 'arg:/_xml', 'single_availability_filter.xsl', NULL, $arguments,$parameters);

?>

Please note that I have put in a blank variable "/_xsl => $xsl", the actuall XSL file is listed directly in the xslt_process fucntion.

Note that we have a third XML data source which is called xml2 and is set a value $xml_rates.  In your XSL stylesheet you can now call this XML data via the following line

<xsl:variable name="filter_rates" select="document('arg:/xml2')/RackRates"/>

the missing link was putting in the the arg:/

Also please note that I am using xslt_set_base which set the base filepath for all your XSL documents.

Hope this helps.
Phelim
Justin Ramos 17-May-2004 06:24
The xslt_ functions no longer work in PHP/5.0; the XSLT extension has been removed. To apply an XSL transformation to an XML document, you must use DomDocument (from DOM) and XsltProcessor (from XSL):

<?
$xml = new DomDocument();
$xml->load('foo.xml');

$xsl = new DomDocument;
$xsl->load('foo.xsl');

$proc = new xsltprocessor();
$proc->importStyleSheet($xsl);
echo($proc->transformToXML($xml));
?>
ajenks at paradise dot net dot nz 07-Feb-2004 10:00
By combining some of the user added notes and some experimentation, here's how I finally got the query string broken down and passed in as top-level parameters:

With a little more effort, this could be turned into a completely generic transform script - i.e. by adding query parms for the xml and xsl files also and excluding them from the $params array (though this lat bit may not be necessary).

Thanks to all those other users whose tips make up most of this solution!

<?php

// Process query string to $params array

$vars = explode("&", $_SERVER['QUERY_STRING']);
for ($i=0;$i<=count($vars);$i++) {
 $var = explode("=", $vars[$i]);
 $params[$var[0]] = $var[1];
}

// Fire up the engine

$xslt = xslt_create();
$xml = 'test.xml';
$xsl = 'test.xsl';

$result = xslt_process($xslt, $xml, $xsl, NULL, array(), $params);
if ($result) {
   echo $result;
}
else {
   print "Error:" . xslt_errno($xslt);
}

xslt_free($xslt);

?>
greg _at_ rhythmicdesign _dot_ com 22-Jan-2004 08:45
Figuring out the syntax to get parameters in was difficult but this works for me:

// Allows user to pass argument from URL as script.php?foo=VALUE

$xml = file_get_contents ('n.xml') ;
$xsl = file_get_contents ('n.xsl') ;

 // Perform the transformation
$args = array (
        '/_xml'    =>    $xml,
        '/_xsl'    =>    $xsl
);
$params = array (
        'foo'    =>    $foo
) ;

 $html = xslt_process($xsltproc, 'arg:/_xml', 'arg:/_xsl', NULL, $args, $params);

then in the XSL FILE:
--------------------------
<xsl:param name="foo"/>

<xsl:template match="/">
    <root>
    <test><xsl:value-of select="$foo"/></test>
    <xsl:apply-templates/></root>

</xsl:template>

Note: the param definition and the '$' dollar sign
ohlesbeauxjours at yahoo dot fr 10-Jun-2003 05:57
Thanks, Martin !

As a matter of fact, your way of doing is probably more logical than mine :)
The point is that scheme handler strangely adds a slash to your URI , if it doesn't start by any slash.

So if you call : document('http:www.url.com',page/@url)
...then $rest gets /www.url.com

But if you call : document('http://www.url.com',page/@url)
...then $rest gets //www.url.com

Another approach could consist in enclosing the scheme "http" in the XML attribute : <page url="http://www.w3.org/TR/REC-xml">
and simply doing a : $file = fopen("http:".$rest,"r");

It all depends on the context...

See also :
http://archive.gingerall.cz/archives/public/sablot2003/msg00598.html
martin_a_thomas at yahoo dot com 27-May-2003 04:06
I had a little trouble making the http scheme handler work until I removed the line with the strip function and then changed the fopen
from 'http://' to 'http:' -

$file = fopen("http:".$rest,"r");

Regards // Martin
ohlesbeauxjours at yahoo dot fr 03-Apr-2003 06:14
The XSLT document() function can only open local files.
But thanks to the Sablotron handlers, you can easely write an http-handler (or even ftp- !!).

This sample opens a particular XHTML page on the W3C, and will parse it to get the TITLE tag content.
The interesting point, here, is that the url to open (www.w3.org/TR/REC-xml) is defined... inside an XML  document :)

// XML content :
$xml='<?xml version="1.0"?>
    <page url="www.w3.org/TR/REC-xml">W3C Recommendation page</page>';

// XSL content :
$xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no" omit-xml-declaration="yes" standalone="yes" media-type="text/html"/>
<xsl:template match="/">
    The title is : <xsl:value-of select="document(concat(\'http:\',page/@url))/html/head/title"/>
</xsl:template>
</xsl:stylesheet>';

// TRANSFORMATION :
function handGetAll($processor,$scheme,$rest) {
 $rest=substr($rest,1);
 switch($scheme) {
        case 'http':
            $file = fopen("http://".$rest,"r");
            while(!feof($file))
                $c .= fgets($file, 1024);
            fclose($file);
            return $c;
            break;
    }
}

$xh = xslt_create();
xslt_set_scheme_handlers($xh,array("get_all" => "handGetAll"));
echo xslt_process($xh,'arg:/_xml', 'arg:/_xsl',NULL,array("/_xml"=>$xml,"/_xsl"=>$xsl));
xslt_free($xh);
twa at carlbro dot dk 14-Jan-2003 10:12
Hi... I'm back with the result :)

After a good discussion on the official Sablotron / PHP mailing list I found out how to fix the problem I had with PHP 4.3.0. So now I will just summarize it here. The full discussion can be found online on this address:
http://archive.gingerall.cz/archives/public/sab-php/msg00252.html

The problem is actually an error in my code (huh? I thought I wrote error-free code). In my XSLT file I use the document() method provided by Sablotron. In my previous example I use this syntax:
  document('foobar')
The real syntax is actually:
  document('arg:/foobar')
The reason why this worked in previous versions of PHP was due to an error in the Sablotron lib (anyway so I think).

Another thing that I would like to share is the syntax of the 2nd, 3rd and 5th argument in the xslt_process() method. In the official examples on this page the names "_xml" and "_xsl" is used. But according to the Sablotron people any name can be used. And if you are wondering if you need the preceding "/" or not - then Lenar L�hmus from the sab-php mailing list told me it would be wise to use it. Normally it works either way, but it is always the best thing to use the slash. For the full discussion on this subject see the other thread at:
http://archive.gingerall.cz/archives/public/sab-php/msg00260.html

/watson
twa at carlbro dot dk 13-Jan-2003 01:13
It seems to be undocumented how to get the XSL parser to use two XML files at the same time to produce the output. It is possible though. Here is how it's done with the XML data in a variable:

First you need to change the 5th argument.
$xh = xslt_create();
$args = array('/_xml'=>$xml1, '/_xsl'=>$xsl, 'xml2'=>$xml2);
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $args);

Inside the XSLT document you then need to do this:
<xsl:template match="/">
  <root>
    <foo>
      <xsl:value-of select="/foo" />
    </foo>
    <bar>
      <xsl:value-of select="document('xml2')/bar" />
    </bar>
  </root>
</xsl:template>

This creates a XML result containing a root node called "root" containing two nodes. One called "foo" with the content of the root node in $xml1 and one called "bar" with the content of the root node in $xml2.

In the $args array I don't know if it is best to write "'xml2'=>$xml2" or "'/xml2'=>$xml2". Both work. I think it has something to do with the level of the argument (/level1/level2/level3). Maybe this site reveals the true syntax:
http://www.gingerall.com/charlie/ga/act/gadoc.act?pg=sablot#i__1029

I don't know if there is another - more elegant way - to do this. But I can't find any documentation on it.

For the moment I can't get this to work in PHP 4.3.0/Windows because there seems to be a problem with the Sablotron that is shipped with this version (I have not tried the UNIX version though). I think a new version of the sablot.dll will fix this problem. But for the moment I can't seem to get PHP to work with this new version. If anyone knows how to do this then please send me a mail. I'll post anything that I find out.

/watson
geiryork at start dot no 04-Jan-2003 07:43
An important detail if you want to use the last argument to include parameters to the template:
<?PHP
xslt_process($xslt, 'foo.xml', 'foo.xslt', NULL, array(), array('foo' => 'FOO'));
?>

In the xsl file:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:param name="foo"/>
<xsl:template match="/">
<xsl:value-of select="foo"/>
.........

Note the <xsl:param name="foo"/> is specified *outside* the template tag, but can be referenced inside it.
sanj at wiredesign dot com 11-Nov-2002 11:34
Okay, now this is a neat function once you play around with it
bit...we're basically using it in two ways...one to preview data
from a mysql database, and the other to actually publish the
output to a .htm file. The following example shows us grabbing
data from the database and then using the xslt_process() function
 to combine this data file a .xsl file residing on the server...

<?php
include("../../includes/connect_to_db.inc");

$query = mysql_query("select * from mytbl where mytbl_id=1");

$mydata = mysql_fetch_array($query);

$xmlString  = '<?xml version="1.0"?><data>';
$xmlString .= '<mytbl_id>'.$mydata["mytbl_id"].'</mytbl_id>';
$xmlString .= "<mytbl_title>".$mydata["mytbl_title"]."</mytbl_title>";
$xmlString .= "<mytbl_filename>".
                     $mydata["mytbl_filename"]."</mytbl_filename>";
$xmlString .= "</data>";

//create instance of xslt parser
$xh = xslt_create();

//store xmlString in an array using a key '/_xml'
$arguments = array('/_xml' => $xmlString);

//to write data to a file
xslt_process($xh, 'arg:/_xml', 'style.xsl', 'result.htm', $arguments);

//to view in brower
echo(xslt_process($xh, 'arg:/_xml', 'style.xsl', NULL, $arguments));

?>

The above function works well, although you can't seem to view
 the resulting htm document in the browser and write to a file at
 the same time...instead you have to call the function twice, once
 to write data to a file and once to display data in a browser.

-----------------------
here's a simple style.xsl file that works with this example...

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <html>
    <head>
    </head>
    <body>
    <h1>Here's my data!</h1>
    <xsl:value-of select="data/mytbl_title" /><br />
    <xsl:value-of select="data/mytbl_filename" /><br />
    </body>
    </html>
</xsl:template>
</xsl:stylesheet>

enjoy!

Sanj Maghera
tom at hubalek dot net 11-Nov-2002 03:52
Hi,

keep in mind that fifth parameter of function xsl_process() is __arguments__ and sixth is __xsl parameters__. I spent a lot of time learning difference between arguments and parameters ;-)

Tom
jordigasulla at yahoo dot com 30-Sep-2002 02:28
The output of the XSLT process doesn't have to be necessarily HTML. If you receive a lot of data in the XML and want to distribute it along all your page, you can convert all your page to XHTML or force the output to be PHP code and then eval()uated. For instance, your XSL document (part of it) could look like:

<xsl:text disable-output-escaping="yes">$networth=</xsl:text><xsl:value-of select="networth" /><xsl:text disable-output-escaping="yes">;</xsl:text>

and your PHP code could look like:

$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
if ($result) {
  eval(addslashes($result));

that way, you can use the variable $networth in wherever you want inside your PHP file, like:

<? print $networth; ?>
dragan at iskrassoderwas dot de 01-Aug-2002 05:09
Your input into xslt-process can of course be of external-php-script-nature. This way, you can use PHP scripts that output XML code to make up the transformation:

// Transforming "Dynamic XML" through static XSL
<?php
// Gonna contain PHP-XML output
$arguments = array(
     '/_xml' => $xml,
);

$xh = xslt_create();

// Read plain PHP-XML output
$xmlData = fopen ("http://somehost/xmloutputtingscript.php", "r");

// Stack up output into one String
while ($line = fgets ($xmlData))
  $xml .= $line;

// Process the document
$result = xslt_process($xh, 'arg:/_xml', 'mystylesheet.xsl', NULL, $arguments);

// Print out your transformed document
echo $result;

xslt_free($xh);
j dot metzger at steptown dot com 06-Jul-2002 02:12
This in example on using variables from php in xsl-stylesheets (Sablotron 0.95)

with:

<xsl:param name="foo" />

and how to pass the param from php to Sablotron
(I'm using Sablotron 0.95)

The php-wrapper to Sablotron has changed somewhat in 4.0.6, so I'm using the new (experimental) syntax.

Maybe this could change again in the future

I use 4.2.1 which is compiled with:
'./configure' '--with-mysql' '--with-apxs' '--enable-xslt' '--with-xslt-sablot=/usr/local/lib' '--with-expat-dir=/usr' '--with-dom' '--with-zlib-dir=/usr'

When you want to use a param passed to the xslt_process you have to put it in the top level of the xslt-script, otherwice it won't work (means: before defining any template)
Afterwards you can use the passed param with

<xsl:value-of select="$yourparamname" />

in the template.

example:

====> xsl-stylesheet <====

<?xml version="1.0"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="html" version="1.0" encoding="UTF-8" indent="no" omit-xml-declaration="yes" doctype-public="-//W3C/DTD XHTML 1.0 Transitional//EN" doctype-system="
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" standalone="yes" media-type="text/html" />

<xsl:param name="tpsession" />

<xsl:template match="/root/output">
   this is the template stuff. and this is the param

<xsl:value-of select="$tpsession" />

</xsl:template>

</xsl:stylesheet>

====> end of xsl - stylesheet <====

o.k. -> to call the xslt_parser (Sablotron 0.95 in my case) with params do this:

<?php

/* php script */

$xh = xslt_create();
$arg = array(    '/_xml'   =>$t_xmlString,
                      '/_xsl'    => $t_xslString );
$param = array('tpsession' = session_name()."=".session_id());

$result = @xslt_process($xh, 'arg:/_xml', 'arg:/_xsl',NULL,$arg,$param);
if(!$result){
print xslt_error($xh);
}
else
print $result;
xslt_free($xh);

/* end of php-script */

?>

That's it -> have fun
tkearns at fastmail dot fm 10-Jun-2002 09:18
For those of you wondering what the hell is up with the very strange format for refering to in-memory data, see
http://www.gingerall.com/charlie/ga/act/gadoc.act?pg=sablot#i__1029

normally you pass a file name (or URI) using the 'file:' syntax. The 'arg:' syntax introduced by sablotron does not refer to a file system path, it refers to an ARGument - and of course, arguments are in-memory. In the case of PHP, the argument reference is an index to the array in parameter 5 of the xslt_process() function. I think the forward slash is just to maintain the convention of path notation.

Someone with more knowledge on the topic could probably provide a more concise definition. If so, it would be nice to have it included as part of the standard documentation set.

Some wrapper functions would make things easier still.

Here's a wrapper I wrote.

function XtDataWithFile($xmlData, $uriXSLT) {
    $args = array ( '/_xml' => $xmlData );
    $xp = xslt_create();
    $out = xslt_process($xp, 'arg:/_xml', $uriXSLT, NULL, $args);
    xslt_free($xp);
    return $out;
}

of course you could do XtFileWithData() can XtDataWithData()
msopacua at idg dot nl 03-Jun-2002 04:00
Took me a while to figure this one out, but no matter what your stylesheet encoding and xml encoding says - argument values, need to be UTF-8.

Version 4.2.1 and sablot 0.90.
tim at zero-interactive dot com 02-May-2002 01:11
[Editors note: this is basic URI syntax. Any URI, is specified as: <protocol>:location. Any resource, that can point to a network, needs '//' to indicate it's "network awareness". F.E.: ftp://, http:// and yes - file://.]

For those of you wanting to know how to fix the annoying bug telling you that an econding type of '' is unacceptable ....

Win2K, PHP 4.2.0

When processing files, you need to prefix each filename with "file://" or else you will get the above mentioned error.  Then you just need to set the encoding in your xslt file to get it to work.

You must use this prefix with your xml, xsl and output files if you are using all three like I am.

Happy hunting!!!
patrice dot lazareff at lbb dot fr dot invalid 18-Apr-2002 06:04
This function's syntax has changed since PHP 4.0.x, here is a quick workaround for those who use a same script with various versions.
Note that in order to work with PHP 4.0.x, the commented part must not be directly within the code (or a parse error will occur).
This is why I commented it out here and call this bit of code via an include.

// PHP 4.0.6/4.1.x difference
$minor = explode(".",phpversion());
if($minor[1] >= 1) // PHP 4.1.x -- preferred
{
    include("php412_XSLT.php");

/* here is the included code
$arguments = array(
'/_xml' => $final_xml,
'/_xsl' => $xsl_content
);

$html_out = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);

end of included code */

} else // PHP 4.0.6 -- works okay
    xslt_process($xsl_content, $final_xml,$html_out);

echo $html_out;
theseer at php dot net 14-Mar-2002 07:22
Note that this extension changed quite heavily in the latest releases. The documentation and howtos on the web may not match your version of php !

To verify your extension, check the configure information

 ( <?php phpinfo(); ?> )

 for either

      --with-sablot  ( old )
 or
    --enable-xslt --with-xslt-sablot (new).

Most ( all?) web documents i found describe the use of the old extension, which also changed in the process of development.

This extension is marked experimental for a reason ;)
lennart at rsd-online dot dk 19-Feb-2002 08:14
Relative paths using xsl:include

i addition to francis's note above you can set the base path with the xslt_set_base function like this on windows like this.

xslt_set_base('file://c:/path to xslt files/')

from you xsl file use the
<xsl:include href="file.xls">

If you wish to have full access to all files in you site only specify the root path and then use
<xsl:include href="somepath/file.xls">

God speed.
francisf at videotron dot ca 12-Feb-2002 04:00
Just because that I have look around and see other look around without any solution, so for prosperity, I give somethings that surely a lot of people know but a lot don't too.

OK, if you want to do xsl:include in your xsl file that will be parsed by your php page with xslt and sablot installed,

you have to put that in your xsl page (on a linux machine):
<xsl:include  href="file:///pathtomyxslfile/xy.xsl">

yes you do have 3 "///", the 2 first are used by sablotron and the third one is used for your path as: /pathtomyxslfile/xy.xsl

It was in the sablotron doc, well part of it.

Tested on:
php 4.1.0
Apache/1.3.22
sablot 0.80

Thanks you and take care.
chris_coupal at hotmail dot com 28-Jan-2002 06:06
If you are getting the data from a database and creating the XML data stream for transformation, you can add the parameters for the stylesheet into the XML data. Once in the data, you can reference them from the XSL stylesheet directly.
ascii_NO_SPAM_ at _NO_SPAM_microcore dot dk 17-Jan-2002 09:42
I noticed a slight difference in html output when upgrading to php4.1.1 on Windows.

I found the garbled output to be caused by [indent="yes"] in <xsl:output /> and simply changed it to [indent="no"].
Bill Humphries <whump at mac dot com> 06-Jan-2002 04:48
It appears that the xslt_process function does not like to have NULLs passed into it for the Argument and Parameter arrays. However, you can pass it an empty Argument array (modulo any typos):

$xh = xslt_create();
$args = array();
$params = array( 'foo' => 'bar' );
$result = xslt_process($xh,
'source.xml','source.xsl',NULL,
$args,$params);
if ($result)
{
 print $result;
} else {
 print "Error: ".xslt_error($xh);
}

That way you don't have to worry about providing methods for reading files into the argument array.
xslt_getopt
xslt_set_base
XSLT (PHP 4) Функции


Установка базового URI для всех XSLT преобразований

xslt_process
xslt_set_encoding
XSLT (PHP 4) Функции
PHP Manual

xslt_set_base

(PHP 4 >= 4.0.5)

xslt_set_base — Установка базового URI для всех XSLT преобразований

Описание

void xslt_set_base ( resource $xh , string $uri )

Задает значение базового URI для всех XSLT преобразований. Этот URI используется в Xpath инструкциях для разбора document() и других команд, имеющих доступ к внешним источникам. Также он используется для разрешения URI элементов <xsl:include> и <xsl:import>.

Список параметров

xh

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

uri

Значение базового URI.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

Версия | Описание
4.3.0 | В версии PHP 4.3.0 значением базового URI по умолчанию является директория выполняющегося скрипта. Фактически, это директория, заданная в константе __FILE__. Умолчания для базового URI в более ранних версиях PHP менее предсказуемы.

Примечания

Замечание:

Учтите, что в случае использования Windows, вам нужно указать file:// в начале пути.

User Contributed Notes

h0bby1 at yahoo dot com 26-Feb-2008 05:20
i use xslt and page can be generated in two mode, one using <? xml-stylesheet href='page.xsl' >, one other using the php sablotron lib, the first one use path relative to the xsl file for includes , but the second with sablotron consider all the includes as relative to the set base path, is there any way to get sablotron to resolve include as relative to xslt file instead of the set_base for all files ?
edmon at oohaa dot net 04-Oct-2004 04:09
$filebase = 'file://' . getcwd () . '/xsl/';
   xslt_set_base($xsltproc, $filebase);

file:// is needed for linux too.
php 4.3.8
Kelvin Cheng 10-Mar-2004 02:44
It works great on my windows platform as below.

<?php
$xh = xslt_create();
$fileBase = 'file://' . getcwd () . '/';
xslt_set_base ( $xh, $fileBase );

...

?>

Actually, it make use of the getcwd() to get the current directory. Hope it can help.
xslt_process
xslt_set_encoding
XSLT (PHP 4) Функции


Задание кодировки для разбора XML документов

xslt_set_base
xslt_set_error_handler
XSLT (PHP 4) Функции
PHP Manual

xslt_set_encoding

(PHP 4 >= 4.0.5)

xslt_set_encoding — Задание кодировки для разбора XML документов

Описание

void xslt_set_encoding ( resource $xh , string $encoding )

Задает кодировку результата XSLT преобразований. При использовании для XSLT преобразований серверного приложения Sablotron эта настройка будет доступна, если Sablotron компилировался с поддержкой кодировок.

Список параметров

xh

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

encoding

Кодировка результата, например iso-8859-1.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

gloob at litio dot org 10-Sep-2007 03:13
Beware with http://bugs.php.net/bug.php?id=23148 if you experienced problems compiling php4-xslt.
francois at flash-france dot com 26-Jan-2005 07:05
sablotron and php have to be correctly linked with iconv library to get this function working

IE on sabotron ./configure :
--with-iconv-prefix=/your/path
Hudson Silva 12-Mar-2004 09:31
I'm running Mandrake Linux v9.1, with Apache 2.0.48 and PHP 4.3.4...I'm have make PHP with XSLT support, and this work fine, expect because a problem...the function xslt_set_encoding don't work, and i have found a solution...simply, type export LDFLAGS=-lstdc++ before start the configure program of PHP. And this will work!
zibi at sails pl 12-Jun-2003 08:33
i'm usig it that way:

$ht=xslt_create();
xslt_set_encoding($ht,"ISO-8859-2");
$args = array ( '/_xml' => $xml, '/_xslt' => $xslt);
$result=xslt_process($ht,'arg:/_xml','arg:/_xslt',NULL,$args);

all placed in very nice class ;-)
xslt_set_base
xslt_set_error_handler
XSLT (PHP 4) Функции


Задание обработчика ошибок для XSLT-процессора

xslt_set_encoding
xslt_set_log
XSLT (PHP 4) Функции
PHP Manual

xslt_set_error_handler

(PHP 4 >= 4.0.4)

xslt_set_error_handler — Задание обработчика ошибок для XSLT-процессора

Описание

void xslt_set_error_handler ( resource $xh , mixed $handler )

Задает функцию обработки ошибок для XSLT-процессора, заданного аргументом xh. Эта функция будет вызываться в случает возникновения ошибок в процессе XSLT преобразования (также она будет вызываться при уведомлениях).

Список параметров

xh

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

handler

Пользовательская функция должна принимать четыре аргумента: ссылку на XSLT-процессор, уровень ошибки, код ошибки и массив сообщений об ошибках. Это может выглядеть так:

error_handler ( resource $xh , int $error_level , int $error_code , array $messages )

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования xslt_set_error_handler()

<?php

// Наш обработчик ошибок XSLT
function xslt_error_handler($handler, $errno, $level, $info)
{
  // проверим список аргументов
  var_dump(func_get_args());
}

// XML содержимое :
$xml='<?xml version="1.0"?>
<para>
 упс, я пропустил закрывающий тэг
</pata>';

// XSL содержимое :
$xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
   <strong><xsl:value-of select="para"/></strong>
</xsl:template>
</xsl:stylesheet>';

$xh = xslt_create();

xslt_set_error_handler($xh, "xslt_error_handler");

echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl',
                  NULL, array("/_xml" => $xml, "/_xsl" => $xsl));

?>

Результатом выполнения данного примера будет что-то подобное:

array(4) {
  [0]=>
  resource(1) of type (XSLT Processor)
  [1]=>
  int(3)
  [2]=>
  int(0)
  [3]=>
  array(6) {
    ["msgtype"]=>
    string(5) "error"
    ["code"]=>
    string(1) "2"
    ["module"]=>
    string(9) "Sablotron"
    ["URI"]=>
    string(9) "arg:/_xml"
    ["line"]=>
    string(1) "4"
    ["msg"]=>
    string(34) "XML parser error 7: mismatched tag"
  }
}

Смотрите также

  • xslt_set_object() - Задает объект, в котором будут реализованы callback-функции, если нужно использовать метод объекта в качестве обработчика

User Contributed Notes

jocke n0spam at selincite dot com 01-Oct-2002 08:20
Addition to the last note. in the array I have used array($this, "myMethod") to make it use an internal function in a class.
I reckon this is how it is meant to work (not tested)
$myObj = new MyObj()
xslt_set_error_handler_($xh, array($myObj, "myErrorMethod"));
26-Aug-2002 01:15
To set the error handler to the instance of an object, use the:

xslt_set_error_handler($xh, array($obj, $method))

syntax.
xslt_set_encoding
xslt_set_log
XSLT (PHP 4) Функции


Задание файла журнала для записи сообщений XSLT процессора

xslt_set_error_handler
xslt_set_object
XSLT (PHP 4) Функции
PHP Manual

xslt_set_log

(PHP 4 >= 4.0.6)

xslt_set_log — Задание файла журнала для записи сообщений XSLT процессора

Описание

void xslt_set_log ( resource $xh [, mixed $log ] )

Эта функция позволяет задать файл, в который будут записываться сообщения XSLT-процессора. Сообщения XSLT-процессора отличаются от сообщений об ошибках, они не являются сообщениями об ошибках, но также зависят от состояния XSLT-процессора. Эти сообщения могут быть полезны для отладки XSLT в случаях, когда преобразование проходит ненадлежащим образом.

По умолчанию протоколирование событий отключено. Для его включения необходимо вызвать функцию xslt_set_log() с аргументом логического типа (boolean). Для задания файла журнала необходимо вызвать эту функцию повторно, но передать ей в качестве аргумента уже строку, содержащую имя файла.

Список параметров

xh

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

log

Этот аргумент может быть логического типа для включения и выключения протоколирования, либо это может быть строка содержащая имя файла журнала, в который будут записываться сообщения, в том числе и об ошибках.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примечания

Замечание:

Учтите, что в случае использования Windows, вам нужно указать file:// в начале пути.

Примеры

Пример #1 Использование возможностей протоколирования XSLT

<?php

$xh = xslt_create();
xslt_set_log($xh, true);
xslt_set_log($xh, getcwd() . '/myfile.log');

$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
echo $result;

xslt_free($xh);
?>

User Contributed Notes

nospam at phppatterns dot com 06-Apr-2003 08:50
With PHP 4.3.1, Sablotron 0.97 on Windows you do not need the 'file://' prepend to specify a log file but the full system path is required.
xslt_set_error_handler
xslt_set_object
XSLT (PHP 4) Функции


Задает объект, в котором будут реализованы callback-функции

xslt_set_log
xslt_set_sax_handler
XSLT (PHP 4) Функции
PHP Manual

xslt_set_object

(PHP 4 >= 4.3.0)

xslt_set_object — Задает объект, в котором будут реализованы callback-функции

Описание

bool xslt_set_object ( resource $processor , object &$obj )

Эта функция позволяет использовать processor внутри объекта object и реализовать все callback-функции как методы этого объекта.

Callback-функции могут задаваться с помощью функций
xslt_set_sax_handlers(),
xslt_set_scheme_handlers() или
xslt_set_error_handler() и быть объявлены как методы
объекта object.

Список параметров

processor

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

obj

Объект.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Использование собственного обработчика ошибок в качестве метода

<?php

class my_xslt_processor {

    var $_xh; // наш XSLT-процессор

    function my_xslt_processor()
    {
        $this->_xh = xslt_create();

        // внедряем процессор в объект $this
        xslt_set_object($this->_xh, $this);

        // задаем обработчик ошибок
        xslt_set_error_handler($this->_xh, "my_xslt_error_handler");
    }

    function my_xslt_error_handler($handler, $errno, $level, $info)
    {
        // проверим список аргументов
        var_dump(func_get_args());
    }
}

?>

User Contributed Notes

There are no user contributed notes for this page.
xslt_set_log
xslt_set_sax_handler
XSLT (PHP 4) Функции


Задает SAX обработчик для XSLT-процессора

xslt_set_object
xslt_set_sax_handlers
XSLT (PHP 4) Функции
PHP Manual

xslt_set_sax_handler

(PHP 4 >= 4.0.3)

xslt_set_sax_handler — Задает SAX обработчик для XSLT-процессора

Описание

void xslt_set_sax_handler ( resource $xh , array $handlers )

Задает SAX обработчики для заданного XSLT-процессора xh.

Список параметров

xh

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

handlers

SAX обработчики должны быть двумерным массивом с определенным форматом (элементы верхнего уровня являются необязательными):

array(
[document] =>
    array(
        обработчик начала документа,
        обработчик окончания документа
    ),
[element] =>
    array(
        обработчик начала элемента,
        обработчик окончания элемента
    ),
[namespace] =>
    array(
        обработчик начала пространства имен,
        обработчик окончания пространства имен
    ),
[comment] => обработчик комментария,
[pi] => обработчик PI,
[character] => обработчик символьных данных
)

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

jas1298 at ecs dot soton dot ac dot uk 04-Mar-2002 12:55
This function appears to be superseded (from 4.0.6) by http://www.php.net/manual/en/function.xslt-set-sax-handlers.php
xslt_set_object
xslt_set_sax_handlers
XSLT (PHP 4) Функции


Задает SAX обработчики, которые будут вызваться после разбора XML докумнента

xslt_set_sax_handler
xslt_set_scheme_handler
XSLT (PHP 4) Функции
PHP Manual

xslt_set_sax_handlers

(PHP 4 >= 4.0.6)

xslt_set_sax_handlers — Задает SAX обработчики, которые будут вызваться после разбора XML докумнента

Описание

void xslt_set_sax_handlers ( resource $processor , array $handlers )

xslt_set_sax_handlers() задает SAX обработчики handlers для документа и заданного ресурса XSLT-процессора processor.

Использование xslt_set_sax_handlers() не сильно отличается от применения SAX парсера, как например xml_parse(), к результату xslt_process() преобразования.

Список параметров

processor

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

handlers

handlers должны быть массивом следующего формата:

<?php

$handlers = array(

  "document" => array(
    "start_doc",
    "end_doc"),

  "element"  => array(
    "start_element",
    "end_element"),

  "namespace" => array(
    "start_namespace",
    "end_namespace"),

  "comment"   => "comment",

  "pi"        => "pi",

  "character" => "characters"

);
?>
Синтаксис функций описан в документации к функциям обработки схем.

Замечание:

Заданный массив не обязан содержать все sax обработчики (хотя он может), но элементы массива должны точно соответствовать формату "обработчик" => "функция", описанному выше.

SAX функции-обработчики имеют следующий формат:

  • start_doc ( resource $processor )

  • end_doc ( resource $processor )

  • start_element ( resource $processor , string $name , array $attributes )

  • end_element ( resource $processor , string $name )

  • start_namespace ( resource $processor , string $prefix , string $uri )

  • end_namespace ( resource $processor , string $prefix )

  • comment ( resource $processor , string $contents )

  • pi ( resource $processor , string $target , string $contents )

  • characters ( resource $processor , string $contents )

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования xslt_set_sax_handlers()

<?php
// От ohlesbeauxjours at yahoo dot fr
// В этом примере к содержимому каждого тэга <auteur>
// применяется функция strtoupper(), а затем выводится
// результат в виде XML дерева:

$xml='<?xml version="1.0"?>
<books>
 <book>
  <title>Mme Bovary</title>
  <author>Gustave Flaubert</author>
 </book>
 <book>
  <title>Mrs Dalloway</title>
  <author>Virginia Woolf</author>
 </book>
</books>';

$xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no" omit-xml-declaration="yes"/>
<xsl:template match="/">
 <xsl:for-each select="books/book">
  <livre>
   <auteur><xsl:value-of select="author/text()"/></auteur>
  </livre>
 </xsl:for-each>
</xsl:template>
</xsl:stylesheet>';

// Обработчики :
function start_document()
{
  // начало чтения документа
}

function end_document()
{
  // завершение чтения документа
}

function start_element($parser, $name, $attributes)
{
  global $result,$tag;
  $result .= "<". $name . ">";
  $tag = $name;
}

function end_element($parser, $name)
{
  global $result;
  $result .= "</" . $name . ">";
}

function characters($parser, $data)
{
  global $result,$tag;
  if ($tag == "auteur" ) {
    $data = strtoupper($data);
  }
  $result .= $data;
}

// Преобразование :
$xh = xslt_create();
$handlers = array("document" => array("start_document","end_document"),
   "element" => array("start_element","end_element"),
   "character" => "characters");

xslt_set_sax_handlers($xh, $handlers);
xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=>$xml, "/_xsl"=>$xsl));
xslt_free($xh);
?>

Также можно воспользоваться функцией xslt_set_object(), если требуется реализовать обработчики внутри объекта.

Пример #2 Обработчик в объектно-ориентированном стиле

<?php
// Объектно-ориентированная версия предыдущего примера

class data_sax_handler {

  var $buffer, $tag, $attrs;

  var $_xh;

  function data_sax_handler($xml, $xsl)
  {
      // our xslt resource
      $this->_xh = xslt_create();

      xslt_set_object($this->_xs, $this);

      // configure sax handlers
      $handlers = array(
        "document" => array('start_document', 'end_document'),
        "element" => array('start_element', 'end_element'),
        "character" => 'characters'
      );

      xslt_set_sax_handlers($this->_xh, $handlers);

      xslt_process($this->_xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=>$xml, "/_xsl"=>$xsl));
      xslt_free($this->_xh);

  }

  function start_document()
  {
        // начало чтения документа
  }

  function end_document() {
        // завершение чтения документа
  }

  function start_element($parser, $name, $attributes) {
        $this->tag = $name;
        $this->buffer .= "<" . $name . ">";
        $this->attrs = $attributes;
  }

  function end_element($parser, $name)
  {
        $this->tag = '';
        $this->buffer .= "</" . $name . ">";
  }

  function characters($parser, $data)
  {
    if ($this->tag == 'auteur') {
          $data = strtoupper($data);
    }
    $this->buffer .= $data;
  }

  function get_buffer() {
    return $this->buffer;
  }

}

$exec = new data_sax_handler($xml, $xsl);

?>

Оба примера выведут следующее:

<livre>
   <auteur>GUSTAVE FLAUBERT</auteur>
</livre>
<livre>
   <auteur>VIRGINIA WOOLF</auteur>
</livre>

User Contributed Notes

There are no user contributed notes for this page.
xslt_set_sax_handler
xslt_set_scheme_handler
XSLT (PHP 4) Функции


Задает обработчики схемы для XSLT-процессора

xslt_set_sax_handlers
xslt_set_scheme_handlers
XSLT (PHP 4) Функции
PHP Manual

xslt_set_scheme_handler

(PHP 4 >= 4.0.5)

xslt_set_scheme_handler — Задает обработчики схемы для XSLT-процессора

Описание

void xslt_set_scheme_handler ( resource $xh , array $handlers )

Задает обработчики схемы для ресурса XSLT-процессора xh.

Список параметров

xh

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

handlers

Обработчики схемы должны быть представлены в виде массива в следующем формате (все элементы являются необязательными):

array(
[get_all] => обработчик get all,
[open] => обработчик open,
[get] => обработчик get,
[put] => обработчик put,
[close] => обработчик close
)

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

User Contributed Notes

There are no user contributed notes for this page.
xslt_set_sax_handlers
xslt_set_scheme_handlers
XSLT (PHP 4) Функции


Задает обработчики схемы для XSLT-процессора

xslt_set_scheme_handler
xslt_setopt
XSLT (PHP 4) Функции
PHP Manual

xslt_set_scheme_handlers

(PHP 4 >= 4.0.6)

xslt_set_scheme_handlers — Задает обработчики схемы для XSLT-процессора

Описание

void xslt_set_scheme_handlers ( resource $xh , array $handlers )

Регистрирует обработчики схемы (XPath обработчики) для документа.

Список параметров

xh

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

handlers

Массив со следующими ключами: "get_all", "open", "get", "put", и "close".

Каждое значение массива должно быть именем функции или массивом в следующем формате: array($obj, "method").

Обратите внимание, наличие всех обработчиков схемы в массиве необязательно (хотя возможно), но каждый элемент массива должен строго соответствовать формату "обработчик" => "функция", описанному выше.

Ниже представлены объявления, которым функции-обработчики схемы должны соответствовать:

string   get_all(resource processor, string scheme, string rest)
resource open(resource processor, string scheme, string rest)
int      get(resource processor, resource fp, string &data)
int      put(resource processor, resource fp, string data)
void     close(resource processor, resource fp)

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования xslt_set_scheme_handlers()

В качастве примера представлена реализация PHP функции "file_exists()".

<?php

// Определение обработчика
function mySchemeHandler($processor, $scheme, $rest)
{
    $rest = substr($rest,1);    // чтобы удалить первый / автоматически добавленный движком
    if ($scheme == 'file_exists') {
        // результат представлен в виде небольшой XML строки
        return '<?xml version="1.0" encoding="UTF-8"?><root>' . (file_exists($rest) ? 'true' : 'false') . '</root>';
    }
}

$SchemeHandlerArray = array('get_all' => 'mySchemeHandler');

// запуск движка
$params = array();
$xh = xslt_create();

xslt_set_scheme_handlers($xh, $SchemeHandlerArray);

$result = xslt_process($xh, "myFile.xml", "myFile.xsl", NULL, array(), $params);
xslt_free($xh);

echo $result;

?>

Теперь можно проверить существование файлов прямо внутри стилевой таблицы:

<xsl:if test="document('file_exists:anotherXMLfile.xml')/root='true'">
 <!-- The file exist -->
</xsl:if>

Смотрите также

  • xslt_set_scheme_handler() - Задает обработчики схемы для XSLT-процессора

User Contributed Notes

There are no user contributed notes for this page.
xslt_set_scheme_handler
xslt_setopt
XSLT (PHP 4) Функции


Установка значений настроек XSLT-процессора

xslt_set_scheme_handlers
Ядро PHP: Руководство хакера по Zend Engine
XSLT (PHP 4) Функции
PHP Manual

xslt_setopt

(PHP 4 >= 4.3.0)

xslt_setopt — Установка значений настроек XSLT-процессора

Описание

mixed xslt_setopt ( resource $processor , int $newmask )

xslt_setopt() устанавливает значения настроек, используя маску newmask, для заданного XSLT-процессора processor.

Список параметров

processor

Идентификатор ссылки на XSLT-процессор, созданный функцией xslt_create().

newmask

newmask битовая маска, созданная из следующих констант:

  • XSLT_SABOPT_PARSE_PUBLIC_ENTITIES - Сообщает процессору о необходимости разбора общедоступных сущностей. По умолчанию эта настройка отключена.

  • XSLT_SABOPT_DISABLE_ADDING_META - Не добавлять мета тэг "Content-Type" при выводе HTML. Умолчания задаются во время компиляции процессора.

  • XSLT_SABOPT_DISABLE_STRIPPING - Не убирать пробелы (только для файлов с данными).

  • XSLT_SABOPT_IGNORE_DOC_NOT_FOUND - Считать неразбираемые документы (функция document()) работоспособными.

Возвращаемые значения

Возвращает предыдущую маску в виде числа, если это возможно; в противном случае TRUE; FALSE в случае ошибки.

Примеры

Пример #1 Пример использования xslt_setopt()

<?php

$xh = xslt_create();

// Дать указание Sablotron обрабатывать общедоступные сущности
xslt_setopt($xh, XSLT_SABOPT_PARSE_PUBLIC_ENTITIES);

// Также попросим его не убирать лишние пробелы
xslt_setopt($xh, xslt_getopt($xh) | XSLT_SABOPT_DISABLE_STRIPPING);

?>

Смотрите также

  • xslt_getopt() - Получение настроек заданного XSLT-процессора

User Contributed Notes

There are no user contributed notes for this page.
xslt_set_scheme_handlers
Ядро PHP: Руководство хакера по Zend Engine
XSLT (PHP 4) Функции


Ядро PHP: Руководство хакера по Zend Engine

  • Preface
  • The "counter" Extension - A Continuing Example
    • Установка и настройка
    • Предопределенные константы
    • Примеры
    • Counter — The Counter class
    • Basic — The basic interface
    • Extended — The extended interface
  • The PHP 5 build system
    • Building PHP for extension development
    • The ext_skel script
    • Talking to the UNIX build system: config.m4
    • Talking to the Windows build system: config.w32
  • Extension structure
    • Files which make up an extension
    • Basic constructs
    • The zend_module structure
    • Extension globals
    • Life cycle of an extension
    • Testing an extension
  • Memory management
    • Basic memory management
    • Data persistence
    • Thread-Safe Resource Manager
  • Working with variables
    • Intro
    • Creating variables and setting values
  • Writing functions
  • Working with classes and objects
  • Working with resources
  • Working with INI settings
  • Working with streams
  • PDO Driver How-To
    • Prerequisites
    • Preparation and Housekeeping
    • Fleshing out your skeleton
    • Building
    • Testing
    • Packaging and distribution
    • pdo_dbh_t definition
    • pdo_stmt_t definition
    • Constants
    • Error handling
  • Extension FAQs
  • Zend Engine 2 API reference
  • Zend Engine 2 Opcodes
    • Opcode Descriptions and Examples
  • Zend Engine 1
    • Old introduction
    • Streams API for PHP Extension Authors
    • Zend API: Взламываем ядро PHP
    • TSRM API

User Contributed Notes

There are no user contributed notes for this page.
xslt_setopt
Preface
Руководство по PHP


Preface

The Zend API has evolved considerably over time, as PHP has become a more robust and widespread language. With the introduction of PHP 5 came the Zend Engine 2 (ZE2). ZE2 came with an almost entirely new Object-Oriented Programming (OOP) model and a number of improvements in the API.

Внимание

This documentation is still under heavy development. The original Zend documentation is preserved in its entirety in the Zend Engine 1 section for those who need it before this documentation is completed.

This section of the manual is devoted to ZE2. The differences in how extensions are written in ZE1 are small; a short reference to them is given in an appendix to this section.

The documentation in this section is current as of PHP 5.3.3, the most recent stable release of PHP 5.3 at the time of this writing. Notable differences in the minor PHP 5 releases (5.0 through 5.3) are given as appropriate.

User Contributed Notes

There are no user contributed notes for this page.
Ядро PHP: Руководство хакера по Zend Engine
The "counter" Extension - A Continuing Example
Ядро PHP: Руководство хакера по Zend Engine


Preface
Установка и настройка
Ядро PHP: Руководство хакера по Zend Engine
PHP Manual

The "counter" Extension - A Continuing Example

Содержание

  • Установка и настройка
  • Предопределенные константы
  • Примеры
  • Counter
  • Basic
  • Extended

Preface

Throughout this Zend documentation, references are made to an example module in order to illustrate various concepts. The "counter" extension is this example, a fictional yet functional Zend module which strives to use as much of the Zend API as is reasonably possible. This short chapter describes the userland interface to the completed extension.

Замечание: "counter" serves no practical purpose whatsoever, as the functionality it provides is far more effectively implemented by appropriate userland code.

User Contributed Notes

There are no user contributed notes for this page.
Preface
Установка и настройка
Ядро PHP: Руководство хакера по Zend Engine


Установка и настройка

Содержание

  • Введение
  • Настройка во время выполнения
  • Типы ресурсов

User Contributed Notes

There are no user contributed notes for this page.
The "counter" Extension - A Continuing Example
Введение
The "counter" Extension - A Continuing Example


Введение

The "counter" extension provides any number of counters to PHP code using it which reset at times determined by the caller.

There are three interfaces to "counter": basic, extended, and objective. The basic interface provides a single counter controlled by INI settings and function calls. The extended interface provides an arbitrary number of named counter resources which may optionally persist beyond the lifetime of a single PHP request. The objective interface combines both the basic and extended interfaces into a Counter class.

User Contributed Notes

There are no user contributed notes for this page.
Установка и настройка
Настройка во время выполнения
Установка и настройка


Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

Counter configuration options
Name | Default | Changeable | Changelog
counter.reset_time | COUNTER_RESET_PER_REQUEST | PHP_INI_ALL |
counter.save_path | "" | PHP_INI_ALL |
counter.initial_value | "0" | PHP_INI_ALL |

Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.

counter.reset_time integer
counter.reset_time tells "counter" to reset the counter used by the basic interface. It may be any of the COUNTER_RESET_* constants (see below).
counter.save_path string
Tells "counter" where to save data that has to persist between invocations of PHP (i.e. any counter that has COUNTER_RESET_NEVER or COUNTER_FLAG_SAVE). A file will be created at this path, which must be readable and writable to whatever user PHP is running as.
counter.initial_value integer
Sets the initial value of the counter used by the basic interface whenever it is reset.

User Contributed Notes

There are no user contributed notes for this page.
Введение
Типы ресурсов
Установка и настройка


Типы ресурсов

The "counter" extension defines one resource type: a counter.

User Contributed Notes

There are no user contributed notes for this page.
Настройка во время выполнения
Предопределенные константы
Установка и настройка


Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если PHP был собран с поддержкой этого расширения или же в том случае, если данное расширение было подгружено во время выполнения.

COUNTER_FLAG_PERSIST (integer)
A counter with this flag will be created as a persistent resource.
COUNTER_FLAG_SAVE (integer)
A counter with this flag will be saved between invocations of PHP.
COUNTER_FLAG_NO_OVERWRITE (integer)
This flag causes counter_create() to avoid overwriting an existing named counter with a new one.
COUNTER_META_NAME (string)
Pass this constant to get the name of a counter resource or object.
COUNTER_META_IS_PERISTENT (string)
Pass this constant to determine whether a counter resource or object is persistent (has the COUNTER_FLAG_PERSIST flag).
COUNTER_RESET_NEVER (integer)
The counter will never be reset.
COUNTER_RESET_PER_LOAD (integer)
The counter will be reset on each invocation of PHP.
COUNTER_RESET_PER_REQUEST (integer)
The counter will be reset on each request.

User Contributed Notes

There are no user contributed notes for this page.
Типы ресурсов
Примеры
The "counter" Extension - A Continuing Example


Примеры

Содержание

  • Basic interface
  • Extended interface
  • Objective interface

User Contributed Notes

There are no user contributed notes for this page.
Предопределенные константы
Basic interface
The "counter" Extension - A Continuing Example


Basic interface

The basic interface provides three simple functions, illustrated here:

Пример #1 "counter"'s basic interface

<?php
$starting_counter_value = counter_get();
counter_bump(1);
$second_counter_value = counter_get();
counter_reset();
$final_counter_value = counter_get();
printf("%3d %3d %3d", $starting_counter_value, $second_counter_value, $final_counter_value);
?>

Результат выполнения данного примера:

  0   1   0

The basic interface also provides a number of INI settings.

User Contributed Notes

There are no user contributed notes for this page.
Примеры
Extended interface
Примеры


Extended interface

The extended interface provides a small suite of functions that allow the user to define an arbitrary number of named counters with unique settings. The basic interface can be used in parallel with the extended interface.

Пример #1 "counter"'s extended interface

<?php
function print_counter_info($counter)
{
    if (is_resource($counter)) {
        printf("Counter's name is '%s' and is%s persistent. Its current value is %d.\n",
            counter_get_meta($counter, COUNTER_META_NAME),
            counter_get_meta($counter, COUNTER_META_IS_PERSISTENT) ? '' : ' not',
            counter_get_value($counter));
    } else {
      print "Not a valid counter!\n";
    }
}

if (($counter_one = counter_get_named("one")) === NULL) {
    $counter_one = counter_create("one", 0, COUNTER_FLAG_PERSIST);
}
counter_bump_value($counter_one, 2);
$counter_two = counter_create("two", 5);
$counter_three = counter_get_named("three");
$counter_four = counter_create("four", 2, COUNTER_FLAG_PERSIST | COUNTER_FLAG_SAVE | COUNTER_FLAG_NO_OVERWRITE);
counter_bump_value($counter_four, 1);

print_counter_info($counter_one);
print_counter_info($counter_two);
print_counter_info($counter_three);
print_counter_info($counter_four);
?>

When run once, the above example outputs:

Counter's name is 'one' and is persistent. Its current value is 2.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 3.

If run a second time within the same instance of PHP, it outputs:

Counter's name is 'one' and is persistent. Its current value is 4.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 4.

If then run a third time in a different instance of PHP, it outputs:

Counter's name is 'one' and is persistent. Its current value is 2.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 5.

User Contributed Notes

There are no user contributed notes for this page.
Basic interface
Objective interface
Примеры


Objective interface

The objective interface provides an object-oriented way to access the extended interfaces. The following example shows how the above one would be implemented using the objective interface. The output of this example is exactly the same, except that instead of printing "Not a valid counter!", this will instead issue a PHP warning that the variable $counter_three is not an object. This example shows that it is possible to subclass the Counter class defined by the extension, as well as that the counter's value is maintained using an instance variable rather than method access.

Пример #1 "counter"'s objective interface

<?php
class MyCounter extends Counter
{
    public function printCounterInfo() {
        printf("Counter's name is '%s' and is%s persistent. Its current value is %d.\n",
            $this->getMeta(COUNTER_META_NAME),
            $this->getMeta(COUNTER_META_IS_PERSISTENT) ? '' : ' not',
            $this->value);
    }
}

Counter::setCounterClass("MyCounter");
if (($counter_one = Counter::getNamed("one")) === NULL) {
    $counter_one = new Counter("one", 0, COUNTER_FLAG_PERSIST);
}
$counter_one->bumpValue(2); // we aren't allowed to "set" the value directly
$counter_two = new Counter("two", 5);
$counter_three = Counter::getNamed("three");
$counter_four = new Counter("four", 2, COUNTER_FLAG_PERSIST | COUNTER_FLAG_SAVE | COUNTER_FLAG_NO_OVERWRITE);
$counter_four->bumpValue(1);

$counter_one->printCounterInfo();
$counter_two->printCounterInfo();
$counter_three->printCounterInfo();
$counter_four->printCounterInfo();
?>

User Contributed Notes

There are no user contributed notes for this page.
Extended interface
Counter
Примеры


The Counter class

Введение

Represents a single counter object.

Обзор классов

Counter {
__construct ( string $name [, integer $initial_value [, integer $flags ]] )
integer getValue ( void )
bumpValue ( integer $offset )
void resetValue ( void )
mixed getMeta ( integer $attribute )
static Counter getNamed ( string $name )
static void setCounterClass ( string $name )
}

Содержание

  • Counter::__construct — Creates an instance of a Counter which maintains a single numeric value.
  • Counter::getValue — Get the current value of a counter.
  • Counter::bumpValue — Change the current value of a counter.
  • Counter::resetValue — Reset the current value of a counter.
  • Counter::getMeta — Return a piece of metainformation about a counter.
  • Counter::getNamed — Retrieve an existing named counter.
  • Counter::setCounterClass — Set the class returned by Counter::getNamed.

User Contributed Notes

There are no user contributed notes for this page.
Objective interface
Counter::__construct
The "counter" Extension - A Continuing Example


Creates an instance of a Counter which maintains a single numeric value.

Counter
Counter::getValue
Counter
PHP Manual

Counter::__construct

Counter::__construct — Creates an instance of a Counter which maintains a single numeric value.

Описание

Counter::__construct() ( string $name [, integer $initial_value [, integer $flags ]] )

Creates an instance of a Counter which maintains a single numeric value.

Список параметров

name
The new counter's name.
initial_value
The initial value of the counter. Defaults to zero (0).
flags
Flags for the new counter, chosen from the COUNTER_FLAG_* constants.

Возвращаемые значения

Returns a Counter object on success.

Ошибки

Counter::__construct() throws an Exception if something goes wrong.

User Contributed Notes

There are no user contributed notes for this page.
Counter
Counter::getValue
Counter


Get the current value of a counter.

Counter::__construct
Counter::bumpValue
Counter
PHP Manual

Counter::getValue

Counter::getValue — Get the current value of a counter.

Описание

integer Counter::getValue ( void )

Counter::getValue() returns the current value of a counter.

Возвращаемые значения

Counter::getValue() returns an integer.

Смотрите также

  • Counter::bumpValue() - Change the current value of a counter.
  • Counter::resetValue() - Reset the current value of a counter.

User Contributed Notes

There are no user contributed notes for this page.
Counter::__construct
Counter::bumpValue
Counter


Change the current value of a counter.

Counter::getValue
Counter::resetValue
Counter
PHP Manual

Counter::bumpValue

Counter::bumpValue — Change the current value of a counter.

Описание

Counter::bumpValue ( integer $offset )

Counter::bumpValue() updates the current value of a counter.

Список параметров

offset
The amount by which to change the counter's value. Can be negative.

Смотрите также

  • Counter::getValue() - Get the current value of a counter.
  • Counter::resetValue() - Reset the current value of a counter.

User Contributed Notes

There are no user contributed notes for this page.
Counter::getValue
Counter::resetValue
Counter


Reset the current value of a counter.

Counter::bumpValue
Counter::getMeta
Counter
PHP Manual

Counter::resetValue

Counter::resetValue — Reset the current value of a counter.

Описание

void Counter::resetValue ( void )

Counter::resetValue() resets the current value of a counter to its original initial value.

Смотрите также

  • Counter::getValue() - Get the current value of a counter.
  • Counter::bumpValue() - Change the current value of a counter.

User Contributed Notes

There are no user contributed notes for this page.
Counter::bumpValue
Counter::getMeta
Counter


Return a piece of metainformation about a counter.

Counter::resetValue
Counter::getNamed
Counter
PHP Manual

Counter::getMeta

Counter::getMeta — Return a piece of metainformation about a counter.

Описание

mixed Counter::getMeta ( integer $attribute )

Counter::getMeta() returns metainformation about a counter.

Список параметров

attribute
The metainformation to retrieve.

Возвращаемые значения

Counter::getMeta() returns values of varying types based on which metainformation was requested.

User Contributed Notes

There are no user contributed notes for this page.
Counter::resetValue
Counter::getNamed
Counter


Retrieve an existing named counter.

Counter::getMeta
Counter::setCounterClass
Counter
PHP Manual

Counter::getNamed

Counter::getNamed — Retrieve an existing named counter.

Описание

static Counter Counter::getNamed ( string $name )

Counter::getNamed() returns an existing counter by name if that name exists, or NULL otherwise. This is a static function.

Список параметров

name
The counter name to search for.

Возвращаемые значения

Counter::getNamed() returns an existing counter by name if that name exists, or NULL otherwise.

User Contributed Notes

There are no user contributed notes for this page.
Counter::getMeta
Counter::setCounterClass
Counter


Set the class returned by Counter::getNamed.

Counter::getNamed
Basic
Counter
PHP Manual

Counter::setCounterClass

Counter::setCounterClass — Set the class returned by Counter::getNamed().

Описание

static void Counter::setCounterClass ( string $name )

Counter::setCounterClass() changes the class of objects returned by Counter::getNamed(). The class being set must not have a public constructor and must be a subclass of Counter. If these conditions are not met, a fatal error is raised. This is a static function.

Список параметров

name
The name of the class to use.

User Contributed Notes

There are no user contributed notes for this page.
Counter::getNamed
Basic
Counter


The basic interface

Содержание

  • counter_get — Get the current value of the basic counter.
  • counter_bump — Update the current value of the basic counter.
  • counter_reset — Reset the current value of the basic counter.

User Contributed Notes

There are no user contributed notes for this page.
Counter::setCounterClass
counter_get
The "counter" Extension - A Continuing Example


Get the current value of the basic counter.

Basic
counter_bump
Basic
PHP Manual

counter_get

counter_get — Get the current value of the basic counter.

Описание

integer counter_get ( void )

counter_get() returns the current value of the basic interface's counter.

Возвращаемые значения

counter_get() returns an integer.

Смотрите также

  • counter_bump() - Update the current value of the basic counter.
  • counter_reset() - Reset the current value of the basic counter.

User Contributed Notes

There are no user contributed notes for this page.
Basic
counter_bump
Basic


Update the current value of the basic counter.

counter_get
counter_reset
Basic
PHP Manual

counter_bump

counter_bump — Update the current value of the basic counter.

Описание

void counter_bump ( integer $offset )

counter_bump() updates the current value of the basic interface's counter.

Список параметров

offset
The amount by which to change the counter's value. Can be negative.

Смотрите также

  • counter_get() - Get the current value of the basic counter.
  • counter_reset() - Reset the current value of the basic counter.

User Contributed Notes

There are no user contributed notes for this page.
counter_get
counter_reset
Basic


Reset the current value of the basic counter.

counter_bump
Extended
Basic
PHP Manual

counter_reset

counter_reset — Reset the current value of the basic counter.

Описание

void counter_reset ( void )

counter_reset() resets the current value of the basic interface's counter to its original initial value.

Смотрите также

  • counter_get() - Get the current value of the basic counter.
  • counter_bump() - Update the current value of the basic counter.

User Contributed Notes

There are no user contributed notes for this page.
counter_bump
Extended
Basic


The extended interface

Содержание

  • counter_create — Creates a counter which maintains a single numeric value.
  • counter_get_value — Get the current value of a counter resource.
  • counter_bump_value — Change the current value of a counter resource.
  • counter_reset_value — Reset the current value of a counter resource.
  • counter_get_meta — Return a piece of metainformation about a counter resource.
  • counter_get_named — Retrieve an existing named counter as a resource.

User Contributed Notes

There are no user contributed notes for this page.
counter_reset
counter_create
The "counter" Extension - A Continuing Example


Creates a counter which maintains a single numeric value.

Extended
counter_get_value
Extended
PHP Manual

counter_create

counter_create — Creates a counter which maintains a single numeric value.

Описание

resource counter_create ( string $name [, integer $initial_value [, integer $flags ]] )

Creates a counter which maintains a single numeric value.

Список параметров

name
The new counter's name.
initial_value
The initial value of the counter. Defaults to zero (0).
flags
Flags for the new counter, chosen from the COUNTER_FLAG_* constants.

Возвращаемые значения

Returns a counter resource.

User Contributed Notes

There are no user contributed notes for this page.
Extended
counter_get_value
Extended


Get the current value of a counter resource.

counter_create
counter_bump_value
Extended
PHP Manual

counter_get_value

counter_get_value — Get the current value of a counter resource.

Описание

integer counter_get_value ( resource $counter )

counter_get_value() returns the current value of a counter resource.

Список параметров

counter
The counter resource to operate on.

Возвращаемые значения

counter_get_value() returns an integer.

Смотрите также

  • counter_bump_value() - Change the current value of a counter resource.
  • counter_reset_value() - Reset the current value of a counter resource.

User Contributed Notes

There are no user contributed notes for this page.
counter_create
counter_bump_value
Extended


Change the current value of a counter resource.

counter_get_value
counter_reset_value
Extended
PHP Manual

counter_bump_value

counter_bump_value — Change the current value of a counter resource.

Описание

void counter_bump_value ( resource $counter , integer $offset )

counter_bump_value() updates the current value of a counter resource.

Список параметров

counter
The counter resource to operate on.
offset
The amount by which to change the counter's value. Can be negative.

Смотрите также

  • counter_get_value() - Get the current value of a counter resource.
  • counter_reset_value() - Reset the current value of a counter resource.

User Contributed Notes

There are no user contributed notes for this page.
counter_get_value
counter_reset_value
Extended


Reset the current value of a counter resource.

counter_bump_value
counter_get_meta
Extended
PHP Manual

counter_reset_value

counter_reset_value — Reset the current value of a counter resource.

Описание

void counter_reset_value ( resource $counter )

counter_reset_value() resets the current value of a counter resource to its original initial value.

Список параметров

counter
The counter resource to operate on.

Смотрите также

  • counter_get_value() - Get the current value of a counter resource.
  • counter_bump_value() - Change the current value of a counter resource.

User Contributed Notes

There are no user contributed notes for this page.
counter_bump_value
counter_get_meta
Extended


Return a piece of metainformation about a counter resource.

counter_reset_value
counter_get_named
Extended
PHP Manual

counter_get_meta

counter_get_meta — Return a piece of metainformation about a counter resource.

Описание

mixed counter_get_meta ( resource $counter , integer $attribute )

counter_get_meta() returns metainformation about a counter resource.

Список параметров

counter
The counter resource to operate on.
attribute
The metainformation to retrieve.

Возвращаемые значения

counter_get_meta() returns values of varying types based on which metainformation was requested.

User Contributed Notes

There are no user contributed notes for this page.
counter_reset_value
counter_get_named
Extended


Retrieve an existing named counter as a resource.

counter_get_meta
The PHP 5 build system
Extended
PHP Manual

counter_get_named

counter_get_named — Retrieve an existing named counter as a resource.

Описание

resource Counter::getNamed ( string $name )

counter_get_named() returns an existing counter by name if that name exists, or NULL otherwise.

Список параметров

name
The counter name to search for.

Возвращаемые значения

counter_get_name() returns an existing counter by name if that name exists, or NULL otherwise.

User Contributed Notes

There are no user contributed notes for this page.
counter_get_meta
The PHP 5 build system
Extended


The PHP 5 build system

Содержание

  • Building PHP for extension development
  • The ext_skel script
  • Talking to the UNIX build system: config.m4
  • Talking to the Windows build system: config.w32

With all the functionality and flexibility available in PHP 5, it is no surprise that it consists of several thousand files and over one million lines of source code. Equally unsurprising is the necessity of a build system to manage so much data. This section describes how to set PHP up for extension development, the layout of an extension within the PHP source tree, and how to interface your extension with the build system.

User Contributed Notes

There are no user contributed notes for this page.
counter_get_named
Building PHP for extension development
Ядро PHP: Руководство хакера по Zend Engine


Building PHP for extension development

In a typical PHP installation, the need for high performance almost always results in optimization at the cost of debugging facilities. This is a reasonable tradeoff for production use, but when developing an extension it falls short. What we need is a build of PHP which will give us some hints what has gone wrong when something does.

The Zend Engine provides a memory manager which is capable of tracking memory leaks in extensions and providing detailed debugging information. This tracking is disabled by default, as is thread-safety. To turn them on, pass the --enable-debug and --enable-maintainer-zts options to configure, along with whatever options you typically use. For instructions on building PHP from source, see the instructions at Общие инструкции по установке. A typical configure line might look like this:

$ ./configure --prefix=/where/to/install/php --enable-debug --enable-maintainer-zts --enable-cgi --enable-cli --with-mysql=/path/to/mysql

User Contributed Notes

rich dot d dot rich at gmail dot com 02-Apr-2011 03:51
This may be obvious, but if you are installing PHP under a home directory, don't enter '--prefix=~/place'. Use the full form '--prefix=/home/fred/place'.

Otherwise, it will half work and cause problems (because the shell char gets expanded in some places and not others).
The PHP 5 build system
The ext_skel script
The PHP 5 build system


The ext_skel script

A PHP extension is composed of several files common to all extensions. As the details of many of those files are similar from extension to extension, it can be laborious to duplicate the content for each one. Fortunately, there is a script which can do all of the initial setup for you. It's called ext_skel, and it's been distributed with PHP since 4.0.

Running ext_skel with no parameters produces this output in PHP 5.2.2:

php-5.2.2/ext$ ./ext_skel
./ext_skel --extname=module [--proto=file] [--stubs=file] [--xml[=file]]
           [--skel=dir] [--full-xml] [--no-help]

  --extname=module   module is the name of your extension
  --proto=file       file contains prototypes of functions to create
  --stubs=file       generate only function stubs in file
  --xml              generate xml documentation to be added to phpdoc-cvs
  --skel=dir         path to the skeleton directory
  --full-xml         generate xml documentation for a self-contained extension
                     (not yet implemented)
  --no-help          don't try to be nice and create comments in the code
                     and helper functions to test if the module compiled
Generally, when developing a new extension the only parameters you will be interested in are --extname and --no-help. Unless you are already experienced with the structure of an extension, you will not want to use --no-help; specifying it causes ext_skel to leave out many helpful comments in the files it generates.

This leaves you with --extname, which tells ext_skel what the name of your extension is. This "name" is an all-lowercase identifier containing only letters and underscores which is unique among everything in the ext/ folder of your PHP distribution.

The --proto option is intended to allow the developer to specify a header file from which a set of PHP functions will be created, ostensibly for the purpose of developing an extension based on a library, but it often functions poorly with most modern header files. A test run on the zlib.h header resulted in a very large number of empty and nonsense prototypes in the ext_skel output files. The --xml and --full-xml options are entirely nonfunctional thus far. The --skel option can be used to specify a modified set of skeleton files to work from, a topic which is beyond the scope of this section.

User Contributed Notes

There are no user contributed notes for this page.
Building PHP for extension development
Talking to the UNIX build system: config.m4
The PHP 5 build system


Talking to the UNIX build system: config.m4

The config.m4 file for an extension tells the UNIX build system what configure options your extension supports, what external libraries and includes you require, and what source files are to be compiled as part of it. A reference to all the commonly used autoconf macros, both PHP-specific and those built into autoconf, is given in the Zend Engine 2 API reference section.

Подсказка

The version of autoconf you have installed makes a difference when developing an extension. For PHP 5.3 and earlier, you will have the best results with autoconf version 2.13 but versions up to and including 2.59 will work. For PHP 5.4 and later the oldest autoconf version you can use is 2.59 and you will have better results with later versions.

Пример #1 An example config.m4 file

dnl $Id$
dnl config.m4 for extension example
PHP_ARG_WITH(example, for example support,
[  --with-example[=FILE]       Include example support. File is the optional path to example-config])
PHP_ARG_ENABLE(example-debug, whether to enable debugging support in example,
[  --enable-example-debug        example: Enable debugging support in example], no, no)
PHP_ARG_WITH(example-extra, for extra libraries for example,
[  --with-example-extra=DIR      example: Location of extra libraries for example], no, no)

dnl Check whether the extension is enabled at all
if test "$PHP_EXAMPLE" != "no"; then

  dnl Check for example-config. First try any path that was given to us, then look in $PATH
  AC_MSG_CHECKING([for example-config])
  EXAMPLE_CONFIG="example-config"
  if test "$PHP_EXAMPLE" != "yes"; then
    EXAMPLE_PATH=$PHP_EXAMPLE
  else
    EXAMPLE_PATH=`$php_shtool path $EXAMPLE_CONFIG`
  fi

  dnl If a usable example-config was found, use it
  if test -f "$EXAMPLE_PATH" && test -x "$EXAMPLE_PATH" && $EXAMPLE_PATH --version > /dev/null 2>&1; then
    AC_MSG_RESULT([$EXAMPLE_PATH])
    EXAMPLE_LIB_NAME=`$EXAMPLE_PATH --libname`
    EXAMPLE_INCDIRS=`$EXAMPLE_PATH --incdirs`
    EXAMPLE_LIBS=`$EXAMPLE_PATH --libs`

    dnl Check that the library works properly
    PHP_CHECK_LIBRARY($EXAMPLE_LIB_NAME, example_critical_function,
    [
      dnl Add the necessary include dirs
      PHP_EVAL_INCLINE($EXAMPLE_INCDIRS)
      dnl Add the necessary libraries and library dirs
      PHP_EVAL_LIBLINE($EXAMPLE_LIBS, EXAMPLE_SHARED_LIBADD)
    ],[
      dnl Bail out
      AC_MSG_ERROR([example library not found. Check config.log for more information.])
    ],[$EXAMPLE_LIBS]
    )
  else
    dnl No usable example-config, bail
    AC_MSG_RESULT([not found])
    AC_MSG_ERROR([Please check your example installation.])
  fi

  dnl Check whether to enable debugging
  if test "$PHP_EXAMPLE_DEBUG" != "no"; then
    dnl Yes, so set the C macro
    AC_DEFINE(USE_EXAMPLE_DEBUG,1,[Include debugging support in example])
  fi

  dnl Check for the extra support
  if test "$PHP_EXAMPLE_EXTRA" != "no"; then
    if test "$PHP_EXAMPLE_EXTRA" == "yes"; then
      AC_MSG_ERROR([You must specify a path when using --with-example-extra])
    fi

    PHP_CHECK_LIBRARY(example-extra, example_critical_extra_function,
    [
      dnl Add the neccessary paths
      PHP_ADD_INCLUDE($PHP_EXAMPLE_EXTRA/include)
      PHP_ADD_LIBRARY_WITH_PATH(example-extra, $PHP_EXAMPLE_EXTRA/lib, EXAMPLE_SHARED_LIBADD)
      AC_DEFINE(HAVE_EXAMPLEEXTRALIB,1,[Whether example-extra support is present and requested])
      EXAMPLE_SOURCES="$EXAMPLE_SOURCES example_extra.c"
    ],[
      AC_MSG_ERROR([example-extra lib not found. See config.log for more information.])
    ],[-L$PHP_EXAMPLE_EXTRA/lib]
    )
  fi

  dnl Finally, tell the build system about the extension and what files are needed
  PHP_NEW_EXTENSION(example, example.c $EXAMPLE_SOURCES, $ext_shared)
  PHP_SUBST(EXAMPLE_SHARED_LIBADD)
fi

A short introduction to autoconf syntax

config.m4 files are written using the GNU autoconf syntax. It can be described in a nutshell as shell scripting augmented by a powerful macro language. Comments are delimited by the string dnl, and strings are quoted using left and right brackets (e.g. [ and ]). Quoting of strings can be nested as many times as needed. A full reference to the syntax can be found in the autoconf manual at » http://www.gnu.org/software/autoconf/manual/.

PHP_ARG_*: Giving users the option

The very first thing seen in the example config.m4 above, aside from a couple of comments, are three lines using PHP_ARG_WITH() and PHP_ARG_ENABLE(). These provide configure with the options and help text seen when running ./configure --help. As the names suggest, the difference between the two is whether they create a --with-* option or an --enable-* option. Every extension should provide at least one or the other with the extension name, so that users can choose whether or not to build the extension into PHP. By convention, PHP_ARG_WITH() is used for an option which takes a parameter, such as the location of a library or program required by an extension, while PHP_ARG_ENABLE() is used for an option which represents a simple flag.

Пример #2 Sample configure output

$ ./configure --help
...
  --with-example[=FILE]       Include example support. FILE is the optional path to example-config
  --enable-example-debug        example: Enable debugging support in example
  --with-example-extra=DIR      example: Location of extra libraries for example
...

$ ./configure --with-example=/some/library/path/example-config --disable-example-debug --with-example-extra=/another/library/path
...
checking for example support... yes
checking whether to enable debugging support in example... no
checking for extra libraries for example... /another/library/path
...

Замечание:

Regardless of the order in which options are specified on the command line when configure is called, the checks will be run in the order they are specified in config.m4.

Processing the user's choices

Now that config.m4 can provide the user with some choices of what to do, it's time to act upon those choices. In the example above, the obvious default for all three options, if any of them are unspecified, is "no". As a matter of convention, it is best to use this as the default for the option which enables the extension, as it will be overridden by phpize for extensions built separately, and should not clutter the extension space by default when being built into PHP. The code to process the three options is by far the most complicated.

Handling the --with-example[=FILE] option

The first check made of the --with-example[=FILE] option is whether it was set at all. As this option controls the inclusion of the entire extension, if it was unspecified, given in the negative form (--without-example ), or given the value "no", nothing else is done at all. In the example above, it is specified with the value /some/library/path/example-config, so the first test succeeds.

Next, the code calls AC_MSG_CHECKING(), an autoconf macro which outputs a standard "checking for something" line, and checks whether the user gave an explicit path to the fictional example-config. In this example, PHP_EXAMPLE got the value /some/library/path/example-config, which is now copied into the EXAMPLE_PATH variable. Had the user specified only --with-example , the code would have executed $php_shtool path $EXAMPLE_CONFIG, which would try to guess the location of example-config using the user's current PATH. Either way, the next step is to check whether the chosen EXAMPLE_PATH is a regular file, is executable, and can be run successfully. If so, AC_MSG_RESULT() is called, which completes the output line started by AC_MSG_CHECKING(). Otherwise, AC_MSG_ERROR() is called, which prints the given message and halts configure immediately.

The code now determines some site-specific configuration information by running example-config several times. The next call is to PHP_CHECK_LIBRARY(), a macro provided by the PHP buildsystem as a wrapper around autoconf's AC_CHECK_LIB(). PHP_CHECK_LIBRARY() attempts to compile, link, and run a program which calls the symbol specified by the second parameter in the library specified by the first, using the string given in the fifth as extra linker options. If the attempt succeeds, the script given in the third parameter is run. This script tells the PHP buildsystem to extract include paths, library paths, and library names from the raw option strings example-config provided. If the attempt fails, the script in the fourth parameter is run instead. In this case, AC_MSG_ERROR() is called to stop processing.

Handling the --enable-example-debug option

Processing the --enable-example-debug is much simpler. A simple check for its truth value is performed. If that check succeeds, AC_DEFINE() is called to make the C macro USE_EXAMPLE_DEBUG available to the source of the extension. The third parameter is a comment string for config.h; it is safe to leave this empty, and often is.

Handling the --with-example-extra=DIR option

For the sake of this example, the fictional "extra" functionality requested by the --with-example-extra=DIR option does not share the fictional example-config program, nor does it have any default paths to search. Therefore, the user is required to provide the installation prefix of the necessary library. This setup is somewhat unlikely in a real-world extension, but is considered illustrative.

The code begins in a now-familiar way by checking the truth value of PHP_EXAMPLE_EXTRA. If a negative form was provided, no further processing is done; the user did not request extra functionality. If a positive form was provided without a parameter, AC_MSG_ERROR() is called to halt processing. The next step is another invocation of PHP_CHECK_LIBRARY(). This time, since there is no set of predefined compiler options provided, PHP_ADD_INCLUDE() and PHP_ADD_LIBRARY_WITH_PATH() are used to construct the necessary include paths, library paths, and library flags for the extra functionality. AC_DEFINE() is also called to indicate to the code that the extra functionality was both requested and available, and a variable is set to tell later code that there are extra source files to build. If the check fails, the familiar AC_MSG_ERROR() is called. A different way to handle the failure would have been to call AC_MSG_WARNING() instead, e.g.:

AC_MSG_WARNING([example-extra lib not found. example will be built without extra functionality.])

In this case, configure would print a warning message rather than an error, and continue processing. Which way such failures are handled is a design decision left to the extension developer.

Telling the buildsystem what was decided

With all the necessary includes and libraries specified, with all the options processed and macros defined, one more thing remains to be done: The build system must be told to build the extension itself, and which files are to be used for that. To do this, the PHP_NEW_EXTENSION() macro is called. The first parameter is the name of the extension, which is the same as the name of the directory containing it. The second parameter is the list of all source files which are part of the extension. See PHP_ADD_BUILD_DIR() for information about adding source files in subdirectories to the build process. The third parameter should always be $ext_shared, a value which was determined by configure when PHP_ARG_WITH() was called for --with-example[=FILE] . The fourth parameter specifies a "SAPI class", and is only useful for extensions which require the CGI or CLI SAPIs specifically. It should be left empty in all other cases. The fifth parameter specifies a list of flags to be added to CFLAGS while building the extension; the sixth is a boolean value which, if "yes", will force the entire extension to be built using $CXX instead of $CC. All parameters after the third are optional. Finally, PHP_SUBST() is called to enable shared builds of the extension. See Extension FAQs for more information on disabling support for building an extension in shared mode.

The counter extension's config.m4 file

The counter extension previously documented has a much simpler config.m4 file than that described above, as it doesn't make use of many buildsystem features. This is a preferred method of operation for any extension that doesn't use an external or bundled library.

Пример #3 counter's config.m4 file

dnl
$
Id$
dnl config.m4 for extension counter

PHP_ARG_ENABLE(counter, for counter support,
[  --enable-counter            Include counter support])

dnl Check whether the extension is enabled at all
if test "$PHP_COUNTER" != "no"; then
  dnl Finally, tell the build system about the extension and what files are needed
  PHP_NEW_EXTENSION(counter, counter.c counter_util.c, $ext_shared)
  PHP_SUBST(COUNTER_SHARED_LIBADD)
fi

User Contributed Notes

There are no user contributed notes for this page.
The ext_skel script
Talking to the Windows build system: config.w32
The PHP 5 build system


Talking to the Windows build system: config.w32

An extension's config.w32 file is similar in usage to the config.m4 file, with two critical differences: first, it is used for Windows builds, and second, it is written in JavaScript. This section makes no attempt to cover JavaScript syntax. For the moment, this section is incomplete in lieu of a Win32 testbed, and an experimental-only port of the example config.m4 is the only example provided.

Пример #1 An example config.w32 file

// $Id$
// vim:ft=javascript
ARG_WITH("example", "for example support", "no");
ARG_ENABLE("example-debug", "for debugging support in example", "no")
ARG_WITH("example-extra", "for extra functionality in example", "no")
if (PHP_EXAMPLE != "no") {
    if (CHECK_LIB("libexample.lib", "example", PHP_EXAMPLE) &&
        CHECK_HEADER_ADD_INCLUDE("example.h", "CFLAGS_EXAMPLE", PHP_EXAMPLE + "\\include")) {

        if (PHP_EXAMPLE_DEBUG != "no") {
            AC_DEFINE('USE_EXAMPLE_DEBUG', 1, 'Debug support in example');
        }

        if (PHP_EXAMPLE_EXTRA != "no" &&
            CHECK_LIB("libexample-extra.lib", "example", PHP_EXAMPLE) &&
            CHECK_HEADER_ADD_INCLUDE("example-extra.h", "CFLAGS_EXAMPLE", PHP_EXAMPLE + ";" + PHP_PHP_BUILD + "\\include") {
            AC_DEFINE('HAVE_EXAMPLEEXTRA', 1, 'Extra functionality in example');
            HAVE_EXTRA = 1;
        } else {
            WARNING( "extra example functionality not enabled, lib not found" );
        }

        EXTENSION("example", "example.c");
        if (HAVE_EXTRA == 1) {
            ADD_SOURCES("example-extra.c");
        }
    } else {
        WARNING( "example not enabled; libraries not found" );
    }
}

The counter extension's config.w32 file

The counter extension previously documented has a much simpler config.w32 file than that described above, as it doesn't make use of many buildsystem features.

Пример #2 counter's config.w32 file

// $Id$
// vim:ft=javascript
ARG_ENABLE("counter", "for counter support", "no");
if (PHP_COUNTER != "no") {
    EXTENSION("counter", "counter.c");
    ADD_SOURCE("counter-util.c");
}

User Contributed Notes

There are no user contributed notes for this page.
Talking to the UNIX build system: config.m4
Extension structure
The PHP 5 build system


Extension structure

Содержание

  • Files which make up an extension
  • Basic constructs
  • The zend_module structure
  • Extension globals
  • Life cycle of an extension
  • Testing an extension

Many extension-writing guides focus on simple examples first and ignore the requirements of more complex implementations until later. Often such guides must repeat themselves over and over in order to describe these new features. This section describes extension structure from the perspective of a mature, practical implementation, in order to prepare users for needs and issues they will almost always encounter in the process of extension development.

User Contributed Notes

There are no user contributed notes for this page.
Talking to the Windows build system: config.w32
Files which make up an extension
Ядро PHP: Руководство хакера по Zend Engine


Files which make up an extension

Whether created by hand, using ext_skel, or by an alternate extension generator, such as » CodeGen, all extensions will have at least four files:

config.m4

UNIX build system configuration (see Talking to the UNIX build system: config.m4)

config.w32

Windows buildsystem configuration (see Talking to the Windows build system: config.w32)

php_counter.h

When building an extension as static module into the PHP binary the build system expects a header file with php_ prepended to the extension name which includes a declaration for a pointer to the extension's module structure. This file usually contains additional macros, prototypes, and globals, just like any header.

counter.c

Main extension source file. By convention, the name of this file is the extension name, but this is not a requirement. This file contains the module structure declaration, INI entries, management functions, userspace functions, and other requirements of an extension.

The buildsystem files are discussed elsewhere; this section concentrates on the rest. These four files make up the bare minimum for an extension, which may also contain any number of headers, source files, unit tests, and other support files. The list of files in the counter extension might look like this:

Пример #1 Files in the counter extension, in no particular order

ext/
 counter/
  .svnignore
  config.m4
  config.w32
  counter_util.h
  counter_util.c
  php_counter.h
  counter.c
  package.xml
  CREDITS
  tests/
   critical_function_001.phpt
   critical_function_002.phpt
   optional_function_001.phpt
   optional_function_002.phpt

Non-source files

The .svnignore file is used for extensions which are checked into the PHP Subversion repository (usually » PECL); the one generated by ext_skel contains:

.deps
*.lo
*.la

These lines tell Subversion to ignore interim files generated by the PHP buildsystem. This is only a convenience, and can be omitted completely without ill effect.

The CREDITS file lists the contributors and/or maintainers of the extension in plain text format. The main purpose of this file is generating the credits information for bundled extensions as used by phpcredits(). By convention the first line of the file should hold the name of the extension, the second a comma separated list of contributors. The contributors are usually ordered by the chronological order of their contributions. In a » PECL package, this information is already maintained in package.xml, for example. This is another file which can be omitted without ill effect.

The package.xml file is specific to » PECL-based extensions; it is a metainformation file which gives details about an extension's dependencies, authors, installation requirements, and other tidbits. In an extension not being hosted in » PECL, this file is extraneous.

User Contributed Notes

There are no user contributed notes for this page.
Extension structure
Basic constructs
Extension structure


Basic constructs

C is a very low-level language by modern definitions. This means that it has no built-in support for many features that PHP takes for granted, such as reflection, dynamic module loading, bounds checking, threadsafe data management and various useful data structures including linked lists and hash tables. At the same time, C is a common denominator of language support and functionality. Given enough work, none of these concepts are impossible; the Zend Engine uses them all.

A lot of effort has gone into making the Zend API both extensible and understandable, but C forces certain necessary declarations upon any extension that to an inexperienced eye seem redundant or plain unnecessary. All of those constructs, detailed in this section, are "write once and forget" in Zend Engine 2 and 3. Here are some excerpts from the pre-generated php_counter.h and counter.c files created by PHP 5.3's ext_skel, showing the pre-generated declarations:

Замечание: The astute reader will notice that there are several declarations in the real files that aren't shown here. Those declarations are specific to various Zend subsystems and are discussed elsewhere as appropriate.

extern zend_module_entry counter_module_entry;
#define phpext_counter_ptr &counter_module_entry

#ifdef PHP_WIN32
#    define PHP_COUNTER_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
#    define PHP_COUNTER_API __attribute__ ((visibility("default")))
#else
#    define PHP_COUNTER_API
#endif

#ifdef ZTS
#include "TSRM.h"
#endif

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_counter.h"

/* ... */

#ifdef COMPILE_DL_COUNTER
ZEND_GET_MODULE(counter)
#endif
  • The lines concerning counter_module_entry declare a global variable, and a macroed pointer to it, which contains the zend_module_entry for the extension. Despite the later discussion regarding the drawbacks of "true" globals, this usage is intentional; Zend takes precautions to avoid misusing this variable.
  • PHP_COUNTER_API is declared for use by non-PHP functions the module intends to export for the use of other modules. The counter extension doesn't declare any of these, and in the final version of the header file, this macro has been removed. The PHPAPI macro is declared identically elsewhere and is used by the standard extension to make the phpinfo() utility functions available to other extensions.
  • The include of TSRM.h is skipped if PHP, or the extension, isn't being compiled with thread-safety, since in that case TSRM isn't used.
  • A standard list of includes, especially the extension's own php_counter.h, is given. config.h gives the extension access to determinations made by configure. php.h is the gateway to the entire PHP and Zend APIs. php_ini.h adds the APIs for runtime configuration (INI) entries. Not all extensions will use this. Finally, ext/standard/info.h imports the aforementioned phpinfo() utility API.
  • COMPILE_DL_COUNTER will only be defined by configure if the counter extension is both enabled and wants to be built as a dynamically loadable module instead of being statically linked into PHP. ZEND_GET_MODULE defines a tiny function which Zend can use to get the extension's zend_module_entry at runtime.

    Замечание: The astute reader who has peeked into main/php_config.h after trying to build with the counter module enabled statically may have noticed that there is also a HAVE_COUNTER constant defined that the source code doesn't check for. There's a simple reason this check isn't done: It's unnecessary. If the extension isn't enabled, the source file will never be compiled.

User Contributed Notes

There are no user contributed notes for this page.
Files which make up an extension
The zend_module structure
Extension structure


The zend_module structure

The main source file of a PHP extension contains several new constructs for a C programmer. The most important of these, the one touched first when starting a new extension, is the zend_module structure. This structure contains a wealth of information that tells the Zend Engine about the extension's dependencies, version, callbacks, and other critical data. The structure has mutated considerably over time; this section will focus on the structure as it has appeared since PHP 5.2, and will identify the very few parts which have changed in PHP 5.3.

The zend_module declaration from counter.c looks like this before any code has been written. The example file was generated by ext_skel --extname=counter, with some obsolete constructs removed:

Пример #1 zend_module declaration in the counter extension

/* {{{ counter_module_entry
 */
zend_module_entry counter_module_entry = {
    STANDARD_MODULE_HEADER,
    "counter",
    counter_functions,
    PHP_MINIT(counter),
    PHP_MSHUTDOWN(counter),
    PHP_RINIT(counter),        /* Replace with NULL if there's nothing to do at request start */
    PHP_RSHUTDOWN(counter),    /* Replace with NULL if there's nothing to do at request end */
    PHP_MINFO(counter),
    "0.1", /* Replace with version number for your extension */
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

This may look a bit daunting at first glance, but most of it is very simple to understand. Here's the declaration of zend_module from zend_modules.h in PHP 5.3:

Пример #2 zend_module definition in PHP 5.3

struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    const struct _zend_ini_entry *ini_entry;
    const struct _zend_module_dep *deps;
    const char *name;
    const struct _zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    const char *version;
    size_t globals_size;
#ifdef ZTS
    ts_rsrc_id* globals_id_ptr;
#else
    void* globals_ptr;
#endif
    void (*globals_ctor)(void *global TSRMLS_DC);
    void (*globals_dtor)(void *global TSRMLS_DC);
    int (*post_deactivate_func)(void);
    int module_started;
    unsigned char type;
    void *handle;
    int module_number;
};

Many of these fields will never be touched by an extension writer. There are a number of standard macros that set them to their proper values automatically. The macro STANDARD_MODULE_HEADER fills in everything up to the deps field. Alternatively, the STANDARD_MODULE_HEADER_EX will leave the deps field empty for the developer's use. The developer is always responsible for everything from name to version. After that, the STANDARD_MODULE_PROPERTIES macro will fill in the rest of the structure, or the STANDARD_MODULE_PROPERTIES_EX macro can be used to leave the extension globals and post-deactivation function fields unfilled. Most modern extensions will make use of module globals.

Замечание:

This table gives the values that each field would have if the developer were to fill in the structure entirely by hand, without recourse to any of the shortcut macros. This is not recommended. The "correct" values for many fields may change. Use the macros whenever possible.

Module structure field values
Field | Value | Description
size [1] [2] [3] | sizeof(zend_module_entry) | The size in bytes of the structure.
zend_api [1] [2] [3] | ZEND_MODULE_API_NO | The version of the Zend API this module was compiled against.
zend_debug [1] [2] [3] | ZEND_DEBUG | A flag indicating whether the module was compiled with debugging turned on.
zts [1] [2] [3] | USING_ZTS | A flag indicating whether the module was compiled with ZTS (TSRM) enabled (see Memory management).
ini_entry [1] [3] | NULL | This pointer is used internally by Zend to keep a non-local reference to any INI entries declared for the module.
deps [3] | NULL | A pointer to a list of dependencies for the module.
name | "mymodule" | The name of the module. This is the short name, such as "spl" or "standard".
functions | mymodule_functions | A pointer to the module's function table, which Zend uses to expose functions in the module to user space.
module_startup_func | PHP_MINIT(mymodule) | A callback function that Zend will call the first time a module is loaded into a particular instance of PHP.
module_shutdown_func | PHP_MSHUTDOWN(mymodule) | A callback function that Zend will call the when a module is unloaded from a particular instance of PHP, typically during final shutdown.
request_startup_func | PHP_RINIT(mymodule) | A callback function that Zend will call at the beginning of each request. This should be as short as possible or NULL as calling this has costs on every request.
request_shutdown_func | PHP_RSHUTDOWN(mymodule) | A callback function that Zend will call at the end of each request. This should be as short as possible or NULL as calling this has costs on every request.
info_func | PHP_MINFO(mymodule) | A callback function that Zend will call when the phpinfo() function is called.
version | NO_VERSION_YET | A string giving the version of the module, as specified by the module developer. It is recommended that the version number be either in the format expected by version_compare() (e.g. "1.0.5-dev"), or a CVS or SVN revision number (e.g. "$Rev: 322138 $").
globals_size [1] [4] [5] [6] | sizeof(zend_mymodule_globals) | The size of the data structure containing the module's globals, if any.
globals_id_ptr [1] [4] [5] [6] [7] | &mymodule_globals_id | Only one of these two fields will exist, depending upon whether the USING_ZTS constant is TRUE. The former is an index into TSRM's allocation table for the module's globals, and the latter is a pointer directly to the globals.
globals_ptr [1] [4] [5] [6] [8] | &mymodule_globals
globals_ctor [4] [5] [6] | PHP_GINIT(mymodule) | This funtion is called to initialize a module's globals before any module_startup_func.
globals_dtor [4] [5] [6] | PHP_GSHUTDOWN(mymodule) | This funtion is called to deallocate a module's globals after any module_shutdown_func.
post_deactivate_func [4] | ZEND_MODULE_POST_ZEND_DEACTIVATE_N(mymodule) | This function is called by Zend after request shutdown. It is rarely used.
module_started [1] [9] [4] | 0 | These fields are used for Zend's internal tracking information.
type [1] [9] [4] | 0
handle [1] [9] [4] | NULL
module_number [1] [9] [4] | 0
[1] This field is not intended for use by module developers. [2] This field is filled in by STANDARD_MODULE_HEADER_EX. [3] This field is filled in by STANDARD_MODULE_HEADER. [4] This field is filled in by STANDARD_MODULE_PROPERTIES. [5] This field is filled in by NO_MODULE_GLOBALS. [6] This field is filled in by PHP_MODULE_GLOBALS. [7] This field only exists when USING_ZTS is TRUE. [8] This field only exists when USING_ZTS is FALSE. [9] This field is filled in by STANDARD_MODULE_PROPERTIES_EX.

Filling in the structure in a practical situation

With all these fields to play with, it can be confusing to know which to use for what purpose. Here is the zend_module definition from the "counter" example extension after updating it to its final form.

Пример #3 Counter extension module definition

/* {{{ counter_module_entry
 */
zend_module_entry counter_module_entry = {
    STANDARD_MODULE_HEADER,
    "counter",
    counter_functions,
    PHP_MINIT(counter),
    PHP_MSHUTDOWN(counter),
    PHP_RINIT(counter),
    PHP_RSHUTDOWN(counter),
    PHP_MINFO(counter),
    NO_VERSION_YET,
    PHP_MODULE_GLOBALS(counter),
    PHP_GINIT(counter),
    PHP_GSHUTDOWN(counter),
    NULL,
    STANDARD_MODULE_PROPERTIES_EX
};
/* }}} */
  • STANDARD_MODULE_HEADER is used since this module doesn't define any dependencies.
  • "counter" is the extension's name, and is used to define the various callback functions the module passes to Zend. "counter" uses module, globals, and request functions at startup and shutdown times, and provides information to phpinfo(), so all seven callbacks are defined.
  • It is assumed that there is a variable of type zend_function_entry * named counter_functions earlier in the file that contains the module definition, listing the functions the module exports to userspace.
  • NO_VERSION_YET is a particularly nice way of telling Zend the module doesn't have a version. It might have been more correct to place "1.0" here instead in a real module.
  • "counter" uses per-module globals, so PHP_MODULE_GLOBALS is used
  • This module has no post-deactivate function, so NULL is used.
  • Since this module does use globals, STANDARD_MODULE_PROPERTIES_EX is used to finish the structure.

What's changed between 5.2 and 5.3?

Nothing. The only differences in the zend_module structure between PHP 5.2 and PHP 5.3 are a few const keywords.

User Contributed Notes

There are no user contributed notes for this page.
Basic constructs
Extension globals
Extension structure


Extension globals

Introduction to globals in a PHP extension

In a language such as C, a "global" variable is a variable that can be accessed from any function without any extra declaration. These traditional globals have a few drawbacks:

  • Barring any special options passed to the compiler, a global variable can be accessed and changed by any piece of code anywhere in the program, whether or not that code should be doing so.
  • A typical global variable is not thread safe.
  • The names of global variables are as global as the variables themselves.

A PHP extension's globals are more properly called the "extension state", since most modules must remember what they're doing between function calls. The "counter" extension is a perfect example of this need: The basic interface calls for a counter with a persistent value. A programmer new to Zend and PHP might do something like this in counter.c to store that value:

Пример #1 The wrong way to store the basic counter interface's value

/* ... */
static long basic_counter_value;

/* ... */

PHP_FUNCTION(counter_get)
{
    RETURN_LONG(basic_counter_value);
}

On the surface this appears a viable solution, and indeed in a simple test it would function correctly. However, there are a number of situations in which more than one copy of PHP is running in the same thread, which means more than one instance of the counter module. Suddenly these multiple threads are sharing the same counter value, which is clearly undesirable. Another problem shows itself when considering that another extension might someday happen to have a global with the same name, and due to the rules of C scoping, this has the potential to cause a compile failure, or worse, a runtime error. Something more elaborate is needed, and so exists Zend's support for thread-safe per-module globals.

Declaring module globals

Whether a module uses only a single global or dozens, they must be defined in a structure, and that structure must be declared. There are some macros that assist with doing so in a way that avoids name conflicts between modules: ZEND_BEGIN_MODULE_GLOBALS(), ZEND_END_MODULE_GLOBALS(), and ZEND_DECLARE_MODULE_GLOBALS(). All three take as a parameter the short name of the module, which in the case of the counter module is simply "counter". Here is the global structure declaration from php_counter.h:

Пример #2 The counter module's globals

ZEND_BEGIN_MODULE_GLOBALS(counter)
    long        basic_counter_value;
ZEND_END_MODULE_GLOBALS(counter)

And this is the declaration from counter.c:

Пример #3 The counter module's global structure declaration

ZEND_DECLARE_MODULE_GLOBALS(counter)

Accessing module globals

As discussed above, per-module globals are declared inside a C structure whose name is obscured by Zend macros. As a result, the ideal way to access members of this structure is by the use of further macros. Accordingly, most if not all extensions which have globals have a declaration like this somewhere in their header file:

Пример #4 Accessor macros for per-module globals

#ifdef ZTS
#define COUNTER_G(v) TSRMG(counter_globals_id, zend_counter_globals *, v)
#else
#define COUNTER_G(v) (counter_globals.v)
#endif

Замечание: This could have been generalized into a macro of its own by the Zend API, but as of PHP 5.3 (and PHP 6 at the time of this writing), that hasn't happened. The global accessor construct is written into the header by ext_skel and thus is generally left alone by extension writers, unless they wish to change the name of the accessor macro.

Замечание: COUNTER_G was the name given to the macro by ext_skel, but it's not necessary for it to have that name and could just as easily be called FOO instead.

Any code in the counter extension that accesses a global must thus wrap it in the macro COUNTER_G.

Внимание

Any function which accesses globals must either be declared by Zend macros, have TSRMLS_DC as its last argument, or call the macro TSRMLS_FETCH before accessing the globals. See the TSRM documentation for more information.

So with all of that in mind, here is our new version of the counter_get():

Пример #5 The right way to store the basic counter interface's value

/* php_counter.h */
ZEND_BEGIN_MODULE_GLOBALS(counter)
    long        basic_counter_value;
ZEND_END_MODULE_GLOBALS(counter)

#ifdef ZTS
#define COUNTER_G(v) TSRMG(counter_globals_id, zend_counter_globals *, v)
#else
#define COUNTER_G(v) (counter_globals.v)
#endif

/* counter.c */
ZEND_DECLARE_MODULE_GLOBALS(counter)

/* ... */

PHP_FUNCTION(counter_get)
{
    RETURN_LONG(COUNTER_G(basic_counter_value));
}

This is a correct implementation. It is not, however, a complete one. The section Life cycle of an extension explains why.

User Contributed Notes

There are no user contributed notes for this page.
The zend_module structure
Life cycle of an extension
Extension structure


Life cycle of an extension

A PHP extension goes through several phases during its lifetime. All of these phases are opportunities for the developer to perform various initialization, termination, or informational functions. The Zend API allows for hooks into five separate phases of an extension's existence, apart from calls by PHP functions.

Loading, unloading, and requests

As the Zend engine runs, it processes one or more "requests" from its client. In the traditional CGI implementation, this corresponds to one execution of a process. However, many other implementations, most notably the Apache module, can map many requests onto a single PHP process. A PHP extension may thus see many requests in its lifetime.

Overview

  • In the Zend API, a module is loaded into memory only once when the associated PHP process starts up. Each module receives a call to the "module initialization" function specified in its zend_module structure as it is loaded.
  • Whenever the associated PHP process starts to handle a request from its client - i.e. whenever the PHP interpreter is told to start working - each module receives a call to the "request initialization" function specified in its zend_module structure.
  • Whenever the associated PHP process is done handling a request, each module receives a call to the "request termination" function specified in its zend_module structure.
  • A given module is unloaded from memory when its associated PHP process is shut down in an orderly manner. The module receives a call to the "module termination" function specified in its zend_module structure at this time.

What to do, and when to do it

There are many tasks that might be performed at any of these four points. This table details where many common initialization and termination tasks belong.

What to do, and when to do it
Module initialization/termination | Request initialization/termination
Allocate/deallocate and initialize module global variables | Allocate/deallocate and initialize request-specific variables
Register/unregister class entries |
Register/unregister INI entries |
Register constants |

The phpinfo() callback

Aside from globals initialization and certain rarely-used callbacks, there is one more part of a module's lifecycle to examine: A call to phpinfo(). The output a user sees from this call, whether text or HTML or anything else, is generated by each individual extension that is loaded into the PHP interpreter at the time the call is made.

To provide for format-neutral output, the header "ext/standard/info.h" provides an array of functions to produce standardized display elements. Specifically, several functions which create the familiar tables exist:

php_info_print_table_start()
Open a table in phpinfo() output. Takes no parameters.
php_info_print_table_header()
Print a table header in phpinfo() output. Takes one parameter, the number of columns, plus the same number of char * parameters which are the texts for each column heading.
php_info_print_table_row()
Print a table row in phpinfo() output. Takes one parameter, the number of columns, plus the same number of char * parameters which are the texts for each column content.
php_info_print_table_end()
Close a table formerly opened by php_info_print_table_start(). Takes no parameters.

Using these four functions, it is possible to produce status information for nearly any combination of features in an extension. Here is the information callback from the counter extension:

Пример #1 counter's PHP_MINFO function

/* {{{ PHP_MINFO(counter) */
PHP_MINFO_FUNCTION(counter)
{
    char        buf[10];

    php_info_print_table_start();
    php_info_print_table_row(2, "counter support", "enabled");
    snprintf(buf, sizeof(buf), "%ld", COUNTER_G(basic_counter_value));
    php_info_print_table_row(2, "Basic counter value", buf);
    php_info_print_table_end();
}
/* }}} */

User Contributed Notes

There are no user contributed notes for this page.
Extension globals
Testing an extension
Extension structure


Testing an extension

One of the accepted requirements of good programming is testing. PHP provides a test harness for unit regression tests, in the form of a script called run-tests.php.

Tests for a particular module are stored in the tests/ subdirectory of the module's folder, and have a .phpt extension. For details of the PHPT format, see » http://qa.php.net/.

User Contributed Notes

There are no user contributed notes for this page.
Life cycle of an extension
Memory management
Extension structure


Memory management

Содержание

  • Basic memory management
  • Data persistence
  • Thread-Safe Resource Manager

Memory management in the Zend Engine is deceptively simple. There are some APIs to learn, and some concepts behind them to understand, but that's about all.

User Contributed Notes

There are no user contributed notes for this page.
Testing an extension
Basic memory management
Ядро PHP: Руководство хакера по Zend Engine


Basic memory management

When programming in the C programming language the developer has to manually care about memory management. As PHP is usually used as a web server module memory management is from special relevance in order to prevent memory leaks. Additionally you should be aware that PHP might be used in threaded environments which means that global variables might lead to race conditions. For information about dealing with thread-global data please refer to the documentation on the Thread-Safe Resource Manager, which serves as thread-isolation facility.

Additionally to these requirements the Zend Engine is faced with a quite special usage pattern where, within a relatively short time, many memory blocks of the size of a zval structure or other small memory blocks are requested and freed again. Memory management in PHP has also to respect the memory_limit.

For fulfilling the above requirements the Zend Engine provides a special memory manager for handling request-bound data. Request-bound data is data that is needed only for serving a single request and which will be freed at the request's end at latest. Extension authors will mostly only have contact with the routines listed in the table below. Although they are implemented as macros for providing some convenience features this documentation will treat them like functions.

Main memory APIs
Prototype | Description
void *emalloc(size_t size) | Allocate size bytes of memory.
void *ecalloc(size_t nmemb, size_t size) | Allocate a buffer for nmemb elements of size bytes and makes sure it is initialized with zeros.
void *erealloc(void *ptr, size_t size) | Resize the buffer ptr, which was allocated using emalloc to hold size bytes of memory.
void efree(void *ptr) | Free the buffer pointed by ptr. The buffer had to be allocated by emalloc.
void *safe_emalloc(size_t nmemb, size_t size, size_t offset) | Allocate a buffer for holding nmemb blocks of each size bytes and an additional offset bytes. This is similar to emalloc(nmemb * size + offset) but adds a special protection against overflows.
char *estrdup(const char *s) | Allocate a buffer that can hold the NULL-terminated string s and copy the s into that buffer.
char *estrndup(const char *s, unsigned int length) | Similar to estrdup while the length of the NULL-terminated string is already known.

Замечание: Unlike their C standard library's counterparts the Zend Engine's memory management functions won't return NULL in case of an problem while allocating the requested memory but bail out and terminate the current request.

As said above it is an essential part of the memory management to avoid having memory leaks and therefore free all memory you've allocated as soon as possible. As a safety net the Zend Engine will free all memory, which had been allocated using above mentioned APIs at the end of a request. If PHP was built using the --enable-debug configuration option this will lead to a warning.

Пример #1 PHP's leak warnings

ZEND_FUNCTION(leak)
{
    long leakbytes = 3;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &leakbytes) == FAILURE) {
        return;
    }

    emalloc(leakbytes);
}

Результатом выполнения данного примера будет что-то подобное:

[Thu Oct 22 02:14:57 2009]  Script:  '-'
/home/johannes/src/PHP_5_3/Zend/zend_builtin_functions.c(1377) :  Freeing 0x088888D4 (3 bytes), script=-
=== Total 1 memory leaks detected ===

Замечание: When dealing with PHP variables you have to make sure the variable's memory is allocated using emalloc and take care of the reference count. Details can be found in Working with variables.

Замечание: This leak detection can only find leaks caused by blocks allocated by emalloc. You're advised to use a memory checker like valgrind or libumem for deeper analysis. To simplify the analysis PHP's memory manager can be disabled by setting the environment variable USE_ZEND_ALLOC=0 before starting PHP.

User Contributed Notes

There are no user contributed notes for this page.
Memory management
Data persistence
Memory management


Data persistence

User Contributed Notes

There are no user contributed notes for this page.
Basic memory management
Thread-Safe Resource Manager
Memory management


Thread-Safe Resource Manager

User Contributed Notes

There are no user contributed notes for this page.
Data persistence
Working with variables
Memory management


Working with variables

Содержание

  • Intro
  • Creating variables and setting values

User Contributed Notes

There are no user contributed notes for this page.
Thread-Safe Resource Manager
Intro
Ядро PHP: Руководство хакера по Zend Engine


Intro

For working with variables in PHP's core you have to learn about different fundamental concepts used in PHP. Firstly PHP is a dynamic and weak typed language. Secondly PHP uses a copy on write mechanism with reference counting for memory handling. Please check the Основы подсчета ссылок chapter for details how reference counting and references work.

PHP variables, in general, consist out of two things: The label, which might, for instance, be an entry in a symbol table, and the actual variable container. For the most parts of this manual we will focus on the variable container.

The variable container, in code called zval, is holding all data needed to handle the variable. This includes not only the actual value but also the current type, a counter counting the number of labels pointing to this container and a flag whether these labels should be treated as references or copies. In PHP 5.3 the relevant structures, which you can find in Zend/zend.h, look like this:

typedef struct _zval_struct zval;

typedef union _zvalue_value {
    long lval;                 /* long value */
    double dval;               /* double value */
    struct {                   /* string type */
        char *val;
        int len;
    } str;
    HashTable *ht;             /* hash table value */
    zend_object_value obj;
} zvalue_value;

struct _zval_struct {
    /* Variable information */
    zvalue_value value;        /* value */
    zend_uint refcount__gc;
    zend_uchar type;           /* active type */
    zend_uchar is_ref__gc;
};

In the zvalue_value one can find the internal representation for the different types the fields used should be clear from the names and comments - especially if one knows that PHP's arrays are infact hash tables. Nonetheless, knowing PHP's types one might miss a few: NULL, boolean and resources. For NULL we need no value, as NULL is the value of that type. For boolean and resource values PHP re-uses the value field. In the case of a boolean it holds either 0 for false or 1 for true. For resource-typed variables it holds the resource id.

Now the good message is that you don't have to know these things in detail as there are - like always in PHP - acces macros. The bad news is that there are many of them: There are macros to access any aspect of the zval and then, as one often deals with pointers to zvals and even pointers to pointers to zvals, for most of them there are shortcuts dereferencing these pointers. These macros are spread over Zend/zend.h, Zend/zend_operators.h and Zend/zend_API.h.

User Contributed Notes

There are no user contributed notes for this page.
Working with variables
Creating variables and setting values
Working with variables


Creating variables and setting values

User Contributed Notes

There are no user contributed notes for this page.
Intro
Writing functions
Working with variables


Writing functions

One core element of an extension are functions which are exported to the PHP userland. Even when you're planning to write object-oriented extensions you are advised to read this chapter as most of the information is valid for methods, too.

When adding a function to an extension, for instance after using the ext_skel script to create the raw infrastructure, you can create a function by implementing it as a C function and then providing an entry for the extension's function table. The function entry can contain a pointer to an argument information structure. Providing this information ins not strictly necessary, unless you plan to accept parameters by reference or want to return a reference, but provides information that can be accessed via PHP's Reflection API. As you will see below the parameters aren't passed as direct function parameters to the implementation but passed on a stack, which is checked by the function's implementation which can't directly serve as source for this information.

Пример #1 Minimal PHP extension with one function

/* {{{ proto void hello_world()
       Do nothing */
PHP_FUNCTION(hello_world)
{
}
/* }}} */

/* {{{ arginfo_hello_world */
ZEND_BEGIN_ARG_INFO(arginfo_hello_world, 0)
ZEND_END_ARG_INFO()
/* }}} */

/* {{{ demo_functions */
function_entry demo_functions[] = {
    PHP_FE(hello_world, arginfo_hello_world)
    {NULL, NULL, NULL}
}
/* }}} */

/* {{{ demo_module_enry */
zend_module_entry demo_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    "demo",
    demo_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
#if ZEND_MODULE_API_NO >= 20010901
    "1.0.0",
#en
    STANDARD_MODULE_PROPERTIES
}
/* }}} */

In this example you can see the above discussed elements and the module structure; if you don't remember this structure go back to The zend_module structure.

The first part of this extension is the actual implementation. As a convention each exported function is preceded by a two line comment describing the function's userland prototype and a short one line comment.

For providing source code compatibility between different versions of PHP the functions declaration is wrapped into the PHP_FUNCTION macro. The compiler's preprocessor will, when using PHP 5.3 transform this into a function like this:

void zif_hello_world(int ht, zval *return_value, zval **return_value_ptr,
                     zval *this_ptr, int return_value_used TSRMLS_DC)
{
}

For preventing a naming conflict between a function exported to userland and another C function with the same name the C symbol of the exported function is prefixed with the prefix zif_. You can also see that this prototype doesn't reference the argument stack. Accessing parameters passed from PHP is described below. The following table lists the C level parameters which are also defined in the INTERNAL_FUNCTION_PARAMETERS macro. Mind that these parameters might change between PHP versions and you should use the provide macros.

INTERNAL_FUNCTION_PARAMETERS
Name and type | Description | Access macros
int ht | Number of actual parameters passed by user | ZEND_NUM_ARGS()
zval *return_value | Pointer to a PHP variable that can be filled with the return value passed to the user. The default type is IS_NULL. | RETVAL_*, RETURN_*
zval **return_value_ptr | When returning references to PHP set this to a pointer to your variable. It is not suggested to return references. |
zval *this_ptr | If this is a method call, points to the PHP variable holding the $this object. | getThis()
int return_value_used | Flag indicating whether the returned value will be used by the caller. |

As said the function shown above will simply return NULL to the user and do nothing else. The function can be called, from the PHP userland, with an arbitrary number of parameters. A more useful function consists of four parts in general:

  1. Declaration of local variables. In C we have to declare locale vars, so we do this at the functions top.

  2. Parameter parsing. PHP passes parameters on a special stack: we have to read them from there, verify the types, cast them if needed and bail out if something goes wrong.

  3. Actual logic. Do whatever is needed.

  4. Set the return value, cleanup, return.

In some cases the exact order of these steps may change. Especially the last two steps are often mixed up, but it's a good idea to stay in that order.

Пример #2 A simple function

/* {{{ proto void hello_world(string name)
   Greets a user */
PHP_FUNCTION(hello_world)
{
    char *name;
    int name_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) {
        return;
    }

    php_printf("Hello %s!", name);

    RETURN_TRUE;
}
/* }}} */

The function above shows these parts. Let's start the analysis with the last lines: php_printf is - as one can guess easily - PHP's version of standard C's printf. Unlike printf it doesn't print to the process's STDOUT channel but to the current output stream, which might be buffered by the user. It should be noted that php_printf, unlike most parts of PHP's API is not binary safe, so if name contains a NULL-byte the rest would be ignored. For a binary safe output PHPWRITE should be used.

Замечание: In general it is considered to directly print data to the output stream, it is suggested to return data as string to the user instead so the user can decide what to do. Exceptions to this rule might be functions dealing with binary data like images while your API should provide a way to access the data even there.

The RETURN_TRUE macro in the last line does three things: It sets the type of the variable we got as return_value pointer to IS_BOOLEAN and the value to a true value. Then it returns from the C function. So when using this macro you're housekeeping for memory and other resources has to be completed as further code of this function won't be executed.

The zend_parse_parameters() function is responsible for reading the parameters passed by the user from the argument stack and putting it with proper casting in local C variables. If the user doesn't pass the wrong number of parameters or types that can't be casted the function will emit a verbose error and return FAILURE. In that case we simply return from the function - by not changing the return_value the default return value of NULL will be returned to the user.

Замечание: Please mind that FAILURE is represented by a -1 and SUCCESS by 0. To make the code clear you should always use the named constants for comparing the value.

The first parameter to zend_parse_parameters() is the number of parameters that have actually been passed to the function by the user. The number is passed as ht parameter to our function but, as discussed above, this should be considered as an implementation detail and ZEND_NUM_ARGS() should be used.

For compatibility with PHP's thread-isolation, the thread-safe resource manager, we also have to pass the thread context using TSRMLS_CC. Unlike in other functions this can't be the last parameter as zend_parse_parameters expects a variable number of parameters - depending on the number of user-parameters to read.

Following the thread context the expected parameters are declared. Each parameter is represented by a character in the string describing the type. In our case we expect one parameter as a string so our type specification is simply "s".

Lastly one has to pass one or more pointers to C variables which should be filled with the variable's value or provide more details. In the case of a string we get the actual string, which will always be NULL-terminated, as a char* and its length, excluding the NULL-byte, as int.

A documentation of all type specifiers and the corresponding additional C types can be found in the file » README.PARAMETER_PARSING_API which is part of the source distribution. The most important types can be found in the table below.

zend_parse_parameters() type specifiers
Modifier | Additional parameter types | Description
b | zend_bool | Boolean value
l | long | A integer (long) value
d | double | A float (double) value
s | char*, int | A binary safe string
h | HashTable* | An array's hash table

User Contributed Notes

There are no user contributed notes for this page.
Creating variables and setting values
Working with classes and objects
Ядро PHP: Руководство хакера по Zend Engine


Working with classes and objects

User Contributed Notes

markem at airmail dot net 09-Jun-2008 08:39
One of the things that I believe should be done in the "__construct" part of a class object is the definition of your variables which are going to be used outside of the class itself.  (Like the $_SESSION information or if you are going to be working with a database and you want to be able to monitor the incoming information and you always want it to go to the same variable.)  I came up with the following which I thought was kind of clever and I just wanted to pass it along so someone else doesn't have to re-invent the wheel.  Put this into your "__construct" function and set the $checkVar to be what is on your forms followed by what name you want the $_SESSION variable (or any variable for that matter) to be set it.  (We deal with small databases so the $_SESSION variable doesn't get all that large.)

    $checkVar['prevPage'] = 'PREVPAGE';
    $checkVar['newPWD'] = 'NEWPWD';
    $checkVar['confirmPWD'] = 'CONFIRMPWD';

    foreach( $checkVar as $key => $value ){
        if( isset($_POST[$key]) ){ $_SESSION[$value] = $_POST[$key]; }
            else if( isset($_GET[$key]) ){ $_SESSION[$value] = $_GET[$key]; }
            else if( isset($_SESSION[$value]) ){}   #   Do nothing
            else { $_SESSION[$value] = ""; }
        }

Here you can see I am keeping track of the previous page, the user's new password, and the confirmation of that password.  The FOREACH loop checks to see if the $_POST variable is set to the key and if so it sets the $_SESSION variable.  The thing is - it uses the associative array to keep track of which $_POST or $_GET entry to use.  Further, if the neither of those two are set it checks first to see if the $_SESSION variable was already set and then if not it at least sets it to a null string so it is defined.  This keeps us from having the error log messages about us using undefined variables too.

I hope everyone likes this and can use it.
Writing functions
Working with resources
Ядро PHP: Руководство хакера по Zend Engine


Working with resources

User Contributed Notes

There are no user contributed notes for this page.
Working with classes and objects
Working with INI settings
Ядро PHP: Руководство хакера по Zend Engine


Working with INI settings

User Contributed Notes

There are no user contributed notes for this page.
Working with resources
Working with streams
Ядро PHP: Руководство хакера по Zend Engine


Working with streams

Замечание:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.

User Contributed Notes

There are no user contributed notes for this page.
Working with INI settings
PDO Driver How-To
Ядро PHP: Руководство хакера по Zend Engine


PDO Driver How-To

Содержание

  • Prerequisites
  • Preparation and Housekeeping
  • Fleshing out your skeleton
  • Building
  • Testing
  • Packaging and distribution
  • pdo_dbh_t definition
  • pdo_stmt_t definition
  • Constants
  • Error handling

The purpose of this How-To is to provide a basic understanding of the steps required to write a database driver that interfaces with the PDO layer. Please note that this is still an evolving API and as such, subject to change. This document was prepared based on version 0.3 of PDO. The learning curve is steep; expect to spend a lot of time on the prerequisites.

User Contributed Notes

There are no user contributed notes for this page.
Working with streams
Prerequisites
Ядро PHP: Руководство хакера по Zend Engine


Prerequisites

The following is list of prerequisites and assumptions needed for writing a PDO database driver:

  1. A working target database, examples, demos, etc. working as per vendor specifications;

  2. A working development environment:

    1. Linux: standard development tools, gcc, ld, make, autoconf, automake, etc., versions dependent on distribution;

    2. Other Unix: standard development tools supplied by vendor plus the GNU development tool set;

    3. Win32: Visual Studio compiler suite;

  3. A working PHP environment version 5.0.3 or higher with a working PEAR extension version 1.3.5 or higher;

  4. A working PDO environment (can be installed using 'sudo pecl install PDO'), including the headers which will be needed to access the PDO type definitions and function declarations;

  5. A good working knowledge of the C programming language;

  6. A good working knowledge of the way to write a PHP extension; George Schlossnagle's Advanced PHP Programming (published by Developer's Library, chapters 21 and 22) is recommended;

  7. Finally, a familiarity with the Zend API that forms the heart of PHP, in particular paying attention to the memory management aspects.

User Contributed Notes

There are no user contributed notes for this page.
PDO Driver How-To
Preparation and Housekeeping
PDO Driver How-To


Preparation and Housekeeping

Source directory layout

The source directory for a typical PDO driver is laid out as follows, where SKEL represents a shortened form of the name of the database that the driver is going to connect to. Even though SKEL is presented here in uppercase (for clarity), the convention is to use lowercase characters.

pdo_SKEL/
  config.m4                  # unix build script
  config.w32                 # win32 build script
  CREDITS
  package.xml                # meta information about the package
  pdo_SKEL.c                 # standard PHP extension glue
  php_pdo_SKEL.h
  php_pdo_SKEL_int.h         # driver private header
  SKEL_dbh.c                 # contains the implementation of the PDO driver interface
  SKEL_stmt.c                # contains the implementation of the PDO statement interface
  tests/

The contents of these files are defined later in this document.

Creating a skeleton

The easiest way to get started is to use the ext_skel shell script found in the PHP build tree in the ext directory. This will build a skeleton directory containing a lot of the files listed above. It can be build by executing the following command from within the ext directory:

./ext_skel --extname=pdo_SKEL

This will generate a directory called pdo_SKEL containing the skeleton files that you can then modify. This directory should then be moved out of the php extension directory. PDO is a PECL extension and should not be included in the standard extension directory. As long as you have PHP and PDO installed, you should be able to build from any directory.

Standard Includes

Build Specific Headers

The header file config.h is generated by the configure process for the platform for the which the driver is being built. If this header is present, the HAVE_CONFIG_H compiler variable is set. This variable should be tested for and if set, the file config.h should be included in the compilation unit.

PHP Headers

The following standard public php headers should be included in each source module:

  1. php.h

  2. php_ini.h

  3. ext/standard/info.h

PDO Interface Headers

The following standard public PDO header files are also included in each source module:

pdo/php_pdo.h

This header file contains definitions of the initialization and shutdown functions in the main driver as well as definitions of global PDO variables.

pdo/php_pdo_driver.h

This header contains the types and API contracts that are used to write a PDO driver. It also contains method signature for calling back into the PDO layer and registering/unregistering your driver with PDO. Most importantly, this header file contains the type definitions for PDO database handles and statements. The two main structures a driver has to deal with, pdo_dbh_t and pdo_stmt_t, are described in more detail in Appendix A and B.

Driver Specific Headers

The typical PDO driver has two header files that are specific to the database implementation. This does not preclude the use of more depending on the implementation. The following two headers are, by convention, standard:

php_pdo_SKEL.h

This header file is virtually an exact duplicate in functionality and content of the previously defined pdo/php_pdo.h that has been specifically tailored for your database. If your driver requires the use of global variables they should be defined using the ZEND_BEGIN_MODULE_GLOBALS and ZEND_END_MODULE_GLOBALS macros. Macros are then used to access these variables. This macro is usually named PDO_SKEL_G(v) where v is global variable to be accessed. Consult the Zend programmer documentation for more information.

php_pdo_SKEL_int.h

This header file typically contains type definitions and function declarations specific to the driver implementation. It also should contain the db specific definitions of a pdo_SKEL_handle and pdo_SKEL_stmt structures. These are the names of the private data structures that are then referenced by the driver_data members of the handle and statement structures.

Optional Headers

Depending on the implementation details for a particular driver it may be necessary to include the following header:

#include <zend_exceptions.h>

User Contributed Notes

There are no user contributed notes for this page.
Prerequisites
Fleshing out your skeleton
PDO Driver How-To


Fleshing out your skeleton

Major Structures and Attributes

The major structures, pdo_dbh_t and pdo_stmt_t are defined and explained in Appendix A and B respectively. Database and Statement attributes are defined in Appendix C. Error handling is explained in Appendix D.

pdo_SKEL.c: PHP extension glue

function entries

static function_entry pdo_SKEL_functions[] = {
  { NULL, NULL, NULL }
};

This structure is used to register functions into the global php function namespace. PDO drivers should try to avoid doing this, so it is recommended that you leave this structure initialized to NULL, as shown in the synopsis above.

Module entry

/* {{{ pdo_SKEL_module_entry */
#if ZEND_EXTENSION_API_NO >= 220050617
static zend_module_dep pdo_SKEL_deps[] = {
    ZEND_MOD_REQUIRED("pdo")
    {NULL, NULL, NULL}
};
#endif
/* }}} */

zend_module_entry pdo_SKEL_module_entry = {
#if ZEND_EXTENSION_API_NO >= 220050617
    STANDARD_MODULE_HEADER_EX, NULL,
    pdo_SKEL_deps,
#else
    STANDARD_MODULE_HEADER,
#endif
    "pdo_SKEL",
    pdo_SKEL_functions,
    PHP_MINIT(pdo_SKEL),
    PHP_MSHUTDOWN(pdo_SKEL),
    NULL,
    NULL,
    PHP_MINFO(pdo_SKEL),
    PHP_PDO_<DB>_MODULE_VERSION,
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_PDO_<DB>
ZEND_GET_MODULE(pdo_db)
#endif

A structure of type zend_module_entry called pdo_SKEL_module_entry must be declared and should include reference to the pdo_SKEL_functions table defined previously.

Standard PHP Module Extension Functions

PHP_MINIT_FUNCTION
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(pdo_SKEL)
{
    return php_pdo_register_driver(&pdo_SKEL_driver);
}
/* }}} */

This standard PHP extension function should be used to register your driver with the PDO layer. This is done by calling the php_pdo_register_driver() function passing a pointer to a structure of type pdo_driver_t typically named pdo_SKEL_driver. A pdo_driver_t contains a header that is generated using the PDO_DRIVER_HEADER(SKEL) macro and pdo_SKEL_handle_factory() function pointer. The actual function is described during the discussion of the SKEL_dbh.c unit.

PHP_MSHUTDOWN_FUNCTION
/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(pdo_SKEL)
{
    php_pdo_unregister_driver(&pdo_SKEL_driver);
    return SUCCESS;
}
/* }}} */

This standard PHP extension function is used to unregister your driver from the PDO layer. This is done by calling the php_pdo_unregister_driver() function, passing the same pdo_SKEL_driver structure that was passed in the init function above.

PHP_MINFO_FUNCTION

This is again a standard PHP extension function. Its purpose is to display information regarding the module when the phpinfo() is called from a script. The convention is to display the version of the module and also what version of the db you are dependent on, along with any other configuration style information that might be relevant.

SKEL_driver.c: Driver implementation

This unit implements all of the database handling methods that support the PDO database handle object. It also contains the error fetching routines. All of these functions will typically need to access the global variable pool. Therefore, it is necessary to use the Zend macro TSRMLS_DC macro at the end of each of these statements. Consult the Zend programmer documentation for more information on this macro.

pdo_SKEL_error

static int pdo_SKEL_error(pdo_dbh_t *dbh,
  pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC)

The purpose of this function is to be used as a generic error handling function within the driver. It is called by the driver when an error occurs within the driver. If an error occurs that is not related to SQLSTATE, the driver should set either dbh->error_code or stmt->error_code to an SQLSTATE that most closely matches the error or the generic SQLSTATE error "HY000". The file pdo_sqlstate.c in the PDO source contains a table of commonly used SQLSTATE codes that the PDO code explicitly recognizes. This setting of the error code should be done prior to calling this function.; This function should set the global pdo_err variable to the error found in either the dbh or the stmt (if the variable stmt is not NULL).

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the current statement or NULL. If NULL, the error is derived by error code found in the dbh.

file

The source file where the error occurred or NULL if not available.

line

The line number within the source file if available.

If the dbh member methods is NULL (which implies that the error is being raised from within the PDO constructor), this function should call the zend_throw_exception_ex() function otherwise it should return the error code. This function is usually called using a helper macro that customizes the calling sequence for either database handling errors or statement handling errors.

Пример #1 Example macros for invoking pdo_SKEL_error

#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)
#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)

For more info on error handling, see Error handling.

Замечание:

Despite being documented here, the PDO driver interface does not specify that this function be present; it is merely a convenient way to handle errors, and it just happens to be equally convenient for the majority of database client library APIs to structure your driver implementation in this way.

pdo_SKEL_fetch_error_func

static int pdo_SKEL_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt,
    zval *info TSRMLS_DC)

The purpose of this function is to obtain additional information about the last error that was triggered. This includes the driver specific error code and a human readable string. It may also include additional information if appropriate. This function is called as a result of the PHP script calling the PDO::errorInfo() method.

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the most current statement or NULL. If NULL, the error translated is derived by error code found in the dbh.

info

A hash table containing error codes and messages.

The error_func should return two pieces of information as successive array elements. The first item is expected to be a numeric error code, the second item is a descriptive string. The best way to set this item is by using add_next_index. Note that the type of the first argument need not be long; use whichever type most closely matches the error code returned by the underlying database API.

/* now add the error information. */
/* These need to be added in a specific order */
add_next_index_long(info, error_code);   /* driver specific error code */
add_next_index_string(info, message, 0); /* readable error message */

This function should return 1 if information is available, 0 if the driver does not have additional info.

SKEL_handle_closer

static int SKEL_handle_closer(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to close an open database.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to close the open database. PDO ignores the return value from this function.

SKEL_handle_preparer

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)

This function will be called by PDO in response to PDO::query() and PDO::prepare() calls from the PHP script. The purpose of the function is to prepare raw SQL for execution, storing whatever state is appropriate into the stmt that is passed in.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

Stmt

Pointer to the returned statement or NULL if an error occurs.

driver_options

Any driver specific/defined options.

This function is essentially the constructor for a stmt object. This function is responsible for processing statement options, and setting driver-specific option fields in the pdo_stmt_t structure.

PDO does not process any statement options on the driver's behalf before calling the preparer function. It is your responsibility to process them before you return, raising an error for any unknown options that are passed.

One very important responsibility of this function is the processing of SQL statement parameters. At the time of this call, PDO does not know if your driver supports binding parameters into prepared statements, nor does it know if it supports named or positional parameter naming conventions.

Your driver is responsible for setting stmt->supports_placeholders as appropriate for the underlying database. This may involve some run-time determination on the part of your driver, if this setting depends on the version of the database server to which it is connected. If your driver doesn't directly support both named and positional parameter conventions, you should use the pdo_parse_params() API to have PDO rewrite the query to take advantage of the support provided by your database.

Пример #2 Using pdo_parse_params

int ret;
    char *nsql = NULL;
    int nsql_len = 0;

    /* before we prepare, we need to peek at the query; if it uses named parameters,
     * we want PDO to rewrite them for us */
    stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL;
    ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);

    if (ret == 1) {
        /* query was re-written */
        sql = nsql;
    } else if (ret == -1) {
        /* couldn't grok it */
        strcpy(dbh->error_code, stmt->error_code);
        return 0;
    }

    /* now proceed to prepare the query in "sql" */

Possible values for supports_placeholders are: PDO_PLACEHOLDER_NAMED, PDO_PLACEHOLDER_POSITIONAL and PDO_PLACEHOLDER_NONE. If the driver doesn't support prepare statements at all, then this function should simply allocate any state that it might need, and then return:

Пример #3 Implementing preparer for drivers that don't support native prepared statements

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
    long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
{
    pdo_SKEL_db_handle *H = (pdo_SKEL_db_handle *)dbh->driver_data;
    pdo_SKEL_stmt *S = ecalloc(1, sizeof(pdo_SKEL_stmt));

    S->H = H;
    stmt->driver_data = S;
    stmt->methods = &SKEL_stmt_methods;
    stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;

    return 1;
}

This function returns 1 on success or 0 on failure.

SKEL_handle_doer

static long SKEL_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)

This function will be called by PDO to execute a raw SQL statement. No pdo_stmt_t is created.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

This function returns 1 on success or 0 on failure.

SKEL_handle_quoter

static int SKEL_handle_quoter(pdo_dbh_t *dbh, const char *unquoted,
  int unquoted_len, char **quoted, int quoted_len, enum pdo_param_type param_type TSRMLS_DC)

This function will be called by PDO to turn an unquoted string into a quoted string for use in a query.

dbh

Pointer to the database handle initialized by the handle factory

unquoted

Pointer to a character string containing the string to be quoted.

unquoted_len

The length of the string to be quoted.

quoted

Pointer to the address where a pointer to the newly quoted string will be returned.

quoted_len

The length of the new string.

param_type

A driver specific hint for driver that have alternate quoting styles

This function is called in response to a call to PDO::quote() or when the driver has set supports_placeholder to PDO_PLACEHOLDER_NONE. The purpose is to quote a parameter when building SQL statements.

If your driver does not support native prepared statements, implementation of this function is required.

This function returns 1 if the quoting process reformatted the string, and 0 if it was not necessary to change the string. The original string will be used unchanged with a 0 return.

SKEL_handle_begin

static int SKEL_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to begin a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to begin a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_commit

static int SKEL_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to end a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to commit a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_rollback

static int SKEL_handle_rollback( pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to rollback a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to rollback a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_get_attribute

static int SKEL_handle_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)

This function will be called by PDO to retrieve a database attribute.

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

return_value

The returned value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to supply this function. PDO driver handles the PDO_ATTR_PERSISTENT, PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_set_attribute

static int SKEL_handle_set_attribute(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to set a database attribute, usually in response to a script calling PDO::setAttribute().

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

val

The new value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to provide this function if it does not need to support additional attributes. The PDO driver handles the PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_last_id

static char * SKEL_handle_last_id(pdo_dbh_t *dbh, const char *name, unsigned int len TSRMLS_DC)

This function will be called by PDO to retrieve the ID of the last inserted row.

dbh

Pointer to the database handle initialized by the handle factory

name

string representing a table or sequence name.

len

the length of the name parameter.

This function returns a character string containing the id of the last inserted row on success or NULL on failure. This is an optional function.

SKEL_check_liveness

static int SKEL_check_liveness(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to test whether or not a persistent connection to a database is alive and ready for use.

dbh

Pointer to the database handle initialized by the handle factory

This function returns 1 if the database connection is alive and ready for use, otherwise it should return 0 to indicate failure or lack of support.

Замечание:

This is an optional function.

SKEL_get_driver_methods

static function_entry *SKEL_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)

This function will be called by PDO in response to a call to any method that is not a part of either the PDO or PDOStatement classes. It's purpose is to allow the driver to provide additional driver specific methods to those classes.

dbh

Pointer to the database handle initialized by the handle factory

kind

One of the following:

PDO_DBH_DRIVER_METHOD_KIND_DBH

Set when the method call was attempted on an instance of the PDO class. The driver should return a pointer a function_entry table for any methods it wants to add to that class, or NULL if there are none.

PDO_DBH_DRIVER_METHOD_KIND_STMT

Set when the method call was attempted on an instance of the PDOStatement class. The driver should return a pointer to a function_entry table for any methods it wants to add to that class, or NULL if there are none.

This function returns a pointer to the function_entry table requested, or NULL there are no driver specific methods.

SKEL_handle_factory

static int SKEL_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC)

This function will be called by PDO to create a database handle. For most databases this involves establishing a connection to the database. In some cases, a persistent connection may be requested, in other cases connection pooling may be requested. All of these are database/driver dependent.

dbh

Pointer to the database handle initialized by the handle factory

driver_options

An array of driver options, keyed by integer option number. See Database and Statement Attributes Table for a list of possible attributes.

This function should fill in the passed database handle structure with its driver specific information on success and return 1, otherwise it should return 0 to indicate failure.

PDO processes the AUTOCOMMIT and PERSISTENT driver options before calling the handle_factory. It is the handle factory's responsibility to process other options.

Driver method table

A static structure of type pdo_dbh_methods named SKEL_methods must be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.

pdo_SKEL_driver

A structure of type pdo_driver_t named pdo_SKEL_driver should be declared. The PDO_DRIVER_HEADER(SKEL) macro should be used to declare the header and the function pointer to the handle factory function should set.

SKEL_statement.c: Statement implementation

This unit implements all of the database statement handling methods that support the PDO statement object.

SKEL_stmt_dtor

static int SKEL_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to destroy a previously constructed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This should do whatever is necessary to free up any driver specific storage allocated for the statement. The return value from this function is ignored.

SKEL_stmt_execute

static int SKEL_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to execute the prepared SQL statement in the passed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_fetch

static int SKEL_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori,
   long offset TSRMLS_DC)

This function will be called by PDO to fetch a row from a previously executed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

ori

One of PDO_FETCH_ORI_xxx which will determine which row will be fetched.

offset

If ori is set to PDO_FETCH_ORI_ABS or PDO_FETCH_ORI_REL, offset represents the row desired or the row relative to the current position, respectively. Otherwise, this value is ignored.

The results of this fetch are driver dependent and the data is usually stored in the driver_data member of the pdo_stmt_t object. The ori and offset parameters are only meaningful if the statement represents a scrollable cursor. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_param_hook

static int SKEL_stmt_param_hook(pdo_stmt_t *stmt,
  struct pdo_bound_param_data *param, enum pdo_param_event event_type TSRMLS_DC)

This function will be called by PDO for handling of both bound parameters and bound columns.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

param

The structure describing either a statement parameter or a bound column.

event_type

The type of event to occur for this parameter, one of the following:

PDO_PARAM_EVT_ALLOC

Called when PDO allocates the binding. Occurs as part of PDOStatement::bindParam(), PDOStatement::bindValue() or as part of an implicit bind when calling PDOStatement::execute(). This is your opportunity to take some action at this point; drivers that implement native prepared statements will typically want to query the parameter information, reconcile the type with that requested by the script, allocate an appropriately sized buffer and then bind the parameter to that buffer. You should not rely on the type or value of the zval at param->parameter at this point in time.

PDO_PARAM_EVT_FREE

Called once per parameter as part of cleanup. You should release any resources associated with that parameter now.

PDO_PARAM_EXEC_PRE

Called once for each parameter immediately before calling SKEL_stmt_execute; take this opportunity to make any final adjustments ready for execution. In particular, you should note that variables bound via PDOStatement::bindParam() are only legal to touch now, and not any sooner.

PDO_PARAM_EXEC_POST

Called once for each parameter immediately after calling SKEL_stmt_execute; take this opportunity to make any post-execution actions that might be required by your driver.

PDO_PARAM_FETCH_PRE

Called once for each parameter immediately prior to calling SKEL_stmt_fetch.

PDO_PARAM_FETCH_POST

Called once for each parameter immediately after calling SKEL_stmt_fetch.

This hook will be called for each bound parameter and bound column in the statement. For ALLOC and FREE events, a single call will be made for each parameter or column. The param structure contains a driver_data field that the driver can use to store implementation specific information about each of the parameters.

For all other events, PDO may call you multiple times as the script issues PDOStatement::execute() and PDOStatement::fetch() calls.

If this is a bound parameter, the is_param flag in the param structure is set, otherwise the param structure refers to a bound column.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_describe_col

static int SKEL_stmt_describe_col(pdo_stmt_t *stmt, int colno TSRMLS_DC)

This function will be called by PDO to query information about a particular column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

The driver should populate the pdo_stmt_t member columns(colno) with the appropriate information. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_get_col_data

static int SKEL_stmt_get_col_data(pdo_stmt_t *stmt, int colno,
  char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC)

This function will be called by PDO to retrieve data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

ptr

Pointer to the retrieved data.

len

The length of the data pointed to by ptr.

caller_frees

If set, ptr should point to emalloc'd memory and the main PDO driver will free it as soon as it is done with it. Otherwise, it will be the responsibility of the driver to free any allocated memory as a result of this call.

The driver should return the resultant data and length of that data in the ptr and len variables respectively. It should be noted that the main PDO driver expects the driver to manage the lifetime of the data. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_set_attr

static int SKEL_stmt_set_attr(pdo_stmt_t *stmt, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to allow the setting of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

val

The new value for the attribute.

This function is driver dependent and allows the driver the capability to set database specific attributes for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional settable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_attr

static int SKEL_stmt_get_attr(pdo_stmt_t *stmt, long attr, zval
   *return_value TSRMLS_DC)

This function will be called by PDO to allow the retrieval of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

return_value

The returned value for the attribute.

This function is driver dependent and allows the driver the capability to retrieve a previously set database specific attribute for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional gettable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_col_meta

static int SKEL_stmt_get_col_meta(pdo_stmt_t *stmt, int colno,
   zval *return_value TSRMLS_DC)
Внимание

This function is not well defined and is subject to change.

This function will be called by PDO to retrieve meta data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number for which data is to be retrieved.

return_value

Holds the returned meta data.

The driver author should consult the documentation for this function that can be found in the php_pdo_driver.h header as this will be the most current. This function returns 1 for success or 0 in the event of failure. The database driver does not need to provide this function.

Statement handling method table

A static structure of type pdo_stmt_methods named SKEL_stmt_methods should be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.

User Contributed Notes

There are no user contributed notes for this page.
Preparation and Housekeeping
Building
PDO Driver How-To


Building

The build process is designed to work with PEAR (see » http://pear.php.net/ for more information about PEAR). There are two files that are used to assist in configuring your package for building. The first is config.m4 which is the autoconf configuration file for all platforms except Win32. The second is config.w32 which is a build configuration file for use on Win32. Skeleton files for these are built for you when you first set up your project. You then need to customize them to fit the needs of your project. Once you've customized your config files, you can build your driver using the following sequence of commands:

Before first build:

$ sudo pecl install PDO

For each build:

$ cd pdo_SKEL
$ phpize
$ ./configure
$ make
$ sudo make install

The process can then be repeated as necessary during the development process.

User Contributed Notes

There are no user contributed notes for this page.
Fleshing out your skeleton
Testing
PDO Driver How-To


Testing

PDO has a set of "core" tests that all drivers should pass before being released. They're designed to run from the PHP source distribution, so running the tests for your driver requires moving things around a bit. The suggested procedure is to obtain the latest PHP 5.1 snapshot and perform the following step:

$ cp -r pdo_SKEL /path/to/php-5.1/ext

This will allow the test harness to run your tests. The next thing you need to do is create a test that will redirect into the PDO common core tests. The convention is to name this file common.phpt; it should be placed in the tests subdirectory that was created by ext_skel when you created your extension skeleton. The content of this file should look something like the following:

--TEST--
SKEL
--SKIPIF--
<?php # vim:ft=php
if (!extension_loaded('pdo_SKEL')) print 'skip'; ?>
--REDIRECTTEST--
if (false !== getenv('PDO_SKEL_TEST_DSN')) {
# user set them from their shell
   $config['ENV']['PDOTEST_DSN'] = getenv('PDO_SKEL_TEST_DSN');
   $config['ENV']['PDOTEST_USER'] = getenv('PDO_SKEL_TEST_USER');
   $config['ENV']['PDOTEST_PASS'] = getenv('PDO_SKEL_TEST_PASS');
   if (false !== getenv('PDO_SKEL_TEST_ATTR')) {
      $config['ENV']['PDOTEST_ATTR'] = getenv('PDO_SKEL_TEST_ATTR');
   }
   return $config;
}
return array(
   'ENV' => array(
           'PDOTEST_DSN' => 'SKEL:dsn',
           'PDOTEST_USER' => 'username',
           'PDOTEST_PASS' => 'password'
       ),
   'TESTS' => 'ext/pdo/tests'
   );

This will cause the common core tests to be run, passing the values of PDOTEST_DSN, PDOTEST_USER and PDOTEST_PASS to the PDO constructor as the dsn, username and password parameters. It will first check the environment, so that appropriate values can be passed in when the test harness is run, rather than hard-coding the database credentials into the test file.

The test harness can be invoked as follows:

$ cd /path/to/php-5.1
$ make TESTS=ext/pdo_SKEL/tests PDO_SKEL_TEST_DSN="skel:dsn" \
 PDO_SKEL_TEST_USER=user PDO_SKEL_TEST_PASS=pass test

User Contributed Notes

There are no user contributed notes for this page.
Building
Packaging and distribution
PDO Driver How-To


Packaging and distribution

Creating a package

PDO drivers are released via PECL; all the usual rules for PECL extensions apply. Packaging is accomplished by creating a valid package.xml file and then running:

$ pecl package

This will create a tarball named PDO_SKEL-X.Y.Z.tgz.

Before releasing the package, you should test that it builds correctly; if you've made a mistake in your config.m4 or package.xml files, the package may not function correctly. You can test the build, without installing anything, using the following invocation:

$ pecl build package.xml

Once this is proven to work, you can test installation:

$ pecl package
$ sudo pecl install PDO_SKEL-X.Y.X.tgz

Full details about package.xml can be found in the PEAR Programmer's documentation (» http://pear.php.net/manual/).

Releasing the package

A PDO driver is released via the PHP Extension Community Library (PECL). Information about PECL can be found at » http://pecl.php.net/.

User Contributed Notes

There are no user contributed notes for this page.
Testing
pdo_dbh_t definition
PDO Driver How-To


pdo_dbh_t definition

All fields should be treated as read-only by the driver, unless explicitly stated otherwise.

pdo_dbh_t

/* represents a connection to a database */
struct _pdo_dbh_t {
    /* driver specific methods */
    struct pdo_dbh_methods *methods;
*
/* driver specific data */
    void *driver_data;
**
/* credentials */
    char *username, *password;
***
/* if true, then data stored and pointed at by this handle must all be
     * persistently allocated */
    unsigned is_persistent:1;
****
/* if true, driver should act as though a COMMIT were executed between
     * each executed statement; otherwise, COMMIT must be carried out manually
     * */
    unsigned auto_commit:1;
*****
/* if true, the driver requires that memory be allocated explicitly for
     * the columns that are returned */
    unsigned alloc_own_columns:1;
******
/* if true, commit or rollBack is allowed to be called */
    unsigned in_txn:1;

    /* max length a single character can become after correct quoting */
    unsigned max_escaped_char_length:3;
*******
/* data source string used to open this handle */
    const char *data_source;
********
unsigned long data_source_len;

    /* the global error code. */
    pdo_error_type error_code;
*********
enum pdo_case_conversion native_case
**********
, desired_case;
};
*

The driver must set this during SKEL_handle_factory().

**

This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.

***

The username and password that were passed into the PDO constructor. The driver should use these values when it initiates a connection to the database.

****

If this is set to 1, then any data that is referenced by the dbh, including whatever structure your driver allocates, MUST be allocated persistently. This is easy to achieve; rather than using the usual emalloc() simply use pemalloc() and pass the value of this flag as the last parameter. Failure to use the appropriate kind of memory can lead to serious memory faults, resulting (in the best case) a hard crash, and in the worst case, an exploitable memory problem.

If, for whatever reason, your driver is not suitable to run persistently, you MUST check this flag in your SKEL_handle_factory() and raise an appropriate error.

*****

You should check this value in your SKEL_handle_doer() and SKEL_stmt_execute() functions; if it evaluates to true, you must attempt to commit the query now. Most database implementations offer an auto-commit mode that handles this automatically.

******

If your database client library API operates by fetching data into a caller-supplied buffer, you should set this flag to 1 during your SKEL_handle_factory(). When set, PDO will call your SKEL_stmt_describer() earlier than it would otherwise. This early call allows you to determine those buffer sizes and issue appropriate calls to the database client library.

If your database client library API simply returns pointers to its own internal buffers for you to copy after each fetch call, you should leave this value set to 0.

*******

If your driver doesn't support native prepared statements (supports_placeholders is set to PDO_PLACEHOLDER_NONE), you must set this value to the maximum length that can be taken up by a single character when it is quoted by your SKEL_handle_quoter() function. This value is used to calculate the amount of buffer space required when PDO executes the statement.

********

This holds the value of the DSN that was passed into the PDO constructor. If your driver implementation needed to modify the DSN for whatever reason, it should update this member during SKEL_handle_factory(). Modifying this member should be avoided. If you do change it, you must ensure that data_source_len is also correct.

*********

Whenever an error occurs during a call to one of your driver methods, you should set this member to the SQLSTATE code that best describes the error and return an error. In this HOW-TO, the suggested practice is to call SKEL_handle_error() when an error is detected, and have it set the error code.

**********

Your driver should set this during SKEL_handle_factory(); the value should reflect how the database returns the names of the columns in result sets. If the name matches the case that was used in the query, set it to PDO_CASE_NATURAL (this is actually the default). If the column names are always returned in upper case, set it to PDO_CASE_UPPER. If the column names are always returned in lower case, set it to PDO_CASE_LOWER. The value you set is used to determine if PDO should perform case folding when the user sets the PDO_ATTR_CASE attribute.

User Contributed Notes

There are no user contributed notes for this page.
Packaging and distribution
pdo_stmt_t definition
PDO Driver How-To


pdo_stmt_t definition

All fields should be treated as read-only unless explicitly stated otherwise.

pdo_stmt_t

/* represents a prepared statement */
struct _pdo_stmt_t {
    /* driver specifics */
    struct pdo_stmt_methods *methods;
*
void *driver_data;
**
/* if true, we've already successfully executed this statement at least
     * once */
    unsigned executed:1;
***
/* if true, the statement supports placeholders and can implement
     * bindParam() for its prepared statements, if false, PDO should
     * emulate prepare and bind on its behalf */
    unsigned supports_placeholders:2;
****
/* the number of columns in the result set; not valid until after
     * the statement has been executed at least once.  In some cases, might
     * not be valid until fetch (at the driver level) has been called at least once.
     * */
    int column_count;
*****
struct pdo_column_data *columns;
******
/* points at the dbh that this statement was prepared on */
    pdo_dbh_t *dbh;

    /* keep track of bound input parameters.  Some drivers support
     * input/output parameters, but you can't rely on that working */
    HashTable *bound_params;
    /* When rewriting from named to positional, this maps positions to names */
    HashTable *bound_param_map;
    /* keep track of PHP variables bound to named (or positional) columns
     * in the result set */
    HashTable *bound_columns;

    /* not always meaningful */
    long row_count;

    /* used to hold the statement's current query */
    char *query_string;
    int query_stringlen;

    /* the copy of the query with expanded binds ONLY for emulated-prepare drivers */
    char *active_query_string;
    int active_query_stringlen;

    /* the cursor specific error code. */
    pdo_error_type error_code;

    /* used by the query parser for driver specific
     * parameter naming (see pgsql driver for example) */
    const char *named_rewrite_template;
};
* | The driver must set this during SKEL_handle_preparer().
** | This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.
*** | This is set by PDO after the statement has been executed for the first time. Your driver can inspect this value to determine if it can skip one-time actions as an optimization.
**** | Discussed in more detail in SKEL_handle_preparer.
***** | Your driver is responsible for setting this field to the number of columns available in a result set. This is usually set during SKEL_stmt_execute() but with some database implementations, the column count may not be available until SKEL_stmt_fetch() has been called at least once. Drivers that implement SKEL_stmt_next_rowset() should update the column count when a new rowset is available.
****** | PDO will allocate this field based on the value that you set for the column count. You are responsible for populating each column during SKEL_stmt_describe(). You must set the precision, maxlen, name, namelen and param_type members for each column. The name is expected to be allocated using emalloc(); PDO will call efree() at the appropriate time.

User Contributed Notes

There are no user contributed notes for this page.
pdo_dbh_t definition
Constants
PDO Driver How-To


Constants

Database and Statement Attributes Table

Attribute

Valid value(s)

PDO_ATTR_AUTOCOMMIT

BOOL

TRUE if autocommit is set, FALSE otherwise.

dbh->auto_commit contains value. Processed by PDO directly.

PDO_ATTR_PREFETCH

LONG

Value of the prefetch size in drivers that support it.

PDO_ATTR_TIMEOUT

LONG

How long to wait for a db operation before timing out.

PDO_ATTR_ERRMODE

LONG

Processed and handled by PDO

PDO_ATTR_SERVER_VERSION

STRING

The "human-readable" string representing the Server/Version this driver is currently connected to.

PDO_ATTR_CLIENT_VERSION

STRING

The "human-readable" string representing the Client/Version this driver supports.

PDO_ATTR_SERVER_INFO

STRING

The "human-readable" description of the Server.

PDO_ATTR_CONNECTION_STATUS

LONG

Values not yet defined

PDO_ATTR_CASE

LONG

Processed and handled by PDO.

PDO_ATTR_CURSOR_NAME

STRING

String representing the name for a database cursor for use in "where current in <name>" SQL statements.

PDO_ATTR_CURSOR

LONG

PDO_CURSOR_FWDONLY

Forward only cursor

PDO_CURSOR_SCROLL

Scrollable cursor

The values for the attributes above are all defined in terms of the Zend API. The Zend API contains macros that can be used to convert a *zval to a value. These macros are defined in the Zend header file, zend_API.h in the Zend directory of your PHP build directory. Some of these attributes can be used with the statement attribute handlers such as the PDO_ATTR_CURSOR and PDO_ATTR_CURSOR_NAME. See the statement attribute handling functions for more information.

User Contributed Notes

There are no user contributed notes for this page.
pdo_stmt_t definition
Error handling
PDO Driver How-To


Error handling

Error handling is implemented using a hand-shaking protocol between PDO and the database driver code. The database driver code signals PDO that an error has occurred via a failure (0) return from any of the interface functions. If a zero is returned, set the field error_code in the control block appropriate to the context (either the pdo_dbh_t or pdo_stmt_t block). In practice, it is probably a good idea to set the field in both blocks to the same value to ensure the correct one is getting used.

The error_mode field is a six-byte field containing a 5 character ASCIIZ SQLSTATE identifier code. This code drives the error message process. The SQLSTATE code is used to look up an error message in the internal PDO error message table (see pdo_sqlstate.c for a list of error codes and their messages). If the code is not known to PDO, a default "Unknown Message" value will be used.

In addition to the SQLSTATE code and error message, PDO will call the driver-specific fetch_err() routine to obtain supplemental data for the particular error condition. This routine is passed an array into which the driver may place additional information. This array has slot positions assigned to particular types of supplemental info:

  1. A native error code. This will frequently be an error code obtained from the database API.

  2. A descriptive string. This string can contain any additional information related to the failure. Database drivers typically include information such as an error message, code location of the failure, and any additional descriptive information the driver developer feels worthy of inclusion. It is generally a good idea to include all diagnostic information obtainable from the database interface at the time of the failure. For driver-detected errors (such as memory allocation problems), the driver developer can define whatever error information that seems appropriate.

User Contributed Notes

There are no user contributed notes for this page.
Constants
Extension FAQs
PDO Driver How-To


Extension FAQs

User Contributed Notes

There are no user contributed notes for this page.
Error handling
Zend Engine 2 API reference
Ядро PHP: Руководство хакера по Zend Engine


Zend Engine 2 API reference

User Contributed Notes

There are no user contributed notes for this page.
Extension FAQs
Zend Engine 2 Opcodes
Ядро PHP: Руководство хакера по Zend Engine


Zend Engine 2 Opcodes

Содержание

  • Opcode Descriptions and Examples

When parsing PHP files, Zend Engine 2 generates a series of operation codes, commonly known as "opcodes", representing the function of the code. This part of the manual details those opcodes and their behaviour.

Opcodes may be dumped for a given PHP file using the vld extension (see » http://pecl.php.net/package/vld).

Opcode List
Number | Name | Has sample code?
0 | NOP | yes
1 | ADD | yes
2 | SUB | yes
3 | MUL | yes
4 | DIV | yes
5 | MOD | yes
6 | SL | yes
7 | SR | yes
8 | CONCAT | yes
9 | BW_OR | yes
10 | BW_AND | yes
11 | BW_XOR | yes
12 | BW_NOT | yes
13 | BOOL_NOT | yes
14 | BOOL_XOR | yes
15 | IS_IDENTICAL | yes
16 | IS_NOT_IDENTICAL | yes
17 | IS_EQUAL | yes
18 | IS_NOT_EQUAL | yes
19 | IS_SMALLER | yes
20 | IS_SMALLER_OR_EQUAL | yes
21 | CAST | yes
22 | QM_ASSIGN | yes
23 | ASSIGN_ADD | yes
24 | ASSIGN_SUB | yes
25 | ASSIGN_MUL | yes
26 | ASSIGN_DIV | yes
27 | ASSIGN_MOD | yes
28 | ASSIGN_SL | yes
29 | ASSIGN_SR | yes
30 | ASSIGN_CONCAT | yes
31 | ASSIGN_BW_OR | yes
32 | ASSIGN_BW_AND | yes
33 | ASSIGN_BW_XOR | yes
34 | PRE_INC | yes
35 | PRE_DEC | yes
36 | POST_INC | yes
37 | POST_DEC | yes
38 | ASSIGN | yes
39 | ASSIGN_REF | yes
40 | ECHO | yes
41 | PRINT | yes
42 | JMP | yes
43 | JMPZ | yes
44 | JMPNZ | yes
45 | JMPZNZ | yes
46 | JMPZ_EX | yes
47 | JMPNZ_EX | yes
48 | CASE | yes
49 | SWITCH_FREE | yes
50 | BRK | yes
51 | CONT | yes
52 | BOOL | yes
53 | INIT_STRING | yes
54 | ADD_CHAR | yes
55 | ADD_STRING | yes
56 | ADD_VAR | yes
57 | BEGIN_SILENCE | yes
58 | END_SILENCE | yes
59 | INIT_FCALL_BY_NAME | yes
60 | DO_FCALL | yes
61 | DO_FCALL_BY_NAME | yes
62 | RETURN | yes
63 | RECV | yes
64 | RECV_INIT | yes
65 | SEND_VAL | yes
66 | SEND_VAR | yes
67 | SEND_REF | yes
68 | NEW | yes
69 | INIT_NS_FCALL_BY_NAME | no
70 | FREE | yes
71 | INIT_ARRAY | yes
72 | ADD_ARRAY_ELEMENT | yes
73 | INCLUDE_OR_EVAL | yes
74 | UNSET_VAR | yes
75 | UNSET_DIM | yes
76 | UNSET_OBJ | yes
77 | FE_RESET | yes
78 | FE_FETCH | yes
79 | EXIT | yes
80 | FETCH_R | yes
81 | FETCH_DIM_R | yes
82 | FETCH_OBJ_R | yes
83 | FETCH_W | yes
84 | FETCH_DIM_W | yes
85 | FETCH_OBJ_W | yes
86 | FETCH_RW | yes
87 | FETCH_DIM_RW | yes
88 | FETCH_OBJ_RW | yes
89 | FETCH_IS | yes
90 | FETCH_DIM_IS | no
91 | FETCH_OBJ_IS | no
92 | FETCH_FUNC_ARG | yes
93 | FETCH_DIM_FUNC_ARG | yes
94 | FETCH_OBJ_FUNC_ARG | yes
95 | FETCH_UNSET | no
96 | FETCH_DIM_UNSET | no
97 | FETCH_OBJ_UNSET | no
98 | FETCH_DIM_TMP_VAR | yes
99 | FETCH_CONSTANT | yes
100 | GOTO | no
101 | EXT_STMT | no
102 | EXT_FCALL_BEGIN | no
103 | EXT_FCALL_END | no
104 | EXT_NOP | no
105 | TICKS | yes
106 | SEND_VAR_NO_REF | no
107 | CATCH | yes
108 | THROW | yes
109 | FETCH_CLASS | yes
110 | CLONE | yes
111 | RETURN_BY_REF | no
112 | INIT_METHOD_CALL | yes
113 | INIT_STATIC_METHOD_CALL | yes
114 | ISSET_ISEMPTY_VAR | yes
115 | ISSET_ISEMPTY_DIM_OBJ | yes
116 | not documented | no
117 | not documented | no
118 | not documented | no
119 | not documented | no
120 | not documented | no
121 | not documented | no
122 | not documented | no
123 | not documented | no
124 | not documented | no
125 | not documented | no
126 | not documented | no
127 | not documented | no
128 | not documented | no
129 | not documented | no
130 | not documented | no
131 | not documented | no
132 | PRE_INC_OBJ | yes
133 | PRE_DEC_OBJ | yes
134 | POST_INC_OBJ | yes
135 | POST_DEC_OBJ | yes
136 | ASSIGN_OBJ | yes
137 | not documented | no
138 | INSTANCEOF | yes
139 | DECLARE_CLASS | yes
140 | DECLARE_INHERITED_CLASS | yes
141 | DECLARE_FUNCTION | yes
142 | RAISE_ABSTRACT_ERROR | yes
143 | DECLARE_CONST | no
144 | ADD_INTERFACE | no
145 | DECLARE_INHERITED_CLASS_DELAYED | no
146 | VERIFY_ABSTRACT_CLASS | no
147 | ASSIGN_DIM | yes
148 | ISSET_ISEMPTY_PROP_OBJ | yes
149 | HANDLE_EXCEPTION | yes
150 | USER_OPCODE | no
152 | ZEND_JMP_SET | no
153 | ZEND_DECLARE_LAMBDA_FUNCTION | no

User Contributed Notes

There are no user contributed notes for this page.
Zend Engine 2 API reference
Opcode Descriptions and Examples
Ядро PHP: Руководство хакера по Zend Engine


Opcode Descriptions and Examples

Содержание

  • ADD
  • ADD_ARRAY_ELEMENT
  • ADD_CHAR
  • ADD_INTERFACE
  • ADD_STRING
  • ADD_VAR
  • ASSIGN
  • ASSIGN_ADD
  • ASSIGN_BW_AND
  • ASSIGN_BW_OR
  • ASSIGN_BW_XOR
  • ASSIGN_CONCAT
  • ASSIGN_DIM
  • ASSIGN_DIV
  • ASSIGN_MOD
  • ASSIGN_MUL
  • ASSIGN_OBJ
  • ASSIGN_REF
  • ASSIGN_SL
  • ASSIGN_SR
  • ASSIGN_SUB
  • BEGIN_SILENCE
  • BOOL
  • BOOL_NOT
  • BOOL_XOR
  • BRK
  • BW_AND
  • BW_NOT
  • BW_OR
  • BW_XOR
  • CASE
  • CAST
  • CATCH
  • CLONE
  • CONCAT
  • CONT
  • DECLARE_CLASS
  • DECLARE_CONST
  • DECLARE_FUNCTION
  • DECLARE_INHERITED_CLASS
  • DECLARE_INHERITED_CLASS_DELAYED
  • DIV
  • DO_FCALL
  • DO_FCALL_BY_NAME
  • ECHO
  • END_SILENCE
  • EXIT
  • EXT_FCALL_BEGIN
  • EXT_FCALL_END
  • EXT_NOP
  • EXT_STMT
  • FE_FETCH
  • FE_RESET
  • FETCH_CLASS
  • FETCH_CONSTANT
  • FETCH_DIM_FUNC_ARG
  • FETCH_DIM_IS
  • FETCH_DIM_R
  • FETCH_DIM_RW
  • FETCH_DIM_TMP_VAR
  • FETCH_DIM_UNSET
  • FETCH_DIM_W
  • FETCH_FUNC_ARG
  • FETCH_IS
  • FETCH_OBJ_FUNC_ARG
  • FETCH_OBJ_IS
  • FETCH_OBJ_R
  • FETCH_OBJ_RW
  • FETCH_OBJ_UNSET
  • FETCH_OBJ_W
  • FETCH_R
  • FETCH_RW
  • FETCH_UNSET
  • FETCH_W
  • FREE
  • GOTO
  • HANDLE_EXCEPTION
  • INCLUDE_OR_EVAL
  • INIT_ARRAY
  • INIT_FCALL_BY_NAME
  • INIT_METHOD_CALL
  • INIT_NS_FCALL_BY_NAME
  • INIT_STATIC_METHOD_CALL
  • INIT_STRING
  • INSTANCEOF
  • IS_EQUAL
  • IS_IDENTICAL
  • IS_NOT_EQUAL
  • IS_NOT_IDENTICAL
  • IS_SMALLER
  • IS_SMALLER_OR_EQUAL
  • ISSET_ISEMPTY_DIM_OBJ
  • ISSET_ISEMPTY_PROP_OBJ
  • ISSET_ISEMPTY_VAR
  • JMP
  • JMPNZ
  • JMPNZ_EX
  • JMPZ
  • JMPZ_EX
  • JMPZNZ
  • MOD
  • MUL
  • NEW
  • NOP
  • POST_DEC
  • POST_DEC_OBJ
  • POST_INC
  • POST_INC_OBJ
  • PRE_DEC
  • PRE_DEC_OBJ
  • PRE_INC
  • PRE_INC_OBJ
  • PRINT
  • QM_ASSIGN
  • RAISE_ABSTRACT_ERROR
  • RECV
  • RECV_INIT
  • RETURN
  • RETURN_BY_REF
  • SEND_REF
  • SEND_VAL
  • SEND_VAR
  • SEND_VAR_NO_REF
  • SL
  • SR
  • SUB
  • SWITCH_FREE
  • THROW
  • TICKS
  • UNSET_DIM
  • UNSET_OBJ
  • UNSET_VAR
  • USER_OPCODE
  • VERIFY_ABSTRACT_CLASS
  • ZEND_DECLARE_LAMBDA_FUNCTION
  • ZEND_JMP_SET

User Contributed Notes

There are no user contributed notes for this page.
Zend Engine 2 Opcodes
ADD
Zend Engine 2 Opcodes


ADD

PHP code

<?php
/*
 * Adds "value1" to "value2" and stores the result into "result".
 * opcode number: 1
 */
echo 1 + 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ADD |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
Opcode Descriptions and Examples
ADD_ARRAY_ELEMENT
Opcode Descriptions and Examples


ADD_ARRAY_ELEMENT

PHP code

<?php
/*
 * Add elem-value as an element to array-value
 * opcode number: 72
 */
$a = array(1,2,3);
print_r($a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'print_r'
8 | 6 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ADD
ADD_CHAR
Opcode Descriptions and Examples


ADD_CHAR

PHP code

<?php
/*
 * add character value2 to string value1 and store in result
 * opcode number: 54
 */
echo "hello\ world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ECHO |  |  |  | 'hello%5C+world'
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ADD_ARRAY_ELEMENT
ADD_INTERFACE
Opcode Descriptions and Examples


ADD_INTERFACE

PHP code

<?php
/*
 *
 * opcode number: 144
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
ADD_CHAR
ADD_STRING
Opcode Descriptions and Examples


ADD_STRING

PHP code

<?php
/*
 * add string value2 to string value2 and store in result
 * opcode number: 55
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ADD_INTERFACE
ADD_VAR
Opcode Descriptions and Examples


ADD_VAR

PHP code

<?php
/*
 * add contents of variable in value2 to string value1 and store in result
 * opcode number: 56
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ADD_STRING
ASSIGN
Opcode Descriptions and Examples


ASSIGN

PHP code

<?php
/*
 * assigns value1 to result
 * opcode number: 38
 */
$a=1;
$a='a';
$a=new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !0,'a'
8 | 2 | ZEND_FETCH_CLASS |  |  | :2 | 'A'
 | 3 | NEW |  |  | $3 | :2
 | 4 | DO_FCALL_BY_NAME |  | 0 |  |
 | 5 | ASSIGN |  |  |  | !0,$3
9 | 6 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ADD_VAR
ASSIGN_ADD
Opcode Descriptions and Examples


ASSIGN_ADD

PHP code

<?php
/*
 * Add value1 to value2 and store in variable indicated by value1
 * opcode number: 23
 */
$a+=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_ADD |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN
ASSIGN_BW_AND
Opcode Descriptions and Examples


ASSIGN_BW_AND

PHP code

<?php
/*
 * Performs binary AND on result and value1 and stores in variable indicated by result.
 * opcode number: 32
 */
$a &= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_AND |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_ADD
ASSIGN_BW_OR
Opcode Descriptions and Examples


ASSIGN_BW_OR

PHP code

<?php
/*
 * Performs binary OR on result and value1 and stores in variable indicated by result.
 * opcode number: 31
 */
$a |= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_OR |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_BW_AND
ASSIGN_BW_XOR
Opcode Descriptions and Examples


ASSIGN_BW_XOR

PHP code

<?php
/*
 * Performs binary XOR on result and value1and stores in variable indicated by result.
 * opcode number: 33
 */
$a ^= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_XOR |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_BW_OR
ASSIGN_CONCAT
Opcode Descriptions and Examples


ASSIGN_CONCAT

PHP code

<?php
/*
 * Concats string values result and value1 and store in variable indicated by result
 * opcode number: 30
 */
$a .= 'z';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_CONCAT |  |  |  | !0,'z'
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_BW_XOR
ASSIGN_DIM
Opcode Descriptions and Examples


ASSIGN_DIM

PHP code

<?php
/*
 *
 * opcode number: 147
 */
$b = 1;
$a[1][2] = $b;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$b, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | FETCH_DIM_W |  |  | $1 | !1,1
 | 2 | ZEND_ASSIGN_DIM |  |  |  | $1,2
 | 3 | ZEND_OP_DATA |  |  |  | !0,$3
8 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_CONCAT
ASSIGN_DIV
Opcode Descriptions and Examples


ASSIGN_DIV

PHP code

<?php
/*
 * Divide result by value1and store in variable indicated by result.
 * opcode number: 26
 */
$a/=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_DIV |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_DIM
ASSIGN_MOD
Opcode Descriptions and Examples


ASSIGN_MOD

PHP code

<?php
/*
 * Perform result mod value1 and store in variable indicated by result
 * opcode number: 27
 */
$a %= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_MOD |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_DIV
ASSIGN_MUL
Opcode Descriptions and Examples


ASSIGN_MUL

PHP code

<?php
/*
 * Multiply result by value1 and store in variable indicated by result
 * opcode number: 25
 */
$a*=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_MUL |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_MOD
ASSIGN_OBJ
Opcode Descriptions and Examples


ASSIGN_OBJ

PHP code

<?php
/*
 *
 * opcode number: 136
 */
$obj->a = $otherobj;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj, !1=$otherobj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ASSIGN_OBJ |  |  |  | !0,'a'
 | 1 | ZEND_OP_DATA |  |  |  | !1
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_MUL
ASSIGN_REF
Opcode Descriptions and Examples


ASSIGN_REF

PHP code

<?php
/*
 * indicates that variable indicated by value1 is to be treated in the global scope for the remainder of the current scope.
 * opcode number: 39
 */
global $a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | FETCH_W | globallock |  | $0 | 'a'
 | 1 | ASSIGN_REF |  |  |  | !0,$0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_OBJ
ASSIGN_SL
Opcode Descriptions and Examples


ASSIGN_SL

PHP code

<?php
/*
 * Shift result by value1 bits to left and store in variable indicated by result
 * opcode number: 28
 */
$a <<= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SL |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_REF
ASSIGN_SR
Opcode Descriptions and Examples


ASSIGN_SR

PHP code

<?php
/*
 * Shift result by value1 bits to right and store in variable indicated by result
 * opcode number: 29
 */
$a >>= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SR |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_SL
ASSIGN_SUB
Opcode Descriptions and Examples


ASSIGN_SUB

PHP code

<?php
/*
 * Subtract value1 from value2 and store in variable indicated by value1
 * opcode number: 24
 */
$a-=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SUB |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_SR
BEGIN_SILENCE
Opcode Descriptions and Examples


BEGIN_SILENCE

PHP code

<?php
/*
 * prepare to perform function call without displaying error messages
 * opcode number: 57
 */
/* Intentional file error */
$my_file = @file ('non_existent_file') or
   die ("error:'$php_errormsg'");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$my_file, !1=$php_errormsg

line | # | op | fetch | ext | return | operands
7 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | SEND_VAL |  |  |  | 'non_existent_file'
 | 2 | DO_FCALL |  | 1 |  | 'file'
 | 3 | END_SILENCE |  |  |  | ~0
 | 4 | ASSIGN |  |  | $2 | !0,$1
 | 5 | JMPNZ_EX |  |  | ~3 | $2,->11
8 | 6 | ADD_STRING |  |  | ~4 | 'error%3A%27'
 | 7 | ADD_VAR |  |  | ~4 | ~4,!1
 | 8 | ADD_CHAR |  |  | ~4 | ~4,39
 | 9 | EXIT |  |  |  | ~4
 | 10 | BOOL |  |  | ~3 | true
 | 11 | FREE |  |  |  | ~3
9 | 12 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ASSIGN_SUB
BOOL
Opcode Descriptions and Examples


BOOL

PHP code

<?php
/*
 * convert value1 to boolean and store in result??????????
 * opcode number: 52
 */
if (1 || 2 || 1) echo "foo";
//$a = true;
//if($a) echo "foo";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | JMPNZ_EX |  |  | ~0 | 1,->2
 | 1 | BOOL |  |  | ~0 | 2
 | 2 | JMPNZ_EX |  |  | ~0 | ~0,->4
 | 3 | BOOL |  |  | ~0 | 1
 | 4 | JMPZ |  |  |  | ~0,->7
 | 5 | ECHO |  |  |  | 'foo'
 | 6 | JMP |  |  |  | ->7
9 | 7 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BEGIN_SILENCE
BOOL_NOT
Opcode Descriptions and Examples


BOOL_NOT

PHP code

<?php
/*
 * Boolean (logical) not of "value"
 * opcode number: 13
 */
echo !1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BOOL_NOT |  |  | ~0 | 1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BOOL
BOOL_XOR
Opcode Descriptions and Examples


BOOL_XOR

PHP code

<?php
/*
 * Boolean (logical) xor of value1
 * opcode number: 14
 */
echo 1 xor 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BOOL_XOR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BOOL_NOT
BRK
Opcode Descriptions and Examples


BRK

PHP code

<?php
/*
 * ???  End of a case block exists the current switch block.  Followed by JMP?
 * opcode number: 50
 */
$x = 0;
while(1) {
    if($x == 0) break;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
7 | 1 | JMPZ |  |  |  | 1,->7
8 | 2 | IS_EQUAL |  |  | ~1 | !0,0
 | 3 | JMPZ |  |  |  | ~1,->6
 | 4 | BRK |  |  |  | 1
 | 5 | JMP |  |  |  | ->6
9 | 6 | JMP |  |  |  | ->1
10 | 7 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BOOL_XOR
BW_AND
Opcode Descriptions and Examples


BW_AND

PHP code

<?php
/*
 * Bit-wise and of value1 and value2
 * opcode number: 10
 */
echo 1&2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_AND |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BRK
BW_NOT
Opcode Descriptions and Examples


BW_NOT

PHP code

<?php
/*
 * Bit-wise not of "value"
 * opcode number: 12
 */
echo ~15;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_NOT |  |  | ~0 | 15
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BW_AND
BW_OR
Opcode Descriptions and Examples


BW_OR

PHP code

<?php
/*
 * Bit-wise or of value1 and value2
 * opcode number: 9
 */
echo 1|2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_OR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BW_NOT
BW_XOR
Opcode Descriptions and Examples


BW_XOR

PHP code

<?php
/*
 * Bit-wise xor of value1 and value2
 * opcode number: 11
 */
echo 1^2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_XOR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BW_OR
CASE
Opcode Descriptions and Examples


CASE

PHP code

<?php
/*
 * Set result to true if value1 equals value2.  The value2 must be a constant value?
 * opcode number: 48
 */
$i=0;
switch ($i) {
   case 0:
         echo "i=0";
         break;
   case 1:
         echo "i=1";
         break;
   case 2:
         echo "i=2";
         break;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
8 | 1 | CASE |  |  | ~1 | !0,0
 | 2 | JMPZ |  |  |  | ~1,->6
9 | 3 | ECHO |  |  |  | 'i%3D0'
10 | 4 | BRK |  |  |  | 1
11 | 5 | JMP |  |  |  | ->8
 | 6 | CASE |  |  | ~1 | !0,1
 | 7 | JMPZ |  |  |  | ~1,->11
12 | 8 | ECHO |  |  |  | 'i%3D1'
13 | 9 | BRK |  |  |  | 1
14 | 10 | JMP |  |  |  | ->13
 | 11 | CASE |  |  | ~1 | !0,2
 | 12 | JMPZ |  |  |  | ~1,->16
15 | 13 | ECHO |  |  |  | 'i%3D2'
16 | 14 | BRK |  |  |  | 1
17 | 15 | JMP |  |  |  | ->16
18 | 16 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
BW_XOR
CAST
Opcode Descriptions and Examples


CAST

PHP code

<?php
/*
 * casts value1 as type value2 (?? Not certain about arguments ??)
 * opcode number: 21
 */
echo (int)1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | CAST |  |  | ~0 | 1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
CASE
CATCH
Opcode Descriptions and Examples


CATCH

PHP code

<?php
/*
 *
 * opcode number: 107
 */
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$error, !1=$e

line | # | op | fetch | ext | return | operands
7 | 0 | ASSIGN |  |  |  | !0,'Always+throw+this+error'
8 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'Exception'
 | 2 | NEW |  |  | $2 | :1
 | 3 | SEND_VAR |  |  |  | !0
 | 4 | DO_FCALL_BY_NAME |  | 1 |  |
 | 5 | ZEND_THROW |  | 0 |  | $2
11 | 6 | ECHO |  |  |  | 'Never+executed'
13 | 7 | JMP |  |  |  | ->15
 | 8 | ZEND_FETCH_CLASS |  |  | :4 | 'Exception'
 | 9 | ZEND_CATCH |  | 15 |  | $4,!1
14 | 10 | ECHO |  |  |  | 'Caught+exception%3A+'
 | 11 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'getMessage'
 | 12 | DO_FCALL_BY_NAME |  | 0 |  |
 | 13 | ECHO |  |  |  | $6
 | 14 | ECHO |  |  |  | '%0A'
18 | 15 | ECHO |  |  |  | 'Hello+World'
19 | 16 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
CAST
CLONE
Opcode Descriptions and Examples


CLONE

PHP code

<?php
/*
 *
 * opcode number: 110
 */
$obj = new A();
$copy = clone $obj;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj, !1=$copy

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_CLONE |  |  | $4 | !0
 | 5 | ASSIGN |  |  |  | !1,$4
8 | 6 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
CATCH
CONCAT
Opcode Descriptions and Examples


CONCAT

PHP code

<?php
/*
 * Concats string values string1 and string2
 * opcode number: 8
 */
echo "hello" . "world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | CONCAT |  |  | ~0 | 'hello','world'
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
CLONE
CONT
Opcode Descriptions and Examples


CONT

PHP code

<?php
/*
 * Continue next iteration of current loop level
 * opcode number: 51
 */
$foo = false;
while(!$foo) {
    $foo = true;
    continue;
}
?>

PHP opcodes

Function name: (null)

compiled vars: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0, false
7 | 1 | BOOL_NOT |  |  | ~1 | !0
 | 2 | JMPZ |  |  |  | ~1, ->5
8 | 3 | ASSIGN |  |  |  | !0, true
9 | 4 | CONT |  |  |  | 1
10 | 5 | JMP |  |  |  | ->1
12 | 6 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
CONCAT
DECLARE_CLASS
Opcode Descriptions and Examples


DECLARE_CLASS

PHP code

<?php
/*
 * Declare a class with the name of class-name as the implementation specified by ID.
 * opcode number: 139
 */
class A {
    function methodA(){
        echo "hello world";
    }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
11 | 1 | RETURN |  |  |  | 1

Function name: methodA

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ECHO |  |  |  | 'hello+world'
9 | 1 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
CONT
DECLARE_CONST
Opcode Descriptions and Examples


DECLARE_CONST

PHP code

<?php
/*
 *
 * opcode number: 143
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
DECLARE_CLASS
DECLARE_FUNCTION
Opcode Descriptions and Examples


DECLARE_FUNCTION

PHP code

<?php
/*
 *
 * opcode number: 141
 */
class A{
 function funcA(){
 }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | RETURN |  |  |  | 1

Function name: funcA

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
DECLARE_CONST
DECLARE_INHERITED_CLASS
Opcode Descriptions and Examples


DECLARE_INHERITED_CLASS

PHP code

<?php
/*
 *
 * opcode number: 140
 */
 if($b){
 class Foo {
  public static $my_static = 'foo';
  public function staticValue() {
    return self::$my_static;
  }
 }

 class Bar extends Foo {
  public function fooStatic() {
     echo parent::$my_static;
  }
 }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$b

line | # | op | fetch | ext | return | operands
6 | 0 | JMPZ |  |  |  | !0,->5
7 | 1 | ZEND_DECLARE_CLASS |  |  | $0 | '%00foo%2Fmnt%2Fworkspace%2Fws_phpscripts%2FPHPopcodes%2Fphpsamples%2FDECLARE_INHERITED_CLASS.php0xb7be503b','foo'
14 | 2 | ZEND_FETCH_CLASS |  |  | :1 | 'Foo'
 | 3 | ZEND_DECLARE_INHERITED_CLASS |  |  | $2 | '%00bar%2Fmnt%2Fworkspace%2Fws_phpscripts%2FPHPopcodes%2Fphpsamples%2FDECLARE_INHERITED_CLASS.php0xb7be50bc','bar'
19 | 4 | JMP |  |  |  | ->5
20 | 5 | RETURN |  |  |  | 1

Function name: staticValue

Compiled variables: !0=$my_static

line | # | op | fetch | ext | return | operands
10 | 0 | ZEND_FETCH_CLASS |  |  |  |
 | 1 | FETCH_R | staticmember |  | $1 | 'my_static'
 | 2 | RETURN |  |  |  | $1
11 | 3 | RETURN |  |  |  | null

Function name: fooStatic

Compiled variables: !0=$my_static

line | # | op | fetch | ext | return | operands
16 | 0 | ZEND_FETCH_CLASS |  |  | :0 |
 | 1 | FETCH_R | staticmember |  | $1 | 'my_static'
 | 2 | ECHO |  |  |  | $1
17 | 3 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
DECLARE_FUNCTION
DECLARE_INHERITED_CLASS_DELAYED
Opcode Descriptions and Examples


DECLARE_INHERITED_CLASS_DELAYED

PHP code

<?php
/*
 *
 * opcode number: 145
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
DECLARE_INHERITED_CLASS
DIV
Opcode Descriptions and Examples


DIV

PHP code

<?php
/*
 * Divides "value1" by "value2" and stores the result into "result".
 * opcode number: 4
 */
echo 6/3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | DIV |  |  | ~0 | 6,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
DECLARE_INHERITED_CLASS_DELAYED
DO_FCALL
Opcode Descriptions and Examples


DO_FCALL

PHP code

<?php
/*
 * Call a function.  Following multiple SEND_VAL, SEND_VAR or SEND_REF.
 * opcode number: 60
 */
$a = phpinfo();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | DO_FCALL |  | 0 |  | 'phpinfo'
 | 1 | ASSIGN |  |  |  | !0,$0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
DIV
DO_FCALL_BY_NAME
Opcode Descriptions and Examples


DO_FCALL_BY_NAME

PHP code

<?php
/*
 * Call a function by name.  Following INIT_FCALL_BY_NAME and multiple SEND_VAL, SEND_VAR or SEND_REF.
 * opcode number: 61
 */
$x = 'phpinfo';
$a = $x();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,'phpinfo'
7 | 1 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !1,$1
8 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
DO_FCALL
ECHO
Opcode Descriptions and Examples


ECHO

PHP code

<?php
/*
 * Dump text
 * opcode number: 40
 */
echo "hello world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ECHO |  |  |  | 'hello+world'
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
DO_FCALL_BY_NAME
END_SILENCE
Opcode Descriptions and Examples


END_SILENCE

PHP code

<?php
/*
 * no longer surpress error messages
 * opcode number: 58
 */
$my_file = @file ('non_existent_file') or
   die ("error:'$php_errormsg'");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$my_file, !1=$php_errormsg

line | # | op | fetch | ext | return | operands
6 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | SEND_VAL |  |  |  | 'non_existent_file'
 | 2 | DO_FCALL |  | 1 |  | 'file'
 | 3 | END_SILENCE |  |  |  | ~0
 | 4 | ASSIGN |  |  | $2 | !0,$1
 | 5 | JMPNZ_EX |  |  | ~3 | $2,->11
7 | 6 | ADD_STRING |  |  | ~4 | 'error%3A%27'
 | 7 | ADD_VAR |  |  | ~4 | ~4,!1
 | 8 | ADD_CHAR |  |  | ~4 | ~4,39
 | 9 | EXIT |  |  |  | ~4
 | 10 | BOOL |  |  | ~3 | true
 | 11 | FREE |  |  |  | ~3
8 | 12 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ECHO
EXIT
Opcode Descriptions and Examples


EXIT

PHP code

<?php
/*
 * Exit running after dumping "message".
 * opcode number: 79
 */
die("foobar");
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | EXIT |  |  |  | 'foobar'
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
END_SILENCE
EXT_FCALL_BEGIN
Opcode Descriptions and Examples


EXT_FCALL_BEGIN

PHP code

<?php
/*
 *
 * opcode number: 102
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
EXIT
EXT_FCALL_END
Opcode Descriptions and Examples


EXT_FCALL_END

PHP code

<?php
/*
 *
 * opcode number: 103
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
EXT_FCALL_BEGIN
EXT_NOP
Opcode Descriptions and Examples


EXT_NOP

PHP code

<?php
/*
 *
 * opcode number: 104
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
EXT_FCALL_END
EXT_STMT
Opcode Descriptions and Examples


EXT_STMT

PHP code

<?php
/*
 *
 * opcode number: 101
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
EXT_NOP
FE_FETCH
Opcode Descriptions and Examples


FE_FETCH

PHP code

<?php
/*
 * Fetch an element from iterator.  If no element is available, jump to address.  Followed by OP_DATA?
 * opcode number: 78
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
EXT_STMT
FE_RESET
Opcode Descriptions and Examples


FE_RESET

PHP code

<?php
/*
 * Initialize an iterator on array-value.  If the array is empty, jump to address.  Followed by FE_FETCH.
 * opcode number: 77
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FE_FETCH
FETCH_CLASS
Opcode Descriptions and Examples


FETCH_CLASS

PHP code

<?php
/*
 *
 * opcode number: 109
 */
$obj = new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FE_RESET
FETCH_CONSTANT
Opcode Descriptions and Examples


FETCH_CONSTANT

PHP code

<?php
/*
 * Fetch the constant value bound to the specified name (name) and stores it into a variable (result).
 * opcode number: 99
 */
define("FOO", "something");
echo FOO;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SEND_VAL |  |  |  | 'FOO'
 | 1 | SEND_VAL |  |  |  | 'something'
 | 2 | DO_FCALL |  | 2 |  | 'define'
7 | 3 | FETCH_CONSTANT |  |  | ~1 | 'FOO'
 | 4 | ECHO |  |  |  | ~1
8 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_CLASS
FETCH_DIM_FUNC_ARG
Opcode Descriptions and Examples


FETCH_DIM_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 93
 */

function foo(&$x)
{
  print($x);
}

$x = array(0, 1, 2, 3, 4, 5);
$z = "foo";

$z($x[0]);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$z

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
12 | 1 | INIT_ARRAY |  |  | ~0 | 0
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 1
 | 3 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 4 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 5 | ADD_ARRAY_ELEMENT |  |  | ~0 | 4
 | 6 | ADD_ARRAY_ELEMENT |  |  | ~0 | 5
 | 7 | ASSIGN |  |  |  | !0,~0
13 | 8 | ASSIGN |  |  |  | !1,'foo'
15 | 9 | INIT_FCALL_BY_NAME |  |  |  | !1
 | 10 | FETCH_DIM_FUNC_ARG |  |  | $3 | !0,0
 | 11 | SEND_VAR |  |  |  | $3
 | 12 | DO_FCALL_BY_NAME |  | 1 |  |
17 | 13 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
7 | 0 | RECV |  |  |  | 1
9 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
10 | 3 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
FETCH_CONSTANT
FETCH_DIM_IS
Opcode Descriptions and Examples


FETCH_DIM_IS

PHP code

<?php
/*
 *
 * opcode number: 90
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
FETCH_DIM_FUNC_ARG
FETCH_DIM_R
Opcode Descriptions and Examples


FETCH_DIM_R

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".  Read-only?
 * opcode number: 81
 */
$x = array(1,2,3);
$a = 'x';
echo $$a[0];
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_DIM_R |  |  | $3 | !1,0
 | 6 | FETCH_R | local |  | $4 | $3
 | 7 | ECHO |  |  |  | $4
9 | 8 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_DIM_IS
FETCH_DIM_RW
Opcode Descriptions and Examples


FETCH_DIM_RW

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".
 * opcode number: 87
 */
$x = array(1,2,3);
$a = 'x';
$$a[0]++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_DIM_R |  |  | $3 | !1,0
 | 6 | FETCH_RW | local |  | $4 | $3
 | 7 | POST_INC |  |  | ~5 | $4
 | 8 | FREE |  |  |  | ~5
9 | 9 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_DIM_R
FETCH_DIM_TMP_VAR
Opcode Descriptions and Examples


FETCH_DIM_TMP_VAR

PHP code

<?php
/*
 * Fetch an entry of an array from a temporal variable?
 * opcode number: 98
 */
list($x) = array("X");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 'X'
 | 1 | FETCH_DIM_TMP_VAR |  |  | $1 | ~0,0
 | 2 | ASSIGN |  |  |  | !0,$1
 | 3 | FREE |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_DIM_RW
FETCH_DIM_UNSET
Opcode Descriptions and Examples


FETCH_DIM_UNSET

PHP code

<?php
/*
 * Fetch an entry of an array variable for the purpose of unset() operation.
 * opcode number: 96
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
FETCH_DIM_TMP_VAR
FETCH_DIM_W
Opcode Descriptions and Examples


FETCH_DIM_W

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".  Write-only?
 * opcode number: 84
 */
$a = 1;
while($a > 0){
    $a = 0;
}
/*$input =array(1,2,3);
while (list($var,) = @each($input)){
    unset($$var);
}*/
/*$a = array(1,2,3);
$x = 'a';
$$x[0] = 1;*/

/*while ($b = each($a)) {
  print $b;
}*/

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | IS_SMALLER |  |  | ~1 | 0,!0
 | 2 | JMPZ |  |  |  | ~1,->5
8 | 3 | ASSIGN |  |  |  | !0,0
9 | 4 | JMP |  |  |  | ->1
23 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_DIM_UNSET
FETCH_FUNC_ARG
Opcode Descriptions and Examples


FETCH_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 92
 */
function foo($x)
{
}

$x = 1;
$y = "x";
$z = "foo";

$z($$y);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$y, !2=$z

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | ASSIGN |  |  |  | !0,1
11 | 2 | ASSIGN |  |  |  | !1,'x'
12 | 3 | ASSIGN |  |  |  | !2,'foo'
14 | 4 | INIT_FCALL_BY_NAME |  |  |  | !2
 | 5 | FETCH_FUNC_ARG | local |  | $3 | !1
 | 6 | SEND_VAR |  |  |  | $3
 | 7 | DO_FCALL_BY_NAME |  | 1 |  |
16 | 8 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
8 | 1 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
FETCH_DIM_W
FETCH_IS
Opcode Descriptions and Examples


FETCH_IS

PHP code

<?php
/*
 * Fetch the value from variable which is to be used to test if it is set or not, through isset()/isempty().
 * opcode number: 89
 */
echo isset($_SESSION['userid']);
echo isset($_SESSION['userid'][1]);
echo isset($_SESSION->prop->prop);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | FETCH_IS |  |  | $0 | '_SESSION'
 | 1 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~1 | $0,'userid'
 | 2 | ECHO |  |  |  | ~1
7 | 3 | FETCH_IS |  |  | $2 | '_SESSION'
 | 4 | FETCH_DIM_IS |  |  | $3 | $2,'userid'
 | 5 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~4 | $3,1
 | 6 | ECHO |  |  |  | ~4
8 | 7 | FETCH_IS |  |  | $5 | '_SESSION'
 | 8 | FETCH_OBJ_IS |  |  | $6 | $5,'prop'
 | 9 | ZEND_ISSET_ISEMPTY_PROP_OBJ |  |  | ~7 | $6,'prop'
 | 10 | ECHO |  |  |  | ~7
9 | 11 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_FUNC_ARG
FETCH_OBJ_FUNC_ARG
Opcode Descriptions and Examples


FETCH_OBJ_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 94
 */
include './classA.php';

function foo(&$x)
{
  print($x);
}

$z = "foo";

$obj = new A();
print $obj->num;
$z($obj->num);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$z, !1=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | INCLUDE_OR_EVAL |  |  |  | '.%2FclassA.php',INCLUDE
8 | 1 | NOP |  |  |  |
13 | 2 | ASSIGN |  |  |  | !0,'foo'
15 | 3 | ZEND_FETCH_CLASS |  |  | :2 | 'A'
 | 4 | NEW |  |  | $3 | :2
 | 5 | DO_FCALL_BY_NAME |  | 0 |  |
 | 6 | ASSIGN |  |  |  | !1,$3
16 | 7 | FETCH_OBJ_R |  |  | $6 | !1,'num'
 | 8 | PRINT |  |  | ~7 | $6
 | 9 | FREE |  |  |  | ~7
17 | 10 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 11 | FETCH_OBJ_FUNC_ARG |  |  | $8 | !1,'num'
 | 12 | SEND_VAR |  |  |  | $8
 | 13 | DO_FCALL_BY_NAME |  | 1 |  |
19 | 14 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
8 | 0 | RECV |  |  |  | 1
10 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
11 | 3 | RETURN |  |  |  | null

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
8 | 0 | RECV |  |  |  | 1
10 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
11 | 3 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
FETCH_IS
FETCH_OBJ_IS
Opcode Descriptions and Examples


FETCH_OBJ_IS

PHP code

<?php
/*
 *
 * opcode number: 91
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
FETCH_OBJ_FUNC_ARG
FETCH_OBJ_R
Opcode Descriptions and Examples


FETCH_OBJ_R

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.  Read-only?
 * opcode number: 82
 */
$x = new A();
$a = 'x';
echo $$a->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_R | local |  | $5 | !1
 | 6 | FETCH_OBJ_R |  |  | $6 | $5,'num'
 | 7 | ECHO |  |  |  | $6
9 | 8 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_OBJ_IS
FETCH_OBJ_RW
Opcode Descriptions and Examples


FETCH_OBJ_RW

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.
 * opcode number: 88
 */
$x = new A();
$a = 'x';
$$a->num++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_RW | local |  | $5 | !1
 | 6 | ZEND_POST_INC_OBJ |  |  | ~7 | $5,'num'
 | 7 | FREE |  |  |  | ~7
9 | 8 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_OBJ_R
FETCH_OBJ_UNSET
Opcode Descriptions and Examples


FETCH_OBJ_UNSET

PHP code

<?php
/*
 * Fetch a property of an object variable for the purpose of unset() operation.
 * opcode number: 97
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
FETCH_OBJ_RW
FETCH_OBJ_W
Opcode Descriptions and Examples


FETCH_OBJ_W

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.  Write-only?
 * opcode number: 85
 */
$x = new A();
$a = 'x';
$$a->num = 1;;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_W | local |  | $5 | !1
 | 6 | ZEND_ASSIGN_OBJ |  |  |  | $5,'num'
 | 7 | ZEND_OP_DATA |  |  |  | 1
9 | 8 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_OBJ_UNSET
FETCH_R
Opcode Descriptions and Examples


FETCH_R

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?  Read-only?
 * opcode number: 80
 */
$x = 1;
$a = 'x';
echo $$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_R | local |  | $2 | !1
 | 3 | ECHO |  |  |  | $2
9 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_OBJ_W
FETCH_RW
Opcode Descriptions and Examples


FETCH_RW

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?
 * opcode number: 86
 */
$x = 1;
$a = 'x';
$$a++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_RW | local |  | $2 | !1
 | 3 | POST_INC |  |  | ~3 | $2
 | 4 | FREE |  |  |  | ~3
9 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_R
FETCH_UNSET
Opcode Descriptions and Examples


FETCH_UNSET

PHP code

<?php
/*
 * Fetch a variable for the purpose of unset() operation.
 * opcode number: 95
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
FETCH_RW
FETCH_W
Opcode Descriptions and Examples


FETCH_W

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?  Write-only?
 * opcode number: 83
 */
$x = 1;
$a = 'x';
$$a = 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_W | local |  | $2 | !1
 | 3 | ASSIGN |  |  |  | $2,2
9 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_UNSET
FREE
Opcode Descriptions and Examples


FREE

PHP code

<?php
/*
 * Release the allocated space of the value.
 * opcode number: 70
 */
 print "Hello World";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | PRINT |  |  | ~0 | 'Hello+World'
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
FETCH_W
GOTO
Opcode Descriptions and Examples


GOTO

PHP code

<?php
/*
 *
 * opcode number: 100
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
FREE
HANDLE_EXCEPTION
Opcode Descriptions and Examples


HANDLE_EXCEPTION

PHP code

<?php
/*
 *
 * opcode number: 149
 */
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
GOTO
INCLUDE_OR_EVAL
Opcode Descriptions and Examples


INCLUDE_OR_EVAL

PHP code

<?php
/*
 * Include the file specified by filename and eval it.
 * opcode number: 73
 */
include("test.php");
eval("test.php");
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | INCLUDE_OR_EVAL |  |  |  | 'test.php',INCLUDE
7 | 1 | INCLUDE_OR_EVAL |  |  |  | 'test.php',EVAL
8 | 2 | RETURN |  |  |  | 1

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
2 | 0 | DO_FCALL |  | 0 |  | 'phpinfo'
3 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
HANDLE_EXCEPTION
INIT_ARRAY
Opcode Descriptions and Examples


INIT_ARRAY

PHP code

<?php
/*
 * Allocate a new array with elem-value as the first element of the array.  Followed by ADD_ARRAY_ELEMENT.
 * opcode number: 71
 */
$a = array(1,2,3);
print_r($a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'print_r'
8 | 6 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
INCLUDE_OR_EVAL
INIT_FCALL_BY_NAME
Opcode Descriptions and Examples


INIT_FCALL_BY_NAME

PHP code

<?php
/*
 * prepare for a function call to function value1
 * opcode number: 59
 */
$x = 'phpinfo';
$a = $x();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,'phpinfo'
7 | 1 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !1,$1
8 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
INIT_ARRAY
INIT_METHOD_CALL
Opcode Descriptions and Examples


INIT_METHOD_CALL

PHP code

<?php
/*
 * Prepare for a method call.  Followed by DO_FCALL.
 * opcode number: 112
 */
class A {
  var $num;
    function incrementNum(){
    $num++;
  }
}

$obj = new A();
$obj->incrementNum();

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
13 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'A'
 | 2 | NEW |  |  | $2 | :1
 | 3 | DO_FCALL_BY_NAME |  | 0 |  |
 | 4 | ASSIGN |  |  |  | !0,$2
14 | 5 | ZEND_INIT_METHOD_CALL |  |  |  | !0,'incrementNum'
 | 6 | DO_FCALL_BY_NAME |  | 0 |  |
16 | 7 | RETURN |  |  |  | 1

Function name: incrementNum

Compiled variables: !0=$num

line | # | op | fetch | ext | return | operands
9 | 0 | POST_INC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
10 | 2 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
INIT_FCALL_BY_NAME
INIT_NS_FCALL_BY_NAME
Opcode Descriptions and Examples


INIT_NS_FCALL_BY_NAME

PHP code

<?php
/*
 *
 * opcode number: 69
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
INIT_METHOD_CALL
INIT_STATIC_METHOD_CALL
Opcode Descriptions and Examples


INIT_STATIC_METHOD_CALL

PHP code

<?php
/*
 *
 * opcode number: 113
 */
class Foo {
    public static function aStaticMethod() {
            echo "hello world\n";
    }
}

Foo::aStaticMethod();
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
12 | 1 | ZEND_INIT_STATIC_METHOD_CALL |  |  |  | 'Foo','aStaticMethod'
 | 2 | ZEND_OP_DATA |  |  |  | 'foo%3A%3Aastaticmethod'
 | 3 | DO_FCALL_BY_NAME |  | 0 |  |
13 | 4 | RETURN |  |  |  | 1

Function name: aStaticMethod

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ECHO |  |  |  | 'hello+world%0A'
9 | 1 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
INIT_NS_FCALL_BY_NAME
INIT_STRING
Opcode Descriptions and Examples


INIT_STRING

PHP code

<?php
/*
 * appears to create a string variable in result
 * opcode number: 53
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
INIT_STATIC_METHOD_CALL
INSTANCEOF
Opcode Descriptions and Examples


INSTANCEOF

PHP code

<?php
/*
 *
 * opcode number: 138
 */
$obj = new A();

if ($obj instanceof A) {
   echo 'A';
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
8 | 4 | ZEND_FETCH_CLASS |  |  | :4 | 'A'
 | 5 | ZEND_INSTANCEOF |  |  | ~5 | !0,$4
 | 6 | JMPZ |  |  |  | ~5,->9
9 | 7 | ECHO |  |  |  | 'A'
10 | 8 | JMP |  |  |  | ->9
11 | 9 | RETURN |  |  |  | 1

User Contributed Notes

asdf at asdf dot com 03-Apr-2012 10:13
Please note, that you get no warnings on non-existent classes:

<?php
class A() {
}

$a = new A();

$exists = ($a instanceof A); //TRUE
$exists = ($a instanceof NonExistentClass); //FALSE
Sasanapuri Satish 13-Jul-2011 01:46
The operator instanceof can also be used to determine whether an object of a class is inheriting property from another class or not.

Example:

<?php

class test
{    var $var;
    function disp()
   {
       echo "Inside the class";
   }
}

$obj=new test;

var_dump($obj instanceof test); // Prints bool(true)

?>
INIT_STRING
IS_EQUAL
Opcode Descriptions and Examples


IS_EQUAL

PHP code

<?php
/*
 * compares if value1 and value2 are equal
 * opcode number: 17
 */
echo (1 == 1);
echo (1 == 'c');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_EQUAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | IS_EQUAL |  |  | ~1 | 1,'c'
 | 3 | ECHO |  |  |  | ~1
8 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
INSTANCEOF
IS_IDENTICAL
Opcode Descriptions and Examples


IS_IDENTICAL

PHP code

<?php
/*
 * Compares value1 and value2 to see if they are equal AND have the same type
 * opcode number: 15
 */
echo (1===1);
echo (1==='a');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_IDENTICAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | IS_IDENTICAL |  |  | ~1 | 1,'a'
 | 3 | ECHO |  |  |  | ~1
8 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
IS_EQUAL
IS_NOT_EQUAL
Opcode Descriptions and Examples


IS_NOT_EQUAL

PHP code

<?php
/*
 * compares if value1 and value2 are not equal
 * opcode number: 18
 */
echo (1 != 1);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_EQUAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
IS_IDENTICAL
IS_NOT_IDENTICAL
Opcode Descriptions and Examples


IS_NOT_IDENTICAL

PHP code

<?php
/*
 * compares value1 and value2 to see if they are unequal or of different types
 * opcode number: 16
 */
echo (1 !== 1);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_IDENTICAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
IS_NOT_EQUAL
IS_SMALLER
Opcode Descriptions and Examples


IS_SMALLER

PHP code

<?php
/*
 * compares if value1 is less than value2
 * opcode number: 19
 */
echo (1 < 2);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_SMALLER |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
IS_NOT_IDENTICAL
IS_SMALLER_OR_EQUAL
Opcode Descriptions and Examples


IS_SMALLER_OR_EQUAL

PHP code

<?php
/*
 * compares if value1 is less than or equal to value2
 * opcode number: 20
 */
echo (1 >= 2);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_SMALLER_OR_EQUAL |  |  | ~0 | 2,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
IS_SMALLER
ISSET_ISEMPTY_DIM_OBJ
Opcode Descriptions and Examples


ISSET_ISEMPTY_DIM_OBJ

PHP code

<?php
/*
 * Tests if the entry of an array is set or not.
 * opcode number: 115
 */
if(isset($a[0])) return 0;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~0 | !0,0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | 0
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
IS_SMALLER_OR_EQUAL
ISSET_ISEMPTY_PROP_OBJ
Opcode Descriptions and Examples


ISSET_ISEMPTY_PROP_OBJ

PHP code

<?php
/*
 *
 * opcode number: 148
 */
$obj = new A();
if(empty($obj->num)) return 0;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_ISSET_ISEMPTY_PROP_OBJ |  |  | ~4 | !0,'num'
 | 5 | JMPZ |  |  |  | ~4,->8
 | 6 | RETURN |  |  |  | 0
 | 7 | JMP |  |  |  | ->8
8 | 8 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ISSET_ISEMPTY_DIM_OBJ
ISSET_ISEMPTY_VAR
Opcode Descriptions and Examples


ISSET_ISEMPTY_VAR

PHP code

<?php
/*
 * Tests if the value of a variable is set or not.
 * opcode number: 114
 */
if(isset($a)){ return 0;}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ISSET_ISEMPTY_VAR |  | 5 | ~0 | !0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | 0
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ISSET_ISEMPTY_PROP_OBJ
JMP
Opcode Descriptions and Examples


JMP

PHP code

<?php
/*
 * Unconditonally jump to the address
 * opcode number: 42
 */
$foo = false;
while(!$foo) {
    $foo = true;
}
?>

PHP opcodes

Function name: (null)

compiled vars: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0, false
7 | 1 | BOOL_NOT |  |  | ~1 | !0
 | 2 | JMPZ |  |  |  | ~1, ->5
8 | 3 | ASSIGN |  |  |  | !0, true
9 | 4 | JMP |  |  |  | ->1
11 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
ISSET_ISEMPTY_VAR
JMPNZ
Opcode Descriptions and Examples


JMPNZ

PHP code

<?php
/*
 * Jump to the address if the value is not zero
 * opcode number: 44
 */
for($i=0; $i<3; $i++){
    echo "hi";
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
 | 1 | IS_SMALLER |  |  | ~1 | !0,3
 | 2 | JMPZNZ |  | 6 |  | ~1,->8
 | 3 | POST_INC |  |  | ~2 | !0
 | 4 | FREE |  |  |  | ~2
 | 5 | JMP |  |  |  | ->1
7 | 6 | ECHO |  |  |  | 'hi'
8 | 7 | JMP |  |  |  | ->3
9 | 8 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
JMP
JMPNZ_EX
Opcode Descriptions and Examples


JMPNZ_EX

PHP code

<?php
/*
 * Jump to the address if the xor of value1 and value2 is zero .. ???
 * opcode number: 47
 */
if(1^2) return;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_XOR |  |  | ~0 | 1,2
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | null
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
JMPNZ
JMPZ
Opcode Descriptions and Examples


JMPZ

PHP code

<?php
/*
 * Jump to the address if the value is zero
 * opcode number: 43
 */
if($a != 0) echo "foo";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_EQUAL |  |  | ~0 | !0,0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | ECHO |  |  |  | 'foo'
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
JMPNZ_EX
JMPZ_EX
Opcode Descriptions and Examples


JMPZ_EX

PHP code

<?php
/*
 * Jump to the address if the xor of value1 and value2 is zero .. ???
 * opcode number: 46
 */

?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
JMPZ
JMPZNZ
Opcode Descriptions and Examples


JMPZNZ

PHP code

<?php
/*
 * Jump to the address if the value is .. ???
 * opcode number: 45
 */
for($i=0; $i<3; $i++){
    echo "hi";
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
 | 1 | IS_SMALLER |  |  | ~1 | !0,3
 | 2 | JMPZNZ |  | 6 |  | ~1,->8
 | 3 | POST_INC |  |  | ~2 | !0
 | 4 | FREE |  |  |  | ~2
 | 5 | JMP |  |  |  | ->1
7 | 6 | ECHO |  |  |  | 'hi'
8 | 7 | JMP |  |  |  | ->3
9 | 8 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
JMPZ_EX
MOD
Opcode Descriptions and Examples


MOD

PHP code

<?php
/*
 * Makes the value of "result" congruent to "value1" modulo "value2".
 * opcode number: 5
 */
echo 6 % 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | MOD |  |  | ~0 | 6,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

napora dot adam at gmail dot com 25-May-2012 04:22
Might be helpful:

I had to create and "INSERT INTO" on every 50th row:

<?php
$lineBreak = 50;
$tableName = 'user';
$tableFields = 'id, name, password';
?>

in the loop:

<?php
if ($counter === 0 || $counter % $lineBreak === 0) {
    echo "INSERT INTO $tableName ($tableFields) VALUES (";
} else {
    echo ' (';
}

// add values comma-delimited

if ($counter === 0 || $counter % $lineBreak === 0) {
    $insertStmt .= ');';
} else {
    $insertStmt .= '),';
}
?>

(in my case I had to check if $no % $o === 0)
shaunny at hotmail dot com 08-Jan-2010 06:35
A simple check to see if a number is divisible by another number,
i.e. if a number is even.

<?php
if ($counter % 2) {
echo "This number is not even.";
} else {
echo "This number is even.";
}
?>
JMPZNZ
MUL
Opcode Descriptions and Examples


MUL

PHP code

<?php
/*
 * Multiplys "value1" by "value2" and stores the result into "result".
 * opcode number: 3
 */
echo 2*3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | MUL |  |  | ~0 | 2,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
MOD
NEW
Opcode Descriptions and Examples


NEW

PHP code

<?php
/*
 * Construct an instance of "type" and store the reference to the object into "result".
 * opcode number: 68
 */
$obj = new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
MUL
NOP
Opcode Descriptions and Examples


NOP

PHP code

<?php
/*
 * no operation
 * opcode number: 0
 */
function A(){};
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: A

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
NEW
POST_DEC
Opcode Descriptions and Examples


POST_DEC

PHP code

<?php
/*
 * decrements variable indicated by value1 by 1 (after performing other operations) and stores in result
 * opcode number: 37
 */
$a--;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | POST_DEC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
NOP
POST_DEC_OBJ
Opcode Descriptions and Examples


POST_DEC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 135
 */
$obj = new A();
$obj->num--;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_POST_DEC_OBJ |  |  | ~5 | !0,'num'
 | 5 | FREE |  |  |  | ~5
8 | 6 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
POST_DEC
POST_INC
Opcode Descriptions and Examples


POST_INC

PHP code

<?php
/*
 * increments variable indicated by value1 by 1 (after performing other operations) and stores in result
 * opcode number: 36
 */
$a++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | POST_INC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
POST_DEC_OBJ
POST_INC_OBJ
Opcode Descriptions and Examples


POST_INC_OBJ

PHP code

<?php
/*
 * Increment the property value specified by prop-name and store the original value into result.
 * opcode number: 134
 */
$obj = new A();
$obj->num++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_POST_INC_OBJ |  |  | ~5 | !0,'num'
 | 5 | FREE |  |  |  | ~5
8 | 6 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
POST_INC
PRE_DEC
Opcode Descriptions and Examples


PRE_DEC

PHP code

<?php
/*
 * decrements variable indicated by value1 by 1 (before performing other operations) and stores in results
 * opcode number: 35
 */
--$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | PRE_DEC |  |  |  | !0
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
POST_INC_OBJ
PRE_DEC_OBJ
Opcode Descriptions and Examples


PRE_DEC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 133
 */
$obj = new A();
--$obj->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_PRE_DEC_OBJ |  |  |  | !0,'num'
8 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
PRE_DEC
PRE_INC
Opcode Descriptions and Examples


PRE_INC

PHP code

<?php
/*
 * increments variable indicated by value1 by 1 (before performing other operations) and stores in result
 * opcode number: 34
 */
++$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | PRE_INC |  |  |  | !0
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
PRE_DEC_OBJ
PRE_INC_OBJ
Opcode Descriptions and Examples


PRE_INC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 132
 */
$obj = new A();
++$obj->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_PRE_INC_OBJ |  |  |  | !0,'num'
8 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
PRE_INC
PRINT
Opcode Descriptions and Examples


PRINT

PHP code

<?php
/*
 *
 * opcode number: 41
 */
print "Hello World";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | PRINT |  |  | ~0 | 'Hello+World'
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
PRE_INC_OBJ
QM_ASSIGN
Opcode Descriptions and Examples


QM_ASSIGN

PHP code

<?php
/*
 * Question Mark Assign, used twice inside a question mark assign to temporarily assign result as value1  (this is followed up with an ASSIGN bytecode)
 * opcode number: 22
 */
function A(){
 echo 1?2:3;
}

function B(){
 $b = 0;
 $a = $b > 1 ? 10: 11;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | NOP |  |  |  |
14 | 2 | RETURN |  |  |  | 1

Function name: A

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | JMPZ |  |  |  | 1,->3
 | 1 | QM_ASSIGN |  |  | ~0 | 2
 | 2 | JMP |  |  |  | ->4
 | 3 | QM_ASSIGN |  |  | ~0 | 3
 | 4 | ECHO |  |  |  | ~0
8 | 5 | RETURN |  |  |  | null

Function name: B

Compiled variables: !0=$b, !1=$a

line | # | op | fetch | ext | return | operands
11 | 0 | ASSIGN |  |  |  | !0,0
12 | 1 | IS_SMALLER |  |  | ~1 | 1,!0
 | 2 | JMPZ |  |  |  | ~1,->5
 | 3 | QM_ASSIGN |  |  | ~2 | 10
 | 4 | JMP |  |  |  | ->6
 | 5 | QM_ASSIGN |  |  | ~2 | 11
 | 6 | ASSIGN |  |  |  | !1,~2
13 | 7 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
PRINT
RAISE_ABSTRACT_ERROR
Opcode Descriptions and Examples


RAISE_ABSTRACT_ERROR

PHP code

<?php
/*
 *
 * opcode number: 142
 */

abstract class fail {
    abstract function show();
}

class pass extends fail {
    function show() {
        echo "Call to function show()\n";
    }
}

$t2 = new pass();
$t2->show();

$t = new fail();
$t->show();

echo "Done\n"; // shouldn't be displayed
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$t2, !1=$t

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
11 | 1 | NOP |  |  |  |
 | 2 | NOP |  |  |  |
17 | 3 | ZEND_FETCH_CLASS |  |  | :3 | 'pass'
 | 4 | NEW |  |  | $4 | :3
 | 5 | DO_FCALL_BY_NAME |  | 0 |  |
 | 6 | ASSIGN |  |  |  | !0,$4
18 | 7 | ZEND_INIT_METHOD_CALL |  |  |  | !0,'show'
 | 8 | DO_FCALL_BY_NAME |  | 0 |  |
20 | 9 | ZEND_FETCH_CLASS |  |  | :9 | 'fail'
 | 10 | NEW |  |  | $10 | :9
 | 11 | DO_FCALL_BY_NAME |  | 0 |  |
 | 12 | ASSIGN |  |  |  | !1,$10
21 | 13 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'show'
 | 14 | DO_FCALL_BY_NAME |  | 0 |  |
23 | 15 | ECHO |  |  |  | 'Done%0A'
24 | 16 | RETURN |  |  |  | 1

Function name: show

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ZEND_RAISE_ABSTRACT_ERROR |  |  |  |
 | 1 | RETURN |  |  |  | null

Function name: show

Compiled variables: none

line | # | op | fetch | ext | return | operands
13 | 0 | ECHO |  |  |  | 'Call+to+function+show%28%29%0A'
14 | 1 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
QM_ASSIGN
RECV
Opcode Descriptions and Examples


RECV

PHP code

<?php
/*
 * Receive a functoin argument of "argument-number" and store the argument value into a variable of "argument-number".  (e.g. $1 for 1)
 * opcode number: 63
 */
function hello($a){}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: hello

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
 | 1 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
RAISE_ABSTRACT_ERROR
RECV_INIT
Opcode Descriptions and Examples


RECV_INIT

PHP code

<?php
/*
 * Initialize a function argument with "value" if not received from caller.  Otherwise same as RECV.
 * opcode number: 64
 */
function hello($a=5){}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: hello

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | RECV_INIT |  |  |  | 1,5
 | 1 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
RECV
RETURN
Opcode Descriptions and Examples


RETURN

PHP code

<?php
/*
 * Return value from a funciton.
 * opcode number: 62
 */
return 1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | 1
7 | 1 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
RECV_INIT
RETURN_BY_REF
Opcode Descriptions and Examples


RETURN_BY_REF

PHP code

<?php
/*
 *
 * opcode number: 111
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
RETURN
SEND_REF
Opcode Descriptions and Examples


SEND_REF

PHP code

<?php
/*
 * Pass the reference value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 67
 */
@each($input);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | FETCH_W | local |  | $1 | 'input'
 | 2 | SEND_REF |  |  |  | $1
 | 3 | DO_FCALL |  | 1 |  | 'each'
 | 4 | END_SILENCE |  |  |  | ~0
7 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
RETURN_BY_REF
SEND_VAL
Opcode Descriptions and Examples


SEND_VAL

PHP code

<?php
/*
 * Pass the constant value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 65
 */
function funcA($msg){
    print $msg;
}

funcA('HELLO');

defined('IN_PHPBB');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | SEND_VAL |  |  |  | 'HELLO'
 | 2 | DO_FCALL |  | 1 |  | 'funca'
12 | 3 | SEND_VAL |  |  |  | 'IN_PHPBB'
 | 4 | DO_FCALL |  | 1 |  | 'defined'
13 | 5 | RETURN |  |  |  | 1

Function name: funcA

Compiled variables: !0=$msg

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
7 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
8 | 3 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
SEND_REF
SEND_VAR
Opcode Descriptions and Examples


SEND_VAR

PHP code

<?php
/*
 * Pass the variable value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 66
 */
$a = array(1,2,3);
if(is_array($a)){ return 0; }
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'is_array'
 | 6 | JMPZ |  |  |  | $2,->9
 | 7 | RETURN |  |  |  | 0
 | 8 | JMP |  |  |  | ->9
8 | 9 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
SEND_VAL
SEND_VAR_NO_REF
Opcode Descriptions and Examples


SEND_VAR_NO_REF

PHP code

<?php
/*
 *
 * opcode number: 106
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
SEND_VAR
SL
Opcode Descriptions and Examples


SL

PHP code

<?php
/*
 * Shift value1 by balue2 bits to left
 * opcode number: 6
 */
echo 8 << 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SL |  |  | ~0 | 8,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
SEND_VAR_NO_REF
SR
Opcode Descriptions and Examples


SR

PHP code

<?php
/*
 * Shift bits to right
 * opcode number: 7
 */
echo 8 >> 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SR |  |  | ~0 | 8,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
SL
SUB
Opcode Descriptions and Examples


SUB

PHP code

<?php
/*
 * Subtracts "value2" from "value1" and stores the result into "result".
 * opcode number: 2
 */
echo 1-2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SUB |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
SR
SWITCH_FREE
Opcode Descriptions and Examples


SWITCH_FREE

PHP code

<?php
/*
 * Release the allocated space of "value"?
 * opcode number: 49
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
SUB
THROW
Opcode Descriptions and Examples


THROW

PHP code

<?php
/*
 *
 * opcode number: 108
 */
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$error, !1=$e

line | # | op | fetch | ext | return | operands
7 | 0 | ASSIGN |  |  |  | !0,'Always+throw+this+error'
8 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'Exception'
 | 2 | NEW |  |  | $2 | :1
 | 3 | SEND_VAR |  |  |  | !0
 | 4 | DO_FCALL_BY_NAME |  | 1 |  |
 | 5 | ZEND_THROW |  | 0 |  | $2
11 | 6 | ECHO |  |  |  | 'Never+executed'
13 | 7 | JMP |  |  |  | ->15
 | 8 | ZEND_FETCH_CLASS |  |  | :4 | 'Exception'
 | 9 | ZEND_CATCH |  | 15 |  | $4,!1
14 | 10 | ECHO |  |  |  | 'Caught+exception%3A+'
 | 11 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'getMessage'
 | 12 | DO_FCALL_BY_NAME |  | 0 |  |
 | 13 | ECHO |  |  |  | $6
 | 14 | ECHO |  |  |  | '%0A'
18 | 15 | ECHO |  |  |  | 'Hello+World'
19 | 16 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
SWITCH_FREE
TICKS
Opcode Descriptions and Examples


TICKS

PHP code

<?php
/*
 *
 * opcode number: 105
 */
// A function that records the time when it is called
function profile()
{
   echo "profile function is called\n";
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
   for ($x = 0; $x < 10; ++$x) {
         echo "hello world\n";
   }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
13 | 1 | SEND_VAL |  |  |  | 'profile'
 | 2 | DO_FCALL |  | 1 |  | 'register_tick_function'
16 | 3 | DO_FCALL |  | 0 |  | 'profile'
20 | 4 | ASSIGN |  |  |  | !0,0
 | 5 | IS_SMALLER |  |  | ~3 | !0,10
 | 6 | JMPZNZ |  | 9 |  | ~3,->13
 | 7 | PRE_INC |  |  |  | !0
 | 8 | JMP |  |  |  | ->5
21 | 9 | ECHO |  |  |  | 'hello+world%0A'
 | 10 | TICKS |  |  |  | 2
22 | 11 | TICKS |  |  |  | 2
 | 12 | JMP |  |  |  | ->7
 | 13 | TICKS |  |  |  | 2
23 | 14 | TICKS |  |  |  | 2
24 | 15 | RETURN |  |  |  | 1

Function name: profile

Compiled variables: none

line | # | op | fetch | ext | return | operands
9 | 0 | ECHO |  |  |  | 'profile+function+is+called%0A'
10 | 1 | RETURN |  |  |  | null

User Contributed Notes

There are no user contributed notes for this page.
THROW
UNSET_DIM
Opcode Descriptions and Examples


UNSET_DIM

PHP code

<?php
/*
 * Unset the entry of array-value, which is specified by index, and store the original element value into "result".
 * opcode number: 75
 */
$a = array(1,2,3);
unset($a[0]);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | UNSET_DIM |  |  | $2 | !0,0
8 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
TICKS
UNSET_OBJ
Opcode Descriptions and Examples


UNSET_OBJ

PHP code

<?php
/*
 * Unset the property of the current object (this) and store the original value into "result".
 * opcode number: 76
 */
$obj = new A();
unset($obj->num);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | UNSET_OBJ |  |  | $4 | !0,'num'
8 | 5 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
UNSET_DIM
UNSET_VAR
Opcode Descriptions and Examples


UNSET_VAR

PHP code

<?php
/*
 * Unset the variable and store the original value into "result".
 * opcode number: 74
 */
$x = 1;
$a='x';
unset($$a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | UNSET_VAR |  |  | $2 | !1
9 | 3 | RETURN |  |  |  | 1

User Contributed Notes

There are no user contributed notes for this page.
UNSET_OBJ
USER_OPCODE
Opcode Descriptions and Examples


USER_OPCODE

PHP code

<?php
/*
 *
 * opcode number: 150
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
UNSET_VAR
VERIFY_ABSTRACT_CLASS
Opcode Descriptions and Examples


VERIFY_ABSTRACT_CLASS

PHP code

<?php
/*
 *
 * opcode number: 146
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
USER_OPCODE
ZEND_DECLARE_LAMBDA_FUNCTION
Opcode Descriptions and Examples


ZEND_DECLARE_LAMBDA_FUNCTION

PHP code

<?php
/*
 *
 * opcode number: 153
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
VERIFY_ABSTRACT_CLASS
ZEND_JMP_SET
Opcode Descriptions and Examples


ZEND_JMP_SET

PHP code

<?php
/*
 *
 * opcode number: 152
 * No sample PHP yet */
?>

User Contributed Notes

There are no user contributed notes for this page.
ZEND_DECLARE_LAMBDA_FUNCTION
Zend Engine 1
Opcode Descriptions and Examples


Zend Engine 1

Содержание

  • Old introduction
  • Streams API for PHP Extension Authors
  • Zend API: Взламываем ядро PHP
  • TSRM API

Zend Engine 1 is the internal engine used by PHP for the entire version 4 release line. It is no longer considered active, but PHP 4 is still in widespread use, so the old ZE1 documentation is preserved here exactly as it was.

User Contributed Notes

There are no user contributed notes for this page.
ZEND_JMP_SET
Old introduction
Ядро PHP: Руководство хакера по Zend Engine


Old introduction

If you are about to begin developing PHP or Zend extensions, you need to prepare yourself for the programming environment provided by the various APIs. This part of the documentation tries to introduce the APIs provided by the different PHP and Zend Engine versions available. Since most of the information available here is somewhat outdated, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL in addition to the manual.

User Contributed Notes

There are no user contributed notes for this page.
Zend Engine 1
Streams API for PHP Extension Authors
Zend Engine 1


Streams API for PHP Extension Authors

Замечание:

The functions in this chapter are for use in the PHP source code and are not PHP functions. Information on userland stream functions can be found in the Stream Reference.

Overview

The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.

The aim of the Streams API is to make it comfortable for developers to open files, URLs and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.

The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs. An additional context parameter, accepted by most stream creation functions, is passed to the wrapper's stream_opener method to fine-tune the behavior of the wrapper.

Any stream, once opened, can also have any number of filters applied to it, which process data as it is read from/written to the stream.

Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the fopencookie() or funopen() function, you can even pass any PHP stream to any library that uses ANSI stdio!

Streams Basics

Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use php_stream_open_wrapper() to obtain the stream handle. This function works very much like fopen, as can be seen from the example below:

Пример #1 simple stream example that displays the PHP home page

php_stream * stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);
if (stream) {
    while(!php_stream_eof(stream)) {
        char buf[1024];

        if (php_stream_gets(stream, buf, sizeof(buf))) {
            printf(buf);
        } else {
            break;
        }
    }
    php_stream_close(stream);
}

The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical.

ANSI stdio equivalent functions in the Streams API
ANSI Stdio Function | PHP Streams Function | Notes
fopen | php_stream_open_wrapper | Streams includes additional parameters
fclose | php_stream_close |
fgets | php_stream_gets |
fread | php_stream_read | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)
fwrite | php_stream_write | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)
fseek | php_stream_seek |
ftell | php_stream_tell |
rewind | php_stream_rewind |
feof | php_stream_eof |
fgetc | php_stream_getc |
fputc | php_stream_putc |
fflush | php_stream_flush |
puts | php_stream_puts | Same semantics as puts, NOT fputs
fstat | php_stream_stat | Streams has a richer stat structure

Streams as Resources

All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible:

Пример #2 How to accept a stream as a parameter

PHP_FUNCTION(example_write_hello)
{
    zval *zstream;
    php_stream *stream;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream))
        return;

    php_stream_from_zval(stream, &zstream);

    /* you can now use the stream.  However, you do not "own" the
        stream, the script does.  That means you MUST NOT close the
        stream, because it will cause PHP to crash! */

    php_stream_write(stream, "hello\n");

    RETURN_TRUE();
}

Пример #3 How to return a stream from a function

PHP_FUNCTION(example_open_php_home_page)
{
    php_stream *stream;

    stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);

    php_stream_to_zval(stream, return_value);

    /* after this point, the stream is "owned" by the script.
        If you close it now, you will crash PHP! */
}

Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log.

Замечание: Always use a debug build of PHP when developing an extension (--enable-debug when running configure), as a lot of effort has been made to warn you about memory and stream leaks.

In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the trouble of writing the code, you can mark a stream as being OK for auto cleanup. What this means is that the streams API will not emit a warning when it is time to auto-cleanup a stream. To do this, you can use php_stream_auto_cleanup().

Streams open options

These constants affect the operation of stream factory functions.

IGNORE_PATH
This is the default option for streams; it requests that the include_path is not to be searched for the requested file.
USE_PATH
Requests that the include_path is to be searched for the requested file.
IGNORE_URL
Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.
IGNORE_URL_WIN
On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.
ENFORCE_SAFE_MODE
Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.
REPORT_ERRORS
If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.
STREAM_MUST_SEEK
This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.

Замечание: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.

STREAM_WILL_CAST
If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires. The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream. Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.

User Contributed Notes

armand at nl dot envida dot net 11-Sep-2003 02:05
To have your extension ignore the open_basedir restrictions that may be set, use
  STREAM_DISABLE_OPENBASEDIR

I'm not sure why this option is left out of the documentation,
there are valid and legit uses for this option.
Old introduction
Zend API: Взламываем ядро PHP
Zend Engine 1


Zend API: Взламываем ядро PHP

Introduction

Those who know don't talk.

Those who talk don't know.

Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.

As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.

Внимание

This information is currently rather outdated, parts of it only cover early stages of the ZendEngine 1.0 API as it was used in early versions of PHP 4.

More recent information may be found in the various README files that come with the PHP source and the » Internals section on the Zend website.

Overview

"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.

Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.

What Is Zend? and What Is PHP?

The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated ( see below). To implement a Web script interpreter, you need three parts:

  1. The interpreter part analyzes the input code, translates it, and executes it.

  2. The functionality part implements the functionality of the language (its functions, etc.).

  3. The interface part talks to the Web server, etc.

Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the complete PHP package. Zend itself really forms only the language core, implementing PHP at its very basics with some predefined functions. PHP contains all the modules that actually create the language's outstanding capabilities.
The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.

Extension Possibilities

As shown above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.

External Modules

External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow.
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk.
 |  | Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution).
To sum up, external modules are great for third-party products, small additions to PHP that are rarely used, or just for testing purposes. To develop additional functionality quickly, external modules provide the best results. For frequent usage, larger implementations, and complex code, the disadvantages outweigh the advantages.

Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.

Built-in Modules

Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
No need to load the module specifically; the functionality is instantly available. | Changes to built-in modules require recompiling of PHP.
No external files clutter up the disk; everything resides in the PHP binary. | The PHP binary grows and consumes more memory.
Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.

The Zend Engine

Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.

Source Layout

Замечание:

Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at » http://httpd.apache.org/) and, of course, with PHP (available at » http://www.php.net/ - does it need to be said?).

Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.

Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.

The following table describes the contents of the major directories.

Directory | Contents
php-src | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory.
php-src/ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it).
php-src/main | This directory contains the main php macros and definitions. (important)
php-src/pear | Directory for the PHP Extension and Application Repository. This directory contains core PEAR files.
php-src/sapi | Contains the code for the different server abstraction layers.
TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
ZendEngine2 | Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important).

Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:

  • php-src/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • php-src/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • php-src/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.

You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend executor, the PHP initialization file support, and such. After reading these files, take the time to navigate around the package a little to see the interdependencies of all files and modules - how they relate to each other and especially how they make use of each other. This also helps you to adapt to the coding style in which PHP is authored. To extend PHP, you should quickly adapt to this style.

Extension Conventions

Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.

Macros

For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)

Memory Management

Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:

Function | Description
emalloc() | Serves as replacement for malloc().
efree() | Serves as replacement for free().
estrdup() | Serves as replacement for strdup().
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.
ecalloc() | Serves as replacement for calloc().
erealloc() | Serves as replacement for realloc().
emalloc(), estrdup(), estrndup(), ecalloc(), and erealloc() allocate internal memory; efree() frees these previously allocated blocks. Memory handled by the e*() functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated.
Внимание

To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks.

Zend also features a thread-safe resource manager to provide better native support for multithreaded Web servers. This requires you to allocate local structures for all of your global variables to allow concurrent threads to be run. Because the thread-safe mode of Zend was not finished back when this was written, it is not yet extensively covered here.

Directory and File Functions

The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.

Zend Function | Regular C Function
V_GETCWD() | getcwd()
V_FOPEN() | fopen()
V_OPEN() | open()
V_CHDIR() | chdir()
V_GETWD() | getwd()
V_CHDIR_FILE() | Takes a file path as an argument and changes the current working directory to that file's directory.
V_STAT() | stat()
V_LSTAT() | lstat()

String Handling

Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)

Complex Types

Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.

Замечание:

To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.

PHP's Automatic Build System

PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see » http://www.gnu.org/software/m4/)

All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.

Step by step, the process looks like this:

:~/cvs/php4/ext:> ./ext_skel --extname=my_module
Creating directory my_module
Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/my_module/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-my_module
5.  $ make
6.  $ ./php -f ext/my_module/my_module.php
7.  $ vi ext/my_module/my_module.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run buildconf, which regenerates the configure script by searching through the ext directory and including all found config.m4 files.

The default config.m4 shown in The default config.m4. is a bit more complex:

Пример #1 The default config.m4.

dnl $Id: build.xml 297078 2010-03-29 16:25:51Z degeberg $
dnl config.m4 for extension my_module

dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.

dnl If your extension references something external, use with:

dnl PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
dnl [  --with-my_module             Include my_module support])

dnl Otherwise use enable:

dnl PHP_ARG_ENABLE(my_module, whether to enable my_module support,
dnl Make sure that the comment is aligned:
dnl [  --enable-my_module           Enable my_module support])

if test "$PHP_MY_MODULE" != "no"; then
  dnl Write more examples of tests here...

  dnl # --with-my_module -> check with-path
  dnl SEARCH_PATH="/usr/local /usr"     # you might want to change this
  dnl SEARCH_FOR="/include/my_module.h"  # you most likely want to change this
  dnl if test -r $PHP_MY_MODULE/; then # path given as parameter
  dnl   MY_MODULE_DIR=$PHP_MY_MODULE
  dnl else # search default path list
  dnl   AC_MSG_CHECKING([for my_module files in default path])
  dnl   for i in $SEARCH_PATH ; do
  dnl     if test -r $i/$SEARCH_FOR; then
  dnl       MY_MODULE_DIR=$i
  dnl       AC_MSG_RESULT(found in $i)
  dnl     fi
  dnl   done
  dnl fi
  dnl
  dnl if test -z "$MY_MODULE_DIR"; then
  dnl   AC_MSG_RESULT([not found])
  dnl   AC_MSG_ERROR([Please reinstall the my_module distribution])
  dnl fi

  dnl # --with-my_module -> add include path
  dnl PHP_ADD_INCLUDE($MY_MODULE_DIR/include)

  dnl # --with-my_module -> chech for lib and symbol presence
  dnl LIBNAME=my_module # you may want to change this
  dnl LIBSYMBOL=my_module # you most likely want to change this

  dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
  dnl [
  dnl   PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MY_MODULE_DIR/lib, MY_MODULE_SHARED_LIBADD)
  dnl   AC_DEFINE(HAVE_MY_MODULELIB,1,[ ])
  dnl ],[
  dnl   AC_MSG_ERROR([wrong my_module lib version or lib not found])
  dnl ],[
  dnl   -L$MY_MODULE_DIR/lib -lm -ldl
  dnl ])
  dnl
  dnl PHP_SUBST(MY_MODULE_SHARED_LIBADD)

  PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared)
fi

If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.

Note: Everything prefixed with dnl is treated as a comment and is not parsed.

The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.

The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.

By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":

if test "$PHP_MY_MODULE" == "yes"; then dnl
    Action.. PHP_EXTENSION(my_module, $ext_shared)
    fi
This would require you to use --enable-my_module each time when reconfiguring and recompiling PHP.

Note: Be sure to run buildconf every time you change config.m4!

We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files.

Creating Extensions

We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. A simple extension. shows the source.

Пример #2 A simple extension.

/* include standard header */
#include "php.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what's in this module */
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}

This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)

Замечание:

The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.

Compiling Modules

There are basically two ways to compile modules:

  • Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.

  • Compile the sources manually.

The first method should definitely be favored, since, as of PHP 4.0, this has been standardized into a sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it's hard to understand at first. We'll provide a more detailed introduction to this later in the chapter, but first let's work with the default files.

The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.

Compiling Using Make

To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.

After you run buildconf, configure --help shows the following additional modules:

  --enable-array_experiments   BOOK: Enables array experiments
  --enable-call_userland       BOOK: Enables userland module
  --enable-cross_conversion    BOOK: Enables cross-conversion module
  --enable-first_module        BOOK: Enables first module
  --enable-infoprint           BOOK: Enables infoprint module
  --enable-reference_test      BOOK: Enables reference test module
  --enable-resource_test       BOOK: Enables resource test module
  --enable-variable_creation   BOOK: Enables variable-creation module

The module shown earlier in A simple extension. can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually

To compile your modules manually, you need the following commands:

Action | Command
Compiling | cc -fpic -DCOMPILE_DL_FIRST_MODULE=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Linking | cc -shared -L/usr/local/lib -rdynamic -o <your_module_file> <your_object_file(s)>
The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL_FIRST_MODULE to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.

Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.

The link command is also a plain vanilla command instructing linkage as a dynamic module.

You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).

Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)

Using Extensions

Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in A test file for first_module.so.. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

Внимание

For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments.

Пример #3 A test file for first_module.so.

<?php

// remove next comment if necessary
// dl("first_module.so");

$param = 2;
$return = first_module($param);

print("We sent '$param' and got '$return'");

?>

Calling this PHP file should output the following:

We sent '2' and got '2'

If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.

If you've gotten this far, congratulations! You just built your first extension to PHP.

Troubleshooting

Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation.

PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.

Source Discussion

Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.

Module Structure

All PHP modules follow a common structure:

  • Header file inclusions (to include all required macros, API definitions, etc.)

  • C declaration of exported functions (required to declare the Zend function block)

  • Declaration of the Zend function block

  • Declaration of the Zend module block

  • Implementation of get_module()

  • Implementation of all exported functions

Header File Inclusions

The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.

Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.

Declaring Exported Functions

To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:

ZEND_FUNCTION ( my_function );

ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:

void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );
Expanding INTERNAL_FUNCTION_PARAMETERS results in the following:
void zif_my_function( int ht
                    , zval * return_value
                    , zval * this_ptr
                    , int return_value_used
                    , zend_executor_globals * executor_globals
                    );

Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.

The parameter list of this declaration is very important; you should keep these parameters in mind (see Zend's Parameters to Functions Called from PHP for descriptions).

Zend's Parameters to Functions Called from PHP
Parameter | Description
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value.
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below.
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer.
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this).
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro TSRMLS_FETCH().

Declaration of the Zend Function Block

Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Internal declaration of zend_function_entry..

Пример #4 Internal declaration of zend_function_entry.

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;
Entry | Description
fname | Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module).
handler | Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier.
func_arg_types | Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL.
In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};
You can see that the last entry in the list always has to be {NULL, NULL, NULL}. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

Замечание:

You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!

The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.

Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.

Macros for Defining Functions shows a list of all the macros that you can use to define functions.

Macros for Defining Functions
Macro Name | Description
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION.
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION.
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead.
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE.

Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.

Declaration of the Zend Module Block

This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Internal declaration of zend_module_entry..

Пример #5 Internal declaration of zend_module_entry.

typedef struct _zend_module_entry zend_module_entry;

    struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    char *name;
    zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    char *version;

[ Rest of the structure is not interesting here ]

};
Entry | Description
size, zend_api, zend_debug and zts | Usually filled with the "STANDARD_MODULE_HEADER", which fills these four members with the size of the whole zend_module_entry, the ZEND_MODULE_API_NO, whether it is a debug build or normal build (ZEND_DEBUG) and if ZTS is enabled (USING_ZTS).
name | Contains the module name (for example, "File functions", "Socket functions", "Crypt", etc.). This name will show up in phpinfo(), in the section "Additional Modules."
functions | Points to the Zend function block, discussed in the preceding section.
module_startup_func | This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINIT.
module_shutdown_func | This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to module_startup_func(). To indicate a failure during deinitialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MSHUTDOWN.
request_startup_func | This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RINIT.
request_shutdown_func | This function is called once after every page request and works as counterpart to request_startup_func(). To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RSHUTDOWN.
info_func | When phpinfo() is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINFO.
version | The version of the module. You can use NO_VERSION_YET if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): "2.5-dev", "2.5RC1", "2.5" or "2.5pl3".
Remaining structure elements | These are used internally and can be prefilled by using the macro STANDARD_MODULE_PROPERTIES_EX. You should not assign any values to them. Use STANDARD_MODULE_PROPERTIES_EX only if you use global startup and shutdown functions; otherwise, use STANDARD_MODULE_PROPERTIES directly.

In our example, this structure is implemented as follows:

zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES,
};
This is basically the easiest and most minimal set of values you could ever use. The module name is set to First Module, then the function list is referenced, after which all startup and shutdown functions are marked as being unused.

For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Macros to Declare Startup and Shutdown Functions. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.

Macros to Declare Startup and Shutdown Functions
Macro | Description
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION.
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION.
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION.
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION.
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION.

Creation of get_module()

This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:

#if COMPILE_DL_FIRSTMOD
     ZEND_GET_MODULE(firstmod)
#endif

The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.

get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.

If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.

Implementation of All Exported Functions

Implementing the exported functions is the final step. The example function in first_module looks like this:

ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}
The function declaration is done using ZEND_FUNCTION, which corresponds to ZEND_FE in the function entry table (discussed earlier).

After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).

Summary

That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.

Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.

Accepting Arguments

One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.

PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.

Determining the Number of Arguments

Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.

The following code checks for the correct number of arguments:

if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;
If the function is not called with two arguments, it exits with an error message. The code snippet above makes use of the tool macro WRONG_PARAM_COUNT, which can be used to generate a standard error message like:
"Warning: Wrong parameter count for firstmodule() in /home/www/htdocs/firstmod.php on line 5"

This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:

ZEND_API void wrong_param_count(void);

#define WRONG_PARAM_COUNT { wrong_param_count(); return; }
As you can see, it calls an internal function named wrong_param_count() that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information."

Retrieving Arguments

Замечание: New parameter parsing API

This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0.

Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameters, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.

The prototype for parameter parsing function looks like this:

int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
The first argument to this function is supposed to be the number of actual parameters passed to your function, so ZEND_NUM_ARGS() can be used for that. The second parameter should always be TSRMLS_CC macro. The third argument is a string that specifies the number and types of arguments your function is expecting, similar to how printf format string specifies the number and format of the output values it should operate on. And finally the rest of the arguments are pointers to variables which should receive the values from the parameters.

zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.

If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.

Here are some sample error messages:

Warning - ini_get_all() requires at most 1 parameter, 2 given
Warning - wddx_deserialize() expects parameter 1 to be string, array given
Of course each error message is accompanied by the filename and line number on which it occurs.

Here is the full list of type specifiers:

  • l - long

  • d - double

  • s - string (with possible null bytes) and its length

  • b - boolean

  • r - resource, stored in zval*

  • a - array, stored in zval*

  • o - object (of any class), stored in zval*

  • O - object (of class specified by class entry), stored in zval*

  • z - the actual zval*

The following characters also have a meaning in the specifier string:

  • | - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.

  • / - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.

  • ! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.

The best way to illustrate the usage of this function is through examples:

/* Gets a long, a string and its length, and a zval. */
long l;
char *s;
int s_len;
zval *param;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "lsz", &l, &s, &s_len, &param) == FAILURE) {
    return;
}

/* Gets an object of class specified by my_ce, and an optional double. */
zval *obj;
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "O|d", &obj, my_ce, &d) == FAILURE) {
    return;
}

/* Gets an object or null, and an array.
   If null is passed for object, obj will be set to NULL. */
zval *obj;
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) {
    return;
}

/* Gets a separated array. */
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) {
    return;
}

/* Get only the first three parameters (useful for varargs functions). */
zval *z;
zend_bool b;
zval *r;
if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) {
    return;
}

Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.

The parsing function has an extended version that allows for an additional flags argument that controls its actions.

int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);

The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.

For example, here is how you would get either a set of three longs or a string:

long l1, l2, l3;
char *s;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                             ZEND_NUM_ARGS() TSRMLS_CC,
                             "lll", &l1, &l2, &l3) == SUCCESS) {
    /* manipulate longs */
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                                    ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) {
    /* manipulate string */
} else {
    php_error(E_WARNING, "%s() takes either three long values or a string as argument",
              get_active_function_name(TSRMLS_C));
    return;
}

With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.

Old way of retrieving arguments (deprecated)

Замечание: Deprecated parameter parsing API

This API is deprecated and superseded by the new ZEND parameter parsing API.

After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():

zval **parameter;

if(zend_get_parameters_ex(1, &parameter) != SUCCESS)
  WRONG_PARAM_COUNT;
All arguments are stored in a zval container, which needs to be pointed to twice. The snippet above tries to retrieve one argument and make it available to us via the parameter pointer.

zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.

The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.

To retrieve more than one argument, you can use a similar snippet:

zval **param1, **param2, **param3, **param4;

if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)
    WRONG_PARAM_COUNT;

zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.

Dealing with a Variable Number of Arguments/Optional Parameters

If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.

For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:

zval **parameter_array[4];

/* get the number of arguments */
argument_count = ZEND_NUM_ARGS();

/* see if it satisfies our minimal request (2 arguments) */
/* and our maximal acceptance (4 arguments) */
if(argument_count < 2 || argument_count > 4)
    WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */
if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
    WRONG_PARAM_COUNT;
First, the number of arguments is checked to make sure that it's in the accepted range. After that, zend_get_parameters_array_ex() is used to fill parameter_array with valid pointers to the argument values.

A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in PHP's implementation of variable arguments in fsockopen().. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

Пример #6 PHP's implementation of variable arguments in fsockopen().

pval **args[5];
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
FLS_FETCH();

if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) {
    CLOSE_SOCK(1);
    WRONG_PARAM_COUNT;
}

switch(arg_count) {
    case 5:
        convert_to_double_ex(args[4]);
        conv = (unsigned long) (Z_DVAL_PP(args[4]) * 1000000.0);
        timeout.tv_sec = conv / 1000000;
        timeout.tv_usec = conv % 1000000;
        /* fall-through */
    case 4:
        if (!PZVAL_IS_REF(*args[3])) {
            php_error(E_WARNING,"error string argument to fsockopen not passed by reference");
        }
        pval_copy_constructor(*args[3]);
        ZVAL_EMPTY_STRING(*args[3]);
        /* fall-through */
    case 3:
        if (!PZVAL_IS_REF(*args[2])) {
            php_error(E_WARNING,"error argument to fsockopen not passed by reference");
            return;
        }
        ZVAL_LONG(*args[2], 0);
        break;
}

convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_P(args[1]);

key = emalloc(Z_STRLEN_P(args[0]) + 10);

fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.

This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.

Accessing Arguments

To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.

To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Argument Conversion Functions).

Note: All conversion functions expect a **zval as parameter.

Argument Conversion Functions
Function | Description
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE).
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise.
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise.
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object".
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0.
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content.
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty.

Замечание:

You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM.

Cross-conversion behavior of PHP.

Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.

Following is a quote from the sample module discussed previously, which makes use of the conversion functions:

zval **parameter;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

convert_to_long_ex(parameter);

RETURN_LONG(Z_LVAL_P(parameter));
After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also forms the return value of this function. Understanding access to the contents of the value requires a short discussion of the zval type, whose definition is shown in PHP/Zend zval type definition..

Пример #7 PHP/Zend zval type definition.

typedef pval zval;

typedef struct _zval_struct zval;

typedef union _zvalue_value {
    long lval;                 /* long value */
    double dval;               /* double value */
    struct {
        char *val;
        int len;
    } str;
    HashTable *ht;             /* hash table value */
    struct {
        zend_class_entry *ce;
        HashTable *properties;
    } obj;
} zvalue_value;

struct _zval_struct {
    /* Variable information */
    zvalue_value value;        /* value */
    unsigned char type;        /* active type */
    unsigned char is_ref;
    short refcount;
};

Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Zend zval Structure, Zend zvalue_value Structure and Zend Variable Type Constants.

Zend zval Structure
Entry | Description
value | Union containing this variable's contents. See Zend zvalue_value Structure for a description.
type | Contains this variable's type. For a list of available types, see Zend Variable Type Constants.
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value.
Zend zvalue_value Structure
Entry | Description
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dval | Use this property if the variable is of the type IS_DOUBLE.
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00.
ht | This entry points to the variable's hash table entry if the variable is an array.
obj | Use this property if the variable is of the type IS_OBJECT.
Zend Variable Type Constants
Constant | Description
IS_NULL | Denotes a NULL (empty) value.
IS_LONG | A long (integer) value.
IS_DOUBLE | A double (floating point) value.
IS_STRING | A string.
IS_ARRAY | Denotes an array.
IS_OBJECT | An object.
IS_BOOL | A Boolean value.
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANT | A constant (defined) value.

To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.

Accessing arrays and objects is a bit more complicated and is discussed later.

Dealing with Arguments Passed by Reference

If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.

What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!

We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.

Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).

zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.

This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.

To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:

my_function(&$parameter);

But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.

This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Testing for referenced parameter passing..

Пример #8 Testing for referenced parameter passing.

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
    return;

/* check for parameter being passed by reference */
if (!PZVAL_IS_REF(parameter)) {
{
    zend_error(E_WARNING, "Parameter wasn't passed by reference");
    RETURN_NULL();
}

/* make changes to the parameter */
ZVAL_LONG(parameter, 10);
Testing for referenced parameter passing

Assuring Write Safety for Other Parameters

You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:

zval **parameter;

/* retrieve parameter */
zend_get_parameters_ex(1, &parameter);

/* at this stage, <parameter> still is connected */
/* to Zend's internal data buffers */

/* make <parameter> write-safe */
SEPARATE_ZVAL(parameter);

/* now we can safely modify <parameter> */
/* without implying global changes */
SEPARATE_ZVAL uses emalloc() to allocate the new zval container, which means that even if you don't deallocate this memory yourself, it will be destroyed automatically upon script termination. However, doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM.

Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.

Creating Variables

When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.

Overview

To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable);

/* the variable is now accessible to the script by using $new_variable_name */

The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.

ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.

Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.

If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
zend_hash_update(
    EG(active_symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
This is actually the standard method used in most modules.

The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);
The macro ZEND_SET_SYMBOL is now being called with a reference to the main, global symbol table by referring EG(symbol_table).

Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.

Similarly, to get a more efficient version, you can hardcode the symbol table update:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
zend_hash_update(
    &EG(symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
Creating variables with different scopes. shows a sample source that creates two variables - local_variable with a local scope and global_variable with a global scope (see Figure 9.7). The full example can be found on the CD-ROM.

Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.

Пример #9 Creating variables with different scopes.

ZEND_FUNCTION(variable_creation)
{
    zval *new_var1, *new_var2;

    MAKE_STD_ZVAL(new_var1);
    MAKE_STD_ZVAL(new_var2);

    ZVAL_LONG(new_var1, 10);
    ZVAL_LONG(new_var2, 5);

    ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1);
    ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2);

    RETURN_NULL();

}
Creating variables with different scopes

Longs (Integers)

Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Creation of a long.).

Пример #10 Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long-&gt;type = IS_LONG;
new_long-&gt;value.lval = 10;
Alternatively, you can use the macro ZVAL_LONG:
zval *new_long;

MAKE_STD_ZVAL(new_long);
ZVAL_LONG(new_long, 10);

Doubles (Floats)

Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.

zval *new_double;

MAKE_STD_ZVAL(new_double);

new_double-&gt;type = IS_DOUBLE;
new_double-&gt;value.dval = 3.45;
Alternatively, you can use the macro ZVAL_DOUBLE:
zval *new_double;

MAKE_STD_ZVAL(new_double);
ZVAL_DOUBLE(new_double, 3.45);

Strings

Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:

zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);

new_string-&gt;type = IS_STRING;
new_string-&gt;value.str.len = strlen(string_contents);
new_string-&gt;value.str.val = estrdup(string_contents);
Note the usage of Zend's estrdup() here. Of course, you can also use the predefined macro ZVAL_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);
ZVAL_STRING(new_string, string_contents, 1);
ZVAL_STRING accepts a third parameter that indicates whether the supplied string contents should be duplicated (using estrdup()). Setting this parameter to 1 causes the string to be duplicated; 0 simply uses the supplied pointer for the variable contents. This is most useful if you want to create a new variable referring to a string that's already allocated in Zend internal memory.

If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.

To create empty strings, set the string length to 0 and use empty_string as contents:

new_string-&gt;type = IS_STRING;
new_string-&gt;value.str.len = 0;
new_string-&gt;value.str.val = empty_string;
Of course, there's a macro for this as well (ZVAL_EMPTY_STRING):
MAKE_STD_ZVAL(new_string);
ZVAL_EMPTY_STRING(new_string);

Booleans

Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:

zval *new_bool;

MAKE_STD_ZVAL(new_bool);

new_bool-&gt;type = IS_BOOL;
new_bool-&gt;value.lval = 1;
The corresponding macros for this type are ZVAL_BOOL (allowing specification of the value) as well as ZVAL_TRUE and ZVAL_FALSE (which explicitly set the value to TRUE and FALSE, respectively).

Arrays

Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.

There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().

zval *new_array;

MAKE_STD_ZVAL(new_array);

array_init(new_array);
array_init() always returns SUCCESS.

To add new elements to the array, you can use numerous functions, depending on what you want to do. Zend's API for Associative Arrays, Zend's API for Indexed Arrays, Part 1 and Zend's API for Indexed Arrays, Part 2 describe these functions. All functions return FAILURE on failure and SUCCESS on success.

Zend's API for Associative Arrays
Function | Description
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long.
add_assoc_unset(zval *array, char *key);() | Adds an unset element.
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element.
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array.
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value.
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string().
add_assoc_zval(zval *array, char *key, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...
Zend's API for Indexed Arrays, Part 1
Function | Description
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long.
add_index_unset(zval *array, uint idx);() | Adds an unset element.
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element.
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array.
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value.
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_index_zval(zval *array, uint idx, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...
Zend's API for Indexed Arrays, Part 2
Function | Description
add_next_index_long(zval *array, long n);() | Adds an element of type long.
add_next_index_unset(zval *array);() | Adds an unset element.
add_next_index_bool(zval *array, int b);() | Adds a Boolean element.
add_next_index_resource(zval *array, int r);() | Adds a resource to the array.
add_next_index_double(zval *array, double d);() | Adds a floating-point value.
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_next_index_zval(zval *array, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update() for associative arrays (see Adding an element to an associative array.) and zend_hash_index_update() for indexed arrays (see Adding an element to an indexed array.):

Пример #11 Adding an element to an associative array.

zval *new_array, *new_element;
char *key = "element_key";

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_update(new_array-&gt;value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

Пример #12 Adding an element to an indexed array.

zval *new_array, *new_element;
int key = 2;

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_index_update(new_array-&gt;value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

To emulate the functionality of add_next_index_*(), you can use this:

zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)

Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.

Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.

Objects

Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.

To initialize an object, you use the function object_init():

zval *new_object;

MAKE_STD_ZVAL(new_object);

if(object_init(new_object) != SUCCESS)
{
    // do error handling here
}
You can use the functions described in Zend's API for Object Creation to add members to your object.

Zend's API for Object Creation
Function | Description
add_property_long(zval *object, char *key, long l);() | Adds a long to the object.
add_property_unset(zval *object, char *key);() | Adds an unset property to the object.
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object.
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object.
add_property_double(zval *object, char *key, double d);() | Adds a double to the object.
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object.
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe.
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects.

Resources

Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.

For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.

Замечание:

In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.

To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.

The Zend function to register your resource handler is defined as:

ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number);

There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.

zend_register_list_destructors_ex() accepts the following parameters:

ld | Normal resource destruction handler callback
pld | Pesistent resource destruction handler callback
type_name | A string specifying the name of your resource. It's always a good thing to specify a unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource.
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.
The return value is a unique integer ID for your resource type.

The resource destruction handler (either normal or persistent resources) has the following prototype:

void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);
The passed rsrc is a pointer to the following structure:
typedef struct _zend_rsrc_list_entry {

    void *ptr;
    int type;
    int refcount;

} zend_rsrc_list_entry;
The member void *ptr is the actual pointer to your resource.

Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:

typedef struct {

    int resource_link;
    int resource_type;

} my_resource;
Our resource destruction handler is probably going to look something like this:
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

    // You most likely cast the void pointer to your structure type

    my_resource *my_rsrc = (my_resource *) rsrc->ptr;

    // Now do whatever needs to be done with you resource. Closing
    // Files, Sockets, freeing additional memory, etc.
    // Also, don't forget to actually free the memory for your resource too!

    do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}

Замечание:

One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!

Now that we have defined

  1. what our resource is and

  2. our resource destruction handler

we can go on and do the rest of the steps:

  1. create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it

  2. define the resource name

  3. write the resource destruction handler

  4. and finally register the handler

// Somewhere in your extension, define the variable for your registered resources.
    // If you wondered what 'le' stands for: it simply means 'list entry'.
    static int le_myresource;

    // It's nice to define your resource name somewhere
    #define le_myresource_name  "My type of resource"

    [...]

    // Now actually define our resource destruction handler
    void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

        my_resource *my_rsrc = (my_resource *) rsrc->ptr;
        do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
    }

    [...]

    PHP_MINIT_FUNCTION(my_extension) {

        // Note that 'module_number' is already provided through the
        // PHP_MINIT_FUNCTION() function definition.

        le_myresource = zend_register_list_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number);

        // You can register additional resources, initialize
        // your global vars, constants, whatever.
    }

To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h. Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:

int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);
rsrc_result | This is an already initialized zval * container.
rsrc_pointer | Your resource pointer you want to store.
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource.
The return value is a unique integer identifier for that resource.

What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:

rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type);

    if (rsrc_result) {
        rsrc_result->value.lval = rsrc_id;
        rsrc_result->type = IS_RESOURCE;
    }

    return rsrc_id;
The returned rsrc_id uniquely identifies the newly registered resource. You can use the macro RETURN_RESOURE to return it to the user:
    RETURN_RESOURCE(rsrc_id)

Замечание:

It is common practice that if you want to return the resource immediately to the user you specify the return_value as the zval * container.

Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.

Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:

ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type)
rsrc | This is your pointer which will point to your previously registered resource.
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *.
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given.
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message.
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource.
This macro has no return value. It is for the developers convenience and takes care of TSRMLS arguments passing and also does check if the resource could be fetched. It throws a warning message and returns the current PHP function with NULL if there was a problem retrieving the resource.

To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.

Macros for Automatic Global Variable Creation

In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table Macros for Global Variable Creation describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

Macros for Global Variable Creation
Macro | Description
SET_VAR_STRING(name, value) | Creates a new string.
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe.
SET_VAR_LONG(name, value) | Creates a new long.
SET_VAR_DOUBLE(name, value) | Creates a new double.

Creating Constants

Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.

To create your own constants, you can use the macros in Macros for Creating Constants. All the macros create a constant with the specified name and value.

You can also specify flags for each constant:

  • CONST_CS - This constant's name is to be treated as case sensitive.

  • CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.

To use the flags, combine them using a inary OR:
 // register a new constant of type "long"
     REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS |
     CONST_PERSISTENT);
There are two types of macros - REGISTER_*_CONSTANT andREGISTER_MAIN_*_CONSTANT. The first type creates constants bound to the current module. These constants are dumped from the symbol table as soon as the module that registered the constant is unloaded from memory. The second type creates constants that remain in the symbol table independently of the module.

Macros for Creating Constants
Macro | Description
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long.
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double.
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory.
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory.

Duplicating Variable Contents: The Copy Constructor

Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).

To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side).

Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).

This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.

Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).

A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
   return;
}

// do modifications to the parameter here

// now we want to return the modified container:
*return_value = *parameter;
zval_copy_ctor(return_value);

The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.

If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.

The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.

Returning Values

Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.

To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Predefined Macros for Returning Values from a Function and Predefined Macros for Setting the Return Value of a Function.

Замечание:

The macros in Predefined Macros for Returning Values from a Function automatically return from your function, those in Predefined Macros for Setting the Return Value of a Function only set the return value; they don't return from your function.

Predefined Macros for Returning Values from a Function
Macro | Description
RETURN_RESOURCE(resource) | Returns a resource.
RETURN_BOOL(bool) | Returns a Boolean.
RETURN_NULL() | Returns nothing (a NULL value).
RETURN_LONG(long) | Returns a long.
RETURN_DOUBLE(double) | Returns a double.
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup().
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however.
RETURN_EMPTY_STRING() | Returns an empty string.
RETURN_FALSE | Returns Boolean false.
RETURN_TRUE | Returns Boolean true.
Predefined Macros for Setting the Return Value of a Function
Macro | Description
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource.
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value.
RETVAL_NULL | Sets the return value to NULL.
RETVAL_LONG(long) | Sets the return value to the specified long.
RETVAL_DOUBLE(double) | Sets the return value to the specified double.
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING).
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known.
RETVAL_EMPTY_STRING | Sets the return value to an empty string.
RETVAL_FALSE | Sets the return value to Boolean false.
RETVAL_TRUE | Sets the return value to Boolean true.

Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.

Printing Information

Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.

zend_printf()

zend_printf() works like the standard printf(), except that it prints to Zend's output stream.

zend_error()

zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.

zend_error(E_WARNING, "This function has been called with empty arguments");
Zend's Predefined Error Messages. shows a list of possible values (see below). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.
Zend's Predefined Error Messages.
Error | Description
E_ERROR | Signals an error and terminates execution of the script immediately.
E_WARNING | Signals a generic warning. Execution continues.
E_PARSE | Signals a parser error. Execution continues.
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini.
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules.
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules.
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules.
Display of warning messages in the browser.

Including Output in phpinfo()

After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().

PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.

Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Source code and screenshot for output in phpinfo. shows a source example and its output. To print the table footer, use php_info_print_table_end().

Пример #13 Source code and screenshot for output in phpinfo().

php_info_print_table_start();
php_info_print_table_header(2, "First column", "Second column");
php_info_print_table_row(2, "Entry in first row", "Another entry");
php_info_print_table_row(2, "Just to fill", "another row here");
php_info_print_table_end();
Output of phpinfo()

Execution Information

You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro TSRMLS_FETCH() once in that function; this will introduce them to your local scope.

Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Printing execution information..

Пример #14 Printing execution information.

zend_printf("The name of the current function is %s&lt;br&gt;", get_active_function_name(TSRMLS_C));
zend_printf("The file currently executed is %s&lt;br&gt;", zend_get_executed_filename(TSRMLS_C));
zend_printf("The current line being executed is %i&lt;br&gt;", zend_get_executed_lineno(TSRMLS_C));
Printing execution information

Startup and Shutdown Functions

Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events.

The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).

For dynamic extensions, module and request startup/shutdown events happen at the same time.

Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.

Calling User Functions

You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.

User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.

ZEND_API int call_user_function_ex(HashTable *function_table, zval *object,
zval *function_name, zval **retval_ptr_ptr,
int param_count, zval **params[],
int no_separation);

Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.

Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro TSRMLS_FETCH once.

The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.

The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!

Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.

Calling user functions. shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.

Пример #15 Calling user functions.

zval **function_name;
zval *retval;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

if((*function_name)->type != IS_STRING)
{
    zend_error(E_ERROR, "Function requires string argument");
}

TSRMSLS_FETCH();

if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS)
{
    zend_error(E_ERROR, "Function call failed");
}

zend_printf("We have %i as type\n", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);

<?php

dl("call_userland.so");

function test_function()
{
    echo "We are in the test function!\n";
    return 'hello';
}

$return_value = call_userland("test_function");

echo "Return value: '$return_value'";
?>

Результат выполнения данного примера:

We are in the test function!
We have 3 as type
Return value: 'hello'

Initialization File Support

PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.

To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.

PHP_INI_BEGIN()
PHP_INI_ENTRY("first_ini_entry",  "has_string_value", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("second_ini_entry", "2",                PHP_INI_SYSTEM, OnChangeSecond)
PHP_INI_ENTRY("third_ini_entry",  "xyz",              PHP_INI_USER, NULL)
PHP_INI_END()
The PHP_INI_ENTRY() macro accepts four parameters: the entry name, the entry value, its change permissions, and a pointer to a change-notification handler. Both entry name and value must be specified as strings, regardless of whether they really are strings or integers.

The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.

The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:

PHP_INI_MH(OnChangeSecond);             // handler for ini-entry "second_ini_entry"

// specify ini-entries here

PHP_INI_MH(OnChangeSecond)
{

    zend_printf("Message caught, our ini entry has been changed to %s&lt;br&gt;", new_value);

    return(SUCCESS);

}
The new value is given to the change handler as string in the variable new_value. When looking at the definition of PHP_INI_MH, you actually have a few parameters to use:
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value,
                                  uint new_value_length, void *mh_arg1,
                                  void *mh_arg2, void *mh_arg3)
All these definitions can be found in php_ini.h. Your message handler will have access to a structure that contains the full entry, the new value, its length, and three optional arguments. These optional arguments can be specified with the additional macros PHP_INI_ENTRY1 (allowing one additional argument), PHP_INI_ENTRY2 (allowing two additional arguments), and PHP_INI_ENTRY3 (allowing three additional arguments).

The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.

Access to initialization entries can also be handled with the macros shown in Macros to Access Initialization Entries in PHP.

Macros to Access Initialization Entries in PHP
Macro | Description
INI_INT(name) | Returns the current value of entry name as integer (long).
INI_FLT(name) | Returns the current value of entry name as float (double).
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long).
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double).
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).

Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():

ZEND_MINIT_FUNCTION(mymodule)
{

    REGISTER_INI_ENTRIES();

}

ZEND_MSHUTDOWN_FUNCTION(mymodule)
{

    UNREGISTER_INI_ENTRIES();

}

Where to Go from Here

You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.

Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.

Reference: Some Configuration Macros

config.m4

The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in M4 Macros for config.m4.

M4 Macros for config.m4
Macro | Description
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure.
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value.
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script.
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module).
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files.
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link.
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest.
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>.

API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see API Macros for Accessing zval Containers).

API Macros for Accessing zval Containers
Macro | Refers to
Z_LVAL(zval) | (zval).value.lval
Z_DVAL(zval) | (zval).value.dval
Z_STRVAL(zval) | (zval).value.str.val
Z_STRLEN(zval) | (zval).value.str.len
Z_ARRVAL(zval) | (zval).value.ht
Z_LVAL_P(zval) | (*zval).value.lval
Z_DVAL_P(zval) | (*zval).value.dval
Z_STRVAL_P(zval_p) | (*zval).value.str.val
Z_STRLEN_P(zval_p) | (*zval).value.str.len
Z_ARRVAL_P(zval_p) | (*zval).value.ht
Z_LVAL_PP(zval_pp) | (**zval).value.lval
Z_DVAL_PP(zval_pp) | (**zval).value.dval
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht

User Contributed Notes

bhavacakra at gmail dot com 10-Mar-2007 01:41
A very nice resource http://devzone.zend.com/public/view/tag/Extension
vijay at planetbazaar dot com 17-Sep-2005 12:53
Notes for Windows PHP5 extension developers:

First, two great articles at http://www.zend.com/php/internals/index.php are in the must read category. Unfortunately an article on building extensions on Windows is yet to arrive at this time. So one gets stuck at section 'Building Your Extension' in the first article - because there is no 'phpize' for Windows to the best of my knowledge.

First point of curiosity is how the extensions that are available for Windows appear in the output of "cscript /nologo configure.js --help". Turns out the magic happens by executing "buildconf.bat". To cut a long story short, it turns out that for Windows, the build system looks for config.w32 in each extension directory instead of config.m4; config.w32 is actually a javascript (from what I gather reading the "vim:ft=javascript" comment at the top of the files).

To get going with the "hello world" sample in the article mentioned above here is the config.w32 to replace config.m4;

--- begin file: config.w32 ---
// hello world module configuration
// vim:ft=javascript
ARG_ENABLE("hello", "hello Enable Hello World support", "no");

if (PHP_HELLO == "yes") {
  EXTENSION("hello", "hello.c", null, "-Iext/hello");
  AC_DEFINE('HAVE_HELLO', 1, 'Whether you ave Hello World');
}

--- end file: config.w32 ---

And just to compare, here is the config.m4

--- begin file: config.m4 ---
dnl vim:ft=m4
dnl hello world module configuration
PHP_ARG_ENABLE(hello, whether to enable Hellow World support,
[ --enable-hello  Enable Hello World support])

if test "$PHP_HELLO" = "yes"; then
  AC_DEFINE(HAVE_HELLO, 1 [Whether you have Hello World])
  PHP_NEW_EXTENSION(hello, hello.c, $ext_shared)
fi

--- end file: config.m4 ---

And finally the key step is to execute 'buildconf.bat'; after this step:

  cscript /nologo configure.js | find "hello"

should show something like:
"--enable-hello     hello Enable Hello World support"
tony dot dodd at btinternet dot com 20-Aug-2005 08:15
These macros are defined in a separate header file called php_ini.h.
josephmdaly at gmail dot com 29-Jul-2005 01:58
It looks like PHP 5 uses a newer version of the windows socket library.

If your extension links to a library that uses the old version you might get a lot of errors about redefining things.

To fix this problem make sure the PHP header files are included before the library�s header files.
josephmdaly at gmail dot com 01-Jul-2005 03:26
Here is a quick example of how to read arrays passed as parameters:

int i;
/* data will be used to store one element on each iteration of a loop */
zval **data = NULL;
/* data_array is the array we are copying values into */
char **data_array = NULL;

/* Use zend_parse_parameters as you normally would with an 'a' in the type
   string.
   In this example it sets the variables data_arg and array_length
*/

data_array = emalloc(sizeof(char *) * array_length);

for (i = 0; i < array_length; i++) {
  /* Get an element out of the hash table as a zval */
  zend_hash_index_find(Z_ARRVAL_P(data_arg), i, (void **)&data);

  /* Make sure the zval is a string */
  convert_to_string(*data);

  /* Convert the zval into a string and store it */
  data_array[i] = Z_STRVAL_PP(data);
}
seymour_levine at hotmail dot com 14-Jun-2005 05:18
A small amount of administration is needed to make this work.

Mainly the dl command does not pick up the module created.

To remedy, use a full path for the extension_dir parameter in php.ini. Then create that subdirectory mod 755 vis:

        extension_dir=/usr/lib/php411

And create php411. The name is arbitrary.

In the php dl command, specify dl('firstmod.so'); do not use any slashes.
Sy Levine 13-Jun-2005 05:29
I installed and run 4.1.1 on RH 7.1  It runs on a separate Apache Server than the one furnished by Red Hat.

A few adminisrative changes were necessary to get  the function going.

The main one was finding and modifying php.ini.

The command: find . -print | grep php.ini should do that.
Mine was in /usr/local/lib

Look for extension_dir in php.ini then type the directive as

extension_dir=/usr/lib/php4

Use no trailing / in the directive. This is where the dl('firstmod.so') php statement accesses your module.

Tip: I do not use a leading / like dl('/firstmod.so') which will be misparsed.  {Note by Ed a PHP ...}

The source module is named firstmod.c.

I compiled and created the firstmod.so with a script based on the various notes about the compile parameters. See
markjolesen, ywarnier, 17-Apr, wish I .
davide dot chiodi at poste dot it 06-Apr-2005 10:34
to build with lcc-win32 compiler:

change #include "php.h" to #include "php-lcc.h"
this is php-lcc.h (copied from excellent windbinder project by Rubem Pechansky)

//ZEND constants
#if defined(_MSC_VER)        // Rick
#    if defined(ZEND_EXPORTS)
#        undef ZEND_EXPORTS
#    endif
#    undef ZEND_DEBUG
#else
#    define PHP_WIN32
#    define ZEND_WIN32
#endif

#define ZEND_DEBUG    FALSE    // Must be FALSE
#define ZTS                    // Must define ZTS (Zend Thread Safety)
#define PHP_REGEX_H            // Skip php_regex.h: '_off_t' not defined anywhere
#define COMPILE_DL_FIRST_MODULE 1
//----------------------------------------------------------------- DEPENDENCIES

#include <php.h>

//---------------------------------------------------------- AUXILIARY FUNCTIONS

int parse_array(zval *array, const char *fmt, ...);

//------------------------------------------------------------------ END OF FILE

you must also used tweaked headers file from winbinder author at this link: http://hypervisual.com/winbinder/files/archived/php4_tweaked_headers.zip
(php 4).
I used php 4.3.10 and all worked fine
ywarnier at beeznest dot org 25-Oct-2004 04:19
Quick note to save time to beginners

To make the example above work, I had to add -I../TSRM because the file tsrm_virtual_cwd.h couldn't be found otherwise (it's located in the TSRM directory which is not included above)

In my case (pure Debian Woody install), php libraries were located in /usr/include/php4 (and php.h was in the 'main' subdirectory) so I had to use this path instead of /usr/local/include
ppmm at wuxinan dot net 19-Jul-2004 05:40
In fact, empty string is not writeable, even when we add an slash after the type decl. Say the implementation of my_test() is like this:

char *s;
int s_len;
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s/", &s, &s_len)

and you pass an empty string my_test("") from the PHP script, then s[0] is not writeable. You will get a seg fault. The reason is that Zend doesn't emalloc a new copy of the empty string dynamically, instead it just assigns the empty_string (which is defined at compile time and located in unwriteable data seg) pointer to s.
someone at apple 01-May-2004 10:55
When following the directions for compiling via make, it may be necessary to delete the configure script before running buildconf.  Otherwise you may get a complaint about buggy cache code and the configure script won't actually be updated.
25-Apr-2004 10:13
If you want to free zval, you can do this:

{
zval *new_var;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_var);

/* set type and variable contents here, see the following sections */

ZVAL_STRING(new_var, "123456", 1);

/* introduce this variable by the name "new_variable_name" into the symbol table */
zend_hash_update(
    EG(active_symbol_table),
    "new_var",
    strlen("new_var") + 1,
    &new_var,
    sizeof(zval *),
    NULL
);

zend_hash_del(
    EG(active_symbol_table),
    "new_var",
    strlen("new_var") + 1);

FREE_ZVAL(new_var);
}
php-lists at nomeaning dot net 24-Apr-2004 12:36
phpmanual at oderwat dot de is incorrect:

TSRMLS_DC and TSRMLS_CC are both correct as listed in the original text.

TSRMLS_DC is used for Zend internal function declarations and TSRMLS_CC must be used when calling such functions.
Julien CROUZET jucrouzet_at_cpan.org 07-Apr-2004 02:51
Remember that even if RETURN_* macros sets the return_value to return variable to user, they also RETURN FROM YOU CODE by a "return ;", any code after these macro will be ignored.

If you want to place code after a return of variable (which is not a good idea for code readability), you'll have to use RETVAL_* macro instead.
Julien CROUZET jucrouzet_at_cpan.org 07-Apr-2004 02:44
Just an example of the way of the way of returning array :

/*
** Creates a array of on element (a long of value 42)
*/
ZEND_FUNCTION("make_42_array")
{
  zval *my_long;

  // Declaring and allocating return_value to be an array
  array_init(return_value);

  //Creates and assign the long element at (long)42
  MAKE_STD_ZVAL(my_long);
  ZVAL_LONG(new_element, 42);

  //Make this our $array[0] I do not use add_index_long to
  //to show a "by-hand" assignation
  zend_hash_index_update(HASH_OF(return_value), 0, (void *)&my_long, sizeof(zval *), NULL);

  //Returns nothing to satisfy the void prototype
  return ;

}
Julien CROUZET jucrouzet_at_cpan.org 05-Apr-2004 03:28
All associate array functions (add_assoc_long for example) are now just aliases of their extended version (add_assoc_long_ex).

The key lenght is calculated with strlen(key) + 1, but remember that this is NOT binary safe (strlen stops on the first null byte).

Users may want to use binary keys, so always prefer extended versions with a secure length !
jason dot lambert at uk dot clara dot net 31-Mar-2004 05:18
Just a note of caution, when using a string value within zend_parse_parameters() you MUST specify the length parameter also, or php may segfault on some machines.

Example possible segfault code:

char *s;
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &s)

Correct code:

char *s;
int s_len;
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &s, &s_len)
Julien CROUZET jucrouzet_at_cpan.org 24-Mar-2004 02:44
As a completion to k at ailis dot de :

According to ARG_SHOULD_BE_SENT_BY_REF macro in zend_compile.h, BYREF_FORCE_REST force the rest of the arguments to be passed as ref.

The first byte have to be the index of BYREF_FORCE_REST in the array.

Means, if you have, 5 args, the first two ones are NOT passed as ref, and the 3 others are, you can do :

static unsigned char rest_arguments_force_ref[] = { 3, BYREF_NONE, BYREF_NONE, BYREF_FORCE_REST };

We can see a few things in this example :

  * As k at ailis dot de said, the first byte is _NOT_ the number of args passed to the function.
  * The argument corresponding to BYREF_FORCE_REST MUST be passed as a reference
  * The others arguments MUST be passed as a reference
glamm at a-s-i dot com 06-Aug-2003 11:14
Regarding the note written by jo-shi at web dot de:

I do not think that the line
  ce = emalloc(sizeof(zend_class_entry));
is required, as the line
  ce = zend_register_internal_class(&class_entry TSRMLS_CC);
actually appears to go through the process of performing the memory allocation and reference counting of the object.
wilf at bigpond dot net dot au 15-Jun-2003 12:26
Another caching problem:

If you seen a message saying that 'may contain buggy cache code', ensure that you delete the 'autom4k...cache' directory before running buildconf.

A good test the see if your new module has been picked up by buildconf is:

$ grep -c my_module configure
(if that returns 0 then buildconf did not work).

Unfortunately this means that you have to completely rebuild your configure script each time you change an M4 file but it doesnt take too long.
wendywds at hotmail dot com 11-May-2003 03:39
Using php-4.3.1 on Redhat Linux 8, step 6 did not work as written.  There is no php executable in /usr/php-4.3.1.  Instead, with help from the pear-general mailing list, I discovered that the newly built php executable is in /usr/php-4.3.1/sapi/cli.  (The very end of the output of 'make' shows -o sapi/cli/php.  According to Johannes on pear-general, it might be in sapi/cgi instead.)

So I had to change step 6 to:
6.  $ sapi/cli/php -f ext/my_module/my_module.php
Ed a PHP enthusiast from NYC 27-Apr-2003 10:55
Thank you very much for the comments above!

Here is a distillation of how to compile your module as a dynamic library, placing it in your web server and loading it in your test .php file being served (PHP 4.3.1).

*** Compiling a module as a .so

$ cd ext/mystuff

$ cc -fpic -DCOMPILE_DL_MYSTUFF=1 -I/usr/local/include -I../../TSRM -I../.. -I../../main -I../../Zend -I../../ext/bcmath/libbcmath/src -c -o mystuff.o mystuff.c

$ cc -shared -L/usr/local/lib -rdynamic -o mystuff.so mystuff.o

*** Move it to the web server (doc root is /www)

$ cp mystuff.so /www/.

$ chmod 644 /www/mystuff.so

*** load the module in the .php file for testing purposes

<?
dl('/mystuff.so');

/*  your php code here  */
?>

The other thing that threw me off my tracks is that when dealing with strings you can allocate memory with emalloc and return the result with the RETURN_STRING macro (duplicate set to 0) and presumably PHP will take care of the efree -- or else I got it wrong and have plenty of leaks  ;-)
16-Apr-2003 11:08
Compiling Manually NOTE:
remenber add -DHAVE_CONFIG_H flag
otherwise you .so can't be ld. then you cp it to php modules directory.
i.e
Compiling cc -fpic -DHAVE_CONFIG_H  -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Mac M�hleisen 19-Mar-2003 11:55
To built the modules shipped with the source just cd into the ext dir for example

cd ext/oci8

and type

export SHLIB_SUFFIX_NAME=so
phpize && aclocal && ./configure && make

now you have a subdir called "modules" with the .so file. Copy it to your extension dir and set everything up in php.ini.

This way you can add extensions to binary distributions like RPMS.
staffan dot palmroos at surfbuy dot se 07-Mar-2003 10:30
The specified_type_or_NULL operator ! in the type specifier string of zend_parse_parameters seems to work for strings too, in addition to (a, o, O, r, and z) as noted.
jo-shi at web dot de 03-Dec-2002 10:54
add_property_[*](*) overwrites existing values in your object:

ex:
 var_dump($myobj);
 object(objectname)(1){
   ["_myvalue"]=>int(23);
 }
 so in func1 i "add" a property again:
 PHP_FUNCTION(func1){
   add_property_long(getThis(),"_myvalue",32);
 }
 should (as expected) result
 object(objectname)(1){
   ["_myvalue"]=>int(32);
 }
/* annotation: getThis() is a function used by many extensions to find out the $this value in an object */
jo-shi at web dot de 03-Dec-2002 10:47
you can add functions to your object:
you may declare global
  static zend_function_entry
    php_my_class_functions[] = {
      ZEND_FE (func1, NULL)
      ZEND_FE (func2, NULL)
      {NULL, NULL, NULL}
    };

you may declare local
  zend_class_entry my_class_entry;
  zend_class_entry *ce;

you should do something like this
  INIT_CLASS_ENTRY(
    func_class_entry,
    "CLASSNAME",
    php_my_class_functions);
  ce = emalloc(sizeof(zend_class_entry));
  ce = zend_register_internal_class (
  &my_class_entry TSRMLS_CC);
  object_init_ex(return_value, ce);
this should produce a returned object in your php_code:
$myobj = yourfunc(/*yourparams*/);
$myobj->func1();
$myobj->func2();
k at ailis dot de 06-Apr-2002 03:56
If you are using one of the above macros you definitely want to use one of those convert-functions if you are not sure what data type is stored in the zval:

  convert_to_string(zval_p)
  convert_to_long(zval_p)
  convert_to_double(zval_p)
  convert_to_boolean(zval_p)
  convert_to_array(zval_p)
  convert_to_object(zval_p)

Otherwise you may get undefined results, because Z_STRVAL_P(zval_p) returns nonsense if the zval contains not a string. If you use convert_to_string() before, the value is converted to a string and you can safely access it via the Z_STRVAL* macros.

There are more useful convert-functions:

Resets the zval to NULL:
  convert_to_null(zval_p)

Converts to a long by using a special base:
  convert_to_long_base(zval_p, base)

There are some more functions which may be useful, but I don't know exactly what they are doing. Just take a look at Zend/zend_operaters.h.
k at ailis dot de 06-Apr-2002 03:41
To complete the macro list:

Access an object:
  Z_OBJ(zval)
  Z_OBJ_P(zval)
  Z_OBJ_PP(zval)

Access object property hash table:
  Z_OBJPROP(zval)
  Z_OBJPROP_P(zval)
  Z_OBJPROP_PP(zval)

Access object class entry:
  Z_OBJCE(zval)
  Z_OBJCE_P(zval)
  Z_OBJCE_PP(zval)

Access a ressource (which is fairly the same as Z_LVAL*):
  Z_RESVAL(zval)
  Z_RESVAL_P(zval)
  Z_RESVAL_PP(zval)
k at ailis dot de 06-Apr-2002 03:33
These macros can be used to access the boolean value of a zval. Yes, you can use Z_LVAL* for booleans, too, but these macros also do a type cast to zend_bool:

Z_BVAL(zval)
Z_BVAL_P(zval)
Z_BVAL_PP(zval)
k at ailis dot de 28-Mar-2002 05:57
Because it is not explained how the arg_types parameter works, I'll try to explain it myself: The arg_types parameter is an array of bytes. The first byte marks how many arg_type-specifiers follows. There are the following macros which can be used to regulate the reference forcing and I interprete them like this (No guarentee):

BYREF_NONE = Force passing by value
BYREF_FORCE = Force passing by reference
BYREF_ALLOW = Allow passing by reference
BYREF_FORCE_REST = ???

Commonly the arg_types parameter is used like this:

static unsigned char third_argument_force_ref[] = { 3, BYREF_NONE, BYREF_NONE, BYREF_FORCE };
ZEND_FE(foobar, third_argument_force_ref)

Note that the first element in the array does NOT specify how many arguments the function is expecting, only how many arg_type-Specifiers follows. Checking of the number of arguments has to be done in the function body itself (i.E. by using the zend_parse_parameters() function)
k at ailis dot de 28-Mar-2002 05:43
An information that is missing here: The function name parameter can be an array with two elements. The first element is an object reference or a class name and the second element is the method name. Zend recognizes if the parameter is a string (which results in a normal function call or a normal method call if the object parameter is used) or if it is an array.
john dot gallet at wanadoo dot fr 26-Mar-2002 11:58
Concerning all add_*_stringl() functions :
they do not behave like snprintf() for instance, i.e. the length of the string is not a *maximum length* but an *exact* length, and you end up with null '\000' or '\@'  caracters in your PHP string if the length parameter is greater than the actual length of the string to be associated with return_value.

Yes, it is clearly written but still a trick if you are used to strncpy() or snprintf().
HTH
k at ailis dot de 18-Mar-2002 08:32
object_init() and object_init_ex() are not calling the constructor of a class. You have to do this by yourself after creating the object.
k at ailis dot de 17-Mar-2002 06:48
There are also the following functions to add zvals to an array or hash:

ZEND_API int add_index_zval(zval *arg, uint index, zval *value);
ZEND_API int add_next_index_zval(zval *arg, zval *value);
ZEND_API int add_assoc_zval_ex(zval *arg, char *key, uint key_len, zval *value)
add_assoc_zval(__arg, __key, __value)
john dot gallet at wanadoo dot fr 04-Jan-2002 04:39
Distinction between --with and --enable : the "something external" means for exemple a shared object. If you are writing a C wrapper for an existing .so library, you should use --with

Do not forget the "cache" effect to modifyng M4 files. When you are testing and getting erros, be sure to delete config.cache before re-running buildconf and ./configure (I spent an hour looking for an error that was not there any more because of that).

HTH and happy developpment.
Streams API for PHP Extension Authors
TSRM API
Zend Engine 1


TSRM API

User Contributed Notes

There are no user contributed notes for this page.
Zend API: Взламываем ядро PHP
ЧАВО
Zend Engine 1


ЧАВО: ЧАсто задаваемые Вопросы и Ответы на них

  • Общая информация
  • Списки рассылки
  • Получение PHP
  • Вопросы по Базам данных
  • Установка
  • Проблемы сборки
  • Использование PHP
  • Хэширование паролей — Безопасное хэширование паролей
  • PHP и HTML
  • PHP и COM
  • PHP и другие языки
  • Переход с PHP 4 на PHP 5
  • Разные вопросы

User Contributed Notes

There are no user contributed notes for this page.
TSRM API
Общая информация
Руководство по PHP


Общая информация

Этот раздел содержит наиболее общие вопросы по PHP: что это такое и что он делает.

  1. Что такое PHP?
  2. Что означает PHP?
  3. Какая связь между версиями PHP?
  4. Могу ли я одновременно запускать несколько версий PHP?
  5. Какие отличия между PHP 4 и PHP 5?
  6. Я думаю, Я нашёл ошибку! Кому я должен сказать?
Что такое PHP?

Из предисловия к руководству:

PHP - это скриптовый язык, который может быть встроен в HTML. Синтаксис языка в большинстве заимствован из C, Java и Perl c добавлением нескольких специфичных для PHP особенностей. Цель языка - позволить web-разработчикам легко создавать динамически генерируемые страницы.

Что означает PHP?

PHP означает PHP: Hypertext Preprocessor. Это название смущает многих людей, так как первое слово в акрониме также является акронимом. Такой тип акронимов называется рекурсивным. Любопытствующие могут посетить » бесплатный вычислительный онлайн-словарь или » статью Википедии по рекурсивным акронимам.

Какая связь между версиями PHP?

PHP/FI 2.0 - ранняя и более неподдерживаемия версия PHP. PHP 3 - улучшенная замена PHP/FI 2.0. PHP 5 - текущая версия, которая использует » Zend engine 2, которая, кроме прочего, предлагает множество дополнительных возможностей для объектно-ориентированного программирования.

Могу ли я одновременно запускать несколько версий PHP?

Да. Смотрите файл INSTALL из дистрибутива исходников PHP.

Какие отличия между PHP 4 и PHP 5?

В то время как PHP 5 был специально задуман быть максимально совместиым со всеми предыдущими версиями, есть несколько важных изменений. Некоторые из них:

  • Новая ООП модель, основанная на Zend Engine 2.0
  • Новое расширение для улучшенной поддержки MySQL
  • Встроенная родная поддержка SQLite
  • Новая константа уровня ошибок E_STRICT, для замечаний во время выполнения кода.
  • Множество новых функций, упрощающих написание кода (и уменьшающих необходимость писать свои собственные функции для многих общих процедур)
За более подробной информацией смотрите разделы Миграция с PHP 4 на PHP 5 и Несовместимые изменения.

Я думаю, Я нашёл ошибку! Кому я должен сказать?

Вам надо обратиться к базе данных ошибок в PHP и убедиться, что ошибка ещё не известна. Если вы не видите её в базе данных, заполните форму сообщения об ошибках. При занесении в базу данных, ошибка получает номер, по которому вы можете отслеживать её статус, поэтому важно использовать базу данных, а не просто послать сообщение в один из списков рассылки, так как это позволит вам позже вернуться и проверить состояние ошибки. База данных ошибок может быть найдена по адресу » http://bugs.php.net/.

User Contributed Notes

There are no user contributed notes for this page.
ЧАВО
Списки рассылки
ЧАВО


Списки рассылки

Этот раздел содержит вопросы о том как связаться с PHP сообществом. Самый лучший способ - списки рассылки.

  1. Есть ли какие-либо списки рассылки по PHP?
  2. Существуют ли какие-либо другие сообщества?
  3. Могу ли я начать свой собственный список рассылки PHP?
  4. Помогите! Похоже, я не могу подписаться/отписаться?
  5. Существует ли где-нибудь архив списков рассылки?
  6. О чём я могу спрашивать в списке рассылки?
  7. Какую информацию я должен включить при посылке в список?
Есть ли какие-либо списки рассылки по PHP?

Конечно! Существует множество списков рассылки на различные темы. Полный перечень списков можно найти на нашей странице » списков рассылки.

Наиболее общий список рассылки - php-general. Чтобы подписаться на него, пошлите пустое письмо на адрес » php-general-subscribe@lists.php.net. Чтобы отписаться, пошлите пустое письмо на адрес » php-general-unsubscribe@lists.php.net.

Также вы можете подписаться/отписаться используя веб-интерфейс на нашей странице » списков рассылки, а инструкции по отписке включены внизу каждого сообщения из рассылки.

Существуют ли какие-либо другие сообщества?

Бесчётно по всему миру. На нашей странице » поддержки для примера есть ссылки на некоторые ресурсы (и информация о том, как узнать больше).

Могу ли я начать свой собственный список рассылки PHP?

Конечно! На самом деле, мы не только (бесплатно) разрешаем это, мы это поощряем! Помогая и делясь своим знанием и опытом по PHP с другими, вы поощряете рост и разработку как глобального сообщества PHP, так и самого языка.

Помогите! Похоже, я не могу подписаться/отписаться?

Если у вас возникла проблема с подпиской или отпиской от списка рассылки, возможно это потому, что программное обеспечение списка рассылки не может определить ваш правильный почтовый адрес. Если ваш адрес был joeblow@example.com, и вы пытаетесь подписаться на php-general, то вы можете послать запрос на подписку по адресу php-general-subscribe-joeblow=example.com@lists.php.net, или запрос на отписку по адресу php-general-unsubscribe-joeblow=example.com@lists.php.net. Для других списков рассылки используйте аналогичные адреса.

Самая частая причина, по которой люди не могут отписаться от наших списков рассылки, это использование пересылки почты. Например, если ваш электронный адрес danbrown@example.com, но вы подписались на список рассылки с адреса php-lists@example.com, который пересылает ее вам на danbrown@example.com, то попытка отписать адрес danbrown@example.com не сработает, так как это адрес неизвестен нашей системе. Вместо этого, вам нужно отписать тот адрес, на который приходит почта, в этом примере, это php-lists@example.com.

Существует ли где-нибудь архив списков рассылки?

Да, список архивов можно найти на странице » списков рассылки. Вы также можете найти дюжины сайтов, которые архивируют и/или отдают содержание наших списков рассылок с помощью вашего любимого поисковика, задав запрос "архивы списков рассылок по php" (php mailing list archives).

Сообщения из списков рассылки также сохраняются как статьи новостей. Сервер новостей доступен по адресу » news://news.php.net/, новости с которого можно читать каким-нибудь новостным клиентом. Также есть экспериментальный веб-интерфейс для сервера новостей, доступный по адресу » http://news.php.net/.

О чём я могу спрашивать в списке рассылки?

С растущей день ото дня популярностью PHP, нагрузка на список рассылки php-general увеличилась и на сегодня составляет примерно от 75 до 200 и более сообщений в день. Поэтому, в интересах всех, используйте список рассылки только в крайнем случае, когда поиски во всех других возможных местах завершились неудачно.

Прежде чем послать сообщение в список, пожалуйста, просмотрите этот FAQ и это руководство, может в них вам удастся найти решение вашей проблемы. Если там ничего не удалось найти, просмотрите архивы списка (см. выше). Если у вас проблема с установкой или настройкой PHP, пожалуйста, прочтите всю сопровождающую документацию и файлы README. Eсли после всего этого вам не удалось найти ответ, то ваш вопрос в списке рассылки более чем желателен.

Для получения наилучших ответов, (и чтобы не расстраивать ваших собратьев-программистов), пожалуйста, проверьте, что вы отсылаете свой вопрос в соответствующий список рассылки. Например, если у вас проблема с установкой PHP, вы должны послать свой вопрос в список рассылки php-install. Предостережение: некоторые списки имеют похожие имена и совершенно различные назначения; вопрос по использованию PHP скриптов в Windows должен быть послан в пользовательский список рассылки - Windows PHP users, а не список PHP разработчиков в Windows - Windows Internals list.

Хорошая идея, перед тем как задавать вопросы, прочитать статью » Как Умно Задавать Вопросы.

Какую информацию я должен включить при посылке в список?

Сообщения типа "Не могу запустить PHP! Помогите мне! В чём дело?" совершенно бесполезны. Если у вас проблема с запуском PHP, вы должны указать операционную систему, версию PHP, как вы его получили (прекомпилированный, SVN, RPM и т.п.), что уже сделали, на чём остановились, и, если есть, точное сообщение об ошибке.

Это также относится к любой другой проблеме. Вам необходимо указать, что вы уже сделали, на чём застопорились, что пытаетесь делать и, если есть, любые сообщения об ошибках. Если проблема с вашим исходным кодом, то надо включить часть кода, которая не работает, указав проблемную строку соответственно помещенным комментарием Но не пытайтесь послать больше, чем необходимо! Иначе ваше сообщение будет тяжело читать и большинство людей его просто пропустит. Если вы затрудняетесь решить какой объём информации достаточен, пошлите столько, сколько необходимо по вашей текущей проблеме, и приготовьтесь выслать больше информации по запросу.

Другая важная вещь, которую стоит помнить, это краткое изложение вашей проблемы в строке темы сообщения. Заголовки типа "ПОМОГИТЕ МНЕЕЕ!!!" или "В чём здесь проблема?" будут проигнорированы большинством читателей.

И на последок, для всеобщей пользы и особенно для вас, весьма рекомендуется прочитать статью » Как Умно Задавать Вопросы.

User Contributed Notes

There are no user contributed notes for this page.
Общая информация
Получение PHP
ЧАВО


Получение PHP

Этот раздел содержит информацию о том, где получить PHP и вопросы, касающиеся OC.

  1. Где я могу взять PHP?
  2. Доступны ли прекомпилированные бинарники?
  3. Где я могу достать библиотеки, необходимые для компиляции некоторых дополнительных расширений PHP?
  4. Как подключить эти библиотеки?
  5. Я получил последнюю версию исходников PHP из SVN. Что нужно для компиляции его под Windows?
  6. Где найти файл возможностей браузеров (Browser Capabilities File)?
  7. Что означает потокобезопасность при скачке PHP?
Где я могу взять PHP?

Вы можете скачать PHP с любого сайта из сети сайтов PHP. Сайты сети можно найти на » http://www.php.net/. Вы также можете воспользоваться анонимным SVN для получения самой последней версии исходников. За подробностями обращайтесь к » http://php.net/svn.php.

Доступны ли прекомпилированные бинарники?

Мы распространяем прекомпилированные бинарники только для Windows, так как мы не в состоянии компилировать PHP со всеми возможными комбинациями расширений даже для самых основных Linux/Unix платформ. Также заметьте, что на сегодня многие дистрибутивы Linux поставляются с PHP. Бинарники для Windows можно скачать с нашей страницы » Downloads, для бинарников под Linux, пожалуйста, посетите web сайт вашего дистрибутива.

Где я могу достать библиотеки, необходимые для компиляции некоторых дополнительных расширений PHP?

Замечание: Звёздочкой (*) помечены библиотеки, которые не могут быть использованы с PHP, установленным как модуль на многопоточных web серверах (IIS, Netscape) под Windows, так как они небезопасны в многопоточной среде. Это не относится к Unix среде.

  • » LDAP (Unix).
  • » LDAP (Unix/Win) : Mozilla Directory (LDAP) SDK
  • » бесплатный LDAP сервер.
  • » Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
  • » SNMP* (Unix): .
  • » GD* (Unix/Win).
  • » mSQL* (Unix).
  • » PostgreSQL (Unix).
  • » IMAP* (Win/Unix).
  • » Sybase-CT* (Linux, libc5) : Доступна локально.
  • » FreeType (libttf):.
  • » ZLib (Unix/Win32).
  • » expat XML parser (Unix/Win32).
  • » PDFLib.
  • » mcrypt.
  • » mhash.
  • » t1lib.
  • » dmalloc.
  • » aspell.
  • » readline.

Как подключить эти библиотеки?

Вам необходимо следовать инструкциям, сопровождающим библиотеку. При запуске скрипта 'configure', некоторые библиотеки (такие как библиотека GD) находятся автоматически, другие должны быть включены с помощью опции '--with-EXTENSION' в 'configure'. Запустите 'configure --help' для получения списка всех опций.

Я получил последнюю версию исходников PHP из SVN. Что нужно для компиляции его под Windows?

Смотрите раздел руководства сборка PHP из исходников под Windows.

Где найти файл возможностей браузеров (Browser Capabilities File)?

Файл browscap.ini можно скачать с » http://browsers.garykeith.com/downloads.asp.

Что означает потокобезопасность при скачке PHP?

Потокобезопасность означает, что данный бинарный файл может работать в многопоточным вебсервере, например таким, как Apache 2 под Windows. Потокобезопасность обеспечивается хранением локальных копий в каждом потоке, так что данные не вступят в противоречие с другим потоком.

Так что же выбрать? Если вы хотите использовать PHP в качестве бинарного файла CGI, то вам не нужна потокобезопасность, так как бинарный файл будет запускаться при каждом запросе. Для многопоточных вебсерверов, таких как IIS5 и IIS6, вам понадобится поточная версия PHP.

User Contributed Notes

There are no user contributed notes for this page.
Списки рассылки
Вопросы по Базам данных
ЧАВО


Вопросы по Базам данных

Этот раздел содержит общие вопросы о связи между PHP и базами данных. Да, сегодня практически любая база данных может быть доступна из PHP.

  1. Я слышал, что можно получить доступ к Microsoft SQL серверу из PHP. Как?
  2. Могу ли я получить доступ к базам данных Microsoft Access?
  3. Клиентские библиотеки MySQL больше не включены в PHP 5, как это отразится на мне? Могу ли я всё так же использовать MySQL c PHP? Я пытаюсь работать с MySQL и получаю ошибки "function undefined" (функция неопределена), что выдаёт их?
  4. После установки поддержки разделения в MySQL, Apache выдаёт дампы сразу после загрузки libphp4.so. Можно ли это исправить?
  5. Почему я получаю ошибки типа "Warning: 0 is not a MySQL result index in <file> on line <x>" или "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?
Я слышал, что можно получить доступ к Microsoft SQL серверу из PHP. Как?

На Windows машинах, вы просто используете поддержку ODBC и соответсвующий ODBC драйвер.

На Unix машинах для доступа к Microsoft SQL серверам вы можете использовать Sybase-CT драйвер, так как они (по крайней мере в основном) совместимы по протоколу. У Sybase есть » бесплатная версия необходимых библиотек для Linux. Для других Unix систем вам необходимо обратиться в Sybase за соответствующими библиотеками. Также смотрите ответ на следующий вопрос.

Могу ли я получить доступ к базам данных Microsoft Access?

Да. Если всё полностью выполняется под Windows 9x/Me или NT/2000, то у вас уже есть все необходимые средства, так как для баз данных Microsoft Access вы можете использовать ODBC и драйверы ODBC от Microsoft.

Если вы хотите связать PHP, выполняющийся на Unix, и MS Access на Windows, то вам будут нужны драйверы ODBC для Unix. Такие ODBC драйверы для Unix есть у » OpenLink Software.

Другая возможность - хранить данные на SQL сервере, который имеет ODBC драйверы для Windows, и затем обращаться к этой базе данных из Microsoft Access (используя ODBC) и из PHP (используя встроенные драйверы) или использовать промежуточный формат понятный и для Access, и для PHP, например, простые файлы или базы данных dBase. По этому поводу Тим Хэйз (Tim Hayes) из OpenLink software пишет:

Использование промежуточной базы данных - не очень хорошая идея, когда есть возможность работать с базой данных на прямую из PHP через ODBC, например с драйверами от OpenLink. Если вам всё-таки надо использовать промежуточный формат, OpenLink выпустил Virtuoso (механизм виртуальной базы данных) для NT, Linux и других платформ Unix. Пожалуйста, посетите наш » вебсайт для бесплатной загрузки.

Другой проверенный вариант - использовать MySQL с её MyODBC драйверами на Windows и делать синхронизацию баз данных. Стив Лоренс (Steve Lawrence) пишет:

  • Установите MySQL согласно поставляемым с ней инструкциям. Последняя версия доступна с » http://www.mysql.com/. Особой конфигурации не требуется, за исключением того, что при настройке баз данных и создании пользователя, в поле хоста вы должны поместить % или имя Windows машины, на которую вы хотите получить доступ из MySQL. Запишите имя вашего сервера, имя пользователя и пароль.
  • Скачайте MyODBC драйвер для Windows с сайта MySQL. Установите его на вашей Windows машине. Вы можете проверить его работоспособность с помощью поставляемых с ним утилит.
  • Создайте пользователя или системный dsn в вашем администраторе ODBC, расположенном в контрольной панели. Создайте dsn имя, введите имя хоста, имя пользователя, пароль и т.д. для вашей базы данных MySQL, сконфигурированной на 1-ом шаге.
  • Установите полную версию Access, это даст вам уверенность, что вы получите все нужные расширения (add-ins). По крайней мере вам будут необходимы поддержка ODBC и администратор связанных таблиц.
  • И теперь самое интересное! Создайте новую базу данных Access. В окне таблицы щёлкните правой кнопкой мышки и выберите Link Tables (Связать Таблицы), либо из файлового меню выберите Get External Data (Получить Внешние Данные) и затем Link Tables. В появившемся окне просмотра файлов выберите файлы типа ODBC. Выберите системный dsn и имя вашего dsn, созданного на 3-ем шаге. Выберите таблицу для связи, нажмите OK и вуаля! Теперь вы можете открыть таблицу и добавить/удалить/отредактировать данные на вашем MySQL сервере! Вы также можете строить запросы, импортировать/экспортировать таблицы в MySQL, создавать формы и отчёты, и т.д.

Полезные Советы и Трюки:

  • Вы можете создавать ваши таблицы в Access, экспортировать их в MySQL и затем привязать их назад. Это убыстряет создание таблиц.
  • При создании таблиц в Access, вы должны определить первичный ключ, чтобы иметь доступ к таблице по записи. Убедитесь что вы создали первичный ключ в MySQL перед тем как привязать таблицу к Access.
  • Если вы изменяете таблицу в MySQL, то вы должны связать её с Access по-новой. Идите в tools>add-ins>linked table manager, следуйте к вашему ODBC DSN, и выберите оттуда таблицу для пересвязки. Там же вы можете изменить источник вашего dsn, для этого, перед тем как нажать OK, просто пометьте "always prompt for new location" (всегда запрашивать новое местонахождение).

Клиентские библиотеки MySQL больше не включены в PHP 5, как это отразится на мне? Могу ли я всё так же использовать MySQL c PHP? Я пытаюсь работать с MySQL и получаю ошибки "function undefined" (функция неопределена), что выдаёт их?

Да. PHP всегда будет поддерживать MySQL в том или ином виде. Единственное что изменилось в PHP 5 - это то, что мы больше не поставляем саму клиентскую библиотеку. Вот некоторые причины для этого:

  • Сегодня клиентские библиотеки уже установлены на большинстве систем.

  • Учитывая предыдущий пункт, имея несколько версий, проще запутаться. Например, если вы компонуете mod_auth_mysql с одной версией, а PHP с другой, и затем разрешаете оба в Apache, то вы получите хороший жирный крах. Также, поставляемые библиотеки не всегда дружат с установленной серверной версией. Наиболее очевидный симптом этого - разногласие по тому где искать файл mysql.socket (файл Unix сокета).

  • Также поддержка была вялой и отставала от релизов всё больше и больше.

  • Последующие версии библиотеки будут под GPL и мы не можем поставлять библиотеку под GPL с проектом лицензируемым по типу BSD/Apache. Поэтому полный разрыв в PHP 5 видится как самый лучший вариант.

На самом деле это заденет не так уж много людей. Пользователи Unix, по крайней мере те, кто знает что они делают, всегда были склонны собирать PHP с уже установленной на их системе библиотекой libmesqlclient, просто задав опцию --with-mysql=/usr при сборке. Пользователи Windows могут включить расширение php_mysql.dll внутри php.ini. Более подробную информацию по установке смотрите в документации MySQL. Также убедитесь, что libmysql.dll доступен в системном PATH. О том как - читайте FAQ: установка системного PATH в Windows. Так как libmysql.dll (и многие другие PHP файлы) находится в папке PHP, вам лучше добавить PHP папку в ваш системный PATH.

После установки поддержки разделения в MySQL, Apache выдаёт дампы сразу после загрузки libphp4.so. Можно ли это исправить?

Это происходит если вы скомпоновали ваши библиотеки MySQL с pthreads. Проверьте используя ldd. Если это так, скомпилируйте MySQL из исходников или перекомпилируйте исходный rpm, отключив поточный код клиента в файле спецификации. Любой из этих вариантов исправит проблему. Затем перекомпилируйте PHP с новыми библиотеками MySQL.

Почему я получаю ошибки типа "Warning: 0 is not a MySQL result index in <file> on line <x>" или "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?

Вы пытаетесь использовать идентификатор результата, который равен 0. 0 означает, что ваш запрос неудался по какой-либо причине. Вам необходимо сделать проверку на ошибки, после того как вы послали ваш запрос, и перед тем, как вы пытаетесь использовать возвращённый идентификатор результата. Правильный способ этой реализации выглядит примерно так:

<?php

$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
?>
или
<?php

$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: " . mysql_error());
?>

User Contributed Notes

ashay dot chaudhary at microsoft dot com 09-May-2010 01:20
Q: I heard it's possible to access Microsoft SQL Server from PHP. How?

"On Windows machines, you can simply use the included ODBC support and the correct ODBC driver."
There is a better solution now, download the SQL Server Driver for PHP from Microsoft's Download Center, it is officially supported by Microsoft.

Source code: sqlsrvphp.codeplex.com
kalle dot kipina at gmail dot com 09-Aug-2007 05:06
As reply to the entry from 20-Mar-2005 01:19:

The trick seems to be to insert the php directory into your path before any of the other libmysql.dll locations.
cantelow at csd dot net 30-Aug-2006 10:48
On Tru64 5.1A, we had what looked like the mysql pthread problem, with php 5 shared lib compiling fine but crashing upon firing up apache.  But, our problem turned out to be this: we were running 2 versions of mysql and attempting to use --with-mysql=/usr/local/newmysql5 to link to our running test mysql5 distribution.  php was still linking against an old /usr/local/lib/mysql mysqlclient library, however (or setting up to use old /usr/local/lib/mysql shared mysqlclient.so, not sure which).

When we made sure that only /usr/local/newmysql5/lib/mysql/ mysqlclient library (which was a static one in our case) was available to our compiling user, our problem with php crashing on apache start went away. (We used tru64's handy setacl command to accomplish this.)  We still have the mysql5 pthread-included compile.
James Coburn 01-Feb-2006 05:31
An easy way to compile PHP5 when you have installed mysql, but
- you can't find the "mysql header files" or
- get this error: Cannot find MySQL header files under /usr/

: simply install mysql-devel from mysql site.
plandis98 at yahoo dot com 18-Dec-2005 10:46
If one is using PHP on Windows to connection to MS SQL Server and does not want to pass credentials via the mssql_connect but instead use MS Connectionless NT Authentication, what is the proper syntax/usage?

I believe you want to turn on secure_connection in php.ini file:
; Use NT authentication when connecting to the server
mssql.secure_connection = On
djlopez at gmx dot de 08-Sep-2005 05:51
How to compile PHP5 when you have installed mysql, but
- you can't find the "mysql header files" or
- get this error: Cannot find MySQL header files under /usr/

If you want to use mysql 4.0 (*not* 4.1 or even higher!) just download & extract the latest mysql4.0 binary distribution to e.g.
/root/mysql40/

but don't start it (it even should not work, if you have a mysql server already running)

Then use --with-mysql=/root/mysql4 within your php5 configuration.

After compiling/installing (make, make install), you may delete the /root/mysql40/ directory, or keep it for later versions of php5.
20-Mar-2005 01:19
Just a quick note which may help Windows users setting up PHP/Apache/MySQL.  I was receiving these two error messages on Apache startup: 1) "The procedure entry point mysql_thread_end could not be located in the dynamic link library LIBMYSQL.dll" and 2) "PHP Startup: Unable to load dynamic library '<my php installation dir>/ext/php_mysql.dll' - The specified procedure could not be found".  After checking that libmysql.dll did exist in my root PHP install dir, and that this dir was in my path, I determined that the problem was an older version of libmysql.dll.  My solution was to search all harddrives for this file (I found 6 copies of 5 different versions), and rename all of them except my PHP install dir copy.  PHP, Apache and MySQL all function as expected after making this change.
knb at gfz-potsdam dot de 11-Oct-2004 02:53
This is a crucial piece of information for SYBASE users:

If you are using the free, but old, 11.x client libs from sybase,
 then compile with option  "--with-sybase-ct=$SYBASE"
substitute $SYBASE with the appropriate directory name.

option --with-sybase (without ct) can somehow be used to talk to old MS-SQL servers, but only with the 11.x client libs.

If you are using free, or have legally obtained, 12.x client libs from sybase, then compile with option  "--with-sybase-ct=$SYBASE/$SYBASE_OCS"
substitute $SYBASE/$SYBASE_OCS with the appropriate directory name.
Получение PHP
Установка
ЧАВО


Установка

Этот раздел содержит общие вопросы по установке PHP. PHP доступен практически для любой ОС (за исключением, может быть, MacOS предшествующей OSX) и любого web сервера.

Для установки PHP следуйте инструкциям в Установка и настройка.

  1. Почему я не должен использовать Apache2 с потоковым MPM в промышленном окружении?
  2. Unix/Windows: Где должен находиться файл php.ini?
  3. Unix: Я установил PHP, но каждый раз при загрузке документа я получаю сообщение 'Document Contains No Data' (Документ Не Содержит Данных)! Что происходит?
  4. Unix: Я установил PHP с помощью RPMS, но Apache не обрабатывает PHP страницы! Что происходит?
  5. Unix: Я установил заплатку в Apache для расширений FrontPage и неожиданно PHP перестал работать. Неужели PHP не совместим с FrontPage расширениями для Apache?
  6. Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю пустой экран.
  7. Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку сервера 500.
  8. Некоторые операционные системы: Я установил PHP без ошибок, но когда я пытаюсь запустить Apache, я получаю ошибки "undefined symbol" (неопределённый символ): [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: Я следовал всем инструкциям, но так и не смог заставить PHP и IIS работать вместе!
  11. Когда PHP запускается как CGI в IIS, PWS, OmniHTTPD или Xitami, я получаю следующую ошибку: Security Alert! PHP CGI cannot be accessed directly..
  12. Как узнать, что мой php.ini был найден и прочтён? Похоже, что мои изменения не были восприняты?
  13. Как на Windows добавить мою PHP директорию в PATH?
  14. Как в Windows сделать файл php.ini доступным для PHP?
  15. Возможно ли использовать согласование содержания в Apache (опция MultiViews) c PHP?
  16. PHP может обрабатывать только GET и POST запросы?
Почему я не должен использовать Apache2 с потоковым MPM в промышленном окружении?

PHP - это клей. Клей, используемый для построения классных веб-приложений, склеивая дюжины сторонних библиотек и создавая впечатление одного согласованного целого, с помощью интуитивного и легко изучаемого языка. Гибкость и мощь PHP полагается на стабильность и устойчивость используемой платформы. Для склейки вместе ему необходимы работающая ОС, работающий веб-сервер и работающие сторонние библиотеки. Когда что-либо из этого перестаёт работать, PHP нужны способы определения проблем и их быстрого исправления. Если вы усложняете низлежащую систему, не разделяя полностью потоки выполнения, не выделяя раздельные сегменты памяти и не предоставляя "песочницу" для игры для каждого запроса, то в вашей PHP системе появятся слабые места.

Если вы хотите использовать потоковый MPM, взгляните на конфигурацию с FastCGI, где вы можете запускать PHP в своём собственном пространстве памяти.

Unix/Windows: Где должен находиться файл php.ini?

На Unix по умолчанию он должен находиться в директории /usr/local/lib, определяемой как <install-path>/lib. Большинство людей изменяют его во время компиляции с помощью опции --with-config-file-path Для примера, вы можете задать что-то типа:

--with-config-file-path=/etc
Затем скопировать файл php.ini-development из дистрибутива в /etc/php.ini и отредактировать его для ваших локальных нужд.

--with-config-file-scan-dir=PATH

На Windows по умолчанию php.ini находится в Windows директории. Если вы используете веб-сервер Apache, php.ini сначала ищется в директории, где был установлен Apache, например, c:\program files\apache group\apache. В этом случае на одной машине у вас могут быть разные файлы php.ini для разных версий Apache.

Смотрите также главу о конфигурационном файле.

Unix: Я установил PHP, но каждый раз при загрузке документа я получаю сообщение 'Document Contains No Data' (Документ Не Содержит Данных)! Что происходит?

Вероятно, PHP падает по какой-то причине. Для того, чтобы убедиться в этом, просмотрите лог ошибок вашего сервера и затем попытайтесь воспроизвести проблему с помощью небольшого тестового примера. Если вы умеете пользоваться 'gdb', то добавьте трассировку к вашему сообщению об ошибке, это поможет разработчикам точно определить проблему. Если вы используете PHP как модуль Apache, попробуйте что-то типа:

  • Остановите ваши httpd процессы

  • gdb httpd

  • Остановите ваши httpd процессы

  • > run -X -f /path/to/httpd.conf

  • Затем вызовите URL, на котором возникает проблема, из вашего браузера

  • > run -X -f /path/to/httpd.conf

  • Если вы получаете дамп, gdb должен сейчас же сообщить вам об этом

  • введите: bt

  • Вам необходимо включить трассировку в ваше сообщение об ошибке, которое должно быть отправлено с » http://bugs.php.net/

Если ваш скрипт использует функции регулярных выражений (preg_match() и компания), то вам необходимо убедиться, что вы скомпилировали PHP и Apache с одним и тем же пакетом регулярных выражений. Это должно происходить автоматически для PHP и Apache 1.3.x

Unix: Я установил PHP с помощью RPMS, но Apache не обрабатывает PHP страницы! Что происходит?

Полагая, что Apache и PHP оба были установлены из пакетов RPM, вам требуется в вашем файле httpd.conf раскомментировать или добавить все или некоторые из следующих строк:

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so
И добавить:
AddType application/x-httpd-php .php
... в глобальные свойства или в свойства VirtualDomain, для которого вы хотите иметь поддержку PHP.

Unix: Я установил заплатку в Apache для расширений FrontPage и неожиданно PHP перестал работать. Неужели PHP не совместим с FrontPage расширениями для Apache?

Нет, PHP прекрасно работает с FrontPage расширениями. Проблема в том, что FrontPage заплатка изменяет некоторые важные для PHP структуры. Перекомпиляция PHP (с помощью 'make clean ; make') после установки FP заплатки должна решить эту проблему.

Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю пустой экран.

Сделайте просмотр исходника ('view source') в web браузере и, вероятно, вы увидите исходный код вашего PHP скрипта. Это означает, что web сервер не послал скрипт PHP для интерпретации. Что-то не так с конфигурацией сервера, проверьте конфигурацию сервера согласно установочным инструкциям PHP.

Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку сервера 500.

Что-то произошло когда сервер пытался выполнить PHP. Чтобы увидеть более вразумительное сообщение об ошибке, используя командную строку, перейдите в директорию где находится исполняемый файл PHP (php.exe на Windows) и запустите php -i. Если при запуске PHP возникли какие-либо проблемы, то появится соответствующее сообщение об ошибке, которое может дать вам понять что делать дальше. Если вы получаете экран, заполненый HTML кодом (вывод функции phpinfo()), то PHP работает и ваша проблема возможно связана с конфигурацией вашего сервера, которую вам необходимо проверить.

Некоторые операционные системы: Я установил PHP без ошибок, но когда я пытаюсь запустить Apache, я получаю ошибки "undefined symbol" (неопределённый символ):
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

На самом деле это связано с клиентскими библиотеками MySQL и не имеет никакого отношения к PHP. Одним нужна опция --with-zlib , другим - нет. Это также описано в MySQL FAQ.

Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Это сообщение об ошибке означает, что PHP не смог вывести абсолютно ничего. Чтобы увидеть более вразумительное сообщение об ошибке, используя командную строку, перейдите в директорию, где находится исполняемый файл PHP (php.exe на Windows) и запустите php -i. Если при запуске PHP возникли какие-либо проблемы, то появится соответствующее сообщение об ошибке, которое может дать вам понять, что делать дальше. Если вы получаете экран, заполненый HTML кодом (вывод функции phpinfo() функции), то PHP работает.

Как только PHP заработает из командной строки, попытайтесь опять вызвать скрипт из браузера. Если он все также не работает, то причина может быть одной из следующих:

  • Анонимный пользователь Internet ISUR_<machinename> не имеет доступ к вашему PHP скрипту, php.exe, php4ts.dll, php.ini или любому загружаемому PHP расширению из за прав доступа, установленных на эти файлы.
  • Файл скрипта не существует (или, вероятно, не там где вы думаете он должен быть, относительно вашей корневой web директории). Заметьте, что для IIS вы можете поймать эту ошибку пометив 'check file exists' при настройке ассоциирования скриптов (script mappings) в Администраторе Internet Сервисов (Internet Services Manager). Если файл скрипта не существует, то сервер выдаст ошибку 404. Также есть дополнительное преимущество, заключащееся в том, что IIS будет выполнять необходимую вам аутентификацию, основываясь на NTLanMan правах доступа на ваш скрипт.
Windows: Я следовал всем инструкциям, но так и не смог заставить PHP и IIS работать вместе!

Убедитесь что все пользователи, кому необходимо запускать PHP скрипты, имеют право выполнять php.exe! IIS использует анонимного пользователя, который добавлен во время установки IIS. Этот пользователь должен иметь права на php.exe. Также любому аутентифицированному пользователю будут нужны права на выполнение php.exe. И для IIS4 вам необходимо сказать ему, что PHP является скриптовой системой. Также вам захочется прочитать это.

Когда PHP запускается как CGI в IIS, PWS, OmniHTTPD или Xitami, я получаю следующую ошибку: Security Alert! PHP CGI cannot be accessed directly..

Вы должны установить директиву cgi.force_redirect в 0. По умолчанию она установлена в 1, поэтому убедитесь, что директива не закоментирована (с ;). Как все директивы, она задается в php.ini

Так как значение по умолчанию 1, то очень важно быть уверенным на 100%, что был прочитан верный php.ini файл. Для подробностей читайте здесь.

Как узнать, что мой php.ini был найден и прочтён? Похоже, что мои изменения не были восприняты?

Чтобы убедиться, что PHP прочитал ваш php.ini, вызовите phpinfo() и недалеко от начала будет находиться строка, озаглавленная Configuration File (php.ini). Она скажет вам, где PHP ищет php.ini и был ли файл прочитан. Если указана только директория, то файл не был прочитан и вы должны поместить ваш php.ini в эту директорию. Если php.ini включён в PATH, то он был прочитан.

Если php.ini был прочитан и вы запускаете PHP как модуль, то не забудьте перезапустить ваш web сервер после внесения изменений в php.ini.

Смотрите также php_ini_loaded_file().

Как на Windows добавить мою PHP директорию в PATH?

На Windows NT+ и Windows Server 2000+:

  • Зайдите в Control Panel и откройте системную иконку (Start -> Settings -> Control Panel -> System, или просто Start -> Control Panel -> System for Windows XP/2003)

  • Перейдите в закладку Advanced

  • Нажмите кнопку 'Environment Variables'

  • Смотрите в окошко 'System Variables'

  • Найдите Path (возможно, вам придется сделать прокрутку, чтобы найти его)

  • Двойной щелчок на Path

  • Добавьте в конец вашу PHP директорию, поставив спереди ';' (например ;C:\php)

  • Нажмите OK

На Windows 98/Me вам необходимо отредактировать файл autoexec.bat:

  • Откройте Notepad (Start -> Run и введите notepad)

  • Откройте файл C:\autoexec.bat

  • Найдите строку с PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;..... и добавьте в конец строки: ;C:\php

  • Сохраните файл и перезапустите ваш компьютер

Замечание: Обязательно перезагрузитесь после указанных шагов для уверенности, что внесенные вами изменения были применены к PATH.

Прежде в руководстве по PHP рекомендовалось копировать файлы в системную директорию Windows, так как эта директория (C:\Windows, C:\WINNT, и т.п.) входит в системный PATH по умолчанию. Копирование файлов в системную директорию Windows давно уже противопоказано и может вызвать проблемы.

Как в Windows сделать файл php.ini доступным для PHP?

Для этого есть несколько путей. Если вы используете Apache, то читайте инструкции по его установке (Apache 1, Apache 2), в ином случае, вы должны установить переменную окружения PHPRC:

На Windows NT, 2000, XP и 2003:

  • Зайдите в Control Panel и откройте системную иконку (Start -> Settings -> Control Panel -> System, или просто Start -> Control Panel -> System for Windows XP/2003)

  • Перейдите в закладку Advanced

  • Нажмите кнопку 'Environment Variables'

  • Посмотрите в окошко 'System variables'

  • Щёлкните на 'New' и введите 'PHPRC' как имя переменной и директорию, где находится php.ini, как значение переменной (например, C:\php)

  • Нажмите OK и перезапустите ваш компьютер

На Windows 98/Me вам необходимо отредактировать файл autoexec.bat:

  • Откройте Notepad (Start -> Run и введите notepad)

  • Откройте файл C:\autoexec.bat

  • Добавьте новую строку в конец файла: set PHPRC=C:\php (замените C:\php на директорию, где находится php.ini). Учтите, что путь не должен содержать пробелы. Например, если вы установили PHP в C:\Program Files\PHP, вы можете вместо этого ввести C:\PROGRA~1\PHP.

  • Сохраните файл и перезапустите ваш компьютер

Возможно ли использовать согласование содержания в Apache (опция MultiViews) c PHP?

Всё работает замечательно, если ссылки на PHP файлы имеют расширение. Этот FAQ рассматривает только случай, когда ссылки на PHP файлы не имеют расширения и вы хотите использовать согласование содержания для отбора PHP файлов из URL без расширений. В этом случае, замените строку AddType application/x-httpd-php .php на:

AddHandler php5-script php
AddType text/html php
Это решение не работает в Apache 1, так как в нём PHP модуль не ловит php-script.

PHP может обрабатывать только GET и POST запросы?

Нет, можно обрабатывать любые запросы, например, CONNECT. Необходимый статус ответа можно послать с помощью функции header(). Если нужно обрабатывать только GET и POST запросы, то этого можно достигнуть с помощью такой конфигурации Apache:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

User Contributed Notes

ssaxena at nriol dot com 12-Mar-2010 02:28
Here are my struggle to get PHP 5.2.12 working on Windows XP SP3, IIS 5.1 (Please note Win XP SP3 has issue of FastCGI)

1. Dowloaded installer and installed in C:\Program Files\PHP as ISAPI module

---->Did not work

Added php5isapi.dll in ISAPI Filter and added the extension .php in Home Dir->Configuration
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

(And the Google was pointing to the Fast CGI issue; Don't know why microsoft has MS-FAST ! )
Uninstalled the PHP and cleaned up the folders, PATH environment variable & PHPRC, the IIS settings and registry entries and shut down(restart is different from shut down) the system to make it very clean

2. Reinstalled the PHP in C:\PHP as ISAPI and did the same as above in IIS
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

Uninstalled and cleaned up same as above and took a breath to make sure what I am doing wrong.
Shutdown the system.

3. Unzipped the php-5.2.12-Win32.zip and did the same as above (this time manually PATH variable and security permission for the PHP folder and following settings)

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system.

4. Downloaded Microsoft Web Platform Installer 2.0 and select the PHP+Fast CGI+Windows Cache for PHP extension and Web Deployment Tools
restarted the system to take effect the settings

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system

5. Took the prev version of PHP php-5.2.4-Win32.zip unzip the folder and did the following changes:

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

set the security permission as IIS_machinename with full access to the C:\PHP folder

------->IT GOT WOKRING

Hope people would be aware of php-5.2.12 and would love the php-5.2.4
Philipp 18-Jul-2008 09:20
When installing or updating php 5.x on Windows 2003 with IIS the installer sets the ISAPI application extension path incrorrectly. (The filename portion of the path is truncated with ~ at the end).

This causes IIS to not serve any .php pages on any of the configured websites.

To solve this, open IIS Manager and expand the tree to "websites". Open "websites" properties dialogue and go to the "Home Directory" tab. Click on the "configuration" button.

In the "Application Configuration" window, select .php from the "Application Extensions" and correct it's path by browsing to the "php5isapi.dll" file in your PHP5 directory.

Choose to replace this configuration option on all configured websites that make use of php when asked.

You can also set this option for individual websites only instead of the top-level website.
jonas at carello dot se 25-Jun-2008 03:53
If after installting/upgrading PHP on Windows 2000/2003/2008 server with IIS, you're only getting blank pages (or if examining the headers, HTTP 500 errors), try the following:

1. Uninstall PHP and remove all traces of it, IIS ISAPI settings, php.ini and the entire PHP directory.

2. Restart the computer.

3. Install PHP again, you can install and use extensions if you wish.

4. Check the ISAPI settings in IIS (or CGI, depending on what you're using).

5. Restart IIS several times (don't ask me why, it makes no sense).

6. If it still doesn't work, copy the following files to %WINDIR%\system32\ from your PHP directory.
(Some files might not exist, I think it depends on your choice of extensions.)

libmysql.dll (if you're using MySQL)
libeay32.dll (even if you're not using OpenSSL)
ssleay32.dll (even if you're not using OpenSSL)
libmcrypt.dll (If you're using mcrypt)
libmhash.dll (If you're using mhash)

7. Restart IIS again.

8. If it still doesn't work, check if you have additional lib*.dll in your PHP folder and try copying these to %WINDIR%\system32\.

The above has helped me 3 times when updating my PHP installation (first from 5.05->5.1.4, second from 5.1.4->5.2.1 and today from 5.2.1->5.2.6).
Each time I've run into the exact same problem, blank pages (500 internal server error).

I hope this helps someone.
john dot calder at manukau dot ac dot nz 03-May-2008 10:19
WINDOWS 2003 and IIS.  BIG LESSON FOR ME was "don't mess with the optional components".
I had lots of trouble until I tried installing without asking for extras and then it was very smooth.
I have found no need to set up paths.
I have found no need to configure IIS.
I have found no need to change security on the PHP folder.

What works for me with Windows/IIS:

1.  You need to be logged-on as "administrator"

2.  Run  "php-5.2.6-win32-installer.msi"
Your ONLY action during this wizard is to select "IIS ISAPI" as the webserver.  Do NOT CHANGE anything else!  I am guessing that the optional extras apply only to Apache because after enabling them I see Apache-related error messages.

3.  Setup a test virtual directory as you would for an ASP or ASP.NET web app.  eg "phptest"
Then use notepad to create a test page eg "test.php"
<?php
phpinfo();
?>

4.  In Internet Explorer, test with eg this address
http://localhost/phptest/test.php

IF this does not give you a beautiful page of details THEN start reading other advice on this page - especially helpful for me was the faq advice to test run "php.exe -i" from the command prompt.
charleslynch at xybersoftware dot com 17-Apr-2008 07:30
One final note to the message below if you are getting the message about not having rights to execute...You need to use IIS right click on the website and choose 'Properties/Home Directory' then on the 'Execute Permissions' combo box you need to choose 'Scripts only'...Click ok...another dialog may appear asking which directories to apply the action too...choose any directories that you intend on using php in and click ok...It should work now...
charleslynch at xybersoftware dot com 17-Apr-2008 11:50
To get php 5.2.5 to work in IIS on Windows Server 2003

1. Install PHP choose the IIS ISAPI webserver option on the first panel of the php install
2. Make sure your website is accessible for example make sure it works with html files
3. Now startup IIS and click on the Web Sevice Extensions folder icon, you should see the PHP Hypertext Processor installled and enabled. Click on the 'All Unknown ISAPI Extensions' and then click the 'Allow' button.
4. Now you need to give the internet users access to the php executable directory ie c:\php or c:\program files\php by using internet explorer and right clicking the php directory and choosing Properties/Security/Add...Now in the 'Select Users or Groups' dialog that appears in the 'Enter the Object Names to select' type in the name of the internet guest account (ie IUSER_TEMPLATE in my case)...click the check names to make sure you got it right and click the OK button.  Finally in the PHP properties dialog click the Internet Guest Account icon and set the permissions to be 'Read & Execute, List Folder Contents and Read'.  Click ok and now it should work.  Create a very simple php file and test it...

If you get the 404 file not found error then the ISAPI extensions are not allowed (#3 above)
If you get a blank page then the ISAPI extensions are probably setup right but you need to give the internet user access rights to the php executable directory (#4 above)
joerg at fenin dot de 02-Nov-2007 02:35
To limit HTTP Request Methods on the Apache server running PHP you should use mod_rewrite or mod_security instead of LimitExcept, to give you more control over the handling of such http errors.  Can go in .htaccess file or httpd.conf

# mod_rewrite
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST)$
  RewriteRule .* - [F,L]
</IfModule>

# mod_security
<IfModule mod_security.c>
  SecFilterSelective REQUEST_METHOD "!^(GET|HEAD|POST)$" "deny,log,status:403"
</IfModule>

You can use the php request method scanner at askapache to see exactly how your server deals with various request methods, and check that your server is configured properly..

http://www.askapache.com/online-tools/request-method-scanner/
scott at chaisson dot net 19-Sep-2007 09:18
Windows 2000 Server and IIS (SP4 and all patches):

After many frustrating hours of trying to figure out the install (again), It took a while, but here are a couple tips:

PHP working with IIS uses c:\winnt\php.ini

It doesn't matter what you set the path to, nor what you set the PHPRC environment variable to. After you get PHP running correctly in the installation folder (using php -i) copy the php.ini file into the c:\winnt folder.

Here's what worked for me:

- Add PHP path to System environment variable

- Add php5activescript.dll from http://snaps.php.net/ to the PHP folder, then Register it: "regsvr32 php5activescript.dll"

Set extension_dir and doc_root directives in PHP.INI:
  extension_dir = C:\WWW\PHP\ext
  doc_root = C:\WWW\Site
  cgi.force_redirect = 0

(the last cgi.force_redirect isn't required, but I like to set it anyway)

Copy the .INI file into WINNT folder

In IIS Manager, right-click "Default Web Site", Click "Home Directory",
  Click "Configuration", "Add" the ISAPI application:
    Executable: <your php install>\php5isapi.dll
    Extension: .php
    Limit to: GET,HEAD,POST
    Check: "Script Engine"
    Uncheck: "Check that file exists"

Finally: Set up an ISAPI filter:
  Click the "ISAPI Filters" tab,
  Filter Name: PHP
  Executable: <your php install>\php5isapi.dll

Notes: You don't have to set any of your folders as "Script source" folders. .PHP files aren't scripts, merely text files that require processing before being shipped off to the browser, which is what the ISAPI filter does.

Finally, working again.

Chase
christianfelix at laszlo dot com 16-Jul-2007 03:39
For Windows XP users

Just add php.ini to windows/system 32 and also save a copy in the setup folder e.g. c:/php/php.ini, c:/php5/php.ini,

You have to follow the suggestions, add to path, uncomment extensions and voila!!
Meiki67 skipthis at geemail 07-Jun-2007 04:41
Had a hard day to MSI install 5.2.3 on WinXP with MySQL. I use a drive substitution (subst drive: path - in my case subst d: c:\drive_d) and installed PHP in D:\PHP - which in reality is C:\DRIVE_D\PHP.  To make a long story short - only after (1) changing all substituted D:\ back to C:\DRIVE_D and (2) resolving all DOS short names to Win long names PHP started to work. The first one is clear - the substitution works only for the active console user - not for services or IUSR. For the second one I have no explanation, since DOS short names should work systemwide - maybe Win handles them correctly but PHP not ?

BTW <?php phpinfo(); ?> was of tremendeous help

Meiki
gui dot priaulx at gmail dot com 03-Jun-2007 12:05
When i first installed PHP 5.2 / 5.1 on Windows 2k3 server standard edition, i got error 404's on every page i tried to load, i then noticed that in the file extention configuration list, .php files where going to E:\PHP\\php5isapi.dll or something similar, the problem was the two back slashes, i'm not sure what their purpose is. After i changed it too one, PHP worked well for about 5 minutes then the Application poop started to crash and a whole new bag of problems fell open, but thats just observation if it helps anyone.
Curtis 18-May-2007 07:39
I have some additional troubleshooting tips for 53.7, which deals with getting a blank screen on your browser when running a PHP script.

In addition to server misconfiguration, it may also be that PHP isn't configured to output errors to the browser, which is the case if you or your host uses a more secure php.ini. If this is the case, you need to find out where errors are being logged to find out if any errors are preventing normal output from being delivered to the client.

If you have access to php.ini, check the 'display_errors' directive, which is, by default, located under the 'error_reporting' directive. It's helpful to have 'display_errors' on during debugging phases, but best to have it off in production environments.

Related functions: http://php.net/ini_set | http://php.net/error_reporting | http://php.net/error_log
knutw at sparhell dot no 06-Nov-2006 09:15
I recntly upgraded from PHP 5.1 to 5.2 on my Windows Server 2003 using IIS6. I selected CGI as before. My PHP folder is as always C:\Program Files\PHP. I also edited my brand new php.ini, enabling all my old extensions and recommended settings for IIS. I like not to keep my old config into a new version.

After upgrade, I just got blank pages in my browser, and the response status was 404 Not found.

I checked my installation twice, using this FAQ, but got no way.

Then I went to IIS Manager, Web Service Extensions. The php Service Extension was Allowed as it should. I deleted the Service Extension and added it. The old extension used short file names containing tilde (PROGRA~) character, but I don'æt know if that gas anything to do with the problem. Anyway, after allowing my" new" Service Extension, pointing to php-cgi.exe as before, mye web sites suddenly worked. So will revommend anyone with thos problem to delete and add the Servcie Extension. It didn't help re-allowing it, restarting IIS or the complete server.
13-Sep-2006 07:03
After setting the PHPRC environment variable, none of my PHP files would hit the preprocessor. The browser was just serving out PHP source code right there in the "view source."

The manual was telling me to set this var to "c:\php," but nothing was working. It's almost as if IIS/Win2000 wasn't reading my php.ini at all.

After I set that variable to "c:\php\php.ini," all of a sudden I was getting honest to goodness PHP pages working.
emzeperx at emzeper dot hu 01-Jan-2006 12:36
You do not have to restart the whole system make effect of changing the PATH env var. For me (sbs2003) worked automatically.
on older systems you can use

set $Path=%path%;c:\php

command to extend immediately the path var.
JUSTANOTHERUSER 14-Aug-2005 11:23
<LimitExcept GET POST>
Deny from all
</LimitExcept>

Does not work with Apache2+ & PHP5 . Apache Refuses to start
per dot fikse at ipj dot no 12-Jul-2005 01:22
Installing PHP 4 or 5 on Windows Server 2003 x64 results in http error 505. This is not a PHP bug. It is due to running a 32-bit ISAPI DLL under the 64-bit version of IIS 6, as documented here: http://support.microsoft.com/?id=895976

Solution: Flip the Metabase flag for Enable32bitAppOnWin64 as described in http://support.microsoft.com/?id=894435 ,
like this: CSCRIPT ADSUTIL.VBS SET W3SVC/AppPools/Enable32bitAppOnWin64 1

(Alternatively with full path: cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1)
patrick hat paddyworks dot com 23-May-2005 09:52
In setting up PHP 5.0.4 + IIS 6  I can concur with vlad at vkelman dot com that setting the environment variable PHPRC is ineffective at telling IIS where to look for php.ini.  The only place PHP5 seems to successfully find php.ini is in C:\Windows.  Using PHPIniDir with Apache2 works like a charm, however.
vlad at vkelman dot com 01-Mar-2005 08:45
In addition of what jimo at mail dot azhsv dot com said:

I don't know which idiot at Microsoft wrote those Knowledge Base articles (http://support.microsoft.com/kb/328360/EN-US/) - maybe the same idiot who created "Web Server Extensions". But the same - adding extensions and enabling them may be achived much simplier: just open III Manager, go to "Web Server Extensions" and add what you need interactively.

I'm trying to make both PHP 4 and PHP 5 running as modules on my machine, PHP 4 under IIS and PHP 5 under Apache 2. It turns out that it much easier to work with Apache. In particular, it allows to use PHPIniDir directive to point PHP to php.ini file. IIS is supposed to allow it with setting the PHPRC environment variable, but for some reason it doesn't work on my machine so far.
barry dot fagin at usafa dot af dot mil 04-Jan-2005 09:22
Fixing 404 (file not found) errors with PHP 5.0.3 and IIS 6.0

IIS 6.0 is installed with security settings that don't permit dynamic content.  This means that even if all the hints in the FAQ are paid attention to (.ini modified correctly, security and permissions correct for IUSR_xxx user, etc), you still get 404 errors for all php files.

To fix this:  IIS Manager -> expand local computer -> Web Services Extensions -> Add web service or extension -> .php, browse to c:\php\php-cgi.exe or wherever you had the php executable installed. That plus setting the doc_root in the .ini file solved the problem.

--BF
furrycod at hotmail dot com 07-Sep-2004 09:35
Great WAMP 1.4.4 (Apache 1.*, MySql 4.*, PHP 4.*) installation article at http://www.circaware.com/articles.php?id=2

This article details how to install these onto a USB stick--which means changing *nothing* on the host PC, such as registry entries, environment variables, files in the Windows path, NT services, ini files, etc.

The USB stick install seems awkward, but I installed WAMP to my harddrive using this article as a guide (essentially replacing E:\ with C:\), and it works fine.  No more trying to decide where the *real* php.ini or my.ini file is that needs to be changed.
masternuthin diespammer at yahoo dot com 23-Jun-2004 03:33
PHP 4.3.7.7 and IIS 6 (w2k3 standard)

Followed note from nigel dot salt at hotmail dot com
but had to modify "Script Map" to "ScriptMap"

Also, had to follow note from jimo at mail dot azhsv dot com

after all that - it worked.
jeff_graham at datacenterservices dot net 01-Feb-2004 01:51
As stated within the note "jimo at mail dot azhsv dot com
29-Nov-2003 04:33
PHP 4 and IIS 6.0 (Windows Server 2003)," I found the same steps were requiered for installation of PhP 5 beta 3 on my Windows 2003 server (Standard Edition)
nigel dot salt at hotmail dot com 13-Dec-2003 05:00
Finally got IIS 5 and PHP 5 to talk.

What worked for me was:

1) Set
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
W3SVC\Parameters\Script Map]
".php"="your path to php\\php.exe"

2) ensure there is not a php.ini in the windows system folder and that there is one wherever you've put PHP

3) edit php.ini and set cgi force redirect to 0 and cgi.rfc2616_headers = 1

4) Put the PHP scripts in their own folder underneath the inetpub root

5) Open the IIS console, right click your new php folder
In the Directory tab
 set application name to the name of the folder
 set executable and script as permission
 set application protection to low
Click configuration and check that .php is mapped to wherever you put
PHP

Restart IIS

Try a very simple PHP page and it should work

Nigel
jimo at mail dot azhsv dot com 29-Nov-2003 07:33
PHP 4 and IIS 6.0 (Windows Server 2003)

Had difficulty getting PHP 4.3.3 to work with Win2003 Ent Server for use with SquirrelMail.  Problem found and believed solved.  Appears to be something New with IIS 6.0 (More security by Micro$oft)  Was getting 404 error and php was not being run as a cgi even though it was in extensions and IIS user had rights to execute it. (php from command line operated correctly)

If you are installing on Windows Server 2003 (only have Enterprise Edition � Not sure if this applies to standard edition), and you have done the normal procedures for inclusion of PHP scripts (either ISAPI or CGI) in IIS, you will still get a 404 error when attempting to execute those scripts even though IIS has rights and the extension points to the correct file.  To alleviate this problem, perform the following:

1.    Open a command prompt window
2.    Change to C:\windows\system32
3.    Execute the command:  cscript  iisext.vbs /AddFile c:\php\php.exe 1 php 0 php
4.    Execute the command:  cscript iisext.vbs /EnFile c:\php\php.exe
5.    To check for correct execution of the above,
6.    Execute the command:  cscript IisExt.vbs /ListFile � the php extension should be listed

If you try just step 4 without step 3 you get an error that the file is not in the list (and won�t be there till you do step 3 above)

After this, IIS seems to like the php extension and work normally.

For additional reference, see the below 3 Micro$oft KB Articles:
HOWTO: Enable and Disable ISAPI Extensions and CGI Applications in IIS 6.0 (MS KB Article 328360)

HOWTO List Web Server Extensions and Extension Files in IIS 6.0 (MS KB Article 328505)

HOWTO Add and Remove Web Service Extension Files in IIS 6.0 (MS KB Article 328419)
peter dot mosinskisNOSPAM at csuci dot edu 06-Mar-2003 12:36
Running Win2K AS + IIS5.0 + PHP 4.3.1, I ran into a nasty problem that I mistakenly thought had to do with something in the php.ini configuration. When I would try to submit a form using the HTTP method GET it would work, but I would get a "404 Page Not Found" error using the POST method.

All my permissions were set correctly, the php.ini was configured correctly. It had to do with URLScan being installed on IIS (see below)

Page 404 File Not Found Error When Using POST method in PHP (and Perl, and otherwise)
-------------------------------------------

This is related to the Microsoft URLScan utility. If you have this problem, the IIS administrator has probably run the IIS Lockdown tool as well as configured URLScan to reject this type of HTTP method when sent in a URL. These tools are meant to enhance web server security.

URLScan configuration files can be found in the \WINNT\system32\inetsrv\urlscan folder on the web server. Specifically, the file to modify is urlscan.ini.

The changes to make are as follows:
1. Make sure UseAllowVerbs=1 under [options]
2. Under the [AllowVerbs] section, list your allowed HTTP methods to include:
    GET
    POST

For more information on the IIS Lockdown tool and URLScan, visit http://technet.microsoft.com
monroe at peoplego dot com 17-May-2002 10:32
INSTALLATION ON OPENBSD 3.1 VIA PORTS COLLECTION
Would have succeed but no mysql support.
I commented out the FLAVORS+= dbase filepro mysql mysql_bundled postgresql iodbc in the /usr/ports/www/php4/Makefile and in the configure options added
--with-mysql=/usr/local   and it worked.

Good Luck
rodent at mighty dot co dot za 17-Apr-2002 04:46
On windows 2000 installation I've had PHP simply hanging when running a PHP script.

To see exactly what is going wrong with PHP in the context of the IUSR_MACHINENAME account create a shortcut on your desktop to point to cmd.exe.

Right click on the shortcut, and select properties.

Then check the 'run as a different user' checkbox of the property pages of the shortcut.

Double click then shortcut, and you will be prompted for a user account to run the cmd.exe shell under.

Enter IUSR_MACHINENAME (replace machine name with the machine name of your system), and enter the password for the account.

If you don't know the password for the IUSR account you might need to go change it in Administrative Tools->Computer Management.

Enter the password, and you will be dropped into a command prompt.

Now run c:\php\php.exe -i and see if you can catch any error messages.

On my system it had a problem accessing c:\winnt\system32\browscap.ini which I was then able to sort out.

Running PHP as the Administrator user didn't give this problem, so being able to impersonate the IIS account was a very useful diagnostic tool.
tanis22 at hotmail dot com 12-Nov-2001 11:01
I figured out why i get this error with just a virtual directory and not the root:

8. Windows: I have installed PHP, but when I to access a PHP script file via my browser, I get the error: cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:
---------------------
Look at the php.ini file and look for

doc_root =

set it to nothing so that it does not only look for that directory. I hope it helps people with IIS and PHP
Вопросы по Базам данных
Проблемы сборки
ЧАВО


Проблемы сборки

В этом разделе собраны наиболее общие ошибки, возникающие на этапе сборки.

  1. Я получил последнюю версию PHP, используя анонимный доступ к SVN, но в нём нет конфигурационного скрипта!
  2. У меня возникают проблемы при конфигурировании PHP для работы с Apache. Он говорит, что не может найти httpd.h, хотя файл находится точно там, где я сказал!
  3. Во время конфигурации PHP (./configure) вы наталкиваетесь на ошибку, схожую со следующей: checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. Когда я пытаюсь запустить Apache, я получаю следующее сообщение: fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. Когда я запускаю configure, он говорит, что не может найти файлы include или библиотеку для GD, gdbm или какого-либо другого пакета!
  6. При компиляции файла language-parser.tab.c мне выдаются ошибки, говорящие yytname undeclared.
  7. Когда я запускаю make, похоже, он выполняется нормально, но на конечной линковке жалуется, что не может найти некоторые файлы.
  8. При компоновке PHP, он жалуется на некоторые неопределённые ссылки.
  9. Я не могу понять как собрать PHP c Apache 1.3.
  10. Я следовал всем шагам по установке модульной версии для Apache на Unix, но мои PHP скрипты выводятся в браузере или я получаю запрос сохранить файл.
  11. В документации рекомендуется использовать: --activate-module=src/modules/php4/libphp4.a, но такой файл не существует, поэтому я заменил это на --activate-module=src/modules/php4/libmodphp4.a и оно не работает!? Что происходит?
  12. Когда я пытаюсь собрать Apache c PHP в виде статического модуля, используя --activate-module=src/modules/php4/libphp4.a он говорит, что мой компилятор не ANSI-совместимый.
  13. Когда я пытаюсь собрать PHP с помощью --with-apxs, я получаю странное сообщение об ошибке.
  14. Во время выполнения make я очень быстро получаю ошибки и множество всяких RUSAGE_.
  15. При компиляции PHP с MySQL, configure выполняется нормально, но во время make я получаю ошибку типа следующей: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', в чём дело?
  16. Я хочу обновить мой PHP. Где я могу найти строку ./configure, которая была использована для моей текущей PHP установки?
  17. При сборке PHP с библиотекой GD, либо выдаются странные ошибки компиляции, либо ошибки сегментации (segfaults) при выполнении.
  18. При компиляции PHP я, кажется, получаю случайные ошибки, например она зависает. Я использую Solaris, если это имеет значение.
Я получил последнюю версию PHP, используя анонимный доступ к SVN, но в нём нет конфигурационного скрипта!

Вам нужен установленный пакет GNU autoconf для того, чтобы сгенерировать конфигурационный скрипт из configure.in. После получения исходников с SVN сервера просто запустите ./buildconf в директории верхнего уровня. (Также, если вы запускаете configure без опции --enable-maintainer-mode, то конфигурационный скрипт не будет перестроен автоматически при изменении файла configure.in, поэтому вам необходимо делать это вручную, когда вы заметите, что configure.in изменился. Один из симптомов - появление таких вещей как @VARIABLE@ в вашем Makefile после выполнения configure или config.status.)

У меня возникают проблемы при конфигурировании PHP для работы с Apache. Он говорит, что не может найти httpd.h, хотя файл находится точно там, где я сказал!

Для configure/setup скрипта вам необходимо указать директорию верхнего уровня, в которой находятся исходники Apache. Это означает, что вам надо задать --with-apache=/path/to/apache , а не --with-apache=/path/to/apache/src .

Во время конфигурации PHP (./configure) вы наталкиваетесь на ошибку, схожую со следующей:

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Не забудьте внимательно прочитать инструкции по установке и заметьте, что для компиляции PHP вам нужно установить как flex, так и bison. В зависимости от ваших настроек, установите bison и flex либо из исходников, либо из пакетов, например, RPM.

Когда я пытаюсь запустить Apache, я получаю следующее сообщение:

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

Эта ошибка обычно появляется, если ядро Apache было скомпилировано как разделяемая библиотека DSO (Dynamic Shared Object). Попробуйте переконфигурировать Apache, используя, по крайней мере, следующие флаги:

--enable-shared=max --enable-rule=SHARED_CORE

Для более подробной информации читайте файл INSTALL в директории верхнего уровня или » страницу руководства Apache по DSO.

Когда я запускаю configure, он говорит, что не может найти файлы include или библиотеку для GD, gdbm или какого-либо другого пакета!

Вы можете сделать так, что скрипт configure будет искать файлы заголовков или библиотеки в нестандартных местах, задав дополнительные флаги для С препроцессора и компоновщика, такие как:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
Если вы используете csh-подобную оболочку (зачем?), то это будет:
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

При компиляции файла language-parser.tab.c мне выдаются ошибки, говорящие yytname undeclared.

Вам необходимо обновить вашу версию Bison. Последнюю версию можно найти на » http://www.gnu.org/software/bison/bison.html.

Когда я запускаю make, похоже, он выполняется нормально, но на конечной линковке жалуется, что не может найти некоторые файлы.

Некоторые старые версии make ошибочно не помещают скомпилированые файлы в поддиректорию functions в той же директории. Попробуйте выполнить cp *.o functions и затем перезапустить make. Если это помогло, то вам действительно надо установить свежую версию GNU make.

При компоновке PHP, он жалуется на некоторые неопределённые ссылки.

Посмотрите на строку для компоновки и убедитесь, что все нужные библиотеки добавлены в конце. Часто забывают '-ldl' и библиотеки, необходимые для поддержки включенных вручную баз данных.

Некоторые люди также сообщают, что при компоновке с Apache им пришлось добавить '-ldl' сразу после libphp4.a.

Я не могу понять как собрать PHP c Apache 1.3.

На самом деле это очень легко. Аккуратно выполните следующие шаги:

  • Скачайте последний дистрибутив Apache 1.3 с » http://httpd.apache.org/download.cgi.
  • Разархивируйте (ungzip/untar) его где-нибудь, например, в /usr/local/src/apache-1.3.
  • Скомпилируйте PHP, сперва запустив ./configure --with-apache=/<path>/apache-1.3 (замените <path> на ваш настоящий путь к директории apache-1.3.)
  • Введите make с последующим make install для сборки PHP и копирования всех необходимых файлов в дерево дистрибутива Apache.
  • Перейдите в вашу директорию /<path>/apache-1.3/src и отредактируйте файл Configuration. Добавьте в файл: AddModule modules/php4/libphp4.a.
  • Введите: ./configure и затем make.
  • Теперь у вас должен быть бинарник httpd, поддерживающий PHP!

Замечание: Вы также можете использовать новый скрипт ./configure в Apache. Смотрите инструкции в файле README.configure, входящем в ваш дистрибутив Apache. Также загляните в файл INSTALL из дистрибутива PHP.

Я следовал всем шагам по установке модульной версии для Apache на Unix, но мои PHP скрипты выводятся в браузере или я получаю запрос сохранить файл.

Это означает, что по какой-то причине модуль PHP не вызывается. Перед тем как обращаться за помощью, проверьте три вещи:

  • Убедитесь, что запускаемый вами бинарник httpd действительно новый, только что построенный httpd. Для этого попробуйте запустить: /path/to/binary/httpd -l Если вы не видите mod_php4.c в списке, то вы запускаете не тот бинарник. Найдите и установите правильный бинарник.
  • Убедитесь, что вы добавили правильный Mime Type в один из ваших Apache .conf файлов. Это должно быть: AddType application/x-httpd-php .php Также убедитесь, что эта строка AddType не попала внутрь <Virtualhost> или <Directory> блока, так как это не даст ей работать с местонахождением вашего тестового скрипта.
  • Наконец, между Apache 1.2 и Apache 1.3 расположение конфигурационных файлов Apache по умолчанию изменилось. Вам надо проверить, что действительно читается тот конфигурационный файл, в который вы добавили строку AddType. Вы можете внести очевидную синтаксическую ошибку в ваш httpd.conf файл или какое-либо другое заметное изменение, которое покажет вам, что читается правильный файл.

В документации рекомендуется использовать: --activate-module=src/modules/php4/libphp4.a, но такой файл не существует, поэтому я заменил это на --activate-module=src/modules/php4/libmodphp4.a и оно не работает!? Что происходит?

Заметьте, что файл libphp4.a не должен существовать. Он будет создан в процессе!

Когда я пытаюсь собрать Apache c PHP в виде статического модуля, используя --activate-module=src/modules/php4/libphp4.a он говорит, что мой компилятор не ANSI-совместимый.

Сообщение об ошибке вводит в заблуждение; это исправлено в более свежих версиях Apache.

Когда я пытаюсь собрать PHP с помощью --with-apxs , я получаю странное сообщение об ошибке.

Проверьте три вещи. Во-первых, по какой-то причине, когда Apache создает Perl скрипт apxs, он получается без правильного компилятора и переменных, задающих флаги. Найдите ваш apxs скрипт (попробуйте команду which apxs), иногда он установлен как /usr/local/apache/bin/apxs или /usr/sbin/apxs. Откройте его и найдите строки, схожие с этими:

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
Если они так и выглядят, то вы нашли вашу проблему. Они могут содержать только пробелы или другие неправильные значения, такие как 'q()'. Измените эти строки на:
my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';                   # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);              # substituted via Makefile.tmpl
Вторая возможная проблема возникает только на Red Hat 6.1 и 6.2. Скрипт apxs, поставляемый с Red Hat, сломан. Ищите эту строку:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
Если вы нашли вышеприведенную строку, измените её на следующее:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
И последнее, если вы переконфигурируете/переустанавливаете Apache, запустите make clean после ./configure и перед make.

Во время выполнения make я очень быстро получаю ошибки и множество всяких RUSAGE_.

При выполнении make во время установки, если вы сталкиваетесь с проблемами, похожими на следующее:

microtime.c: In function `php_if_getrusage':
microtime.c:94: storage size of `usg' isn't known
microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function)
microtime.c:97: (Each undeclared identifier is reported only once
microtime.c:97: for each function it appears in.)
microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function)
make[3]: *** [microtime.lo] Error 1
make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/master/php-4.0.1/ext'
make: *** [all-recursive] Error 1

Ваша система сломана. Вы должны исправить ваши файлы /usr/include, установив пакет glibc-devel, который соответствует вашей glibc. Это абсолютно не зависит от PHP. Для доказательства попробуйте следующий простой тест:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
Если выдаются ошибки, то ваши include файлы испорчены.

При компиляции PHP с MySQL, configure выполняется нормально, но во время make я получаю ошибку типа следующей: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', в чём дело?

Во-первых, важно понимать, что это Warning (предупреждение), а не фатальная ошибка. Так как это последнее, что выводится во время make, оно может выглядеть как фатальная ошибка, но это не так. Конечно, если ваш компилятор умирает на предупреждениях, (Warnings), то тогда да. Также имейте ввиду, что поддержка MySQL включена по умолчанию.

Замечание:

Начиная с PHP 4.3.2 вы также будете видеть следующий текст после того как сборка (make) завершится:

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).
(Сборка завершена, можно безопасно игнорировать
предупреждения о tempnam и tmpnam.)

Я хочу обновить мой PHP. Где я могу найти строку ./configure, которая была использована для моей текущей PHP установки?

Либо смотрите файл config.nice в дереве исходников вашей текущей PHP установки, либо, если это недоступно, просто выполните скрипт:

<?php phpinfo(); ?>
В начале вывода будет находиться строка ./configure, которая была использована для сборки текущего PHP.

При сборке PHP с библиотекой GD, либо выдаются странные ошибки компиляции, либо ошибки сегментации (segfaults) при выполнении.

Убедитесь, что ваша библиотека GD и PHP компонуются с одними и теми же зависимыми библиотеками (например, libpng).

При компиляции PHP я, кажется, получаю случайные ошибки, например она зависает. Я использую Solaris, если это имеет значение.

Использование не GNU утилит во время компиляции PHP может вызвать проблемы. Чтобы быть уверенным, что компиляция PHP будет работать, используйте GNU утилиты. Например, в Solaris, использование SunOS BSD-совместимой или Solaris версии sed не будет работать, а GNU или Sun POSIX (xpg4) версии sed будет. Ссылки: » GNU sed, » GNU flex, and » GNU bison.

User Contributed Notes

Fabio 22-Feb-2012 01:47
When building PHP 5.3.x for Apache 2.4.x you may get an error in the apxs query for the MPM_NAME.
This is because the apxs included in Apache 2.4.x doesn't recognize that query anymore.

To resolve this issue one should modify the PHP configure file to use the right MPM module used by Apache.

To know the used MPM you can execute this command: apachectl -t -D DUMP_MODULES | grep mpm

Then, edit the PHP configure file, search for the APXS_MPM variable and force its value to prefork, event or worker according to the value returned by the previous command.

Hope it helps.
-
Fabio
terry at mackintoshweb dot com 19-Sep-2009 08:43
The configure script of PHP 5.3.0 has some test lines that use expr with the option --, my expr (version 2.0) does not except --.  This causes a run of error messages from the shell like:

./configure: line 2xxx: test: =: unary operator expected
expr: syntax error

I used buildconf --force to see if it would fix this.
While it resulted in a quit different file, it still had the lines of code with expr -- in it.
05-May-2007 06:48
@ anca-phpdoc at anca dot tv:

You can use ./configure --with-libxml-dir=/path_to_xml2-config
chris dot good at NOSPAM dot infor dot com 10-May-2006 12:12
Re Solaris
I was able to compile PHP 5.0.4 under Solaris 2.6 but I had to use gcc to do it. The source is not compatible with the Solaris C preprocessor. I did not have to install any of the gnu utilities (like sed etc) to get it to compile. It clean compiled & linked immediately using gcc 3.3.2.
timothy at imail dot ru 02-May-2006 07:24
Note on PHP5 setup under RedHat 7

Sometimes php5 fails to build with the following message:

[root@www bin]# ./php5
./php5: error while loading shared libraries: unexpected reloc type 0x80

Below is the configure script used:

# PHP5 CLI build, CGI/SAPI disabled
# Created by configure

'./configure' \
'--enable-libxml' \
'--with-mysql=/path_to_mysql' \
'--with-libxml=/path_to_my_libxml' \
'--program-suffix=5' \
'--disable-cgi' \
"$@"

I used the following trick to get round this:

0. If it is not a clean installation, run 'make clean' to get rid of improperly compiled files

1. run ./configure with required options
2. edit makefile:
2.1 find any LDFLAGS or PROGRAM_LDFLAGS definition
2.2 append -lstdc++ to the end of it
3. Run 'make'
4. Run 'make install'
5. Enjoy!!!
anca-phpdoc at anca dot tv 08-Dec-2005 07:48
For the configure newbies among us:

If you update or reinstall any of the libraries used to compile in a different directory than they started out, you will need to make sure that you update the config.cache file (or re-generate it) so that configure will not look in the wrong place for the information.

On Mac OS X, for example, I updated my libxml using Fink.  Fink placed the files in the /sw directory.  However, php was still looking for important libxml files (such as xml2-config) in the old directory (/usr/bin/xml2-config).   After updating config.cache with the new value of the xml2-config path, I was able to compile correctly.
datemplar at freePotatoes dot fr 03-Oct-2005 05:15
If the option --with-apsx2=/path/to/apxs seems to have absolutely no effect and if the configure script ignores the Apache 2.x support, try to shutdown your Apache server (/path/to/bin/apachectl stop) and retry.

It worked here.
didier b. 07-Aug-2005 04:52
I post here because I was unable to find the information on the web.
I hope it will help someone.

Let say you have 2 apache ruuning, on one you want to have disable_functions set and on the other one you don't.

In fact I have (one) solution compiling two differents php modules with differents path to php.ini

using :
--with-config-file-path=/etc/php5  (for the first one)
--with-config-file-path=/etc/php5.nonchroote (for the second one)

for the second one I do not use "make install" but just
"cp .libs/libphp5.so /usr/lib/apache/1.3/libphp5.nonchroote.so"

Then you have to change the
LoadModule php5_module        /usr/lib/apache/1.3/libphp5.nonchroote.so in the second httpd.conf
brad at computechnv dot com 07-Apr-2005 03:07
My problem was actually with mod_dav (which referred me here). Since they took the time to point people here, I thought I'd go ahead and add my two cents worth and expand on the above since it obviously affects PHP as well. I am running Fedora Core 3, Apache 2.0.53, & PHP 5.03. Apache and PHP were built from source.

The first suggestion in section 13 above was close, but not exactly what I needed. jimsteele's suggestion would have worked, but you would have to do it every time you use APXS. What I did was copy these lines:

my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE';
my $CFG_LD_SHLIB      = 'gcc';
my $CFG_LDFLAGS_SHLIB = q(-shared);

and pasted them in the configuration section of my apxs file. Worked like a champ.
dl927 at torfree dot net 11-Feb-2004 09:17
Compiling mod_php4 port on a clean freeBSD 4.8 install for Apache2 needed FOR_APACHE2= yes manually inserted into Makefile prior to version check.
dale at botkin dot org 04-Nov-2002 02:20
If you have customized your Apache to lie about its version number, you may need to edit configure to skip the version number check.  Just /APACHE_VERSION in configure to find the instance(s) where configure checks to make sure you have the right combination of --with-apxs or --with_apxs2 and Apache 1.3 or 2.0.  Assuming you're smart enough to remember which version of Apache you have, you can just delete or comment out the version check and continue to march.
jimsteele at nospam dot com 14-Oct-2001 01:43
Defining the right environment variables for my Apache "make" invocation allowed the correct "apxs" file to be generated for me.  Your mileage may vary.

cd ../apache_1.3.22
CFLAGS_SHLIB="-fpic -DSHARED_MODULE" \
  LD_SHLIB=gcc \
  LDFLAGS_MOD_SHLIB="-shared" \
  make
Установка
Использование PHP
ЧАВО


Использование PHP

В этом разделе собрано множество общих ошибок, которые могут вам встретиться при написании PHP скриптов.

  1. Я не могу запомнить порядок аргументов PHP-функций, они что, случайны?
  2. Я хочу написать общий PHP скрипт, который может обрабатывать данные, приходящие из любой формы. Как узнать какие переменные метода POST доступны?
  3. Мне надо преобразовать все одиночные кавычки (') в обратный слэш с последующей одиночной кавычкой (\'). Как я могу сделать это с помощью регулярного выражения? Я также хотел бы преобразовать " в \" и \ в \\.
  4. Все мои " превратились в \", а ' в \', как избавиться от всех этих ненужных обратных слэшей? Как и почему они появились?
  5. Как директива PHP register_globals касается меня?
  6.       Когда я делаю следующее, вывод распечатывается не в том порядке:

<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>

     Что происходит?
  7. Эй, что произошло с моими строками? <pre> <?php echo "Это должно быть на первой строке."; ?> <?php echo "А это должно быть на следующей строке."; ?> </pre>
  8. Я получаю сообщение 'Warning: Cannot send session cookie - headers already sent...' или 'Cannot add header information - headers already sent...'.
  9. Мне необходим прямой доступ к информации в заголовке запроса. Как я могу это сделать?
  10. Когда я пытаюсь использовать аутентификацию с IIS, я получаю 'No Input file specified'.
  11. Windows: У меня нет доступа к файлам, разделяемых с другим компьютером, по IIS.
  12. Как я должен совмещать XML и PHP? Он жалуется на мои <?xml тэги!
  13. Где я могу найти полный список переменных, доступных мне в PHP?
  14. Как я могу генерировать PDF файлы без использования платных или коммерческих библиотек, как PDFLib? Я бы хотел что-нибудь бесплатное и не требующее внешних библиотек PDF.
  15. Я пытаюсь получить доступ к одной из стандартных CGI переменных (таких как $DOCUMENT_ROOT или $HTTP_REFERER) в определённой пользователем функции и, похоже, она не может быть найдена. В чём дело?
  16. Несколько PHP директив могут принимать сокращения для байтовых значений в отличие от только integer байтовах значений. Каковы все доступные сокращения? И могу ли я использовать их вне php.ini?
  17. Windows: Я постоянно получаю таймауты при соединении с localhost, хотя с "127.0.0.1" все работает нормально?
Я не могу запомнить порядок аргументов PHP-функций, они что, случайны?

PHP - это клей, который скрепляет вместе сотни различных внешних библиотек, поэтому иногда это кажется довольно запутанным. Однако, общее правило таково:

Параметры функций работы с массивами упорядочены в виде "иголка (needle), сено (haystack)", тогда как порядок в строковых функциях обратный, то есть аналогичен "сено, иголка".

Я хочу написать общий PHP скрипт, который может обрабатывать данные, приходящие из любой формы. Как узнать какие переменные метода POST доступны?

PHP предлагает множество предопределённых переменных, таких как суперглобальная $_POST. Вы можете пройтись по $_POST так как это ассоциативный массив всех значений, пришедших с POST. Для примера, давайте просто пройдёмся по ним с foreach, проверим на пустые (empty()) значения и распечатаем.

<?php
$empty = $post = array();
foreach ($_POST as $varname => $varvalue) {
    if (empty($varvalue)) {
        $empty[$varname] = $varvalue;
    } else {
        $post[$varname] = $varvalue;
    }
}

print "<pre>";
if (empty($empty)) {
    print "В POST не было пустых значений, вот что там было:\n";
    var_dump($post);
} else {
    print "Пришло  " . count($empty) . " пустых значений\n";
    print "Всего отправлено:\n"; var_dump($post);
    print "Пустых:\n";  var_dump($empty);
    exit;
}
?>

Замечание: Суперглобальные переменные: замечание о доступности

Начиная с PHP 4.1.0, стали доступными суперглобальные массивы, такие как $_GET, $_POST, $_SERVER и т.д. Дополнительную информацию смотрите в разделе руководства superglobals

Мне надо преобразовать все одиночные кавычки (') в обратный слэш с последующей одиночной кавычкой (\'). Как я могу сделать это с помощью регулярного выражения? Я также хотел бы преобразовать " в \" и \ в \\.

Подразумевая, что вы хотите использовать результат преобразования в работе с базой данных, используйте соответствующий механизм экранирования, идущий с используемой вами базой данных. Например, используйте mysql_real_escape_string() с MySQL и pg_escape_string() с PostgreSQL. Есть также более общие функции addslashes() и stripslashes(), они часто встречаются в старом PHP-коде.

Замечание: Замечание о директиве: magic_quotes_gpc

Директива PHP magic_quotes_gpc имеет значение по умолчанию on (включена). По сути это применяет функцию addslashes() ко всем GET-, POST- и COOKIE-данным. Чтобы удалить добавленные слэши, вы можете использовать stripslashes().

Все мои " превратились в \", а ' в \', как избавиться от всех этих ненужных обратных слэшей? Как и почему они появились?

Наиболее частой причиной магического появления обратных слэшей - это включенная PHP-директива magic_quotes_gpc. Этот функционал PHP уже устарел и на него нельзя полагаться, поэтому эту директиву рекомендуется отключить. Кроме того, для удаления обратных слэшей из строк можно использовать функцию stripslashes().

Замечание: Замечание о директиве: magic_quotes_gpc

Директива PHP magic_quotes_gpc имеет значение по умолчанию on (включена). По сути это применяет функцию addslashes() ко всем GET-, POST- и COOKIE-данным. Чтобы удалить добавленные слэши, вы можете использовать stripslashes().

Как директива PHP register_globals касается меня?

Во-первых, следует объяснить что делает эта директива. Скажем, используется вот такой URL: http://example.com/foo.php?animal=cat и в foo.php у нас находится следующий PHP-код:

<?php
// Использование $_GET в данном случае более предпочтительно
echo $_GET['animal'];

// Чтобы переменная $animal была определена, директива register_globals должна
// быть включена.
// НЕ ДЕЛАЙТЕ ЭТОГО!
echo $animal;

// Это касается всех переменных, включая $_SERVER
echo $_SERVER['PHP_SELF'];

// Опять-таки, чтобы $PHP_SELF была определена, надо включить register_globals
// НЕ ДЕЛАЙТЕ ЭТОГО!
echo $PHP_SELF;
?>

Код выше демонстрирует как register_globals создаёт множество переменных. Годами такой стиль написания не одобрялся и годами register_globals была выключена по умолчанию. Учтите, что эта возможность помечена устаревшей и будет в конце концов удалена. Несмотря на то, что большинство хостингов отключает register_globals, осталось еще много устаревших статей, руководств и книг, которые требуют включения этой директивы. Действуйте соответственно.

См. также следующие источники за дополнительной информацией:

  • Директива register_globals
  • Глава о безопасности и register_globals
  • Работа с внешними данными
  • В качестве альтернативы используйте суперглобальные переменные

Замечание:

В примере выше мы использовали URL, который содержал QUERY_STRING. Передача информации подобным образом происходит с помощью метода HTTP GET, вот почему мы использовали суперглобальный массив $_GET.

Когда я делаю следующее, вывод распечатывается не в том порядке:
<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
Что происходит?

Для того, чтобы использовать результат вашей функции в выражении (таком как соединение с другими строками, как в вышеприведённом примере), вам необходимо вернуть значение с помощью return(), а не выводить его через echo().

Эй, что произошло с моими строками?
<pre>
<?php echo "Это должно быть на первой строке."; ?>
<?php echo "А это должно быть на следующей строке."; ?>
</pre>

В PHP, блок кода завершается либо с "?>", либо с "?>\n" (где \n означает "новая строка"). В вышеприведённом примере предложения выведутся на одной строке, так как PHP опускает символ новой строки после завершения блока. Это означает, что вам необходимо вставить дополнительный символ новой строки после каждого блока PHP кода, для того чтобы вывод продолжался с новой строки.

Почему PHP делает это? Потому что при форматировании обычного HTML это, обычно, упрощает вашу жизнь когда вам не нужна эта новая строка и вам не надо создавать невероятно длинные строки для того, чтобы сделать исходник страницы читаемым.

Я получаю сообщение 'Warning: Cannot send session cookie - headers already sent...' или 'Cannot add header information - headers already sent...'.

Функциям header(), setcookie(), и функциям сессии нужно добавить заголовки к выходному потоку, но заголовки могут быть посланы только перед всем другим содержимым. Перед использованием этих функций нельзя ничего выводить, в том числе HTML. Функция headers_sent() проверит, если ваш скрипт уже послал заголовки; также смотрите функции управления выводом.

Мне необходим прямой доступ к информации в заголовке запроса. Как я могу это сделать?

Это делает функция getallheaders(), если вы запускаете PHP как модуль Apache. Так, следующий кусок кода покажет вам все заголовки запроса:

<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
    echo "headers[$name] = $content<br />\n";
}
?>

Также смотрите
apache_lookup_uri(),
apache_response_headers() и
fsockopen()

Когда я пытаюсь использовать аутентификацию с IIS, я получаю 'No Input file specified'.

Это недостаток модели безопасности IIS. Проблема общая для всех CGI программ, выполняющихся под IIS. Чтобы обойти проблему, создайте простой HTML файл (необрабатываемый PHP) как входную страницу в аутентифицируемой директории. Затем используйте META тэг для перенаправления на PHP страницу или поместите ссылку, указывающую на PHP страницу. После этого PHP распознает аутентификацию правильно. С модулем ISAPI такой проблемы нет. Это не должно повлиять на другие веб-серверы NT. Для дополнительной информации смотрите: » http://support.microsoft.com/kb/q160422/ и раздел руководства HTTP Аутентификация.

Windows: У меня нет доступа к файлам, разделяемых с другим компьютером, по IIS.

Вам необходимо сделать изменения. Идите в Internet Information Services. Найдите ваш PHP файл и перейдите в его свойства. Идите в закладку File Security, Edit -> Anonymous access and authentication control.

Вы можете исправить проблему либо сняв отметку с Anonymous Access и оставив отмеченным Integrated Window Authentication, либо отметив Anonymous Access и отредактировать права пользователя, так как у него может не быть прав.

Как я должен совмещать XML и PHP? Он жалуется на мои <?xml тэги!

Для того, чтобы встроить <?xml напрямую в ваш PHP код, вам надо отключить короткие тэги, установив PHP директиву short_open_tags в 0. Вы можете установить эту директиву с помощью ini_set(). Независимо от того, включена short_open_tags или нет, вы можете делать что-то типа: <?php echo '<?xml'; ?>. По умолчанию эта директива включена (On).

Где я могу найти полный список переменных, доступных мне в PHP?

Читайте страницу руководства по предопределённым переменным, так как она содержит частичный список предопределённых переменных, доступных вашему скрипту. Полный список доступных переменных (и множество другой информации) можно увидеть, вызвав функцию phpinfo(). Не забудьте прочитать раздел руководства по переменным, лежащим вне PHP так как он описывает общие сценарии для внешних переменных, таких как HTML форма, Cookie и URL.

Замечание: register_globals: важное замечание

Начиная с PHP 4.2.0, значением директивы PHP register_globals по умолчанию является off (выключено). Сообщество PHP рекомендует не полагаться на эту директиву, а использовать вместо этого иные средства, такие как superglobals.

Как я могу генерировать PDF файлы без использования платных или коммерческих библиотек, как PDFLib? Я бы хотел что-нибудь бесплатное и не требующее внешних библиотек PDF.

Есть несколько альтернатив, написанных на PHP, таких как » FPDF и » TCPDF.

Есть также расширение Haru, использующее внешнюю свободную библиотеку libHaru.

Я пытаюсь получить доступ к одной из стандартных CGI переменных (таких как $DOCUMENT_ROOT или $HTTP_REFERER) в определённой пользователем функции и, похоже, она не может быть найдена. В чём дело?

Важно осознавать, что директива PHP register_globals также затрагивает переменные окружения и сервера. Когда register_globals = off (по умолчанию off, начиная с PHP 4.2.0), default is off since PHP 4.2.0), $DOCUMENT_ROOT не будет существовать. Вместо нее используйте $_SERVER['DOCUMENT_ROOT']. Если register_globals = on, то переменные $DOCUMENT_ROOT и $GLOBALS['DOCUMENT_ROOT'] будут также существовать.

Если вы уверены, что register_globals = on и удивляетесь почему $DOCUMENT_ROOT недоступна внутри функции, то это потому, что, как любые другие переменные, она требует global $DOCUMENT_ROOT внутри функции. Также смотрите страницу руководства по области определения переменных. Рекомендуется работать с register_globals = off.

Замечание: Суперглобальные переменные: замечание о доступности

Начиная с PHP 4.1.0, стали доступными суперглобальные массивы, такие как $_GET, $_POST, $_SERVER и т.д. Дополнительную информацию смотрите в разделе руководства superglobals

Несколько PHP директив могут принимать сокращения для байтовых значений в отличие от только integer байтовах значений. Каковы все доступные сокращения? И могу ли я использовать их вне php.ini?

Доступные опции: K (для килобайт), M (для мегабайт) и G (для гигабайт; доступна начиная с PHP 5.1.0); они не чувствительны к регистру. Всё остальное считается байтами. 1M равно одному мегабайту или 1048576 байтам. 1K равно одному килобайту или 1024 байтам. Вы не можете использовать эти сокращения вне php.ini, вместо этого используйте целочисленные значения в байтах. Смотрите документацию по ini_get() для примеров как преобразовать эти значения.

Замечание: килобайт и кибибайт

В нотации PHP один килобайт равен 1024 байтам, тогда как стандарт IEC считает это кибибайтом. В итоге: k и K = 1024 байта.

Windows: Я постоянно получаю таймауты при соединении с localhost, хотя с "127.0.0.1" все работает нормально?

До версии PHP 5.3.4, существовала ошибка в коде резолвинга доменного имени, не дававшая определить адрес localhost при включенном IPv6, во всех ситуациях связанных с потоками. Для обхода этой проблемы можно использовать "127.0.0.1" или отключить резолвинг IPv6 в файле hosts.

User Contributed Notes

info at zankmusic dot com 09-May-2009 09:10
Just spent a couple days on this one...
As previously posted, if you set
upload_max_filesize = 0.25M, the value reads correctly in phpinfo(), BUT it is effectively ZERO when implemented.

Note that the following also give ZERO bytes:

upload_max_filesize =  10M  (note the two white spaces before 10M), but the phpinfo() reads '10M' and everything looks ok.

I removed all white spaces in my php.ini file and viola...working fine again.
greenie2600 at yahoo dot com 10-Oct-2007 10:31
Here's a simple function that will convert the shorthand values described in point 64.16 to a number of bytes.

I use this to display the maximum size of file uploads to the user, so they don't waste time uploading a huge file only to find that it's too big. (I've been unable to find any browsers that actually support the MAX_FILE_SIZE technique described in chapter 38, and it's certainly not part of any W3C spec, so this is the next best thing.)

Here's how you'd use my function for that purpose (though you might want to abstract this to a function of its own):

<?php
echo 'Maximum file size: ' . convertBytes( ini_get( 'upload_max_filesize' ) ) / 1048576 . 'MB';
?>

And here's the function:

<?php
/**
 * Convert a shorthand byte value from a PHP configuration directive to an integer value
 * @param    string   $value
 * @return   int
 */
function convertBytes( $value ) {
    if ( is_numeric( $value ) ) {
        return $value;
    } else {
        $value_length = strlen( $value );
        $qty = substr( $value, 0, $value_length - 1 );
        $unit = strtolower( substr( $value, $value_length - 1 ) );
        switch ( $unit ) {
            case 'k':
                $qty *= 1024;
                break;
            case 'm':
                $qty *= 1048576;
                break;
            case 'g':
                $qty *= 1073741824;
                break;
        }
        return $qty;
    }
}
?>
kjn 02-Jul-2007 01:46
64.16 Byte Values

The number that precedes K, M, or G should be an integer.

E.g. this php.ini directive:
   post_max_size = 0.25M
is interpreted as 0, and thus prevents all POSTs.

It is particularly unhelpful that phpinfo() reports the string value assigned to post_max_size (0.25M), and not the numerical value that PHP extracts from that string (0M).
oldcheesemonkey at yahoo dot com 19-Jan-2006 12:54
In reference to faq.using:
6.  I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.

This can be caused by starting a session and then calling a class function in a php file that has any whitespace either before the very first or after the very last php tags <?php  and ?>.
Make sure there is NO whitespace before the initial tag and after the closing tag.
Проблемы сборки
Хэширование паролей
ЧАВО


Безопасное хэширование паролей

В этом разделе разъясняются причины, стоящие за хэшированием паролей в целях безопасности, а также эффективные методы хэширования.

  1. Почему я должен хэшировать пароли пользователей в моем приложении?
  2. Почему популярные хэширующие функции, такие как md5 и sha1 не подходят для паролей?
  3. Если популярные хэширующие функции не подходят, как же я тогда должен хэшировать свои пароли?
  4. Что такое соль?
Почему я должен хэшировать пароли пользователей в моем приложении?

Хэширование паролей является одним из самых базовых соображенй безопасности, которые необходимо сделать, при разработке приложения, принимающего пароли от пользователей. Без хэширования, пароли, хранящиеся в базе вашего приложения, могут быть украдены, например, если ваша база данных была скомпрометирована, а затем немедленно могут быть применены для компрометации не только вашего приложения, но и аккаунтов ваших пользователей на других сервисах, если они не используют уникальных паролей.

Применяя хэширующий алгоритм к пользовательским паролям перед сохранением их в своей базе данных, вы делаете невозможным разгадывание оригинального пароля для атакующего вашу базу данных, в то же время сохраняя возможность сравнения полученного хэша с оригинальным паролем.

Важно заметить, однако, что хэширование паролей защищает их только от компрометирования в вашем хранилище, но не обязательно от вмешательства вредоносного кода в вашем приложении.

Почему популярные хэширующие функции, такие как md5() и sha1() не подходят для паролей?

Такие хэширующие алгоритмы как MD5, SHA1 и SHA256 были спроектированы очень быстрыми и эффективными. При наличии современных технологий и оборудования, стало довольно просто выяснить результат этих алгоритмов методом "грубой силы" для определения оригинальных вводимых данных.

Из-за той скорости, с которой современные компьютеры могут "обратить" эти хэширующие алгоритмы, многие профессионалы компьютерной безопасности строго не рекомендуют использовать их для хэширования паролей.

Если популярные хэширующие функции не подходят, как же я тогда должен хэшировать свои пароли?

При хэшировании паролей существует два важных соображения: это стоимость вычисления и соль. Чем выше стоимость вычисления хэширующего алгоритма, тем больше времени требуется для взлома его вывода методом "грубой силы".

В поставке PHP существует две функции, которые осуществляют хэширование с помощью указанного алгоритма.

Первой такой функцией является crypt(), в которой встроена поддержка нескольких хэширующих алгоритмов. Использование этой функции гарантирует наличие выбранного вами алгоритма, т.к. PHP содержит встроенную реализацию каждого поддерживаемого алгоритма, в случае отсутствия данного алгоритма в вашей операционной системе.

Второй хэширующей функцией является hash(), которая поддерживает намного больше алгоритмов и их вариаций, чем crypt(), но не поддерживает некоторые алгоритмы, доступные в crypt(). Расширение Hash включено в поставку PHP, но может быть отключено при компиляции, поэтому его наличие не гарантируется, в отличие от функции crypt(), входящей в ядро PHP.

Рекомендуемым к использованию алгоритмом является Blowfish, так как он имеет намного более высокую стоимость вычисления, чем MD5 или SHA1, являясь в то же время масштабируемым.

Что такое соль?

Криптографическая соль представляет собой данные, которые применяются в процессе хэширования для предотвращения возможности разгадать оригинальный ввод с помощью поиска результата хэширования в списке заранее вычисленных пар ввод-хэш, известном также как "радужная" таблица.

Более простыми словами, соль - это кусочек дополнительных данных, которые делают ваши хэши намного более устойчивыми к взлому. Существует много онлайн-сервисов, предоставляющих обширные списки заранее вычисленных хэшей вместе с их оригинальным вводом. Использование соли делает поиск результирующего хэша в таком списке маловероятным или даже невозможным.

User Contributed Notes

alice2287 at live dot com 13-Mar-2012 04:25
For those wishing to increase the computational cost of brute-forcing their password hashes by iterating the hash command multiple times, but don't want to increase the risk of a hash collision, simply re-append the password to the hash each iteration.

<?php

$iterations = 10;
$hash = crypt($password,$salt);
for ($i = 0; $i < $iterations; ++$i)
{
    $hash = crypt($hash . $password,$salt);
}

?>

This, of course, can be used with md5(), sha1(), etc. as well as crypt().

Some other recommendations:

- Use the highest number of iterations possible without introducing a significantly noticeable delay to authenticating users, or causing more CPU use than your host will allow.
- Use a unique salt for each user, ideally a random one.
- Use a salt of at least 24 bytes, especially if you're using a weaker algorithm like MD5 or SHA-1.
Использование PHP
PHP и HTML
ЧАВО


PHP и HTML

PHP и HTML тесно взаимодействуют: PHP может генерировать HTML, а HTML может передавать информацию PHP. Перед чтением вопросов в этом разделе важно чтобы вы понимали как получать переменные извне PHP. Страницы руководства по этой теме содержат много примеров. Обращайте особое внимание на то, что register_globals значит для вас.

  1. Какое кодирование/декодирование я должен выполнять при передаче значения через форму/URL?
  2. Я пытаюсь использовать <input type="image">, но переменные $foo.x и $foo.y недоступны. $_GET['foo.x'] тоже не существует. Где они?
  3. Как создать массивы в HTML <form>?
  4. Как получить все результаты из HTML тэга select с опцией multiple?
  5. Как я могу передать переменную из JavaScript в PHP?
Какое кодирование/декодирование я должен выполнять при передаче значения через форму/URL?

Здесь несколько этапов, на которых кодировка важна. Предположим, что у вас есть $data типа string, содержащая строку, которую вы хотите передать без кодирования. Вот эти этапы:

  • Интерпретация HTML. Для того, чтобы задать произвольную строку, вы должны заключить её в двойные кавычки и вызвать htmlspecialchars() на всё значение.

  • URL: URL состоит из нескольких частей. Если вы хотите чтобы ваши данные были восприняты как один элемент, вы должны закодировать их с помощью urlencode().

Пример #1 Скрытый элемент HTML формы

<?php
    echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
?>

Замечание: Использовать urlencode() для $data неправильно, так как это обязанность браузера кодировать (urlencode()) эти данные. Все популярные браузеры делают это правильно. Отметьте, что это происходит вне зависимости от метода (например, GET или POST). Однако, вы заметите это только в случае GET запроса, так как POST запросы обычно скрыты.

Пример #2 Данные, редактируемые пользователем

<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

Замечание: Данные показываются браузером как предполагается, потому что браузер будет интерпретировать экранированные HTML символы. При отправке через GET или POST данные будут закодированы (urlencoded) браузером для передачи и раскодированы (urldecoded) PHP. Поэтому вам не надо выполнять какое-либо url-кодирование/раскодирование самим, все выполняется автомагически.

Пример #3 В URL

<?php
    echo "<a href='" . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . "'>\n";
?>

Замечание: На самом деле вы представляетесь HTML GET запросом, поэтому необходимо вручную закодировать (urlencode()) данные.

Замечание: Вам надо применить htmlspecialchars() на полный URL, потому что URL появляется как значение HTML атрибута. В этом случае, браузер сначала раскодирует всё значение (де-htmlspecialchars()) и затем URL. PHP поймет URL правильно, так как вы закодировали данные с urlencode(). Вы заметите, что & в URL заменяется на &amp;. Хотя большинство браузеров это исправляют, если вы забудете об этом, но всё же это не всегда возможно. Поэтому, даже если ваш URL не динамический, вам надо закодировать его с помощью htmlspecialchars().

Я пытаюсь использовать <input type="image">, но переменные $foo.x и $foo.y недоступны. $_GET['foo.x'] тоже не существует. Где они?

При отправке формы, вместо стандартной кнопки посылки возможно использовать изображение с тэгом как:

<input type="image" src="image.gif" name="foo" />
Когда пользователь щёлкает где-либо на картинке, серверу будет послана сопутствующая форма с двумя дополнительными переменными: foo.x и foo.y.

Так как имена foo.x и foo.y нелегальны в PHP, они автомагически превращаются в foo_x и foo_y. То есть, точки заменяются на подчёркивания. Вы обращаетесь к этим переменным так же как и к любым другим, описанным в разделе о получении переменных извне PHP. Например, $_GET['foo_x'].

Замечание:

Пробелы в именах переменных запроса преобразуются в подчёркивания.

Как создать массивы в HTML <form>?

Для того, чтобы результаты <form> были посланы вашему PHP скрипту как массив, именуйте элементы <input>, <select> или <textarea> следующим образом:

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Заметьте квадратные скобки после имени переменной, это делает её массивом. Вы можете сгруппировать элементы в массив, присваивая одно и то же имя разным элементам:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
Это создаст два массива, MyArray и MyOtherArray, которые будут посланы PHP скрипту. Также возможно задать определённые ключи для ваших массивов:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
Массив AnotherArray теперь будет содержать ключи 0, 1, email и phone.

Замечание:

Определять ключи массивов в HTML необязательно. Если вы не задаёте ключи, массив заполняется в порядке появления элементов в форме. Наш первый пример будет содержать ключи 0, 1, 2 и 3.

Также смотрите Функции для работы с массивами и Переменные извне PHP.

Как получить все результаты из HTML тэга select с опцией multiple?

HTML тэг select с multiple позволяет пользователю выбрать несколько элементов из списка. Эти элементы затем передаются обработчику формы. Проблема в том, что они все переданы с одним и тем же именем. Например:

<select name="var" multiple="yes">
Каждая выбранная опция поступит обработчику формы как:
var=option1
var=option2
var=option3
Каждая опция будет затирать содержимое предыдущей переменной $var. Решение - воспользоваться возможностью PHP "массив из элемента формы". Должно быть задано следующее:
<select name="var[]" multiple="yes">
Это укажет PHP обращаться с $var как с массивом и каждое присваивание значения для var[] добавит элемент в массив. Первый элемент становится $var[0], следующий $var[1] и т.д. Функция count() может быть использована для определения сколько элементов было выбрано и функция sort() может быть использована для сортировки массива опций, если необходимо.

Заметьте, что если вы используете JavaScript, то [] в имени элемента может вызвать проблемы, если вы пытаетесь обращаться к элементу по имени. Вместо, используйте числовой ID элемента формы или заключите имя переменной в одиночные кавычки и используйте как индекс массива элементов, например:

variable = documents.forms[0].elements['var[]'];

Как я могу передать переменную из JavaScript в PHP?

Так как JavaScript является (обычно) клиентской технологией, а PHP является (обычно) серверной технологией, и так как HTML - протокол "без состояния", эти два языка не могут разделять переменные напрямую.

Однако, возможно передавать переменные между ними. Один из способов достичь этого - сгенерировать JavaScript код из PHP и заставить браузер обновиться, посылая определённые переменные назад PHP скрипту. Нижеприведённый пример показывает как это сделать -- он позволяет PHP коду получить высоту и ширину экрана, что, обычно, возможно только на стороне клиента.

Пример #4 Генерирование Javascript из PHP

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // выводим переменные с размерами
  echo "Screen width is: ". $_GET['width'] ."<br />\n";
  echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
  // передаем переменные с размерами
  // (сохраняем оригинальную строку запроса
  //   -- post переменные нужно будет передавать другим способом)

  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>

User Contributed Notes

ciprian dot stingu at gmail dot com 16-Feb-2012 09:45
Using jquery is even easier to send (post) data between javascript and php

<?php
//make an asynchronous request
$.post("somefile.php", {"Param1" : true, "Param2" : 1, "Param3" : "some text"},
    function(received_data)
    {
        //do something with received data
        $("#some_element").html(received_data);
    });

//make a post request
$.ajax({
    type: "POST",
    url: "somefile.php",
    data: {"Param1" : true, "Param2" : 1, "Param3" : "some text"},
    success: function(received_data)
        {//do something with received data},
    async: false
});
?>
jamespclare at gmail dot com 11-Aug-2011 02:57
To pass information from php to javascript is fairly easy. In the form section you can do something like this:

<form name="InfoPassed" action="MaterialModule.php" method="post">
<input type="text" name="PhpVariable" value="<?php print $_SESSION['Name']; ?>"/>
</form>

<script type="text/javascript">
var value=document.InfoPassed.PhpVariable.value;
</script>

but doing it the other way (i.e. from Javascript to PHP) is impossible without involving the submit button

<form name="InfoPassed" action="MaterialModule.php" method="post">
<input type="text" name="PhpVariable"/>
<input type="submit" value="Submit"/>
</form>

<script type="text/javascript">
document.InfoPassed.PhpVariable.value=200;
</script>

<?php
if(isset($_POST["PhpVariable"])){
//do stuff with variable
}
?>

I'm more than happy to be corrected but none of the examples stated it was possible to do it without the submit button.
Andreas R. 01-May-2007 05:14
Actually Example 56.1 doesn't conform to what is stated in the text above it, namely:
* HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.
In the example code single quotes are used instead of double quotes:
<?php
     echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
 ?>
which should be instead:
<?php
     echo "<input type='hidden' value=\"" . htmlspecialchars($data) . "\" />\n";
 ?>
If single quotes are used, they should be escaped too using ENT_QUOTES quote style for htmlspecialchars.
francesco 07-Nov-2006 06:41
Another way to pass variables from JavaScript to PHP.

<script type="text/javascript" language="JavaScript">
<!--
function getScreenResolution()
{
    return document.form.ScreenResolution.value = screen.width + "x" + screen.height;
}
//-->
</script>
<form name="form" action="screen.php?show=ok" method="post" >
<input name="ScreenResolution" type="text" size="20" maxlength="9" />
<input name="show" type="submit" value="Submit" onclick="getScreenResolution()" />
</form>
<?php
    echo $_POST['ScreenResolution'];
?>
tchibolecafe at freemail dot hu 12-Aug-2006 04:34
Notes on question "1. What encoding/decoding do I need when I pass a value through a
form/URL?"

Doing an htmlspecialchars() when echoing a string as an HTML attribute value is not enough to make the string safe if you have accented (non-ASCII) characters in it. See http://www.w3.org/TR/REC-html40/appendix/notes.html#non-ascii-chars

The referred document recommends the following method to be used:

<?php
  function fs_attr($path){
    $retval='';
    for($i=0;$i<strlen($path);$i++){
      $c=$path{$i};
      if(ord($c)<128){
        $retval.=$c;
      }else{
        $retval.=urlencode(utf8_encode($c));
      }
    }
    return htmlspecialchars($retval);
  }

  $img_path='éöüä.jpg';
  echo '<img src="'.fs_attr($img_path).'">';
?>

However, using utf8 encoding for path names is among others supported by Windows NT, above method fails when running for example on an Apache server on Linux.

A more fail safe way:

<?php
        function fs_attr($path){
                $retval='';
                for($i=0;$i<strlen($path);$i++){
                        $c=$path{$i};
                        if(ord($c)<128){
                                $retval.=$c;
                        }else{
                                if(PHP_OS==='WINNT')
                                        $retval.=urlencode(utf8_encode($c));
                                else
                                        $retval.=urlencode($c);
                        }
                }

                return htmlspecialchars($retval);
        }
?>

There may be operating systems that want utf8 encoding, other than WINNT. Even this latter one won't work on those systems. I don't know about any possibility to determine immediately which encoding to be used on the file system of the server...
dot dot dot NO php SPAM at NO willfris dot nl SPAM dot dot dot 12-Jul-2006 03:19
@Torsten{
In http://www.w3.org/TR/xhtml1/#C_8 it says:
"Unfortunately, this constraint cannot be expressed in the XHTML 1.0 DTDs."
}

http://www.w3.org/TR/xhtml1/#C_8 also says: "When defining fragment identifiers to be backward-compatible, only strings matching the pattern [A-Za-z][A-Za-z0-9:_.-]* should be used."
I'll come back to this.

Since it's all about fragment identifiers, I can't see why using an array like arrayname[] would be used. I think arrayname[name] should be used this way the fragment identifiers stay unique.
Since [ and ] are not allowed, why not use something what is allowed and use str_replace?
example:   :_. = [ & ._: = ]   so: name="arrayname:_.name._:" OR name="arrayname:_.0._:" and offcourse also add the id attribute then for backward compatibility.
Torsten 22-Feb-2006 02:30
Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier.  If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements.
jetboy 30-Dec-2005 07:06
While previous notes stating that square brackets in the name attribute are valid in HTML 4 are correct, according to this:

http://www.w3.org/TR/xhtml1/#C_8

the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document.
FatalError 29-Dec-2005 02:29
Actually, you can pass variables between JavaScript and PHP without even refreshing the page. To do this, you have to use AJAX, which is what dmsuperman at comcast dot net was showing in that example.
tms at infamous dot net 22-Nov-2005 06:23
Regarding drane's claim that square brackets ([]) in form input elements (as PHP uses for arrays in forms) are invalid HTML: the NAME attribute of an input element is CDATA, not NAME or ID.

Square brackets are allowed in CDATA, no problem.

(Link is mangled because it's too long:

http://www.w3.org/TR/1999/REC-html401-19991224/ interact/forms.html#h-17.4
rybasso 06-Oct-2005 02:19
If U wish to build POST request depend on form which contains select-multiple use the following js code:

var id = theForm.elements[e].id;

if (theForm.elements[e].type=='select-multiple') {
                for (f=0;f<theForm.elements[e].length;f++) {
                    if(theForm.elements[e].options[f].selected==true)
                         qs+= id+'['+f+']='+escape(theForm.elements[e].options[f].value);
                         qs+=(qs=='')?'':'&';
                }
            }
dmsuperman at comcast dot net 10-Sep-2005 09:05
Here's a great way to pass JavaScript to PHP without even leaving the page:

<script type="text/javascript">
<!--

function xmlreq(){
  if(window.XMLHttpRequest){
    req = new XMLHttpRequest();
  }else if(window.ActiveXObject){
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return(req);
}
function sendPhp(url){
  var req = xmlreq();
  req.onreadystatechange = stateHandler;
  req.open("GET", url, true);
  req.send(null);
}

sendPhp("updatedatabase.php?username=blah&displayname=whatever");
//-->
</script>
fuchs at michaelfuchs dot org 09-Aug-2005 12:54
Here's a new one, which might cause problems for people:

To make my multiple select box contents accessible to both PHP and JavaScript (using getElementById()), I was using both name and id attributes - and naming them the same, for consistency:

<select multiple="multiple" id="bob[]" name="bob[]">

However, I've discovered that - for reasons unknown - using the brackets in the id causes only a single value (rather than multiple values) to get returned to the $_POST['bob'] array. What you want is:

<select multiple="multiple" id="bob" name="bob[]">

Hope this saves some time/frustration.
fib at affordit dot fr 13-Jul-2005 07:26
I was working on a small interface for a client and he wanted a template to be generated dynamically. The issue came up when I had to retrieve the values for an array of text variables. I couldn't find any tutorial to help me out so after a few investigations this is how I made it work:

<?php

  $line_class=array();
  $line_item=array();

    for ($i=$rows_number;$i>0;$i--)
      {
       $line_class[$i]=$_POST['line_class'.$i.''];
       $line_item[$i]=$_POST['line_item'.$i.''];
      }

?>

 Hope this helps someone ... at least they will do the job sooner than I did :D.
levinb at cs dot rpi dot edu 16-Jun-2005 09:17
Well, I was working on this one project, on the assumption that I could get the values of all elements with the same name from an appropriately named array.  Well, I was *very* disappointed when I couldn't, so I made it so I did anyway.

The following script should convert the raw post data to a $_POST variable, with form data from SELECT elements and their ilk being transformed into an array.  It's heavily unoptimized, and I probably missed something, but it's relatively easy to read.  I welcome corrections.

<?php

if ($_POST) {
        $postdata = file_get_contents('php://input');

        $uglybugger = '/(?<=&)([^&=]+)(?:=([^&]*))/';
        $matches = array();

        preg_match_all($uglybugger, $postdata, $matches);

        $_POST = array();

        $match_count = count($matches[0]);
        for ($i = 0; $i < $match_count; $i++) {
                if (!isset($_POST[$matches[1][$i]])) {
                        $_POST[$matches[1][$i]] = array();
                }
                $_POST[$matches[1][$i]][] = $matches[2][$i];
        }
        $match_count = count($_POST);
        for ($i = 0; $i < $match_count; $i++) {
                if (count($_POST[$i]) == 1) {
                        $_POST[$i] = $_POST[$i][0];
                }
        }
}

?>
noah at noah dot org 10-May-2005 10:10
In your action, "random_picker_action.php"
shouldn't you initialize $picks? The code didn't work
for me until I added the line:
    $picks = $_REQUEST['picks'];

Here is the full random_picker_action.php

Yours,
Noah

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
   <title>How to Pass an Array from Javascript to PHP: Action Page</title>
  <!-- File: random_picker_action.php -->
</head>
<body>
<p>
<h3>How to Pass an Array from Javascript to PHP: Action Page</h3>
<?php
  $picks = $_REQUEST['picks'];
  $picks = urldecode(stripslashes($picks));
  echo "<b>JavaScript said: " . $picks . "</b><p>";
  $picks = unserialize($picks);
  if(sizeof($picks) > 0)
  {
   reset($picks);
   echo "You picked the following items:<p>";
   while($item = each($picks))
     echo  $item['value'] . " off, " . str_replace("_", " ", $item['key']) . "<br>";
  }
  else
   echo "You did not pick any items<p>";
?>
</body>
</html>
richard dot prangnell at ntlworld dot com 27-Feb-2005 09:09
Further to my note posted on  26-Feb-2005 at 04:44, I have refined the JavaScript function "send_picks()" to make it more robust and universal. The original version was designed to handle string keys and +ve integer key values only; fine for the original purpose of handling random picks for a shopping cart application but it produced a mal-formed array if any -ve or non-integer key values were submitted. The new version treats both keys and key values as strings, irrespective of the data type; and we all know just how easy it is to manipulate numeric strings as numbers in PHP:-). Key values can now be anything you like; including:
"5"
"2 dozen"
"A gross"
"12.5"
"blue"
and so forth. Here's the updated code:

    <script type="text/javascript">
      function send_picks()
      {
        form1.picks.value="";
        var e, picked = 0;
        for (var i = 0 ; i < form1.elements.length - 2; i++)
        {
          e = form1.elements[i];
          if(e.value != "0" && e.value.length > 0)
          {
            e = form1.elements[i]
            picked++;
                form1.picks.value = form1.picks.value + "s:"
              + e.name.length + ":\"" + e.name + "\";s:"
              + e.value.length + ":\"" + e.value + "\";";
          }
        }
        form1.picks.value = "a:" + picked + ":{" + form1.picks.value + "}";
      }
    </script>

Note the line:
        for (var i = 0 ; i < form1.elements.length - 2; i++)
The  "-2" term is to let the function skip the last 2 elements in the form, a "hidden" input and the "submit" button. No doubt different form layouts will need a different value here.
An incidental bonus is that getting JavaScript to process a floating point input as a string rather than a number avoids the usual rounding errors that tend to turn an input such as "1.2" into a number beginning 1.199999... with about 30 places of decimals - yes, its JavaScript rather than PHP that is responsible for this kind of behaviour.
richard dot prangnell at ntlworld dot com 26-Feb-2005 08:44
The following HTML form page and PHP action page illustrate an elegant and powerful client side JavaScript to server side PHP data transfer technique perfectly matched to PHP's associative array feature. Browse to the form page and select some items by entering an INTEGER > 1 then click on Submit (Don't put strings or reals in the input fields - error trapping has been stripped out for brevity). Try selecting one, some, all or none of the items, changing the names of the form input variables (and the associated labels, for clarity!) or adding to the number of items "on offer". At no point do you need to alter either the JavaScript function or the action page in any way - just be aware that extra coding and error trapping is required - especially where the key values in the application could be something other than integers:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>How to Pass an Array from Javascript to PHP: Form Page</title>
  <!-- File: random_picker.php -->
    <script type="text/javascript">
      function send_picks()
      {
        form1.picks.value="";
        var picked = 0;
        for (var i = 0 ; i < form1.elements.length; i++)
        {
          if(form1.elements[i].value > 0)
          {
            e = form1.elements[i]
            picked++;
                form1.picks.value = form1.picks.value + "s:" + e.name.length + ":\""
            + e.name + "\";i:" + e.value + ";";

          }
        }
        form1.picks.value = "a:" + picked + ":{" + form1.picks.value + "}";
      }
    </script>
</head>
<body>
<p>
<h3 align="center">How to Pass an Array from Javascript to PHP: Form Page</h3>
<form name="form1" action="random_picker_action.php" method="post"
  onsubmit="JavaScript:send_picks()">
<table align="center" border="1" cellpadding="5" cellspacing="0">
  <tr><td>Item 13</td>
  <td><input type="text" name="item_13" value="0" size="4"></td>
  </tr>
  <tr><td>Part number 2</td>
  <td><input type="text" name="Part_number_2" value="0" size="4"></td>
  </tr>
  <tr><td>Drawing ref 327</td>
  <td><input type="text" name="Drawing_ref_327" value="0" size="4"></td>
  </tr>
  <tr><td>Organic Carrots</td>
  <td><input type="text" name="Organic_carrots" value="0" size="4"></td>
  </tr>
  <tr><td colspan="2" align="center">
      <input type="submit" value="Submit Picks">
      <input type="hidden" name="picks" value=""></td>
  </tr>
</table>
</form>
</body>
</html>

The action page for the above form page is listed below. Notice the really ingenious feature; the form variable is simply unserialized  to turn it into a fully functional PHP array! The action page doesn't need to know anything about "expected" variable names because everything PHP needs to know is right inside the array. Note also that for maximum efficiency only "picked" item data is sent. If no items at all are picked, a perfectly formed empty array is sent:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>How to Pass an Array from Javascript to PHP: Action Page</title>
  <!-- File: random_picker_action.php -->
</head>
<body>
<p>
<h3>How to Pass an Array from Javascript to PHP: Action Page</h3>
<?php
  $picks = urldecode(stripslashes($picks));
  echo "<b>JavaScript said: " . $picks . "</b><p>";
  $picks = unserialize($picks);
  if(sizeof($picks) > 0)
  {
    reset($picks);
    echo "You picked the following items:<p>";
    while($item = each($picks))
      echo  $item['value'] . " off, " . str_replace("_", " ", $item['key']) . "<br>";
  }
  else
    echo "You did not pick any items<p>";
?>
</body>
</html>

I hope you find this technique useful - let me know what you think - I can already hear the jaws of Java Jocks dropping!
alberto dot delatorre at gmail dot com 15-Jan-2005 11:41
Other way to make a form with array fields, and use JavaScript features on them, is use both name and id attributes on the field as:

<input type="text" name="myfield[]" id="myfield1"/>
<input type="text" name="myfield[]" id="myfield2"/>
<script language="JavaScript">
document.getElementById("myfield1");
document.getElementById("myfield2");
</script>

This is an easy way to do it. To number the fields, do a simple for structure and you have done.
dreptack at op dot pl 02-Jan-2005 12:37
I needed to post html form through image input element. But my problem was I had to use multiple image-buttons, each one for a single row of form table. Pressing the button was mention to tell script to delete this row from table and also (in the same request) save other data from the form table.
I wrote simple test-script to see what variable I should check for in a script:

I have a html document:

<form action="test.php" method="post">
<input type="image" name="varscalar" src="/images/no.gif" />
<input type="image" name="vararray[12]" src="/images/no.gif" />
</form>

And a php script:
<?php
  if ($_POST) {
    echo "post: <pre>"; print_r($_POST); echo '</pre>';
  }
?>

What I've discovered suprised me a lot!

After hitting on varscalar:

post:
Array
(
    [varscalar_x] => 6
    [varscalar_y] => 7
)

After hitting on upper right corner of vararray:

post:
Array
(
    [vararray] => Array
        (
            [12] => 2
        )

)

This mean when clicking on image-type input element, which name is an array, only y-part of a value is remembered.

The result is the same on: php 4.1.2 on Win98se, php 4.3.9-1 on linux
seec77 at zahav dot net dot il 22-Dec-2004 03:35
Another unfortunate result of appending "[]" to input field names to pass form data in arrays to PHP, is that people will be able to detect you are running PHP. You can tell by the whole documentation section on hiding PHP, that some people might not want the public to know their site is generated with PHP (usually for security reasons), but the "[]" will blow your cover.
So beware! If you are trying to hide PHP, you will have to stay away from passing form data as arrays!
Karen 04-Aug-2004 05:38
I am using code I got from SitePoint that uses stripslashes because of magic quotes...I finally figured out that it kept my html form select multiple field from working correctly even though I was using name="arrName[]" as the field name -- I was only getting the word array as the value, and all the things I tried there was nothing else there. The stripslashes was part of an included include file, so it took me hours to debug.  Hopefully this will help keep others from wasting time.
Jim Granger 18-Jun-2004 10:11
Kenn White wrote:

So for XHTML strict, the bottom line:
 1. form, use id, not name
 2. input, use id if you can, but if you need to use bracketed notation (for example, passing PHP arrays), i.e., foo[], you *MUST* use name for XHTML strict validation.

I don't think they are going to deprecate name entirely. For one thing, to be of any use, radio boxes and occasionally checkboxes must have the same identifying mark, in this case a name. By the rules of the DTD, id's MUST be unique. In that respect, it is probably better to not use id in input elements at all.

Of course, it's a good idea to use ids as sparingly as possible.
ppmm at wuxinan dot net 13-Jun-2004 04:11
3. How do I create arrays in a HTML <form>?

The feature is nice in the sense of simplifying programming. However, this does have side-effect. Look at this URL below:

http://www.php.net/source.php?url[]=/index.php

As a common viewpoint, exposing the absolute filesystem path in the webpage is always a bad thing. I reported this problem at bugs.php.net a few days before and I get a response saying "it's up to programmers". I think it's fair, however, webmaster should really learn to check the variables at the beginning of the script. In the above case, the PHP script should at least check like this:

if (!is_string(url)) die("with some error message");

As what I experienced, many PHP-based websites have this problem. I would think a perfect solution is that PHP does not do this automatic parsing, and when a PHP script expects an array to be posted, they would do something like

parse_http_array($_GET, "url");

only after this point, $_GET['url']) exists. Before this statement, only $_GET['url[]'] is available. Well, I am kind of too demanding I guess, but what I really intended to say is that webmaster should know this problem.
vlad at vkelman dot com 04-Jun-2004 07:04
"4.  How do I get all the results from a select multiple HTML tag?"

I think that behavior of PHP which forces to use [] after a name of 'select' control with multiple attribute specified is very unfortunate. I understand it comes from old times when registerglobals = on was commonly used. But it creates incompatibility between PHP and ASP or other server-side scripting languages. The same HTML page with 'select' control cannot post to PHP and ASP server pages, because ASP does not require [] and automatically recognize when arrays are posted.
Kenn White kennwhite dot nospam at hotmail dot com 13-Mar-2004 08:18
Concerning XHTML Strict and array notation in forms, hopefully the information below will be useful:

If I have a form, name="f", and, say, an input text box, name="user_data[Password]", then in Javascript, to reference it I would do something like:

var foo = f['user_data[Password]'].value;

Now, say that in making the switch to XHTML strict, I decide to fully embrace standards compliance, and change my form to id="f", and the input text box to id="user_data[Password]"

Because these have id instead of name, I discover, that all my javascript validation routines just broke.  It seems that I have to now change all my js code to something like:

document.getElementById( 'user_data[Password]' ).focus();

I test this on all the major modern browsers, and it works well.  I'm thinking, Great!  Until I try to validate said page.  It turns out that the bracket characters are invalid in id attributes.  Ack!  So I read this thread:

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=
UTF-8&th=78dea36fd65d9bbe&seekm=
pqx99.19%24006.13377%40news.ca.inter.net#link11
(link needs to be spliced, sorry)

What does this mean, I start asking myself?  Do I have to abandon my goal to migrate to XHTML strict?  Transitional seems so unsatisfying.  And why bother with a technique that seems to work on most browsers, if it's broken.  Alas, there is hope.

But then I read http://www.w3.org/TR/xhtml1/#h-4.10 carefully.  It says "name" is deprecated as a form attribute, but *NOT* specifically as an attribute in form *elements*.  It seems my solution is to use "id" for the form itself, but I can legally use "name" for the individual form components, such as select and text input boxes.  I get the impression that "name" as an attribute is eventually going away completely, but in extensive testing using the W3C validator, it passes "name" on form components, as long as "id" (or, strangely, nothing) is used to denote the form itself.

So for XHTML strict, the bottom line:
 1. form, use id, not name
 2. input, use id if you can, but if you need to use bracketed notation (for example, passing PHP arrays), i.e., foo[], you *MUST* use name for XHTML strict validation.

-kenn

kennwhite.nospam@hotmail.com
davis at risingtiger dot net 09-Jan-2004 12:14
I thought this might be useful to fellow PHP heads like myself out there.

I recently came across a need to transfer full fledged mutli-dimensional arrays from PHP to JAVASCRIPT.

So here it is and hopefuly good things come from it.

<?php
function phparray_jscript($array, $jsarray)
{
    function loop_through($array,$dimen,$localarray)
    {
        foreach($array as $key => $value)
        {
            if(is_array($value))
            {
                echo ($localarray.$dimen."[\"$key\"] = new Array();\n");
                loop_through($value,($dimen."[\"".$key."\"]"),$localarray);
            }
            else
            {
                echo ($localarray.$dimen."[\"$key\"] = \"$value\";\n");
            }
        }
    }

    echo "<script language=\"Javascript1.1\">\n";
    echo "var $jsarray = new Array();\n";
    loop_through($array,"",$jsarray);
    echo "</script>";
}
?>
email at njschedules dot com 18-Oct-2003 09:13
If you try to include an XHTML document in a PHP document, you may be including this:

<?xml version="1.0" encoding="iso-8859-1"?>

which would, of course, be read as PHP code. To avoid this problem, use:

<?php echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"; ?>

Hope I can save you from those nasty warning messages :)
03-Oct-2003 03:25
Responding to the suggestion for using this line:

<form onSubmit="selection.name=selection.name + '[]'">

This did not work for me.  I had to make a function makeArray:

function makeArray(selectBox)
{
selectBox.name=selectBox.name + "[]";
}

Then, in the submit button, add this:

onClick='makeArray(this.form.selection)'

I couldn't get anything else to work.

--Rafi
jasonpb at bellsouth dot net 29-Sep-2003 11:29
Another good way for passing javascript to php without having to have a page reload is to use an img tag.

(example)
Add this where you want to collect the vars from
This can also be a .html page
<script language="javascript">
<!--//
// Define variables
if (navigator.appname != 'Netscape') {color= "color="+screen.colorDepth+"&";}
else {color = "color="+screen.pixelDepth+"&";}
avail = "avail="+screen.availwidth+"x"+screen.availheight+"&";
res = "res="+screen.width+"x"+screen.height;
isize = '" width="1" height="1" border="0"';
// Generate img tag
img = '<img name="img"
src="javascript.php?'+color+avail+res+isize+'">';
//Print it to browser
document.write(img);
//-->
</script>

Now you have the javascript vars passed along to the javascript.php page, all thats left is to add a couple lines of php code to gather the info up.

(example)
<?
// Get the vars from the javascript
$res = $_GET['res'];
$avail_res = $_GET['avail'];
$color_depth = $_GET['color'];
// Do something with the info
echo "You Screen's Resolution is $res, Your Available Screen Resolution is $avail_res, and the Color Depth on your screen is $color_depth.";
?>
Thats it!!
Hope it may help someone!
martellare at hotmail dot com 15-Mar-2003 12:28
I do not think you are right about not being able to specify something for the value attribute, but I can see where you would have thought it would fail:

A fair warning about testing to see if a variable exists...
when it comes to strings, the values '' and '0' are interpreted as false when tested this way...

<?php
if ($string) { ... }  //false for $string == '' || $string == '0'
?>

The best practice for testing to see if you received a variable from the form (which in the case of a checkbox, only happens when it is checked) is to test using this...

<?php
if ( isSet($string) ) { ... } //true if and only if the variable is set
?>

The function tests to see if the variable has been set, regardless of its contents.

By the way, if anyone's curious, when you do make a checkbox without specifying the value attribute, the value sent from the form for that checkbox becomes 'on'.  (That's for HTML in general, not PHP-specific).
martellare at hotmail dot com 26-Nov-2002 11:25
A JavaScript Note: Using element indexes to reference form elements can cause problems when you want to add new elements to your form; it can shift the indexes of the elements that are already there.

For example, You've got an array of checkboxes that exist at the beginning of a form:
===================

<FORM>
    <INPUT type="checkbox" name="fruits[]" value="apple">apple
    <INPUT type="checkbox" name="fruits[]" value="orange">orange
    <INPUT type="checkbox" name="fruits[]" value="banana">banana
</FORM>

===================
... These elements could be referenced in JavaScript like so:
===================

<SCRIPT language="JavaScript" type="text/javascript">
<!--
    var index = 0; //could be 1 or 2 as well
    alert(document.forms[0].elements[index]);
//-->
</SCRIPT>

===================
However, if you added a new textbox before these elements, the checkboxes indexes become 1 - 3 instead of 0 - 2;  That can mess up what ever code you create depending on those indexes.

Instead, try referencing your html arrays in JavaScript this way.  I know it works in Netscape 4 & IE 6, I hope it to some extent is universal...
===================

<SCRIPT language="JavaScript" type="text/javascript">
<!--
    var message = "";
    for (var i = 0; i < document.forms[0].elements['fruits[]'].length; i++)
    {
        message += "events[" + i + "]: " + document.forms[0].elements['fruits[]'][i].value + "\n";
    }
    alert(message);
//-->
</SCRIPT>

===================
karatidt at web dot de 17-Nov-2002 12:57
this code selects all elements with javascript
and hands them over to an array in php *sorry my english is not good*

javascript:

<script language="JavaScript">
<!--
function SelectAll(combo)
 {
   for (var i=0;i<combo.options.length;i++)
    {
      combo.options[i].selected=true;
    }
 }
//-->
</script>

html code:
<form name="form" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<select name="auswahl[]" size="10" multiple>
<option value="bill@ms.com">Bill Gates</option>
<option value="bill@unemployed.com">Bill Clinton</option>
<option value="bart@brat.com">Bart Simpson</option>
<option value="oj@free.com">OJ Simpson</option>
<option value="j@nbc.com">Jay Leno</option>
</select>

<input type="submit" name="submit1"  value="OK" onclick="SelectAll(document.form.elements['auswahl[]'])">
</form>

php code:

$auswahl = $_POST["auswahl"];

foreach ($auswahl as $value)
    {
        echo $value."<br>";
    }
bas at cipherware dot nospam dot com 17-Oct-2002 09:52
Ad 3. "How do I create arrays in a HTML <form>?":

You may have problems to access form elements, which have [] in their name, from JavaScript. The following syntax works in IE and Mozilla (Netscape).

index = 0;
theForm = document.forms[0];
theTextField = theForm['elementName[]'][index];
hjncom at hjncom dot net 25-May-2002 03:30
I think '[' and ']' are valid characters for name attributes.

http://www.w3.org/TR/html401/interact/forms.html#h-17.4
-> InputType of 'name' attribute is 'CDATA'(not 'NAME' type)

http://www.w3.org/TR/html401/types.html#h-6.2
-> about CDATA('name' attribute is not 'NAME' type!)
...CDATA is a sequence of characters from the document character set and may include character entities...

http://www.w3.org/TR/html401/sgml/entities.html
--> about character entity references in HTML 4
([ - &#91, ] - &#93)
Хэширование паролей
PHP и COM
ЧАВО


PHP и COM

PHP может быть использован для доступа к COM и DCOM объектам на Win32 платформах.

  1. Я собрал DLL для кое-каких вычислений. Можно ли запустить эту DLL из PHP?
  2. Что значит 'Unsupported variant type: xxxx (0xxxxx)'?
  3. Возможно ли манипулирование визуальными объектами в PHP?
  4. Могу ли я сохранять COM объекты в сессии?
  5. Как я могу поймать COM ошибки?
  6. Можно ли генерировать DLL файлы из PHP скриптов как это можно делать в Perl?
  7. Что значит 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?
  8. Как можно запускать COM объекты с удалённого сервера?
  9. Я получаю 'DCOM is disabled in C:\path...\scriptname.php on line 6', что делать?
  10. Возможно ли с помощью PHP загрузить/манипулировать ActiveX объектом на странице?
  11. Возможно ли получить выполняющийся экземпляр компонента?
  12. Есть ли способ обработать событие, посланное COM объектом?
  13. У меня возникают проблемы при попытке вызвать метод COM объекта, который предоставляет более чем один интерфейс. Что я могу сделать?
  14. Значит PHP работает с COM, как насчёт COM+?
  15. Если PHP может манипулировать COM объектами, можно ли представить себе использование MTS для управления ресурсами компонентов в соединении с PHP?
Я собрал DLL для кое-каких вычислений. Можно ли запустить эту DLL из PHP?

Если это простая DLL, то пока ещё нет возможности вызвать её из PHP. Если DLL содержит COM сервер, то вы можете получить доступ к ней, если она реализует интерфейс IDispatch.

Что значит 'Unsupported variant type: xxxx (0xxxxx)'?

Существуют дюжины VARIANT типов и их комбинаций. Большинство из них уже поддерживаются, но несколько всё ещё не реализованы. Массивы поддерживаются не полностью. Только одномерные индексированные массивы могут передаваться между PHP и COM. Если вы обнаружите неподдерживаемые типы, пожалуйста, сообщите о них как об ошибке (если это ещё не сделано) и предоставьте всю доступную информацию.

Возможно ли манипулирование визуальными объектами в PHP?

В общем да, но так как PHP в основном используется как скриптовый язык для web и выполняется в контексте web сервера, то визуальные объекты никогда не появятся на рабочем столе (desktop) сервера. Если вы используете PHP как скрипт для приложений, например в связке с PHP-GTK, тогда нет ограничений на доступ и манипулирование визуальными объектами через COM.

Могу ли я сохранять COM объекты в сессии?

Нет, не можете. Так как экземпляры COM объектов рассматриваются как ресурсы, то они доступны только в контексте одного скрипта.

Как я могу поймать COM ошибки?

В PHP 5 COM расширение возбуждает исключение com_exception, которое вы можете перехватить и затем проверить поле code для того, чтобы определить что делать дальше.

В PHP 4 поймать COM ошибки средствами, отличными от тех, что предлагает сам PHP (@, track_errors, ...) невозможно.

Можно ли генерировать DLL файлы из PHP скриптов как это можно делать в Perl?

Нет, к сожалению такое средство недоступно для PHP.

Что значит 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?

Эта ошибка может возникнуть по разным причинам:

  • неправильный CLSID
  • отсутствует запрошенная DLL
  • запрошенный компонент не реализует интерфейс IDispatch

Как можно запускать COM объекты с удалённого сервера?

Точно так же как вы запускаете локальные объекты. Вам только надо передать IP удалённой машины как второй параметер COM конструктора.

Убедитесь, что в вашем php.ini вы установили com.allow_dcom =TRUE

Я получаю 'DCOM is disabled in C:\path...\scriptname.php on line 6', что делать?

Отредактируйте ваш php.ini и установите com.allow_dcom =TRUE.

Возможно ли с помощью PHP загрузить/манипулировать ActiveX объектом на странице?

PHP здесь не причём. ActiveX объекты загружаются на стороне клиента, если они были запрошены из HTML документа. Связи с PHP скриптом нет и, следовательно, прямое взаимодействие с серверной стороной невозможно.

Возможно ли получить выполняющийся экземпляр компонента?

Это возможно с помощью моникеров. Если вы хотите получить несколько ссылок на один и тот же экземпляр Word, вы можете создать этот экземпляр как показано:

<?php
$word = new COM("C:\docs\word.doc");
?>

Это создаст новый экземпляр, если нет доступного выполняющегося экземпляра или будет возвращена ссылка на выполняющийся экземпляр, если таковой доступен.

Есть ли способ обработать событие, посланное COM объектом?

Используя com_event_sink() вы можете определить приёмник события и привязать его. Вы можете заставить PHP сгенерировать скелет класса приёмника событий, используя com_print_typeinfo().

У меня возникают проблемы при попытке вызвать метод COM объекта, который предоставляет более чем один интерфейс. Что я могу сделать?

Ответ так же прост как и неудовлетворителен. Не знаю точно, но думаю, что вы не можете ничего сделать. Если у кого-то есть точная информация по этому вопросу, пожалуйста, дайте » мне знать :)

Значит PHP работает с COM, как насчёт COM+?

COM+ расширяет COM, предоставляя систему для управления компонентами через MTS и MSMQ, но здесь нет ничего особенного, что PHP должен поддерживать для использования таких компонент.

Если PHP может манипулировать COM объектами, можно ли представить себе использование MTS для управления ресурсами компонентов в соединении с PHP?

Сам PHP ещё не обрабатывает транзакции. Таким образом, если возникает ошибка, откат не инициируется. Если вы используете компоненты, поддерживающие транзакции, вам будет необходимо реализовать управление транзакциями самим.

User Contributed Notes

microtrash at at gmail dot com 09-Jul-2008 11:29
In reference to question 1:

On one project I had a dll that exposed certain functions I wished to call from within PHP.  I created a PHP Module which had a matching function for each in the DLL.  The PHP Module did no processing, merely served as an adapter for the original DLL.
codeslinger at compsalot dot com 27-Jan-2007 05:18
in response to item #1 above:  "If this is a simple DLL there is no way yet to run it from PHP."

Answer: There are several different packages/add-ons to php that enable low level access to the windows api. One of the most popular of these packages is available at http://www.winbinder.org

Winbinder does have the ability to load a dll and call it's functions.  Winbinder also provides a large set of windows apis for creating windows and controls.  This is useful for creating stand-alone desktop apps.  It is a possible alternative to php-gtk.

I've had mixed results with Winbinder, some things work very well, others are buggy; source code is available.  It's worth a look, Evaluate carefully.
17-Jul-2005 04:56
Re: The Windows English CHM Sample with MS Word Automation.

I see that $Word->Release() is called after $Word->Quit().
This seems to be erroneous. Actually, $Word->Release() should not have to be called if proper COM garbage collection is taking place. Release() is a C++ construction not used in either Visual Basic or VBScript or even MS-JScript. Just to be sure, however, I ran the sample through php.exe (5.04 CLI on Windows XP SP1 with Office 2003) and got a RPC failed error on the line containing $Word->Release(). The rest of the sample works fine, and the results are as expected. So, I propose 2 scenarios:
      1.There is a problem with the documentation (more likely).
      2.There is a problem with PHP504 itself, as this problem is reproduced with any COM Automation call, not just Word.
jeanpierre dot vincent at gmail dot com 03-Feb-2005 06:56
Be careful with function com_event_sink(), it doesn't totally work : when catching events, all parameters given to your callback function have the same value as the last one => see bug http://bugs.php.net/bug.php?id=31040
junk.ghost@virgin dOtt net 05-Oct-2004 09:27
It may be obvious to everyone else but...

If you want to write your own COM DLL in MSVC++6 and you want to pass it a string, you need the following in your .idl file:

HRESULT function_name([in] BSTR parameter_name,
                      [retval, out] BSTR * retval);

retval is the result of your function as a string to be passed back.

BSTR is an unsigned short *, so if you want to use your string with STL string etc. you may need to convert parameters to and from char *.

The burden of my message is that from PHP

$comThing = new COM("comThing.comThing");
print $comThing->function_name("Jeremy");

Jeremy will be marshalled as wide chars, which match BSTR.
ALAN at DONTSPAMMEE;HOGAR dot COM 16-Aug-2002 09:39
ONE SAMPLE USING MS-XML3 PARSER ON WINDOWS
<?
  $xml= new COM("Microsoft.XMLDOM");
  $xml->async=false;
  $xml->load("STYLE.xml");
  $xsl = new COM("Microsoft.XMLDOM");
  $xsl->async=false;
  $xsl->load("STYLE.xsl");
  $response=$xml->transformNode($xsl);
  print $response;
?>
PHP и HTML
PHP и другие языки
ЧАВО


PHP и другие языки

PHP самый лучший язык для web программирования, а как насчёт других языков?

  1. PHP против ASP?
  2. PHP против Cold Fusion?
  3. PHP против Perl?
PHP против ASP?

На самом деле, ASP сам по себе языком не является, это акроним для Active Server Pages, в действительности для программирования с ASP используется Visual Basic Script, JScript и C#, среди прочих. Наибольшим недостатком ASP является то, что это частная система и по родному используется только на Microsoft Internet Information Server (IIS). Это ограничивает его доступность только для Win32 серверов. Существует пара проектов в работе, которые позволяют ASP выполняться в других окружениях и на других web серверах: » InstantASP от » Halcyon (коммерческий), Chili!Soft ASP от » Chili!Soft (коммерческий), и » Mono (опенсорс). Считается, что ASP медленнее и более громоздкий чем PHP, а также менее стабильный. Некоторыми плюсами ASP является то, что так как в нём в основном используется VBScript, то подхватить язык относительно легко, если вы уже знаете как программировать в Visual Basic. Поддержка ASP по умолчанию включена в IIS, что упрощает его установку и запуск. Однако, встроенные в ASP компоненты очень ограничены, поэтому если вам требуются "продвинутые" возможности, такие как взаимодействие с FTP серверами, вам придётся покупать дополнительные компоненты.

PHP против Cold Fusion?

В общем считается, что PHP быстрее и более эффективен для сложных программных задач и для пробования новых идей. Также на PHP обычно ссылаются как на более стабильный и менее требовательный к ресурсам. Cold Fusion имеет лучшую обработку ошибок, абстракцию баз данных и разбор дат, хотя в PHP 4 тоже уделено внимание абстракции баз данных. Отличительной сильной стороной Cold Fusion является его превосходная поисковая система, но многие резонно аргументируют, что поисковая система это не то, что должно быть включено в скриптовый язык для веб. PHP работает почти на каждой существующей платформе, Cold Fusion доступен только для Windows, Solaris, Linux, MacOS и AIX. Cold Fusion имеет хорошую IDE и в общем в нём легче начинать, тогда как PHP вначале требует больше знаний по программированию. Cold Fusion был спроектирован в расчёте на не программистов, когда PHP сосредотачивается на программистах.

PHP против Perl?

Наибольшее преимущество PHP перед Perl это то, что PHP был спроектирован для написания скриптов для веб, в то время, как Perl был создан для более широкого круга задач и поэтому может быть очень сложным. Гибкость/сложность Perl усложняет совместную работу разработчиков с разным уровнем квалификации. PHP имеет менее запутанный и более строгий формат без ущерба для гибкости. PHP проще интегрировать в существующий HTML, чем Perl. По большому счету, PHP имеет почти что все 'хорошие' функциональные возможности Perl: конструкции, синтаксис и так далее, не становясь таким же сложным, каким может быть Perl. Даже командная строка PHP (CLI) достаточно мощна для выполнения сложных задач, таких, для которых традиционно использовался Perl. Perl довольно испытанный и точный язык, он существует с конца восьмидесятых, но PHP довольно быстро созрел, и продолжает делать фантастические успехи.

User Contributed Notes

cs dot abdullah at hotmail dot com 05-Nov-2010 03:57
I have taken ZCE (Zend Certified Engineer) before couple of years and I am working in the field of Compiler Construction. However, from my opinion PHP is the best language that is used to design web solution because it extendable language. As a programmer in C, I found PHP internally as easy as externally.

PHP is the best ever !.
steve at caralan dot com 09-Aug-2009 04:25
Comparison of programming languages is a pretty spurious exercise, but here goes:

I have programmed with Perl for many years and have yet to find anything I want to do that Perl can't deliver. It is justifiably described as the "Swiss Army Chainsaw" of programming.

I am much less experienced with PHP but have found it to be relatively lightweight. PHP isn't Perl.

However, in my opinion PHP is much easier to work with and does what it's designed to do more elegantly than Perl. PHP is usually the best option within the areas where PHP is designed to excel.

I wouldn't want to be without either tool. Having both is the best solution.
tony 16-Apr-2008 01:01
The paragraph on "Cold Fusion" (it's actually "ColdFusion", by the way), and in the included link is so woefully inaccurate and out of date, that it's not even funny.
I'm not going to debate the the pros and cons of each language, but PLEASE -- let people be informed by information that's more based in reality.
fabioissamu at yahoo dot com 21-Feb-2007 11:48
Tim Bray, who - among many other things - co-edited the XML 1.0 and XML namespace definitions, was invited to the International PHP Conference to give a keynote about "How to combine PHP technology with Java based on Enterprise Systems". I had the pleasure to talk with him and I like his spirit. During his keynote, he presented some very interesting comparison between the popular development "frameworks" PHP, Ruby on Rails (RoR, Rails) and Java

http://www.tbray.org/talks/php.de.pdf

in that he show PHP the first in scalability
bb at servertje dot nl 06-Jun-2006 04:58
I think it's worth to mention that it's incredible easy to write a PHP module in C and use it in your scripts with the speed of true machine language. All the PHP API functions are there and there's plenty of examples due to the many existing modules and their source codes.

The advantage here is programming the relative simple business logic in PHP and programming those core functions that really require speed in PHP modules, if you really have to.
Compiled Java classes act more like optimised / confuscated scripts and still needs an interpreter in the end.

The only disadvantage about PHP is the somewhat quirky language and inconsistant (and long) function names, which makes it hard for newbies to learn from scratch.
good dot midget at gmail dot com 16-Dec-2005 02:49
I think there's been a slight overlook within the comments about PHP's model for OOP.

Firstly, I was absolutely thrilled to see the enhancements of PHP5.  I've been using PHP for... gees...  a long time now.  But what's always been lacking has been fully implemented OOP.  Now, granted, there are ways to do things like method overloading, but c`mon.... really...  Now, I know the argument is that PHP is related to the web - not application development.  I believe that the PHP community today suffers from this mentality.  The fact of the matter is that the world is rapidly shifting towards an SOA mentality, and rich applications presented through the web.  In light of this PHP should be regarded as valuable tool for application development.

I would say that while PHP has tremendous strength, it equally lacks in its implementation of OOP requirements.  I find that most suggested "design patterns" are weak workarounds in PHP.  C# (.NET), Java -- hell even ActionScript have a fully OO implementation allowing effective implementation of recognized design patterns.  Futhermore, due to PHP's lack of OO support, true collaborative team development is greatly hindered.  This is particularly evidenced in the lack of strict type casting.  Legit development teams rely on this to effectively lock down their interfaces, implement error handling, etc etc etc.

I'm very dissappointed to see that languages (like C#), sponsored by the likes of M$ have been able to develop such mature OO languages so rapidly, while PHP remains... well... practically in the stone age.

Once these issues are addressed I think we'll see more support of PHP, and less resistance to its place in the enterprise.  Abstraction is a stupid thing to bicker about.  How long does it really take to write a good data abstraction layer - that can be repurposed.  What's more important is the capability of the language.

Hopefully IBM will jump in here and kick things into high gear.  Let's get rid of all the back support and compatabilities for legacy code in favor of maturing the language and increasing its value (and decreasing objections from the enterprise market)
daniel at cedilotte dot com 03-Nov-2005 09:58
Another thing related to PHP vs ASP.

In PHP, it's possible to make sure your Include files are not included more than once. Where as in ASP/VBScript, you can't due to the fact that SSI is processed before the VB code.
ahumeniy at vtr dot net 21-May-2005 09:43
I agree with Web Consultant concerning to ASP.net and .net framework. It's necessary an update to this article.

Currently, ASP.net is at the same level than PHP and, i would say that is better because i can choose what language to use (PHP is also available for .net by the way).

Thanks to it's common language runtime, .net technology allows the programer to choice wich language to use.

Also, ASP.net can make things that PHP don't such as manipulate the server's filesystem (y use that technique in the database system of my own CMS made with .net) and not only the files that are inside the website. Also, ASP.net make a lot easier for programmers to make programs that communicate with the web site without needing of a browser (I use that technique in a small application that allows my site's users to "navigate" the site and also send and receive personal messages a lot faster than with the web)

PHP needs to get improved to be better than ASP.net. I hope that the better wins
symcbean 20-Feb-2005 03:00
I really must take issue with (Cash at nospam dot thesilverside dot com)'s comments regarding enterprise applications and PHP.

Yes, PHP is an interpreted language (but...PHP Accelerator? also you can write caching *with* PHP, also checkout http://shootout.alioth.debian.org/, and have you seen the benchmarks for Pharrot?). Adding more tiers into your application is a recipe for disaster since it reduces scalability by creating bottlenecks/crossovers and has a big impact on transparency. I'll admit that for a very few applications, then server hardware is more expensive than developer time - like if you're turning around more than 500000 hits/hour, then it may work out cheaper to develop in 'C' with half the servers than PHP, but this is far from the sort of volume I've seen on an enterprise application. There's a lot been written elsewhere on PHP and scalability which I won't repeat here.

There are issues with using PHP for this kind of application. Firstly managment of privilege - but that applies (AFAIK) to any web-based system. There's also the problem of namespace collisions in large apps.

Since I regularly develop embedded applications with PHP using HTTP as the communications substrate for transactions spanning 6 or more origanisations, I'd like to know whay I shouldn't be using PHP / processing synchronously, and how I can create a near real-time system without synchronous operation.

It'd be a sad world to live in where there was only one programming language/methodoly/idiom - diversity is a great thing. Java provides beans and struts, Coldfusion provides fast development and .NET....(suggestions please). PHP comes closest to solving my problems, many of which are very much in the enterprise applications domain.
Web Consultant Since 1994 19-Jan-2005 11:26
...Well, all I can say about ASP.NET and the .Net frameworks is that rather than adopt them we decided to switch all of our development to PHP and other open-source tools. We simply got tired of all the churing of the development platform from $soft: things like changing API's during final betas, undocumented api's etc.

Ive programmed in C, C++, VB, ASP (since the original beta in 1995) and ASP.Net, Com, Com+, .Net Frameworks and in C("sharp"). The fact of the matter is that most of these new and "improved" development tools dont save much, if any money, and are mostly, unnecessary. We have found PHP to be an excellent replacement for similar $soft tools and technologies for web development.

Its true that there is a bit more code required to supplement things that $soft and others give you for a price, but the bottom line is that most of these things are not very difficult to do properly. In our business there is a huge risk from not having access to source code and we simply cant be held hostage by a third party company: when you add up the dollar value of this risk for our business it far exceeds the few dollars we need to spend in extra supplemental coding - which is done once so its a one-time cost.
berjoza at bigmir dot net 26-Mar-2004 08:25
How about PHP and JAVA?
You can use PHP vs JAVA in following order
  1. In php.ini file add
    - extension=php_java.dll
    -
      [Java]
         java.class.path   =  "c:\usr\local\php\extensions\php_java.jar"
         java.home       =  "c:\usr\local\j2sdk1.4.2_03"
         java.library       =  "c:\usr\local\j2sdk1.4.2_03\jre\bin\server\jvm.dll"
         java.library.path =  "c:\usr\local\php\extensions"
Cash at nospam dot thesilverside dot com 11-Jan-2004 11:12
To correctly utilize PHP in enterprise applications, one may want to bear in mind that if PHP is being used synchronously, it should be kept to the presentation layer only. Other languages that were previously mentioned througout the notes above (such as Perl, Java, and the .NET CLR... if you're on Windows) would be more appropriately used within the business process and data access layers. If you really want to maintain higher speed on presentation, then perhaps one would want to incorporate asynchronous instead of synchronous processing into the presentation layer of your application.

In other words, if you are using a connected data source, such as a SQL database, try shifting the processing time back a layer by providing a medium interval return from the data source to an XML file that the web service can access. This will allow your web presentation layer to load the data significantly faster than it is now. It will also give more resources back to PHP and your web service processes.

If you still cannot get the PHP processes back up to par, then you should consider using PHP as an asynchronous page constructor, thus shifting PHP itself back to the business process layer and allowing the web service (Apache, IIS, Netscape, etc.) to return HTML files instead.

Aside from page caching, (to my knowledge) you simply cannot get any faster than that.
Tricrokra 26-Oct-2003 05:28
I have to note that a very big advantage of PHP over ASP is that PHP has much easier commands...

Take openening of a file in ASP...
First create a file object... I put this into a function because the line is simpy to long and I called it "Init fileobject"

<%
Initfileobject     'The Sub I created in order not to type that idot line all the time
Set Fil = FileObject.OpenTextFile(Server.MapPath("data")&"\datafile")
datavar = Fil.ReadLine
CloseFile Fil
Set Fil = Nothing
Set FileObject = Nothing
%>

Why always those objects...

The same thing in PHP

<?php
$fil = fopen("data/datafile","r");
$datavar = fgets($fil);
fclose($fil);
?>

That's all...

And that while VBScript is based on BASIC (BEGINNERS Allpurpose Symbolic Instruction Code)...

I code too shortly in PHP to make a full analysis yet, but the complex object structues of VBScript is something I really put in question, PHP has a much easier syntax when it comes to that...

One of the first things I saw was that PHP is based on C, which is one of the hardest programming languages in the world. That makes the syntax of for example the "for" statement less to my desire, which I like better in VBScript (ASP)... If you are an experienced C or C++ programmer, I think PHP makes automaticly the best choice out of PHP vs ASP.

But I did find out in only 1 hour that the syntax of PHP gives you much less typing than ASP, that is a fact. I think that for the rest the pick of language is pretty personal.

When it comes to stability. ASP servers crash very much. I don't think ASP itself is the evil one in this. ASP only runs on Windows servers, and we all know how much Windows crashes. I truely believe that also picks a part of the puzzle...
atoi_monte at hotmail dot com 24-Jul-2003 11:34
---------------------------------
QUOTE:
This is a comparison between PHP and Java/JSP:

http://www.tek271.com/articles/JavaOrPhp.html

Any comments?
---------------------------------

Probably the worst comparison I have seen in a long while. They penalize PHP for class scope and global variables and such.

1)  While that may be relevant for APPLICATION programming, it's totally irrelevant for web programming.  Web programming, imho, is about being able to get a quick, organized solution out QUICKLY so that it can be maintained and dynamic. The global variables, lack of package system, and loosely typed nature of PHP makes it easier to use and get stuff done in, while the syntax is still clean and easy to maintain. On applications programming.. yes.. Java is a better solution. But for web programming, JSP doesn't hold a candle to PHP, imo.

2) With PHP 5, I would just like to remind everyone, there will be a lot of concessions to Java programmers (mostly to lure C++ hackers to PHP over C# or Java) like constants, abstract stuff, and access control. While it won't impact the programming that much ( you can still code just like you always have) you can at least feel more like C++ when we finally get to use PHP5.

dan
anonymous at coward dot com 09-Apr-2003 12:23
As far as I can see, Web Consultant apparently missed the topic, which was "3. PHP vs. Cold Fusion", not "PHP vs. compiled languages (JSP,ASP.NET, and ColdFusion MX)".

We probably all agree that PHP, compared to what ColdFusion was at the time of the writing of that part of this FAQ, is far more capable of complex scripts, and also generally outperforms ColdFusion in similar tasks, too.

I'm not familiar with ColdFusion MX, but as it sounds like it's a rather new product, I would draw the conclusion that it isn't what the writer of this FAQ had in mind when addressing PHP vs. ColdFusion comparisons.

Surely, Web Consultant must have made the same conclusion based on his discovery that the FAQ is outdated and thus should be updated.

cheers.
Web Consultant 04-Apr-2003 01:39
Sounds like this FAQ needs to be updated.

How about ASP.NET and .NET Framework?
How about ColdFusion MX?

PHP has limited/None out-of-the-box database integration with popular RDBMS(Oracle,SQL Server), integration with COM and to Java Servlet and Enterprise Javabeans, that alone make ColdFusion MX and ASP.NET an attractive development platform.

PHP might be good for developing non complex websites for no cost; however when you are developing enterprise web  systems that have to integrate with many different flavor of sources .. php does not have the out-of-the-box functionality for the above needs.

"PHP is commonly said to be faster and more efficient for complex programming tasks and trying out new ideas. PHP is generally referred to as more stable and less resource intensive as well. "

I like to see proof of this statement. How is a interpreted  languge faster and less resource intensive than a compiled languge(JSP,ASP.NET, and ColdFusion MX)?

ColdFusion MX Server cost about $1300, but the total built in functionality and versatility makes it a worthwhile. If you start out with PHP, ask yourself how much time and money you have in developing the source to provide the functionality you are looking for.

PHP vs ColdFusion MX
http://www.macromedia.com/devnet/mx/coldfusion/articles/php_cfmx.html
phalcomb at arbolnet dot com 05-Feb-2003 06:29
My experience with ASP and PHP is about equal, I think they both serve equally as good of a purpose depending on what the programmer is trying to do. I do like the syntax of PHP a lot and the speed of it is great, although the client/server interactivity of ASP with Windows and MAC clients is what I'm excited to see grow with future versions of PHP.
mavi_br at someplace dot com 13-Dec-2002 05:02
I've been working with PHP, JSP, Java and CFM for 2 years now.
I can tell that for web development only, php is not nearly as good as cfm on speed, on ease to use and on interaction.
On the other hand you just can't do anything very special with CF like opening a socket with the ease of php.
I would say : use what you need for your application, cfm is truly the fastest, as it has a daemon running instead of a per request, plus the ability to cache queries that is awesome.
php is fast but is a pain on some aspects and has loads of bugs.
JSP have almost no bug at all, or at least i did not find any, but it is hard to debug.
Good thing on JSP is that you can write real applications and have perfect interaction by using classes, plus it is much more of a serious language.The only problem is that you take at least twice times to make same program on JSP and it is not even close as well documented and easy to use as php.
dir at badblue dot com 25-Sep-2002 09:51
To ahabra,

Very interesting page.  I would ask the following, however as you investigate this topic further... you'll soon become the PHP vs. Java guru.

Your comparisons are interesting and well thought out.  I would also add some higher-level (less computer-science oriented, simply because the task at hand is generating web pages 'on the fly').  As a pure CS language, there is no doubt that Java is superior.  But as a web page generator, I have moved from a Java-centric approach to a PHP approach, leveraging servlets or beans as needed "under the covers".

Therefore, some higher-level things to consider:

1) Compare the complexity of real-world production applications (postnuke.com vs ? in content management, phpbb.com vs. ? in discussion boards, jpgraph vs. ? in graphing).  In my mind, the proof is in the pudding - which technology results in the better, more production-ready applications?  They may be out there for Java - I would just like to know where they are and who is using them.

2) Compare slinging (generation) of markup which is where PHP excels (as it was designed to sling markup - this includes features such as character transformations, variable accessibility, web page captures (see the fopen call which captures a web page in a single function call).  Your point about a string being encapsulated in a string class is somewhat irrelevant if you are a programmer cranking markup.  Embedding object-oriented code into a page can be much more painful (and slower to execute) than leveraging traditional coding techniques.

3) Compare native database and directory support.  Java would have the advantage in generic database access (JDBC) but PHP has the advantage in LDAP support (JNDI has several bugs which we have run into - quite painful) and native database access (e.g., Oracle or MySQL integration).

Overall, well done - and a very popular topic!  It's worth building it out further.
developer at i-space dot org 04-Mar-2002 08:34
If you ever tried to configure a web server for WAP, serving WML content you know it's not an easy job. You can easily make dynamic WML pages for mobile phone users with PHP. All the options and extras from DB+PHP oriented web-site can easily be transfomed into a WAP version of your site. With a single line - Header("Content-type: text/vnd.wap.wml"); you can be in another "mobile" dimension :). Take all you need ... and even more.
PHP и COM
Переход с PHP 4 на PHP 5
ЧАВО


Переход с PHP 4 на PHP 5

Этот раздел поможет вам при переходе с PHP 4 на PHP 5.

  1. Переход с PHP 4 на PHP 5
  2. Работает ли MySQL в PHP 5? Похоже, она исчезла?
  3. Я слышал, что PHP 5 имеет полностью новую модель ООП, будет ли мой существующий код работать? Где найти информацию об этих новых возможностях ООП?
  4. Что ещё изменилось в PHP 5 кроме новой модели ООП? Также есть ли отдельная версия этого руководства для PHP 5?
Переход с PHP 4 на PHP 5

Хотя PHP 5 предлагает много новых возможностей, он проектировался для совместимости с ранними версиями PHP насколько это только возможно, с минимумом поломок функционала.

Не забудьте прочитать соответствующее приложение по переходу на PHP 5 в этом руководстве, так как оно содержит еще больше информации на тему мигрирования на PHP 5.

Работает ли MySQL в PHP 5? Похоже, она исчезла?

MySQL поддерживается с единственным изменением в том, что поддержка MySQL более не включена по умолчанию в PHP 5. Это главным образом означает, что PHP по умолчанию не включает опцию --with-mysql в строку для configure, поэтому вам надо сделать это вручную при компиляции PHP. Пользователи Windows должны будут отредактировать php.ini и включить php_mysql.dll DLL, так как эта DLL не существовала ранее в PHP 4, она была просто включена в бинарную версию PHP для Windows.

Также клиентские библиотеки MySQL больше не поставляются с PHP. Более подробно эта тема освещена здесь и для знания деталей установки MySQL обязательно еще прочитайте раздел по MySQL. Пример строки конфигурации: --with-mysql=/usr , в то время как пользователям Windows будет нужна доступная в системе libmySQL.dll.

Я слышал, что PHP 5 имеет полностью новую модель ООП, будет ли мой существующий код работать? Где найти информацию об этих новых возможностях ООП?

Основное изменение в PHP 5 - это изменение в модели ООП, так как PHP 5 теперь использует Zend Engine 2.0. Директива zend.ze1_compatibility_mode включает совместимость с Zend Engine 1.0 (PHP 4).

Новая модель ООП документирована в справочнике языка по ООП и приложении по переходу к ООП.

Что ещё изменилось в PHP 5 кроме новой модели ООП? Также есть ли отдельная версия этого руководства для PHP 5?

Существует несколько других изменений, за подробностями обращайтесь в приложение по переходу на PHP 5. Специальной для PHP 5 версии этого руководства не будет, так как в основном объёме PHP остается всё тем же.

User Contributed Notes

gfrank at neoservers dot com 24-Jun-2007 08:17
To get PHP5 and PHP4 to work at the same time you will also need to change all "php_value", "php_flag", "php_admin_flag", and "php_admin_value" occurences; otherwise, you can't set configuration file settings.
odnowa-sql at o2 dot no-spam pl 29-Apr-2007 05:13
You can run PHP4 and PHP5 as Apache2 modules at the same time. The trick is to hack the sources a little bit.
Change all occurences of application/x-httpd-php (and MIME type for sources) to application/x-httpd-php5 and then add that mime type to apache conf.
PHP и другие языки
Разные вопросы
ЧАВО


Разные вопросы

Некоторые вопросы могут не подходить для других категорий. Вы можете найти их здесь.

  1. Как обращаться со сжатыми bz2 руководствами под Windows?
  2. Что означает & рядом с аргументом в объявлении функции, например asort?
  3. Как обращаться с register_globals?
Как обращаться со сжатыми bz2 руководствами под Windows?

Если у вас нет архиватора для работы с bz2 файлами, то » скачайте утилиту для командной строки от Redhat (пожалуйста, ищите подробности ниже).

Если вы не хотите использовать утилиту командной строки, вы можете попробовать бесплатные средства, такие как » Stuffit Expander, » UltimateZip, » 7-Zip или » Quick Zip. Если у вас есть такие утилиты как » WinRAR или » Power Archiver, то с их помощью вы можете легко распаковать bz2 файлы. Если вы пользуетесь Total Commander (бывший Windows Commander), подключаемый модуль bz2 для этой программы доступен бесплатно с сайта » Total Commander.

Утилита командной строки bzip2 от Redhat:

Пользователи Win2K Sp2 должны взять последнюю версию 1.0.2, пользователи всех других Windows должны взять версию 1.00. После загрузки переименуйте исполняемый файл в bzip2.exe. Для удобства положите его в директорию в вашем пути, например C:\Windows, где C соответствует диску, на котором установлен ваш Windows.

Замечание: lang обозначает ваш язык и x - желаемый формат, например pdf. Чтобы распаковать php_manual_lang.x.bz2, следуйте этим простым инструкциям:

  • откройте окно c командной строкой (command prompt)
  • перейдите в директорию (команда cd), куда вы сохранили скачанный php_manual_lang.x.bz2
  • вызовите bzip2 -d php_manual_lang.x.bz2 для извлечения php_manual_lang.x в ту же директорию

В случае, если вы скачали php_manual_lang.tar.bz2, содержащий множество html файлов, процедура точно такая же. Единственное отличие заключается в том, что вы получили файл php_manual_lang.tar. Известно, что формат tar обрабатывается большинством распространённых архиваторов под Windows, например такими как » WinZip.

Что означает & рядом с аргументом в объявлении функции, например asort()?

Это означает, что аргумент передаётся по ссылке и функция, вероятно, изменит его согласно документации. Таким путём вы можете передать только переменные и вам не обязательно задавать & при вызове функции (и это даже не рекомендуется).

Как обращаться с register_globals?

Для информации по проблемам безопасности, связанных с register_globals, читайте Использование register_globals в главе "Безопасность".

Предпочтительнее использовать superglobals, чем полагаться на то, что register_globals установлена в On.

Если вы пользуетесь виртуальным (shared) хостингом с выключенной register_globals и вам надо использовать некоторые существующие приложения, которые требуют, чтобы эта опция была включена; или вы на каком-либо сервере, где эта возможность включена, но вы хотите эмулировать проблему по безопасности, то возможно вам надо эмулировать противоположную установку с помощью PHP. Всегда лучше сначала спросить, если можно каким-либо образом изменить опцию в конфигурации PHP, но если это невозможно, то вы можете воспользоваться следующими совместимыми кусками кода.

Пример #1 Эмулирование Register Globals

Следующее эмулирует register_globals установленную в On. Если вы меняли директиву variables_order, измените соответственно и $superglobals.

<?php
// Emulate register_globals on
if (!ini_get('register_globals')) {
    $superglobals = array($_SERVER, $_ENV,
        $_FILES, $_COOKIE, $_POST, $_GET);
    if (isset($_SESSION)) {
        array_unshift($superglobals, $_SESSION);
    }
    foreach ($superglobals as $superglobal) {
        extract($superglobal, EXTR_SKIP);
    }
}
?>

Следующее эмулирует register_globals установленную в Off. Помните, что этот код должен вызываться в самом начале вашего скрипта, или после вызова session_start(), если вы используете сессии.

<?php
// Emulate register_globals off
function unregister_GLOBALS()
{
    if (!ini_get('register_globals')) {
        return;
    }

    // Might want to change this perhaps to a nicer error
    if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
        die('GLOBALS overwrite attempt detected');
    }

    // Variables that shouldn't be unset
    $noUnset = array('GLOBALS',  '_GET',
                     '_POST',    '_COOKIE',
                     '_REQUEST', '_SERVER',
                     '_ENV',     '_FILES');

    $input = array_merge($_GET,    $_POST,
                         $_COOKIE, $_SERVER,
                         $_ENV,    $_FILES,
                         isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());

    foreach ($input as $k => $v) {
        if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) {
            unset($GLOBALS[$k]);
        }
    }
}

unregister_GLOBALS();

?>

User Contributed Notes

doerr at apkk dot de 28-Dec-2010 05:41
If you only needed register_globals for get/post variables, the effictive solution for 5.3 is:
  import_request_variables("GPC", "");

But if the skripts relied on session_register() you'll have to do more:
- Replace all variables that appeared after session_register with _SESSION equivalents - so $myvar becomes $_SESSION['myvar']
- Take care if your variables appeared inside strings - 'Hello $user !' works, but 'Hello $_SESSION['user'] !' not - so you have to concatenate the string: 'Hello '.$_SESSION['user'] .' !'
- Session variables in function declarations (for whatever purpose) will not work - keeping the old (local) names will work in most cases.
- Finally, replace the session_register(..) line with session_start()
19-Jul-2005 09:08
using .htaccess file to disable register globals (register_globals)

The syntax for setting an option is:

php_value name value
php_flag name on or off

Example:

php_flag register_globals off
php_value arg_separator.output &amp;

The example turns off register_globals and sets the value of arg_separator.output to &amp; which is preferred rather than the default &.

Note: you can also set boolean options with the php_value directive, the string will be converted to boolean before assignment.

you can also use .htaccess to  turn magic quotes on or off.
Search php.net and you'll find it
markus 18-Jun-2005 03:34
Considering the comment below. I think there's a way to avoid that "problem":

<?php
//
// $starttime is an example of a variable that we might need to define,
// even before, running the "register_globals OFF" emulator below.
//
list($msec, $sec) = explode(' ', microtime());
$starttime = ((float)$msec + (float)$sec);

//
// If register_globals is ON, ensure no unexpected globals are defined.
// ie. We'll try to emulate a register_globals OFF environment.
//
if( (bool)@ini_get('register_globals') )
{
    $superglobals = array($_ENV, $_GET, $_POST, $_COOKIE, $_FILES, $_SERVER);
    if( isset($_SESSION) )
    {
        array_unshift($superglobals, $_SESSION);
    }
    $knownglobals = array(
        //
        // Known PHP Reserved globals and superglobals:
        //
        '_ENV',        'HTTP_ENV_VARS',
        '_GET',        'HTTP_GET_VARS',
        '_POST',    'HTTP_POST_VARS',
        '_COOKIE',    'HTTP_COOKIE_VARS',
        '_FILES',    'HTTP_FILES_VARS',
        '_SERVER',    'HTTP_SERVER_VARS',
        '_SESSION',    'HTTP_SESSION_VARS',
        '_REQUEST',

        //
        // Global variables used by this code snippet:
        //
        'superglobals',
        'knownglobals',
        'superglobal',
        'global',
        'void',

        //
        // Known global variables defined before this code snippet is reached.
        //
        'starttime',
    );
    foreach( $superglobals as $superglobal )
    {
        foreach( $superglobal as $global => $void )
        {
            if( !in_array($global, $knownglobals) )
            {
                unset($GLOBALS[$global]);
            }
        }
    }
}
?>

Note the stuff related to the $_SESSION array depends on whether the PHP session has been started or not. You might want to call session_start() before this point (or set session.auto_start ON).

HTH+ :)
php at REMOVEMEkennel17 dot co dot uk 12-Apr-2005 08:22
Regarding simulating register_globals = off, note that it is impossible to adequately prevent $_SESSION variables from being globalised, as the array (and thus the globals) are created on a call to session_start().  You would therefore have to 'undo' this when you start a session as using it at the start of your script will have no effect.

To avoid potential problems, use a prefix that is unique for all session variables (e.g. 'SESS_'), and only access them via the $_SESSION array.  The prefix ensures that you don't have a naming clash (and therefore a security risk) with any non-session globals.
Переход с PHP 4 на PHP 5
Appendices
ЧАВО


Appendices

  • История PHP и смежных проектов
    • История PHP
    • История смежных с PHP проектов
    • Книги о PHP
    • Публикации, посвященные PHP
  • Переход с PHP 5.3.x на PHP 5.4.x
    • Что изменилось в PHP 5.4.x ?
    • Обратно несовместимые изменения
    • Новые возможности
    • Изменения в модулях SAPI
    • Устаревшие функции и возможности в PHP 5.4.x
    • Измененные функции
    • Новые функции
    • Новые классы и интерфейсы
    • Новые методы
    • Удаленные расширения
    • Другие изменения в расширениях
    • Новые глобальные константы
    • Изменения в обработке INI-файлов
    • Другие изменения
  • Переход c PHP 5.2.x на PHP 5.3.x
    • Что нового в PHP 5.3.x ?
    • Обратно несовместимые изменения
    • Новые возможности
    • Изменения в поддержке Windows
    • Изменения в модулях SAPI
    • Устаревшие функции и возможности в PHP 5.3.x
    • Функции и возможности, которые ранее считались устаревшими, а теперь снова возвращены в PHP 5.3.x
    • Новые параметры
    • Новые функции
    • Новые обертки потоков
    • Новые фильтры потоков
    • Новые константы классов
    • Новые методы
    • Новые расширения
    • Удаленные расширения
    • Другие изменения в расширениях
    • Новые классы
    • Новые глобальные константы
    • Изменение в работе с INI-файлами
    • Другие изменения
  • Переход с PHP 5.1.x на PHP 5.2.x
    • Изменения в PHP 5.2.x
    • Изменения, нарушающие обратную совместимость
    • Новые сообщения об ошибках
    • Изменения в поддержке datetime в PHP
    • Новые параметры
    • Новые функции
    • Новые методы
    • Удалённые расширения
    • Новые расширения
    • Новые классы
    • Новые глобальные константы
    • Новые константы классов
    • Новые конфигурационные параметры INI
    • Сообщения об ошибках
    • Другие улучшения
  • Переход с PHP 5.0.x на PHP 5.1.x
    • Основные возможности PHP 5.1.x
    • Changes in reference handling
    • Reading []
    • Integer values in function parameters
    • Class and object changes
    • Extensions
    • Date/time support
    • Changes in database support
    • Checking for E_STRICT
  • Переход с PHP 4 на PHP 5.0.x
    • Что изменилось в PHP 5.0.x
    • Изменения, повлекшие за собой обратную несовместимость
    • CLI и CGI
    • Миграция конфигурационных файлов
    • Новые функции
    • Новые директивы
    • Базы данных
    • Новая Объектная Модель
    • Сообщения об ошибках
  • Classes and Objects (PHP 4)
    • class
    • extends
    • Constructors
    • Scope Resolution Operator (::)
    • parent
    • Serializing objects - objects in sessions
    • The magic functions __sleep and __wakeup
    • References inside the constructor
    • Comparing objects
  • Отладка в PHP
    • Об отладке в PHP
  • Configure options
    • List of core configure options
  • Директивы php.ini
    • Список директив php.ini
    • Список разделов php.ini
    • Описание встроенных директив php.ini
  • Список/классификация расширений
    • В алфавитном порядке
    • По составу
    • По состоянию
  • Список псевдонимов функций
  • Список зарезервированных слов
    • Список ключевых слов
    • Предопределенные классы
    • Предопределенные константы
  • List of Resource Types
  • Список доступных фильтров
    • Строковые фильтры
    • Преобразовывающие фильтры
    • Компрессионные фильтры
    • Шифрующие фильтры
  • Список поддерживаемых транспортных протоколов
    • Интернет-сокеты: TCP, UDP, SSL, and TLS
    • Unix-сокеты: UNIX и UDG
  • Таблица сравнения типов в PHP
  • Список меток (tokens) парсера
  • Руководство по именованию
    • Глобальное пространство имён
    • Правила
    • Советы
  • Об этом руководстве
    • Форматы
    • О заметках пользователей
    • Как читать определения функции (прототип)
    • Версии PHP, документированные в этом руководстве
    • Как узнать больше о PHP
    • Как помочь в написании документации
    • Как создаются форматы документации
    • Переводы
  • Creative Commons Attribution 3.0
  • Алфавитный список
    • Список функций и методов
    • Список примеров

User Contributed Notes

There are no user contributed notes for this page.
Разные вопросы
История PHP и смежных проектов
Руководство по PHP


История PHP и смежных проектов

Содержание

  • История PHP
  • История смежных с PHP проектов
  • Книги о PHP
  • Публикации, посвященные PHP

PHP прошел длинный путь со дня своего рождения в середине 1990-х. От скромного появления до становления одним из самых популярных языков веб-программирования - эволюция PHP словно IT-сказка. Эта небольшая статья для тех из вас, кому интересно как развивался PHP. Если вы хотите прикоснуться к кусочку Интернет истории, то вы можете найти старые релизы PHP в » Музее PHP.

User Contributed Notes

There are no user contributed notes for this page.
Appendices
История PHP
Appendices


История PHP

PHP Tools, FI, Construction Kit и PHP/FI

PHP, как всем известно, на самом деле преемник продукта под названием PHP/FI. Созданное в 1994 году Расмусом Лердорфом, самое первое воплощение PHP было простым набором CGI-скриптов, написанных на языке программирования Си. Изначально используя их для отслеживания посещений своего веб-резюме, он назвал этот набор скриптов "Personal Homepages Tools" ("Инструменты для персональных домашних страниц"), но более часто упоминалось название "PHP Tools". Со временем требовалось все больше улучшений функциональности, и Расмус переписал PHP Tools, создав более крупную и богатую реализацию. Эта новая реализация была способна взаимодействать с базами данных и многое другое, что создавало фреймворк, с помощью которого пользователи могли создавать простые динамические веб-приложения, такие как гостевые книги. В июне 1995 года Расмус » открыл исходный код PHP Tools общественности, что позволило разработчикам использовать его по своему усмотрению. Это также дало возможность пользователям исправлять ошибки в коде и улучшать его.

В сентябре того же года, Расмус расширил PHP и на короткое время убрал из названия PHP. Теперь в виде инструмента FI (сокращение от "Интерпретатор Форм"), новая реализация включала в себя некоторые основные функциональные возможности того PHP, который мы знаем сегодня. Она имела Perl-подобные переменные, автоматическую интерпретацию форм и встраиваемый в HTML синтаксис. Синтаксис языка был похож на Perl, хотя и был гораздо более ограниченным, простым, и в некоторой степени противоречивым. Для того, чтобы вставлять код в HTML-файл, разработчикам пришлось использовать HTML комментарии. Хотя этот метод был не совсем хорошо принят, FI по-прежнему набирал популярность в качестве CGI-инструмента, но все-таки не в качестве языка. Однако, перемены начались в следующем месяце, когда в октябре 1995 года Расмус выпустил полностью переписанный код. С вернувшимся именем PHP, но уже сокращенным от "Personal Home Page Construction Kit", это был первый релиз, который мог похвастаться расширенным интерфейсом сценариев. Язык намеренно напоминал Си по структуре, что делал его легким для восприятия разработчиками, знакомыми с Си, Perl и подобными языками. Будучи все еще ограниченными UNIX и POSIX-совместимыми системами, был изучен вопрос для реализации языка в Windows NT.

Код получил еще одно существенное преобразование в апреле 1996 года. Объединив названия предыдущих версиий, Расмус представил PHP/FI. Реализации второго поколения начали по-настоящему развивать PHP из набора инструментов в самостоятельный язык программирования. PHP включал в себя встроенную поддержку для DBM, mSQL и Postgres95 баз данных, cookies, поддержку определяемых пользователем функций и многое другое. В июне PHP/FI была присвоена версия 2.0. Интересно, однако, что существовала только одна версия PHP 2.0. Когда она, наконец, в ноябре 1997 года преодолела статус бета-версии, парсер языка был уже полностью переписан.

Несмотря на короткую историю разработки, PHP/FI продолжал набирать популярность в молодом мире веб-разработки. В 1997 и 1998, PHP/FI стал культом для нескольких тысяч пользователей по всему миру. Исследования Netcraft в мае 1998 года показали, что почти 60 тысяч доменов передавали заголовки, содержащие "PHP". Это число равнялось примерно 1% от всех доменов в Интернете в то время. Несмотря на эти впечатляющие цифры, развитие PHP/FI было ограничено: несмотря на нескольких второстепенных участников, в целом он по-прежнему разработывался одним человеком.

Пример #1 Пример кода на PHP/FI

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Эй, у вас Нетскейп!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Извините, такой записи нет<p>
<!--endif exit-->
  Добро пожаловать, <!--$user-->!<p>
  На вашем счету осталось <!--$index:0--> "кредитов".<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 был первой версией, напоминающей PHP, каким мы знаем его сегодня. Посчитав PHP/FI 2.0 все еще неэффективным и недостаточно функциональным для использования в коммерческих приложениях, разрабатываемых для их университетского проекта, Энди Гутманс и Зив Сураски из Тель-Авива начали еще раз заново переписывать парсер в 1997 году. Связавшись с Расмусом, они обсудили различные аспекты текущей реализации и их новой разработки PHP. Для улучшения движка и использования уже существующей базы пользователей PHP/FI, Энди, Расмус и Зив решили сотрудничать в развитии нового, независимого языка программирования. Этот совершенно новый язык был выпущен под новым именем, без упоминания о персональном использовании, как в PHP/FI 2.0. Он был назван просто "PHP" - аббревиатура, означающая рекурсивный акроним - PHP: Hypertext Preprocessor.

Одной из сильнейших сторон PHP 3.0 была возможность расширения ядра. Кроме обеспечения пользователей надежной инфраструктурой из множества различных баз данных, протоколов и API, расширяемость PHP 3.0 привлекла к нему множество сторонних разработчиков, желающих добавить к языку свои расширения. Возможно, это и был главный ключ к успеху, но стоит добавить, что немаловажным шагом оказалась поддержка ООП синтаксиса и намного более мощного и последовательного синтаксиса самого языка.

В июне 1998 года, со множеством новых разработчиков со всего мира присоединившихся к проекту, PHP 3.0 был представлен новой командой разработчиков, как официальный преемник PHP/FI. Активное развитие PHP/FI 2.0, фактически прекратившееся в ноябре прошлого года, теперь официально закончилось. Примерно через девять месяцев открытого публичного тестирования, при объявлении официального выпуска PHP 3.0, он уже был установлен на более чем 70000 доменах по всему миру, и уже не ограничивается POSIX-совместимыми операционными системами. Относительно небольшая доля доменов с установленным PHP была размещена на серверах под управлением Windows 95, 98 и NT, а также Macintosh. На пике своего развития, PHP 3.0 был установлен приблизительно на 10% веб-серверов в Интернете.

PHP 4

К зиме 1998 года, практически сразу после официального выхода PHP 3.0, Энди Гутманс и Зив Сураски начали переработку ядра PHP. В задачи входило увеличение производительности сложных приложений и улучшение модульности кодовой базы PHP. PHP 3.0 дал возможность подобным приложениям успешно работать с набором баз данных и поддерживать большое количество различных API и протоколов, но PHP 3.0 не имел качественной поддержки модулей и приложения работали неэффективно.

Новый движок, названный 'Zend Engine' (от имен создателей: Zeev и Andi), успешно справлялся с поставленными задачами и впервые был представлен в середине 1999 года. PHP 4.0, основанный на этом движке и принесший с собой набор дополнительных функций, официально вышел в мае 2000 года, почти через два года после выхода своего предшественника. Кроме значительного улучшения производительности, PHP 4.0 имел еще несколько ключевых нововведений, таких как поддержка намного большего числа веб-серверов, поддержка HTTP сессий, буферизация вывода, более безопасные способы обработки вводимой пользователем информации и несколько новых языковых конструкций.

PHP 5

После долгой разработки и нескольких пре-релизов в июле 2004 был выпущен PHP 5. В основном он управляется ядром Zend Engine 2.0 с новой объектной моделью и множеством различных других нововведений.

Команда разработчиков PHP включает в себя десятки разработчиков, а также десятки других организаций, работающих над связанными с PHP и его поддержкой проектами, такими как PEAR, PECL и документацией, а также базовую инфраструктуру сети более чем из ста серверов на шести из семи континентах мира. Основываясть на статистике прошлых лет, можно с уверенностью предположить, что PHP теперь установлен на десятки или даже, возможно, сотни миллионов доменов по всему миру.

User Contributed Notes

There are no user contributed notes for this page.
История PHP и смежных проектов
История смежных с PHP проектов
История PHP и смежных проектов


История смежных с PHP проектов

PEAR

» PEAR (PHP Extension and Application Repository - Репозиторий Приложений и Расширений PHP. Изначально, PHP Extension and Add-on Repository - Репозиторий Дополнений и Расширений PHP) - это PHP-версия базовых классов. В будущем возможен его рост и становление ключевым способом публикации расширений PHP среди разработчиков.

PEAR зародился в ходе дискуссий на встрече разработчиков PHP (PHP Developers' Meeting - PDM), проходившей в январе 2000 года в Тель-Авиве. Автором PEAR является Стиг С. Баккен (Stig S. Bakken), который посвятил разработку своей первой дочери, Мэлин Баккен (Malin Bakken).

С начала 2000 года PEAR вырос до огромного проекта с большим количеством разработчиков, работающих над реализацией общего и повторно используемого функционала на благо для всего сообщества PHP. В настоящее время PEAR включает в себя широкий спектр классов для работы с базами данных, кэширования контента, математических вычислений, электронной коммерции и многого другого.

Дополнительная информация о PEAR может быть найдена в » документации.

Инициатива Гарантии Качества PHP

Группа » Инициативы Гарантии Качества PHP была основана весной 2000 в ответ на критику недостаточного бета-тестирования PHP для производственных окружений. Сейчас эта группа состоит из людей, прекрасно понимающих основу кода PHP. Эти разработчики тратят множество времени на обнаружение и устранение ошибок в PHP. Кроме того, много других членов команды тестируют эти исправления и сообщают о результатах их работы на различных платформах.

PHP-GTK

» PHP-GTK является расширением PHP для написания GUI-приложений, работающих на стороне клиента. Андрей Змиевски (Andrei Zmievski) вспоминает процесс планирования и разработки PHP-GTK:

Я всегда интересовался GUI-программированием, и я нахожу Gtk+ очень приятным средством разработки, исключая то, что работать с ним на C немного утомительно. После просмотра PyGtk и GTK-Perl, я решил попробовать написать интерфейс PHP для работы с Gtk+, пусть с минимальными возможностями. Начиная с августа 2000 года, у меня появилось немного больше свободного времени и я начал эксперименты. В разработке я основывался на PyGtk, который обладает большим количеством возможностей и приятным объектно-ориентированным интерфейсом. Джеймс Хэнстридж (James Henstridge), автор PyGtk, давал очень полезные советы в течение первых этапов разработки.

Написание вручную интерфейсов ко всем функциям Gtk+ даже не рассматривалось. Я остановился на идее генератора кода, похожего на аналогичный генератор PyGtk. Генератор читает .defs файлы, содержащие информацию о классах, константах и методах Gtk+ и генерирует C-код, являющийся интерфейсом в PHP. То, что не могло быть сгенерировано автоматически, создается вручную в .overrides файлах.

Работа над генератором кода и самой инфраструктурой шла достаточно долго, ввиду того, что я не имел достаточно свободного времени для работы. После того, как я показал PHP-GTK Фрэнку Кромману (Frank Kromman), он заинтересовался и начал помогать мне с генератором кода и версией для Win32. Когда мы написали и запустили первую программу Hello World, это было очень захватывающе. Потребовалось несколько месяцев для придания PHP-GTK презентабельного вида и первая версия вышла 1 марта 2001 года. История быстро попала в SlashDot.

Чувствуя, что PHP-GTK может расти, я создал отдельные почтовые конференции, CVS-репозиторий, а также сайт gtk.php.net с помощью Колина Виеброка (Colin Viebrock). Требовалась документация и здесь на помощь пришел Джеймс Мур (James Moore).

Со времен создания PHP-GTK получил широкую известность. У нас есть своя группа документирования, люди начинают писать расширения для PHP-GTK и все больше и больше прекрасных приложений с его помощью.

User Contributed Notes

There are no user contributed notes for this page.
История PHP
Книги о PHP
История PHP и смежных проектов


Книги о PHP

С ростом PHP, его начали узнавать по всему миру, как популярный язык программирования. Одним из наиболее интересных способов суждения об этом может послужить обзор книг о PHP.

Насколько нам известно, первой книгой, посвященной PHP, была чешская книга, выпущенная в апреле 1999 года под названием 'PHP - tvorba interaktivních internetových aplikací' (PHP - Создание интерактивных интернет-приложений). Автором книги является Jirka Kosek. В следующем месяце следом за ней выходит немецкая книга Эгона Шмидта (Egon Schmid), Кристиана Картуса (Christian Cartus) и Ричарда Блюма (Richard Blum). Вскоре после этого была опубликована первая на английском языке книга, посвященная PHP, - 'Core PHP Programming' Леона Аткинсона (Leon Atkinson). Все эти книги описывали PHP 3.0.

Эти книги были первыми в своем роде, и вскоре было выпущено большое количество книг различных авторов и издательств. Существует более 400 книг на английском, более 100 на немецком, и больше 50 на французском и испанском языках! Кроме того, можно найти книги о PHP на многих других языках, включая корейский, японский и иврит.

Очевидно, что такое большое количество книг, написанных разными авторами и опубликованных многими издательствами на столь многих языках, является весомым подтверждением мирового успеха PHP.

User Contributed Notes

There are no user contributed notes for this page.
История смежных с PHP проектов
Публикации, посвященные PHP
История PHP и смежных проектов


Публикации, посвященные PHP

По нашей информации, первая статья о PHP была опубликована в чешском варианте 'Computerworld' весной 1998 и освещала PHP 3.0. Как и в случае с книгами, эта была первая в серии статья из множества посвященных PHP и опубликованных в различных известных журналах.

Статьи о PHP публиковались в 'Dr. Dobbs', 'Linux Enterprise', 'Linux Magazine' и многих других изданиях. А статьи о переносе основанных на ASP приложений на PHP под Windows появились даже в принадлежащей самому Microsoft MSDN!

User Contributed Notes

craig dot cmehil at sap dot com 31-Aug-2005 05:39
For those moving into specific areas of PHP and interacting with other systems there are some great publications about SAP, http://www.sap.com, interacting with PHP found on SDN, http://sdn.sap.com.

https://forums.sdn.sap.com/thread.jspa?threadID=38415&tstart=0
Книги о PHP
Переход с PHP 5.3.x на PHP 5.4.x
История PHP и смежных проектов


Переход с PHP 5.3.x на PHP 5.4.x

Содержание

  • Что изменилось в PHP 5.4.x ?
  • Обратно несовместимые изменения
  • Новые возможности
  • Изменения в модулях SAPI
  • Устаревшие функции и возможности в PHP 5.4.x
  • Измененные функции
  • Новые функции
  • Новые классы и интерфейсы
  • Новые методы
  • Удаленные расширения
  • Другие изменения в расширениях
  • Новые глобальные константы
  • Изменения в обработке INI-файлов
  • Другие изменения

Смотрите также руководство по миграции для версий PHP 5.0.x, 5.1.x, 5.2.x и 5.3.x.

User Contributed Notes

There are no user contributed notes for this page.
Публикации, посвященные PHP
Что изменилось в PHP 5.4.x ?
Appendices


Что изменилось в PHP 5.4.x ?

Большинство изменений в PHP 5.4.x никак не повлияет на существующий код. Есть несколько несовместимостей и новых возможностей, которые должны быть учтены, и код должен быть протестирован перед тем как переключиться на новую версию PHP на рабочих серверах.

Для систем, которые обновились с более старой версии PHP, соответствующую документацию можно получить по адресам:

  • Замечания по обновлению для PHP 5.3.x.
  • Замечания по обновлению для PHP 5.2.x.
  • Замечания по обновлению для PHP 5.1.x.
  • Переход с PHP 4 на PHP 5.

User Contributed Notes

There are no user contributed notes for this page.
Переход с PHP 5.3.x на PHP 5.4.x
Обратно несовместимые изменения
Переход с PHP 5.3.x на PHP 5.4.x


Обратно несовместимые изменения

Хотя большая часть существующего кода PHP 5 должна работать без изменений, пожалуйста, примите к сведению следующие обратно несовместимые изменения:

  • Безопасный режим более не поддерживается. Любое приложение, которое полагается на безопасный режим, возможно, требует внесения корректировок по части безопасности.
  • "Волшебные" кавычки теперь не работают. Приложения, которые используют эту возможность, могут нуждаться в обновлении во избежание проблем с безопасностью. Функции get_magic_quotes_gpc() и get_magic_quotes_runtime() теперь всегда возвращают FALSE. Функция set_magic_quotes_runtime() вызывает ошибку уровня E_CORE_ERROR.
  • Директивы php.ini register_globals и register_long_arrays были удалены.
  • Возможность передачи по ссылке во время вызова функции была убрана.
  • Операторы break и continue теперь не принимают аргументов в виде переменной. Например, выражение break 1 + foo() * $bar; невозможно. Вы по-прежнему можете использовать явный аргумент в виде статической константы. Например, break 2;.
  • В расширении date and time временная зона не может быть более установлена с помощью переменной окружения TZ. Вместо этого вам необходимо указать временную зону, используя опцию php.ini date.timezone или функцию date_default_timezone_set(). PHP теперь не будет пытаться определять временную зону. Вместо этого будет установлена зона "UTC" и выдано предупреждение E_WARNING.
  • Нецифровые смещения строк, например $a['foo'], где $a - это строка, теперь возвращают false в функции isset() и true в функции empty() и вызывают предупреждение E_WARNING при подобном использовании. Смещения, заданные типами double, bool и null также приводят к генерации предупреждения E_NOTICE, а строки, содержащие числа ($a['2']), все еще работают как и раньше. Обратите внимание, что смещения, подобные '12.3' и '5 foobar' рассматриваются как нечисловые и вызывают предупреждение E_WARNING, но преобразовываются к 12 и 5 соответственно по причине необходимости сохранения обратной совместимости. Примечание: следующий код возвращает различные результаты. $str='abc';var_dump(isset($str['x'])); // false for PHP 5.4 or later, but true for 5.3 or less
  • Преобразование массива в строку теперь приводит к предупреждению E_NOTICE, но результат преобразования будет по-прежнему строка "Array".
  • Преобразование NULL, FALSE или пустой строки в объект путем добавления свойства теперь будет генерировать ошибку уровня E_WARNING вместо ошибки E_STRICT.
  • Имена параметров, которые "затеняют" имена суперглобальных переменных, теперь расцениваются как фатальная ошибка. Это правило запрещает код, подобный этому: function foo($_GET, $_POST) {}.
  • Хеш-алгоритмы Salsa10 и Salsa20 были удалены.
  • Функция array_combine() теперь возвращает array() вместо FALSE, когда в качестве параметров заданы два пустых массива.
  • Если вы используете функцию htmlentities() с азиатскими наборами символов, то она работает также, как функция htmlspecialchars(). Так всегда было в предыдущих версиях PHP, а теперь генерируется ошибка уровня E_STRICT.

Следующие ключевые слова теперь являются зарезервированными и не могут использоваться в качестве названия функций, классов и прочих имен:

  • trait
  • callable
  • insteadof

Следующие функции были удалены из PHP:

  • define_syslog_variables()
  • import_request_variables()
  • session_is_registered(), session_register() и session_unregister().
  • Алиасы
mysqli_bind_param(), mysqli_bind_result(),
mysqli_client_encoding(), mysqli_fetch(),
mysqli_param_count(), mysqli_get_metadata(),
mysqli_send_long_data(), mysqli::client_encoding() и mysqli_stmt::stmt().

User Contributed Notes

There are no user contributed notes for this page.
Что изменилось в PHP 5.4.x ?
Новые возможности
Переход с PHP 5.3.x на PHP 5.4.x


Новые возможности

PHP версии 5.4.0 предлагает широкий спектр новых возможностей:

  • Добавлена поддержка трейтов.
  • Добавлен короткий синтаксис объявления массивов. Например, $a = [1, 2, 3, 4]; или $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];.
  • Добавлена возможность разыменования массивов, возвращаемых функциями. Например: foo()[0].
  • Классы для создания анонимных функций (Closures) теперь поддерживают $this.
  • Оператор <?= теперь доступен всегда, несмотря на значение php.ini опции short_open_tag.
  • Добавлена возможность получения доступа к члену класса при создании экземпляра. Например: (new Foo)->bar().
  • Теперь поддерживается такой синтаксис: Class::{expr}().
  • Добавлен бинарный формат задания чисел, например: 0b001001101.
  • Улучшены сообщения об ошибках разбора и предупреждения о несовместимых аргументах.
  • Расширение по работе с сессиями теперь может отслеживать процесс загрузки файлов.
  • Встроенный веб-сервер в режиме командной строки для разработчиков.

User Contributed Notes

Anonymous 22-Oct-2011 08:50
The keyword 'insteadof' is introduced with PHP 5.4 http://php.net/language.oop5.traits.php
Обратно несовместимые изменения
Изменения в модулях SAPI
Переход с PHP 5.3.x на PHP 5.4.x


Изменения в модулях SAPI

  • Доступен новый модуль SAPI, называемый cli-server.
  • Добавлена CLI-опция --rz, которая отображает информацию о имени расширения Zend.
  • Добавлена ссылка #inisetting=value для изменения php.ini опций в процессе работы скрипта при интерактивной работе в консоли.
  • Добавлены функции, совместимые с Apache: apache_child_terminate(),
getallheaders(), apache_request_headers()
и apache_response_headers() для FastCGI SAPI.
  • PHP-FPM: Добавлена опция process.max для контроля количества ветвлений FPM-процессов.

User Contributed Notes

There are no user contributed notes for this page.
Новые возможности
Устаревшие функции и возможности в PHP 5.4.x
Переход с PHP 5.3.x на PHP 5.4.x


Устаревшие функции и возможности в PHP 5.4.x

Устаревшие функции:

  • mcrypt_generic_end()
  • mysql_list_dbs()

User Contributed Notes

There are no user contributed notes for this page.
Изменения в модулях SAPI
Измененные функции
Переход с PHP 5.3.x на PHP 5.4.x


Измененные функции

К некоторым функциям были добавлены новые необязательные параметры в PHP 5.4:

Ядро PHP:

  • Добавлен необязательный аргумент limit к функциям debug_backtrace() и debug_print_backtrace() для ограничения количества возвращаемых фреймов стека.
  • Функция is_link() теперь работает правильно с символическими ссылками в системе Windows Vista или более поздними. Более ранние версии не поддерживали символические ссылки.

OpenSSL:

  • В функции openssl_encrypt() и openssl_decrypt() добавлена опция "no padding" (не дополнять размер шифруемого блока).

Intl:

  • Функции idn_to_ascii() и idn_to_utf8() теперь принимают два дополнительных параметра: один указывает вид (IDNA 2003 или UTS #46) и другой, передаваемый по ссылке, предназначен для возврата детальной информации об операции в случае выбора UTS #46.

User Contributed Notes

There are no user contributed notes for this page.
Устаревшие функции и возможности в PHP 5.4.x
Новые функции
Переход с PHP 5.3.x на PHP 5.4.x


Новые функции

В PHP 5.4 введены несколько новых функций:

Ядро PHP:

  • hex2bin() - Преобразует шестнадцатеричное представление данных в двоичное
  • http_response_code() - Получить или установить код ответа HTTP
  • get_declared_traits() - Получить список задекларированных трейтов
  • getimagesizefromstring()
  • stream_set_chunk_size()
  • socket_import_stream()
  • trait_exists()
  • header_register_callback()

SPL:

  • class_uses()

Сессии:

  • session_status()
  • session_register_shutdown()

Mysqli:

  • mysqli_error_list()
  • mysqli_stmt_error_list()

Libxml:

  • libxml_set_external_entity_loader()

LDAP:

  • ldap_control_paged_result()
  • ldap_control_paged_result_response()

Intl:

  • transliterator_create()
  • transliterator_create_from_rules()
  • transliterator_create_inverse()
  • transliterator_get_error_code()
  • transliterator_get_error_message()
  • transliterator_list_ids()
  • transliterator_transliterate()

Zlib:

  • zlib_decode()
  • zlib_encode()

User Contributed Notes

There are no user contributed notes for this page.
Измененные функции
Новые классы и интерфейсы
Переход с PHP 5.3.x на PHP 5.4.x


Новые классы и интерфейсы

Следующие классы были введены в PHP 5.4.0:

SPL:

  • CallbackFilterIterator
  • RecursiveCallbackFilterIterator

Reflection:

  • ReflectionZendExtension

Json:

  • JsonSerializable

Session:

  • SessionHandler
  • SessionHandlerInterface

Snmp:

  • SNMP

Intl:

  • Transliterator
  • Spoofchecker

User Contributed Notes

There are no user contributed notes for this page.
Новые функции
Новые методы
Переход с PHP 5.3.x на PHP 5.4.x


Новые методы

Некоторые новые методы были введены в 5.4.0:

XSL:

  • XsltProcessor::setSecurityPrefs()
  • XsltProcessor::getSecurityPrefs()

SPL:

  • RegexIterator::getRegex()
  • SplObjectStorage::getHash()
  • DirectoryIterator::getExtension()
  • SplDoublyLinkedList::serialize()
  • SplDoublyLinkedList::unserialize()
  • SplFileInfo::getExtension()
  • SplFileObject::fputcsv()
  • SplQueue::serialize()
  • SplQueue::unserialize()
  • SplStack::serialize()
  • SplStack::unserialize()
  • SplTempFileObject::fputcsv()

Reflection:

  • ReflectionExtension::isPersistent()
  • ReflectionExtension::isTemporary()
  • ReflectionClass::isCloneable()

Closure:

  • Closure::bind()
  • Closure::bindTo()

PDO_dblib:

  • PDO::newRowset()

StreamWrapper:

  • StreamWrapper::stream_metadata()
  • StreamWrapper::stream_truncate()

User Contributed Notes

There are no user contributed notes for this page.
Новые классы и интерфейсы
Удаленные расширения
Переход с PHP 5.3.x на PHP 5.4.x


Удаленные расширения

Следующие расширения перемещены в репозиторий PECL и более не будут поставляться с дистрибутивом PHP. Версии этих расширений в виде пакетов PECL будут создаваться в соответствии с потребностями пользователей.

  • sqlite Обратите внимание, что расширения ext/sqlite3 и ext/pdo_sqlite остаются нетронутыми.

User Contributed Notes

There are no user contributed notes for this page.
Новые методы
Другие изменения в расширениях
Переход с PHP 5.3.x на PHP 5.4.x


Другие изменения в расширениях

Изменения в расширениях и новые возможности:

  • mysqli - mysqli_result теперь реализует класс Traversable
  • pdo_mysql - Удалена поддержка возможности сборки с клиентскими библиотеками MySQL старше версии 4.1.
  • Расширения mysql, mysqli и PDO_mysql используют mysqlnd в качестве библиотеки по умолчанию. Все еще возможно использовать libmysql, указав путь в конфигурационных настройках.
  • mysqlnd - Добавлена поддержка именованных каналов (named pipes).

User Contributed Notes

There are no user contributed notes for this page.
Удаленные расширения
Новые глобальные константы
Переход с PHP 5.3.x на PHP 5.4.x


Новые глобальные константы

Ядро PHP:

  • ENT_DISALLOWED
  • ENT_HTML401
  • ENT_HTML5
  • ENT_SUBSTITUTE
  • ENT_XML1
  • ENT_XHTML
  • IPPROTO_IP
  • IPPROTO_IPV6
  • IPV6_MULTICAST_HOPS
  • IPV6_MULTICAST_IF
  • IPV6_MULTICAST_LOOP
  • IP_MULTICAST_IF
  • IP_MULTICAST_LOOP
  • IP_MULTICAST_TTL
  • MCAST_JOIN_GROUP
  • MCAST_LEAVE_GROUP
  • MCAST_BLOCK_SOURCE
  • MCAST_UNBLOCK_SOURCE
  • MCAST_JOIN_SOURCE_GROUP
  • MCAST_LEAVE_SOURCE_GROUP

Curl:

  • CURLOPT_MAX_RECV_SPEED_LARGE
  • CURLOPT_MAX_SEND_SPEED_LARGE

LibXML:

  • LIBXML_HTML_NODEFDTD
  • LIBXML_HTML_NOIMPLIED
  • LIBXML_PEDANTIC

OpenSSL:

  • OPENSSL_CIPHER_AES_128_CBC
  • OPENSSL_CIPHER_AES_192_CBC
  • OPENSSL_CIPHER_AES_256_CBC
  • OPENSSL_RAW_DATA
  • OPENSSL_ZERO_PADDING

Буферизация вывода:

  • PHP_OUTPUT_HANDLER_CLEAN
  • PHP_OUTPUT_HANDLER_CLEANABLE
  • PHP_OUTPUT_HANDLER_DISABLED
  • PHP_OUTPUT_HANDLER_FINAL
  • PHP_OUTPUT_HANDLER_FLUSH
  • PHP_OUTPUT_HANDLER_FLUSHABLE
  • PHP_OUTPUT_HANDLER_REMOVABLE
  • PHP_OUTPUT_HANDLER_STARTED
  • PHP_OUTPUT_HANDLER_STDFLAGS
  • PHP_OUTPUT_HANDLER_WRITE

Сессии:

  • PHP_SESSION_ACTIVE
  • PHP_SESSION_DISABLED
  • PHP_SESSION_NONE

Потоки:

  • STREAM_META_ACCESS
  • STREAM_META_GROUP
  • STREAM_META_GROUP_NAME
  • STREAM_META_OWNER
  • STREAM_META_OWNER_NAME
  • STREAM_META_TOUCH

Zlib:

  • ZLIB_ENCODING_DEFLATE
  • ZLIB_ENCODING_GZIP
  • ZLIB_ENCODING_RAW

Intl:

  • U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR
  • IDNA_CHECK_BIDI
  • IDNA_CHECK_CONTEXTJ
  • IDNA_NONTRANSITIONAL_TO_ASCII
  • IDNA_NONTRANSITIONAL_TO_UNICODE
  • INTL_IDNA_VARIANT_2003
  • INTL_IDNA_VARIANT_UTS46
  • IDNA_ERROR_EMPTY_LABEL
  • IDNA_ERROR_LABEL_TOO_LONG
  • IDNA_ERROR_DOMAIN_NAME_TOO_LONG
  • IDNA_ERROR_LEADING_HYPHEN
  • IDNA_ERROR_TRAILING_HYPHEN
  • IDNA_ERROR_HYPHEN_3_4
  • IDNA_ERROR_LEADING_COMBINING_MARK
  • IDNA_ERROR_DISALLOWED
  • IDNA_ERROR_PUNYCODE
  • IDNA_ERROR_LABEL_HAS_DOT
  • IDNA_ERROR_INVALID_ACE_LABEL
  • IDNA_ERROR_BIDI
  • IDNA_ERROR_CONTEXTJ

Json:

  • JSON_PRETTY_PRINT
  • JSON_UNESCAPED_SLASHES
  • JSON_NUMERIC_CHECK
  • JSON_UNESCAPED_UNICODE
  • JSON_BIGINT_AS_STRING

User Contributed Notes

There are no user contributed notes for this page.
Другие изменения в расширениях
Изменения в обработке INI-файлов
Переход с PHP 5.3.x на PHP 5.4.x


Изменения в обработке INI-файлов

Следующие php.ini директивы были удалены:

  • register_globals и register_long_arrays
  • magic_quotes_gpc, magic_quotes_runtime, и magic_quotes_sybase
  • allow_call_time_pass_reference
  • define_syslog_variables
  • highlight.bg
  • session.bug_compat_42 и session.bug_compat_warn
  • y2k_compliance
  • safe_mode, safe_mode_gid, safe_mode_include_dir, safe_mode_exec_dir, safe_mode_allowed_env_vars, и safe_mode_protected_env_vars

Следующие php.ini директивы были добавлены:

  • cli.pager и cli.prompt для CLI SAPI, используя функцию readline в интерактивном режиме.
  • cli_server.color для включения ANSI-раскраски в консольном выводе встроенного веб-сервера для разработки.
  • max_input_vars - указывает какое количество входных переменных GET/POST/COOKIE может быть принято.
  • zend.multibyte - для управления новой возможностью автоопределения закодированных Unicode скриптов и файлов.
  • zend.script_encoding - Это значение будет использоваться до тех пор, пока не встретится директива "declare(encoding=...)" в начале скрипта.
  • zend.signal_check - для проверки замененных обработчиков сигналов при завершении.
  • session.upload_progress.enabled, session.upload_progress.cleanup, session.upload_progress.prefix, session.upload_progress.name, session.upload_progress.freq, session.upload_progress.min_freq
  • enable_post_data_reading - Когда отключено, данные POST не читаются (и не обрабатываются)
  • windows_show_crt_warning - Эта директива включает отображение предупреждений Windows CRT. До этого момента отображение было включено по умолчанию.

Следующие php.ini директивы были изменены:

  • session.entropy_file теперь принимает значение по умолчанию /dev/random или /dev/urandom в зависимости от того, что было определено на этапе компиляции.
  • session.entropy_length теперь принимает значение по умолчанию 32.

User Contributed Notes

There are no user contributed notes for this page.
Новые глобальные константы
Другие изменения
Переход с PHP 5.3.x на PHP 5.4.x


Другие изменения

  • Кодировкой по умолчанию для функций htmlspecialchars() и htmlentities() сейчас является UTF-8, вместо прежней ISO-8859-1. Обратите внимание, что изменения кодировки вывода с помощью конфигурационной опции default_charset не действует на вышеупомянутые функции до тех пор, пока вы не передадите "" (пустую строку) в качестве параметра кодировки в вызовы функций htmlspecialchars()/htmlentities(). В целом мы не рекомендуем так делать, потому что вы должны иметь возможность изменить кодировку вывода без воздействия на кодировку во время исполнения, используемую этими функциями. Самый безопасный подход - явно установить кодировку при каждом вызове функций htmlspecialchars() и htmlentities().
  • E_ALL теперь включает ошибки уровня E_STRICT в конфигурационной директиве error_reporting.
  • У SNMP теперь есть объектно-ориентированный API. Функции теперь возвращают FALSE на каждую ошибку, включая относящиеся к SNMP. (Нет такого экземпляра, конец MIB и т.д.). Таким образом, в частности, изменяется предыдущее поведение функций get/walk, которые возвращали пустую строку при ошибках, относящихся к SNMP. Теперь поддерживаются множественные запросы OID get/getnext/set. Исключен код совместимости с UCD-SNMP, учитывая что обновление до net-snmp v5.3+, Net-SNMP v5.4+ является необходимым для версии под Windows. Ради добавления поддержки IPv6 разрешение DNS имен в удаленном SNMP агенте теперь выполнено с помощью расширения, а не через библиотеку Net-SNMP.
  • OpenSSL теперь поддерживает AES.
  • CLI SAPI теперь больше не прерывает работу при фатальных ошибках, когда используется интерактивный режим с поддержкой readline.
  • Переменная $_SERVER['REQUEST_TIME_FLOAT'] была добавлена и содержит время с точностью до микросекунд.
  • Добавлены новые хэш-алгоритмы: fnv132, fnv164, joaat
  • Теперь работает задание смещений в строке последовательно, например: $a[0][0], где $a - строка.
  • Преобразование массивов из SimpleXMLElement теперь всегда содержит все узлы вместо только первого подходящего узла. Теперь выводятся все потомки SimpleXMLElement при использовании функций var_dump(), var_export() и print_r().
  • Стало актуальным требование присутствия аргументов абстрактного конструктора класса __construct в базовом классе при наследовании.

User Contributed Notes

There are no user contributed notes for this page.
Изменения в обработке INI-файлов
Переход c PHP 5.2.x на PHP 5.3.x
Переход с PHP 5.3.x на PHP 5.4.x


Переход c PHP 5.2.x на PHP 5.3.x

Содержание

  • Что нового в PHP 5.3.x ?
  • Обратно несовместимые изменения
  • Новые возможности
  • Изменения в поддержке Windows
  • Изменения в модулях SAPI
  • Устаревшие функции и возможности в PHP 5.3.x
  • Функции и возможности, которые ранее считались устаревшими, а теперь снова возвращены в PHP 5.3.x
  • Новые параметры
  • Новые функции
  • Новые обертки потоков
  • Новые фильтры потоков
  • Новые константы классов
  • Новые методы
  • Новые расширения
  • Удаленные расширения
  • Другие изменения в расширениях
  • Новые классы
  • Новые глобальные константы
  • Изменение в работе с INI-файлами
  • Другие изменения

Смотрите также руководство по миграции для версий PHP 5.0.x, 5.1.x и 5.2.x.

User Contributed Notes

There are no user contributed notes for this page.
Другие изменения
Что нового в PHP 5.3.x ?
Appendices


Что нового в PHP 5.3.x ?

Большинство изменений в PHP 5.3.x никак не повлияет на существующий код. Есть несколько несовместимостей и новых возможностей, которые должны быть учтены, и код должен быть протестирован перед тем как переключиться на новую версию PHP на рабочих серверах.

Для систем, которые обновились с более старой версии PHP, соответствующую документацию можно получить по адресам:

  • Замечания по обновлению для PHP 5.2.x.
  • Замечания по обновлению для PHP 5.1.x.
  • Переход с PHP 4 на PHP 5.

User Contributed Notes

There are no user contributed notes for this page.
Переход c PHP 5.2.x на PHP 5.3.x
Обратно несовместимые изменения
Переход c PHP 5.2.x на PHP 5.3.x


Обратно несовместимые изменения

Хотя большая часть существующего кода PHP 5 должна работать без изменений, пожалуйста, примите к сведению следующие обратно несовместимые изменения:

  • Новый внутренний API разбора параметров был применен во всех расширениях, идущих в комплекте с PHP 5.3.x. Этот API разбора параметров требует от функций возвращать NULL при передаче несовместимых параметров. Есть некоторые исключения из этого правила, например, функция get_class(), которая будет продолжать возвращать FALSE в случае ошибки.
  • clearstatcache() больше не очищает кэш функции realpath по умолчанию.
  • Функция realpath() стала полностью независима от платформы. Следствием этого является то, что некорректные относительные пути, такие как __FILE__ . "/../x" более не работают.
  • Семейство функций call_user_func() стало использовать $this даже если вызываемая функция - это родительский класс.
  • Функции работы с массивами natsort(),
natcasesort(), usort(),
uasort(), uksort(),
array_flip() и array_unique() больше
не принимают объекты в качестве аргументов. Для применения этих функций к
объекту необходимо сначала привести его к типу array.
  • Поведение функций при передаче параметров по значению, в которых параметры передаются по ссылке, было изменено. Там, где прежде функция принимала параметр по значению, сейчас генерируется фатальная ошибка. Любой прежний код, который передает константы или значения в качестве параметров функциям, которые ожидают ссылки, необходимо будет изменить, чтобы присвоить значение переменной перед вызовом функции.
  • Новая библиотека mysqlnd требует применения нового 41-го байтного формата пароля, который был введен в MySQL 4.1. Если вы продолжаете использовать 16-ти байтные пароли, это будет вынуждать функции mysql_connect() и подобные ей генерировать ошибку "mysqlnd cannot connect to MySQL 4.1+ using old authentication."
  • Новая библиотека mysqlnd не читает конфигурационные файлы mysql (my.cnf/my.ini), как это делает старая библиотека libmysql. Если ваш код использует настройки в конфигурационном файле, вы можете загрузить их явно с помощью функции mysqli_options(). Обратите внимание, что это означает, что константы PDO PDO::MYSQL_ATTR_READ_DEFAULT_FILE и PDO::MYSQL_ATTR_READ_DEFAULT_GROUP не определены, если MySQL не компилировался с поддержкой mysqlnd.
  • Завершающий символ "/" быд удален из класса SplFileInfo и других связанных с ним классов каталогов.
  • Магический метод __toString() не принимает более аргументы.
  • Магические методы
__get(),
__set(),
__isset(),
__unset(), и
__call() должны всегда
быть публичными и не могут быть статическими. Сигнатуры методов теперь стали более строгими.
  • Магический метод __call() теперь вызывается при доступе к приватным и защищенным методам.
  • func_get_arg(), func_get_args() и func_num_args() теперь не могут быть вызваны извне зоны видимости файла, который включается директивой include() или require() из функции в вызывающем файле.
  • Добавлен слой эмуляции расширения MHASH, чтобы служить оберткой вокруг расширения Hash. Однако не все алгоритмы покрыты, в их числе и алгоритм s2k хэширования. Это означает, что алгоритм s2k хэширования больше недоступен в пакете PHP 5.3.0.

Следующие ключевые слова теперь являются зарезервированными и не могут использоваться в качестве названия функции, класса и прочих имен.

  • goto
  • namespace

User Contributed Notes

mahbub at mahbubblog dot com 21-Sep-2010 09:36
If you're having the mysql connectivity problem for the short password format,there is a fix written by Mixu here

http://tinyurl.com/324pjer
Boris &#39;borzakov&#39; Ploujoux 14-Sep-2010 06:17
For those who often use the short open tag notations <? ... ?> and mostly <?= $var ?> (useful for template files) instead of standard notation <?php ... ?> : be careful !

In 5.3 version, the setting directive of the first notation is not PHP_INI_ALL anymore but PHP_INI_PERDIR.
In other words, you can't enable the "short_open_tag" directive directly with ini_set() function anymore ; you'll now have to set it in php.ini or httpd.conf (if you have access to it), or per-dir with .htaccess files.

See : http://www.php.net/manual/en/ini.core.php#ini.short-open-tag
munaw at munaw dot com 25-Aug-2010 08:32
gd_info():
    Note:
    Previous to PHP 5.3.0, the JPEG Support attribute was named JPG Support.

Be aware of this, in case you verify GD image support by this attribute!
mitek17 sobaka gmail.com 14-Apr-2010 11:42
After php version > 5.2.9 flush() stopped working. As a result the  output buffer will not be returned at all.
scott dot mcnaught at synergy8 dot com 07-Oct-2009 07:34
fopen('/dev/stdin/') no longer works
use fopen('php://stdin') instead

Cheers,
Scott
Chris Bolt 15-Sep-2009 07:03
call_user_func_array() no longer accepts null as a second parameter and calls the function. It now emits a warning and does not call the function.
Что нового в PHP 5.3.x ?
Новые возможности
Переход c PHP 5.2.x на PHP 5.3.x


Новые возможности

PHP 5.3.0 предлагает широкий спектр новых возможностей:

  • Добавлена поддержка пространств имен.
  • Добавлена поддержка позднего статического связывания.
  • Добавлена поддержка меток перехода (ограниченный goto).
  • Добавлена поддержка нативных замыканий (closures) (Lambda/Anonymous функции).
  • Появились два магических метода: __callStatic() и __invoke().
  • Появилась поддержка синтаксиса Nowdoc, подобный Heredoc, но с одинарными кавычками.
  • Теперь возможно использовать Heredoc для инициализации статических переменных и свойств/констант классов.
  • Heredoc теперь может быть объявлен используя двойные кавычки, дополняющие синтаксис Nowdoc.
  • Константы теперь могут быть объявлены вне класса, используя ключевое слово const.
  • У тернарного оператора есть теперь сокращенный вид: ?:.
  • Обертка (wrapper) HTTP-потока стала воспринимать коды статуса от 200 до 399 как успешные.
  • Стал возможен динамический доступ к статическим методам.
  • Исключения теперь могут быть вложенными.
  • Добавлен сборщик мусора для циклических ссылок. Он включен по умолчанию.
  • Функция mail() теперь поддерживает журналирование отправки письма (Примечание: это применимо только для писем, отправленных этой функцией.)

User Contributed Notes

There are no user contributed notes for this page.
Обратно несовместимые изменения
Изменения в поддержке Windows
Переход c PHP 5.2.x на PHP 5.3.x


Изменения в поддержке Windows

Изменения к выпускам PHP для Windows:

  • Минимально необходимая версия Windows теперь Windows XP SP3. Windows 98, ME, 2000 и NT4 больше не поддерживаются.
  • Бинарные файлы для Windows теперь скомпилированы для i586 и более поздних платформ. Платформы i386 и i486 более не поддерживаются.
  • Теперь есть экспериментальная поддержка для x64 версий PHP под Windows.
  • Теперь присутствует поддержка компилятора Visual C++ 9 (VC9), используемого в Visual Studio 2008. Снапшоты и релизы будут также доступны для VC9. Старые бинарные файлы для VC6 все еще поддерживаются и выпускаются в соответствии с VC9.
  • Библиотека PDO_OCI php_pdo_oci8.dll (для использования с клиентскими библиотеками для сервера Oracle версии 8) более не собирается. Вместо нее используйте php_pdo_oci.dll (без '8') с клиентскими библиотеками Oracle 10 или 11. Соединение с базами данных других версий все еще поддерживается.
  • Для расширения OCI8 новая библиотека php_oci8_11g.dll доступна как дополнение к php_oci8.dll. Подключена может быть только одна из библиотек. Используйте php_oci8.dll с клиентскими библиотеками Oracle 10.2. Используйте php_oci8_11g.dll с клиентскими библиотеками Oracle 11. Соединение с базами данных других версий все еще поддерживается.

Поддержка Windows была добавлена для следующих функций:

  • checkdnsrr()
  • dns_get_record()
  • fnmatch()
  • getmxrr()
  • getopt()
  • imagecolorclosesthwb()
  • inet_ntop()
  • inet_pton()
  • link()
  • linkinfo()
  • mcrypt_create_iv()
  • readlink()
  • socket_create_pair() - Эта функция была доступна и прежде на платформе Windows, но была отключена начиная с PHP 4.3.0 по причине ошибки в ней.
  • stream_socket_pair()
  • symlink()
  • time_nanosleep()
  • time_sleep_until()

Другие изменения:

  • Улучшена переносимость функций stat(), touch(), filemtime(), filesize() и других функций, связанных с ними (100% переносимость для имеющейся информации).
  • Теперь возможно создание жестких ссылок на Windows используя функцию link(), и символических ссылок, используя функцию symlink(). Жесткие ссылки доступны начиная с Windows 2000, символические - начиная с Windows Vista.
  • Версия PHP для Windows теперь предоставляет набор констант с префиксом PHP_WINDOWS_*. Список констант и примеры использования можно найти в разделе Предопределенные константы.
Внимание

Поддержка модуля ISAPI была прекращена. Вместо него используйте улучшенный модуль FastCGI SAPI.

Замечание: Стал доступен новый отдельный сайт для PHP под Windows, включающий раздел загрузок, релиз-кандидаты и снапшоты в различных вариантах (thread-safe/not-thread-safe, VC6/VC9, x86/x64). URL этого сайта следующий » http://windows.php.net/.

User Contributed Notes

Anonymous 11-Jan-2010 04:43
Due to the required getaddrinfo() function in Ws2_32.dll added to Windows XP SP2 and later.

The minimum Windows version is now Windows XP SP2; Windows XP SP1, 2000, 98, ME, and NT4 are no longer supported.

See: http://bugs.php.net/48761
philmee95 at gmail dot com 25-Jul-2009 01:48
Well worth the effort to set up fast cgi on windows. No more lockups with php or 40 procs running...and 1 killing IIS. Some PHP INI vars can't be overriden in your php files, so read up (like timeout). 8 months and no more locked up iis.
kevinpeno at gmail dot com 30-Jun-2009 02:53
Fast CGI is available for IIS6. Reading the IIS website (which is more appropriate since it is server specific) yields plenty of results regarding PHP setup under the fastCGI module. They even have an entire domain associated with PHP.

Note: links were denied because they were supposedly spam? Everything you need to know is linked at the beginning of this site:  http://php.iis.net/
Новые возможности
Изменения в модулях SAPI
Переход c PHP 5.2.x на PHP 5.3.x


Изменения в модулях SAPI

  • Доступен новый модуль SAPI, называемый litespeed.
  • Поддержка FastCGI в CGI SAPI теперь всегда включена и не может быть отключена. Для более детальной информации см. sapi/cgi/CHANGES.
  • Новая CGI SAPI опция -T может быть использована для измерения времени повторяющегося исполнения скрипта.
  • В CGI/FastCGI теперь есть поддержка для .htaccess-стиля файлов php.ini, определяемых пользователем.
  • Функция dl() теперь отключена по умолчанию, и доступна только для CLI, CGI и встраиваемых SAPI.

User Contributed Notes

There are no user contributed notes for this page.
Изменения в поддержке Windows
Устаревшие функции и возможности в PHP 5.3.x
Переход c PHP 5.2.x на PHP 5.3.x


Устаревшие функции и возможности в PHP 5.3.x

PHP 5.3.0 вводит два новых уровня ошибок: E_DEPRECATED и E_USER_DEPRECATED. Уровень ошибки E_DEPRECATED используется, чтобы показать, что функция или возможность устарела. Ошибка E_USER_DEPRECATED предназначена для обозначения устаревших функций в пользовательском коде, подобно уровням E_USER_ERROR и E_USER_WARNING.

Следующий список - это перечень устаревших INI-директив. Использование любой из этих директив будет приводить к генерации ошибки E_DEPRECATED при запуске.

  • define_syslog_variables
  • register_globals
  • register_long_arrays
  • safe_mode
  • magic_quotes_gpc
  • magic_quotes_runtime
  • magic_quotes_sybase
  • Комментарии, начинающиеся с символа "#", теперь считаются устаревшими в INI-файлах.

Устаревшие функции:

  • call_user_method() (используйте call_user_func())
  • call_user_method_array() (используйте call_user_func_array())
  • define_syslog_variables()
  • dl()
  • ereg() (используйте preg_match())
  • ereg_replace() (используйте preg_replace())
  • eregi() (используйте preg_match() с модификатором 'i')
  • eregi_replace() (используйте preg_replace() с модификатором 'i')
  • set_magic_quotes_runtime() и ее синоним magic_quotes_runtime()
  • session_register() (используйте суперглобальный массив $_SESSION)
  • session_unregister() (используйте суперглобальный массив $_SESSION)
  • session_is_registered() (используйте суперглобальный массив $_SESSION)
  • set_socket_blocking() (используйте stream_set_blocking())
  • split() (используйте preg_split())
  • spliti() (используйте preg_split() с модификатором 'i')
  • sql_regcase()
  • mysql_db_query() (используйте mysql_select_db() и mysql_query())
  • mysql_escape_string() (используйте mysql_real_escape_string())
  • Передача строки, задающей категорию функций, на которые будет влиять установка локали, сейчас считается устаревшим вариантом. Используйте вместо этого семейство констант LC_*
  • Параметр is_dst в функции mktime(). Вместо него используйте новые функции работы с временными зонами.

Устаревшие возможности:

  • Присвоение по ссылке возвращаемого значения оператором new является устаревшим.
  • Передача по ссылке во время исполнения считается устаревшим способом.

User Contributed Notes

shad at shartley dot net 23-Sep-2010 03:20
Correction on my previous note.

sed -i 's/\$HTTP_\(.*\)_VARS/\$_\1/g' {} \;

will screw up multiple instances of $HTTP_*_VARS in the file.

You'll have to use an instance of sed like:

sed -i 's/\$HTTP_SERVER_VARS/\$_SERVER/g'
i.e.
find ./ -name "*.php" -exec sed -i 's/\$HTTP_POST_VARS/\$_POST/g' {} \;
find ./ -name "*.php" -exec sed -i 's/\$HTTP_GET_VARS/\$_GET/g' {} \;
...

for each of the deprecated variables you might have in your files.

It also occurred to me a simple php conversion script would also work:

$search=array(
    "/HTTP_SERVER_VARS/",
    "/HTTP_POST_VARS/",
    "/HTTP_ENV_VARS/",
    "/HTTP_GET_VARS/",
    "/HTTP_COOKIE_VARS/",
    "/HTTP_SESSION_VARS/",
    "/HTTP_POST_FILES/");
$replace=array(
    "_SERVER",
     "_POST",
    "_ENV",
    "_GET",
    "_COOKIES",
    "_SESSION","_FILES");
$content=file_get_contents("somefile.php");
$content=preg_replace($search,$replace,$content);
file_put_contents("somefile.php",$content);

add directory recursion functions, ect.
shad at shartley dot net 11-Sep-2010 04:37
If you previously defined register_long_arrays in php.ini and have a lot of code with $HTTP_*_VARS that need to be replaced the following may help on *.nix systems:

sed -i 's/\$HTTP_\(.*\)_VARS/\$_\1/g' filename.php

What this command does is replace all occurrences of $HTTP_*_VARS with their respective $_ counter parts, e.g. $HTTP_COOKIES_VAR to $_COOKIES

To replace alot of files, you might combine it with the find command:
find ./ -name "*.php" -exec sed -i 's/\$HTTP_\(.*\)_VARS/\$_\1/g' {} \;

For other deprecated variables like $HTTP_POST_FILES change your sed arguments:

sed -i 's/\$HTTP_POST_FILES/\$_FILES/g'

Deprecated variables created by the register_long_arrays directive as far as I know are:
$_POST
$_GET
$_SERVER
$_ENV
$_COOKIE
$_SESSION
Anonymous 26-Mar-2010 05:02
A backward compatibility break which is not documented:

Fatal error: Uncaught exception 'RuntimeException' with message 'Directory name must not be empty.'

This happens with new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $staticPath ) )
Изменения в модулях SAPI
Функции и возможности, которые ранее считались устаревшими, а теперь снова возвращены в PHP 5.3.x
Переход c PHP 5.2.x на PHP 5.3.x


Функции и возможности, которые ранее считались устаревшими, а теперь снова возвращены в PHP 5.3.x

Функция is_a() более не является устаревшей по причине своей популярности; она не будет больше генерировать ошибку E_STRICT.

User Contributed Notes

There are no user contributed notes for this page.
Устаревшие функции и возможности в PHP 5.3.x
Новые параметры
Переход c PHP 5.2.x на PHP 5.3.x


Новые параметры

К некоторым функциям были добавлены новые необязательные параметры в PHP 5.3:

Ядро PHP:

  • clearstatcache() - Добавлен параметр clear_realpath_cache и filename.
  • copy() - Добавлен параметр контекста потока context.
  • fgetcsv() - Добавлен параметр escape.
  • ini_get_all() - Добавлен параметр details.
  • nl2br() - Добавлен параметр is_xhtml.
  • parse_ini_file() - Добавлен параметр scanner_mode.
  • round() - Добавлен параметр mode.
  • stream_context_create() - Добавлен параметр params.
  • strstr() и stristr() - Добавлен параметр before_needle.

json:

  • json_encode() - Добавлен параметр options.
  • json_decode() - Добавлен параметр depth.

Потоки:

  • stream_select(),
stream_set_blocking(),
stream_set_timeout() и
stream_set_write_buffer() теперь работают с пользовательскими
обертками потоков.

sybase_ct:

  • sybase_connect() - Добавлен параметр new.

Новые параметры методов в PHP 5.3.0:

Ядро PHP:

  • Exception::__construct() - Добавлен параметр previous.

User Contributed Notes

There are no user contributed notes for this page.
Функции и возможности, которые ранее считались устаревшими, а теперь снова возвращены в PHP 5.3.x
Новые функции
Переход c PHP 5.2.x на PHP 5.3.x


Новые функции

В PHP 5.3 введены несколько новых функций:

Ядро PHP:

  • array_replace() - Заменяет элементы массива элементами других переданных массивов.
  • array_replace_recursive() - Рекурсивно заменяет элементы массива элементами переданных массивов.
  • class_alias() - Создает псевдоним для пользовательского класса.
  • forward_static_call() - Вызывает пользовательскую функцию из контекста метода.
  • forward_static_call_array() - Вызывает пользовательскую функцию из контекста метода с аргументами, содержащимися в массиве.
  • gc_collect_cycles() Принудительно включает коллектор существующих циклических ссылок.
  • gc_disable() - Деактивирует коллектор циклических ссылок.
  • gc_enable() - Активирует коллектор циклических ссылок.
  • gc_enabled() - Возвращает статус коллектора циклических ссылок.
  • get_called_class() - Возвращает имя класса, в котором был вызван статический метод.
  • gethostname() - Возвращает имя хоста для локального компьютера.
  • header_remove() - Удаляет HTTP-заголовок, ранее установленный функцией header().
  • lcfirst() - Переводит в нижний регистр первый символ строки.
  • parse_ini_string() - Разбирает строку конфигурации.
  • quoted_printable_encode() - Кодирует 8-битную строку с помощью метода quoted-printable.
  • str_getcsv() - Выполняет разбор CSV-строки в массив.
  • stream_context_set_default() - Устанавливает контекст потоков по умолчанию.
  • stream_supports_lock() - Возвращает TRUE, если поток поддерживает блокирование.
  • stream_context_get_params() - Получает параметры контекста потока.
  • streamWrapper::stream_cast() - Получает базовый ресурс потока.
  • streamWrapper::stream_set_option() - Изменяет опции потока.

Date/Time:

  • date_add() - Добавляет заданное количество дней, месяцев, лет, минут и секунд к объекту DateTime.
  • date_create_from_format() - Возвращает объект DateTime, приведенный в соответствие с заданным форматом.
  • date_diff() - Возвращает разницу между двумя объектами DateTime.
  • date_get_last_errors() - Возвращает предупреждения и ошибки, которые произошли при последней операции с датой или временем.
  • date_parse_from_format() - Получает информацию о заданной дате.
  • date_sub() - Вычитает заданное количество дней, месяцев, лет, минут и секунд от объекта. DateTime.
  • timezone_version_get() - Возвращает версию базы данных timezonedb.

GMP:

  • gmp_testbit() - Проверяет, установлен ли бит.

Hash:

  • hash_copy() - Копирование контекста хэширования.

IMAP:

  • imap_gc() - Очищает кэш IMAP.
  • imap_utf8_to_mutf7() - Кодирует строку UTF-8 в модифицированный UTF-7.
  • imap_mutf7_to_utf8() - Декодирует строку из модифицированного UTF-7 в UTF-8.

JSON:

  • json_last_error() - Возвращает последнюю ошибку JSON.

MySQL Improved:

  • mysqli_fetch_all() - Извлекает все строки результата в виде ассоциативного массива с ключами в виде чисел или в совмещенном виде.
  • mysqli_get_connection_stats() - Возвращает статистику соединения с клиентом.
  • mysqli_poll() - Опрос соединений.
  • mysqli_reap_async_query() - Получает результат асинхронного запроса.

OpenSSL:

  • openssl_random_pseudo_bytes() - Возвращает строку заданной длины, заполненную псевдослучайной последовательностью байт.

PCNTL:

  • pcntl_signal_dispatch() - Вызывает обработчик сигналов для отложенных сигналов.
  • pcntl_sigprocmask() - Устанавливает и получает заблокированные сигналы.
  • pcntl_sigtimedwait() - Ожидание сигнала с таймаутом.
  • pcntl_sigwaitinfo() - Ожидание сигнала.

PCRE:

  • preg_filter() - Выполняет поиск и замену по регулярному выражению, возвращая только результаты совпавшего шаблона.

Семафоры:

  • msg_queue_exists() - Проверка на существование очереди сообщений.
  • shm_has_var() - Проверяет, существует ли конкретный ключ внутри сегмента разделяемой памяти.

Следующие функции теперь полностью реализованы в PHP на всех ОС, на которых может работать PHP:

  • acosh()
  • asinh()
  • atanh()
  • expm1()
  • log1p()

User Contributed Notes

There are no user contributed notes for this page.
Новые параметры
Новые обертки потоков
Переход c PHP 5.2.x на PHP 5.3.x


Новые обертки потоков

Следующие обертки потоков были введены в версии 5.3.0:

  • glob://
  • phar://

User Contributed Notes

There are no user contributed notes for this page.
Новые функции
Новые фильтры потоков
Переход c PHP 5.2.x на PHP 5.3.x


Новые фильтры потоков

Следующие фильтры потоков были введены в версии 5.3.0:

  • dechunk (изменяет кодировку HTTP chunked на противоположную, т.е. исходную)
  • Фильтр bz2.decompress теперь поддерживает конкатенацию.

User Contributed Notes

There are no user contributed notes for this page.
Новые обертки потоков
Новые константы классов
Переход c PHP 5.2.x на PHP 5.3.x


Новые константы классов

Некоторые новые константы классов были добавлены в версии 5.3.0:

PDO_FIREBIRD:

  • PDO::FB_ATTR_DATE_FORMAT - Устанавливает формат даты.
  • PDO::FB_ATTR_TIME_FORMAT - Устанавливает формат времени.
  • PDO::FB_ATTR_TIMESTAMP_FORMAT - Устанавливает формат временной метки.

User Contributed Notes

There are no user contributed notes for this page.
Новые фильтры потоков
Новые методы
Переход c PHP 5.2.x на PHP 5.3.x


Новые методы

Несколько новых методов были введены в версии 5.3.0:

Date/Time:

  • DateTime::add() - Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime.
  • DateTime::createFromFormat() - Возвращает объект DateTime, приведенный в соответствие с заданным форматом.
  • DateTime::diff() - Возвращает разницу между двумя объектами DateTime.
  • DateTime::getLastErrors() - Возвращает предупреждения и ошибки, которые произошли при последней операции с датой или с временем.
  • DateTime::sub() - Вычитает заданное количество дней, месяцев, лет, минут и секунд от объекта. DateTime.

Класс Exception:

  • Exception::getPrevious() - Возвращает предыдущее исключение.

DOM:

  • DOMNode::getLineNo() - Возвращает номер строки узла.

PDO_FIREBIRD:

  • PDO::setAttribute() - Устанавливает атрибут.

Reflection:

  • ReflectionClass::getNamespaceName() - Возвращает пространство имен, в котором определен данный класс.
  • ReflectionClass::getShortName() - Возвращает короткое имя данного класса (без части, в которой находится пространство имен).
  • ReflectionClass::inNamespace() - Проверяет, объявлен ли класс в пространстве имен.
  • ReflectionFunction::getNamespaceName() - Возвращает название пространства имен, в котором определена данная функция.
  • ReflectionFunction::getShortName() - Возвращает короткое имя функции (без пространства имен).
  • ReflectionFunction::inNamespace() - Проверяет, определена ли функция в пространстве имен.
  • ReflectionProperty::setAccessible() - Устанавливает могут ли непубличные свойства быть запрошены.

SPL:

  • SplObjectStorage::addAll() - Добавляет все элементы к другому объекту SplObjectStorage.
  • SplObjectStorage::removeAll() - Убирает все элементы из другого объекта SplObjectStorage.

XSL:

  • XSLTProcessor::setProfiling() - Устанавливает файл для вывода профиля.

User Contributed Notes

There are no user contributed notes for this page.
Новые константы классов
Новые расширения
Переход c PHP 5.2.x на PHP 5.3.x


Новые расширения

Следующие расширения были добавлены начиная с PHP 5.3.0:

  • Enchant - Слой абстракции над различными библиотеками правописания
  • Fileinfo - Усовершенствованная и более серьезная замена (с полной бинарной совместимостью) расширению Mimetype, которое было удалено.
  • INTL - Расширение для интернационализации. INTL - это обертка вокруг библиотеки » ICU.
  • Phar - Реализация файлов-архивов PHP.
  • SQLite3 - Поддержка БД SQLite версии 3.

Mysqlnd - это новая основная библиотека, поставляемая с PHP. Это адаптированная для PHP замена для libmysql. Mysqlnd будет использована для сборки расширения mysql, mysqli и PDO_MySQL, если libmysql не будет найдена в системе. Она также может быть использована вместо libmysql даже когда libmysql присутствует. Mysqlnd рекомендуется для всех инсталляций PHP из соображений производительности.

User Contributed Notes

There are no user contributed notes for this page.
Новые методы
Удаленные расширения
Переход c PHP 5.2.x на PHP 5.3.x


Удаленные расширения

Следующие расширения перемещены в репозиторий PECL и более не будут поставляться с дистрибутивом PHP. Версии этих расширений в виде пакетов PECL будут создаваться в соответствии с потребностями пользователей.

  • dbase - Более не поддерживается
  • fbsql - Более не поддерживается
  • fdf - Поддерживается
  • ming - Поддерживается
  • msql - Более не поддерживается
  • ncurses - Поддерживается
  • sybase - Убрано из дистрибутива; вместо него используйте расширение sybase_ct
  • mhash - Убрано из дистрибутива; вместо него используйте расширение hash. hash обладает полной совместимостью с mhash; все существующие приложения, использующие старые функции будут продолжать работать.

User Contributed Notes

keith 27-Oct-2010 12:39
Hash does NOT fully implement mhash.  Notably Joomla has 2 lines in helper.php that use an unsupported function: mhash_keygen_s2k(,,,).

Other functions of mhash can be rewritten:

<?php
echo bin2hex(mhash(MHASH_RIPEMD160 ,"my_password"));

echo hash("ripemd160" ,"my_password");
?>
schwilch at gmx dot de 16-Jun-2010 05:39
MSsqlserverDriver does not support mssql-functions but sqlsrv-functions.
If you do not want to change all of your php-scripts for using other functions and another function-handling of db-connection-parameters you should use freeTDS for Windows (download for example at moodle.org) and php_dblib.dll.
I hope this helps others with MS-Systems.
Cam 28-Aug-2009 08:57
The MSSQL extension is no longer present in the 5.3.0 release, but this fact is not mentioned on this page. Perhaps that should be added.

It seems that the recommended solution is to use "SQL Server Driver for PHP" by Microsoft (http://www.microsoft.com/sqlserver/2005/en/us/php-driver.aspx). However, it is reported that the current release (v1.0) does not support PHP 5.3.0 (see http://forums.iis.net/t/1158918.aspx). Apparently, v1.1 will support PHP 5.3, but it is currently in CTP release.
Новые расширения
Другие изменения в расширениях
Переход c PHP 5.2.x на PHP 5.3.x


Другие изменения в расширениях

Следующие расширения не могут быть отключены в момент конфигурирования сборки:

  • PCRE
  • Reflection
  • SPL

Изменения в поведении расширений и новые возможности:

  • Date and Time - Переменная окружения TZ более не используется для определения временной зоны
  • cURL - cURL теперь поддерживает SSH
  • Network - dns_check_record() теперь возвращает дополнительные записи типа TXT.
  • Hash - Теперь поддерживаются хэш-алгоритмы SHA-224 и salsa.
  • mbstring - Теперь есть поддержка для кодировки CP850.
  • OCI8 - Вызов функции oci_close() при постоянном соединении, или выход за зону видимости переменной, ссылающейся на постоянное соединение, теперь приводит к откату любой незавершенной транзакции. Для того, чтобы избежать непредсказуемого поведения, явно дается команда подтверждения или отката транзакции при необходимости. Предыдущее поведение может быть включено с помощью INI-директивы oci8.old_oci_close_semantics. Теперь поддерживается пул постоянных соединений к БД (DRCP) и быстрое оповещение приложения (FAN). Поддерживается внешняя аутентификация Oracle (за исключением Windows). Функция oci_bind_by_name() теперь поддерживает тип данных SQLT_AFC (также известный как CHAR).
  • OpenSSL - Теперь поддерживаются функции свертки и шифрования OpenSSL. Также стало возможно получение доступа к внутренним значениям DSA, RSA и DH ключей.
  • Сессии - Сессионные файлы теперь более не хранятся в "/tmp", когда применены ограничения open_basedir, за исключением случая, когда директория "/tmp" явно добавлена к списку разрешенных путей.
  • SOAP Теперь поддерживает установленные пользователем HTTP-заголовки.
  • MySQLi Теперь поддерживает постоянные соединения, путем добавление к хосту "p:".
  • Обработка изображений и GD Индекс "JPG Support", возвращаемый функцией gd_info() был переименован в "JPEG Support".

User Contributed Notes

There are no user contributed notes for this page.
Удаленные расширения
Новые классы
Переход c PHP 5.2.x на PHP 5.3.x


Новые классы

Следующие новые классы были введены в PHP 5.3.0:

Date/Time:

  • DateInterval
  • DatePeriod

Phar:

  • Phar
  • PharData
  • PharException
  • PharFileInfo

SPL:

  • FilesystemIterator
  • GlobIterator
  • MultipleIterator
  • RecursiveTreeIterator
  • SplDoublyLinkedList
  • SplFixedArray
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplQueue
  • SplStack

User Contributed Notes

There are no user contributed notes for this page.
Другие изменения в расширениях
Новые глобальные константы
Переход c PHP 5.2.x на PHP 5.3.x


Новые глобальные константы

Ядро PHP:

  • __DIR__
  • __NAMESPACE__
  • E_DEPRECATED
  • E_USER_DEPRECATED
  • INI_SCANNER_NORMAL
  • INI_SCANNER_RAW
  • PHP_MAXPATHLEN
  • PHP_WINDOWS_NT_DOMAIN_CONTROLLER
  • PHP_WINDOWS_NT_SERVER
  • PHP_WINDOWS_NT_WORKSTATION
  • PHP_WINDOWS_VERSION_BUILD
  • PHP_WINDOWS_VERSION_MAJOR
  • PHP_WINDOWS_VERSION_MINOR
  • PHP_WINDOWS_VERSION_PLATFORM
  • PHP_WINDOWS_VERSION_PRODUCTTYPE
  • PHP_WINDOWS_VERSION_SP_MAJOR
  • PHP_WINDOWS_VERSION_SP_MINOR
  • PHP_WINDOWS_VERSION_SUITEMASK

cURL:

  • CURLOPT_PROGRESSFUNCTION

GD:

  • IMG_FILTER_PIXELATE

JSON:

  • JSON_ERROR_CTRL_CHAR
  • JSON_ERROR_DEPTH
  • JSON_ERROR_NONE
  • JSON_ERROR_STATE_MISMATCH
  • JSON_ERROR_SYNTAX
  • JSON_FORCE_OBJECT
  • JSON_HEX_TAG
  • JSON_HEX_AMP
  • JSON_HEX_APOS
  • JSON_HEX_QUOT

LDAP:

  • LDAP_OPT_NETWORK_TIMEOUT

libxml:

  • LIBXML_LOADED_VERSION

PCRE:

  • PREG_BAD_UTF8_OFFSET_ERROR

PCNTL:

  • BUS_ADRALN
  • BUS_ADRERR
  • BUS_OBJERR
  • CLD_CONTIUNED
  • CLD_DUMPED
  • CLD_EXITED
  • CLD_KILLED
  • CLD_STOPPED
  • CLD_TRAPPED
  • FPE_FLTDIV
  • FPE_FLTINV
  • FPE_FLTOVF
  • FPE_FLTRES
  • FPE_FLTSUB
  • FPE_FLTUND
  • FPE_INTDIV
  • FPE_INTOVF
  • ILL_BADSTK
  • ILL_COPROC
  • ILL_ILLADR
  • ILL_ILLOPC
  • ILL_ILLOPN
  • ILL_ILLTRP
  • ILL_PRVOPC
  • ILL_PRVREG
  • POLL_ERR
  • POLL_HUP
  • POLL_IN
  • POLL_MSG
  • POLL_OUT
  • POLL_PRI
  • SEGV_ACCERR
  • SEGV_MAPERR
  • SI_ASYNCIO
  • SI_KERNEL
  • SI_MESGQ
  • SI_NOINFO
  • SI_QUEUE
  • SI_SIGIO
  • SI_TIMER
  • SI_TKILL
  • SI_USER
  • SIG_BLOCK
  • SIG_SETMASK
  • SIG_UNBLOCK
  • TRAP_BRKPT
  • TRAP_TRACE

User Contributed Notes

There are no user contributed notes for this page.
Новые классы
Изменение в работе с INI-файлами
Переход c PHP 5.2.x на PHP 5.3.x


Изменение в работе с INI-файлами

В PHP 5.3.0 была значительно улучшена производительность при разборе INI-файлов, и добавлено несколько новых синтаксических возможностей.

  • Стандартные php.ini файлы были реорганизованы и переименованы. php.ini-development содержит настройки, рекомендуемые для использования при разработке. php.ini-production содержит настройки, рекомендуемые при производственной эксплуатации.
  • Теперь присутствует поддержка двух специальных секций: [PATH=/opt/httpd/www.example.com/] и [HOST=www.example.com]. Директивы, установленные в этих секциях не могут быть переопределены в пользовательских INI-файлах или при выполнении. Более детальную информацию об этих секциях можно найти здесь.
  • zend_extension_debug и zend_extension_ts были удалены. Используйте директиву zend_extension для загрузки всех расширений Zend.
  • Директива zend.ze1_compatibility_mode была удалена. Если эта INI-директива установлена в On, то при запуске будет сгенерирована ошибка E_ERROR.
  • Сейчас стало возможно использование полного пути для загрузки модулей, используя директиву "extension".
  • "ini-variables" могут быть использованы почти везде в php.ini файле.
  • В процессе исполнения скрипта возможно ужесточение ограничений, заданных директивойopen_basedir.
  • Стало возможным использовать буквенно-цифровые или переменные индексы в массивах INI-опций.
  • Функция get_cfg_var() сейчас способна возвращать массив из INI-опций.
  • Добавлена новая директива mail.add_x_header
  • Новая директива user_ini.filename
  • Также новая user_ini.cache_ttl
  • Также новая exit_on_timeout
  • Директива open_basedir сейчас может быть установлена где угодно (PHP_INI_ALL)

Следующие новые INI-директивы были добавлены:

  • user_ini.filename и user_ini.cache_ttl для нового механизма INI-файла в стиле .htaccess.
  • Добавлена директива mbstring.http_output_conv_mimetype. Она указывает шаблон регулярного выражения для типов контента, для которых активируется функция mb_output_handler().
  • Добавлена request_order. Позволяет контролировать, какая внешняя переменная будет доступна в массиве $_REQUEST.

Следующие INI-директивы получили новые значения по умолчанию:

  • session.use_only_cookies теперь установлена в "1" (включено) по умолчанию.
  • oci8.default_prefetch изменено с "10" на "100".

User Contributed Notes

There are no user contributed notes for this page.
Новые глобальные константы
Другие изменения
Переход c PHP 5.2.x на PHP 5.3.x


Другие изменения

  • SplFileInfo::getpathinfo() теперь возвращает информацию о пути.
  • У SplObjectStorage теперь есть поддержка ArrayAccess. Теперь также возможно хранить ассоциативную информацию с объектами в SplObjectStorage.
  • В расширении GD теперь возможно объединение пикселей в группы с помощью функции imagefilter().
  • Вывод функции var_dump() теперь включает свойства приватных объектов.
  • Функция session_start() теперь возвращает FALSE, когда начало сессии происходит неудачно.
  • Функция property_exists() теперь проверяет существование свойства независимо от доступности (так же как method_exists()).
  • Обертки потоков теперь могут использоваться include_path.
  • Параметр initial для функции array_reduce() теперь может быть любого типа.
  • Функции работы с директориями opendir(), scandir() и dir() теперь используют контекст потока по умолчанию, если он не задан явно.
  • У функции crypt() теперь есть поддержка Blowfish и расширенного DES, и возможности crypt() теперь 100% переносимы. У PHP имеется своя собственная внутренняя реализация crypt, которая ипользуется вместо crypt или crypt_r, когда они не найдены.
  • Функция getopt() теперь принимает "длинные опции" на всех платформах. Поддерживаются необязательные значения и = в качестве отделителя для коротких опций.
  • У функции fopen() теперь есть новый режим (n), который передает константу O_NONBLOCK соответствующему низлежащему системному вызову open(). Обратите внимание, что этот режим в настоящее время не поддерживается в системах Windows.
  • Функция getimagesize() сейчас поддерживает файлы-иконки (.ico).
  • Расширение mhash перемещено в репозиторий PECL, но расширение Hash было изменено для поддержки mhash, если PHP скомпилирован с опцией --with-mhash. Обратите внимание, что расширение Hash не требует библиотеки mhash вне зависимости от того, включена ли эмуляция mhash или нет.

User Contributed Notes

There are no user contributed notes for this page.
Изменение в работе с INI-файлами
Переход с PHP 5.1.x на PHP 5.2.x
Переход c PHP 5.2.x на PHP 5.3.x


Переход с PHP 5.1.x на PHP 5.2.x

Содержание

  • Изменения в PHP 5.2.x
  • Изменения, нарушающие обратную совместимость
  • Новые сообщения об ошибках
  • Изменения в поддержке datetime в PHP
  • Новые параметры
  • Новые функции
  • Новые методы
  • Удалённые расширения
  • Новые расширения
  • Новые классы
  • Новые глобальные константы
  • Новые константы классов
  • Новые конфигурационные параметры INI
  • Сообщения об ошибках
  • Другие улучшения

Смотрите также руководство по миграции для версий PHP 5.0.x, 5.1.x и 5.3.x.

User Contributed Notes

There are no user contributed notes for this page.
Другие изменения
Изменения в PHP 5.2.x
Appendices


Изменения в PHP 5.2.x

Большая часть изменений в PHP 5.2.x не затронет существующий код. Тем не менее, есть несколько несовместимых изменений и новых сообщений об ошибках, которые должны быть учтены при переходе. Также рекомендуется оттестировать код перед переходом на новую версию PHP в боевой установке.

Прочтите раздел "Переход на PHP 5.1.x", если предыдущей версией PHP была PHP 5.0.x.

Аналогично, если предыдущей версией была PHP 4, прочтите также раздел "Переход с PHP 4 на PHP 5".

User Contributed Notes

There are no user contributed notes for this page.
Переход с PHP 5.1.x на PHP 5.2.x
Изменения, нарушающие обратную совместимость
Переход с PHP 5.1.x на PHP 5.2.x


Изменения, нарушающие обратную совместимость

Хотя большая часть существущего кода на PHP 5 должна работать без изменений, нужно обратить внимание на следующие нарушения обратной совместимости:

  • getrusage() возвращает NULL, если переданы несовместимые аргументы, начиная с PHP 5.2.1.
  • ZipArchive::setCommentName() возвращает TRUE при удачном выполнении, начиная с PHP 5.2.1.
  • ZipArchive::setCommentIndex() возвращает TRUE при удачном выполнении, начиная с PHP 5.2.1.
  • SplFileObject::getFilename() возвращает имя файла, а не относительный/путь/к/файлу, начиная с PHP 5.2.1.
  • Изменён приоритет переменной окружения PHPRC в Win32. Переменная окружения PHPRC имеет теперь больший приоритет, чем путь, сохранённый в реестре Windows.
  • CLI SAPI больше не проверяет текущую директорию на наличие php.ini или php-cli.ini. В PHP 5.1.x существовала недокументированная особенность: исполняемый файл CLI проверял текущую директорию на наличие конфигурационного файла PHP. Это потенциально могло привести к непредсказуемому поведению в случае, если был найден нежелательный конфигурационный файл. Эта функциональность была удалена в версии 5.2.0 и PHP более не ищет в текущей директории файлы php.ini или php-cli.ini. См. также раздел "Командная строка" данного руководства.
  • Добавлено предупреждение при поиске остатка от деления на 0. В предыдущих версиях PHP выполнение операции "integer % 0" не вызывало никаких предупреждений. Результатом операции было значение FALSE. Начиная с PHP 5.2.0 эта операция вызовет E_WARNING, как и в любом другом случае деления на 0.
    <?php
    print 10 % 0;
    /* Warning:  Division by zero in filename on line n */
    ?>
  • __toString() вызывается в случаях преобразования в строку. "Магический" метод __toString() вызывается в строковом контексте, то есть во всех случаях, когда объект используется как строка. В версии PHP 5.2.0 была удалена функциональность по умолчанию, возвращавшая строку с идентификатором объекта. Эта функциональность вызывала проблемы, поскольку идентификатор в общем случае не уникален. Это изменение означает, что ваше приложение будет вести себя неправильно, если оно полагается на идентификатор объекта в виде возвращаемого значения. Попытка использовать это значение как строку вызовет перехватываемую фатальную ошибку.
    <?php
    class foo {}
    $foo = new foo;
    print     $foo;
    /* Catchable fatal error:  Object of class foo could
       not be converted to string in filename on line n */
    ?>
    Даже с методом __toString() объекты не могут использоваться для индексации массива. Возможно, позднее будет реализовано встроенное хэширование для таких случаев, но в PHP 5.2.x вам придётся реализовать собственное вычисление хэш-значений или использовать новую функцию SPL: spl_object_hash(). Из метода __toString() нельзя бросать исключения.
    <?php
    class foo {
        public function     __toString() {
            throw new     Exception;
        }
    }

    try {
        print new     foo;
            /* Fatal error:  Method foo::__toString() must
           not throw an exception in filename on line n */
    } catch(Exception $e) {}
    ?>
  • Не поддерживаются абстрактные статические методы классов. По недосмотру, PHP 5.0.x и 5.1.x позволяли определять абстрактные статические методы классов. Начиная с PHP 5.2.x такие методы могут быть только у интерфейсов.
    <?php
    abstract class foo {
        abstract static function     bar();
            /* Strict Standards:  Static function foo::bar()
           should not be abstract in filename on line n */
    }
    ?>
  • Расширение Oracle требует как минимум Oracle 10 под Windows.
  • Добавлена поддержка RFC2397 (data: stream). Добавление URL-схемы "data" может потенциально привести к нарушению работы кода под Windows. Если вы работаете с файловой системой NTFS, используете мета-потоки и ваше приложение работает с файлом "data:" не указывая путь к нему, это вызовет ошибку. Чтобы исправить её, используйте протокол "file:" для доступа к файлу. См. также » RFC 2397
    <?php
    /* При allow_url_include равной OFF (по умолчанию) */
    include "data:;base64,PD9waHAgcGhwaW5mbygpOz8+";
    /* Warning:  include(): URL file-access is disabled
       in the server configuration in filename on line n */
    ?>
  • Регрессия в шаблонах glob() В версии 5.2.4 исправление безопасности привело к регрессии для шаблонов вида "/foo/*/bar/*". Начиная с версии 5.2.5 функция glob() больше не будет выдавать предупреждение, а возвратит FALSE, если нарушены ограничения openbase_dir.

User Contributed Notes

goellerk at bucks dot edu 07-Jun-2010 02:20
str_pad has been modified as well, to enforce UPPERCASE sensitivity on the pad_type declaration.

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

If entered as:
$foo = 10;
$wrong = str_pad($foo, 4,'0',str_pad_left);
print "wrong is '$wrong'<br>";

$right = str_pad($foo,4,'0',STR_PAD_LEFT);
print "right is '$right'<br>";

results:
wrong is '    '
right is '  10'
Alexander Schuch 04-Feb-2010 06:42
If the sole reason for having "abstract static methods" is to force the implementation of such a method in a child, consider using an interface for them. The abstract class implements the interface, and a child class extends the base class and defines the "abstract static methods".

<?php
interface I
{
static public function f();
}

abstract class C implements I
{
// more/other methods go here
}

class D extends C
{
static public function f()
{
echo 'I am f().';
}
}
?>
jbarker at erepublic dot com 21-Feb-2008 06:44
If any of your code relies on includes of URLS  à la allow_url_fopen, be aware that a new directive (allow_url_include) has been added, and that it defaults to Off.
Tachy 31-Jan-2008 08:04
$string="12345";
$rightstring1=substr($string,-3);
$rightstring2=substr($string,-8);
echo "Result1: ".$rightstring1."<BR>";
echo "Result2: ".$rightstring2."<BR>";

PHP5.1.x:
Result1: 345
Result2: 12345

PHP5.2.x
Result1: 345
Result2: <Empty>
php dot manual at frankkleine dot de 10-Nov-2007 04:17
Between PHP 5.2.3 and 5.2.4 another backward incompatible change was introduced: parent classes now can not access private properties of child classes with get_object_vars(). See the following example:

class Bar {
    public function dumpBar()  {
        var_dump(get_object_vars($this));
    }
}
class Foo extends Bar {
    public $public = 'public';
    protected $protected = 'protected';
    private $private = 'private';

    public function dump() {
        var_dump(get_object_vars($this));
    }
}

$foo = new Foo();
$foo->dump();
$foo->dumpBar();

The result with PHP < 5.2.4:
E:\php\tests>php get_object_vars.php
array(3) {
  ["public"]    => string(6) "public"
  ["protected"] => string(9) "protected"
  ["private"]   => string(7) "private"
}

array(3) {
  ["public"]    => string(6) "public"
  ["protected"] => string(9) "protected"
  ["private"]   => string(7) "private"
}

And the result with PHP >= 5.2.4:
E:\php-5.2.4-Win32>php ../php/tests/get_object_vars.php
array(3) {
  ["public"]    => string(6) "public"
  ["protected"] => string(9) "protected"
  ["private"]   => string(7) "private"
}

array(2) {
  ["public"]    => string(6) "public"
  ["protected"] => string(9) "protected"
}

As you can see the private property is missing now when dumped from the parent class Bar.
Erik Osterman 29-Mar-2007 07:44
It should be noted that if you provide a __toString method, you can cast the object to a string and use it as an array key (PHP 5.2.x).

e.g.   $array[ (string)$myObject ] = 'foobar';

This is an alternative to using spl_object_hash.
Изменения в PHP 5.2.x
Новые сообщения об ошибках
Переход с PHP 5.1.x на PHP 5.2.x


Новые сообщения об ошибках

Ниже перечислены новые сообщения об ошибках, не упоминавшиеся ранее в этом документе.

Пример #1 В ядре PHP

<?php
echo " ";
session_regenerate_id();
/*  Warning:  session_regenerate_id(): Cannot regenerate
    session id - headers already sent in filename on line n */

str_word_count("string", 4);
/* Warning:  str_word_count(): Invalid format value 4
   in filename on line n */

strripos("foo", "f", 4);
/* Notice:  strripos(): Offset is greater than the
   length of haystack string in filename on line n */

strrpos("foo", "f", 4);
/* Notice:  strrpos(): Offset is greater than the
   length of haystack string in filename on line n */

/* Начиная с PHP 5.2.1, при значении allow_url_include = OFF (по умолчанию) */
include "php://input";
/* Warning:  include(): URL file-access is disabled
   in the server configuration in filename on line n */
?>

Пример #2 Объектно-ориентированный код в ядре PHP

<?php
interface foo {
}
class bar implements foo, foo {
}
/* Fatal error: Class bar cannot implement previously
   implemented interface foo in filename on line n */

class foo {
    public $bar;
    function __get($var)
    {
        return $this->bar;
    }
}

$foo = new foo;
$bar =& $foo->prop;
/* Notice: Indirect modification of overloaded property
   foo::$prop has no effect in filename on line n */

class foo implements iterator {
    public function current() {
    }
    public function next() {
    }
    public function key() {
    }
    public function valid() {
    }
    public function rewind() {
    }
}

$foo = new foo();
foreach($foo as &$ref) {}
/* Fatal error: An iterator cannot be used with foreach
   by reference in filename on line n */

class foo {
    private function __construct() {
    }
}
class bar extends foo {
    public function __construct() {
        parent::__construct();
        /* Fatal error:  Cannot call private
           foo::__construct() in filename on line n */
    }
}
new bar;

stream_filter_register("", "class");
/* Warning:  stream_filter_register(): Filter name
   cannot be empty in filename on line n */

stream_filter_register("filter", "");
/* Warning:  stream_filter_register(): Class name
   cannot be empty in filename on line n */
?>

Пример #3 В расширении bzip2

<?php
bzopen("", "w");
/* Warning:  bzopen(): filename cannot be empty
   in filename on line n */

bzopen("foo", "a");
/* Warning:  bzopen(): 'a' is not a valid mode for
   bzopen(). Only 'w' and 'r' are supported in
   filename on line n */

$fp = fopen("foo", "w");
bzopen($fp, "r");
/* Warning:  bzopen(): cannot read from a stream
   opened in write only mode in filename on line n */
?>

Пример #4 В расширении datetime

<?php
strtotime("today", "now");
/* Warning:  strtotime() expects parameter 2 to be
   long, string given in filename on line n */

/* As of PHP 5.2.1 */
new DateTime(new stdclass);
/* Fatal error: Uncaught exception 'Exception' with
   message 'DateTime::__construct() expects parameter
   1 to be string, object given' in filename:n */
?>

Пример #5 В расширении dBase

<?php
dbase_open("foo", -1);
/* Warning: Invalid access mode -1 in filename on line n */

/* As of PHP 5.2.1 */
dbase_open("foo", null);
/* Warning: The filename cannot be empty in filename on line n */
?>

Пример #6 В расширении mcrypt

<?php
$key = "секретный ключ";
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td),
                        MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, "");
/* Warning: mcrypt_generic(): An empty string was
   passed in filename on line n */
?>

Пример #7 В расширении oci8

<?php
oci_connect("user", "pass", "db", "bogus_charset");
/* Warning: Invalid character set name:
   bogus_charset in filename on line n */

$oci = oci_connect("user", "pass", "db");
oci_password_change($oci, "", "old", "new");
/* Warning: username cannot be empty in filename
   on line n */

oci_password_change($oci, "user", "", "new");
/* Warning: old password cannot be empty in filename
   on line n */

oci_password_change($oci, "user", "old", "");
/* Warning: new password cannot be empty in filename
   on line n */
?>

Пример #8 В расширении SPL

<?php
$obj = new SplFileObject(__FILE__);
$obj->fgetcsv("foo");
/* Warning:  SplFileObject::fgetcsv(): delimiter must
   be a character in filename on line n */

$obj->fgetcsv(",", "foo");
/* Warning:  SplFileObject::fgetcsv(): enclosure must
   be a character in filename on line n */
?>

Пример #9 В расширении Semaphore (sysvmsg)

<?php
/* Warning:  maximum size of the message has to be
   greater then zero in filename on line n */
?>

Пример #10 Пример Zip для версий 5.2.1+

<?php
$obj = new ZipArchive();
$obj->open('archive.zip');
$obj->setCommentName('', 'комментарий');
/* Notice:  ZipArchive::setCommentName(): Empty string
   as entry name in filename on line n */

/* Начиная с PHP 5.2.1 */
$obj->getCommentName('');
/* Notice:  ZipArchive::getCommentName(): Empty string
   as entry name in filename on line n */
?>

User Contributed Notes

There are no user contributed notes for this page.
Изменения, нарушающие обратную совместимость
Изменения в поддержке datetime в PHP
Переход с PHP 5.1.x на PHP 5.2.x


Изменения в поддержке datetime в PHP

Начиная с PHP 5.1.0, в ядро PHP включено расширение date. Это новая реализация поддержки работы с датой и временем в PHP. Хотя расширение попытается угадать системные настройки временной зоны, лучше установить их вручную. Это можно сделать одним из трёх способов:

  • в php.ini при помощи параметра date.timezone
  • в системе при помощи переменной окружения TZ
  • из скрипта при помощи функции date_default_timezone_set()

Поддерживаемые идентификаторы временных зон перечислены в документации.

Начиная с PHP 5.2.x существует объектное представление даты и временной зоны: DateTime и DateTimeZone соответственно. Их методы соответствуют существующим функциям для работы с датой.

User Contributed Notes

There are no user contributed notes for this page.
Новые сообщения об ошибках
Новые параметры
Переход с PHP 5.1.x на PHP 5.2.x


Новые параметры

В PHP 5.2.x у некоторых функций появились новые, необязательные параметры:

Ядро PHP:

  • htmlentities() - добавлен параметр double_encode в PHP 5.2.3.
  • htmlspecialchars() - добавлен параметр double_encode в PHP 5.2.3.
  • base64_decode() - добавлен параметр strict
  • setcookie() - добавлен параметр httponly
  • setrawcookie() - добавлен параметр httponly
  • session_set_cookie_params() - добавлен параметр httponly
  • memory_get_usage() - добавлен параметр real_usage
  • get_loaded_extensions() - добавлен параметр zend_extensions в PHP 5.2.4

curl:

  • curl_multi_info_read() - добавлен параметр msgs_in_queue

datetime

  • date() - добавлен символ форматирования "u" (миллисекунды) в PHP 5.2.2

imap:

  • imap_open() - добавлен параметр n_retries
  • imap_reopen() - добавлен параметр n_retries

mbstring:

  • mb_strrpos() - добавлен параметр offset
    Внимание

    Параметр offset добавлен на место параметра encoding. Обратная совместимость обеспечивается указанием encoding как третьего параметра. Однако использовать это не рекомендуется, так как поддержка encoding как третьего параметра будет удалена в последующих версиях PHP.

ming:

  • SWFMovie::streamMP3() - добавлен параметр skip в PHP 5.2.1

openssl:

  • openssl_verify() - добавлен параметр signature_algo

pgsql:

  • pg_escape_bytea() - добавлен параметр connection
  • pg_escape_string() - добавлен параметр connection

simplexml:

  • SimpleXMLElement::__construct() - добавлен параметр is_prefix
  • SimpleXMLElement::attributes() - добавлен параметр is_prefix
  • SimpleXMLElement::children() - добавлен параметр is_prefix
  • simplexml_load_file() - добавлен параметр is_prefix
  • simplexml_load_string() - добавлен параметр is_prefix

spl:

  • array iterator_to_array(Traversable it [, bool use_keys = true]) - добавлен параметр use_keys в PHP 5.2.1

xmlreader:

  • XMLReader::open() - добавлены параметры encoding и options
  • XMLReader::XML() - добавлены параметры encoding и options

XMLWriter:

  • xmlwriter_write_element() - параметр content стал необязательным в PHP 5.2.3
  • xmlwriter_write_element_ns() - параметр content стал необязательным в PHP 5.2.3

User Contributed Notes

There are no user contributed notes for this page.
Изменения в поддержке datetime в PHP
Новые функции
Переход с PHP 5.1.x на PHP 5.2.x


Новые функции

В PHP 5.2.x было добавлено несколько новых функций:

Ядро PHP:

  • array_fill_keys() - Создаёт массив, используя элементы первого параметра в виде ключей и присваивая всем значение val
  • error_get_last() - Возвращает последнюю ошибку в ассоциативном массиве или NULL, если ошибок не было.
  • image_type_to_extension() - Возвращает расширение файла для типа изображения, полученного из getimagesize(), exif_read_data(), exif_thumbnail(), exif_imagetype()
  • memory_get_peak_usage() - Возвращает максимум выделенной для PHP памяти
  • sys_get_temp_dir() - Возвращает путь к директории для временных файлов. (Добавлено в 5.2.1)
  • timezone_abbreviations_list() - Возвращает ассоциативный массив, содержащий для каждой аббревиатуры временной зоны флаг летнего времени (DST), смещение от стандартного времени и название пояса.
  • timezone_identifiers_list() - Возвращает массив идентификаторов всех временных зон.
  • timezone_name_from_abbr() - Возвращает название временной зоны по аббревиатуре
  • stream_socket_shutdown() - Закрывает соединение или его часть на сокете, связанном с потоком, который будет закрыт. Начиная с PHP 5.2.1.

Image:

  • imagegrabscreen() - Делает снимок всего экрана. Начиная с PHP 5.2.2.
  • imagegrabwindow() - Делает снимок окна. Начиная с PHP 5.2.2.

libXML:

  • libxml_disable_entity_loader() - Отключает возможность загрузки внешних сущностей. Начиная с PHP 5.2.11.

mbstring:

  • mb_stripos() - Находит позицию первого вхождения строки в другой строке. Регистронезависимая.
  • mb_stristr() - Находит первое вхождение строки в другой строке. Регистронезависимая.
  • mb_strrchr() - Находит последнее вхождение символа строки в другой строке.
  • mb_strrichr() - Находит последнее вхождение символа из строки в другой строке. Регистронезависимая.
  • mb_strripos() - Находит позицию последнего вхождения строки в другой строке. Регистронезависимая.
  • mb_strstr() - Находит первое вхождение строки в другой строке.

ming (Начиная с PHP 5.2.1):

  • void ming_setSWFCompression(int num) - Устанавливает сжатие выходного потока.
  • void swfmovie::namedanchor(string name) - Создаёт якорь.
  • void swfmovie::protect([string password]) - Защищает выходной поток.

openssl:

  • openssl_csr_get_public_key() - Извлекает открытый ключ из CERT и подготавливает его к использованию.
  • openssl_csr_get_subject() - Возвращает предмет (subject) CERT
  • openssl_pkey_get_details() - Возвращает массив с информацией о ключе (bits, pkey, type)

spl:

  • spl_object_hash() - Возвращает хэш-значение для данного объекта
  • int iterator_apply(Traversable it, mixed function [, mixed params]) - Вызывает функцию для каждого элемента итератора.

pcre:

  • preg_last_error() - Возвращает код ошибки для последнего поиска по регулярному выражению.

pgsql:

  • pg_field_table() - Возвращает название таблицы, которой принадлежит поле, или oid таблицы, если oid_only содержит TRUE

posix:

  • posix_initgroups() - Вычисляет список доступа группы по имени пользователя.

gmp:

  • gmp_nextprime() - Находит следующее простое число.

xmlwriter:

  • xmlwriter_full_end_element() - Закрывает текущий элемент, возвращает FALSE при ошибке.
  • xmlwriter_write_raw() - Пишет текст, возвращает FALSE при ошибке.
  • xmlwriter_start_dtd_entity() - Начинает DTD-сущность, возвращает FALSE при ошибке.
  • xmlwriter_end_dtd_entity() - Заканчивает текущую DTD-сущность, возвращает FALSE при ошибке.
  • xmlwriter_write_dtd_entity() - Записывает полную DTD-сущность, возвращает FALSE при ошибке.

User Contributed Notes

There are no user contributed notes for this page.
Новые параметры
Новые методы
Переход с PHP 5.1.x на PHP 5.2.x


Новые методы

В 5.2.0 были добавлены новые методы:

dom:

  • DOMDocument::registerNodeClass() - Регистрирует расширенный класс для создания базового типа узла.
  • DOMElement::setIDAttribute() - Объявляет атрибут, указанный по имени, типом указанного идентификатора.
  • DOMElement::setIDAttributeNode() - Объявляет атрибут, указанный по узлу, типом указанного идентификатора.
  • DOMElement::setIDAttributeNS() - Объявляет атрибут, указанный по локальному имени и URI пространства имен, типом указанного идентификатора.
  • DOMNode::C14N()([bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Записывает каноническую запись узлов в строку.
  • DOMNode::C14NFile()(string uri [, bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Записывает каноническую запись узлов в файл.
  • DOMNode::getNodePath()() - Возвращает xpath узла

soap:

  • SoapServer::setObject()(object obj) - Устанавливает объект-обработчик SOAP-запросов.

spl:

  • int ArrayObject::asort()(void) - Сортирует массив по значениям.
  • int ArrayObject::ksort()(void) - Сортирует массив по ключам.
  • int ArrayObject::natcasesort()(void) - Сортирует массив по ключам, используя регистронезависимую сортировку алгоритмом "natural order".
  • int ArrayObject::natsort()(void) - Сортирует массив по значениям, используя сортировку алгоритмом "natural order".
  • int ArrayObject::uasort()(callback cmp_function) - Сортирует массив по значениям, используя функцию сравнения, заданную пользователем.
  • int ArrayObject::uksort()(callback cmp_function) - Сортирует массив по ключам, используя функцию сравнения, заданную пользователем.
  • ArrayIterator AppendIterator::getArrayIterator()() - Предоставляет доступ к внутреннему итератору (ArrayIterator).
  • int AppendIterator::getIteratorIndex()() - Возвращает индекс итератора.
  • bool CachingIterator::getCache()() - Возвращает флаг кэша.
  • int CachingIterator::getFlags()() - Возвращает внутренние флаги.
  • bool CachingIterator::offsetExists()(mixed index) - Возвращает TRUE, если индекс существует.
  • string CachingIterator::offsetGet()(mixed index) - Возвращает внутренний кэш при его использовании.
  • void CachingIterator::offsetSet()(mixed index, mixed newval) - Устанавливает индекс в кэше.
  • void CachingIterator::offsetUnset()(mixed index) - Очищает индекс в кэше.
  • void CachingIterator::setFlags()() - Устанавливает внутренние флаги.
  • array("delimiter" =>, "enclosure" =>) SplFileObject::getCsvControl()(void) - Возвращает разделяющий и обрамляющий символы, используемые в fgetcsv().
  • void SplFileObject::setCsvControl()([string delimiter = ',' [, string enclosure = '"']]) - Устанавливает разделяющий и обрамляющий символы, используемые в fgetcsv().

Tidy

  • tidyNode tidyNode::getParent()() - Возвращает родительский узел текущего. (Добавлено в PHP 5.2.2)

XMLReader

  • boolean XMLReader::setSchema() - Использует W3C XSD схему для проверки документа при обработке. Можно использовать перед первым вызовом XMLReader::read().

zip:

  • ZipArchive::addEmptyDir()() - Создаёт пустую директорию в архиве.

User Contributed Notes

There are no user contributed notes for this page.
Новые функции
Удалённые расширения
Переход с PHP 5.1.x на PHP 5.2.x


Удалённые расширения

Эти расширения были перенесены в PECL и более не являются частью дистрибутива PHP. Пакеты в PECL для этих расширений будут создаваться по запросам пользователей.

  • filePro
  • Hyperwave API

User Contributed Notes

There are no user contributed notes for this page.
Новые методы
Новые расширения
Переход с PHP 5.1.x на PHP 5.2.x


Новые расширения

Следующие расширения были добавлены (по умолчанию) в PHP 5.2.0:

  • Filter - Проверяет и фильтрует данные. Разработан для работы с небезопасными данными, такими, как пользовательский ввод. Это расширение включено по умолчанию. Режим RAW (по умолчанию) не влияет на входные данные.
  • JSON - Реализует работу с форматом обмена данными the JavaScript Object Notation (JSON). Это расширение включено по умолчанию.
  • Zip - Позволяет прозрачно читать и писать ZIP-архивы и файлы в них.

User Contributed Notes

There are no user contributed notes for this page.
Удалённые расширения
Новые классы
Переход с PHP 5.1.x на PHP 5.2.x


Новые классы

Следующие классы были добавлены в PHP 5.2.0:

  • DateTime
  • DateTimeZone
  • RegexIterator - extends FilterIterator; implements Iterator, Traversable, OuterIterator Константы:
    • RegexIterator::ALL_MATCHES
    • RegexIterator::GET_MATCH
    • RegexIterator::MATCH
    • RegexIterator::REPLACE
    • RegexIterator::SPLIT
    • RegexIterator::USE_KEY
    Свойства:
    • public replacement
    Методы:
    • RegexIterator::__construct(Iterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Создаёт RegexIterator из другого итератора и регулярного выражения.
    • bool RegexIterator::accept() - Проверяет (string)current() на соответствие регулярному выражению.
    • bool RegexIterator::getFlags() - Возвращает текущие флаги.
    • bool RegexIterator::getMode() - Возвращает текущий режим работы.
    • bool RegexIterator::getPregFlags() - Фозвращает текущие флаги PREG (или NULL, если они не используются)
    • bool RegexIterator::setFlags(int new_flags) - Устанавливает флаги.
    • bool RegexIterator::setMode(int new_mode) - Устанавливает новый режим работы.
    • bool RegexIterator::setPregFlags(int new_flags) - Устанавливает флаги PREG.
  • RecursiveRegexIterator Константы:
    • RecursiveRegexIterator::ALL_MATCHES
    • RecursiveRegexIterator::GET_MATCH
    • RecursiveRegexIterator::MATCH
    • RecursiveRegexIterator::REPLACE
    • RecursiveRegexIterator::SPLIT
    • RecursiveRegexIterator::USE_KEY
    Методы:
    • RecursiveRegexIterator::__construct(RecursiveIterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Создаёт RecursiveRegexIterator из другого рекурсивного итератора и регулярного выражения.
    • RecursiveRegexIterator RecursiveRegexIterator::getChildren() - Возвращает внутренний итератор потомков, содержащихся в текущем RecursiveRegexIterator.
    • bool RecursiveRegexIterator::hasChildren() - Проверяет, есть ли у текущего элемента внутреннего итератора потомки.

User Contributed Notes

There are no user contributed notes for this page.
Новые расширения
Новые глобальные константы
Переход с PHP 5.1.x на PHP 5.2.x


Новые глобальные константы

Ядро PHP:

  • M_EULER
  • M_LNPI
  • M_SQRT3
  • M_SQRTPI
  • PATHINFO_FILENAME
  • PREG_BACKTRACK_LIMIT_ERROR
  • PREG_BAD_UTF8_ERROR
  • PREG_INTERNAL_ERROR
  • PREG_NO_ERROR
  • PREG_RECURSION_LIMIT_ERROR
  • UPLOAD_ERR_EXTENSION
  • STREAM_SHUT_RD
  • STREAM_SHUT_WR
  • STREAM_SHUT_RDWR

curl:

  • CURLE_FILESIZE_EXCEEDED
  • CURLE_FTP_SSL_FAILED
  • CURLE_LDAP_INVALID_URL
  • CURLFTPAUTH_DEFAULT
  • CURLFTPAUTH_SSL
  • CURLFTPAUTH_TLS
  • CURLFTPSSL_ALL
  • CURLFTPSSL_CONTROL
  • CURLFTPSSL_NONE
  • CURLFTPSSL_TRY
  • CURLOPT_FTP_SSL
  • CURLOPT_FTPSSLAUTH
  • CURLOPT_TCP_NODELAY Добавлено в PHP 5.2.1.
  • CURLOPT_TIMEOUT_MS Добавлено в PHP 5.2.3
  • CURLOPT_CONNECTTIMEOUT_MS Добавлено в PHP 5.2.3

GMP:

  • GMP_VERSION Добавлено в PHP 5.2.2.

ming:

  • SWFTEXTFIELD_USEFONT
  • SWFTEXTFIELD_AUTOSIZE
  • SWF_SOUND_NOT_COMPRESSED
  • SWF_SOUND_ADPCM_COMPRESSED
  • SWF_SOUND_MP3_COMPRESSED
  • SWF_SOUND_NOT_COMPRESSED_LE
  • SWF_SOUND_NELLY_COMPRESSED
  • SWF_SOUND_5KHZ
  • SWF_SOUND_11KHZ
  • SWF_SOUND_22KHZ
  • SWF_SOUND_44KHZ
  • SWF_SOUND_8BITS
  • SWF_SOUND_16BITS
  • SWF_SOUND_MONO
  • SWF_SOUND_STEREO

openssl:

  • OPENSSL_VERSION_NUMBER
  • OPENSSL_VERSION_TEXT

snmp:

  • SNMP_OID_OUTPUT_FULL
  • SNMP_OID_OUTPUT_NUMERIC

Semaphore:

  • MSG_EAGAIN
  • MSG_ENOMSG

User Contributed Notes

There are no user contributed notes for this page.
Новые классы
Новые константы классов
Переход с PHP 5.1.x на PHP 5.2.x


Новые константы классов

pdo:

  • PDO::ATTR_DEFAULT_FETCH_MODE
  • PDO::FETCH_PROPS_LATE
  • PDO::FETCH_KEY_PAIR Преобразует 2-колоночный результат в ассоциативный массив. (Добавлено в PHP 5.2.3)

spl:

  • CachingIterator::FULL_CACHE
  • CachingIterator::TOSTRING_USE_INNER
  • SplFileObject::READ_AHEAD
  • SplFileObject::READ_CSV
  • SplFileObject::SKIP_EMPTY

User Contributed Notes

There are no user contributed notes for this page.
Новые глобальные константы
Новые конфигурационные параметры INI
Переход с PHP 5.1.x на PHP 5.2.x


Новые конфигурационные параметры INI

Новые директивы php.ini, добавленные в PHP 5.2.0:

  • allow_url_include Эта опция даёт возможность различать стандартные файловые операции с удалёнными файлами и подключение удалённых файлов. Хотя обычно требуется первое, второе может привести к проблемам с безопасностью. Начиная с PHP 5.2.0, вы можете разрешить операции с удалёнными файлами и при этом запретить их подключение к локальным скриптам. Это конфигурация по умолчанию.
  • pcre.backtrack_limit Лимит обратных ссылок PCRE.
  • pcre.recursion_limit Лимит рекурсии PCRE. Пожалуйста, имейте в виду, что при установке достаточно большого значения в этом параметре, весь доступный стек процесса может быть занят и PHP остановится из-за превышения размера стека, установленного операционной системой.
  • session.cookie_httponly Устанавливает доступ в отсылаемых cookies только через протокол HTTP. Это означает, что cookies не будут доступны скриптовым языкам, например, таким как JavaScript. Эта установка может помочь в борьбе с XSS-атаками, хотя она и поддерживается не всеми браузерами.

Новые директивы в PHP 5.2.2:

  • max_input_nesting_level Ограничивает вложенность входных переменных, по умолчанию 64.

User Contributed Notes

There are no user contributed notes for this page.
Новые константы классов
Сообщения об ошибках
Переход с PHP 5.1.x на PHP 5.2.x


Сообщения об ошибках

Некоторые существующие ошибки (E_ERROR) теперь можно поймать при помощи обработчиков. Если E_RECOVERABLE_ERROR не обработана, она будет вести себя как E_ERROR. Ошибки этого типа записываются в лог как Catchable fatal error.

Это означает, что значение константы E_ALL error_reporting теперь равно 6143, тогда как предыдущее значение было 2047. Так как имена констант не имеют смысла вне PHP, иногда используются их числовые значения. То есть, например, при установке error_reporting через httpd.conf или .htaccess, данное значение нужно будет сменить при переходе на новую версию PHP. То же касается и числовых значений, если они используются вместо имён констант в скриптах.

Как побочный эффект этих изменений, чтобы предотвратить двойное сообщение об ошибке при параметре track_errors выставленном в On, теперь необходимо возвращать FALSE из пользовательских обработчиков, чтобы отобразилось значение $php_errormsg. Это позволяет точно контролировать уровни сообщений.

User Contributed Notes

There are no user contributed notes for this page.
Новые конфигурационные параметры INI
Другие улучшения
Переход с PHP 5.1.x на PHP 5.2.x


Другие улучшения

  • Улучшено управление памятью и увеличен лимит памяти по умолчанию. Новый менеджер памяти выделяет меньше памяти и работает быстрее, чем предыдущая реализация. Он запрашивает память большими блоками и затем управляет кучей сам. Значение memory_limit в php.ini проверяется не при каждом вызове emalloc(), как раньше, а только при действительном запросе памяти у системы. Это означает, что memory_limit гораздо более точен, чем раньше, так как старый менеджер памяти не учитывал дополнительные затраты библиотеки malloc. Благодаря новому механизму может показаться, что используется больше памяти, тогда как на самом деле это не так. Чтобы скомпенсировать это кажущееся увеличение, значение memory_limit также увеличено с 8 до 16 мегабайт.
  • Добавлена поддержка конструкторов в интерфейсах. Это позволяет проверять сигнатуру конструкторов в реализациях интерфейса. Начиная с PHP 5.2.0, интерфейсы могут содержать конструкторы. Если вы объявляете конструктор в интерфейсе, каждая его реализация должна иметь конструктор с той же сигнатурой, что и конструктор интерфейса. Под "сигнатурой" мы понимаем возвращаемый тип и набор параметров, включая указание типов и передачу параметров по ссылке или значению.

User Contributed Notes

There are no user contributed notes for this page.
Сообщения об ошибках
Переход с PHP 5.0.x на PHP 5.1.x
Переход с PHP 5.1.x на PHP 5.2.x


Переход с PHP 5.0.x на PHP 5.1.x

Содержание

  • Основные возможности PHP 5.1.x
  • Changes in reference handling
  • Reading []
  • Integer values in function parameters
  • Class and object changes
  • Extensions
  • Date/time support
  • Changes in database support
  • Checking for E_STRICT

Смотрите также руководство по миграции для версий PHP 5.0.x, 5.2.x и 5.3.x.

User Contributed Notes

There are no user contributed notes for this page.
Другие улучшения
Основные возможности PHP 5.1.x
Appendices


Основные возможности PHP 5.1.x

Некоторые из ключевых возможностей PHP 5.1.x содержат:

  • Полностью переписан код по работе с датами с расширенной поддержкой временных зон.

  • Значительное улучшение производительности по сравнению с PHP 5.0.X.

  • Расширение PDO сейчас включено по умолчанию.

  • Свыше 30 новых функций в различных расширениях и во встроенной функциональности.

  • Свыше 400 различных исправлений ошибок.

User Contributed Notes

There are no user contributed notes for this page.
Переход с PHP 5.0.x на PHP 5.1.x
Changes in reference handling
Переход с PHP 5.0.x на PHP 5.1.x


Changes in reference handling

  • Обзор

  • Code that worked under PHP 4.3.x, but now fails

  • Code that worked under PHP 4.3.x, but now throws an error

  • Code that failed under PHP 4.3.x, but now works

  • Code that should have worked under PHP 5.0.x

  • Warnings that came and went

Обзор

From the PHP script writer's point of view, the change most likely to impact legacy code is in the way that references are handled in all PHP versions post-dating the PHP 4.4.0 release.

Until and including PHP 4.3, it was possible to send, assign or return variables by reference that should really be returned by value, such as a constant, a temporary value (e.g. the result of an expression), or the result of a function that had itself been returned by value, as here:

<?php
$foo = "123";

function return_value() {
    global $foo;
    return $foo;
}

$bar = &return_value();
?>

Although this code would usually work as expected under PHP 4.3, in the general case the result is undefined. The Zend Engine could not act correctly on these values as references. This bug could and did lead to various hard-to-reproduce memory corruption problems, particularly where the code base was large.

In PHP 4.4.0, PHP 5.0.4 and all subsequent PHP releases, the Engine was fixed to 'know' when the reference operation is being used on a value that should not be referenced. The actual value is now used in such cases, and a warning is emitted. The warning takes the form of an E_NOTICE in PHP 4.4.0 and up, and E_STRICT in PHP 5.0.4 and up.

Code that could potentially produce memory corruption can no longer do so. However, some legacy code might work differently as a result.

Code that worked under PHP 4.3, but now fails

<?php
function func(&$arraykey) {
    return $arraykey; // function returns by value!
}

$array = array('a', 'b', 'c');
foreach (array_keys($array) as $key) {
    $y = &func($array[$key]);
    $z[] =& $y;
}

var_dump($z);
?>
<

Running the above script under any version of PHP that pre-dates the reference fix would produce this output:

array(3) {
  [0]=>
  &string(1) "a"
  [1]=>
  &string(1) "b"
  [2]=>
  &string(1) "c"
}

Following the reference fix, the same code would result in:

array(3) {
  [0]=>
  &string(1) "c"
  [1]=>
  &string(1) "c"
  [2]=>
  &string(1) "c"
}

This is because, following the changes, func() assigns by value. The value of $y is re-assigned, and reference-binding is preserved from $z. Prior to the fix, the value was assigned by reference, leading $y to be re-bound on each assignment. The attempt to bind to a temporary value by reference was the cause of the memory corruption.

Such code can be made to work identically in both the pre-fix and the post-fix PHP versions. The signature of func() can be altered to return by reference, or the reference assignment can be removed from the result of func().

<?php
function func() {
    return 'function return';
}

$x = 'original value';
$y =& $x;
$y = &func();
echo $x;
?>

In PHP 4.3 $x would be 'original value', whereas after the changes it would be 'function return' - remember that where the function does not return by reference, the reference assignment is converted to a regular assignment. Again, this can be brought to a common base, either by forcing func() to return by reference or by eliminating the by-reference assignment.

Code that worked under PHP 4.3.x, but now throws an error

<?php
class Foo {

    function getThis() {
        return $this;
    }

    function destroyThis() {
        $baz =& $this->getThis();
    }
}

$bar = new Foo();
$bar->destroyThis();
var_dump($bar);
?>

In PHP 5.0.3, $bar evaluated to NULL instead of returning an object. That happened because getThis() returns by value, but the value here is assigned by reference. Although it now works in the expected way, this is actually invalid code which will throw an E_NOTICE under PHP 4.4 or an E_STRICT under PHP 5.0.4 and up.

Code that failed under PHP 4.3.x, but now works

<?php
function &f() {
    $x = "foo";
    var_dump($x);
    print "$x\n";
    return($a);
}

for ($i = 0; $i < 3; $i++) {
    $h = &f();
}
?>

In PHP 4.3 the third call to var_dump() produces NULL, due to the memory corruption caused by returning an uninitialized value by reference. This is valid code in PHP 5.0.4 and up, but threw errors in earlier releases of PHP.

<?php
$arr = array('a1' => array('alfa' => 'ok'));
$arr =& $arr['a1'];
echo '-'.$arr['alfa']."-\n";
?>

Until PHP 5.0.5, it wasn't possible to assign an array element by reference in this way. It now is.

Code that should have worked under PHP 5.0.x

There are a couple of instances of bugs reported under PHP 5.0 prior to the reference fixes which now 'work'. However, in both cases errors are thrown by PHP 5.1.x, because the code was invalid in the first place. Returning values by reference using self:: now works in the general case but throws an E_STRICT warning, and although your mileage may vary when assigning by reference to an overloaded object, you will still see an E_ERROR when you try it, even where the assignment itself appears to work.

Warnings that came and went

Nested calls to functions returning by reference are valid code under both PHP 4.3.x and PHP 5.1.x, but threw an unwarranted E_NOTICE or E_STRICT under the intervening PHP releases.

<?php
function & foo() {
    $var = 'ok';
    return $var;
}

function & bar() {
    return foo();
}

$a =& bar();
echo "$a\n";
?>

User Contributed Notes

There are no user contributed notes for this page.
Основные возможности PHP 5.1.x
Reading []
Переход с PHP 5.0.x на PHP 5.1.x


Reading []

<?php
class XmlTest {

    function test_ref(&$test) {
        $test = "ok";
    }

    function test($test) { }

    function run() {
        $ar = array();
        $this->test_ref($ar[]);
        var_dump($ar);
        $this->test($ar[]);
    }
}

$o = new XmlTest();
$o->run();
?>

This should always have thrown a fatal E_ERROR, because [] cannot be used for reading in PHP. It is invalid code in PHP 4.4.2 and PHP 5.0.5 upward.

User Contributed Notes

There are no user contributed notes for this page.
Changes in reference handling
Integer values in function parameters
Переход с PHP 5.0.x на PHP 5.1.x


Integer values in function parameters

With the advent of PHP 5.0.x, a new parameter parsing API was introduced which is used by a large number of PHP functions. In all versions of PHP between 5.0.x and 5.1.x, the handling of integer values was very strict and would reject non-well formed numeric values when a PHP function expected an integer. These checks have now been relaxed to support non-well formed numeric strings such as " 123" and "123 ", and will no longer fail as they did under PHP 5.0.x. However, to promote code safety and input validation, PHP functions will now emit an E_NOTICE when such strings are passed as integers.

User Contributed Notes

There are no user contributed notes for this page.
Reading []
Class and object changes
Переход с PHP 5.0.x на PHP 5.1.x


Class and object changes

  • instanceof, is_a(), is_subclass_of() and catch

  • Abstract private methods

  • Access modifiers in interfaces

  • Changes in inheritance rules

  • Class constants

instanceof, is_a(), is_subclass_of() and catch

In PHP 5.0, is_a() was deprecated and replaced by the instanceof operator. There were some issues with the initial implementation of instanceof, which relied on __autoload() to search for missing classes. If the class was not present, instanceof would throw a fatal E_ERROR due to the failure of __autoload() to discover that class. The same behaviour occurred in the catch operator and the is_subclass_of() function, for the same reason.

None of these functions or operators call __autoload() in PHP 5.1.x, and the class_exists() workarounds used in code written for PHP 5.0.x, while not problematic in any way, are no longer necessary.

Abstract private methods

Abstract private methods were supported between PHP 5.0.0 and PHP 5.0.4, but were then disallowed on the grounds that the behaviours of private and abstract are mutually exclusive.

Access modifiers in interfaces

Under PHP 5.0, function declarations in interfaces were treated in exactly the same way as function declarations in classes. This has not been the case since October 2004, at which point only the public access modifier was allowed in interface function declarations. Since April 2005 - which pre-dates the PHP 5.0b1 release - the static modifier has also been allowed. However, the protected and private modifiers will now throw an E_ERROR, as will abstract. Note that this change should not affect your existing code, as none of these modifiers makes sense in the context of interfaces anyway.

Changes in inheritance rules

Under PHP 5.0, it was possible to have a function declaration in a derived class that did not match the declaration of the same function in the base class, e.g.

This code will cause an E_STRICT error to be emitted under PHP 5.1.x.

<?php
class Base {
    function &return_by_ref() {
        $r = 1;
        return $r;
    }
}

class Derived extends Base {
    function return_by_ref() {
        return 1;
    }
}
?>

Class constants

Under PHP 5.0.x, the following code was valid:

Under PHP 5.1.x, redefinition of a class constant will throw a fatal E_ERROR.

<?php
class test {
    const foobar = 'foo';
    const foobar = 'bar';
}

?>

User Contributed Notes

There are no user contributed notes for this page.
Integer values in function parameters
Extensions
Переход с PHP 5.0.x на PHP 5.1.x


Extensions

  • Extensions that are gone from the PHP core

  • Class constants in new PHP 5.1.x extensions

Extensions that are gone from the PHP core

One of the first things you're likely to notice when you download PHP 5.1.x is that several of the older extensions have disappeared. Those extensions that are still actively maintained are available in the PHP Extension Community Library (PECL), at » http://pecl.php.net/.

Removed extensions
Extension | Alternative/Status
ext/cpdf | pecl/pdflib
ext/dbx | pecl/dbx
ext/dio | pecl/dio
ext/fam | Not actively maintained
ext/ingres_ii | pecl/ingres
ext/ircg | Not actively maintained
ext/mcve | pecl/mcve
ext/mnogosearch | Not actively maintained
ext/oracle | ext/oci8 or ext/pdo_oci
ext/ovrimos | Not actively maintained
ext/pfpro | Not actively maintained
ext/w32api | » pecl/ffi
ext/yp | Not actively maintained
ext/activescript | » pecl/activescript

Modules in PECL that are not actively maintained (i.e. have not been supported for some time, have no active maintainer working on them currently, and do not have any PECL package releases), are still available in SVN at » http://svn.php.net/viewvc/pecl. However, unreleased PHP modules are by their nature unsupported, and your mileage may vary when attempting to install or use them.

Class constants in new PHP 5.1.x extensions

The Zend Engine 2.1 API allows extension developers to declare class constants in object oriented extensions. New extensions written for PHP 5.1.x, including SPL, PDO, XMLReader and date, have their constants in the format PDO::CLASS_CONSTANT rather than in the C format PDO_CLASS_CONSTANT in order to minimise pollution of the global namespace in PHP.

User Contributed Notes

There are no user contributed notes for this page.
Class and object changes
Date/time support
Переход с PHP 5.0.x на PHP 5.1.x


Date/time support

Date/time support has been fully rewritten in PHP 5.1.x, and no longer uses the system settings to 'know' the timezone in operation. It will instead utilize, in the following order:

  • The timezone set using the date_default_timezone_set() function (if any)

  • The TZ environment variable (if non empty)

  • "magical" guess (if the operating system supports it)

  • If none of the above options succeeds, UTC

To ensure accuracy (and avoid an E_STRICT warning), you will need to define your timezone in your php.ini using the following format:

date.timezone = Europe/London

The supported timezones are listed, in this format, in the timezones appendix.

Also note that strtotime() now returns FALSE on failure, instead of -1.

User Contributed Notes

There are no user contributed notes for this page.
Extensions
Changes in database support
Переход с PHP 5.0.x на PHP 5.1.x


Changes in database support

  • PDO overview

  • Changes in MySQL support

  • Changes in SQLite support

PDO overview

PHP Data Objects (PDO) were introduced as a PECL extension under PHP 5.0, and became part of the core PHP distribution in PHP 5.1.x. The PDO extension provides a consistent interface for database access, and is used alongside database-specific PDO drivers. Each driver may also have database-specific functions of its own, but basic data access functionality such as issuing queries and fetching data is covered by PDO functions, using the driver named in PDO::__construct().

Note that the PDO extension, and its drivers, are intended to be built as shared extensions. This will enable straightforward driver upgrades from PECL, without forcing you to rebuild all of PHP.

At the point of the PHP 5.1.x release, PDO is more than ready for widespread testing and could be adopted in most situations. However, it is important to understand that PDO and its drivers are comparatively young and may be missing certain database-specific features; evaluate PDO carefully before you use it in new projects.

Legacy code will generally rely on the pre-existing database extensions, which are still maintained.

Changes in MySQL support

In PHP 4, MySQL 3 support was built-in. With the release of PHP 5.0 there were two MySQL extensions, named 'mysql' and 'mysqli', which were designed to support MySQL < 4.1 and MySQL 4.1 and up, respectively. With the introduction of PDO, which provides a very fast interface to all the database APIs supported by PHP, the PDO_MYSQL driver can support any of the current versions (MySQL 3, 4 or 5) in PHP code written for PDO, depending on the MySQL library version used during compilation. The older MySQL extensions remain in place for reasons of back compatibility, but are not enabled by default.

Changes in SQLite support

In PHP 5.0.x, SQLite 2 support was provided by the built-in sqlite extension, which was also available as a PECL extension in PHP 4.3 and PHP 4.4. With the introduction of PDO, the sqlite extension doubles up to act as a 'sqlite2' driver for PDO; it is due to this that the sqlite extension in PHP 5.1.x has a dependency upon the PDO extension.

PHP 5.1.x ships with a number of alternative interfaces to sqlite:

The sqlite extension provides the "classic" sqlite procedural/OO API that you may have used in prior versions of PHP. It also provides the PDO 'sqlite2' driver, which allows you to access legacy SQLite 2 databases using the PDO API.

PDO_SQLITE provides the 'sqlite' version 3 driver. SQLite version 3 is vastly superior to SQLite version 2, but the file formats of the two versions are not compatible.

If your SQLite-based project is already written and working against earlier PHP versions, then you can continue to use ext/sqlite without problems, but will need to explicitly enable both PDO and sqlite. New projects should use PDO and the 'sqlite' (version 3) driver, as this is faster than SQLite 2, has improved locking concurrency, and supports both prepared statements and binary columns natively.

You must enable PDO to use the SQLite extension. If you want to build the PDO extension as a shared extension, then the SQLite extension must also be built shared. The same holds true for any extension that provides a PDO driver

User Contributed Notes

There are no user contributed notes for this page.
Date/time support
Checking for E_STRICT
Переход с PHP 5.0.x на PHP 5.1.x


Checking for E_STRICT

If you only have a single script to check, you can pick up E_STRICT errors using PHP's commandline lint facility:

php -d error_reporting=4095 -l script_to_check.php

For larger projects, the shell script below will achieve the same task:

#!/bin/sh

directory=$1

shift

# These extensions are checked
extensions="php inc"

check_file ()
{
  echo -ne "Doing PHP syntax check on $1 ..."

  # Options:
  ERRORS=`/www/php/bin/php -d display_errors=1 -d html_errors=0 -d error_prepend_string=" " -d error_append_string=" " -d error_reporting=4095 -l $1 | grep -v "No syntax errors detected"`

  if test -z "$ERRORS"; then
    echo -ne "OK."
  else
    echo -e "Errors found!\n$ERRORS"
  fi

  echo
}

# loop over remaining file args
for FILE in "$@" ; do
  for ext in $extensions; do
     if echo $FILE | grep "\.$ext$" > /dev/null; then
       if test -f $FILE; then
         check_file "$FILE"
       fi
     fi
  done
done

User Contributed Notes

designteam at casemumbai dot com 25-Nov-2008 10:39
Example usage:

<?php
//Errors will be printed on the screen with the following line
error_reporting(E_STRICT);

function change (&$var) {
  $var += 10;
}

$var = 1;
change(++$var);
echo "var=$var";
change($var = 5);
echo "var=$var";

?>

More examples:
http://en.wikipedia.org/wiki/E_STRICT
Changes in database support
Переход с PHP 4 на PHP 5.0.x
Переход с PHP 5.0.x на PHP 5.1.x


Переход с PHP 4 на PHP 5.0.x

Содержание

  • Что изменилось в PHP 5.0.x
  • Изменения, повлекшие за собой обратную несовместимость
  • CLI и CGI
  • Миграция конфигурационных файлов
  • Новые функции
  • Новые директивы
  • Базы данных
  • Новая Объектная Модель
  • Сообщения об ошибках

Смотрите также руководство по миграции для версий PHP 5.1.x, 5.2.x и 5.3.x.

User Contributed Notes

There are no user contributed notes for this page.
Checking for E_STRICT
Что изменилось в PHP 5.0.x
Appendices


Что изменилось в PHP 5.0.x

PHP 5 и интегрированный Zend Engine 2 привнесли очень многое в плане производительности и возможностей PHP, но также было приложено максимум усилий для того, чтобы сохранить совместимость с максимальным объемом существующего кода. Поэтому миграция вашего кода с PHP 4 на 5 должна быть крайне проста. Большинство существующего кода на PHP 4 должно запускаться без всяких проблем, но о некоторых различиях все равно необходимо знать, а также не забудьте протестировать ваш код перед сменой версии в production-средах.

User Contributed Notes

There are no user contributed notes for this page.
Переход с PHP 4 на PHP 5.0.x
Изменения, повлекшие за собой обратную несовместимость
Переход с PHP 4 на PHP 5.0.x


Изменения, повлекшие за собой обратную несовместимость

Несмотря на то, что большинство кода на PHP 4 должно работать безо всяких изменений, вам следует обратить внимание на следующие изменения, повлекшие за собой обратную несовместимость:

  • Несколько новых зарезервированных ключевых слов.
  • strrpos() и strripos() теперь используют всю строку искомого параметра (needle).
  • Неправильное использование смещения внутри строки вызывает E_ERROR вместо E_WARNING. Пример неправильного использования: $str = 'abc'; unset($str[0]);.
  • array_merge() теперь принимает в качестве аргументов только массивы. Если была передана переменная, не являющаяся массивом, будет сгенерирована ошибка E_WARNING для каждого такого параметра. Будьте внимательны, потому что ваш код может вдруг начать генерировать ошибки E_WARNING.
  • Переменная сервера PATH_TRANSLATED больше не определяется неявно под Apache2 SAPI, в отличие от ситуации в PHP 4, где ей присваивается то же значение, что и переменной сервера SCRIPT_FILENAME, когда она не определяется Apache. Это изменение было сделано для соответствия » спецификации CGI/1.1. Пожалуйста, обратитесь к » ошибке #23610 для получения дальнейший информации, а также посмотрите описание $_SERVER['PATH_TRANSLATED'] в данном руководстве. Это изменение также имеет место в PHP версий >= 4.3.2.
  • Константа T_ML_COMMENT больше не объявляется расширением Tokenizer. Если директива error_reporting установлена в E_ALL, PHP сгенерирует предупреждение. Несмотря на то, что T_ML_COMMENT не использовалась вообще, она была объявлена в PHP 4. Как в PHP 4, так и в PHP 5 // и /* */ определяются как T_COMMENT. Так или иначе, комментарии /** */ в стиле PHPDoс, которые начиная с PHP 5 анализируются PHP, распознаются как T_DOC_COMMENT.
  • Суперглобальный массив $_SERVER будет создан вместе с переменными argc и argv, если variables_order включает "S". Если вы специально настроили свою систему таким образом, что $_SERVER не создаётся, тогда, конечно, её не будет. Изменение заключается в том, чтобы сделать argc и argv всегда доступными в CLI-версии, вне зависимости от директивы variables_order. Как уже было сказано, CLI-версия теперь всегда будет объявлять переменные argc и argv.
  • Объект без свойств больше не считается "пустым".
  • В некоторых случаях класс должен быть объявлен перед использованием. Это происходит только в том случае, если используются некоторые новые функции PHP 5 (такие как интерфейсы). В остальном поведение остается старым.
  • get_class(), get_parent_class() и get_class_methods() теперь возвращают имена классов/методов так, как они были объявлены (с учетом регистра), что может привести к проблемам со старыми скриптами, которые полагаются на прежнее поведение (имя класса/метода всегда было приведено к нижнему регистру). Возможным решением является поиск этих функций в ваших скриптах и использование в них strtolower(). Изменения относительно регистрозависимости также затрагивают магические предопределенные константы __CLASS__, __METHOD__ и __FUNCTION__. Значения возвращаются именно в том виде, в котором они были объявлены (с учетом регистра).
  • ip2long() теперь возвращает FALSE, а не -1, если в качестве аргумента функции передается неправильный IP-адрес.
  • Если во включенном файле объявлены какие-либо функции, они могут использоваться и в главном файле, вне зависимости от того, располагаются они до return() или после. Если файл включается дважды, PHP 5 генерирует фатальную ошибку, так как функции уже были объявлены, в то время, как PHP 4 не жалуется на это. Рекомендуется использовать include_once() вместо проверки, был ли уже включен файл и условного возврата внутри включенного файла.
  • include_once() и require_once() сначала стандартизируют путь к включенному файлу в Windows, так что при включении A.php и a.php файл включается только один раз.
  • Передача массива в функцию по значению больше не сбрасывает внутренний указатель массива, используемый для доступа к его элементам в данной функции. Иными словами, в PHP 4 при передаче массива в функцию его внутренний указатель сбрасывался внутри функции, тогда как в PHP 5 при передаче массива в функцию данный указатель останется в том же положении, в котором он был до передачи массива в функцию.

Пример #1 strrpos() и strripos() теперь используют в качестве искомого параметра (needle) всю строку

<?php
var_dump(strrpos('ABCDEF','DEF')); //int(3)

var_dump(strrpos('ABCDEF','DAF')); //bool(false)
?>

Пример #2 Объект без свойств больше не считается "пустым"

<?php
class test { }
$t = new test();

var_dump(empty($t)); // echo bool(false)

if ($t) {
    // Будет выполнено
}
?>

Пример #3 В некоторых случаях классы должны быть объявлены перед использованием

<?php

//работает без ошибок:
$a = new a();
class a {
}

//вызывает ошибку:
$a = new b();

interface c{
}
class b implements c {
}

?>

User Contributed Notes

michael dot darmousseh at gmail dot com 03-Feb-2010 05:53
Hack way to fix the array_merge problem so that it works with your existing php4 code

<?php
function array_merge5()
{
    $args = func_get_args();
    foreach($args as $key=>$arg)
        $args[$key] = (array) $arg;
    return call_user_func_array("array_merge", $args);
}
?>

just put it somewhere completely accessible to your codebase and change all of your calls to array_merge to array_merge5.
paul at oconnor-web dot net 10-Apr-2008 04:17
The __call function will also lowercase the method arguement:

<?php
   function __call($method, $args) {
     if ($method == 'Foo') {
       return true;
     } else {
       return false
     }
   }
?>

(= false)
Steven 19-Mar-2008 04:07
Three more that we discovered:

== 1. No longer can re-assign $this ==

The follwoing example works under PHP4 (it outputs "OK"), but produces a fatal error under PHP5:

<?php
  class a
  {
    var $text;
    function a() { $this->text = 'OK'; }
  }

  class b
  {
    var $text = 'NOT OK';
    function b() { $this = new a(); }
  }

  $myClass = new b();
  echo $myClass->text;
?>

== 2. No comments allowed after shorthand echo block ==

The follwoing example works under PHP4, but produces a sytax error under PHP5.

<?=//comment?>

== 3. Constructors return a reference as default ==

The follwoing example works under PHP4, but produces an E_NOTICE notice under PHP5.

<?php
  class MyClass { function MyClass() { echo('OK'); } }
  $myObj = null;
  $myObj &= new MyClass();
?>

Removing the ampersand solves the problem
Aggelos Orfanakos 08-Nov-2007 05:10
As with array_merge(), array_merge_recursive() returns NULL in PHP 5 if a non-array parameter is passed to it.
Sinured 10-Aug-2007 04:43
Not mentioned above: The PHP/FI 2 function style (old_function aka cfunction) is no longer supported as of PHP 5.
nami 26-Jul-2007 07:22
addition of the note on 07-Sep-2004 06:40

if you write down your code like this PHP5 will just work fine:

<?php
     $array_1 = array('key1'=>'oranges','key2'=>'apples');
     $array_2 = array('key3'=>'pears','key4'=>'tomatoes');
     $array_3 = array();
     $arr_gemerged = array_merge($array_1,$array_2,$array_3);
     echo "result:<br>";
     print_r($arr_gemerged);
     echo "<br>";
?>

---

so you have to declare array_3 as array() instead of NULL
kemal djakman 22-Jun-2007 06:11
The handling of accessing empty property of a class error has also changed:
<?php

class Foo {

    var $Bar = 'xxx';

    function F() {
        echo $this->$Bar;
    }
}

$Obj = new Foo();
$Obj->F();

?>

Notice the $ sign after object dereference opr?  $Bar is empty inside method F.   PHP4 would only generate a warning, PHP5 throws a fatal error
Amir Laher 29-Apr-2007 02:34
Some other things to be aware of:

some extra strictness:
* object members can no longer be accessed using array-member syntax
* function-calls with too many arguments will now cause errors.

Also, from PHP5.2, custom session handlers are affected:
* Best not to use global objects in custom session-handling functions. These would get destructed *before* the session is written (unless session_write_close() is called explicitly).
28-Feb-2006 02:03
is_a have been deprecated. You can simply replace all occurences with the new instanceOf operator, although this will break backwards-compatibility with php4.
dward . maidencreek.com 02-Nov-2004 12:54
Another change that we've had problems with while trying to use PHP4 code in PHP5 is how $this is carried across static method calls if they are not declared static in PHP5.  The main issue was that debug_backtrace() now shows the first class with -> instead of the second with :: in the backtrace element when the method in the second class was called statically (using ::) from a method in the first class.
07-Sep-2004 09:40
Be careful with array_merge in PHP5.1 not only a E_WARNING is thrown, but also the result is an empty array. So if you merge two select queries and the last one is empty you will end up with no array at all.

<?php
        $array_1 = array('key1'=>'oranges','key2'=>'apples');
        $array_2 = array('key3'=>'pears','key4'=>'tomatoes');
        $array_3 = null;
        $arr_gemerged = array_merge($array_1,$array_2,$array_3);
        print_r($arr_gemerged);
        echo "<br>";
?>

Result on php4:
Array ( [key1] => oranges [key2] => apples [key3] => pears [key4] => tomatoes )

Result on php5:
Warning: array_merge() [function.array-merge]: Argument #3 is not an array in /removed/by/danbrown/for/manual.php on line 7
john.g 26-Aug-2004 10:45
PATH_TRANSLATED is handy when using Apache's ModRewrite engine, as it gives you the name and path of the resulting file rather than the one that was requested by the user. Since PHP 5.0 and Apache 2 no longer support this variable, I created a workaround by adding an environment variable to my ModRewrite command:

Original:
RewriteRule ^/test/(.*)\.php(.*) /test/prefix_$1.php$2

Adjusted:
RewriteRule ^/test/(.*)\.php(.*) /test/prefix_$1.php$2 [E=TARGET:prefix_$1.php]

I could then find out the resulting file name through the super global $_ENV, for instance:

<?php
echo "The actual filename is ".$_ENV['REDIRECT_TARGET'];
?>

Note: The "REDIRECT_" prefix appears to be allocated automatically by ModRewrite.
cyberhorse 05-Aug-2004 10:07
clone() is a php function now.

if you create a subclass, it no longer uses samename methods in superclass as a constructor.
Что изменилось в PHP 5.0.x
CLI и CGI
Переход с PHP 4 на PHP 5.0.x


CLI и CGI

В PHP 5 были сделаны некоторые изменения в именах исполняемых файлов CLI и CGI. В PHP 5, CGI-версия была переименована в php-cgi.exe (ранее php.exe), а CLI-версия теперь располагается в главной директории (ранее cli/php.exe).

В PHP 5 также появился новый режим: php-win.exe. Он эквивалентен CLI-версии, за исключением того, что php-win ничего не выводит и, соответсвенно, не открывает консоль (окошко dos не появляется на экране). Такое поведение похоже на php-gtk.

В PHP 5, CLI-версия всегда предоставляет глобальные переменные $argv и $argc, вне зависимости от каких-либо директив в php.ini. Даже установка register_argc_argv в off не повлияет на поведение интерфейса командной строки.

Смотрите также справочник по командной строке.

User Contributed Notes

shoebappa at gmail dot com 12-Mar-2008 12:41
I pulled my hair out for 10 hours trying to figure out why my CGI Wrappers would spit out the shell script and not run the code.

From: http://ubuntuforums.org/showthread.php?t=341164&highlight=apache+php

"PHP4 needs a specific configuration so that it won't try to execute the starter script.
Edit /etc/php4/cgi/php.ini, search for cgi.fix_pathinfo and set it to 1.

If you don't do this, PHP5 will work fine (it has cgi.fix_pathinfo compiled right in), but PHP4 will simply output the starter script. (You can even put <?php phpinfo (); ?> inside the starter script and will see the PHP information.)"
Изменения, повлекшие за собой обратную несовместимость
Миграция конфигурационных файлов
Переход с PHP 4 на PHP 5.0.x


Миграция конфигурационных файлов

Так как ISAPI-модули сменили свои имена с php4xxx на php5xxx, вам необходимо произвести некоторые изменения в конфигурационных файлах. Также произошли изменения в именах файлов CLI и CGI. Пожалуйста, обратитесь к соответствующему разделу для получения дополнительной информации.

Изменения в конфигурации Apache минимальны. Пример ниже показывает изменения, которые вам требуется произвести:

Пример #1 Изменения конфигурационных файлах Apache при переходе на PHP 5

# замените эту строку:
LoadModule php4_module /php/sapi/php4apache2.dll

# на эту:
LoadModule php5_module /php/php5apache2.dll

Если ваш веб-сервер работает с PHP в CGI-режиме, вы должны обратить внимание на то, что CGI-версия сменила свое имя с php.exe на php-cgi.exe. В Apache вам нужно произвести изменения наподобие следующих:

Пример #2 Изменения в конфигурационных файлах Apache при переходе на PHP 5, CGI-режим

# замените эту строку:
Action application/x-httpd-php "/php/php.exe"

# на эту:
Action application/x-httpd-php "/php/php-cgi.exe"

При использовании других веб-серверов вам необходимо сменить либо имя CGI, либо имя ISAPI модулей.

User Contributed Notes

There are no user contributed notes for this page.
CLI и CGI
Новые функции
Переход с PHP 4 на PHP 5.0.x


Новые функции

В PHP 5 появилось некоторое количество новых функций. Вот их список:

Массивы:

  • array_combine() - Создает массив, используя один массив для ключей, а другой - для их значений
  • array_diff_uassoc() - Вычисляет различие массивов с дополнительной проверкой индексов, производимой заданной пользователем callback-функцией
  • array_udiff() - Вычисляет различие массивов, используя callback-функцию для сравнения данных
  • array_udiff_assoc() - Вычисляет различие массивов с дополнительной проверкой индексов. Данные сравниваются с использованием callback-функции
  • array_udiff_uassoc() - Вычисляет различие массивов с дополнительной проверкой индексов. Как данные, так и индексы сравниваются при помощи callback-функции
  • array_walk_recursive() - Применяет пользовательскую функцию рекурсивно к каждому элементу массива
  • array_uintersect_assoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов. Данные сравниваются с использованием callback-функции
  • array_uintersect_uassoc() - Вычисляет пересечение массивов с дополнительной проверкой индексов. Как данные, так и индексы сравниваются при помощи callback-функции
  • array_uintersect() - Вычисляет пересечение массивов. Данные сравниваются с использованием callback-функции

InterBase:

  • ibase_affected_rows() - Возвращает количество записей, затронутых предыдущим запросом
  • ibase_backup() - Инициирует задачу резервного копирования в менеджере сервисов и сразу же возвращает управление
  • ibase_commit_ret() - Фиксирует транзакцию, не закрывая её
  • ibase_db_info() - Запрашивает статистику базы данных
  • ibase_drop_db() - Удаляет базу данных
  • ibase_errcode() - Возвращает код ошибки
  • ibase_free_event_handler() - Отменяет зарегистрированный обработчик события
  • ibase_gen_id() - Инкрементирует именованный генератор и возвращает его новое значение
  • ibase_maintain_db() - Выполняет команду поддержки на сервере баз данных
  • ibase_name_result() - Присваивает имя набору результатов
  • ibase_num_params() - Возвращает число параметров в подготовленном запросе
  • ibase_param_info() - Возвращает информацию о параметре в подготовленном запросе
  • ibase_restore() - Инициирует задачу восстановления в менеджере сервисов и сразу же возвращает управление
  • ibase_rollback_ret() - Откатывает транзакцию с сохранением её контекста
  • ibase_server_info() - Запрашивает статистику базы данных
  • ibase_service_attach() - Соединяется с менеджером сервисов
  • ibase_service_detach() - Разрывает соединение с менеджером сервисов
  • ibase_set_event_handler() - Регистрирует callback-функцию, которая вызывается при публикации события
  • ibase_wait_event() - Ожидает события, отправленного базой данных

iconv:

  • iconv_mime_decode() - Декодирует поле MIME-заголовка
  • iconv_mime_decode_headers() - Декодирует сразу несколько полей MIME-заголовков
  • iconv_mime_encode() - Строит поле MIME-заголовка
  • iconv_strlen() - Возвращает количество символов в строке
  • iconv_strpos() - Находит позицию первого вхождения needle внутри haystack
  • iconv_strrpos() - Находит позицию последнего вхождения needle внутри haystack
  • iconv_substr() - Вырезает часть строки

Потоки:

  • stream_copy_to_stream() - Копирует данные с одного потока на другой
  • stream_get_line() - Получает строку из заданного ресурса потока до данного разделителя
  • stream_socket_accept() - Разрешает соединение на сокет, созданный stream_socket_server()
  • stream_socket_client() - Открывает соединение с доменным сокетом Internet или Unix
  • stream_socket_get_name() - Получает имена локальных или удаленных сокетов
  • stream_socket_recvfrom() - Получает данные от сокета, вне зависимости от того, произведено соединение или нет
  • stream_socket_sendto() - Посылает сообщение сокету, вне зависимости от того, произведено соединение или нет
  • stream_socket_server() - Создает доменный сокет Internet или Unix на стороне сервера

Связанные с датой и временем:

  • idate() - Форматирует локальное время/дату в виде целого числа
  • date_sunset() - Время захода солнца для данного дня и месторасположения
  • date_sunrise() - Время восхода солнца для данного дня и месторасположения
  • time_nanosleep() - Задержка на заданное число секунд и наносекунд

Строки:

  • str_split() - Преобразует строку в массив
  • strpbrk() - Ищет любой набор символов в строке
  • substr_compare() - Бинарно-безопасное опционально регистрозависимое сравнение двух строк, начиная со смещения и до определенной длины символов

Другие:

  • convert_uudecode() - Декодирует строку, закодированную uuencode
  • convert_uuencode() - Кодирует строку в uuencode
  • curl_copy_handle() - Копирует дескриптор cURL вместе со всеми его настройками
  • dba_key_split() - Разбивает ключ в строковом представлении в представление массива
  • dbase_get_header_info() - Получает заголовочную информацию базы данных dBase
  • dbx_fetch_row() - Выбирает записи из результата запроса, в котором установлен флаг DBX_RESULT_UNBUFFERED
  • fbsql_set_password() - Меняет пароль указанного пользователя
  • file_put_contents() - Пишет строку в файл
  • ftp_alloc() - Выделяет место для загружаемого файла
  • get_declared_interfaces() - Возвращает массив всех объявленных интерфейсов
  • get_headers() - Выбирает все заголовки, посланные сервером в ответ на HTTP-запрос
  • headers_list() - Возвращает список посланных (или готовых к отправке) заголовков ответа
  • http_build_query() - Генерирует URL-кодированную строку запроса
  • image_type_to_extension() - Возвращает расширение файла
для типа изображения, возвращенного getimagesize(),
exif_read_data(),
exif_thumbnail(),
exif_imagetype()
  • imagefilter() - Применяет фильтр изображения, используя выбранную фазу
  • imap_getacl() - Возвращает ACL для данного почтового ящика
  • ldap_sasl_bind() - Осуществляет привязку к LDAP-директории используя SASL
  • mb_list_encodings() - Возвращает массив всех поддерживаемых кодировок
  • pcntl_getpriority() - Возвращает приоритет любого процесса
  • pcntl_wait() - Ждет или возвращает статус дочернего разветвленного процесса в зависимости от объявления системного вызова waitpid()
  • pg_version() - Возвращает массив с информацией о версии клиента, протокола и сервера (если доступно)
  • php_check_syntax() - Проверяет синтаксис указанного файла
  • php_strip_whitespace() - Возвращает исходный код с удаленными комментариями и пробелами
  • proc_nice() - Изменяет приоритет текущего процесса
  • pspell_config_data_dir() - Изменяет расположение языковых файлов данных
  • pspell_config_dict_dir() - Изменяет расположение основного списка слов
  • setrawcookie() - Посылает cookie без URL-кодирования его значения
  • scandir() - Выводит список файлов и директорий по указанному пути
  • snmp_read_mib() - Читает и анализирует MIB-файл в активное MIB-дерево
  • sqlite_fetch_column_types() - Возвращает массив типов столбцов для определенной таблицы

Замечание:

Модуль Tidy полностью сменил свой API.

User Contributed Notes

There are no user contributed notes for this page.
Миграция конфигурационных файлов
Новые директивы
Переход с PHP 4 на PHP 5.0.x


Новые директивы

В PHP 5 появилось несколько директив php.ini. Вот их список:

  • mail.force_extra_parameters - Принудительно добавляет указанные параметры к списку передаваемых исполняемому файлу sendmail. Эти параметры всегда будут заменять значение пятого параметра mail(), даже в защищенном режиме
  • register_long_arrays - Разрешает/запрещает PHP регистрировать устаревшие длинные массивы $HTTP_*_VARS
  • session.hash_function - Выбирает хэш-функцию (MD5 или SHA-1)
  • session.hash_bits_per_character - Определяет, сколько битов хранится в каждом символе при конвертации данных бинарного хэша во что-то читабельное (с 4 до 6)
  • zend.ze1_compatibility_mode - Включает режим совместимости с Zend Engine 1 (PHP 4)

User Contributed Notes

There are no user contributed notes for this page.
Новые функции
Базы данных
Переход с PHP 4 на PHP 5.0.x


Базы данных

В PHP 5 были произведены некоторые изменения, касающиеся СУБД (MySQL и SQLite).

В PHP 5 клиентские библиотеки MySQL больше не поставляются в комплекте из-за лицензионных и некоторых других проблем. Для получения дополнительной информации читайте соответствующую запись в FAQ.

Также присутствует новый модуль, MySQLi (Improved MySQL), предназначенный для работы с MySQL 4.1 и выше.

Начиная с PHP 5, модуль SQLite встроен в PHP. SQLite - это встраиваемая SQL СУБД, а не клиентская библиотека для соединения с сервером баз данных (таким как MySQL или PostgreSQL). Библиотека SQLite читает и записывает напрямую в файлы базы данных на диске.

User Contributed Notes

There are no user contributed notes for this page.
Новые директивы
Новая Объектная Модель
Переход с PHP 4 на PHP 5.0.x


Новая Объектная Модель

В PHP 5 появилась новая объектная модель. Работа с объектами в PHP была полностью переписана, позволяя достигнуть лучшей производительности и предоставляя новые возможности. В предыдущих версиях PHP работа с объектами производилась аналогично примитивным типам (к примеру, integer и string). Недостатком этого метода являлось то, что семантически весь объект копировался при присвоении переменной или передачи её в качестве параметра функции. При новом подходе на объекты ссылаются по дескриптору, а не по значению (дескриптор можно представить себе как идентификатор объекта).

Многие PHP-программисты даже не в курсе хитростей механизма копирования в старой объектной модели, что означает, что большинство из PHP-приложений будут работать либо вовсе безо всяких изменений, либо с совсем небольшими изменениями.

Новая объектная модель задокументирована в "Справочнике по языку".

В PHP 5, функция, имеющая такое же имя как и класс, будет вызываться в качестве конструктора, только если она определена в этом же классе. В PHP 4 она также вызывалась при определении в родительском классе.

Обратите внимание также на директиву zend.ze1_compatibility_mode для совместимости с PHP 4.

User Contributed Notes

zzo38 07-Oct-2007 08:06
You should be able to clone a object in compatibility of PHP4,PHP5 with:
<?php
 $x=unserialize(serialize($y));
?>
bdas at premiergroup dot uk dot com 25-May-2007 07:49
Since PHP5 upgraded PHP to an OOP language, they CHANGED the metaphor so that when you copy an object, you just get a pointer to it (as in C# and Java) and so therefore they needed to make a way to CLONE objects as well in case you need a REAL copy of the object.

Most cases, clone is not needed, simply because a real copy of an object is usually not mandatory.  In special cases, object cloning can be used to save time in porting.
quinn at strangecode dot com 19-May-2006 08:53
Here is another possible solution for migrating code to php 5 when using $this = 'something' reassignments. In my case, I had several classes  with methods that were self-instantiating with static calls. I was able to simply use a different variable: I changed $this to $_this and it worked the same because I copied an instance of the original object by reference using an instantiation factory method:

class DB {
    function &getInstance()
    {
        static $instance = null;

        if ($instance === null) {
            $instance = new DB();
        }

        return $instance;
    }
    ...

In every method needing access to this object I assigned it to a temporary variable by reference:

    function doSomething ()
    {
        $_this =& DB::getInstance();

        $_this->doSomethingElse();
        $_this->param['id'] = 123;
    }

Which allows method calls or saving data back to the original object.

I originally created classes like this so I didn't need to keep track of instantiations or global objects. I could just call DB::doSomething() and the object is created dynamically or referenced from an already existing object.
Базы данных
Сообщения об ошибках
Переход с PHP 4 на PHP 5.0.x


Сообщения об ошибках

Начиная с PHP 5 был объявлен новый уровень ошибок - E_STRICT со значением 2048. Он позволяет PHP давать советы по способности взаимодействия и будущей совместимости вашего кода, а также отслеживает случаи использования устаревшего кода.

Замечание: E_ALL не включает E_STRICT, так что по умолчанию этот уровень ошибок выключен. Для просмотра этих сообщений вы должны специально включить E_STRICT в используемом вами уровне сообщений об ошибках.

Подробнее смотрите в главе "Предопределенные константы".

User Contributed Notes

Anonymous 31-Mar-2008 05:52
To enable full error reporting (recommended for development boxes) use:

use error_reporting(E_ALL | E_STRICT);

or in php.ini:

error_reporting  =  E_ALL | E_STRICT
Новая Объектная Модель
Classes and Objects (PHP 4)
Переход с PHP 4 на PHP 5.0.x


Classes and Objects (PHP 4)

Содержание

  • class
  • extends
  • Constructors
  • Scope Resolution Operator (::)
  • parent
  • Serializing objects - objects in sessions
  • The magic functions __sleep and __wakeup
  • References inside the constructor
  • Comparing objects

User Contributed Notes

There are no user contributed notes for this page.
Сообщения об ошибках
class
Appendices


class

A class is a collection of variables and functions working with these variables. Variables are defined by var and functions by function. A class is defined using the following syntax:

<?php
class Cart {
    var $items;  // Items in our shopping cart

    // Add $num articles of $artnr to the cart

    function add_item($artnr, $num) {
        $this->items[$artnr] += $num;
    }

    // Take $num articles of $artnr out of the cart

    function remove_item($artnr, $num) {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } elseif ($this->items[$artnr] == $num) {
            unset($this->items[$artnr]);
            return true;
        } else {
            return false;
        }
    }
}
?>

This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.

Внимание

You can NOT break up a class definition into multiple files. You also can NOT break a class definition into multiple PHP blocks, unless the break is within a method declaration. The following will not work:

<?php
class test {
?>
<?php
    function test() {
        print 'OK';
    }
}
?>

However, the following is allowed:

<?php
class test {
    function test() {
        ?>
        <?php
        print 'OK';
    }
}
?>

The following cautionary notes are valid for PHP 4.

Предостережение

The name stdClass is used internally by Zend and is reserved. You cannot have a class named stdClass in PHP.

Предостережение

The function names __sleep and __wakeup are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. See below for more information.

Предостережение

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor (see below).

<?php
class Cart {
    /* None of these will work in PHP 4. */
    var $todays_date = date("Y-m-d");
    var $name = $firstname;
    var $owner = 'Fred ' . 'Jones';
    /* Arrays containing constant values will, though. */
    var $items = array("VCR", "TV");
}

/* This is how it should be done. */
class Cart {
    var $todays_date;
    var $name;
    var $owner;
    var $items = array("VCR", "TV");

    function Cart() {
        $this->todays_date = date("Y-m-d");
        $this->name = $GLOBALS['firstname'];
        /* etc. . . */
    }
}
?>

Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.

<?php
$cart = new Cart;
$cart->add_item("10", 1);

$another_cart = new Cart;
$another_cart->add_item("0815", 3);
?>

This creates the objects $cart and $another_cart, both of the class Cart. The function add_item() of the $cart object is being called to add 1 item of article number 10 to the $cart. 3 items of article number 0815 are being added to $another_cart.

Both, $cart and $another_cart, have functions add_item(), remove_item() and a variable items. These are distinct functions and variables. You can think of the objects as something similar to directories in a filesystem. In a filesystem you can have two different files README.TXT, as long as they are in different directories. Just like with directories where you'll have to type the full pathname in order to reach each file from the toplevel directory, you have to specify the complete name of the function you want to call: in PHP terms, the toplevel directory would be the global namespace, and the pathname separator would be ->. Thus, the names $cart->items and $another_cart->items name two different variables. Note that the variable is named $cart->items, not $cart->$items, that is, a variable name in PHP has only a single dollar sign ($).

<?php
// correct, single $
$cart->items = array("10" => 1);

// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);

// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1);
?>

Within a class definition, you do not know under which name the object will be accessible in your program: at the time the Cart class was written, it was unknown whether the object would be named $cart, $another_cart, or something else later. Thus, you cannot write $cart->items within the Cart class itself. Instead, in order to be able to access its own functions and variables from within a class, one can use the pseudo-variable $this which can be read as 'my own' or 'current object'. Thus, '$this->items[$artnr] += $num' can be read as 'add $num to the $artnr counter of my own items array' or 'add $num to the $artnr counter of the items array within the current object'.

Замечание:

The $this pseudo-variable is not usually defined if the method in which it is hosted is called statically. This is not, however, a strict rule: $this is defined if a method is called statically from within another object. In this case, the value of $this is that of the calling object. This is illustrated in the following example:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        A::foo();
    }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

Результат выполнения данного примера:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

Замечание:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

User Contributed Notes

masonswolf at gmail dot com 16-May-2012 11:38
You can invoke a class above its definitions in some cases, but there are very important exceptions to this behavior. If your class extends another class, and the interpreter doesn't see the extended class first, then it won't be added to the symbol table until the code has stepped through it in runtime. As a result, if you try to invoke it above the definition, you'll get a "class not found" fatal error.

And those suck.

So, to provide an example, the following will output a fatal error
<?php
Bar::bar();
exit;

class Bar extends Foo { } //will fatal because Foo not seen yet

class Foo {
    static function bar() { echo 'yep, this is Foo::bar'; }
}
?>

However, THIS code will work just fine:
<?php
Bar::bar();
exit;

class Foo {
    static function bar() { echo 'yep, this is Foo::bar'; }
}

class Bar extends Foo { } //will work because Foo came first
?>

Notice that if you include a file containing the class you will extend, and then extend the class in the same file as its invocation, you can also get the class not found fatal. This happens even if the 'include' call happens before the child class's definition.

Eg. the following will also output a fatal error
<?php
include_once('file_with_foo.php');

Bar::bar();
exit;

class Bar extends Foo { }
?>

Hope that clarifies things.
pov at fingerprint.fr 09-Dec-2011 01:22
I just discovered a behaviour that has to be mentioned.

Let's consider the following file

<?php
Foo::bar();
exit;

class Foo {
  function bar() { echo 'yep, this is Foo::bar'; }
}
?>

You may expect :
- an error on the Foo::bar call, because the class is not defined
- removing the code after the exit without side-effect

But it won't, and it will output the string !
It seems every class definition is executed at parse-time.

But without errors; if your file is
<?php
Foo::bar();
exit;

class Foo {
  function bar() { echo 'yep, this is Foo::bar'; }
}
class Foo {
  function bar() { echo 'yep, this is another Foo::bar'; }
}
?>
it will still output the first string, not doing any "Already exiting class" error !

So if you intend preventing a double include by doing in an included file :
<?php
if (class_exists('Foo')) { return; }

class Foo {
  static function register() { ... }
}
Foo::register();
?>
the Foo::register method won't be called !

Very strange development choice; I suppose it is due to ascending compatibility.
Hope it can help...
boukeversteegh at gmail dot com 27-Aug-2010 10:28
You can also instantiate objects using variables containing the name of the class:

<?php

$type = 'Foo';
$foo   = new $type();

print_r( $foo );
/* Prints:
Foo Object
(
)
*/
?>

The following works as well:
<?php

$somefoo    = new Foo();
$anotherfoo = new $somefoo();

# so you don't have to do:
$anotherfoo = new get_class( $somefoo)();
?>
Classes and Objects (PHP 4)
extends
Classes and Objects (PHP 4)


extends

Often you need classes with similar variables and functions to another existing class. In fact, it is good practice to define a generic class which can be used in all your projects and adapt this class for the needs of each of your specific projects. To facilitate this, classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class (this is called 'inheritance' despite the fact that nobody died) and what you add in the extended definition. It is not possible to subtract from a class, that is, to undefine any existing functions or variables. An extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.

<?php
class Named_Cart extends Cart {
    var $owner;

    function set_owner ($name) {
        $this->owner = $name;
    }
}
?>

This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts:

<?php
$ncart = new Named_Cart;    // Create a named cart
$ncart->set_owner("kris");  // Name that cart
print $ncart->owner;        // print the cart owners name
$ncart->add_item("10", 1);  // (inherited functionality from cart)
?>

This is also called a "parent-child" relationship. You create a class, parent, and use extends to create a new class based on the parent class: the child class. You can even use this new child class and create another class based on this child class.

Замечание:

Classes must be defined before they are used! If you want the class Named_Cart to extend the class Cart, you will have to define the class Cart first. If you want to create another class called Yellow_named_cart based on the class Named_Cart you have to define Named_Cart first. To make it short: the order in which the classes are defined is important.

User Contributed Notes

geilt at esotech dot org 10-Feb-2012 06:27
I have found this the best way to grab a parents variables and such (that I love to set in the constructor, like standardized table names, etc.). I just call the parents constructor in the child constructor, then change variables inside the child constructor that needs to be customized for that class, or just leave it alone to make sure I understand I am using the parents constructor in the child constructor. (it's a good note and practice of mine.).

<?php
class MyParentClass
{
    $this->table_one = "my_table";
    $this->table_two = "variable_table";
}

class MyChildClass extends MyParentClass
{
    public function construct()
    {
        parent::__construct();

        $this->table_two = "newly_defined_table";

    }
    public function action()
   {
      $table1 = $this->table_one;
      $table2 = $this->table_two;

      return $table1 . " - " . $table2;
   }
}

$myChildClass = new MyChildClass;

echo $myChildClass->action();

//Displays my_table - newly_defined_table
?>
datahell at elxis dot org 23-Dec-2010 11:32
If you have a class that extends an other and both classes have a function with the same name then visibility to both classes should be the same, else you will have a fatal error.

An other interested part in the example bellow is that if visibility of the showName method is private then $this->name() will execute the showName method on class test. If it is public or protected it will execute method showName on class extendTest.

<?php
class test {

    public function __construct() {
    }

    public function name() {
        $this->xname('John');
    }

    private function showName($name) {
        echo 'my name in test is '.$name;
    }
}

class extendTest extends test {

    public function __construct() {
        parent::__construct();
    }

    private function showName($name) {
        echo 'my name in extendTest is '.$name;
    }
}

$test = new extendTest();
$test->name();
?>

result: my name in test is John

If we change visibility of the showName method to public or protected then the result of the above will be:
my name in extendTest is John
admin at dmsoft-wy dot com 27-Sep-2010 05:46
You don't need to include_once the parent class if it's already declared.  You do have to load the parent first and then the child.
bilalghouri at live dot com 14-Sep-2010 01:33
One thing I figured out after a long time about extending a parent class that, if the child class does not have any construct function, it will use its parent's construct.

for example:

<?php
class Main
{
    public $a;

    public function __construct()
    {
        echo '::Parent Class initiated::';

        $this -> a = 'we are in the parent class';
    }
}

class Child extends Main
{
    public function getA()
    {
        return $this -> a;
    }
}

$main = new Main();
$main -> child = new Child;

echo $main -> child -> getA();

//Output - ::Parent Class initiated::::Parent Class initiated::we are in the parent class
?>

However, If we have a constructor in the child class as well:

<?php
class Child extends Main
{
    public function __construct()
    {

    }
    public function getA()
    {
        return $this -> a;
    }
}
?>

Then :

<?php
$main = new Main();
$main -> child = new Child;

echo $main -> child -> getA();

// Output - ::Parent Class initiated::
?>

Note that the parent variable 'a' is not inherited by the child class if the constructor from the parent class isnt called.
This behaviour of extension made me waste a lot of my precious time, as I could not understand why some of my child classes were inheriting parent variables and some were not.
Hope this helps someone..
f4bi0_ at hotmail dot com 29-Jun-2010 11:19
<?php
// what if we want to extend more then one class?

Abstract class ExtensionBridge
{
    // array containing all the extended classes
    private $_exts = array();
    public $_this;

    function __construct(){$_this = $this;}

    public function addExt($object)
    {
        $this->_exts[]=$object;
    }

    public function __get($varname)
    {
        foreach($this->_exts as $ext)
        {
            if(property_exists($ext,$varname))
            return $ext->$varname;
        }
    }

    public function __call($method,$args)
    {
        foreach($this->_exts as $ext)
        {
            if(method_exists($ext,$method))
            return call_user_method_array($method,$ext,$args);
        }
        throw new Exception("This Method {$method} doesn't exists");
    }

}

class Ext1{
 private $name="";
 private $id="";
 public function setID($id){$this->id = $id;}
 public function setName($name){$this->name = $name;}
 public function getID(){return $this->id;}
 public function getName(){return $this->name;}
}

class Ext2{
 private $address="";
 private $country="";
 public function setAddress($address){$this->address = $address;}
 public function setCountry($country){$this->country = $country;}
 public function getAddress(){return $this->address;}
 public function getCountry(){return $this->country;}
}

class Extender extends ExtensionBridge
{
    function __construct()
    {
        parent::addExt(new Ext1());
        parent::addExt(new Ext2());
    }

    public function __toString()
    {
        return $this->getName().', from: '.$this->getCountry();
    }
}

$o = new Extender();
$o->setName("fabio");
$o->setCountry("brazil");
echo $o;
?>
don't hesitate to email me, happy coding! ;)
Frank 10-Jan-2010 09:46
Just a quick example of how PHP will handle a parent calling a function named in both the parent and the child class.  You would think it might use the function the way it is defined in the parent, but it does use the function that is defined in the child.

<?php
class One{
    function showOne(){
        echo 'Function One prints';
    }
    function hitFunction(){
        $this->showOne();
    }
}
class Two extends One{
    function showOne(){
        echo 'Function Two prints';
    }
}

$thistwo = new Two;
$thistwo->hitFunction(); //prints "Function Two prints"
?>
Edward_nl 03-Mar-2006 02:54
If you are using a child-class. Remember to call the constructor of the parent class aswell before you start using it. Otherwise you might get different results then you expected. It is stated in this document, but I got confused by the given example. So, here is my example:

<?php
error_reporting(E_ALL);

class test {
  var $var;

  function test() {
    $this->var = 3;
  }
}

class testing extends test {
   function testing() {
     parent::test();
   }

   function My_test() {
     return $this->var;
   }
}

$p = new testing();
echo $p->My_test();
// Returns 3
alan hogan 26-Nov-2005 05:48
Just a note:  It is possible to have a class inherit from multiple other classes, but only in a one-at-a-time linear hierarchy.

So this works, and C gets A and B functions:

<?php
class A {
  public function af() { print 'a';}
  public function bark() {print ' arf!';}
}
class B extends A {
  public function bf() { print 'b';}
}
class C extends B {
  public function cf() { print 'c';}
  public function bark() {print ' ahem...'; parent::bark();}
}

$c = new C;
$c->af(); $c->bf(); $c->cf();
print "<br />";
$c->bark();
/**results:**/
//abc
//ahem... arf!
?>

This does NOT work:

<?php
class A {
  public function af() { print 'a';}
  public function bark() {print ' arf!';}
}
class B {
  public function bf() { print 'b';}
}
class C extends B, A /*illegal*/ {
  public function cf() { print 'c';}
  public function bark() {print ' ahem...'; parent::bark();}
}

$c = new C;
$c->af(); $c->bf(); $c->cf();
print "<br />";
$c->bark();
//Parse Error
?>
Bash I. 18-Nov-2005 09:43
Here is a simple idea that I use when I need my abstract classes (the inherited classes) implemented before my functional classes.

<?php

    $_CLASSES = array_merge (
        glob ("classes/*/*.abstract.php"),
        glob ("classes/*/*.class.php")
    );

    foreach ($_CLASSES AS $_CLASS) {
        require ($_CLASS);
    }

?>
volte6 at nowhere dot com 31-Mar-2005 10:11
When declaring a class that relies upon another file ( because it extends the class defined in that file ), you should ALWAYS require_once() that file at the top.
This applies even when planning on looping through and including everything in the folder. Use require_once() in your loop, and at the top of the file that NEEDS the include.
tomnezvigin at comcast dot net 06-Mar-2005 05:19
This may seem obvious, but check this scenario. You have a class folder:

+ class
--classA.php
--classB.php
--classC.php
--mainClass.php

Here... classA, classB, classC all extend the mainClass.

If you try to create a function that automatically includes all of the classes in a folder, normally, they are included alphabetically.

When you try to instantiate classC, for example, you will get an error:

"Cannot inherit from undefined class mainClass"

EVEN IF you instantiate the mainClass before you instantiate all of the other classes.

In other words, make sure your primary class is included before all others.
Msquared 19-Nov-2004 06:48
Multiple inheritence is often more trouble than it's worth.  For example, you have a class foo that inherits from both class bar and class baz.  Classes bar and baz both have a fubar() method.  When you create a foo object and call its fubar() method, which fubar() method is called: bar's or baz's?

It seems to me that using aggregate to glue one class's methods and data to another object is a bit like Ruby's fixins, but I could be wrong...

[[Editor's note:
The aggregate_* functions have been dropped, as of PHP 5
-S
]]
efredin at redtempest dot com 02-Mar-2004 05:35
It is possible to override a method innherited from a parent class by simply re-defining the method (for those of us who enjoy using abstract classes).

<?php
class A
{
    var $foo;

    function A()
    {
        $this->foo = "asdf";
    }

    function bar()
    {
        echo $this->foo." : Running in A";
    }
}

class B extends A
{
    function bar()
    {
        echo $this->foo." : Running in B";
    }
}

$myClass = new B;
$myClass->bar();
?>
mazsolt at yahoo dot com 04-Jul-2003 08:49
Just a simple example about inheritance:

<?php
class a1{
  var $a=10;
  function a1($a){
     $this->a=$a;
  }
}

class a2 extends a1{
  var $x=11;
  function a2($x,$y){
     $this->x=$x;
     parent::a1($y); // or a1::a1($y) or $this->a1($y)
  }
}

class a3 extends a2{
  var $q=999;
}

$x=new a3(99,9);
echo $x->a,"<br>",$x->x,"<br> ",$x->q;
?>

The output will be:

9
99
999
calimero at creatixnet dot com 22-Jun-2003 08:58
Just a quick note to make things more clear : while multiple inheritance is not allowed, several levels of single inheritance  ARE ALLOWED indeed. Just test this example :

<?php
class A {
    var $name='A';

    function disp() {
        echo $this->name;
    }
}

class B extends A {
    var $name='B';
}

class C extends B {
    var $name='C';
}

$truc = new C() ;
$truc->disp(); // Will output C
?>

This is especially important to keep in mind while building a huge object hierarchy. for example :

+GenericObject
->+ Person
->->Employee
->+Computer
->->+WorkStation
->->-> PPC
->->-> Intel
->->+Server
->->->LDAPServer
->->->IntranetWebServer

.. and so on. Multiple level hierarchy relationship are possible in a tree-like structure (each child has one and only one parent, except for the root object).
quinton at free dot fr 10-Jun-2003 01:07
a nice example using extends and multiple classes  and constructors.

<?php

class CoreObject {
  var $name;

  function CoreObject($name){
    $this->_constructor($name);
  }

  function _constructor($name){
    $this->name = $name;
  }

  function show(){
    printf("%s::%s\n", $this->get_class(), $this->name);
  }

  function get_class(){
      return get_class($this);
  }
}

class Container extends CoreObject{
 var $members;
 function Container($name){
   $this->_constructor($name);
 }

 function &add(&$ref){
   $this->members[] = $ref;
   return ($ref);
 }

  function show(){
   parent::show();
   foreach($this->members as $item){
     $item->show();
   }
 }
 function apply(){
 }
}

class Person extends CoreObject{
  function Person($name){
    $this->_constructor($name);
  }
}

class Family extends Container {

 var $members;
 function Family($name){
   $this->_constructor($name);
 }
}

echo "<pre>\n";

$family = new Family('my family');
$family->add(new Person('father'));
$family->add(new Person('mother'));
$family->add(new Person('girl'));
$family->add(new Person('boy'));

$family->show();

print_r($family);

?>
inerte is my hotmail.com username 27-Sep-2002 01:36
[Editor's note: For an alternative to multiple inheritance, see the dynamic binding via object aggregation in the corresponding section of the manual.]

Multiple Inheritance is not supported but it is easy to emulate it:

<?php
class multipleInheritance
{
    function callClass($class_to_call)
    {
        return new $class_to_call();
    }
}

class A
{
    function insideA()
    {
        echo "I'm inside A!<br />";
    }
}

class B
{

    function insideB()
    {
        echo "I'm inside B!<br />";
    }
}

class C extends multipleInheritance
{
    function insideC()
    {
        $a = parent::callClass('A');
        $a->insideA();
        $b = parent::callClass('B');
        $b->insideB();
    }
}

$c = new C();
$c->insideC();
?>

---
This will succesfully echo:
I'm inside A!
I'm inside B!
schultz at rancon dot de 15-Aug-2002 10:37
This prints out 'ab'.  No need to create a new instance of a, therefor both methods still exists with same name.

<?php

class a {
  function samename(){
    echo 'a';
  }
}

class b extends a{
  function samename(){
    echo 'b';
  }
  function b(){
    a::samename();
    b::samename();
  }
}

$test_obj = new b();
?>
griffon9 at hotmail dot com 18-Jul-2002 04:42
Just to clarify something about inheritance. The following code :

<?php
class a
{
     function call()
     {
          $this->toto();
     }

     function toto()
     {
          echo('Toto of A');
     }
}

class b extends a
{
     function toto()
     {
          echo('Toto of B');
     }
}

$b=new b;
$b->call();

?>

...will correctly display "toto of B" (that is, the function declared in the parent is correctly calling the redefined function in the child)
php_AT_undeen_DOT_com 11-Dec-2001 11:31
if the class B that extends class A does not have a constuctor function (i.e. a function named B), then the constructor function of A will be used instead, you don't need to make a constructor in B just to call the constructor of A.

For example:

<?php
class A
{
  function A()
    {
      echo "HEY! I'm A!\n";

    }
}

class B extends A
{
}

$b = new B();
?>

produces the output:
HEY! I'm A!
bpotier at edreamers dot org 07-Nov-2001 12:08
Just one thing that may seem obvious but not mentionned in this page is that you need to include/require the file containing the parent class or else you'll get an error:

<?php
require(dirname(__FILE__).'/'.'myParent.php');
// ...
myChild extends myParent {
  // ...
}
// ...
?>
class
Constructors
Classes and Objects (PHP 4)


Constructors

Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base class will be called, if it exists.

<?php
class Auto_Cart extends Cart {
    function Auto_Cart() {
        $this->add_item("10", 1);
    }
}
?>

This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can take arguments and these arguments can be optional, which makes them much more useful. To be able to still use the class without parameters, all parameters to constructors should be made optional by providing default values.

<?php
class Constructor_Cart extends Cart {
    function Constructor_Cart($item = "10", $num = 1) {
        $this->add_item ($item, $num);
    }
}

// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;

// Shop for real...
$different_cart = new Constructor_Cart("20", 17);
?>

You also can use the @ operator to mute errors occurring in the constructor, e.g. @new.

<?php
class A
{
    function A()
    {
        echo "I am the constructor of A.<br />\n";
    }

    function B()
    {
        echo "I am a regular function named B in class A.<br />\n";
        echo "I am not a constructor in A.<br />\n";
    }
}

class B extends A
{
}

// This will call B() as a constructor
$b = new B;
?>

The function B() in class A will suddenly become a constructor in class B, although it was never intended to be. PHP 4 does not care if the function is being defined in class B, or if it has been inherited.

Предостережение

PHP doesn't call constructors of the base class automatically from a constructor of a derived class. It is your responsibility to propagate the call to constructors upstream where appropriate.

Destructors are functions that are called automatically when an object is destroyed, either with unset() or by simply going out of scope. There are no destructors in PHP. You may use register_shutdown_function() instead to simulate most effects of destructors.

User Contributed Notes

There are no user contributed notes for this page.
extends
Scope Resolution Operator (::)
Classes and Objects (PHP 4)


Scope Resolution Operator (::)

Предостережение

The following is valid for PHP 4 and later only.

Sometimes it is useful to refer to functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this.

<?php
class A {
    function example() {
        echo "I am the original function A::example().<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am the redefined function B::example().<br />\n";
        A::example();
    }
}

// there is no object of class A.
// this will print
//   I am the original function A::example().<br />
A::example();

// create an object of class B.
$b = new B;

// this will print
//   I am the redefined function B::example().<br />
//   I am the original function A::example().<br />
$b->example();
?>

The above example calls the function example() in class A, but there is no object of class A, so that we cannot write $a->example() or similar. Instead we call example() as a 'class function', that is, as a function of the class itself, not any object of that class.

There are class functions, but there are no class variables. In fact, there is no object at all at the time of the call. Thus, a class function may not use any object variables (but it can use local and global variables), and it may not use $this at all.

In the above example, class B redefines the function example(). The original definition in class A is shadowed and no longer available, unless you are referring specifically to the implementation of example() in class A using the ::-operator. Write A::example() to do this (in fact, you should be writing parent::example(), as shown in the next section).

In this context, there is a current object and it may have object variables. Thus, when used from WITHIN an object function, you may use $this and object variables.

User Contributed Notes

singh206 at gmail dot com 22-Jul-2008 11:12
Using PHP 4, I was unable to see an easy method for retrieving static constants in a library, as well as static functions.  There was no need to set variables, as the library is final, used for Configuration settings.

<?php
class StaticLibrary
{
    //static constants are set here
    function finalConstants(&$Vars)
    {
        $Vars['someVar']        = 'Hello';
        $Vars['anotherVar']     = 'World';
        $Vars['moreVars']       = 'Keep It Coming';
    }

    //usage: StaticLibrary::vars('someVar')
    function vars($v)
    {
               static $Vars;
             if (!is_array($Vars)) { $Vars = array(); StaticLibrary::finalConstants($Vars); } //setup access to the static contants in our Final library
             return($Vars[$v]); //return some var
      }

    //usage: StaticLibrary::staticFunction('Some string and I want to ')
    function staticFunction($str)
    {
            $str .= 'freak that string!';
            return $str;
    }
}
?>

  I appreciate the ideas below!!
philipp dot feigl at gmail dot com 10-Dec-2007 06:06
As already pointed out in a previous comment, there is no way to statically access variables, i wrote this small workaround

<?php
class A {
    var $MY_VIRTUAL_CONST = 1;
    function MY_VIRTUAL_CONST() { $vars = get_class_vars(__CLASS__); return $vars[strToUpper(__FUNCTION__)]; }
}

echo A::MY_VIRTUAL_CONST();
?>

This magically retrieves the correct value without creating an object instance and its easily copy & pasteable, as the methods content is completly generic.
Robert Chapin 24-Jun-2007 07:42
I revised this example to give a better feel for the scope and overloading rules in PHP 4.

<?php
class A {
    function example() {
        echo "I am the original function A::example().<br />\n";
        $this->other();
    }
    function other() {
        echo "I am the original function A::other().<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am the redefined function B::example().<br />\n";
        A::example();
    }
    function other() {
        echo "I am the redefined function B::other().<br />\n";
    }
}

// there is no object of class A.
// this will print
//   I am the original function A::example().<br />
//   PHP Fatal error:  Call to a member function on a non-object in test.php on line 5
A::example();

// create an object of class B.
$b = new B;

// this will print
//   I am the redefined function B::example().<br />
//   I am the original function A::example().<br />
//   I am the redefined function B::other().<br />
$b->example();
?>

Robert Chapin
Chapin Information Services
deadimp at gmail dot com 06-Feb-2007 09:04
I've noticed that you can't easily obtain a re-scoping of a function-to-object by external means, and it can only really be done by functions ["methods" to be proper] inside the class.
I dub this phenomon "inability to externally modifiy scope resolution of class method", 'cause I don't really know the technical name. (Maybe something else along the lines of "inability to combine scope resolution and member selector operators".)
Enough of this, on to the example:
<?php
class Base {
 var $a=5;
 function Func() {
  echo "Base::Func $this->a<br>";
 }
}
class Child extends Base {
 function Func() {
  $this->a=35;
  Base::Func();
  //$this->Base::Func(); //Won't work either
  echo "Child::Func $this->a<br>";
 }
}
$obj=new Child;
$obj->Func(); //That works, outputs as expected
$obj->Base::Func(); //ERROR - See below
?>
As for the error, I get the Hebrew "double colon", as Shachar Shemesh mentioned: "parse error, unexpected T_PAAMAYIM_NEKUDOTAYIM"
I find it odd that I can't do this, and using C++ (where you are able to do this), I feel restricted in this sense.
And I can't think of any workarounds right now, aside from using this scope resolution in the class scope.

NOTE: I'm using PHP 5.0.5 right now (used to be using 4.x, but might've switched it in xampp)
Ken Ismert -- kismert_at_gmail_dot_com 14-Sep-2006 06:31
You can simulate the PHP 5 self keyword for static objects in PHP 4 by simply using the class name:

<?php
class A {
    function static1() {
        return '1';
    }
    function static2() {
        // equivalent to self::static1() in PHP 5
        return A::static1() . ' and 2';
    }
}
// treat class A as static.
// this will print
//  1 and 2
A::static2();
?>

The A:: reference works just as well internally as externally.
Shachar Shemesh 09-Sep-2006 12:41
The PHP lexical analyzer gives this token the name "T_PAAMAYIM_NEKUDOTAYIM". It might as well have been written in Hebrew. Wait, it IS written in Hebrew. It means "double colon".

I'm writing this comment mostly so that people who are searching the web for what the #(!(@*&#$ errors such as "unexpected T_PAAMAYIM_NEKUDOTAYIM" or "missing T_PAAMAYIM_NEKUDOTAYIM" mean get to the right page in the PHP manual.

Shachar
docey 28-Jul-2006 11:38
after doing some research as the manual was somewhat
vague, i found out that using $this in a class-function is
not fatal as the manual implied, its not even a warning.

it simply comes with a notice saying: $this is undefined.

it appears the class-function is just as a global function.
and as such the static keyword holds its value after scope
changes.

however it seems to also holds its value after the class
gets instanced. take a simple counter function thats a
member of a class. make a few calls to the counter to
let it count to lets say 3. then instance the class and let
it count it again 3 times. you think the score is now 3,
infact its 6.

so one simple way to find out if a function is called from
a instanced class or not is to have the constructor set a
class variable and then check for it using isset. since in
the class-function scope the $this is unavailable isset
will return false. but when the class has been instanced
it will return true.

btw, i tested it with php4.4.2CLI.

hope this will clear somethings up.
rudy at sandbenders dot ca 14-Nov-2005 10:20
my last note is actually not 100% correct... as it is, trying to return a reference to an element of the class variables array won't work, even though the classVars function is declared as (possibly) returning a reference... the correct way to return a reference to one of your class variables would be

<?php

class theClass {
    ...
    function &classVars($name = NULL, ...) {
        static $myClassVars;
        ...
        $myRef =& $myClassVars[$name];

        return($myRef);
    }
}

?>

which works as expected when you're looking for a reference. This should only be necessary when you're trying to return a reference to a piece of the array as opposed to the whole array itself. Simply doing this

<?php

return($myClassVars);

?>

works as expected, ie: you can get a reference to the whole array without needing to explicitly create a reference to it before returning.
rudy at sandbenders dot ca 13-Nov-2005 10:05
Since re-posting a simplified version of the peterjoel.com solution to class variables in php4 was kinda lame, here's the modified solution to give you one function (per class) that allows you to use any number of 'class' variables...

<?php

class theClass {
    function &classVars($name = NULL, $value = NULL) {  // The classVars function is (possibly) returning a reference...
        static $myClassVars;  // Define a static var to hold our 'class' vars...

        if (!is_array($myClassVars)) {  // Initialize the array if it isn't already...
            $myClassVars = array();
        }

        if (!is_null($name) && !is_null($value)) {  // If we got two arguments, set the class var that was passed...
            $myClassVars[$name] = $value;
        }

        if (!is_null($name)) {  // If we got one argument, return the var it's referring to...
            return($myClassVars[$name]);
        } else {
            return(NULL);
        }
    }
}

// Setting class variables...

theClass::classVars("varOne", "valueOne");
theClass::classVars("varTwo", "valueTwo");

// Getting class variables...

$myRef = &theClass::classVars("varOne");
echo theClass::classVars("varTwo");

?>

You should be able to store anything in your class vars this way, and depending on how you call the function, you can have either a copy or a reference to the class var returned (see manual on 'returning by reference'...) Again, hope this helps someone...
rudy at sandbenders dot ca 13-Nov-2005 09:40
'emulating' class variables in php4... peter at textstore dot c() dot il  put me on the right track... I came up with the following and then before posting this realized that peterjoel.com has already posted almost the exact same thing... anyways, this is a little simpler and only involves one function instead of a getter/setter pair...

class myClass {
    function &myVar($arg = NULL) {
        static $myClassVar;
        if (!is_null($arg)) {
            $myClassVar = $arg;
        }
        return($myClassVar);
    }
}

// Setting the 'class' var...

myClass::myVar($myNewClassVar);

// Getting the 'class' var...

$classVarRef = &myClass::myVar();

This should let you set up 'class' vars that will hold anything you can reference... with a little creative array usage, you could modify this to allow any number of class vars without having to write the same above function for each one... hope someone finds it useful...
JDS <jeff at newtnotes dot com> 31-Aug-2005 07:10
Using an anonymous class instance via the scope resolution operator does not appear to call the constructor method of the class.  Thus, any "stuff" set up within a constructor method (the method called when creating a new instance of a class) will not get set up using anonymous classes.

So for example something like this

<?php
Class A{
    var $thing;
    function A(
        $this->thing = "hello";
    )
    function get ($var){
        return $this->$var;
    }
}

echo A::get('thing');
?>

will not print anything as A::thing does not get "set up" outside of the constructor.

You would have to create an instance of class A to get any value for A::thing.

For example:
<?php
$a = new A();
echo $a->get('thing');
?>
(prints "hello")

This is based on my observations and not from any official documentation.  I may be wrong about the details.
evert at collab dot nl 28-Aug-2005 01:21
A note to RichardBronosky's suggestion:

This is a very insecure method, never unserialize user data because they might be able upload a totally different class.
They can only specify properties, not methods but if they can research your code they might be able to do uninteded stuff or create a XSS attack.

So only unserialize user-data when you are in a controlled safe enviroment.

Evert
RichardBronosky (firstname at lastname dot com) 09-May-2005 02:33
In reply to tim dot ward at stivesdirect dot com:
I had a need to to do a very similar thing.  I wrote a class that will be used to create an object which can serialize itself into a cookie and be used to recover itself from the cookie later.  To do the recovery you must use the Scope Resolution Operator (::) to call a function as a class function (vs. and object function).  The recovery is very simple to initiate because there is only one line of code to call (e.g. $the_object = the_class::the_function(); )  But the function you call must do a ton of stuff, and call a few other functions within the class.  This is where the problem lies.

I would like to thank <brooke at jump dot net>, <pollita at php dot net>, and <MagicalTux at FF.ST> (from http://php.net/manual/en/function.get-class.php) for leading me to the solution.

<?php
class foo
{
   function get_object_from_cookie(...)
   {
      ...
      return unserialize($decrypted_cookie_data);
   }
   function recover_from_cookie()
   {
      ...prepare to recover...
      // The next line is the tricky part.
      $o = call_user_func(array(__CLASS__, 'get_object_from_cookie'), $encryption_secret, $cookie_name);
      $temp = $o->get_stuff();
      $o->other_stuff = $o->do_calculate($temp);
      $o->do_complicated_things();
      return $o;
   }
}
$bar = foo::recover_from_cookie();
...
?>

I hope that saves someone an hour.  It sure would have saved me one.
mark at branly dot com 07-Mar-2005 02:53
I didn't see where this issue was addressed so in regards to this post:

\\-------\\//-------//
when using "::" operator inside class functions, you can achieve quite interesting results. let's take this example:

  class cCat {
   function Miew(){
     // cCat does not have a member "kind", but cDog has, and we'll use it
     echo "I am ".$this->kind.", and I say MIEW\n";

     // here things are even stranger: does cCat class
     // support WhoAmI function? guess again...
     $this->WhoAmI();
   }
  }

  class cDog {
   var $kind = "DOG";
   function Bark(){
       // let's make this dog act like a cat:)
       cCat::Miew();
   }

   function WhoAmI(){
     echo "Yes, I'm really ".$this->kind."!";
   }
  }

  $dog = new cDog();
  echo $dog->Bark();

outputs:
I am DOG, and I say MIEW
Yes, I'm really DOG!

The interesting thing here is that cDog is not descendant of cCat nor vice versa, but cCat was able to use cDog member variable and function. When calling cCat::Miew() function, your $this variable is passed to that function, remaining cDog instance!

It looks like PHP doesn't check if some class is an ancestor of the class, calling function via '::'.

//------//\\--------\\

The problem here is not that PHP is not checking ancestry. The problem is that "$this" refers to the calling object $dog even though it is referenced inside the cCat class definition. Since a cCat is never instantiated, $this has not been scoped to it.

To further illustrate the point, if you never instatiate dog (or any object for that matter), $this will never be set and when you statically call the miew function, you will get the following output:

"I am , and I say MIEW"

This flexibility of member handling, PHP does not afford to methods and as such the second line of the miew function will generate a fatal error reporting that the method has been called from a non object.

If you did want to take it one step further in the whole ancestry guessing issue, try instatiating cCat and calling the miew function. You will get the same result as above *EXCEPT* the fatal error will inform you the function has not been defined.

So, there you have it--PHP DOES NOT guess at inheritance.
mark@thedarkside 24-Feb-2005 03:04
Carrying on from the previous note, it is possible to call a member function statically using a variable for the name of the class, i.e.:

<?php
class MyObject {
   function myfunc() {
      return "Hello! ($this)";  // '$this' to determine whether it is being called statically
   }
}

$type = "MyObject";
$object = new $type();

$message = $object->myfunc();
$message = MyObject->myfunc();
$message = call_user_func(array(&$type, "myfunc"));

O.K., so it's not using the scope resolution operator, but it does what you want... it calls 'myfunc' statically from the class named by $type.
Tom Wiltshire 24-Feb-2005 04:33
It's worth noting that you can't use a variable with this operator.
The following is legal:

    class MyObject {
        function myfunc() {
            return "Hello!";
        }
    }
    $type = "MyObject";
    $object = new $type();
    $message = $object->myfunc();

(Puts "hello" in $message)

You can also use the scope operator:

    $message = MyObject::myfunc();

However, the following is NOT legal:

    $message = $type::myfunc();

It's a pity, 'cos right now I've got a situation where it'd be really handy, but that's the way it goes!
stefano at obliquid dot it 07-Jul-2004 05:22
peter has a good point to suggest the use of static function variables instead of static class variables that PHP 4 does not support.

Unfortunately, also the first sentence of the manual is misleading "... refer to functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this.".

You cannot use the :: operator on class variables since there are no static class variables. I lost some time trying to refer to class variable with this operator, so I think it may be useful to post a warning.

http://dev.obliquid.com
tango23 at inbox dot lv 06-May-2004 07:20
>> That's how to make class' static variable in PHP4.

Note, that nobody seems to have a way of actually making a global static server-wide object in PHP.

All the static/class var ways above work only within a single PHP page.

If you want to do something like:

class Logger
{
   ...
   function Logger($filepath)
   ...
}

in some global include file:
$logobj = new Logger("mylogfile");

and then in all of your pages:

$logobj->log("my message");

and there is no way you can make this logobj static (such that all your pages can refer to without making unncecessary copies).

Can't be done with using uninstantiated Logger::log() funcs either, because you are not setting the logfile filepath parameter anywhere persistent.

The only kludge seems to be to use the filepath as a global variable and use Logger:: syntax.
altherac at yahoo dot fr 14-Mar-2004 02:28
Using a class function is a good way to write a Singleton pattern in php 4 using a static variable.

The sample code below shows the pattern in action :

<?
    class Singleton
    {
        var $_info = null;

        function Singleton() {
            $this->_info = 'Original value';
        }

        function getInfo() {
            return $this->_info;
        }

        function setInfo($info) {
            $this->_info = $info;
        }

        function &getInstance() {
            static $instance = null;

            if (is_null($instance)) {
                $instance = new Singleton();
            }
            return $instance;
        }
    }

    $a = & Singleton::getInstance();
    $b = & Singleton::getInstance();
    $a->setInfo('Hi, my name is A');
    echo $b->getInfo();

?>

I have seen some Singleton pattern implementations that were using an external function to instanciate the object, but I don't think it is the best way to implement the pattern.

You may want to force the getInstance() function to be called in a static way with the :: operator by testing if $this is set and raising an error or returning a null value (depending on your design).
Rami Kayyali (rami at bluecubex dot com) 07-Nov-2003 08:20
Regarding the note by "gk at proliberty dot com". No, eval() isn't superior to call_user_func(), eval() has security issues and performance overhead.
To achieve the same results using your example with call_user_func, simply pass $this_class by reference. This is probably because call_user_func is passing a copy of $this_class.

<?php

function init(&$this_class, $current_class, $params= NULL ){
    $this_class->classFiles[] = __FILE__;

    $parent_class=get_parent_class($current_class);
    if( !empty($parent_class)){
        // call_user_func() NOW DOES CORRECTLY UPDATE $this_class->classFiles :)
        call_user_func(array($parent_class,'init'),
        &$this_class,$parent_class,$params);
    }

} // init()

?>

But please note, call-time pass-by-reference has been deprecared, or at least, PHP 4.3.2 says so.

Conclusion: Minimize using eval as much as possible, many projects had major security issues because they were using eval().
brooke at jump dot net 07-Nov-2003 03:27
Someone mentioned that eval was better than call_user_func because the latter would not result in updates to the objects. I'm not sure this is the right place for such a debate, but if it is, then the right way is:

call_user_func(array(&this, $method), $arg1, $arg2);

You put a reference to (instead of a copy of) this in the array which you pass on.
wikiz at studentas dot lt 15-Jun-2003 05:40
when using "::" operator inside class functions, you can achieve quite interesting results. let's take this example:

  class cCat {
    function Miew(){
      // cCat does not have a member "kind", but cDog has, and we'll use it
      echo "I am ".$this->kind.", and I say MIEW\n";

      // here things are even stranger: does cCat class
      // support WhoAmI function? guess again...
      $this->WhoAmI();
    }
  }

  class cDog {
    var $kind = "DOG";
    function Bark(){
       // let's make this dog act like a cat:)
       cCat::Miew();
    }

    function WhoAmI(){
      echo "Yes, I'm really ".$this->kind."!";
    }
  }

  $dog = new cDog();
  echo $dog->Bark();

outputs:
I am DOG, and I say MIEW
Yes, I'm really DOG!

The interesting thing here is that cDog is not descendant of cCat nor vice versa, but cCat was able to use cDog member variable and function. When calling cCat::Miew() function, your $this variable is passed to that function, remaining cDog instance!

It looks like PHP doesn't check if some class is an ancestor of the class, calling function via '::'.
gk at proliberty dot com 28-May-2003 06:33
Contrary to the comment above, I have found that call_user_func()
is inferior to eval() because call_user_func() does not correctly
update objects passed by reference.

In the example below, each of my subclasses calls init(), passing
a reference to the current object, whose class variables are
initialized by classes in the hierarchy. The class variable
$this->classFiles contains the paths of each file for classes in
the hierarchy. It is not updated correctly using call_user_func()
but eval() works fine.

<?php
///////////////////////////////////////////////////////
/*
  xobj( );
    constructor
    SUBCLASSES MUST NOT have any constructors
*/
/////////////////////////////////////////////////////////
function xobj( $params= NULL ){

    $current_class=get_class($this);
    $this->init($this, $current_class, $params);
    // $this->classFiles[0] is the file containing the final subclass
    $this->classFile=$this->classFiles[0];
    print_r($this->classFiles); exit;
    $this->_init($params);
}

///////////////////////////////////////////////////////
/*
  void init(&$this_class, $current_class, $params= NULL );
    initialization
    this class MUST be overridden to set $this->classFiles correctly:
    initialization requires __FILE__ to get the path of every class file
*/
/////////////////////////////////////////////////////////
function init(&$this_class, $current_class, $params= NULL ){
    $this_class->classFiles[] = __FILE__;

    $parent_class=get_parent_class($current_class);
    if( !empty($parent_class)){
        eval("$parent_class::init(\$this_class, \$parent_class, \$params);");
        // call_user_func() DOES NOT CORRECTLY UPDATE $this_class->classFiles:
        //call_user_func(array($parent_class,'init'),
$this_class,$parent_class,$params);
    }

} // init()

?>

RESULT, using eval():
Array
(
    [0] => /usr/local/apache/htdocs/common/php/xobj/xobj_subclass.php
    [1] => /usr/local/apache/htdocs/common/php/xobj/xobj.php
)

RESULT, using call_user_func():
Array
(
    [0] => /usr/local/apache/htdocs/common/php/xobj/xobj_subclass.php
)
pollita at php dot net 28-Dec-2002 07:47
While the method described by robinv at ecosse dot net to call a method of an arbitrarily named function will work:

eval("$classname::$methodname(\$param1,\$param2);");

There is another way to do so without using eval():

call_user_func(array($classname,$methodname),$param1,$param2);

This will do the same thing without the performance hit of eval and without the added security concerns.
peterjoel.com 17-Nov-2002 08:12
You can implement a getter/setter pair to emulate a class variable. The syntax isn't so weird:

<?

class A{
    function getVar($val=NULL){
        static $class_variable = 0;
        if($val != NULL){
            $class_variable = $val;
        }
        return $class_variable;
    }
    function setVar($val=0){
        return A::getVar($val);
    }
}

A::setVar(3);
print A::getVar();

?>
frederik at spam pandora dot be 13-Nov-2002 02:46
My approach to using class constants is by making them functions.
Instead of

$var CONSTANT = 1;

I use

function CONSTANT { return 1; }

Now, when using this:

$i = ConstantClass::CONSTANT();

You can do anything with it: comparing, addition, multiplication. The syntax is a bit weird, but it works perfectly.
pierrick at hydromel_no_spam_ dot net 24-Sep-2002 11:39
It's possible to access class member variables:

class Test {
    var $vA = "hello world";
}

$class_var = get_class_vars(Test);
echo $class_var["vA"];

It's sound to be an ellegant way to acces them, no ? ;)
steven at caltech dot co dot uk 28-Aug-2002 06:50
Re: jdominic@prodigy.net 08-Aug-2002 05:49

While it would be nice to have static instance variables you can simply create a method with the same name which returns the value you require. This means you don't have to instantiate an object when you only need its static content. For example:

class Colour {

      function default () { return "black"; }
}

var $backgroundColour = Colour::default ();
jdominic at prodigy dot net 08-Aug-2002 12:49
According to the documentation, there is no way to have a class variable, only class functions. There should be class variables, because there's no way to implement CONSTANTS. Something like this won't work:

<?
        class Employee {

        var $ACTIVE_EMPLOYEE = 1;

        //etc..
        }

        echo Employee::ACTIVE_EMPLOYEE;

        //Also tryed:

        echo Employee::$ACTIVE_EMPLOYEE

?>

returns:
Parse error: parse error, unexpected ';', expecting '(' in /home/x/public_html/Test.php on line 9

It forces you to create an instance of the class:

$emp = new Employee();
echo $emp->ACTIVE_EMPLOYEE;
carl at thep.lu.se 13-Mar-2002 09:20
Note that if you have two classes, 'foo' and 'bar', and a function in foo called with $instance_of_foo->func() calls bar::func2(), $this will be defined in func2, and it will point at an object of class foo. In fact, you can redefine $this to point to an object of any class before calling bar::func2() to have $this to be a reference to that object. This means that you can't have functions that can be called either as static (::) or member(->), since you won't be able to tell the difference. This is a quite unfortunate consequence of the combination of references not containing any type information and it not being possible to call an explicitly chosen base class member function (that is, if x extends y there's no clean way to call y::f() on an object of class x (The unclean way is to assign $this to $instance_of_x, call y::f(), and reset $this to its old value.)).
peter at textstore dot c() dot il 29-Jul-2001 04:38
And now, encapsulated in constructor. Isn't it nice? Ye, and it WILL work when   more objects of class are serialized & unserialized ONLY when serialized in array / hash by one serialize() call - as serialize() should be used. However, when unserialized, it doesn't affect actual instances' "static" variable - thus, there will be 2 or more static variables after unserialization... but you can still change __wakeup() and to access "real"(actual) class' static value's reference, thus you have to use special function for every static value, as in example above... Ye, PHP is good!@

<?
  class O {

    function O() {
        static $statValue=0;
        $this->statValue= &$statValue;
    }
  }

  $o1= &new O;
  $o2= &new O;

  echo "\$o1: ".$o1->statValue."<br>";
  echo "\$o2: ".$o2->statValue."<br>";

  $o1->statValue= 5;
  $o2->statValue= 10;

  echo "\$o1: ".$o1->statValue."<br>";
  echo "\$o2: ".$o2->statValue."<br>";
?>
peter at textstore dot c() dot il 29-Jul-2001 04:10
That's how to make class' static variable in PHP4. That means reference returned by function value() is the same for all instances of class O, thus they can share common data. This reference is common just for instances on same PHP page, of course.

<?  class O {
    function &value() {
     static $val=0;
     return $val;
    }
  }

  $o1= &new O;
  $o2= &new O;

  echo "\$o1: ".$o1->value()."<b"."r>";
  echo "\$o2: ".$o2->value()."<b"."r>";

  $ref1= &$o1->value();
  $ref1= 5;

  $ref2= &$o2->value();
  $ref2= 10;

  echo "\$o1: ".$o1->value()."<b"."r>";
  echo "\$o2: ".$o2->value()."<b"."r>";
?>
Constructors
parent
Classes and Objects (PHP 4)


parent

You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialisation of code in your base class.

Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. By doing this, you avoid using the name of your base class in more than one place. Should your inheritance tree change during implementation, the change is easily made by simply changing the extends declaration of your class.

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

User Contributed Notes

greg-wilson at hotmail dot com 06-Mar-2012 06:24
You can access/modify variables of the parent class from multiple subclasses:

class Superclass{
    private static $arr = array();

    protected addArrayElement($element){
        self::$arr[] = $element;
    }

    protected printArray(){
        var_dump( self::$arr );
    }
}

class SubclassA extends Superclass{
    public function addToArray($elem){
        parent::addArrayElement($elem);
    }
}

class SubclassB extends Superclass{
    public function addToSameArray($elem){
        parent::addArrayElement($elem);
    }
}

$classA = new SubclassA;
$classA->addToArray("first");
$classB = new SubclassB;
$classB->addToSameArray("second");

calling '$classB->printArray()' results in both "first" and "second" being printed, demonstrating shared static access to a superclass variable from multiple extended classes.
pjm at pehjota dot com 20-Oct-2009 10:32
I've seen people in the comments below use this, but I've also seen some unecessary workarounds to achieve it. So I thought I'd clarify, even though it is shown in the documentation. You CAN reference non-static parent methods, as in other languages. For example...

<?php

abstract class ParentClass {
    public function doSomething() {
        echo "done.\n";
    }
}

class ChildClass extends ParentClass {
    public function doSomething() {
        echo "attempting something.\n";
        parent::doSomething();
    }
}

$obj = new ChildClass();
$obj->doSomething();

?>

This will output both "attempting something." and "done." As you might expect, it also works if the parent method is protected. Users of other languages may have tried defining static and non-static methods with the same name. This is why that doesn't work ("parent" can refer to both static and non-static methods, and there's no way to differentiate them).

However, you CANNOT use the "parent" keyword to reference the parent's variables. When in a class, "parent" will always look for static variables. For example, this results in an "Access to undeclared static property" fatal error:

<?php

abstract class ParentClass {
    public $var = 5;
}

class ChildClass extends ParentClass {
    public function setVar($val) {
        parent::$var = $val;
    }
    public function getVar() {
        return parent::$var;
    }
}

$obj = new ChildClass();
$obj->setVar(6);  // Results in fatal error.
echo $obj->getVar() . "\n";  // Results in fatal error.
echo $obj->var . "\n";  // Would work and reference the parent's $var unless the child has its own $var.

?>
lesion at autistici dot org 05-Jun-2009 03:27
take care of using parent::method with not declared method when using __call because in this case the string method will be lowercase:

<?php
class A {
    function __call( $method, $args ) {
      echo get_class( $this )  . ' ' . $method . "\n";
    }
}

class B extends A {
    function getTest() {
        parent::getTest();
    }
}

$a = new A();
$a->getTest();
$b = new B();
$b->getTest();

?>

output:

A getTest
B gettest
php at stock-consulting dot com 10-Oct-2008 09:40
It appears that parent refers to the base class of the subclass in which the method is defined, not the subclass in which the method is exceuted. This behaviour is consistent with other object-oriented languages. PHP's documentation is a bit unclear here, so I had to test it (PHP5.2.6).
nate @ 8 10-Aug-2008 11:29
in below example need to use

$this->b->par =& $this;

to ensure future changes to the parent are also referenced
nate at 8 02-Aug-2008 09:06
To simulate traditional C# like parent access, child classes can be defined in the parent's constructor and linked via explict definition. ($this->b->par = $this;)

<?php
class A {

  var $foo;
  var $b;

  function A(){
    $this->foo = "foo!";
    $this->b = new B;
    $this->b->par = $this;
    }

  function bar(){
    print("bar!");
    }

};

class B {

  var $par;

  function B(){
    }

  function bar(){
    print( $this->par->foo );
    $this->par->bar();
    }

};

$test = new A;
$test->b->bar();
?>

This returns:

foo!bar!

demonstrating both variable and function access via the parent.
10-Mar-2007 03:49
<?php
    class A {
      function X() {
        echo 'y';
      }
    }

    class B extends A{
      function X() {
        echo 'z';
      }

      function Y() {
        echo parent::X();
      }
    }

    class C extends B {
      function Z () {
        echo parent::Y();
      }
    }

$c = new C();
$c->Z();                  //output is 'y'
?>
KOmaSHOOTER at gmx dot de 19-Dec-2004 05:59
An example for using a memberfunction with another memberfunction.

The sequencing for the creating of the class is important.

<?php
class A
{
   function example()
   {
       echo "I am A::example() and provide basic functionality.<br>\n";
   }
}

class B extends A
{
   function example()
   {
       echo "I am B::example() and provide additional functionality.<br>\n";
       parent::example();
   }
}

class C extends A
{

   function example()
   {
          global $b;
       echo "I am c::example() and provide additional functionality.<br>\n";
       parent::example();
       $b->example();
   }
}
$b = new B();
$c = new C();
$c->example();
;?>

Result:

I am c::example() and provide additional functionality.
I am A::example() and provide basic functionality.
I am B::example() and provide additional functionality.
I am A::example() and provide basic functionality.
27-May-2004 10:40
About the constructors :

Yes, a good pratrice could be to use a method called by the real constructor. In PHP 5, constructor are unified with the special __construct method. So we could do :

<?php
class A {
    var $a = "null";
    function A() {
        $args = func_get_args();
        call_user_func_array(array(&$this, "__construct"), $args);
    }
    function __construct($a) {
        $this->a = $a;
        echo "A <br/>";
    }
}

class B extends A {
    var $b = "null";

    function __construct($a, $b) {
        $this->b = $b;
        echo "B <br/>";
        parent::__construct($a);
    }
    function display() {
        echo $this->a, " / ", $this->b, "<br/>";
    }
}

$b = new B("haha", "bobo");
$b->display();

?>

It will have the same behavior than standard php constructors, except that you can not pass arguments by reference.
andyfaeglasgowTAKE_ME_OUT at yahoo dot co dot uk 13-May-2004 08:15
re: referring to a parents variables

The documentation doesn't say anything about how one should refer to the variables of a parent class in a child class (maybe it's obvious but I thought I'd point it out anyway).

class Actress {
    var $bust;

    function Actress() {$this->bust = "32C";}
    function show() {echo "Bust: $this->bust...";}
}

class HollywoodActress extends Actress{
    var $attitude;

    function HollywoodActress () {
        $this->Actress();
        $this->attitude = "Fiery";
    }

    function show() {
        parent::show();
        echo "Attitude: $this->attitude";
    }

    function modify_bust() {
        $this->bust = "32DD";
    }
}

$girl_at_theatre = new Actress();
$girl_at_theatre->show();
//output: "Bust: 32C..."

$object_of_gossip = new HollywoodActress();
$object_of_gossip->modify_bust();
$object_of_gossip->show();
//output: "Bust: 32D:...Attidude: Fiery"
ckrack at i-z dot de 05-May-2004 09:39
Note that we can use $this in the parent's method like we might expect.
It will be used as the instance of the extended class.

<?php
class foo {
    var $x;
    function foofoo()
    {
        $this->x = "foofoo";
        return;
    }
}
class bar extends foo {
    // we have var $x; from the parent already here.
    function barbar()
    {
        parent::foofoo();
        echo $this->x;
    }
}
$b = new bar;
$b->barbar(); // prints: "foofoo"
?>
bitmore.co.kr 09-Feb-2004 01:13
/* Original */
/*
class A {
    var $x;
    function A() { $this->x = 32; }
    function joke() { print "A::joke" . A::x . "<br>\n"; # SYNTAX ERROR!! }
}
class B extends A {
    var $x;
    function B() {
        parent::A();
        $this->x = 44;
    }
    function joke() {
        parent::joke();
        print "B::joke " . $this->x . "<br>\n";
    }
}
echo A::joke();
echo B::joke();
*/

/* Original */
/* Modify */
/*
class A {
    var $x;
    function A() { $this->x = 32; }
    function joke() {
        $this = new A;
        print "A::joke = " . $this->x . "<br>\n";
    }
}
class B extends A {
    var $x;
    function B() {
        parent::A();
        $this->x = 44;
    }
    function joke() {
        parent::joke();
        $this = new B;
        print "B::joke = " . $this->x . "<br>\n";
    }
}

echo A::joke();
echo B::joke();

//print Show
A::joke = 32
A::joke = 32
B::joke = 44
*/
James Sleeman 10-Jan-2004 06:27
It should be noted that when using parent:: you are able to call a method defined within the parent, or any class that the parent is extending.. for example.

<?php
  class A
  {
    function test()
    {
      echo 'Hello ';
    }
  }

  class B extends A
  {

  }

  class C extends B
  {
    function test()
    {
      parent::test();
      echo 'Bobby.';
    }
  }

  $D =& new C();
  $D->test();
?>

Outputs "Hello Bobby.", the fact that B does not define test() means that A's test() is called, it should also be noted that test() is called in the context of an 'A' class, so if you try and call parent:: in A's test() it will correctly fail.

It's also worth noting that parent:: also works fine in a static method, eg <?php  C::test(); ?> still outputs "Hello Bobby.", and you can even do <?php B::test(); ?> which correctly outputs "Hello ", even though we're calling a static method that lives in an ancestor class!
adrian dabrowski 14-Sep-2003 07:48
if you like to use the here suggested method of calling a parent constructer by using get_parent_class(), you will expirience undesired behaviour, if your parent is using the same technique.

class A {
  function A() {
     $me = get_class($this);
     echo "A:this is $me, I have no parent\n";
  }
}

class B extends A {
  function B() {
     $par = get_parent_class($this);
     $me = get_class($this);
     echo "B:this is $me, my parent is $par\n";

     parent::$par();
  }
}

class C extends B {
  function C() {
     $par = get_parent_class($this);
     $me = get_class($this);
     echo "C:this is $me, my parent is $par\n";

     parent::$par();
  }
}
new C();

this will not produce the output you probably expected:
C:this is c, my parent is b
B:this is b, my parent is a
A:this is a, i have no parent

...but insted you will get in serious troubles:
C:this is c, my parent is b
B:this is c, my parent is b

Fatal error:  Call to undefined function:  b() in .............. on line 16

$this is always pointing to the 'topmost' class - it seems like this is php's way to cope with polymorphic OOP.
hustbaer 23-Aug-2003 10:37
something on the note of 'minoc':

in this setup, the "$this->$par();" will lead to infinite recursion...

class foo extends bar {
  function foo() {

    $par = get_parent_class($this);
    $this->$par();

    // then normal constructor stuff.
    // ...
  }

  function bar()
  {
    echo "this makes no sense, but who cares :)";
  }
}

but the problem is easity fixed by going like so:

class foo extends bar {
  function foo() {

    $par = get_parent_class($this);
    parent::$par();

    // then normal constructor stuff.
    // ...
  }

  function bar()
  {
    echo "this makes no sense, but who cares :)";
  }
}
mazsolt at yahoo dot com 05-Jul-2003 03:04
There is a difference between PHP and C# managing the overloaded variables of the parent class:

<?php
class a{
var $a=1;
function display(){
echo $this->a;
}
}

class b extends a{
var $a=9;
}

$x=new b;
$x->display(); // will display 9
?>

The same code in C# will display the value from the parent class.

[C#]
class a{
private int a=1;
public int display(){
return this.a;
}
}

class b:a{
private int a=9;
}

b x = new b();
Response.Write(b.display()); // will display 1
horne at teradyne dot com 26-Mar-2003 08:09
I've been scouring through the comments but haven't been able to find an example of how to use variable overriding. The manual hints that it is possible, but there aren't any examples. See the code for what I want to do:

class A {
  var $x;

  function A() {
    $this->x = 32;
  }

  function joke() {
    print "A::joke" . A::x . "<br>\n"; # SYNTAX ERROR!!
  }
}

class B extends A {
  var $x;

  function B() {
    parent::A();
    $this->x = 44;
  }

  function joke() {
    parent::joke();
    print "B::joke " . $this->x . "<br>\n";
  }
}

I want the following output when I call B::joke:

A::joke 32
B::joke 44

what do I get if I replace the A::x with $this->x?

A::joke 44
B::joke 44

How do I set the variable $x in the base class? Or, how do I get $this to point to the part of the class that is owned by class A?

I've tried the following (quite invalid) syntaxes:
A::x
A::$x
${A::x}
A::{$this->x}

It'd be nice to have a concrete example of how to access (read and write) parent variable members, or explicitly say that it is not possible to do that.
lelegiuly at iol dot it 24-Mar-2003 08:18
Sorry but my example above it's correct only if there's one class that inherits by another class. If the hierarchical tree is deeper than 2 my example doesn't work. The result is a infinite loop cycle.
Why? Because the only instanced object is the B class (in my example).

$this alwais refer to instanced object.

See also the "sal at stodge dot org" notes in 4 October 2002.
lelegiuly at iol dot it 06-Mar-2003 08:46
If you like Java and you have to call parent constructor, this is my method:

class object {
   function super() {
     $par = get_parent_class($this);
     $this->$par();
   }
}
class A extends object {
   function A() {
     echo "A constructor\n";
   }
}
class B extends A {
   function B() {
     $this->super();
     echo "B constructor\n";
   }
}

Include the classes above, instance a new B class and this is the output:

A constructor

B constructor

In your web application every class will extend the object class.
Good luck, Emanuele :)
Dan 01-Mar-2003 05:03
I agree with "anonymous coward". That syntax seems silly in a constructor and only results in an extra function being called. The only time the parent will ever change is if you change the extends expression in your class definition.

However, the parent:: syntax is very useful when you need to add extra functionality to a method of a child class which is already defined in the parent class.

Example:

class foo {
   var $prop;

   function foo($prop = 1) {$this->prop = $prop;}

   function SetProp($prop) {$this->prop = $prop;}
}

class bar extends foo {
   var $lastprop;

   function bar($prop = NULL) {
      is_null($prop) ? $this->foo() : $this->foo($prop);
   }

   function SetProp($prop) {
      $this->lastprop = $this->prop;
      parent::SetProp($prop);
   }
}
anonymous at cowards dot com 07-Dec-2002 12:48
Um, reading through all the gyrations on getting C++ constructor
semantics from PHP, I am wondering if I am just blindly missing something
when I use:

class A {
    function A () {  echo "A Constructor\n"; }
}

class B extends A {
    function B () { $this->A (); echo "B Constructor\n"; }
}

class C extends B {
    function C () { $this->B (); echo "C Constructor\n"; }
}

$c = new C ();

produces:

A Constructor
B Constructor
C Constructor

I'm new to PHP, but it seems to me that this is simpler and cleaner
than the solutions discussed here, with the only disadvantage being that
when you change the name of your superclass you have to change one
line in your subclass.

What am I missing? Are there advanced PHP-OO considerations that
make this code undesireable??
aid at logic dot org dot uk 05-Dec-2002 12:27
With regard to the chaining of Constrcutures, surely this is a simple and replaible method..?

<?php
class A
  {
  function A()
    {
    print "Constructor A<br>\n" ;
    }
  }

class B extends A
  {
  function B()
    {
    parent::A () ;
    print "Constructor B<br>\n" ;
    }
  }

class C extends B
  {
  function C()
    {
    parent::B ();
    print "Constructor C<br>\n" ;
    }
  }

$o = new C;
?>
Which outputs,

Constructor A
Constructor B
Constructor C
sal at stodge dot org 03-Oct-2002 09:57
<p>When using the technique suggested by "<b>minoc at mindspring dot com</b>" on this page - USE EXTREME CAUTION.</p>

The problem is that if you inherit of a class that uses this kludge in the constructor you will end up with a recursive constructor - unless that new class has a constructor of it's own that by-passes the kludged constructor.

What I am saying, is you can use this technique as long as you can ensure that each class you inherit from a class containing this technique in the constructor has a constructor class of it's own that does not call the parent constructor...

On balance it is probably easier to specify the name of the constructor class explicitly!

If you make this mistake the symptoms are pretty easy to spot - PHP spirals into an infinitely recursive loop as soon as you attempt to construct a new class. Your web-server will returns an empty document.
mwwaygoo at hotmail dot com 20-Sep-2002 08:54
With the example given previous from johnremovethreewordsplatte@pobox.com

You should only do this if your initialisation is different (no point in extending if it isn't)

When you extend a class its constructor still remains valid and is executed when constructed.  Writing a new constructor in the extended class overwrites the old one - inheritance.

so the following will also work

class Superclass {
function Superclass($arg) {
$this->initialize($arg);
}
function initialize($arg) {
$this->setArg($arg);
}
}

class Subclass extends Superclass {
//initialize() is inherited:
//BUT so is constructor

function extra_stuff($arg) {
echo "extra stuff " . $arg;

}
}

THE constructor is the function who's name is the same as the class that it is defined within.
AND remains the constructor even in extended classes, until redefined.

Think of the constructor as a seperate function from all the others.  As if PHP looks at your class and makes a copy of the function of the same name as the class and calls it "Constructor".

You can also create a function within the extended class with the same name as the constructor in the parent class without re-writing the constructor.  Because you are not altering the "Constructor" function.
(BUT any redefined variables are used in the constructor, as expected)

ie
class One
{
  var $v = "one";

  function One()
  {
    print "Class One::Constructor value=" . $this->v . "<br />\n";
  }
}

class Two extends One
{
  var $v = "two";

  function one()
  {
    print "REDEFINED : Class Two::Function One value=" . $this->v . "<br />\n";
  }
}

$o = new One();
$o->one();
$p = new Two();
$p->one();

results in :-
Class One::Constructor value=one
Class One::Constructor value=one
Class One::Constructor value=two
REDEFINED : Class Two::Function One value=two
johnremovethreewordsplatte at pobox dot com 12-Aug-2002 05:16
Combining the above suggestions with the "Pull Up Constructor Body" refactoring from Fowler (http://www.refactoring.com/catalog/pullUpConstructorBody.html), I found an elegant way to inherit constructors in PHP. Both superclass and subclass constructors call an initialize() method, which can be inherited or overridden. For simple cases (which almost all of mine are), no calls to parent::anything are necessary using this technique. The resulting code is easy to read and understand:

class Superclass {
    function Superclass($arg) {
        $this->initialize($arg);
    }
    function initialize($arg) {
        $this->setArg($arg);
    }
}

class Subclass extends Superclass {
    function Subclass($arg) {
        //initialize() is inherited:
        $this->initialize($arg);
    }
}
gibby at onebox dot com 15-Jun-2002 04:25
Regarding the example above, I believe the result is misleading, if you're inferring that the $this in Class One's OneDo method refers to One.

If that wasn't your conclusion, then my apologies-- I misunderstood you.

But if it was, it might save trouble to note that $this is effectively an alias for $o (a Class Two object).  $v is available to $o, and that's how it's being picked up.  $this is $o in that example, not One (One is a class and has no implementation).

I hope that's helpful.

Brad
seedpod23 at hotmail dot com 29-May-2002 11:19
This example might illustrate something which was unclear to me when using the $parent::method() syntax.

I didn't see any documentation on whether or not $this (object variables) would be available in the parent class method so I wrote this example:

class One {

  var $v = "one";

  function OneDo() {
    print "One::OneDo " . $this->v . "<br>\n";
  }
}

class Two extends One {

  function CallParent() {
    parent::OneDo();
  }
}

$o = new Two();

$o->CallParent();

The output is "One::OneDo one", happy day!
php at earthside dot arg 08-Apr-2002 10:41
Here is the workaround I came up with based on the comments about using a 'constructor' method and the parent:: syntax...

#cat test.php
<?php
class foo {
  function foo() { $this->constructor(); }
  function constructor() {
    echo get_class($this)." (foo)\n";
  }
}
class bar extends foo {
  function bar() { $this->constructor(); }
  function constructor() {
    echo get_class($this)." (bar)\n";
    parent::constructor();
  }
}
class baz extends bar {
  function & baz() { $this->constructor(); }
  function & constructor() {
    echo get_class($this)." (baz)\n";
    parent::constructor();
  }
}
$o = new baz;
?>
#php test.php
X-Powered-By: PHP/4.1.2
Content-type: text/html

baz (baz)
baz (bar)
baz (foo)
#

--
'a' -> 'o' in email TLD
minoc at mindspring dot com 07-Sep-2001 04:52
w/ PHP 4.0.5, I was able to chain
my constructors easily with:

class foo extends bar {
  function foo() {

    $par = get_parent_class($this);
    $this->$par();

    // then normal constructor stuff.
    // ...
  }
}
tim dot parkinson at ntlworld dot com 28-Jul-2001 05:37
There is an implication here that variables of the parent class are available.  You can't access variables using parent::
venome at gmx dot net 25-Jun-2001 08:57
If you have a complex class hierarchy, I find that it's a good idea to have a function constructor() in every class, and the 'real' php constructor only exists in the absolute base class.

From the basic constructor, you call $this->constructor(). Now descendants simply have to call parent::constructor() in their own constructor, which eliminates complicated parent calls.
Scope Resolution Operator (::)
Serializing objects - objects in sessions
Classes and Objects (PHP 4)


Serializing objects - objects in sessions

serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The functions in an object will not be saved, only the name of the class.

In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object $a of class A on page1.php and serialize this, you'll get a string that refers to class A and contains all values of variabled contained in $a. If you want to be able to unserialize this on page2.php, recreating $a of class A, the definition of class A must be present in page2.php. This can be done for example by storing the class definition of class A in an include file and including this file in both page1.php and page2.php.

<?php
// classa.inc:

  class A {
      var $one = 1;

      function show_one() {
          echo $this->one;
      }
  }

// page1.php:

  include("classa.inc");

  $a = new A;
  $s = serialize($a);
  // store $s somewhere where page2.php can find it.
  $fp = fopen("store", "w");
  fwrite($fp, $s);
  fclose($fp);

// page2.php:

  // this is needed for the unserialize to work properly.
  include("classa.inc");

  $s = implode("", @file("store"));
  $a = unserialize($s);

  // now use the function show_one() of the $a object.
  $a->show_one();
?>

If you are using sessions and use session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This basically means that these objects can show up on any of your pages once they become part of your session.

It is strongly recommended that you include the class definitions of all such registered objects on all of your pages, even if you do not actually use these classes on all of your pages. If you don't and an object is being unserialized without its class definition being present, it will lose its class association and become an object of class __PHP_Incomplete_Class_Name without any functions available at all, that is, it will become quite useless.

So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.

User Contributed Notes

There are no user contributed notes for this page.
parent
The magic functions __sleep and __wakeup
Classes and Objects (PHP 4)


The magic functions __sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

User Contributed Notes

ranware2200 at yahoo dot com 27-Jan-2011 12:27
This is a simple example of how to implement serialization using the __sleep and __wakeup magic methods...

<?php
//student.class.php
class Student{
    private $full_name = '';
    private $score = 0;
    private $grades = array();

    public function __construct($full_name, $score, $grades)
    {
        $this->full_name = $full_name;
        $this->grades = $grades;
        $this->score = $score;
    }

    public function show()
    {
        echo $this->full_name;
    }

    function __sleep()
    {
        echo 'Going to sleep...';
        return array('full_name', 'grades', 'score');
    }

    function __wakeup()
    {
        echo 'Waking up...';
    }
}
?>

<?php
//a.php
include 'student.class.php';

$student = new Student('bla bla', 'a', array('a' => 90, 'b' => 100));
$student->show();
echo "<br />\n";
$s = serialize($student);
echo $s ."<br />\n";
$fp = fopen('./uploads/session.s', 'w');
fwrite($fp, $s);
fclose($fp);
?>

<?php
//b.php
include 'student.class.php';

$s = implode('', file("./uploads/session.s"));
echo $s ."<br />\n";
$a = unserialize($s);
$a->show();
?>
Serializing objects - objects in sessions
References inside the constructor
Classes and Objects (PHP 4)


References inside the constructor

Creating references within the constructor can lead to confusing results. This tutorial-like section helps you to avoid problems.

<?php
class Foo {
    function Foo($name) {
        // create a reference inside the global array $globalref
        global $globalref;
        $globalref[] = &$this;
        // set name to passed value
        $this->setName($name);
        // and put it out
        $this->echoName();
    }

    function echoName() {
        echo "<br />", $this->name;
    }

    function setName($name) {
        $this->name = $name;
    }
}
?>

Let us check out if there is a difference between $bar1 which has been created using the copy = operator and $bar2 which has been created using the reference =& operator...

<?php
$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */

$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */
?>

Apparently there is no difference, but in fact there is a very significant one: $bar1 and $globalref[0] are _NOT_ referenced, they are NOT the same variable. This is because "new" does not return a reference by default, instead it returns a copy.

Замечание: There is no performance loss (since PHP 4 and up use reference counting) returning copies instead of references. On the contrary it is most often better to simply work with copies instead of references, because creating references takes some time where creating copies virtually takes no time (unless none of them is a large array or object and one of them gets changed and the other(s) one(s) subsequently, then it would be wise to use references to change them all concurrently).

To prove what is written above let us watch the code below.
<?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');

// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set from outside
set in constructor */

// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');

// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set from outside
set from outside */
?>

Another final example, try to understand it.

<?php
class A {
    function A($i) {
        $this->value = $i;
        // try to figure out why we do not need a reference here
        $this->b = new B($this);
    }

    function createRef() {
        $this->c = new B($this);
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->value;
    }
}

class B {
    function B(&$a) {
        $this->a = &$a;
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->a->value;
    }
}

// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new A(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();

$a->value = 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();

?>

Результат выполнения данного примера:

class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11

User Contributed Notes

There are no user contributed notes for this page.
The magic functions __sleep and __wakeup
Comparing objects
Classes and Objects (PHP 4)


Comparing objects

In PHP 4, objects are compared in a very simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. Similar rules are applied when comparing two objects using the identity operator (===).

If we were to execute the code in the example below:

Пример #1 Example of object comparison in PHP 4

<?php
function bool2str($bool) {
    if ($bool === false) {
            return 'FALSE';
    } else {
            return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2) {
    echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
    echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
    echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
    echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}

class Flag {
    var $flag;

    function Flag($flag=true) {
            $this->flag = $flag;
    }
}

class SwitchableFlag extends Flag {

    function turnOn() {
        $this->flag = true;
    }

    function turnOff() {
        $this->flag = false;
    }
}

$o = new Flag();
$p = new Flag(false);
$q = new Flag();

$r = new SwitchableFlag();

echo "Compare instances created with the same parameters\n";
compareObjects($o, $q);

echo "\nCompare instances created with different parameters\n";
compareObjects($o, $p);

echo "\nCompare an instance of a parent class with one from a subclass\n";
compareObjects($o, $r);
?>

Результат выполнения данного примера:

Compare instances created with the same parameters
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Compare instances created with different parameters
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Compare an instance of a parent class with one from a subclass
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Which is the output we will expect to obtain given the comparison rules above. Only instances with the same values for their attributes and from the same class are considered equal and identical.

Even in the cases where we have object composition, the same comparison rules apply. In the example below we create a container class that stores an associative array of Flag objects.

Пример #2 Compound object comparisons in PHP 4

<?php
class FlagSet {
    var $set;

    function FlagSet($flagArr = array()) {
        $this->set = $flagArr;
    }

    function addFlag($name, $flag) {
        $this->set[$name] = $flag;
    }

    function removeFlag($name) {
        if (array_key_exists($name, $this->set)) {
            unset($this->set[$name]);
        }
    }
}

$u = new FlagSet();
$u->addFlag('flag1', $o);
$u->addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=>$q, 'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));

echo "\nComposite objects u(o,p) and v(q,p)\n";
compareObjects($u, $v);

echo "\nu(o,p) and w(q)\n";
compareObjects($u, $w);
?>

Результат выполнения данного примера:

Composite objects u(o,p) and v(q,p)
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

u(o,p) and w(q)
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

User Contributed Notes

There are no user contributed notes for this page.
References inside the constructor
Отладка в PHP
Classes and Objects (PHP 4)


Отладка в PHP

Содержание

  • Об отладке в PHP

User Contributed Notes

Anonymous 02-Nov-2011 01:36
If anyone's trying to actually set up the official debugger from Zend (http://www.zend.com/en/products/studio/downloads) with PHP 5.3.8, you'll notice the zip only contains the nts (non-thread-safe) version of the debugger for PHP 5.3.x. Try as you might, it just doesn't seem to work with the tread-safe version of PHP 5.3.8, so for Windows at least I found you'll also need to have the NON-THREAD-SAFE version of PHP installed.
dcz at phpbb-seo dot com 18-Mar-2011 02:32
Here my little contribution for a simple yet handy debug function :
<?php
/**
* dbug (mixed $expression [, mixed $expression [, $... ]])
* Author : dcz
* Feel free to use as you wish at your own risk ;-)
*/
function dbug() {
    static $output = '', $doc_root;
    $args = func_get_args();
    if (!empty($args) && $args[0] === 'print') {
        $_output = $output;
        $output = '';
        return $_output;
    }
    // do not repeat the obvious (matter of taste)
    if (!isset($doc_root)) {
        $doc_root = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
    }
    $backtrace = debug_backtrace();
    // you may want not to htmlspecialchars here
    $line = htmlspecialchars($backtrace[0]['line']);
    $file = htmlspecialchars(str_replace(array('\\', $doc_root), array('/', ''), $backtrace[0]['file']));
    $class = !empty($backtrace[1]['class']) ? htmlspecialchars($backtrace[1]['class']) . '::' : '';
    $function = !empty($backtrace[1]['function']) ? htmlspecialchars($backtrace[1]['function']) . '() ' : '';
    $output .= "<b>$class$function =&gt;$file #$line</b><pre>";
    ob_start();
    foreach ($args as $arg) {
        var_dump($arg);
    }
    $output .= htmlspecialchars(ob_get_contents(), ENT_COMPAT, 'UTF-8');
    ob_end_clean();
    $output .= '</pre>';
}
?>

usage :
<?php
dbug($scalar, $array, $object, $resource, CONSTANT);
//..
dbug($other);
//..
echo dbug('print'); // actually output the result of all previous calls
// looks like :
// class::method() =>/path/from/doc/root/file.php #line
// var_dump result

?>

I found it handy not to directly output result data because this makes it possible to debug variables before headers are sent (useful for pre sessions start code for example).
morten sickel 17-Feb-2011 10:39
In my debug function I added some functionallity to print out from where the function was called:

<?php
function debug($value=''){
    $btr=debug_backtrace();
    $line=$btr[0]['line'];
    $file=basename($btr[0]['file']);
    print"<pre>$file:$line</pre>\n";
    if(is_array($value)){
        print"<pre>";
        print_r($value);
        print"</pre>\n";
    }elseif(is_object($value)){
        $value.dump();
    }else{
        print("<p>&gt;${value}&lt;</p>");
    }
}
?>

Thereby it is easy to keep the overview if you debug more variables simultaneously or, if the program crashes somewhere, just throw in a few debug() and you'll easily see how far the program comes
frank at silverwolfmedia dothere com 19-Nov-2009 04:23
I always include debugging code in all may major projects. I use an object (e.g. $CFG) to store the settings the control the code's behavior, which includes a $CFG->debug variable to control the level of debugging verbosity. I set it to 0 before rollout, which ensures that even if some debugging code was left in accidentally, this will be deactivated and not spew debugging information in a live website.

I use the following functions to facilitate debugging messages. They live in a single code module which I only need include() to use it. Note the global reference to $CFG:

<?php
// Dump the contents of a variable into HTML comments for debugging:
function debugVar ($var) {
  global $CFG;

  if ($CFG->debug) {
    echo "\n<!--\nDEBUG INFO: \n";
    if (is_array ($var))
      print_r ($var)
    else
      var_dump ($var);
    echo "\n-->\n";
  }
}

// Dump function parameters into HTML comments for debugging:
function debugFunc () {
  global $CFG;

  if ($CFG->debug) {
    $argv = func_get_args ();
    echo "\n<!--\nDEBUG INFO: \n";
    print_r ($argv);
    echo "\n-->\n";
  }
}

// Dump a debugging message into HTML comments for debugging:
function debugMsg ($msg) {
  global $CFG;

  if ($CFG->debug) {
    echo "\n<!--\nDEBUG INFO: \n";
    echo $msg;
    echo "\n-->\n";
  }
}
?>

Usage is simple:

To check a variable, call <?php debugVar ($variable); ?>

To check  parameters passed to a function, call
<?php debugFunc ($var1, $var2, $var3 ...); ?>

To print a debug message, call
<?php debugMsg ("Function xyz returned " . $retVal); ?>

Then check your HTML source to find the debugging output in the comments.

Don't forget to set $CFG->debug to 0 before rollout. If you're paranoid you can also include a javascript alert() box to be triggered by a : $CFG->debug > 0" condition upon each page reload, although that gets really annoying really fast. :-)

// Frank
turaz dot w4l at gmail dot com 06-Aug-2009 04:14
I usually use this simple function in combo with a die(); in order to have on screen the value of a variable or array:

<?php
function debug_view ( $what ) {
    echo '<pre>';
    if ( is_array( $what ) )  {
        print_r ( $what );
    } else {
        var_dump ( $what );
    }
    echo '</pre>';
}
?>
tomboul 09-Apr-2009 03:51
Here a best printed var_dump : show_php
It's a reccursive function for output many kind of structured data (array, class, etc ...)

<?php
function show_php($var,$indent='&nbsp;&nbsp;',$niv='0')
{
    $str='';
    if(is_array($var))    {
        $str.= "<b>[array][".count($var)."]</b><br />";
        foreach($var as $k=>$v)        {
            for($i=0;$i<$niv;$i++) $str.= $indent;
            $str.= "$indent<em>\"{$k}\"=></em>";
            $str.=show_php($v,$indent,$niv+1);
        }
    }
    else if(is_object($var)) {

        $str.= "<b>[objet]-class=[".get_class($var)."]-method=[";
        $arr = get_class_methods($var);
           foreach ($arr as $method) {
               $str .= "[function $method()]";
           }
        $str.="]-";
        $str.="</b>";
        $str.=show_php(get_object_vars($var),$indent,$niv+1);
    }
    else {
        $str.= "<em>[".gettype($var)."]</em>=[{$var}]<br />";
    }
    return($str);
}
?>

EXAMPLE :

array example to debug :

<?php
$tab=array(
    "first"=>"firstValue",
    "second"=>array(
        "first"=>1,
        "second"=>2,
        "third"=>array(
            "first"=>"one",
            "second"=>"two"
        ),
    ),
);
?>

result of show_php :

<?php
echo "tab=".show_php($tab);
?>

tab=[array][2]
  "first"=>[string]=[firstValue]
  "second"=>[array][3]
    "first"=>[integer]=[1]
    "second"=>[integer]=[2]
    "third"=>[array][2]
      "first"=>[string]=[one]
      "second"=>[string]=[two]

result of var_dump :

<?php
echo "tab=";
var_dump($tab);
echo "<br>";
?>

tab=array(2) { ["first"]=> string(10) "firstValue" ["second"]=> array(3) { ["first"]=> int(1) ["second"]=> int(2) ["third"]=> array(2) { ["first"]=> string(3) "one" ["second"]=> string(3) "two" } } }
Diego 18-Feb-2009 04:21
If you don't find a syntax error, you can comment out a block where you assume the error (or put it out of the document by [ctrl] + [X], but keep a copy on your HD for the case, your computer crashes) and check, if the syntax error is still there.
If not, it must be anywhere in your commented text; if yes, it must be somewhere else.
If you want to locate the error better, do it again with an other and/or smaller piece of code, till you get it.
online _ use _ only == hotmail.com 15-Mar-2006 03:41
I still find that printing out variable values at problem points in the code is one of the easiest ways for me to debug.  If you're interested in knowing the full contents of an object/array/scalar, then use

var_dump($var).
Comparing objects
Об отладке в PHP
Appendices


Об отладке в PHP

В PHP нет встроенных средств отладки, однако вы можете использовать внешние отладчики. » Zend IDE имеет встроенный отладчик, а также есть несколько бесплатных расширений отладки, такие как DBG, находящееся по адресу » http://www.php-debugger.com/dbg/, » Advanced PHP Debugger (APD) или » Xdebug.

User Contributed Notes

There are no user contributed notes for this page.
Отладка в PHP
Configure options
Отладка в PHP


Configure options

Содержание

  • List of core configure options

User Contributed Notes

Jay 10-Jan-2009 04:23
As Thani said, it will complain about a lot of libXML depend extensions. Here are all the ones I had to disable:

--disable-libxml --disable-dom --disable-simplexml --disable-xml --disable-xmlreader --disable-xmlwriter --without-pear
Thani 21-Jul-2008 05:35
One of the above mentioned to enable libxml. Instead use disable-all and enable only the required extensions. Otherwise it will complain of libxml for extensions that depend on libxml.
Neil Davis 04-Mar-2008 08:07
If you have compiled php without specifying a --with-config-file-path=PATH
then reconfigure php using --with-config-file-path=PATH, you must do a "make clean" then "make" & "make install" before reinstalling. If you don't make clean first, phpinfo will report the new location set by --with-config-file-path=PATH, but actually be looking for php.ini in the old location.

I'm not sure if this is intended behavior or not but this is a gotcha that got me after compiling, then reconfiguring, then doing make install. It caused a little head scratching.

It's good practice to do make clean after any configuration change anyway. Bite the bullet and take the time to do it right to avoid unexpected module behavior.

-Neil
raj at ap dot krakow dot pl 07-Feb-2008 12:52
It's not stated clearly anywhere in the documentation, but the CGI version won't build if you specify the --with-apxs= option to configure (the CLI version will, however). The only way I found to have *both* Apache module *and* CGI versions of PHP installed was to run configure/make twice - first with --with-apxs= option, to build the Apache module, then without it, to build the CGI binary.
I think if the doc says that the CGI version is built by default, it *should* be built by default, unless you specify --disable-cgi. If --with-apxs= automatically disables CGI, the --disable-cgi option doesn't seem to have any use.
codeslinger at compsalot dot com 30-Nov-2006 01:26
Note: PHP5 has a zillion dependencies on libxml, it is not practical to disable it, you must install it.

libxml can be found here: http://www.xmlsoft.org/

But this is actualy a good thing; "Almost everything regarding XML support was rewritten for PHP 5".

For more info see: http://www.zend.com/php5/articles/php5-xmlphp.php
jovcic ate gseis stop ucla stop edu 08-Jul-2005 06:26
If you'e compiling a shared extension (e.g. pspell) whose libs & headers are not in the usual place, use the following:

--with-pspell=shared,/my/custom/path/to/pspell/

Took me forever to figure out, since Google had no answer for me.
joerg at fenin dot de 14-Apr-2005 12:15
If some options do not become active after doing a configure; make; make install, try to do a make clean after configure. That worked for me when enabling memory limts (--enable-memory-limit).
16-Jan-2004 03:33
>/usr/local/lib needs to be listed in /etc/ld.so.conf, but it should already
>be there on most systems.  The above notes all apply to Linux only,
>but may be useful on other platforms as well

 It is much simpler just to put /usr/local/pgsql/lib into /etc/ld.so.conf and then run ldconfig.
steve at njord dot org 05-Oct-2003 05:32
If you're trying to build with --with-imap and your uw-imap stuff is built SSLTYPE=nopwd then you will fail the "Checking if IMAP works" check if you don't also build with --with-imap-ssl

Another hour and a half of my life lost to find that one.

Steve
squeeNoSpam at NoSpamAddress dot com 14-Aug-2002 12:06
[Editor's note: The reason why some general options for the "configure" scripts are not documented is that said script is part of the GNU autoconf tools, and as such its general options are documented elsewhere, e.g.: http://www.gnu.org/manual/autoconf/index.html and http://www.airs.com/ian/configure/. Some are also documented in the INSTALL file that comes with the source distribution.]

The --prefix=PREFIX configure option isn't mentioned here. It apparently defaults to /usr/local, and sets the position of the php includes and libs. (in PREFIX/include/php and PREFIX/lib/php)
tysonlt from web_SPAMOFF_media com au 14-Apr-2002 10:42
RE: Servlet support, I found that you need to configure --with-servlet=/usr/local/tomcat/common.

I found checking the configure script (always a good idea) that it looks for {dir_prefix}/lib/servlet.jar file, and this is found in the tomcat/common directory.

Hope this helps a bit!
ceo at l-i-e dot com 14-Aug-2001 12:05
--enable-sigchild is only relevent to users of Oracle who are having <defunc> processes.
petrov at rice dot edu 03-Nov-2000 10:27
If you are building with --with-pgsql=/some/dir, make sure that you still have libpq loaded up by ldconfig.  I compiled and installed postgres from the tarball and then had to manually create the symlinks in /usr/local/lib.  In particular, after you have built and installed postgres, you need to do the following (presuming you installed to /usr/local/pgsql):

# cd /usr/local/lib
# ln -s ../pgsql/lib/libpq.so.2.1 libpq.so.2.1
# ln -s ../pgsql/lib/libpq.so.2.1 libpq.so.2
# ln -s ../pgsql/lib/libpq.so.2.1 libpq.so
# ldconfig

/usr/local/lib needs to be listed in /etc/ld.so.conf, but it should already be there on most systems.  The above notes all apply to Linux only, but may be useful on other platforms as well.

--sam
Об отладке в PHP
List of core configure options
Appendices


List of core configure options

Below is a partial list of configure options used by the PHP configure scripts when compiling in Unix-like environments. Most configure options are listed in their appropriate locations on the extension reference pages and not here. For a complete up-to-date list of configure options, run ./configure --help in your PHP source directory after running autoconf (see also the Installation chapter). You may also be interested in reading the » GNU configure documentation for information on additional configure options such as --prefix=PREFIX.

Замечание:

These are only used at compile time. If you want to alter PHP's runtime configuration, please see the chapter on Runtime Configuration.

  • Miscellaneous
  • PHP Behaviour
  • Server

Configure Options in PHP

Замечание:

These options are only used in PHP as of PHP 4.1.0, although some are available in older versions too. If you want to compile an older version, some options will probably not be available.

Различные опции

--enable-debug

Компилировать с информацией об отладке.

--with-layout=TYPE

Устанавливает, каким образом установленные файлы будут расположены. TYPE принимает значения PHP (по умолчанию) или GNU.

--with-pear=DIR

Установить PEAR в DIR (по умолчанию PREFIX/lib/php).

--without-pear

Не устанавливать PEAR.

--enable-sigchild

Включить собственный дескриптор SIGCHLD для PHP.

--disable-rpath

Не передавать дополнительные пути для поиска библиотек времени исполнения.

--enable-libgcc

Явно использовать libgcc.

--enable-php-streams

Включить экспериментальный функционал потоков PHP. Используйте только в случае если вы тестируете код!

--with-zlib-dir[=DIR]

Определить местонахождение библиотеки zlib.

--enable-trans-sid

Включить прозрачную передачу идентификатора сессии. Применимо только к PHP 4.1.2 или ниже. Начиная с PHP 4.2.0, эта опция всегда включена.

--with-tsrm-pthreads

Использовать нити (threads) POSIX (по умолчанию).

--enable-shared[=PKGS]

Собирать общие библиотеки [по умолчанию=yes].

--enable-static[=PKGS]

Собирать статические библиотеки [по умолчанию=yes].

--enable-fast-install[=PKGS]

Оптимизировать для быстрой установки [по умолчанию=yes].

--with-gnu-ld

Предполагать что компилятор С использует GNU ld [по умолчанию=no].

--disable-libtool-lock

Избегать блокирования (может испортить параллельные сборки).

--with-pic

Пытаться использовать только PIC/не-PIC объекты [по умолчанию=use both (использовать оба)]

--enable-memory-limit

Компилировать с поддержкой ограничения памяти. (не доступно начиная с PHP 5.2.1 - всегда включено)

--disable-url-fopen-wrapper

Отключить обертку fopen с поддержкой URL, которая позволяет получать доступ к файлам через HTTP или FTP. (не доступно начиная с 5.2.5)

--enable-versioning

Экспортировать только необходимую информацию для отладки. см. INSTALL для дополнительной иформации.

PHP опции

--enable-maintainer-mode

Включает правила сборки и зависимости, которые не будут полезными для начинающего установщика (а иногда сбивающие с толку).

--with-config-file-path=PATH

Устанавливает путь, по котором будет искаться файл php.ini, значение по умолчанию PREFIX/lib.

--enable-safe-mode

Включает безопасный режим по умолчанию.

--with-exec-dir[=DIR]

Разрешить исполнять файлы только из DIR, в безопасним режиме по умолчанию /usr/local/php/bin.

--enable-magic-quotes

Включает магические кавычки по умолчанию.

--disable-short-tags

Отключает короткую форму записи начального тега <? по умолчанию.

--enable-zend-multibyte

Включает многобайтовый код в парсере языка и сканере при запуске. Когда PHP скомпилирован с этой опцией, становится активной также директива encoding в declare конструкции.

--with-libdir

Определеяет папку библиотек для сборки PHP в Unix системах. Для 64-битных систем опция требует особого аргумента --with-libdir=lib64 для папки lib64.

SAPI опции

Следующий список влючает доступные опции SAPI (Server Application Programming Interface) для PHP.

--with-aolserver=DIR

Определяет путь к установленному AOLserver.

--with-apxs[=FILE]

Собирает динамический модуль для Apache. FILE - это опциональный путь к инструменту Apache apxs; по умолчанию для apxs. Убедитесь в том, что вы указали версию apxs, которая действительно установлена в вашей системе, а не ту, которая находится в исхониках apache.

--with-apache[=DIR]

Собирает статичный модуль для Apache. DIR - это верхний уровень папки сборки Apache, по умолчанию /usr/local/apache.

--with-mod_charset

Включает таблицы перекодировки для модуля mod_charset (для версии Russian Apache).

--with-apxs2[=FILE]

Собирает динамический модуль для Apache 2.0. FILE - это опциональный путь к инструменту Apache apxs; по умолчанию для apxs.

--with-caudium=DIR

Собирает PHP как Pike-модуль для использования с Caudium. DIR - это путь к папке сервера Caudium, по умолчанию значение установлено в /usr/local/caudium/server.

--disable-cli

Доступно с версии PHP 4.3.0. Отключает сборку CLI-версии PHP (опция также вызывает --without-pear). Больше информации можно получить в разделе Использование PHP в командной строке.

--enable-embed[=TYPE]

Включает сборку встроенной библиотеки SAPI. TYPE может принимать значение shared или static, по умолчанию установлено shared. Доступно с версии PHP 4.3.0.

--with-fhttpd[=DIR]

Сборка fhttpd модуля. DIR - путь к исходникам fhttpd, по умолчанию /usr/local/src/fhttpd. Опция не доступна после версии PHP 4.3.0.

--with-isapi=DIR

Сборка PHP как модуля ISAPI для использования в Zeus.

--with-nsapi=DIR

Указывает путь к установленному Netscape/iPlanet/SunONE веб-серверу.

--with-phttpd=DIR

Нет информации.

--with-pi3web=DIR

Сборка PHP как модуля для использования в Pi3Web.

--with-roxen=DIR

Сборка PHP как Pike-модуля. DIR - это базовая папка Roxen, обычно /usr/local/roxen/server.

--enable-roxen-zts

Сборка модуля Roxen, используя Zend Thread Safety.

--with-servlet[=DIR]

Включает поддержку сервлетов. DIR - это базовая папка установки JSDK. SAPI требует java-расширения, может быть собрана как доступная для dl.

--with-thttpd=SRCDIR

Сборка PHP как thttpd-модуля.

--with-tux=MODULEDIR

Сборка PHP как TUX-модуля (только для Linux).

--with-webjames=SRCDIR

Сборка PHP как WebJames-модуля (только для RISC OS)

--disable-cgi

Отключает сборку CGI-версии PHP. Доступно с версии PHP 4.3.0.

В PHP 5.3.0 этот аргумент включает FastCGI, который предварительно должен быть включен аргументом --enable-fastcgi.

--enable-force-cgi-redirect

Включает проверку безопасности для внутрисерверных переходов. Вам следует использовать ее, если вы запускаете CGI-версию с Apache.

В PHP 5.3.0 эта опция включена по умолчанию и больше не нуждается в установке. Для ее отключения необходимо установить ini-директиве cgi.force_redirect значение 0.

--enable-discard-path

Если эта опция включена, PHP CGI может быть безопасно размещен вне веб-дерева, и у пользователей не будет возможности обойти проверку .htaccess.

В PHP 5.3.0 этот аргумент отклчен по умолчанию и более не доступен. Для его включения необходимо установить ini-директиве cgi.discard_path значение 1.

--with-fastcgi

Сборка PHP как FastCGI-приложения. Не доступно начиная с PHP 4.3.0, вместо нее вам следует использовать --enable-fastcgi .

--enable-fastcgi

Если эта опция включена, то CGI-модуль будет собран с поддержкой FastCGI. Доступно начиная с PHP 4.3.0

В PHP 5.3.0 этот параметр больше не доступен. Используйте вместо него --enable-cgi.

--disable-path-info-check

Если опция указана, то пути, подобные /info.php/test?a=b будут вызывать ошибки в работе. Доступно начиная с PHP 4.3.0. Для более детальной информации см. » Руководство Apache.

User Contributed Notes

quantoid 11-Dec-2009 04:00
use --enable-soap to use SoapClient/Server classes
robert_frew at hotmail dot com 28-Jul-2009 12:25
In PHP 5.3, they have added built in support for Litespeed Webserver (LSWS) LSAPI.

Just add:

--with-litespeed

during configure.
Configure options
Директивы php.ini
Configure options


Директивы php.ini

Содержание

  • Список директив php.ini
  • Список разделов php.ini
  • Описание встроенных директив php.ini

User Contributed Notes

Frappy 29-Nov-2006 07:13
You can use the ini_set() function to set a directive's  value in your scripts provided the "CHANGEABLE" attribute in the above chart is PHP_INI_USER or PHP_INI_ALL.
russell <at> loosenut <dot> com 05-Oct-2006 01:40
In order for these settings to work in your htaccess file, you will need to add "Options" to your AllowOverride specifications for the directory/webserver if it's not already allowed.
chad 0x40 herballure 0x2e com 16-May-2006 10:30
PHP_INI_SYSTEM can be configured per-directory by placing it inside a per-directory block in httpd.conf.

    # Selectively enable APC for wildly popular directories
    # apc.enabled is Off in php.ini to reduce memory use
    <Directory /usr/local/apache2/htdocs/forum>
        php_flag apc.enabled On
    </Directory>
ensnared at gmail dot com 21-Apr-2006 10:14
In .htaccess, only true/false on/off flags can be set using php_flag. To set other values you need to use php_value, like this:

php_value upload_max_filesize 20M
RebootConcepts.com 31-Mar-2006 01:34
add settings to a .htaccess file with 'php_flag' like this:

php_flag register_globals off
php_flag magic_quotes_gpc on
List of core configure options
Список директив php.ini
Appendices


Список директив php.ini

Этот список включает директивы php.ini, которые вы можете использовать для настройки PHP.

Столбец "Место изменения" показывает когда и где может быть установлена директива. Для получения информации о значениях этих директив смотрите раздел "Где может быть установлена директива?".

Конфигурационные опции
Имя | По умолчанию | Место изменения | Список изменений
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL в PHP 4.0.0. Удалена в PHP 5.4.0.
allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 4.3.4.
allow_url_include | "0" | PHP_INI_ALL | PHP_INI_SYSTEM в PHP 5. Доступна с версии PHP 5.2.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3. Доступна с версии PHP 4.1.0.
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM в APC <= 3.0.12. Доступна с версии APC 3.0.0.
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM в APC 2. PHP_INI_ALL в APC <= 3.0.12.
apc.enable_cli | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.7.
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.6.
apc.filters | NULL | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.include_once_override | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.12.
apc.localcache | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.14.
apc.localcache.size | "512" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.14.
apc.max_file_size | "1M" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.7.
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.num_files_hint | "1000" | PHP_INI_SYSTEM |
apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM в APC 2. Удалена в APC 3.0.13.
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.11.
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.13.
apc.rfc1867_freq | "0" | PHP_INI_SYSTEM |
apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM |
apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM |
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "30" | PHP_INI_SYSTEM |
apc.slam_defense | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.0.
apc.stat | "1" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.10.
apc.stat_ctime | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.13.
apc.ttl | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.0.
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.0.
apc.user_ttl | "0" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.0.
apc.write_lock | "1" | PHP_INI_SYSTEM | Доступна с версии APC 3.0.11.
apd.bitmask | "0" | PHP_INI_ALL | Удалена в apd 0.9.
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Доступна с версии apd 0.9.
arg_separator | "&" | PHP_INI_ALL | Удалена в PHP 4.0.6.
arg_separator.input | "&" | PHP_INI_PERDIR | Доступна с версии PHP 4.0.5.
arg_separator.output | "&" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL в PHP 4.0.0.
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
async_send | "0" | PHP_INI_ALL | Доступна с версии PHP 4.2.0. Удалена в PHP 4.3.0.
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
auto_detect_line_endings | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
auto_globals_jit | "1" | PHP_INI_PERDIR | Доступна с версии PHP 5.0.0.
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
axis2.client_home | "~/work/axisc/c/deply" | PHP_INI_ALL |
axis2.enable_exception | "1" | PHP_INI_ALL |
axis2.enable_trace | "1" | PHP_INI_ALL |
axis2.log_path | "/tmp" | PHP_INI_ALL |
bcmath.scale | "0" | PHP_INI_ALL |
bcompiler.enabled | "1" | PHP_INI_ALL | Доступна с версии bcompiler 0.8.
birdstep.max_links | "-1" | PHP_INI_ALL | Доступна с версии PHP 4.2.0.
blenc.key_file | "/usr/local/etc/blenckeys" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 5.2.1.
cgi.discard_path | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.3.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 5.2.0. Доступна с версии PHP 4.3.0.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 5.2.0. Доступна с версии PHP 4.2.0.
cgi.nph | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.5.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 5.2.0. Доступна с версии PHP 4.2.0.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
child_terminate | "0" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
cli.pager | "" | PHP_INI_ALL | Доступна с версии PHP 5.4.0.
cli.prompt | "\\b \\> " | PHP_INI_ALL | Доступна с версии PHP 5.4.0.
cli_server.color | "0" | PHP_INI_ALL | Доступна с версии PHP 5.4.0.
coin_acceptor.autoreset | "On" | PHP_INI_ALL | Удалена в coin_acceptor 0.2.
coin_acceptor.auto_initialize | "Off" | PHP_INI_ALL | Доступна с версии coin_acceptor 0.2.
coin_acceptor.auto_reset | "On" | PHP_INI_ALL | Доступна с версии coin_acceptor 0.2.
coin_acceptor.command_function | "Off" | PHP_INI_ALL | Доступна с версии coin_acceptor 0.3.
coin_acceptor.delay | "53132" | PHP_INI_ALL | Удалена в coin_acceptor 0.2.
coin_acceptor.delay_coins | "53132" | PHP_INI_ALL | Доступна с версии coin_acceptor 0.2.
coin_acceptor.delay_prom | "55748" | PHP_INI_ALL | Доступна с версии coin_acceptor 0.2.
coin_acceptor.device | "/dev/ttyS1" | PHP_INI_ALL | Удалена в coin_acceptor 0.2.
coin_acceptor.lock_on_close | "Off" | PHP_INI_ALL | Доступна с версии coin_acceptor 0.2.
coin_acceptor.start_unlocked | "On" | PHP_INI_ALL | Доступна с версии coin_acceptor 0.2.
com.allow_dcom | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.5.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM в PHP 4. Доступна с версии PHP 4.1.0.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM в PHP 4. Доступна с версии PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM в PHP 4. Доступна с версии PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.5.
crack.default_dictionary | NULL | PHP_INI_PERDIR | PHP_INI_SYSTEM в crack <= 0.2. Доступна с версии PHP 4.0.5. Удалена в PHP 5.0.0.
daffodildb.default_host | "localhost" | PHP_INI_ALL |
daffodildb.default_password | "daffodil" | PHP_INI_ALL |
daffodildb.default_socket | NULL | PHP_INI_ALL |
daffodildb.default_user | "DAFFODIL" | PHP_INI_ALL |
daffodildb.port | "3456" | PHP_INI_ALL |
date.default_latitude | "31.7667" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
date.default_longitude | "35.2333" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
date.sunrise_zenith | "90.583333" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
date.sunset_zenith | "90.583333" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
date.timezone | "" | PHP_INI_ALL | Доступна с версии PHP 5.1.0.
dba.default_handler | "" | PHP_INI_ALL | Доступна с версии PHP 4.3.3.
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Доступна с версии PHP 4.3.0. Удалена в PHP 5.1.0.
default_charset | "" | PHP_INI_ALL |
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
define_syslog_variables | "0" | PHP_INI_ALL | Удалена в PHP 5.4.0.
detect_unicode | "1" | PHP_INI_ALL | Доступна с версии PHP 5.1.0. Эта возможность устарела и будет обязательно удалена в будущем.
disable_classes | "" | Только php.ini | Доступна с версии PHP 4.3.2.
disable_functions | "" | Только php.ini | Доступна с версии PHP 4.0.1.
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL | Доступна с версии PHP 4.0.3.
docref_ext | "" | PHP_INI_ALL | Доступна с версии PHP 4.3.2.
docref_root | "" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | Эта возможность устарела и будет обязательно удалена в будущем.
engine | "1" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
etpan.default.charset | "utf-8" | PHP_INI_ALL |
etpan.default.protocol | "imap" | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
exif.encode_jis | "" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
exit_on_timeout | "" | PHP_INI_ALL | Доступна с версии PHP 5.3.0
expect.logfile | "" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expose_php | "1" | Только php.ini |
extension | NULL | Только php.ini |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 5.2.0. Доступна с версии PHP 4.3.0.
fastcgi.logging | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0. Доступна с версии PHP 4.4.0.
fbsql.allow_persistant | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6. Удалена в PHP 4.2.0.
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.2.0.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.batchSize | "1000" | PHP_INI_SYSTEM | Доступна с версии PHP 4.2.0. Удалена в PHP 5.1.0.
fbsql.batchsize | "1000" | PHP_INI_ALL | Доступна с версии PHP 5.1.0.
fbsql.default_database | "" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.default_host | NULL | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.max_results | "128" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6.
fbsql.mbatchSize | "1000" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.6. Удалена в PHP 4.2.0.
fbsql.show_timestamp_decimals | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.5.
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 4.2.3. Доступна с версии PHP 4.0.3.
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL в filter <= 0.9.4. Доступна с версии PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL в filter <= 0.9.4. Доступна с версии PHP 5.2.0.
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "0" | PHP_INI_ALL | Доступна с версии PHP 5.1.3.
geoip.custom_directory | NULL | PHP_INI_ALL | Доступна с версии geoip 1.0.1.
geoip.database_standard | "GeoIP.dat" | PHP_INI_ALL | Удалена в geoip 1.0.1.
gpc_order | "GPC" | PHP_INI_ALL | Удалена в PHP 5.0.0.
hidef.ini_path | (char*)default_ini_path | PHP_INI_SYSTEM |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | Удалена в PHP 5.4.0.
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM в PHP <= 4.2.3. Доступна с версии PHP 4.0.2.
htscanner.config_file | ".htaccess" | PHP_INI_SYSTEM |
htscanner.default_docroot | "/" | PHP_INI_SYSTEM |
htscanner.default_ttl | "300" | PHP_INI_SYSTEM | Доступна с версии htscanner 0.6.0.
htscanner.stop_on_error | "0" | PHP_INI_SYSTEM | Доступна с версии htscanner 0.7.0.
http.allowed_methods | "" | PHP_INI_ALL | Доступна с версии pecl_http 0.4.0. Удалена в pecl_http 1.0.0.
http.allowed_methods_log | "" | PHP_INI_ALL | Доступна с версии pecl_http 0.12.0. Удалена в pecl_http 1.0.0.
http.cache_log | "" | PHP_INI_ALL | Доступна с версии pecl_http 0.8.0. Удалена в pecl_http 1.0.0.
http.composite_log | "" | PHP_INI_ALL | Доступна с версии pecl_http 0.12.0. Удалена в pecl_http 1.0.0.
http.etag.mode | "MD5" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.etag_mode | "MD5" | PHP_INI_ALL | Доступна с версии pecl_http 0.12.0. Удалена в pecl_http 1.0.0.
http.force_exit | "1" | PHP_INI_ALL | Доступна с версии pecl_http 0.18.0.
http.log.allowed_methods | "" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.log.cache | "" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.log.composite | "" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.log.not_found | "" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.log.redirect | "" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.ob_deflate_auto | "0" | PHP_INI_PERDIR | Доступна с версии pecl_http 0.21.0. Удалена в pecl_http 1.0.0.
http.ob_deflate_flags | "0" | PHP_INI_ALL | Доступна с версии pecl_http 0.21.0. Удалена в pecl_http 1.0.0.
http.ob_inflate_auto | "0" | PHP_INI_PERDIR | Доступна с версии pecl_http 0.21.0. Удалена в pecl_http 1.0.0.
http.ob_inflate_flags | "0" | PHP_INI_ALL | Доступна с версии pecl_http 0.21.0. Удалена в pecl_http 1.0.0.
http.only_exceptions | "0" | PHP_INI_ALL | Доступна с версии pecl_http 0.11.0.
http.persistent.handles.ident | "GLOBAL" | PHP_INI_ALL | Доступна с версии pecl_http 1.5.0.
http.persistent.handles.limit | "-1" | PHP_INI_SYSTEM | Доступна с версии pecl_http 1.5.0.
http.redirect_log | "" | PHP_INI_ALL | Доступна с версии pecl_http 0.12.0. Удалена в pecl_http 1.0.0.
http.request.datashare.connect | "0" | PHP_INI_SYSTEM | Доступна с версии pecl_http 1.3.0.
http.request.datashare.cookie | "0" | PHP_INI_SYSTEM | Доступна с версии pecl_http 1.3.0.
http.request.datashare.dns | "1" | PHP_INI_SYSTEM | Доступна с версии pecl_http 1.3.0.
http.request.datashare.ssl | "0" | PHP_INI_SYSTEM | Доступна с версии pecl_http 1.3.0.
http.request.methods.allowed | "" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.request.methods.custom | "" | PHP_INI_PERDIR | Доступна с версии pecl_http 1.0.0.
http.send.deflate.start_auto | "0" | PHP_INI_PERDIR | Доступна с версии pecl_http 1.0.0.
http.send.deflate.start_flags | "0" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.send.inflate.start_auto | "0" | PHP_INI_PERDIR | Доступна с версии pecl_http 1.0.0.
http.send.inflate.start_flags | "0" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
http.send.not_found_404 | "1" | PHP_INI_ALL | Доступна с версии pecl_http 1.0.0.
hyerwave.allow_persistent | "0" | PHP_INI_SYSTEM | Удалена в PHP 4.3.2.
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.3.2. Удалена в PHP 5.0.0.
hyperwave.default_port | "418" | PHP_INI_ALL | Удалена в PHP 5.0.0.
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
ibase.default_db | NULL | PHP_INI_SYSTEM | Доступна с версии PHP 5.0.0.
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Доступна с версии ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Доступна с версии ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Доступна с версии ibm_db2 1.0.2.
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Удалена в PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Удалена в PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Удалена в PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Удалена в PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Удалена в PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Удалена в PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Удалена в PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Удалена в PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Удалена в PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Удалена в PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Удалена в PHP 5.2.1.
ignore_repeated_errors | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
ignore_repeated_source | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
ignore_user_abort | "0" | PHP_INI_ALL |
imlib2.font_cache_max_size | "524288" | PHP_INI_ALL |
imlib2.font_path | "/usr/share/php/fonts/" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR в PHP <= 4.2.3.
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
ingres.array_index_start | "1" | PHP_INI_ALL | Доступна с версии ingres 1.4.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Доступна с версии ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Доступна с версии ingres 1.1.
ingres.default_database | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
ingres.default_password | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
ingres.default_user | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
ingres.max_links | "-1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
ingres.report_db_warnings | "1" | PHP_INI_ALL | Доступна с версии ingres 1.1.
ingres.timeout | "-1" | PHP_INI_ALL | Доступна с версии ingres 1.4.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Доступна с версии ingres 1.2.1.
ircg.control_user | "nobody" | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.1.0.
ircg.keep_alive_interval | "60" | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.1.0.
ircg.max_format_message_sets | "12" | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.1.0.
ircg.shared_mem_size | "6000000" | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.1.0.
ircg.work_dir | "/tmp/ircg" | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.1.0.
last_modified | "0" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
ldap.base_dn | NULL | PHP_INI_ALL | Удалена в PHP 4.2.0.
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log.dbm_dir | "" | PHP_INI_ALL | Удалена в PHP 4.0.1.
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3. В PHP 5.3.0 помечена как устаревшая. Удалена в PHP 5.4.0.
magic_quotes_runtime | "0" | PHP_INI_ALL | Удалена в PHP 5.4.0.
magic_quotes_sybase | "0" | PHP_INI_ALL | Удалена в PHP 5.4.0.
mail.add_x_header | "0" | PHP_INI_SYSTEM|PHP_INI_PERDIR | Доступна с версии PHP 5.3.0.
mail.force_extra_parameters | NULL | Только php.ini | Доступна с версии PHP 5.0.0.
mail.log | "" | PHP_INI_ALL | Доступна с версии PHP 5.3.0.
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Доступна с версии PHP 4.1.0. Удалена в PHP 4.2.0.
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | PHP_INI_ALL |
max_execution_time | "30" | PHP_INI_ALL |
max_input_nesting_level | "64" | PHP_INI_PERDIR | Доступна с версии PHP 4.4.8 и PHP 5.2.3.
max_input_vars | 1000 | PHP_INI_PERDIR | Доступна с версии PHP 5.3.9.
max_input_time | "-1" | PHP_INI_PERDIR | Доступна с версии PHP 4.3.0.
mbstring.detect_order | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.6.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Доступна с версии PHP 4.3.0.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM в PHP <= 4.2.3; PHP_INI_SYSTEM | PHP_INI_PERDIR начиная с версии PHP 4.3 по 5.2.6. Доступна с версии PHP 4.2.0.
mbstring.http_input | "pass" | PHP_INI_ALL | Доступна с версии PHP 4.0.6.
mbstring.http_output | "pass" | PHP_INI_ALL | Доступна с версии PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.6.
mbstring.language | "neutral" | PHP_INI_ALL | Доступна с версии PHP 4.3.0; PHP_INI_PERDIR в PHP <= 5.2.6
mbstring.script_encoding | NULL | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Доступна с версии PHP 5.1.2.
mbstring.substitute_character | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.6.
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.2.
mcrypt.modes_dir | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.2.
memcache.allow_failover | "1" | PHP_INI_ALL | Доступна с версии memcache 2.0.2.
memcache.chunk_size | "8192" | PHP_INI_ALL | Доступна с версии memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Доступна с версии memcache 2.0.2.
memcache.hash_function | "crc32" | PHP_INI_ALL | Доступна с версии memcache 2.2.0.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Доступна с версии memcache 2.2.0.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Доступна с версии memcache 2.1.0.
memory_limit | "128M" | PHP_INI_ALL |
mime_magic.debug | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Доступна с версии PHP 4.3.0.
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.batchsize | "0" | PHP_INI_ALL | Доступна с версии PHP 4.0.4.
mssql.charset | "" | PHP_INI_ALL | Доступна с версии PHP 5.1.2.
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.datetimeconvert | "1" | PHP_INI_ALL | Доступна с версии PHP 4.2.0.
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_procs | "-1" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.3.0.
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Доступна с версии PHP 4.1.0.
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM в PHP <= 4.3.2. Доступна с версии PHP 4.3.0.
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.1.
mysql.default_user | NULL | PHP_INI_ALL |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
mysqli.default_host | NULL | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Доступна с версии PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.0.0.
namazu.debugmode | "0" | PHP_INI_ALL |
namazu.lang | NULL | PHP_INI_ALL |
namazu.loggingmode | "0" | PHP_INI_ALL |
namazu.sortmethod | NULL | PHP_INI_ALL |
namazu.sortorder | NULL | PHP_INI_ALL |
nsapi.read_timeout | "60" | PHP_INI_ALL | Доступна с версии PHP 4.3.3.
oci8.default_prefetch | "10" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.2.
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.2.
oci8.old_oci_close_semantics | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.2.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.2.
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.2.
oci8.privileged_connect | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.2.
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.2.
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.default_db | NULL | PHP_INI_ALL |
odbc.default_pw | NULL | PHP_INI_ALL |
odbc.default_user | NULL | PHP_INI_ALL |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbtp.datetime_format | "object" | PHP_INI_ALL |
odbtp.detach_default_queries | "0" | PHP_INI_ALL |
odbtp.guid_format | "string" | PHP_INI_ALL | Доступна с версии odbtp 1.1.3.
odbtp.interface_file | "/usr/local/share/odbtp.conf" | PHP_INI_ALL |
odbtp.truncation_errors | "1" | PHP_INI_ALL |
opendirectory.default_separator | "/" | PHP_INI_ALL | Удалена в opendirectory 0.2.2.
opendirectory.max_refs | "-1" | PHP_INI_ALL |
opendirectory.separator | "/" | PHP_INI_ALL | Доступна с версии opendirectory 0.2.2.
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM в PHP < 5.2.3.
oracle.allow_persistent | "-1" | PHP_INI_ALL | Удалена в PHP 5.1.0.
oracle.max_links | "-1" | PHP_INI_ALL | Удалена в PHP 5.1.0.
oracle.max_persistent | "-1" | PHP_INI_ALL | Удалена в PHP 5.1.0.
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR | Доступна с версии PHP 4.0.4.
pam.servicename | "php" | PHP_INI_ALL |
pcre.backtrack_limit | "1000000" | PHP_INI_ALL | Доступна с версии PHP 5.2.0.
pcre.recursion_limit | "100000" | PHP_INI_ALL | Доступна с версии PHP 5.2.0.
pdo.dsn.* |  | php.ini only | Доступна с версии PHP 5.1.0.
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Доступна с версии PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.1. Эта возможность устарела и будет обязательно удалена в будущем.
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
pfpro.defaultport | "443" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
pfpro.proxyaddress | "" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
pfpro.proxylogon | "" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
pfpro.proxypassword | "" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
pfpro.proxyport | "" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 5.1.0.
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
phar.extract_list | "" | PHP_INI_ALL | Доступна с версии phar 1.1.0.
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
enable_post_data_reading | On | PHP_INI_SYSTEM|PHP_INI_PERDIR | Доступна с версии PHP 5.4.0.
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM в PHP <= 4.2.3. Доступна с версии PHP 4.0.3.
precision | "14" | PHP_INI_ALL |
printer.default_printer | "" | PHP_INI_ALL | Доступна с версии PHP 4.0.6. Удалена в PHP 4.1.1.
python.append_path | "" | PHP_INI_ALL |
python.prepend_path | "." | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.0.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3. Помечена устаревшей в PHP 5.3.0. Удалена в PHP 5.4.0.
register_long_arrays | "1" | PHP_INI_PERDIR | Доступна с версии PHP 5.0.0. Помечена устаревшей в PHP 5.3.0. Удалена в PHP 5.4.0.
report_memleaks | "1" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
report_zend_debug | "1" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
request_order | "" | PHP_INI_SYSTEM|PHP_INI_PERDIR | Доступна с версии PHP 5.3.0
runkit.internal_override | "0" | PHP_INI_SYSTEM |
runkit.superglobal | "" | PHP_INI_PERDIR |
safe_mode | "0" | PHP_INI_SYSTEM | Удалена в PHP 5.4.0.
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Удалена в PHP 5.4.0.
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Удалена в PHP 5.4.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.1.0. Удалена в PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Доступна с версии PHP 4.1.0. Удалена в PHP 5.4.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Удалена в PHP 5.4.0.
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
serialize_precision | "17" | PHP_INI_ALL | Доступна с версии PHP 4.3.2. До версии PHP 5.3.5 значение по умолчанию было равно 100.
session.auto_start | "0" | PHP_INI_ALL |
session.bug_compat_42 | "1" | PHP_INI_ALL | Доступна с версии PHP 4.3.0. Удалена в PHP 5.4.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Доступна с версии PHP 4.3.0. Удалена в PHP 5.4.0.
session.cache_expire | "180" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_httponly | "" | PHP_INI_ALL | Доступна с версии PHP 5.2.0.
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL | Доступна с версии PHP 4.0.4.
session.entropy_file | "" | PHP_INI_ALL |
session.entropy_length | "0" | PHP_INI_ALL |
session.gc_dividend | "100" | PHP_INI_ALL | Доступна с версии PHP 4.3.0. Удалена в PHP 4.3.2.
session.gc_divisor | "100allow_call_time_pass_reference" | PHP_INI_ALL | Доступна с версии PHP 4.3.2.
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.gc_probability | "1" | PHP_INI_ALL |
session.hash_bits_per_character | "4" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
session.hash_function | "0" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
session.name | "PHPSESSID" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.save_path | "" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL в PHP <= 4.2.3. PHP_INI_PERDIR в PHP < 5. Доступна с версии PHP 4.0.3.
session_pgsql.create_table | "1" | PHP_INI_SYSTEM |
session_pgsql.db | "host=localhost dbname=php_session user=nobody" | PHP_INI_SYSTEM |
session_pgsql.disable | "0" | PHP_INI_SYSTEM |
session_pgsql.failover_mode | "0" | PHP_INI_SYSTEM |
session_pgsql.gc_interval | "3600" | PHP_INI_SYSTEM |
session_pgsql.keep_expired | "0" | PHP_INI_SYSTEM |
session_pgsql.sem_file_name | "/tmp/php_session_pgsql" | PHP_INI_SYSTEM |
session_pgsql.serializable | "0" | PHP_INI_SYSTEM |
session_pgsql.short_circuit | "0" | PHP_INI_SYSTEM |
session_pgsql.use_app_vars | "0" | PHP_INI_SYSTEM |
session_pgsql.vacuum_interval | "21600" | PHP_INI_SYSTEM |
short_open_tag | "1" | PHP_INI_ALL | PHP_INI_ALL в PHP 4.0.0. PHP_INI_PERDIR в PHP < 5.3.0
simple_cvs.authMethod | "0" | PHP_INI_ALL |
simple_cvs.compressionLevel | "0" | PHP_INI_ALL |
simple_cvs.cvsRoot | "0" | PHP_INI_ALL |
simple_cvs.host | "0" | PHP_INI_ALL |
simple_cvs.moduleName | "0" | PHP_INI_ALL |
simple_cvs.userName | "0" | PHP_INI_ALL |
simple_cvs.workingDir | "0" | PHP_INI_ALL |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
soap.wsdl_cache | "1" | PHP_INI_ALL | Доступна с версии PHP 5.1.5.
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
soap.wsdl_cache_limit | "5" | PHP_INI_ALL | Доступна с версии PHP 5.1.5.
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite.assoc_case | "0" | PHP_INI_ALL | Доступна с версии PHP 5.0.0.
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL в PHP <= 4.0.2. PHP_INI_SYSTEM в PHP <= 4.0.3.
sybase.hostname | NULL | PHP_INI_ALL | Удалена в PHP 4.0.2.
sybase.interface_file | "" | PHP_INI_ALL |
sybase.login_timeout | "0" | PHP_INI_ALL | Удалена в PHP 4.0.2.
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL в PHP <= 4.0.2. PHP_INI_SYSTEM в PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL в PHP <= 4.0.2. PHP_INI_SYSTEM в PHP <= 4.0.3.
sybase.min_client_severity | "10" | PHP_INI_ALL | Удалена в PHP 4.0.2.
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybase.min_server_severity | "10" | PHP_INI_ALL | Удалена в PHP 4.0.2.
sybase.timeout | "0" | PHP_INI_ALL | Удалена в PHP 4.0.2.
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 4.0.2. Доступна с версии PHP 4.0.2. Удалена в PHP 4.0.3.
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
sybct.hostname | NULL | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 4.0.3.
sybct.login_timeout | "-1" | PHP_INI_ALL | Доступна с версии PHP 4.0.2.
sybct.max_links | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 4.0.2. Доступна с версии PHP 4.0.2. Удалена в PHP 4.0.3.
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 4.0.2. Доступна с версии PHP 4.0.2. Удалена в PHP 4.0.3.
sybct.min_client_severity | "10" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 4.0.3.
sybct.min_server_severity | "10" | PHP_INI_ALL | Доступна с версии PHP 4.0.2. Удалена в PHP 4.0.3.
sybct.packet_size | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.5.
sybct.timeout | "0" | PHP_INI_ALL | Доступна с версии PHP 4.0.2.
sysvshm.init_mem | "10000" | PHP_INI_ALL |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR в PHP 5. Доступна с версии PHP 5.0.0.
tidy.default_config | "" | PHP_INI_SYSTEM | Доступна с версии PHP 5.0.0.
track_errors | "0" | PHP_INI_ALL |
track_vars | "1" | PHP_INI_ALL | Удалена в PHP 4.0.3.
unserialize_callback_func | NULL | PHP_INI_ALL | Доступна с версии PHP 4.2.0.
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
max_file_uploads | 20 | PHP_INI_SYSTEM | Доступна с версии PHP 5.2.12.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Доступна с версии PHP 4.0.4.
user_agent | NULL | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM | Доступна с версии PHP 5.3.0.
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM | Доступна с версии PHP 5.3.0.
valkyrie.auto_validate | "0" | PHP_INI_ALL |
valkyrie.config_path | NULL | PHP_INI_ALL |
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 5.0.5.
velocis.max_links | "-1" | PHP_INI_ALL | Удалена в PHP 4.2.0.
vld.active | "0" | PHP_INI_SYSTEM |
vld.execute | "1" | PHP_INI_SYSTEM | Доступна с версии vld 0.8.0.
vld.skip_append | "0" | PHP_INI_SYSTEM | Доступна с версии vld 0.8.0.
vld.skip_prepend | "0" | PHP_INI_SYSTEM | Доступна с версии vld 0.8.0.
windows_show_crt_warning | "0" | PHP_INI_ALL | Доступна с версии PHP 5.4.0.
xbithack | "0" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
xdebug.auto_profile | "0" | PHP_INI_ALL | Удалена в Xdebug 2.0.0.
xdebug.auto_profile_mode | "0" | PHP_INI_ALL | Удалена в Xdebug 2.0.0.
xdebug.auto_trace | "0" | PHP_INI_ALL |
xdebug.collect_includes | "1" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.collect_params | "0" | PHP_INI_ALL |
xdebug.collect_return | "0" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.collect_vars | "0" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.default_enable | "1" | PHP_INI_ALL | PHP_INI_SYSTEM в Xdebug 1.
xdebug.dump.COOKIE | NULL | PHP_INI_ALL |
xdebug.dump.ENV | NULL | PHP_INI_ALL |
xdebug.dump.FILES | NULL | PHP_INI_ALL |
xdebug.dump.GET | NULL | PHP_INI_ALL |
xdebug.dump.POST | NULL | PHP_INI_ALL |
xdebug.dump.REQUEST | NULL | PHP_INI_ALL |
xdebug.dump.SERVER | NULL | PHP_INI_ALL |
xdebug.dump.SESSION | NULL | PHP_INI_ALL |
xdebug.dump_globals | "1" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.dump_once | "1" | PHP_INI_ALL |
xdebug.dump_undefined | "0" | PHP_INI_ALL |
xdebug.extended_info | "1" | PHP_INI_SYSTEM | Доступна с версии Xdebug 2.0.0.
xdebug.idekey | "" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.manual_url | "http://www.php.net" | PHP_INI_ALL |
xdebug.max_nesting_level | "100" | PHP_INI_ALL |
xdebug.output_dir | "/tmp" | PHP_INI_PERDIR | PHP_INI_SYSTEM в Xdebug <= 1.2.0. Удалена в Xdebug 2.0.0.
xdebug.profiler_aggregate | "0" | PHP_INI_PERDIR | Доступна с версии Xdebug 2.0.0.
xdebug.profiler_append | "0" | PHP_INI_PERDIR | Доступна с версии Xdebug 2.0.0.
xdebug.profiler_enable | "0" | PHP_INI_PERDIR | Доступна с версии Xdebug 2.0.0.
xdebug.profiler_enable_trigger | "0" | PHP_INI_PERDIR | Доступна с версии Xdebug 2.0.0.
xdebug.profiler_output_dir | "/tmp" | PHP_INI_PERDIR | Доступна с версии Xdebug 2.0.0.
xdebug.profiler_output_name | "cachegrind.out.%p" | PHP_INI_PERDIR | Доступна с версии Xdebug 2.0.0.
xdebug.remote_autostart | "0" | PHP_INI_ALL | Доступна с версии PHP 4.1.0.
xdebug.remote_enable | "0" | PHP_INI_PERDIR |
xdebug.remote_handler | "dbgp" | PHP_INI_ALL |
xdebug.remote_host | "localhost" | PHP_INI_ALL |
xdebug.remote_log | "" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.remote_mode | "req" | PHP_INI_ALL |
xdebug.remote_port | "9000" | PHP_INI_ALL |
xdebug.show_exception_trace | "0" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.show_local_vars | "0" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.show_mem_delta | "0" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.trace_format | "0" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.trace_options | "0" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.trace_output_dir | "/tmp" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.trace_output_name | "trace.%c" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.var_display_max_children | "128" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.var_display_max_data | "512" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xdebug.var_display_max_depth | "3" | PHP_INI_ALL | Доступна с версии Xdebug 2.0.0.
xmlrpc_errors | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.1.0.
xmlrpc_error_number | "0" | PHP_INI_ALL | Доступна с версии PHP 4.1.0.
xmms.path | "/usr/bin/xmms" | PHP_INI_ALL |
xmms.session | "0" | PHP_INI_ALL |
y2k_compliance | "1" | PHP_INI_ALL | Удалена в PHP 5.4.0.
yami.response.timeout | "5" | PHP_INI_ALL | Доступна с версии yami 1.0.1.
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_file | NULL | PHP_INI_ALL | Доступна с версии PHP 4.3.0. Удалена в PHP 5.0.0.
yaz.log_mask | NULL | PHP_INI_ALL | Доступна с версии yaz 1.0.3.
yaz.max_links | "100" | PHP_INI_ALL | Доступна с версии PHP 4.3.0. Удалена в PHP 5.0.0
zend.enable_gc | "1" | PHP_INI_ALL | Доступна с версии PHP 5.3.0.
zend.multibyte | "0" | PHP_INI_PERDIR | Доступна с версии PHP 5.4.0.
zend.script_encoding | NULL | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.3.0.
zend.signal_check | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.4.0
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.3.0.
zend_extension | NULL | Только php.ini |
zend_extension_debug | NULL | Только php.ini |
zend_extension_debug_ts | NULL | Только php.ini |
zend_extension_ts | NULL | Только php.ini |
zlib.output_compression | "0" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
zlib.output_compression_level | "-1" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
zlib.output_handler | "" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.
Директивы php.ini
Список разделов php.ini
Директивы php.ini


Список разделов php.ini

В этом списке указаны разделы, в которых вы можете настроить PHP в зависимости от хоста или пути. Эти разделы необязательны.

Данные разделы не имеют прямого влияния на PHP. Они нужны для группировки других директив php.ini вместе и для возможности действовать в зависимости от определенного хоста или пути.

Данные разделы используются только в режиме CGI/FastCGI и в них не могут быть использованы директивы extension и zend_extension.

Разделы
Название | Место изменения | История изменений
[HOST=] | PHP_INI_SYSTEM | Добавлено в PHP 5.3.0.
[PATH=] | PHP_INI_SYSTEM | Добавлено в PHP 5.3.0.

Краткое разъяснение конфигурационных директив.

[HOST=<host>]

Данный раздел позволяет определять набор php.ini директив, которые будут применяться только к указанному хосту.

Пример #1 Активация полного логирования и сообщения об ошибках для dev. домена

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

Данный раздел позволяет определять набор php.ini директив, которые будут применяться, если скрипт будет запущен из указанного пути.

Пример #2 Добавление скрипта безопасности для защищенных зон

[PATH=/home/site/public/secure]
auto_prepend_file=security.php

User Contributed Notes

Asad 11-Mar-2012 04:27
Important thing to note:

Directives set in these sections cannot be overridden by user-defined INI files or at runtime.
z dot himdi at bita dot nl 04-Aug-2011 07:53
On Windows IIS 7 server I noticed that [PATH=] was not listened to. [HOST=] however worked.
leo 06-May-2011 03:21
Just developed the probably first php.ini hack to add commands which will only be parsed before PHP 5.3 when using mod_php.

<?php

# Disable eAccelerator by default
eaccelerator.enable = 0

# Now, to prevent incompatibilities with Zend Optimizer+, we
# want to enable eAccelerator only in PHP 5.2 or lower.
[HOST=*]
eaccelerator.enable = 1

?>

What is happening here? In PHP 5.3, php.ini sections to set up PHP on a per host basis have been introduced:

http://www.php.net/manual/en/ini.sections.php

These sections only work in CGI/FastCGI mode, however there still seems to be a difference in how the php.ini file is parsed in PHP 5.2 and PHP 5.3 when using mod_php: PHP 5.3 ignores everything below the line [HOST=*], whereas PHP 5.2 does not.

In the above example, PHP 5.3 only reads "eaccelerator.enable = 0" and then stops at the invalid command [HOST=*]. However, PHP 5.2 seems to ignore the invalid command and parses the whole configuration file, ending up with "eaccelerator.enable = 1".
stickman 05-Jan-2011 01:39
This doesn't seem to work with php-fpm.
The values defined under PATH or HOST will become the new master value for all the processes (as if they were redefined).
crash at lubyte dot de 06-Sep-2010 05:45
If you have a system which uses separated PHP inis for loading extensions (Debian, Fedora and most other distributions do so), [PATH=] or [HOST=] will prevent loading extensions defined in those ini files (extension= and zend_extension=).

I had some headache, when I added a hosts.ini to /etc/php5/cgi/conf.d (Debians default), where I wanted to define some defaults for a host name. The manual says extension= and zend_extension= aren't allowed in [HOST=] and [PATH=] (see above). I figured out that you can easily fix that with adding [PHP] after your definitions.

For example hosts.ini:
[HOST=dev.example.com]
display_errors = on

[PHP]

this will change the section back to [PHP] where extension= and zend_extension= is allowed.
robert dot johnson at icap dot com 12-Apr-2010 10:26
Adding PATH= applies only to the named path and does not include sub-directories, you have to add a PATH= value for each sub-directory.

Also some settings have no effect even though phpinfo recognises and displays the per-folder value as the 'local' value, and the default as the 'master' value.

'fastcgi.impersonate' always uses the master setting.
public at grik dot net 24-Sep-2009 03:00
In [HOST=...] one should use only the 1st server name from the list of server names.

I.E. if you have
server_name example.com, example2.com;
and will use www.example.com in a browser,
use [HOST=example.com] in php.ini for both addresses.

PHP looks not at the HOST request header (as I expected), but at the SERVER_NAME parameter (which by default is the 1st from the list of names, no matter what the HOST is).
Список директив php.ini
Описание встроенных директив php.ini
Директивы php.ini


Описание встроенных директив php.ini

Этот список включает встроенные директивы php.ini, которые вы можете использовать для настройки PHP. Директивы, которые обрабатываются модулями, перечислены и подробно описаны на страницах документаций соответствующих модулей. К примеру, информация о директивах сессий может быть найдена на странице документации сессий.

Опции Httpd

Опции Httpd
Имя | По умолчанию | Место изменения | Список изменений
async_send | "0" | PHP_INI_ALL |

Языковые опции

Опции языка и прочих настроек
Имя | По умолчанию | Место изменения | Список изменений
short_open_tag | "1" | PHP_INI_ALL | PHP_INI_ALL в PHP <= 4.0.0. PHP_INI_PERDIR в PHP < 5.3.0
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.0.0.
precision | "14" | PHP_INI_ALL |
serialize_precision | "17" | PHP_INI_ALL | Доступна с версии PHP 4.3.2. До версии PHP 5.3.5 значение по умолчанию было равно 100.
y2k_compliance | "1" | PHP_INI_ALL | Удалена в PHP 5.4.0.
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL в PHP 4.0.0.
disable_functions | "" | php.ini only | Доступна с версии PHP 4.0.1.
disable_classes | "" | php.ini only | Доступна с версии PHP 4.3.2.
exit_on_timeout | "" | PHP_INI_ALL | Доступна с версии PHP 5.3.0.
expose_php | "1" | Только php.ini |
zend.multibyte | "0" | PHP_INI_ALL | Доступна с версии PHP 5.4.0
zend.script_encoding | NULL | PHP_INI_ALL | Доступна с версии PHP 5.4.0
zend.signal_check | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 5.4.0
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Доступна с версии PHP 5.0.0. Удалена в PHP 5.3.0
detect_unicode | "1" | PHP_INI_ALL | Доступна с версии PHP 5.1.0. Эта возможность устарела и будет обязательно удалена в будущем.

Краткое разъяснение конфигурационных директив.

short_open_tag boolean

Определяет, разрешается ли короткая форма записи (<? ?>) тегов PHP. Если вы хотите использовать PHP совместно с XML, вы можете отключить эту опцию, чтобы беспрепятственно использовать <?xml ?>. В противном случае, вы можете отобразить это при помощи PHP, например: <?php echo '<?xml version="1.0"?>'; ?>. Если же эта опция отключена, вы должны использовать длинную форму открывающего тега PHP (<?php ?>).

Замечание:

Эта директива также влияла на сокращение <?= до версии PHP 5.4.0, которое идентично записи <? echo. Для использования этого сокращения должна была быть включена директива short_open_tag. Начиная с версии PHP 5.4.0 запись <?= стала доступна всегда.

asp_tags boolean
Включает использование тегов в стиле ASP в дополнение к обычным тегам <?php ?>. Это касается и сокращения для отображения значения переменных <%= $value %>. Для получения дополнительной информации, обратитесь к разделу Экранирование HTML.
precision integer
Количество значащих цифр, отображаемых для чисел с плавающей точкой.
serialize_precision integer
Количество сохраняемых значащих цифр при сериализации чисел с плавающей точкой.
y2k_compliance boolean
Включение совместимости с 2000 годом (создаст проблемы с несовместимыми браузерами)
allow_call_time_pass_reference boolean

Нужно ли выводить предупреждение, если аргументы передаются по ссылке при вызове функции. Рекомендуется указывать в объявлении функции передаваемые по ссылке аргументы. Попробуйте выключить эту опцию и убедиться, что ваши скрипты правильно работают без нее и что они будут работать с будущими версиями языка (вы будете получать предупреждение каждый раз, когда вы будете пользоваться этой возможностью).

Передача аргументов по ссылке во время вызова функции была объявлена устаревшей из соображений чистоты кода. Функция может менять свои аргументы недокументированным способом, если бы аргумент не объявлялся передаваемым по ссылке. Чтобы избежать побочных эффектов, лучше явно указывать, какие аргументы передаются по ссылке только при объявлении функции.

См. также Подробное описание ссылок.

Список изменений для allow_call_time_pass_reference
Версия | Описание
5.4.0 | Удалена из PHP.
5.3.0 | Генерирует ошибку уровня E_DEPRECATED.
5.0.0 | Устарела и генерирует ошибку уровня E_COMPILE_WARNING.

expose_php boolean

Выдает факт присутствия PHP на сервере, включая передачу версии PHP в HTTP-заголовке (например, X-Powered-By: PHP/5.3.7). Идентификаторы логотипов также показываются, таким образом, при добавлении их к ссылке на сайте с PHP будет показан соответствующий логотип (например, » http://www.php.net/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). Отключение данной опции также влияет на вывод функции phpinfo(), в этом случае логотип PHP и информация о разработчиках, принимавших участие в разработке PHP, отображаться не будет.

Смотрите также php_logo_guid() и phpcredits().

disable_functions string

Эта директива позволяет отключить некоторые функции по причинам безопасности. Она принимает список имен функций, разделенный запятыми. disable_functions не подвержена влиянию безопасного режима.

Только внутренние функции могут быть отключены с помощью этой директивы. Пользовательские функции ей не подвержены.

Эта директива должна быть установлена в php.ini. Например, ее нельзя использовать в httpd.conf.

disable_classes string
Эта директива позволяет отключить некоторые классы по причинам безопасности. Она принимает список имен классов, разделенных запятыми. disable_classes не подвержена влиянию безопасного режима. Эта директива должна быть установлена в php.ini. Например, ее нельзя использовать в httpd.conf.

Замечание: Замечание о доступности
Эта директива стала доступной в PHP 4.3.2

zend.ze1_compatibility_mode boolean

Включает режим совместимости с Zend Engine 1 (PHP 4). Это влияет на клонирование, приведение типов (объекты без свойств приводятся к FALSE или 0) и сравнение объектов. В этом режиме объекты по умолчанию передаются по значению вместо ссылки.

См. также раздел Переход с PHP 4 на PHP 5.

Внимание

Эта возможность была помечена УСТАРЕВШЕЙ и БЫЛА УДАЛЕНА в версии PHP 5.3.0.

zend.multibyte boolean

Разрешает парсинг исходных файлов в многобайтных кодировках.

zend.script_encoding string

Данное значение будет использовано, только при отсутствии директивы declare(encoding=...) в начале скрипта.

zend.signal_check boolean

Определяет, нужно ли проверять замененные обработчики сигналов при завершении скрипта.

detect_unicode boolean

Определяет, нужно ли проверять BOM (Byte Order Mark, метка порядка байт) и корректность многобайтных символов в файле. Эта проверка производится до вызова __halt_compiler(). Доступна только в режиме Zend Multibyte.

exit_on_timeout boolean

Эта директива только для Apache1 mod_php, которая заставляет потомка Apache завершиться, если произошел тайм-аут исполнения скрипта PHP. Такой тайм-аут приводит к внутреннему вызову longjmp() в Apache1, который оставляет некоторые расширения в несогласованном состоянии. По завершении процесса все неснятые блокировки или память будут очищены.

Ограничения ресурсов

Ограничения ресурсов
Имя | По умолчанию | Место изменения | Список изменений
memory_limit | "128M" | PHP_INI_ALL | "8M" до PHP 5.2.0, "16M" в PHP 5.2.0

Краткое разъяснение конфигурационных директив.

memory_limit integer

Эта директива задает максимальный объем памяти в байтах, который разрешается использовать скрипту. Это помогает предотвратить ситуацию, при которой плохо написанный скрипт съедает всю доступную память сервера. Для того, чтобы убрать ограничения, установите значение этой директивы в -1.

В версиях до PHP 5.2.1 для использования этой директивы, она должна была быть указана на этапе компиляции. Так, ваша строка конфигурации должна была включать: --enable-memory-limit . Эта опция компиляции была также необходима для использования функций memory_get_usage() и memory_get_peak_usage() до версии 5.2.1.

Если используется integer, значение измеряется байтами. Вы также можете использовать сокращенную запись, которая описана в этом разделе FAQ.

См. также: max_execution_time.

Настройка производительности

Настройка производительности
Название | Значение по умолчанию | Место изменения | История изменений
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Доступна с версии PHP 5.1.0.

Краткое разъяснение конфигурационных директив.

realpath_cache_size integer

Определяет размера кэша realpath, используемого в PHP. Это значение должно быть увеличено на системах, в которых PHP открывает большое количество файлов соответственно количеству выполняемых файловых операций.

realpath_cache_ttl integer

Время (в секундах) в течение которого будет использован кэш realpath для указанного файла или директории. Для систем с редко меняющимися файлайми это значение можно увеличить.

Обработка данных

Конфигурационные опции обработки данных
Имя | По умолчанию | Место изменения | Список изменений
track_vars | "On" | PHP_INI_?? |
arg_separator.output | "&" | PHP_INI_ALL | Доступна с версии PHP 4.0.5.
arg_separator.input | "&" | PHP_INI_PERDIR | Доступна с версии PHP 4.0.5.
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 5.0.5.
request_order | "" | PHP_INI_PERDIR | Доступна с версии PHP 5.3.0
auto_globals_jit | "1" | PHP_INI_PERDIR | Доступна с версии PHP 5.0.0.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3. Удалена в PHP 5.4.0.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
register_long_arrays | "1" | PHP_INI_PERDIR | Доступна с версии PHP 5.0.0. Помечена устаревшей в PHP 5.3.0. Удалена в PHP 5.4.0.
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM в PHP <= 4.2.3. Доступна с версии PHP 4.0.3.
gpc_order | "GPC" | PHP_INI_ALL |
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "" | PHP_INI_ALL |
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3. Доступна с версии PHP 4.1.0.
allow_webdav_methods | "0" | PHP_INI_PERDIR |

Краткое разъяснение конфигурационных директив.

track_vars boolean

Если включено, переменные окружения, GET, POST, Cookie и серверные переменные могут быть получены через глобальные ассоциативные массивы $_ENV, $_GET, $_POST, $_COOKIE и $_SERVER.

Обратите внимание, что начиная с версии PHP 4.0.3, track_vars всегда включена.

arg_separator.output string

Этот разделитель используется в генерируемых PHP URL в качестве разделителя аргументов.

arg_separator.input string

Список разделителей, используемых PHP для получения переменных из URL.

Замечание:

Каждый символ в этой директиве считается разделителем!

variables_order string

Устанавливает порядок обработки переменных EGPCS (Environment, Get, Post, Cookie, и Server). Например, если variables_order установлена в "SP", то PHP создаст superglobals $_SERVER и $_POST, но не будет создавать $_ENV, $_GET и $_COOKIE. Установка в "" означает, что ни одна superglobals не будет установлена.

Если включена устаревшая директива register_globals, то variables_order также устанавливает порядок экспорта переменных ENV, GET, POST, COOKIE и SERVER в глобальное пространство. Например, если порядок переменных установлен как "EGPCS", register_globals включена, и существуют обе $_GET['action'] и $_POST['action'], то переменная $action будет содержать значение $_POST['action'], так как P в нашем примере идет после G.

Внимание

В CGI и FastCGI SAPI, в $_SERVER также добавляются значения переменных окружения; S всегда эквивалентна ES вне зависимости от самого положения E в этой директиве.

Замечание:

Эта директива также влияет на содержимое и порядок переменной $_REQUEST.

request_order string

Эта директива регулирует порядок, в котором PHP добавляет переменные GET, POST и Cookie в массив _REQUEST. Добавление производится слева направо, новые значения перезаписывают старые.

Если значение этой директивы не установлено, то используется значение директивы variables_order для содержимого переменной $_REQUEST.

Учтите, что файлы php.ini, поставляемые с дистрибутивом, по соображениям безопасности не содержат значение 'C' (cookies).

auto_globals_jit boolean

Когда включено, переменные SERVER и ENV создаются в тот момент, когда они впервые используются (Just In Time), а не в начале выполнения скрипта. Если эти переменные в скрипте не используются, включение этой директивы приведет к росту производительности.

Директивы PHP register_globals, register_long_arrays и register_argc_argv должны быть выключены для правильной работы этой директивы. Начиная с версии PHP 5.1.3 стало необязательно выключать register_argc_argv.

Внимание

Использование переменных SERVER и ENV проверяется на стадии компиляции, поэтому их использование с помощью, например, переменных переменных не запустит их инициализацию.

register_globals boolean

Регистрировать или нет переменные EGPCS (Environment, GET, POST, Cookie, Server) в качестве глобальных переменных.

Начиная с версии » PHP 4.2.0, значением по умолчанию для этой директивы является off.

Пожалуйста, ознакомтесь с главой о безопасности Использование глобальных переменных для получения дополнительной информации.

Обратите внимание, что register_globals не может быть установлена во время выполнения скрипта (ini_set()). Тем не менее, вы можете использовать .htaccess, если ваш сервер позволяет это, как описано выше. Пример директивы в .htaccess: php_flag register_globals off.

Замечание:

На поведение register_globals влияет директива variables_order.

Внимание

Данная возможность была помечена УСТАРЕВШЕЙ начиная с версии PHP 5.3.0 и была УДАЛЕНА в версии PHP 5.4.0.

register_argc_argv boolean
Сообщает PHP, следует ли объявлять переменные argv и argc (которые будут содержать GET-информацию). См. также Использование PHP в командной строке.
register_long_arrays boolean
Сообщает PHP, следует ли регистрировать устаревшие длинные предопределенные переменные типа $HTTP_*_VARS. Если включена (по умолчанию), то длинные предопределенные переменные PHP, например $HTTP_GET_VARS, будут объявлены. Если вы их не используете, рекомендуем отключить их из соображений производительности. Вместо них следует использовать суперглобальные массивы, например $_GET. Эта директива стала доступна с версии PHP 5.0.0.
Внимание

Данная возможность была помечена УСТАРЕВШЕЙ начиная с версии PHP 5.3.0 и была УДАЛЕНА в версии PHP 5.4.0.

enable_post_data_reading boolean
При отключении этой опции влечет суперглобальные переменные $_POST и $_FILES не будут заполняться. Единственным способом прочесть POST-данные будет чтение обертки потока php://input. Это может оказаться полезным при проксировании запросов или обработки POST-данных способом, более эффективно использующим память.
post_max_size integer
Устанавливает максимально допустимый размер данных, отправляемых методом POST. Это значение также влияет на загрузку файлов. Для загрузки больших файлов это значение должно быть больше значения директивы upload_max_filesize. Если дополнительно используется ограничение памяти, memory_limit также влияет на загрузку файлов. В сущности, memory_limit должна быть больше чем post_max_size. Если используется integer, значение измеряется байтами. Вы также можете использовать сокращенную запись, которая описана в этом разделе FAQ. Если размер POST-данных больше чем post_max_size, суперглобальные переменные $_POST и $_FILES будут пустыми. Это можно отследить различными способами, например передав $_GET переменную в скрипт, обрабатывающий данные, т.е. <form action="edit.php?processed=1">, а затем проверить, установлена ли переменная $_GET['processed'].

Замечание:

PHP разрешает сокращения значений бит, включая K (кило), M (мега) и G (гига). PHP автоматически преобразует все эти сокращения. Будьте осторожны с превышением диапазона 32-битных целых значений (если вы используете 32-битную версию), так как это приведет к ошибке вашего скрипта.

gpc_order string

Устанавливает порядок обработки переменных GET/POST/COOKIE. Значением по умолчанию для этой директивы является "GPC". Установка ее в "GP", к примеру, приведет к тому, что PHP будет полностью игнорировать cookies и перезапишет любую GET-переменную POST-переменной с таким же именем.

Замечание:

Эта опция недоступна в PHP 4. Вместо нее используйте variables_order.

auto_prepend_file string

Определяет имя файла, который будет автоматически обрабатываться перед основным файлом. Файл вызывается так, будто он был подключен при помощи функции require(), так что include_path также используется.

Специальное значение none отключает эту директиву.

auto_append_file string

Определяет имя файла, который будет автоматически обрабатываться после основного файла. Файл вызывается так, будто он был подключен при помощи функции require(), так что include_path тоже используется.

Специальное значение none отключает эту директиву.

Замечание: Если скрипт завершает работу при помощи exit(), auto-append НЕ выполняется.

default_mimetype string

default_charset string

PHP всегда отправляет кодировку по умолчанию в заголовке Content-Type. Чтобы отключить отправку кодировки, просто установите ее пустой строкой.

always_populate_raw_post_data boolean

Всегда заполнять переменную $HTTP_RAW_POST_DATA, содержащую "сырые" POST-данные. В противном случае, переменная будет заполнена только при неопознанном MIME типе данных. Однако, предпочтительным способом доступа к "сырым" POST-данным является php://input. $HTTP_RAW_POST_DATA недоступна при enctype="multipart/form-data".

allow_webdav_methods boolean

Разрешает обработку HTTP-запросов WebDAV при помощи PHP-скриптов (например PROPFIND, PROPPATCH, MOVE, COPY и т.д.). Эта директива не существует начиная с версии PHP 4.3.2. Если вы хотите получить POST-данные этих запросов, вы должны также включить always_populate_raw_post_data.

См. также: magic_quotes_gpc, magic_quotes_runtime и magic_quotes_sybase.

Пути и Директории

Конфигурационные Опции Путей и Директорий
Имя | По умолчанию | Место изменения | Список изменений
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM в PHP < 5.3.0
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
extension | NULL | Только php.ini |
zend_extension | NULL | Только php.ini |
zend_extension_debug | NULL | Только php.ini | Доступна до PHP 5.3.0.
zend_extension_debug_ts | NULL | Только php.ini | Доступна до PHP 5.3.0.
zend_extension_ts | NULL | Только php.ini | Доступна до PHP 5.3.0.
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 5.2.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.3.0. PHP_INI_ALL до версии PHP 5.2.1.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.2.0. PHP_INI_ALL до версии PHP 5.2.1.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | Доступна с версии PHP 4.2.0. PHP_INI_ALL до версии PHP 5.2.1.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Доступна с версии PHP 4.3.0.
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | Доступна с версии PHP 4.3.0. PHP_INI_ALL до версии PHP 5.2.1.
fastcgi.logging | "1" | PHP_INI_SYSTEM | Доступна с версии PHP 4.3.0. PHP_INI_ALL до версии PHP 5.2.1.

Краткое разъяснение конфигурационных директив.

include_path string

Указывает список директорий, в которых функции require(), include(), fopen(), file(), readfile() и file_get_contents() ищут файлы. Формат соответствует формату системной переменной окружения PATH: список директорий, разделенных двоеточием в Unix или точкой с запятой в Windows.

При поиске подключаемых файлов PHP отдельно рассматривает каждое значение в include_path. Он проверяет первый путь, если файл в нем не найден, то он переходит к следующему, и так до тех пор, пока не найдет подключаемый файл, либо вернет предупреждение или ошибку. Вы можете изменить ваш include_path во время выполнения скрипта с помощью функции set_include_path().

Пример #1 include_path в Unix

include_path=".:/php/includes"

Пример #2 include_path в Windows

include_path=".;c:\php\includes"

Использование . в include_path позволяет задавать относительные пути для подключения файлов, так как точка означает текущую директорию. Однако, более эффективно использовать include './file', чем заставлять PHP каждый раз проверять текущую директорию при подключении каждого файла.

open_basedir string

Ограничивает указанным деревом каталогов файлы, которые могут быть открыты с помощью PHP, включая сам файл. Эта директива НЕ подвержена влиянию безопасного режима.

Когда скрипт пытается открыть файл, например, с помощью функции fopen() или gzopen(), проверяется местонахождение файла. Если файл находится вне указанного дерева каталогов, PHP откажется его открывать. Все символические ссылки будут раскрыты, так что с их помощью не удастся обойти это ограничение. Если файл не существует, то символическая ссылка не сможет быть прочитана и имя файла (прочитанное) будет рассматриваться open_basedir .

Специальное значение . обозначает, что рабочая директория скрипта будет использована в качестве базовой директории. Однако, это немного опасно, так как текущая директория скрипта может быть легко изменена с помощью chdir().

В httpd.conf, open_basedir может быть выключена (например, для некоторых виртуальных хостов) тем же способом, что и любая другая конфигурационная директива: "php_admin_value open_basedir none".

В Windows разделяйте директории точкой с запятой. На всех остальных системах, разделяйте директории двоеточием. При работе в качестве модуля Apache, пути open_basedir автоматически наследуются от родительских директорий.

Ограничение, определяемое open_basedir является именем директории начиная с версии PHP 5.2.16 и 5.3.4. Предыдущие версии использовали это значение в качестве префикса. Это означает, что "open_basedir = /dir/incl" также разрешит доступ к "/dir/include" и "/dir/incls", если они существуют. Если вы захотите ограничить доступ только указанной директорией, поставьте в конце слэш. Например: open_basedir = /dir/incl/

По умолчанию все файлы могут быть открыты.

Замечание:

Начиная с версии PHP 5.3.0 значение open_basedir можно сделать более строгим во время выполнения скрипта. Это означает, что если open_basedir была установлена в /www/ в php.ini, то скрипт может ужать конфигурацию до /www/tmp/ во время выполнения с помощью ini_set(). При указании нескольких директорий можно использовать константу PATH_SEPARATOR в качестве разделителя путей, не зависящего от операционной системы.

doc_root string

"Корневая директория" PHP на этом сервере. Используется только в случае, если не пустая. Если PHP сконфигурирован с безопасный режим, файлы вне этой директории не обрабатываются. Если PHP не был скомпилирован с FORCE_REDIRECT, вам следует установить doc_root, если вы используете PHP в качестве CGI под любым веб-сервером (кроме IIS). Альтернативой является использование конфигурационной директивы cgi.force_redirect, речь о которой идет ниже.

user_dir string

Базовое имя директории, используемой в домашнем каталоге пользователя для PHP файлов, например, public_html.

extension_dir string

В какой директории PHP должен искать динамически загружаемые расширения. См. также: enable_dl и dl().

extension string

Какие динамически загружаемые расширения должны быть загружены при старте PHP.

zend_extension string

Абсолютный путь до динамически загружаемого расширения Zend (например, APD), которое должно быть загружено при старте PHP.

zend_extension_debug string

Вариант zend_extension для расширений, скомпилированных с отладочной информацией до PHP 5.3.0.

zend_extension_debug_ts string

Вариант zend_extension для потокобезопасных расширений, скомпилированных с отладочной информацией до PHP 5.3.0.

zend_extension_ts string

Вариант zend_extension для потокобезопасных расширений.

cgi.check_shebang_line boolean

Контролирует, нужно ли проверять первую строку CGI PHP-скрипта на содержание #! (shebang). Эта строка может быть необходима, если скрипт должен поддерживать как отдельный запуск, так и с помощью PHP CGI. PHP в режиме CGI пропускает эту строку и игнорирует ее содержимое, если данная директива включена.

cgi.fix_pathinfo boolean

Обеспечивает поддержку правильных PATH_INFO/PATH_TRANSLATED в CGI. Раньше PHP просто устанавливал PATH_TRANSLATED в SCRIPT_FILENAME и не обращал внимания на PATH_INFO. Для получения дополнительной информации о PATH_INFO, обратитесь к спецификации CGI. Установка этого значения в 1 заставит PHP CGI исправлять свой путь в соответствии со спецификацией. Значение 0 соответствует предыдущему поведению. По умолчанию опция включена. Вы должны исправить свои скрипты так, чтобы они использовали SCRIPT_FILENAME вместо PATH_TRANSLATED.

cgi.force_redirect boolean

Директива cgi.force_redirect необходима для обеспечения безопасности во время работы PHP в качестве CGI под большинством веб-серверов. Если оставить ее неопределенной, по умолчанию PHP включает эту директиву. Вы можете выключить ее на свой страх и риск.

Замечание:

Пользователям Windows: При использовании IIS эта опция должна быть отключена. Тоже самое необходимо для OmniHTTPD и Xitami.

cgi.redirect_status_env string

Если cgi.force_redirect включена и вы работаете не под веб-сервером Apache или Netscape (iPlanet), вам может понадобится установить переменную окружения, которую будет искать PHP чтобы убедиться, что он может продолжать выполнение.

Замечание:

Установка этой переменной может повлечь за собой проблемы с безопасностью, так что вы должны знать, что вы делаете.

cgi.rfc2616_headers int

Сообщает PHP, какой тип заголовков использовать при отправке кода ответа HTTP. Если установлено в 0, PHP отправляет заголовок "Status:", который поддерживается Apache и другими веб-серверами. Если установлено в 1, PHP отправляет заголовок, соответствующий » RFC 2616. Оставьте в значении 0, если вы не уверены в том, что это значит.

fastcgi.impersonate string

FastCGI под IIS (в ОС на базе WINNT) поддерживает возможность имперсонации прав безопасности вызывающего клиента. Это позволяет IIS определить контекст безопасности, в котором выполняется запрос. mod_fastcgi под Apache на текущий момент не поддерживает эту возможность (03/17/2002). Установите в 1 при работе под IIS. Значение по умолчанию - ноль.

fastcgi.logging boolean

Включает логирование SAPI при использовании FastCGI. Логирование включено по умолчанию.

Закачивание Файлов

Конфигурационные Опции Закачивания Файлов
Имя | По умолчанию | Место изменения | Список изменений
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL в PHP <= 4.2.3. Доступна с версии PHP 4.0.3.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR | Доступна с версии PHP 5.3.9.
max_input_vars | 1000 | PHP_INI_PERDIR | Доступна с версии PHP 5.3.9.
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL в PHP <= 4.2.3.
max_file_uploads | 20 | PHP_INI_SYSTEM | Доступна с версии PHP 5.2.12.

Краткое разъяснение конфигурационных директив.

file_uploads boolean или integer

Разрешать или не разрешать закачивание файлов. См. также директивы upload_max_filesize, upload_tmp_dir и post_max_size.

Если используется integer, значение измеряется байтами. Вы также можете использовать сокращенную запись, которая описана в этом разделе FAQ.
upload_tmp_dir string

Временная директория, используемая для хранения файлов во время закачивания. Должна быть доступна для записи пользователю, от имени которого запущен PHP. Если не указана, используется директория по умолчанию для вашей системы.

Если к указанной директории нет прав на запись, PHP откатится обратно к системной временной директории, используемой по умолчанию. Если включена директива open_basedir, то для успешной загрузки файлов системная директория по умолчанию должна быть разрешена.

upload_max_filesize integer

Максимальный размер закачиваемого файла.

Если используется integer, значение измеряется байтами. Вы также можете использовать сокращенную запись, которая описана в этом разделе FAQ.
max_file_uploads integer

Максимально разрешенное количество одновременно закачиваемых файлов. Начиная с PHP 5.3.4, пустые поля загрузки не рассматриваются этим ограничением.

Общий SQL

Конфигурационные Опции Общего SQL
Имя | По умолчанию | Место изменения | Список изменений
sql.safe_mode | "0" | PHP_INI_SYSTEM |

Краткое разъяснение конфигурационных директив.

sql.safe_mode boolean

Если включена, функции соединения с базой данных, использующие значения по умолчанию, будут использовать эти значения вместо передаваемых аргументов. Для значений по умолчанию смотрите документацию по функциям подключения соответствующей базы данных.

Особые настройки для ОС Windows

Особые опции конфигурации для ОС Windows
Имя | По умолчанию | Меняемо | Список изменений
windows_show_crt_warning | "0" | PHP_INI_ALL | Доступна начиная с PHP 5.4.0.

Краткое разъяснение конфигурационных директив.

windows_show_crt_warning boolean

При включении данной директивы будут отображаться предупреждения Windows CRT. Данные предупреждения ранее показывались по умолчанию до версии PHP 5.4.0.

User Contributed Notes

iko at vision dot sk 01-May-2012 08:49
auto_globals_jit setting is also affecting $_REQUEST superglobal in 5.3 It is not explicitly stated in documentation.
kghbln 17-Nov-2011 03:09
Adding multiple directories to open_basedir:

open_basedir = "/var/www/htdocs/:/var/www/tmp/" adds both paths /var/www/htdocs/ and /var/www/tmp/. Do not forget the trailing slash, otherwise the last directory will be considered as a prefix (< 5.3.4).

On Windows you use ; as the seperator.
JL 09-Sep-2011 09:46
If you need to use a path in your include_path that has a space in it - I found that I could make it work (in windows anyway) by setting a path like this
L:\Information Technology\Resources\lib\
in the include path like this listed below

include_path = ".;L:\Information" " Technology\Resources\lib\"
AntonioK 10-Mar-2011 05:29
Note that there is no way to disable eval() work by using disable_functions directive, because eval() is a language construct and not a function.

Many people advise to disable such potentially-insecure functions like system(), exec(), passthru(), eval() and so on in php.ini when not running in safe mode, but eval() would still work even it listed in disable_functions.
rlammers at linuxmail dot org 09-Jan-2011 04:23
This is a possible solution for a problem which seems to be a php-ini-problem but is not.

If a $_POST is used with large fields e.g. textarea's with more than 120kb characters php returns a blank screen, even if the max_post_size is 8M.

This problem may be caused by an apache-module SecFilter.

Adding the following lines to the .htaccess solves the problem.
SecFilterEngine Off
SecFilterScanPOST Off

I know this is not a php-issue, but i'm still posting it here since it looks like it is a php-problem and I did not find any sites or forums offering this solution.
amolitor at molitor-design dot com 10-Feb-2010 03:23
Amusingly, the include_path logically includes the current directory of the running file as the last entry all the time anyways, so part of the business about shoving "." into the include_path is spurious -- it's "there" on the end all the time, at least in the 5.2.12 source (see main/fopen_wrappers.c around line 503).

This one had me goin' for a while.
libkhorse at gmail dot com 06-Aug-2009 12:14
For 'short_open_tag',
though it is marked as PHP_INI_ALL in changable column,
you should  note the CHANGE_LOG column also:

PHP_INI_ALL                in PHP <= 4.0.0.
PHP_INI_PERDIR            in PHP < 5.3.0

So as of 4.0, it will not work if you wanna use
ini_set('short_open_tag') to change it's value on the fly.
mrok at mrok dot com 22-Mar-2009 08:29
Note that on some Unix systems (i.e. PHP 5.1.6 on Centos 5.2) include_path in php.ini should NOT be quoted.

For example, instead of

 include_path='.:/usr/share/php'

use

 include_path=.:/usr/share/php

Using quotes does not cause any error message, but all of your require_once() directives will fail (indicating that file could not be opened) - unless full path to target file is provided.
info at adaniels dot nl 10-Feb-2009 08:12
When display_errors is off, PHP will send an HTTP 500 result header on a fatal error. This is usefull when working with AJAX applications.
the_tevildo at yahoo dot com 19-Nov-2008 08:54
A handy trick to pick up parse errors in test_file.php if you can't set display_errors in php.ini or use .htaccess:

<?php
error_reporting  (E_ALL);
ini_set ('display_errors', true);
include('./test_file.php');
?>
senf_glas at hotmail dot com 09-Apr-2008 04:31
"post_max_size"

"[..]This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. <form action="edit.php?processed=1">, and then checking if $_GET['processed'] is set."

using PHP 4.4.8 it seems that only the $_POST array will be empty in case of the file is largen than post_max_size.
so above mentioned method does not work in my case.
i need to use $_POST['processed'] instead of $_GET['processed']
Jeff 11-Mar-2008 06:17
If you are having trouble getting the auto_prepend_file to work with the command line interface make sure that you have set it in the cli specific php.ini and that the read permission is set correctly for that php.ini file.
gilthans dot NO dot SPAM at gmail dot com 03-Dec-2007 10:52
If you want to display the upload limit without knowing the server configuration, this may be useful:
<?php
function let_to_num($v){ //This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)
    $l = substr($v, -1);
    $ret = substr($v, 0, -1);
    switch(strtoupper($l)){
    case 'P':
        $ret *= 1024;
    case 'T':
        $ret *= 1024;
    case 'G':
        $ret *= 1024;
    case 'M':
        $ret *= 1024;
    case 'K':
        $ret *= 1024;
        break;
    }
    return $ret;
}
$max_upload_size = min(let_to_num(ini_get('post_max_size')), let_to_num(ini_get('upload_max_filesize')));

echo "Maximum upload file size is ".($max_upload_size/(1024*1024))."MB.";
?>
Do note however that this limit is not completely reliable; there are other factors which need to be taken into account, such as any other $_POST data and their size, the memory limit, and the script time limit. This does, however, give some rough limit, and helps you avoid "Doh!" problems where you can't figure out why your file won't upload. :)
stepheneliotdewey at GmailDotCom 26-Jun-2007 04:03
While the manual says that the file specified by auto_prepend_file is included as if it were called by include(), in fact the file is included as if it were called by require().

In other words, if PHP cannot find the file that you specify with auto_prepend_file, it will throw a fatal error.
lanny at freemail dot hu 25-Dec-2006 03:05
register_long_arrays has a very odd behavior (at least in PHP 5.2):

With register_long_arrays=Off the $GLOBALS array will not contain [_SERVER] and [_REQUEST]. They are accessible as superglobals ($_SERVER, $_REQUEST), but they disappear from the $GLOBALS array!
ludicruz at yahoo dot com 19-Dec-2006 10:38
to make sure that all requests use SSL you can use this in a file that is set for auto_prepend_file. This ensures that all requests are SSL

<?php
if(empty($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' )
        header("Location: https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}") and exit();
?>
xangelusx at hotmail dot com 24-Jul-2006 07:28
I wish the documentation was more clear as to whether the arg_separator.output character is automatically encoded when PHP outputs it. In other words, is "&" valid or do I need to specify the encoded character "&amp;"? It would make sense to specify only "&" and hope that it is encoded as needed. That way the value could be read by other functions and encoded only when output to HTML, rather than having to test whether it is already encoded and decode it when necessary (for header redirection for example)
leo at korfu dot cz 29-May-2006 03:45
"If the size of post data is greater than post_max_size..."

It seems that a more elegant way is comparison between post_max_size and $_SERVER['CONTENT_LENGTH']. Please note that the latter includes not only size of uploaded file plus post data but also multipart sequences. Leo
csg at DEL_THISdiatom dot de 02-Sep-2005 02:55
Starting with PHP 4.4.0 (at least PHP version 4.3.10 did have old, documented behaviour) interpretation of value of "session.save_path" did change in conjunction with "save_mode" and "open_basedir" enabled.

Documented ( http://de.php.net/manual/en/ref.session.php#ini.session.save-path ):
  Values of "session.save_path" should or may be  **without**  ending slash.
  For instance:
<?php
  // Valid only  *before* PHP 4.4.0:
  ini_set( "session.save_path", "/var/httpd/kunde/phptmp" );
?> will mean:
  The directory "/var/httpd/kunde/phptmp/" will be used to write data and therefore must be writable by the web server.

Starting with PHP 4.4.0 the server complains that "/var/httpd/kunde/" is not writable.
Solution: Add an ending slash in call of ini_set (or probably whereever you set "session.save_path"), e.g.:
<?php
  // Note the slash on ".....phptmp/":
  ini_set( "session.save_path", "/var/httpd/kunde/phptmp/" );
?>

Hope, that does help someone.
Manu 27-Jul-2005 05:02
Warning, if you change upload_max_filesize, please note that both post_max_size and memory_limit directives may have to change too.
david dot tulloh at infaze dot com dot au 26-Jun-2005 06:19
I did a little experimentation on the behaviour of auto_prepend_file as the order of access wasn't clear to me from the documentation.

1. Apache checks to see if the target file exists.
2. The prepend file is called
3. The target file is called

This means that you can use auto_prepend_file to change the target file before you access it however you can't generate new files.
Joe 09-Jun-2005 01:05
Please be mindful, that if you plan on re-configuring / recompiling to add --enable-memory-limit support, you may need to run a 'make clean' before you run 'make'. Otherwise, you may end up with a phpinfo() that shows up with --enable-memory-limit as a configure parameter, but the memory_get_usage() function will still force a fatal error.
Список разделов php.ini
Список/классификация расширений
Директивы php.ini


Список/классификация расширений

Содержание

  • В алфавитном порядке
  • По составу
  • По состоянию

Это приложение классифицирует по различным критериям более 150 расширений, документированных в руководстве по PHP.

User Contributed Notes

There are no user contributed notes for this page.
Описание встроенных директив php.ini
В алфавитном порядке
Appendices


В алфавитном порядке

  • AMQP
  • Apache
  • APC
  • APD
  • Массивы
  • BBCode
  • BC Math
  • bcompiler
  • Bzip2
  • Cairo
  • Календарь
  • chdb
  • Classkit
  • Классы/Объекты
  • COM
  • Crack
  • Ctype
  • CUBRID
  • cURL
  • Cyrus
  • Дата/Время
  • DBA
  • dBase
  • DB++
  • dbx
  • Direct IO
  • Каталоги
  • DOM
  • DOM XML (PHP 4)
  • .NET
  • Eio
  • Enchant
  • Обработка ошибок
  • Запуск программы
  • Exif
  • Expect
  • FAM
  • FrontBase
  • FDF
  • Fileinfo
  • filePro
  • Функции для работы с файловой системой
  • Filter
  • FriBiDi
  • FTP
  • Управление функциями
  • Gearman
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Gupnp
  • haru
  • Hash
  • htscanner
  • HTTP
  • Hyperwave
  • Hyperwave API
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • ID3
  • Informix
  • IIS
  • GD
  • ImageMagick
  • IMAP
  • inclued
  • PHP Опции/Информация
  • Ingres
  • Inotify
  • intl
  • Java
  • JSON
  • Judy
  • KADM5
  • KTaglib
  • LDAP
  • Libevent
  • libxml
  • LZF
  • Mail
  • Mailparse
  • Math
  • MaxDB
  • Многобайтные строки
  • Mcrypt
  • MCVE
  • Memcache
  • Memcached
  • Memtrack
  • Mhash
  • Mimetype
  • Ming
  • Misc.
  • mnoGoSearch
  • Mongo
  • mqseries
  • Msession
  • mSQL
  • Mssql
  • Mysql
  • mysqli
  • Mysqlnd
  • mysqlnd_ms
  • mysqlnd_qc
  • Ncurses
  • Gopher
  • Network
  • Newt
  • YP/NIS
  • Lotus Notes
  • NSAPI
  • OAuth
  • Object Aggregation
  • OCI8
  • oggvorbis
  • OpenAL
  • OpenSSL
  • Контроль вывода
  • Object overloading
  • Ovrimos SQL
  • Paradox
  • Parsekit
  • PCNTL
  • PCRE
  • PDF
  • PDO
  • 4D (PDO)
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird/Interbase (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • POSIX
  • Принтер
  • Proctitle
  • PS
  • Pspell
  • qtdom
  • Radius
  • Rar
  • Readline
  • Recode
  • Reflection
  • Регулярные выражения POSIX
  • RPM Reader
  • RRD
  • runkit
  • SAM
  • SCA
  • scream
  • SDO
  • SDO DAS XML
  • SDO-DAS-Relational
  • Semaphore
  • Сессии
  • Session PgSQL
  • Управление разделяемой памятью
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Solr
  • Sphinx
  • SPL
  • SPL Types
  • SPPLUS
  • SQLite
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Статистика
  • Stomp
  • Streams
  • Строки
  • SVM
  • SVN
  • SWF
  • Swish
  • Sybase
  • TCP
  • Tidy
  • Tokenizer (Лексер)
  • tokyo_tyrant
  • ODBC
  • URL
  • V8js
  • Функции для работы с переменными
  • vpopmail
  • W32api
  • WDDX
  • Weakref
  • win32ps
  • win32service
  • WinCache
  • xattr
  • xdiff
  • Xhprof
  • XML-анализатор
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • XSLT (PHP 4)
  • Yaml
  • YAZ
  • Zip
  • Zlib

User Contributed Notes

There are no user contributed notes for this page.
Список/классификация расширений
По составу
Список/классификация расширений


По составу

Расширения, входящие в состав ядра

На самом деле это ненастоящие расширения. Они являются частью ядра PHP и не могут быть исключены из бинарного дистрибутива PHP с помощью опций компиляции.

  • Массивы

  • Классы/Объекты

  • Дата/Время

  • Каталоги

  • Обработка ошибок

  • Запуск программы

  • Функции для работы с файловой системой

  • Filter

  • Управление функциями

  • PHP Опции/Информация

  • Mail

  • Math

  • Misc.

  • Network

  • Контроль вывода

  • Reflection

  • Регулярные выражения POSIX

  • Сессии

  • SPL

  • Streams

  • Строки

  • Tokenizer (Лексер)

  • URL

  • Функции для работы с переменными

Поставляемые расширения

Эти расширения поставляются вместе с PHP.

  • Apache

  • BC Math

  • Bzip2

  • Календарь

  • COM

  • Ctype

  • cURL

  • DBA

  • dBase

  • DOM

  • .NET

  • Exif

  • FrontBase

  • FDF

  • FTP

  • Gettext

  • GMP

  • Hash

  • Firebird/InterBase

  • iconv

  • Informix

  • GD

  • IMAP

  • JSON

  • LDAP

  • libxml

  • Многобайтные строки

  • Mcrypt

  • Mhash

  • Mimetype

  • Ming

  • mSQL

  • Mssql

  • Mysql

  • mysqli

  • Mysqlnd

  • Ncurses

  • NSAPI

  • Object Aggregation

  • OCI8

  • OpenSSL

  • PCNTL

  • PCRE

  • PDO

  • 4D (PDO)

  • CUBRID (PDO)

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • MS SQL Server (PDO)

  • PostgreSQL

  • POSIX

  • Pspell

  • Readline

  • Recode

  • Semaphore

  • Управление разделяемой памятью

  • SimpleXML

  • SNMP

  • SOAP

  • Sockets

  • SQLite

  • SQLite3

  • SVN

  • Sybase

  • Tidy

  • ODBC

  • WDDX

  • XML-анализатор

  • XMLReader

  • XML-RPC

  • XMLWriter

  • XSL

  • XSLT (PHP 4)

  • Yaml

  • Zip

  • Zlib

Внешние расширения

Для компиляции этих расширений могут потребоваться внешние библиотеки.

  • BBCode

  • Bzip2

  • chdb

  • Crack

  • cURL

  • dBase

  • DB++

  • dbx

  • DOM

  • DOM XML (PHP 4)

  • Eio

  • Enchant

  • FAM

  • FrontBase

  • FDF

  • Fileinfo

  • FriBiDi

  • GeoIP

  • Gettext

  • GMP

  • haru

  • Hyperwave

  • Hyperwave API

  • Firebird/InterBase

  • IBM DB2

  • Informix

  • ImageMagick

  • IMAP

  • Ingres

  • Java

  • LDAP

  • Libevent

  • libxml

  • MaxDB

  • Mcrypt

  • Memcache

  • Mhash

  • Ming

  • mnoGoSearch

  • Msession

  • mSQL

  • Mssql

  • Mysql

  • mysqli

  • Mysqlnd

  • Ncurses

  • Newt

  • OAuth

  • OCI8

  • oggvorbis

  • OpenAL

  • OpenSSL

  • Ovrimos SQL

  • Paradox

  • PDF

  • 4D (PDO)

  • CUBRID (PDO)

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • MS SQL Server (PDO)

  • PostgreSQL

  • PS

  • Pspell

  • qtdom

  • Radius

  • Rar

  • Readline

  • Recode

  • RRD

  • Session PgSQL

  • SimpleXML

  • SNMP

  • SOAP

  • Sphinx

  • SSH2

  • SWF

  • Swish

  • Sybase

  • Tidy

  • ODBC

  • vpopmail

  • WDDX

  • xattr

  • xdiff

  • XML-анализатор

  • XMLReader

  • XMLWriter

  • XSL

  • XSLT (PHP 4)

  • YAZ

PECL расширения

Эти расширения доступны в » PECL. Существуют и другие PECL расширения, но они пока не документированы в этом руководстве.

  • APC

  • APD

  • BBCode

  • bcompiler

  • chdb

  • Classkit

  • Crack

  • Cyrus

  • DB++

  • dbx

  • Direct IO

  • DOM XML (PHP 4)

  • Eio

  • Enchant

  • Expect

  • FAM

  • Fileinfo

  • filePro

  • FriBiDi

  • GeoIP

  • GnuPG

  • haru

  • Hash

  • htscanner

  • HTTP

  • Hyperwave

  • Hyperwave API

  • IBM DB2

  • ID3

  • IIS

  • ImageMagick

  • inclued

  • Ingres

  • Inotify

  • Java

  • JSON

  • KADM5

  • KTaglib

  • Libevent

  • LZF

  • Mailparse

  • MaxDB

  • MCVE

  • Memcache

  • mnoGoSearch

  • Mongo

  • mqseries

  • Msession

  • mysqlnd_qc

  • Ncurses

  • Gopher

  • Newt

  • YP/NIS

  • Lotus Notes

  • OAuth

  • oggvorbis

  • OpenAL

  • Ovrimos SQL

  • Paradox

  • Parsekit

  • PDF

  • PDO

  • 4D (PDO)

  • CUBRID (PDO)

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • MS SQL Server (PDO)

  • Phar

  • Принтер

  • PS

  • qtdom

  • Radius

  • Rar

  • RPM Reader

  • RRD

  • runkit

  • SAM

  • SCA

  • scream

  • SDO

  • SDO DAS XML

  • SDO-DAS-Relational

  • Session PgSQL

  • Sphinx

  • SPPLUS

  • ssdeep

  • SSH2

  • Статистика

  • SVN

  • SWF

  • Swish

  • TCP

  • vpopmail

  • W32api

  • Weakref

  • win32ps

  • win32service

  • WinCache

  • xattr

  • xdiff

  • Yaml

  • YAZ

  • Zip

User Contributed Notes

There are no user contributed notes for this page.
В алфавитном порядке
По состоянию
Список/классификация расширений


По состоянию

Здесь приводится список расширений, не рекомендованных для промышленного использования - они либо слишком "старые" (устарели), либо слишком "новые" (экспериментальные).

Устаревшие расширения

Эти расширения устарели и в основном заменены другими.

  • Memtrack

  • Mimetype

  • Object overloading

Экспериментальные расширения

Поведение этих расширений - включая названия функций и вся остальная документация, относящаяся к ним - может измениться без уведомления в будущем релизе PHP. Используйте эти расширения на свой страх и риск.

  • bcompiler

  • DB++

  • .NET

  • haru

  • Hash

  • ImageMagick

  • Java

  • Ming

  • Ncurses

  • Newt

  • Lotus Notes

  • Object Aggregation

  • Paradox

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • Oracle (PDO)

  • PS

  • qtdom

  • SCA

  • SDO-DAS-Relational

  • Swish

  • vpopmail

  • W32api

  • XML-RPC

User Contributed Notes

There are no user contributed notes for this page.
По составу
Список псевдонимов функций
Список/классификация расширений


Список псевдонимов функций

В этом списке приведены все псевдонимы. Использование псевдонимов нежелательно, поскольку они могут быть переименованы или признаны устаревшими, что приведет к невозможности портирования скрипта. Этот список может помочь тем пользователям, которые решили привести синтаксис своих прежних скриптов к используемому в настоящий момент синтаксису. В PHP довольно немного функций, доступных сразу по нескольким именам. В некоторых случаях нет предпочитаемого варианта, хорошим примером является is_int() и is_integer(). Однако, есть функции, изменившие свои названия вследствие чистки API или по какой-либо другой причине, а старые имена были оставлены в целях обратной совместимости. Обычно не рекомендуется использовать эти псевдонимы, так как причиной их существования может быть устаревание или смена имени основной функции, что может привести к проблемам портирования скрипта. Данный список предоставляется для помощи при обновлении старых скриптов к новому синтаксису.

Псевдонимы
Псевдоним | Основная функция | Расширение
_ | gettext() | Gettext
add | swfmovie_add() | Ming (flash)
add | swfsprite_add() | Ming (flash)
add_root | domxml_add_root() | DOM XML
addaction | swfbutton_addAction() | Ming (flash)
addcolor | swfdisplayitem_addColor() | Ming (flash)
addentry | swfgradient_addEntry() | Ming (flash)
addfill | swfshape_addfill() | Ming (flash)
addshape | swfbutton_addShape() | Ming (flash)
addstring | swftext_addString() | Ming (flash)
addstring | swftextfield_addString() | Ming (flash)
align | swftextfield_align() | Ming (flash)
attributes | domxml_attributes() | DOM XML
children | domxml_children() | DOM XML
chop | rtrim() | Базовый синтаксис
close | closedir() | Базовый синтаксис
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | Неклассифицированные функции
dir | getdir() | Базовый синтаксис
diskfreespace | disk_free_space() | Файловая система
domxml_getattr | domxml_get_attribute() | DOM XML
domxml_setattr | domxml_set_attribute() | DOM XML
doubleval | floatval() | Базовый синтаксис
drawarc | swfshape_drawarc() | Ming (flash)
drawcircle | swfshape_drawcircle() | Ming (flash)
drawcubic | swfshape_drawcubic() | Ming (flash)
drawcubicto | swfshape_drawcubicto() | Ming (flash)
drawcurve | swfshape_drawcurve() | Ming (flash)
drawcurveto | swfshape_drawcurveto() | Ming (flash)
drawglyph | swfshape_drawglyph() | Ming (flash)
drawline | swfshape_drawline() | Ming (flash)
drawlineto | swfshape_drawlineto() | Ming (flash)
dtd | domxml_intdtd() | DOM XML
dumpmem | domxml_dumpmem() | DOM XML
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | Базовый синтаксис
get_attribute | domxml_get_attribute() | DOM XML
getascent | swffont_getAscent() | Ming (flash)
getascent | swftext_getAscent() | Ming (flash)
getattr | domxml_get_attribute() | DOM XML
getdescent | swffont_getDescent() | Ming (flash)
getdescent | swftext_getDescent() | Ming (flash)
getheight | swfbitmap_getHeight() | Ming (flash)
getleading | swffont_getLeading() | Ming (flash)
getleading | swftext_getLeading() | Ming (flash)
getshape1 | swfmorph_getShape1() | Ming (flash)
getshape2 | swfmorph_getShape2() | Ming (flash)
getwidth | swfbitmap_getWidth() | Ming (flash)
getwidth | swffont_getWidth() | Ming (flash)
getwidth | swftext_getWidth() | Ming (flash)
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | Многобайтовые строки
i18n_discover_encoding | mb_detect_encoding() | Многобайтовые строки
i18n_http_input | mb_http_input() | Многобайтовые строки
i18n_http_output | mb_http_output() | Многобайтовые строки
i18n_internal_encoding | mb_internal_encoding() | Многобайтовые строки
i18n_ja_jp_hantozen | mb_convert_kana() | Многобайтовые строки
i18n_mime_header_decode | mb_decode_mimeheader() | Многобайтовые строки
i18n_mime_header_encode | mb_encode_mimeheader() | Многобайтовые строки
imap_create | imap_createmailbox() | IMAP
imap_fetchtext | imap_body() | IMAP
imap_getmailboxes | imap_list_full() | IMAP
imap_getsubscribed | imap_lsub_full() | IMAP
imap_header | imap_headerinfo() | IMAP
imap_listmailbox | imap_list() | IMAP
imap_listsubscribed | imap_lsub() | IMAP
imap_rename | imap_renamemailbox() | IMAP
imap_scan | imap_listscan() | IMAP
imap_scanmailbox | imap_listscan() | IMAP
ini_alter | ini_set() | Базовый синтаксис
is_double | is_float() | Базовый синтаксис
is_integer | is_int() | Базовый синтаксис
is_long | is_int() | Базовый синтаксис
is_real | is_float() | Базовый синтаксис
is_writeable | is_writable() | Базовый синтаксис
join | implode() | Базовый синтаксис
key_exists | array_key_exists() | Базовый синтаксис
labelframe | swfmovie_labelFrame() | Ming (flash)
labelframe | swfsprite_labelFrame() | Ming (flash)
last_child | domxml_last_child() | DOM XML
lastchild | domxml_last_child() | DOM XML
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | Базовый синтаксис
mbstrcut | mb_strcut() | Многобайтовые строки
mbstrlen | mb_strlen() | Многобайтовые строки
mbstrpos | mb_strpos() | Многобайтовые строки
mbstrrpos | mb_strrpos() | Многобайтовые строки
mbsubstr | mb_substr() | Многобайтовые строки
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash)
ming_setscale | ming_setScale() | Ming (flash)
move | swfdisplayitem_move() | Ming (flash)
movepen | swfshape_movepen() | Ming (flash)
movepento | swfshape_movepento() | Ming (flash)
moveto | swfdisplayitem_moveTo() | Ming (flash)
moveto | swffill_moveTo() | Ming (flash)
moveto | swftext_moveTo() | Ming (flash)
msql | msql_db_query() | mSQL
msql_createdb | msql_create_db() | mSQL
msql_dbname | msql_result() | mSQL
msql_dropdb | msql_drop_db() | mSQL
msql_fieldflags | msql_field_flags() | mSQL
msql_fieldlen | msql_field_len() | mSQL
msql_fieldname | msql_field_name() | mSQL
msql_fieldtable | msql_field_table() | mSQL
msql_fieldtype | msql_field_type() | mSQL
msql_freeresult | msql_free_result() | mSQL
msql_listdbs | msql_list_dbs() | mSQL
msql_listfields | msql_list_fields() | mSQL
msql_listtables | msql_list_tables() | mSQL
msql_numfields | msql_num_fields() | mSQL
msql_numrows | msql_num_rows() | mSQL
msql_regcase | sql_regcase() | mSQL
msql_selectdb | msql_select_db() | mSQL
msql_tablename | msql_result() | mSQL
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_close | sybase_close() | Sybase
mssql_close | sybase_close() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_min_client_severity | sybase_min_client_severity() | Sybase
mssql_min_error_severity | sybase_min_error_severity() | Sybase
mssql_min_message_severity | sybase_min_message_severity() | Sybase
mssql_min_server_severity | sybase_min_server_severity() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_query | sybase_query() | Sybase
mssql_query | sybase_query() | Sybase
mssql_result | sybase_result() | Sybase
mssql_result | sybase_result() | Sybase
mssql_select_db | sybase_select_db() | Sybase
mssql_select_db | sybase_select_db() | Sybase
multcolor | swfdisplayitem_multColor() | Ming (flash)
mysql | mysql_db_query() | MySQL
mysql_createdb | mysql_create_db() | MySQL
mysql_db_name | mysql_result() | MySQL
mysql_dbname | mysql_result() | MySQL
mysql_dropdb | mysql_drop_db() | MySQL
mysql_fieldflags | mysql_field_flags() | MySQL
mysql_fieldlen | mysql_field_len() | MySQL
mysql_fieldname | mysql_field_name() | MySQL
mysql_fieldtable | mysql_field_table() | MySQL
mysql_fieldtype | mysql_field_type() | MySQL
mysql_freeresult | mysql_free_result() | MySQL
mysql_listdbs | mysql_list_dbs() | MySQL
mysql_listfields | mysql_list_fields() | MySQL
mysql_listtables | mysql_list_tables() | MySQL
mysql_numfields | mysql_num_fields() | MySQL
mysql_numrows | mysql_num_rows() | MySQL
mysql_selectdb | mysql_select_db() | MySQL
mysql_tablename | mysql_result() | MySQL
name | domxml_attrname() | DOM XML
new_child | domxml_new_child() | DOM XML
new_xmldoc | domxml_new_xmldoc() | DOM XML
nextframe | swfmovie_nextFrame() | Ming (flash)
nextframe | swfsprite_nextFrame() | Ming (flash)
node | domxml_node() | DOM XML
oci8append | ocicollappend() | OCI8
oci8assign | ocicollassign() | OCI8
oci8assignelem | ocicollassignelem() | OCI8
oci8close | ocicloselob() | OCI8
oci8free | ocifreecoll() | OCI8
oci8free | ocifreedesc() | OCI8
oci8getelem | ocicollgetelem() | OCI8
oci8load | ociloadlob() | OCI8
oci8max | ocicollmax() | OCI8
oci8ocifreecursor | ocifreestatement() | OCI8
oci8save | ocisavelob() | OCI8
oci8savefile | ocisavelobfile() | OCI8
oci8size | ocicollsize() | OCI8
oci8trim | ocicolltrim() | OCI8
oci8writetemporary | ociwritetemporarylob() | OCI8
oci8writetofile | ociwritelobtofile() | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
output | swfmovie_output() | Ming (flash)
parent | domxml_parent() | DOM XML
pdf_add_outline | pdf_add_bookmark() | PDF
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Базовый синтаксис
recode | recode_string() | Recode
remove | swfmovie_remove() | Ming (flash)
remove | swfsprite_remove() | Ming (flash)
rewind | rewinddir() | Базовый синтаксис
root | domxml_root() | DOM XML
rotate | swfdisplayitem_rotate() | Ming (flash)
rotateto | swfdisplayitem_rotateTo() | Ming (flash)
rotateto | swffill_rotateTo() | Ming (flash)
save | swfmovie_save() | Ming (flash)
savetofile | swfmovie_saveToFile() | Ming (flash)
scale | swfdisplayitem_scale() | Ming (flash)
scaleto | swfdisplayitem_scaleTo() | Ming (flash)
scaleto | swffill_scaleTo() | Ming (flash)
set_attribute | domxml_set_attribute() | DOM XML
set_content | domxml_set_content() | DOM XML
setaction | swfbutton_setAction() | Ming (flash)
setattr | domxml_set_attribute() | DOM XML
setbackground | swfmovie_setBackground() | Ming (flash)
setbounds | swftextfield_setBounds() | Ming (flash)
setcolor | swftext_setColor() | Ming (flash)
setcolor | swftextfield_setColor() | Ming (flash)
setdepth | swfdisplayitem_setDepth() | Ming (flash)
setdimension | swfmovie_setDimension() | Ming (flash)
setdown | swfbutton_setDown() | Ming (flash)
setfont | swftext_setFont() | Ming (flash)
setfont | swftextfield_setFont() | Ming (flash)
setframes | swfmovie_setFrames() | Ming (flash)
setframes | swfsprite_setFrames() | Ming (flash)
setheight | swftext_setHeight() | Ming (flash)
setheight | swftextfield_setHeight() | Ming (flash)
sethit | swfbutton_setHit() | Ming (flash)
setindentation | swftextfield_setIndentation() | Ming (flash)
setleftfill | swfshape_setleftfill() | Ming (flash)
setleftmargin | swftextfield_setLeftMargin() | Ming (flash)
setline | swfshape_setline() | Ming (flash)
setlinespacing | swftextfield_setLineSpacing() | Ming (flash)
setmargins | swftextfield_setMargins() | Ming (flash)
setmatrix | swfdisplayitem_setMatrix() | Ming (flash)
setname | swfdisplayitem_setName() | Ming (flash)
setname | swftextfield_setName() | Ming (flash)
setover | swfbutton_setOver() | Ming (flash)
setrate | swfmovie_setRate() | Ming (flash)
setratio | swfdisplayitem_setRatio() | Ming (flash)
setrightfill | swfshape_setrightfill() | Ming (flash)
setrightmargin | swftextfield_setRightMargin() | Ming (flash)
setspacing | swftext_setSpacing() | Ming (flash)
setup | swfbutton_setUp() | Ming (flash)
show_source | highlight_file() | Базовый синтаксис
sizeof | count() | Базовый синтаксис
skewx | swfdisplayitem_skewX() | Ming (flash)
skewxto | swfdisplayitem_skewXTo() | Ming (flash)
skewxto | swffill_skewXTo() | Ming (flash)
skewy | swfdisplayitem_skewY() | Ming (flash)
skewyto | swfdisplayitem_skewYTo() | Ming (flash)
skewyto | swffill_skewYTo() | Ming (flash)
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Базовый синтаксис
streammp3 | swfmovie_streamMp3() | Ming (flash)
swfaction | swfaction_init() | Ming (flash)
swfbitmap | swfbitmap_init() | Ming (flash)
swfbutton | swfbutton_init() | Ming (flash)
swffill | swffill_init() | Ming (flash)
swffont | swffont_init() | Ming (flash)
swfgradient | swfgradient_init() | Ming (flash)
swfmorph | swfmorph_init() | Ming (flash)
swfmovie | swfmovie_init() | Ming (flash)
swfshape | swfshape_init() | Ming (flash)
swfsprite | swfsprite_init() | Ming (flash)
swftext | swftext_init() | Ming (flash)
swftextfield | swftextfield_init() | Ming (flash)
unlink | domxml_unlink_node() | DOM XML
xptr_new_context | xpath_new_context() | DOM XML

User Contributed Notes

There are no user contributed notes for this page.
По состоянию
Список зарезервированных слов
Appendices


Список зарезервированных слов

Содержание

  • Список ключевых слов
  • Предопределенные классы
  • Предопределенные константы

Следующий список - это список зарезервированных идентификаторов в PHP. Никакой идентификатор из этого списка не должен быть использован в качестве идентификатора в любом из ваших скриптов. Этот список включает ключевые слова и предопределенные переменные, константы и имена классов. Этот список не являются исчерпывающим и полным.

User Contributed Notes

SR 04-Oct-2007 10:53
[Editorial note: parent and self are reserved class names. Functions and constants with their names can be declared, but not userspace classes]

true, false and null are not listed because they are globally-defined constants, not reserved words.

No idea about parent or self, though.
londonx at gmail dot com 05-Mar-2007 02:14
Naming a PHP5 class "variant" (with a constructor called the same) and then making an instance of it using __autoload triggers an error which disappears as soon as the name is changed. This should mean that "variant" is also a reserved word.
01-Nov-2006 04:42
Two things:

1. It would be nice for this list to differentiate those reserved words, which are language constructs used *with* parentheses (isset, unset, empty, eval, exit, die, ...) and those rather to be used *without* parentheses (all includes, echo, print, return, ...?)

This would really help define some common coding styles...

2. Do you write NULL, TRUE, FALSE or null, true, false? (I find CAPITAL letters better, however typing them can be annoying so I stick with using all lowercase letters, but what's the standard?)
10-Jan-2006 03:41
I don't see the boolean constants 'true' and 'false' listed among the reserved words/keywords/constants.
Список псевдонимов функций
Список ключевых слов
Appendices


Список ключевых слов

У этих слов есть специальное значение в PHP. Некоторые из них представляют собой вещи, которые выглядят как функции, некоторые похожи на константы и так далее, но они ими не являются в действительности. Они - конструкции языка. Вы не можете использовать следующие слова как константы, имена классов, функции или имена методов. Использование их как имен переменных в общем допускается, однако может привести к путанице.

Зарезервированные слова в PHP
abstract (начиная с PHP 5) | and | array() | as | break
case | catch (начиная с PHP 5) | cfunction (только в PHP 4) | class | clone (начиная с PHP 5)
const | continue | declare | default | do
else | elseif | enddeclare | endfor | endforeach
endif | endswitch | endwhile | extends | final (начиная с PHP 5)
for | foreach | function | global | goto (начиная с PHP 5.3)
if | implements (начиная с PHP 5) | interface (начиная с PHP 5) | instanceof (начиная с PHP 5)
namespace (начиная PHP 5.3) | new | old_function (только в PHP 4) | or | private (начиная с PHP 5)
protected (начиная с PHP 5) | public (начиная с PHP 5) | static | switch | throw (начиная с PHP 5)
try (начиная с PHP 5) | use | var | while | xor
Константы периода трансляции
__CLASS__ | __DIR__ (начиная с PHP 5.3) | __FILE__ | __LINE__ | __FUNCTION__ | __METHOD__
__NAMESPACE__ (начиная с PHP 5.3) |  |  |  |
Конструкции языка
die() | echo() | empty() | exit() | eval()
include() | include_once() | isset() | list() | require()
require_once() | return() | print() | unset() | __halt_compiler()

User Contributed Notes

Bob 06-Sep-2009 02:02
There are some cases when you need to use a reserved keyword or language construct as a class method name. In this instance, there is very little chance of namespace conflicts (as the class itself acts as a namespace). If you try to define the method the old way, you will get an unexpected token error.

There is an unobtrusive, and very useful way to use a reserved keyword for a method name. For example, you want to define two class methods 'list' and 'unset' (these two are language builtins and normally not allowed for method names).

<?php
class MyClass
{
    // Define MyClass::unset() with a different name, e.g. 'rm'
    public function rm($arg)
    {
        /* code... */
    }
    // Define MyClass::list() with a different name, e.g. 'ls'
    public function ls($arg = null)
    {
        /* code... */
    }
    // Now define a __call() method (requires PHP > 5.2.3 to take effect)
    public function __call($func, $args)
    {
        switch ($func)
        {
            case 'list':
                return $this->ls((isset($args[0]))? $args[0]: null);
            break;
            case 'unset':
                return $this->rm($args[0]);
            break;
            default:
                trigger_error("Call to undefined method ".__CLASS__."::$func()", E_USER_ERROR);
            die ();
        }
    }
}
?>

The only caveat is that to use the long method names, you need PHP > 5.2.3. However, a nice feature is that if you are using an older version than 5.2.3, all of the __call() stuff is ignored and the class will behave as expected (in other words, it degrades gracefully).

You also need to be aware of the methods' expected arguments. MyClass::ls()'s argument is optional, so the extra isset() check is required. If your methods take more arguments, they will need to be manually dereferenced from the $args array, e.g. <?php return $this->my_func($args[0], $args[1], $args[2]);?> for 3 required arguments.

This is a nice trick, and can let you code better APIs for newer versions of PHP. However, if this script is to be run on older PHP installations, be very sure to use the short method names.
Список зарезервированных слов
Предопределенные классы
Список зарезервированных слов


Предопределенные классы

В этом разделе перечисляются стандартные предопределенные классы. Разнообразные расширения определяют другие классы, которые описаны в соответствующей справочной информации.

Стандартные определенные классы

Эти классы определены вместе со стандартным набором функций, идущим со сборкой PHP.

Directory
Создается функцией dir().
stdClass
Создается приведением типа к объекту.
__PHP_Incomplete_Class
Возможно создается функцией unserialize().

Предопределенные классы PHP 5

Эти дополнительные предопределенные классы были введены в PHP версии 5.0.0

exception
php_user_filter

Closure

Предопределенный конечный класс Closure был введен в PHP 5.3.0. Он используется для внутренней реализации анонимных функций.

Для более детальной информации смотрите страницу класса.

Специальные классы

Следующие идентификаторы не могут использоваться в качестве имени класса, так как у них есть специальное назначение.

self
Текущий класс.
static
Текущий класс в рабочем цикле.
parent
Родительский класс.

User Contributed Notes

spark at limao dot com dot br 15-Aug-2011 02:21
if you want a Dynamic class you can extend from, add atributes AND methods on the fly you can use this:
<?php
    class Dynamic extends stdClass{
        public function __call($key,$params){
            if(!isset($this->{$key})) throw new Exception("Call to undefined method ".get_class($this)."::".$key."()");
            $subject = $this->{$key};
            call_user_func_array($subject,$params);
        }
    }
?>

this will accept both arrays, strings and Closures:
<?php
    $dynamic->myMethod = "thatFunction";
    $dynamic->hisMethod = array($instance,"aMethod");
    $dynamic->newMethod = array(SomeClass,"staticMethod");
    $dynamic->anotherMethod = function(){
        echo "Hey there";
    };
?>

then call them away =D
Typer85 at gmail dot com 17-Feb-2007 08:58
In response to the note below mine,

This list is not incomplete. Read the Manual folks, its listed there plain and simple:

"This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference."

Depending on what extensions you have, they might define their own classes. This list is just the standard classes as defined by PHP with no regards to extensions.
Simon Kissane 14-Sep-2004 12:54
The above list is incomplete. For example, on my PHP 5.0 configuration (yours may differ depending on the extensions you choose to install), the following classes are predefined:

== "Core" ==
stdClass
Exception
__PHP_Incomplete_Class
php_user_filter
Directory

== Reflection API ==
ReflectionException
Reflection
ReflectionFunction
ReflectionParameter
ReflectionMethod
ReflectionClass
ReflectionObject
ReflectionProperty
ReflectionExtension

== SQLLite ==
SQLiteDatabase
SQLiteResult
SQLiteUnbuffered
SQLiteException

== Standard PHP Lib. ==
RecursiveIteratorIterator
FilterIterator
ParentIterator
LimitIterator
CachingIterator
CachingRecursiveIterator
ArrayObject
ArrayIterator
DirectoryIterator
RecursiveDirectoryIterator

== SimpleXML ==
SimpleXMLElement
SimpleXMLIterator

== DOM/XSL/XPath extensions ==
DOMException
DOMStringList
DOMNameList
DOMImplementationList
DOMImplementationSource
DOMImplementation
DOMNode
DOMNameSpaceNode
DOMDocumentFragment
DOMDocument
DOMNodeList
DOMNamedNodeMap
DOMCharacterData
DOMAttr
DOMElement
DOMText
DOMComment
DOMTypeinfo
DOMUserDataHandler
DOMDomError
DOMErrorHandler
DOMLocator
DOMConfiguration
DOMCdataSection
DOMDocumentType
DOMNotation
DOMEntity
DOMEntityReference
DOMProcessingInstruction
DOMStringExtend
DOMXPath
XSLTProcessor
unknown 23-Jul-2002 10:29
It's handy to have a array of the reserved classes.....
var_dump (get_declared_classes ());
Список ключевых слов
Предопределенные константы
Список зарезервированных слов


Предопределенные константы

Объявленные в ядре константы

Нижеописанные константы объявляются ядром PHP и охватывают PHP, Zend engine и SAPI-модули.

PHP_VERSION (string)
Текущая версия PHP в виде строки в формате "major.minor.release[extra]".
PHP_MAJOR_VERSION (integer)
Текущая "основная" (major) версия PHP в виде целого числа (например, int(5) для версии "5.2.7-extra"). Доступна начиная с версии PHP 5.2.7.
PHP_MINOR_VERSION (integer)
Текущая "промежуточная" версия PHP в виде целого числа (например, int(2) для версии "5.2.7-extra"). Доступна начиная с версии PHP 5.2.7.
PHP_RELEASE_VERSION (integer)
Текущая "релиз"-версия (release) PHP в виде целого числа (например, int(7) для версии "5.2.7-extra"). Доступна начиная с версии PHP 5.2.7.
PHP_VERSION_ID (integer)
Текущая версия PHP в виде целого числа, ее удобно использовать при сравнениях версиий (например, int(50207) для версии "5.2.7-extra"). Доступна начиная с версии PHP 5.2.7.
PHP_EXTRA_VERSION (string)
Текущая "экстра"-версия PHP в виде строки (например, '-extra' для версии "5.2.7-extra"). Обычно используется в различных дистрибутивах для индикации версий пакетов. Доступна начиная с версии PHP 5.2.7.
PHP_ZTS (integer)
Доступна начиная с версии PHP 5.2.7.
PHP_DEBUG (integer)
Доступна начиная с версии PHP 5.2.7.
PHP_MAXPATHLEN (integer)
Максимальная длина файловых имен (включая путь), поддерживаемая данной сборкой PHP. Доступна начиная с версии PHP 5.3.0.
PHP_OS (string)
PHP_SAPI (string)
Серверное API данной сборки PHP. Доступна начиная с версии PHP 4.2.0. Смотрите также php_sapi_name().
PHP_EOL (string)
Корректный символ конца строки, используемый на данной платформе. Доступна начиная с версии PHP 4.3.10 и PHP 5.0.2
PHP_INT_MAX (integer)
Максимальное целое число, поддерживаемое данной сборкой PHP. Обычно это int(2147483647). Доступно начиная с версии PHP 4.4.0 и PHP 5.0.5
PHP_INT_SIZE (integer)
Доступна начиная с версии PHP 4.4.0 и PHP 5.0.5
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
PHP_PREFIX (string)
Значение опции "--prefix", указанной при запуске configure. Доступна начиная с версии PHP 4.3.0
PHP_BINDIR (string)
Указывает путь установки бинарных файлов.
PHP_BINARY (string)
Указывает путь к исполняемым файлам PHP во время выполнения скрипта. Доступна с PHP 5.4.
PHP_MANDIR (string)
Указывает путь установки страниц документации man. Доступна, начиная с версии PHP 5.3.7.
PHP_LIBDIR (string)
PHP_DATADIR (string)
PHP_SYSCONFDIR (string)
PHP_LOCALSTATEDIR (string)
PHP_CONFIG_FILE_PATH (string)
PHP_CONFIG_FILE_SCAN_DIR (string)
PHP_SHLIB_SUFFIX (string)
Суффикс, используемый для динамически линкуемых библиотек, такой как "so" (характерный для большинства Unix-систем) или "dll" (Windows). Доступен начиная с версии PHP 4.3.0
PHP_OUTPUT_HANDLER_START (integer)
PHP_OUTPUT_HANDLER_CONT (integer)
PHP_OUTPUT_HANDLER_END (integer)
E_ERROR (integer)
Константа, указывающая уровень сообщений об ошибках
E_WARNING (integer)
E_PARSE (integer)
E_NOTICE (integer)
E_CORE_ERROR (integer)
E_CORE_WARNING (integer)
E_COMPILE_ERROR (integer)
E_COMPILE_WARNING (integer)
E_USER_ERROR (integer)
E_USER_WARNING (integer)
E_USER_NOTICE (integer)
E_DEPRECATED (integer)
Доступна начиная с версии PHP 5.3.0
E_USER_DEPRECATED (integer)
Доступна начиная с версии PHP 5.3.0
E_ALL (integer)
E_STRICT (integer)
Доступна начиная с версии PHP 5.0.0
__COMPILER_HALT_OFFSET__ (integer)
Доступна начиная с версии PHP 5.1.0
TRUE (boolean)
Смотрите раздел Булев тип.
FALSE (boolean)
Смотрите раздел Булев тип.
NULL (boolean)
Смотрите Null.

Смотрите также: Магические константы.

Стандартные предопределенные константы

Все константы, входящие в состав ядра расширений, теперь определены в PHP по умолчанию.

User Contributed Notes

soywiz at gmail dot com 19-Jan-2009 03:32
Another way to determine PHP_INT_MIN:

<?php
define('PHP_INT_MIN', ~PHP_INT_MAX);
?>

It should work always:

MAX for 8bit-signed: 01111111
MIN for 8bit-signed: 10000000

In 32 bits:
php -r"echo (int)base_convert(str_repeat('1', 31), 2, 10) - PHP_INT_MAX;"
0
<?php echo ~(int)base_convert(str_repeat('1', 31), 2, 10); ?>
-2147483648
isonomia 08-May-2008 05:18
As PHP_INT_MAX is only available since PHP 4.4.0 and PHP 5.0.5 here is a function that should enable sensible values on most machines (16,32 & 64bit):-

<?php
function get_int_max()
{
    $max=0x7fff;
    $probe = 0x7fffffff;
    while ($max == ($probe>>16))
    {
        $max = $probe;
        $probe = ($probe << 16) + 0xffff;
    }
    return $max;
}

if (!defined('PHP_INT_MAX'))
{
    define ('PHP_INT_MAX', get_int_max());
}
define ('PHP_INT_MIN', (int)(PHP_INT_MAX+1));
?>
monky at kymp dot net 12-Jan-2008 11:55
You can get minimum integer size by adding 1 to PHP_INT_MAX. Just remember to use casting.

<?php

echo (int)(PHP_INT_MAX+1);

?>
Tea Bore 28-Sep-2005 12:09
Use get_defined_constants() to retrieve these constants.

<?php

print '<pre>';
print_r(get_defined_constants());
print '</pre>';

?>
Предопределенные классы
List of Resource Types
Список зарезервированных слов


List of Resource Types

The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.

Resource Types
Resource Type Name | Created By | Used By | Destroyed By | Definition
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | None | Aspell dictionary
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | None | COM object reference
VARIANT
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | PDF document with CPDF lib
cpdf outline
cubrid connection | cubrid_connect() cubrid_connect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() | cubrid_close() cubrid_disconnect() | Connection to CUBRID database
persistent cubrid connection | cubrid_pconnect() cubrid_pconnect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() | Persistent connection to CUBRID database
cubrid request | cubrid_prepare() cubrid_execute() cubrid_query() cubrid_unbuffered_query() | cubrid_bind() cubrid_column_names() cubrid_column_types() cubrid_current_oid() cubrid_execute() cubrid_free_result() cubrid_get_query_timeout() cubrid_move_cursor() cubrid_next_result() cubrid_num_cols() cubrid_num_rows() cubrid_set_query_timeout() cubrid_data_seek() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_field() cubrid_fetch_lengths() cubrid_fetch_object() cubrid_fetch_row() cubrid_field_flags() cubrid_field_len() cubrid_field_name() cubrid_field_seek() cubrid_field_table() cubrid_field_type() cubrid_num_fields() cubrid_result() | cubrid_close_prepare() cubrid_close_request() | CUBRID request
cubrid lob | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close()
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | Curl session
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection
dbx_result_object | dbx_query() | None | dbx result
domxml attribute
domxml document
domxml node
xpath context
xpath object
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() | fbsql_close() | Link to fbsql database
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File
ftp | ftp_connect(), ftp_ssl_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site(), ftp_alloc(), ftp_chmod(), ftp_exec(), ftp_get_option(), ftp_nb_continue(), ftp_nb_fget(), ftp_nb_fput(), ftp_nb_get(), ftp_nb_put(), ftp_raw(), ftp_set_option() | ftp_close() | FTP stream
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | GD Image
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD
gd PS encoding
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server
imap chain persistent
imap persistent
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction
java
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result
ldap result entry
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server
SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFGradient
SWFMorph
SWFMovie
SWFShape
SWFSprite
SWFText
SWFTextField
mnogosearch agent
mnogosearch result
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL
msql query | msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_flags(), msql_field_len(), msql_field_name(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsoft SQL Server database
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsoft SQL Server
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsoft SQL Server result
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result
oci8 collection
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database
oci8 descriptor
oci8 server
oci8 session
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result
birdstep link
birdstep result
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file
pdf object
pdf outline
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result
pgsql string
printer
printer brush
printer font
printer pen
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close()
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket
sockets i/o vector
stream | opendir() | readdir(), rewinddir() | closedir() | Dir handle
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library
sybase-db result | sybase_query(), sybase_unbuffered_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), 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_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file

User Contributed Notes

csaba at alum dot mit dot edu 06-Nov-2009 10:25
On my PHP 5.2 under Windows Vista, the resource type listed as interbase link is actually Firebird/InterBase link
Nathan Anderson 26-Feb-2003 04:17
Like the LDAP functions, the MS-SQL functions mssql_connect() and mssql_pconnect() do not return resources, they return "A positive MS SQL link identifier on success, or FALSE  on error."
ian at eiloart dot comNOSPAM 08-Aug-2001 03:02
Actually, the ldap functions don't return or expect to be passed resources at all. So you can use an integer, and is_resource and get_resource_type aren't any use with ldap.
Предопределенные константы
Список доступных фильтров
Appendices


Список доступных фильтров

Содержание

  • Строковые фильтры
  • Преобразовывающие фильтры
  • Компрессионные фильтры
  • Шифрующие фильтры

Следующий список перечисляет несколько встроенных фильтров для использования с stream_filter_append(). Ваша версия PHP может включать больше (или меньше) фильтров, чем перечислено здесь.

Следует акцентировать внимание на определенной асимметричности функций stream_filter_append() и stream_filter_prepend(). Каждый поток в PHP имеет небольшой буфер чтения, в котором он хранит блоки данных, полученные из файловой системы или другого ресурса, для того чтобы обрабатывать данные наиболее эффективным образом. Как только данные переносятся из ресурса во внутренний буфер потока, они сразу же обрабатываются закрепленными за потоком фильтрами, независимо от того, готово ли приложение PHP принимать данные или нет. Если данные находятся в буфере чтения в момент, когда в фильтр что-то дописывают в конец, данные будут немедленно обработаны этим фильтром, таким образом их нахождение в буфере будет прозрачным. В то же время, если данные находятся в буфере в момент, когда в фильтр что-то дописывают в начало, данные НЕ будут обработаны этим фильтром. Вместо этого, они будут ждать момента, когда следующий блок данных будет получен из ресурса.

Для получения списка фильтров, установленных в вашу версию PHP, используйте функцию stream_get_filters().

User Contributed Notes

There are no user contributed notes for this page.
List of Resource Types
Строковые фильтры
Appendices


Строковые фильтры

Все эти фильтры служат для того самого, что подразумевают их имена в соответствии с поведением встроенных в PHP функций для работы со строками. Для получения дополнительной информации о конкретном фильтре, обратитесь к странице руководства соответствующей функции.

string.rot13 (с версии PHP 4.3.0) Использование этого фильтра эквивалентно обработке всех данных потока функцией str_rot13().

Пример #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Выведет:  Guvf vf n grfg.   */
?>

string.toupper (с версии PHP 5.0.0) Использование этого фильтра эквивалентно обработке всех данных потока функцией strtoupper().

Пример #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Выведет:  THIS IS A TEST.   */
?>

string.tolower (с версии PHP 5.0.0) Использование этого фильтра эквивалентно обработке всех данных потока функцией strtolower().

Пример #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Выведет:  this is a test.   */
?>

string.strip_tags (с версии PHP 5.0.0) Использование этого фильтра эквивалентно обработке всех данных потока функцией strip_tags(). Он принимает аргументы в одной из двух форм: Либо в виде строки со списком тегов, как и второй аргумент функции strip_tags(), либо массив названий тегов.

Пример #4 string.strip_tags

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Выведет:  <b>bolded text</b> enlarged to a level 1 heading   */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Выведет:  <b>bolded text</b> enlarged to a level 1 heading   */
?>

User Contributed Notes

There are no user contributed notes for this page.
Список доступных фильтров
Преобразовывающие фильтры
Список доступных фильтров


Преобразовывающие фильтры

Как и фильтры string.*, фильтры convert.* совершают действия, соответствующие их именам. Преобразовывающие фильтры были добавлены в PHP 5.0.0. Для получения дополнительной информации о конкретном фильтре, обратитесь к странице руководства соответствующей функции.

convert.base64-encode и convert.base64-decode Использование этих фильтров эквивалентно обработке всех данных потока функциями base64_encode() и base64_decode() соответственно. convert.base64-encode поддерживает аргументы, переданные в виде ассоциативного массива. Если указан аргумент line-length, результат base64 будет разделен на куски длинной line-length символов каждый. Если указан аргумент line-break-chars, каждый кусок будет разделен указанными символами. Эти параметры дают такой же эффект, как и использование base64_encode() в паре с chunk_split().

Пример #1 convert.base64-encode и convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Выведет:  VGhpcyBpcyBhIHRlc3QuCg==  */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Выведет:  VGhpcyBp
          :  cyBhIHRl
          :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Выведет:  This is a test.  */
?>

convert.quoted-printable-encode и convert.quoted-printable-decode Использование decode-версии этого фильтра эквивалентно обработке всех данных потока функцией quoted_printable_decode(). У фильтра convert.quoted-printable-encode нет эквивалентной функции. convert.quoted-printable-encode поддерживает аргументы, переданные в виде ассоциативного массива. В дополнение к аргументам, поддерживаемыми convert.base64-encode, convert.quoted-printable-encode также поддерживает boolean-аргументы binary и force-encode-first. convert.base64-decode поддерживает лишь аргумент line-break-chars в качестве подсказки для чистки закодированных данных.

Пример #2 convert.quoted-printable-encode & convert.quoted-printable-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Выведет:  =This is a test.=0A  */
?>

User Contributed Notes

There are no user contributed notes for this page.
Строковые фильтры
Компрессионные фильтры
Список доступных фильтров


Компрессионные фильтры

В то время, как Компрессионные обертки обеспечивают способ создания gzip- и bz2-совместимых файлов в локальной файловой системе, они не предоставляют общих средств для компрессии в сетевых потоках, как и не предоставляют средств для создания потока без компрессии с последующим превращением в компрессируемый. Для этих целей к любым потоковым ресурсам в любое время могут применяться компрессионные фильтры.

Замечание: Компрессионные фильтры не генерируют заголовков и окончаний, которые используют утилиты командной строки, такие как gzip. Они просто компрессируют (сжимают) и декомпрессируют (разжимают) порции данных в компрессируемом потоке данных.

zlib.deflate (компрессия) и zlib.inflate (декомпрессия) являются реализациями компрессионных методов, описаных в » RFC 1951. Фильтр deflate принимает три аргумента, переданных в виде ассоциативного массива. level определяет, какой уровень компрессии использовать (1-9). Повышение этого значения приведет к уменьшению объемов данных за счет увеличения времени обработки. Существуют также два специальных уровня компрессии: 0 (для отключения компрессии) и -1 (внутреннее значение по умолчанию библиотеки zlib -- на текущий момент равно 6). window - это логарифм с основанием 2 от размера окна диапазона сжатия. Высокие значения (вплоть до 15 -- 32768 байт) приводят к улучшению компрессии за счет роста необходимой памяти, в то время как низкие значения (вплоть до 9 -- 512 байт) приводят к ухудшению компрессии за счет уменьшения необходимой памяти. Значением аргумента window по умолчанию на текущий момент является 15. memory определяет масштаб резервируемой памяти. Допустимые значения находятся в диапазоне от 1 (минимальное резервирование) до 9 (максимальное резервирование). Такое резервирование памяти влияет только на скорость и не влияет на размер генерируемых данных.

Замечание: Так как уровень компрессии является наиболее часто используемым аргументом, вы можете передать только его в качестве обычного целого числа (integer), вместо того чтобы передавать массив из одного элемента.

Компрессионные фильтры zlib.* доступны с версии PHP 5.1.0, если включена поддержка zlib. Они так же доступны в качестве обратного порта для версий 5.0.x путем установки пакета » zlib_filter из » PECL. Эти фильтры не доступны в PHP 4.

Пример #1 zlib.deflate и zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "Оригинальный текст длиной " . strlen($original_text) . " символов.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "Сжатый файл размером " . filesize('test.deflated') . " байт.\n";
echo "Оригинальный текст:\n";
/* Использование readfile и zlib.inflate для декомпресии на лету */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Генерирует вывод:

Оригинальный текст длиной 70 символов.
Сжатый файл размером 56 байт.
Оригинальный текст:
This is a test.
This is only a test.
This is not an important string.

 */
?>

Пример #2 Упрощенное использование zlib.deflate

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "Оригинальный текст длиной " . strlen($original_text) . " символов.\n";

$fp = fopen('test.deflated', 'w');
/* Здесь "6" указывает уровень компрессии 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "Сжатый файл размером " . filesize('test.deflated') . " байт.\n";

/* Генерирует вывод:

Оригинальный текст длиной 70 символов.
Сжатый файл размером 56 байт.

 */
?>

bzip2.compress и bzip2.decompress работают точно так же, как и фильтры zlib, описанные выше. Фильтр bzip2.compress принимает два аргумента в виде элементов ассоциативного массива: blocks является целочисленным (integer) значением в диапазоне от 1 до 9 и указывает на количество 100-килобайтовых блоков памяти для резервирования в качестве рабочего пространства. work - это так же целочисленное (integer) значение в диапазоне от 0 до 250, определяющее сколько усилий нужно потратить на обычный метод компрессии перед переключением на медленный, но более надежный метод. Изменение этого параметра влияет только на скорость компрессии. Ни размер сжатого результата, ни используемый объем памяти не изменяются при помощи этой настройки. Значение 0 указывает библиотеке bzip использовать собственное внутреннее значение по умолчанию. Фильтр bzip2.decompress принимает всего один аргумент, который может быть передан либо как обычное boolean-значение, либо как элемент small ассоциативного массива. Когда small установлен в TRUE, библиотека bzip совершит декомпрессию с минимальным расходом памяти за счет понижения скорости.

Компрессионные фильтры bzip2.* доступны с версии PHP 5.1.0, если включена поддержка bz2. Они так же доступны в качестве обратного порта для версий 5.0.x путем установки пакета » bz2_filter из » PECL. Эти фильтры не доступны в PHP 4.

Пример #3 bzip2.compress и bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "Оригинальный файл размером " . filesize('LICENSE') . " байт.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "Сжатый файл размером " . filesize('LICENSE.compressed') . " байт.\n";

/* Генерирует вывод:

Оригинальный файл размером 3288 байт.
Сжатый файл размером 1488 байт.

 */
?>

User Contributed Notes

There are no user contributed notes for this page.
Преобразовывающие фильтры
Шифрующие фильтры
Список доступных фильтров


Шифрующие фильтры

mcrypt.* и mdecrypt.* обеспечивают симметричное шифрование и дешифрование при помощи libmcrypt. Оба набора фильтров поддерживают те же алгоритмы, что и расширение mcrypt в виде mcrypt.ciphername, где ciphername - это название шифра, как если бы оно передавалось функции mcrypt_module_open(). Также доступны следующие пять параметров:

Параметры фильтра mcrypt
Параметр | Обязателен? | По умолчанию | Пример значения
mode | Нет | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Нет | ini_get('mcrypt.algorithms_dir') | Путь к модулям алгоритмов
modes_dir | Нет | ini_get('mcrypt.modes_dir') | Путь к модулям режимов
iv | Да | N/A | Обычно 8, 16 или 32 байта бинарных данных. Зависит от шифра
key | Да | N/A | Обычно 8, 16 или 32 байта бинарных данных. Зависит от шифра

Пример #1 Шифрование вывода в файл используя 3DES

<?php
$passphrase = 'My secret';

/* Включает читаемую секретную фразу
 * в воспроизводимую пару iv/key
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secret-file.enc', 'wb');
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'Secret secret secret data');
fclose($fp);
?>

Пример #2 Чтение зашифрованного файла

<?php
$passphrase = 'My secret';

/* Включает читаемую секретную фразу
 * в воспроизводимую пару iv/key
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secret-file.enc', 'rb');
stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);
$data = rtrim(stream_get_contents($fp));
fclose($fp);

echo $data;
?>

User Contributed Notes

There are no user contributed notes for this page.
Компрессионные фильтры
Список поддерживаемых транспортных протоколов
Список доступных фильтров


Список поддерживаемых транспортных протоколов

Содержание

  • Интернет-сокеты: TCP, UDP, SSL, and TLS
  • Unix-сокеты: UNIX и UDG

Нижеследующий список содержит информацию о протоколах передачи, встроенных в PHP и готовых для использования функциями работы с сокетами, такими как fsockopen() и stream_socket_client(). Эти протоколы не применяются в расширениях для работы с Сокетами.

Для получения списка поддерживаемых протоколов передачи, встроенных в вашу версию PHP, используйте функцию stream_get_transports().

User Contributed Notes

There are no user contributed notes for this page.
Шифрующие фильтры
Интернет-сокеты: TCP, UDP, SSL, and TLS
Appendices


Интернет-сокеты: TCP, UDP, SSL, and TLS

PHP 4, PHP 5. ssl:// & tls:// начиная с версии PHP 4.3.0 sslv2:// & sslv3:// начиная с версии PHP 5.0.2

Замечание: Если транспортный протокол не указан, будет использован tcp://.

  • 127.0.0.1
  • fe80::1
  • www.example.com
  • tcp://127.0.0.1
  • tcp://fe80::1
  • tcp://www.example.com
  • udp://www.example.com
  • ssl://www.example.com
  • sslv2://www.example.com
  • sslv3://www.example.com
  • tls://www.example.com

Интернет-сокеты требуют указания порта в дополнение к адресу. В случае fsockopen(), порт передаётся вторым параметром и не затрагивает строку адреса. При работе с stream_socket_client() и другими близкими функциями, как и в случае со стандартными URL, порт указывается в конце адреса, отделённый двоеточием.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Замечание: IPv6 численные адреса с указанием порта
Во втором примере выше, в то время как IPv4 и имя хоста не изменились, за исключением добавления номера порта после двоеточия, адрес IPv6 заключён в квадратные скобки: [fe80::1]. Это сделано для того, чтобы отличить двоеточие в адресе от двоеточия при указании порта.

Протоколы ssl:// and tls:// (доступные только если поддержка openssl включена в PHP) являются расширениями tcp://, дополняющими его SSL-шифрованием. Начиная с PHP 4.3.0, для работы с ssl-протоколами, PHP должен быть статически собран с поддержкой OpenSSL, а с версии PHP 5.0.0 он также может быть представлен и как модуль.

ssl:// будет пытаться использовать соединения SSL V2 или SSL V3 в зависимости от возможностей и настроек удаленного хоста. sslv2:// и sslv3:// позволяют особо указать использование SSL V2 или SSL V3.

User Contributed Notes

stefan at example dot com 20-Aug-2010 05:42
Actually, PHP is very able to start with an unencrypted connection and then switch to an encrypted one - refer to http://php.net/stream_socket_enable_crypto .
pablo dot livardo at gmail dot com 09-Dec-2009 09:56
I've been having a problem with a TLS connection.

<?php
$fp = fsockopen("tls://mail.example.com", 587, $errno, $errstr);
?>

Which gives me an error of:

SSL operation failed with code 1. OpenSSL Error messages: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

I believe this is caused by PHP not being able to start with an unencrypted connection and then switch to encryption even though the functionality is built into OpenSSL.

For Google Mail users you can avoid this by using port 465 instead of 587.
Список поддерживаемых транспортных протоколов
Unix-сокеты: UNIX и UDG
Список поддерживаемых транспортных протоколов


Unix-сокеты: UNIX и UDG

unix:// и udg:// (udg:// начиная с PHP 5)

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// даёт возможность использовать unix-сокеты, а udg:// предоставляет альтернативный способ передачи данных в них, с использованием пользовательского протокола датаграмм.

Unix-сокеты, в отличие от Интернет-сокетов не требуют указания порта. В случае fsockopen() параметр portno должен быть равен 0.

User Contributed Notes

Matthew Fortune 16-Feb-2007 03:03
It appears that fsockopen prior to php5 did not need the unix:// qualifier when opening a unix domain socket:

php4: fsockopen("/tmp/mysocket"......);

php5: fsockopen("unix:///tmp/mysocket"......);

This caught me out when upgrading.
Интернет-сокеты: TCP, UDP, SSL, and TLS
Таблица сравнения типов в PHP
Список поддерживаемых транспортных протоколов


Таблица сравнения типов в PHP

Следующие таблицы демонстрируют работу PHP с типами переменных и операторами сравнения, как в случае свободного, так и в случае строгого сравнения. Также эта информация относится к разделу документации по приведению типов. Вдохновением на создание этого раздела мы обязаны различным комментариям пользователей и работе над » BlueShoes.

До осмотра таблиц, важно знать и понимать типы переменных и их значения. К примеру, "42" - string, в то время как 42 - integer. FALSE - boolean, а "false" - string.

Замечание:

HTML-формы не передают целые, дробные числа или булевые переменные: они всегда передают строки. Для проверки является ли строка числом, используйте функцию is_numeric().

Замечание:

Использование if ($x), если $x не определена, сгенерирует ошибку уровня E_NOTICE. Вместо этого используйте функцию empty() или isset() и/или инициализируйте переменную.

Замечание:

Некоторые арифметические операции могут вернуть значение, представленное константой NAN (Not A Number, не-число). Любое строгое или нестрогое сравнение этого значения с каким-либо другим, включая его самого, вернет FALSE (т.е. NAN != NAN и NAN !== NAN). Примерами операций, возвращающих NAN, являются sqrt(-1), asin(2) и asinh(0).

Сравнение типов $x и результатов функций PHP, связанных с типами
Выражение | gettype() | empty() | is_null() | isset() | boolean : if($x)
$x = ""; | string | TRUE | FALSE | TRUE | FALSE
$x = null | NULL | TRUE | TRUE | FALSE | FALSE
var $x; | NULL | TRUE | TRUE | FALSE | FALSE
$x неопределена | NULL | TRUE | TRUE | FALSE | FALSE
$x = array(); | array | TRUE | FALSE | TRUE | FALSE
$x = false; | boolean | TRUE | FALSE | TRUE | FALSE
$x = true; | boolean | FALSE | FALSE | TRUE | TRUE
$x = 1; | integer | FALSE | FALSE | TRUE | TRUE
$x = 42; | integer | FALSE | FALSE | TRUE | TRUE
$x = 0; | integer | TRUE | FALSE | TRUE | FALSE
$x = -1; | integer | FALSE | FALSE | TRUE | TRUE
$x = "1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "0"; | string | TRUE | FALSE | TRUE | FALSE
$x = "-1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "php"; | string | FALSE | FALSE | TRUE | TRUE
$x = "true"; | string | FALSE | FALSE | TRUE | TRUE
$x = "false"; | string | FALSE | FALSE | TRUE | TRUE

Гибкое сравнение с помощью ==
 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE
FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE
1 | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE
-1 | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
"1" | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | TRUE
array() | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | FALSE
"php" | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE

Жесткое сравнение с помощью ===
 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
1 | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
-1 | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"1" | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE
array() | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE
"php" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE

User Contributed Notes

php at richardneill dot org 12-Apr-2012 07:45
Be wary of string-comparison where both strings might be interpreted as numbers.  Eg:

$x="123456789012345678901234567890"; $y="123456789012345678900000000000";
echo  ($x==$y)?"equal":"not_equal";   #Prints equal !!

Both strings are getting converted to floats, then losing precision, then becoming equal :-(

Using "===" or making either of the strings non-numeric will prevent this.
[This is on a 32-bit machine, on a 64-bit, you will have to make the strings longer to see the effect]
Jouriy LYSENKO 17-Jun-2011 02:18
If $var not declared.

In php 5.2 :
<?php if($var) ?> - work

in php 5.3 :
<?php if($var) ?> - dont work and generate error E_NOTICE
mauritsdajong at gmail dot com 18-Feb-2011 07:12
When we're doing loose comparisons (with double equals signs), the following fact is interesting.

false == array() evaluates to true
false == "" evaluates to true
array() == "" however, evaluates to false
php at benizi dot com 15-Feb-2010 10:31
It's interesting to note that 'empty()' and 'boolean : if($x)'
are paired as logical opposites, as are 'is_null()' and 'isset()'.
edgar at goodforall dot eu 15-Dec-2009 06:55
Some function to write out your own comparisson table in tsv format. Can be easily modified to add more testcases and/or binary functions. It will test all comparables against each other with all functions.

<?php
$funcs = array(
        /* Testing equality */
        'eq' => '==',
        'ne' => '!=',
        'gt' => '>',
        'lt' => '<',
        'ne2' => '<>',
        'lte' => '<=',
        'gte' => '>=',
        /* Testing identity */
        'id' => '===',
        'nid' => '!=='
);
class Test {
        protected $a;
        public $b;
        public function __construct($a,$b){
                $this->a = $a;
                $this->b = $b;
        }
        public function getab(){
                return $this->a.",". $this->b;
        }

}
$tst1 = new Test(1,2);
$tst2 = new Test(1,2);
$tst3 = new Test(2,2);
$tst4 = new Test(1,1);

$arr1 = array(1,2,3);
$arr2 = array(2,3,4);
$arr3 = array('a','b','c','d');
$arr4 = array('a','b','c');
$arr5 = array();

$comp1 = array(
        'ints' => array(-1,0,1,2),
        'floats' => array(-1.1,0.0,1.1,2.0),
        'string' => array('str', 'str1', '', '1'),
        'bools' => array(true, false),
        'null' => array(null),
        'objects' => array($tst1,$tst2,$tst3,$tst4),
        'arrays' => array($arr1, $arr2, $arr3, $arr4, $arr5)
);
$fbody = array();

foreach($funcs as $name => $op){
        $fbody[$name] = create_function('$a,$b', 'return $a ' . $op . ' $b;');
}

$table = array(array('function', 'comp1', 'comp2', 'f comp1 comp2', 'type'));
/* Do comparisons */
$comp2  = array();
foreach($comp1 as $type => $val){
        $comp2[$type] = $val;
}

foreach($comp1 as $key1 => $val1){
        foreach($comp2 as $key2 => $val2){
                addTableEntry($key1, $key2, $val1, $val2);
        }
}
$out = '';
foreach($table as $row){
        $out .= sprintf("%-20s\t%-20s\t%-20s\t%-20s\t%-20s\n", $row[0], $row[1], $row[2], $row[3], $row[4]);
}

print $out;
exit;

function addTableEntry($n1, $n2, $comp1, $comp2){
        global $table, $fbody;
        foreach($fbody as $fname => $func){
                        foreach($comp1 as $val1){
  foreach($comp2 as $val2){
                                        $val = $func($val1,$val2);
                                                $table[] = array($fname, gettype($val1) . ' => ' . sprintval($val1), gettype($val2) .' => ' . sprintval($val2), gettype($val) . ' => ' . sprintval($val), gettype($val1) . "-" . gettype($val2) . '-' . $fname);
                                        }
                        }
        }
}

function sprintval($val){
        if(is_object($val)){
                return 'object-' . $val->getab();
        }
        if(is_array($val)){
                return implode(',', $val);
        }
        if(is_bool($val)){
                if($val){
                        return 'true';
                }
                return 'false';
        }
        return strval($val);
}

?>
rich 08-May-2008 07:20
The note about object comparison should be corrected. Cloning objects does not imply instances are the same, so === would return FALSE.

Compare object
<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //false
?>
gernovich at ya dot ru 08-May-2008 12:48
Universal comparison test.

<?php

$tests = array();
$tests['==']  = create_function('$a, $b', 'return $a==$b;');
$tests['==='] = create_function('$a, $b', 'return $a===$b;');
$tests['!='] = create_function('$a, $b', 'return $a!=$b;');
$tests['<>'] = create_function('$a, $b', 'return $a<>$b;');
$tests['!=='] = create_function('$a, $b', 'return $a!==$b;');
$tests['<']   = create_function('$a, $b', 'return $a<$b;');
$tests['>']   = create_function('$a, $b', 'return $a>$b;');
$tests['<=']  = create_function('$a, $b', 'return $a<=$b;');
$tests['>=']  = create_function('$a, $b', 'return $a>=$b;');

$comparison = array();
$comparison['TRUE'] = true;
$comparison['FALSE'] = false;
$comparison['1'] = 1;
$comparison['0'] = 0;
$comparison['-1'] = -1;
$comparison['3,14'] = pi();
$comparison['"1"'] = '1';
$comparison['"0"'] = '0';
$comparison['"-1"'] = '-1';
$comparison['NULL'] = null;
$comparison['array()'] = array();
$comparison['"php"'] = 'php';

print '<h1>PHP version '.PHP_VERSION.' type comparison tables</h1>';

foreach ($tests as $test=>$function) {
    print "<h2>Comparisons with $test</h2>";
    print "<table border='1'>";
    print "<tr>";
    print "<th>&nbsp;</th>";
    foreach (array_keys($comparison) as $name) {
        print "<th>$name</th>";
    }
    print "</tr>";
    foreach ($comparison as $arg_1_name => $arg_1_value) {
        print '<tr>';
        print "<th>$arg_1_name</th>";
        foreach ($comparison as $arg_2_value) {
            print '<td>';
            print $function($arg_1_value, $arg_2_value)==true ?
                        '<span style="color:#00F;">TRUE</span>' : '<span style="color:#F00;">FALSE</span>';
            print '</td>';
        }
        print "</tr>";
    }
    print "</table>";
}

?>
info at shaelf dot ru 06-Jan-2008 01:51
Compare object
<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //true
?>
frank 14-Aug-2007 03:06
A comparison table for <=,<,=>,> would be nice...
Following are TRUE (tested PHP4&5):
NULL <= -1
NULL <= 0
NULL <= 1
!(NULL >= -1)
NULL >= 0
!(NULL >= 1)
That was a surprise for me (and it is not like SQL, I would like to have the option to have SQL semantics with NULL...).
15-Mar-2007 02:06
Re: omit's comment

The note omit quotes is referring to the VALUE returned, not its name. If you put 42 into a text field, the corresponding array value will be the string "42". The note makes no comment on the array's keys.
omit 23-Aug-2006 11:32
the manual said "HTML Forms do not pass integers, floats, or booleans; they pass strings"

while this is true, php will sometimes change the type to either type array, or possibly type integer(no, not a numeric string) if it was used as an array key. php seems to do this when it parses the request data into the predefined variable arrays.

example:

<input type="text" name="foo[5]">
<input type="text" name="foo[7]">

now obviously the browser will send those names as a string. but php will change thier type.

<?php

// $_POST['foo'] is an array
var_dump($_POST['foo']);

foreach ($_POST['foo'] as $key => $val) {
    // the keys 5 and 7 will be type integer
    var_dump($key);
}

?>

because of this, its also a good idea to check the types of your variables.
Jan 29-Dec-2005 11:23
Note that php comparison is not transitive:

"php" == 0 => true
0 == null => true
null == "php" => false
jerryschwartz at comfortable dot com 26-Jul-2005 01:04
In some languages, a boolean is promoted to an integer (with a value of 1 or -1, typically) if used in an expression with an integer. I found that PHP has it both ways:

If you add a boolean with a value of true to an integer with a value of 3, the result will be 4 (because the boolean is cast as an integer).

On the other hand, if you test a boolean with a value of true for equality with an integer with a value of three, the result will be true (because the integer is cast as a boolean).

Surprisingly, at first glance, if you use either < or > as the comparison operator the result is always false (again, because the integer as cast as a boolean, and true is neither greater nor less than true).
tom 17-Jun-2005 02:27
<?php
if (strlen($_POST['var']) > 0) {
    // form value is ok
}
?>

When working with HTML forms this a good way to:

(A) let "0" post values through like select or radio values that correspond to array keys or checkbox booleans that would return FALSE with empty(), and;
(B) screen out $x = "" values, that would return TRUE with isset()!

Because HTML forms post values as strings, this is a good way to test variables!

[[Editor Note: This will create a PHP Error of level E_NOTICE if the checked variable (in this case $_POST['var']) is undefined. It may be used after (in conjuection with) isset() to prevent this.]]
aidan at php dot net 24-Jan-2005 07:00
The way PHP handles comparisons when multiple types are concerned is quite confusing.

For example:
"php" == 0

This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.
Unix-сокеты: UNIX и UDG
Список меток (tokens) парсера
Appendices


Список меток (tokens) парсера

Различные части PHP внутренне представлены типами вроде T_SR. PHP выводит идентификаторы вроде этого в ошибках парсинга, например: "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."

Предполагается, что вы знаете что означает T_SR. Для всех, кто этого не знает ниже есть таблица этих идентификаторов с синтаксисом и ссылками на соответствующие разделы документации.

Замечание: Использование T_* констант

Все метки приведенные ниже также являются PHP-константами. Их значение автоматически генерируется на основе базовой инфраструктуры анализатора РНР. Это означает, что конкретное значение метки может изменяться между двумя версиями PHP. Например, константа T_FILE имеет значение 365 в PHP 5.3, в то время как это же значение относится к T_TRAIT в PHP 5.4, а значение константы T_FILE равно 369. Это означает, что для обеспечения совместивости в различных версиях PHP ваш код никогда не должен зависеть напрямую от значений T_* констант из какой-либо определенной версии PHP. Вместо этого ваш код должен использовать собственные значения (использовать длинные числа типа 10000) и соответствующую стратегию, которая будет работать со всеми версиями PHP и значениями T_* констант.

Метки
Метка | Синтаксис | Ссылка
T_ABSTRACT | abstract | Абстрактные классы (начиная с PHP 5.0.0)
T_AND_EQUAL | &= | операторы присваивания
T_ARRAY | array() | array(), синтаксис массива
T_ARRAY_CAST | (array) | приведение типа
T_AS | as | foreach
T_BAD_CHARACTER |  | все что ниже ASCII 32 исключая \t (0x09), \n (0x0a) и \r (0x0d)
T_BOOLEAN_AND | && | логические операторы
T_BOOLEAN_OR | || | логические операторы
T_BOOL_CAST | (bool) or (boolean) | приведение типа
T_BREAK | break | break
T_CASE | case | switch
T_CATCH | catch | Исключения (начиная с PHP 5.0.0)
T_CHARACTER |  | больше не используется
T_CLASS | class | классы и объекты
T_CLASS_C | __CLASS__ | магические константы (начиная с PHP 4.3.0)
T_CLONE | clone | классы и объекты (начиная с PHP 5.0.0)
T_CLOSE_TAG | ?> or %> | PHP-код внутри HTML
T_COMMENT | // или #, и /* */ в PHP 5 | комментарии
T_CONCAT_EQUAL | .= | операторы присваивания
T_CONST | const | константы класса
T_CONSTANT_ENCAPSED_STRING | "foo" или 'bar' | строковой синтаксис
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | переменные внутри строки
T_DEC | -- | операторы инкремента\декремента
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | магические константы (начиная с PHP 5.3.0)
T_DIV_EQUAL | /= | операторы присваивания
T_DNUMBER | 0.12, и т.д. | числа с плавающей точкой
T_DOC_COMMENT | /** */ | PHPDoc-комментарии (начиная с PHP 5.0.0)
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | переменная внутри строки
T_DOUBLE_ARROW | => | синтаксис массивов
T_DOUBLE_CAST | (real), (double) или (float) | приведение типов
T_DOUBLE_COLON | :: | см. ниже T_PAAMAYIM_NEKUDOTAYIM
T_ECHO | echo | echo()
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | константная часть строки с переменными
T_ENDDECLARE | enddeclare | declare, альтернативный синтаксис
T_ENDFOR | endfor | for, альтернативный синтаксис
T_ENDFOREACH | endforeach | foreach, альтернативный синтаксис
T_ENDIF | endif | if, альтернативный синтаксис
T_ENDSWITCH | endswitch | switch, альтернативный синтаксис
T_ENDWHILE | endwhile | while, альтернативный синтаксис
T_END_HEREDOC |  | синтаксис heredoc
T_EVAL | eval() | eval()
T_EXIT | exit or die | exit(), die()
T_EXTENDS | extends | extends, классы и объекты
T_FILE | __FILE__ | магические константы
T_FINAL | final | Ключевое слово "final" (доступно с PHP 5.0.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function or cfunction | функции
T_FUNC_C | __FUNCTION__ | магические константы (начиная с PHP 4.3.0)
T_GLOBAL | global | область видимости переменной
T_GOTO | goto | (доступно с PHP 5.3.0)
T_HALT_COMPILER | __halt_compiler() | __halt_compiler (доступно с PHP 5.1.0)
T_IF | if | if
T_IMPLEMENTS | implements | Интерфейсы объектов (доступно с PHP 5.0.0)
T_INC | ++ | операторы инкремента\декремента
T_INCLUDE | include() | include()
T_INCLUDE_ONCE | include_once() | include_once()
T_INLINE_HTML |  | текст вне PHP
T_INSTANCEOF | instanceof | операторы типа (начиная с PHP 5.0.0)
T_INT_CAST | (int) или (integer) | приведение типов
T_INTERFACE | interface | Интерфейсы объектов (начиная с PHP 5.0.0)
T_ISSET | isset() | isset()
T_IS_EQUAL | == | операторы сравнения
T_IS_GREATER_OR_EQUAL | >= | операторы сравнения
T_IS_IDENTICAL | === | операторы сравнения
T_IS_NOT_EQUAL | != or <> | операторы сравнения
T_IS_NOT_IDENTICAL | !== | операторы сравнения
T_IS_SMALLER_OR_EQUAL | <= | операторы сравнения
T_LINE | __LINE__ | магические константы
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, и т.д. | целые числа
T_LOGICAL_AND | and | логические операторы
T_LOGICAL_OR | or | логические операторы
T_LOGICAL_XOR | xor | логические операторы
T_METHOD_C | __METHOD__ | магические константы (начиная с PHP 5.0.0)
T_MINUS_EQUAL | -= | операторы присваивания
T_ML_COMMENT | /* и */ | комментарии (только PHP 4)
T_MOD_EQUAL | %= | операторы присваивания
T_MUL_EQUAL | *= | операторы присваивания
T_NAMESPACE | namespace | пространства имен (начиная с PHP 5.3.0)
T_NS_C | __NAMESPACE__ | пространства имен (начиная с PHP 5.3.0)
T_NS_SEPARATOR | \ | пространства имен (начиная с PHP 5.3.0)
T_NEW | new | классы и объекты
T_NUM_STRING | "$a[0]" | цифровой индекс массива внутри строки
T_OBJECT_CAST | (object) | приведение типов
T_OBJECT_OPERATOR | -> | классы и объекты
T_OLD_FUNCTION | old_function | (только в PHP 4)
T_OPEN_TAG | <?php, <? или <% | PHP-код внутри HTML
T_OPEN_TAG_WITH_ECHO | <?= or <%= | PHP-код внутри HTML
T_OR_EQUAL | |= | операторы присваивания
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Также определяется как T_DOUBLE_COLON.
T_PLUS_EQUAL | += | операторы присваивания
T_PRINT | print() | print()
T_PRIVATE | private | классы и объекты (начиная с PHP 5.0.0)
T_PUBLIC | public | классы и объекты (начиная с PHP 5.0.0)
T_PROTECTED | protected | классы и объекты (начиная с PHP 5.0.0)
T_REQUIRE | require() | require()
T_REQUIRE_ONCE | require_once() | require_once()
T_RETURN | return | возвращаемые значения
T_SL | << | побитовые операторы
T_SL_EQUAL | <<= | операторы присваивания
T_SR | >> | побитовые операторы
T_SR_EQUAL | >>= | операторы присваивания
T_START_HEREDOC | <<< | синтаксис heredoc
T_STATIC | static | область видимости переменной
T_STRING | "parent" | идентификаторы, например строки, объектно-ориентированные ключевые слова вроде parent и self, функции, классы и некоторые другие.
T_STRING_CAST | (string) | приведение типов
T_STRING_VARNAME | "${a | переменные внутри строки
T_SWITCH | switch | switch
T_THROW | throw | Исключения (начиная с PHP 5.0.0)
T_TRY | try | Исключения (начиная с PHP 5.0.0)
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | приведение типов (начиная с PHP 5.0.0)
T_USE | use | пространства имен (начиная с PHP 5.3.0; зарезервировано с PHP 4.0.0)
T_VAR | var | классы и объекты
T_VARIABLE | $foo | переменные
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | операторы присваивания

Смотрите также token_name().

User Contributed Notes

fgm at osinet dot fr 22-Sep-2008 01:08
T_ENCAPSED_AND_WHITESPACED is returned when parsing strings with evaluated content, like "some $value" or this example from the Strings reference page:

<?php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

This last example is tokenized as:
T_ECHO
  echo
T_WHITESPACE
  %20 (a space character)
T_START_HEREDOC
  <<
T_ENCAPSED_AND_WHITESPACE
  My name is "
T_VARIABLE
  $name
T_ENCAPSED_AND_WHITESPACE
  ". I am printing some
T_VARIABLE
  $foo
T_OBJECT_OPERATOR
  ->
T_STRING
  foo
T_ENCAPSED_AND_WHITESPACE
  . Now, I am printing some
T_CURLY_OPEN
  {
T_VARIABLE
  $foo
T_OBJECT_OPERATOR
  ->
T_STRING
  bar
(terminal)
  [
T_LNUMBER
  1
(terminal)
  ]
(terminal)
  }
T_ENCAPSED_AND_WHITESPACE
  . This should print a capital 'A': \x41
T_END_HEREDOC
  EOT
(terminal)
  ;
nathan at unfinitydesign dot com 22-Sep-2008 05:52
T_ENCAPSED_AND_WHITESPACE is whitespace which intersects a group of tokens. For example, an "unexpected T_ENCAPSED_AND_WHITESPACE" error is produced by the following code:

<?php
$main_output_world = 'snakes!'
echo('There are' 10 $main_output_world);
?>

Note the missing concatenation operator between the two strings leads to the whitespace error that is so named above. The concatenation operator instructs PHP to ignore the whitespace between the two code tokens (the so named "encapsed" data"), rather than parse it as a token itself.

The correct code would be:

<?php
$main_output_world = 'snakes!'
echo('There are' . 10 . $main_output_world);
?>

Note the addition of the concatenation operator between each token.
o_O Tync 03-Aug-2008 08:21
Some tokens are not documented, so here they are:
all of them are located within non-constant ""-strings:

T_CHARACTER - \r\n\t... . They're presented AS IS and NOT replaced with actual characters

T_ENCAPSED_AND_WHITESPACE - whitespace

T_DOLLAR_OPEN_CURLY_BRACES - ${ (ONLY in non-constant ""-strings)

T_STRING - strings (example: "$a aa")

T_NUM_STRING - numbers (exaple: "$a 0")

still have no idea what T_ENCAPSED_AND_WHITESPACE means... :(
Таблица сравнения типов в PHP
Руководство по именованию
Appendices


Руководство по именованию

Содержание

  • Глобальное пространство имён
  • Правила
  • Советы

Этот документ содержит советы по выбору имён для идентификаторов PHP-кода. При выборе имён для кода, создающего идентификаторы в глобальном пространстве имён, важно принимать во внимание это руководство, чтобы избежать коллизий имён из будущих версий PHP с вашим кодом.

User Contributed Notes

clancy hood at gmail dot com 11-Apr-2009 10:15
The specified permitted characters in variable names (including the first character) are somewhat more permissive than you might expect.

The specified regex is [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* (from ./functions.user-defined.php)

On running the following you can see those outside of [a-zA-Z0-9_] that work. Your browser/shell may not display all properly, and some editors (I tested in Textmate) may simply remove things it doesn't grok as whitespace.  However, there are some pretty sexy characters in there should you be looking for a unique namespace which is not too lengthy.  Using them can be inconvenient for others who may not have a suitable keyboard for single-stroke entry (mine is Spanish). Best used for a program's internally relevant methods - which are those we wish least to pollute a namespace.

<?php

    header('Content-type:text/plain; charset=utf-8');

    function unichr($u) {
        return mb_convert_encoding('&#'.intval($u).';', 'UTF-8', 'HTML-ENTITIES');
    }

    for($i = hexdec("7f"); $i <= hexdec("ff"); $i++) echo unichr($i)."\n";

    // simple example

    function ñ(){
        echo "I'm ok!";
    }

    ñ();

?>
Список меток (tokens) парсера
Глобальное пространство имён
Appendices


Глобальное пространство имён

Обзор конструкций, создающих идентификаторы в глобальном пространстве имён.

  • функции

  • классы

  • интерфейсы

  • константы (не константы классов)

  • переменные, объявленные вне функций/методов

User Contributed Notes

There are no user contributed notes for this page.
Руководство по именованию
Правила
Руководство по именованию


Правила

Следующий список правил дает обзор прав именования, которые проект PHP оставляет себе при выборе новых идентификаторов. Полным руководством является официальный "» Стандарт написания кода":

  • PHP владеет глобальным пространством имён, но старается находить описательные имена и избегать очевидных коллизий.

  • Имена функций используют подчёркивания между словами, а имена классов используют как camelCase, так и PascalCase.

  • PHP добавляет префикс к глобальным именам, принадлежащим расширению с именем этого расширения. (В прошлом было множество исключений из этого правила.) Например:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (пример исключения, допущенного в прошлом)

    • new SplFileObject()

  • Тем не менее, итераторы и исключения просто получают постфиксы "Iterator" и "Exception." Примеры:

    • ArrayIterator

    • LogicException

  • PHP резервирует все идентификаторы, начинающиеся с __ как "магические". Рекомендуется не создавать идентификаторов, начинающихся с __, кроме как с целью использовать документированную "магическую" функциональность. Примеры:

    • __get()

    • __autoload()

User Contributed Notes

Jon at kexsof dot com 22-Oct-2007 05:08
Angst relief for Drupal apprentices:
remember that the prefix (and suffix) for PHP magical symbols
is two (2) underscores.  The Drupal coding standard is one underscore
for some types of programmer-created identifiers.
Глобальное пространство имён
Советы
Руководство по именованию


Советы

Для написания кода, защищённого от коллизий, в будущем рекомендуется добавлять префикс или суффикс ко всем именам в глобальном пространстве имён. Рекомендуется использовать 3-4буквенный префикс, отделенный подчёркиванием. Также для избежания коллизий между разными проектами рекомендуется разузнать о существующих префиксах (или суффиксах) и, соответственно, распространить информацию о выбранном вами варианте. Примеры:

  • MyPx_someFunc()

  • Foo_Date

  • $asdf_dbh

User Contributed Notes

There are no user contributed notes for this page.
Правила
Об этом руководстве
Руководство по именованию


Об этом руководстве

Содержание

  • Форматы
  • О заметках пользователей
  • Как читать определения функции (прототип)
  • Версии PHP, документированные в этом руководстве
  • Как узнать больше о PHP
  • Как помочь в написании документации
  • Как создаются форматы документации
  • Переводы

User Contributed Notes

DaveRandom 16-Mar-2012 10:26
Since searching for _ (an underscore) in the function list ends up here, and _() is a valid alias for gettext() you may be looking for this page if you've ended up here:

http://php.net/manual/en/function.gettext.php
kulakov74 at yandex dot ru 21-Aug-2007 08:38
I improved the script php_manual_prefs.js provided with the extended chm-version to better hilight user comments and code samples as I found those in the original version too dull (gray). Note that this all cannot be done using stylesheets only as the code samples in the chm-docs do not have any distinct classes etc and can only be parsed with a script. What I added to the original script follows. The timeouts are used because the page is not loaded right at once so we have to wait for complete loading. The colors (aColorMap) can be customized. This also improves navigation links positioning in short pages, so instead of directly following contents they are now bottom-aligned. This fix needs some extra styles so they follow the code, along with some general styles.

setTimeout("AddStyles(); window.focus();", 50);

//-----------

var D, TimerId, oNav, oPage;

function AddStyles(){
D=document; ChangeExamples(); ChangeNotes();
}

function ChangeExamples(){
var aDivs, DivNo, oDiv, aSpans, SpanNo, oSpan, aColorMap, Color, aCodes;

aColorMap=[];
aColorMap['#007700']='yellow';
aColorMap['#0000bb']='white';
aColorMap['#dd0000']='yellow';
aColorMap['#ff8000']='Aqua';
//aColorMap['']='';

//Scan examples
aDivs=D.getElementsByTagName('DIV');
for(DivNo=0; DivNo<aDivs.length; DivNo++){
    oDiv=aDivs[DivNo];
    if (oDiv.className!='examplecode') continue;
    //Change colors
    oDiv.style.backgroundColor='black';
    oDiv.style.backgroundImage='none';
    //oDiv.style.color='white';

    aSpans=oDiv.getElementsByTagName('SPAN');
    for(SpanNo=0; SpanNo<aSpans.length; SpanNo++){
        oSpan=aSpans[SpanNo];
        Color=oSpan.style.color;
        oSpan.style.color=aColorMap[Color];
        if (Color=='#dd0000') oSpan.style.backgroundColor='DarkRed';
        oSpan.style.fontFamily='Lucida Console';
        }
    aCodes=oDiv.getElementsByTagName('CODE');
    for(SpanNo=0; SpanNo<aCodes.length; SpanNo++){
        oSpan=aCodes[SpanNo];
        oSpan.style.color='yellow';
        oSpan.style.fontFamily='Lucida Console';
        }
    }
}

function ChangeNotes(){
var oNotes, oDiv, aDivs, DivNo, oP, aPs;

oNotes=D.getElementById('pageNotes');
if (!oNotes){
    setTimeout('ChangeNotes();', 100); return;
    }
aDivs=oNotes.getElementsByTagName('DIV');
for(DivNo=0; DivNo<aDivs.length; DivNo++){
    oDiv=aDivs[DivNo];
    aPs=oDiv.getElementsByTagName('P');
    oP=aPs[0];
    oP.style.backgroundColor='DarkGreen';
    oP.style.color='yellow';
    oP.style.marginBottom='0px';
    oP=aPs[1];
    oP.style.backgroundColor='LightYellow';
    oP.firstChild.style.fontFamily='Lucida Console';
    //oP.firstChild.style.fontSize='12px';
    oP.style.border='1px solid DarkGreen';
    oP.style.borderTopWidth='0px';
    }

//return;
oNav=D.getElementById('pageNav');
oPage=D.getElementById('pageContent');
AlignNav(); window.onresize=AlignNav;
}

function AlignNav(){
var Pos, NavBottom, Diff;

Pos=AbsPos(oNav);
NavBottom=Pos[1]+oNav.offsetHeight;
Diff=oPage.offsetHeight-NavBottom;
if (Diff!=0) oNav.style.top=(Diff+oNav.style.posTop)+'px';
}

function AbsPos(O, Parent){
var X=0, Y=0, Next;

Next=O; if (Parent==null) Parent=D;
while (Next!=null && Next!==Parent){
    Y+=Next.offsetTop; X+=Next.offsetLeft; Next=Next.offsetParent;
    }
return [X, Y];
}

//----------
This is to be added in style.css:

Body{
    font-family: Verdana;
    font-size: 80%;
    height: 100%;
}

P{
    text-align:justify;
}

#pageContent{
    height: 100%;
}

#pageNav {
    position:relative;
}

.literal{
    background-color: LightCyan;
}

TR.question TD{
    background:LightYellow;
}

TR.answer TD{
    background:#F0FFF0;
}
Советы
Форматы
Appendices


Форматы

Руководство по PHP доступно в нескольких форматах. Эти форматы могут быть разделены на две группы: формат для чтения онлайн и форматы, доступные для загрузки.

Замечание:

Некоторые издательства выпустили печатные версии этого руководства. Однако, мы не рекомендуем пользоваться ими вследствие их быстрого устаревания.

Вы можете пользоваться руководством онлайн » на сайте PHP.net, а также на многочисленных сайтах-зеркалах. Чтобы обеспечить наиболее высокую скорость загрузки, вам нужно выбрать ближайший к вам сайт-зеркало. В данный момент онлайн версия PHP руководства имеет два отдельных стиля CSS - для просмотра онлайн (веб) и предназначенный для печати.

Преимуществом онлайн руководства над большинством оффлайн форматов является интеграция с замечаниями пользователей и » быстрыми ссылками, очень удобными для быстрого доступа к желаемой части руководства. Очевидным недостатком является то, что вам нужно находиться в онлайне, чтобы пользоваться руководством в онлайн форматах.

Существуют несколько форматов для использования в оффлайн, и вы можете выбрать формат, наиболее подходящий для использования в вашей операционной системе и отвечающий вашим читательским предпочтениям. Чтобы узнать больше о том, каким образом создается такое количество форматов руководства, обратитесь к разделу 'Как мы создаем форматы руководства'.

Наиболее кроссплатформенным форматом этого руководства является HTML-версия. Она доступна как в виде одного HTML-файла, так и в виде архива, содержащего несколько тысяч файлов, каждый из которых является отдельной главой руководства. Мы предоставляем эти версии руководств сжатыми, поэтому вам понадобится утилита разархивирования для доступа к файлам внутри архива.

На платформах Windows доступна версия руководства в формате Windows HTML Help, который может быть просмотрен с помощью приложения Windows HTML Help. Эта версия предусматривает поиск по тексту руководства, содержание и поддержку использования закладок. Многие среды разработки PHP-программ в Windows также используют эту версию из-за легкости доступа. Существуют также программы для просмотра CHM под Linux. Смотрите » xCHM или » GnoCHM.

Есть также » расширенная версия CHM, она обновляется менее часто, но зато обеспечивает множество дополнительных возможностей. К сожалению, из-за используемых технологий создания этого формата, она работает только на Microsoft Windows.

User Contributed Notes

There are no user contributed notes for this page.
Об этом руководстве
О заметках пользователей
Об этом руководстве


О заметках пользователей

Заметки пользователей играют большую роль в процессе создания этого руководства. Позволяя читателям высылать нам примеры, выявленные опечатки и другие сведения с помощью их браузеров, мы имеем возможность интегрировать эти замечания в основной текст руководства. Пока замечания пользователей не были добавлены в руководство, с ними можно ознакомиться онлайн и в некоторых оффлайн форматах.

Замечание:

Заметки пользователей не подвергаются модерации перед тем, как стать публично доступными, таким образом, качество написания примеров кода и даже их корректность не может быть гарантирована. (Так же, как не может быть гарантировано качество и точность собственно текста руководства).

Замечание:

По лицензионному соглашению заметки пользователей рассматриваются как часть самого руководства по PHP, поэтому к ним применима та же лицензия, что и к самому руководству (на данный момент Creative Commons Attribution). Подробности могут быть найдены на странице Авторские права данного руководства.

User Contributed Notes

There are no user contributed notes for this page.
Форматы
Как читать определения функции (прототип)
Об этом руководстве


Как читать определения функции (прототип)

Документация к каждой функции в руководстве была написана с учетом быстрого обращения к этой документации. Зная как правильно читать и понимать текст, вам будет намного проще изучать PHP. Вместо того, чтобы полагаться на примеры или копирование/вставку, нужно просто понять как читать определения функции (прототипы). Давайте начнем:

Замечание: Предпосылки: Базовое понимание типов

Хотя PHP и является слабо типизированным языком, важно иметь базовое представление о типах, так как они играют большую роль в PHP.

Определения функций показывают нам какого типа значения они возвращают. Для первого примера возьмем определение функции strlen():

strlen

(PHP 4, PHP 5)
strlen -- Возвращает длину строки

Описание
int strlen ( string $string )

Возвращает длину переданной строки.

Объяснение определения функции
Часть | Описание
strlen | Имя функции.
(PHP 4, PHP 5) | strlen() была во всех версиях PHP 4 и PHP 5
int | Тип возвращаемого этой функцией значения, в данном случае integer (так как длина строки измеряется числом).
( string $string ) | Первый (и в данном случае единственный) параметр/аргумент этой функции называется string, а его типом является string.

Можно переписать вышеуказанное определение функции в более общем виде:

      возвращаемый тип    имя функции    ( тип параметра   имя параметра )

Много функций принимают несколько параметров, например, in_array(). Ее прототип выглядит так:

      bool in_array ( mixed $needle, array $haystack [, bool $strict])

Что это означает? in_array() возвращает boolean, TRUE в случае успешной работы (если needle был найден в haystack) или FALSE в случае возникновения ошибки (если needle не был найден в haystack). Первый параметр называется needle ("иголка") и может принимать много различных типов, поэтому он называется "смешанным". Этот смешанный needle (то, что мы ищем) может быть любым скалярным значением (string, integer, или float), либо массивом. haystack ("стог сена", массив, в котором мы ищем) - это второй параметр. Третий необязательный параметр называется strict ("строго"). Все необязательные параметры пишутся в [ квадратных скобках ]. Руководство указывает, что параметр strict по умолчанию принимает значение boolean FALSE. Смотрите отдельную страницу документации по каждой функции для более подробной информации по их работе.

Есть также функции с более сложной информацией о версиях PHP. Возьмем для примера html_entity_decode():

(PHP 4 >= 4.3.0, PHP 5)

Это означает, что функция появилась в официальных версиях языка только с выхода PHP 4.3.0.

User Contributed Notes

php dot devel at homelinkcs dot com 12-Jul-2005 05:50
More specifically, an ampersand (&) prepended to an argument name means that the argument will be passed by reference (http://www.php.net/manual/en/language.references.pass.php).
ceo at l-i-e dot com 09-Mar-2005 03:16
Another thing to watch for is the & in the argument list.

That generally means that the function is going to *CHANGE* the value you pass in, in some way, and you can't rely on it being the same as what you handed off to the function.
О заметках пользователей
Версии PHP, документированные в этом руководстве
Об этом руководстве


Версии PHP, документированные в этом руководстве

Данное руководство содержит информацию о прошлых, настоящих и будущих версиях PHP. Изменения поведения документированы замечаниями, историей изменений и непосредственно в тексте самого руководства. Самой ранней документируемой версией PHP является 4.1.0, а поздней - PHP 5.x.x.

Если документация доступна для самой последней (еще невыпущенной) разрабатываемой версии PHP, она помечается либо как "доступно в SVN" либо "разрабатываемая версия". И хотя эти изменения запланированы, в редких случаях они могут измениться.

Вся разработка ведется в Subversion (SVN) и может быть получена способом, описанным на странице » анонимный доступ к SVN. Или же те же самые исходные коды могут быть скачаны в виде » снимков исходного кода PHP, доступных для каждой активной ветки разработки PHP.

Для ясности, руководство указывает основную, промежуточную и дробную версию релизов PHP. Возьмем для примера версию PHP 5.3.1, 5 является основной версией, 3 является промежуточной, и 1 является дробной версией. Обычно новые возможности в PHP добавляются только в основных и промежуточных версиях, а исправления ошибок - в дробных. Однако, это соглашение не всегда верно.

Также учтите, что руководство по PHP пишется в настоящем, а не в будущем времени, даже для задокументированных, но еще не доступных возможностей. Это сделано для того, чтобы облегчить испытание временем для данного руководства, таким образом можно избежать рутинных грамматических правок с каждой новой выпущенной версией PHP.

Много раз в руководстве указываются "значения по умолчанию" для различных директив PHP. Эти значения основаны на том, как ведет себя PHP без конфигурационного файла php.ini, поэтому они могут отличаться от тех, что приведены в распространяемых вместе с PHP файлах php.ini-development и php.ini-production. Они также относятся к последней версии PHP, хотя история изменений упоминает только прошлые значения. За подробной информацией об этих значениях и их истории изменений обращайтесь к приложению со списком PHP директив.

User Contributed Notes

There are no user contributed notes for this page.
Как читать определения функции (прототип)
Как узнать больше о PHP
Об этом руководстве


Как узнать больше о PHP

Это руководство не пытается охватить вопросы общего программирования. Если вы являетесь новичком или даже начинающим программистом, написание PHP-программ может показаться вам трудным, если вы будете использовать только это руководство. Вам, скорее всего, может понадобиться материал, более подходящий для начинающих.

Существует несколько списков рассылки, предназначенных для обсуждения всех аспектов программирования на PHP. Если вы чувствуете, что не можете найти решение какой-либо проблемы, кто-нибудь из подписчиков списка, вполне вероятно, сможет вам помочь. Все виды поддержки пользователей, в том числе и почтовые списки рассылки, перечислены на » странице поддержки PHP.net. Кроме того, на » странице ссылок PHP.net доступен список веб-сайтов, посвященных статьям по PHP, форумам и галереям кода.

User Contributed Notes

There are no user contributed notes for this page.
Версии PHP, документированные в этом руководстве
Как помочь в написании документации
Об этом руководстве


Как помочь в написании документации

Существуют три способа, чтобы помочь нам в улучшении документации.

Если вам встречаются ошибки в этом руководстве, на любом языке, сообщайте о них с помощью системы сообщения об ошибках, доступной по адресу » http://bugs.php.net/. Классифицируйте ваше сообщение как "Documentation Problem" ("Ошибка в документации"). Все проблемы с документацией, включая ошибки с различными форматами руководства, должны быть отправлены как сообщение об ошибке.

Замечание:

Пожалуйста, не используйте систему сообщения об ошибках для того, чтобы получить какого-либо рода помощь. Вместо этого воспользуйтесь какими-либо » видами поддержки, упомянутыми выше.

Посылая заметки, пользователи могут предоставить различные примеры, предостережения и разъяснения для других читателей. Но, пожалуйста, не используйте систему аннотации для сообщений об ошибках. Более подробные сведения о заметках пользователей вы можете получить, ознакомившись с главой 'О заметках пользователей' этого приложения.

Руководство по PHP было переведено на много языков. Знание английского и другого иностранного языка дает вам еще один способ улучшить это руководство, работая в команде переводчиков. Если вы собираетесь приступить к переводу, обратитесь к » http://doc.php.net/php/dochowto/.

Проект документации PHP также имеет IRC канал (чат), где можно найти много авторов данного руководства. Заходите на #php.doc на сайте irc.efnet.org и обсуждайте различные способы улучшить данное руководство.

User Contributed Notes

There are no user contributed notes for this page.
Как узнать больше о PHP
Как создаются форматы документации
Об этом руководстве


Как создаются форматы документации

Это руководство написано на XML с использованием » DocBook XML DTD, с помощью » PhD (The [PH]P based [D]ocBook renderer, Генератор из формата Docbook на PHP) в целях поддержки и форматирования.

Использование XML в качестве единственного исходного формата позволяет нам создавать документацию во многих форматах, позволяя в то же время редактировать только один исходный документ для всех форматов. Утилитой для форматирования руководства является » PhD. Для создания руководства в формате Windows HTML Help мы используем » Microsoft HTML Help Workshop и, разумеется, сам PHP для дополнительных преобразований и форматирования.

Вы можете загрузить руководство на многих языках и во многих форматах, более подробно смотрите » http://www.php.net/docs.php. Исходный код XML можно загрузить из SVN и просмотреть онлайн по адресу » http://svn.php.net/viewvc/. Документация находится в модуле phpdoc.

User Contributed Notes

There are no user contributed notes for this page.
Как помочь в написании документации
Переводы
Об этом руководстве


Переводы

Руководство по PHP доступно не только в нескольких форматах, но и на различных языках. Сначала текст руководства пишется на английском, а затем команды людей по всему миру переводят его на свой родной язык. Если перевод документации какой-либо функции или главы еще не был завершен, система сборки руководства использует соответствующий английский вариант.

Люди, осуществляющие перевод документации, начинают с использования исходного кода в формате XML, доступного по адресу » http://svn.php.net/viewvc/ и затем переводят его на свой родной язык. Для перевода не используются сгенерированные версии (например, HTML или обычный текст), так как система сборки документации сама заботится о преобразовании XML в читабельные форматы.

Замечание:

Если вы хотите принять участие в переводе документации на ваш родной язык, присоединитесь к команде перевода, подписавшись на список рассылки phpdoc: вышлите пустое сообщение на адрес » phpdoc-subscribe@lists.php.net. Адрес списка рассылки - phpdoc@lists.php.net. Укажите в сообщении, что вы заинтересованы в участии в переводе руководства и кто-нибудь поможет вам начать новый перевод или найти команду, занимающуюся переводом на ваш язык.

В настоящее время руководство доступно, частично или в полной мере, на более чем 10 языках.

Все эти версии руководства доступны для загрузки по адресу » http://www.php.net/docs.php.

User Contributed Notes

There are no user contributed notes for this page.
Как создаются форматы документации
Creative Commons Attribution 3.0
Об этом руководстве


Creative Commons Attribution 3.0

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  1. "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.
  2. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License.
  3. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership.
  4. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
  5. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work.
  6. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  7. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
  8. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.

2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.

3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  1. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
  2. to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified.";
  3. to Distribute and Publicly Perform the Work including as incorporated in Collections; and,
  4. to Distribute and Publicly Perform Adaptations.

  5. For the avoidance of doubt:

    1. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;
    2. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and,
    3. Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License.

The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved.

4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  1. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(b), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(b), as requested.
  2. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Section 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4 (b) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
  3. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination.

  1. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  2. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  1. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  2. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  3. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  4. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent
  5. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
  6. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law.

User Contributed Notes

There are no user contributed notes for this page.
Переводы
Алфавитный список
Appendices


Алфавитный список

Содержание

  • Список функций и методов
  • Список примеров

User Contributed Notes

There are no user contributed notes for this page.
Creative Commons Attribution 3.0
Список функций и методов
Appendices


Список функций и методов

Список всех функций и методов в руководстве

  • a
    • abs - Модуль числа
    • acos - Арккосинус
    • acosh - Гиперболический арккосинус
    • addcslashes - Экранирует cтроку слэшами в стиле языка C
    • addslashes - Экранирует строку с помощью слэшей
    • aggregate - Dynamic class and object aggregation of methods and properties
    • aggregate_info - Gets aggregation information for a given object
    • aggregate_methods - Dynamic class and object aggregation of methods
    • aggregate_methods_by_list - Selective dynamic class methods aggregation to an object
    • aggregate_methods_by_regexp - Selective class methods aggregation to an object using a regular expression
    • aggregate_properties - Dynamic aggregation of class properties to an object
    • aggregate_properties_by_list - Selective dynamic class properties aggregation to an object
    • aggregate_properties_by_regexp - Selective class properties aggregation to an object using a regular expression
    • aggregation_info - Псевдоним aggregate_info
    • AMQPChannel::commitTransaction - Commit a pending transaction
    • AMQPChannel::isConnected - Check the channel connection
    • AMQPChannel::qos - Set the Quality Of Service settings for the given channel
    • AMQPChannel::rollbackTransaction - Rollback a transaction
    • AMQPChannel::setPrefetchCount - Set the number of messages to prefetch from the broker
    • AMQPChannel::setPrefetchSize - Set the window size to prefetch from the broker
    • AMQPChannel::startTransaction - Start a transaction
    • AMQPChannel::__construct - Create an instance of an AMQPChannel object
    • AMQPConnection::connect - Установить соединение с брокером AMQP
    • AMQPConnection::disconnect - Закрыть соединение с брокером AMQP
    • AMQPConnection::getHost - Get the configured host
    • AMQPConnection::getLogin - Get the configured login
    • AMQPConnection::getPassword - Get the configured password
    • AMQPConnection::getPort - Get the configured port
    • AMQPConnection::getVhost - Get the configured vhost
    • AMQPConnection::isConnected - Определить, подключен ли объект AMQPConnection к брокеру
    • AMQPConnection::reconnect - Закрыть все открытые соединения и создать новое соединение с брокером AMQP
    • AMQPConnection::setHost - Установить хост AMPQ
    • AMQPConnection::setLogin - Установить логин
    • AMQPConnection::setPassword - Установить пароль
    • AMQPConnection::setPort - Установить порт AMPQ
    • AMQPConnection::setVhost - Установить виртуальный хост AMQP
    • AMQPConnection::__construct - Создать новый экземпляр AMQPConnection
    • AMQPEnvelope::getAppId - Get the message appid
    • AMQPEnvelope::getBody - Get the message body
    • AMQPEnvelope::getContentEncoding - Get the message contentencoding
    • AMQPEnvelope::getContentType - Get the message contenttype
    • AMQPEnvelope::getCorrelationId - Get the message correlation id
    • AMQPEnvelope::getDeliveryTag - Get the message delivery tag
    • AMQPEnvelope::getExchange - Get the message exchange
    • AMQPEnvelope::getExpiration - Get the message expiration
    • AMQPEnvelope::getHeader - Get a specific message header
    • AMQPEnvelope::getHeaders - Get the message headers
    • AMQPEnvelope::getMessageId - Get the message id
    • AMQPEnvelope::getPriority - Get the message priority
    • AMQPEnvelope::getReplyTo - Get the message replyto
    • AMQPEnvelope::getRoutingKey - Get the message routing key
    • AMQPEnvelope::getTimeStamp - Get the message timestamp
    • AMQPEnvelope::getType - Get the message type
    • AMQPEnvelope::getUserId - Get the message user id
    • AMQPEnvelope::isRedelivery - Whether this is a redelivery of the message
    • AMQPExchange::bind - Привязка к другому обменнику
    • AMQPExchange::declare - Объявить новый обменник на брокере
    • AMQPExchange::delete - Удалить обменник из брокера
    • AMQPExchange::getArgument - Get the argument associated with the given key
    • AMQPExchange::getArguments - Get all arguments set on the given exchange
    • AMQPExchange::getFlags - Get the flag bitmask
    • AMQPExchange::getName - Get the configured name
    • AMQPExchange::getType - Get the configured type
    • AMQPExchange::publish - Опубликовать сообщение в обменнике
    • AMQPExchange::setArgument - Set the value for the given key
    • AMQPExchange::setArguments - Set all arguments on the exchange
    • AMQPExchange::setFlags - Set the flags on an exchange
    • AMQPExchange::setName - Set the name of the exchange
    • AMQPExchange::setType - Set the type of the exchange
    • AMQPExchange::__construct - Создает экземпляр AMQPExchange
    • AMQPQueue::ack - Подтвердить получение сообщения
    • AMQPQueue::bind - Связать данную очередь с ключом маршрутизации на обменнике
    • AMQPQueue::cancel - Отменить привязку очереди
    • AMQPQueue::consume - Использовать сообщения из очереди
    • AMQPQueue::declare - Объявить новую очередь
    • AMQPQueue::delete - Удалить очередь и её содержимое
    • AMQPQueue::get - Получить следующее сообщение из очереди
    • AMQPQueue::getArgument - Get the argument associated with the given key
    • AMQPQueue::getArguments - Get all arguments set on the given queue
    • AMQPQueue::getFlags - Get the flag bitmask
    • AMQPQueue::getName - Get the configured name
    • AMQPQueue::nack - Mark a message as explicitly not acknowledged.
    • AMQPQueue::purge - Очистить содержимое очереди
    • AMQPQueue::setArgument - Set the value for the given key
    • AMQPQueue::setArguments - Set all arguments on the queue
    • AMQPQueue::setFlags - Set the queue flags
    • AMQPQueue::setName - Set the queue name
    • AMQPQueue::unbind - Удалить привязку очереди к ключу маршрутизации
    • AMQPQueue::__construct - Создать экземпляр объекта AMQPQueue
    • apache_child_terminate - Завершить процесс Apache по окончании текущего запроса
    • apache_getenv - Возвращает переменную окружения подпроцесса сервера Apache
    • apache_get_modules - Возвращает список загруженных модулей сервера Apache
    • apache_get_version - Возвращает версию Apache
    • apache_lookup_uri - Осуществить частичный запрос на указанный URI и вернуть все полученные сведения
    • apache_note - Возвращает и устанавливает уведомления к запросу Apache
    • apache_request_headers - Получает список всех заголовков HTTP-запроса
    • apache_reset_timeout - Сбрасывает таймер сервера Apache
    • apache_response_headers - Возвращает список всех HTTP заголовков ответа Apache
    • apache_setenv - Устанавливает переменную subprocess_env Apache
    • APCIterator::current - Get current item
    • APCIterator::getTotalCount - Get total count
    • APCIterator::getTotalHits - Get total cache hits
    • APCIterator::getTotalSize - Get total cache size
    • APCIterator::key - Get iterator key
    • APCIterator::next - Move pointer to next item
    • APCIterator::rewind - Rewinds iterator
    • APCIterator::valid - Checks if current position is valid
    • APCIterator::__construct - Constructs an APCIterator iterator object
    • apc_add - Cache a new variable in the data store
    • apc_bin_dump - Get a binary dump of the given files and user variables
    • apc_bin_dumpfile - Output a binary dump of cached files and user variables to a file
    • apc_bin_load - Load a binary dump into the APC file/user cache
    • apc_bin_loadfile - Load a binary dump from a file into the APC file/user cache
    • apc_cache_info - Retrieves cached information from APC's data store
    • apc_cas - Updates an old value with a new value
    • apc_clear_cache - Clears the APC cache
    • apc_compile_file - Stores a file in the bytecode cache, bypassing all filters.
    • apc_dec - Decrease a stored number
    • apc_define_constants - Defines a set of constants for retrieval and mass-definition
    • apc_delete - Removes a stored variable from the cache
    • apc_delete_file - Deletes files from the opcode cache
    • apc_exists - Checks if APC key exists
    • apc_fetch - Fetch a stored variable from the cache
    • apc_inc - Increase a stored number
    • apc_load_constants - Loads a set of constants from the cache
    • apc_sma_info - Retrieves APC's Shared Memory Allocation information
    • apc_store - Cache a variable in the data store
    • apd_breakpoint - Останавливает интерпретатор и ожидает символ возврата каретки (CR) из сокета
    • apd_callstack - Возвращает текущий вызов стека в виде массива
    • apd_clunk - Выводит предупреждение и стек вызова
    • apd_continue - Restarts the interpreter
    • apd_croak - Throw an error, a callstack and then exit
    • apd_dump_function_table - Outputs the current function table
    • apd_dump_persistent_resources - Return all persistent resources as an array
    • apd_dump_regular_resources - Return all current regular resources as an array
    • apd_echo - Echo to the debugging socket
    • apd_get_active_symbols - Get an array of the current variables names in the local scope
    • apd_set_pprof_trace - Starts the session debugging
    • apd_set_session - Changes or sets the current debugging level
    • apd_set_session_trace - Starts the session debugging
    • apd_set_session_trace_socket - Starts the remote session debugging
    • AppendIterator::append - Добавляет итератор
    • AppendIterator::current - Возвращает текущее значение
    • AppendIterator::getArrayIterator - Возвращает класс итератора массива ArrayIterator
    • AppendIterator::getInnerIterator - Возвращает внутренний итератор
    • AppendIterator::getIteratorIndex - Возвращает индекс итератора
    • AppendIterator::key - Возвращает текущий ключ
    • AppendIterator::next - Переходит к следующему элементу
    • AppendIterator::rewind - Перематывает итератор
    • AppendIterator::valid - Проверяет срок действия текущего элемента
    • AppendIterator::__construct - Создает AppendIterator
    • array - Создает массив
    • ArrayAccess::offsetExists - Определяет, существует ли заданное смещение (ключ)
    • ArrayAccess::offsetGet - Возвращает заданное смещение (ключ)
    • ArrayAccess::offsetSet - Устанавливает заданное смещение (ключ)
    • ArrayAccess::offsetUnset - Удаляет смещение
    • ArrayIterator::append - Добавить элемент
    • ArrayIterator::asort - Сортирует массив по значениям
    • ArrayIterator::count - Посчитать количество элементов
    • ArrayIterator::current - Возвращает текущий элемент в массиве
    • ArrayIterator::getArrayCopy - Возвращает копию массива
    • ArrayIterator::getFlags - Получает флаги
    • ArrayIterator::key - Возвращает ключ текущего элемента массива
    • ArrayIterator::ksort - Сортирует массив по ключам
    • ArrayIterator::natcasesort - Сортирует массив "натурально", с учетом регистра
    • ArrayIterator::natsort - Сортирует массив "натурально"
    • ArrayIterator::next - Перемещает указатель за следующую запись
    • ArrayIterator::offsetExists - Проверяет существует ли смещение
    • ArrayIterator::offsetGet - Получает значение для смещения
    • ArrayIterator::offsetSet - Устанавливает значение для смещения
    • ArrayIterator::offsetUnset - Сбрасывает значение по смещению
    • ArrayIterator::rewind - Перемещает указатель в начало массива
    • ArrayIterator::seek - Перещает указатель на выбранную позицию
    • ArrayIterator::serialize - Сериализует массив
    • ArrayIterator::setFlags - Устанавливает флаги, управляющие поведением
    • ArrayIterator::uasort - Сортировка, определенная пользователем
    • ArrayIterator::uksort - Сортировка, определенная пользователем
    • ArrayIterator::unserialize - Десериализация
    • ArrayIterator::valid - Проверяет, содержит ли массив еще записи
    • ArrayIterator::__construct - Создает ArrayIterator
    • ArrayObject::append - Добавляет значение в конец массива
    • ArrayObject::asort - Сортирует записи по значению
    • ArrayObject::count - Возвращает количество публичных свойств ArrayObject
    • ArrayObject::exchangeArray - Заменяет текущий массив на другой
    • ArrayObject::getArrayCopy - Создаёт копию ArrayObject
    • ArrayObject::getFlags - Получает флаги поведения
    • ArrayObject::getIterator - Создаёт новый итератор из экземпляра ArrayObject
    • ArrayObject::getIteratorClass - Возвращает имя класса итератора для ArrayObject
    • ArrayObject::ksort - Сортирует записи по ключам
    • ArrayObject::natcasesort - Сортирует массив, используя регистронезависимый алгоритм "natural order"
    • ArrayObject::natsort - Сортирует массив, используя алгоритм "natural order"
    • ArrayObject::offsetExists - Проверяет, существует ли указанный индекс
    • ArrayObject::offsetGet - Возвращает значение по указанному индексу
    • ArrayObject::offsetSet - Установливает новое значение по указанному индексу
    • ArrayObject::offsetUnset - Удаляет значение по указанному индексу
    • ArrayObject::serialize - Сериализует ArrayObject
    • ArrayObject::setFlags - Устанавливает флаги поведения
    • ArrayObject::setIteratorClass - Устанавливает имя класса итератора для ArrayObject
    • ArrayObject::uasort - Сортирует записи, используя пользовательскую функцию для сравнения элементов и сохраняя при этом связь ключ/значение
    • ArrayObject::uksort - Сортирует массив по ключам, используя пользовательскую функцию для сравнения
    • ArrayObject::unserialize - Десериализует ArrayObject
    • ArrayObject::__construct - Создает новый объект типа массив
    • array_change_key_case - Меняет регистр ключей в массиве
    • array_chunk - Разбивает массив на части
    • array_combine - Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений
    • array_count_values - Подсчитывает количество всех значений массива
    • array_diff - Вычислить расхождение массивов
    • array_diff_assoc - Вычисляет расхождение массивов с дополнительной проверкой индекса
    • array_diff_key - Вычисляет расхождение массивов, сравнивая ключи
    • array_diff_uassoc - Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
    • array_diff_ukey - Вычисляет расхождение массивов, используя callback-функцию для сравнения ключей
    • array_fill - Заполняет массив значениями
    • array_fill_keys - Создает массив и заполняет его значениями, с определенными ключами
    • array_filter - Фильтрует элементы массива с помощью callback-функции
    • array_flip - Меняет местами ключи с их значениями в массиве
    • array_intersect - Вычисляет схождение массивов
    • array_intersect_assoc - Вычисляет схождение массивов с дополнительной проверкой индекса
    • array_intersect_key - Вычислить пересечение массивов, сравнивая ключи
    • array_intersect_uassoc - Вычисляет схождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
    • array_intersect_ukey - Вычисляет схождение массивов, используя callback-функцию для сравнения ключей
    • array_keys - Возвращает все или некоторое подмножество ключей массива
    • array_key_exists - Проверяет, присутствует ли в массиве указанный ключ или индекс
    • array_map - Применяет callback-функцию ко всем элементам указанных массивов
    • array_merge - Сливает один или большее количество массивов
    • array_merge_recursive - Рекурсивное слияние двух или более массивов
    • array_multisort - Сортирует несколько массивов или многомерные массивы
    • array_pad - Дополнить размер массива определенным значением до заданной величины
    • array_pop - Извлекает последний элемент массива
    • array_product - Вычислить произведение значений массива
    • array_push - Добавляет один или несколько элеметов в конец массива
    • array_rand - Выбирает одно или несколько случайных значений из массива
    • array_reduce - Итеративно уменьшает массив к единственному значению, используя callback-функцию
    • array_replace - Замена элементов массива элементами других переданных массивов
    • array_replace_recursive - Рекурсивно заменяет элементы первого массива элементами переданных массивов
    • array_reverse - Возвращает массив с элементами в обратном порядке
    • array_search - Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
    • array_shift - Извлекает первый элемент массива
    • array_slice - Выбирает срез массива
    • array_splice - Удаляет часть массива и заменяет её чем-нибудь ещё
    • array_sum - Вычисляет сумму значений массива
    • array_udiff - Вычисляет расхождение массивов, используя для сравнения callback-функцию
    • array_udiff_assoc - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
    • array_udiff_uassoc - Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
    • array_uintersect - Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
    • array_uintersect_assoc - Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
    • array_uintersect_uassoc - Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений callback-функцию
    • array_unique - Убирает повторяющиеся значения из массива
    • array_unshift - Добавляет один или несколько элементов в начало массива
    • array_values - Выбирает все значения массива
    • array_walk - Применяет пользовательскую функцию к каждому элементу массива
    • array_walk_recursive - Рекурсивно применяет пользовательскую функцию к каждому элементу массива
    • arsort - Сортирует массив в обратном порядке, сохраняя ключи
    • asin - Арксинус
    • asinh - Гиперболический арксинус
    • asort - Сортирует массив, сохраняя ключи
    • assert - Проверка утверждения (равен ли результат FALSE)
    • assert_options - Установка/получение различных установок проверки утверждений
    • atan - Арктангенс
    • atan2 - Арктангенс двух переменных
    • atanh - Гиперболический арктангенс
  • b
    • base64_decode - Декодирует данные, закодированные алгоритмом MIME base64
    • base64_encode - Kодирует данные алгоритмом MIME base64
    • basename - Возвращает последний компонент имени из указанного пути
    • base_convert - Преобразование числа между произвольными системами счисления
    • bbcode_add_element - Добавляет элемент bbcode
    • bbcode_add_smiley - Добавляет смайлы для разбора парсером
    • bbcode_create - Create a BBCode Resource
    • bbcode_destroy - Закрывает ресурс BBCode_container
    • bbcode_parse - Производит разбор строки в соответствии с заданным набором правил
    • bbcode_set_arg_parser - Подключает другой парсер для применения иного набора правил в качестве параметров разбора
    • bbcode_set_flags - Устанавливает или изменяет настройки парсера
    • bcadd - Сложить 2 числа произвольной точности
    • bccomp - Сравнение двух чисел произвольной точности
    • bcdiv - Операция деления для чисел произвольной точности
    • bcmod - Получает остаток от деления чисел с произвольной точностью
    • bcmul - Умножение двух чисел с произвольной точностью
    • bcompiler_load - Reads and creates classes from a bz compressed file
    • bcompiler_load_exe - Reads and creates classes from a bcompiler exe file
    • bcompiler_parse_class - Reads the bytecodes of a class and calls back to a user function
    • bcompiler_read - Reads and creates classes from a filehandle
    • bcompiler_write_class - Writes a defined class as bytecodes
    • bcompiler_write_constant - Writes a defined constant as bytecodes
    • bcompiler_write_exe_footer - Writes the start pos, and sig to the end of a exe type file
    • bcompiler_write_file - Writes a php source file as bytecodes
    • bcompiler_write_footer - Writes the single character \x00 to indicate End of compiled data
    • bcompiler_write_function - Writes a defined function as bytecodes
    • bcompiler_write_functions_from_file - Writes all functions defined in a file as bytecodes
    • bcompiler_write_header - Writes the bcompiler header
    • bcompiler_write_included_filename - Writes an included file as bytecodes
    • bcpow - Возведение в степень чисел с произвольной точностью
    • bcpowmod - Возводит одно число в степень другого и возвращает остаток от деления результата на третье число
    • bcscale - Задает количество чисел после десятичной точки по умолчанию для всех bc math функций.
    • bcsqrt - Извлекает квадратный корень из числа с произвольной точностью
    • bcsub - Вычитает одно число с произвольной точностью из другого
    • bin2hex - Преобразует бинарные данные в шестнадцатиричное представление
    • bindec - Двоичное в десятичное
    • bindtextdomain - Устанавливает путь для домена
    • bind_textdomain_codeset - Устанавливает кодировку, в которой будут возвращаться сообщения из каталога сообщений домена
    • bson_decode - Преобразовует объект BSON в массив PHP
    • bson_encode - Преобразовует переменную PHP в строку BSON
    • bzclose - Закрывает файл bzip2
    • bzcompress - Сжимает строку с использованием bzip2
    • bzdecompress - Распаковывает данные, сжатые с использованием bzip2
    • bzerrno - Возвращает код ошибки работы с bzip2
    • bzerror - Возвращает код и строку ошибки работы с bzip2 в виде массива
    • bzerrstr - Возвращает строку ошибки работы с bzip2
    • bzflush - Форсирует запись всех буферизированных данных
    • bzopen - Открывает файл, сжатый с использованием bzip2
    • bzread - Бинарно-безопасное чтение файла bzip2
    • bzwrite - Бинарно-безопасная запись bzip2 файла
  • c
    • CachingIterator::count - Возвращает число элементов в итераторе
    • CachingIterator::current - Возвращает текущий элемент
    • CachingIterator::getCache - Назначение getCache
    • CachingIterator::getFlags - Получает используемые флаги
    • CachingIterator::getInnerIterator - Возвращает внутренний итератор
    • CachingIterator::hasNext - Проверяет, имеет ли внутренний итератор допустимый следующий элемент
    • CachingIterator::key - Возвращает ключ для текущего элемента
    • CachingIterator::next - Перемещает итератор к следующему элементу
    • CachingIterator::offsetExists - Назначение offsetExists
    • CachingIterator::offsetGet - Назначение offsetGet
    • CachingIterator::offsetSet - Назначение offsetSet
    • CachingIterator::offsetUnset - Назначение offsetUnset
    • CachingIterator::rewind - Возвращает итератор в начало
    • CachingIterator::setFlags - Назначение setFlags
    • CachingIterator::valid - Проверяет, является ли текущий элемент допустимым
    • CachingIterator::__construct - Строит новый объект CachingIterator для итератора
    • CachingIterator::__toString - Возвращает строковое представление текущего элемента
    • Cairo::availableFonts - Retrieves the availables font types
    • Cairo::availableSurfaces - Retrieves all available surfaces
    • Cairo::statusToString - Retrieves the current status as string
    • Cairo::version - Retrives cairo's library version
    • Cairo::versionString - Retrieves cairo version as string
    • CairoContext::appendPath - Appends a path to current path
    • CairoContext::arc - Adds a circular arc
    • CairoContext::arcNegative - Adds a negative arc
    • CairoContext::clip - Establishes a new clip region
    • CairoContext::clipExtents - Computes the area inside the current clip
    • CairoContext::clipPreserve - Establishes a new clip region from the current clip
    • CairoContext::clipRectangleList - Retrieves the current clip as a list of rectangles
    • CairoContext::closePath - Closes the current path
    • CairoContext::copyPage - Emits the current page
    • CairoContext::copyPath - Creates a copy of the current path
    • CairoContext::copyPathFlat - Gets a flattened copy of the current path
    • CairoContext::curveTo - Adds a curve
    • CairoContext::deviceToUser - Transform a coordinate
    • CairoContext::deviceToUserDistance - Transform a distance
    • CairoContext::fill - Fills the current path
    • CairoContext::fillExtents - Computes the filled area
    • CairoContext::fillPreserve - Fills and preserve the current path
    • CairoContext::fontExtents - Get the font extents
    • CairoContext::getAntialias - Retrives the current antialias mode
    • CairoContext::getCurrentPoint - The getCurrentPoint purpose
    • CairoContext::getDash - The getDash purpose
    • CairoContext::getDashCount - The getDashCount purpose
    • CairoContext::getFillRule - The getFillRule purpose
    • CairoContext::getFontFace - The getFontFace purpose
    • CairoContext::getFontMatrix - The getFontMatrix purpose
    • CairoContext::getFontOptions - The getFontOptions purpose
    • CairoContext::getGroupTarget - The getGroupTarget purpose
    • CairoContext::getLineCap - The getLineCap purpose
    • CairoContext::getLineJoin - The getLineJoin purpose
    • CairoContext::getLineWidth - The getLineWidth purpose
    • CairoContext::getMatrix - The getMatrix purpose
    • CairoContext::getMiterLimit - The getMiterLimit purpose
    • CairoContext::getOperator - The getOperator purpose
    • CairoContext::getScaledFont - The getScaledFont purpose
    • CairoContext::getSource - The getSource purpose
    • CairoContext::getTarget - The getTarget purpose
    • CairoContext::getTolerance - The getTolerance purpose
    • CairoContext::glyphPath - The glyphPath purpose
    • CairoContext::hasCurrentPoint - The hasCurrentPoint purpose
    • CairoContext::identityMatrix - The identityMatrix purpose
    • CairoContext::inFill - The inFill purpose
    • CairoContext::inStroke - The inStroke purpose
    • CairoContext::lineTo - The lineTo purpose
    • CairoContext::mask - The mask purpose
    • CairoContext::maskSurface - The maskSurface purpose
    • CairoContext::moveTo - The moveTo purpose
    • CairoContext::newPath - The newPath purpose
    • CairoContext::newSubPath - The newSubPath purpose
    • CairoContext::paint - The paint purpose
    • CairoContext::paintWithAlpha - The paintWithAlpha purpose
    • CairoContext::pathExtents - The pathExtents purpose
    • CairoContext::popGroup - The popGroup purpose
    • CairoContext::popGroupToSource - The popGroupToSource purpose
    • CairoContext::pushGroup - The pushGroup purpose
    • CairoContext::pushGroupWithContent - The pushGroupWithContent purpose
    • CairoContext::rectangle - The rectangle purpose
    • CairoContext::relCurveTo - The relCurveTo purpose
    • CairoContext::relLineTo - The relLineTo purpose
    • CairoContext::relMoveTo - The relMoveTo purpose
    • CairoContext::resetClip - The resetClip purpose
    • CairoContext::restore - The restore purpose
    • CairoContext::rotate - The rotate purpose
    • CairoContext::save - The save purpose
    • CairoContext::scale - The scale purpose
    • CairoContext::selectFontFace - The selectFontFace purpose
    • CairoContext::setAntialias - The setAntialias purpose
    • CairoContext::setDash - The setDash purpose
    • CairoContext::setFillRule - The setFillRule purpose
    • CairoContext::setFontFace - The setFontFace purpose
    • CairoContext::setFontMatrix - The setFontMatrix purpose
    • CairoContext::setFontOptions - The setFontOptions purpose
    • CairoContext::setFontSize - The setFontSize purpose
    • CairoContext::setLineCap - The setLineCap purpose
    • CairoContext::setLineJoin - The setLineJoin purpose
    • CairoContext::setLineWidth - The setLineWidth purpose
    • CairoContext::setMatrix - The setMatrix purpose
    • CairoContext::setMiterLimit - The setMiterLimit purpose
    • CairoContext::setOperator - The setOperator purpose
    • CairoContext::setScaledFont - The setScaledFont purpose
    • CairoContext::setSource - The setSource purpose
    • CairoContext::setSourceRGB - The setSourceRGB purpose
    • CairoContext::setSourceRGBA - The setSourceRGBA purpose
    • CairoContext::setSourceSurface - The setSourceSurface purpose
    • CairoContext::setTolerance - The setTolerance purpose
    • CairoContext::showPage - The showPage purpose
    • CairoContext::showText - The showText purpose
    • CairoContext::status - The status purpose
    • CairoContext::stroke - The stroke purpose
    • CairoContext::strokeExtents - The strokeExtents purpose
    • CairoContext::strokePreserve - The strokePreserve purpose
    • CairoContext::textExtents - The textExtents purpose
    • CairoContext::textPath - The textPath purpose
    • CairoContext::transform - The transform purpose
    • CairoContext::translate - The translate purpose
    • CairoContext::userToDevice - The userToDevice purpose
    • CairoContext::userToDeviceDistance - The userToDeviceDistance purpose
    • CairoContext::__construct - Creates a new CairoContext
    • CairoFontFace::getType - Retrieves the font face type
    • CairoFontFace::status - Check for CairoFontFace errors
    • CairoFontFace::__construct - Creates a new CairoFontFace object
    • CairoFontOptions::equal - The equal purpose
    • CairoFontOptions::getAntialias - The getAntialias purpose
    • CairoFontOptions::getHintMetrics - The getHintMetrics purpose
    • CairoFontOptions::getHintStyle - The getHintStyle purpose
    • CairoFontOptions::getSubpixelOrder - The getSubpixelOrder purpose
    • CairoFontOptions::hash - The hash purpose
    • CairoFontOptions::merge - The merge purpose
    • CairoFontOptions::setAntialias - The setAntialias purpose
    • CairoFontOptions::setHintMetrics - The setHintMetrics purpose
    • CairoFontOptions::setHintStyle - The setHintStyle purpose
    • CairoFontOptions::setSubpixelOrder - The setSubpixelOrder purpose
    • CairoFontOptions::status - The status purpose
    • CairoFontOptions::__construct - The __construct purpose
    • CairoFormat::strideForWidth - Provides an appropiate stride to use
    • CairoGradientPattern::addColorStopRgb - The addColorStopRgb purpose
    • CairoGradientPattern::addColorStopRgba - The addColorStopRgba purpose
    • CairoGradientPattern::getColorStopCount - The getColorStopCount purpose
    • CairoGradientPattern::getColorStopRgba - The getColorStopRgba purpose
    • CairoGradientPattern::getExtend - The getExtend purpose
    • CairoGradientPattern::setExtend - The setExtend purpose
    • CairoImageSurface::createForData - The createForData purpose
    • CairoImageSurface::createFromPng - Creates a new CairoImageSurface form a png image file
    • CairoImageSurface::getData - Gets the image data as string
    • CairoImageSurface::getFormat - Get the image format
    • CairoImageSurface::getHeight - Retrieves the height of the CairoImageSurface
    • CairoImageSurface::getStride - The getStride purpose
    • CairoImageSurface::getWidth - Retrieves the width of the CairoImageSurface
    • CairoImageSurface::__construct - Creates a new CairoImageSurface
    • CairoLinearGradient::getPoints - The getPoints purpose
    • CairoLinearGradient::__construct - The __construct purpose
    • CairoMatrix::initIdentity - Creates a new identity matrix
    • CairoMatrix::initRotate - Creates a new rotated matrix
    • CairoMatrix::initScale - Creates a new scaling matrix
    • CairoMatrix::initTranslate - Creates a new translation matrix
    • CairoMatrix::invert - The invert purpose
    • CairoMatrix::multiply - The multiply purpose
    • CairoMatrix::rotate - The rotate purpose
    • CairoMatrix::scale - Applies scaling to a matrix
    • CairoMatrix::transformDistance - The transformDistance purpose
    • CairoMatrix::transformPoint - The transformPoint purpose
    • CairoMatrix::translate - The translate purpose
    • CairoMatrix::__construct - Creates a new CairoMatrix object
    • CairoPattern::getMatrix - The getMatrix purpose
    • CairoPattern::getType - The getType purpose
    • CairoPattern::setMatrix - The setMatrix purpose
    • CairoPattern::status - The status purpose
    • CairoPattern::__construct - The __construct purpose
    • CairoPdfSurface::setSize - The setSize purpose
    • CairoPdfSurface::__construct - The __construct purpose
    • CairoPsSurface::dscBeginPageSetup - The dscBeginPageSetup purpose
    • CairoPsSurface::dscBeginSetup - The dscBeginSetup purpose
    • CairoPsSurface::dscComment - The dscComment purpose
    • CairoPsSurface::getEps - The getEps purpose
    • CairoPsSurface::getLevels - The getLevels purpose
    • CairoPsSurface::levelToString - The levelToString purpose
    • CairoPsSurface::restrictToLevel - The restrictToLevel purpose
    • CairoPsSurface::setEps - The setEps purpose
    • CairoPsSurface::setSize - The setSize purpose
    • CairoPsSurface::__construct - The __construct purpose
    • CairoRadialGradient::getCircles - The getCircles purpose
    • CairoRadialGradient::__construct - The __construct purpose
    • CairoScaledFont::extents - The extents purpose
    • CairoScaledFont::getCtm - The getCtm purpose
    • CairoScaledFont::getFontFace - The getFontFace purpose
    • CairoScaledFont::getFontMatrix - The getFontMatrix purpose
    • CairoScaledFont::getFontOptions - The getFontOptions purpose
    • CairoScaledFont::getScaleMatrix - The getScaleMatrix purpose
    • CairoScaledFont::getType - The getType purpose
    • CairoScaledFont::glyphExtents - The glyphExtents purpose
    • CairoScaledFont::status - The status purpose
    • CairoScaledFont::textExtents - The textExtents purpose
    • CairoScaledFont::__construct - The __construct purpose
    • CairoSolidPattern::getRgba - The getRgba purpose
    • CairoSolidPattern::__construct - The __construct purpose
    • CairoSurface::copyPage - The copyPage purpose
    • CairoSurface::createSimilar - The createSimilar purpose
    • CairoSurface::finish - The finish purpose
    • CairoSurface::flush - The flush purpose
    • CairoSurface::getContent - The getContent purpose
    • CairoSurface::getDeviceOffset - The getDeviceOffset purpose
    • CairoSurface::getFontOptions - The getFontOptions purpose
    • CairoSurface::getType - The getType purpose
    • CairoSurface::markDirty - The markDirty purpose
    • CairoSurface::markDirtyRectangle - The markDirtyRectangle purpose
    • CairoSurface::setDeviceOffset - The setDeviceOffset purpose
    • CairoSurface::setFallbackResolution - The setFallbackResolution purpose
    • CairoSurface::showPage - The showPage purpose
    • CairoSurface::status - The status purpose
    • CairoSurface::writeToPng - The writeToPng purpose
    • CairoSurface::__construct - The __construct purpose
    • CairoSurfacePattern::getExtend - The getExtend purpose
    • CairoSurfacePattern::getFilter - The getFilter purpose
    • CairoSurfacePattern::getSurface - The getSurface purpose
    • CairoSurfacePattern::setExtend - The setExtend purpose
    • CairoSurfacePattern::setFilter - The setFilter purpose
    • CairoSurfacePattern::__construct - The __construct purpose
    • CairoSvgSurface::getVersions - Used to retrieve a list of supported SVG versions
    • CairoSvgSurface::restrictToVersion - The restrictToVersion purpose
    • CairoSvgSurface::versionToString - The versionToString purpose
    • CairoSvgSurface::__construct - The __construct purpose
    • cairo_create - Returns a new CairoContext object on the requested surface.
    • cairo_font_face_get_type - Description
    • cairo_font_options_create - Description
    • cairo_font_options_equal - Description
    • cairo_font_options_get_antialias - Description
    • cairo_font_options_get_hint_metrics - Description
    • cairo_font_options_get_hint_style - Description
    • cairo_font_options_get_subpixel_order - Description
    • cairo_font_options_hash - Description
    • cairo_font_options_merge - Description
    • cairo_font_options_set_antialias - Description
    • cairo_font_options_set_hint_metrics - Description
    • cairo_font_options_set_hint_style - Description
    • cairo_font_options_set_subpixel_order - Description
    • cairo_font_options_status - Description
    • cairo_format_stride_for_width - Description
    • cairo_image_surface_create - Description
    • cairo_image_surface_create_for_data - Description
    • cairo_image_surface_create_from_png - Description
    • cairo_image_surface_get_data - Description
    • cairo_image_surface_get_format - Description
    • cairo_image_surface_get_height - Description
    • cairo_image_surface_get_stride - Description
    • cairo_image_surface_get_width - Description
    • cairo_matrix_create_translate - Псевдоним CairoMatrix::initTranslate
    • cairo_matrix_invert - Description
    • cairo_matrix_multiply - Description
    • cairo_matrix_rotate - Description
    • cairo_matrix_transform_distance - Description
    • cairo_matrix_transform_point - Description
    • cairo_matrix_translate - Description
    • cairo_pattern_add_color_stop_rgb - Description
    • cairo_pattern_add_color_stop_rgba - Description
    • cairo_pattern_create_for_surface - Description
    • cairo_pattern_create_linear - Description
    • cairo_pattern_create_radial - Description
    • cairo_pattern_create_rgb - Description
    • cairo_pattern_create_rgba - Description
    • cairo_pattern_get_color_stop_count - Description
    • cairo_pattern_get_color_stop_rgba - Description
    • cairo_pattern_get_extend - Description
    • cairo_pattern_get_filter - Description
    • cairo_pattern_get_linear_points - Description
    • cairo_pattern_get_matrix - Description
    • cairo_pattern_get_radial_circles - Description
    • cairo_pattern_get_rgba - Description
    • cairo_pattern_get_surface - Description
    • cairo_pattern_get_type - Description
    • cairo_pattern_set_extend - Description
    • cairo_pattern_set_filter - Description
    • cairo_pattern_set_matrix - Description
    • cairo_pattern_status - Description
    • cairo_pdf_surface_create - Description
    • cairo_pdf_surface_set_size - Description
    • cairo_ps_get_levels - Description
    • cairo_ps_level_to_string - Description
    • cairo_ps_surface_create - Description
    • cairo_ps_surface_dsc_begin_page_setup - Description
    • cairo_ps_surface_dsc_begin_setup - Description
    • cairo_ps_surface_dsc_comment - Description
    • cairo_ps_surface_get_eps - Description
    • cairo_ps_surface_restrict_to_level - Description
    • cairo_ps_surface_set_eps - Description
    • cairo_ps_surface_set_size - Description
    • cairo_scaled_font_create - Description
    • cairo_scaled_font_extents - Description
    • cairo_scaled_font_get_ctm - Description
    • cairo_scaled_font_get_font_face - Description
    • cairo_scaled_font_get_font_matrix - Description
    • cairo_scaled_font_get_font_options - Description
    • cairo_scaled_font_get_scale_matrix - Description
    • cairo_scaled_font_get_type - Description
    • cairo_scaled_font_glyph_extents - Description
    • cairo_scaled_font_status - Description
    • cairo_scaled_font_text_extents - Description
    • cairo_surface_copy_page - Description
    • cairo_surface_create_similar - Description
    • cairo_surface_finish - Description
    • cairo_surface_flush - Description
    • cairo_surface_get_content - Description
    • cairo_surface_get_device_offset - Description
    • cairo_surface_get_font_options - Description
    • cairo_surface_get_type - Description
    • cairo_surface_mark_dirty - Description
    • cairo_surface_mark_dirty_rectangle - Description
    • cairo_surface_set_device_offset - Description
    • cairo_surface_set_fallback_resolution - Description
    • cairo_surface_show_page - Description
    • cairo_surface_status - Description
    • cairo_surface_write_to_png - Description
    • cairo_svg_surface_create - Description
    • cairo_svg_surface_restrict_to_version - Description
    • cairo_svg_version_to_string - Description
    • calculhmac - Получить HMAC-ключ (Необходимо 2 параметра)
    • calcul_hmac - Получить HMAC-ключ (необходимо 8 параметров)
    • CallbackFilterIterator::accept - Calls the callback with the current value, the current key and the inner iterator as arguments
    • CallbackFilterIterator::__construct - Create a filtered iterator from another iterator
    • call_user_func - Вызывает пользовательскую функцию, указанную в первом параметре
    • call_user_func_array - Вызывает пользовательскую функцию с массивом параметров
    • call_user_method - Вызывает метод указанного объекта [устаревшее]
    • call_user_method_array - Вызывает метод объекта с массивом параметров [устаревшее]
    • cal_days_in_month - Возвращает количество дней в месяце для заданного года и календаря
    • cal_from_jd - Преобразует дату, заданную в юлианском календаре, в дату указанного календаря
    • cal_info - Возвращает информацию о заданном календаре
    • cal_to_jd - Преобразует заданную дату в Юлианское исчисление
    • ceil - Округляет дробь в большую сторону
    • chdb::get - Gets the value associated with a key
    • chdb::__construct - Creates a chdb instance
    • chdb_create - Creates a chdb file
    • chdir - Изменяет каталог
    • checkdate - Проверяет корректность даты по григорианскому календарю
    • checkdnsrr - Проверяет записи DNS, соответствующие переданному имени узла интернета или IP-адресу
    • chgrp - Изменяет группу владельцев файла
    • chmod - Изменяет режим доступа к файлу
    • chop - Псевдоним rtrim
    • chown - Изменяет владельца файла
    • chr - Возвращает символ по его коду
    • chroot - Изменяет корневой каталог
    • chunk_split - Разбивает строку на фрагменты
    • classkit_import - Импортирует определения методов нового класса из файла
    • classkit_method_add - Динамически добавляет новый метод в заданный класс
    • classkit_method_copy - Копирует метод из одного класса в другой
    • classkit_method_redefine - Динамически меняет код заданного метода
    • classkit_method_remove - Динамически удаляет заданный метод
    • classkit_method_rename - Динамически меняет имя заданного метода
    • class_alias - Создает псевдоним для указанного класса
    • class_exists - Проверяет, был ли объявлен класс
    • class_implements - Return the interfaces which are implemented by the given class
    • class_parents - Return the parent classes of the given class
    • class_uses - Return the traits used by the given class
    • clearstatcache - Очищает кэш состояния файлов
    • closedir - Освобождает дескриптор каталога
    • closelog - Завершает соединение с системным журналом
    • Closure::bind - Дублирует замыкание с указанием связанного объекта и области видимости класса
    • Closure::bindTo - Дублирует замыкание с указанием связанного объекта и области видимости класса
    • Closure::__construct - Конструктор запрещающий создавать новые объекты
    • Collator::asort - Sort array maintaining index association
    • Collator::compare - Compare two Unicode strings
    • Collator::create - Create a collator
    • Collator::getAttribute - Get collation attribute value
    • Collator::getErrorCode - Get collator's last error code
    • Collator::getErrorMessage - Get text for collator's last error code
    • Collator::getLocale - Get the locale name of the collator
    • Collator::getSortKey - Get sorting key for a string
    • Collator::getStrength - Get current collation strength
    • Collator::setAttribute - Set collation attribute
    • Collator::setStrength - Set collation strength
    • Collator::sort - Sort array using specified collator
    • Collator::sortWithSortKeys - Sort array using specified collator and sort keys
    • Collator::__construct - Create a collator
    • compact - Создает массив, содержащий названия переменных и их значения
    • com_addref - Increases the components reference counter [deprecated]
    • com_create_guid - Generate a globally unique identifier (GUID)
    • com_event_sink - Connect events from a COM object to a PHP object
    • com_get - Gets the value of a COM Component's property [deprecated]
    • com_get_active_object - Returns a handle to an already running instance of a COM object
    • com_invoke - Calls a COM component's method [deprecated]
    • com_isenum - Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
    • com_load - Creates a new reference to a COM component [deprecated]
    • com_load_typelib - Loads a Typelib
    • com_message_pump - Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo - Print out a PHP class definition for a dispatchable interface
    • com_propget - Псевдоним com_get
    • com_propput - Псевдоним com_set
    • com_propset - Псевдоним com_set
    • com_release - Decreases the components reference counter [deprecated]
    • com_set - Assigns a value to a COM component's property
    • connection_aborted - Проверяет подключение клиента
    • connection_status - Возвращает статус соединения в битах
    • connection_timeout - Проверяет превышение скриптом максимального времени выполнения
    • constant - Возвращает значение константы
    • Constants for PDO_4D - Constants for PDO_4D
    • convert_cyr_string - Преобразует строку из одной кириллической кодировки в другую
    • convert_uudecode - Декодирует строку из формата uuencode в обычный вид
    • convert_uuencode - Кодирует строку в формат uuencode
    • copy - Копирует файл
    • cos - Косинус
    • cosh - Гиперболический косинус
    • count - Подсчитывает количество элементов массива или что-то в объекте
    • Countable::count - Количество элементов объекта
    • Counter::bumpValue - Change the current value of a counter.
    • Counter::getMeta - Return a piece of metainformation about a counter.
    • Counter::getNamed - Retrieve an existing named counter.
    • Counter::getValue - Get the current value of a counter.
    • Counter::resetValue - Reset the current value of a counter.
    • Counter::setCounterClass - Set the class returned by Counter::getNamed.
    • Counter::__construct - Creates an instance of a Counter which maintains a single numeric value.
    • counter_bump - Update the current value of the basic counter.
    • counter_bump_value - Change the current value of a counter resource.
    • counter_create - Creates a counter which maintains a single numeric value.
    • counter_get - Get the current value of the basic counter.
    • counter_get_meta - Return a piece of metainformation about a counter resource.
    • counter_get_named - Retrieve an existing named counter as a resource.
    • counter_get_value - Get the current value of a counter resource.
    • counter_reset - Reset the current value of the basic counter.
    • counter_reset_value - Reset the current value of a counter resource.
    • count_chars - Возвращает информацию о символах, входящих в строку
    • crack_check - Проверяет взломостойкость переданного пароля
    • crack_closedict - Закрывает открытый ранее словарь CrackLib
    • crack_getlastmessage - Возвращает текстовое сообщение о последней проверке взломостойкости пароля
    • crack_opendict - Открывает новый словарь CrackLib
    • crc32 - Вычисляет полином CRC32 для строки
    • create_function - Создаёт анонимную (лямбда) функцию
    • crypt - Необратимое хэширование строки
    • ctype_alnum - Проверяет на наличие буквенно-цифровых символов
    • ctype_alpha - Проверяет на наличие буквенных символов
    • ctype_cntrl - Проверяет на наличие управляющих символов
    • ctype_digit - Проверяет на наличие цифровых символов в строке
    • ctype_graph - Проверяет наличие всех печатных символов, кроме пробела
    • ctype_lower - Проверяет наличие символов в нижнем регистре
    • ctype_print - Проверяет на наличие печатных символов
    • ctype_punct - Проверяет на наличие печатных символов, которые в то же время не являются пробельными или буквенно-цифровыми символами
    • ctype_space - Проверяет наличие пробельных символов
    • ctype_upper - Проверяет на наличие символов в верхнем регистре
    • ctype_xdigit - Проверяет наличие шестнадцатиричных цифр
    • cubrid_affected_rows - Return the number of rows affected by the last SQL statement
    • cubrid_bind - Bind variables to a prepared statement as parameters
    • cubrid_client_encoding - Return the current CUBRID connection charset
    • cubrid_close - Close CUBRID connection
    • cubrid_close_prepare - Close the request handle
    • cubrid_close_request - Close the request handle
    • cubrid_column_names - Get the column names in result
    • cubrid_column_types - Get column types in result
    • cubrid_col_get - Get contents of collection type column using OID
    • cubrid_col_size - Get the number of elements in collection type column using OID
    • cubrid_commit - Commit a transaction
    • cubrid_connect - Open a connection to a CUBRID Server
    • cubrid_connect_with_url - Establish the environment for connecting to CUBRID server
    • cubrid_current_oid - Get OID of the current cursor location
    • cubrid_data_seek - Move the internal row pointer of the CUBRID result
    • cubrid_db_name - Get db name from results of cubrid_list_dbs
    • cubrid_disconnect - Close a database connection
    • cubrid_drop - Delete an instance using OID
    • cubrid_errno - Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error - Get the error message
    • cubrid_error_code - Get error code for the most recent function call
    • cubrid_error_code_facility - Get the facility code of error
    • cubrid_error_msg - Get last error message for the most recent function call
    • cubrid_execute - Execute a prepared SQL statement
    • cubrid_fetch - Fetch the next row from a result set
    • cubrid_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • cubrid_fetch_assoc - Return the associative array that corresponds to the fetched row
    • cubrid_fetch_field - Get column information from a result and return as an object
    • cubrid_fetch_lengths - Return an array with the lengths of the values of each field from the current row
    • cubrid_fetch_object - Fetche the next row and returns it as an object
    • cubrid_fetch_row - Return a numerical array with the values of the current row
    • cubrid_field_flags - Return a string with the flags of the given field offset
    • cubrid_field_len - Get the maximum length of the specified field
    • cubrid_field_name - Return the name of the specified field index
    • cubrid_field_seek - Move the result set cursor to the specified field offset
    • cubrid_field_table - Return the name of the table of the specified field
    • cubrid_field_type - Return the type of the column corresponding to the given field offset
    • cubrid_free_result - Free the memory occupied by the result data
    • cubrid_get - Get a column using OID
    • cubrid_get_autocommit - Get auto-commit mode of the connection
    • cubrid_get_charset - Return the current CUBRID connection charset
    • cubrid_get_class_name - Get the class name using OID
    • cubrid_get_client_info - Return the client library version
    • cubrid_get_db_parameter - Returns the CUBRID database parameters
    • cubrid_get_query_timeout - Get the query timeout value of the request
    • cubrid_get_server_info - Return the CUBRID server version
    • cubrid_insert_id - Return the ID generated for the lastest updated AUTO_INCREMENT column
    • cubrid_is_instance - Check whether the instance pointed by OID exists
    • cubrid_list_dbs - Return an array with the list of all existing CUBRID databases
    • cubrid_load_from_glo - Read data from a GLO instance and save it in a file
    • cubrid_lob_close - Close BLOB/CLOB data
    • cubrid_lob_export - Export BLOB/CLOB data to file
    • cubrid_lob_get - Get BLOB/CLOB data
    • cubrid_lob_send - Read BLOB/CLOB data and send straight to browser
    • cubrid_lob_size - Get BLOB/CLOB data size
    • cubrid_lock_read - Set a read lock on the given OID
    • cubrid_lock_write - Set a write lock on the given OID
    • cubrid_move_cursor - Move the cursor in the result
    • cubrid_new_glo - Create a glo instance
    • cubrid_next_result - Get result of next query when executing multiple SQL statements
    • cubrid_num_cols - Return the number of columns in the result set
    • cubrid_num_fields - Return the number of columns in the result set
    • cubrid_num_rows - Get the number of rows in the result set
    • cubrid_pconnect - Open a persistent connection to a CUBRID server
    • cubrid_pconnect_with_url - Open a persistent connection to CUBRID server
    • cubrid_ping - Ping a server connection or reconnect if there is no connection
    • cubrid_prepare - Prepare an SQL statement for execution
    • cubrid_put - Update a column using OID
    • cubrid_query - Send a CUBRID query
    • cubrid_real_escape_string - Escape special characters in a string for use in an SQL statement
    • cubrid_result - Return the value of a specific field in a specific row
    • cubrid_rollback - Roll back a transaction
    • cubrid_save_to_glo - Save requested file in a GLO instance
    • cubrid_schema - Get the requested schema information
    • cubrid_send_glo - Read data from glo and send it to std output
    • cubrid_seq_drop - Delete an element from sequence type column using OID
    • cubrid_seq_insert - Insert an element to a sequence type column using OID
    • cubrid_seq_put - Update the element value of sequence type column using OID
    • cubrid_set_add - Insert a single element to set type column using OID
    • cubrid_set_autocommit - Set autocommit mode of the connection
    • cubrid_set_db_parameter - Sets the CUBRID database parameters
    • cubrid_set_drop - Delete an element from set type column using OID
    • cubrid_set_query_timeout - Set the timeout time of query execution
    • cubrid_unbuffered_query - Perform a query without fetching the results into memory
    • cubrid_version - Get the CUBRID PHP module's version
    • curl_close - Завершает сеанс cURL
    • curl_copy_handle - Копирует дескриптор cURL вместе со всеми его настройками
    • curl_errno - Возвращает код последней ошибки
    • curl_error - Возвращает строку с описанием последней ошибки текущего сеанса
    • curl_exec - Выполняет запрос cURL
    • curl_getinfo - Возвращает информацию об определенной операции
    • curl_init - Инициализирует сеанс cURL
    • curl_multi_add_handle - Добавляет обычный cURL дескриптор к набору cURL дескрипторов
    • curl_multi_close - Закрывает набор cURL дескрипторов
    • curl_multi_exec - Запускает под-соединения текущего дескриптора cURL
    • curl_multi_getcontent - Возвращает результат операции, если была установлена опция CURLOPT_RETURNTRANSFER
    • curl_multi_info_read - Возвращает информацию о текущих операциях
    • curl_multi_init - Создает набор cURL-дескрипторов
    • curl_multi_remove_handle - Удаляет cURL дескриптор из набора cURL дескрипторов
    • curl_multi_select - Ждет активности на любом curl_multi соединении
    • curl_setopt - Устанавливает параметр для сеанса CURL
    • curl_setopt_array - Устанавливает несколько параметров для сеанса cURL
    • curl_version - Возвращает версию cURL
    • current - Возвращает текущий элемент массива
    • cyrus_authenticate - Аутентификация на сервере Cyrus IMAP
    • cyrus_bind - Привязать обратные вызовы для Cyrus IMAP соединения
    • cyrus_close - Закрывает соединение с сервером Cyrus IMAP
    • cyrus_connect - Установить соединение с сервером Cyrus IMAP
    • cyrus_query - Послать запрос Cyrus IMAP серверу
    • cyrus_unbind - Убрать привязки обратных вызовов для Cyrus IMAP соединения
  • d
    • data:// - Схема Data (RFC 2397)
    • date - Форматирует вывод системной даты/времени
    • DateInterval::createFromDateString - Создает объект класса DateInterval, используя данные из переданной строки
    • DateInterval::format - Форматирует интервал
    • DateInterval::__construct - Создает новый объект DateInterval
    • DatePeriod::__construct - Создает новый объект DatePeriod
    • DateTime::add - Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
    • DateTime::createFromFormat - Создает и возвращает экземпляр класса DateTime, соответствующий заданному формату
    • DateTime::diff - Возвращает разницу между двумя DateTime объектами
    • DateTime::format - Возвращает дату приведенную к заданному формату
    • DateTime::getLastErrors - Возвращает предупреждения и ошибки
    • DateTime::getOffset - Возвращает смещение временной зоны
    • DateTime::getTimestamp - Получение метки времени в стиле Unix
    • DateTime::getTimezone - Возвращает временную зону, соответствующую заданному объекту DateTime
    • DateTime::modify - Изменение временной метки
    • DateTime::setDate - Установка даты
    • DateTime::setISODate - Установка ISO даты
    • DateTime::setTime - Установка времени
    • DateTime::setTimestamp - Устанавливает дату и время, основываясь на метке времени Unix
    • DateTime::setTimezone - Установка временной зоны для объекта класса DateTime
    • DateTime::sub - Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime
    • DateTime::__construct - Конструктор класса DateTime
    • DateTime::__set_state - Обработчик __set_state
    • DateTime::__wakeup - Обработчик __wakeup
    • DateTimeZone::getLocation - Возвращает информацию о местоположении для временной зоны
    • DateTimeZone::getName - Возвращает имя временной зоны
    • DateTimeZone::getOffset - Возвращает смещение временной зоны от GMT
    • DateTimeZone::getTransitions - Возвращает все переходы для временной зоны
    • DateTimeZone::listAbbreviations - Возвращает ассоциативный массив содержащий флаг перехода на летнее время, смещение и имя временной зоны
    • DateTimeZone::listIdentifiers - Вовращает численно индексированный массив со всеми идентификаторами временных зон
    • DateTimeZone::__construct - Создает новый объект DateTimeZone
    • date_add - Псевдоним DateTime::add
    • date_create - Псевдоним DateTime::__construct
    • date_create_from_format - Псевдоним DateTime::createFromFormat
    • date_date_set - Псевдоним DateTime::setDate
    • date_default_timezone_get - Возвращает временную зону, используемой по умолчанию всеми функциями даты/времени в скрипте
    • date_default_timezone_set - Устанавливает временную зону по умолчанию для всех функций даты/времени в скрипте
    • date_diff - Псевдоним DateTime::diff
    • date_format - Псевдоним DateTime::format
    • date_get_last_errors - Псевдоним DateTime::getLastErrors
    • date_interval_create_from_date_string - Псевдоним DateInterval::createFromDateString
    • date_interval_format - Псевдоним DateInterval::format
    • date_isodate_set - Псевдоним DateTime::setISODate
    • date_modify - Псевдоним DateTime::modify
    • date_offset_get - Псевдоним DateTime::getOffset
    • date_parse - Возвращает ассоциативный массив с подробной информацией о заданной дате
    • date_parse_from_format - Получение информации о заданной в определенном формате дате
    • date_sub - Псевдоним DateTime::sub
    • date_sunrise - Возвращает время рассвета для заданных дня и местоположения
    • date_sunset - Возвращает время захода солнца для заданных дня и местоположения
    • date_sun_info - Возвращает массив с информацией о закате/рассвете и начале/окончании сумерек
    • date_timestamp_get - Псевдоним DateTime::getTimestamp
    • date_timestamp_set - Псевдоним DateTime::setTimestamp
    • date_timezone_get - Псевдоним DateTime::getTimezone
    • date_timezone_set - Псевдоним DateTime::setTimezone
    • date_time_set - Псевдоним DateTime::setTime
    • db2_autocommit - Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param - Binds a PHP variable to an SQL statement parameter
    • db2_client_info - Returns an object with properties that describe the DB2 database client
    • db2_close - Closes a database connection
    • db2_columns - Returns a result set listing the columns and associated metadata for a table
    • db2_column_privileges - Returns a result set listing the columns and associated privileges for a table
    • db2_commit - Commits a transaction
    • db2_connect - Returns a connection to a database
    • db2_conn_error - Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg - Returns the last connection error message and SQLCODE value
    • db2_cursor_type - Returns the cursor type used by a statement resource
    • db2_escape_string - Used to escape certain characters
    • db2_exec - Executes an SQL statement directly
    • db2_execute - Executes a prepared SQL statement
    • db2_fetch_array - Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc - Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both - Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object - Returns an object with properties representing columns in the fetched row
    • db2_fetch_row - Sets the result set pointer to the next row or requested row
    • db2_field_display_size - Returns the maximum number of bytes required to display a column
    • db2_field_name - Returns the name of the column in the result set
    • db2_field_num - Returns the position of the named column in a result set
    • db2_field_precision - Returns the precision of the indicated column in a result set
    • db2_field_scale - Returns the scale of the indicated column in a result set
    • db2_field_type - Returns the data type of the indicated column in a result set
    • db2_field_width - Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys - Returns a result set listing the foreign keys for a table
    • db2_free_result - Frees resources associated with a result set
    • db2_free_stmt - Frees resources associated with the indicated statement resource
    • db2_get_option - Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id - Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read - Gets a user defined size of LOB files with each invocation
    • db2_next_result - Requests the next result set from a stored procedure
    • db2_num_fields - Returns the number of fields contained in a result set
    • db2_num_rows - Returns the number of rows affected by an SQL statement
    • db2_pclose - Closes a persistent database connection
    • db2_pconnect - Returns a persistent connection to a database
    • db2_prepare - Prepares an SQL statement to be executed
    • db2_primary_keys - Returns a result set listing primary keys for a table
    • db2_procedures - Returns a result set listing the stored procedures registered in a database
    • db2_procedure_columns - Returns a result set listing stored procedure parameters
    • db2_result - Returns a single column from a row in the result set
    • db2_rollback - Rolls back a transaction
    • db2_server_info - Returns an object with properties that describe the DB2 database server
    • db2_set_option - Set options for connection or statement resources
    • db2_special_columns - Returns a result set listing the unique row identifier columns for a table
    • db2_statistics - Returns a result set listing the index and statistics for a table
    • db2_stmt_error - Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg - Returns a string containing the last SQL statement error message
    • db2_tables - Returns a result set listing the tables and associated metadata in a database
    • db2_table_privileges - Returns a result set listing the tables and associated privileges in a database
    • dbase_add_record - Добавляет запись в базу данных
    • dbase_close - Закрывает базу данных
    • dbase_create - Создает базу данных
    • dbase_delete_record - Удаление записей из базы данных
    • dbase_get_header_info - Получает информацию о свойствах полей базы данных
    • dbase_get_record - Получает записи из базы данных, как из индексированного массива
    • dbase_get_record_with_names - Получает запись из базы данных в виде ассоциативного массива
    • dbase_numfields - Получает количество полей базы данных
    • dbase_numrecords - Получает количество записей в базе данных
    • dbase_open - Открывает базу данных
    • dbase_pack - Фиксирует удаление из базы данных
    • dbase_replace_record - Заменяет запись в базе данных
    • dba_close - Close a DBA database
    • dba_delete - Delete DBA entry specified by key
    • dba_exists - Check whether key exists
    • dba_fetch - Fetch data specified by key
    • dba_firstkey - Fetch first key
    • dba_handlers - List all the handlers available
    • dba_insert - Insert entry
    • dba_key_split - Splits a key in string representation into array representation
    • dba_list - List all open database files
    • dba_nextkey - Fetch next key
    • dba_open - Open database
    • dba_optimize - Optimize database
    • dba_popen - Open database persistently
    • dba_replace - Replace or insert entry
    • dba_sync - Synchronize database
    • dbplus_add - Add a tuple to a relation
    • dbplus_aql - Perform AQL query
    • dbplus_chdir - Get/Set database virtual current directory
    • dbplus_close - Close a relation
    • dbplus_curr - Get current tuple from relation
    • dbplus_errcode - Get error string for given errorcode or last error
    • dbplus_errno - Get error code for last operation
    • dbplus_find - Set a constraint on a relation
    • dbplus_first - Get first tuple from relation
    • dbplus_flush - Flush all changes made on a relation
    • dbplus_freealllocks - Free all locks held by this client
    • dbplus_freelock - Release write lock on tuple
    • dbplus_freerlocks - Free all tuple locks on given relation
    • dbplus_getlock - Get a write lock on a tuple
    • dbplus_getunique - Get an id number unique to a relation
    • dbplus_info - Get information about a relation
    • dbplus_last - Get last tuple from relation
    • dbplus_lockrel - Request write lock on relation
    • dbplus_next - Get next tuple from relation
    • dbplus_open - Open relation file
    • dbplus_prev - Get previous tuple from relation
    • dbplus_rchperm - Change relation permissions
    • dbplus_rcreate - Creates a new DB++ relation
    • dbplus_rcrtexact - Creates an exact but empty copy of a relation including indices
    • dbplus_rcrtlike - Creates an empty copy of a relation with default indices
    • dbplus_resolve - Resolve host information for relation
    • dbplus_restorepos - Restore position
    • dbplus_rkeys - Specify new primary key for a relation
    • dbplus_ropen - Open relation file local
    • dbplus_rquery - Perform local (raw) AQL query
    • dbplus_rrename - Rename a relation
    • dbplus_rsecindex - Create a new secondary index for a relation
    • dbplus_runlink - Remove relation from filesystem
    • dbplus_rzap - Remove all tuples from relation
    • dbplus_savepos - Save position
    • dbplus_setindex - Set index
    • dbplus_setindexbynumber - Set index by number
    • dbplus_sql - Perform SQL query
    • dbplus_tcl - Execute TCL code on server side
    • dbplus_tremove - Remove tuple and return new current tuple
    • dbplus_undo - Undo
    • dbplus_undoprepare - Prepare undo
    • dbplus_unlockrel - Give up write lock on relation
    • dbplus_unselect - Remove a constraint from relation
    • dbplus_update - Update specified tuple in relation
    • dbplus_xlockrel - Request exclusive lock on relation
    • dbplus_xunlockrel - Free exclusive lock on relation
    • dbx_close - Close an open connection/database
    • dbx_compare - Compare two rows for sorting purposes
    • dbx_connect - Open a connection/database
    • dbx_error - Report the error message of the latest function call in the module
    • dbx_escape_string - Escape a string so it can safely be used in an sql-statement
    • dbx_fetch_row - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
    • dbx_query - Send a query and fetch all results (if any)
    • dbx_sort - Sort a result from a dbx_query by a custom sort function
    • dcgettext - Переопределяет одно сообщение в домене
    • dcngettext - Версия dcgettext для множественного числа
    • deaggregate - Removes the aggregated methods and properties from an object
    • debug_backtrace - Выводит стек вызовов функций в массив
    • debug_print_backtrace - Выводит стек вызовов функций
    • debug_zval_dump - Выводит строковое представление внутреннего значения zend
    • decbin - Переводит число из десятичной системы счисления в двоичную
    • dechex - Переводит число из десятичной системы счисления в шестнадцатиричную
    • decoct - Переводит число из десятичной системы счисления в восьмеричную
    • define - Определяет именованную константу
    • defined - Проверяет существование указанной именованной константы
    • define_syslog_variables - Инициализирует все syslog переменные
    • deg2rad - Преобразует значение из градусов в радианы
    • delete - См.описание функции unlink или unset
    • dgettext - Позволяет переопределить текущий домен
    • die - Эквивалент функции exit
    • dio_close - Closes the file descriptor given by fd
    • dio_fcntl - Performs a c library fcntl on fd
    • dio_open - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
    • dio_read - Reads bytes from a file descriptor
    • dio_seek - Seeks to pos on fd from whence
    • dio_stat - Gets stat information about the file descriptor fd
    • dio_tcsetattr - Sets terminal attributes and baud rate for a serial port
    • dio_truncate - Truncates file descriptor fd to offset bytes
    • dio_write - Writes data to fd with optional truncation at length
    • dir - Возвращает экземпляр класса Directory
    • Directory::close - Close directory handle
    • Directory::read - Read entry from directory handle
    • Directory::rewind - Rewind directory handle
    • DirectoryIterator::current - Возвращает текущий элемент DirectoryIterator
    • DirectoryIterator::getATime - Возвращает время последнего доступа к текущему элементу DirectoryIterator
    • DirectoryIterator::getBasename - Возвращает имя файла (без расширения) текущего элемента DirectoryIterator
    • DirectoryIterator::getCTime - Возвращает время последнего изменения i-узла текущего элемента DirectoryIterator
    • DirectoryIterator::getExtension - Возвращает расширение файла
    • DirectoryIterator::getFilename - Возвращает имя файла текущего элемента DirectoryIterator
    • DirectoryIterator::getGroup - Возвращает идентификатор группы текущего элемента DirectoryIterator
    • DirectoryIterator::getInode - Возвращает inode текущего элемента DirectoryIterator
    • DirectoryIterator::getMTime - Возвращает время последнего изменения текущего элемента DirectoryIterator
    • DirectoryIterator::getOwner - Возвращает индентификатор владельца текущего элемента DirectoryIterator
    • DirectoryIterator::getPath - Возвращает путь к текущему элементу DirectoryIterator без имени файла
    • DirectoryIterator::getPathname - Возвращает путь и имя файла текущего элемента DirectoryIterator
    • DirectoryIterator::getPerms - Возвращает набор прав для текущего элемента DirectoryIterator item
    • DirectoryIterator::getSize - Возвращает размер текущего элемента DirectoryIterator
    • DirectoryIterator::getType - Определяет тип текущего элемента DirectoryIterator
    • DirectoryIterator::isDir - Определяет, является ли текущий элемент DirectoryIterator директорией
    • DirectoryIterator::isDot - Определяет, является ли текущий элемент DirectoryIterator '.' или '..'
    • DirectoryIterator::isExecutable - Определяет, является ли текущий элемент DirectoryIterator исполняемым
    • DirectoryIterator::isFile - Определяет, является ли текущий элемент DirectoryIterator обычным файлом
    • DirectoryIterator::isLink - Определяет, является ли текущий элемент DirectoryIterator символической ссылкой
    • DirectoryIterator::isReadable - Определяет, доступен ли текущий элемент DirectoryIterator для чтения
    • DirectoryIterator::isWritable - Определяет, доступен ли текущий элемент DirectoryIterator для записи
    • DirectoryIterator::key - Возвращает ключ текущего элемента DirectoryIterator
    • DirectoryIterator::next - Перемещает указатель на следующий элемент DirectoryIterator
    • DirectoryIterator::rewind - Устанавливает указатель на первый элемент DirectoryIterator
    • DirectoryIterator::seek - Перемещает указатель DirectoryIterator на определённую позицию
    • DirectoryIterator::valid - Проверяет, является ли текущий элемент DirectoryIterator допустимым файлом
    • DirectoryIterator::__construct - Создаёт новый итератор директорий по пути
    • DirectoryIterator::__toString - Возвращает имя файла в виде строки
    • dirname - Возвращает имя родительского каталога из указанного пути
    • diskfreespace - Псевдоним disk_free_space
    • disk_free_space - Возвращает размер доступного пространства в каталоге или в файловой системе
    • disk_total_space - Возвращает общий размер каталога или раздела файловой системы
    • dl - Загружает PHP расширение во время выполнения
    • dngettext - Версия dgettext для множественного числа
    • dns_check_record - Псевдоним checkdnsrr
    • dns_get_mx - Псевдоним getmxrr
    • dns_get_record - Fetch DNS Resource Records associated with a hostname
    • DOMAttr::isId - Проверяет, является ли атрибут описанным в DTD ID
    • DOMAttr::__construct - Создает экземпляр класса DOMAttr
    • DomAttribute::name - Возвращает имя атрибута
    • DomAttribute::set_value - Устанавливает значение атрибута
    • DomAttribute::specified - Проверяет, задан ли атрибут
    • DomAttribute::value - Возвращает значение атрибута
    • DOMCdataSection::__construct - Создает новый экземпляр класса DOMCdataSection
    • DOMCharacterData::appendData - Добавляет строку в конец символьных данных узла
    • DOMCharacterData::deleteData - Удаление диапазона символов из узла
    • DOMCharacterData::insertData - Вставляет строку после заданного отступа из 16-битных блоков
    • DOMCharacterData::replaceData - Заменяет подстроку в узле типа DOMCharacterData
    • DOMCharacterData::substringData - Извлекает определенный диапазон данных из узла
    • DOMComment::__construct - Создает новый экземпляр класса DOMComment
    • DomDocument::add_root - Добавляет корневой узел [устаревший метод]
    • DOMDocument::createAttribute - Создает новый атрибут
    • DOMDocument::createAttributeNS - Создает новый узел-атрибут с соответствующим ему пространством имен
    • DOMDocument::createCDATASection - Создает новый cdata узел
    • DOMDocument::createComment - Создает новый узел-комментарий
    • DOMDocument::createDocumentFragment - Создание фрагмента докуента
    • DOMDocument::createElement - Создает новый узел-элемент
    • DOMDocument::createElementNS - Создание нового узла-элемента с соответствующим пространством имен
    • DOMDocument::createEntityReference - Создание нового узла-ссылки на сущность
    • DOMDocument::createProcessingInstruction - Создает новый PI-узел
    • DOMDocument::createTextNode - Создает новый текстовый узел
    • DomDocument::create_attribute - Создает новый атрибут
    • DomDocument::create_cdata_section - Создает новый узел типа cdata
    • DomDocument::create_comment - Создает новый узел-комментарий
    • DomDocument::create_element - Создает новый узел-элемент
    • DomDocument::create_element_ns - Создает новый элемент с соответствующим пространством имен
    • DomDocument::create_entity_reference - Создает ссылку на сущность
    • DomDocument::create_processing_instruction - Создает новый PI узел
    • DomDocument::create_text_node - Создает новый текстовый узел
    • DomDocument::doctype - Возвращает тип документа
    • DomDocument::document_element - Возвращает узел корневого элемента
    • DomDocument::dump_file - Сохраняет XML дерево в файл
    • DomDocument::dump_mem - Представляет XML дерево в виде строки
    • DOMDocument::getElementById - Ищет элемент с заданным id
    • DOMDocument::getElementsByTagName - Ищет все элементы с заданным локальным именем
    • DOMDocument::getElementsByTagNameNS - Ищет элементы с заданным именем в определенном пространстве имен
    • DomDocument::get_elements_by_tagname - Возвращает массив узлов с заданным тэгом в документе или пустой массив, если таких элементов не найдено
    • DomDocument::get_element_by_id - Ищет элемент с заданным id
    • DomDocument::html_dump_mem - Преобразует дерево XML в HTML строку
    • DOMDocument::importNode - Импорт узла в текущий документ
    • DOMDocument::load - Загрузка XML из файла
    • DOMDocument::loadHTML - Загрузка HTML из строки
    • DOMDocument::loadHTMLFile - Загрузка HTML из файла
    • DOMDocument::loadXML - Загрузка XML из строки
    • DOMDocument::normalizeDocument - Нормализует документ
    • DOMDocument::registerNodeClass - Регистрация расширенного класса, используемого для создания базового типа узлов
    • DOMDocument::relaxNGValidate - Производит проверку документа на правильность построения посредством relaxNG
    • DOMDocument::relaxNGValidateSource - Проверяет документ посредством relaxNG
    • DOMDocument::save - Сохраняет XML дерево из внутреннего представления в файл
    • DOMDocument::saveHTML - Сохраняет документ из внутреннего представления в строку, используя HTML форматирование
    • DOMDocument::saveHTMLFile - Сохраняет документ из внутреннего представления в файл, используя HTML форматирование
    • DOMDocument::saveXML - Сохраняет XML дерево из внутреннего представления в виде строки
    • DOMDocument::schemaValidate - Проверяет действительности документа, основываясь на заданной схеме
    • DOMDocument::schemaValidateSource - Проверяет действительность документа, основываясь на схеме
    • DOMDocument::validate - Проверяет документ на соответствие его DTD
    • DomDocument::xinclude - Подстановка XIncludes в объекте DomDocument
    • DOMDocument::__construct - Создание нового DOMDocument объекта
    • DOMDocumentFragment::appendXML - Добавление необработанных XML данных
    • DomDocumentType::entities - Возвращает список сущностей
    • DomDocumentType::internal_subset - Возвращает подмножество внутренней структуры dom документа
    • DomDocumentType::name - Возвращает имя типа документа
    • DomDocumentType::notations - Возвращает список обозначений
    • DomDocumentType::public_id - Возвращает общедоступный (public) идентификатор типа документа
    • DomDocumentType::system_id - Возвращает системный идентификатор типа документа
    • DOMElement::getAttribute - Возвращает значение атрибута
    • DOMElement::getAttributeNode - Возвращает узел атрибута
    • DOMElement::getAttributeNodeNS - Возвращает узел атрибута
    • DOMElement::getAttributeNS - Возвращает значение атрибута
    • DOMElement::getElementsByTagName - Возвращает элементы по имени тэга
    • DOMElement::getElementsByTagNameNS - Получение элементов по локальному имени в заданном пространстве имен
    • DomElement::get_attribute - Возвращает значение заданного атрибута
    • DomElement::get_attribute_node - Возвращает узел заданного атрибута
    • DomElement::get_elements_by_tagname - Получает элементы по имени
    • DOMElement::hasAttribute - Проверяет наличие атрибута
    • DOMElement::hasAttributeNS - Проверяет, существует ли заданный атрибут
    • DomElement::has_attribute - Проверяет, есть ли атрибут в текущем узле
    • DOMElement::removeAttribute - Удаляет атрибут
    • DOMElement::removeAttributeNode - Удаляет атрибут
    • DOMElement::removeAttributeNS - Удаляет атрибут
    • DomElement::remove_attribute - Удаляет атрибут
    • DOMElement::setAttribute - Устанавливает значение атрибута
    • DOMElement::setAttributeNode - Добавляет новый узел атрибута к элементу
    • DOMElement::setAttributeNodeNS - Добавляет новый атрибут к элементу
    • DOMElement::setAttributeNS - Добавляет новый атрибут
    • DOMElement::setIdAttribute - Объявляет атрибут с заданным именем ключевым атрибутом
    • DOMElement::setIdAttributeNode - Объявляет заданный узал атрибута ключевым
    • DOMElement::setIdAttributeNS - Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим
    • DomElement::set_attribute - Устанавливает значение атрибута
    • DomElement::set_attribute_node - Добавляет новый атрибут
    • DomElement::tagname - Возвращает имя текущего элемента
    • DOMElement::__construct - Создание нового объекта класса DOMElement
    • DOMEntityReference::__construct - Создает новый объект класса DOMEntityReference
    • DOMImplementation::createDocument - Создает объект класса DOMDocument заданного типа с элементом document
    • DOMImplementation::createDocumentType - Создает пустой объект класса DOMDocumentType
    • DOMImplementation::hasFeature - Тестирует реализацию специфичных возможностей объекта DOMImplementation
    • DOMImplementation::__construct - Создает новый объект класса DOMImplementation
    • DOMNamedNodeMap::getNamedItem - Извлекает узел с заданным именем
    • DOMNamedNodeMap::getNamedItemNS - Извлекает узел с заданным локальным именем и URI пространства имен
    • DOMNamedNodeMap::item - Извлекает узел с заданным индексом
    • DomNode::add_namespace - Добавляет узлу объявление пространства имен
    • DOMNode::appendChild - Добавляет новый дочерний узел в конец списка потомков
    • DomNode::append_child - Добавляет нового сына в конец списка сыновей
    • DomNode::append_sibling - Добавляет к узлу нового брата
    • DomNode::attributes - Возвращает список атрибутов
    • DOMNode::C14N - Canonicalize nodes to a string
    • DOMNode::C14NFile - Canonicalize nodes to a file
    • DomNode::child_nodes - Возвращает сыновей узла
    • DOMNode::cloneNode - Клонирует узел
    • DomNode::clone_node - Копирует узел
    • DomNode::dump_node - Представляет одиночный узел в виде строки
    • DomNode::first_child - Возвращает первого сына узла
    • DOMNode::getLineNo - Возвращает номер строки узла
    • DOMNode::getNodePath - Получение XPath пути к узлу
    • DomNode::get_content - Получает содержимое узла
    • DOMNode::hasAttributes - Проверяет, содержит ли данный узел атрибуты
    • DOMNode::hasChildNodes - Проверяет, содержит ли данный узел потомков
    • DomNode::has_attributes - Проверяет, есть ли в узле атрибуты
    • DomNode::has_child_nodes - Проверяет, есть ли у узла потомки
    • DOMNode::insertBefore - Добавляет новый дочерний узел перед опорным узлом
    • DomNode::insert_before - Вставляет новый узел в качестве сына
    • DOMNode::isDefaultNamespace - Проверяет, совпадает ли URI пространства имен узла с пространством имен по умолчанию
    • DOMNode::isSameNode - Проверяет, являются ли два узла одним и тем же узлом
    • DOMNode::isSupported - Проверяет, поддерживается ли заданное свойство в определенной версии
    • DomNode::is_blank_node - Проверяет, есть ли содержимое в узле
    • DomNode::last_child - Возвращает последнего сына узла
    • DOMNode::lookupNamespaceURI - Получает URI пространства имен узла по префиксу
    • DOMNode::lookupPrefix - Возвращает префикс пространства имен узла из URI пространства имен
    • DomNode::next_sibling - Возвращает следующего брата узла
    • DomNode::node_name - Возвращает имя узла
    • DomNode::node_type - Возвращает тип узла
    • DomNode::node_value - Возвращает значение узла
    • DOMNode::normalize - Нормализует узел
    • DomNode::owner_document - Возвращает документ, которому принадлежит этот узел
    • DomNode::parent_node - Возвращает родителя узла
    • DomNode::prefix - Возвращает префикс пространства имен узла
    • DomNode::previous_sibling - Возвращает предыдущего брата узла
    • DOMNode::removeChild - Удаляет дочерний узел из списка потомков
    • DomNode::remove_child - Удаляет сына из списка сыновей
    • DOMNode::replaceChild - Заменяет дочерний узел
    • DomNode::replace_child - Замена сына
    • DomNode::replace_node - Заменяет узел
    • DomNode::set_content - Устанавливает содержимое узла
    • DomNode::set_name - Устанавливает имя узла
    • DomNode::set_namespace - Устанавливает пространство имен узла
    • DomNode::unlink_node - Удаляет узел
    • DOMNodelist::item - Извлекает узел с заданным индексом
    • DomProcessingInstruction::data - Возвращает данные узла ProcessingInstruction
    • DomProcessingInstruction::target - Возвращает цель узла ProcessingInstruction
    • DOMProcessingInstruction::__construct - Создает новый объект классаDOMProcessingInstruction
    • DOMText::isWhitespaceInElementContent - Определяет, содержит ли текстовый узел пробел в содержимом
    • DOMText::splitText - Разделяет узел на два, начиная с заданной позиции
    • DOMText::__construct - Создает объект класса DOMText
    • domxml_new_doc - Создает новый пустой XML документ
    • domxml_open_file - Создает объект DOM из XML файла
    • domxml_open_mem - Создает объект DOM XML документа
    • domxml_version - Получает номер версии XML библиотеки
    • domxml_xmltree - Создает дерево объектов PHP из XML документа
    • domxml_xslt_stylesheet - Создает объект DomXsltStylesheet из строки XSL
    • domxml_xslt_stylesheet_doc - Создает объект класса DomXsltStylesheet из объекта DomDocument
    • domxml_xslt_stylesheet_file - Создает объект DomXsltStylesheet из XML файла
    • domxml_xslt_version - Получает версию XSLT библиотеки
    • DOMXPath::evaluate - Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно
    • DOMXPath::query - Выполняет заданное XPath выражение
    • DOMXPath::registerNamespace - Ассоциирует пространство имен с объектом DOMXPath
    • DOMXPath::registerPhpFunctions - Регистрация функций PHP как XPath функций
    • DOMXPath::__construct - Создает новый объект класса DOMXPath
    • DomXsltStylesheet::process - Применяет XSLT-преобразование к объекту DomDocument
    • DomXsltStylesheet::result_dump_file - Сохраняет результат XSLT-Преобразования в файл
    • DomXsltStylesheet::result_dump_mem - Представляет результат XSLT-Преобразования в виде строки
    • dom_import_simplexml - Получает объект класса DOMElement из объекта класса SimpleXMLElement
    • dotnet_load - Загружает модуль DOTNET
    • doubleval - Псевдоним floatval
  • e
    • each - Возвращает текущую пару ключ/значение из массива и смещает его указатель
    • easter_date - Метка времени Unix соответствующая полуночи на Пасху в заданном году
    • easter_days - Получение количества дней между 21 марта и Пасхой в заданном году
    • echo - Выводит одну или более строк
    • eio_busy - Artificially increase load. Could be useful in tests, benchmarking.
    • eio_cancel - Cancels a request
    • eio_chmod - Change file/direcrory permissions.
    • eio_chown - Change file/direcrory permissions.
    • eio_close - Close file
    • eio_custom - Execute custom request like any other eio_* call.
    • eio_dup2 - Duplicate a file descriptor
    • eio_event_loop - Polls libeio until all requests proceeded
    • eio_fallocate - Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod - Change file permissions.
    • eio_fchown - Change file ownership
    • eio_fdatasync - Synchronize a file's in-core state with storage device.
    • eio_fstat - Get file status
    • eio_fstatvfs - Get file system statistics
    • eio_fsync - Synchronize a file's in-core state with storage device
    • eio_ftruncate - Truncate a file
    • eio_futime - Change file last access and modification times
    • eio_get_event_stream - Get stream representing a variable used in internal communications with libeio.
    • eio_grp - Createsa request group.
    • eio_grp_add - Adds a request to the request group.
    • eio_grp_cancel - Cancels a request group
    • eio_grp_limit - Set group limit
    • eio_link - Create a hardlink for file
    • eio_lstat - Get file status
    • eio_mkdir - Create directory
    • eio_mknod - Create a special or ordinary file.
    • eio_nop - Does nothing, except go through the whole request cycle.
    • eio_npending - Returns number of finished, but unhandled requests
    • eio_nready - Returns number of not-yet handled requests
    • eio_nreqs - Returns number of requests to be processed
    • eio_nthreads - Returns number of threads currently in use
    • eio_open - Opens a file
    • eio_poll - Can be to be called whenever there are pending requests that need finishing.
    • eio_read - Read from a file descriptor at given offset.
    • eio_readahead - Perform file readahead into page cache
    • eio_readdir - Reads through a whole directory
    • eio_readlink - Read value of a symbolic link.
    • eio_realpath - Get the canonicalized absolute pathname.
    • eio_rename - Change the name or location of a file.
    • eio_rmdir - Remove a directory
    • eio_sendfile - Transfer data between file descriptors
    • eio_set_max_idle - Set maximum number of idle threads.
    • eio_set_max_parallel - Set maximum parallel threads
    • eio_set_max_poll_reqs - Set maximum number of requests processed in a poll.
    • eio_set_max_poll_time - Set maximum poll time
    • eio_set_min_parallel - Set minimum parallel thread number
    • eio_stat - Get file status
    • eio_statvfs - Get file system statistics
    • eio_symlink - Create a symbolic link
    • eio_sync - Commit buffer cache to disk
    • eio_syncfs - Calls Linux' syncfs syscall, if available
    • eio_sync_file_range - Sync a file segment with disk
    • eio_truncate - Truncate a file
    • eio_unlink - Delete a name and possibly the file it refers to
    • eio_utime - Change file last access and modification times.
    • eio_write - Write to file
    • empty - Проверяет, пуста ли переменная
    • EmptyIterator::current - Метод current()
    • EmptyIterator::key - Метод key()
    • EmptyIterator::next - Метод next()
    • EmptyIterator::rewind - Метод rewind()
    • EmptyIterator::valid - Метод valid()
    • enchant_broker_describe - Enumerates the Enchant providers
    • enchant_broker_dict_exists - Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free - Free the broker resource and its dictionnaries
    • enchant_broker_free_dict - Free a dictionary resource
    • enchant_broker_get_error - Returns the last error of the broker
    • enchant_broker_init - create a new broker object capable of requesting
    • enchant_broker_list_dicts - Returns a list of available dictionaries
    • enchant_broker_request_dict - create a new dictionary using a tag
    • enchant_broker_request_pwl_dict - creates a dictionary using a PWL file
    • enchant_broker_set_ordering - Declares a preference of dictionaries to use for the language
    • enchant_dict_add_to_personal - add a word to personal word list
    • enchant_dict_add_to_session - add 'word' to this spell-checking session
    • enchant_dict_check - Check whether a word is correctly spelled or not
    • enchant_dict_describe - Describes an individual dictionary
    • enchant_dict_get_error - Returns the last error of the current spelling-session
    • enchant_dict_is_in_session - whether or not 'word' exists in this spelling-session
    • enchant_dict_quick_check - Check the word is correctly spelled and provide suggestions
    • enchant_dict_store_replacement - Add a correction for a word
    • enchant_dict_suggest - Will return a list of values if any of those pre-conditions are not met
    • end - Устанавливает внутренний указатель массива на его последний элемент
    • ereg - Совпадение с регулярным выражением
    • eregi - Совпадение с регулярным выражением без учёта регистра
    • eregi_replace - Осуществляет замену по регулярному выражению без учета регистра
    • ereg_replace - Осуществляет замену по регулярному выражению
    • ErrorException::getSeverity - Возвращает критичность исключения
    • ErrorException::__construct - Создание исключения
    • error_get_last - Получение информации о последней произошедшей ошибке
    • error_log - Отправляет сообщение об ошибке
    • error_reporting - Задает, какие ошибки PHP попадут в отчет
    • escapeshellarg - Экранирует строку для того, чтобы она могла быть использована как аргумент командной строки
    • escapeshellcmd - Экранирует метасимволы командной строки
    • eval - Исполняет код PHP, содержащейся в строке
    • event_add - Add an event to the set of monitored events
    • event_base_free - Destroy event base
    • event_base_loop - Handle events
    • event_base_loopbreak - Abort event loop
    • event_base_loopexit - Exit loop after a time
    • event_base_new - Create and initialize new event base
    • event_base_priority_init - Set the number of event priority levels
    • event_base_set - Associate event base with an event
    • event_buffer_base_set - Associate buffered event with an event base
    • event_buffer_disable - Disable a buffered event
    • event_buffer_enable - Enable a buffered event
    • event_buffer_fd_set - Change a buffered event file descriptor
    • event_buffer_free - Destroy buffered event
    • event_buffer_new - Create new buffered event
    • event_buffer_priority_set - Assign a priority to a buffered event
    • event_buffer_read - Read data from a buffered event
    • event_buffer_set_callback - Set or reset callbacks for a buffered event
    • event_buffer_timeout_set - Set read and write timeouts for a buffered event
    • event_buffer_watermark_set - Set the watermarks for read and write events
    • event_buffer_write - Write data to a buffered event
    • event_del - Remove an event from the set of monitored events
    • event_free - Free event resource
    • event_new - Create new event
    • event_set - Prepare an event
    • Examples with PDO_4D - Examples PDO_4D
    • Exception::getCode - Получает код исключения
    • Exception::getFile - Получает файл, в котором возникло исключение
    • Exception::getLine - Получает строку, в которой возникло исключение
    • Exception::getMessage - Получает сообщение исключения
    • Exception::getPrevious - Возвращает предыдущее исключение
    • Exception::getTrace - Получает трассировку стека
    • Exception::getTraceAsString - Получает трассировку стека в виде строки
    • Exception::__clone - Клонировать исключение
    • Exception::__construct - Создать исключение
    • Exception::__toString - Строковое представление исключения
    • exec - Исполняет внешнюю программу
    • exif_imagetype - Определение типа изображения
    • exif_read_data - Читает EXIF-заголовки JPEG и TIFF изображений
    • exif_tagname - Получение имени заголовка по его индексу
    • exif_thumbnail - Получает встроенный эскиз TIFF или JPEG изображения
    • exit - Выводит сообщение и прекращает выполнение текущего скрипта
    • exp - Вычисляет число e в степени
    • expect:// - Потоки для взаимодействия с процессами
    • expect_expectl - Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen - Execute command via Bourne shell, and open the PTY stream to the process
    • explode - Разбивает строку с помощью разделителя
    • expm1 - Возвращает exp(number) - 1, рассчитанное таким образом, что результат точен, даже если number близок к нулю.
    • extension_loaded - Определение, загружено ли расширение
    • extract - Импортирует переменные из массива в текущую таблицу символов
    • ezmlm_hash - Вычисляет хеш-сумму, необходимую для EZMLM
  • f
    • fam_cancel_monitor - Terminate monitoring
    • fam_close - Close FAM connection
    • fam_monitor_collection - Monitor a collection of files in a directory for changes
    • fam_monitor_directory - Monitor a directory for changes
    • fam_monitor_file - Monitor a regular file for changes
    • fam_next_event - Get next pending FAM event
    • fam_open - Open connection to FAM daemon
    • fam_pending - Check for pending FAM events
    • fam_resume_monitor - Resume suspended monitoring
    • fam_suspend_monitor - Temporarily suspend monitoring
    • fbsql_affected_rows - Возвращет число затронутых строк в предыдущем FrontBase действии
    • fbsql_autocommit - Enable or disable autocommit
    • fbsql_blob_size - Get the size of a BLOB
    • fbsql_change_user - Change logged in user of the active connection
    • fbsql_clob_size - Get the size of a CLOB
    • fbsql_close - Close FrontBase connection
    • fbsql_commit - Commits a transaction to the database
    • fbsql_connect - Open a connection to a FrontBase Server
    • fbsql_create_blob - Create a BLOB
    • fbsql_create_clob - Create a CLOB
    • fbsql_create_db - Create a FrontBase database
    • fbsql_database - Get or set the database name used with a connection
    • fbsql_database_password - Sets or retrieves the password for a FrontBase database
    • fbsql_data_seek - Move internal result pointer
    • fbsql_db_query - Send a FrontBase query
    • fbsql_db_status - Get the status for a given database
    • fbsql_drop_db - Drop (delete) a FrontBase database
    • fbsql_errno - Returns the error number from previous operation
    • fbsql_error - Returns the error message from previous operation
    • fbsql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • fbsql_fetch_assoc - Fetch a result row as an associative array
    • fbsql_fetch_field - Get column information from a result and return as an object
    • fbsql_fetch_lengths - Get the length of each output in a result
    • fbsql_fetch_object - Fetch a result row as an object
    • fbsql_fetch_row - Get a result row as an enumerated array
    • fbsql_field_flags - Get the flags associated with the specified field in a result
    • fbsql_field_len - Returns the length of the specified field
    • fbsql_field_name - Get the name of the specified field in a result
    • fbsql_field_seek - Set result pointer to a specified field offset
    • fbsql_field_table - Get name of the table the specified field is in
    • fbsql_field_type - Get the type of the specified field in a result
    • fbsql_free_result - Free result memory
    • fbsql_get_autostart_info - Описание
    • fbsql_hostname - Get or set the host name used with a connection
    • fbsql_insert_id - Get the id generated from the previous INSERT operation
    • fbsql_list_dbs - List databases available on a FrontBase server
    • fbsql_list_fields - List FrontBase result fields
    • fbsql_list_tables - List tables in a FrontBase database
    • fbsql_next_result - Move the internal result pointer to the next result
    • fbsql_num_fields - Get number of fields in result
    • fbsql_num_rows - Get number of rows in result
    • fbsql_password - Get or set the user password used with a connection
    • fbsql_pconnect - Open a persistent connection to a FrontBase Server
    • fbsql_query - Send a FrontBase query
    • fbsql_read_blob - Read a BLOB from the database
    • fbsql_read_clob - Read a CLOB from the database
    • fbsql_result - Get result data
    • fbsql_rollback - Rollback a transaction to the database
    • fbsql_rows_fetched - Get the number of rows affected by the last statement
    • fbsql_select_db - Select a FrontBase database
    • fbsql_set_characterset - Change input/output character set
    • fbsql_set_lob_mode - Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password - Change the password for a given user
    • fbsql_set_transaction - Set the transaction locking and isolation
    • fbsql_start_db - Start a database on local or remote server
    • fbsql_stop_db - Stop a database on local or remote server
    • fbsql_tablename - Псевдоним fbsql_table_name
    • fbsql_table_name - Get table name of field
    • fbsql_username - Get or set the username for the connection
    • fbsql_warnings - Enable or disable FrontBase warnings
    • fclose - Закрывает открытый дескриптор файла
    • fdf_add_doc_javascript - Adds javascript code to the FDF document
    • fdf_add_template - Добавляет шаблон в FDF-документ
    • fdf_close - Закрывает FDF-документ
    • fdf_create - Create a new FDF document
    • fdf_enum_values - Call a user defined function for each document value
    • fdf_errno - Return error code for last fdf operation
    • fdf_error - Return error description for FDF error code
    • fdf_get_ap - Get the appearance of a field
    • fdf_get_attachment - Extracts uploaded file embedded in the FDF
    • fdf_get_encoding - Получает значение ключа /Encoding
    • fdf_get_file - Получает значение ключа /F
    • fdf_get_flags - Gets the flags of a field
    • fdf_get_opt - Gets a value from the opt array of a field
    • fdf_get_status - Получает значение ключа /STATUS
    • fdf_get_value - Get the value of a field
    • fdf_get_version - Gets version number for FDF API or file
    • fdf_header - Sets FDF-specific output headers
    • fdf_next_field_name - Get the next field name
    • fdf_open - Open a FDF document
    • fdf_open_string - Read a FDF document from a string
    • fdf_remove_item - Sets target frame for form
    • fdf_save - Save a FDF document
    • fdf_save_string - Returns the FDF document as a string
    • fdf_set_ap - Set the appearance of a field
    • fdf_set_encoding - Sets FDF character encoding
    • fdf_set_file - Set PDF document to display FDF data in
    • fdf_set_flags - Sets a flag of a field
    • fdf_set_javascript_action - Sets an javascript action of a field
    • fdf_set_on_import_javascript - Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt - Sets an option of a field
    • fdf_set_status - Set the value of the /STATUS key
    • fdf_set_submit_form_action - Sets a submit form action of a field
    • fdf_set_target_frame - Set target frame for form display
    • fdf_set_value - Set the value of a field
    • fdf_set_version - Sets version number for a FDF file
    • feof - Проверяет, достигнут ли конец файла
    • fflush - Сбрасывает буфер вывода в файл
    • fgetc - Считывает символ из файла
    • fgetcsv - Читает строку из файла и производит разбор данных CSV
    • fgets - Читает строку из файла
    • fgetss - Прочитать строку из файла и отбросить HTML-теги
    • file - Читает содержимое файла и помещает его в массив
    • file:// - Доступ к локальной файловой системе
    • fileatime - Возвращает время последнего доступа к файлу
    • filectime - Возвращает время изменения индексного дескриптора файла
    • filegroup - Получает идентификатор группы файла
    • fileinode - Возвращает индексный дескриптор файла
    • filemtime - Возвращает время последнего изменения файла
    • fileowner - Возвращает идентификатор владельца файла
    • fileperms - Возвращает информацию о правах на файл
    • filepro - Read and verify the map file
    • filepro_fieldcount - Find out how many fields are in a filePro database
    • filepro_fieldname - Gets the name of a field
    • filepro_fieldtype - Gets the type of a field
    • filepro_fieldwidth - Gets the width of a field
    • filepro_retrieve - Retrieves data from a filePro database
    • filepro_rowcount - Find out how many rows are in a filePro database
    • filesize - Возвращает размер файла
    • FilesystemIterator::current - The current file
    • FilesystemIterator::getFlags - Get the handling flags
    • FilesystemIterator::key - Retrieve the key for the current file
    • FilesystemIterator::next - Move to the next file
    • FilesystemIterator::rewind - Rewinds back to the beginning
    • FilesystemIterator::setFlags - Sets handling flags
    • FilesystemIterator::__construct - Constructs a new filesystem iterator
    • filetype - Возвращает тип файла
    • file_exists - Проверяет наличие указанного файла или каталога
    • file_get_contents - Читает содержимое файла в строку
    • file_put_contents - Пишет строку в файл
    • FilterIterator::accept - Проверяет, является ли текущий элемент итератора допустимым
    • FilterIterator::current - Получает значение текущего элемента
    • FilterIterator::getInnerIterator - Получает внутренний итератор
    • FilterIterator::key - Получает текущий ключ
    • FilterIterator::next - Перемещает итератор к следующему элементу
    • FilterIterator::rewind - Возвращает итератор в начало
    • FilterIterator::valid - Проверяет, является ли текущий элемент допустимым
    • FilterIterator::__construct - Создает FilterIterator
    • filter_has_var - Проверяет существование переменной указанного типа
    • filter_id - Возвращает идентификатор, принадлежащий именованному фильтру
    • filter_input - Принимает переменную извне PHP и, при необходимости, фильтрует ее
    • filter_input_array - Принимает несколько переменных извне PHP и, при необходимости, фильтрует их
    • filter_list - Возвращает список всех поддерживаемых фильтров
    • filter_var - Фильтрует переменную с помощью определенного фильтра
    • filter_var_array - Принимает несколько переменных и, при необходимости, фильтрует их
    • finfo_buffer - Возвращает информацию о строке буфера
    • finfo_close - Закрывает ресурс Fileinfo
    • finfo_file - Возвращает информацио о файле
    • finfo_open - Создает ресурс Fileinfo
    • finfo_set_flags - Set libmagic configuration options
    • floatval - Возвращает значение переменной в виде числа с плавающей точкой
    • flock - Портируемая консультативная блокировка файлов
    • floor - Округляет дробь в меньшую сторону
    • flush - Сброс буфера вывода
    • fmod - Возвращает дробный остаток от деления по модулю
    • fnmatch - Проверяет совпадение имени файла с шаблоном
    • fopen - Открывает файл или URL
    • forward_static_call - Call a static method
    • forward_static_call_array - Call a static method and pass the arguments as array
    • fpassthru - Выводит все оставшиеся данные из файлового указателя
    • fprintf - Записывает отформатированную строку в поток
    • fputcsv - Форматирует строку в виде CSV и записывает её в файловый указатель
    • fputs - Псевдоним fwrite
    • fread - Бинарно-безопасное чтение файла
    • FrenchToJD - Преобразует дату Французского республиканского календаря в количество дней в Юлианском летоисчислении
    • fribidi_log2vis - Convert a logical string to a visual one
    • fscanf - Обрабатывает данные из файла в соответствии с форматом
    • fseek - Устанавливает смещение в файловом указателе
    • fsockopen - Open Internet or Unix domain socket connection
    • fstat - Получает информацию о файле используя открытый файловый указатель
    • ftell - Сообщает текущую позицию чтения/записи файла
    • ftok - Convert a pathname and a project identifier to a System V IPC key
    • ftp:// - Доступ к URL-адресам по протоколу FTP(s)
    • ftp_alloc - Резервирует место на диске для закачиваемого файла
    • ftp_cdup - Переходит в родительскую директорию
    • ftp_chdir - Изменяет текущую директорию на FTP сервере
    • ftp_chmod - Устанавливает права доступа к файлу
    • ftp_close - Закрывает соединение с FTP-сервером
    • ftp_connect - Устанавливает соединение с FTP-сервером
    • ftp_delete - Удаляет файл на FTP-сервере
    • ftp_exec - Запрашивает выполнение команды на FTP-сервере
    • ftp_fget - Скачивает файл с FTP-сервера и сохраняет его в предварительно открытом файле
    • ftp_fput - Загружает предварительно открытый файл на FTP-сервер
    • ftp_get - Загружает файл с FTP-сервера
    • ftp_get_option - Получает текущие параметры FTP соединения
    • ftp_login - Выполняет вход на FTP сервер
    • ftp_mdtm - Возвращает время последней модификации файла
    • ftp_mkdir - Создаёт директорию
    • ftp_nb_continue - Продолжает асинхронную операцию
    • ftp_nb_fget - Скачивает файл с FTP сервера в асинхронном режиме и сохраняет его в предварительно открытом файле
    • ftp_nb_fput - Загружает предварительно открытый файл на FTP-сервер в асинхронном режиме
    • ftp_nb_get - Скачивает файл с FTP-сервера в асинхронном режиме и сохраняет его в локальный файл
    • ftp_nb_put - Загружает файл на FTP сервер в асинхронном режиме
    • ftp_nlist - Возвращает список файлов в заданной директории
    • ftp_pasv - Включает или выключает пассивный режим
    • ftp_put - Загружает файл на FTP-сервер
    • ftp_pwd - Возвращает имя текущей директории
    • ftp_quit - Псевдоним ftp_close
    • ftp_raw - Отправляет произвольную команду FTP-серверу
    • ftp_rawlist - Возвращает подробный список файлов в заданной директории
    • ftp_rename - Переименовывает файл или директорию на FTP-сервере
    • ftp_rmdir - Удаляет директорию
    • ftp_set_option - Устанавливает параметры соединения с FTP сервером
    • ftp_site - Отправляет серверу команду SITE
    • ftp_size - Возвращает размер указанного файла
    • ftp_ssl_connect - Устанавливает соединение с FTP-сервером через SSL
    • ftp_systype - Возвращает тип операционной системы FTP-сервера
    • ftruncate - Урезает файл до указанной длинны
    • function_exists - Возвращает TRUE, если указанная функция определена
    • func_get_arg - Возвращает элемент из списка аргументов
    • func_get_args - Возвращает массив, содержащий аргументы функции
    • func_num_args - Возвращает количество аргументов, переданных функции
    • fwrite - Бинарно-безопасная запись в файл
  • g
    • gc_collect_cycles - Принудительный запуск сборщика мусора
    • gc_disable - Отключает сборщик циклических ссылок
    • gc_enable - Включает сборщик циклических ссылок
    • gc_enabled - Возвращает текущее состояние сборщика циклических ссылок
    • gd_info - Вывод информации о текущей установленной GD библиотеке
    • GearmanClient::addOptions - Добавить клиентские опции
    • GearmanClient::addServer - Добавить сервер задач для клиента
    • GearmanClient::addServers - Добавить список серверов задач для клиента
    • GearmanClient::addTask - Добавить задачу, которая будет выполнена в параллельном режиме
    • GearmanClient::addTaskBackground - Добавить фоновую задачу для работы в параллельном режиме
    • GearmanClient::addTaskHigh - Добавить высокоприоритетную задачу для работы в параллельном режиме
    • GearmanClient::addTaskHighBackground - Добавить высокоприоритетную фоновую задачу для работы в параллельном режиме
    • GearmanClient::addTaskLow - Добавить низкоприоритетную задачу для работы в параллельном режиме
    • GearmanClient::addTaskLowBackground - Добавить низкоприоритетную фоновую задачу для работы в параллельном режиме
    • GearmanClient::addTaskStatus - Добавить задачу для получения статуса
    • GearmanClient::clearCallbacks - Очистить все функции обратного вызова данной задачи
    • GearmanClient::clone - Создать копию объекта GearmanClient
    • GearmanClient::context - Возвращает контекст приложения
    • GearmanClient::data - Возвращает данные приложения (функция устарела)
    • GearmanClient::do - Выполняет одну задачу и возвращает результат [Устаревший метод]
    • GearmanClient::doBackground - Запускает выполнение задачи в фоновом режиме
    • GearmanClient::doHigh - Запускает на выполнение задачу с высоким приоритетом
    • GearmanClient::doHighBackground - Запускает на выполнение с высоким приоритетом задачу в фоновом режиме
    • GearmanClient::doJobHandle - Получить дескриптор выполняющейся задачи
    • GearmanClient::doLow - Запускает на выполнение задачу с низким приоритетом
    • GearmanClient::doLowBackground - Запускает на выполнение с низким приоритетом задачу в фоновом режиме
    • GearmanClient::doNormal - Run a single task and return a result
    • GearmanClient::doStatus - Get the status for the running task
    • GearmanClient::echo - Отправляет данные всем серверам заданий, чтобы проверить отклик [Устаревший метод]
    • GearmanClient::error - Вернуть строку ошибки для последней встретившейся ошибки
    • GearmanClient::getErrno - Получить значение errno
    • GearmanClient::jobStatus - Get the status of a background job
    • GearmanClient::ping - Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions - Удалить клиентские опции
    • GearmanClient::returnCode - Получить последний возвращённый код Gearman
    • GearmanClient::runTasks - Запустить список задач в параллельном режиме
    • GearmanClient::setClientCallback - Установить функцию обратного вызова, когда есть пакет данных для задачи (устаревший метод)
    • GearmanClient::setCompleteCallback - Установите функцию, которая будет вызвана по завершении задачи
    • GearmanClient::setContext - Установить данные приложения
    • GearmanClient::setCreatedCallback - Установить функцию обратного вызова, когда задача ставится в очередь
    • GearmanClient::setData - Установить данные приложения (устаревший метод)
    • GearmanClient::setDataCallback - Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback - Set a callback for worker exceptions
    • GearmanClient::setFailCallback - Set callback for job failure
    • GearmanClient::setOptions - Set client options
    • GearmanClient::setStatusCallback - Set a callback for collecting task status
    • GearmanClient::setTimeout - Set socket I/O activity timeout
    • GearmanClient::setWarningCallback - Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback - Set a callback for accepting incremental data updates
    • GearmanClient::timeout - Get current socket I/O activity timeout value
    • GearmanClient::__construct - Создать экземпляр GearmanClient
    • GearmanJob::complete - Send the result and complete status (deprecated)
    • GearmanJob::data - Send data for a running job (deprecated)
    • GearmanJob::exception - Send exception for running job (deprecated)
    • GearmanJob::fail - Send fail status (deprecated)
    • GearmanJob::functionName - Get function name
    • GearmanJob::handle - Get the job handle
    • GearmanJob::returnCode - Get last return code
    • GearmanJob::sendComplete - Send the result and complete status
    • GearmanJob::sendData - Send data for a running job
    • GearmanJob::sendException - Send exception for running job (exception)
    • GearmanJob::sendFail - Send fail status
    • GearmanJob::sendStatus - Send status
    • GearmanJob::sendWarning - Send a warning
    • GearmanJob::setReturn - Set a return value
    • GearmanJob::status - Send status (deprecated)
    • GearmanJob::unique - Get the unique identifier
    • GearmanJob::warning - Send a warning (deprecated)
    • GearmanJob::workload - Get workload
    • GearmanJob::workloadSize - Get size of work load
    • GearmanJob::__construct - Create a GearmanJob instance
    • GearmanTask::create - Create a task (deprecated)
    • GearmanTask::data - Get data returned for a task
    • GearmanTask::dataSize - Get the size of returned data
    • GearmanTask::function - Get associated function name (deprecated)
    • GearmanTask::functionName - Get associated function name
    • GearmanTask::isKnown - Determine if task is known
    • GearmanTask::isRunning - Test whether the task is currently running
    • GearmanTask::jobHandle - Get the job handle
    • GearmanTask::recvData - Read work or result data into a buffer for a task
    • GearmanTask::returnCode - Get the last return code
    • GearmanTask::sendData - Send data for a task (deprecated)
    • GearmanTask::sendWorkload - Send data for a task
    • GearmanTask::taskDenominator - Get completion percentage denominator
    • GearmanTask::taskNumerator - Get completion percentage numerator
    • GearmanTask::unique - Get the unique identifier for a task
    • GearmanTask::uuid - Get the unique identifier for a task (deprecated)
    • GearmanTask::__construct - Create a GearmanTask instance
    • GearmanWorker::addFunction - Register and add callback function
    • GearmanWorker::addOptions - Add worker options
    • GearmanWorker::addServer - Add a job server
    • GearmanWorker::addServers - Add job servers
    • GearmanWorker::clone - Create a copy of the worker
    • GearmanWorker::echo - Test job server response
    • GearmanWorker::error - Get the last error encountered
    • GearmanWorker::getErrno - Get errno
    • GearmanWorker::options - Get worker options
    • GearmanWorker::register - Register a function with the job server
    • GearmanWorker::removeOptions - Remove worker options
    • GearmanWorker::returnCode - Get last Gearman return code
    • GearmanWorker::setOptions - Set worker options
    • GearmanWorker::setTimeout - Set socket I/O activity timeout
    • GearmanWorker::timeout - Get socket I/O activity timeout
    • GearmanWorker::unregister - Unregister a function name with the job servers
    • GearmanWorker::unregisterAll - Unregister all function names with the job servers
    • GearmanWorker::wait - Wait for activity from one of the job servers
    • GearmanWorker::work - Wait for and perform jobs
    • GearmanWorker::__construct - Create a GearmanWorker instance
    • geoip_continent_code_by_name - Получить двухсимвольный код континента
    • geoip_country_code3_by_name - Получить трехсимвольный код страны
    • geoip_country_code_by_name - Получить двухсимвольный код страны
    • geoip_country_name_by_name - Получить полное название страны
    • geoip_database_info - Возвращает информацию о базе GeoIP
    • geoip_db_avail - Проверяет доступность базы GeoIP
    • geoip_db_filename - Возвращает имя файла соответствующей базы GeoIP
    • geoip_db_get_all_info - Возвращает подробную информацию обо всех типах базы GeoIP
    • geoip_id_by_name - Возвращает тип интернет соединения
    • geoip_isp_by_name - Возвращает имя Интернет провайдера (ISP)
    • geoip_org_by_name - Возвращает название организации, владеющей IP адресом
    • geoip_record_by_name - Возвращает подробную информацию об адресе, найденом в базе GeoIP
    • geoip_region_by_name - Возвращает коды страны и региона
    • geoip_region_name_by_code - Возвращает название региона для выбраной страны и кода региона
    • geoip_time_zone_by_country_and_region - Возвращает временную зону и код региона для некоторых стран
    • getallheaders - Возвращает все заголовки HTTP-запроса
    • getcwd - Получает имя текущего рабочего каталога
    • getdate - Возвращает информацию о дате/времени
    • getenv - Получение значения переменной окружения
    • gethostbyaddr - Получает доменное имя узла, соответствующее переданному IP-адресу
    • gethostbyname - Получает адрес IPv4, соответствующий переданному имени узла интернета
    • gethostbynamel - Возвращает список адресов IPv4, соответствующих переданному доменному имени узла
    • gethostname - Получает имя хоста
    • getimagesize - Получение размера изображения
    • getimagesizefromstring - Получение размера изображения из строки данных
    • getlastmod - Определение времени последней модификации страницы
    • getmxrr - Получает запись MX, соответствующую переданному доменному имени узла
    • getmygid - Получение GID владельца PHP скрипта
    • getmyinode - Получение значения inode текущего скрипта
    • getmypid - Получение ID процесса PHP
    • getmyuid - Получение UID владельца скрипта PHP
    • getopt - Извлечение параметров из списка аргументов командной строки
    • getprotobyname - Получает номер протокола по имени
    • getprotobynumber - Получает имя протокола по номеру
    • getrandmax - Вовзращает максимально возможное случайное число
    • getrusage - Получает информацию об использовании текущего ресурса
    • getservbyname - Получает номер порта, присвоенного Интернет службе и протоколу
    • getservbyport - Получает Интернет службу, соответствующую заданному порту и протоколу
    • gettext - Ищет сообщение в текущем домене
    • gettimeofday - Возвращает текущее время
    • gettype - Возвращает тип переменной
    • get_browser - Сообщает о возможностях браузера пользователя
    • get_called_class - Имя класса, полученное с помощью позднего статического связывания
    • get_cfg_var - Извлекает значение настройки конфигурации PHP
    • get_class - Возвращает имя класса, к которому принадлежит объект
    • get_class_methods - Возвращает массив имен методов класса
    • get_class_vars - Возвращает объявленные по умолчанию свойства класса
    • get_current_user - Получение имени владельца текущего PHP скрипта
    • get_declared_classes - Возвращает массив с именами объявленных классов
    • get_declared_interfaces - Возвращает массив всех объявленных интерфейсов
    • get_declared_traits - Returns an array of all declared traits
    • get_defined_constants - Возвращает ассоциативный массив с именами и значениями всех предопределенных констант
    • get_defined_functions - Возвращает массив всех определённых функций
    • get_defined_vars - Возвращает массив всех определенных переменных
    • get_extension_funcs - Возвращает массив имен функций модуля
    • get_headers - Возвращает все заголовки из ответа сервера на HTTP-запрос
    • get_html_translation_table - Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities
    • get_included_files - Возвращает массив имен включенных в скрипт файлов
    • get_include_path - Получение текущего значения настройки include_path
    • get_loaded_extensions - Возвращает массив имен всех скомпилированных и загруженных модулей
    • get_magic_quotes_gpc - Получение текущего значения настройки конфигурации magic_quotes_gpc
    • get_magic_quotes_runtime - Получение текущего значения настройки конфигурации magic_quotes_runtime
    • get_meta_tags - Извлекает из файла содержимое всех мета-тегов и возвращает как ассоциативный массив
    • get_object_vars - Возвращает свойства указанного объекта
    • get_parent_class - Возвращает имя родительского класса для объекта или класса
    • get_required_files - Псевдоним get_included_files
    • get_resource_type - Возвращает тип ресурса
    • glob - Находит файловые пути, совпадающие с шаблоном
    • glob:// - Нахождение путей, соответствующих шаблону
    • GlobIterator::count - Get the number of directories and files
    • GlobIterator::__construct - Construct a directory using glob
    • Gmagick::addimage - Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage - Adds random noise to the image
    • Gmagick::annotateimage - Annotates an image with text
    • Gmagick::blurimage - Adds blur filter to image
    • Gmagick::borderimage - Surrounds the image with a border
    • Gmagick::charcoalimage - Simulates a charcoal drawing
    • Gmagick::chopimage - Removes a region of an image and trims
    • Gmagick::clear - Clears all resources associated to Gmagick object
    • Gmagick::commentimage - Adds a comment to your image
    • Gmagick::compositeimage - Composite one image onto another
    • Gmagick::cropimage - Extracts a region of the image
    • Gmagick::cropthumbnailimage - Creates a crop thumbnail
    • Gmagick::current - The current purpose
    • Gmagick::cyclecolormapimage - Displaces an image's colormap
    • Gmagick::deconstructimages - Returns certain pixel differences between images
    • Gmagick::despeckleimage - The despeckleimage purpose
    • Gmagick::destroy - The destroy purpose
    • Gmagick::drawimage - Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage - Enhance edges within the image
    • Gmagick::embossimage - Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage - Improves the quality of a noisy image
    • Gmagick::equalizeimage - Equalizes the image histogram
    • Gmagick::flipimage - Creates a vertical mirror image
    • Gmagick::flopimage - The flopimage purpose
    • Gmagick::frameimage - Adds a simulated three-dimensional border
    • Gmagick::gammaimage - Gamma-corrects an image
    • Gmagick::getcopyright - Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename - The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor - Returns the image background color
    • Gmagick::getimageblueprimary - Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor - Returns the image border color
    • Gmagick::getimagechanneldepth - Gets the depth for a particular image channel
    • Gmagick::getimagecolors - Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace - Gets the image colorspace
    • Gmagick::getimagecompose - Returns the composite operator associated with the image
    • Gmagick::getimagedelay - Gets the image delay
    • Gmagick::getimagedepth - Gets the depth of the image
    • Gmagick::getimagedispose - Gets the image disposal method
    • Gmagick::getimageextrema - Gets the extrema for the image
    • Gmagick::getimagefilename - Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat - Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma - Gets the image gamma
    • Gmagick::getimagegreenprimary - Returns the chromaticy green primary point
    • Gmagick::getimageheight - Returns the image height
    • Gmagick::getimagehistogram - Gets the image histogram
    • Gmagick::getimageindex - Gets the index of the current active image
    • Gmagick::getimageinterlacescheme - Gets the image interlace scheme
    • Gmagick::getimageiterations - Gets the image iterations
    • Gmagick::getimagematte - Return if the image has a matte channel
    • Gmagick::getimagemattecolor - Returns the image matte color
    • Gmagick::getimageprofile - Returns the named image profile.
    • Gmagick::getimageredprimary - Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent - Gets the image rendering intent
    • Gmagick::getimageresolution - Gets the image X and Y resolution
    • Gmagick::getimagescene - Gets the image scene
    • Gmagick::getimagesignature - Generates an SHA-256 message digest
    • Gmagick::getimagetype - Gets the potential image type.
    • Gmagick::getimageunits - Gets the image units of resolution
    • Gmagick::getimagewhitepoint - Returns the chromaticity white point
    • Gmagick::getimagewidth - Returns the width of the image
    • Gmagick::getpackagename - Returns the GraphicsMagick package name.
    • Gmagick::getquantumdepth - Returns the Gmagick quantum depth as a string.
    • Gmagick::getreleasedate - Returns the GraphicsMagick release date as a string.
    • Gmagick::getsamplingfactors - Gets the horizontal and vertical sampling factor.
    • Gmagick::getsize - Returns the size associated with the Gmagick object
    • Gmagick::getversion - Returns the GraphicsMagick API version
    • Gmagick::hasnextimage - Checks if the object has more images
    • Gmagick::haspreviousimage - Checks if the object has a previous image
    • Gmagick::implodeimage - Creates a new image as a copy
    • Gmagick::labelimage - Adds a label to an image.
    • Gmagick::levelimage - Adjusts the levels of an image
    • Gmagick::magnifyimage - Scales an image proportionally 2x
    • Gmagick::mapimage - Replaces the colors of an image with the closest color from a reference image.
    • Gmagick::medianfilterimage - Applies a digital filter
    • Gmagick::minifyimage - Scales an image proportionally to half its size
    • Gmagick::modulateimage - Control the brightness, saturation, and hue
    • Gmagick::motionblurimage - Simulates motion blur
    • Gmagick::newimage - Creates a new image
    • Gmagick::nextimage - Moves to the next image
    • Gmagick::normalizeimage - Enhances the contrast of a color image
    • Gmagick::oilpaintimage - Simulates an oil painting
    • Gmagick::previousimage - Move to the previous image in the object
    • Gmagick::profileimage - Adds or removes a profile from an image
    • Gmagick::quantizeimage - Analyzes the colors within a reference image
    • Gmagick::quantizeimages - The quantizeimages purpose
    • Gmagick::queryfontmetrics - Returns an array representing the font metrics
    • Gmagick::queryfonts - Returns the configured fonts
    • Gmagick::queryformats - Returns formats supported by Gmagick.
    • Gmagick::radialblurimage - Radial blurs an image
    • Gmagick::raiseimage - Creates a simulated 3d button-like effect
    • Gmagick::read - Reads image from filename
    • Gmagick::readimage - Reads image from filename
    • Gmagick::readimageblob - Reads image from a binary string
    • Gmagick::readimagefile - The readimagefile purpose
    • Gmagick::reducenoiseimage - Smooths the contours of an image
    • Gmagick::removeimage - Removes an image from the image list
    • Gmagick::removeimageprofile - Removes the named image profile and returns it
    • Gmagick::resampleimage - Resample image to desired resolution
    • Gmagick::resizeimage - Scales an image
    • Gmagick::rollimage - Offsets an image
    • Gmagick::rotateimage - Rotates an image
    • Gmagick::scaleimage - Scales the size of an image
    • Gmagick::separateimagechannel - Separates a channel from the image
    • Gmagick::setfilename - Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor - Sets the image background color.
    • Gmagick::setimageblueprimary - Sets the image chromaticity blue primary point.
    • Gmagick::setimagebordercolor - Sets the image border color.
    • Gmagick::setimagechanneldepth - Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace - Sets the image colorspace
    • Gmagick::setimagecompose - Sets the image composite operator
    • Gmagick::setimagedelay - Sets the image delay
    • Gmagick::setimagedepth - Sets the image depth
    • Gmagick::setimagedispose - Sets the image disposal method
    • Gmagick::setimagefilename - Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat - Sets the format of a particular image
    • Gmagick::setimagegamma - Sets the image gamma
    • Gmagick::setimagegreenprimary - TSets the image chromaticity green primary point.
    • Gmagick::setimageindex - Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme - Sets the interlace scheme of the image.
    • Gmagick::setimageiterations - Sets the image iterations.
    • Gmagick::setimageprofile - Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary - Sets the image chromaticity red primary point.
    • Gmagick::setimagerenderingintent - Sets the image rendering intent
    • Gmagick::setimageresolution - Sets the image resolution
    • Gmagick::setimagescene - Sets the image scene
    • Gmagick::setimagetype - Sets the image type
    • Gmagick::setimageunits - Sets the image units of resolution.
    • Gmagick::setimagewhitepoint - Sets the image chromaticity white point.
    • Gmagick::setsamplingfactors - Sets the image sampling factors.
    • Gmagick::setsize - Sets the size of the Gmagick object
    • Gmagick::shearimage - Creating a parallelogram
    • Gmagick::solarizeimage - Applies a solarizing effect to the image
    • Gmagick::spreadimage - Randomly displaces each pixel in a block
    • Gmagick::stripimage - Strips an image of all profiles and comments
    • Gmagick::swirlimage - Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage - Changes the size of an image
    • Gmagick::trimimage - Remove edges from the image
    • Gmagick::write - Writes an image to the specified filename
    • Gmagick::writeimage - Writes an image to the specified filename
    • Gmagick::__construct - The Gmagick constructor
    • GmagickDraw::annotate - Draws text on the image
    • GmagickDraw::arc - Draws an arc
    • GmagickDraw::bezier - Draws a bezier curve
    • GmagickDraw::ellipse - Draws an ellipse on the image
    • GmagickDraw::getfillcolor - Returns the fill color
    • GmagickDraw::getfillopacity - Returns the opacity used when drawing
    • GmagickDraw::getfont - Returns the font
    • GmagickDraw::getfontsize - Returns the font pointsize
    • GmagickDraw::getfontstyle - Returns the font style
    • GmagickDraw::getfontweight - Returns the font weight
    • GmagickDraw::getstrokecolor - Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity - Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth - Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration - Returns the text decoration
    • GmagickDraw::gettextencoding - Returns the code set used for text annotations
    • GmagickDraw::line - The line purpose
    • GmagickDraw::point - Draws a point
    • GmagickDraw::polygon - Draws a polygon
    • GmagickDraw::polyline - Draws a polyline
    • GmagickDraw::rectangle - Draws a rectangle
    • GmagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle - Draws a rounded rectangle
    • GmagickDraw::scale - Adjusts the scaling factor
    • GmagickDraw::setfillcolor - Sets the fill color to be used for drawing filled objects.
    • GmagickDraw::setfillopacity - The setfillopacity purpose
    • GmagickDraw::setfont - Sets the fully-specified font to use when annotating with text.
    • GmagickDraw::setfontsize - Sets the font pointsize to use when annotating with text.
    • GmagickDraw::setfontstyle - Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight - Sets the font weight
    • GmagickDraw::setstrokecolor - Sets the color used for stroking object outlines.
    • GmagickDraw::setstrokeopacity - Specifies the opacity of stroked object outlines.
    • GmagickDraw::setstrokewidth - Sets the width of the stroke used to draw object outlines.
    • GmagickDraw::settextdecoration - Specifies a decoration
    • GmagickDraw::settextencoding - Specifies specifies the text code set
    • GmagickPixel::getcolor - Returns the color
    • GmagickPixel::getcolorcount - Returns the color count associated with this color
    • GmagickPixel::getcolorvalue - Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor - Sets the color
    • GmagickPixel::setcolorvalue - Sets the normalized value of one of the channels
    • GmagickPixel::__construct - The GmagickPixel constructor
    • gmdate - Форматирует дату/время по Гринвичу
    • gmmktime - Возвращает метку времени Unix для времени по Гринвичу
    • gmp_abs - Абсолютная величина
    • gmp_add - Сложение чисел
    • gmp_and - Побитовое И
    • gmp_clrbit - Сброс бита
    • gmp_cmp - Сравнение чисел
    • gmp_com - Вычисляет дополнение до единицы числа
    • gmp_div - Псевдоним gmp_div_q
    • gmp_divexact - Деление чисел без остатка
    • gmp_div_q - Деление чисел
    • gmp_div_qr - Деление чисел и получение частного и остатка
    • gmp_div_r - Остаток от деления чисел
    • gmp_fact - Факториал
    • gmp_gcd - Вычисление наибольшего общего делителя
    • gmp_gcdext - Вычисление НОД и множителей
    • gmp_hamdist - Расстояние Хэмминга
    • gmp_init - Создание GMP числа
    • gmp_intval - Преобразование числа GMP в целое число
    • gmp_invert - Инверсия остатка от деления
    • gmp_jacobi - Символ Якоби
    • gmp_legendre - Символ Лежандра
    • gmp_mod - Вычисление остатка от целочисленного деления
    • gmp_mul - Умножение чисел
    • gmp_neg - Изменение знака числа
    • gmp_nextprime - Поиск следующего простого числа
    • gmp_or - Побитовое ИЛИ
    • gmp_perfect_square - Проверка числа на точный квадрат
    • gmp_popcount - Количество единиц в двоичной записи числа
    • gmp_pow - Возводит число в степень
    • gmp_powm - Возводит число в степень и производит деление по модулю
    • gmp_prob_prime - Проверяет, является ли число "вероятно простым"
    • gmp_random - Случайное число
    • gmp_scan0 - Поиск нуля в числе
    • gmp_scan1 - Поиск единицы в числе
    • gmp_setbit - Установка бита
    • gmp_sign - Знак числа
    • gmp_sqrt - Вычисление квадратного корня
    • gmp_sqrtrem - Квадратный корень с остатком
    • gmp_strval - Преобразование GMP числа в строку
    • gmp_sub - Вычитание чисел
    • gmp_testbit - Проверка, установлен ли бит в 1
    • gmp_xor - Побитовое исключающее ИЛИ
    • gmstrftime - Форматирует дату/время по Гринвичу с учетом текущей локали
    • gnupg_adddecryptkey - Add a key for decryption
    • gnupg_addencryptkey - Добавляет ключ для шифрования
    • gnupg_addsignkey - Добавить ключ для подписания
    • gnupg_cleardecryptkeys - Удаляет все ключи, которые были установлены для расшифровки раньше
    • gnupg_clearencryptkeys - Удаляет все ключи, которые были установлены для шифрования раньше
    • gnupg_clearsignkeys - Удаляет все ключи, которые были установлены для подписания раньше
    • gnupg_decrypt - Расшифровывает переданный текст
    • gnupg_decryptverify - Расшифровывает и проверяет подпись переданного текста
    • gnupg_encrypt - Encrypts a given text
    • gnupg_encryptsign - Шифрует и подписывает переданный текст
    • gnupg_export - Экспортирует ключ
    • gnupg_geterror - Возвращает текст сообщения об ошибке, если функция не была выполнена
    • gnupg_getprotocol - Возвращает текущий активный протокол для всех операций
    • gnupg_import - Imports a key
    • gnupg_init - Инициализировать GnuPG
    • gnupg_keyinfo - Возвращает массив с информацией обо всех ключах, которые соответствуют заданному шаблону
    • gnupg_setarmor - Переключает вывод в текстовом или бинарном режиме
    • gnupg_seterrormode - Устанавливает режим отчетов об ошибках (error_reporting)
    • gnupg_setsignmode - Устанавливает режим подписывания
    • gnupg_sign - Подписывает переданный текст
    • gnupg_verify - Проверяет подпись текста
    • gopher_parsedir - Translate a gopher formatted directory entry into an associative array.
    • grapheme_extract - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
    • grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
    • grapheme_strlen - Get string length in grapheme units
    • grapheme_strpos - Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack.
    • grapheme_substr - Return part of a string
    • GregorianToJD - Преобразует дату по Григорианскому календарю в количество дней в Юлианском летоисчислении
    • gupnp_context_get_host_ip - Get the IP address
    • gupnp_context_get_port - Get the port
    • gupnp_context_get_subscription_timeout - Get the event subscription timeout
    • gupnp_context_host_path - Start hosting
    • gupnp_context_new - Create a new context
    • gupnp_context_set_subscription_timeout - Sets the event subscription timeout
    • gupnp_context_timeout_add - Sets a function to be called at regular intervals
    • gupnp_context_unhost_path - Stop hosting
    • gupnp_control_point_browse_start - Start browsing
    • gupnp_control_point_browse_stop - Stop browsing
    • gupnp_control_point_callback_set - Set control point callback
    • gupnp_control_point_new - Create a new control point
    • gupnp_device_action_callback_set - Set device callback function
    • gupnp_device_info_get - Get info of root device
    • gupnp_device_info_get_service - Get the service with type
    • gupnp_root_device_get_available - Check whether root device is available
    • gupnp_root_device_get_relative_location - Get the relative location of root device.
    • gupnp_root_device_new - Create a new root device
    • gupnp_root_device_set_available - Set whether or not root_device is available
    • gupnp_root_device_start - Start main loop
    • gupnp_root_device_stop - Stop main loop
    • gupnp_service_action_get - Retrieves the specified action arguments
    • gupnp_service_action_return - Return succesfully
    • gupnp_service_action_return_error - Return error code
    • gupnp_service_action_set - Sets the specified action return values
    • gupnp_service_freeze_notify - Freeze new notifications
    • gupnp_service_info_get - Get full info of service
    • gupnp_service_info_get_introspection - Get resource introspection of service
    • gupnp_service_introspection_get_state_variable - Returns the state variable data
    • gupnp_service_notify - Notifies listening clients
    • gupnp_service_proxy_action_get - Send action to the service and get value
    • gupnp_service_proxy_action_set - Send action to the service and set value
    • gupnp_service_proxy_add_notify - Sets up callback for variable change notification
    • gupnp_service_proxy_callback_set - Set service proxy callback for signal
    • gupnp_service_proxy_get_subscribed - Check whether subscription is valid to the service
    • gupnp_service_proxy_remove_notify - Cancels the variable change notification
    • gupnp_service_proxy_send_action - Send action with multiple parameters synchronously
    • gupnp_service_proxy_set_subscribed - (Un)subscribes to the service.
    • gupnp_service_thaw_notify - Sends out any pending notifications and stops queuing of new ones.
    • gzclose - Закрывает открытый gz-файл по его указателю
    • gzcompress - Сжимает строку
    • gzdecode - Распаковывает строку, упакованную с помощью gzip
    • gzdeflate - Сжимает строку
    • gzencode - Сжимает строку в формате gzip
    • gzeof - Проверяет, находится ли текущая позиция в конце (EOF) gz-файла
    • gzfile - Считывает весь gz-файл в массив
    • gzgetc - Возвращает символ из gz-файла
    • gzgets - Возвращает строку из gz-файла
    • gzgetss - Возвращает строку из gz-файла с удалёнными HTML-тегами
    • gzinflate - Распаковывает строку
    • gzopen - Открывает gz-файл
    • gzpassthru - Выводит все оставшиеся данные из указателя gz-файла.
    • gzputs - Псевдоним gzwrite
    • gzread - Бинарное чтение gz-файла
    • gzrewind - Перемещает указатель на позицию в gz-файле в начало
    • gzseek - Перемещает указатель на позицию в gz-файле
    • gztell - Возвращает текущую позицию для чтения/записи в gz-файле
    • gzuncompress - Распаковывает строку
    • gzwrite - Бинарная запись в gz-файл
  • h
    • HaruAnnotation::setBorderStyle - Set the border style of the annotation
    • HaruAnnotation::setHighlightMode - Set the highlighting mode of the annotation
    • HaruAnnotation::setIcon - Set the icon style of the annotation
    • HaruAnnotation::setOpened - Set the initial state of the annotation
    • HaruDestination::setFit - Set the appearance of the page to fit the window
    • HaruDestination::setFitB - Set the appearance of the page to fit the bounding box of the page within the window
    • HaruDestination::setFitBH - Set the appearance of the page to fit the width of the bounding box
    • HaruDestination::setFitBV - Set the appearance of the page to fit the height of the boudning box
    • HaruDestination::setFitH - Set the appearance of the page to fit the window width
    • HaruDestination::setFitR - Set the appearance of the page to fit the specified rectangle
    • HaruDestination::setFitV - Set the appearance of the page to fit the window height
    • HaruDestination::setXYZ - Set the appearance of the page
    • HaruDoc::addPage - Add new page to the document
    • HaruDoc::addPageLabel - Set the numbering style for the specified range of pages
    • HaruDoc::createOutline - Create a HaruOutline instance
    • HaruDoc::getCurrentEncoder - Get HaruEncoder currently used in the document
    • HaruDoc::getCurrentPage - Return current page of the document
    • HaruDoc::getEncoder - Get HaruEncoder instance for the specified encoding
    • HaruDoc::getFont - Get HaruFont instance
    • HaruDoc::getInfoAttr - Get current value of the specified document attribute
    • HaruDoc::getPageLayout - Get current page layout
    • HaruDoc::getPageMode - Get current page mode
    • HaruDoc::getStreamSize - Get the size of the temporary stream
    • HaruDoc::insertPage - Insert new page just before the specified page
    • HaruDoc::loadJPEG - Load a JPEG image
    • HaruDoc::loadPNG - Load PNG image and return HaruImage instance
    • HaruDoc::loadRaw - Load a RAW image
    • HaruDoc::loadTTC - Load the font with the specified index from TTC file
    • HaruDoc::loadTTF - Load TTF font file
    • HaruDoc::loadType1 - Load Type1 font
    • HaruDoc::output - Write the document data to the output buffer
    • HaruDoc::readFromStream - Read data from the temporary stream
    • HaruDoc::resetError - Reset error state of the document handle
    • HaruDoc::resetStream - Rewind the temporary stream
    • HaruDoc::save - Save the document into the specified file
    • HaruDoc::saveToStream - Save the document into a temporary stream
    • HaruDoc::setCompressionMode - Set compression mode for the document
    • HaruDoc::setCurrentEncoder - Set the current encoder for the document
    • HaruDoc::setEncryptionMode - Set encryption mode for the document
    • HaruDoc::setInfoAttr - Set the info attribute of the document
    • HaruDoc::setInfoDateAttr - Set the datetime info attributes of the document
    • HaruDoc::setOpenAction - Define which page is shown when the document is opened
    • HaruDoc::setPageLayout - Set how pages should be displayed
    • HaruDoc::setPageMode - Set how the document should be displayed
    • HaruDoc::setPagesConfiguration - Set the number of pages per set of pages
    • HaruDoc::setPassword - Set owner and user passwords for the document
    • HaruDoc::setPermission - Set permissions for the document
    • HaruDoc::useCNSEncodings - Enable Chinese simplified encodings
    • HaruDoc::useCNSFonts - Enable builtin Chinese simplified fonts
    • HaruDoc::useCNTEncodings - Enable Chinese traditional encodings
    • HaruDoc::useCNTFonts - Enable builtin Chinese traditional fonts
    • HaruDoc::useJPEncodings - Enable Japanese encodings
    • HaruDoc::useJPFonts - Enable builtin Japanese fonts
    • HaruDoc::useKREncodings - Enable Korean encodings
    • HaruDoc::useKRFonts - Enable builtin Korean fonts
    • HaruDoc::__construct - Construct new HaruDoc instance
    • HaruEncoder::getByteType - Get the type of the byte in the text
    • HaruEncoder::getType - Get the type of the encoder
    • HaruEncoder::getUnicode - Convert the specified character to unicode
    • HaruEncoder::getWritingMode - Get the writing mode of the encoder
    • HaruFont::getAscent - Get the vertical ascent of the font
    • HaruFont::getCapHeight - Get the distance from the baseline of uppercase letters
    • HaruFont::getDescent - Get the vertical descent of the font
    • HaruFont::getEncodingName - Get the name of the encoding
    • HaruFont::getFontName - Get the name of the font
    • HaruFont::getTextWidth - Get the total width of the text, number of characters, number of words and number of spaces
    • HaruFont::getUnicodeWidth - Get the width of the character in the font
    • HaruFont::getXHeight - Get the distance from the baseline of lowercase letters
    • HaruFont::measureText - Calculate the number of characters which can be included within the specified width
    • HaruImage::getBitsPerComponent - Get the number of bits used to describe each color component of the image
    • HaruImage::getColorSpace - Get the name of the color space
    • HaruImage::getHeight - Get the height of the image
    • HaruImage::getSize - Get size of the image
    • HaruImage::getWidth - Get the width of the image
    • HaruImage::setColorMask - Set the color mask of the image
    • HaruImage::setMaskImage - Set the image mask
    • HaruOutline::setDestination - Set the destination for the outline
    • HaruOutline::setOpened - Set the initial state of the outline
    • HaruPage::arc - Append an arc to the current path
    • HaruPage::beginText - Begin a text object and set the current text position to (0,0)
    • HaruPage::circle - Append a circle to the current path
    • HaruPage::closePath - Append a straight line from the current point to the start point of the path
    • HaruPage::concat - Concatenate current transformation matrix of the page and the specified matrix
    • HaruPage::createDestination - Create new HaruDestination instance
    • HaruPage::createLinkAnnotation - Create new HaruAnnotation instance
    • HaruPage::createTextAnnotation - Create new HaruAnnotation instance
    • HaruPage::createURLAnnotation - Create and return new HaruAnnotation instance
    • HaruPage::curveTo - Append a Bezier curve to the current path
    • HaruPage::curveTo2 - Append a Bezier curve to the current path
    • HaruPage::curveTo3 - Append a Bezier curve to the current path
    • HaruPage::drawImage - Show image at the page
    • HaruPage::ellipse - Append an ellipse to the current path
    • HaruPage::endPath - End current path object without filling and painting operations
    • HaruPage::endText - End current text object
    • HaruPage::eofill - Fill current path using even-odd rule
    • HaruPage::eoFillStroke - Fill current path using even-odd rule, then paint the path
    • HaruPage::fill - Fill current path using nonzero winding number rule
    • HaruPage::fillStroke - Fill current path using nonzero winding number rule, then paint the path
    • HaruPage::getCharSpace - Get the current value of character spacing
    • HaruPage::getCMYKFill - Get the current filling color
    • HaruPage::getCMYKStroke - Get the current stroking color
    • HaruPage::getCurrentFont - Get the currently used font
    • HaruPage::getCurrentFontSize - Get the current font size
    • HaruPage::getCurrentPos - Get the current position for path painting
    • HaruPage::getCurrentTextPos - Get the current position for text printing
    • HaruPage::getDash - Get the current dash pattern
    • HaruPage::getFillingColorSpace - Get the current filling color space
    • HaruPage::getFlatness - Get the flatness of the page
    • HaruPage::getGMode - Get the current graphics mode
    • HaruPage::getGrayFill - Get the current filling color
    • HaruPage::getGrayStroke - Get the current stroking color
    • HaruPage::getHeight - Get the height of the page
    • HaruPage::getHorizontalScaling - Get the current value of horizontal scaling
    • HaruPage::getLineCap - Get the current line cap style
    • HaruPage::getLineJoin - Get the current line join style
    • HaruPage::getLineWidth - Get the current line width
    • HaruPage::getMiterLimit - Get the value of miter limit
    • HaruPage::getRGBFill - Get the current filling color
    • HaruPage::getRGBStroke - Get the current stroking color
    • HaruPage::getStrokingColorSpace - Get the current stroking color space
    • HaruPage::getTextLeading - Get the current value of line spacing
    • HaruPage::getTextMatrix - Get the current text transformation matrix of the page
    • HaruPage::getTextRenderingMode - Get the current text rendering mode
    • HaruPage::getTextRise - Get the current value of text rising
    • HaruPage::getTextWidth - Get the width of the text using current fontsize, character spacing and word spacing
    • HaruPage::getTransMatrix - Get the current transformation matrix of the page
    • HaruPage::getWidth - Get the width of the page
    • HaruPage::getWordSpace - Get the current value of word spacing
    • HaruPage::lineTo - Draw a line from the current point to the specified point
    • HaruPage::measureText - Calculate the number of characters which can be included within the specified width
    • HaruPage::moveTextPos - Move text position to the specified offset
    • HaruPage::moveTo - Set starting point for new drawing path
    • HaruPage::moveToNextLine - Move text position to the start of the next line
    • HaruPage::rectangle - Append a rectangle to the current path
    • HaruPage::setCharSpace - Set character spacing for the page
    • HaruPage::setCMYKFill - Set filling color for the page
    • HaruPage::setCMYKStroke - Set stroking color for the page
    • HaruPage::setDash - Set the dash pattern for the page
    • HaruPage::setFlatness - Set flatness for the page
    • HaruPage::setFontAndSize - Set font and fontsize for the page
    • HaruPage::setGrayFill - Set filling color for the page
    • HaruPage::setGrayStroke - Sets stroking color for the page
    • HaruPage::setHeight - Set height of the page
    • HaruPage::setHorizontalScaling - Set horizontal scaling for the page
    • HaruPage::setLineCap - Set the shape to be used at the ends of lines
    • HaruPage::setLineJoin - Set line join style for the page
    • HaruPage::setLineWidth - Set line width for the page
    • HaruPage::setMiterLimit - Set the current value of the miter limit of the page
    • HaruPage::setRGBFill - Set filling color for the page
    • HaruPage::setRGBStroke - Set stroking color for the page
    • HaruPage::setRotate - Set rotation angle of the page
    • HaruPage::setSize - Set size and direction of the page
    • HaruPage::setSlideShow - Set transition style for the page
    • HaruPage::setTextLeading - Set text leading (line spacing) for the page
    • HaruPage::setTextMatrix - Set the current text transformation matrix of the page
    • HaruPage::setTextRenderingMode - Set text rendering mode for the page
    • HaruPage::setTextRise - Set the current value of text rising
    • HaruPage::setWidth - Set width of the page
    • HaruPage::setWordSpace - Set word spacing for the page
    • HaruPage::showText - Print text at the current position of the page
    • HaruPage::showTextNextLine - Move the current position to the start of the next line and print the text
    • HaruPage::stroke - Paint current path
    • HaruPage::textOut - Print the text on the specified position
    • HaruPage::textRect - Print the text inside the specified region
    • hash - Генерирует хеш-код (дайджест сообщения)
    • hash_algos - Возвращает список зарегистрированных алгоритмов хеширования
    • hash_copy - Копирует контекст хеширования
    • hash_file - Генерация хеш-значения, используя содержимое заданного файла
    • hash_final - Завершает инкриментальное хеширование и возвращает результат в виде хеш-кода
    • hash_hmac - Генерация хеш-кода на основе ключа, используя метод HMAC
    • hash_hmac_file - Генерация хэш-кода на основе ключа, используя метод HMAC и содержимое полученного файла
    • hash_init - Инициализация инкриментального контекста хеширования
    • hash_update - Добавляет данные в активный контекст хеширования
    • hash_update_file - Добавляет данные из файла в активный контекст хеширования
    • hash_update_stream - Добавляет данные из открытого потока в активный контекст хеширования
    • header - Send a raw HTTP header
    • headers_list - Возвращает список переданных (или готовых к передаче) заголовков
    • headers_sent - Проверяет были ли и куда отправлены заголовки
    • header_register_callback - Вызывает функцию заголовка (header)
    • header_remove - Удаляет предварительно установленные заголовки
    • hebrev - Преобразует текст на иврите из логической кодировки в визуальную
    • hebrevc - Преобразует текст на иврите из логической кодировки в визуальную с преобразованием перевода строки
    • hex2bin - Преобразует шестнадцатеричные данные в двоичные
    • hexdec - Переводит число из шестнадцатиричной системы счисления в десятичную
    • highlight_file - Подсветка синтаксиса файла
    • highlight_string - Подсветка синтаксиса строки
    • htmlentities - Преобразует все возможные символы в соответствующие HTML-сущности
    • htmlspecialchars - Преобразует специальные символы в HTML-сущности
    • htmlspecialchars_decode - Преобразует специальные HTML-сущности обратно в соответствующие символы
    • html_entity_decode - Преобразует все HTML-сущности в соответствующие символы
    • http:// - Доступ к URL-адресам по протоколу HTTP(s)
    • HttpDeflateStream::factory - HttpDeflateStream class factory
    • HttpDeflateStream::finish - Finalize deflate stream
    • HttpDeflateStream::flush - Flush deflate stream
    • HttpDeflateStream::update - Update deflate stream
    • HttpDeflateStream::__construct - HttpDeflateStream class constructor
    • HttpInflateStream::factory - HttpInflateStream class factory
    • HttpInflateStream::finish - Finalize inflate stream
    • HttpInflateStream::flush - Flush inflate stream
    • HttpInflateStream::update - Update inflate stream
    • HttpInflateStream::__construct - HttpInflateStream class constructor
    • HttpMessage::addHeaders - Add headers
    • HttpMessage::detach - Detach HttpMessage
    • HttpMessage::factory - Create HttpMessage from string
    • HttpMessage::fromEnv - Create HttpMessage from environment
    • HttpMessage::fromString - Create HttpMessage from string
    • HttpMessage::getBody - Get message body
    • HttpMessage::getHeader - Get header
    • HttpMessage::getHeaders - Get message headers
    • HttpMessage::getHttpVersion - Get HTTP version
    • HttpMessage::getParentMessage - Get parent message
    • HttpMessage::getRequestMethod - Get request method
    • HttpMessage::getRequestUrl - Get request URL
    • HttpMessage::getResponseCode - Get response code
    • HttpMessage::getResponseStatus - Get response status
    • HttpMessage::getType - Get message type
    • HttpMessage::guessContentType - Guess content type
    • HttpMessage::prepend - Prepend message(s)
    • HttpMessage::reverse - Reverse message chain
    • HttpMessage::send - Send message
    • HttpMessage::setBody - Set message body
    • HttpMessage::setHeaders - Set headers
    • HttpMessage::setHttpVersion - Set HTTP version
    • HttpMessage::setRequestMethod - Set request method
    • HttpMessage::setRequestUrl - Set request URL
    • HttpMessage::setResponseCode - Set response code
    • HttpMessage::setResponseStatus - Set response status
    • HttpMessage::setType - Set message type
    • HttpMessage::toMessageTypeObject - Create HTTP object regarding message type
    • HttpMessage::toString - Get string representation
    • HttpMessage::__construct - HttpMessage constructor
    • HttpQueryString::get - Get (part of) query string
    • HttpQueryString::mod - Modifiy query string copy
    • HttpQueryString::set - Set query string params
    • HttpQueryString::singleton - HttpQueryString singleton
    • HttpQueryString::toArray - Get query string as array
    • HttpQueryString::toString - Get query string
    • HttpQueryString::xlate - Change query strings charset
    • HttpQueryString::__construct - HttpQueryString constructor
    • HttpRequest::addCookies - Add cookies
    • HttpRequest::addHeaders - Add headers
    • HttpRequest::addPostFields - Add post fields
    • HttpRequest::addPostFile - Add post file
    • HttpRequest::addPutData - Add put data
    • HttpRequest::addQueryData - Add query data
    • HttpRequest::addRawPostData - Add raw post data
    • HttpRequest::addSslOptions - Add ssl options
    • HttpRequest::clearHistory - Clear history
    • HttpRequest::enableCookies - Enable cookies
    • HttpRequest::getContentType - Get content type
    • HttpRequest::getCookies - Get cookies
    • HttpRequest::getHeaders - Get headers
    • HttpRequest::getHistory - Get history
    • HttpRequest::getMethod - Get method
    • HttpRequest::getOptions - Get options
    • HttpRequest::getPostFields - Get post fields
    • HttpRequest::getPostFiles - Get post files
    • HttpRequest::getPutData - Get put data
    • HttpRequest::getPutFile - Get put file
    • HttpRequest::getQueryData - Get query data
    • HttpRequest::getRawPostData - Get raw post data
    • HttpRequest::getRawRequestMessage - Get raw request message
    • HttpRequest::getRawResponseMessage - Get raw response message
    • HttpRequest::getRequestMessage - Get request message
    • HttpRequest::getResponseBody - Get response body
    • HttpRequest::getResponseCode - Get response code
    • HttpRequest::getResponseCookies - Get response cookie(s)
    • HttpRequest::getResponseData - Get response data
    • HttpRequest::getResponseHeader - Get response header(s)
    • HttpRequest::getResponseInfo - Get response info
    • HttpRequest::getResponseMessage - Get response message
    • HttpRequest::getResponseStatus - Get response status
    • HttpRequest::getSslOptions - Get ssl options
    • HttpRequest::getUrl - Get url
    • HttpRequest::resetCookies - Reset cookies
    • HttpRequest::send - Send request
    • HttpRequest::setBody - Set request body to send, overwriting previously set request body.
    • HttpRequest::setContentType - Set content type
    • HttpRequest::setCookies - Set cookies
    • HttpRequest::setHeaders - Set headers
    • HttpRequest::setMethod - Set method
    • HttpRequest::setOptions - Set options
    • HttpRequest::setPostFields - Set post fields
    • HttpRequest::setPostFiles - Set post files
    • HttpRequest::setPutData - Set put data
    • HttpRequest::setPutFile - Set put file
    • HttpRequest::setQueryData - Set query data
    • HttpRequest::setRawPostData - Set raw post data
    • HttpRequest::setSslOptions - Set ssl options
    • HttpRequest::setUrl - Set URL
    • HttpRequest::__construct - HttpRequest constructor
    • HttpRequestPool::attach - Attach HttpRequest
    • HttpRequestPool::detach - Detach HttpRequest
    • HttpRequestPool::getAttachedRequests - Get attached requests
    • HttpRequestPool::getFinishedRequests - Get finished requests
    • HttpRequestPool::reset - Reset request pool
    • HttpRequestPool::send - Send all requests
    • HttpRequestPool::socketPerform - Perform socket actions
    • HttpRequestPool::socketSelect - Perform socket select
    • HttpRequestPool::__construct - HttpRequestPool constructor
    • HttpRequestPool::__destruct - HttpRequestPool destructor
    • HttpResponse::capture - Capture script output
    • HttpResponse::getBufferSize - Get buffer size
    • HttpResponse::getCache - Get cache
    • HttpResponse::getCacheControl - Get cache control
    • HttpResponse::getContentDisposition - Get content disposition
    • HttpResponse::getContentType - Get content type
    • HttpResponse::getData - Get data
    • HttpResponse::getETag - Get ETag
    • HttpResponse::getFile - Get file
    • HttpResponse::getGzip - Get gzip
    • HttpResponse::getHeader - Get header
    • HttpResponse::getLastModified - Get last modified
    • HttpResponse::getRequestBody - Get request body
    • HttpResponse::getRequestBodyStream - Получить поток тела запроса
    • HttpResponse::getRequestHeaders - Get request headers
    • HttpResponse::getStream - Get Stream
    • HttpResponse::getThrottleDelay - Get throttle delay
    • HttpResponse::guessContentType - Guess content type
    • HttpResponse::redirect - Redirect
    • HttpResponse::send - Send response
    • HttpResponse::setBufferSize - Set buffer size
    • HttpResponse::setCache - Set cache
    • HttpResponse::setCacheControl - Set cache control
    • HttpResponse::setContentDisposition - Set content disposition
    • HttpResponse::setContentType - Set content type
    • HttpResponse::setData - Set data
    • HttpResponse::setETag - Set ETag
    • HttpResponse::setFile - Set file
    • HttpResponse::setGzip - Set gzip
    • HttpResponse::setHeader - Set header
    • HttpResponse::setLastModified - Set last modified
    • HttpResponse::setStream - Set stream
    • HttpResponse::setThrottleDelay - Set throttle delay
    • HttpResponse::status - Send HTTP response status
    • http_build_cookie - Build cookie string
    • http_build_query - Генерирует URL-кодированную строку запроса
    • http_build_str - Build query string
    • http_build_url - Build a URL
    • http_cache_etag - Caching by ETag
    • http_cache_last_modified - Caching by last modification
    • http_chunked_decode - Decode chunked-encoded data
    • http_date - Compose HTTP RFC compliant date
    • http_deflate - Deflate data
    • http_get - Perform GET request
    • http_get_request_body - Get request body as string
    • http_get_request_body_stream - Get request body as stream
    • http_get_request_headers - Get request headers as array
    • http_head - Perform HEAD request
    • http_inflate - Inflate data
    • http_match_etag - Match ETag
    • http_match_modified - Match last modification
    • http_match_request_header - Match any header
    • http_negotiate_charset - Negotiate client's preferred character set
    • http_negotiate_content_type - Negotiate client's preferred content type
    • http_negotiate_language - Negotiate client's preferred language
    • http_parse_cookie - Parse HTTP cookie
    • http_parse_headers - Parse HTTP headers
    • http_parse_message - Parse HTTP messages
    • http_parse_params - Parse parameter list
    • http_persistent_handles_clean - Clean up persistent handles
    • http_persistent_handles_count - Stat persistent handles
    • http_persistent_handles_ident - Get/set ident of persistent handles
    • http_post_data - Perform POST request with pre-encoded data
    • http_post_fields - Perform POST request with data to be encoded
    • http_put_data - Perform PUT request with data
    • http_put_file - Perform PUT request with file
    • http_put_stream - Perform PUT request with stream
    • http_redirect - Issue HTTP redirect
    • http_request - Perform custom request
    • http_request_body_encode - Encode request body
    • http_request_method_exists - Check whether request method exists
    • http_request_method_name - Get request method name
    • http_request_method_register - Register request method
    • http_request_method_unregister - Unregister request method
    • http_response_code - Получает или устанавливает код ответа HTTP
    • http_send_content_disposition - Send Content-Disposition
    • http_send_content_type - Send Content-Type
    • http_send_data - Send arbitrary data
    • http_send_file - Send file
    • http_send_last_modified - Send Last-Modified
    • http_send_status - Send HTTP response status
    • http_send_stream - Send stream
    • http_support - Check built-in HTTP support
    • http_throttle - HTTP throttling
    • hwapi_attribute_new - Creates instance of class hw_api_attribute
    • hwapi_content_new - Create new instance of class hw_api_content
    • hwapi_hgcsp - Returns object of class hw_api
    • hwapi_object_new - Creates a new instance of class hwapi_object_new
    • hw_api::checkin - Checks in an object
    • hw_api::checkout - Checks out an object
    • hw_api::children - Returns children of an object
    • hw_api::content - Returns content of an object
    • hw_api::copy - Copies physically
    • hw_api::dbstat - Returns statistics about database server
    • hw_api::dcstat - Returns statistics about document cache server
    • hw_api::dstanchors - Returns a list of all destination anchors
    • hw_api::dstofsrcanchor - Returns destination of a source anchor
    • hw_api::find - Search for objects
    • hw_api::ftstat - Returns statistics about fulltext server
    • hw_api::hwstat - Returns statistics about Hyperwave server
    • hw_api::identify - Log into Hyperwave Server
    • hw_api::info - Returns information about server configuration
    • hw_api::insert - Inserts a new object
    • hw_api::insertanchor - Inserts a new object of type anchor
    • hw_api::insertcollection - Inserts a new object of type collection
    • hw_api::insertdocument - Inserts a new object of type document
    • hw_api::link - Creates a link to an object
    • hw_api::lock - Locks an object
    • hw_api::move - Moves object between collections
    • hw_api::object - Retrieve attribute information
    • hw_api::objectbyanchor - Returns the object an anchor belongs to
    • hw_api::parents - Returns parents of an object
    • hw_api::remove - Delete an object
    • hw_api::replace - Replaces an object
    • hw_api::setcommittedversion - Commits version other than last version
    • hw_api::srcanchors - Returns a list of all source anchors
    • hw_api::srcsofdst - Returns source of a destination object
    • hw_api::unlock - Unlocks a locked object
    • hw_api::user - Returns the own user object
    • hw_api::userlist - Returns a list of all logged in users
    • hw_api_attribute::key - Returns key of the attribute
    • hw_api_attribute::langdepvalue - Returns value for a given language
    • hw_api_attribute::value - Returns value of the attribute
    • hw_api_attribute::values - Returns all values of the attribute
    • hw_api_content::mimetype - Returns mimetype
    • hw_api_content::read - Read content
    • hw_api_error::count - Returns number of reasons
    • hw_api_error::reason - Returns reason of error
    • hw_api_object::assign - Clones object
    • hw_api_object::attreditable - Checks whether an attribute is editable
    • hw_api_object::count - Returns number of attributes
    • hw_api_object::insert - Inserts new attribute
    • hw_api_object::remove - Removes attribute
    • hw_api_object::title - Returns the title attribute
    • hw_api_object::value - Returns value of attribute
    • hw_api_reason::description - Returns description of reason
    • hw_api_reason::type - Returns type of reason
    • hw_Array2Objrec - Convert attributes from object array to object record
    • hw_changeobject - Changes attributes of an object (obsolete)
    • hw_Children - Object ids of children
    • hw_ChildrenObj - Object records of children
    • hw_Close - Closes the Hyperwave connection
    • hw_Connect - Opens a connection
    • hw_connection_info - Prints information about the connection to Hyperwave server
    • hw_cp - Copies objects
    • hw_Deleteobject - Deletes object
    • hw_DocByAnchor - Object id object belonging to anchor
    • hw_DocByAnchorObj - Object record object belonging to anchor
    • hw_Document_Attributes - Object record of hw_document
    • hw_Document_BodyTag - Body tag of hw_document
    • hw_Document_Content - Returns content of hw_document
    • hw_Document_SetContent - Sets/replaces content of hw_document
    • hw_Document_Size - Size of hw_document
    • hw_dummy - Hyperwave dummy function
    • hw_EditText - Retrieve text document
    • hw_Error - Error number
    • hw_ErrorMsg - Returns error message
    • hw_Free_Document - Frees hw_document
    • hw_GetAnchors - Object ids of anchors of document
    • hw_GetAnchorsObj - Object records of anchors of document
    • hw_GetAndLock - Return object record and lock object
    • hw_GetChildColl - Object ids of child collections
    • hw_GetChildCollObj - Object records of child collections
    • hw_GetChildDocColl - Object ids of child documents of collection
    • hw_GetChildDocCollObj - Object records of child documents of collection
    • hw_GetObject - Object record
    • hw_GetObjectByQuery - Search object
    • hw_GetObjectByQueryColl - Search object in collection
    • hw_GetObjectByQueryCollObj - Search object in collection
    • hw_GetObjectByQueryObj - Search object
    • hw_GetParents - Object ids of parents
    • hw_GetParentsObj - Object records of parents
    • hw_getrellink - Get link from source to dest relative to rootid
    • hw_GetRemote - Gets a remote document
    • hw_getremotechildren - Gets children of remote document
    • hw_GetSrcByDestObj - Returns anchors pointing at object
    • hw_GetText - Retrieve text document
    • hw_getusername - Name of currently logged in user
    • hw_Identify - Identifies as user
    • hw_InCollections - Check if object ids in collections
    • hw_Info - Info about connection
    • hw_InsColl - Insert collection
    • hw_InsDoc - Insert document
    • hw_insertanchors - Inserts only anchors into text
    • hw_InsertDocument - Upload any document
    • hw_InsertObject - Inserts an object record
    • hw_mapid - Maps global id on virtual local id
    • hw_Modifyobject - Modifies object record
    • hw_mv - Moves objects
    • hw_New_Document - Create new document
    • hw_objrec2array - Convert attributes from object record to object array
    • hw_Output_Document - Prints hw_document
    • hw_pConnect - Make a persistent database connection
    • hw_PipeDocument - Retrieve any document
    • hw_Root - Root object id
    • hw_setlinkroot - Set the id to which links are calculated
    • hw_stat - Returns status string
    • hw_Unlock - Unlock object
    • hw_Who - List of currently logged in users
    • hypot - Рассчитывает длину гипотенузы прямоугольного треугольника
  • i
    • ibase_add_user - Add a user to a security database (only for IB6 or later)
    • ibase_affected_rows - Return the number of rows that were affected by the previous query
    • ibase_backup - Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add - Add data into a newly created blob
    • ibase_blob_cancel - Cancel creating blob
    • ibase_blob_close - Close blob
    • ibase_blob_create - Create a new blob for adding data
    • ibase_blob_echo - Output blob contents to browser
    • ibase_blob_get - Get len bytes data from open blob
    • ibase_blob_import - Create blob, copy file in it, and close it
    • ibase_blob_info - Return blob length and other useful info
    • ibase_blob_open - Open blob for retrieving data parts
    • ibase_close - Close a connection to an InterBase database
    • ibase_commit - Commit a transaction
    • ibase_commit_ret - Commit a transaction without closing it
    • ibase_connect - Open a connection to an InterBase database
    • ibase_db_info - Request statistics about a database
    • ibase_delete_user - Delete a user from a security database (only for IB6 or later)
    • ibase_drop_db - Drops a database
    • ibase_errcode - Return an error code
    • ibase_errmsg - Return error messages
    • ibase_execute - Execute a previously prepared query
    • ibase_fetch_assoc - Fetch a result row from a query as an associative array
    • ibase_fetch_object - Get an object from a InterBase database
    • ibase_fetch_row - Fetch a row from an InterBase database
    • ibase_field_info - Get information about a field
    • ibase_free_event_handler - Cancels a registered event handler
    • ibase_free_query - Free memory allocated by a prepared query
    • ibase_free_result - Free a result set
    • ibase_gen_id - Increments the named generator and returns its new value
    • ibase_maintain_db - Execute a maintenance command on the database server
    • ibase_modify_user - Modify a user to a security database (only for IB6 or later)
    • ibase_name_result - Assigns a name to a result set
    • ibase_num_fields - Get the number of fields in a result set
    • ibase_num_params - Return the number of parameters in a prepared query
    • ibase_param_info - Return information about a parameter in a prepared query
    • ibase_pconnect - Open a persistent connection to an InterBase database
    • ibase_prepare - Prepare a query for later binding of parameter placeholders and execution
    • ibase_query - Execute a query on an InterBase database
    • ibase_restore - Initiates a restore task in the service manager and returns immediately
    • ibase_rollback - Roll back a transaction
    • ibase_rollback_ret - Roll back a transaction without closing it
    • ibase_server_info - Request information about a database server
    • ibase_service_attach - Connect to the service manager
    • ibase_service_detach - Disconnect from the service manager
    • ibase_set_event_handler - Register a callback function to be called when events are posted
    • ibase_timefmt - Sets the format of timestamp, date and time type columns returned from queries
    • ibase_trans - Begin a transaction
    • ibase_wait_event - Wait for an event to be posted by the database
    • iconv - Преобразование строки в требуемую кодировку
    • iconv_get_encoding - Получает текущее значение настроек преобразования кодировок
    • iconv_mime_decode - Декодирует поле MIME-заголовка
    • iconv_mime_decode_headers - Декодирует несколько полей заголовка MIME
    • iconv_mime_encode - Сжимает поле MIME-заголовка
    • iconv_set_encoding - Устанавливает значение для преобразования символов кодировки
    • iconv_strlen - Возвращает количество символов в строке
    • iconv_strpos - Возвращает позицию первого вхождения подстроки
    • iconv_strrpos - Возвращает позицию последнего вхождения подстроки
    • iconv_substr - Получение части строки
    • id3_get_frame_long_name - Возвращает длинное имя ID3v2 кадра
    • id3_get_frame_short_name - Возвращает короткое имя ID3v2 кадра
    • id3_get_genre_id - Возвращает идентификатор жанра
    • id3_get_genre_list - Возвращает все возможные значения жанра
    • id3_get_genre_name - Возвращает имя по идентификатору жанра
    • id3_get_tag - Возвращает всю информацию, сохранённую в ID3-теге
    • id3_get_version - Возвращает версию ID3-тега
    • id3_remove_tag - Удаляет существующий ID3-тег
    • id3_set_tag - Обновляет информацию в ID3 теге
    • idate - Преобразует локальное время/дату в целое число
    • idn_to_ascii - Convert domain name to IDNA ASCII form.
    • idn_to_unicode - Псевдоним idn_to_utf8
    • idn_to_utf8 - Convert domain name from IDNA ASCII to Unicode.
    • ifxus_close_slob - Deletes the slob object
    • ifxus_create_slob - Creates an slob object and opens it
    • ifxus_free_slob - Deletes the slob object
    • ifxus_open_slob - Opens an slob object
    • ifxus_read_slob - Reads nbytes of the slob object
    • ifxus_seek_slob - Sets the current file or seek position
    • ifxus_tell_slob - Returns the current file or seek position
    • ifxus_write_slob - Writes a string into the slob object
    • ifx_affected_rows - Get number of rows affected by a query
    • ifx_blobinfile_mode - Set the default blob mode for all select queries
    • ifx_byteasvarchar - Set the default byte mode
    • ifx_close - Close Informix connection
    • ifx_connect - Open Informix server connection
    • ifx_copy_blob - Duplicates the given blob object
    • ifx_create_blob - Creates an blob object
    • ifx_create_char - Creates an char object
    • ifx_do - Execute a previously prepared SQL-statement
    • ifx_error - Returns error code of last Informix call
    • ifx_errormsg - Returns error message of last Informix call
    • ifx_fetch_row - Get row as an associative array
    • ifx_fieldproperties - List of SQL fieldproperties
    • ifx_fieldtypes - List of Informix SQL fields
    • ifx_free_blob - Deletes the blob object
    • ifx_free_char - Deletes the char object
    • ifx_free_result - Releases resources for the query
    • ifx_getsqlca - Get the contents of sqlca.sqlerrd[0..5] after a query
    • ifx_get_blob - Return the content of a blob object
    • ifx_get_char - Return the content of the char object
    • ifx_htmltbl_result - Formats all rows of a query into a HTML table
    • ifx_nullformat - Sets the default return value on a fetch row
    • ifx_num_fields - Returns the number of columns in the query
    • ifx_num_rows - Count the rows already fetched from a query
    • ifx_pconnect - Open persistent Informix connection
    • ifx_prepare - Prepare an SQL-statement for execution
    • ifx_query - Send Informix query
    • ifx_textasvarchar - Set the default text mode
    • ifx_update_blob - Updates the content of the blob object
    • ifx_update_char - Updates the content of the char object
    • ignore_user_abort - Устанавливает, необходимо ли прерывать работу скрипта при отключении клиента
    • iis_add_server - Creates a new virtual web server
    • iis_get_dir_security - Gets Directory Security
    • iis_get_script_map - Gets script mapping on a virtual directory for a specific extension
    • iis_get_server_by_comment - Return the instance number associated with the Comment
    • iis_get_server_by_path - Return the instance number associated with the Path
    • iis_get_server_rights - Gets server rights
    • iis_get_service_state - Returns the state for the service defined by ServiceId
    • iis_remove_server - Removes the virtual web server indicated by ServerInstance
    • iis_set_app_settings - Creates application scope for a virtual directory
    • iis_set_dir_security - Sets Directory Security
    • iis_set_script_map - Sets script mapping on a virtual directory
    • iis_set_server_rights - Sets server rights
    • iis_start_server - Starts the virtual web server
    • iis_start_service - Starts the service defined by ServiceId
    • iis_stop_server - Stops the virtual web server
    • iis_stop_service - Stops the service defined by ServiceId
    • image2wbmp - Выводит изображение в браузер или пишет в файл
    • imagealphablending - Задание режима сопряжения цветов для изображения
    • imageantialias - Требуется ли применять функции сглаживания или нет
    • imagearc - Рисование дуги
    • imagechar - Рисование символа по горизонтали
    • imagecharup - Рисование символа вертикально
    • imagecolorallocate - Создание цвета для изображения
    • imagecolorallocatealpha - Создание цвета для изображения
    • imagecolorat - Получение индекса цвета пиксела
    • imagecolorclosest - Получение индекса цвета ближайшего к заданному
    • imagecolorclosestalpha - Получение индекса цвета ближайшего к заданному с учетом прозрачности
    • imagecolorclosesthwb - Получение индекса цвета, имеющего заданный тон, белизну и затемнение
    • imagecolordeallocate - Разрыв ассоциации переменной с цветом для заданного изображения
    • imagecolorexact - Получение индекса заданного цвета
    • imagecolorexactalpha - Получение индекса заданного цвета и альфа компонента
    • imagecolormatch - Делает цвета палитровой версии изображения более соответствующими truecolor версии
    • imagecolorresolve - Получает идентификатор конкретного цвета или его ближайший аналог
    • imagecolorresolvealpha - Получает идентификатор конкретного цвета и альфа компонента или его ближайший аналог
    • imagecolorset - Установка набора цветов для заданного индекса палитры
    • imagecolorsforindex - Получение цветов, соответствующих индексу
    • imagecolorstotal - Определение количества цветов в палитре изображения
    • imagecolortransparent - Определяет цвет как прозрачный
    • imageconvolution - Наложение искривляющей матрицы 3х3, используя коэффициент и смещение
    • imagecopy - Копирование части изображения
    • imagecopymerge - Копирует часть изображения с наложением
    • imagecopymergegray - Копирует часть изображения с наложением в градациях серого
    • imagecopyresampled - Копирование и изменение размера изображения с ресемплированием
    • imagecopyresized - Копирование и изменение размера части изображения
    • imagecreate - Создание нового палитрового изображения
    • imagecreatefromgd - Создание нового изображения на основе GD файла или URL
    • imagecreatefromgd2 - Создание нового изображения на основе GD2 или URL
    • imagecreatefromgd2part - Создание нового изображения на основе части GD2 файла или URL
    • imagecreatefromgif - Создает новое изображение из файла или URL
    • imagecreatefromjpeg - Создает новое изображение из файла или URL
    • imagecreatefrompng - Создает новое изображение из файла или URL
    • imagecreatefromstring - Создание нового изображения из потока представленного строкой
    • imagecreatefromwbmp - Создает новое изображение из файла или URL
    • imagecreatefromxbm - Создает новое изображение из файла или URL
    • imagecreatefromxpm - Создает новое изображение из файла или URL
    • imagecreatetruecolor - Создание нового полноцветного изображения
    • imagedashedline - Рисование пунктирной линии
    • imagedestroy - Уничтожение изображения
    • imageellipse - Рисование эллипса
    • imagefill - Заливка
    • imagefilledarc - Рисование и заливка дуги
    • imagefilledellipse - Рисование закрашенного эллипса
    • imagefilledpolygon - Рисование закрашенного многоугольника
    • imagefilledrectangle - Рисование закрашенного прямоугольника
    • imagefilltoborder - Заливка цветом
    • imagefilter - Применяет фильтр к изображению
    • imagefontheight - Получение высоты шрифта
    • imagefontwidth - Получение ширины шрифта
    • imageftbbox - Определение границ текста выводимого шрифтом freetype2
    • imagefttext - Нанесение текста на изображение, используя шрифты FreeType 2
    • imagegammacorrect - Применение гамма коррекции к GD изображению
    • imagegd - Вывод GD-изображения в браузер или в файл
    • imagegd2 - Вывод GD2 изображения в броузер или файл
    • imagegif - Выводит изображение в браузер или пишет в файл
    • imagegrabscreen - Захватывает изображение с экрана
    • imagegrabwindow - Захватывает изображение окна
    • imageinterlace - Включение или выключение интерлейсинга
    • imageistruecolor - Определяет, является ли изображение полноцветным
    • imagejpeg - Выводит изображение в браузер или пишет в файл
    • imagelayereffect - Установка флага альфа сопряжения для использования эффектов наложения изображений встроенной libgd библиотеки
    • imageline - Рисование линии
    • imageloadfont - Загрузка шрифта
    • imagepalettecopy - Копирование палитры из одного изображения в другое
    • imagepng - Вывод PNG изображения в броузер или файл
    • imagepolygon - Рисование многоугольника
    • imagepsbbox - Выдает параметры рамки, обрамляющей текст написанный шрифтом PostScript Type1
    • imagepsencodefont - Изменение вектора кодировки шрифта
    • imagepsextendfont - Растягивание или сжатие шрифта
    • imagepsfreefont - Освобождение памяти, занятой шрифтом PostScript Type
    • imagepsloadfont - Загрузка шрифта PostScript Type 1 из файла
    • imagepsslantfont - Наклон шрифта
    • imagepstext - Рисование текста поверх изображения, используя шрифты PostScript Type1
    • imagerectangle - Рисование прямоугольника
    • imagerotate - Поворот изображения с заданным углом
    • imagesavealpha - Установка флага сохранения всей информации альфа компонента (в противовес одноцветной прозрачности) и сохранение PNG изобаржения
    • imagesetbrush - Установка изображения (кисти), посредством которого будут рисоваться линии
    • imagesetpixel - Рисование точки
    • imagesetstyle - Установка стиля рисования линий
    • imagesetthickness - Установка толщины линий
    • imagesettile - Установка изображения, которое будет использовано в качестве элемента мозаичной заливки
    • imagestring - Рисование строки текста горизонтально
    • imagestringup - Рисование строки текста вертикально
    • imagesx - Получение ширины изображения
    • imagesy - Получение высоты изображения
    • imagetruecolortopalette - Преобразование полноцветного изображения в палитровое
    • imagettfbbox - Получение параметров рамки обрамляющей текст написанный TrueType шрифтом
    • imagettftext - Рисование текста на изображении шрифтом TrueType
    • imagetypes - Возвращает список типов изображений, поддерживаемых PHP сборкой
    • imagewbmp - Выводит изображение в браузер или пишет в файл
    • imagexbm - Вывод XBM изображения в броузер или файл
    • image_type_to_extension - Получение расширения файла для типа изображения
    • image_type_to_mime_type - Получение Mime-типа для типа изображения, возвращаемого функциями getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • Imagick::adaptiveBlurImage - Добавляет адаптивный фильтр размытия к изображению
    • Imagick::adaptiveResizeImage - Адаптивное изменение размера изображения с данными триангуляции
    • Imagick::adaptiveSharpenImage - Адаптивное изменение резкости изображения
    • Imagick::adaptiveThresholdImage - Выбор порога для каждого пикселя в зависимости от диапазона интенсивности
    • Imagick::addImage - Добавляет новое изображение к списку изображений объекта Imagick
    • Imagick::addNoiseImage - Накладывает случайный шум на изображение
    • Imagick::affineTransformImage - Преобразование изображения
    • Imagick::animateImages - Анимация одного или нескольких изображений
    • Imagick::annotateImage - Добавляет текстовый комментарий на изображение
    • Imagick::appendImages - Объединяет набор изображений
    • Imagick::averageImages - Усредняет набор изображений
    • Imagick::blackThresholdImage - Перевести все пиксели ниже порогового значения в черный цвет
    • Imagick::blurImage - Добавляет фильтр размытия к изображению
    • Imagick::borderImage - Окружает изображение рамкой
    • Imagick::charcoalImage - Рисование углем
    • Imagick::chopImage - Удаляет область изображения и обрезает его
    • Imagick::clear - Очищает все ресурсы, связанные с объектом Imagick
    • Imagick::clipImage - Обрезка вдоль ближайшего контура с профилем 8BIM
    • Imagick::clipPathImage - Отсечь вдоль обозначенного контура с профилем 8BIM
    • Imagick::clone - Создает точную копию объекта Imagick
    • Imagick::clutImage - Заменяет цвета в изображении
    • Imagick::coalesceImages - Composites a set of images
    • Imagick::colorFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::colorizeImage - Смешивание цвета заливки с изображением
    • Imagick::combineImages - Combines one or more images into a single image
    • Imagick::commentImage - Adds a comment to your image
    • Imagick::compareImageChannels - Returns the difference in one or more images
    • Imagick::compareImageLayers - Returns the maximum bounding region between images
    • Imagick::compareImages - Compares an image to a reconstructed image
    • Imagick::compositeImage - Composite one image onto another
    • Imagick::contrastImage - Change the contrast of the image
    • Imagick::contrastStretchImage - Enhances the contrast of a color image
    • Imagick::convolveImage - Applies a custom convolution kernel to the image
    • Imagick::cropImage - Извлекает область изображения
    • Imagick::cropThumbnailImage - Creates a crop thumbnail
    • Imagick::current - Возвращает ссылку на текущий объект Imagick
    • Imagick::cycleColormapImage - Displaces an image's colormap
    • Imagick::decipherImage - Deciphers an image
    • Imagick::deconstructImages - Returns certain pixel differences between images
    • Imagick::deleteImageArtifact - Delete image artifact
    • Imagick::deskewImage - Removes skew from the image
    • Imagick::despeckleImage - Reduces the speckle noise in an image
    • Imagick::destroy - Удаляет объект Imagick
    • Imagick::displayImage - Выводит изображение
    • Imagick::displayImages - Выводит изображение или последовательность изображений
    • Imagick::distortImage - Distorts an image using various distortion methods
    • Imagick::drawImage - Выполняет рендеринг объекта ImagickDraw на текущем изображении
    • Imagick::edgeImage - Enhance edges within the image
    • Imagick::embossImage - Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage - Enciphers an image
    • Imagick::enhanceImage - Improves the quality of a noisy image
    • Imagick::equalizeImage - Equalizes the image histogram
    • Imagick::evaluateImage - Applies an expression to an image
    • Imagick::exportImagePixels - Exports raw image pixels
    • Imagick::extentImage - Set image size
    • Imagick::flattenImages - Merges a sequence of images
    • Imagick::flipImage - Создает вертикальное зеркало изображения
    • Imagick::floodFillPaintImage - Changes the color value of any pixel that matches target
    • Imagick::flopImage - Создает горизонтальное зеркало изображения
    • Imagick::frameImage - Adds a simulated three-dimensional border
    • Imagick::functionImage - Applies a function on the image
    • Imagick::fxImage - Evaluate expression for each pixel in the image
    • Imagick::gammaImage - Gamma-corrects an image
    • Imagick::gaussianBlurImage - Blurs an image
    • Imagick::getColorspace - Возвращает цветовую палитру
    • Imagick::getCompression - Возвращает тип сжатия объекта
    • Imagick::getCompressionQuality - Возвращает качество сжатия объекта
    • Imagick::getCopyright - Возвращает копирайт API ImageMagick в виде строки
    • Imagick::getFilename - Имя файла результирующего изображения
    • Imagick::getFont - Возвращает название шрифта
    • Imagick::getFormat - Возвращает формат Imagick объекта
    • Imagick::getGravity - Возвращает значение гравитации (притяжения)
    • Imagick::getHomeURL - Возвращает домашний URL библиотеки ImageMagick
    • Imagick::getImage - Возвращает новый объект Imagick
    • Imagick::getImageAlphaChannel - Возвращает альфа-канал изображения
    • Imagick::getImageArtifact - Get image artifact
    • Imagick::getImageBackgroundColor - Возвращает цвет фона изображения
    • Imagick::getImageBlob - Returns the image sequence as a blob
    • Imagick::getImageBluePrimary - Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor - Возвращает цвет рамки изображения
    • Imagick::getImageChannelDepth - Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion - Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions - Gets channel distortions
    • Imagick::getImageChannelExtrema - Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis - The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean - Gets the mean and standard deviation
    • Imagick::getImageChannelRange - Gets channel range
    • Imagick::getImageChannelStatistics - Returns statistics for each channel in the image
    • Imagick::getImageClipMask - Gets image clip mask
    • Imagick::getImageColormapColor - Returns the color of the specified colormap index
    • Imagick::getImageColors - Возвращает число уникальных цветов в изображении
    • Imagick::getImageColorspace - Возвращает цветовую палитру изображения
    • Imagick::getImageCompose - Возвращает составной оператор, связанный с изображением
    • Imagick::getImageCompression - Возвращает текущий тип компрессии изображения
    • Imagick::getImageCompressionQuality - Возвращает текущее качество сжатия изображения
    • Imagick::getImageDelay - Gets the image delay
    • Imagick::getImageDepth - Gets the image depth
    • Imagick::getImageDispose - Gets the image disposal method
    • Imagick::getImageDistortion - Compares an image to a reconstructed image
    • Imagick::getImageExtrema - Gets the extrema for the image
    • Imagick::getImageFilename - Возвращает имя файла конкретного изображения в последовательности
    • Imagick::getImageFormat - Возвращает формат конкретного изображения в последовательности
    • Imagick::getImageGamma - Возвращает гамму изображения
    • Imagick::getImageGeometry - Возвращает ширину и высоту в виде ассоциативного массива
    • Imagick::getImageGravity - Возвращает значение гравитации (притяжения)
    • Imagick::getImageGreenPrimary - Returns the chromaticy green primary point
    • Imagick::getImageHeight - Возвращает высоту изображения
    • Imagick::getImageHistogram - Gets the image histogram
    • Imagick::getImageIndex - Gets the index of the current active image
    • Imagick::getImageInterlaceScheme - Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod - Returns the interpolation method
    • Imagick::getImageIterations - Gets the image iterations
    • Imagick::getImageLength - Returns the image length in bytes
    • Imagick::getImageMagickLicense - Returns a string containing the ImageMagick license
    • Imagick::getImageMatte - Return if the image has a matte channel
    • Imagick::getImageMatteColor - Returns the image matte color
    • Imagick::getImageOrientation - Gets the image orientation
    • Imagick::getImagePage - Returns the page geometry
    • Imagick::getImagePixelColor - Returns the color of the specified pixel
    • Imagick::getImageProfile - Returns the named image profile
    • Imagick::getImageProfiles - Returns the image profiles
    • Imagick::getImageProperties - Returns the image properties
    • Imagick::getImageProperty - Returns the named image property
    • Imagick::getImageRedPrimary - Returns the chromaticity red primary point
    • Imagick::getImageRegion - Extracts a region of the image
    • Imagick::getImageRenderingIntent - Gets the image rendering intent
    • Imagick::getImageResolution - Gets the image X and Y resolution
    • Imagick::getImagesBlob - Returns all image sequences as a blob
    • Imagick::getImageScene - Gets the image scene
    • Imagick::getImageSignature - Generates an SHA-256 message digest
    • Imagick::getImageSize - Возвращает размер (длину) изображения в байтах
    • Imagick::getImageTicksPerSecond - Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity - Gets the image total ink density
    • Imagick::getImageType - Возвращает возможный тип изображения
    • Imagick::getImageUnits - Gets the image units of resolution
    • Imagick::getImageVirtualPixelMethod - Returns the virtual pixel method
    • Imagick::getImageWhitePoint - Returns the chromaticity white point
    • Imagick::getImageWidth - Возвращает ширину изображения
    • Imagick::getInterlaceScheme - Gets the object interlace scheme
    • Imagick::getIteratorIndex - Gets the index of the current active image
    • Imagick::getNumberImages - Returns the number of images in the object
    • Imagick::getOption - Returns a value associated with the specified key
    • Imagick::getPackageName - Returns the ImageMagick package name
    • Imagick::getPage - Returns the page geometry
    • Imagick::getPixelIterator - Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator - Возвращает объект ImagickPixelIterator для секции изображения
    • Imagick::getPointSize - Возвращает размер точки
    • Imagick::getQuantumDepth - Возвращает величину глубины
    • Imagick::getQuantumRange - Возвращает величину диапазона объекта Imagick
    • Imagick::getReleaseDate - Возвращает дату релиза ImageMagick
    • Imagick::getResource - Возвращает размер используемой памяти указанного ресурса
    • Imagick::getResourceLimit - Возвращает заданный лимит ресурсов
    • Imagick::getSamplingFactors - Возвращает горизонтальный и вертикальный фактор выборки
    • Imagick::getSize - Возвращает размер, связанный с объектом Imagick
    • Imagick::getSizeOffset - Возвращает размер смещения
    • Imagick::getVersion - Возвращает версию API ImageMagick
    • Imagick::haldClutImage - Replaces colors in the image
    • Imagick::hasNextImage - Checks if the object has more images
    • Imagick::hasPreviousImage - Checks if the object has a previous image
    • Imagick::identifyImage - Identifies an image and fetches attributes
    • Imagick::implodeImage - Creates a new image as a copy
    • Imagick::importImagePixels - Imports image pixels
    • Imagick::labelImage - Adds a label to an image
    • Imagick::levelImage - Adjusts the levels of an image
    • Imagick::linearStretchImage - Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage - Animates an image or images
    • Imagick::magnifyImage - Scales an image proportionally 2x
    • Imagick::mapImage - Replaces the colors of an image with the closest color from a reference image.
    • Imagick::matteFloodfillImage - Changes the transparency value of a color
    • Imagick::medianFilterImage - Applies a digital filter
    • Imagick::mergeImageLayers - Merges image layers
    • Imagick::minifyImage - Scales an image proportionally to half its size
    • Imagick::modulateImage - Control the brightness, saturation, and hue
    • Imagick::montageImage - Creates a composite image
    • Imagick::morphImages - Method morphs a set of images
    • Imagick::mosaicImages - Forms a mosaic from images
    • Imagick::motionBlurImage - Simulates motion blur
    • Imagick::negateImage - Negates the colors in the reference image
    • Imagick::newImage - Creates a new image
    • Imagick::newPseudoImage - Creates a new image
    • Imagick::nextImage - Moves to the next image
    • Imagick::normalizeImage - Enhances the contrast of a color image
    • Imagick::oilPaintImage - Simulates an oil painting
    • Imagick::opaquePaintImage - Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers - Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage - Performs an ordered dither
    • Imagick::paintFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage - Change any pixel that matches color
    • Imagick::paintTransparentImage - Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage - Fetch basic attributes about the image
    • Imagick::pingImageBlob - Quickly fetch attributes
    • Imagick::pingImageFile - Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage - Simulates a Polaroid picture
    • Imagick::posterizeImage - Reduces the image to a limited number of color level
    • Imagick::previewImages - Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage - Move to the previous image in the object
    • Imagick::profileImage - Adds or removes a profile from an image
    • Imagick::quantizeImage - Analyzes the colors within a reference image
    • Imagick::quantizeImages - Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics - Returns an array representing the font metrics
    • Imagick::queryFonts - Returns the configured fonts
    • Imagick::queryFormats - Returns formats supported by Imagick
    • Imagick::radialBlurImage - Radial blurs an image
    • Imagick::raiseImage - Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage - Creates a high-contrast, two-color image
    • Imagick::readImage - Reads image from filename
    • Imagick::readImageBlob - Reads image from a binary string
    • Imagick::readImageFile - Reads image from open filehandle
    • Imagick::recolorImage - Recolors image
    • Imagick::reduceNoiseImage - Smooths the contours of an image
    • Imagick::remapImage - Remaps image colors
    • Imagick::removeImage - Removes an image from the image list
    • Imagick::removeImageProfile - Removes the named image profile and returns it
    • Imagick::render - Renders all preceding drawing commands
    • Imagick::resampleImage - Resample image to desired resolution
    • Imagick::resetImagePage - Reset image page
    • Imagick::resizeImage - Scales an image
    • Imagick::rollImage - Offsets an image
    • Imagick::rotateImage - Rotates an image
    • Imagick::roundCorners - Rounds image corners
    • Imagick::sampleImage - Scales an image with pixel sampling
    • Imagick::scaleImage - Scales the size of an image
    • Imagick::segmentImage - Segments an image
    • Imagick::separateImageChannel - Separates a channel from the image
    • Imagick::sepiaToneImage - Sepia tones an image
    • Imagick::setBackgroundColor - Sets the object's default background color
    • Imagick::setColorspace - Set colorspace
    • Imagick::setCompression - Sets the object's default compression type
    • Imagick::setCompressionQuality - Sets the object's default compression quality
    • Imagick::setFilename - Sets the filename before you read or write the image
    • Imagick::setFirstIterator - Sets the Imagick iterator to the first image
    • Imagick::setFont - Sets font
    • Imagick::setFormat - Sets the format of the Imagick object
    • Imagick::setGravity - Sets the gravity
    • Imagick::setImage - Replaces image in the object
    • Imagick::setImageAlphaChannel - Sets image alpha channel
    • Imagick::setImageArtifact - Set image artifact
    • Imagick::setImageBackgroundColor - Sets the image background color
    • Imagick::setImageBias - Sets the image bias for any method that convolves an image
    • Imagick::setImageBluePrimary - Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor - Sets the image border color
    • Imagick::setImageChannelDepth - Sets the depth of a particular image channel
    • Imagick::setImageClipMask - Sets image clip mask
    • Imagick::setImageColormapColor - Sets the color of the specified colormap index
    • Imagick::setImageColorspace - Sets the image colorspace
    • Imagick::setImageCompose - Sets the image composite operator
    • Imagick::setImageCompression - Sets the image compression
    • Imagick::setImageCompressionQuality - Sets the image compression quality
    • Imagick::setImageDelay - Sets the image delay
    • Imagick::setImageDepth - Sets the image depth
    • Imagick::setImageDispose - Sets the image disposal method
    • Imagick::setImageExtent - Sets the image size
    • Imagick::setImageFilename - Sets the filename of a particular image
    • Imagick::setImageFormat - Sets the format of a particular image
    • Imagick::setImageGamma - Sets the image gamma
    • Imagick::setImageGravity - Sets the image gravity
    • Imagick::setImageGreenPrimary - Sets the image chromaticity green primary point
    • Imagick::setImageIndex - Set the iterator position
    • Imagick::setImageInterlaceScheme - Sets the image compression
    • Imagick::setImageInterpolateMethod - Sets the image interpolate pixel method
    • Imagick::setImageIterations - Sets the image iterations
    • Imagick::setImageMatte - Sets the image matte channel
    • Imagick::setImageMatteColor - Sets the image matte color
    • Imagick::setImageOpacity - Sets the image opacity level
    • Imagick::setImageOrientation - Sets the image orientation
    • Imagick::setImagePage - Sets the page geometry of the image
    • Imagick::setImageProfile - Adds a named profile to the Imagick object
    • Imagick::setImageProperty - Sets an image property
    • Imagick::setImageRedPrimary - Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent - Sets the image rendering intent
    • Imagick::setImageResolution - Sets the image resolution
    • Imagick::setImageScene - Sets the image scene
    • Imagick::setImageTicksPerSecond - Sets the image ticks-per-second
    • Imagick::setImageType - Sets the image type
    • Imagick::setImageUnits - Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod - Sets the image virtual pixel method
    • Imagick::setImageWhitePoint - Sets the image chromaticity white point
    • Imagick::setInterlaceScheme - Sets the image compression
    • Imagick::setIteratorIndex - Set the iterator position
    • Imagick::setLastIterator - Sets the Imagick iterator to the last image
    • Imagick::setOption - Set an option
    • Imagick::setPage - Sets the page geometry of the Imagick object
    • Imagick::setPointSize - Sets point size
    • Imagick::setResolution - Sets the image resolution
    • Imagick::setResourceLimit - Sets the limit for a particular resource in megabytes
    • Imagick::setSamplingFactors - Sets the image sampling factors
    • Imagick::setSize - Sets the size of the Imagick object
    • Imagick::setSizeOffset - Sets the size and offset of the Imagick object
    • Imagick::setType - Sets the image type attribute
    • Imagick::shadeImage - Creates a 3D effect
    • Imagick::shadowImage - Simulates an image shadow
    • Imagick::sharpenImage - Sharpens an image
    • Imagick::shaveImage - Shaves pixels from the image edges
    • Imagick::shearImage - Creating a parallelogram
    • Imagick::sigmoidalContrastImage - Adjusts the contrast of an image
    • Imagick::sketchImage - Simulates a pencil sketch
    • Imagick::solarizeImage - Applies a solarizing effect to the image
    • Imagick::sparseColorImage - Interpolates colors
    • Imagick::spliceImage - Splices a solid color into the image
    • Imagick::spreadImage - Randomly displaces each pixel in a block
    • Imagick::steganoImage - Hides a digital watermark within the image
    • Imagick::stereoImage - Composites two images
    • Imagick::stripImage - Strips an image of all profiles and comments
    • Imagick::swirlImage - Swirls the pixels about the center of the image
    • Imagick::textureImage - Repeatedly tiles the texture image
    • Imagick::thresholdImage - Изменяет отдельные пиксели на основе порогового значения
    • Imagick::thumbnailImage - Changes the size of an image
    • Imagick::tintImage - Applies a color vector to each pixel in the image
    • Imagick::transformImage - Convenience method for setting crop size and the image geometry
    • Imagick::transparentPaintImage - Paints pixels transparent
    • Imagick::transposeImage - Creates a vertical mirror image
    • Imagick::transverseImage - Creates a horizontal mirror image
    • Imagick::trimImage - Remove edges from the image
    • Imagick::uniqueImageColors - Discards all but one of any pixel color
    • Imagick::unsharpMaskImage - Sharpens an image
    • Imagick::valid - Checks if the current item is valid
    • Imagick::vignetteImage - Adds vignette filter to the image
    • Imagick::waveImage - Applies wave filter to the image
    • Imagick::whiteThresholdImage - Force all pixels above the threshold into white
    • Imagick::writeImage - Writes an image to the specified filename
    • Imagick::writeImageFile - Writes an image to a filehandle
    • Imagick::writeImages - Writes an image or image sequence
    • Imagick::writeImagesFile - Writes frames to a filehandle
    • Imagick::__construct - Конструктор объекта Imagick
    • ImagickDraw::affine - Adjusts the current affine transformation matrix
    • ImagickDraw::annotation - Draws text on the image
    • ImagickDraw::arc - Draws an arc
    • ImagickDraw::bezier - Draws a bezier curve
    • ImagickDraw::circle - Draws a circle
    • ImagickDraw::clear - Clears the ImagickDraw
    • ImagickDraw::clone - Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color - Draws color on image
    • ImagickDraw::comment - Adds a comment
    • ImagickDraw::composite - Composites an image onto the current image
    • ImagickDraw::destroy - Frees all associated resources
    • ImagickDraw::ellipse - Draws an ellipse on the image
    • ImagickDraw::getClipPath - Obtains the current clipping path ID
    • ImagickDraw::getClipRule - Returns the current polygon fill rule
    • ImagickDraw::getClipUnits - Returns the interpretation of clip path units
    • ImagickDraw::getFillColor - Returns the fill color
    • ImagickDraw::getFillOpacity - Returns the opacity used when drawing
    • ImagickDraw::getFillRule - Returns the fill rule
    • ImagickDraw::getFont - Returns the font
    • ImagickDraw::getFontFamily - Returns the font family
    • ImagickDraw::getFontSize - Returns the font pointsize
    • ImagickDraw::getFontStyle - Returns the font style
    • ImagickDraw::getFontWeight - Returns the font weight
    • ImagickDraw::getGravity - Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias - Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor - Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray - Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset - Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap - Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin - Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit - Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity - Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth - Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment - Returns the text alignment
    • ImagickDraw::getTextAntialias - Returns the current text antialias setting
    • ImagickDraw::getTextDecoration - Returns the text decoration
    • ImagickDraw::getTextEncoding - Returns the code set used for text annotations
    • ImagickDraw::getTextUnderColor - Returns the text under color
    • ImagickDraw::getVectorGraphics - Returns a string containing vector graphics
    • ImagickDraw::line - Draws a line
    • ImagickDraw::matte - Paints on the image's opacity channel
    • ImagickDraw::pathClose - Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute - Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative - Draws an elliptical arc
    • ImagickDraw::pathFinish - Terminates the current path
    • ImagickDraw::pathLineToAbsolute - Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute - Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative - Draws a horizontal line
    • ImagickDraw::pathLineToRelative - Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute - Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative - Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute - Starts a new sub-path
    • ImagickDraw::pathMoveToRelative - Starts a new sub-path
    • ImagickDraw::pathStart - Declares the start of a path drawing list
    • ImagickDraw::point - Draws a point
    • ImagickDraw::polygon - Draws a polygon
    • ImagickDraw::polyline - Draws a polyline
    • ImagickDraw::pop - Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath - Terminates a clip path definition
    • ImagickDraw::popDefs - Terminates a definition list
    • ImagickDraw::popPattern - Terminates a pattern definition
    • ImagickDraw::push - Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath - Starts a clip path definition
    • ImagickDraw::pushDefs - Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern - Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle - Draws a rectangle
    • ImagickDraw::render - Renders all preceding drawing commands onto the image
    • ImagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle - Draws a rounded rectangle
    • ImagickDraw::scale - Adjusts the scaling factor
    • ImagickDraw::setClipPath - Associates a named clipping path with the image
    • ImagickDraw::setClipRule - Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits - Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor - Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL - Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule - Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont - Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily - Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize - Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch - Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle - Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight - Sets the font weight
    • ImagickDraw::setGravity - Sets the text placement gravity
    • ImagickDraw::setStrokeAlpha - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias - Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor - Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray - Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset - Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap - Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin - Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit - Specifies the miter limit
    • ImagickDraw::setStrokeOpacity - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL - Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth - Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment - Specifies a text alignment
    • ImagickDraw::setTextAntialias - Controls whether text is antialiased
    • ImagickDraw::setTextDecoration - Specifies a decoration
    • ImagickDraw::setTextEncoding - Specifies specifies the text code set
    • ImagickDraw::setTextUnderColor - Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics - Sets the vector graphics
    • ImagickDraw::setViewbox - Sets the overall canvas size
    • ImagickDraw::skewX - Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY - Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate - Applies a translation to the current coordinate system
    • ImagickDraw::__construct - The ImagickDraw constructor
    • ImagickPixel::clear - Очищает ресурсы, связанные с этим объектом
    • ImagickPixel::destroy - Освобождает ресурсы, связанные с этим объектом
    • ImagickPixel::getColor - Возвращает цвет
    • ImagickPixel::getColorAsString - Возвращает цвет в виде строки
    • ImagickPixel::getColorCount - Возвращает количество цветов связанных с этим цветом
    • ImagickPixel::getColorValue - Возвращает нормализованное значение цвета канала
    • ImagickPixel::getHSL - Возвращает нормализованный HSL-цвет объекта ImagickPixel
    • ImagickPixel::isSimilar - Проверить разницу между этим цветом и другим
    • ImagickPixel::setColor - Устанавливает цвет
    • ImagickPixel::setColorValue - Устанавливает нормализованное значение одного из каналов
    • ImagickPixel::setHSL - Установка нормализованного HSL цвета
    • ImagickPixel::__construct - Конструктор ImagickPixel
    • ImagickPixelIterator::clear - Очищает ресурсы, связанные с PixelIterator
    • ImagickPixelIterator::destroy - Освобождает ресурсы, связанные с PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow - Возвращает текущий ряд объекта ImagickPixel
    • ImagickPixelIterator::getIteratorRow - Возвращает текущий пиксель итератора ряда
    • ImagickPixelIterator::getNextIteratorRow - Возвращает следующий ряд итератора пикселей
    • ImagickPixelIterator::getPreviousIteratorRow - Возвращает предыдущий ряд
    • ImagickPixelIterator::newPixelIterator - Возвращает новый итератор пикселей
    • ImagickPixelIterator::newPixelRegionIterator - Возвращает новый итератор пикселей
    • ImagickPixelIterator::resetIterator - Сбрасывает итератор пикселей
    • ImagickPixelIterator::setIteratorFirstRow - Устанавливает итератор пикселей на первый ряд
    • ImagickPixelIterator::setIteratorLastRow - Устанавливает итератор пикселей на последний ряд
    • ImagickPixelIterator::setIteratorRow - Устанавливает номер ряда в итераторе пикселей
    • ImagickPixelIterator::syncIterator - Синхронизирует итератор пикселей
    • ImagickPixelIterator::__construct - Конструктор ImagickPixelIterator
    • imap_8bit - Конвертирует 8-битную строку в quoted-printable строку
    • imap_alerts - Returns all IMAP alert messages that have occurred
    • imap_append - Добавляет строковое сообщение в указанный почтовый ящик
    • imap_base64 - Decode BASE64 encoded text
    • imap_binary - Convert an 8bit string to a base64 string
    • imap_body - Read the message body
    • imap_bodystruct - Read the structure of a specified body section of a specific message
    • imap_check - Check current mailbox
    • imap_clearflag_full - Clears flags on messages
    • imap_close - Close an IMAP stream
    • imap_create - Псевдоним imap_createmailbox
    • imap_createmailbox - Create a new mailbox
    • imap_delete - Mark a message for deletion from current mailbox
    • imap_deletemailbox - Delete a mailbox
    • imap_errors - Returns all of the IMAP errors that have occured
    • imap_expunge - Delete all messages marked for deletion
    • imap_fetchbody - Fetch a particular section of the body of the message
    • imap_fetchheader - Returns header for a message
    • imap_fetchmime - Fetch MIME headers for a particular section of the message
    • imap_fetchstructure - Read the structure of a particular message
    • imap_fetchtext - Псевдоним imap_body
    • imap_fetch_overview - Read an overview of the information in the headers of the given message
    • imap_gc - Clears IMAP cache
    • imap_getacl - Gets the ACL for a given mailbox
    • imap_getmailboxes - Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed - List all the subscribed mailboxes
    • imap_get_quota - Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot - Retrieve the quota settings per user
    • imap_header - Псевдоним imap_headerinfo
    • imap_headerinfo - Read the header of the message
    • imap_headers - Returns headers for all messages in a mailbox
    • imap_last_error - Gets the last IMAP error that occurred during this page request
    • imap_list - Read the list of mailboxes
    • imap_listmailbox - Псевдоним imap_list
    • imap_listscan - Returns the list of mailboxes that matches the given text
    • imap_listsubscribed - Псевдоним imap_lsub
    • imap_lsub - List all the subscribed mailboxes
    • imap_mail - Send an email message
    • imap_mailboxmsginfo - Get information about the current mailbox
    • imap_mail_compose - Create a MIME message based on given envelope and body sections
    • imap_mail_copy - Copy specified messages to a mailbox
    • imap_mail_move - Move specified messages to a mailbox
    • imap_mime_header_decode - Decode MIME header elements
    • imap_msgno - Gets the message sequence number for the given UID
    • imap_num_msg - Gets the number of messages in the current mailbox
    • imap_num_recent - Gets the number of recent messages in current mailbox
    • imap_open - Open an IMAP stream to a mailbox
    • imap_ping - Check if the IMAP stream is still active
    • imap_qprint - Convert a quoted-printable string to an 8 bit string
    • imap_rename - Псевдоним imap_renamemailbox
    • imap_renamemailbox - Rename an old mailbox to new mailbox
    • imap_reopen - Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist - Parses an address string
    • imap_rfc822_parse_headers - Parse mail headers from a string
    • imap_rfc822_write_address - Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody - Save a specific body section to a file
    • imap_scan - Псевдоним imap_listscan
    • imap_scanmailbox - Псевдоним imap_listscan
    • imap_search - This function returns an array of messages matching the given search criteria
    • imap_setacl - Sets the ACL for a giving mailbox
    • imap_setflag_full - Sets flags on messages
    • imap_set_quota - Sets a quota for a given mailbox
    • imap_sort - Gets and sort messages
    • imap_status - Returns status information on a mailbox
    • imap_subscribe - Subscribe to a mailbox
    • imap_thread - Returns a tree of threaded message
    • imap_timeout - Set or fetch imap timeout
    • imap_uid - This function returns the UID for the given message sequence number
    • imap_undelete - Unmark the message which is marked deleted
    • imap_unsubscribe - Unsubscribe from a mailbox
    • imap_utf7_decode - Decodes a modified UTF-7 encoded string
    • imap_utf7_encode - Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 - Converts MIME-encoded text to UTF-8
    • implode - Объединяет элементы массива в строку
    • import_request_variables - Импортирует переменные GET/POST/Cookie в глобальную область видимости
    • inclued_get_data - Get the inclued data
    • inet_ntop - Конвертирует упакованный интернет адрес в читаемый формат
    • inet_pton - Конвертирует читаемый IP адрес в упакованное in_addr представление
    • InfiniteIterator::next - Moves the inner Iterator forward or rewinds it
    • InfiniteIterator::__construct - Constructs an InfiniteIterator
    • ingres_autocommit - Switch autocommit on or off
    • ingres_autocommit_state - Test if the connection is using autocommit
    • ingres_charset - Returns the installation character set
    • ingres_close - Close an Ingres database connection
    • ingres_commit - Commit a transaction
    • ingres_connect - Open a connection to an Ingres database
    • ingres_cursor - Get a cursor name for a given result resource
    • ingres_errno - Get the last Ingres error number generated
    • ingres_error - Get a meaningful error message for the last error generated
    • ingres_errsqlstate - Get the last SQLSTATE error code generated
    • ingres_escape_string - Escape special characters for use in a query
    • ingres_execute - Execute a prepared query
    • ingres_fetch_array - Fetch a row of result into an array
    • ingres_fetch_assoc - Fetch a row of result into an associative array
    • ingres_fetch_object - Fetch a row of result into an object
    • ingres_fetch_proc_return - Get the return value from a procedure call
    • ingres_fetch_row - Fetch a row of result into an enumerated array
    • ingres_field_length - Get the length of a field
    • ingres_field_name - Get the name of a field in a query result
    • ingres_field_nullable - Test if a field is nullable
    • ingres_field_precision - Get the precision of a field
    • ingres_field_scale - Get the scale of a field
    • ingres_field_type - Get the type of a field in a query result
    • ingres_free_result - Free the resources associated with a result identifier
    • ingres_next_error - Get the next Ingres error
    • ingres_num_fields - Get the number of fields returned by the last query
    • ingres_num_rows - Get the number of rows affected or returned by a query
    • ingres_pconnect - Open a persistent connection to an Ingres database
    • ingres_prepare - Prepare a query for later execution
    • ingres_query - Send an SQL query to Ingres
    • ingres_result_seek - Set the row position before fetching data
    • ingres_rollback - Roll back a transaction
    • ingres_set_environment - Set environment features controlling output options
    • ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
    • ini_alter - Псевдоним ini_set
    • ini_get - Получает значение настройки конфигурации
    • ini_get_all - Получение всех настроек конфигурации
    • ini_restore - Восстанавливает значение настройки конфигурации
    • ini_set - Установка значения настройки конфигурации
    • inotify_add_watch - Add a watch to an initialized inotify instance
    • inotify_init - Initialize an inotify instance
    • inotify_queue_len - Return a number upper than zero if there are pending events
    • inotify_read - Read events from an inotify instance
    • inotify_rm_watch - Remove an existing watch from an inotify instance
    • interface_exists - Проверяет, определен ли интерфейс
    • IntlDateFormatter::create - Create a date formatter
    • IntlDateFormatter::format - Format the date/time value as a string
    • IntlDateFormatter::getCalendar - Get the calendar used for the IntlDateFormatter
    • IntlDateFormatter::getDateType - Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode - Get the error code from last operation
    • IntlDateFormatter::getErrorMessage - Get the error text from the last operation.
    • IntlDateFormatter::getLocale - Get the locale used by formatter
    • IntlDateFormatter::getPattern - Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType - Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZoneId - Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::isLenient - Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime - Parse string to a field-based time value
    • IntlDateFormatter::parse - Parse string to a timestamp value
    • IntlDateFormatter::setCalendar - sets the calendar used to the appropriate calendar, which must be
    • IntlDateFormatter::setLenient - Set the leniency of the parser
    • IntlDateFormatter::setPattern - Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZoneId - Sets the time zone to use
    • intl_error_name - Get symbolic name for a given error code
    • intl_get_error_code - Get the last error code
    • intl_get_error_message - Get description of the last error
    • intl_is_failure - Check whether the given error code indicates failure
    • intval - Возвращает целое значение переменной
    • in_array - Проверяет, присутствует ли в массиве значение
    • ip2long - Конвертирует строку, содержащую (IPv4) Интернет адрес с точками в допустимый адрес
    • iptcembed - Встраивание двоичных IPTC данных в JPEG изображение
    • iptcparse - Разбор двоичных IPTC данных на отдельные тэги
    • isset - Определяет, была ли установлена переменная значением отличным от NULL
    • is_a - Проверяет, принадлежит ли объект к данному классу или содержит данный класс в числе своих предков
    • is_array - Определяет, является ли переменная массивом
    • is_bool - Проверяет, является ли переменная булевой
    • is_callable - Проверяет, может ли значение переменной быть вызвано в качестве функции
    • is_dir - Определяет, является ли имя файла директорией
    • is_double - Псевдоним is_float
    • is_executable - Определяет, является ли файл исполняемым
    • is_file - Определяет, является ли файл обычным файлом
    • is_finite - Проверяет, является ли значение допустимым конечным числом
    • is_float - Проверяет, является ли переменная числом с плавающей точкой
    • is_infinite - Проверяет, является ли значение бесконечным
    • is_int - Проверяет, является ли переменная переменной целочисленного типа
    • is_integer - Псевдоним is_int
    • is_link - Определяет, является ли файл символической ссылкой
    • is_long - Псевдоним is_int
    • is_nan - Проверяет, является ли значение "не числом"
    • is_null - Проверяет, является ли значение переменной равным NULL
    • is_numeric - Проверяет, является ли переменная числом или строкой, содержащей число
    • is_object - Проверяет, является ли переменная объектом
    • is_readable - Определяет существование файла и доступен ли он для чтения
    • is_real - Псевдоним is_float
    • is_resource - Проверяет, является ли переменная ресурсом
    • is_scalar - Проверяет, является ли переменная скалярным значением
    • is_soap_fault - Checks if a SOAP call has failed
    • is_string - Проверяет, является ли переменная строкой
    • is_subclass_of - Проверяет, содержит ли объект в своем дереве предков указанный класс
    • is_tainted - Checks whether a string is tainted
    • is_uploaded_file - Определяет, был ли файл загружен при помощи HTTP POST
    • is_writable - Определяет, доступен ли файл для записи
    • is_writeable - Псевдоним is_writable
    • Iterator::current - Возвращает текущий элемент
    • Iterator::key - Возвращает ключ текущего элемента
    • Iterator::next - Переходит к следующему элементу
    • Iterator::rewind - Возвращает итератор на первый элемент
    • Iterator::valid - Проверка корректности позиции
    • IteratorAggregate::getIterator - Возвращает внешний итератор
    • IteratorIterator::current - Получает текущее значение
    • IteratorIterator::getInnerIterator - Получает внутренний итератор
    • IteratorIterator::key - Получает ключ текущего элемента
    • IteratorIterator::next - Перемещает итератор к следующему элементу
    • IteratorIterator::rewind - Возвращает итератор к первому элементу
    • IteratorIterator::valid - Проверяет, является ли итератор допустимым
    • IteratorIterator::__construct - Создает итератор из чего-либо, что является обходимым (traversable)
    • iterator_apply - Вызывает функцию для каждого элемента в итераторе
    • iterator_count - Подсчитывает количество элементов в итераторе
    • iterator_to_array - Копирует итератор в массив
  • j
    • java_last_exception_clear - Clear last Java exception
    • java_last_exception_get - Get last Java exception
    • JDDayOfWeek - Возвращает день недели
    • JDMonthName - Возвращает название месяца
    • JDToFrench - Переводит число дней в Юлианском летоисчислении в дату по Французскому республиканскому календарю
    • JDToGregorian - Переводит число дней в Юлианском летоисчислении в дату по Григорианскому календарю
    • jdtojewish - Переводит число дней в Юлианском летоисчислении в дату по Иудейскому календарю
    • JDToJulian - Переводит число дней в Юлианском летоисчислении в дату по Юлианскому календарю
    • jdtounix - Переводит число дней в Юлианском летоисчислении в метку времени Unix
    • JewishToJD - Переводит дату по Иудейскому календарю в число дней в Юлианском летоисчислении
    • join - Псевдоним implode
    • jpeg2wbmp - Конвертирует изображение из формата JPEG в WBMP
    • JsonSerializable::jsonSerialize - Уточняет данные, которые должны быть сериализованы в JSON
    • json_decode - Декодирует JSON строку
    • json_encode - Возвращает JSON-представление данных
    • json_last_error - Возвращает последнюю ошибку
    • Judy::byCount - Locate the Nth index present in the Judy array
    • Judy::count - Count the number of elements in the Judy array
    • Judy::first - Search for the first index in the Judy array
    • Judy::firstEmpty - Search for the first absent index in the Judy array
    • Judy::free - Free the entire Judy array
    • Judy::getType - Return the type of the current Judy array
    • Judy::last - Search for the last index in the Judy array
    • Judy::lastEmpty - Search for the last absent index in the Judy array
    • Judy::memoryUsage - Return the memory used by the Judy array
    • Judy::next - Search for the next index in the Judy array
    • Judy::nextEmpty - Search for the next absent index in the Judy array
    • Judy::offsetExists - Whether a offset exists
    • Judy::offsetGet - Offset to retrieve
    • Judy::offsetSet - Offset to set
    • Judy::offsetUnset - Offset to unset
    • Judy::prev - Search for the previous index in the Judy array
    • Judy::prevEmpty - Search for the previous absent index in the Judy array
    • Judy::size - Return the size of the current Judy array
    • Judy::__construct - Construct a new Judy object
    • Judy::__destruct - Destruct a Judy object
    • judy_type - Return the type of a Judy array
    • judy_version - Return or print the current PHP Judy version
    • JulianToJD - Переводит дату по Юлианскому календарю в число дней в Юлианском летоисчислении
  • k
    • kadm5_chpass_principal - Changes the principal's password
    • kadm5_create_principal - Creates a kerberos principal with the given parameters
    • kadm5_delete_principal - Deletes a kerberos principal
    • kadm5_destroy - Closes the connection to the admin server and releases all related resources
    • kadm5_flush - Flush all changes to the Kerberos database
    • kadm5_get_policies - Gets all policies from the Kerberos database
    • kadm5_get_principal - Gets the principal's entries from the Kerberos database
    • kadm5_get_principals - Gets all principals from the Kerberos database
    • kadm5_init_with_password - Opens a connection to the KADM5 library
    • kadm5_modify_principal - Modifies a kerberos principal with the given parameters
    • key - Выбирает ключ из массива
    • krsort - Сортирует массив по ключам в обратном порядке
    • ksort - Сортирует массив по ключам
    • KTaglib_ID3v2_AttachedPictureFrame::getDescription - Returns a description for the picture in a picture frame
    • KTaglib_ID3v2_AttachedPictureFrame::getMimeType - Returns the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::getType - Returns the type of the image
    • KTaglib_ID3v2_AttachedPictureFrame::savePicture - Saves the picture to a file
    • KTaglib_ID3v2_AttachedPictureFrame::setMimeType - Set's the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::setPicture - Sets the frame picture to the given image
    • KTaglib_ID3v2_AttachedPictureFrame::setType - Set the type of the image
    • KTaglib_ID3v2_Frame::getSize - Returns the size of the frame in bytes
    • KTaglib_ID3v2_Frame::__toString - Returns a string representation of the frame
    • KTaglib_ID3v2_Tag::addFrame - Add a frame to the ID3v2 tag
    • KTaglib_ID3v2_Tag::getFrameList - Returns an array of ID3v2 frames, associated with the ID3v2 tag
    • KTaglib_MPEG_AudioProperties::getBitrate - Returns the bitrate of the MPEG file
    • KTaglib_MPEG_AudioProperties::getChannels - Returns the amount of channels of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLayer - Returns the layer of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLength - Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::getSampleBitrate - Returns the sample bitrate of a MPEG file
    • KTaglib_MPEG_AudioProperties::getVersion - Returns the version of a MPEG file
    • KTaglib_MPEG_AudioProperties::isCopyrighted - Returns the copyright status of an MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal - Returns if the file is marked as the original file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled - Returns if protection mechanisms of an MPEG file are enabled
    • KTaglib_MPEG_File::getAudioProperties - Returns an object that provides access to the audio properties
    • KTaglib_MPEG_File::getID3v1Tag - Returns an object representing an ID3v1 tag
    • KTaglib_MPEG_File::getID3v2Tag - Returns a ID3v2 object
    • KTaglib_MPEG_File::__construct - Opens a new file
    • KTaglib_Tag::getAlbum - Returns the title string from a ID3 tag
    • KTaglib_Tag::getArtist - Returns the artist string from a ID3 tag
    • KTaglib_Tag::getComment - Returns the comment from a ID3 tag
    • KTaglib_Tag::getGenre - Returns the genre from a ID3 tag
    • KTaglib_Tag::getTitle - Returns the title string from a ID3 tag
    • KTaglib_Tag::getTrack - Returns the track number from a ID3 tag
    • KTaglib_Tag::getYear - Returns the year from a ID3 tag
    • KTaglib_Tag::isEmpty - Returns true if the tag is empty
  • l
    • Lapack::eigenValues - This function returns the eigenvalues for a given square matrix
    • Lapack::identity - Return an identity matrix
    • Lapack::leastSquaresByFactorisation - Calculate the linear least squares solution of a matrix using QR factorisation
    • Lapack::leastSquaresBySVD - Solve the linear least squares problem, using SVD
    • Lapack::pseudoInverse - Calculate the inverse of a matrix
    • Lapack::singularValues - Calculated the singular values of a matrix
    • Lapack::solveLinearEquation - Solve a system of linear equations
    • lcfirst - Преобразует первый символ строки в нижний регистр
    • lcg_value - Комбинированный линейно конгруэнтный генератор
    • lchgrp - Изменяет группу, которой принадлежит символическая ссылка
    • lchown - Изменяет владельца символической ссылки
    • ldap_8859_to_t61 - Переводит символы из кодировки ISO-8859 в t61
    • ldap_add - Добавить запись в LDAP директорию
    • ldap_bind - Привязать к LDAP директории
    • ldap_close - Псевдоним ldap_unbind
    • ldap_compare - Сравнить значение атрибута, найденного в записи определённой DN
    • ldap_connect - Подключиться к серверу LDAP
    • ldap_control_paged_result - Send LDAP pagination control
    • ldap_control_paged_result_response - Retrieve the LDAP pagination cookie
    • ldap_count_entries - Посчитать число записей в результатах поиска
    • ldap_delete - Удаляет запись из директории LDAP
    • ldap_dn2ufn - Преобразовать DN в удобный для пользователя формат именования
    • ldap_err2str - Преобразовать код ошибки LDAP в строковое сообщение об ошибке
    • ldap_errno - Возвратить номер ошибки LDAP последней команды
    • ldap_error - Возвратить сообщение об ошибке LDAP последней команды
    • ldap_explode_dn - Разделить DN на его составные части
    • ldap_first_attribute - Вернуть первый атрибут
    • ldap_first_entry - Возвратить первый идентификатор результата first result id
    • ldap_first_reference - Возвращает первую справку
    • ldap_free_result - Освободить память результата
    • ldap_get_attributes - Получает атрибуты из записи в результатах поиска
    • ldap_get_dn - Получить DN результирующей записи
    • ldap_get_entries - Получает все записи результата
    • ldap_get_option - Получить текущее значение данной опции
    • ldap_get_values - Получает все значения из записи результата
    • ldap_get_values_len - Получить все бинарные значения из записи результата
    • ldap_list - Одноуровневый поиск
    • ldap_modify - Изменить LDAP запись
    • ldap_mod_add - Добавить значения атрибута к текущим атрибутам
    • ldap_mod_del - Удалить значения атрибута из текущих атрибутов
    • ldap_mod_replace - Заменить значения атрибутов на новые
    • ldap_next_attribute - Получить следующий атрибут из результата
    • ldap_next_entry - Получить следующую запись результата
    • ldap_next_reference - Возвращает следующую справку
    • ldap_parse_reference - Извлекает информацию из справочника
    • ldap_parse_result - Извлечь информацию из результата
    • ldap_read - Читает запись
    • ldap_rename - Изменить имя записи
    • ldap_sasl_bind - Привязать к LDAP директории, используя SASL
    • ldap_search - Поиск по LDAP дереву
    • ldap_set_option - Установить значение данной опции
    • ldap_set_rebind_proc - Установить функцию обратного вызова для повторного связывания при ссылочном поиске
    • ldap_sort - Сортировать записи LDAP
    • ldap_start_tls - Запускает TLS
    • ldap_t61_to_8859 - Переводит символы из кодировки t61 в ISO-8859
    • ldap_unbind - Разорвать привязку к директории LDAP
    • levenshtein - Вычисляет расстояние Левенштейна между двумя строками
    • libxml_clear_errors - Очистка буфера ошибок libxml
    • libxml_disable_entity_loader - Отключение возможности загрузки сущностей из внешних источников
    • libxml_get_errors - Получение массива произошедших ошибок
    • libxml_get_last_error - Извлечение последней ошибки из libxml
    • libxml_set_external_entity_loader - Changes the default external entity loader
    • libxml_set_streams_context - Установка контекста потока для следующей загрузки или записи документа посредством libxml
    • libxml_use_internal_errors - Отключение ошибок libxml и передача полномочий по выборке и обработке информации об ошибках пользователю
    • LimitIterator::current - Get current element
    • LimitIterator::getInnerIterator - Get inner iterator
    • LimitIterator::getPosition - Return the current position
    • LimitIterator::key - Get current key
    • LimitIterator::next - Move the iterator forward
    • LimitIterator::rewind - Rewind the iterator to the specified starting offset
    • LimitIterator::seek - Seek to the given position
    • LimitIterator::valid - Check whether the current element is valid
    • LimitIterator::__construct - Construct a LimitIterator
    • link - Создаёт жёсткую ссылку
    • linkinfo - Возвращает информацию о ссылке
    • list - Присваивает переменным из списка значения подобно массиву
    • Locale::acceptFromHttp - Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::composeLocale - Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches - Checks if a language tag filter matches with locale
    • Locale::getAllVariants - Gets the variants for the input locale
    • Locale::getDefault - Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage - Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName - Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion - Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript - Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant - Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords - Gets the keywords for the input locale
    • Locale::getPrimaryLanguage - Gets the primary language for the input locale
    • Locale::getRegion - Gets the region for the input locale
    • Locale::getScript - Gets the script for the input locale
    • Locale::lookup - Searches the language tag list for the best match to the language
    • Locale::parseLocale - Returns a key-value array of locale ID subtag elements.
    • Locale::setDefault - sets the default runtime locale
    • localeconv - Возвращает информацию о числовых форматах
    • localtime - Возвращает локальное время
    • log - Натуральный логарифм
    • log1p - Возвращает log(1 + number), рассчитанный таким, что результат точен, даже если значение number близко к нулю
    • log10 - Десятичный логарифм
    • long2ip - Конвертирует (IPv4) адрес Интернет сети в стандартную строку с точками
    • lstat - Возвращает информацию о файле или символической ссылке
    • ltrim - Удаляет пробелы (или другие символы) из начала строки
    • Lua::assign - Assign a PHP variable to Lua
    • Lua::call - Call Lua functions
    • Lua::eval - Evaluate a string as Lua code
    • Lua::getVersion - The getversion purpose
    • Lua::include - Parse a Lua script file
    • Lua::registerCallback - Register a PHP function to Lua
    • Lua::__construct - Lua constructor
    • LuaClosure::__invoke - invoke luaclosure
    • lzf_compress - LZF compression
    • lzf_decompress - LZF decompression
    • lzf_optimized_for - Determines what LZF extension was optimized for
  • m
    • magic_quotes_runtime - Псевдоним set_magic_quotes_runtime
    • mail - Отправляет электронную почту
    • mailparse_determine_best_xfer_encoding - Gets the best way of encoding
    • mailparse_msg_create - Create a mime mail resource
    • mailparse_msg_extract_part - Extracts/decodes a message section
    • mailparse_msg_extract_part_file - Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file - Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free - Frees a MIME resource
    • mailparse_msg_get_part - Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_part_data - Returns an associative array of info about the message
    • mailparse_msg_get_structure - Returns an array of mime section names in the supplied message
    • mailparse_msg_parse - Incrementally parse data into buffer
    • mailparse_msg_parse_file - Parses a file
    • mailparse_rfc822_parse_addresses - Parse RFC 822 compliant addresses
    • mailparse_stream_encode - Streams data from source file pointer, apply encoding and write to destfp
    • mailparse_uudecode_all - Scans the data from fp and extract each embedded uuencoded file
    • main - Заглушка для main
    • max - Возвращает наибольшее значение
    • maxdb_affected_rows - Gets the number of affected rows in a previous MaxDB operation
    • maxdb_autocommit - Turns on or off auto-commiting database modifications
    • maxdb_bind_param - Псевдоним maxdb_stmt_bind_param
    • maxdb_bind_result - Псевдоним maxdb_stmt_bind_result
    • maxdb_change_user - Changes the user of the specified database connection
    • maxdb_character_set_name - Returns the default character set for the database connection
    • maxdb_client_encoding - Псевдоним maxdb_character_set_name
    • maxdb_close - Closes a previously opened database connection
    • maxdb_close_long_data - Псевдоним maxdb_stmt_close_long_data
    • maxdb_commit - Commits the current transaction
    • maxdb_connect - Open a new connection to the MaxDB server
    • maxdb_connect_errno - Returns the error code from last connect call
    • maxdb_connect_error - Returns a string description of the last connect error
    • maxdb_data_seek - Adjusts the result pointer to an arbitary row in the result
    • maxdb_debug - Performs debugging operations
    • maxdb_disable_reads_from_master - Disable reads from master
    • maxdb_disable_rpl_parse - Disable RPL parse
    • maxdb_dump_debug_info - Dump debugging information into the log
    • maxdb_embedded_connect - Open a connection to an embedded MaxDB server
    • maxdb_enable_reads_from_master - Enable reads from master
    • maxdb_enable_rpl_parse - Enable RPL parse
    • maxdb_errno - Returns the error code for the most recent function call
    • maxdb_error - Returns a string description of the last error
    • maxdb_escape_string - Псевдоним maxdb_real_escape_string
    • maxdb_execute - Псевдоним maxdb_stmt_execute
    • maxdb_fetch - Псевдоним maxdb_stmt_fetch
    • maxdb_fetch_array - Fetch a result row as an associative, a numeric array, or both
    • maxdb_fetch_assoc - Fetch a result row as an associative array
    • maxdb_fetch_field - Returns the next field in the result set
    • maxdb_fetch_fields - Returns an array of resources representing the fields in a result set
    • maxdb_fetch_field_direct - Fetch meta-data for a single field
    • maxdb_fetch_lengths - Returns the lengths of the columns of the current row in the result set
    • maxdb_fetch_object - Returns the current row of a result set as an object
    • maxdb_fetch_row - Get a result row as an enumerated array
    • maxdb_field_count - Returns the number of columns for the most recent query
    • maxdb_field_seek - Set result pointer to a specified field offset
    • maxdb_field_tell - Get current field offset of a result pointer
    • maxdb_free_result - Frees the memory associated with a result
    • maxdb_get_client_info - Returns the MaxDB client version as a string
    • maxdb_get_client_version - Get MaxDB client info
    • maxdb_get_host_info - Returns a string representing the type of connection used
    • maxdb_get_metadata - Псевдоним maxdb_stmt_result_metadata
    • maxdb_get_proto_info - Returns the version of the MaxDB protocol used
    • maxdb_get_server_info - Returns the version of the MaxDB server
    • maxdb_get_server_version - Returns the version of the MaxDB server as an integer
    • maxdb_info - Retrieves information about the most recently executed query
    • maxdb_init - Initializes MaxDB and returns an resource for use with maxdb_real_connect
    • maxdb_insert_id - Returns the auto generated id used in the last query
    • maxdb_kill - Disconnects from a MaxDB server
    • maxdb_master_query - Enforce execution of a query on the master in a master/slave setup
    • maxdb_more_results - Check if there any more query results from a multi query
    • maxdb_multi_query - Performs a query on the database
    • maxdb_next_result - Prepare next result from multi_query
    • maxdb_num_fields - Get the number of fields in a result
    • maxdb_num_rows - Gets the number of rows in a result
    • maxdb_options - Set options
    • maxdb_param_count - Псевдоним maxdb_stmt_param_count
    • maxdb_ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • maxdb_prepare - Prepare an SQL statement for execution
    • maxdb_query - Performs a query on the database
    • maxdb_real_connect - Opens a connection to a MaxDB server
    • maxdb_real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • maxdb_real_query - Execute an SQL query
    • maxdb_report - Enables or disables internal report functions
    • maxdb_rollback - Rolls back current transaction
    • maxdb_rpl_parse_enabled - Check if RPL parse is enabled
    • maxdb_rpl_probe - RPL probe
    • maxdb_rpl_query_type - Returns RPL query type
    • maxdb_select_db - Selects the default database for database queries
    • maxdb_send_long_data - Псевдоним maxdb_stmt_send_long_data
    • maxdb_send_query - Send the query and return
    • maxdb_server_end - Shut down the embedded server
    • maxdb_server_init - Initialize embedded server
    • maxdb_set_opt - Псевдоним maxdb_options
    • maxdb_sqlstate - Returns the SQLSTATE error from previous MaxDB operation
    • maxdb_ssl_set - Used for establishing secure connections using SSL
    • maxdb_stat - Gets the current system status
    • maxdb_stmt_affected_rows - Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • maxdb_stmt_bind_param - Binds variables to a prepared statement as parameters
    • maxdb_stmt_bind_result - Binds variables to a prepared statement for result storage
    • maxdb_stmt_close - Closes a prepared statement
    • maxdb_stmt_close_long_data - Ends a sequence of maxdb_stmt_send_long_data
    • maxdb_stmt_data_seek - Seeks to an arbitray row in statement result set
    • maxdb_stmt_errno - Returns the error code for the most recent statement call
    • maxdb_stmt_error - Returns a string description for last statement error
    • maxdb_stmt_execute - Executes a prepared Query
    • maxdb_stmt_fetch - Fetch results from a prepared statement into the bound variables
    • maxdb_stmt_free_result - Frees stored result memory for the given statement handle
    • maxdb_stmt_init - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
    • maxdb_stmt_num_rows - Return the number of rows in statements result set
    • maxdb_stmt_param_count - Returns the number of parameter for the given statement
    • maxdb_stmt_prepare - Prepare an SQL statement for execution
    • maxdb_stmt_reset - Resets a prepared statement
    • maxdb_stmt_result_metadata - Returns result set metadata from a prepared statement
    • maxdb_stmt_send_long_data - Send data in blocks
    • maxdb_stmt_sqlstate - Returns SQLSTATE error from previous statement operation
    • maxdb_stmt_store_result - Transfers a result set from a prepared statement
    • maxdb_store_result - Transfers a result set from the last query
    • maxdb_thread_id - Returns the thread ID for the current connection
    • maxdb_thread_safe - Returns whether thread safety is given or not
    • maxdb_use_result - Initiate a result set retrieval
    • maxdb_warning_count - Returns the number of warnings from the last query for the given link
    • mb_check_encoding - Проверяет, что кодировка для строки выбрана верно
    • mb_convert_case - Производит смену регистра символов в строке
    • mb_convert_encoding - Преобразует кодировку символов
    • mb_convert_kana - Преобразование кодировок "kana" из одной в другую ("zen-kaku", "han-kaku" и другие)
    • mb_convert_variables - Преобразует символы в переменной(-ых) из одной кодировки в другую
    • mb_decode_mimeheader - Декодирует строку в MIME-заголовке
    • mb_decode_numericentity - Декодирует числовую HTML-ссылку в символ
    • mb_detect_encoding - Определение кодировки символов
    • mb_detect_order - Установка/получение списка кодировок для механизмов определения кодировки
    • mb_encode_mimeheader - Кодирование строки для MIME-заголовка
    • mb_encode_numericentity - Кодирование символа в числовую HTML-ссылку
    • mb_encoding_aliases - Получает псевдонимы известного типа кодировки
    • mb_ereg - Совпадение с регулярным выражением с поддержкой многобайтовых символов
    • mb_eregi - Поиск соответствий регулярному выражению поддерживающий многобайтные символы и нечувствительный к регистру
    • mb_eregi_replace - Осуществляет замену по регулярному выражению с поддержкой многобайтовых символов без учета регистра
    • mb_ereg_match - Совпадение с регулярным выражением для многобайтовой строки
    • mb_ereg_replace - Осуществляет замену по регулярному выражению с поддержкой многобайтовых символов
    • mb_ereg_replace_callback - Perform a regular expresssion seach and replace with multibyte support using a callback
    • mb_ereg_search - Поиск соответствий регулярному выражению для строк в многобайтных кодировках
    • mb_ereg_search_getpos - Возвращает начальную позицию следующего совпадения с регулярным выражением
    • mb_ereg_search_getregs - Выводит результат последнего сравнения с регулярным выражением
    • mb_ereg_search_init - Инициализация поиска соответствий регулярному выражению многобайтной строкой и текстом регулярного выражения
    • mb_ereg_search_pos - Возвращает позицию и длину совпавшего с регулярным выражением участка многобайтной строки
    • mb_ereg_search_regs - Возвращает совпавшую с регулярным выражением часть строки
    • mb_ereg_search_setpos - Задает начальную позицию в строке, с которой начнется поиск соответствий регулярному выражению
    • mb_get_info - Получает внутренние настройки mbstring
    • mb_http_input - Определение кодировки символов входных данных HTTP-запроса
    • mb_http_output - Установка/получение кодировки символов HTTP вывода
    • mb_internal_encoding - Установка/получение внутренней кодировки скрипта
    • mb_language - Установка/получение текущего языка
    • mb_list_encodings - Возвращает массив всех поддерживаемых кодировок
    • mb_output_handler - Callback-функция, преобразующая кодировку символов в выходном буфере
    • mb_parse_str - Разбор данных запросов GET/POST/COOKIE и установка значений глобальных переменных
    • mb_preferred_mime_name - Получение набора символов MIME
    • mb_regex_encoding - Возвращает текущую кодировку для многобайтового регулярного выражения в виде строки
    • mb_regex_set_options - Установка/получение значений по умолчанию для настроек функций mbregex
    • mb_send_mail - Отправка закодированного сообщения
    • mb_split - Разделение строк в многобайтных кодировках, используя регулярное выражение
    • mb_strcut - Получение части строки
    • mb_strimwidth - Получение строки, образанной до заданной ширины
    • mb_stripos - Поиск позиции первого вхождения одной строки в другую, нечувствителен к регистру
    • mb_stristr - Находит первое вхождение подстроки в строке без учета регистра
    • mb_strlen - Получает длину строки
    • mb_strpos - Поиск позиции первого вхождения одной строки в другую
    • mb_strrchr - Поиск последнего вхождения одной строки в другую
    • mb_strrichr - Поиск последнего вхождения одной строки в другую, нечувствительный к регистру
    • mb_strripos - Поиск последнего вхождения одной строки в другую, нечувствительный к регистру
    • mb_strrpos - Поиск позиции последнего вхождения одной строки в другую
    • mb_strstr - Находит первое вхождение подстроки в строке
    • mb_strtolower - Приведение строки к нижнему регистру
    • mb_strtoupper - Приведение строки к верхнему регистру
    • mb_strwidth - Возвращает ширину строки
    • mb_substitute_character - Задание/получение символа заместителя
    • mb_substr - Возвращает часть строки
    • mb_substr_count - Возвращает количество вхождений подстроки
    • mcrypt_cbc - Шифрует/дешифрует даные в режиме CBC
    • mcrypt_cfb - Encrypts/decrypts data in CFB mode
    • mcrypt_create_iv - Creates an initialization vector (IV) from a random source
    • mcrypt_decrypt - Decrypts crypttext with given parameters
    • mcrypt_ecb - Deprecated: Encrypts/decrypts data in ECB mode
    • mcrypt_encrypt - Encrypts plaintext with given parameters
    • mcrypt_enc_get_algorithms_name - Returns the name of the opened algorithm
    • mcrypt_enc_get_block_size - Returns the blocksize of the opened algorithm
    • mcrypt_enc_get_iv_size - Returns the size of the IV of the opened algorithm
    • mcrypt_enc_get_key_size - Returns the maximum supported keysize of the opened mode
    • mcrypt_enc_get_modes_name - Returns the name of the opened mode
    • mcrypt_enc_get_supported_key_sizes - Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_enc_is_block_algorithm - Checks whether the algorithm of the opened mode is a block algorithm
    • mcrypt_enc_is_block_algorithm_mode - Checks whether the encryption of the opened mode works on blocks
    • mcrypt_enc_is_block_mode - Checks whether the opened mode outputs blocks
    • mcrypt_enc_self_test - Runs a self test on the opened module
    • mcrypt_generic - This function encrypts data
    • mcrypt_generic_deinit - This function deinitializes an encryption module
    • mcrypt_generic_end - This function terminates encryption
    • mcrypt_generic_init - This function initializes all buffers needed for encryption
    • mcrypt_get_block_size - Gets the block size of the specified cipher
    • mcrypt_get_cipher_name - Gets the name of the specified cipher
    • mcrypt_get_iv_size - Returns the size of the IV belonging to a specific cipher/mode combination
    • mcrypt_get_key_size - Gets the key size of the specified cipher
    • mcrypt_list_algorithms - Gets an array of all supported ciphers
    • mcrypt_list_modes - Gets an array of all supported modes
    • mcrypt_module_close - Closes the mcrypt module
    • mcrypt_module_get_algo_block_size - Returns the blocksize of the specified algorithm
    • mcrypt_module_get_algo_key_size - Returns the maximum supported keysize of the opened mode
    • mcrypt_module_get_supported_key_sizes - Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_module_is_block_algorithm - This function checks whether the specified algorithm is a block algorithm
    • mcrypt_module_is_block_algorithm_mode - Returns if the specified module is a block algorithm or not
    • mcrypt_module_is_block_mode - Returns if the specified mode outputs blocks or not
    • mcrypt_module_open - Opens the module of the algorithm and the mode to be used
    • mcrypt_module_self_test - This function runs a self test on the specified module
    • mcrypt_ofb - Encrypts/decrypts data in OFB mode
    • md5 - Возвращает MD5-хэш строки
    • md5_file - Возвращает MD5-хэш файла
    • mdecrypt_generic - Decrypts data
    • Memcache::add - Add an item to the server
    • Memcache::addServer - Add a memcached server to connection pool
    • Memcache::close - Close memcached server connection
    • Memcache::connect - Open memcached server connection
    • Memcache::decrement - Decrement item's value
    • Memcache::delete - Delete item from the server
    • Memcache::flush - Flush all existing items at the server
    • Memcache::get - Retrieve item from the server
    • Memcache::getExtendedStats - Get statistics from all servers in pool
    • Memcache::getServerStatus - Returns server status
    • Memcache::getStats - Get statistics of the server
    • Memcache::getVersion - Return version of the server
    • Memcache::increment - Increment item's value
    • Memcache::pconnect - Open memcached server persistent connection
    • Memcache::replace - Replace value of the existing item
    • Memcache::set - Store data at the server
    • Memcache::setCompressThreshold - Enable automatic compression of large values
    • Memcache::setServerParams - Changes server parameters and status at runtime
    • Memcached::add - Add an item under a new key
    • Memcached::addByKey - Add an item under a new key on a specific server
    • Memcached::addServer - Add a server to the server pool
    • Memcached::addServers - Add multiple servers to the server pool
    • Memcached::append - Append data to an existing item
    • Memcached::appendByKey - Append data to an existing item on a specific server
    • Memcached::cas - Compare and swap an item
    • Memcached::casByKey - Compare and swap an item on a specific server
    • Memcached::decrement - Decrement numeric item's value
    • Memcached::delete - Delete an item
    • Memcached::deleteByKey - Delete an item from a specific server
    • Memcached::fetch - Fetch the next result
    • Memcached::fetchAll - Fetch all the remaining results
    • Memcached::flush - Invalidate all items in the cache
    • Memcached::get - Retrieve an item
    • Memcached::getByKey - Retrieve an item from a specific server
    • Memcached::getDelayed - Request multiple items
    • Memcached::getDelayedByKey - Request multiple items from a specific server
    • Memcached::getMulti - Retrieve multiple items
    • Memcached::getMultiByKey - Retrieve multiple items from a specific server
    • Memcached::getOption - Retrieve a Memcached option value
    • Memcached::getResultCode - Return the result code of the last operation
    • Memcached::getResultMessage - Return the message describing the result of the last operation
    • Memcached::getServerByKey - Map a key to a server
    • Memcached::getServerList - Get the list of the servers in the pool
    • Memcached::getStats - Get server pool statistics
    • Memcached::getVersion - Get server pool version info
    • Memcached::increment - Increment numeric item's value
    • Memcached::prepend - Prepend data to an existing item
    • Memcached::prependByKey - Prepend data to an existing item on a specific server
    • Memcached::replace - Replace the item under an existing key
    • Memcached::replaceByKey - Replace the item under an existing key on a specific server
    • Memcached::set - Store an item
    • Memcached::setByKey - Store an item on a specific server
    • Memcached::setMulti - Store multiple items
    • Memcached::setMultiByKey - Store multiple items on a specific server
    • Memcached::setOption - Set a Memcached option
    • Memcached::__construct - Create a Memcached instance
    • memcache_debug - Включить/выключить вывод отладочной информации
    • memory_get_peak_usage - Returns the peak of memory allocated by PHP
    • memory_get_usage - Returns the amount of memory allocated to PHP
    • MessageFormatter::create - Constructs a new Message Formatter
    • MessageFormatter::format - Format the message
    • MessageFormatter::formatMessage - Quick format message
    • MessageFormatter::getErrorCode - Get the error code from last operation
    • MessageFormatter::getErrorMessage - Get the error text from the last operation
    • MessageFormatter::getLocale - Get the locale for which the formatter was created.
    • MessageFormatter::getPattern - Get the pattern used by the formatter
    • MessageFormatter::parse - Parse input string according to pattern
    • MessageFormatter::parseMessage - Quick parse input string
    • MessageFormatter::setPattern - Set the pattern used by the formatter
    • metaphone - Возвращает ключ metaphone для строки
    • method_exists - Проверяет, существует ли метод в данном классе
    • mhash - Computes hash
    • mhash_count - Gets the highest available hash ID
    • mhash_get_block_size - Gets the block size of the specified hash
    • mhash_get_hash_name - Gets the name of the specified hash
    • mhash_keygen_s2k - Generates a key
    • microtime - Возвращает текущую метку времени Unix с микросекундами
    • mime_content_type - Определяет MIME-тип содержимого файла (устаревшее)
    • min - Находит наименьшее значение
    • ming_keypress - Returns the action flag for keyPress(char)
    • ming_setcubicthreshold - Set cubic threshold
    • ming_setscale - Set the global scaling factor.
    • ming_setswfcompression - Sets the SWF output compression
    • ming_useconstants - Use constant pool
    • ming_useswfversion - Sets the SWF version
    • mkdir - Создаёт директорию
    • mktime - Возвращает метку времени Unix для заданной даты
    • money_format - Форматирует число как денежную величину
    • Mongo::close - Closes this connection
    • Mongo::connect - Connects to a database server
    • Mongo::connectUtil - Connects with a database server
    • Mongo::dropDB - Drops a database [deprecated]
    • Mongo::getHosts - Updates status for all hosts associated with this
    • Mongo::getPoolSize - Get pool size for connection pools
    • Mongo::getSlave - Returns the address being used by this for slaveOkay reads
    • Mongo::getSlaveOkay - Get slaveOkay setting for this connection
    • Mongo::listDBs - Lists all of the databases available.
    • Mongo::poolDebug - Returns information about all connection pools.
    • Mongo::selectCollection - Gets a database collection
    • Mongo::selectDB - Gets a database
    • Mongo::setPoolSize - Set the size for future connection pools.
    • Mongo::setSlaveOkay - Change slaveOkay setting for this connection
    • Mongo::switchSlave - Choose a new slave for slaveOkay reads
    • Mongo::__construct - Creates a new database connection object
    • Mongo::__get - Gets a database
    • Mongo::__toString - String representation of this connection
    • MongoBinData::__construct - Creates a new binary data object.
    • MongoBinData::__toString - The string representation of this binary data object.
    • MongoCode::__construct - Creates a new code object
    • MongoCode::__toString - Returns this code as a string
    • MongoCollection::batchInsert - Inserts multiple documents into this collection
    • MongoCollection::count - Counts the number of documents in this collection
    • MongoCollection::createDBRef - Creates a database reference
    • MongoCollection::deleteIndex - Deletes an index from this collection
    • MongoCollection::deleteIndexes - Delete all indices for this collection
    • MongoCollection::drop - Drops this collection
    • MongoCollection::ensureIndex - Creates an index on the given field(s), or does nothing if the index already exists
    • MongoCollection::find - Querys this collection, returning a MongoCursor for the result set
    • MongoCollection::findOne - Querys this collection, returning a single element
    • MongoCollection::getDBRef - Fetches the document pointed to by a database reference
    • MongoCollection::getIndexInfo - Returns information about indexes on this collection
    • MongoCollection::getName - Returns this collection's name
    • MongoCollection::getSlaveOkay - Get slaveOkay setting for this collection
    • MongoCollection::group - Performs an operation similar to SQL's GROUP BY command
    • MongoCollection::insert - Inserts an array into the collection
    • MongoCollection::remove - Remove records from this collection
    • MongoCollection::save - Saves an object to this collection
    • MongoCollection::setSlaveOkay - Change slaveOkay setting for this collection
    • MongoCollection::toIndexString - Converts keys specifying an index to its identifying string
    • MongoCollection::update - Update records based on a given criteria
    • MongoCollection::validate - Validates this collection
    • MongoCollection::__construct - Creates a new collection
    • MongoCollection::__get - Gets a collection
    • MongoCollection::__toString - String representation of this collection
    • MongoCursor::addOption - Adds a top-level key/value pair to a query
    • MongoCursor::batchSize - Limits the number of elements returned in one batch.
    • MongoCursor::count - Counts the number of results for this query
    • MongoCursor::current - Returns the current element
    • MongoCursor::dead - Checks if there are documents that have not been sent yet from the database for this cursor
    • MongoCursor::doQuery - Execute the query.
    • MongoCursor::explain - Return an explanation of the query, often useful for optimization and debugging
    • MongoCursor::fields - Sets the fields for a query
    • MongoCursor::getNext - Return the next object to which this cursor points, and advance the cursor
    • MongoCursor::hasNext - Checks if there are any more elements in this cursor
    • MongoCursor::hint - Gives the database a hint about the query
    • MongoCursor::immortal - Sets whether this cursor will timeout
    • MongoCursor::info - Gets the query, fields, limit, and skip for this cursor
    • MongoCursor::key - Returns the current result's _id
    • MongoCursor::limit - Limits the number of results returned
    • MongoCursor::next - Advances the cursor to the next result
    • MongoCursor::partial - If this query should fetch partial results from mongos if a shard is down
    • MongoCursor::reset - Clears the cursor
    • MongoCursor::rewind - Returns the cursor to the beginning of the result set
    • MongoCursor::skip - Skips a number of results
    • MongoCursor::slaveOkay - Sets whether this query can be done on a slave
    • MongoCursor::snapshot - Use snapshot mode for the query
    • MongoCursor::sort - Sorts the results by given fields
    • MongoCursor::tailable - Sets whether this cursor will be left open after fetching the last results
    • MongoCursor::timeout - Sets a client-side timeout for this query
    • MongoCursor::valid - Checks if the cursor is reading a valid result.
    • MongoCursor::__construct - Create a new cursor
    • MongoDate::__construct - Creates a new date.
    • MongoDate::__toString - Returns a string representation of this date
    • MongoDB::authenticate - Log in to this database
    • MongoDB::command - Execute a database command
    • MongoDB::createCollection - Creates a collection
    • MongoDB::createDBRef - Creates a database reference
    • MongoDB::drop - Drops this database
    • MongoDB::dropCollection - Drops a collection [deprecated]
    • MongoDB::execute - Runs JavaScript code on the database server.
    • MongoDB::forceError - Creates a database error
    • MongoDB::getDBRef - Fetches the document pointed to by a database reference
    • MongoDB::getGridFS - Fetches toolkit for dealing with files stored in this database
    • MongoDB::getProfilingLevel - Gets this database's profiling level
    • MongoDB::getSlaveOkay - Get slaveOkay setting for this database
    • MongoDB::lastError - Check if there was an error on the most recent db operation performed
    • MongoDB::listCollections - Get a list of collections in this database
    • MongoDB::prevError - Checks for the last error thrown during a database operation
    • MongoDB::repair - Repairs and compacts this database
    • MongoDB::resetError - Clears any flagged errors on the database
    • MongoDB::selectCollection - Gets a collection
    • MongoDB::setProfilingLevel - Sets this database's profiling level
    • MongoDB::setSlaveOkay - Change slaveOkay setting for this database
    • MongoDB::__construct - Creates a new database
    • MongoDB::__get - Gets a collection
    • MongoDB::__toString - The name of this database
    • MongoDBRef::create - Creates a new database reference
    • MongoDBRef::get - Fetches the object pointed to by a reference
    • MongoDBRef::isRef - Checks if an array is a database reference
    • MongoGridFS::delete - Delete a file from the database
    • MongoGridFS::drop - Drops the files and chunks collections
    • MongoGridFS::find - Queries for files
    • MongoGridFS::findOne - Returns a single file matching the criteria
    • MongoGridFS::get - Retrieve a file from the database
    • MongoGridFS::put - Stores a file in the database
    • MongoGridFS::remove - Removes files from the collections
    • MongoGridFS::storeBytes - Chunkifies and stores bytes in the database
    • MongoGridFS::storeFile - Stores a file in the database
    • MongoGridFS::storeUpload - Saves an uploaded file to the database
    • MongoGridFS::__construct - Creates new file collections
    • MongoGridFSCursor::current - Returns the current file
    • MongoGridFSCursor::getNext - Return the next file to which this cursor points, and advance the cursor
    • MongoGridFSCursor::key - Returns the current result's filename
    • MongoGridFSCursor::__construct - Create a new cursor
    • MongoGridFSFile::getBytes - Returns this file's contents as a string of bytes
    • MongoGridFSFile::getFilename - Returns this file's filename
    • MongoGridFSFile::getResource - Returns a resource that can be used to read the stored file
    • MongoGridFSFile::getSize - Returns this file's size
    • MongoGridFSFile::write - Writes this file to the filesystem
    • MongoGridfsFile::__construct - Create a new GridFS file
    • MongoId::getHostname - Gets the hostname being used for this machine's ids
    • MongoId::getInc - Gets the incremented value to create this id
    • MongoId::getPID - Gets the process id used to create this
    • MongoId::getTimestamp - Gets the number of seconds since the epoch that this id was created
    • MongoId::__construct - Creates a new id
    • MongoId::__set_state - Create a dummy MongoId
    • MongoId::__toString - Returns a hexidecimal representation of this id
    • MongoInt32::__construct - Creates a new 32-bit integer.
    • MongoInt32::__toString - Returns the string representation of this 32-bit integer.
    • MongoInt64::__construct - Creates a new 64-bit integer.
    • MongoInt64::__toString - Returns the string representation of this 64-bit integer.
    • MongoLog::getLevel - Gets the log level
    • MongoLog::getModule - Gets the modules currently being logged
    • MongoLog::setLevel - Sets logging level
    • MongoLog::setModule - Sets driver functionality to log
    • MongoPool::getSize - Get pool size for connection pools
    • MongoPool::info - Returns information about all connection pools.
    • MongoPool::setSize - Set the size for future connection pools.
    • MongoRegex::__construct - Creates a new regular expression
    • MongoRegex::__toString - A string representation of this regular expression
    • MongoTimestamp::__construct - Creates a new timestamp.
    • MongoTimestamp::__toString - Returns a string representation of this timestamp
    • move_uploaded_file - Перемещает загруженный файл в новое место
    • mqseries_back - MQSeries MQBACK
    • mqseries_begin - MQseries MQBEGIN
    • mqseries_close - MQSeries MQCLOSE
    • mqseries_cmit - MQSeries MQCMIT
    • mqseries_conn - MQSeries MQCONN
    • mqseries_connx - MQSeries MQCONNX
    • mqseries_disc - MQSeries MQDISC
    • mqseries_get - MQSeries MQGET
    • mqseries_inq - MQSeries MQINQ
    • mqseries_open - MQSeries MQOPEN
    • mqseries_put - MQSeries MQPUT
    • mqseries_put1 - MQSeries MQPUT1
    • mqseries_set - MQSeries MQSET
    • mqseries_strerror - Returns the error message corresponding to a result code (MQRC).
    • msession_connect - Connect to msession server
    • msession_count - Get session count
    • msession_create - Create a session
    • msession_destroy - Destroy a session
    • msession_disconnect - Close connection to msession server
    • msession_find - Find all sessions with name and value
    • msession_get - Get value from session
    • msession_get_array - Get array of msession variables
    • msession_get_data - Get data session unstructured data
    • msession_inc - Increment value in session
    • msession_list - List all sessions
    • msession_listvar - List sessions with variable
    • msession_lock - Lock a session
    • msession_plugin - Call an escape function within the msession personality plugin
    • msession_randstr - Get random string
    • msession_set - Set value in session
    • msession_set_array - Set msession variables from an array
    • msession_set_data - Set data session unstructured data
    • msession_timeout - Set/get session timeout
    • msession_uniq - Get unique id
    • msession_unlock - Unlock a session
    • msg_get_queue - Create or attach to a message queue
    • msg_queue_exists - Check whether a message queue exists
    • msg_receive - Receive a message from a message queue
    • msg_remove_queue - Destroy a message queue
    • msg_send - Send a message to a message queue
    • msg_set_queue - Set information in the message queue data structure
    • msg_stat_queue - Returns information from the message queue data structure
    • msql - Alias of msql_db_query
    • msql_affected_rows - Returns number of affected rows
    • msql_close - Close mSQL connection
    • msql_connect - Open mSQL connection
    • msql_createdb - Псевдоним msql_create_db
    • msql_create_db - Create mSQL database
    • msql_data_seek - Move internal row pointer
    • msql_dbname - Псевдоним msql_result
    • msql_db_query - Send mSQL query
    • msql_drop_db - Drop (delete) mSQL database
    • msql_error - Returns error message of last msql call
    • msql_fetch_array - Fetch row as array
    • msql_fetch_field - Get field information
    • msql_fetch_object - Fetch row as object
    • msql_fetch_row - Get row as enumerated array
    • msql_fieldflags - Alias of msql_field_flags
    • msql_fieldlen - Alias of msql_field_len
    • msql_fieldname - Alias of msql_field_name
    • msql_fieldtable - Alias of msql_field_table
    • msql_fieldtype - Alias of msql_field_type
    • msql_field_flags - Get field flags
    • msql_field_len - Get field length
    • msql_field_name - Get the name of the specified field in a result
    • msql_field_seek - Set field offset
    • msql_field_table - Get table name for field
    • msql_field_type - Get field type
    • msql_free_result - Free result memory
    • msql_list_dbs - List mSQL databases on server
    • msql_list_fields - List result fields
    • msql_list_tables - List tables in an mSQL database
    • msql_numfields - Alias of msql_num_fields
    • msql_numrows - Alias of msql_num_rows
    • msql_num_fields - Get number of fields in result
    • msql_num_rows - Get number of rows in result
    • msql_pconnect - Open persistent mSQL connection
    • msql_query - Send mSQL query
    • msql_regcase - Alias of sql_regcase
    • msql_result - Get result data
    • msql_select_db - Select mSQL database
    • msql_tablename - Alias of msql_result
    • mssql_bind - Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close - Close MS SQL Server connection
    • mssql_connect - Open MS SQL server connection
    • mssql_data_seek - Moves internal row pointer
    • mssql_execute - Executes a stored procedure on a MS SQL server database
    • mssql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • mssql_fetch_assoc - Returns an associative array of the current row in the result
    • mssql_fetch_batch - Returns the next batch of records
    • mssql_fetch_field - Get field information
    • mssql_fetch_object - Fetch row as object
    • mssql_fetch_row - Get row as enumerated array
    • mssql_field_length - Get the length of a field
    • mssql_field_name - Get the name of a field
    • mssql_field_seek - Seeks to the specified field offset
    • mssql_field_type - Gets the type of a field
    • mssql_free_result - Free result memory
    • mssql_free_statement - Free statement memory
    • mssql_get_last_message - Returns the last message from the server
    • mssql_guid_string - Converts a 16 byte binary GUID to a string
    • mssql_init - Initializes a stored procedure or a remote stored procedure
    • mssql_min_error_severity - Sets the minimum error severity
    • mssql_min_message_severity - Sets the minimum message severity
    • mssql_next_result - Move the internal result pointer to the next result
    • mssql_num_fields - Gets the number of fields in result
    • mssql_num_rows - Gets the number of rows in result
    • mssql_pconnect - Open persistent MS SQL connection
    • mssql_query - Send MS SQL query
    • mssql_result - Get result data
    • mssql_rows_affected - Returns the number of records affected by the query
    • mssql_select_db - Select MS SQL database
    • mt_getrandmax - Показывает максимально возможное значение случайного числа
    • mt_rand - Генерирует случайное значение методом mt
    • mt_srand - Переинициализирует генератор случайных чисел mt
    • MultipleIterator::attachIterator - Присоединяет итератор
    • MultipleIterator::containsIterator - Проверяет, присоединен ли итератор
    • MultipleIterator::countIterators - Получает число присоединенных итераторов
    • MultipleIterator::current - Получает зарегистрированные итераторы
    • MultipleIterator::detachIterator - Отсоединяет итератор
    • MultipleIterator::getFlags - Получает информацию о флагах
    • MultipleIterator::key - Получает зарегистрированные итераторы
    • MultipleIterator::next - Перемещает все присоединенные итераторы к своим следующим элементам
    • MultipleIterator::rewind - Возвращает в начало все присоединенные итераторы
    • MultipleIterator::setFlags - Устанавливает флаги
    • MultipleIterator::valid - Проверяет корректность подытераторов
    • MultipleIterator::__construct - Создает новый MultipleIterator
    • mysqli::$affected_rows - Получает число строк, затронутых предыдущей операцией MySQL
    • mysqli::$client_info - Возвращает версию клиента MySQL в виде строки
    • mysqli::$client_version - Получает информацию о клиенте MySQL
    • mysqli::$connect_errno - Возвращает код ошибки последней попытки соединения
    • mysqli::$connect_error - Возвращает описание последней ошибки подключения
    • mysqli::$errno - Возвращает код ошибки последнего вызова функции
    • mysqli::$error - Returns a string description of the last error
    • mysqli::$error_list - Returns a list of errors from the last command executed
    • mysqli::$field_count - Возвращает число столбцов, затронутых последним запросом
    • mysqli::$host_info - Возвращает строку, содержащую тип используемого соединения
    • mysqli::$info - Retrieves information about the most recently executed query
    • mysqli::$insert_id - Возвращает автоматически генерируемый ID, используя последний запрос
    • mysqli::$protocol_version - Возвращает версию используемого MySQL протокола
    • mysqli::$server_info - Возвращает версию MySQL сервера
    • mysqli::$server_version - Возвращает версию сервера MySQL, представленую в виде integer
    • mysqli::$sqlstate - Returns the SQLSTATE error from previous MySQL operation
    • mysqli::$thread_id - Returns the thread ID for the current connection
    • mysqli::$warning_count - Returns the number of warnings from the last query for the given link
    • mysqli::autocommit - Включает или отключает автоматическую фиксацию изменений базы данных
    • mysqli::change_user - Позволяет сменить пользователя подключенного к базе данных
    • mysqli::character_set_name - Возвращает кодировку по умолчанию, установленную для соединения с БД
    • mysqli::close - Closes a previously opened database connection
    • mysqli::commit - Фиксирует текущую транзакцию
    • mysqli::debug - Выполняет процедуры отладки
    • mysqli::disable_reads_from_master - Disable reads from master
    • mysqli::dump_debug_info - Журналирование отладочной информации
    • mysqli::get_charset - Returns a character set object
    • mysqli::get_client_info - Возвращает версию клиента MySQL в виде строки
    • mysqli::get_connection_stats - Возвращает статистику соединения с клиентом
    • mysqli::get_warnings - Get result of SHOW WARNINGS
    • mysqli::init - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
    • mysqli::kill - Asks the server to kill a MySQL thread
    • mysqli::more_results - Check if there are any more query results from a multi query
    • mysqli::multi_query - Performs a query on the database
    • mysqli::next_result - Prepare next result from multi_query
    • mysqli::options - Set options
    • mysqli::ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • mysqli::poll - Poll connections
    • mysqli::prepare - Prepare an SQL statement for execution
    • mysqli::query - Performs a query on the database
    • mysqli::real_connect - Opens a connection to a mysql server
    • mysqli::real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • mysqli::real_query - Execute an SQL query
    • mysqli::reap_async_query - Get result from async query
    • mysqli::refresh - Refreshes
    • mysqli::rollback - Rolls back current transaction
    • mysqli::rpl_query_type - Returns RPL query type
    • mysqli::select_db - Устанавливает базу данных для выполняемых запросов
    • mysqli::send_query - Send the query and return
    • mysqli::set_charset - Sets the default client character set
    • mysqli::set_local_infile_default - Unsets user defined handler for load local infile command
    • mysqli::set_local_infile_handler - Set callback function for LOAD DATA LOCAL INFILE command
    • mysqli::ssl_set - Used for establishing secure connections using SSL
    • mysqli::stat - Gets the current system status
    • mysqli::stmt_init - Initializes a statement and returns an object for use with mysqli_stmt_prepare
    • mysqli::store_result - Transfers a result set from the last query
    • mysqli::thread_safe - Returns whether thread safety is given or not
    • mysqli::use_result - Initiate a result set retrieval
    • mysqli::__construct - Open a new connection to the MySQL server
    • mysqli_bind_param - Синоним функции mysqli_stmt_bind_param
    • mysqli_bind_result - Синоним функции mysqli_stmt_bind_result
    • mysqli_client_encoding - Синоним функции mysqli_character_set_name
    • mysqli_connect - Псевдоним mysqli::__construct
    • mysqli_disable_rpl_parse - Блокировать разбор RPL
    • mysqli_driver::embedded_server_end - Stop embedded server
    • mysqli_driver::embedded_server_start - Initialize and start embedded server
    • mysqli_enable_reads_from_master - Включает чтение с мастера
    • mysqli_enable_rpl_parse - Включает разбор RPL
    • mysqli_escape_string - Псевдоним функции mysqli_real_escape_string
    • mysqli_execute - Синоним для mysqli_stmt_execute
    • mysqli_fetch - Синоним для mysqli_stmt_fetch
    • mysqli_get_cache_stats - Returns client Zval cache statistics
    • mysqli_get_client_stats - Возвращает статистику клиента для каждого процесса
    • mysqli_get_metadata - Синоним для mysqli_stmt_result_metadata
    • mysqli_master_query - Enforce execution of a query on the master in a master/slave setup
    • mysqli_param_count - Синоним для mysqli_stmt_param_count
    • mysqli_report - Enables or disables internal report functions
    • mysqli_result::$current_field - Получает смещение указателя по отношению к текущему полю
    • mysqli_result::$field_count - Get the number of fields in a result
    • mysqli_result::$lengths - Returns the lengths of the columns of the current row in the result set
    • mysqli_result::$num_rows - Получает число рядов в результирующей выборке
    • mysqli_result::data_seek - Adjusts the result pointer to an arbitary row in the result
    • mysqli_result::fetch_all - Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array - Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc - Извлекает результирующий ряд в виде ассоциативного массива
    • mysqli_result::fetch_field - Returns the next field in the result set
    • mysqli_result::fetch_fields - Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_field_direct - Fetch meta-data for a single field
    • mysqli_result::fetch_object - Returns the current row of a result set as an object
    • mysqli_result::fetch_row - Get a result row as an enumerated array
    • mysqli_result::field_seek - Установить указатель поля на определенное смещение
    • mysqli_result::free - Frees the memory associated with a result
    • mysqli_rpl_parse_enabled - Check if RPL parse is enabled
    • mysqli_rpl_probe - RPL probe
    • mysqli_send_long_data - Синоним для mysqli_stmt_send_long_data
    • mysqli_set_opt - Синоним для mysqli_options
    • mysqli_slave_query - Force execution of a query on a slave in a master/slave setup
    • mysqli_stmt::$affected_rows - Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • mysqli_stmt::$errno - Returns the error code for the most recent statement call
    • mysqli_stmt::$error - Returns a string description for last statement error
    • mysqli_stmt::$error_list - Returns a list of errors from the last statement executed
    • mysqli_stmt::$field_count - Возвращает число полей в заданном выражении
    • mysqli_stmt::$insert_id - Получает ID сгенерированный предыдущей операцией INSERT
    • mysqli_stmt::$num_rows - Возвращает число строк в результате запроса
    • mysqli_stmt::$param_count - Returns the number of parameter for the given statement
    • mysqli_stmt::$sqlstate - Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::attr_get - Получает текущее значение атрибута запроса
    • mysqli_stmt::attr_set - Изменяет поведение подготовленного запроса
    • mysqli_stmt::bind_param - Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result - Binds variables to a prepared statement for result storage
    • mysqli_stmt::close - Закрывает подготовленный запрос
    • mysqli_stmt::data_seek - Seeks to an arbitrary row in statement result set
    • mysqli_stmt::execute - Executes a prepared Query
    • mysqli_stmt::fetch - Связывает результаты подготовленного выражения с переменными
    • mysqli_stmt::free_result - Освобождает память от результата запроса, указанного дескриптором
    • mysqli_stmt::get_result - Получает результат из подготовленного запроса
    • mysqli_stmt::get_warnings - Получает результат от SHOW WARNINGS
    • mysqli_stmt::more_results - Check if there are more query results from a multiple query
    • mysqli_stmt::next_result - Reads the next result from a multiple query
    • mysqli_stmt::prepare - Prepare an SQL statement for execution
    • mysqli_stmt::reset - Resets a prepared statement
    • mysqli_stmt::result_metadata - Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data - Send data in blocks
    • mysqli_stmt::store_result - Transfers a result set from a prepared statement
    • mysqli_warning::next - The next purpose
    • mysqli_warning::__construct - The __construct purpose
    • MysqlndUhConnection::changeUser - Changes the user of the specified mysqlnd database connection
    • MysqlndUhConnection::charsetName - Returns the default character set for the database connection
    • MysqlndUhConnection::close - Closes a previously opened database connection
    • MysqlndUhConnection::connect - Open a new connection to the MySQL server
    • MysqlndUhConnection::endPSession - End a persistent connection
    • MysqlndUhConnection::escapeString - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • MysqlndUhConnection::getAffectedRows - Gets the number of affected rows in a previous MySQL operation
    • MysqlndUhConnection::getErrorNumber - Returns the error code for the most recent function call
    • MysqlndUhConnection::getErrorString - Returns a string description of the last error
    • MysqlndUhConnection::getFieldCount - Returns the number of columns for the most recent query
    • MysqlndUhConnection::getHostInformation - Returns a string representing the type of connection used
    • MysqlndUhConnection::getLastInsertId - Returns the auto generated id used in the last query.
    • MysqlndUhConnection::getLastMessage - Retrieves information about the most recently executed query
    • MysqlndUhConnection::getProtocolInformation - Returns the version of the MySQL protocol used
    • MysqlndUhConnection::getServerInformation - Returns the version of the MySQL server
    • MysqlndUhConnection::getServerStatistics - Gets the current system status
    • MysqlndUhConnection::getServerVersion - Returns the version of the MySQL server as an integer
    • MysqlndUhConnection::getSqlstate - Returns the SQLSTATE error from previous MySQL operation
    • MysqlndUhConnection::getStatistics - Returns statistics about the client connection.
    • MysqlndUhConnection::getThreadId - Returns the thread ID for the current connection
    • MysqlndUhConnection::getWarningCount - Returns the number of warnings from the last query for the given link
    • MysqlndUhConnection::init - Initialize mysqlnd connection
    • MysqlndUhConnection::killConnection - Asks the server to kill a MySQL thread
    • MysqlndUhConnection::listFields - List MySQL table fields
    • MysqlndUhConnection::listMethod - Wrapper for assorted list commands
    • MysqlndUhConnection::moreResults - Check if there are any more query results from a multi query
    • MysqlndUhConnection::nextResult - Prepare next result from multi_query
    • MysqlndUhConnection::ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • MysqlndUhConnection::query - Performs a query on the database
    • MysqlndUhConnection::queryReadResultsetHeader - Read a result set header
    • MysqlndUhConnection::reapQuery - Get result from async query
    • MysqlndUhConnection::refreshServer - Flush or reset tables and caches
    • MysqlndUhConnection::restartPSession - Restart a persistent mysqlnd connection
    • MysqlndUhConnection::selectDb - Selects the default database for database queries
    • MysqlndUhConnection::sendClose - Sends a close command to MySQL
    • MysqlndUhConnection::sendQuery - Sends a query to MySQL
    • MysqlndUhConnection::serverDumpDebugInformation - Dump debugging information into the log for the MySQL server
    • MysqlndUhConnection::setAutocommit - Turns on or off auto-commiting database modifications
    • MysqlndUhConnection::setCharset - Sets the default client character set
    • MysqlndUhConnection::setClientOption - Sets a client option
    • MysqlndUhConnection::setServerOption - Sets a server option
    • MysqlndUhConnection::shutdownServer - The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand - Sends a basic COM_* command
    • MysqlndUhConnection::simpleCommandHandleResponse - Process a response for a basic COM_* command send to the client
    • MysqlndUhConnection::sslSet - Used for establishing secure connections using SSL
    • MysqlndUhConnection::stmtInit - Initializes a statement and returns a resource for use with mysqli_statement::prepare
    • MysqlndUhConnection::storeResult - Transfers a result set from the last query
    • MysqlndUhConnection::txCommit - Commits the current transaction
    • MysqlndUhConnection::txRollback - Rolls back current transaction
    • MysqlndUhConnection::useResult - Initiate a result set retrieval
    • MysqlndUhConnection::__construct - The __construct purpose
    • MysqlndUhPreparedStatement::execute - Executes a prepared Query
    • MysqlndUhPreparedStatement::prepare - Prepare an SQL statement for execution
    • MysqlndUhPreparedStatement::__construct - The __construct purpose
    • mysqlnd_ms_get_last_gtid - Returns the latest global transaction ID
    • mysqlnd_ms_get_last_used_connection - Returns an array which describes the last used connection
    • mysqlnd_ms_get_stats - Returns query distribution and connection statistics
    • mysqlnd_ms_match_wild - Finds whether a table name matches a wildcard pattern or not
    • mysqlnd_ms_query_is_select - Find whether to send the query to the master, the slave or the last used MySQL server
    • mysqlnd_ms_set_qos - Sets the quality of service needed from the cluster
    • mysqlnd_ms_set_user_pick_server - Sets a callback for user-defined read/write splitting
    • mysqlnd_qc_clear_cache - Flush all cache contents
    • mysqlnd_qc_get_available_handlers - Returns a list of available storage handler
    • mysqlnd_qc_get_cache_info - Returns information on the current handler, the number of cache entries and cache entries, if available
    • mysqlnd_qc_get_core_stats - Statistics collected by the core of the query cache
    • mysqlnd_qc_get_normalized_query_trace_log - Returns a normalized query trace log for each query inspected by the query cache
    • mysqlnd_qc_get_query_trace_log - Returns a backtrace for each query inspected by the query cache
    • mysqlnd_qc_set_cache_condition - Set conditions for automatic caching
    • mysqlnd_qc_set_is_select - Installs a callback which decides whether a statement is cached
    • mysqlnd_qc_set_storage_handler - Change current storage handler
    • mysqlnd_qc_set_user_handlers - Sets the callback functions for a user-defined procedural storage handler
    • mysqlnd_uh_convert_to_mysqlnd - Converts a MySQL connection handle into a mysqlnd connection handle
    • mysqlnd_uh_set_connection_proxy - Installs a proxy for mysqlnd connections
    • mysqlnd_uh_set_statement_proxy - Installs a proxy for mysqlnd statements
    • mysql_affected_rows - Возвращает число затронутых прошлой операцией рядов
    • mysql_client_encoding - Возвращает кодировку соединения
    • mysql_close - Закрывает соединение с сервером MySQL
    • mysql_connect - Открывает соединение с сервером MySQL
    • mysql_create_db - Создает базу данных MySQL
    • mysql_data_seek - Перемещает внутренний указатель в результате запроса
    • mysql_db_name - Возвращает название базы данных из вызова к mysql_list_dbs
    • mysql_db_query - Переключается на указанную базу данных и посылает запрос
    • mysql_drop_db - Уничтожает базу данных MySQL
    • mysql_errno - Возвращает численный код ошибки выполнения последней операции с MySQL
    • mysql_error - Возвращает текст ошибки последней операции с MySQL
    • mysql_escape_string - Экранирует строку для использования в mysql_query
    • mysql_fetch_array - Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба
    • mysql_fetch_assoc - Возвращает ряд результата запроса в качестве ассоциативного массива
    • mysql_fetch_field - Возвращает информацию о колонке из результата запроса в виде объекта
    • mysql_fetch_lengths - Возвращает длину каждого поля в результате
    • mysql_fetch_object - Обрабатывает ряд результата запроса и возвращает объект
    • mysql_fetch_row - Обрабатывает ряд результата запроса и возвращает массив с числовыми индексами
    • mysql_field_flags - Возвращает флаги, связанные с указанным полем результата запроса
    • mysql_field_len - Возвращает длину указанного поля
    • mysql_field_name - Возвращает название указанной колонки результата запроса
    • mysql_field_seek - Устанавливает внутренний указатель результата на переданное смещение поля
    • mysql_field_table - Возвращает название таблицы, которой принадлежит указанное поле
    • mysql_field_type - Возвращает тип указанного поля из результата запроса
    • mysql_free_result - Освобождает память от результата запроса
    • mysql_get_client_info - Возвращает данные о MySQL-клиенте
    • mysql_get_host_info - Возвращает информацию о соединении с MySQL
    • mysql_get_proto_info - Возвращает информацию о протоколе MySQL
    • mysql_get_server_info - Возвращает информацию о сервере MySQL
    • mysql_info - Возвращает информацию о последнем запросе
    • mysql_insert_id - Возвращает идентификатор, сгенерированный при последнем INSERT-запросе
    • mysql_list_dbs - Возвращает список баз данных, доступных на сервере
    • mysql_list_fields - Возвращает список колонок таблицы
    • mysql_list_processes - Возвращает список процессов MySQL
    • mysql_list_tables - Возвращает список таблиц базы данных MySQL
    • mysql_num_fields - Возвращает количество полей результата запроса
    • mysql_num_rows - Возвращает количество рядов результата запроса
    • mysql_pconnect - Устанавливает постоянное соединение с сервером MySQL
    • mysql_ping - Проверяет соединение с сервером и пересоединяется при необходимости
    • mysql_query - Посылает запрос MySQL
    • mysql_real_escape_string - Экранирует специальные символы в строках для использования в выражениях SQL
    • mysql_result - Возвращает данные результата запроса
    • mysql_select_db - Выбирает базу данных MySQL
    • mysql_set_charset - Устанавливает кодировку клиента
    • mysql_stat - Возвращает текущий статус сервера
    • mysql_tablename - Возвращает имя таблицы, содержащей указанное поле
    • mysql_thread_id - Возвращает идентификатор текущего потока
    • mysql_unbuffered_query - Посылает запрос MySQL без авто-обработки результата и его буферизации
    • m_checkstatus - Check to see if a transaction has completed
    • m_completeauthorizations - Number of complete authorizations in queue, returning an array of their identifiers
    • m_connect - Establish the connection to MCVE
    • m_connectionerror - Get a textual representation of why a connection failed
    • m_deletetrans - Delete specified transaction from MCVE_CONN structure
    • m_destroyconn - Destroy the connection and MCVE_CONN structure
    • m_destroyengine - Free memory associated with IP/SSL connectivity
    • m_getcell - Get a specific cell from a comma delimited response by column name
    • m_getcellbynum - Get a specific cell from a comma delimited response by column number
    • m_getcommadelimited - Get the RAW comma delimited data returned from MCVE
    • m_getheader - Get the name of the column in a comma-delimited response
    • m_initconn - Create and initialize an MCVE_CONN structure
    • m_initengine - Ready the client for IP/SSL Communication
    • m_iscommadelimited - Checks to see if response is comma delimited
    • m_maxconntimeout - The maximum amount of time the API will attempt a connection to MCVE
    • m_monitor - Perform communication with MCVE (send/receive data) Non-blocking
    • m_numcolumns - Number of columns returned in a comma delimited response
    • m_numrows - Number of rows returned in a comma delimited response
    • m_parsecommadelimited - Parse the comma delimited response so m_getcell, etc will work
    • m_responsekeys - Returns array of strings which represents the keys that can be used for response parameters on this transaction
    • m_responseparam - Get a custom response parameter
    • m_returnstatus - Check to see if the transaction was successful
    • m_setblocking - Set blocking/non-blocking mode for connection
    • m_setdropfile - Set the connection method to Drop-File
    • m_setip - Set the connection method to IP
    • m_setssl - Set the connection method to SSL
    • m_setssl_cafile - Set SSL CA (Certificate Authority) file for verification of server certificate
    • m_setssl_files - Set certificate key files and certificates if server requires client certificate verification
    • m_settimeout - Set maximum transaction time (per trans)
    • m_sslcert_gen_hash - Generate hash for SSL client certificate verification
    • m_transactionssent - Check to see if outgoing buffer is clear
    • m_transinqueue - Number of transactions in client-queue
    • m_transkeyval - Add key/value pair to a transaction. Replaces deprecated transparam()
    • m_transnew - Start a new transaction
    • m_transsend - Finalize and send the transaction
    • m_uwait - Wait x microsecs
    • m_validateidentifier - Whether or not to validate the passed identifier on any transaction it is passed to
    • m_verifyconnection - Set whether or not to PING upon connect to verify connection
    • m_verifysslcert - Set whether or not to verify the server ssl certificate
  • n
    • natcasesort - Сортирует массив, используя алгоритм "natural order" без учета регистра символов
    • natsort - Сортирует массив, используя алгоритм "natural order"
    • ncurses_addch - Add character at current position and advance cursor
    • ncurses_addchnstr - Add attributed string with specified length at current position
    • ncurses_addchstr - Add attributed string at current position
    • ncurses_addnstr - Add string with specified length at current position
    • ncurses_addstr - Output text at current position
    • ncurses_assume_default_colors - Define default colors for color 0
    • ncurses_attroff - Turn off the given attributes
    • ncurses_attron - Turn on the given attributes
    • ncurses_attrset - Set given attributes
    • ncurses_baudrate - Returns baudrate of terminal
    • ncurses_beep - Let the terminal beep
    • ncurses_bkgd - Set background property for terminal screen
    • ncurses_bkgdset - Control screen background
    • ncurses_border - Draw a border around the screen using attributed characters
    • ncurses_bottom_panel - Moves a visible panel to the bottom of the stack
    • ncurses_can_change_color - Checks if terminal color definitions can be changed
    • ncurses_cbreak - Switch of input buffering
    • ncurses_clear - Clear screen
    • ncurses_clrtobot - Clear screen from current position to bottom
    • ncurses_clrtoeol - Clear screen from current position to end of line
    • ncurses_color_content - Retrieves RGB components of a color
    • ncurses_color_set - Set active foreground and background colors
    • ncurses_curs_set - Set cursor state
    • ncurses_define_key - Define a keycode
    • ncurses_def_prog_mode - Saves terminals (program) mode
    • ncurses_def_shell_mode - Saves terminals (shell) mode
    • ncurses_delay_output - Delay output on terminal using padding characters
    • ncurses_delch - Delete character at current position, move rest of line left
    • ncurses_deleteln - Delete line at current position, move rest of screen up
    • ncurses_delwin - Delete a ncurses window
    • ncurses_del_panel - Remove panel from the stack and delete it (but not the associated window)
    • ncurses_doupdate - Write all prepared refreshes to terminal
    • ncurses_echo - Activate keyboard input echo
    • ncurses_echochar - Single character output including refresh
    • ncurses_end - Stop using ncurses, clean up the screen
    • ncurses_erase - Erase terminal screen
    • ncurses_erasechar - Returns current erase character
    • ncurses_filter - Set LINES for iniscr() and newterm() to 1
    • ncurses_flash - Flash terminal screen (visual bell)
    • ncurses_flushinp - Flush keyboard input buffer
    • ncurses_getch - Read a character from keyboard
    • ncurses_getmaxyx - Returns the size of a window
    • ncurses_getmouse - Reads mouse event
    • ncurses_getyx - Returns the current cursor position for a window
    • ncurses_halfdelay - Put terminal into halfdelay mode
    • ncurses_has_colors - Checks if terminal has color capabilities
    • ncurses_has_ic - Check for insert- and delete-capabilities
    • ncurses_has_il - Check for line insert- and delete-capabilities
    • ncurses_has_key - Check for presence of a function key on terminal keyboard
    • ncurses_hide_panel - Remove panel from the stack, making it invisible
    • ncurses_hline - Draw a horizontal line at current position using an attributed character and max. n characters long
    • ncurses_inch - Get character and attribute at current position
    • ncurses_init - Initialize ncurses
    • ncurses_init_color - Define a terminal color
    • ncurses_init_pair - Define a color pair
    • ncurses_insch - Insert character moving rest of line including character at current position
    • ncurses_insdelln - Insert lines before current line scrolling down (negative numbers delete and scroll up)
    • ncurses_insertln - Insert a line, move rest of screen down
    • ncurses_insstr - Insert string at current position, moving rest of line right
    • ncurses_instr - Reads string from terminal screen
    • ncurses_isendwin - Ncurses is in endwin mode, normal screen output may be performed
    • ncurses_keyok - Enable or disable a keycode
    • ncurses_keypad - Turns keypad on or off
    • ncurses_killchar - Returns current line kill character
    • ncurses_longname - Returns terminals description
    • ncurses_meta - Enables/Disable 8-bit meta key information
    • ncurses_mouseinterval - Set timeout for mouse button clicks
    • ncurses_mousemask - Sets mouse options
    • ncurses_mouse_trafo - Transforms coordinates
    • ncurses_move - Move output position
    • ncurses_move_panel - Moves a panel so that its upper-left corner is at [startx, starty]
    • ncurses_mvaddch - Move current position and add character
    • ncurses_mvaddchnstr - Move position and add attributed string with specified length
    • ncurses_mvaddchstr - Move position and add attributed string
    • ncurses_mvaddnstr - Move position and add string with specified length
    • ncurses_mvaddstr - Move position and add string
    • ncurses_mvcur - Move cursor immediately
    • ncurses_mvdelch - Move position and delete character, shift rest of line left
    • ncurses_mvgetch - Move position and get character at new position
    • ncurses_mvhline - Set new position and draw a horizontal line using an attributed character and max. n characters long
    • ncurses_mvinch - Move position and get attributed character at new position
    • ncurses_mvvline - Set new position and draw a vertical line using an attributed character and max. n characters long
    • ncurses_mvwaddstr - Add string at new position in window
    • ncurses_napms - Sleep
    • ncurses_newpad - Creates a new pad (window)
    • ncurses_newwin - Create a new window
    • ncurses_new_panel - Create a new panel and associate it with window
    • ncurses_nl - Translate newline and carriage return / line feed
    • ncurses_nocbreak - Switch terminal to cooked mode
    • ncurses_noecho - Switch off keyboard input echo
    • ncurses_nonl - Do not translate newline and carriage return / line feed
    • ncurses_noqiflush - Do not flush on signal characters
    • ncurses_noraw - Switch terminal out of raw mode
    • ncurses_pair_content - Retrieves foreground and background colors of a color pair
    • ncurses_panel_above - Returns the panel above panel
    • ncurses_panel_below - Returns the panel below panel
    • ncurses_panel_window - Returns the window associated with panel
    • ncurses_pnoutrefresh - Copies a region from a pad into the virtual screen
    • ncurses_prefresh - Copies a region from a pad into the virtual screen
    • ncurses_putp - Apply padding information to the string and output it
    • ncurses_qiflush - Flush on signal characters
    • ncurses_raw - Switch terminal into raw mode
    • ncurses_refresh - Refresh screen
    • ncurses_replace_panel - Replaces the window associated with panel
    • ncurses_resetty - Restores saved terminal state
    • ncurses_reset_prog_mode - Resets the prog mode saved by def_prog_mode
    • ncurses_reset_shell_mode - Resets the shell mode saved by def_shell_mode
    • ncurses_savetty - Saves terminal state
    • ncurses_scrl - Scroll window content up or down without changing current position
    • ncurses_scr_dump - Dump screen content to file
    • ncurses_scr_init - Initialize screen from file dump
    • ncurses_scr_restore - Restore screen from file dump
    • ncurses_scr_set - Inherit screen from file dump
    • ncurses_show_panel - Places an invisible panel on top of the stack, making it visible
    • ncurses_slk_attr - Returns current soft label key attribute
    • ncurses_slk_attroff - Turn off the given attributes for soft function-key labels
    • ncurses_slk_attron - Turn on the given attributes for soft function-key labels
    • ncurses_slk_attrset - Set given attributes for soft function-key labels
    • ncurses_slk_clear - Clears soft labels from screen
    • ncurses_slk_color - Sets color for soft label keys
    • ncurses_slk_init - Initializes soft label key functions
    • ncurses_slk_noutrefresh - Copies soft label keys to virtual screen
    • ncurses_slk_refresh - Copies soft label keys to screen
    • ncurses_slk_restore - Restores soft label keys
    • ncurses_slk_set - Sets function key labels
    • ncurses_slk_touch - Forces output when ncurses_slk_noutrefresh is performed
    • ncurses_standend - Stop using 'standout' attribute
    • ncurses_standout - Start using 'standout' attribute
    • ncurses_start_color - Initializes color functionality
    • ncurses_termattrs - Returns a logical OR of all attribute flags supported by terminal
    • ncurses_termname - Returns terminals (short)-name
    • ncurses_timeout - Set timeout for special key sequences
    • ncurses_top_panel - Moves a visible panel to the top of the stack
    • ncurses_typeahead - Specify different filedescriptor for typeahead checking
    • ncurses_ungetch - Put a character back into the input stream
    • ncurses_ungetmouse - Pushes mouse event to queue
    • ncurses_update_panels - Refreshes the virtual screen to reflect the relations between panels in the stack
    • ncurses_use_default_colors - Assign terminal default colors to color id -1
    • ncurses_use_env - Control use of environment information about terminal size
    • ncurses_use_extended_names - Control use of extended names in terminfo descriptions
    • ncurses_vidattr - Display the string on the terminal in the video attribute mode
    • ncurses_vline - Draw a vertical line at current position using an attributed character and max. n characters long
    • ncurses_waddch - Adds character at current position in a window and advance cursor
    • ncurses_waddstr - Outputs text at current postion in window
    • ncurses_wattroff - Turns off attributes for a window
    • ncurses_wattron - Turns on attributes for a window
    • ncurses_wattrset - Set the attributes for a window
    • ncurses_wborder - Draws a border around the window using attributed characters
    • ncurses_wclear - Clears window
    • ncurses_wcolor_set - Sets windows color pairings
    • ncurses_werase - Erase window contents
    • ncurses_wgetch - Reads a character from keyboard (window)
    • ncurses_whline - Draws a horizontal line in a window at current position using an attributed character and max. n characters long
    • ncurses_wmouse_trafo - Transforms window/stdscr coordinates
    • ncurses_wmove - Moves windows output position
    • ncurses_wnoutrefresh - Copies window to virtual screen
    • ncurses_wrefresh - Refresh window on terminal screen
    • ncurses_wstandend - End standout mode for a window
    • ncurses_wstandout - Enter standout mode for a window
    • ncurses_wvline - Draws a vertical line in a window at current position using an attributed character and max. n characters long
    • newt_bell - Send a beep to the terminal
    • newt_button - Create a new button
    • newt_button_bar - This function returns a grid containing the buttons created.
    • newt_centered_window - Open a centered window of the specified size
    • newt_checkbox - Описание
    • newt_checkbox_get_value - Retreives value of checkox resource
    • newt_checkbox_set_flags - Configures checkbox resource
    • newt_checkbox_set_value - Sets the value of the checkbox
    • newt_checkbox_tree - Описание
    • newt_checkbox_tree_add_item - Adds new item to the checkbox tree
    • newt_checkbox_tree_find_item - Finds an item in the checkbox tree
    • newt_checkbox_tree_get_current - Returns checkbox tree selected item
    • newt_checkbox_tree_get_entry_value - Описание
    • newt_checkbox_tree_get_multi_selection - Описание
    • newt_checkbox_tree_get_selection - Описание
    • newt_checkbox_tree_multi - Описание
    • newt_checkbox_tree_set_current - Описание
    • newt_checkbox_tree_set_entry - Описание
    • newt_checkbox_tree_set_entry_value - Описание
    • newt_checkbox_tree_set_width - Описание
    • newt_clear_key_buffer - Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls - Описание
    • newt_compact_button - Описание
    • newt_component_add_callback - Описание
    • newt_component_takes_focus - Описание
    • newt_create_grid - Описание
    • newt_cursor_off - Описание
    • newt_cursor_on - Описание
    • newt_delay - Описание
    • newt_draw_form - Описание
    • newt_draw_root_text - Displays the string text at the position indicated
    • newt_entry - Описание
    • newt_entry_get_value - Описание
    • newt_entry_set - Описание
    • newt_entry_set_filter - Описание
    • newt_entry_set_flags - Описание
    • newt_finished - Uninitializes newt interface
    • newt_form - Create a form
    • newt_form_add_component - Adds a single component to the form
    • newt_form_add_components - Add several components to the form
    • newt_form_add_hot_key - Описание
    • newt_form_destroy - Destroys a form
    • newt_form_get_current - Описание
    • newt_form_run - Runs a form
    • newt_form_set_background - Описание
    • newt_form_set_height - Описание
    • newt_form_set_size - Описание
    • newt_form_set_timer - Описание
    • newt_form_set_width - Описание
    • newt_form_watch_fd - Описание
    • newt_get_screen_size - Fills in the passed references with the current size of the terminal
    • newt_grid_add_components_to_form - Описание
    • newt_grid_basic_window - Описание
    • newt_grid_free - Описание
    • newt_grid_get_size - Описание
    • newt_grid_h_close_stacked - Описание
    • newt_grid_h_stacked - Описание
    • newt_grid_place - Описание
    • newt_grid_set_field - Описание
    • newt_grid_simple_window - Описание
    • newt_grid_v_close_stacked - Описание
    • newt_grid_v_stacked - Описание
    • newt_grid_wrapped_window - Описание
    • newt_grid_wrapped_window_at - Описание
    • newt_init - Initialize newt
    • newt_label - Описание
    • newt_label_set_text - Описание
    • newt_listbox - Описание
    • newt_listbox_append_entry - Описание
    • newt_listbox_clear - Описание
    • newt_listbox_clear_selection - Описание
    • newt_listbox_delete_entry - Описание
    • newt_listbox_get_current - Описание
    • newt_listbox_get_selection - Описание
    • newt_listbox_insert_entry - Описание
    • newt_listbox_item_count - Описание
    • newt_listbox_select_item - Описание
    • newt_listbox_set_current - Описание
    • newt_listbox_set_current_by_key - Описание
    • newt_listbox_set_data - Описание
    • newt_listbox_set_entry - Описание
    • newt_listbox_set_width - Описание
    • newt_listitem - Описание
    • newt_listitem_get_data - Описание
    • newt_listitem_set - Описание
    • newt_open_window - Open a window of the specified size and position
    • newt_pop_help_line - Replaces the current help line with the one from the stack
    • newt_pop_window - Removes the top window from the display
    • newt_push_help_line - Saves the current help line on a stack, and displays the new line
    • newt_radiobutton - Описание
    • newt_radio_get_current - Описание
    • newt_redraw_help_line - Описание
    • newt_reflow_text - Описание
    • newt_refresh - Updates modified portions of the screen
    • newt_resize_screen - Описание
    • newt_resume - Resume using the newt interface after calling newt_suspend
    • newt_run_form - Runs a form
    • newt_scale - Описание
    • newt_scale_set - Описание
    • newt_scrollbar_set - Описание
    • newt_set_help_callback - Описание
    • newt_set_suspend_callback - Set a callback function which gets invoked when user presses the suspend key
    • newt_suspend - Tells newt to return the terminal to its initial state
    • newt_textbox - Описание
    • newt_textbox_get_num_lines - Описание
    • newt_textbox_reflowed - Описание
    • newt_textbox_set_height - Описание
    • newt_textbox_set_text - Описание
    • newt_vertical_scrollbar - Описание
    • newt_wait_for_key - Doesn't return until a key has been pressed
    • newt_win_choice - Описание
    • newt_win_entries - Описание
    • newt_win_menu - Описание
    • newt_win_message - Описание
    • newt_win_messagev - Описание
    • newt_win_ternary - Описание
    • next - Передвигает внутренний указатель массива на одну позицию вперёд
    • ngettext - Версия gettext для сообщений во множественном числе
    • nl2br - Вставляет HTML-код разрыва строки перед каждым переводом строки
    • nl_langinfo - Возвращает информацию о языке и локали
    • NoRewindIterator::current - Получает текущее значение
    • NoRewindIterator::getInnerIterator - Получает внутренний итератор
    • NoRewindIterator::key - Получает текущий ключ
    • NoRewindIterator::next - Перемещает итератор к следующему элементу
    • NoRewindIterator::rewind - Предотвращает возврат внутреннего итератора в начало
    • NoRewindIterator::valid - Проверяет итератор
    • NoRewindIterator::__construct - Создает новый объект NoRewindIterator
    • Normalizer::isNormalized - Checks if the provided string is already in the specified normalization form.
    • Normalizer::normalize - Normalizes the input provided and returns the normalized string
    • notes_body - Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_copy_db - Copy a Lotus Notes database
    • notes_create_db - Create a Lotus Notes database
    • notes_create_note - Create a note using form form_name
    • notes_drop_db - Drop a Lotus Notes database
    • notes_find_note - Returns a note id found in database_name
    • notes_header_info - Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_list_msgs - Returns the notes from a selected database_name
    • notes_mark_read - Mark a note_id as read for the User user_name
    • notes_mark_unread - Mark a note_id as unread for the User user_name
    • notes_nav_create - Create a navigator name, in database_name
    • notes_search - Find notes that match keywords in database_name
    • notes_unread - Returns the unread note id's for the current User user_name
    • notes_version - Get the version Lotus Notes
    • nsapi_request_headers - Fetch all HTTP request headers
    • nsapi_response_headers - Fetch all HTTP response headers
    • nsapi_virtual - Perform an NSAPI sub-request
    • nthmac - Получить NTHMAC-ключ (Необходимо 2 параметра)
    • NumberFormatter::create - Create a number formatter
    • NumberFormatter::format - Format a number
    • NumberFormatter::formatCurrency - Format a currency value
    • NumberFormatter::getAttribute - Get an attribute
    • NumberFormatter::getErrorCode - Get formatter's last error code.
    • NumberFormatter::getErrorMessage - Get formatter's last error message.
    • NumberFormatter::getLocale - Get formatter locale
    • NumberFormatter::getPattern - Get formatter pattern
    • NumberFormatter::getSymbol - Get a symbol value
    • NumberFormatter::getTextAttribute - Get a text attribute
    • NumberFormatter::parse - Parse a number
    • NumberFormatter::parseCurrency - Parse a currency number
    • NumberFormatter::setAttribute - Set an attribute
    • NumberFormatter::setPattern - Set formatter pattern
    • NumberFormatter::setSymbol - Set a symbol value
    • NumberFormatter::setTextAttribute - Set a text attribute
    • number_format - Форматирует число с разделением групп
  • o
    • OAuth::disableDebug - Turn off verbose debugging
    • OAuth::disableRedirects - Turn off redirects
    • OAuth::disableSSLChecks - Turn off SSL checks
    • OAuth::enableDebug - Turn on verbose debugging
    • OAuth::enableRedirects - Turn on redirects
    • OAuth::enableSSLChecks - Turn on SSL checks
    • OAuth::fetch - Fetch an OAuth protected resource
    • OAuth::generateSignature - Generate a signature
    • OAuth::getAccessToken - Fetch an access token
    • OAuth::getCAPath - Gets CA information
    • OAuth::getLastResponse - Get the last response
    • OAuth::getLastResponseHeaders - Get headers for last response
    • OAuth::getLastResponseInfo - Get HTTP information about the last response
    • OAuth::getRequestHeader - Generate OAuth header string signature
    • OAuth::getRequestToken - Fetch a request token
    • OAuth::setAuthType - Set authorization type
    • OAuth::setCAPath - Set CA path and info
    • OAuth::setNonce - Set the nonce for subsequent requests
    • OAuth::setRequestEngine - The setRequestEngine purpose
    • OAuth::setRSACertificate - Set the RSA certificate
    • OAuth::setSSLChecks - Tweak specific SSL checks for requests.
    • OAuth::setTimestamp - Set the timestamp
    • OAuth::setToken - Sets the token and secret
    • OAuth::setVersion - Set the OAuth version
    • OAuth::__construct - Create a new OAuth object
    • OAuth::__destruct - The destructor
    • OAuthProvider::addRequiredParameter - Add required parameters
    • OAuthProvider::callconsumerHandler - Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler - Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler - Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest - Check an oauth request
    • OAuthProvider::consumerHandler - Set the consumerHandler handler callback
    • OAuthProvider::generateToken - Generate a random token
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - Remove a required parameter
    • OAuthProvider::reportProblem - Report a problem
    • OAuthProvider::setParam - Set a parameter
    • OAuthProvider::setRequestTokenPath - Set request token path
    • OAuthProvider::timestampNonceHandler - Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler - Set the tokenHandler handler callback
    • OAuthProvider::__construct - Constructs a new OAuthProvider object
    • oauth_get_sbs - Generate a Signature Base String
    • oauth_urlencode - Encode a URI to RFC 3986
    • ob_clean - Очищает (стирает) буфер вывода
    • ob_deflatehandler - Deflate output handler
    • ob_end_clean - Очищает (стирает) буфер вывода и отключает буферизацию вывода
    • ob_end_flush - Сброс (отправка) буфера вывода и отключение буферизации вывода
    • ob_etaghandler - ETag output handler
    • ob_flush - Сброс (отправка) буфера вывода
    • ob_get_clean - Получить содержимое буфера и очистить его
    • ob_get_contents - Возвращает содержимое буфера вывода
    • ob_get_flush - Сброс буфера вывода, возвращая его содержимое и отключение буферизации вывода
    • ob_get_length - Возвращает размер буфера вывода
    • ob_get_level - Возвращает уровень вложенности механизма буферизации вывода
    • ob_get_status - Получить статус буфера вывода
    • ob_gzhandler - callback-функция, используемая для gzip-сжатия буфера вывода при вызове ob_start
    • ob_iconv_handler - Преобразует символы из текущей кодировки в кодировку выходного буфера
    • ob_implicit_flush - Функция включает/выключает неявный сброс
    • ob_inflatehandler - Inflate output handler
    • ob_list_handlers - Список всех используемых обработчиков вывода
    • ob_start - Включение буферизации вывода
    • ob_tidyhandler - Функция обратного вызова ob_start для восстановление буфера
    • OCI-Collection::append - Appends element to the collection
    • OCI-Collection::assign - Assigns a value to the collection from another existing collection
    • OCI-Collection::assignElem - Assigns a value to the element of the collection
    • OCI-Collection::free - Frees the resources associated with the collection object
    • OCI-Collection::getElem - Returns value of the element
    • OCI-Collection::max - Returns the maximum number of elements in the collection
    • OCI-Collection::size - Returns size of the collection
    • OCI-Collection::trim - Trims elements from the end of the collection
    • OCI-Lob::append - Appends data from the large object to another large object
    • OCI-Lob::close - Closes LOB descriptor
    • OCI-Lob::eof - Tests for end-of-file on a large object's descriptor
    • OCI-Lob::erase - Erases a specified portion of the internal LOB data
    • OCI-Lob::export - Exports LOB's contents to a file
    • OCI-Lob::flush - Flushes/writes buffer of the LOB to the server
    • OCI-Lob::free - Frees resources associated with the LOB descriptor
    • OCI-Lob::getBuffering - Returns current state of buffering for the large object
    • OCI-Lob::import - Imports file data to the LOB
    • OCI-Lob::load - Returns large object's contents
    • OCI-Lob::read - Reads part of the large object
    • OCI-Lob::rewind - Moves the internal pointer to the beginning of the large object
    • OCI-Lob::save - Saves data to the large object
    • OCI-Lob::saveFile - Псевдоним OCI-Lob::import
    • OCI-Lob::seek - Sets the internal pointer of the large object
    • OCI-Lob::setBuffering - Changes current state of buffering for the large object
    • OCI-Lob::size - Returns size of large object
    • OCI-Lob::tell - Returns the current position of internal pointer of large object
    • OCI-Lob::truncate - Truncates large object
    • OCI-Lob::write - Writes data to the large object
    • OCI-Lob::writeTemporary - Writes a temporary large object
    • OCI-Lob::writeToFile - Псевдоним OCI-Lob::export
    • ocibindbyname - Псевдоним oci_bind_by_name
    • ocicancel - Псевдоним oci_cancel
    • ocicloselob - Псевдоним OCI-Lob::close
    • ocicollappend - Псевдоним OCI-Collection::append
    • ocicollassign - Псевдоним OCI-Collection::assign
    • ocicollassignelem - Псевдоним OCI-Collection::assignElem
    • ocicollgetelem - Псевдоним OCI-Collection::getElem
    • ocicollmax - Псевдоним OCI-Collection::max
    • ocicollsize - Псевдоним OCI-Collection::size
    • ocicolltrim - Псевдоним OCI-Collection::trim
    • ocicolumnisnull - Псевдоним oci_field_is_null
    • ocicolumnname - Псевдоним oci_field_name
    • ocicolumnprecision - Псевдоним oci_field_precision
    • ocicolumnscale - Псевдоним oci_field_scale
    • ocicolumnsize - Псевдоним oci_field_size
    • ocicolumntype - Псевдоним oci_field_type
    • ocicolumntyperaw - Псевдоним oci_field_type_raw
    • ocicommit - Псевдоним oci_commit
    • ocidefinebyname - Псевдоним oci_define_by_name
    • ocierror - Псевдоним oci_error
    • ociexecute - Псевдоним oci_execute
    • ocifetch - Псевдоним oci_fetch
    • ocifetchinto - Возвращает следующий ряд в массив (устарела)
    • ocifetchstatement - Псевдоним oci_fetch_all
    • ocifreecollection - Псевдоним OCI-Collection::free
    • ocifreecursor - Псевдоним oci_free_statement
    • ocifreedesc - Псевдоним OCI-Lob::free
    • ocifreestatement - Псевдоним oci_free_statement
    • ociinternaldebug - Псевдоним oci_internal_debug
    • ociloadlob - Псевдоним OCI-Lob::load
    • ocilogoff - Псевдоним oci_close
    • ocilogon - Псевдоним oci_connect
    • ocinewcollection - Псевдоним oci_new_collection
    • ocinewcursor - Псевдоним oci_new_cursor
    • ocinewdescriptor - Псевдоним oci_new_descriptor
    • ocinlogon - Псевдоним oci_new_connect
    • ocinumcols - Псевдоним oci_num_fields
    • ociparse - Псевдоним oci_parse
    • ociplogon - Псевдоним oci_pconnect
    • ociresult - Псевдоним oci_result
    • ocirollback - Псевдоним oci_rollback
    • ocirowcount - Псевдоним oci_num_rows
    • ocisavelob - Псевдоним OCI-Lob::save
    • ocisavelobfile - Псевдоним OCI-Lob::import
    • ociserverversion - Псевдоним oci_server_version
    • ocisetprefetch - Псевдоним oci_set_prefetch
    • ocistatementtype - Псевдоним oci_statement_type
    • ociwritelobtofile - Псевдоним OCI-Lob::export
    • ociwritetemporarylob - Псевдоним OCI-Lob::writeTemporary
    • oci_bind_array_by_name - Связывает PHP массив с массивом Oracle PL/SQL
    • oci_bind_by_name - Прикрепляет переменную PHP к соответствующей метке в SQL-выражении
    • oci_cancel - Заканчивает процесс чтения из курсора
    • oci_client_version - Возвращает версию клиентской библиотеки
    • oci_close - Закрывает соединение с сервером Oracle
    • oci_commit - Фиксирует транзакцию базы данных
    • oci_connect - Устанавливает соединение с базой данных Oracle
    • oci_define_by_name - Сопоставляет переменную PHP столбцу результата запроса
    • oci_error - Возвращает последнюю ошибку
    • oci_execute - Выполняет подготовленное выражение
    • oci_fetch - Выбирает следующую строку из результата в буфер
    • oci_fetch_all - Выбирает все строки из результата запроса в двумерный массив
    • oci_fetch_array - Возвращает следующую строку из результата запроса в виде ассоциативного или нумерованного массива
    • oci_fetch_assoc - Возвращает следующую строку из результата запроса в виде ассоциативного массива
    • oci_fetch_object - Возвращает следующую строку из результата запроса в виде объекта
    • oci_fetch_row - Возвращает следующую строку из результата запроса в виде нумерованного массива
    • oci_field_is_null - Проверяет, равняется ли поле NULL
    • oci_field_name - Возвращает имя поля из результата запроса
    • oci_field_precision - Возвращает точность поля
    • oci_field_scale - Возвращает масштаб поля
    • oci_field_size - Возвращает размер поля
    • oci_field_type - Возвращает тип поля
    • oci_field_type_raw - Возвращает исходный Oracle тип поля
    • oci_free_statement - Освобождает ресурсы, занимаемые курсором или SQL-выражением
    • oci_internal_debug - Включает и выключает внутреннюю отладку
    • oci_lob_copy - Копирует объект LOB
    • oci_lob_is_equal - Сравнивает два объекта LOB/FILE
    • oci_new_collection - Создает новый объект коллекции
    • oci_new_connect - Устанавливает новое соединение с сервером Oracle
    • oci_new_cursor - Возвращает идентификатор созданного курсора
    • oci_new_descriptor - Инициализирует новый дескриптор объекта LOB или FILE
    • oci_num_fields - Возвращает количество полей в результате запроса
    • oci_num_rows - Возвращает количество строк, измененных в процессе выполнения запроса
    • oci_parse - Подготавливает запрос к выполнению
    • oci_password_change - Изменяет пароль пользователя Oracle
    • oci_pconnect - Устанавливает постоянное соединение с сервером Oracle
    • oci_result - Возвращает значение поля из результата запроса
    • oci_rollback - Откатывает транзакции, ожидающие обработки
    • oci_server_version - Возвращает версию сервера Oracle
    • oci_set_action - Задает имя для действия
    • oci_set_client_identifier - Задает идентификатор клиента
    • oci_set_client_info - Задает информацию о клиенте
    • oci_set_edition - Задает выпуск (edition) базы данных
    • oci_set_module_name - Задает имя модулю
    • oci_set_prefetch - Устанавливает количество строк, которые будут автоматически выбраны в буфер
    • oci_statement_type - Возвращает тип выражения
    • octdec - Переводит число из восьмеричной системы счисления в десятичную
    • odbc_autocommit - Toggle autocommit behaviour
    • odbc_binmode - Handling of binary column data
    • odbc_close - Close an ODBC connection
    • odbc_close_all - Close all ODBC connections
    • odbc_columnprivileges - Lists columns and associated privileges for the given table
    • odbc_columns - Lists the column names in specified tables
    • odbc_commit - Commit an ODBC transaction
    • odbc_connect - Connect to a datasource
    • odbc_cursor - Get cursorname
    • odbc_data_source - Returns information about a current connection
    • odbc_do - Псевдоним odbc_exec
    • odbc_error - Get the last error code
    • odbc_errormsg - Get the last error message
    • odbc_exec - Prepare and execute an SQL statement
    • odbc_execute - Execute a prepared statement
    • odbc_fetch_array - Fetch a result row as an associative array
    • odbc_fetch_into - Fetch one result row into array
    • odbc_fetch_object - Fetch a result row as an object
    • odbc_fetch_row - Fetch a row
    • odbc_field_len - Get the length (precision) of a field
    • odbc_field_name - Get the columnname
    • odbc_field_num - Return column number
    • odbc_field_precision - Псевдоним odbc_field_len
    • odbc_field_scale - Get the scale of a field
    • odbc_field_type - Datatype of a field
    • odbc_foreignkeys - Retrieves a list of foreign keys
    • odbc_free_result - Free resources associated with a result
    • odbc_gettypeinfo - Retrieves information about data types supported by the data source
    • odbc_longreadlen - Handling of LONG columns
    • odbc_next_result - Checks if multiple results are available
    • odbc_num_fields - Number of columns in a result
    • odbc_num_rows - Number of rows in a result
    • odbc_pconnect - Open a persistent database connection
    • odbc_prepare - Prepares a statement for execution
    • odbc_primarykeys - Gets the primary keys for a table
    • odbc_procedurecolumns - Retrieve information about parameters to procedures
    • odbc_procedures - Get the list of procedures stored in a specific data source
    • odbc_result - Get result data
    • odbc_result_all - Print result as HTML table
    • odbc_rollback - Rollback a transaction
    • odbc_setoption - Adjust ODBC settings
    • odbc_specialcolumns - Retrieves special columns
    • odbc_statistics - Retrieve statistics about a table
    • odbc_tableprivileges - Lists tables and the privileges associated with each table
    • odbc_tables - Get the list of table names stored in a specific data source
    • ogg:// - Аудио потоки
    • openal_buffer_create - Generate OpenAL buffer
    • openal_buffer_data - Load a buffer with data
    • openal_buffer_destroy - Destroys an OpenAL buffer
    • openal_buffer_get - Retrieve an OpenAL buffer property
    • openal_buffer_loadwav - Load a .wav file into a buffer
    • openal_context_create - Create an audio processing context
    • openal_context_current - Make the specified context current
    • openal_context_destroy - Destroys a context
    • openal_context_process - Process the specified context
    • openal_context_suspend - Suspend the specified context
    • openal_device_close - Close an OpenAL device
    • openal_device_open - Initialize the OpenAL audio layer
    • openal_listener_get - Retrieve a listener property
    • openal_listener_set - Set a listener property
    • openal_source_create - Generate a source resource
    • openal_source_destroy - Destroy a source resource
    • openal_source_get - Retrieve an OpenAL source property
    • openal_source_pause - Pause the source
    • openal_source_play - Start playing the source
    • openal_source_rewind - Rewind the source
    • openal_source_set - Set source property
    • openal_source_stop - Stop playing the source
    • openal_stream - Begin streaming on a source
    • opendir - Открывает дескриптор каталога
    • openlog - Открывает соединение к системному журналу
    • openssl_cipher_iv_length - Gets the cipher iv length
    • openssl_csr_export - Exports a CSR as a string
    • openssl_csr_export_to_file - Exports a CSR to a file
    • openssl_csr_get_public_key - Returns the public key of a CERT
    • openssl_csr_get_subject - Returns the subject of a CERT
    • openssl_csr_new - Generates a CSR
    • openssl_csr_sign - Sign a CSR with another certificate (or itself) and generate a certificate
    • openssl_decrypt - Decrypts data
    • openssl_dh_compute_key - Computes shared secret for public value of remote DH key and local DH key
    • openssl_digest - Computes a digest
    • openssl_encrypt - Encrypts data
    • openssl_error_string - Return openSSL error message
    • openssl_free_key - Free key resource
    • openssl_get_cipher_methods - Gets available cipher methods
    • openssl_get_md_methods - Gets available digest methods
    • openssl_get_privatekey - Псевдоним openssl_pkey_get_private
    • openssl_get_publickey - Псевдоним openssl_pkey_get_public
    • openssl_open - Open sealed data
    • openssl_pkcs7_decrypt - Decrypts an S/MIME encrypted message
    • openssl_pkcs7_encrypt - Encrypt an S/MIME message
    • openssl_pkcs7_sign - Sign an S/MIME message
    • openssl_pkcs7_verify - Verifies the signature of an S/MIME signed message
    • openssl_pkcs12_export - Exports a PKCS#12 Compatible Certificate Store File to variable.
    • openssl_pkcs12_export_to_file - Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_read - Parse a PKCS#12 Certificate Store into an array
    • openssl_pkey_export - Gets an exportable representation of a key into a string
    • openssl_pkey_export_to_file - Gets an exportable representation of a key into a file
    • openssl_pkey_free - Frees a private key
    • openssl_pkey_get_details - Returns an array with the key details
    • openssl_pkey_get_private - Get a private key
    • openssl_pkey_get_public - Extract public key from certificate and prepare it for use
    • openssl_pkey_new - Generates a new private key
    • openssl_private_decrypt - Decrypts data with private key
    • openssl_private_encrypt - Encrypts data with private key
    • openssl_public_decrypt - Decrypts data with public key
    • openssl_public_encrypt - Encrypts data with public key
    • openssl_random_pseudo_bytes - Generate a pseudo-random string of bytes
    • openssl_seal - Seal (encrypt) data
    • openssl_sign - Generate signature
    • openssl_verify - Verify signature
    • openssl_x509_checkpurpose - Verifies if a certificate can be used for a particular purpose
    • openssl_x509_check_private_key - Checks if a private key corresponds to a certificate
    • openssl_x509_export - Exports a certificate as a string
    • openssl_x509_export_to_file - Exports a certificate to file
    • openssl_x509_free - Free certificate resource
    • openssl_x509_parse - Parse an X509 certificate and return the information as an array
    • openssl_x509_read - Parse an X.509 certificate and return a resource identifier for it
    • ord - Возвращает ASCII-код символа
    • OuterIterator::getInnerIterator - Возвращает внутренний итератор для текущего элемента
    • output_add_rewrite_var - Добавить обработчик значений URL
    • output_reset_rewrite_vars - Сброс значений установленных обработчиком URL
    • overload - Enable property and method call overloading for a class
    • override_function - Overrides built-in functions
    • ovrimos_close - Closes the connection to ovrimos
    • ovrimos_commit - Commits the transaction
    • ovrimos_connect - Connect to the specified database
    • ovrimos_cursor - Returns the name of the cursor
    • ovrimos_exec - Executes an SQL statement
    • ovrimos_execute - Executes a prepared SQL statement
    • ovrimos_fetch_into - Fetches a row from the result set
    • ovrimos_fetch_row - Fetches a row from the result set
    • ovrimos_field_len - Returns the length of the output column
    • ovrimos_field_name - Returns the output column name
    • ovrimos_field_num - Returns the (1-based) index of the output column
    • ovrimos_field_type - Returns the type of the output column
    • ovrimos_free_result - Frees the specified result_id
    • ovrimos_longreadlen - Specifies how many bytes are to be retrieved from long datatypes
    • ovrimos_num_fields - Returns the number of columns
    • ovrimos_num_rows - Returns the number of rows affected by update operations
    • ovrimos_prepare - Prepares an SQL statement
    • ovrimos_result - Retrieves the output column
    • ovrimos_result_all - Prints the whole result set as an HTML table
    • ovrimos_rollback - Rolls back the transaction
  • p
    • pack - Упаковывает данные в бинарную строку
    • ParentIterator::accept - Determines acceptability
    • ParentIterator::getChildren - Return the inner iterator's children contained in a ParentIterator
    • ParentIterator::hasChildren - Check whether the inner iterator's current element has children
    • ParentIterator::next - Move the iterator forward
    • ParentIterator::rewind - Rewind the iterator
    • ParentIterator::__construct - Constructs a ParentIterator
    • parsekit_compile_file - Compile a string of PHP code and return the resulting op array
    • parsekit_compile_string - Compile a string of PHP code and return the resulting op array
    • parsekit_func_arginfo - Return information regarding function argument(s)
    • parse_ini_file - Обрабатывает конфигурационный файл
    • parse_ini_string - Разбирает строку конфигурации
    • parse_str - Разбирает строку в переменные
    • parse_url - Разбирает URL и возвращает его компоненты
    • passthru - Выполняет внешнюю программу и отображает необработанный вывод
    • pathinfo - Возвращает информацию о пути к файлу
    • pclose - Закрывает файловый указатель процесса
    • pcntl_alarm - Set an alarm clock for delivery of a signal
    • pcntl_exec - Executes specified program in current process space
    • pcntl_fork - Forks the currently running process
    • pcntl_getpriority - Get the priority of any process
    • pcntl_setpriority - Change the priority of any process
    • pcntl_signal - Installs a signal handler
    • pcntl_signal_dispatch - Calls signal handlers for pending signals
    • pcntl_sigprocmask - Sets and retrieves blocked signals
    • pcntl_sigtimedwait - Waits for signals, with a timeout
    • pcntl_sigwaitinfo - Waits for signals
    • pcntl_wait - Waits on or returns the status of a forked child
    • pcntl_waitpid - Waits on or returns the status of a forked child
    • pcntl_wexitstatus - Returns the return code of a terminated child
    • pcntl_wifexited - Checks if status code represents a normal exit
    • pcntl_wifsignaled - Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped - Checks whether the child process is currently stopped
    • pcntl_wstopsig - Returns the signal which caused the child to stop
    • pcntl_wtermsig - Returns the signal which caused the child to terminate
    • PDF_activate_item - Activate structure element or other content item
    • PDF_add_annotation - Add annotation [deprecated]
    • PDF_add_bookmark - Add bookmark for current page [deprecated]
    • PDF_add_launchlink - Add launch annotation for current page [deprecated]
    • PDF_add_locallink - Add link annotation for current page [deprecated]
    • PDF_add_nameddest - Create named destination
    • PDF_add_note - Set annotation for current page [deprecated]
    • PDF_add_outline - Add bookmark for current page [deprecated]
    • PDF_add_pdflink - Add file link annotation for current page [deprecated]
    • PDF_add_table_cell - Add a cell to a new or existing table
    • PDF_add_textflow - Create Textflow or add text to existing Textflow
    • PDF_add_thumbnail - Add thumbnail for current page
    • PDF_add_weblink - Add weblink for current page [deprecated]
    • PDF_arc - Рисует дугу окружности против часовой стрелки
    • PDF_arcn - Рисует дугу окружности по часовой стрелке
    • PDF_attach_file - Add file attachment for current page [deprecated]
    • PDF_begin_document - Create new PDF file
    • PDF_begin_font - Start a Type 3 font definition
    • PDF_begin_glyph - Start glyph definition for Type 3 font
    • PDF_begin_item - Open structure element or other content item
    • PDF_begin_layer - Start layer
    • PDF_begin_page - Start new page [deprecated]
    • PDF_begin_page_ext - Start new page
    • PDF_begin_pattern - Start pattern definition
    • PDF_begin_template - Start template definition [deprecated]
    • PDF_begin_template_ext - Start template definition
    • PDF_circle - Рисует окружность
    • PDF_clip - Clip to current path
    • PDF_close - Закрывает pdf-документ [устаревшее]
    • PDF_closepath - Close current path
    • PDF_closepath_fill_stroke - Close, fill and stroke current path
    • PDF_closepath_stroke - Close and stroke path
    • PDF_close_image - Закрывает изображение
    • PDF_close_pdi - Close the input PDF document [deprecated]
    • PDF_close_pdi_page - Close the page handle
    • PDF_concat - Concatenate a matrix to the CTM
    • PDF_continue_text - Output text in next line
    • PDF_create_3dview - Создает объемное изображение
    • PDF_create_action - Create action for objects or events
    • PDF_create_annotation - Создает прямоугольную аннотацию
    • PDF_create_bookmark - Create bookmark
    • PDF_create_field - Create form field
    • PDF_create_fieldgroup - Create form field group
    • PDF_create_gstate - Create graphics state object
    • PDF_create_pvf - Create PDFlib virtual file
    • PDF_create_textflow - Create textflow object
    • PDF_curveto - Draw Bezier curve
    • PDF_define_layer - Create layer definition
    • PDF_delete - Удаляет объект PDFlib
    • PDF_delete_pvf - Delete PDFlib virtual file
    • PDF_delete_table - Delete table object
    • PDF_delete_textflow - Delete textflow object
    • PDF_encoding_set_char - Add glyph name and/or Unicode value
    • PDF_endpath - End current path
    • PDF_end_document - Close PDF file
    • PDF_end_font - Terminate Type 3 font definition
    • PDF_end_glyph - Terminate glyph definition for Type 3 font
    • PDF_end_item - Close structure element or other content item
    • PDF_end_layer - Deactivate all active layers
    • PDF_end_page - Finish page
    • PDF_end_page_ext - Finish page
    • PDF_end_pattern - Finish pattern
    • PDF_end_template - Finish template
    • PDF_fill - Fill current path
    • PDF_fill_imageblock - Fill image block with variable data
    • PDF_fill_pdfblock - Fill PDF block with variable data
    • PDF_fill_stroke - Fill and stroke path
    • PDF_fill_textblock - Fill text block with variable data
    • PDF_findfont - Prepare font for later use [deprecated]
    • PDF_fit_image - Place image or template
    • PDF_fit_pdi_page - Place imported PDF page
    • PDF_fit_table - Place table on page
    • PDF_fit_textflow - Format textflow in rectangular area
    • PDF_fit_textline - Place single line of text
    • PDF_get_apiname - Get name of unsuccessfull API function
    • PDF_get_buffer - Get PDF output buffer
    • PDF_get_errmsg - Возвращает текст ошибки
    • PDF_get_errnum - Возвращает код ошибки
    • PDF_get_font - Возвращает шрифт [устаревшее]
    • PDF_get_fontname - Возвращает название шрифта [устаревшее]
    • PDF_get_fontsize - Font handling [deprecated]
    • PDF_get_image_height - Возвращает высоту изображения [устаревшее]
    • PDF_get_image_width - Возвращает ширину изображения [устаревшее]
    • PDF_get_majorversion - Get major version number [deprecated]
    • PDF_get_minorversion - Get minor version number [deprecated]
    • PDF_get_parameter - Get string parameter
    • PDF_get_pdi_parameter - Get PDI string parameter [deprecated]
    • PDF_get_pdi_value - Get PDI numerical parameter [deprecated]
    • PDF_get_value - Get numerical parameter
    • PDF_info_font - Query detailed information about a loaded font
    • PDF_info_matchbox - Query matchbox information
    • PDF_info_table - Retrieve table information
    • PDF_info_textflow - Query textflow state
    • PDF_info_textline - Perform textline formatting and query metrics
    • PDF_initgraphics - Reset graphic state
    • PDF_lineto - Draw a line
    • PDF_load_3ddata - Load 3D model
    • PDF_load_font - Search and prepare font
    • PDF_load_iccprofile - Search and prepare ICC profile
    • PDF_load_image - Open image file
    • PDF_makespotcolor - Make spot color
    • PDF_moveto - Set current point
    • PDF_new - Создает объект PDFlib
    • PDF_open_ccitt - Open raw CCITT image [deprecated]
    • PDF_open_file - Создает PDF-файл [устаревшее]
    • PDF_open_gif - Открывает GIF-изображение [устаревшее]
    • PDF_open_image - Use image data [deprecated]
    • PDF_open_image_file - Read image from file [deprecated]
    • PDF_open_jpeg - Открывает JPEG-изображение [устаревшее]
    • PDF_open_memory_image - Open image created with PHP's image functions [not supported]
    • PDF_open_pdi - Open PDF file [deprecated]
    • PDF_open_pdi_document - Prepare a pdi document
    • PDF_open_pdi_page - Prepare a page
    • PDF_open_tiff - Открывает TIFF-изображение [устаревшее]
    • PDF_pcos_get_number - Get value of pCOS path with type number or boolean
    • PDF_pcos_get_stream - Get contents of pCOS path with type stream, fstream, or string
    • PDF_pcos_get_string - Get value of pCOS path with type name, string, or boolean
    • PDF_place_image - Place image on the page [deprecated]
    • PDF_place_pdi_page - Place PDF page [deprecated]
    • PDF_process_pdi - Process imported PDF document
    • PDF_rect - Рисует прямоугольник
    • PDF_restore - Restore graphics state
    • PDF_resume_page - Resume page
    • PDF_rotate - Поворачивает систему координат
    • PDF_save - Save graphics state
    • PDF_scale - Масштабирует систему координат
    • PDF_setcolor - Set fill and stroke color
    • PDF_setdash - Set simple dash pattern
    • PDF_setdashpattern - Set dash pattern
    • PDF_setflat - Set flatness
    • PDF_setfont - Set font
    • PDF_setgray - Set color to gray [deprecated]
    • PDF_setgray_fill - Set fill color to gray [deprecated]
    • PDF_setgray_stroke - Set stroke color to gray [deprecated]
    • PDF_setlinecap - Set linecap parameter
    • PDF_setlinejoin - Set linejoin parameter
    • PDF_setlinewidth - Set line width
    • PDF_setmatrix - Set current transformation matrix
    • PDF_setmiterlimit - Set miter limit
    • PDF_setpolydash - Set complicated dash pattern [deprecated]
    • PDF_setrgbcolor - Set fill and stroke rgb color values [deprecated]
    • PDF_setrgbcolor_fill - Set fill rgb color values [deprecated]
    • PDF_setrgbcolor_stroke - Set stroke rgb color values [deprecated]
    • PDF_set_border_color - Set border color of annotations [deprecated]
    • PDF_set_border_dash - Set border dash style of annotations [deprecated]
    • PDF_set_border_style - Set border style of annotations [deprecated]
    • PDF_set_char_spacing - Set character spacing [deprecated]
    • PDF_set_duration - Set duration between pages [deprecated]
    • PDF_set_gstate - Activate graphics state object
    • PDF_set_horiz_scaling - Set horizontal text scaling [deprecated]
    • PDF_set_info - Fill document info field
    • PDF_set_info_author - Fill the author document info field [deprecated]
    • PDF_set_info_creator - Fill the creator document info field [deprecated]
    • PDF_set_info_keywords - Fill the keywords document info field [deprecated]
    • PDF_set_info_subject - Fill the subject document info field [deprecated]
    • PDF_set_info_title - Fill the title document info field [deprecated]
    • PDF_set_layer_dependency - Define relationships among layers
    • PDF_set_leading - Set distance between text lines [deprecated]
    • PDF_set_parameter - Set string parameter
    • PDF_set_text_matrix - Set text matrix [deprecated]
    • PDF_set_text_pos - Устанавливает позицию текста
    • PDF_set_text_rendering - Determine text rendering [deprecated]
    • PDF_set_text_rise - Set text rise [deprecated]
    • PDF_set_value - Set numerical parameter
    • PDF_set_word_spacing - Set spacing between words [deprecated]
    • PDF_shading - Define blend
    • PDF_shading_pattern - Define shading pattern
    • PDF_shfill - Fill area with shading
    • PDF_show - Output text at current position
    • PDF_show_boxed - Output text in a box [deprecated]
    • PDF_show_xy - Output text at given position
    • PDF_skew - Skew the coordinate system
    • PDF_stringwidth - Return width of text
    • PDF_stroke - Stroke path
    • PDF_suspend_page - Suspend page
    • PDF_translate - Set origin of coordinate system
    • PDF_utf8_to_utf16 - Конвертирует строку из UTF-8 в UTF-16
    • PDF_utf16_to_utf8 - Конвертирует строку из UTF-16 в UTF-8
    • PDF_utf32_to_utf16 - Конвертирует строку из UTF-32 в UTF-16
    • PDO::beginTransaction - Инициализация транзакции
    • PDO::commit - Фиксирует транзакцию
    • PDO::cubrid_schema - Get the requested schema information
    • PDO::errorCode - Fetch the SQLSTATE associated with the last operation on the database handle
    • PDO::errorInfo - Fetch extended error information associated with the last operation on the database handle
    • PDO::exec - Execute an SQL statement and return the number of affected rows
    • PDO::getAttribute - Получить атрибут соеденения с базой данных
    • PDO::getAvailableDrivers - Возвращает массив доступных драйверов PDO
    • PDO::inTransaction - Проверяет, есть ли внутри транзакция
    • PDO::lastInsertId - Returns the ID of the last inserted row or sequence value
    • PDO::pgsqlLOBCreate - Creates a new large object
    • PDO::pgsqlLOBOpen - Opens an existing large object stream
    • PDO::pgsqlLOBUnlink - Deletes the large object
    • PDO::prepare - Prepares a statement for execution and returns a statement object
    • PDO::query - Executes an SQL statement, returning a result set as a PDOStatement object
    • PDO::quote - Quotes a string for use in a query.
    • PDO::rollBack - Rolls back a transaction
    • PDO::setAttribute - Set an attribute
    • PDO::sqliteCreateAggregate - Registers an aggregating User Defined Function for use in SQL statements
    • PDO::sqliteCreateFunction - Registers a User Defined Function for use in SQL statements
    • PDO::__construct - Создает экземпляр PDO, предоставляющий соединение с базой данных
    • PDOStatement::bindColumn - Bind a column to a PHP variable
    • PDOStatement::bindParam - Binds a parameter to the specified variable name
    • PDOStatement::bindValue - Binds a value to a parameter
    • PDOStatement::closeCursor - Closes the cursor, enabling the statement to be executed again.
    • PDOStatement::columnCount - Returns the number of columns in the result set
    • PDOStatement::debugDumpParams - Dump an SQL prepared command
    • PDOStatement::errorCode - Fetch the SQLSTATE associated with the last operation on the statement handle
    • PDOStatement::errorInfo - Fetch extended error information associated with the last operation on the statement handle
    • PDOStatement::execute - Executes a prepared statement
    • PDOStatement::fetch - Fetches the next row from a result set
    • PDOStatement::fetchAll - Returns an array containing all of the result set rows
    • PDOStatement::fetchColumn - Returns a single column from the next row of a result set
    • PDOStatement::fetchObject - Fetches the next row and returns it as an object.
    • PDOStatement::getAttribute - Retrieve a statement attribute
    • PDOStatement::getColumnMeta - Returns metadata for a column in a result set
    • PDOStatement::nextRowset - Advances to the next rowset in a multi-rowset statement handle
    • PDOStatement::rowCount - Returns the number of rows affected by the last SQL statement
    • PDOStatement::setAttribute - Set a statement attribute
    • PDOStatement::setFetchMode - Set the default fetch mode for this statement
    • PDO_4D DSN - Connecting to 4D SQL server
    • PDO_CUBRID DSN - Connecting to CUBRID databases
    • PDO_DBLIB DSN - Connecting to Microsoft SQL Server and Sybase databases
    • PDO_FIREBIRD DSN - Connecting to Firebird and Interbase databases
    • PDO_IBM DSN - Connecting to IBM databases
    • PDO_INFORMIX DSN - Connecting to Informix databases
    • PDO_MYSQL DSN - Connecting to MySQL databases
    • PDO_OCI DSN - Connecting to Oracle databases
    • PDO_ODBC DSN - Connecting to ODBC or DB2 databases
    • PDO_PGSQL DSN - Connecting to PostgreSQL databases
    • PDO_SQLITE DSN - Connecting to SQLite databases
    • PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
    • pfsockopen - Открывает постоянное соединение с Интернет или сокетом Unix домена
    • pg_affected_rows - Возвращает количество затронутых запросом записей (кортежей)
    • pg_cancel_query - Остановка асинхронного запроса.
    • pg_client_encoding - Получение кодировки клиента.
    • pg_close - Закрывает соединение с базой данных PostgreSQL
    • pg_connect - Открывает соединение с базой данных PostgreSQL
    • pg_connection_busy - Проверяет, занято ли соединение в данный момент.
    • pg_connection_reset - Сброс подключение (переподключение)
    • pg_connection_status - Определяет состояние подключения
    • pg_convert - Преобразует значения ассоциативного массива в приемлемые для использования в SQL запросах
    • pg_copy_from - Вставляет записи из массива в таблицу
    • pg_copy_to - Копирует данные из таблицы в массив
    • pg_dbname - Определяет имя базы данных
    • pg_delete - Удаляет записи
    • pg_end_copy - Синхронизирует с бэкендом PostgreSQL
    • pg_escape_bytea - Экранирует спецсимволы в строке для вставки в поле типа bytea
    • pg_escape_identifier - Escape a identifier for insertion into a text field
    • pg_escape_literal - Escape a literal for insertion into a text field
    • pg_escape_string - Экранирование спецсимволов в строке запроса
    • pg_execute - Запускает выполнение ранее подготовленного параметризованного запроса и ждет результат
    • pg_fetch_all - Выбирает все данные из результата запроса и помещает их в массив
    • pg_fetch_all_columns - Выбирает все записи из одной колонки результата запроса и помещает их в массив
    • pg_fetch_array - Возвращает строку результата в виде массива
    • pg_fetch_assoc - Выбирает строку результата запроса и помещает данные в ассоциативный массив
    • pg_fetch_object - Выбирает строку результата запроса и возвращает данные в виде объекта
    • pg_fetch_result - Возвращает запись из результата запроса
    • pg_fetch_row - Выбирает строку результата запроса и помещает данные в массив
    • pg_field_is_null - Проверка поля на значение SQL NULL
    • pg_field_name - Возвращает наименование поля
    • pg_field_num - Возвращает порядковый номер именованного поля
    • pg_field_prtlen - Возвращает количество печатаемых символов
    • pg_field_size - Возвращает размер поля
    • pg_field_table - Возвращает наименование или идентификатор таблицы, содержащей заданное поле
    • pg_field_type - Возвращает имя типа заданного поля
    • pg_field_type_oid - Возвращает идентификатор типа заданного поля
    • pg_free_result - Очистка результата запроса и освобождение памяти
    • pg_get_notify - Получение SQL NOTIFY сообщения
    • pg_get_pid - Получает ID процесса сервера БД
    • pg_get_result - Получение результата асинхронного запроса
    • pg_host - Возвращает имя хоста, соответствующего подключению
    • pg_insert - Заносит данные из массива в таблицу базы данных
    • pg_last_error - Получает сообщение о последней произошедшей ошибке на соединении с базой данных
    • pg_last_notice - Возвращает последнее уведомление от сервера PostgreSQL
    • pg_last_oid - Возвращает OID последней добавленной в базу строки
    • pg_lo_close - Закрывает большой объект
    • pg_lo_create - Создает большой объект
    • pg_lo_export - Вывод большого объекта в файл
    • pg_lo_import - Импорт большого объекта из файла
    • pg_lo_open - Открывает большой объект базы данных
    • pg_lo_read - Читает данные большого объекта
    • pg_lo_read_all - Читает содержимое большого объекта и посылает напрямую в броузер
    • pg_lo_seek - Перемещает внутренний указатель большого объекта
    • pg_lo_tell - Возвращает текущее положение внутреннего указателя большого объекта
    • pg_lo_unlink - Удаление большого объекта
    • pg_lo_write - Записывает данные в большой объект
    • pg_meta_data - Получение метаданных таблицы
    • pg_num_fields - Возвращает количество полей в выборке
    • pg_num_rows - Возвращает количество строк в выборке
    • pg_options - Получение параметров соединения с сервером баз данных
    • pg_parameter_status - Просмотр текущих значений параметров сервера
    • pg_pconnect - Открывает постоянное соединение с сервером PostgreSQL
    • pg_ping - Проверка соединения с базой данных
    • pg_port - Возвращает номер порта, соответствующий заданному соединению
    • pg_prepare - Посылает запрос на создание параметризованного SQL выражения и ждет его завершения
    • pg_put_line - Передает на PostgreSQL сервер строку с завершающим нулем
    • pg_query - Выполняет запрос
    • pg_query_params - Посылает параметризованный запрос на сервер, параметры передаются отдельно от текста SQL запроса
    • pg_result_error - Возвращает сообщение об ошибке, связанной с запросом результата
    • pg_result_error_field - Возвращает конкретное поле из отчета об ошибках
    • pg_result_seek - Смещает указатель на строку выборки в ресурсе результата запроса
    • pg_result_status - Возвращает состояние результата запроса
    • pg_select - Выбирает записи из базы данных
    • pg_send_execute - Запускает предварительно подготовленный SQL запрос и передает ему параметры; не ожидает возвращаемого результата
    • pg_send_prepare - Посылает запрос на создание параметризованного SQL выражения; не ожидает его завершения
    • pg_send_query - Отправляет асинхронный запрос
    • pg_send_query_params - Посылает параметризованный запрос на сервер, не ожидает возвращаемого результата
    • pg_set_client_encoding - Устанавливает клиентскую кодировку
    • pg_set_error_verbosity - Определяет объем текста сообщений, возвращаемых функциями pg_last_error и pg_result_error
    • pg_trace - Включает трассировку подключения PostgreSQL
    • pg_transaction_status - Возвращает текущее состояние транзакции на сервере
    • pg_tty - Возвращает имя терминала TTY, связанное с соединением
    • pg_unescape_bytea - Убирает экранирование двоичных данных типа bytea
    • pg_untrace - Отключает трассировку соединения с PostgreSQL
    • pg_update - Обновление данных в таблице
    • pg_version - Возвращает массив, содержащий версии клиента, протокола клиент-серверного взаимодействия и сервера (если доступно)
    • phar:// - PHP архив
    • Phar::addEmptyDir - Add an empty directory to the phar archive
    • Phar::addFile - Add a file from the filesystem to the phar archive
    • Phar::addFromString - Add a file from the filesystem to the phar archive
    • Phar::apiVersion - Returns the api version
    • Phar::buildFromDirectory - Construct a phar archive from the files within a directory.
    • Phar::buildFromIterator - Construct a phar archive from an iterator.
    • Phar::canCompress - Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite - Returns whether phar extension supports writing and creating phars
    • Phar::compress - Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::compressAllFilesBZIP2 - Compresses all files in the current Phar archive using Bzip2 compression
    • Phar::compressAllFilesGZ - Compresses all files in the current Phar archive using Gzip compression
    • Phar::compressFiles - Compresses all files in the current Phar archive
    • Phar::convertToData - Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable - Convert a phar archive to another executable phar archive file format
    • Phar::copy - Copy a file internal to the phar archive to another new file within the phar
    • Phar::count - Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub - Create a phar-file format specific stub
    • Phar::decompress - Decompresses the entire Phar archive
    • Phar::decompressFiles - Decompresses all files in the current Phar archive
    • Phar::delete - Delete a file within a phar archive
    • Phar::delMetadata - Deletes the global metadata of the phar
    • Phar::extractTo - Extract the contents of a phar archive to a directory
    • Phar::getMetadata - Returns phar archive meta-data
    • Phar::getModified - Return whether phar was modified
    • Phar::getSignature - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub - Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression - Return array of supported compression algorithms
    • Phar::getSupportedSignatures - Return array of supported signature types
    • Phar::getVersion - Return version info of Phar archive
    • Phar::hasMetadata - Returns whether phar has global meta-data
    • Phar::interceptFileFuncs - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat - Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename - Returns whether the given filename is a valid phar filename
    • Phar::isWritable - Returns true if the phar archive can be modified
    • Phar::loadPhar - Loads any phar archive with an alias
    • Phar::mapPhar - Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount - Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer - Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists - determines whether a file exists in the phar
    • Phar::offsetGet - Gets a PharFileInfo object for a specific file
    • Phar::offsetSet - set the contents of an internal file to those of an external file
    • Phar::offsetUnset - remove a file from a phar
    • Phar::running - Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias - Set the alias for the Phar archive
    • Phar::setDefaultStub - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata - Sets phar archive meta-data
    • Phar::setSignatureAlgorithm - set the signature algorithm for a phar and apply it. The
    • Phar::setStub - Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering - Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering - Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::uncompressAllFiles - Uncompresses all files in the current Phar archive
    • Phar::unlinkArchive - Completely remove a phar archive from disk and from memory
    • Phar::webPhar - mapPhar for web-based phars. front controller for web applications
    • Phar::__construct - Construct a Phar archive object
    • PharData::addEmptyDir - Add an empty directory to the tar/zip archive
    • PharData::addFile - Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString - Add a file from the filesystem to the tar/zip archive
    • PharData::buildFromDirectory - Construct a tar/zip archive from the files within a directory.
    • PharData::buildFromIterator - Construct a tar or zip archive from an iterator.
    • PharData::compress - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles - Compresses all files in the current tar/zip archive
    • PharData::convertToData - Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable - Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy - Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress - Decompresses the entire Phar archive
    • PharData::decompressFiles - Decompresses all files in the current zip archive
    • PharData::delete - Delete a file within a tar/zip archive
    • PharData::delMetadata - Deletes the global metadata of a zip archive
    • PharData::extractTo - Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable - Returns true if the tar/zip archive can be modified
    • PharData::offsetSet - set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset - remove a file from a tar/zip archive
    • PharData::setAlias - dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub - dummy function (Phar::setDefaultStub is not valid for PharData)
    • PharData::setStub - dummy function (Phar::setStub is not valid for PharData)
    • PharData::__construct - Construct a non-executable tar or zip archive object
    • PharException - The PharException class provides a phar-specific exception class for try/catch blocks.
    • PharFileInfo::chmod - Sets file-specific permission bits
    • PharFileInfo::compress - Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::decompress - Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata - Deletes the metadata of the entry
    • PharFileInfo::getCompressedSize - Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getCRC32 - Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getMetadata - Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags - Returns the Phar file entry flags
    • PharFileInfo::hasMetadata - Returns the metadata of the entry
    • PharFileInfo::isCompressed - Returns whether the entry is compressed
    • PharFileInfo::isCompressedBZIP2 - Returns whether the entry is compressed using bzip2
    • PharFileInfo::isCompressedGZ - Returns whether the entry is compressed using gz
    • PharFileInfo::isCRCChecked - Returns whether file entry has had its CRC verified
    • PharFileInfo::setCompressedBZIP2 - Compresses the current Phar entry within the phar using Bzip2 compression
    • PharFileInfo::setCompressedGZ - Compresses the current Phar entry within the phar using gz compression
    • PharFileInfo::setMetadata - Sets file-specific meta-data saved with a file
    • PharFileInfo::setUncompressed - Uncompresses the current Phar entry within the phar, if it is compressed
    • PharFileInfo::__construct - Construct a Phar entry object
    • php:// - Доступ к различным потокам ввода-вывода
    • phpcredits - Prints out the credits for PHP
    • phpinfo - Outputs information about PHP's configuration
    • phpversion - Gets the current PHP version
    • php_check_syntax - Проверяет (и запускает) PHP синтаксис указанного файла
    • php_ini_loaded_file - Retrieve a path to the loaded php.ini file
    • php_ini_scanned_files - Return a list of .ini files parsed from the additional ini dir
    • php_logo_guid - Gets the logo guid
    • php_sapi_name - Returns the type of interface between web server and PHP
    • php_strip_whitespace - Возвращает исходный код без комментариев и пробелов
    • php_uname - Returns information about the operating system PHP is running on
    • php_user_filter::filter - Called when applying the filter
    • php_user_filter::onClose - Called when closing the filter
    • php_user_filter::onCreate - Called when creating the filter
    • pi - Возвращает число Пи
    • png2wbmp - Преобразование PNG файла в WBMP
    • popen - Открывает файловый указатель процесса
    • pos - Псевдоним current
    • posix_access - Determine accessibility of a file
    • posix_ctermid - Get path name of controlling terminal
    • posix_errno - Псевдоним posix_get_last_error
    • posix_getcwd - Pathname of current directory
    • posix_getegid - Return the effective group ID of the current process
    • posix_geteuid - Return the effective user ID of the current process
    • posix_getgid - Return the real group ID of the current process
    • posix_getgrgid - Return info about a group by group id
    • posix_getgrnam - Return info about a group by name
    • posix_getgroups - Return the group set of the current process
    • posix_getlogin - Return login name
    • posix_getpgid - Get process group id for job control
    • posix_getpgrp - Return the current process group identifier
    • posix_getpid - Return the current process identifier
    • posix_getppid - Return the parent process identifier
    • posix_getpwnam - Return info about a user by username
    • posix_getpwuid - Return info about a user by user id
    • posix_getrlimit - Return info about system resource limits
    • posix_getsid - Get the current sid of the process
    • posix_getuid - Return the real user ID of the current process
    • posix_get_last_error - Retrieve the error number set by the last posix function that failed
    • posix_initgroups - Calculate the group access list
    • posix_isatty - Determine if a file descriptor is an interactive terminal
    • posix_kill - Send a signal to a process
    • posix_mkfifo - Create a fifo special file (a named pipe)
    • posix_mknod - Create a special or ordinary file (POSIX.1)
    • posix_setegid - Set the effective GID of the current process
    • posix_seteuid - Set the effective UID of the current process
    • posix_setgid - Set the GID of the current process
    • posix_setpgid - Set process group id for job control
    • posix_setsid - Make the current process a session leader
    • posix_setuid - Set the UID of the current process
    • posix_strerror - Retrieve the system error message associated with the given errno
    • posix_times - Get process times
    • posix_ttyname - Determine terminal device name
    • posix_uname - Get system name
    • pow - Возведение в степень
    • preg_filter - Производит поиск и замену по регулярному выражению
    • preg_grep - Возвращает массив вхождений, которые соответствуют шаблону
    • preg_last_error - Возвращает код ошибки выполнения последнего регулярного выражения PCRE
    • preg_match - Выполняет проверку на соответствие регулярному выражению
    • preg_match_all - Выполняет глобальный поиск шаблона в строке
    • preg_quote - Экранирует символы в регулярных выражениях
    • preg_replace - Выполняет поиск и замену по регулярному выражению
    • preg_replace_callback - Выполняет поиск по регулярному выражению и замену с использованием callback-функции
    • preg_split - Разбивает строку по регулярному выражению
    • prev - Передвигает внутренний указатель массива на одну позицию назад
    • print - Выводит строку
    • printer_abort - Удаляет файл из буфера подготовки к печати
    • printer_close - Закрывает соединение с принтером
    • printer_create_brush - Create a new brush
    • printer_create_dc - Создает новый контекст устройства
    • printer_create_font - Create a new font
    • printer_create_pen - Create a new pen
    • printer_delete_brush - Удаляет кисть
    • printer_delete_dc - Удаляет контекст устройства
    • printer_delete_font - Удаляет выбранный шрифт
    • printer_delete_pen - Удаляет перо
    • printer_draw_bmp - Рисует bmp
    • printer_draw_chord - Рисует хорду
    • printer_draw_elipse - Рисует эллипс
    • printer_draw_line - Рисует линию
    • printer_draw_pie - Рисует сектор круга
    • printer_draw_rectangle - Рисует прямоугольник
    • printer_draw_roundrect - Рисует прямоугольник со сглаженными углами
    • printer_draw_text - Рисует текст
    • printer_end_doc - Закрывает документ
    • printer_end_page - Закрывает активную страницу
    • printer_get_option - Получает настройки принтера
    • printer_list - Возвращает массив принтеров, подсоединенных к серверу
    • printer_logical_fontheight - Получает логическую высоту шрифта
    • printer_open - Открывает соединение с принтером
    • printer_select_brush - Выбирает кисть
    • printer_select_font - Выбирает шрифт
    • printer_select_pen - Выбирает перо
    • printer_set_option - Настройка соединения с принтером
    • printer_start_doc - Начинает новый документ
    • printer_start_page - Начинает новую страницу
    • printer_write - Отправляет данные на принтер
    • printf - Выводит отформатированную строку
    • print_r - Выводит удобочитаемую информацию о переменной
    • proc_close - Завершает процесс, открытый при помощи функции proc_open и возвращает код завершения этого процесса
    • proc_get_status - Получает информацию о процессе, открытом при помощи функции proc_open
    • proc_nice - Изменяет приоритет текущего процесса
    • proc_open - Выполняет команду и открывает указатель на файл для ввода/вывода
    • proc_terminate - Уничтожает процесс, открытый при помощи функции proc_open
    • property_exists - Проверяет, содержит ли объект или класс указанный атрибут
    • pspell_add_to_personal - Добавляет слово в персональный список слов
    • pspell_add_to_session - Добавляет слово в список слов в текущей сессии
    • pspell_check - Проверяет слово
    • pspell_clear_session - Очищает текущую сессию
    • pspell_config_create - Создает конфигурацию, используемую для открытия словаря
    • pspell_config_data_dir - Расположение файлов с языковыми данными
    • pspell_config_dict_dir - Расположение основного списка слов
    • pspell_config_ignore - Игнорирует слова длиной менее N символов
    • pspell_config_mode - Изменяет режим количества возвращаемых вариантов исправления
    • pspell_config_personal - Устанавливает файл, содержащий персональный список слов
    • pspell_config_repl - Устанавливает файл, содержащий замещающие пары
    • pspell_config_runtogether - Рассматривает объединённые слова как правильные сложные слова
    • pspell_config_save_repl - Определяет, сохранять ли список замещающих пар вместе со списком слов
    • pspell_new - Загружает новый словарь
    • pspell_new_config - Загружает новый словарь с установками на основе заданной конфигурации
    • pspell_new_personal - Загружает новый словарь с персональным списком слов
    • pspell_save_wordlist - Сохраняет персональный список слов в файле
    • pspell_store_replacement - Сохраняет замещающую пару для слова
    • pspell_suggest - Предлагает варианты исправления слова
    • ps_add_bookmark - Add bookmark to current page
    • ps_add_launchlink - Adds link which launches file
    • ps_add_locallink - Adds link to a page in the same document
    • ps_add_note - Adds note to current page
    • ps_add_pdflink - Adds link to a page in a second pdf document
    • ps_add_weblink - Adds link to a web location
    • ps_arc - Draws an arc counterclockwise
    • ps_arcn - Draws an arc clockwise
    • ps_begin_page - Start a new page
    • ps_begin_pattern - Start a new pattern
    • ps_begin_template - Start a new template
    • ps_circle - Draws a circle
    • ps_clip - Clips drawing to current path
    • ps_close - Closes a PostScript document
    • ps_closepath - Closes path
    • ps_closepath_stroke - Closes and strokes path
    • ps_close_image - Closes image and frees memory
    • ps_continue_text - Continue text in next line
    • ps_curveto - Draws a curve
    • ps_delete - Deletes all resources of a PostScript document
    • ps_end_page - End a page
    • ps_end_pattern - End a pattern
    • ps_end_template - End a template
    • ps_fill - Fills the current path
    • ps_fill_stroke - Fills and strokes the current path
    • ps_findfont - Loads a font
    • ps_get_buffer - Fetches the full buffer containig the generated PS data
    • ps_get_parameter - Gets certain parameters
    • ps_get_value - Gets certain values
    • ps_hyphenate - Hyphenates a word
    • ps_include_file - Reads an external file with raw PostScript code
    • ps_lineto - Draws a line
    • ps_makespotcolor - Create spot color
    • ps_moveto - Sets current point
    • ps_new - Creates a new PostScript document object
    • ps_open_file - Opens a file for output
    • ps_open_image - Reads an image for later placement
    • ps_open_image_file - Opens image from file
    • ps_open_memory_image - Takes an GD image and returns an image for placement in a PS document
    • ps_place_image - Places image on the page
    • ps_rect - Draws a rectangle
    • ps_restore - Restore previously save context
    • ps_rotate - Sets rotation factor
    • ps_save - Save current context
    • ps_scale - Sets scaling factor
    • ps_setcolor - Sets current color
    • ps_setdash - Sets appearance of a dashed line
    • ps_setflat - Sets flatness
    • ps_setfont - Sets font to use for following output
    • ps_setgray - Sets gray value
    • ps_setlinecap - Sets appearance of line ends
    • ps_setlinejoin - Sets how contected lines are joined
    • ps_setlinewidth - Sets width of a line
    • ps_setmiterlimit - Sets the miter limit
    • ps_setoverprintmode - Sets overprint mode
    • ps_setpolydash - Sets appearance of a dashed line
    • ps_set_border_color - Sets color of border for annotations
    • ps_set_border_dash - Sets length of dashes for border of annotations
    • ps_set_border_style - Sets border style of annotations
    • ps_set_info - Sets information fields of document
    • ps_set_parameter - Sets certain parameters
    • ps_set_text_pos - Sets position for text output
    • ps_set_value - Sets certain values
    • ps_shading - Creates a shading for later use
    • ps_shading_pattern - Creates a pattern based on a shading
    • ps_shfill - Fills an area with a shading
    • ps_show - Output text
    • ps_show2 - Output a text at current position
    • ps_show_boxed - Output text in a box
    • ps_show_xy - Output text at given position
    • ps_show_xy2 - Output text at position
    • ps_stringwidth - Gets width of a string
    • ps_string_geometry - Gets geometry of a string
    • ps_stroke - Draws the current path
    • ps_symbol - Output a glyph
    • ps_symbol_name - Gets name of a glyph
    • ps_symbol_width - Gets width of a glyph
    • ps_translate - Sets translation
    • putenv - Sets the value of an environment variable
    • px_close - Closes a paradox database
    • px_create_fp - Create a new paradox database
    • px_date2string - Converts a date into a string.
    • px_delete - Deletes resource of paradox database
    • px_delete_record - Deletes record from paradox database
    • px_get_field - Returns the specification of a single field
    • px_get_info - Return lots of information about a paradox file
    • px_get_parameter - Gets a parameter
    • px_get_record - Returns record of paradox database
    • px_get_schema - Returns the database schema
    • px_get_value - Gets a value
    • px_insert_record - Inserts record into paradox database
    • px_new - Create a new paradox object
    • px_numfields - Returns number of fields in a database
    • px_numrecords - Returns number of records in a database
    • px_open_fp - Open paradox database
    • px_put_record - Stores record into paradox database
    • px_retrieve_record - Returns record of paradox database
    • px_set_blob_file - Sets the file where blobs are read from
    • px_set_parameter - Sets a parameter
    • px_set_tablename - Sets the name of a table (deprecated)
    • px_set_targetencoding - Sets the encoding for character fields (deprecated)
    • px_set_value - Sets a value
    • px_timestamp2string - Converts the timestamp into a string.
    • px_update_record - Updates record in paradox database
  • q
    • qdom_error - Возвращает строку ошибки из последней операции QDOM или FALSE, если ошибок не было
    • qdom_tree - Создает дерево XML-строки
    • QuickHashIntHash::add - This method adds a new entry to the hash
    • QuickHashIntHash::delete - This method deletes am entry from the hash
    • QuickHashIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize - Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntHash::__construct - Creates a new QuickHashIntHash object
    • QuickHashIntSet::add - This method adds a new entry to the set
    • QuickHashIntSet::delete - This method deletes an entry from the set
    • QuickHashIntSet::exists - This method checks whether a key is part of the set
    • QuickHashIntSet::getSize - Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile - This factory method creates a set from a file
    • QuickHashIntSet::loadFromString - This factory method creates a set from a string
    • QuickHashIntSet::saveToFile - This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString - This method returns a serialized version of the set
    • QuickHashIntSet::__construct - Creates a new QuickHashIntSet object
    • QuickHashIntStringHash::add - This method adds a new entry to the hash
    • QuickHashIntStringHash::delete - This method deletes am entry from the hash
    • QuickHashIntStringHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize - Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntStringHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntStringHash::__construct - Creates a new QuickHashIntStringHash object
    • QuickHashStringIntHash::add - This method adds a new entry to the hash
    • QuickHashStringIntHash::delete - This method deletes am entry from the hash
    • QuickHashStringIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize - Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashStringIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashStringIntHash::__construct - Creates a new QuickHashStringIntHash object
    • quoted_printable_decode - Преобразует строку, закодированную методом quoted-printable в 8-битовую строку
    • quoted_printable_encode - Кодирует 8-битную строку в с помощью метода quoted-printable
    • quotemeta - Экранирует специальные символы
  • r
    • rad2deg - Преобразует значение из радианов в градусы
    • radius_acct_open - Creates a Radius handle for accounting
    • radius_add_server - Adds a server
    • radius_auth_open - Creates a Radius handle for authentication
    • radius_close - Frees all ressources
    • radius_config - Causes the library to read the given configuration file
    • radius_create_request - Create accounting or authentication request
    • radius_cvt_addr - Converts raw data to IP-Address
    • radius_cvt_int - Converts raw data to integer
    • radius_cvt_string - Converts raw data to string
    • radius_demangle - Demangles data
    • radius_demangle_mppe_key - Derives mppe-keys from mangled data
    • radius_get_attr - Extracts an attribute
    • radius_get_vendor_attr - Extracts a vendor specific attribute
    • radius_put_addr - Attaches an IP-Address attribute
    • radius_put_attr - Attaches a binary attribute
    • radius_put_int - Attaches an integer attribute
    • radius_put_string - Attaches a string attribute
    • radius_put_vendor_addr - Attaches a vendor specific IP-Address attribute
    • radius_put_vendor_attr - Attaches a vendor specific binary attribute
    • radius_put_vendor_int - Attaches a vendor specific integer attribute
    • radius_put_vendor_string - Attaches a vendor specific string attribute
    • radius_request_authenticator - Returns the request authenticator
    • radius_send_request - Sends the request and waites for a reply
    • radius_server_secret - Returns the shared secret
    • radius_strerror - Returns an error message
    • rand - Генерирует случайное число
    • range - Создает массив, содержащий диапазон элементов
    • rar:// - RAR
    • RarArchive::close - Close RAR archive and free all resources
    • RarArchive::getComment - Get comment text from the RAR archive
    • RarArchive::getEntries - Get full list of entries from the RAR archive
    • RarArchive::getEntry - Get entry object from the RAR archive
    • RarArchive::isBroken - Test whether an archive is broken (incomplete)
    • RarArchive::isSolid - Check whether the RAR archive is solid
    • RarArchive::open - Open RAR archive
    • RarArchive::setAllowBroken - Whether opening broken archives is allowed
    • RarArchive::__toString - Get text representation
    • RarEntry::extract - Extract entry from the archive
    • RarEntry::getAttr - Get attributes of the entry
    • RarEntry::getCrc - Get CRC of the entry
    • RarEntry::getFileTime - Get entry last modification time
    • RarEntry::getHostOs - Get entry host OS
    • RarEntry::getMethod - Get pack method of the entry
    • RarEntry::getName - Get name of the entry
    • RarEntry::getPackedSize - Get packed size of the entry
    • RarEntry::getStream - Get file handler for entry
    • RarEntry::getUnpackedSize - Get unpacked size of the entry
    • RarEntry::getVersion - Get minimum version of RAR program required to unpack the entry
    • RarEntry::isDirectory - Test whether an entry represents a directory
    • RarEntry::isEncrypted - Test whether an entry is encrypted
    • RarEntry::__toString - Get text representation of entry
    • RarException::isUsingExceptions - Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions - Activate and deactivate error handling with exceptions
    • rar_wrapper_cache_stats - Кэш доступов и отказов обертки URL
    • rawurldecode - Декодирование URL-кодированной строки
    • rawurlencode - URL-кодирование строки согласно RFC 3986
    • readdir - Получает элемент каталога по его дескриптору
    • readfile - Выводит файл
    • readgzfile - Выводит содержимое gz-файла
    • readline - Reads a line
    • readline_add_history - Adds a line to the history
    • readline_callback_handler_install - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
    • readline_callback_handler_remove - Removes a previously installed callback handler and restores terminal settings
    • readline_callback_read_char - Reads a character and informs the readline callback interface when a line is received
    • readline_clear_history - Clears the history
    • readline_completion_function - Registers a completion function
    • readline_info - Gets/sets various internal readline variables
    • readline_list_history - Lists the history
    • readline_on_new_line - Inform readline that the cursor has moved to a new line
    • readline_read_history - Reads the history
    • readline_redisplay - Redraws the display
    • readline_write_history - Writes the history
    • readlink - Возвращает файл, на который указывает символическая ссылка
    • read_exif_data - Псевдоним exif_read_data
    • realpath - Возвращает канонизированный абсолютный путь к файлу
    • realpath_cache_get - Получает записи из кэша реального пути
    • realpath_cache_size - Получает размер кэша реального пути
    • recode - Псевдоним recode_string
    • recode_file - Recode from file to file according to recode request
    • recode_string - Recode a string according to a recode request
    • RecursiveArrayIterator::getChildren - Returns an iterator for the current entry if it is an array or an object.
    • RecursiveArrayIterator::hasChildren - Returns whether current entry is an array or an object.
    • RecursiveCachingIterator::getChildren - Возвращает потомков внутреннего итератора в виде объекта RecursiveCachingIterator
    • RecursiveCachingIterator::hasChildren - Проверяет, имеет ли текущий элемент внутреннего итератора потомков
    • RecursiveCachingIterator::__construct - Конструктор
    • RecursiveCallbackFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveCallbackFilterIterator::__construct - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Returns an iterator for the current entry if it is a directory
    • RecursiveDirectoryIterator::getSubPath - Get sub path
    • RecursiveDirectoryIterator::getSubPathname - Get sub path and name
    • RecursiveDirectoryIterator::hasChildren - Returns whether current entry is a directory and not '.' or '..'
    • RecursiveDirectoryIterator::key - Return path and filename of current dir entry
    • RecursiveDirectoryIterator::next - Move to next entry
    • RecursiveDirectoryIterator::rewind - Rewind dir back to the start
    • RecursiveDirectoryIterator::__construct - Constructs a RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveFilterIterator::__construct - Create a RecursiveFilterIterator from a RecursiveIterator
    • RecursiveIterator::getChildren - Returns an iterator for the current entry.
    • RecursiveIterator::hasChildren - Returns if an iterator can be created fot the current entry.
    • RecursiveIteratorIterator::beginChildren - Begin children
    • RecursiveIteratorIterator::beginIteration - Begin Iteration
    • RecursiveIteratorIterator::callGetChildren - Get children
    • RecursiveIteratorIterator::callHasChildren - Has children
    • RecursiveIteratorIterator::current - Access the current element value
    • RecursiveIteratorIterator::endChildren - End children
    • RecursiveIteratorIterator::endIteration - End Iteration
    • RecursiveIteratorIterator::getDepth - Get the current depth of the recursive iteration
    • RecursiveIteratorIterator::getInnerIterator - Get inner iterator
    • RecursiveIteratorIterator::getMaxDepth - Get max depth
    • RecursiveIteratorIterator::getSubIterator - The current active sub iterator
    • RecursiveIteratorIterator::key - Access the current key
    • RecursiveIteratorIterator::next - Move forward to the next element
    • RecursiveIteratorIterator::nextElement - Next element
    • RecursiveIteratorIterator::rewind - Rewind the iterator to the first element of the top level inner iterator
    • RecursiveIteratorIterator::setMaxDepth - Set max depth
    • RecursiveIteratorIterator::valid - Check whether the current position is valid
    • RecursiveIteratorIterator::__construct - Construct a RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Returns an iterator for the current entry.
    • RecursiveRegexIterator::hasChildren - Returns whether an iterator can be obtained for the current entry.
    • RecursiveRegexIterator::__construct - Creates a new RecursiveRegexIterator.
    • RecursiveTreeIterator::beginChildren - Begin children
    • RecursiveTreeIterator::beginIteration - Begin iteration
    • RecursiveTreeIterator::callGetChildren - Get children
    • RecursiveTreeIterator::callHasChildren - Has children
    • RecursiveTreeIterator::current - Get current element
    • RecursiveTreeIterator::endChildren - End children
    • RecursiveTreeIterator::endIteration - End iteration
    • RecursiveTreeIterator::getEntry - Get current entry
    • RecursiveTreeIterator::getPostfix - Get the postfix
    • RecursiveTreeIterator::getPrefix - Get the prefix
    • RecursiveTreeIterator::key - Get the key of the current element
    • RecursiveTreeIterator::next - Move to next element
    • RecursiveTreeIterator::nextElement - Next element
    • RecursiveTreeIterator::rewind - Rewind iterator
    • RecursiveTreeIterator::setPrefixPart - Set a part of the prefix
    • RecursiveTreeIterator::valid - Check validity
    • RecursiveTreeIterator::__construct - Construct a RecursiveTreeIterator
    • Reflection::export - Экспортирует Reflection
    • Reflection::getModifierNames - Получение имен модификаторов
    • ReflectionClass::export - Экспортирует класс
    • ReflectionClass::getConstant - Возвращает определенную константу
    • ReflectionClass::getConstants - Возвращает константы
    • ReflectionClass::getConstructor - Возвращает конструктор
    • ReflectionClass::getDefaultProperties - Возвращает свойства по умолчанию
    • ReflectionClass::getDocComment - Возвращает doc-блоки комментариев
    • ReflectionClass::getEndLine - Возвращает номер последней строки
    • ReflectionClass::getExtension - Возвращает информацию о расширении
    • ReflectionClass::getExtensionName - Возвращает имя расширения
    • ReflectionClass::getFileName - Возвращает имя файла, в котором объявлен класс
    • ReflectionClass::getInterfaceNames - Возвращает имена интерфейсов
    • ReflectionClass::getInterfaces - Возвращает интерфейсы
    • ReflectionClass::getMethod - Возвращает объект класса ReflectionMethod
    • ReflectionClass::getMethods - Возвращает список методов
    • ReflectionClass::getModifiers - Возвращает информацию о модификаторах класса
    • ReflectionClass::getName - Возвращает имя класса
    • ReflectionClass::getNamespaceName - Возвращает название пространства имён
    • ReflectionClass::getParentClass - Возвращает родительский класс
    • ReflectionClass::getProperties - Возвращает свойства
    • ReflectionClass::getProperty - Возвращает свойство
    • ReflectionClass::getShortName - Возвращает короткое имя
    • ReflectionClass::getStartLine - Возвращает номер начальной строки
    • ReflectionClass::getStaticProperties - Возвращает static свойства
    • ReflectionClass::getStaticPropertyValue - Возвращает значение static свойства
    • ReflectionClass::getTraitAliases - Возвращает массив trait-псевдонимов
    • ReflectionClass::getTraitNames - Возвращает массив trait-имён, задействованных в этом классе
    • ReflectionClass::getTraits - Возвращает массив traits, задействованных в этом классе
    • ReflectionClass::hasConstant - Проверяет, задана ли константа
    • ReflectionClass::hasMethod - Проверяет, задан ли метод
    • ReflectionClass::hasProperty - Проверяет, задано ли свойство
    • ReflectionClass::implementsInterface - Проверяет, реализуется ли интерфейс
    • ReflectionClass::inNamespace - Проверяет, определён ли класс в пространстве имён
    • ReflectionClass::isAbstract - Проверяет, является ли класс абстрактным
    • ReflectionClass::isCloneable - Проверяет, можно ли клонировать этот класс
    • ReflectionClass::isFinal - Проверяет, является ли класс окончательным (final)
    • ReflectionClass::isInstance - Проверяет, принадлежит ли объект классу
    • ReflectionClass::isInstantiable - Проверяет, можно ли создать экземпляр класса
    • ReflectionClass::isInterface - Проверяет, является ли класс интерфейсом
    • ReflectionClass::isInternal - Проверяет, является ли класс встроенным
    • ReflectionClass::isIterateable - Проверяет, является ли класс итерируемым
    • ReflectionClass::isSubclassOf - Проверяет, является ли класс подклассом
    • ReflectionClass::isTrait - Проверяет, является ли класс trait
    • ReflectionClass::isUserDefined - Проверяет, является ли класс пользовательским
    • ReflectionClass::newInstance - Создаёт экземпляр класса с переданными аргументами
    • ReflectionClass::newInstanceArgs - Создаёт экземпляр класса с переданными параметрами
    • ReflectionClass::newInstanceWithoutConstructor - Создаёт новый экземпляр класса без вызова конструктора
    • ReflectionClass::setStaticPropertyValue - Устанавливает значение static-свойства
    • ReflectionClass::__construct - Создаёт объект класса ReflectionClass
    • ReflectionClass::__toString - Возвращает строковое представление объекта класса ReflectionClass
    • ReflectionExtension::export - Экспортирует модуль
    • ReflectionExtension::getClasses - Возвращает классы
    • ReflectionExtension::getClassNames - Получение имен классов
    • ReflectionExtension::getConstants - Получение констант
    • ReflectionExtension::getDependencies - Получение зависимостей
    • ReflectionExtension::getFunctions - Получение функций расширения
    • ReflectionExtension::getINIEntries - Получение ini-настроек расширения
    • ReflectionExtension::getName - Получение имени расширения
    • ReflectionExtension::getVersion - Получение версии расширения
    • ReflectionExtension::info - Вывод информации о расширении
    • ReflectionExtension::isPersistent - Определяет, является ли расширение постоянным
    • ReflectionExtension::isTemporary - Определяет, является ли расширение временным
    • ReflectionExtension::__clone - Клонирует объект
    • ReflectionExtension::__construct - Создаёт объект класса ReflectionExtension
    • ReflectionExtension::__toString - Преобразование в строку
    • ReflectionFunction::export - Экспорт функции
    • ReflectionFunction::getClosure - Возвращает динамически созданное замыкание для функции
    • ReflectionFunction::invoke - Вызывает функцию
    • ReflectionFunction::invokeArgs - Вызов функции с передачей аргументов
    • ReflectionFunction::isDisabled - Проверяет, что функция отключена
    • ReflectionFunction::__construct - Конструктор класса ReflectionFunction
    • ReflectionFunction::__toString - Представление в виде строки
    • ReflectionFunctionAbstract::getClosureThis - Возвращает указатель this замыкания
    • ReflectionFunctionAbstract::getDocComment - Получает документируемый комментарий
    • ReflectionFunctionAbstract::getEndLine - Получает номер строки завершения описания функции
    • ReflectionFunctionAbstract::getExtension - Получает информацию о расширении
    • ReflectionFunctionAbstract::getExtensionName - Получение имени расширения
    • ReflectionFunctionAbstract::getFileName - Получает имя файла
    • ReflectionFunctionAbstract::getName - Получает имя функции
    • ReflectionFunctionAbstract::getNamespaceName - Получение имени пространства имен
    • ReflectionFunctionAbstract::getNumberOfParameters - Получает количество аргументов
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters - Получает количество обязательных аргументов
    • ReflectionFunctionAbstract::getParameters - Получает аргументы
    • ReflectionFunctionAbstract::getShortName - Получает короткое имя функции
    • ReflectionFunctionAbstract::getStartLine - Получает начальный номер строки
    • ReflectionFunctionAbstract::getStaticVariables - Получает статические переменные
    • ReflectionFunctionAbstract::inNamespace - Проверяет, находится ли функция в пространстве имен
    • ReflectionFunctionAbstract::isClosure - Проверяет, является ли функция замыканием
    • ReflectionFunctionAbstract::isDeprecated - Проверяет, является ли функция устаревшей
    • ReflectionFunctionAbstract::isInternal - Проверяет, является ли функция внутренней
    • ReflectionFunctionAbstract::isUserDefined - Проверяет, является ли функция определенной пользователем
    • ReflectionFunctionAbstract::returnsReference - Проверяет, что функция возвращает ссылку
    • ReflectionFunctionAbstract::__clone - Копирующий конструктор
    • ReflectionFunctionAbstract::__toString - Преобразование в строку
    • ReflectionMethod::export - Экспорт отраженного метода
    • ReflectionMethod::getClosure - Возвращает динамически созданное замыкание для метода
    • ReflectionMethod::getDeclaringClass - Получает класс, объявляющий отображенный метод
    • ReflectionMethod::getModifiers - Получает модификаторы метода
    • ReflectionMethod::getPrototype - Получает прототип метода (если такой есть)
    • ReflectionMethod::invoke - Вызов
    • ReflectionMethod::invokeArgs - Вызов метода с передачей аргументов массивом
    • ReflectionMethod::isAbstract - Проверяет, является ли метод абстрактным
    • ReflectionMethod::isConstructor - Проверяет, является ли метод конструктором
    • ReflectionMethod::isDestructor - Проверяет, является ли метод деструктором
    • ReflectionMethod::isFinal - Проверяет, может ли метод иметь наследников (final)
    • ReflectionMethod::isPrivate - Проверяет, является ли метод частным (private)
    • ReflectionMethod::isProtected - Проверяет, является ли метод защищенным (protected)
    • ReflectionMethod::isPublic - Проверяет, является ли метод общедоступным (public)
    • ReflectionMethod::isStatic - Проверяет, является ли метод статическим
    • ReflectionMethod::setAccessible - Делает метод доступным
    • ReflectionMethod::__construct - Конструктор класса ReflectionMethod
    • ReflectionMethod::__toString - Возвращает строковое представление объекта Reflection method
    • ReflectionObject::export - Экспорт
    • ReflectionObject::__construct - Конструктор класса ReflectionObject
    • ReflectionParameter::allowsNull - Проверяет, допустимо ли значение null для аргумента
    • ReflectionParameter::canBePassedByValue - Проверяет, можно ли передать этот аргумент по значению
    • ReflectionParameter::export - Экспорт
    • ReflectionParameter::getClass - Получение класса
    • ReflectionParameter::getDeclaringClass - Получение объявляющего класса
    • ReflectionParameter::getDeclaringFunction - Получение объявляющей функции
    • ReflectionParameter::getDefaultValue - Получение значения по умолчанию аргумента
    • ReflectionParameter::getName - Получение имени аргумента
    • ReflectionParameter::getPosition - Получение позиции аргумента
    • ReflectionParameter::isArray - Проверяет, ожидает ли аргумент массив в качестве значения
    • ReflectionParameter::isDefaultValueAvailable - Проверяет доступно ли значение по умолчанию аргумента
    • ReflectionParameter::isOptional - Проверка, является ли аргумент необязательным
    • ReflectionParameter::isPassedByReference - Проверяет, что аргумент передан по ссылке
    • ReflectionParameter::__clone - Копирующий конструктор
    • ReflectionParameter::__construct - Конструктор класса
    • ReflectionParameter::__toString - Преобразование в строку
    • ReflectionProperty::export - Экспорт
    • ReflectionProperty::getDeclaringClass - Получение объявляющего класса
    • ReflectionProperty::getDocComment - Получение документируемого комментария
    • ReflectionProperty::getModifiers - Получение модификаторов
    • ReflectionProperty::getName - Получение имени свойства
    • ReflectionProperty::getValue - Получение значения
    • ReflectionProperty::isDefault - Проверяет, является ли значение свойством по умолчанию
    • ReflectionProperty::isPrivate - Проверяет, является ли свойство частным (private)
    • ReflectionProperty::isProtected - Проверяет, является ли свойство защищенным (protected)
    • ReflectionProperty::isPublic - Проверяет, является ли свойство общедоступным (public)
    • ReflectionProperty::isStatic - Проверка, является ли свойство статическим
    • ReflectionProperty::setAccessible - Задание доступности свойства
    • ReflectionProperty::setValue - Задание значения свойству
    • ReflectionProperty::__clone - Копирующий конструктор
    • ReflectionProperty::__construct - Конструктор класса ReflectionProperty
    • ReflectionProperty::__toString - Преобразование в строку
    • ReflectionZendExtension::export - Экспорт
    • ReflectionZendExtension::getAuthor - Получение автора
    • ReflectionZendExtension::getCopyright - Получение строки авторских прав
    • ReflectionZendExtension::getName - Получение строки имени
    • ReflectionZendExtension::getURL - Получение URL
    • ReflectionZendExtension::getVersion - Получение номера версии
    • ReflectionZendExtension::__clone - Копирующий конструктор
    • ReflectionZendExtension::__construct - Конструктор
    • ReflectionZendExtension::__toString - Преобразование в строку
    • Reflector::export - Экспорт
    • Reflector::__toString - Представление в виде строки
    • RegexIterator::accept - Get accept status
    • RegexIterator::getFlags - Get flags
    • RegexIterator::getMode - Returns operation mode.
    • RegexIterator::getPregFlags - Returns the regular expression flags.
    • RegexIterator::getRegex - Returns current regular expression
    • RegexIterator::setFlags - Sets the flags.
    • RegexIterator::setMode - Sets the operation mode.
    • RegexIterator::setPregFlags - Sets the regular expression flags.
    • RegexIterator::__construct - Create a new RegexIterator
    • register_shutdown_function - Регистрирует функцию, которая выполнится по завершении работы скрипта
    • register_tick_function - Регистрирует функцию для выполнения при каждом тике
    • rename - Переименовывает файл или директорию
    • rename_function - Renames orig_name to new_name in the global function table
    • reset - Устанавливает внутренний указатель массива на его первый элемент
    • ResourceBundle::count - Get number of elements in the bundle
    • ResourceBundle::create - Create a resource bundle
    • ResourceBundle::get - Get data from the bundle
    • ResourceBundle::getErrorCode - Get bundle's last error code.
    • ResourceBundle::getErrorMessage - Get bundle's last error message.
    • ResourceBundle::getLocales - Get supported locales
    • restore_error_handler - Восстанавливает предыдущий обработчик ошибок
    • restore_exception_handler - Восстанавливает предыдущий обработчик исключений
    • restore_include_path - Restores the value of the include_path configuration option
    • rewind - Сбрасывает курсор у файлового указателя
    • rewinddir - Сбросить дескриптор каталога
    • rmdir - Удаляет директорию
    • round - Округляет число типа float
    • rpm_close - Closes an RPM file
    • rpm_get_tag - Retrieves a header tag from an RPM file
    • rpm_is_valid - Tests a filename for validity as an RPM file
    • rpm_open - Opens an RPM file
    • rpm_version - Returns a string representing the current version of the rpmreader extension
    • RRDCreator::addArchive - Adds RRA - archive of data values for each data source.
    • RRDCreator::addDataSource - Adds data source definition for RRD database.
    • RRDCreator::save - Saves the RRD database to a file
    • RRDCreator::__construct - Creates new RRDCreator instance
    • RRDGraph::save - Saves the result of query into image
    • RRDGraph::saveVerbose - Saves the RRD database query into image and returns the verbose information about generated graph.
    • RRDGraph::setOptions - Sets the options for rrd graph export
    • RRDGraph::__construct - Creates new RRDGraph instance
    • RRDUpdater::update - Update the RRD database file
    • RRDUpdater::__construct - Creates new RRDUpdater instance
    • rrd_create - Creates rrd database file
    • rrd_error - Gets latest error message.
    • rrd_fetch - Fetch the data for graph as array.
    • rrd_first - Gets the timestamp of the first sample from rrd file.
    • rrd_graph - Creates image from a data.
    • rrd_info - Gets information about rrd file
    • rrd_last - Gets unix timestamp of the last sample.
    • rrd_lastupdate - Gets information about last updated data.
    • rrd_restore - Restores the RRD file from XML dump.
    • rrd_tune - Tunes some RRD database file header options.
    • rrd_update - Updates the RRD database.
    • rrd_version - Gets information about underlying rrdtool library
    • rrd_xport - Exports the information about RRD database.
    • rsort - Сортирует массив в обратном порядке
    • rtrim - Удаляет пробелы (или другие символы) из конца строки
    • runkit_class_adopt - Конвертирует базовый класс в наследованный ("усыновляет"). Дополняет методы наследованными при необходимости.
    • runkit_class_emancipate - Конвертирует наследующий класс в базовый, удаляет из него наследуемые методы.
    • runkit_constant_add - Объявляет константу. Схожа с функцией define(), но позволяет создавать локальные константы внутри классов.
    • runkit_constant_redefine - Переназначить уже определенную константу.
    • runkit_constant_remove - Удаляет уже определенную константу.
    • runkit_function_add - Добавляет новую функцию аналогично create_function
    • runkit_function_copy - Копирует функцию с новым именем
    • runkit_function_redefine - Заменяет определение функции новой реализацией.
    • runkit_function_remove - Удаляет определенную функцию
    • runkit_function_rename - Переименовывает функцию
    • runkit_import - Обрабатывает PHP файл, импортируя функции и классы, перезаписывая при необходимости.
    • runkit_lint - Проверяет PHP-синтаксис выбранного кода
    • runkit_lint_file - Проверяет PHP-синтаксис выбранного файла
    • runkit_method_add - Добавляет метод в класс
    • runkit_method_copy - Копирование метода из одного класса в другой
    • runkit_method_redefine - Изменяет код выбранного метода
    • runkit_method_remove - Удаляет выбранный метод
    • runkit_method_rename - Переименовывает выбранный метод
    • runkit_return_value_used - Определяет, используется ли возвращаемое функцией значение
    • Runkit_Sandbox - Класс Runkit Sandbox -- это виртуальная машина PHP
    • runkit_sandbox_output_handler - Задает функцию для захвата и/или обработки данных из "песочницы".
    • Runkit_Sandbox_Parent - Класс анти-песочницы для Runkit
    • runkit_superglobals - Возвращает индексный массив зарегистрированных суперглобальных переменных.
  • s
    • SAMConnection::commit - Commits (completes) the current unit of work.
    • SAMConnection::connect - Establishes a connection to a Messaging Server
    • SAMConnection::disconnect - Disconnects from a Messaging Server
    • SAMConnection::errno - Contains the unique numeric error code of the last executed SAM operation.
    • SAMConnection::error - Contains the text description of the last failed SAM operation.
    • SAMConnection::isConnected - Queries whether a connection is established to a Messaging Server
    • SAMConnection::peek - Read a message from a queue without removing it from the queue.
    • SAMConnection::peekAll - Read one or more messages from a queue without removing it from the queue.
    • SAMConnection::receive - Receive a message from a queue or subscription.
    • SAMConnection::remove - Remove a message from a queue.
    • SAMConnection::rollback - Cancels (rolls back) an in-flight unit of work.
    • SAMConnection::send - Send a message to a queue or publish an item to a topic.
    • SAMConnection::setDebug - Turn on or off additional debugging output.
    • SAMConnection::subscribe - Create a subscription to a specified topic.
    • SAMConnection::unsubscribe - Cancel a subscription to a specified topic.
    • SAMConnection::__construct - Creates a new connection to a Messaging Server
    • SAMMessage::body - The body of the message.
    • SAMMessage::header - The header properties of the message.
    • SAMMessage::__construct - Creates a new Message object
    • SCA::createDataObject - create an SDO
    • SCA::getService - Obtain a proxy for a service
    • scandir - Получает список файлов и каталогов, расположенных по указанному пути
    • SCA_LocalProxy::createDataObject - create an SDO
    • SCA_SoapProxy::createDataObject - create an SDO
    • SDO_DAS_ChangeSummary::beginLogging - Begin change logging
    • SDO_DAS_ChangeSummary::endLogging - End change logging
    • SDO_DAS_ChangeSummary::getChangedDataObjects - Get the changed data objects from a change summary
    • SDO_DAS_ChangeSummary::getChangeType - Get the type of change made to an SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldContainer - Get the old container for a deleted SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldValues - Get the old values for a given changed SDO_DataObject
    • SDO_DAS_ChangeSummary::isLogging - Test to see whether change logging is switched on
    • SDO_DAS_DataFactory::addPropertyToType - Adds a property to a type
    • SDO_DAS_DataFactory::addType - Add a new type to a model
    • SDO_DAS_DataFactory::getDataFactory - Get a data factory instance
    • SDO_DAS_DataObject::getChangeSummary - Get a data object's change summary
    • SDO_DAS_Relational::applyChanges - Applies the changes made to a data graph back to the database.
    • SDO_DAS_Relational::createRootDataObject - Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
    • SDO_DAS_Relational::executePreparedQuery - Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
    • SDO_DAS_Relational::executeQuery - Executes a given SQL query against a relational database and returns the results as a normalised data graph.
    • SDO_DAS_Relational::__construct - Creates an instance of a Relational Data Access Service
    • SDO_DAS_Setting::getListIndex - Get the list index for a changed many-valued property
    • SDO_DAS_Setting::getPropertyIndex - Get the property index for a changed property
    • SDO_DAS_Setting::getPropertyName - Get the property name for a changed property
    • SDO_DAS_Setting::getValue - Get the old value for the changed property
    • SDO_DAS_Setting::isSet - Test whether a property was set prior to being modified
    • SDO_DAS_XML::addTypes - To load a second or subsequent schema file to a SDO_DAS_XML object
    • SDO_DAS_XML::create - To create SDO_DAS_XML object for a given schema file
    • SDO_DAS_XML::createDataObject - Creates SDO_DataObject for a given namespace URI and type name
    • SDO_DAS_XML::createDocument - Creates an XML Document object from scratch, without the need to load a document from a file or string.
    • SDO_DAS_XML::loadFile - Returns SDO_DAS_XML_Document object for a given path to xml instance document
    • SDO_DAS_XML::loadString - Returns SDO_DAS_XML_Document for a given xml instance string
    • SDO_DAS_XML::saveFile - Saves the SDO_DAS_XML_Document object to a file
    • SDO_DAS_XML::saveString - Saves the SDO_DAS_XML_Document object to a string
    • SDO_DAS_XML_Document::getRootDataObject - Returns the root SDO_DataObject
    • SDO_DAS_XML_Document::getRootElementName - Returns root element's name
    • SDO_DAS_XML_Document::getRootElementURI - Returns root element's URI string
    • SDO_DAS_XML_Document::setEncoding - Sets the given string as encoding
    • SDO_DAS_XML_Document::setXMLDeclaration - Sets the xml declaration
    • SDO_DAS_XML_Document::setXMLVersion - Sets the given string as xml version
    • SDO_DataFactory::create - Create an SDO_DataObject
    • SDO_DataObject::clear - Clear an SDO_DataObject's properties
    • SDO_DataObject::createDataObject - Create a child SDO_DataObject
    • SDO_DataObject::getContainer - Get a data object's container
    • SDO_DataObject::getSequence - Get the sequence for a data object
    • SDO_DataObject::getTypeName - Return the name of the type for a data object.
    • SDO_DataObject::getTypeNamespaceURI - Return the namespace URI of the type for a data object.
    • SDO_Exception::getCause - Get the cause of the exception.
    • SDO_List::insert - Insert into a list
    • SDO_Model_Property::getContainingType - Get the SDO_Model_Type which contains this property
    • SDO_Model_Property::getDefault - Get the default value for the property
    • SDO_Model_Property::getName - Get the name of the SDO_Model_Property
    • SDO_Model_Property::getType - Get the SDO_Model_Type of the property
    • SDO_Model_Property::isContainment - Test to see if the property defines a containment relationship
    • SDO_Model_Property::isMany - Test to see if the property is many-valued
    • SDO_Model_ReflectionDataObject::export - Get a string describing the SDO_DataObject.
    • SDO_Model_ReflectionDataObject::getContainmentProperty - Get the property which defines the containment relationship to the data object
    • SDO_Model_ReflectionDataObject::getInstanceProperties - Get the instance properties of the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getType - Get the SDO_Model_Type for the SDO_DataObject
    • SDO_Model_ReflectionDataObject::__construct - Construct an SDO_Model_ReflectionDataObject
    • SDO_Model_Type::getBaseType - Get the base type for this type
    • SDO_Model_Type::getName - Get the name of the type
    • SDO_Model_Type::getNamespaceURI - Get the namespace URI of the type
    • SDO_Model_Type::getProperties - Get the SDO_Model_Property objects defined for the type
    • SDO_Model_Type::getProperty - Get an SDO_Model_Property of the type
    • SDO_Model_Type::isAbstractType - Test to see if this SDO_Model_Type is an abstract data type
    • SDO_Model_Type::isDataType - Test to see if this SDO_Model_Type is a primitive data type
    • SDO_Model_Type::isInstance - Test for an SDO_DataObject being an instance of this SDO_Model_Type
    • SDO_Model_Type::isOpenType - Test to see if this type is an open type
    • SDO_Model_Type::isSequencedType - Test to see if this is a sequenced type
    • SDO_Sequence::getProperty - Return the property for the specified sequence index.
    • SDO_Sequence::insert - Insert into a sequence
    • SDO_Sequence::move - Move an item to another sequence position
    • SeekableIterator::seek - Осуществляет перемещение к заданной позиции
    • sem_acquire - Acquire a semaphore
    • sem_get - Get a semaphore id
    • sem_release - Release a semaphore
    • sem_remove - Remove a semaphore
    • Serializable::serialize - Представляет объект в виде строки
    • Serializable::unserialize - Создает объект
    • serialize - Генерирует пригодное для хранения представление переменной
    • SessionHandler::close - Close the session
    • SessionHandler::destroy - Destroy a session
    • SessionHandler::gc - Cleanup old sessions
    • SessionHandler::open - Initialize session
    • SessionHandler::read - Read session data
    • SessionHandler::write - Write session data
    • SessionHandlerInterface::close - Закрывает сессию
    • SessionHandlerInterface::destroy - Уничтожает сессию
    • SessionHandlerInterface::gc - Очищает старые сессии
    • SessionHandlerInterface::open - Initialize session
    • SessionHandlerInterface::read - Читает данные сессии
    • SessionHandlerInterface::write - Записать данные сессии
    • session_cache_expire - Return current cache expire
    • session_cache_limiter - Get and/or set the current cache limiter
    • session_commit - Псевдоним session_write_close
    • session_decode - Decodes session data from a session encoded string
    • session_destroy - Destroys all data registered to a session
    • session_encode - Encodes the current session data as a session encoded string
    • session_get_cookie_params - Возвращает параметры cookie сессии
    • session_id - Get and/or set the current session id
    • session_is_registered - Определяет, зарегистрирована ли глобальная переменная в сессии
    • session_module_name - Возвращает и/или устанавливает модуль текущей сессии
    • session_name - Get and/or set the current session name
    • session_pgsql_add_error - Increments error counts and sets last error message
    • session_pgsql_get_error - Returns number of errors and last error message
    • session_pgsql_get_field - Get custom field value
    • session_pgsql_reset - Reset connection to session database servers
    • session_pgsql_set_field - Set custom field value
    • session_pgsql_status - Get current save handler status
    • session_regenerate_id - Update the current session id with a newly generated one
    • session_register - Register one or more global variables with the current session
    • session_register_shutdown - Session shutdown function
    • session_save_path - Get and/or set the current session save path
    • session_set_cookie_params - Set the session cookie parameters
    • session_set_save_handler - Sets user-level session storage functions
    • session_start - Start new or resume existing session
    • session_status - Returns the current session status
    • session_unregister - Unregister a global variable from the current session
    • session_unset - Free all session variables
    • session_write_close - Write session data and end session
    • setcookie - Send a cookie
    • setlocale - Устанавливает настройки локали
    • setproctitle - Set the process title
    • setrawcookie - Посылает cookie не преобразовывая значение
    • setthreadtitle - Set the thread title
    • settype - Присваивает переменной новый тип
    • set_error_handler - Задает определенный пользователем обработчик ошибок
    • set_exception_handler - Задает пользовательский обработчик исключений
    • set_file_buffer - Псевдоним stream_set_write_buffer
    • set_include_path - Sets the include_path configuration option
    • set_magic_quotes_runtime - Sets the current active configuration setting of magic_quotes_runtime
    • set_socket_blocking - Псевдоним stream_set_blocking
    • set_time_limit - Limits the maximum execution time
    • sha1 - Возвращает SHA1-хэш строки
    • sha1_file - Возвращает SHA1-хэш файла
    • shell_exec - Выполняет команду через шелл и возвращает полный вывод в виде строки
    • shmop_close - Закрытие блока разделяемой памяти
    • shmop_delete - Удаление блока разделяемой памяти
    • shmop_open - Резервирование или использование блока разделяемой памяти
    • shmop_read - Чтение данных из участка разделяемой памяти
    • shmop_size - Возвращает размер блока в разделяемой памяти
    • shmop_write - Запись данных в разделяемую память
    • shm_attach - Creates or open a shared memory segment
    • shm_detach - Disconnects from shared memory segment
    • shm_get_var - Returns a variable from shared memory
    • shm_has_var - Check whether a specific entry exists
    • shm_put_var - Inserts or updates a variable in shared memory
    • shm_remove - Removes shared memory from Unix systems
    • shm_remove_var - Removes a variable from shared memory
    • show_source - Псевдоним highlight_file
    • shuffle - Перемешивает массив
    • signeurlpaiement - Получить платежный url (Необходимо 2 параметра)
    • similar_text - Вычисляет степень похожести двух строк
    • SimpleXMLElement::addAttribute - Добавляет атрибут к SimpleXML-элементу
    • SimpleXMLElement::addChild - Добавляет дочерний элемент к узлу XML
    • SimpleXMLElement::asXML - Возвращает сформированный XML документ в виде строки используя SimpleXML элемент
    • SimpleXMLElement::attributes - Возвращает атрибуты элемента
    • SimpleXMLElement::children - Поиск дочерних элементов данного узла
    • SimpleXMLElement::count - Считает количество дочерних элементов у текущего элемента
    • SimpleXMLElement::getDocNamespaces - Возвращает объявленное пространство имен в документе
    • SimpleXMLElement::getName - Получение имени XML элемента
    • SimpleXMLElement::getNamespaces - Получение пространств имен, используемых в документе
    • SimpleXMLElement::registerXPathNamespace - Создает префикс/пространство имен контекста для следующего XPath запроса
    • SimpleXMLElement::saveXML - Псевдоним SimpleXMLElement::asXML
    • SimpleXMLElement::xpath - Запускает XPath запрос к XML данным
    • SimpleXMLElement::__construct - Создание нового SimpleXMLElement объекта
    • SimpleXMLIterator::current - Возвращает текущий элемент
    • SimpleXMLIterator::getChildren - Возвращает вложенные элементы текущего элемента
    • SimpleXMLIterator::hasChildren - Проверяет, имеет ли текущий элемент вложенные элементы
    • SimpleXMLIterator::key - Возвращает текущий ключ
    • SimpleXMLIterator::next - Перемещает итератор к следующему элементу
    • SimpleXMLIterator::rewind - Возвращает итератор к первому элементу
    • SimpleXMLIterator::valid - Проверяет, является ли текущий элемент допустимым
    • simplexml_import_dom - Получает объект класса SimpleXMLElement из узла DOM.
    • simplexml_load_file - Интерпретирует XML-файл в объект
    • simplexml_load_string - Интерпретирует строку с XML в объект
    • sin - Синус
    • sinh - Гиперболический синус
    • sizeof - Псевдоним count
    • sleep - Откладывает выполнение
    • snmp2_get - Fetch an SNMP object
    • snmp2_getnext - Fetch the SNMP object which follows the given object id
    • snmp2_real_walk - Return all objects including their respective object ID within the specified one
    • snmp2_set - Set the value of an SNMP object
    • snmp2_walk - Fetch all the SNMP objects from an agent
    • snmp3_get - Fetch an SNMP object
    • snmp3_getnext - Fetch the SNMP object which follows the given object id
    • snmp3_real_walk - Return all objects including their respective object ID within the specified one
    • snmp3_set - Set the value of an SNMP object
    • snmp3_walk - Fetch all the SNMP objects from an agent
    • SNMP::close - Close SNMP session
    • SNMP::get - Fetch an SNMP object
    • SNMP::getErrno - Get last error code
    • SNMP::getError - Get last error message
    • SNMP::getnext - Fetch an SNMP object which follows the given object id
    • SNMP::set - Set the value of an SNMP object
    • SNMP::setSecurity - Configures security-related SNMPv3 session parameters
    • SNMP::walk - Fetch SNMP object subtree
    • SNMP::__construct - Creates SNMP instance representing session to remote SNMP agent
    • snmpget - Fetch an SNMP object
    • snmpgetnext - Fetch the SNMP object which follows the given object id
    • snmprealwalk - Return all objects including their respective object ID within the specified one
    • snmpset - Set the value of an SNMP object
    • snmpwalk - Fetch all the SNMP objects from an agent
    • snmpwalkoid - Query for a tree of information about a network entity
    • snmp_get_quick_print - Fetches the current value of the UCD library's quick_print setting
    • snmp_get_valueretrieval - Return the method how the SNMP values will be returned
    • snmp_read_mib - Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print - Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print - Return all objects including their respective object id within the specified one
    • snmp_set_oid_output_format - Set the OID output format
    • snmp_set_quick_print - Set the value of quick_print within the UCD SNMP library
    • snmp_set_valueretrieval - Specify the method how the SNMP values will be returned
    • SoapClient::SoapClient - Конструктор SoapClient
    • SoapClient::__call - Вызывает SOAP-функцию (устаревший)
    • SoapClient::__construct - Конструктор SoapClient
    • SoapClient::__doRequest - Выполняет SOAP-запрос
    • SoapClient::__getFunctions - Возвращает список доступных SOAP функций
    • SoapClient::__getLastRequest - Возвращает последний SOAP-запрос
    • SoapClient::__getLastRequestHeaders - Возвращает SOAP-заголовки последнего запроса
    • SoapClient::__getLastResponse - Возвращает последний SOAP-ответ
    • SoapClient::__getLastResponseHeaders - Возвращает SOAP-заголовки последнего ответа
    • SoapClient::__getTypes - Возвращает список SOAP-типов
    • SoapClient::__setCookie - Устанавливает cookie
    • SoapClient::__setLocation - Устанавливает адрес используемой веб-службы
    • SoapClient::__setSoapHeaders - Устанавливает SOAP-заголовки для последующих вызовов
    • SoapClient::__soapCall - Вызывает SOAP-функцию
    • SoapFault::SoapFault - SoapFault constructor
    • SoapFault::__construct - SoapFault constructor
    • SoapFault::__toString - Obtain a string representation of a SoapFault
    • SoapHeader::SoapHeader - SoapHeader constructor
    • SoapHeader::__construct - SoapHeader constructor
    • SoapParam::SoapParam - SoapParam constructor
    • SoapParam::__construct - SoapParam constructor
    • SoapServer::addFunction - Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader - Add a SOAP header to the response
    • SoapServer::fault - Issue SoapServer fault indicating an error
    • SoapServer::getFunctions - Returns list of defined functions
    • SoapServer::handle - Handles a SOAP request
    • SoapServer::setClass - Устанавливает класс, который будет обрабатывать SOAP-запросы
    • SoapServer::setObject - Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence - Sets SoapServer persistence mode
    • SoapServer::SoapServer - SoapServer constructor
    • SoapServer::__construct - SoapServer constructor
    • SoapVar::SoapVar - SoapVar constructor
    • SoapVar::__construct - SoapVar constructor
    • socket_accept - Accepts a connection on a socket
    • socket_bind - Binds a name to a socket
    • socket_clear_error - Clears the error on the socket or the last error code
    • socket_close - Closes a socket resource
    • socket_connect - Initiates a connection on a socket
    • socket_create - Create a socket (endpoint for communication)
    • socket_create_listen - Opens a socket on port to accept connections
    • socket_create_pair - Creates a pair of indistinguishable sockets and stores them in an array
    • socket_getpeername - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_get_option - Gets socket options for the socket
    • socket_get_status - Псевдоним stream_get_meta_data
    • socket_import_stream - Import a stream
    • socket_last_error - Returns the last error on the socket
    • socket_listen - Listens for a connection on a socket
    • socket_read - Reads a maximum of length bytes from a socket
    • socket_recv - Receives data from a connected socket
    • socket_recvfrom - Receives data from a socket whether or not it is connection-oriented
    • socket_select - Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send - Sends data to a connected socket
    • socket_sendto - Sends a message to a socket, whether it is connected or not
    • socket_set_block - Sets blocking mode on a socket resource
    • socket_set_blocking - Псевдоним stream_set_blocking
    • socket_set_nonblock - Sets nonblocking mode for file descriptor fd
    • socket_set_option - Sets socket options for the socket
    • socket_set_timeout - Псевдоним stream_set_timeout
    • socket_shutdown - Shuts down a socket for receiving, sending, or both
    • socket_strerror - Return a string describing a socket error
    • socket_write - Write to a socket
    • SolrClient::addDocument - Adds a document to the index
    • SolrClient::addDocuments - Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit - Finalizes all add/deletes made to the index
    • SolrClient::deleteById - Delete by Id
    • SolrClient::deleteByIds - Deletes by Ids
    • SolrClient::deleteByQueries - Removes all documents matching any of the queries
    • SolrClient::deleteByQuery - Deletes all documents matching the given query
    • SolrClient::getDebug - Returns the debug data for the last connection attempt
    • SolrClient::getOptions - Returns the client options set internally
    • SolrClient::optimize - Defragments the index
    • SolrClient::ping - Checks if Solr server is still up
    • SolrClient::query - Sends a query to the server
    • SolrClient::request - Sends a raw update request
    • SolrClient::rollback - Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter - Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet - Changes the specified servlet type to a new value
    • SolrClient::threads - Checks the threads status
    • SolrClient::__construct - Constructor for the SolrClient object
    • SolrClient::__destruct - Destructor for SolrClient
    • SolrClientException::getInternalInfo - Возвращает внутреннюю информацию о том, где было вызвано исключение
    • SolrDocument::addField - Adds a field to the document
    • SolrDocument::clear - Drops all the fields in the document
    • SolrDocument::current - Retrieves the current field
    • SolrDocument::deleteField - Removes a field from the document
    • SolrDocument::fieldExists - Checks if a field exists in the document
    • SolrDocument::getField - Retrieves a field by name
    • SolrDocument::getFieldCount - Returns the number of fields in this document
    • SolrDocument::getFieldNames - Returns an array of fields names in the document
    • SolrDocument::getInputDocument - Returns a SolrInputDocument equivalent of the object
    • SolrDocument::key - Retrieves the current key
    • SolrDocument::merge - Merges source to the current SolrDocument
    • SolrDocument::next - Moves the internal pointer to the next field
    • SolrDocument::offsetExists - Checks if a particular field exists
    • SolrDocument::offsetGet - Retrieves a field
    • SolrDocument::offsetSet - Adds a field to the document
    • SolrDocument::offsetUnset - Removes a field
    • SolrDocument::reset - This is an alias to SolrDocument::clear()
    • SolrDocument::rewind - Resets the internal pointer to the beginning
    • SolrDocument::serialize - Used for custom serialization
    • SolrDocument::sort - Sorts the fields in the document
    • SolrDocument::toArray - Returns an array representation of the document
    • SolrDocument::unserialize - Custom serialization of SolrDocument objects
    • SolrDocument::valid - Checks if the current position internally is still valid
    • SolrDocument::__clone - Creates a copy of a SolrDocument object
    • SolrDocument::__construct - Constructor
    • SolrDocument::__destruct - Destructor
    • SolrDocument::__get - Acess the field as a property
    • SolrDocument::__isset - Checks if a field exists
    • SolrDocument::__set - Adds another field to the document
    • SolrDocument::__unset - Removes a field from the document
    • SolrDocumentField::__construct - Конструктор
    • SolrDocumentField::__destruct - Деструктор
    • SolrException::getInternalInfo - Возвращает внутреннюю информацию о том, где было вызвано исключение
    • SolrGenericResponse::__construct - Конструктор
    • SolrGenericResponse::__destruct - Деструктор
    • SolrIllegalArgumentException::getInternalInfo - Возвращает внутреннюю информацию о том, где было вызвано исключение
    • SolrIllegalOperationException::getInternalInfo - Возвращает внутреннюю информацию о том, где было вызвано исключение
    • SolrInputDocument::addField - Adds a field to the document
    • SolrInputDocument::clear - Resets the input document
    • SolrInputDocument::deleteField - Removes a field from the document
    • SolrInputDocument::fieldExists - Checks if a field exists
    • SolrInputDocument::getBoost - Retrieves the current boost value for the document
    • SolrInputDocument::getField - Retrieves a field by name
    • SolrInputDocument::getFieldBoost - Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount - Returns the number of fields in the document
    • SolrInputDocument::getFieldNames - Returns an array containing all the fields in the document
    • SolrInputDocument::merge - Merges one input document into another
    • SolrInputDocument::reset - This is an alias of SolrInputDocument::clear
    • SolrInputDocument::setBoost - Sets the boost value for this document
    • SolrInputDocument::setFieldBoost - Sets the index-time boost value for a field
    • SolrInputDocument::sort - Sorts the fields within the document
    • SolrInputDocument::toArray - Returns an array representation of the input document
    • SolrInputDocument::__clone - Creates a copy of a SolrDocument
    • SolrInputDocument::__construct - Constructor
    • SolrInputDocument::__destruct - Destructor
    • SolrModifiableParams::__construct - Конструктор
    • SolrModifiableParams::__destruct - Деструктор
    • SolrObject::getPropertyNames - Returns an array of all the names of the properties
    • SolrObject::offsetExists - Checks if the property exists
    • SolrObject::offsetGet - Used to retrieve a property
    • SolrObject::offsetSet - Sets the value for a property
    • SolrObject::offsetUnset - Sets the value for the property
    • SolrObject::__construct - Creates Solr object
    • SolrObject::__destruct - Destructor
    • SolrParams::add - This is an alias for SolrParams::addParam
    • SolrParams::addParam - Adds a parameter to the object
    • SolrParams::get - This is an alias for SolrParams::getParam
    • SolrParams::getParam - Returns a parameter value
    • SolrParams::getParams - Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams - Returns an array of URL-encoded parameters
    • SolrParams::serialize - Used for custom serialization
    • SolrParams::set - An alias of SolrParams::setParam
    • SolrParams::setParam - Sets the parameter to the specified value
    • SolrParams::toString - Returns all the name-value pair parameters in the object
    • SolrParams::unserialize - Used for custom serialization
    • SolrPingResponse::getResponse - Returns the response from the server
    • SolrPingResponse::__construct - Constructor
    • SolrPingResponse::__destruct - Destructor
    • SolrQuery::addFacetDateField - Maps to facet.date
    • SolrQuery::addFacetDateOther - Adds another facet.date.other parameter
    • SolrQuery::addFacetField - Adds another field to the facet
    • SolrQuery::addFacetQuery - Adds a facet query
    • SolrQuery::addField - Specifies which fields to return in the result
    • SolrQuery::addFilterQuery - Specifies a filter query
    • SolrQuery::addHighlightField - Maps to hl.fl
    • SolrQuery::addMltField - Sets a field to use for similarity
    • SolrQuery::addMltQueryField - Maps to mlt.qf
    • SolrQuery::addSortField - Used to control how the results should be sorted
    • SolrQuery::addStatsFacet - Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField - Maps to stats.field parameter
    • SolrQuery::getFacet - Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd - Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields - Returns all the facet.date fields
    • SolrQuery::getFacetDateGap - Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd - Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther - Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart - Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields - Returns all the facet fields
    • SolrQuery::getFacetLimit - Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod - Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount - Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing - Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset - Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix - Returns the facet prefix
    • SolrQuery::getFacetQueries - Returns all the facet queries
    • SolrQuery::getFacetSort - Returns the facet sort type
    • SolrQuery::getFields - Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries - Returns an array of filter queries
    • SolrQuery::getHighlight - Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField - Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields - Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter - Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter - Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize - Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm - Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength - Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars - Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous - Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern - Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop - Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch - Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost - Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre - Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets - Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter - Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt - Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost - Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount - Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields - Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms - Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens - Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength - Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency - Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency - Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength - Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields - Returns the query fields and their boosts
    • SolrQuery::getQuery - Returns the main query
    • SolrQuery::getRows - Returns the maximum number of documents
    • SolrQuery::getSortFields - Returns all the sort fields
    • SolrQuery::getStart - Returns the offset in the complete result set
    • SolrQuery::getStats - Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets - Returns all the stats facets that were set
    • SolrQuery::getStatsFields - Returns all the statistics fields
    • SolrQuery::getTerms - Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField - Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound - Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound - Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit - Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound - Returns the term to start at
    • SolrQuery::getTermsMaxCount - Returns the maximum document frequency
    • SolrQuery::getTermsMinCount - Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix - Returns the term prefix
    • SolrQuery::getTermsReturnRaw - Whether or not to return raw characters
    • SolrQuery::getTermsSort - Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound - Returns the term to stop at
    • SolrQuery::getTimeAllowed - Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeFacetDateField - Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther - Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField - Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery - Removes one of the facet.query parameters
    • SolrQuery::removeField - Removes a field from the list of fields
    • SolrQuery::removeFilterQuery - Removes a filter query
    • SolrQuery::removeHighlightField - Removes one of the fields used for highlighting
    • SolrQuery::removeMltField - Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField - Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField - Removes one of the sort fields
    • SolrQuery::removeStatsFacet - Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField - Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler - Toggles the echoHandler parameter
    • SolrQuery::setEchoParams - Determines what kind of parameters to include in the response
    • SolrQuery::setExplainOther - Sets the explainOther common query parameter
    • SolrQuery::setFacet - Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd - Maps to facet.date.end
    • SolrQuery::setFacetDateGap - Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart - Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit - Maps to facet.limit
    • SolrQuery::setFacetMethod - Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount - Maps to facet.mincount
    • SolrQuery::setFacetMissing - Maps to facet.missing
    • SolrQuery::setFacetOffset - Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix - Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort - Determines the ordering of the facet field constraints
    • SolrQuery::setHighlight - Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField - Specifies the backup field to use
    • SolrQuery::setHighlightFormatter - Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter - Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize - The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm - Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength - Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars - Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous - Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern - Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop - Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch - Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost - Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre - Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets - Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter - Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt - Enables or disables moreLikeThis
    • SolrQuery::setMltBoost - Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount - Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms - Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens - Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength - Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency - Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency - Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength - Sets the minimum word length
    • SolrQuery::setOmitHeader - Exclude the header from the returned results
    • SolrQuery::setQuery - Sets the search query
    • SolrQuery::setRows - Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo - Flag to show debug information
    • SolrQuery::setStart - Specifies the number of rows to skip
    • SolrQuery::setStats - Enables or disables the Stats component
    • SolrQuery::setTerms - Enables or disables the TermsComponent
    • SolrQuery::setTermsField - Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound - Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound - Include the upper bound term in the result set
    • SolrQuery::setTermsLimit - Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound - Specifies the Term to start from
    • SolrQuery::setTermsMaxCount - Sets the maximum document frequency
    • SolrQuery::setTermsMinCount - Sets the minimum document frequency
    • SolrQuery::setTermsPrefix - Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw - Return the raw characters of the indexed term
    • SolrQuery::setTermsSort - Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound - Sets the term to stop at
    • SolrQuery::setTimeAllowed - The time allowed for search to finish
    • SolrQuery::__construct - Constructor
    • SolrQuery::__destruct - Destructor
    • SolrQueryResponse::__construct - Конструктор
    • SolrQueryResponse::__destruct - Деструктор
    • SolrResponse::getDigestedResponse - Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus - Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage - Returns more details on the HTTP status
    • SolrResponse::getRawRequest - Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders - Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse - Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders - Returns the raw response headers from the server
    • SolrResponse::getRequestUrl - Returns the full URL the request was sent to
    • SolrResponse::getResponse - Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode - Sets the parse mode
    • SolrResponse::success - Was the request a success
    • SolrUpdateResponse::__construct - Конструктор
    • SolrUpdateResponse::__destruct - Деструктор
    • SolrUtils::digestXmlResponse - Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars - Escapes a lucene query string
    • SolrUtils::getSolrVersion - Returns the current version of the Solr extension
    • SolrUtils::queryPhrase - Prepares a phrase from an unescaped lucene string
    • solr_get_version - Возвращает текущую версию расширения Apache Solr
    • sort - Сортирует массив
    • soundex - Возвращает ключ soundex для строки
    • SphinxClient::addQuery - Добавление запроса к очереди запросов
    • SphinxClient::buildExcerpts - Построение текстовых фрагментов
    • SphinxClient::buildKeywords - Извлечение ключевых слов из запроса
    • SphinxClient::close - Закрытие ранее открытого постоянного соединения
    • SphinxClient::escapeString - Экранирование спецсимволов
    • SphinxClient::getLastError - Получение последнего сообщения об ошибке
    • SphinxClient::getLastWarning - Получение последнего предупреждения
    • SphinxClient::open - Создание постоянного подключения к серверу
    • SphinxClient::query - Выполнение поискового запроса
    • SphinxClient::resetFilters - Обнуление всех фильтров
    • SphinxClient::resetGroupBy - Сброс всех настроек группировок
    • SphinxClient::runQueries - Выполнение набора поисковых запросов
    • SphinxClient::setArrayResult - Изменение формата массива с набором результатов запроса
    • SphinxClient::setConnectTimeout - Установка таймаута соединения
    • SphinxClient::setFieldWeights - Установка весовых коэффициентов полей
    • SphinxClient::setFilter - Добавление фильтра по типу поля integer
    • SphinxClient::setFilterFloatRange - Добавление фильтра по диапазону значений (для поля типа float)
    • SphinxClient::setFilterRange - Добавление фильтра по диапазону значений (для поля типа integer)
    • SphinxClient::setGeoAnchor - Установка опорной точки для рассчета географической удаленности
    • SphinxClient::setGroupBy - Установка аттрибута группировки
    • SphinxClient::setGroupDistinct - Установка названия аттрибута для расчета количества уникальных значений при группировке
    • SphinxClient::setIDRange - Установка диапазона значений допустимых ID документов
    • SphinxClient::setIndexWeights - Установка весовых коэффициентов индексов
    • SphinxClient::setLimits - Установка смещения и предельного числа значений для набора результатов
    • SphinxClient::setMatchMode - Установка режима совпадения при полнотекстовом поиске
    • SphinxClient::setMaxQueryTime - Установка максимального времени выполнения запроса
    • SphinxClient::setOverride - Временное переопределение значений атрибута для документов
    • SphinxClient::setRankingMode - Установка режима ранжирования
    • SphinxClient::setRetries - Установка количества повторных попыток и задержки между ними
    • SphinxClient::setSelect - Установка условия выборки
    • SphinxClient::setServer - Установка хоста и порта searchd
    • SphinxClient::setSortMode - Установка режима сортировки результатов
    • SphinxClient::status - Запрос статуса searchd
    • SphinxClient::updateAttributes - Обновление аттрибутов документа
    • SphinxClient::__construct - Создание нового объекта SphinxClient
    • SplDoublyLinkedList::bottom - Получает узел, находящийся в начале двусвязного списка
    • SplDoublyLinkedList::count - Подсчитывает количество элементов в двусвязном списке
    • SplDoublyLinkedList::current - Возвращает текущий элемент массива
    • SplDoublyLinkedList::getIteratorMode - Возвращает режим итерации
    • SplDoublyLinkedList::isEmpty - Проверяет, является ли двусвязный список пустым
    • SplDoublyLinkedList::key - Возвращает индекс текущего узла
    • SplDoublyLinkedList::next - Перемещает итератор к следующему элементу
    • SplDoublyLinkedList::offsetExists - Проверяет, существует ли запрашиваемый индекс
    • SplDoublyLinkedList::offsetGet - Возвращает значение по указанному индексу
    • SplDoublyLinkedList::offsetSet - Устанавливает значение по заданному индексу $index в $newval
    • SplDoublyLinkedList::offsetUnset - Удаляет значение по указанному индексу $index
    • SplDoublyLinkedList::pop - Удаляет (выталкивает) узел, находящийся в конце двусвязного списка
    • SplDoublyLinkedList::prev - Перемещает итератор к предыдущему элементу
    • SplDoublyLinkedList::push - Помещает элемент в конец двусвязного списка
    • SplDoublyLinkedList::rewind - Возвращает итератор в начало
    • SplDoublyLinkedList::serialize - Сериализует хранилище
    • SplDoublyLinkedList::setIteratorMode - Устанавливает режим итерации
    • SplDoublyLinkedList::shift - Удаляет узел, находящийся в начале двусвязного списка
    • SplDoublyLinkedList::top - Получает узел, находящийся в конце двусвязного списка
    • SplDoublyLinkedList::unserialize - Десериализует хранилище
    • SplDoublyLinkedList::unshift - Вставляет элемент в начало двусвязного списка
    • SplDoublyLinkedList::valid - Проверяет, содержит ли узлы двусвязный список
    • SplDoublyLinkedList::__construct - Создает новый двусвязный список
    • SplEnum::getConstList - Returns all consts (possible values) as an array.
    • SplFileInfo::getATime - Получает время последнего обращения к файлу
    • SplFileInfo::getBasename - Получает базовое имя файла
    • SplFileInfo::getCTime - Gets the inode change time
    • SplFileInfo::getExtension - Получает расширение файла
    • SplFileInfo::getFileInfo - Получает объект SplFileInfo для файла
    • SplFileInfo::getFilename - Получает имя файла
    • SplFileInfo::getGroup - Получает группу файла
    • SplFileInfo::getInode - Gets the inode for the file
    • SplFileInfo::getLinkTarget - Gets the target of a link
    • SplFileInfo::getMTime - Получает время последнего изменения
    • SplFileInfo::getOwner - Gets the owner of the file
    • SplFileInfo::getPath - Gets the path without filename
    • SplFileInfo::getPathInfo - Gets an SplFileInfo object for the path
    • SplFileInfo::getPathname - Gets the path to the file
    • SplFileInfo::getPerms - Gets file permissions
    • SplFileInfo::getRealPath - Gets absolute path to file
    • SplFileInfo::getSize - Получает размер файла
    • SplFileInfo::getType - Получает тип файла
    • SplFileInfo::isDir - Сообщает, является ли файл каталогом
    • SplFileInfo::isExecutable - Сообщает, является ли файл исполняемым
    • SplFileInfo::isFile - Сообщает, ссылается ли объект на обычный файл
    • SplFileInfo::isLink - Сообщает, является ли файл ссылкой
    • SplFileInfo::isReadable - Сообщает, является ли файл доступным для чтения
    • SplFileInfo::isWritable - Сообщает, является ли элемент доступным для записи
    • SplFileInfo::openFile - Получает объект SplFileObject для файла
    • SplFileInfo::setFileClass - Sets the class name used with SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Sets the class used with getFileInfo and getPathInfo
    • SplFileInfo::__construct - Создает новый объект SplFileInfo
    • SplFileInfo::__toString - Возвращает путь к файлу в виде строки
    • SplFileObject::current - Retrieve current line of file
    • SplFileObject::eof - Проверяет, достигнут ли конец файла
    • SplFileObject::fflush - Сбрасывает буфер вывода в файл
    • SplFileObject::fgetc - Читает символ из файла
    • SplFileObject::fgetcsv - Gets line from file and parse as CSV fields
    • SplFileObject::fgets - Читает строку из файла
    • SplFileObject::fgetss - Gets line from file and strip HTML tags
    • SplFileObject::flock - Портируемая блокировка файла
    • SplFileObject::fpassthru - Output all remaining data on a file pointer
    • SplFileObject::fputcsv - Выводит поля массива в виде строки CSV
    • SplFileObject::fscanf - Parses input from file according to a format
    • SplFileObject::fseek - Seek to a position
    • SplFileObject::fstat - Получает информацию о файле
    • SplFileObject::ftell - Return current file position
    • SplFileObject::ftruncate - Truncates the file to a given length
    • SplFileObject::fwrite - Запись в файл
    • SplFileObject::getChildren - No purpose
    • SplFileObject::getCsvControl - Получает символы разделителя и ограничителя для CSV
    • SplFileObject::getCurrentLine - Alias of SplFileObject::fgets
    • SplFileObject::getFlags - Gets flags for the SplFileObject
    • SplFileObject::getMaxLineLen - Получает максимальную длину строки
    • SplFileObject::hasChildren - SplFileObject does not have children
    • SplFileObject::key - Get line number
    • SplFileObject::next - Читает следующую строку
    • SplFileObject::rewind - Rewind the file to the first line
    • SplFileObject::seek - Seek to specified line
    • SplFileObject::setCsvControl - Устанавливает символы разделителя и ограничителя для CSV
    • SplFileObject::setFlags - Установливает флаги для SplFileObject
    • SplFileObject::setMaxLineLen - Устанавливает максимальную длину строки
    • SplFileObject::valid - Проверяет, достигнут ли конец файла (EOF)
    • SplFileObject::__construct - Construct a new file object.
    • SplFileObject::__toString - Псевдоним SplFileObject::current
    • SplFixedArray::count - Возвращает размер массива
    • SplFixedArray::current - Возвращает текущий элемент массива
    • SplFixedArray::fromArray - Импортирует PHP-массив в объект класса SplFixedArray
    • SplFixedArray::getSize - Получает размер массива
    • SplFixedArray::key - Возвращает индекс текущего элемента массива
    • SplFixedArray::next - Переходит к следующему элементу массива
    • SplFixedArray::offsetExists - Возвращает факт наличия указанного индекса массива
    • SplFixedArray::offsetGet - Возвращает значение по указанному индексу
    • SplFixedArray::offsetSet - Устанавливает новое значение по заданному индексу
    • SplFixedArray::offsetUnset - Удаляет значение по индексу $index
    • SplFixedArray::rewind - Выставляет итератор массива в начало
    • SplFixedArray::setSize - Изменяет размер массива
    • SplFixedArray::toArray - Возвращает обычный PHP-массив со значениями фиксированного массива
    • SplFixedArray::valid - Проверяет массив на наличие элементов
    • SplFixedArray::__construct - Создает новый массив фиксированной длины
    • SplHeap::compare - Compare elements in order to place them correctly in the heap while sifting up.
    • SplHeap::count - Counts the number of elements in the heap.
    • SplHeap::current - Return current node pointed by the iterator
    • SplHeap::extract - Extracts a node from top of the heap and sift up.
    • SplHeap::insert - Inserts an element in the heap by sifting it up.
    • SplHeap::isEmpty - Checks whether the heap is empty.
    • SplHeap::key - Return current node index
    • SplHeap::next - Move to the next node
    • SplHeap::recoverFromCorruption - Recover from the corrupted state and allow further actions on the heap.
    • SplHeap::rewind - Rewind iterator back to the start (no-op)
    • SplHeap::top - Peeks at the node from the top of the heap
    • SplHeap::valid - Check whether the heap contains more nodes
    • SplHeap::__construct - Constructs a new empty heap
    • split - Разбиение строки на массив по регулярному выражению
    • spliti - Разбивает строку в массив с помощью регулярного выражения без учета регистра
    • SplMaxHeap::compare - Compare elements in order to place them correctly in the heap while sifting up.
    • SplMinHeap::compare - Compare elements in order to place them correctly in the heap while sifting up.
    • SplObjectStorage::addAll - Adds all objects from another storage
    • SplObjectStorage::attach - Adds an object in the storage
    • SplObjectStorage::contains - Checks if the storage contains a specific object
    • SplObjectStorage::count - Returns the number of objects in the storage
    • SplObjectStorage::current - Returns the current storage entry
    • SplObjectStorage::detach - Removes an object from the storage
    • SplObjectStorage::getHash - Calculate a unique identifier for the contained objects
    • SplObjectStorage::getInfo - Returns the data associated with the current iterator entry
    • SplObjectStorage::key - Returns the index at which the iterator currently is
    • SplObjectStorage::next - Move to the next entry
    • SplObjectStorage::offsetExists - Checks whether an object exists in the storage
    • SplObjectStorage::offsetGet - Returns the data associated with an object
    • SplObjectStorage::offsetSet - Associates data to an object in the storage
    • SplObjectStorage::offsetUnset - Removes an object from the storage
    • SplObjectStorage::removeAll - Removes objects contained in another storage from the current storage
    • SplObjectStorage::removeAllExcept - Removes all objects except for those contained in another storage from the current storage
    • SplObjectStorage::rewind - Rewind the iterator to the first storage element
    • SplObjectStorage::serialize - Serializes the storage
    • SplObjectStorage::setInfo - Sets the data associated with the current iterator entry
    • SplObjectStorage::unserialize - Unserializes a storage from its string representation
    • SplObjectStorage::valid - Returns if the current iterator entry is valid
    • SplObserver::update - Получает уведомление от субъекта
    • SplPriorityQueue::compare - Compare priorities in order to place elements correctly in the heap while sifting up.
    • SplPriorityQueue::count - Counts the number of elements in the queue.
    • SplPriorityQueue::current - Return current node pointed by the iterator
    • SplPriorityQueue::extract - Extracts a node from top of the heap and sift up.
    • SplPriorityQueue::insert - Inserts an element in the queue by sifting it up.
    • SplPriorityQueue::isEmpty - Проверяет, является ли очередь пустой
    • SplPriorityQueue::key - Return current node index
    • SplPriorityQueue::next - Move to the next node
    • SplPriorityQueue::recoverFromCorruption - Recover from the corrupted state and allow further actions on the queue.
    • SplPriorityQueue::rewind - Rewind iterator back to the start (no-op)
    • SplPriorityQueue::setExtractFlags - Sets the mode of extraction
    • SplPriorityQueue::top - Peeks at the node from the top of the queue
    • SplPriorityQueue::valid - Check whether the queue contains more nodes
    • SplPriorityQueue::__construct - Создает новую пустую очередь
    • SplQueue::dequeue - Удаляет элемент из очереди
    • SplQueue::enqueue - Добавляет элемент в очередь
    • SplQueue::setIteratorMode - Устанавливает режим итератора
    • SplQueue::__construct - Создает новую очередь, реализованную с использованием двусвязного списка
    • SplStack::setIteratorMode - Устанавливает режим итератора
    • SplStack::__construct - Создатет новый стек, реализованный с использованием двусвязного списка
    • SplSubject::attach - Присоединяет наблюдателя (объект класса SplObserver)
    • SplSubject::detach - Отсоединяет наблюдателя
    • SplSubject::notify - Посылает уведомление наблюдателю
    • SplTempFileObject::__construct - Создает новый объект, представляющий временный файл
    • SplType::__construct - Creates a new value of some type
    • spl_autoload - Default implementation for __autoload()
    • spl_autoload_call - Try all registered __autoload() function to load the requested class
    • spl_autoload_extensions - Register and return default file extensions for spl_autoload
    • spl_autoload_functions - Return all registered __autoload() functions
    • spl_autoload_register - Register given function as __autoload() implementation
    • spl_autoload_unregister - Unregister given function as __autoload() implementation
    • spl_classes - Возвращает доступные классы SPL
    • spl_object_hash - Return hash id for given object
    • Spoofchecker::areConfusable - Checks if a given text contains any confusable characters
    • Spoofchecker::isSuspicious - Checks if a given text contains any suspicious characters
    • Spoofchecker::setAllowedLocales - Locales to use when running checks
    • Spoofchecker::setChecks - Set the checks to run
    • Spoofchecker::__construct - Constructor
    • sprintf - Возвращает отформатированную строку
    • SQL acceptable by 4D - PDO and SQL 4D
    • SQLite3::busyTimeout - Sets the busy connection handler
    • SQLite3::changes - Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close - Closes the database connection
    • SQLite3::createAggregate - Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createFunction - Registers a PHP function for use as an SQL scalar function
    • SQLite3::escapeString - Returns a string that has been properly escaped
    • SQLite3::exec - Executes a result-less query against a given database
    • SQLite3::lastErrorCode - Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg - Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID - Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension - Attempts to load an SQLite extension library
    • SQLite3::open - Opens an SQLite database
    • SQLite3::prepare - Подготавливает SQL-запрос для выполнения
    • SQLite3::query - Выполняет SQL-запрос
    • SQLite3::querySingle - Executes a query and returns a single result
    • SQLite3::version - Returns the SQLite3 library version as a string constant and as a number
    • SQLite3::__construct - Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3Result::columnName - Returns the name of the nth column
    • SQLite3Result::columnType - Returns the type of the nth column
    • SQLite3Result::fetchArray - Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize - Closes the result set
    • SQLite3Result::numColumns - Returns the number of columns in the result set
    • SQLite3Result::reset - Resets the result set back to the first row
    • SQLite3Stmt::bindParam - Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue - Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear - Clears all current bound parameters
    • SQLite3Stmt::close - Closes the prepared statement
    • SQLite3Stmt::execute - Executes a prepared statement and returns a result set object
    • SQLite3Stmt::paramCount - Returns the number of parameters within the prepared statement
    • SQLite3Stmt::reset - Resets the prepared statement
    • sqlite_array_query - Выполняет запрос к базе данных и возвращает результат в виде массива
    • sqlite_busy_timeout - Устанавливает или полностью отключает время ожидания
    • sqlite_changes - Возвращает количество записей, которые были изменены последним SQL-запросом
    • sqlite_close - Закрывает открытую базу данных SQLite
    • sqlite_column - Выбирает столбец из текущей записи результата запроса
    • sqlite_create_aggregate - Регистрирует агрегирующую функцию для использования в SQL-запросах
    • sqlite_create_function - Регистрирует "стандартную" функцию (UDF) для использования в SQL-запросах
    • sqlite_current - Возвращает текущую запись из результирующего набора в виде массива
    • sqlite_error_string - Возвращает строку с описанием ошибки
    • sqlite_escape_string - Экранирует спецсимволы в строке для использования в запросе
    • sqlite_exec - Выполняет запрос, не возвращающий записей
    • sqlite_factory - Открывает базу данных SQLite и возвращает объект
    • sqlite_fetch_all - Выбирает все записи из результата запроса и возвращает многомерный массив
    • sqlite_fetch_array - Выбирает следующую запись из результата запроса и возвращает массив
    • sqlite_fetch_column_types - Возвращает массив, содержащий информацию о типах полей в таблице
    • sqlite_fetch_object - Выбирает следующую запись из результата запроса и возвращает объект
    • sqlite_fetch_single - Выбирает значение первого поля из результата запроса и возвращает в виде строки
    • sqlite_fetch_string - Псевдоним sqlite_fetch_single
    • sqlite_field_name - Возвращает имя указанного поля
    • sqlite_has_more - Определяет, есть ли еще записи в результате запроса
    • sqlite_has_prev - Определяет, доступна ли предыдущая запись
    • sqlite_key - Возвращает текущую позицию указателя
    • sqlite_last_error - Возвращает код ошибки последней операции с SQLite
    • sqlite_last_insert_rowid - Возвращает идентификатор последней вставленной записи
    • sqlite_libencoding - Возвращает кодировку, используемую подключенной библиотекой SQLite
    • sqlite_libversion - Возвращает версию подключенной библиотеки SQLite
    • sqlite_next - Переходит на следующую запись
    • sqlite_num_fields - Возвращает количество полей в результате запроса
    • sqlite_num_rows - Возвращает количество записей в результате запроса
    • sqlite_open - Открывает базу данных SQLite или создает ее, если она не существует
    • sqlite_popen - Открывает постоянное подключение к базе данных SQLite или создает ее, если она не существует
    • sqlite_prev - Переходит на предыдущую запись
    • sqlite_query - Выполняет запрос к базе данных и возвращает идентификатор результата
    • sqlite_rewind - Переходит к первой записи
    • sqlite_seek - Переходит к определенному номеру записи в буферизованном результирующем наборе
    • sqlite_single_query - Выполняет запрос и возвращает массив со значениями одного поля или первую запись
    • sqlite_udf_decode_binary - Декодирует бинарные данные, переданные в качестве параметров в UDF
    • sqlite_udf_encode_binary - Кодирует бинарные данные перед тем как вернуть их из UDF
    • sqlite_unbuffered_query - Выполняет запрос без буферизации результатов
    • sqlite_valid - Проверяет, есть ли еще доступные ряды
    • sqlsrv_begin_transaction - Begins a database transaction
    • sqlsrv_cancel - Cancels a statement
    • sqlsrv_client_info - Returns information about the client and specified connection
    • sqlsrv_close - Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit - Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure - Changes the driver error handling and logging configurations
    • sqlsrv_connect - Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors - Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute - Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch - Makes the next row in a result set available for reading
    • sqlsrv_fetch_array - Returns a row as an array
    • sqlsrv_fetch_object - Retrieves the next row of data in a result set as an object
    • sqlsrv_field_metadata - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt - Frees all resources for the specified statement
    • sqlsrv_get_config - Returns the value of the specified configuration setting
    • sqlsrv_get_field - Gets field data from the currently selected row
    • sqlsrv_has_rows - Indicates whether the specified statement has rows
    • sqlsrv_next_result - Makes the next result of the specified statement active
    • sqlsrv_num_fields - Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows - Retrieves the number of rows in a result set
    • sqlsrv_prepare - Prepares a query for execution
    • sqlsrv_query - Prepares and executes a query.
    • sqlsrv_rollback - Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data - Sends data from parameter streams to the server
    • sqlsrv_server_info - Returns information about the server
    • SQL types with PDO_4D and PHP - SQL types with PDO_4D and PHP
    • sql_regcase - Создает регулярное выражение для регистронезависимого сравнения
    • sqrt - Квадратный корень
    • srand - Изменяет начальное число генератора псевдослучайных чисел
    • sscanf - Разбирает строку в соответствии с заданным форматом
    • ssdeep_fuzzy_compare - Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash - Create a fuzzy hash from a string
    • ssdeep_fuzzy_hash_filename - Create a fuzzy hash from a file
    • ssh2:// - Secure Shell 2
    • ssh2_auth_hostbased_file - Authenticate using a public hostkey
    • ssh2_auth_none - Authenticate as "none"
    • ssh2_auth_password - Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file - Authenticate using a public key
    • ssh2_connect - Connect to an SSH server
    • ssh2_exec - Execute a command on a remote server
    • ssh2_fetch_stream - Fetch an extended data stream
    • ssh2_fingerprint - Retrieve fingerprint of remote server
    • ssh2_methods_negotiated - Return list of negotiated methods
    • ssh2_publickey_add - Add an authorized publickey
    • ssh2_publickey_init - Initialize Publickey subsystem
    • ssh2_publickey_list - List currently authorized publickeys
    • ssh2_publickey_remove - Remove an authorized publickey
    • ssh2_scp_recv - Request a file via SCP
    • ssh2_scp_send - Send a file via SCP
    • ssh2_sftp - Initialize SFTP subsystem
    • ssh2_sftp_lstat - Stat a symbolic link
    • ssh2_sftp_mkdir - Create a directory
    • ssh2_sftp_readlink - Return the target of a symbolic link
    • ssh2_sftp_realpath - Resolve the realpath of a provided path string
    • ssh2_sftp_rename - Rename a remote file
    • ssh2_sftp_rmdir - Remove a directory
    • ssh2_sftp_stat - Stat a file on a remote filesystem
    • ssh2_sftp_symlink - Create a symlink
    • ssh2_sftp_unlink - Delete a file
    • ssh2_shell - Request an interactive shell
    • ssh2_tunnel - Open a tunnel through a remote server
    • stat - Возвращает информацию о файле
    • stats_absolute_deviation - Возвращает абсолютное отклонение массива значений
    • stats_cdf_beta - CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.
    • stats_cdf_binomial - Calculates any one parameter of the binomial distribution given values for the others.
    • stats_cdf_cauchy - Не документирована
    • stats_cdf_chisquare - Calculates any one parameter of the chi-square distribution given values for the others.
    • stats_cdf_exponential - Не документирована
    • stats_cdf_f - Calculates any one parameter of the F distribution given values for the others.
    • stats_cdf_gamma - Calculates any one parameter of the gamma distribution given values for the others.
    • stats_cdf_laplace - Не документирована
    • stats_cdf_logistic - Не документирована
    • stats_cdf_negative_binomial - Calculates any one parameter of the negative binomial distribution given values for the others.
    • stats_cdf_noncentral_chisquare - Calculates any one parameter of the non-central chi-square distribution given values for the others.
    • stats_cdf_noncentral_f - Calculates any one parameter of the Non-central F distribution given values for the others.
    • stats_cdf_poisson - Calculates any one parameter of the Poisson distribution given values for the others.
    • stats_cdf_t - Calculates any one parameter of the T distribution given values for the others.
    • stats_cdf_uniform - Не документирована
    • stats_cdf_weibull - Не документирована
    • stats_covariance - Вычисляет ковариацию двух наборов данных
    • stats_dens_beta - Не документирована
    • stats_dens_cauchy - Не документирована
    • stats_dens_chisquare - Не документирована
    • stats_dens_exponential - Не документирована
    • stats_dens_f - Описание
    • stats_dens_gamma - Не документирована
    • stats_dens_laplace - Не документирована
    • stats_dens_logistic - Не документирована
    • stats_dens_negative_binomial - Не документирована
    • stats_dens_normal - Не документирована
    • stats_dens_pmf_binomial - Не документирована
    • stats_dens_pmf_hypergeometric - Описание
    • stats_dens_pmf_poisson - Не документирована
    • stats_dens_t - Не документирована
    • stats_dens_weibull - Не документирована
    • stats_den_uniform - Не документирована
    • stats_harmonic_mean - Возвращает среднее гармоническое массива значений
    • stats_kurtosis - Вычисляет эксцесс данных в массиве
    • stats_rand_gen_beta - Generates beta random deviate
    • stats_rand_gen_chisquare - Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.
    • stats_rand_gen_exponential - Generates a single random deviate from an exponential distribution with mean "av"
    • stats_rand_gen_f - Generates a random deviate
    • stats_rand_gen_funiform - Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma - Generates random deviates from a gamma distribution
    • stats_rand_gen_ibinomial - Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE
    • stats_rand_gen_ibinomial_negative - Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).
    • stats_rand_gen_int - Генерирует случайное число в диапазоне от 1 до 2147483562
    • stats_rand_gen_ipoisson - Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).
    • stats_rand_gen_iuniform - Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncenral_chisquare - Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0
    • stats_rand_gen_noncentral_f - Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.
    • stats_rand_gen_noncentral_t - Generates a single random deviate from a noncentral T distribution
    • stats_rand_gen_normal - Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.
    • stats_rand_gen_t - Generates a single random deviate from a T distribution
    • stats_rand_get_seeds - Не документирована
    • stats_rand_phrase_to_seeds - generate two seeds for the RGN random number generator
    • stats_rand_ranf - Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
    • stats_rand_setall - Не документирована
    • stats_skew - Вычисляет асимметрию данных в массиве
    • stats_standard_deviation - Возвращает стандартное отклонение
    • stats_stat_binomial_coef - Не документирована
    • stats_stat_correlation - Не документирована
    • stats_stat_gennch - Не документирована
    • stats_stat_independent_t - Не документирована
    • stats_stat_innerproduct - Описание
    • stats_stat_noncentral_t - Calculates any one parameter of the noncentral t distribution give values for the others.
    • stats_stat_paired_t - Не документирована
    • stats_stat_percentile - Не документирована
    • stats_stat_powersum - Не документирована
    • stats_variance - Возвращает дисперсию генеральной совокупности
    • Stomp::abort - Отменяет выполнение текущей транзакции
    • Stomp::ack - Подтверждает получение сообщения
    • Stomp::begin - Создает транзакцию
    • Stomp::commit - Выполняет текущую транзакцию
    • Stomp::error - Возвращает последнюю ошибку Stomp
    • Stomp::getReadTimeout - Возвращает время максимального ожидания операции чтения
    • Stomp::getSessionId - Возвращает идентификатор текущей сессии Stomp
    • Stomp::hasFrame - Проверяет, возможно ли чтение фрейма
    • Stomp::readFrame - Выполняет операцию чтения следующего фрейма
    • Stomp::send - Отправляет сообщение
    • Stomp::setReadTimeout - Устанавливает предельное время ожидания операции чтения
    • Stomp::subscribe - Регистрирует подписку на указанную рассылку
    • Stomp::unsubscribe - Удаляет существующую подписку
    • Stomp::__construct - Открывает соединение
    • Stomp::__destruct - Закрывает Stomp-соединение
    • StompException::getDetails - Возвращает сведения об исключении
    • StompFrame::__construct - Конструктор
    • stomp_connect_error - Возвращает строку с описанием последней ошибки подключения
    • stomp_version - Возвращает текущую версию расширения Stomp
    • strcasecmp - Бинарно-безопасное сравнение строк без учета регистра
    • strchr - Псевдоним strstr
    • strcmp - Бинарно-безопасное сравнение строк
    • strcoll - Сравнение строк с учетом текущей локали
    • strcspn - Возвращает длину участка в начале строки, не соответствующего маске
    • streamWrapper::dir_closedir - Close directory handle
    • streamWrapper::dir_opendir - Open directory handle
    • streamWrapper::dir_readdir - Read entry from directory handle
    • streamWrapper::dir_rewinddir - Rewind directory handle
    • streamWrapper::mkdir - Create a directory
    • streamWrapper::rename - Renames a file or directory
    • streamWrapper::rmdir - Removes a directory
    • streamWrapper::stream_cast - Retrieve the underlaying resource
    • streamWrapper::stream_close - Close an resource
    • streamWrapper::stream_eof - Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush - Flushes the output
    • streamWrapper::stream_lock - Advisory file locking
    • streamWrapper::stream_metadata - Change stream options
    • streamWrapper::stream_open - Opens file or URL
    • streamWrapper::stream_read - Read from stream
    • streamWrapper::stream_seek - Seeks to specific location in a stream
    • streamWrapper::stream_set_option - Change stream options
    • streamWrapper::stream_stat - Retrieve information about a file resource
    • streamWrapper::stream_tell - Retrieve the current position of a stream
    • streamWrapper::stream_truncate - Truncate stream
    • streamWrapper::stream_write - Write to stream
    • streamWrapper::unlink - Delete a file
    • streamWrapper::url_stat - Retrieve information about a file
    • streamWrapper::__construct - Constructs a new stream wrapper
    • streamWrapper::__destruct - Destructs an existing stream wrapper
    • stream_bucket_append - Append bucket to brigade
    • stream_bucket_make_writeable - Return a bucket object from the brigade for operating on
    • stream_bucket_new - Create a new bucket for use on the current stream
    • stream_bucket_prepend - Prepend bucket to brigade
    • stream_context_create - Создаёт контекст потока
    • stream_context_get_default - Получает контекст потока по умолчанию
    • stream_context_get_options - Получает настройки для потока/обёртки/контекста
    • stream_context_get_params - Извлекает параметры из контекста
    • stream_context_set_default - Устанавливает контекст потоков по умолчанию
    • stream_context_set_option - Устанавливает опцию для потока/обёртки/контекста
    • stream_context_set_params - Устанавливает параметры для потока/обертки/контекста
    • stream_copy_to_stream - Копирует данные из одного потока в другой
    • stream_encoding - Устанавливает кодировку для потока
    • stream_filter_append - Прикрепляет фильтр к потоку
    • stream_filter_prepend - Прикрепляет фильтр к потоку
    • stream_filter_register - Регистрирует потоковый фильтр, определённый пользователем
    • stream_filter_remove - Удаляет фильтр из потока
    • stream_get_contents - Читает оставшуюся часть потока в строку
    • stream_get_filters - Извлекает список зарегистрированных фильтров
    • stream_get_line - Получает строку из потокового ресурса до указанного разделителя
    • stream_get_meta_data - Извлекает заголовок/метаданные из потоков/файловых указателей
    • stream_get_transports - Возвращает список зарегистрированных транспортов сокета
    • stream_get_wrappers - Извлекает список зарегистрированных потоков
    • stream_is_local - Проверяет, является ли поток локальным потоком
    • stream_notification_callback - Callback-функция для параметра контекста notification
    • stream_register_wrapper - Псевдоним stream_wrapper_register
    • stream_resolve_include_path - Составляет полное имя файла, используя пути включения
    • stream_select - Запускает эквивалент системного вызова select() на заданных массивах потоков с таймаутом, указанным параметрами tv_sec и tv_usec
    • stream_set_blocking - Устанавливает блокирующий/неблокирующий режим на потоке
    • stream_set_chunk_size - Set the stream chunk size
    • stream_set_read_buffer - Устанавливает буферизацию чтения файла на указанном потоке
    • stream_set_timeout - Устанавливает значение тайм-аута на потоке
    • stream_set_write_buffer - Устанавливает буферизацию файла при записи в указанный поток
    • stream_socket_accept - Принимает соединение на сокете, созданном c помощью функции stream_socket_server
    • stream_socket_client - Открывает соединение с интернет-сокетом или с доменным сокетом Unix
    • stream_socket_enable_crypto - Включает или отключает шифрование на уже подсоединённом сокете
    • stream_socket_get_name - Извлекает название локального или удалённого сокета
    • stream_socket_pair - Создаёт пару связанных неразличимых потоковых сокетов
    • stream_socket_recvfrom - Получает данные из сокета, подсоединённого или нет
    • stream_socket_sendto - Отправляет сообщение в сокет, независимо от того, подсоединён он или нет
    • stream_socket_server - Создаёт интернет-сокет или доменный сокет Unix
    • stream_socket_shutdown - Закрывает полнодуплексное соединение
    • stream_supports_lock - Определяет, поддерживает ли поток блокировку
    • stream_wrapper_register - Регистрирует обёртку URL, реализованную в виде PHP-класса
    • stream_wrapper_restore - Восстанавливает ранее разрегистрированную встроенную обёртку
    • stream_wrapper_unregister - Отменяет регистрацию обертки URL
    • strftime - Форматирует текущую дату/время с учетом текущих настроек локали
    • stripcslashes - Удаляет экранирование символов, произведенное функцией addcslashes
    • stripos - Возвращает позицию первого вхождения подстроки без учета регистра
    • stripslashes - Удаляет экранирование символов
    • strip_tags - Удаляет HTML и PHP-теги из строки
    • stristr - Регистро-независимый вариант функции strstr
    • strlen - Возвращает длину строки
    • strnatcasecmp - Сравнение строк без учета регистра с использованием алгоритма "natural order"
    • strnatcmp - Сравнение строк с использованием алгоритма "natural order"
    • strncasecmp - Бинарно-безопасное сравнение первых n символов строк без учета регистра
    • strncmp - Бинарно-безопасное сравнение первых n символов строк
    • strpbrk - Ищет в строке любой символ из заданного набора
    • strpos - Возвращает позицию первого вхождения подстроки
    • strptime - Разбирает строку даты/времени сгенерированную функцией strftime
    • strrchr - Находит последнее вхождение символа в строке
    • strrev - Переворачивает строку задом наперед
    • strripos - Возвращает позицию последнего вхождения подстроки без учета регистра
    • strrpos - Возвращает позицию последнего вхождения подстроки в строке
    • strspn - Возвращает длину участка в начале строки, полностью соответствующего маске
    • strstr - Находит первое вхождение подстроки
    • strtok - Разбивает строку на токены
    • strtolower - Преобразует строку в нижний регистр
    • strtotime - Преобразует текстовое представление даты на английском языке в метку времени Unix
    • strtoupper - Преобразует строку в верхний регистр
    • strtr - Преобразует заданные символы или заменяет подстроки
    • strval - Возвращает строковое значение переменной
    • str_getcsv - Выполняет разбор CSV-строки в массив
    • str_ireplace - Регистро-независимый вариант функции str_replace
    • str_pad - Дополняет строку другой строкой до заданной длины
    • str_repeat - Возвращает повторяющуюся строку
    • str_replace - Заменяет все вхождения строки поиска на строку замены
    • str_rot13 - Выполняет преобразование ROT13 над строкой
    • str_shuffle - Переставляет символы в строке случайным образом
    • str_split - Преобразует строку в массив
    • str_word_count - Возвращает информацию о словах, входящих в строку
    • substr - Возвращает подстроку
    • substr_compare - Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
    • substr_count - Возвращает число вхождений подстроки
    • substr_replace - Заменяет часть строки
    • SVM::crossvalidate - Test training params on subsets of the training data.
    • SVM::getOptions - Return the current training parameters
    • SVM::setOptions - Set training parameters
    • SVM::train - Create a SVMModel based on training data
    • SVM::__construct - Construct a new SVM object
    • SVMModel::checkProbabilityModel - Returns true if the model has probability information
    • SVMModel::getLabels - Get the labels the model was trained on
    • SVMModel::getNrClass - Returns the number of classes the model was trained with
    • SVMModel::getSvmType - Get the SVM type the model was trained with
    • SVMModel::getSvrProbability - Get the sigma value for regression types
    • SVMModel::load - Load a saved SVM Model
    • SVMModel::predict - Predict a value for previously unseen data
    • SVMModel::predict_probability - Return class probabilities for previous unseen data
    • SVMModel::save - Save a model to a file
    • SVMModel::__construct - Construct a new SVMModel
    • svn_add - Добавляет элементы в список запланированных для добавления в рабочую копию
    • svn_auth_get_parameter - Возвращает параметр аутентификации
    • svn_auth_set_parameter - Устанавливает параметр аутентификации
    • svn_blame - Построчно выводит автора и редакцию для файла
    • svn_cat - Возвращает содержимое файла в репозитарии
    • svn_checkout - Получает рабочую копию из репозитория
    • svn_cleanup - Рекурсивно очищает рабочую копию директории, завершает незаконченные операции и снимает блокировки
    • svn_client_version - Возвращает версию клиентских библиотек SVN
    • svn_commit - Отправляет изменения из рабочей директории в репозиторий
    • svn_delete - Удаляет элементы из рабочей копии или репозитория
    • svn_diff - Рекурсивно показывает различия двух файлов
    • svn_export - Экспортирует содержимое директории SVN
    • svn_fs_abort_txn - Отменяет тразнакцию, возвращает TRUE если отмена прошла успешно или FALSE в противном случае
    • svn_fs_apply_text - Создает и возвращает поток, который будет использован для замены
    • svn_fs_begin_txn2 - Создает новую транзакцию
    • svn_fs_change_node_prop - Возвращает TRUE если операция прошла успешно или FALSE в противном случае
    • svn_fs_check_path - Определяет, какая сущность находится в пути репозитария fsroot
    • svn_fs_contents_changed - Возвращает TRUE если содержимое отличается или FALSE в противном случае
    • svn_fs_copy - Копирует файл или директорию, возвращает TRUE если операция прошла успешно или FALSE в противном случае
    • svn_fs_delete - Удаляет файл или директорию, возвращает TRUE если операция прошла успешно или FALSE в противном случае
    • svn_fs_dir_entries - Перечисляет элементы директории по заданному пути; возвращает хэш имен директорий и типов файлов
    • svn_fs_file_contents - Возвращает поток для доступа к содержимому файла из данной файловой системы
    • svn_fs_file_length - Возвращает длину файла из данной файловой системы
    • svn_fs_is_dir - Возвращает TRUE если по данному пути находится директория или FALSE в противном случае
    • svn_fs_is_file - Возвращает TRUE если по данному пути находится файл или FALSE в противном случае
    • svn_fs_make_dir - Создает новую пустую директорию, возвращает TRUE если операция прошла успешно или FALSE в противном случае
    • svn_fs_make_file - Создает новый пустой файл, возвращает TRUE если операция прошла успешно или FALSE в противном случае
    • svn_fs_node_created_rev - Возвращает номер ревизии, когда был создан путь в файловой системе
    • svn_fs_node_prop - Возвращает значение свойства для узла
    • svn_fs_props_changed - Возвращает TRUE если свойства разные или FALSE в противном случае
    • svn_fs_revision_prop - Возвращает значение данного свойства
    • svn_fs_revision_root - Возвращает дескриптор определенной версии корневой директории репозитария
    • svn_fs_txn_root - Создает и возвращает корень транзакции
    • svn_fs_youngest_rev - Возвращает номер самой ранней ревизии в файловой системе
    • svn_import - Импорт пути без версии в репозитории
    • svn_log - Возвращает комментарии к правкам в репозитории
    • svn_ls - Возвращает список содержимого директории репозитория URL, опционально для конкретной ревизии
    • svn_mkdir - Создает директорию в рабочей копии или в репозитарии
    • svn_repos_create - Создание нового репозитория Subversion
    • svn_repos_fs - Возвращает дескриптор файловой системы для репозитория
    • svn_repos_fs_begin_txn_for_commit - Создание новой транзакции
    • svn_repos_fs_commit_txn - Отправка транзакции и возвращение номера ревизии
    • svn_repos_hotcopy - Создает свежую копию репозитория по адресу repospath и копирует в destpath
    • svn_repos_open - Открывает репозиторий с общей блокировкой
    • svn_repos_recover - Запускает процедуры восстановления репозитория
    • svn_revert - Отменяет локальные изменения рабочей копии
    • svn_status - Возвращает SVN статус файлов и директорий рабочей копии
    • svn_update - Обновляет рабочую копию
    • SWFAction::__construct - Creates a new SWFAction
    • SWFBitmap::getHeight - Returns the bitmap's height
    • SWFBitmap::getWidth - Returns the bitmap's width
    • SWFBitmap::__construct - Loads Bitmap object
    • SWFButton::addAction - Adds an action
    • SWFButton::addASound - Associates a sound with a button transition
    • SWFButton::addShape - Adds a shape to a button
    • SWFButton::setAction - Sets the action
    • SWFButton::setDown - Alias for addShape(shape, SWFBUTTON_DOWN)
    • SWFButton::setHit - Alias for addShape(shape, SWFBUTTON_HIT)
    • SWFButton::setMenu - enable track as menu button behaviour
    • SWFButton::setOver - Alias for addShape(shape, SWFBUTTON_OVER)
    • SWFButton::setUp - Alias for addShape(shape, SWFBUTTON_UP)
    • SWFButton::__construct - Creates a new Button
    • SWFDisplayItem::addAction - Adds this SWFAction to the given SWFSprite instance
    • SWFDisplayItem::addColor - Adds the given color to this item's color transform
    • SWFDisplayItem::endMask - Another way of defining a MASK layer
    • SWFDisplayItem::getRot - Описание
    • SWFDisplayItem::getX - Описание
    • SWFDisplayItem::getXScale - Описание
    • SWFDisplayItem::getXSkew - Описание
    • SWFDisplayItem::getY - Описание
    • SWFDisplayItem::getYScale - Описание
    • SWFDisplayItem::getYSkew - Описание
    • SWFDisplayItem::move - Moves object in relative coordinates
    • SWFDisplayItem::moveTo - Moves object in global coordinates
    • SWFDisplayItem::multColor - Multiplies the item's color transform
    • SWFDisplayItem::remove - Removes the object from the movie
    • SWFDisplayItem::rotate - Rotates in relative coordinates
    • SWFDisplayItem::rotateTo - Rotates the object in global coordinates
    • SWFDisplayItem::scale - Scales the object in relative coordinates
    • SWFDisplayItem::scaleTo - Scales the object in global coordinates
    • SWFDisplayItem::setDepth - Sets z-order
    • SWFDisplayItem::setMaskLevel - Defines a MASK layer at level
    • SWFDisplayItem::setMatrix - Sets the item's transform matrix
    • SWFDisplayItem::setName - Sets the object's name
    • SWFDisplayItem::setRatio - Sets the object's ratio
    • SWFDisplayItem::skewX - Sets the X-skew
    • SWFDisplayItem::skewXTo - Sets the X-skew
    • SWFDisplayItem::skewY - Sets the Y-skew
    • SWFDisplayItem::skewYTo - Sets the Y-skew
    • SWFFill::moveTo - Moves fill origin
    • SWFFill::rotateTo - Sets fill's rotation
    • SWFFill::scaleTo - Sets fill's scale
    • SWFFill::skewXTo - Sets fill x-skew
    • SWFFill::skewYTo - Sets fill y-skew
    • SWFFont::getAscent - Returns the ascent of the font, or 0 if not available
    • SWFFont::getDescent - Returns the descent of the font, or 0 if not available
    • SWFFont::getLeading - Returns the leading of the font, or 0 if not available
    • SWFFont::getShape - Returns the glyph shape of a char as a text string
    • SWFFont::getUTF8Width - Calculates the width of the given string in this font at full height
    • SWFFont::getWidth - Returns the string's width
    • SWFFont::__construct - Loads a font definition
    • SWFFontChar::addChars - Adds characters to a font for exporting font
    • SWFFontChar::addUTF8Chars - Adds characters to a font for exporting font
    • SWFGradient::addEntry - Adds an entry to the gradient list
    • SWFGradient::__construct - Creates a gradient object
    • SWFMorph::getShape1 - Gets a handle to the starting shape
    • SWFMorph::getShape2 - Gets a handle to the ending shape
    • SWFMorph::__construct - Creates a new SWFMorph object
    • SWFMovie::add - Adds any type of data to a movie
    • SWFMovie::addExport - Описание
    • SWFMovie::addFont - Описание
    • SWFMovie::importChar - Описание
    • SWFMovie::importFont - Описание
    • SWFMovie::labelFrame - Labels a frame
    • SWFMovie::nextFrame - Moves to the next frame of the animation
    • SWFMovie::output - Dumps your lovingly prepared movie out
    • SWFMovie::remove - Removes the object instance from the display list
    • SWFMovie::save - Saves the SWF movie in a file
    • SWFMovie::saveToFile - Описание
    • SWFMovie::setbackground - Sets the background color
    • SWFMovie::setDimension - Sets the movie's width and height
    • SWFMovie::setFrames - Sets the total number of frames in the animation
    • SWFMovie::setRate - Sets the animation's frame rate
    • SWFMovie::startSound - Описание
    • SWFMovie::stopSound - Описание
    • SWFMovie::streamMP3 - Streams a MP3 file
    • SWFMovie::writeExports - Описание
    • SWFMovie::__construct - Creates a new movie object, representing an SWF version 4 movie
    • SWFPrebuiltClip::__construct - Возвращает объект класса SWFPrebuiltClip
    • SWFShape::addFill - Adds a solid fill to the shape
    • SWFShape::drawArc - Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
    • SWFShape::drawCircle - Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
    • SWFShape::drawCubic - Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCubicTo - Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCurve - Draws a curve (relative)
    • SWFShape::drawCurveTo - Draws a curve
    • SWFShape::drawGlyph - Draws the first character in the given string into the shape using the glyph definition from the given font
    • SWFShape::drawLine - Draws a line (relative)
    • SWFShape::drawLineTo - Draws a line
    • SWFShape::movePen - Moves the shape's pen (relative)
    • SWFShape::movePenTo - Moves the shape's pen
    • SWFShape::setLeftFill - Sets left rasterizing color
    • SWFShape::setLine - Sets the shape's line style
    • SWFShape::setRightFill - Sets right rasterizing color
    • SWFShape::__construct - Creates a new shape object
    • SWFSound::__construct - Возвращает новый объект SWFSound из заданного файла
    • SWFSoundInstance::loopCount - Описание
    • SWFSoundInstance::loopInPoint - Описание
    • SWFSoundInstance::loopOutPoint - Описание
    • SWFSoundInstance::noMultiple - Описание
    • SWFSprite::add - Adds an object to a sprite
    • SWFSprite::labelFrame - Labels frame
    • SWFSprite::nextFrame - Moves to the next frame of the animation
    • SWFSprite::remove - Removes an object to a sprite
    • SWFSprite::setFrames - Sets the total number of frames in the animation
    • SWFSprite::startSound - Описание
    • SWFSprite::stopSound - Описание
    • SWFSprite::__construct - Creates a movie clip (a sprite)
    • SWFText::addString - Draws a string
    • SWFText::addUTF8String - Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
    • SWFText::getAscent - Returns the ascent of the current font at its current size, or 0 if not available
    • SWFText::getDescent - Returns the descent of the current font at its current size, or 0 if not available
    • SWFText::getLeading - Returns the leading of the current font at its current size, or 0 if not available
    • SWFText::getUTF8Width - calculates the width of the given string in this text objects current font and size
    • SWFText::getWidth - Computes string's width
    • SWFText::moveTo - Moves the pen
    • SWFText::setColor - Sets the current text color
    • SWFText::setFont - Sets the current font
    • SWFText::setHeight - Sets the current font height
    • SWFText::setSpacing - Sets the current font spacing
    • SWFText::__construct - Creates a new SWFText object
    • SWFTextField::addChars - adds characters to a font that will be available within a textfield
    • SWFTextField::addString - Concatenates the given string to the text field
    • SWFTextField::align - Sets the text field alignment
    • SWFTextField::setBounds - Sets the text field width and height
    • SWFTextField::setColor - Sets the color of the text field
    • SWFTextField::setFont - Sets the text field font
    • SWFTextField::setHeight - Sets the font height of this text field font
    • SWFTextField::setIndentation - Sets the indentation of the first line
    • SWFTextField::setLeftMargin - Sets the left margin width of the text field
    • SWFTextField::setLineSpacing - Sets the line spacing of the text field
    • SWFTextField::setMargins - Sets the margins width of the text field
    • SWFTextField::setName - Sets the variable name
    • SWFTextField::setPadding - Sets the padding of this textfield
    • SWFTextField::setRightMargin - Sets the right margin width of the text field
    • SWFTextField::__construct - Creates a text field object
    • SWFVideoStream::getNumFrames - Возвращает количество кадров в видео-файле
    • SWFVideoStream::setDimension - Устанавливает размер видео
    • SWFVideoStream::__construct - Возвращает объект класса SWFVideoStream
    • swf_actiongeturl - Get a URL from a Shockwave Flash movie
    • swf_actiongotoframe - Play a frame and then stop
    • swf_actiongotolabel - Display a frame with the specified label
    • swf_actionnextframe - Go forward one frame
    • swf_actionplay - Start playing the flash movie from the current frame
    • swf_actionprevframe - Go backwards one frame
    • swf_actionsettarget - Set the context for actions
    • swf_actionstop - Stop playing the flash movie at the current frame
    • swf_actiontogglequality - Toggle between low and high quality
    • swf_actionwaitforframe - Skip actions if a frame has not been loaded
    • swf_addbuttonrecord - Controls location, appearance and active area of the current button
    • swf_addcolor - Set the global add color to the rgba value specified
    • swf_closefile - Close the current Shockwave Flash file
    • swf_definebitmap - Define a bitmap
    • swf_definefont - Defines a font
    • swf_defineline - Define a line
    • swf_definepoly - Define a polygon
    • swf_definerect - Define a rectangle
    • swf_definetext - Define a text string
    • swf_endbutton - End the definition of the current button
    • swf_enddoaction - End the current action
    • swf_endshape - Completes the definition of the current shape
    • swf_endsymbol - End the definition of a symbol
    • swf_fontsize - Change the font size
    • swf_fontslant - Set the font slant
    • swf_fonttracking - Set the current font tracking
    • swf_getbitmapinfo - Get information about a bitmap
    • swf_getfontinfo - Gets font information
    • swf_getframe - Get the frame number of the current frame
    • swf_labelframe - Label the current frame
    • swf_lookat - Define a viewing transformation
    • swf_modifyobject - Modify an object
    • swf_mulcolor - Sets the global multiply color to the rgba value specified
    • swf_nextid - Returns the next free object id
    • swf_oncondition - Describe a transition used to trigger an action list
    • swf_openfile - Open a new Shockwave Flash file
    • swf_ortho - Defines an orthographic mapping of user coordinates onto the current viewport
    • swf_ortho2 - Defines 2D orthographic mapping of user coordinates onto the current viewport
    • swf_perspective - Define a perspective projection transformation
    • swf_placeobject - Place an object onto the screen
    • swf_polarview - Define the viewer's position with polar coordinates
    • swf_popmatrix - Restore a previous transformation matrix
    • swf_posround - Enables or Disables the rounding of the translation when objects are placed or moved
    • swf_pushmatrix - Push the current transformation matrix back onto the stack
    • swf_removeobject - Remove an object
    • swf_rotate - Rotate the current transformation
    • swf_scale - Scale the current transformation
    • swf_setfont - Change the current font
    • swf_setframe - Switch to a specified frame
    • swf_shapearc - Draw a circular arc
    • swf_shapecurveto - Draw a quadratic bezier curve between two points
    • swf_shapecurveto3 - Draw a cubic bezier curve
    • swf_shapefillbitmapclip - Set current fill mode to clipped bitmap
    • swf_shapefillbitmaptile - Set current fill mode to tiled bitmap
    • swf_shapefilloff - Turns off filling
    • swf_shapefillsolid - Set the current fill style to the specified color
    • swf_shapelinesolid - Set the current line style
    • swf_shapelineto - Draw a line
    • swf_shapemoveto - Move the current position
    • swf_showframe - Display the current frame
    • swf_startbutton - Start the definition of a button
    • swf_startdoaction - Start a description of an action list for the current frame
    • swf_startshape - Start a complex shape
    • swf_startsymbol - Define a symbol
    • swf_textwidth - Get the width of a string
    • swf_translate - Translate the current transformations
    • swf_viewport - Select an area for future drawing
    • Swish::getMetaList - Get the list of meta entries for the index
    • Swish::getPropertyList - Get the list of properties for the index
    • Swish::prepare - Prepare a search query
    • Swish::query - Execute a query and return results object
    • Swish::__construct - Construct a Swish object
    • SwishResult::getMetaList - Get a list of meta entries
    • SwishResult::stem - Stems the given word
    • SwishResults::getParsedWords - Get an array of parsed words
    • SwishResults::getRemovedStopwords - Get an array of stopwords removed from the query
    • SwishResults::nextResult - Get the next search result
    • SwishResults::seekResult - Set current seek pointer to the given position
    • SwishSearch::execute - Execute the search and get the results
    • SwishSearch::resetLimit - Reset the search limits
    • SwishSearch::setLimit - Set the search limits
    • SwishSearch::setPhraseDelimiter - Set the phrase delimiter
    • SwishSearch::setSort - Set the sort order
    • SwishSearch::setStructure - Set the structure flag in the search object
    • sybase_affected_rows - Gets number of affected rows in last query
    • sybase_close - Closes a Sybase connection
    • sybase_connect - Opens a Sybase server connection
    • sybase_data_seek - Moves internal row pointer
    • sybase_deadlock_retry_count - Sets the deadlock retry count
    • sybase_fetch_array - Fetch row as array
    • sybase_fetch_assoc - Fetch a result row as an associative array
    • sybase_fetch_field - Get field information from a result
    • sybase_fetch_object - Fetch a row as an object
    • sybase_fetch_row - Get a result row as an enumerated array
    • sybase_field_seek - Sets field offset
    • sybase_free_result - Frees result memory
    • sybase_get_last_message - Returns the last message from the server
    • sybase_min_client_severity - Sets minimum client severity
    • sybase_min_error_severity - Sets minimum error severity
    • sybase_min_message_severity - Sets minimum message severity
    • sybase_min_server_severity - Sets minimum server severity
    • sybase_num_fields - Gets the number of fields in a result set
    • sybase_num_rows - Get number of rows in a result set
    • sybase_pconnect - Open persistent Sybase connection
    • sybase_query - Sends a Sybase query
    • sybase_result - Get result data
    • sybase_select_db - Selects a Sybase database
    • sybase_set_message_handler - Sets the handler called when a server message is raised
    • sybase_unbuffered_query - Send a Sybase query and do not block
    • symlink - Создаёт символическую ссылку
    • syslog - Генерирует сообщение для системного журнала
    • system - Выполняет внешнюю программу и отображает её вывод
    • sys_getloadavg - Поулчает среднюю загрузку системы
    • sys_get_temp_dir - Returns directory path used for temporary files
  • t
    • taint - Taint a string
    • tan - Тангенс
    • tanh - Гиперболический тангенс
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - Создаёт файл с уникальным именем
    • textdomain - Устанавливает домен по умолчанию
    • tidy::$errorBuffer - Return warnings and errors which occurred parsing the specified document
    • tidy::body - Возвращает объект tidyNode, начиная с тега <body> разобранного tidy-дерева
    • tidy::cleanRepair - Выполнить настроенную очистку и восстановление разобранной разметки
    • tidy::diagnose - Запуск настроенной диагностики для разобранной и восстановленной разметки
    • tidy::getConfig - Получает текущую конфигурацию Tidy
    • tidy::getHtmlVer - Получает обнаруженную HTML версию для указанного документа
    • tidy::getOpt - Возвращает значение указанного параметра конфигурации для документа tidy
    • tidy::getoptdoc - Возвращает описание для опции с указанным названием
    • tidy::getRelease - Получить дату релиза (версию) для библиотеки Tidy
    • tidy::getStatus - Получает статус указанного документа
    • tidy::head - Возвращает объект tidyNode, начиная с тега <head> разобранного tidy-дерева
    • tidy::html - Возвращает объект tidyNode, начиная с тега <html> разобранного tidy-дерева
    • tidy::isXhtml - Определяет, является ли документ XHTML-документом
    • tidy::isXml - Определяет, является ли документ общим XML-документом (не HTML/XHTML)
    • tidy::parseFile - Разбор разметки в файле или URI
    • tidy::parseString - Разбор документа, хранимого в строке
    • tidy::repairFile - Воcстанавливает разметку файла и возвращает его в виде строки
    • tidy::repairString - Восстанавливает строку, используя по возможности конфигурационный файл
    • tidy::root - Возвращает объект tidyNode, представляющий вершину разобранного tidy-дерева
    • tidy::__construct - Создает новый tidy-объект
    • tidyNode::getParent - Возвращает родительский узел текущего узла
    • tidyNode::hasChildren - Проверяет существование потомков у узла
    • tidyNode::hasSiblings - Проверяет существование соседних узлов
    • tidyNode::isAsp - Проверяет текущий узел на соответствие ASP
    • tidyNode::isComment - Проверяет, является ли узел комментарием
    • tidyNode::isHtml - Проверяет, является ли текущий узел частью HTML-документа
    • tidyNode::isJste - Проверяет текущий узел на соответствие JSTE
    • tidyNode::isPhp - Проверяет, является ли текущий узел PHP-кодом
    • tidyNode::isText - Проверяет, является ли текущий узел обычным текстом (не разметкой)
    • tidy_access_count - Возвращает число доступных предупреждений Tidy, встретившихся в рассмотренном документе
    • tidy_config_count - Возвращает число ошибок конфигурации Tidy, встретившихся при рассмотрении документа
    • tidy_error_count - Возвращает число ошибок Tidy, встретившихся при рассмотрении документа
    • tidy_get_output - Возвращает строку, представляющую разобранную tidy-разметку
    • tidy_load_config - Загрузить конфигурационный файл ASCII Tidy с указанной кодировкой
    • tidy_reset_config - Сбрасывает конфигурацию Tidy в стандартные значения
    • tidy_save_config - Сохранить текущие настройки в файл
    • tidy_setopt - Обновляет конфигурационные настройки для указанного документа tidy
    • tidy_set_encoding - Устанавливает входную/выходную кодировку символов для указанной разметки
    • tidy_warning_count - Возвращает число Tidy-предупреждений, встреченных в указанном документе
    • time - Возвращает текущую метку времени Unix
    • timezone_abbreviations_list - Псевдоним DateTimeZone::listAbbreviations
    • timezone_identifiers_list - Псевдоним DateTimeZone::listIdentifiers
    • timezone_location_get - Псевдоним DateTimeZone::getLocation
    • timezone_name_from_abbr - Возвращает временную зону в соответствии с аббревиатурой
    • timezone_name_get - Псевдоним DateTimeZone::getName
    • timezone_offset_get - Псевдоним DateTimeZone::getOffset
    • timezone_open - Псевдоним DateTimeZone::__construct
    • timezone_transitions_get - Псевдоним DateTimeZone::getTransitions
    • timezone_version_get - Получение номера версии базы данных временных зон
    • time_nanosleep - Откладывает исполнение на заданное число секунд и наносекунд
    • time_sleep_until - Откладывает исполнение скрипта до заданного времени
    • tmpfile - Создаёт временный файл
    • token_get_all - Разбивает переданный исходный код на PHP-лексемы
    • token_name - Возвращает символьное имя для переданной PHP-лексемы
    • TokyoTyrant::add - Adds to a numeric key
    • TokyoTyrant::connect - Connect to a database
    • TokyoTyrant::connectUri - Connects to a database
    • TokyoTyrant::copy - Copies the database
    • TokyoTyrant::ext - Execute a remote script
    • TokyoTyrant::fwmKeys - Returns the forward matching keys
    • TokyoTyrant::get - The get purpose
    • TokyoTyrant::getIterator - Get an iterator
    • TokyoTyrant::num - Number of records in the database
    • TokyoTyrant::out - Removes records
    • TokyoTyrant::put - Puts values
    • TokyoTyrant::putCat - Concatenates to a record
    • TokyoTyrant::putKeep - Puts a record
    • TokyoTyrant::putNr - Puts value
    • TokyoTyrant::putShl - Concatenates to a record
    • TokyoTyrant::restore - Restore the database
    • TokyoTyrant::setMaster - Set the replication master
    • TokyoTyrant::size - Returns the size of the value
    • TokyoTyrant::stat - Get statistics
    • TokyoTyrant::sync - Synchronize the database
    • TokyoTyrant::tune - Tunes connection values
    • TokyoTyrant::vanish - Empties the database
    • TokyoTyrant::__construct - Construct a new TokyoTyrant object
    • TokyoTyrantIterator::current - Get the current value
    • TokyoTyrantIterator::key - Returns the current key
    • TokyoTyrantIterator::next - Move to next key
    • TokyoTyrantIterator::rewind - Rewinds the iterator
    • TokyoTyrantIterator::valid - Rewinds the iterator
    • TokyoTyrantIterator::__construct - Construct an iterator
    • TokyoTyrantQuery::addCond - Adds a condition to the query
    • TokyoTyrantQuery::count - Counts records
    • TokyoTyrantQuery::current - Returns the current element
    • TokyoTyrantQuery::hint - Get the hint string of the query
    • TokyoTyrantQuery::key - Returns the current key
    • TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries
    • TokyoTyrantQuery::next - Moves the iterator to next entry
    • TokyoTyrantQuery::out - Removes records based on query
    • TokyoTyrantQuery::rewind - Rewinds the iterator
    • TokyoTyrantQuery::search - Searches records
    • TokyoTyrantQuery::setLimit - Limit results
    • TokyoTyrantQuery::setOrder - Orders results
    • TokyoTyrantQuery::valid - Checks the validity of current item
    • TokyoTyrantQuery::__construct - Construct a new query
    • TokyoTyrantTable::add - Adds a record
    • TokyoTyrantTable::genUid - Generate unique id
    • TokyoTyrantTable::get - Get a row
    • TokyoTyrantTable::getIterator - Get an iterator
    • TokyoTyrantTable::getQuery - Get a query object
    • TokyoTyrantTable::out - Remove records
    • TokyoTyrantTable::put - Store a row
    • TokyoTyrantTable::putCat - Concatenates to a row
    • TokyoTyrantTable::putKeep - Put a new record
    • TokyoTyrantTable::putNr - Puts value
    • TokyoTyrantTable::putShl - Concatenates to a record
    • TokyoTyrantTable::setIndex - Sets index
    • touch - Устанавливает время доступа и модификации файла
    • trait_exists - Checks if the trait exists
    • Transliterator::create - Create a transliterator
    • Transliterator::createFromRules - Create transliterator from rules
    • Transliterator::createInverse - Create an inverse transliterator
    • Transliterator::getErrorCode - Get last error code
    • Transliterator::getErrorMessage - Get last error message
    • Transliterator::listIDs - Get transliterator IDs
    • Transliterator::transliterate - Transliterate a string
    • Transliterator::__construct - Private constructor to deny instantiation
    • trigger_error - Вызывает пользовательскую ошибку/предупреждение/уведомление
    • trim - Удаляет пробелы (или другие символы) из начала и конца строки
  • u
    • uasort - Сортирует массив, используя пользовательскую функцию для сравнения элементов с сохранением ключей
    • ucfirst - Преобразует первый символ строки в верхний регистр
    • ucwords - Преобразует в верхний регистр первый символ каждого слова в строке
    • udm_add_search_limit - Add various search limits
    • udm_alloc_agent - Allocate mnoGoSearch session
    • udm_alloc_agent_array - Allocate mnoGoSearch session
    • udm_api_version - Получает версию mnoGoSearch API
    • udm_cat_list - Get all the categories on the same level with the current one
    • udm_cat_path - Get the path to the current category
    • udm_check_charset - Проверяет, известен ли данный набор символов mnogosearch
    • udm_check_stored - Check connection to stored
    • udm_clear_search_limits - Очищает все ограничения поиска mnoGoSearch
    • udm_close_stored - Close connection to stored
    • udm_crc32 - Возвращает контрольную сумму CRC32 данной строки
    • udm_errno - Получает номер ошибки mnoGoSearch
    • udm_error - Получает сообщение об ошибке mnoGoSearch
    • udm_find - Perform search
    • udm_free_agent - Освобождает сессию mnoGoSearch
    • udm_free_ispell_data - Освобождает память, выделенную для ispell-данных
    • udm_free_res - Освобождает память, выделенную для результатов mnoGoSearch
    • udm_get_doc_count - Получает общее количество документов в базе данных
    • udm_get_res_field - Fetch a result field
    • udm_get_res_param - Get mnoGoSearch result parameters
    • udm_hash32 - Возвращает контрольную сумму Hash32 данной строки
    • udm_load_ispell_data - Загружает ispell-данные
    • udm_open_stored - Open connection to stored
    • udm_set_agent_param - Set mnoGoSearch agent session parameters
    • uksort - Сортирует массив по ключам, используя пользовательскую функцию для сравнения ключей
    • umask - Изменяет текущую umask
    • uniqid - Генерирует уникальный ID
    • unixtojd - Переводит метку времени Unix в Юлианский день
    • unlink - Удаляет файл
    • unpack - Распаковывает данные из бинарной строки
    • unregister_tick_function - Удаляет функцию из списка зарегистрированных для выполнения при каждом тике
    • unserialize - Создает PHP-значение из хранимого представления
    • unset - Удаляет переменную
    • untaint - Untaint strings
    • urldecode - Декодирование URL-кодированной строки
    • urlencode - URL-кодирование строки
    • user_error - Синоним для trigger_error
    • use_soap_error_handler - Set whether to use the SOAP error handler
    • usleep - Откладывает выполнение на микросекунды
    • usort - Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов
    • utf8_decode - Преобразует строку с ISO-8859-1 символами кодированную в UTF-8 в однобайтную ISO-8859-1
    • utf8_encode - Кодирует строку ISO-8859-1 в кодировке UTF-8
  • v
    • V8Js::executeString - Execute a string as Javascript code
    • V8Js::getExtensions - Return an array of registered extensions
    • V8Js::getPendingException - Return pending uncaught Javascript exception
    • V8Js::registerExtension - Register Javascript extensions for V8Js
    • V8Js::__construct - Construct a new V8Js object
    • V8JsException::getJsFileName - The getJsFileName purpose
    • V8JsException::getJsLineNumber - The getJsLineNumber purpose
    • V8JsException::getJsSourceLine - The getJsSourceLine purpose
    • V8JsException::getJsTrace - The getJsTrace purpose
    • variant_abs - Returns the absolute value of a variant
    • variant_add - "Adds" two variant values together and returns the result
    • variant_and - Performs a bitwise AND operation between two variants
    • variant_cast - Convert a variant into a new variant object of another type
    • variant_cat - concatenates two variant values together and returns the result
    • variant_cmp - Compares two variants
    • variant_date_from_timestamp - Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp - Converts a variant date/time value to Unix timestamp
    • variant_div - Returns the result from dividing two variants
    • variant_eqv - Performs a bitwise equivalence on two variants
    • variant_fix - Returns the integer portion of a variant
    • variant_get_type - Returns the type of a variant object
    • variant_idiv - Converts variants to integers and then returns the result from dividing them
    • variant_imp - Performs a bitwise implication on two variants
    • variant_int - Returns the integer portion of a variant
    • variant_mod - Divides two variants and returns only the remainder
    • variant_mul - Multiplies the values of the two variants
    • variant_neg - Performs logical negation on a variant
    • variant_not - Performs bitwise not negation on a variant
    • variant_or - Performs a logical disjunction on two variants
    • variant_pow - Returns the result of performing the power function with two variants
    • variant_round - Rounds a variant to the specified number of decimal places
    • variant_set - Assigns a new value for a variant object
    • variant_set_type - Convert a variant into another type "in-place"
    • variant_sub - Subtracts the value of the right variant from the left variant value
    • variant_xor - Performs a logical exclusion on two variants
    • VarnishAdmin::auth - Authenticate on a varnish instance
    • VarnishAdmin::ban - Ban URLs using a VCL expression
    • VarnishAdmin::banUrl - Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic - Clear varnish instance panic messages
    • VarnishAdmin::connect - Connect to a varnish instance administration interface
    • VarnishAdmin::getPanic - Get the last panic message on a varnish instance
    • VarnishAdmin::getParams - Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning - Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat - Set the class compat configuration param
    • VarnishAdmin::setHost - Set the class host configuration param
    • VarnishAdmin::setIdent - Set the class ident configuration param
    • VarnishAdmin::setParam - Set configuration param on the current varnish instance
    • VarnishAdmin::setPort - Set the class port configuration param
    • VarnishAdmin::setSecret - Set the class secret configuration param
    • VarnishAdmin::setTimeout - Set the class timeout configuration param
    • VarnishAdmin::start - Start varnish worker process
    • VarnishAdmin::stop - Stop varnish worker process
    • VarnishAdmin::__construct - VarnishAdmin constructor
    • VarnishLog::getLine - Get next log line
    • VarnishLog::getTagName - Get the log tag string representation by its index
    • VarnishLog::__construct - Varnishlog constructor
    • VarnishStat::getSnapshot - Get the current varnish instance statistics snapshot
    • VarnishStat::__construct - VarnishStat constructor
    • var_dump - Выводит информацию о переменной
    • var_export - Выводит в браузер или возвращает интерпретируемое строковое представление переменной
    • version_compare - Compares two "PHP-standardized" version number strings
    • vfprintf - Записывает отформатированную строку в поток
    • virtual - Выполняет подзапрос Apache
    • vpopmail_add_alias_domain - Add an alias for a virtual domain
    • vpopmail_add_alias_domain_ex - Add alias to an existing virtual domain
    • vpopmail_add_domain - Add a new virtual domain
    • vpopmail_add_domain_ex - Add a new virtual domain
    • vpopmail_add_user - Add a new user to the specified virtual domain
    • vpopmail_alias_add - Insert a virtual alias
    • vpopmail_alias_del - Deletes all virtual aliases of a user
    • vpopmail_alias_del_domain - Deletes all virtual aliases of a domain
    • vpopmail_alias_get - Get all lines of an alias for a domain
    • vpopmail_alias_get_all - Get all lines of an alias for a domain
    • vpopmail_auth_user - Attempt to validate a username/domain/password
    • vpopmail_del_domain - Delete a virtual domain
    • vpopmail_del_domain_ex - Delete a virtual domain
    • vpopmail_del_user - Delete a user from a virtual domain
    • vpopmail_error - Get text message for last vpopmail error
    • vpopmail_passwd - Change a virtual user's password
    • vpopmail_set_user_quota - Sets a virtual user's quota
    • vprintf - Выводит отформатированную строку
    • vsprintf - Возвращает отформатированную строку
  • w
    • w32api_deftype - Defines a type for use with other w32api_functions
    • w32api_init_dtype - Creates an instance of the data type typename and fills it with the values passed
    • w32api_invoke_function - Invokes function funcname with the arguments passed after the function name
    • w32api_register_function - Registers function function_name from library with PHP
    • w32api_set_call_method - Sets the calling method used
    • wddx_add_vars - Add variables to a WDDX packet with the specified ID
    • wddx_deserialize - Unserializes a WDDX packet
    • wddx_packet_end - Ends a WDDX packet with the specified ID
    • wddx_packet_start - Starts a new WDDX packet with structure inside it
    • wddx_serialize_value - Serialize a single value into a WDDX packet
    • wddx_serialize_vars - Serialize variables into a WDDX packet
    • WeakMap::count - Counts the number of live entries in the map
    • WeakMap::current - Returns the current value under iteration
    • WeakMap::key - Returns the current key under iteration.
    • WeakMap::next - Advances to the next map element
    • WeakMap::offsetExists - Checks whether a certain object is in the map
    • WeakMap::offsetGet - Returns the value pointed to by a certain object
    • WeakMap::offsetSet - Updates the map with a new key-value pair
    • WeakMap::offsetUnset - Removes an entry from the map
    • WeakMap::rewind - Rewinds the iterator to the beginning of the map
    • WeakMap::valid - Returns whether the iterator is still on a valid map element
    • WeakMap::__construct - Constructs a new map
    • Weakref::acquire - Acquires a strong reference on that object
    • Weakref::get - Returns the object pointed to by the weak reference
    • Weakref::release - Releases a previously acquired reference
    • Weakref::valid - Checks whether the object referenced still exists
    • Weakref::__construct - Constructs a new weak reference
    • win32_continue_service - Возобновляет работу приостановленной службы
    • win32_create_service - Creates a new service entry in the SCM database
    • win32_delete_service - Deletes a service entry from the SCM database
    • win32_get_last_control_message - Returns the last control message that was sent to this service
    • win32_pause_service - Pauses a service
    • win32_ps_list_procs - List running processes
    • win32_ps_stat_mem - Stat memory utilization
    • win32_ps_stat_proc - Stat process
    • win32_query_service_status - Queries the status of a service
    • win32_set_service_status - Update the service status
    • win32_start_service - Запускает службу
    • win32_start_service_ctrl_dispatcher - Добавляет в Диспетчер Служб скрипт, который может быть использован как служба с заданным именем
    • win32_stop_service - Останавливает службу
    • wincache_fcache_fileinfo - Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo - Retrieves information about file cache memory usage
    • wincache_lock - Acquires an exclusive lock on a given key
    • wincache_ocache_fileinfo - Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo - Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed - Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo - Retrieves information about resolve file path cache
    • wincache_rplist_meminfo - Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info - Retrieves information about files cached in the session cache
    • wincache_scache_meminfo - Retrieves information about session cache memory usage
    • wincache_ucache_add - Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas - Compares the variable with old value and assigns new value to it
    • wincache_ucache_clear - Deletes entire content of the user cache
    • wincache_ucache_dec - Decrements the value associated with the key
    • wincache_ucache_delete - Deletes variables from the user cache
    • wincache_ucache_exists - Checks if a variable exists in the user cache
    • wincache_ucache_get - Gets a variable stored in the user cache
    • wincache_ucache_inc - Increments the value associated with the key
    • wincache_ucache_info - Retrieves information about data stored in the user cache
    • wincache_ucache_meminfo - Retrieves information about user cache memory usage
    • wincache_ucache_set - Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock - Releases an exclusive lock on a given key
    • wordwrap - Переносит строку по указанному количеству символов
  • x
    • xattr_get - Получение расширенных атрибутов файла
    • xattr_list - Просмотр списка расширенных атрибутов файла
    • xattr_remove - Удаление расширенных атрибутов файла
    • xattr_set - Установка расширенных атрибутов файла
    • xattr_supported - Проверка поддержки расширенных атрибутов
    • xdiff_file_bdiff - Make binary diff of two files
    • xdiff_file_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_file_bpatch - Patch a file with a binary diff
    • xdiff_file_diff - Make unified diff of two files
    • xdiff_file_diff_binary - Alias of xdiff_file_bdiff
    • xdiff_file_merge3 - Merge 3 files into one
    • xdiff_file_patch - Patch a file with an unified diff
    • xdiff_file_patch_binary - Alias of xdiff_file_bpatch
    • xdiff_file_rabdiff - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff - Make binary diff of two strings
    • xdiff_string_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_string_bpatch - Patch a string with a binary diff
    • xdiff_string_diff - Make unified diff of two strings
    • xdiff_string_diff_binary - Alias of xdiff_string_bdiff
    • xdiff_string_merge3 - Merge 3 strings into one
    • xdiff_string_patch - Patch a string with an unified diff
    • xdiff_string_patch_binary - Alias of xdiff_string_bpatch
    • xdiff_string_rabdiff - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
    • xhprof_disable - Stops xhprof profiler
    • xhprof_enable - Start xhprof profiler
    • xhprof_sample_disable - Stops xhprof sample profiler
    • xhprof_sample_enable - Description
    • XMLReader::close - Закрыть ввод XMLReader
    • XMLReader::expand - Возвратить копию текущего узла в виде объекта DOM
    • XMLReader::getAttribute - Получить значение атрибута с определённым именем
    • XMLReader::getAttributeNo - Получить значение атрибута по индексу
    • XMLReader::getAttributeNs - Получить значение атрибута по localname и URI
    • XMLReader::getParserProperty - Указывает, было ли определенное свойство установлено
    • XMLReader::isValid - Показать, является ли разбираемый документ синтаксически правильным
    • XMLReader::lookupNamespace - Найти пространство имён для префикса
    • XMLReader::moveToAttribute - Переместить курсор к атрибуту с заданным именем
    • XMLReader::moveToAttributeNo - Переместить курсор на атрибут по индексу
    • XMLReader::moveToAttributeNs - Переместить курсор к именованному атрибуту
    • XMLReader::moveToElement - Позиционировать курсор на родительском элементе текущего атрибута
    • XMLReader::moveToFirstAttribute - Переместить позицию курсора на первый атрибут
    • XMLReader::moveToNextAttribute - Переместить позицию курсора на следующий атрибут
    • XMLReader::next - Переместить курсор на следующий узел, пропуская все поддеревья
    • XMLReader::open - Установить URI, содержащий XML-документ для разобора
    • XMLReader::read - Переместиться к следующему узлу в документе
    • XMLReader::readInnerXML - Извлечь XML из текущего узла
    • XMLReader::readOuterXML - Получить XML из текущего узла, включая сам узел
    • XMLReader::readString - Прочитать содержимое текущего узла как строку
    • XMLReader::setParserProperty - Устанавливает опцию парсера
    • XMLReader::setRelaxNGSchema - Устанавить имя файла или URI для схемы RelaxNG
    • XMLReader::setRelaxNGSchemaSource - Устанавливает данные, содержащие схему RelaxNG
    • XMLReader::setSchema - Проверить документ, используя XSD
    • XMLReader::XML - Установить данные, содержащие XML для разбора
    • xmlrpc_decode - Декодирует XML в нативные типы PHP
    • xmlrpc_decode_request - Декодирует XML в нативные типы PHP
    • xmlrpc_encode - Генерирует XML для PHP значения
    • xmlrpc_encode_request - Генерирует XML для метода запроса
    • xmlrpc_get_type - Получает XML-RPC тип для значения PHP
    • xmlrpc_is_fault - Определяет, является ли массив значений представлением ошибки XMLRPC
    • xmlrpc_parse_method_descriptions - Декодирует XML в список описаний методов
    • xmlrpc_server_add_introspection_data - Добавляет документацию самоанализа
    • xmlrpc_server_call_method - Разбирает XML запросы и вызывающие методы
    • xmlrpc_server_create - Создаёт XML-RPC сервер
    • xmlrpc_server_destroy - Уничтожает серверные ресурсы
    • xmlrpc_server_register_introspection_callback - Регистрирует функцию PHP для генерации документации
    • xmlrpc_server_register_method - Регистрирует функцию PHP к методу ресурса, соответствующему method_name
    • xmlrpc_set_type - Устанавливает тип XML-RPC, base64 или datetime для значения строки PHP
    • XMLWriter::endAttribute - Завершить атрибут
    • XMLWriter::endCData - Завершить текущую секцию CDATA
    • XMLWriter::endComment - Завершить комментарий
    • XMLWriter::endDocument - Завершить текущий документ
    • XMLWriter::endDTD - Завершить текущий DTD
    • XMLWriter::endDTDAttlist - Завершить текущий DTD
    • XMLWriter::endDTDElement - Завершить текущий элемент DTD
    • XMLWriter::endDTDEntity - Завершить текущую запись DTD
    • XMLWriter::endElement - Завершить текущий элемент
    • XMLWriter::endPI - Завершить текущую инструкцию обработки (PI)
    • XMLWriter::flush - Сбросить текущий буфер
    • XMLWriter::fullEndElement - Завершить текущий элемент
    • XMLWriter::openMemory - Создать новый объект XMLWriter, используя память для строкового вывода
    • XMLWriter::openURI - Создать новый объект XMLWriter, используя исходный URI для вывода
    • XMLWriter::outputMemory - Возвратить текущий буфер
    • XMLWriter::setIndent - Включить или отключить отступы
    • XMLWriter::setIndentString - Установить строку, используемую для отступов
    • XMLWriter::startAttribute - Создать начальный атрибут
    • XMLWriter::startAttributeNS - Создать стартовый атрибут пространства имен
    • XMLWriter::startCData - Создать начальный тэг CDATA
    • XMLWriter::startComment - Создает стартовый комментарий
    • XMLWriter::startDocument - Создать тэг документа
    • XMLWriter::startDTD - Создать стартовый DTD тэг
    • XMLWriter::startDTDAttlist - Создает стартовый список атрибутов DTD
    • XMLWriter::startDTDElement - Создать начальный элемент DTD
    • XMLWriter::startDTDEntity - Создать начальную запись DTD
    • XMLWriter::startElement - Создать стартовый тэг элемента
    • XMLWriter::startElementNS - Создать начальный тег элемента пространства имен
    • XMLWriter::startPI - Создать начальный тэг PI
    • XMLWriter::text - Записать текст
    • XMLWriter::writeAttribute - Записать полный атрибут
    • XMLWriter::writeAttributeNS - Записать полный атрибут пространства имен
    • XMLWriter::writeCData - Записать полный тэг CDATA
    • XMLWriter::writeComment - Записать полный тэг комментария
    • XMLWriter::writeDTD - Записать полный тэг DTD
    • XMLWriter::writeDTDAttlist - Записать полный тэг DTD AttList
    • XMLWriter::writeDTDElement - Записать полный тэг элемента DTD
    • XMLWriter::writeDTDEntity - Записать полный тэг DTD записи
    • XMLWriter::writeElement - Записать полный тег элемента
    • XMLWriter::writeElementNS - Записать полное пространство имен тега элемента
    • XMLWriter::writePI - Записать инструкцию обработки (PI)
    • XMLWriter::writeRaw - Пишет необработанный XML-текст
    • xml_error_string - Получение строки ошибки XML анализатора
    • xml_get_current_byte_index - Получает текущий для XML анализатора байтовый индекс
    • xml_get_current_column_number - Получает от XML парсера номер текущего столбца
    • xml_get_current_line_number - Получает от XML-парсера номер текущей строки
    • xml_get_error_code - Получает код ошибки XML-парсера
    • xml_parse - Запускает разбор XML документа
    • xml_parser_create - Создание XML анализатора
    • xml_parser_create_ns - Создание XML анализатора с поддержкой пространств имен
    • xml_parser_free - Освобождение XML анализатора
    • xml_parser_get_option - Получение значения настройки XML анализатора
    • xml_parser_set_option - Установка значения настройки XML анализатора
    • xml_parse_into_struct - Разбор XML данных и помещение в массив
    • xml_set_character_data_handler - Установка обработчика символьных данных
    • xml_set_default_handler - Установка обработчика по умолчанию
    • xml_set_element_handler - Установка обработчика начального и конечного элементов
    • xml_set_end_namespace_decl_handler - Установка обработчика выхода за пределы пространства имен
    • xml_set_external_entity_ref_handler - Установка обработчика внешних сущностей
    • xml_set_notation_decl_handler - Установка обработчика объявления условных обозначений
    • xml_set_object - Использование XML анализатора внутри объекта
    • xml_set_processing_instruction_handler - Установка обработчика инструкций препроцессора (PI)
    • xml_set_start_namespace_decl_handler - Установка обработчика входа в пределы пространства имен
    • xml_set_unparsed_entity_decl_handler - Установка обработчика неразобранных объявлений сущностей
    • xpath_eval - Вычисляет XPath Location Path в переданной строке
    • xpath_eval_expression - Вычисляет XPath Location Path в переданной строке
    • xpath_new_context - Создает новый xpath контекст
    • xpath_register_ns - Регистрирует пространство имен в переданном XPath контексте
    • xpath_register_ns_auto - Регистрация заданного пространства имен в определенном XPath контексте
    • xptr_eval - Вычисляет XPtr Location Path в заданной строке
    • xptr_new_context - Создает новый контекст XPath
    • XSLTProcessor::getParameter - Возвращает значение параметра
    • XsltProcessor::getSecurityPrefs - Get security preferences
    • XSLTProcessor::hasExsltSupport - Определяет имеет ли PHP поддержку EXSLT
    • XSLTProcessor::importStylesheet - Импортирует таблицу стилей
    • XSLTProcessor::registerPHPFunctions - Включает возможность использовать PHP функции в качестве функций XSLT
    • XSLTProcessor::removeParameter - Удаляет параметр
    • XSLTProcessor::setParameter - Устанавливает значение параметра
    • XSLTProcessor::setProfiling - Устанавливает файл для профилирования
    • XsltProcessor::setSecurityPrefs - Set security preferences
    • XSLTProcessor::transformToDoc - Преобразовует в DOMDocument
    • XSLTProcessor::transformToUri - Преобразует в URI
    • XSLTProcessor::transformToXML - Преобразует в XML
    • XSLTProcessor::__construct - Создаёт новый экземпляр класса XSLTProcessor
    • xslt_backend_info - Возвращает информацию о настройках, заданных при компиляции расширения (backend)
    • xslt_backend_name - Возвращает имя расширения
    • xslt_backend_version - Возвращает номер версии Sablotron
    • xslt_create - Создает новый XSLT-процессор
    • xslt_errno - Возвращает код ошибки
    • xslt_error - Возвращает сообщение об ошибке
    • xslt_free - Освобождение XSLT-процессора
    • xslt_getopt - Получение настроек заданного XSLT-процессора
    • xslt_process - Запуск XSLT преобразования
    • xslt_setopt - Установка значений настроек XSLT-процессора
    • xslt_set_base - Установка базового URI для всех XSLT преобразований
    • xslt_set_encoding - Задание кодировки для разбора XML документов
    • xslt_set_error_handler - Задание обработчика ошибок для XSLT-процессора
    • xslt_set_log - Задание файла журнала для записи сообщений XSLT процессора
    • xslt_set_object - Задает объект, в котором будут реализованы callback-функции
    • xslt_set_sax_handler - Задает SAX обработчик для XSLT-процессора
    • xslt_set_sax_handlers - Задает SAX обработчики, которые будут вызваться после разбора XML докумнента
    • xslt_set_scheme_handler - Задает обработчики схемы для XSLT-процессора
    • xslt_set_scheme_handlers - Задает обработчики схемы для XSLT-процессора
  • y
    • Yaf_Action_Abstract::execute - Execute the action
    • Yaf_Action_Abstract::getController - get controller instance
    • Yaf_Application::app - Retrive an Application instance
    • Yaf_Application::bootstrap - Call bootstrap
    • Yaf_Application::clearLastError - Clear the last error info
    • Yaf_Application::environ - Retrive environ
    • Yaf_Application::execute - Execute a callback
    • Yaf_Application::getAppDirectory - Get the application directory
    • Yaf_Application::getConfig - Retrive the config instance
    • Yaf_Application::getDispatcher - Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg - Get message of the last occurred error
    • Yaf_Application::getLastErrorNo - Get code of last occurred error
    • Yaf_Application::getModules - Get defined module names
    • Yaf_Application::run - Start Yaf_Application
    • Yaf_Application::setAppDirectory - Change the application directory
    • Yaf_Application::__clone - Yaf_Application can not be cloned
    • Yaf_Application::__construct - Yaf_Application constructor
    • Yaf_Application::__destruct - The __destruct purpose
    • Yaf_Application::__sleep - Yaf_Application can not be serialized
    • Yaf_Application::__wakeup - Yaf_Application can not be unserialized
    • Yaf_Config_Abstract::get - Getter
    • Yaf_Config_Abstract::readonly - Find a config whether readonly
    • Yaf_Config_Abstract::set - Setter
    • Yaf_Config_Abstract::toArray - Cast to array
    • Yaf_Config_Ini::count - The count purpose
    • Yaf_Config_Ini::current - The current purpose
    • Yaf_Config_Ini::key - The key purpose
    • Yaf_Config_Ini::next - The next purpose
    • Yaf_Config_Ini::offsetExists - The offsetExists purpose
    • Yaf_Config_Ini::offsetGet - The offsetGet purpose
    • Yaf_Config_Ini::offsetSet - The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Ini::readonly - The readonly purpose
    • Yaf_Config_Ini::rewind - The rewind purpose
    • Yaf_Config_Ini::toArray - The toArray purpose
    • Yaf_Config_Ini::valid - The valid purpose
    • Yaf_Config_Ini::__construct - The __construct purpose
    • Yaf_Config_Ini::__get - The __get purpose
    • Yaf_Config_Ini::__isset - The __isset purpose
    • Yaf_Config_Ini::__set - The __set purpose
    • Yaf_Config_Simple::count - The count purpose
    • Yaf_Config_Simple::current - The current purpose
    • Yaf_Config_Simple::key - The key purpose
    • Yaf_Config_Simple::next - The next purpose
    • Yaf_Config_Simple::offsetExists - The offsetExists purpose
    • Yaf_Config_Simple::offsetGet - The offsetGet purpose
    • Yaf_Config_Simple::offsetSet - The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Simple::readonly - The readonly purpose
    • Yaf_Config_Simple::rewind - The rewind purpose
    • Yaf_Config_Simple::toArray - The toArray purpose
    • Yaf_Config_Simple::valid - The valid purpose
    • Yaf_Config_Simple::__construct - The __construct purpose
    • Yaf_Config_Simple::__get - The __get purpose
    • Yaf_Config_Simple::__isset - The __isset purpose
    • Yaf_Config_Simple::__set - The __set purpose
    • Yaf_Controller_Abstract::display - The display purpose
    • Yaf_Controller_Abstract::forward - The forward purpose
    • Yaf_Controller_Abstract::getInvokeArg - The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs - The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Controller_Abstract::getRequest - The getRequest purpose
    • Yaf_Controller_Abstract::getResponse - The getResponse purpose
    • Yaf_Controller_Abstract::getView - The getView purpose
    • Yaf_Controller_Abstract::getViewpath - The getViewpath purpose
    • Yaf_Controller_Abstract::initView - The initView purpose
    • Yaf_Controller_Abstract::redirect - The redirect purpose
    • Yaf_Controller_Abstract::render - The render purpose
    • Yaf_Controller_Abstract::setViewpath - The setViewpath purpose
    • Yaf_Controller_Abstract::__clone - Yaf_Controller_Abstract can not be cloned
    • Yaf_Controller_Abstract::__construct - Yaf_Controller_Abstract constructor
    • Yaf_Dispatcher::autoRender - Switch on/off autorendering
    • Yaf_Dispatcher::catchException - Switch on/off exception catching
    • Yaf_Dispatcher::disableView - Disable view rendering
    • Yaf_Dispatcher::dispatch - Dispatch a request
    • Yaf_Dispatcher::enableView - enable view rendering
    • Yaf_Dispatcher::flushInstantly - Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication - Retrive the application
    • Yaf_Dispatcher::getInstance - Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest - Retrive the request instance
    • Yaf_Dispatcher::getRouter - Retrive router instance
    • Yaf_Dispatcher::initView - Initialize view and return it
    • Yaf_Dispatcher::registerPlugin - Register a plugin
    • Yaf_Dispatcher::returnResponse - The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction - Change default action name
    • Yaf_Dispatcher::setDefaultController - Change default controller name
    • Yaf_Dispatcher::setDefaultModule - Change default module name
    • Yaf_Dispatcher::setErrorHandler - The setErrorHandler purpose
    • Yaf_Dispatcher::setRequest - The setRequest purpose
    • Yaf_Dispatcher::setView - Set a custom view engine
    • Yaf_Dispatcher::throwException - Switch on/off exception throwing
    • Yaf_Dispatcher::__clone - Yaf_Dispatcher can not be cloned
    • Yaf_Dispatcher::__construct - Yaf_Dispatcher constructor
    • Yaf_Dispatcher::__sleep - Yaf_Dispatcher can not be serialized
    • Yaf_Dispatcher::__wakeup - Yaf_Dispatcher can not be unserialized
    • Yaf_Exception::getPrevious - The getPrevious purpose
    • Yaf_Exception::__construct - The __construct purpose
    • Yaf_Loader::autoload - The autoload purpose
    • Yaf_Loader::clearLocalNamespace - The clearLocalNamespace purpose
    • Yaf_Loader::getInstance - The getInstance purpose
    • Yaf_Loader::getLibraryPath - get the library path
    • Yaf_Loader::getLocalNamespace - The getLocalNamespace purpose
    • Yaf_Loader::import - The import purpose
    • Yaf_Loader::isLocalName - The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace - The registerLocalNamespace purpose
    • Yaf_Loader::setLibraryPath - Change the library path
    • Yaf_Loader::__clone - The __clone purpose
    • Yaf_Loader::__construct - The __construct purpose
    • Yaf_Loader::__sleep - The __sleep purpose
    • Yaf_Loader::__wakeup - The __wakeup purpose
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup - The dispatchLoopStartup purpose
    • Yaf_Plugin_Abstract::postDispatch - The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch - The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse - The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown - The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup - RouterStartup hook
    • Yaf_Registry::del - The del purpose
    • Yaf_Registry::get - The get purpose
    • Yaf_Registry::has - The has purpose
    • Yaf_Registry::set - The set purpose
    • Yaf_Registry::__clone - The __clone purpose
    • Yaf_Registry::__construct - The __construct purpose
    • Yaf_Request_Abstract::getActionName - The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri - The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName - The getControllerName purpose
    • Yaf_Request_Abstract::getEnv - The getEnv purpose
    • Yaf_Request_Abstract::getException - The getException purpose
    • Yaf_Request_Abstract::getLanguage - The getLanguage purpose
    • Yaf_Request_Abstract::getMethod - The getMethod purpose
    • Yaf_Request_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Request_Abstract::getParam - The getParam purpose
    • Yaf_Request_Abstract::getParams - The getParams purpose
    • Yaf_Request_Abstract::getRequestUri - The getRequestUri purpose
    • Yaf_Request_Abstract::getServer - The getServer purpose
    • Yaf_Request_Abstract::isCli - The isCli purpose
    • Yaf_Request_Abstract::isDispatched - The isDispatched purpose
    • Yaf_Request_Abstract::isGet - The isGet purpose
    • Yaf_Request_Abstract::isHead - The isHead purpose
    • Yaf_Request_Abstract::isOptions - The isOptions purpose
    • Yaf_Request_Abstract::isPost - The isPost purpose
    • Yaf_Request_Abstract::isPut - The isPut purpose
    • Yaf_Request_Abstract::isRouted - The isRouted purpose
    • Yaf_Request_Abstract::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Abstract::setActionName - The setActionName purpose
    • Yaf_Request_Abstract::setBaseUri - The setBaseUri purpose
    • Yaf_Request_Abstract::setControllerName - The setControllerName purpose
    • Yaf_Request_Abstract::setDispatched - The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName - The setModuleName purpose
    • Yaf_Request_Abstract::setParam - The setParam purpose
    • Yaf_Request_Abstract::setRequestUri - The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted - The setRouted purpose
    • Yaf_Request_Http::get - The get purpose
    • Yaf_Request_Http::getCookie - The getCookie purpose
    • Yaf_Request_Http::getFiles - The getFiles purpose
    • Yaf_Request_Http::getPost - The getPost purpose
    • Yaf_Request_Http::getQuery - fetch a query parameter
    • Yaf_Request_Http::getRequest - The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Http::__clone - The __clone purpose
    • Yaf_Request_Http::__construct - The __construct purpose
    • Yaf_Request_Simple::get - The get purpose
    • Yaf_Request_Simple::getCookie - The getCookie purpose
    • Yaf_Request_Simple::getFiles - The getFiles purpose
    • Yaf_Request_Simple::getPost - The getPost purpose
    • Yaf_Request_Simple::getQuery - The getQuery purpose
    • Yaf_Request_Simple::getRequest - The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Simple::__clone - The __clone purpose
    • Yaf_Request_Simple::__construct - The __construct purpose
    • Yaf_Response_Abstract::appendBody - The appendBody purpose
    • Yaf_Response_Abstract::clearBody - The clearBody purpose
    • Yaf_Response_Abstract::clearHeaders - The clearHeaders purpose
    • Yaf_Response_Abstract::getBody - The getBody purpose
    • Yaf_Response_Abstract::getHeader - The getHeader purpose
    • Yaf_Response_Abstract::prependBody - The prependBody purpose
    • Yaf_Response_Abstract::response - The response purpose
    • Yaf_Response_Abstract::setAllHeaders - The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody - The setBody purpose
    • Yaf_Response_Abstract::setHeader - The setHeader purpose
    • Yaf_Response_Abstract::setRedirect - The setRedirect purpose
    • Yaf_Response_Abstract::__clone - The __clone purpose
    • Yaf_Response_Abstract::__construct - The __construct purpose
    • Yaf_Response_Abstract::__destruct - The __destruct purpose
    • Yaf_Response_Abstract::__toString - The __toString purpose
    • Yaf_Router::addConfig - Add config-defined routes into Router
    • Yaf_Router::addRoute - Add new Route into Router
    • Yaf_Router::getCurrentRoute - Get the effective route name
    • Yaf_Router::getRoute - The getRoute purpose
    • Yaf_Router::getRoutes - The getRoutes purpose
    • Yaf_Router::route - The route purpose
    • Yaf_Router::__construct - Yaf_Router constructor
    • Yaf_Route_Interface::route - route a request
    • Yaf_Route_Map::route - The route purpose
    • Yaf_Route_Map::__construct - The __construct purpose
    • Yaf_Route_Regex::route - The route purpose
    • Yaf_Route_Regex::__construct - The __construct purpose
    • Yaf_Route_Rewrite::route - The route purpose
    • Yaf_Route_Rewrite::__construct - The __construct purpose
    • Yaf_Route_Simple::route - Route a request
    • Yaf_Route_Simple::__construct - Yaf_Route_Simple constructor
    • Yaf_Route_Static::match - The match purpose
    • Yaf_Route_Static::route - Route a request
    • Yaf_Route_Supervar::route - The route purpose
    • Yaf_Route_Supervar::__construct - The __construct purpose
    • Yaf_Session::count - The count purpose
    • Yaf_Session::current - The current purpose
    • Yaf_Session::del - The del purpose
    • Yaf_Session::getInstance - The getInstance purpose
    • Yaf_Session::has - The has purpose
    • Yaf_Session::key - The key purpose
    • Yaf_Session::next - The next purpose
    • Yaf_Session::offsetExists - The offsetExists purpose
    • Yaf_Session::offsetGet - The offsetGet purpose
    • Yaf_Session::offsetSet - The offsetSet purpose
    • Yaf_Session::offsetUnset - The offsetUnset purpose
    • Yaf_Session::rewind - The rewind purpose
    • Yaf_Session::start - The start purpose
    • Yaf_Session::valid - The valid purpose
    • Yaf_Session::__clone - The __clone purpose
    • Yaf_Session::__construct - The __construct purpose
    • Yaf_Session::__get - The __get purpose
    • Yaf_Session::__isset - The __isset purpose
    • Yaf_Session::__set - The __set purpose
    • Yaf_Session::__sleep - The __sleep purpose
    • Yaf_Session::__unset - The __unset purpose
    • Yaf_Session::__wakeup - The __wakeup purpose
    • Yaf_View_Interface::assign - Assign value to View engine
    • Yaf_View_Interface::display - Render and output a template
    • Yaf_View_Interface::getScriptPath - The getScriptPath purpose
    • Yaf_View_Interface::render - Render a template
    • Yaf_View_Interface::setScriptPath - The setScriptPath purpose
    • Yaf_View_Simple::assign - Assign values
    • Yaf_View_Simple::assignRef - The assignRef purpose
    • Yaf_View_Simple::clear - Clear Assigned values
    • Yaf_View_Simple::display - Render and display
    • Yaf_View_Simple::getScriptPath - Get template base directory
    • Yaf_View_Simple::render - Render template
    • Yaf_View_Simple::setScriptPath - Set tempalte base directory
    • Yaf_View_Simple::__construct - The __construct purpose
    • Yaf_View_Simple::__get - Retrieve assigned variable
    • Yaf_View_Simple::__isset - The __isset purpose
    • Yaf_View_Simple::__set - Set value to engine
    • yaml_emit - Returns the YAML representation of a value
    • yaml_emit_file - Отправляет YAML-представление значения в файл
    • yaml_parse - Parse a YAML stream
    • yaml_parse_file - Parse a YAML stream from a file
    • yaml_parse_url - Parse a Yaml stream from a URL
    • yaz_addinfo - Возвращает дополнительную информацию в случае ошибки
    • yaz_ccl_conf - Кофигурирует CCL-парсер
    • yaz_ccl_parse - Invoke CCL Parser
    • yaz_close - Закрывает соединение YAZ
    • yaz_connect - Подготавливает соединение с сервером Z39.50
    • yaz_database - Specifies the databases within a session
    • yaz_element - Specifies Element-Set Name for retrieval
    • yaz_errno - Returns error number
    • yaz_error - Returns error description
    • yaz_es - Prepares for an Extended Service Request
    • yaz_es_result - Inspects Extended Services Result
    • yaz_get_option - Returns value of option for connection
    • yaz_hits - Returns number of hits for last search
    • yaz_itemorder - Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present - Prepares for retrieval (Z39.50 present)
    • yaz_range - Specifies a range of records to retrieve
    • yaz_record - Returns a record
    • yaz_scan - Prepares for a scan
    • yaz_scan_result - Returns Scan Response result
    • yaz_schema - Specifies schema for retrieval
    • yaz_search - Prepares for a search
    • yaz_set_option - Sets one or more options for connection
    • yaz_sort - Задает критерий сортировки
    • yaz_syntax - Задает предпочитаемый синтаксис для извлекаемой записи
    • yaz_wait - Ожидает выполнения запросов Z39.50 серверами
    • yp_all - Traverse the map and call a function on each entry
    • yp_cat - Return an array containing the entire map
    • yp_errno - Returns the error code of the previous operation
    • yp_err_string - Returns the error string associated with the given error code
    • yp_first - Returns the first key-value pair from the named map
    • yp_get_default_domain - Fetches the machine's default NIS domain
    • yp_master - Returns the machine name of the master NIS server for a map
    • yp_match - Returns the matched line
    • yp_next - Returns the next key-value pair in the named map
    • yp_order - Returns the order number for a map
  • z
    • zend_logo_guid - Gets the Zend guid
    • zend_thread_id - Returns a unique identifier for the current thread
    • zend_version - Gets the version of the current Zend engine
    • ZipArchive::addEmptyDir - Добавляет новую директорию
    • ZipArchive::addFile - Добавляет в ZIP-архив файл по указанному пути
    • ZipArchive::addFromString - Добавяет файл в ZIP-архив, используя его содержимое
    • ZipArchive::close - Закрывает активный архив (открытый или вновь созданный)
    • ZipArchive::deleteIndex - Удаляет элемент в архиве, используя его индекс
    • ZipArchive::deleteName - Удаляет элемент в архиве, используя его имя
    • ZipArchive::extractTo - Извлекает содержимое архива
    • ZipArchive::getArchiveComment - Возвращает комментарий ZIP-архива
    • ZipArchive::getCommentIndex - Возвращает комментарий элемента, используя его индекс
    • ZipArchive::getCommentName - Возвращает комментарий элемента, используя его имя
    • ZipArchive::getFromIndex - Возвращает содержимое элемента по его индексу
    • ZipArchive::getFromName - Возвращает содержимое элемента по его имени
    • ZipArchive::getNameIndex - Возвращает имя элемента по его индексу
    • ZipArchive::getStatusString - Возвращают статус сообщения об ошибке, системный и/или zip-статус
    • ZipArchive::getStream - Получить дескриптор файла элемента, определенный по имени элемента (только для чтения)
    • ZipArchive::locateName - Возвращает индекс элемента в архиве
    • ZipArchive::open - Открывает ZIP-архив
    • ZipArchive::renameIndex - Переименовывает элемент по его индексу
    • ZipArchive::renameName - Переименовывает элемент по его имени
    • ZipArchive::setArchiveComment - Устанавливает комментарий к ZIP-архиву
    • ZipArchive::setCommentIndex - Устанавливает комментарий к элементу по его индексу
    • ZipArchive::setCommentName - Устанавливает комментарий к элементу, заданному по имени
    • ZipArchive::statIndex - Получение детальной информации о элементе по его индексу
    • ZipArchive::statName - Получение детальной информации о элементе по его имени
    • ZipArchive::unchangeAll - Отменяет все изменения, сделанные в архиве
    • ZipArchive::unchangeArchive - Возвращает все глобальные изменения, сделанные в архиве
    • ZipArchive::unchangeIndex - Отменяет все измения у позиции с заданным индексом
    • ZipArchive::unchangeName - Отменяет все измения у позиции с заданным именем
    • zip_close - Закрывает дескриптор ZIP-архива
    • zip_entry_close - Закрывает дескриптор директории
    • zip_entry_compressedsize - Возвращает сжатый размер файла для дескриптора директории
    • zip_entry_compressionmethod - Возвращает метод сжатия дескриптора директории
    • zip_entry_filesize - Возвращает реальный размер файла для дескриптора директории
    • zip_entry_name - Получает имя дескриптора директории
    • zip_entry_open - Открывает директорию для чтения
    • zip_entry_read - Читает данные из открытого ранее дескриптора директории
    • zip_open - Открывает ZIP-архив
    • zip_read - Считывает следующую запись в ZIP-архиве
    • zlib:// - Сжатые потоки
    • zlib_decode - Uncompress any raw/gzip/zlib encoded data
    • zlib_encode - Compress data with the specified encoding
    • zlib_get_coding_type - Возвращает способ кодирования, используемый для сжатия вывода
  • _
    • __autoload - Attempt to load undefined class
    • __halt_compiler - Останавливает работу компилятора
  • �
    • Контекстные опции Phar - Список контекстных опций Phar
    • Контекстные опции сокета - Список контекстных опций сокета
    • Опции контекста CURL - Список опций контекста CURL
    • Опции контекста HTTP - Cписок опций контекста HTTP
    • Опции контекста SSL - Список опций контекста SSL
    • Параметры контекста - Список параметров контекста
    • Параметры контекста FTP - Список параметров контекста FTP

User Contributed Notes

There are no user contributed notes for this page.
Алфавитный список
Список примеров
Алфавитный список


Список примеров

Список всех примеров в руководстве

  • Example#0 - Пример программирования на PHP
  • Example#1 - Первый скрипт на PHP: hello.php
  • Example#2 - Получение информации о системе из PHP
  • Example#3 - Вывод значения переменной (элемента массива)
  • Example#4 - Пример использования управляющих структур и функций
  • Example#5 - Смешение режимов HTML и PHP
  • Example#6 - Простейшая форма HTML
  • Example#7 - Выводим данные формы
  • Example#8 - Инструкция по установке PHP, как подгружаемого модуля Apache
  • Example#9 - Инструкция по статической сборке PHP и Apache
  • Example#10 - Примеры команд перезапуска Apache
  • Example#11 -
  • Example#12 -
  • Example#13 -
  • Example#14 -
  • Example#15 -
  • Example#16 -
  • Example#17 -
  • Example#18 -
  • Example#19 -
  • Example#20 -
  • Example#21 -
  • Example#22 -
  • Example#23 -
  • Example#24 -
  • Example#25 -
  • Example#26 - Пример части файла lighttpd.conf
  • Example#27 - Создание FastCGI-обработчиков
  • Example#28 - Подключение к удаленным процессам fastcgi
  • Example#29 - OpenBSD Package Install Example
  • Example#30 - Debian Install Example with Apache 2
  • Example#31 - Stopping and starting Apache once PHP is installed
  • Example#32 - Methods for listing additional PHP 5 packages
  • Example#33 - Install PHP with MySQL, cURL
  • Example#34 - Структура пакета PHP 5
  • Example#35 - CGI and FastCGI settings in php.ini
  • Example#36 - Configuring FastCGI extension to handle PHP requests
  • Example#37 - Configuring file access permissions
  • Example#38 - Configuring FastCGI and PHP recycling
  • Example#39 - Configuring FastCGI timeout settings
  • Example#40 - Changing the location of php.ini file
  • Example#41 - CGI и FastCGI настройки в php.ini
  • Example#42 - Создание IIS FastCGI пула процессов
  • Example#43 - Создание сопоставления обработчика запросов PHP
  • Example#44 - определение аккаунта, используемого IIS при анонимной идентификации
  • Example#45 - Настройка разрешения доступа к файлам
  • Example#46 - Установка index.php как документ по умолчанию в IIS
  • Example#47 - Настройка FastCGI и PHP утилизации
  • Example#48 - Конфигурация установок таймаута FastCGI
  • Example#49 - Изменение положения файла php.ini
  • Example#50 - PHP как модуль Apache 1.3.x
  • Example#51 - PHP и Apache 1.3.x как CGI
  • Example#52 - PHP как обработчик Apache 2.x
  • Example#53 -
  • Example#54 - PHP как CGI под Apache 2.x
  • Example#55 - Конфигурация Apache для запуска PHP как FastCGI
  • Example#56 - Конфигурация ISAPI для Sambar
  • Example#57 - Включение расширения Bzip2 в PHP-Windows
  • Example#58 - Изменения реестра
  • Example#59 - Передача переменных окружения и настроек PHP пулу
  • Example#60 - Вызов phpinfo
  • Example#61 - Пример php.ini
  • Example#62 - Пример конфигурации Apache
  • Example#63 -
  • Example#64 - Продвинутое изолирование с использованием условий
  • Example#65 - Открывающие и закрывающие теги PHP
  • Example#66 - Целые числа
  • Example#67 - Странности с восьмеричными числами
  • Example#68 - Переполнение целых на 32-битных системах
  • Example#69 - Переполнение целых на 64-битных системах
  • Example#70 - Неверный пример
  • Example#71 - Пример определения heredoc-строки
  • Example#72 - Пример применения heredoc в аргументах
  • Example#73 - Использование heredoc для инциализации статических переменных
  • Example#74 - Использование двойных кавычек в heredoc
  • Example#75 - Пример использования nowdoc
  • Example#76 - Пример использования статичных данных
  • Example#77 - Пример простого синтаксиса
  • Example#78 - Несколько примеров строк
  • Example#79 - Простой массив
  • Example#80 - Пример преобразования типов и перезаписи элементов
  • Example#81 - Смешанные ключи типов integer и string
  • Example#82 - Индексированные массивы без ключа
  • Example#83 - Ключи для некоторых элементов
  • Example#84 - Доступ к элементам массива
  • Example#85 - Разыменование массива
  • Example#86 - Использование array()
  • Example#87 - Коллекция
  • Example#88 - Изменение элемента в цикле
  • Example#89 - Индекс, начинающийся с единицы
  • Example#90 - Заполнение массива
  • Example#91 - Сортировка массива
  • Example#92 - Рекурсивные и многомерные массивы
  • Example#93 - Callback function examples
  • Example#94 - Callback example using a Closure
  • Example#95 - Значения по умолчанию в неинициализированных переменных
  • Example#96 - Использование global
  • Example#97 - Использование $GLOBALS вместо global
  • Example#98 - Суперглобальные переменные и область видимости
  • Example#99 - Демонстрация необходимости статических переменных
  • Example#100 - Пример использования статических переменных
  • Example#101 - Статические переменные и рекурсивные функции
  • Example#102 - Объявление статических переменных
  • Example#103 - Пример переменного имени свойства
  • Example#104 - Простая HTML-форма
  • Example#105 - Доступ к данным из простой HTML POST-формы
  • Example#106 - Более сложные переменные формы
  • Example#107 - Пример использования setcookie
  • Example#108 - Правильные и неправильные имена констант
  • Example#109 - Определение констант
  • Example#110 - Определение констант с помощью ключевого слова const
  • Example#111 - Ассоциативность
  • Example#112 - Присваивание по ссылке
  • Example#113 - Побитовыми операции И, ИЛИ и ИСКЛЮЧАЮЩЕЕ ИЛИ (AND, OR и XOR) над целыми числами
  • Example#114 - Побитовая операция ИСКЛЮЧАЮЩЕЕ ИЛИ (XOR) над строками
  • Example#115 - Побитовый сдвиг над целыми числами
  • Example#116 - Алгоритм сравнения обычных массивов
  • Example#117 - Присваивание значения по умолчанию
  • Example#118 - Неочевидное поведение тернарного оператора
  • Example#119 - Арифметические операции с символьными переменными
  • Example#120 - Объяснение логических операторов
  • Example#121 - Сравнение массивов
  • Example#122 - Использование instanceof с классами
  • Example#123 - Использование instanceof с наследуемыми классами
  • Example#124 - Использование instanceof для проверки того, что объект не является экземпляром класса
  • Example#125 - Использование instanceof для класса
  • Example#126 - Использование instanceof с другими переменными
  • Example#127 - Избежание поиска класса и фатальных ошибок с instanceof в PHP 5.0
  • Example#128 - Оператор switch
  • Example#129 - Оператор switch допускает сравнение со строками
  • Example#130 - Пример использования тика
  • Example#131 - Пример использования тиков
  • Example#132 - Определение кодировки для скрипта.
  • Example#133 - Простой пример include
  • Example#134 - Включение внутри функции
  • Example#135 - Пример include через HTTP
  • Example#136 - Сравнение возвращаемого значения при include
  • Example#137 - Выражения include и return
  • Example#138 - Использование буферизинованного вывода для включения PHP файла в строку
  • Example#139 - Пример include_once в регистро-независимых ОС для PHP 4
  • Example#140 - Пример использования goto
  • Example#141 - Пример использования goto в цикле
  • Example#142 - Следующий пример работать не будет
  • Example#143 - Псевдокод для демонстрации использования функций
  • Example#144 - Функции, зависящие от условий
  • Example#145 - Вложенные функции
  • Example#146 - Рекурсивные функции
  • Example#147 - Передача массива в функцию
  • Example#148 - Передача аргументов по ссылке
  • Example#149 - Использование значений по умолчанию в определении функции
  • Example#150 - Использование нескалярных типов в качестве значений по умолчанию
  • Example#151 - Некорректное использование значений по умолчанию
  • Example#152 - Корректное использование значений по умолчанию
  • Example#153 - Использование конструкции return
  • Example#154 - Возврат нескольких значений в виде массива
  • Example#155 - Возврат результата по ссылке
  • Example#156 - Работа с функциями посредством переменных
  • Example#157 - Обращение к методам класса посредством переменных
  • Example#158 - Пример вызова переменного метода со статическим свойством
  • Example#159 - Пример анонимной функции
  • Example#160 - Пример присвоения анонимной функции переменной
  • Example#161 - Замыкания и область видимости
  • Example#162 - Простое определение класса
  • Example#163 - Переменная $this
  • Example#164 - Создание экземпляра класса
  • Example#165 - Присваивание объекта
  • Example#166 - Создание новых объектов
  • Example#167 - Простое наследование классов
  • Example#168 - Определение свойств
  • Example#169 - Пример использования nowdoc для инициализации свойств
  • Example#170 - Объявление и использование константы
  • Example#171 - Пример со статичными данными
  • Example#172 - Пример автоматической загрузки
  • Example#173 - Еще один пример автоматической загрузки
  • Example#174 - Автоматическая загрузка с перехватом исключения в версиях 5.3.0+
  • Example#175 - Автоматическая загрузка с перехватом исключения в версиях 5.3.0+ - Класс пользовательского исключения не подгружен
  • Example#176 - Использование унифицированных конструкторов
  • Example#177 - Конструкторы в классах, находящихся в пространстве имен
  • Example#178 - Пример использования деструктора
  • Example#179 - Объявление свойства класса
  • Example#180 - Объявление метода
  • Example#181 - Доступ к элементам с модификатором private из объектов одного типа
  • Example#182 - Пример наследования
  • Example#183 - Использование :: вне объявления класса
  • Example#184 - Использование :: внутри объявления класса
  • Example#185 - Обращение к методу в родительском классе
  • Example#186 - Пример статического свойства
  • Example#187 - Пример статического метода
  • Example#188 - Пример абстрактного класса
  • Example#189 - Пример интерфейса
  • Example#190 - Расширяемые интерфейсы
  • Example#191 - Множественное наследование интерфейсов
  • Example#192 - Интерфейсы с константами
  • Example#193 - Пример использования трейта
  • Example#194 - Пример приоритета старшинства
  • Example#195 - Пример альтернативного порядка приоритета
  • Example#196 - Пример использования нескольких трейтов
  • Example#197 - Пример разрешения конфликтов
  • Example#198 - Пример изменения видимости метода
  • Example#199 - Пример трейтов, скомпонованных из трейтов
  • Example#200 - Экпресс требования с абстрактными методами
  • Example#201 - Статические переменные
  • Example#202 - Статические методы
  • Example#203 - Определение свойств
  • Example#204 - Разрешение конфликтов
  • Example#205 - Перегрузка свойств с помощью методов __get(), __set(), __isset() и __unset()
  • Example#206 - Перегрузка методов с помощью методов __call() и __callStatic()
  • Example#207 - Итерация простого объекта
  • Example#208 - Объект Iteration, реализующий интерфейс Iterator
  • Example#209 - Объект Iteration, реализующий интерфейс IteratorAggregate
  • Example#210 - Параметризированный фабричный метод
  • Example#211 - Пример Синглтона
  • Example#212 - Sleep и wakeup
  • Example#213 - Простой пример
  • Example#214 - Использование __invoke()
  • Example#215 - Использование __set_state() (начиная с PHP 5.1.0)
  • Example#216 - Пример окончательных (final) методов
  • Example#217 - Пример окончательного (final) класса
  • Example#218 - Клонирование объекта
  • Example#219 - Пример сравнения объектов в PHP 5
  • Example#220 - Пример контроля типов
  • Example#221 - Использование self::
  • Example#222 - Простое использованиеstatic::
  • Example#223 - Использование static:: в нестатическом контексте
  • Example#224 - Перенаправленные и не перенаправленные вызовы
  • Example#225 - Ссылки и объекты
  • Example#226 - Пример синтаксиса, использующего пространство имен
  • Example#227 - Объявление единого пространства имен
  • Example#228 - Объявление простого пространства имен
  • Example#229 - Определение пространства имен с иерархией
  • Example#230 - Описание нескольких пространств имен, простой синтаксис
  • Example#231 - Описание нескольких пространств имен, синтаксис со скобками
  • Example#232 - Описание глобального и обычного пространства имен в одном файле
  • Example#233 - Описание глобального и обычного пространства имен в одном файле
  • Example#234 - Доступ к глобальным классам, функциям и константам из пространства имен
  • Example#235 - Динамически доступные элементы
  • Example#236 - Динамически доступные элементы пространства имен
  • Example#237 - Пример использование константы __NAMESPACE__ в коде с пространством имен
  • Example#238 - Пример использование константы __NAMESPACE__ в глобальном пространстве
  • Example#239 - использование константы __NAMESPACE__ для динамического конструирования имени
  • Example#240 - Оператор namespace, внутри пространства имен
  • Example#241 - Оператор namespace в глобальном коде
  • Example#242 - импорт/создание псевдонима имени с помощью оператора use
  • Example#243 - импорт/создание псевдонима имени с помощью оператора use, комбинирование нескольких операторов use
  • Example#244 - Импорт и динамические имена
  • Example#245 - Импортирование и абсолютные имена
  • Example#246 - Недопустимое правило импорта
  • Example#247 - Использованиие глобального пространства и его задание
  • Example#248 - Доступ к глобальным классам внутри пространства имен
  • Example#249 - Необходимость прибегнуть к глобальным функциям/константам внутри пространства имен
  • Example#250 - Примеры разрешения имен
  • Example#251 - Доступ к глобальным классам вне пространства имен
  • Example#252 - Доступ к глобальным классам вне пространства имен
  • Example#253 - Доступ ко внутренним классам в пространствах имен
  • Example#254 - Доступ ко внутренним классам, функциям или константам в пространствах имен
  • Example#255 - Абсолютные имена
  • Example#256 - Полные имена
  • Example#257 - Неполные имена классов
  • Example#258 - Неполные имена функций или констант
  • Example#259 - Подводные камни при использовании имени пространства имен внутри строки с двойными кавычками
  • Example#260 - Неопределенные константы
  • Example#261 - Неопределенные константы
  • Example#262 - Выброс исключений
  • Example#263 - Вложенные исключения
  • Example#264 - Встроеный класс Exception
  • Example#265 - Наследование класса Exception (PHP 5.3.0+)
  • Example#266 - Использование ссылок с неинициализированными переменными
  • Example#267 - Присвоение ссылок глобальным переменным внутри функции
  • Example#268 - Ссылки и foreach
  • Example#269 - Пример $GLOBALS
  • Example#270 - Пример использования $_SERVER
  • Example#271 - Пример использования $_GET
  • Example#272 - Пример использования $_POST
  • Example#273 - Пример использования $_ENV
  • Example#274 - Пример использования $_COOKIE
  • Example#275 - Пример $php_errormsg
  • Example#276 - Пример $http_response_header
  • Example#277 - Пример использования $argc
  • Example#278 - Пример использования$argv
  • Example#279 - Пример использования Exception::getMessage
  • Example#280 - Пример использования Exception::getPrevious
  • Example#281 - Пример использования Exception::getCode
  • Example#282 - Пример использования Exception::getFile
  • Example#283 - Пример использования Exception::getLine
  • Example#284 - Пример использования Exception::getTrace
  • Example#285 - Пример использования Exception::getTraceAsString
  • Example#286 - Пример использования Exception::__toString
  • Example#287 - Используем set_error_handler для превращения сообщений об ошибках в ErrorException.
  • Example#288 - Пример использования ErrorException::getSeverity
  • Example#289 - Основы использования
  • Example#290 - Основы использования
  • Example#291 - Основы использования
  • Example#292 - Пример использования ArrayAccess::offsetExists
  • Example#293 - Основы использования
  • Example#294 - Пример Closure::bind
  • Example#295 - Пример Closure::bindTo
  • Example#296 - Пример использования bindto
  • Example#297 - Извлечь страницу и отправить данные методом POST
  • Example#298 - Игнорировать переадресации, но извлечь заголовки и содержимое
  • Example#299 - Получает страницу и посылает POST-запрос
  • Example#300 - Определение URL, с которого был забран документ после переадресаций
  • Example#301 - Отправка пользовательских заголовков вместе с HTTP-запросом
  • Example#302 - php://temp/maxmemory
  • Example#303 - php://filter/resource=<поток для фильтрации>
  • Example#304 - php://filter/read=<список фильтров для применения к цепочке чтения>
  • Example#305 - php://filter/write=<список фильтров для применения к цепочке записи>
  • Example#306 - Вывод содержимого data://
  • Example#307 - Получение типа потока
  • Example#308 - Основы использования
  • Example#309 - Открытие потока из активного соединения
  • Example#310 - Обход RAR-архива
  • Example#311 - Открытие зашифрованного файла (шифрование заголовка)
  • Example#312 - Недостаточная проверка внешних данных ведет к...
  • Example#313 - ... атаке на файловую систему
  • Example#314 - Более безопасная проверка имени файла
  • Example#315 - Более строгая проверка имени файла
  • Example#316 - Скрипт, уязвимый к нулевому байту
  • Example#317 - Correctly validating the input
  • Example#318 - Использование хешированных паролей
  • Example#319 - Постраничный вывод результата... и создание суперпользователя в PostgreSQL
  • Example#320 - Листинг статей... и некоторых паролей (для любой базы данных)
  • Example#321 - От восстановления пароля... до получения дополнительных привилегий (для любой базы данных)
  • Example#322 - Выполнение команд операционной системы на сервере (для базы MSSQL)
  • Example#323 - Более безопасная реализация постраничной навигации
  • Example#324 - Атака на переменные в HTML-странице
  • Example#325 - Использование стандартных отладочных переменных
  • Example#326 - Поиск потенциально опасных переменных при помощи E_ALL
  • Example#327 - Пример опасного кода с register_globals = on
  • Example#328 - Пример использования сессий со значением register_globals on или off
  • Example#329 - Обнаружение попытки подмены переменных
  • Example#330 - Потенциально опасное использование переменных
  • Example#331 - Отключение волшебных кавычек на сервере
  • Example#332 - Отключение волшебных кавычек во время выполнения скрипта
  • Example#333 - Маскировка PHP под другие языки программирования
  • Example#334 - Использование неизвестных расширений для PHP-скриптов
  • Example#335 - Маскировка PHP-кода под HTML-файлы
  • Example#336 - Пример Basic HTTP-аутентификации
  • Example#337 - Пример Digest HTTP-аутентификации
  • Example#338 - Пример HTTP-аутентификации с принудительным вводом новой пары логин/пароль
  • Example#339 - Простая поисковая форма XForms
  • Example#340 - Использование XForm совместно с массивом $_POST
  • Example#341 - Форма для загрузки файлов
  • Example#342 - Проверка загружаемых на сервер файлов
  • Example#343 - Загрузка массива файлов
  • Example#344 - Загрузка нескольких файлов
  • Example#345 - Saving HTTP PUT files
  • Example#346 - Получение заголовка удаленной страницы
  • Example#347 - Сохранение данных на удаленном сервере
  • Example#348 - Пример, демонстрирующий отличие CGI SAPI:
  • Example#349 -
  • Example#350 - Вывод встроенных (и загружаемых) PHP и Zend модулей
  • Example#351 - Ошибка синтаксиса при использовании двойных кавычек
  • Example#352 - Использование одинарных кавычек для предотвращения подстановки переменных в консоли
  • Example#353 - Использование опций -B, -R и -E для подсчета количества строк в проекте.
  • Example#354 - Использование -v для получения типа SAPI и версии PHP и Zend
  • Example#355 - Пример --ini
  • Example#356 - Базовое использование --rf
  • Example#357 - Пример --rc
  • Example#358 - Пример --re
  • Example#359 - Пример --ri
  • Example#360 - Запуск PHP-скрипта как консольного
  • Example#361 - Скрипт, предназначенный для запуска из командной строки (script.php)
  • Example#362 - Пакетный файл для запуска PHP-скрипта из командной строки (script.bat)
  • Example#363 - Запуск кода в интерактивной консоли
  • Example#364 - Автодополнение по Tab
  • Example#365 - Установка настройки php.ini в интерактивной консоли
  • Example#366 - Запуск web-сервера
  • Example#367 - Запуск с указанием корневой директории
  • Example#368 - Использование скрипта маршрутизации
  • Example#369 - Создание нового контейнера zval
  • Example#370 - Вывод информации о zval
  • Example#371 - Увеличение счетчика ссылок zval
  • Example#372 - Уменьшение счетчика ссылок zval
  • Example#373 - Создание array zval
  • Example#374 - Добавление уже существующего элемента в массив
  • Example#375 - Удаление элемента из массива
  • Example#376 - Добавление массива новым элементом в самого себя
  • Example#377 - Удаление $a
  • Example#378 - Пример использования памяти
  • Example#379 - Влияние на производительность
  • Example#380 - Запуск скрипта
  • Example#381 - Сборка PHP для включения теста производительности GC
  • Example#382 - Статистика GC
  • Example#383 - An apc.rfc1867 example
  • Example#384 - A apc_add example
  • Example#385 - apc_bin_load example
  • Example#386 - A apc_cache_info example
  • Example#387 - apc_cas example
  • Example#388 - apc_dec example
  • Example#389 - apc_define_constants example
  • Example#390 - apc_delete_file example
  • Example#391 - A apc_delete example
  • Example#392 - apc_exists example
  • Example#393 - A apc_fetch example
  • Example#394 - apc_inc example
  • Example#395 - apc_load_constants example
  • Example#396 - A apc_sma_info example
  • Example#397 - A apc_store example
  • Example#398 - A APCIterator::__construct example
  • Example#399 - Typical session using tcplisten
  • Example#400 - Пример использования apd_callstack
  • Example#401 - Пример использования apd_clunk
  • Example#402 - apd_continue example
  • Example#403 - apd_croak example
  • Example#404 - apd_dump_function_table example
  • Example#405 - apd_dump_persistent_resources example
  • Example#406 - apd_dump_regular_resources example
  • Example#407 - apd_echo example
  • Example#408 - apd_get_active_symbols example
  • Example#409 - apd_set_pprof_trace example
  • Example#410 - apd_set_session_trace_socket example
  • Example#411 - apd_set_session_trace example
  • Example#412 - apd_set_session example
  • Example#413 - override_function example
  • Example#414 - rename_function example
  • Example#415 - bcompiler_load_exe example
  • Example#416 - bcompiler_load example
  • Example#417 - bcompiler_parse_class example
  • Example#418 - bcompiler_read example
  • Example#419 - bcompiler_write_class example
  • Example#420 - bcompiler_write_constant example
  • Example#421 - bcompiler_write_exe_footer example
  • Example#422 - bcompiler_write_file example
  • Example#423 - bcompiler_write_footer example
  • Example#424 - bcompiler_write_function example
  • Example#425 - bcompiler_write_functions_from_file example
  • Example#426 - bcompiler_write_header example
  • Example#427 - Обработка ошибок в скрипте
  • Example#428 - Пример использования debug_backtrace
  • Example#429 - Пример использования debug_print_backtrace
  • Example#430 - Пример использования error_get_last
  • Example#431 - Примеры использования error_log
  • Example#432 - Примеры использования error_reporting
  • Example#433 - Пример использования restore_error_handler
  • Example#434 - Пример использования restore_exception_handler
  • Example#435 - Обработка ошибок с помощью функций set_error_handler и trigger_error
  • Example#436 - Пример использования set_exception_handler
  • Example#437 - Пример использования trigger_error
  • Example#438 - Getting the data within the PHP application itself (function)
  • Example#439 - Example use of gengraph.php
  • Example#440 - Listing data via inclued dumps (configuration)
  • Example#441 - inclued_get_data example
  • Example#442 - Creating large array in a function
  • Example#443 - Пример контроля вывода
  • Example#444 - Пример использования функции ob_end_clean
  • Example#445 - Пример использования функции ob_end_flush
  • Example#446 - Простой пример использования функции ob_get_clean
  • Example#447 - Простой пример использования функции ob_get_contents
  • Example#448 - Пример использования функции ob_get_flush
  • Example#449 - Простой пример использования функции ob_get_length
  • Example#450 - Пример использования функции ob_gzhandler
  • Example#451 - Пример использования функции ob_list_handlers
  • Example#452 - Пример callback-функции, определенной пользователем
  • Example#453 - Пример использования функции output_add_rewrite_var
  • Example#454 - Пример использования функции output_reset_rewrite_vars
  • Example#455 - Overloading a PHP class
  • Example#456 - Пример использования assert_options
  • Example#457 - Обработка ошибочного утверждения пользовательским обработчиком
  • Example#458 - Примеры использования dl
  • Example#459 - Пример использования extension_loaded
  • Example#460 - Пример использования gc_enabled
  • Example#461 - Пример использования get_current_user
  • Example#462 - Пример использвания get_defined_constants
  • Example#463 - Выводит XML функции
  • Example#464 - Пример использования get_include_path
  • Example#465 - Пример использования get_included_files
  • Example#466 - Пример использования get_loaded_extensions
  • Example#467 - Пример использования get_magic_quotes_gpc
  • Example#468 - Пример использования get_magic_quotes_runtime
  • Example#469 - Пример использования getenv
  • Example#470 - Пример использования getlastmod
  • Example#471 - Пример использования getopt
  • Example#472 - Пример использования getopt №2
  • Example#473 - Пример использования getopt №3
  • Example#474 - Пример использования getrusage
  • Example#475 - Примеры использования ini_get_all
  • Example#476 - Отключение details
  • Example#477 - Несколько примеров использования ini_get
  • Example#478 - Пример использования ini_restore
  • Example#479 - Установка значения ini настройки
  • Example#480 - A memory_get_usage example
  • Example#481 - php_ini_loaded_file example
  • Example#482 - A simple example to list the returned ini files
  • Example#483 - php_logo_guid example
  • Example#484 - php_sapi_name example
  • Example#485 - Some php_uname examples
  • Example#486 - A few OS related constant examples
  • Example#487 - Prints the general credits
  • Example#488 - Prints the core developers and the documentation group
  • Example#489 - Printing all the credits
  • Example#490 - phpinfo Example
  • Example#491 - phpversion example
  • Example#492 - PHP_VERSION_ID example and usage
  • Example#493 - Setting an environment variable
  • Example#494 - restore_include_path example
  • Example#495 - set_include_path example
  • Example#496 - Adding to the include path
  • Example#497 - set_magic_quotes_runtime example
  • Example#498 - sys_get_temp_dir example
  • Example#499 - version_compare examples
  • Example#500 - zend_logo_guid example
  • Example#501 - zend_thread_id example
  • Example#502 - zend_version example
  • Example#503 - Пользовательские суперглобальные переменные при runkit.superglobal=_FOO,_BAR в php.ini
  • Example#504 - Пример создания безопасной песочницы
  • Example#505 - Работа с переменными в песочнице
  • Example#506 - Использование функций песочницы
  • Example#507 - Передача аргументов функциям в песочнице
  • Example#508 - Задействует возможность использовать Runkit_Sandbox_Parent в песочнице
  • Example#509 - Доступ к переменным родительского окружения
  • Example#510 - Пример runkit_class_adopt
  • Example#511 - Пример runkit_class_emancipate
  • Example#512 - Пример runkit_function_add
  • Example#513 - Пример runkit_function_copy
  • Example#514 - Пример runkit_function_redefine
  • Example#515 - Пример runkit_method_add
  • Example#516 - Пример runkit_method_copy
  • Example#517 - Пример runkit_method_redefine
  • Example#518 - Пример runkit_method_remove
  • Example#519 - Пример runkit_method_rename
  • Example#520 - Пример runkit_return_value_used
  • Example#521 - Перевод вывода в переменную
  • Example#522 - Enabling and disabling scream at runtime
  • Example#523 - Weakref usage example
  • Example#524 - WeakRef usage example
  • Example#525 - Weakref::acquire example
  • Example#526 - Nested acquire/release example
  • Example#527 - Weakref::__construct example
  • Example#528 - Weakref::release example
  • Example#529 - Weakmap usage example
  • Example#530 - wincache.ignorelist example
  • Example#531 - Authentication configuration for wincache.php
  • Example#532 - Enabling WinCache session handler
  • Example#533 - Enabling WinCache functions reroutes
  • Example#534 - Reroute.ini file content
  • Example#535 - A wincache_fcache_fileinfo example
  • Example#536 - A wincache_fcache_meminfo example
  • Example#537 - Using wincache_lock
  • Example#538 - A wincache_ocache_fileinfo example
  • Example#539 - A wincache_ocache_meminfo example
  • Example#540 - A wincache_refresh_if_changed example
  • Example#541 - A wincache_rplist_fileinfo example
  • Example#542 - A wincache_rplist_meminfo example
  • Example#543 - A wincache_scache_info example
  • Example#544 - A wincache_scache_meminfo example
  • Example#545 - wincache_ucache_add with key as a string
  • Example#546 - wincache_ucache_add with key as an array
  • Example#547 - Using wincache_ucache_cas
  • Example#548 - using wincache_ucache_clear
  • Example#549 - Using wincache_ucache_dec
  • Example#550 - Using wincache_ucache_delete with key as a string
  • Example#551 - Usingwincache_ucache_delete with key as an array
  • Example#552 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#553 - Using wincache_ucache_exists
  • Example#554 - wincache_ucache_get with key as a string
  • Example#555 - wincache_ucache_get with key as an array
  • Example#556 - Using wincache_ucache_inc
  • Example#557 - Using wincache_ucache_info
  • Example#558 - A wincache_ucache_meminfo example
  • Example#559 - wincache_ucache_set with key as a string
  • Example#560 - wincache_ucache_set with key as an array
  • Example#561 - Using wincache_unlock
  • Example#562 - Xhprof example with the optional GUI
  • Example#563 - xhprof_disable example
  • Example#564 - xhprof_enable examples
  • Example#565 - xhprof_sample_disable example
  • Example#566 - Пример использования id3_get_frame_long_name
  • Example#567 - Пример использования id3_get_frame_short_name
  • Example#568 - Пример использования id3_get_genre_id
  • Example#569 - Пример использования id3_get_genre_list
  • Example#570 - Пример использования id3_get_genre_name
  • Example#571 - Пример использования id3_get_tag
  • Example#572 - Пример использования id3_get_tag
  • Example#573 - Примеры использования id3_get_version
  • Example#574 - id3_remove_tag example
  • Example#575 - Пример использования id3_set_tag
  • Example#576 - Opens a new MP3 file and read the title
  • Example#577 - Reading an OGG/Vorbis file
  • Example#578 - Encode an audio file to OGG/Vorbis
  • Example#579 - KADM5 extension overview example
  • Example#580 - Example of changing principal's password
  • Example#581 - Example of principal's creation
  • Example#582 - kadm5_delete_principal example
  • Example#583 - kadm5_get_policies example
  • Example#584 - kadm5_get_principal example
  • Example#585 - kadm5_get_principals example
  • Example#586 - KADM5 initialization example
  • Example#587 - Example of modifying principal
  • Example#588 - radius_acct_open example
  • Example#589 - radius_add_server example
  • Example#590 - radius_auth_open example
  • Example#591 - radius_create_request example
  • Example#592 - radius_cvt_addr example
  • Example#593 - radius_cvt_int example
  • Example#594 - radius_cvt_string example
  • Example#595 - radius_get_attr example
  • Example#596 - radius_get_vendor_attr example
  • Example#597 - radius_put_attr example
  • Example#598 - radius_put_int example
  • Example#599 - radius_put_string example
  • Example#600 - radius_put_vendor_attr example
  • Example#601 - Пример использования cal_days_in_month
  • Example#602 - Пример использования cal_from_jd
  • Example#603 - Пример cal_info
  • Example#604 - Пример использования easter_date
  • Example#605 - Пример использования easter_days
  • Example#606 - Календарные функции
  • Example#607 - Пример использования jdtojewish
  • Example#608 - Пример использования DateTime::add
  • Example#609 - Другие примеры с DateTime::add
  • Example#610 - Будьте внимательны при добавлении месяцев
  • Example#611 - Пример использования DateTime::__construct
  • Example#612 - Хитрости при использовании DateTime::__construct
  • Example#613 - Пример использования DateTime::createFromFormat
  • Example#614 - Хитрости при использовании DateTime::createFromFormat
  • Example#615 - Пример использования DateTime::diff
  • Example#616 - Сравнение объектов DateTime
  • Example#617 - Пример использования DateTime::format
  • Example#618 - Пример использования DateTime::getLastErrors
  • Example#619 - Пример использования DateTime::getOffset
  • Example#620 - Пример использования DateTime::getTimestamp
  • Example#621 - Пример использования DateTime::getTimezone
  • Example#622 - Пример использования DateTime::modify
  • Example#623 - Будьте осторожны при добавлении и вычитании месяцев
  • Example#624 - Пример использования DateTime::setDate
  • Example#625 - Значения, превышающие диапазон своего поля, добавляются к старшим полям
  • Example#626 - Пример использования DateTime::setISODate
  • Example#627 - Значения, превышающие допустимые пределы, добавляются к старшим полям
  • Example#628 - Поиск месяца по номеру недели
  • Example#629 - Пример использования DateTime::setTime
  • Example#630 - Значения, превышающие диапазон своего поля, добавляются к старшим полям
  • Example#631 - Пример использования DateTime::setTimestamp
  • Example#632 - Использование DateTime::setTimestamp в качестве альтернативы в PHP 5.2
  • Example#633 - Пример использования DateTime::setTimeZone
  • Example#634 - Пример использования DateTime::sub
  • Example#635 - Другие примеры DateTime::sub
  • Example#636 - Будьте внимательны при вычитании месяцев
  • Example#637 - Фиксация ошибок при создании экземпляра DateTimeZone
  • Example#638 - Пример использования DateTimeZone::getLocation
  • Example#639 - Пример использования DateTimeZone::getOffset
  • Example#640 - Пример использования timezone_transitions_get
  • Example#641 - Пример использования timezone_abbreviations_list
  • Example#642 - Пример использования timezone_identifiers_list
  • Example#643 - Пример использования DateInterval
  • Example#644 - Пример использования DateInterval
  • Example#645 - DateInterval и перенос единиц
  • Example#646 - DateInterval и DateTime::diff с модификаторами %a и %d
  • Example#647 - Пример использования функции checkdate
  • Example#648 - Получение временной зоны по умолчанию
  • Example#649 - Получение аббревиатуры временной зоны
  • Example#650 - Получение временной зоны по умолчанию
  • Example#651 - Пример использования date_parse_from_format
  • Example#652 - Пример использования date_parse
  • Example#653 - Пример использования date_sun_info
  • Example#654 - Пример использования date_sunrise
  • Example#655 - Пример исользования date_sunset
  • Example#656 - Примеры использования функции date
  • Example#657 - Экранирование символов в функции date
  • Example#658 - Пример совместного использования функций date и mktime
  • Example#659 - Форматирование с использованием date
  • Example#660 - Пример использования функции getdate
  • Example#661 - Пример использования функции gettimeofday
  • Example#662 - Пример использования gmdate
  • Example#663 - Базовый пример использования gmmktime
  • Example#664 - Пример использования функции gmstrftime
  • Example#665 - Пример использования idate
  • Example#666 - Пример использования localtime
  • Example#667 - Замер времени выполнения скрипта с помощью функции microtime
  • Example#668 - Замер времени выполнения скрипта в PHP 5
  • Example#669 - Пример использования функции mktime
  • Example#670 - mktime example
  • Example#671 - Последний день месяца
  • Example#672 - Пример использования функции strftime с разными локалями
  • Example#673 - Пример номеров недели по ISO 8601:1988
  • Example#674 - Кросплатформенный пример использования модификатора %e
  • Example#675 - Показываем все известные и неизвестные форматы.
  • Example#676 - Пример использования strptime
  • Example#677 - Пример использования функции strtotime
  • Example#678 - Проверка ошибок
  • Example#679 - Пример использования time
  • Example#680 - Пример использования timezone_name_from_abbr
  • Example#681 - Определение версии базы данных временных зон
  • Example#682 - Writing a string with a specified color to the screen
  • Example#683 - ncurses_getmouse example
  • Example#684 - Writing a string with a specified color to the screen
  • Example#685 - Writing a string with a specified color to the screen
  • Example#686 - ncurses_mousemask example
  • Example#687 - Writing a string with a specified color to the screen
  • Example#688 - Newt Usage Example
  • Example#689 - A newt_button example
  • Example#690 - A newt_draw_root_text example
  • Example#691 - A newt_form_add_component example
  • Example#692 - A newt_form_add_components example
  • Example#693 - A newt_form example
  • Example#694 - A newt_get_screen_size example
  • Example#695 - A newt_win_entries example
  • Example#696 - Readline Callback Interface Example
  • Example#697 - readline Example
  • Example#698 - Пример работы с bzip2
  • Example#699 - Сжатие данных
  • Example#700 - Распаковка строки
  • Example#701 - Пример использования bzerror
  • Example#702 - Пример использования bzopen
  • Example#703 - Пример использования bzread
  • Example#704 - Пример использования bzwrite
  • Example#705 - Using an external file
  • Example#706 - Using a file within a phar archive
  • Example#707 - Converting a phar archive from phar to tar file format
  • Example#708 - phar.extract_list usage example
  • Example#709 - phar.cache_list usage example
  • Example#710 - A Phar::addEmptyDir example
  • Example#711 - A Phar::addFile example
  • Example#712 - A Phar::addFromString example
  • Example#713 - A Phar::apiVersion example
  • Example#714 - A Phar::buildFromDirectory example
  • Example#715 - A Phar::buildFromIterator with SplFileInfo
  • Example#716 - A Phar::buildFromIterator with other iterators
  • Example#717 - A Phar::canCompress example
  • Example#718 - A Phar::canWrite example
  • Example#719 - A Phar::compress example
  • Example#720 - A Phar::compressAllFilesBZIP2 example
  • Example#721 - A Phar::compressAllFilesGZ example
  • Example#722 - A Phar::compressFiles example
  • Example#723 - A Phar::__construct example
  • Example#724 - A Phar::convertToData example
  • Example#725 - A Phar::convertToExecutable example
  • Example#726 - A Phar::copy example
  • Example#727 - A Phar::count example
  • Example#728 - A Phar::createDefaultStub example
  • Example#729 - A Phar::decompress example
  • Example#730 - A Phar::decompressFiles example
  • Example#731 - A Phar::delMetaData example
  • Example#732 - A Phar::delete example
  • Example#733 - A Phar::extractTo example
  • Example#734 - A Phar::getMetadata example
  • Example#735 - A Phar::getStub example
  • Example#736 - A Phar::hasMetadata example
  • Example#737 - A Phar::interceptFileFuncs example
  • Example#738 - A Phar::interceptFileFuncs example
  • Example#739 - A Phar::isBuffering example
  • Example#740 - A Phar::isCompressed example
  • Example#741 - A Phar::loadPhar example
  • Example#742 - A Phar::mapPhar example
  • Example#743 - A Phar::mount example
  • Example#744 - A Phar::mungServer example
  • Example#745 - A Phar::offsetExists example
  • Example#746 - Phar::offsetGet example
  • Example#747 - A Phar::offsetSet example
  • Example#748 - A Phar::offsetUnset example
  • Example#749 - A Phar::running example
  • Example#750 - A Phar::setAlias example
  • Example#751 - A Phar::setDefaultStub example
  • Example#752 - A Phar::setMetadata example
  • Example#753 - A Phar::setStub example
  • Example#754 - A Phar::startBuffering example
  • Example#755 - A Phar::stopBuffering example
  • Example#756 - A Phar::uncompressAllFiles example
  • Example#757 - A Phar::unlinkArchive example
  • Example#758 - A Phar::webPhar example
  • Example#759 - A PharData::addEmptyDir example
  • Example#760 - A PharData::addFile example
  • Example#761 - A PharData::addFromString example
  • Example#762 - A PharData::buildFromDirectory example
  • Example#763 - A PharData::buildFromIterator with SplFileInfo
  • Example#764 - A PharData::buildFromIterator with other iterators
  • Example#765 - A PharData::compress example
  • Example#766 - A PharData::compressFiles example
  • Example#767 - A PharData::__construct example
  • Example#768 - A PharData::convertToData example
  • Example#769 - A PharData::convertToExecutable example
  • Example#770 - A PharData::copy example
  • Example#771 - A PharData::decompress example
  • Example#772 - A PharData::decompressFiles example
  • Example#773 - A PharData::delMetaData example
  • Example#774 - A PharData::delete example
  • Example#775 - A PharData::extractTo example
  • Example#776 - A PharData::offsetSet example
  • Example#777 - A PharData::offsetUnset example
  • Example#778 - A Phar::setMetadata example
  • Example#779 - A PharFileInfo::chmod example
  • Example#780 - A PharFileInfo::compress example
  • Example#781 - A PharFileInfo::__construct example
  • Example#782 - A PharFileInfo::decompress example
  • Example#783 - A PharFileInfo::delMetaData example
  • Example#784 - A PharFileInfo::getCRC32 example
  • Example#785 - A PharFileInfo::getCompressedSize example
  • Example#786 - A PharFileInfo::getMetadata example
  • Example#787 - A PharFileInfo::getPharFlags example
  • Example#788 - A PharFileInfo::isCRCChecked example
  • Example#789 - A PharFileInfo::isCompressed example
  • Example#790 - A PharFileInfo::isCompressedBZIP2 example
  • Example#791 - A PharFileInfo::isCompressedGZ example
  • Example#792 - A PharFileInfo::setCompressedBZIP2 example
  • Example#793 - A PharFileInfo::setCompressedGZ example
  • Example#794 - A PharFileInfo::setMetadata example
  • Example#795 - A PharFileInfo::setUncompressed example
  • Example#796 - Установка Rar
  • Example#797 - Декомпрессия на лету
  • Example#798 - Пример извлечения перечня файлов и директорий из RAR-архива
  • Example#799 - Объектно-ориентированный стиль
  • Example#800 - Процедурный стиль
  • Example#801 - Объектно-ориентированный стиль
  • Example#802 - Процедурный стиль
  • Example#803 - Объектно-ориентированный стиль
  • Example#804 - Процедурный стиль
  • Example#805 - Объектно-ориентированный стиль
  • Example#806 - Процедурный стиль
  • Example#807 - Объектно-ориентированный стиль
  • Example#808 - Процедурный стиль
  • Example#809 - Объектно-ориентированный стиль
  • Example#810 - Процедурный стиль
  • Example#811 - Объектно-ориентированный стиль
  • Example#812 - Процедурный стиль
  • Example#813 - Volume Callback
  • Example#814 - Объектно-ориентированный стиль
  • Example#815 - Процедурный стиль
  • Example#816 - RarArchive::__toString example
  • Example#817 - RarEntry::extract example
  • Example#818 - How to extract all files in archive:
  • Example#819 - RarEntry::getAttr example
  • Example#820 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#821 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#822 - RarEntry::getMethod example
  • Example#823 - RarEntry::getName example
  • Example#824 - RarEntry::getPackedSize example
  • Example#825 - RarEntry::getStream example
  • Example#826 - RarEntry::getUnpackedSize example
  • Example#827 - RarEntry::getVersion example
  • Example#828 - RarException::isUsingExceptions example
  • Example#829 - RarException::setUsingExceptions example
  • Example#830 - Создание Zip архива
  • Example#831 - Собрать и отобразить подробную информацию об архиве
  • Example#832 - Использование обертки потока Zip, чтение мета-информации OpenOffice
  • Example#833 - Пример использования Zip
  • Example#834 - Создание новой директории в архиве.
  • Example#835 - Открыть и разархивировать
  • Example#836 - Добавить запись в новый архив
  • Example#837 - Добавить файл в директорию внутри архива
  • Example#838 - Удалить файл из архива, используя его индекс
  • Example#839 - Удалить файл или каталог из архива по имени.
  • Example#840 - Извлечь все содержимое
  • Example#841 - Извлечь два элемента
  • Example#842 - Вывести комментарий архива
  • Example#843 - Вывести комментарий элемента
  • Example#844 - Вывести комментарий элемента
  • Example#845 - Получить содержимое файла
  • Example#846 - Получить содержимое файла
  • Example#847 - Преобразовать изображении из ZIP-элемента
  • Example#848 - Пример использования getnameindex
  • Example#849 - Получить сожержимое элемента при помощи fread и сохранить его
  • Example#850 - То же, что и в предыдущем примере, но используя fopen и через обертку zip-потока
  • Example#851 - ZIP-поток и изображение могут быть использованы также в функции XML
  • Example#852 - Создается архив и затем ипользуется метод ZipArchive::locateName
  • Example#853 - Открытие и извлечение
  • Example#854 - Создание архива
  • Example#855 - Переименование одного элемента
  • Example#856 - Переименование одного элемента
  • Example#857 - Создание архива и установка комментария
  • Example#858 - Открывает архив и устанавливает комментарий к элементу
  • Example#859 - Открытие архива и установка комментария к элементу
  • Example#860 - Получение статистической информации о элементе
  • Example#861 - Получение статистической информации о элементе
  • Example#862 - Небольшой пример использования Zlib
  • Example#863 - Пример использования gzclose
  • Example#864 - Пример использования gzcompress
  • Example#865 - Пример использования gzdeflate
  • Example#866 - Создание файла gzip
  • Example#867 - Пример использования gzeof
  • Example#868 - Пример использования gzfile
  • Example#869 - Пример использования gzgetc
  • Example#870 - Пример использования gzgets
  • Example#871 - Пример использования gzgetss
  • Example#872 - Пример использования gzinflate
  • Example#873 - Пример использования gzopen
  • Example#874 - Пример использования gzpassthru
  • Example#875 - Пример использования gzread
  • Example#876 - Пример использования gzseek
  • Example#877 - Пример использования gzuncompress
  • Example#878 - Пример использования gzwrite
  • Example#879 - Пример использования CrackLib
  • Example#880 - Пример использования hash_algos
  • Example#881 - Пример использования hash_copy
  • Example#882 - Использование hash_file
  • Example#883 - Пример использования hash_final
  • Example#884 - Пример использования hash_hmac_file
  • Example#885 - Пример использования hash_hmac
  • Example#886 - Пример инкриментального хеширования
  • Example#887 - Пример использования hash_update_stream
  • Example#888 - Пример использования hash
  • Example#889 - Encrypt an input value with TripleDES under 2.2.x in ECB mode
  • Example#890 - Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode
  • Example#891 - mcrypt_create_iv Example
  • Example#892 - mcrypt_enc_get_algorithms_name example
  • Example#893 - mcrypt_enc_get_modes_name example
  • Example#894 - mcrypt_enc_get_supported_key_sizes example
  • Example#895 - mcrypt_encrypt Example
  • Example#896 - mcrypt_get_block_size example
  • Example#897 - mcrypt_get_cipher_name Example
  • Example#898 - mcrypt_get_iv_size Example
  • Example#899 - mcrypt_get_key_size Example
  • Example#900 - mcrypt_list_algorithms Example
  • Example#901 - mcrypt_list_modes Example
  • Example#902 - mcrypt_module_open Examples
  • Example#903 - Using mcrypt_module_open in encryption
  • Example#904 - mcrypt_module_self_test example
  • Example#905 - mdecrypt_generic Example
  • Example#906 - Computes the MD5 digest and hmac and print it out as hex
  • Example#907 - Traversing all hashes
  • Example#908 - mhash_get_block_size Example
  • Example#909 - mhash_get_hash_name Example
  • Example#910 - openssl_cipher_iv_length example
  • Example#911 - Creating a self-signed-certificate
  • Example#912 - openssl_csr_sign example - signing a CSR (how to implement your own CA)
  • Example#913 - openssl_error_string example
  • Example#914 - openssl_get_cipher_methods example
  • Example#915 - openssl_get_md_methods example
  • Example#916 - openssl_open example
  • Example#917 - openssl_pkcs7_decrypt example
  • Example#918 - openssl_pkcs7_encrypt example
  • Example#919 - openssl_pkcs7_sign example
  • Example#920 - openssl_random_pseudo_bytes example
  • Example#921 - openssl_seal example
  • Example#922 - openssl_sign example
  • Example#923 - openssl_verify example
  • Example#924 - DBA example
  • Example#925 - Traversing a database
  • Example#926 - dba_handlers Example
  • Example#927 - dbx_close example
  • Example#928 - dbx_compare example
  • Example#929 - dbx_connect example
  • Example#930 - dbx_error example
  • Example#931 - dbx_escape_string example
  • Example#932 - How to handle the returned value
  • Example#933 - lists each field's name and type
  • Example#934 - outputs the content of data property into HTML table
  • Example#935 - How to handle UNBUFFERED queries
  • Example#936 - How to handle the returned value
  • Example#937 - dbx_sort example
  • Example#938 - DSN-less connections
  • Example#939 - odbc_execute and odbc_prepare example
  • Example#940 - odbc_fetch_into examples
  • Example#941 - odbc_next_result
  • Example#942 - odbc_execute and odbc_prepare example
  • Example#943 - odbc_result examples
  • Example#944 - odbc_setoption examples
  • Example#945 - using PDO::ATTR_DRIVER_NAME
  • Example#946 - Connecting to MySQL
  • Example#947 - Handling connection errors
  • Example#948 - Closing a connection
  • Example#949 - Persistent connections
  • Example#950 - Executing a batch in a transaction
  • Example#951 - Repeated inserts using prepared statements
  • Example#952 - Repeated inserts using prepared statements
  • Example#953 - Fetching data using prepared statements
  • Example#954 - Calling a stored procedure with an output parameter
  • Example#955 - Calling a stored procedure with an input/output parameter
  • Example#956 - Invalid use of placeholder
  • Example#957 - Create a PDO instance and set the error mode
  • Example#958 - Displaying an image from a database
  • Example#959 - Inserting an image into a database
  • Example#960 - Inserting an image into a database: Oracle
  • Example#961 - Откат транзакции
  • Example#962 - Фиксация транзакции
  • Example#963 - Создание экземпляра PDO через вызов драйвера
  • Example#964 - Создание экземпляра PDO через вызов URI
  • Example#965 - Создание экземпляра PDO, используя псевдоним
  • Example#966 - Retrieving an SQLSTATE code
  • Example#967 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#968 - Issuing a DELETE statement
  • Example#969 - Получение атрибутов соединения с базой данных
  • Example#970 - Пример PDO::getAvailableDrivers
  • Example#971 - Prepare an SQL statement with named parameters
  • Example#972 - Prepare an SQL statement with question mark parameters
  • Example#973 - Demonstrate PDO::query
  • Example#974 - Quoting a normal string
  • Example#975 - Quoting a dangerous string
  • Example#976 - Quoting a complex string
  • Example#977 - Roll back a transaction
  • Example#978 - Binding result set output to PHP variables
  • Example#979 - Execute a prepared statement with named placeholders
  • Example#980 - Execute a prepared statement with question mark placeholders
  • Example#981 - Call a stored procedure with an INOUT parameter
  • Example#982 - Execute a prepared statement with named placeholders
  • Example#983 - Execute a prepared statement with question mark placeholders
  • Example#984 - A PDOStatement::closeCursor example
  • Example#985 - Counting columns
  • Example#986 - PDOStatement::debugDumpParams example with named parameters
  • Example#987 - PDOStatement::debugDumpParams example with unnamed parameters
  • Example#988 - Retrieving an SQLSTATE code
  • Example#989 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#990 - Execute a prepared statement with bound variables
  • Example#991 - Execute a prepared statement with an array of insert values (named parameters)
  • Example#992 - Execute a prepared statement with an array of insert values (placeholders)
  • Example#993 - Execute a prepared statement with question mark placeholders
  • Example#994 - Fetching rows using different fetch styles
  • Example#995 - Fetching rows with a scrollable cursor
  • Example#996 - Fetch all remaining rows in a result set
  • Example#997 - Fetching all values of a single column from a result set
  • Example#998 - Grouping all values by a single column
  • Example#999 - Instantiating a class for each result
  • Example#1000 - Calling a function for each result
  • Example#1001 - Return first column of the next row
  • Example#1002 - Retrieving column metadata
  • Example#1003 - Fetching multiple rowsets returned from a stored procedure
  • Example#1004 - Return the number of deleted rows
  • Example#1005 - Counting rows returned by a SELECT statement
  • Example#1006 - Setting the fetch mode
  • Example#1007 - Insert LOBs in CUBRID PDO
  • Example#1008 - Fetch LOBs in CUBRID PDO
  • Example#1009 - PDO_CUBRID DSN examples
  • Example#1010 - A PDO::cubrid_schema example
  • Example#1011 - PDO_DBLIB DSN examples
  • Example#1012 - PDO_FIREBIRD DSN examples
  • Example#1013 - PDO_IBM DSN example using db2cli.ini
  • Example#1014 - PDO_IBM DSN example using a connection string
  • Example#1015 - PDO_INFORMIX DSN example using odbc.ini
  • Example#1016 - PDO_INFORMIX DSN example using a connection string
  • Example#1017 - Буферизация запросов в MySQL
  • Example#1018 - Setting the connection character set to UTF-8 prior to PHP 5.3.6
  • Example#1019 - PDO_MYSQL DSN examples
  • Example#1020 - PDO_SQLSRV DSN examples
  • Example#1021 - PDO_OCI DSN examples
  • Example#1022 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#1023 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#1024 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#1025 - PDO_PGSQL DSN examples
  • Example#1026 - A PDO::pgsqlLOBCreate example
  • Example#1027 - A PDO::pgsqlLOBOpen example
  • Example#1028 - A PDO::pgsqlLOBUnlink example
  • Example#1029 - PDO_SQLITE DSN examples
  • Example#1030 - max_length aggregation function example
  • Example#1031 - PDO::sqliteCreateFunction example
  • Example#1032 - DSN examples for PDO_4D
  • Example#1033 - Basic example with PDO_4D
  • Example#1034 - Accessing 4D language from pdo_4d
  • Example#1035 - Escaping 4D table names
  • Example#1036 - Example of Data Retrieval
  • Example#1037 - Example of Data Insertion
  • Example#1038 - cubrid_bind example
  • Example#1039 - cubrid_bind BLOB/CLOB example
  • Example#1040 - cubrid_bind BLOB/CLOB example
  • Example#1041 - cubrid_close_prepare example
  • Example#1042 - cubrid_close_request example
  • Example#1043 - cubrid_col_get example
  • Example#1044 - cubrid_col_size example
  • Example#1045 - cubrid_column_names example
  • Example#1046 - cubrid_column_types example
  • Example#1047 - cubrid_commit example
  • Example#1048 - cubrid_connect_with_url url without properties example
  • Example#1049 - cubrid_connect_with_url url with properties example
  • Example#1050 - cubrid_connect example
  • Example#1051 - cubrid_current_oid example
  • Example#1052 - cubrid_disconnect example
  • Example#1053 - cubrid_drop example
  • Example#1054 - cubrid_error_code_facility example
  • Example#1055 - cubrid_error_code example
  • Example#1056 - cubrid_error_msg example
  • Example#1057 - cubrid_execute example
  • Example#1058 - cubrid_fetch example
  • Example#1059 - cubrid_free_result example
  • Example#1060 - cubrid_get_charset example
  • Example#1061 - cubrid_get_class_name example
  • Example#1062 - cubrid_get_client_info example
  • Example#1063 - cubrid_get_db_parameter example
  • Example#1064 - cubrid_get_query_timeout example
  • Example#1065 - cubrid_get_server_info example
  • Example#1066 - cubrid_get example
  • Example#1067 - cubrid_insert_id example
  • Example#1068 - cubrid_is_instance example
  • Example#1069 - cubrid_lob_close example
  • Example#1070 - cubrid_lob_export example
  • Example#1071 - cubrid_lob_get example
  • Example#1072 - cubrid_lob_send example
  • Example#1073 - cubrid_lob_size example
  • Example#1074 - cubrid_lock_read example
  • Example#1075 - cubrid_lock_write example
  • Example#1076 - cubrid_move_cursor example
  • Example#1077 - cubrid_next_result example
  • Example#1078 - cubrid_num_cols example
  • Example#1079 - cubrid_num_rows example
  • Example#1080 - cubrid_connect_with_url url without properties example
  • Example#1081 - cubrid_connect_with_url url with properties example
  • Example#1082 - cubrid_connect example
  • Example#1083 - cubrid_prepare example
  • Example#1084 - cubrid_put example
  • Example#1085 - cubrid_rollback example
  • Example#1086 - cubrid_schema example
  • Example#1087 - cubrid_seq_drop example
  • Example#1088 - cubrid_seq_insert example
  • Example#1089 - cubrid_seq_put example
  • Example#1090 - cubrid_set_add example
  • Example#1091 - cubrid_get_db_parameter example
  • Example#1092 - cubrid_set_drop example
  • Example#1093 - cubrid_version example
  • Example#1094 - cubrid_affected_rows example
  • Example#1095 - cubrid_client_encoding example
  • Example#1096 - cubrid_close example
  • Example#1097 - cubrid_data_seek example
  • Example#1098 - cubrid_db_name example
  • Example#1099 - cubrid_errno example
  • Example#1100 - cubrid_error example
  • Example#1101 - cubrid_fetch_array example
  • Example#1102 - cubrid_fetch_assoc example
  • Example#1103 - cubrid_fetch_field example
  • Example#1104 - cubrid_fetch_lengths example
  • Example#1105 - cubrid_fetch_object example
  • Example#1106 - cubrid_fetch_row example
  • Example#1107 - cubrid_field_flags example
  • Example#1108 - cubrid_field_len example
  • Example#1109 - cubrid_field_name example
  • Example#1110 - cubrid_field_seek example
  • Example#1111 - cubrid_field_table example
  • Example#1112 - cubrid_field_type example
  • Example#1113 - cubrid_list_dbs example
  • Example#1114 - cubrid_num_fields example
  • Example#1115 - cubrid_ping example
  • Example#1116 - Invalid Query
  • Example#1117 - Valid Query
  • Example#1118 - cubrid_real_escape_string example
  • Example#1119 - cubrid_result example
  • Example#1120 - cubrid_unbuffered_query example
  • Example#1121 - cubrid_load_from_glo example
  • Example#1122 - cubrid_new_glo example
  • Example#1123 - cubrid_save_to_glo example
  • Example#1124 - cubrid_send_glo example
  • Example#1125 - Вставка записи в базу данных dBase
  • Example#1126 - Закрытие файла базы данных dBase
  • Example#1127 - Создание файла базы данных dBase
  • Example#1128 - Получение свойств полей файла базы данных dBase
  • Example#1129 - Список всех зарегистрированных пользователей в базе данных
  • Example#1130 - Пример использования dbase_numfields
  • Example#1131 - Цикл по всем записям базы данных
  • Example#1132 - Открытие dBase файл базы данных
  • Example#1133 - Очистка базы данных dBase
  • Example#1134 - Обновление записи в базе данных
  • Example#1135 - ibase_blob_get example
  • Example#1136 - ibase_blob_import example
  • Example#1137 - ibase_connect example
  • Example#1138 - ibase_execute example
  • Example#1139 - ibase_fetch_object example
  • Example#1140 - ibase_field_info example
  • Example#1141 - ibase_name_result example
  • Example#1142 - ibase_num_fields example
  • Example#1143 - ibase_query example
  • Example#1144 - ibase_set_event_handler example
  • Example#1145 - ibase_timefmt example
  • Example#1146 - fbsql_close example
  • Example#1147 - fbsql_connect example
  • Example#1148 - fbsql_create_blob example
  • Example#1149 - fbsql_create_clob example
  • Example#1150 - fbsql_create_db example
  • Example#1151 - fbsql_data_seek example
  • Example#1152 - fbsql_create_clob example
  • Example#1153 - fbsql_errno Example
  • Example#1154 - fbsql_error Example
  • Example#1155 - fbsql_fetch_array example
  • Example#1156 - fbsql_fetch_assoc example
  • Example#1157 - fbsql_fetch_field example
  • Example#1158 - fbsql_fetch_object example
  • Example#1159 - fbsql_field_name example
  • Example#1160 - fbsql_field_type example
  • Example#1161 - fbsql_list_dbs example
  • Example#1162 - fbsql_list_fields example
  • Example#1163 - fbsql_next_result example
  • Example#1164 - fbsql_num_rows example
  • Example#1165 - fbsql_query example
  • Example#1166 - fbsql_query example
  • Example#1167 - fbsql_read_blob example
  • Example#1168 - fbsql_read_clob example
  • Example#1169 - fbsql_table_name example
  • Example#1170 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1171 - Setting the AUTOCOMMIT value for a connection
  • Example#1172 - Binding PHP variables to a prepared statement
  • Example#1173 - Calling stored procedures with IN and OUT parameters
  • Example#1174 - Inserting a binary large object (BLOB) directly from a file
  • Example#1175 - A db2_client_info example
  • Example#1176 - Closing a connection
  • Example#1177 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1178 - Retrieving the error message returned by a failed connection attempt
  • Example#1179 - Creating a cataloged connection
  • Example#1180 - Creating an uncataloged connection
  • Example#1181 - Creating a connection with autocommit off by default
  • Example#1182 - i5/OS best performance
  • Example#1183 - Using trusted context
  • Example#1184 - A db2_escape_string example
  • Example#1185 - Creating a table with db2_exec
  • Example#1186 - Executing a SELECT statement with a scrollable cursor
  • Example#1187 - Returning XML data as an SQL ResultSet
  • Example#1188 - Performing a "JOIN" with XML data
  • Example#1189 - Returning SQL data as part of a larger XML document
  • Example#1190 - Preparing and executing an SQL statement with parameter markers
  • Example#1191 - Calling a stored procedure with an OUT parameter
  • Example#1192 - Returning XML data as an SQL ResultSet
  • Example#1193 - Performing a "JOIN" with XML data
  • Example#1194 - Returning SQL data as part of a larger XML document
  • Example#1195 - Iterating through a forward-only cursor
  • Example#1196 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1197 - Iterating through a forward-only cursor
  • Example#1198 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1199 - Iterating through a forward-only cursor
  • Example#1200 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1201 - A db2_fetch_object example
  • Example#1202 - Iterating through a result set
  • Example#1203 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1204 - Setting and retrieving parameters through a connection resource
  • Example#1205 - A db2_last_insert_id example
  • Example#1206 - Iterating through different types of data
  • Example#1207 - Calling a stored procedure that returns multiple result sets
  • Example#1208 - Retrieving the number of fields in a result set
  • Example#1209 - Closing a persistent connection
  • Example#1210 - A db2_pconnect example
  • Example#1211 - Using trusted context
  • Example#1212 - Preparing and executing an SQL statement with parameter markers
  • Example#1213 - A db2_result example
  • Example#1214 - Rolling back a DELETE statement
  • Example#1215 - A db2_server_info example
  • Example#1216 - Setting one parameter with a connection resource
  • Example#1217 - Setting multiple parameters with a connection resource
  • Example#1218 - Setting multiple parameters with an invalid key
  • Example#1219 - Setting multiple parameters with an invalid value
  • Example#1220 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1221 - Setting multiple parameters with the wrong resource
  • Example#1222 - Putting it all together
  • Example#1223 - i5/OS cursors are read-only
  • Example#1224 - Informix affected rows
  • Example#1225 - Closing a Informix connection
  • Example#1226 - Connect to a Informix database
  • Example#1227 - ifx_do Example
  • Example#1228 - ifx_errormsg example
  • Example#1229 - Informix fetch rows
  • Example#1230 - Informix SQL fieldproperties
  • Example#1231 - Fieldnames and SQL fieldtypes
  • Example#1232 - Retrieve Informix sqlca.sqlerrd[x] values
  • Example#1233 - Informix results as HTML table
  • Example#1234 - ifx_num_fields Example
  • Example#1235 - Show all rows of the "orders" table as a HTML table
  • Example#1236 - Insert some values into the "catalog" table
  • Example#1237 - Example usage of PassEnv for Ingres
  • Example#1238 - Simple Ingres Example
  • Example#1239 - ingres_charset - Get the installation character set
  • Example#1240 - Open a connection to an Ingres database
  • Example#1241 - Get cursor name for a query resource
  • Example#1242 - Get the last Ingres error number generated
  • Example#1243 - Get a message for the last error generated
  • Example#1244 - Get the last SQLSTATE error code generated
  • Example#1245 - Escape special characters for use in a query
  • Example#1246 - Fetch a row of result into an array
  • Example#1247 - Fetch a row into an associative array
  • Example#1248 - Fetch a row into an object
  • Example#1249 - Get the return value from a procedure call
  • Example#1250 - Fetch a row of result into an enumerated array
  • Example#1251 - Free a result resource
  • Example#1252 - Send a simple select
  • Example#1253 - Passing query parameters to ingres_query
  • Example#1254 - Inserting a BLOB with parameter types
  • Example#1255 - Position the cursor on the 3rd row
  • Example#1256 - Set date_format to ISO4
  • Example#1257 - Set timezone to HONG-KONG
  • Example#1258 - Issue a simple un-buffered select
  • Example#1259 - Passing query parameters to ingres_unbuffered_query
  • Example#1260 - Inserting a BLOB with parameter types
  • Example#1261 - MaxDB extension overview example
  • Example#1262 - Example for use of SELECT INTO statements
  • Example#1263 - Example fore using database procedures
  • Example#1264 - Объектно-ориентированный стиль
  • Example#1265 - Процедурный стиль
  • Example#1266 - Объектно-ориентированный стиль
  • Example#1267 - Процедурный стиль
  • Example#1268 - Объектно-ориентированный стиль
  • Example#1269 - Процедурный стиль
  • Example#1270 - Объектно-ориентированный стиль
  • Example#1271 - Процедурный стиль
  • Example#1272 - Объектно-ориентированный стиль
  • Example#1273 - Процедурный стиль
  • Example#1274 - maxdb_connect_errno sample
  • Example#1275 - maxdb_connect_error sample
  • Example#1276 - Объектно-ориентированный стиль
  • Example#1277 - Процедурный стиль
  • Example#1278 - Объектно-ориентированный стиль
  • Example#1279 - Процедурный стиль
  • Example#1280 - Процедурный стиль
  • Example#1281 - Объектно-ориентированный стиль
  • Example#1282 - Процедурный стиль
  • Example#1283 - Объектно-ориентированный стиль
  • Example#1284 - Процедурный стиль
  • Example#1285 - Объектно-ориентированный стиль
  • Example#1286 - Процедурный стиль
  • Example#1287 - Объектно-ориентированный стиль
  • Example#1288 - Процедурный стиль
  • Example#1289 - Объектно-ориентированный стиль
  • Example#1290 - Процедурный стиль
  • Example#1291 - Объектно-ориентированный стиль
  • Example#1292 - Процедурный стиль
  • Example#1293 - Объектно-ориентированный стиль
  • Example#1294 - Процедурный стиль
  • Example#1295 - Объектно-ориентированный стиль
  • Example#1296 - Процедурный стиль
  • Example#1297 - Объектно-ориентированный стиль
  • Example#1298 - Процедурный стиль
  • Example#1299 - Объектно-ориентированный стиль
  • Example#1300 - Процедурный стиль
  • Example#1301 - Объектно-ориентированный стиль
  • Example#1302 - Процедурный стиль
  • Example#1303 - Объектно-ориентированный стиль
  • Example#1304 - Процедурный стиль
  • Example#1305 - Объектно-ориентированный стиль
  • Example#1306 - Процедурный стиль
  • Example#1307 - maxdb_get_client_info
  • Example#1308 - maxdb_get_client_version
  • Example#1309 - Объектно-ориентированный стиль
  • Example#1310 - Процедурный стиль
  • Example#1311 - Объектно-ориентированный стиль
  • Example#1312 - Процедурный стиль
  • Example#1313 - Объектно-ориентированный стиль
  • Example#1314 - Процедурный стиль
  • Example#1315 - Объектно-ориентированный стиль
  • Example#1316 - Процедурный стиль
  • Example#1317 - Объектно-ориентированный стиль
  • Example#1318 - Процедурный стиль
  • Example#1319 - Объектно-ориентированный стиль
  • Example#1320 - Процедурный стиль
  • Example#1321 - Объектно-ориентированный стиль
  • Example#1322 - Процедурный стиль
  • Example#1323 - Объектно-ориентированный стиль
  • Example#1324 - Процедурный стиль
  • Example#1325 - Объектно-ориентированный стиль
  • Example#1326 - Процедурный стиль
  • Example#1327 - Объектно-ориентированный стиль
  • Example#1328 - Процедурный стиль
  • Example#1329 - Объектно-ориентированный стиль
  • Example#1330 - Процедурный стиль
  • Example#1331 - Объектно-ориентированный стиль
  • Example#1332 - Процедурный стиль
  • Example#1333 - Объектно-ориентированный стиль
  • Example#1334 - Процедурный стиль
  • Example#1335 - Объектно-ориентированный стиль
  • Example#1336 - Процедурный стиль
  • Example#1337 - Объектно-ориентированный стиль
  • Example#1338 - Процедурный стиль
  • Example#1339 - Процедурный стиль
  • Example#1340 - Объектно-ориентированный стиль
  • Example#1341 - Процедурный стиль
  • Example#1342 - Объектно-ориентированный стиль
  • Example#1343 - Процедурный стиль
  • Example#1344 - Объектно-ориентированный стиль
  • Example#1345 - Процедурный стиль
  • Example#1346 - Объектно-ориентированный стиль
  • Example#1347 - Процедурный стиль
  • Example#1348 - Объектно-ориентированный стиль
  • Example#1349 - Процедурный стиль
  • Example#1350 - Объектно-ориентированный стиль
  • Example#1351 - Процедурный стиль
  • Example#1352 - Процедурный стиль (SELECT INTO)
  • Example#1353 - Процедурный стиль (DB procedure)
  • Example#1354 - Объектно-ориентированный стиль (extended syntax)
  • Example#1355 - Объектно-ориентированный стиль
  • Example#1356 - Процедурный стиль
  • Example#1357 - Объектно-ориентированный стиль
  • Example#1358 - Процедурный стиль
  • Example#1359 - Объектно-ориентированный стиль
  • Example#1360 - Процедурный стиль
  • Example#1361 - Объектно-ориентированный стиль
  • Example#1362 - Процедурный стиль
  • Example#1363 - Объектно-ориентированный стиль
  • Example#1364 - Процедурный стиль
  • Example#1365 - Объектно-ориентированный стиль
  • Example#1366 - Процедурный стиль
  • Example#1367 - Объектно-ориентированный стиль
  • Example#1368 - Процедурный стиль
  • Example#1369 - Объектно-ориентированный стиль
  • Example#1370 - Процедурный стиль
  • Example#1371 - Объектно-ориентированный стиль
  • Example#1372 - Процедурный стиль
  • Example#1373 - Объектно-ориентированный стиль
  • Example#1374 - Процедурный стиль
  • Example#1375 - Объектно-ориентированный стиль
  • Example#1376 - Процедурный стиль
  • Example#1377 - Объектно-ориентированный стиль
  • Example#1378 - Процедурный стиль
  • Example#1379 - Объектно-ориентированный стиль
  • Example#1380 - Процедурный стиль
  • Example#1381 - Объектно-ориентированный стиль
  • Example#1382 - Процедурный стиль
  • Example#1383 - Объектно-ориентированный стиль
  • Example#1384 - Процедурный стиль
  • Example#1385 - Mongo::__construct replica set example
  • Example#1386 - Connecting to a domain socket
  • Example#1387 - Mongo::__construct authentication example
  • Example#1388 - Changing pool size
  • Example#1389 - Mongo::listDBs example
  • Example#1390 - Mongo::selectCollection example
  • Example#1391 - Mongo::setPoolSize example
  • Example#1392 - MongoDB::command "distinct" example
  • Example#1393 - MongoDB::command "distinct" example
  • Example#1394 - MongoDB::command MapReduce example
  • Example#1395 - MongoDB::createCollection capped collection example
  • Example#1396 - MongoDB::createDBRef example
  • Example#1397 - MongoDB::createDBRef example
  • Example#1398 - MongoDB::drop example
  • Example#1399 - Simple MongoDB::execute example
  • Example#1400 - Parameter MongoDB::execute example
  • Example#1401 - Scope example
  • Example#1402 - MongoDB::getDBRef example
  • Example#1403 - MongoDB::getGridFS example
  • Example#1404 - MongoDB::lastError NULL error example
  • Example#1405 - MongoDB::lastError duplicate key example
  • Example#1406 - MongoDB::listCollections example
  • Example#1407 - MongoDB::repair example
  • Example#1408 - MongoCollection::batchInsert example
  • Example#1409 - MongoCollection::batchInsert example with ignoring errors
  • Example#1410 - MongoCollection::count example
  • Example#1411 - MongoCollection::createDBRef example
  • Example#1412 - MongoCollection::deleteIndex example
  • Example#1413 - MongoCollection::deleteIndexes example
  • Example#1414 - MongoCollection::drop example
  • Example#1415 - MongoCollection::ensureIndex example
  • Example#1416 - Drop duplicates example
  • Example#1417 - Geospatial Indexing
  • Example#1418 - MongoCollection::find example
  • Example#1419 - MongoCollection::find example using $where
  • Example#1420 - MongoCollection::find example using $in
  • Example#1421 - Getting results as an array
  • Example#1422 - MongoCollection::findOne document by its id.
  • Example#1423 - MongoCollection::findOne document by some condition.
  • Example#1424 - MongoCollection::getDBRef example
  • Example#1425 - MongoCollection::find example
  • Example#1426 - MongoCollection::getName example
  • Example#1427 - MongoCollection::group example
  • Example#1428 - MongoCollection::group example
  • Example#1429 - Passing a keys function
  • Example#1430 - MongoCollection::insert _id example
  • Example#1431 - MongoCollection::insert safe example
  • Example#1432 - MongoCollection::remove with justOne example
  • Example#1433 - MongoCollection::save example
  • Example#1434 - MongoCollection::toIndexString example
  • Example#1435 - MongoCollection::__toString example
  • Example#1436 - MongoCollection::update
  • Example#1437 - MongoCollection::update upsert example
  • Example#1438 - MongoCollection::update multiple example
  • Example#1439 - MongoCursor::addOption example
  • Example#1440 - Mongo::batchSize and combinations with MongoCursor::limit
  • Example#1441 - MongoCursor::count example
  • Example#1442 - MongoCursor::doQuery example
  • Example#1443 - MongoCursor::explain example
  • Example#1444 - MongoCursor::info example
  • Example#1445 - MongoCursor::slaveOkay example
  • Example#1446 - MongoCursor::sort example
  • Example#1447 - MongoCursor::tailable example
  • Example#1448 - MongoCursor::timeout example
  • Example#1449 - MongoId::__construct example
  • Example#1450 - Parameter example
  • Example#1451 - MongoId::__toString example
  • Example#1452 - MongoCode::__construct example
  • Example#1453 - Using MongoCode with $where
  • Example#1454 - MongoCode::__toString example
  • Example#1455 - MongoDate::__construct example
  • Example#1456 - MongoRegex::__construct example
  • Example#1457 - MongoRegex::__toString example
  • Example#1458 - MongoDBRef::create example
  • Example#1459 - MongoCollection::createDBRef example
  • Example#1460 - MongoGridFS::findOne example
  • Example#1461 - MongoGridFSFile::getBytes example
  • Example#1462 - MongoGridFSFile::getResource example
  • Example#1463 - MongoGridFSFile::write example
  • Example#1464 - Changing pool size
  • Example#1465 - Mongo::setPoolSize example
  • Example#1466 - mSQL usage example
  • Example#1467 - msql_fetch_array example
  • Example#1468 - msql_fetch_object example
  • Example#1469 - msql_fetch_row example
  • Example#1470 - msql_query example
  • Example#1471 - mssql_bind example
  • Example#1472 - mssql_close example
  • Example#1473 - mssql_connect example
  • Example#1474 - mssql_data_seek example
  • Example#1475 - mssql_execute example
  • Example#1476 - mssql_fetch_array example
  • Example#1477 - mssql_fetch_assoc example
  • Example#1478 - mssql_fetch_batch example
  • Example#1479 - mssql_fetch_field example
  • Example#1480 - mssql_fetch_object example
  • Example#1481 - mssql_fetch_row example
  • Example#1482 - mssql_field_length example
  • Example#1483 - mssql_field_name example
  • Example#1484 - Using mssql_field_seek on the example for mssql_fetch_field
  • Example#1485 - mssql_field_type example
  • Example#1486 - mssql_free_result example
  • Example#1487 - mssql_free_statement example
  • Example#1488 - mssql_get_last_message example
  • Example#1489 - mssql_guid_string example
  • Example#1490 - mssql_init example
  • Example#1491 - mssql_min_error_severity example
  • Example#1492 - mssql_min_message_severity example
  • Example#1493 - mssql_next_result example
  • Example#1494 - mssql_num_fields example
  • Example#1495 - mssql_num_rows example
  • Example#1496 - mssql_pconnect using the new_link parameter
  • Example#1497 - mssql_query example
  • Example#1498 - mssql_result example
  • Example#1499 - Faster alternative to above example
  • Example#1500 - mssql_rows_affected example
  • Example#1501 - mssql_select_db example
  • Example#1502 - Escaping the database name with square brackets
  • Example#1503 - Comparing the three MySQL APIs
  • Example#1504 - Configure commands for using mysqlnd or libmysql
  • Example#1505 - Unbuffered query example: mysqli
  • Example#1506 - Unbuffered query example: pdo_mysql
  • Example#1507 - Unbuffered query example: mysql
  • Example#1508 - Пример работы с MySQL
  • Example#1509 - Пример использования mysql_affected_rows
  • Example#1510 - Пример использования mysql_affected_rows с транзакциями
  • Example#1511 - Пример использования mysql_client_encoding
  • Example#1512 - Пример использования mysql_close
  • Example#1513 - Пример использования mysql_connect
  • Example#1514 - Пример использования mysql_connect с синтаксисом hostname:port
  • Example#1515 - Пример использования mysql_connect с синтаксисом ":/path/to/socket"
  • Example#1516 - Пример создания базы данных MySQL
  • Example#1517 - Пример использования mysql_data_seek
  • Example#1518 - Пример использования mysql_db_name
  • Example#1519 - Пример использования альтернативы mysql_db_query
  • Example#1520 - Альтернативный пример использования mysql_drop_db
  • Example#1521 - Пример использования mysql_errno
  • Example#1522 - Пример использования mysql_error
  • Example#1523 - Пример использования mysql_escape_string
  • Example#1524 - Запрос с применением псевдонимов для дублирующихся имен колонок
  • Example#1525 - mysql_fetch_array с MYSQL_NUM
  • Example#1526 - mysql_fetch_array с MYSQL_ASSOC
  • Example#1527 - mysql_fetch_array с MYSQL_BOTH
  • Example#1528 - Расширенный пример использования mysql_fetch_assoc
  • Example#1529 - Пример использования mysql_fetch_field
  • Example#1530 - Пример использования mysql_fetch_lengths
  • Example#1531 - Пример использования mysql_fetch_object
  • Example#1532 - Пример использования mysql_fetch_object
  • Example#1533 - Получение одного ряда с помощью mysql_fetch_row
  • Example#1534 - Пример использования mysql_field_flags
  • Example#1535 - Пример использования mysql_field_len
  • Example#1536 - Пример использования mysql_field_name
  • Example#1537 - Пример использования mysql_field_table
  • Example#1538 - Пример использования mysql_field_type
  • Example#1539 - Пример использования mysql_free_result
  • Example#1540 - Пример использования mysql_get_client_info
  • Example#1541 - Пример использования mysql_get_host_info
  • Example#1542 - Пример использования mysql_get_proto_info
  • Example#1543 - Пример использования mysql_get_server_info
  • Example#1544 - Корректные виды запросов MySQL
  • Example#1545 - Пример использования mysql_insert_id
  • Example#1546 - Пример использования mysql_list_dbs
  • Example#1547 - Пример использования mysql_list_fields
  • Example#1548 - Пример использования mysql_list_processes
  • Example#1549 - Пример использования mysql_list_tables
  • Example#1550 - Пример использования mysql_num_fields
  • Example#1551 - Пример использования mysql_num_rows
  • Example#1552 - Пример использования mysql_ping
  • Example#1553 - Неверный запрос
  • Example#1554 - Верный запрос
  • Example#1555 - Простой пример использования mysql_real_escape_string
  • Example#1556 - Пример взлома с использованием SQL-инъекции
  • Example#1557 - Пример использования mysql_result
  • Example#1558 - Пример использования mysql_select_db
  • Example#1559 - Пример использования mysql_stat
  • Example#1560 - Альтернативный пример использования mysql_stat
  • Example#1561 - Пример использования mysql_tablename
  • Example#1562 - Пример использования mysql_thread_id
  • Example#1563 - Easy migration from the old mysql extension
  • Example#1564 - Object-oriented and procedural interface
  • Example#1565 - Bad coding style
  • Example#1566 - Special meaning of localhost
  • Example#1567 - Setting defaults
  • Example#1568 - Bad coding style
  • Example#1569 - Navigation through buffered results
  • Example#1570 - Navigation through buffered results
  • Example#1571 - Text protocol returns strings by default
  • Example#1572 - Native data types with mysqlnd and connection option
  • Example#1573 - First stage: prepare
  • Example#1574 - Second stage: bind and execute
  • Example#1575 - INSERT prepared once, executed multiple times
  • Example#1576 - Less round trips using multi-INSERT SQL
  • Example#1577 - Native datatypes
  • Example#1578 - Output variable binding
  • Example#1579 - Using mysqli_result to fetch results
  • Example#1580 - Buffered result set for flexible read out
  • Example#1581 - Calling a stored procedure
  • Example#1582 - Using session variables
  • Example#1583 - Fetching results from stored procedures
  • Example#1584 - Stored Procedures and Prepared Statements
  • Example#1585 - Stored Procedures and Prepared Statements using bind API
  • Example#1586 - Multiple Statements
  • Example#1587 - SQL Injection
  • Example#1588 - Setting auto commit mode with SQL and through the API
  • Example#1589 - Commit and rollback
  • Example#1590 - Accessing result set meta data
  • Example#1591 - Prepared statements metadata
  • Example#1592 - Пример $mysqli->affected_rows
  • Example#1593 - Пример использования mysqli::autocommit
  • Example#1594 - Пример использования mysqli::change_user
  • Example#1595 - mysqli::character_set_name example
  • Example#1596 - mysqli_get_client_info
  • Example#1597 - mysqli_get_client_version
  • Example#1598 - Пример использования mysqli::commit
  • Example#1599 - Пример использования $mysqli->connect_errno
  • Example#1600 - Пример использования $mysqli->connect_error
  • Example#1601 - mysqli::__construct example
  • Example#1602 - Generating a Trace File
  • Example#1603 - Пример использования $mysqli->errno
  • Example#1604 - $mysqli->error_list example
  • Example#1605 - $mysqli->error example
  • Example#1606 - Пример использования $mysqli->field_count
  • Example#1607 - mysqli::get_charset example
  • Example#1608 - mysqli_get_client_info
  • Example#1609 - Пример использования mysqli_get_client_stats
  • Example#1610 - mysqli_get_client_version
  • Example#1611 - Пример использования mysqli_get_connection_stats
  • Example#1612 - Пример использования $mysqli->host_info
  • Example#1613 - Пример использования $mysqli->protocol_version
  • Example#1614 - Пример использования $mysqli->server_info
  • Example#1615 - Пример использования $mysqli->server_version
  • Example#1616 - $mysqli->info example
  • Example#1617 - Пример функции $mysqli->insert_id
  • Example#1618 - mysqli::kill example
  • Example#1619 - mysqli::multi_query example
  • Example#1620 - mysqli::ping example
  • Example#1621 - A mysqli_poll example
  • Example#1622 - mysqli::prepare example
  • Example#1623 - mysqli::query example
  • Example#1624 - mysqli::real_connect example
  • Example#1625 - mysqli::real_escape_string example
  • Example#1626 - mysqli::rollback example
  • Example#1627 - Пример использования mysqli::select_db
  • Example#1628 - mysqli::set_charset example
  • Example#1629 - mysqli::set_local_infile_handler example
  • Example#1630 - $mysqli->sqlstate example
  • Example#1631 - mysqli::stat example
  • Example#1632 - $mysqli->thread_id example
  • Example#1633 - mysqli::use_result example
  • Example#1634 - $mysqli->warning_count example
  • Example#1635 - Объектно-ориентированный стиль
  • Example#1636 - Процедурный стиль
  • Example#1637 - Объектно-ориентированный стиль
  • Example#1638 - Процедурный стиль
  • Example#1639 - Объектно-ориентированный стиль
  • Example#1640 - Процедурный стиль
  • Example#1641 - Объектно-ориентированный стиль
  • Example#1642 - Процедурный стиль
  • Example#1643 - Объектно-ориентированный стиль
  • Example#1644 - Процедурный стиль
  • Example#1645 - Объектно-ориентированный стиль
  • Example#1646 - Процедурный стиль
  • Example#1647 - Объектно-ориентированный стиль
  • Example#1648 - Процедурный стиль
  • Example#1649 - Объектно-ориентированный стиль
  • Example#1650 - Процедурный стиль
  • Example#1651 - Объектно-ориентированный стиль
  • Example#1652 - Процедурный стиль
  • Example#1653 - Объектно-ориентированный стиль
  • Example#1654 - Процедурный стиль
  • Example#1655 - Объектно-ориентированный стиль
  • Example#1656 - Процедурный стиль
  • Example#1657 - Объектно-ориентированный стиль
  • Example#1658 - Процедурный стиль
  • Example#1659 - Объектно-ориентированный стиль
  • Example#1660 - Процедурный стиль
  • Example#1661 - Объектно-ориентированный стиль
  • Example#1662 - Процедурный стиль
  • Example#1663 - Объектно-ориентированный стиль
  • Example#1664 - Объектно-ориентированный стиль
  • Example#1665 - Процедурный стиль
  • Example#1666 - Объектно-ориентированный стиль
  • Example#1667 - Процедурный стиль
  • Example#1668 - Объектно-ориентированный стиль
  • Example#1669 - Процедурный стиль
  • Example#1670 - Объектно-ориентированный стиль
  • Example#1671 - Процедурный стиль
  • Example#1672 - Объектно-ориентированный стиль
  • Example#1673 - Процедурный стиль
  • Example#1674 - Объектно-ориентированный стиль
  • Example#1675 - Процедурный стиль
  • Example#1676 - Пример mysqli_result с использованием класса iterator
  • Example#1677 - Объектно-ориентированный стиль
  • Example#1678 - Процедурный стиль
  • Example#1679 - Объектно-ориентированный стиль
  • Example#1680 - Процедурный стиль
  • Example#1681 - Объектно-ориентированный стиль
  • Example#1682 - Процедурный стиль
  • Example#1683 - Объектно-ориентированный стиль
  • Example#1684 - Процедурный стиль
  • Example#1685 - Объектно-ориентированный стиль
  • Example#1686 - Процедурный стиль
  • Example#1687 - Объектно-ориентированный стиль
  • Example#1688 - Процедурный стиль
  • Example#1689 - Объектно-ориентированный стиль
  • Example#1690 - Процедурный стиль
  • Example#1691 - Объектно-ориентированный стиль
  • Example#1692 - Процедурный стиль
  • Example#1693 - Объектно-ориентированный стиль
  • Example#1694 - Процедурный стиль
  • Example#1695 - A mysqli_get_cache_stats example
  • Example#1696 - Объектно-ориентированный стиль
  • Example#1697 - Enabling the plugin (php.ini)
  • Example#1698 - Minimal plugin-specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#1699 - Recommended minimal plugin-specific config (mysqlnd_ms_plugin.ini)
  • Example#1700 - Using one server as a master and as a slave (testing only!)
  • Example#1701 - Plugin specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#1702 - Opening a load balanced connection
  • Example#1703 - Executing statements
  • Example#1704 - Plugin config with one slave and one master
  • Example#1705 - Pitfall: connection state and SQL user variables
  • Example#1706 - Plugin config with one slave and one master
  • Example#1707 - SQL hints to prevent connection switches
  • Example#1708 - Fighting replication lag
  • Example#1709 - Table creation on a slave
  • Example#1710 - Plugin config with one slave and one master
  • Example#1711 - Using SQL hints for transactions
  • Example#1712 - Transaction aware load balancing: trx_stickiness setting
  • Example#1713 - Transaction aware
  • Example#1714 - Session consistency: read your writes
  • Example#1715 - Requesting session consistency
  • Example#1716 - Maximum age/slave lag
  • Example#1717 - Limiting slave lag
  • Example#1718 - Fail over not set
  • Example#1719 - No slave within time limit
  • Example#1720 - Create counter table on master
  • Example#1721 - Plugin config: SQL for client-side GTID injection
  • Example#1722 - Transparent global transaction ID injection
  • Example#1723 - Plugin config: SQL for fetching GTID
  • Example#1724 - Obtaining GTID after injection
  • Example#1725 - Plugin config: Checking for a certain GTID
  • Example#1726 - Session consistency service level and GTID combined
  • Example#1727 - Plugin config: using MySQL 5.6.5-m8 built-in GTID feature
  • Example#1728 - Recap: quality of service to request read your writes
  • Example#1729 - Plugin config: no special entries for caching
  • Example#1730 - Caching a slave request
  • Example#1731 - Read your writes and caching combined
  • Example#1732 - Provoking a connection error
  • Example#1733 - Connection error on query execution
  • Example#1734 - Provoking a connection error
  • Example#1735 - Most basic failover
  • Example#1736 - Converting a PHP array (hash) into JSON format
  • Example#1737 - Using section names example
  • Example#1738 - List of anonymous slaves
  • Example#1739 - Master list using symbolic names
  • Example#1740 - Keywords to configure a server
  • Example#1741 - New roundrobin filter, old functionality
  • Example#1742 - The user filter replaces mysqlnd_ms_set_user_pick_server
  • Example#1743 - Invalid filter sequence
  • Example#1744 - Random load balancing with random filter
  • Example#1745 - Random once load balancing with random filter
  • Example#1746 - roundrobin filter
  • Example#1747 - Setting a callback
  • Example#1748 - Using a callback
  • Example#1749 - Returning random masters and slaves
  • Example#1750 - Global limit on slave lag
  • Example#1751 - Optional master failover when failing to connect to slave
  • Example#1752 - Disabling lazy connection
  • Example#1753 - String escaping on a lazy connection handle
  • Example#1754 - Master on write for consistent reads
  • Example#1755 - Using master to execute transactions
  • Example#1756 - Using section names example
  • Example#1757 - List-like syntax
  • Example#1758 - Verify plugin activity in a non-threaded deployment model
  • Example#1759 - Recording statistics during shutdown
  • Example#1760 - Example demonstrating the usage of mysqlnd_ms constants
  • Example#1761 - mysqlnd_ms_get_last_gtid example
  • Example#1762 - mysqlnd_ms_get_last_used_connection example
  • Example#1763 - mysqlnd_ms_get_stats example
  • Example#1764 - mysqlnd_ms_match_wild example
  • Example#1765 - mysqlnd_ms_query_is_select example
  • Example#1766 - mysqlnd_ms_set_qos example
  • Example#1767 - mysqlnd_ms_set_user_pick_server example
  • Example#1768 - Enabling the plugin (php.ini)
  • Example#1769 - Using the MYSQLND_QC_ENABLE_SWITCH SQL hint
  • Example#1770 - Using the MYSQLND_QC_DISABLE_SWITCH SQL hint
  • Example#1771 - Example showing which type of statements are not cached
  • Example#1772 - Enabling caching for all statements using the mysqlnd_qc.cache_no_table ini setting
  • Example#1773 - Setting the TTL with the mysqlnd_qc.ttl ini setting
  • Example#1774 - Setting TTL with SQL hints
  • Example#1775 - Setting a callback with mysqlnd_qc_set_is_select
  • Example#1776 - Enabling the slam defense mechanism
  • Example#1777 - Collecting a query trace
  • Example#1778 - Setting the backtrace depth with the mysqlnd_qc.query_trace_bt_depth ini setting
  • Example#1779 - Collecting statistics data with the mysqlnd_qc.time_statistics ini setting
  • Example#1780 - Example mysqlnd_qc_get_cache_info usage
  • Example#1781 - Example mysqlnd_qc_get_normalized_query_trace_log usage
  • Example#1782 - Using a user-defined storage handler
  • Example#1783 - Using SQL hint constants
  • Example#1784 - Example mysqlnd_qc_set_cache_condition usage
  • Example#1785 - mysqlnd_qc_get_available_handlers example
  • Example#1786 - mysqlnd_qc_get_cache_info example
  • Example#1787 - mysqlnd_qc_get_core_stats example
  • Example#1788 - mysqlnd_qc_get_normalized_query_trace_log example
  • Example#1789 - mysqlnd_qc_get_query_trace_log example
  • Example#1790 - mysqlnd_qc_set_cache_condition example
  • Example#1791 - mysqlnd_qc_set_is_select example
  • Example#1792 - mysqlnd_qc_set_storage_handler example
  • Example#1793 - Enabling the plugin (php.ini)
  • Example#1794 - Pseudo-code: what a built-in class does
  • Example#1795 - Installing a proxy
  • Example#1796 - Proxy registration, mysqlnd_uh.enable=1
  • Example#1797 - Proxy installation disabled
  • Example#1798 - Connection proxy
  • Example#1799 - Prepared statement proxy
  • Example#1800 - Basic Monitoring
  • Example#1801 - MysqlndUhConnection::changeUser example
  • Example#1802 - MysqlndUhConnection::charsetName example
  • Example#1803 - MysqlndUhConnection::close example
  • Example#1804 - MysqlndUhConnection::connect example
  • Example#1805 - MysqlndUhConnection::endPSession example
  • Example#1806 - MysqlndUhConnection::escapeString example
  • Example#1807 - MysqlndUhConnection::getAffectedRows example
  • Example#1808 - MysqlndUhConnection::getErrorNumber example
  • Example#1809 - MysqlndUhConnection::getErrorString example
  • Example#1810 - MysqlndUhConnection::getFieldCount example
  • Example#1811 - MysqlndUhConnection::getHostInformation example
  • Example#1812 - MysqlndUhConnection::getLastInsertId example
  • Example#1813 - MysqlndUhConnection::getLastMessage example
  • Example#1814 - MysqlndUhConnection::getProtocolInformation example
  • Example#1815 - MysqlndUhConnection::getServerInformation example
  • Example#1816 - MysqlndUhConnection::getServerStatistics example
  • Example#1817 - MysqlndUhConnection::getServerVersion example
  • Example#1818 - MysqlndUhConnection::getSqlstate example
  • Example#1819 - MysqlndUhConnection::getStatistics example
  • Example#1820 - MysqlndUhConnection::getThreadId example
  • Example#1821 - MysqlndUhConnection::getWarningCount example
  • Example#1822 - MysqlndUhConnection::init example
  • Example#1823 - MysqlndUhConnection::kill example
  • Example#1824 - MysqlndUhConnection::listFields example
  • Example#1825 - MysqlndUhConnection::listMethod example
  • Example#1826 - MysqlndUhConnection::moreResults example
  • Example#1827 - MysqlndUhConnection::nextResult example
  • Example#1828 - MysqlndUhConnection::ping example
  • Example#1829 - MysqlndUhConnection::query example
  • Example#1830 - MysqlndUhConnection::queryReadResultsetHeader example
  • Example#1831 - MysqlndUhConnection::reapQuery example
  • Example#1832 - MysqlndUhConnection::refreshServer example
  • Example#1833 - MysqlndUhConnection::restartPSession example
  • Example#1834 - MysqlndUhConnection::selectDb example
  • Example#1835 - MysqlndUhConnection::sendClose example
  • Example#1836 - MysqlndUhConnection::sendQuery example
  • Example#1837 - MysqlndUhConnection::serverDumpDebugInformation example
  • Example#1838 - MysqlndUhConnection::setAutocommit example
  • Example#1839 - MysqlndUhConnection::setCharset example
  • Example#1840 - MysqlndUhConnection::setClientOption example
  • Example#1841 - MysqlndUhConnection::setServerOption example
  • Example#1842 - MysqlndUhConnection::simpleCommand example
  • Example#1843 - MysqlndUhConnection::simpleCommandHandleResponse example
  • Example#1844 - MysqlndUhConnection::sslSet example
  • Example#1845 - MysqlndUhConnection::stmtInit example
  • Example#1846 - MysqlndUhConnection::storeResult example
  • Example#1847 - MysqlndUhConnection::txCommit example
  • Example#1848 - MysqlndUhConnection::txRollback example
  • Example#1849 - MysqlndUhConnection::useResult example
  • Example#1850 - MysqlndUhPreparedStatement::execute example
  • Example#1851 - MysqlndUhPreparedStatement::prepare example
  • Example#1852 - mysqlnd_uh_convert_to_mysqlnd example
  • Example#1853 - mysqlnd_uh_set_connection_proxy example
  • Example#1854 - Простой запрос
  • Example#1855 - Вставка с использованием привязанных переменных
  • Example#1856 - Вставка данных в поле типа CLOB
  • Example#1857 - Использование PL/SQL хранимых процедур
  • Example#1858 - Использование PL/SQL хранимых процедур
  • Example#1859 - Вызов PL/SQL процедур, возвращающих REF CURSOR
  • Example#1860 - Пример использования oci_bind_array_by_name
  • Example#1861 - Добавление данных с использованием oci_bind_by_name
  • Example#1862 - Одна привязка для многократного использования
  • Example#1863 - Прикрепление в цикле foreach
  • Example#1864 - Прикрепление в выражение WHERE
  • Example#1865 - Прикрепление в выражение LIKE
  • Example#1866 - Прикрепление в выражение REGEXP_LIKE
  • Example#1867 - Прикрепление нескольких значений в выржаение IN
  • Example#1868 - Прикрепеление ROWID, возвращаемое запросом
  • Example#1869 - OUT-прикрепление ROWID, возвращаемое при INSERT
  • Example#1870 - Прикрепление для хранимой функции PL/SQL
  • Example#1871 - Прикрепление параметров для PL/SQL хранимой процедуры
  • Example#1872 - Прикрепление CLOB-объекта
  • Example#1873 - Пример использования oci_client_version
  • Example#1874 - Закрытие соединения
  • Example#1875 - Соединение базы данных не закрывается до тех пор, пока не будут закрыты все его ссылки
  • Example#1876 - Закрытие соединения, открытого несколько раз
  • Example#1877 - Соединение закрывается при уходе переменных из области видимости
  • Example#1878 - Пример использования oci_commit
  • Example#1879 - Пример использования oci_connect с синтаксисом Easy Connect
  • Example#1880 - Пример использования oci_connect используя имя Network Connect
  • Example#1881 - Пример использования oci_connect с использованием определенного набора символов
  • Example#1882 - Пример использования многократных вызовов oci_connect
  • Example#1883 - Пример использования oci_define_by_name
  • Example#1884 - Пример использования oci_define_by_name с регистрозависимыми именами столбцов
  • Example#1885 - Пример использования oci_define_by_name со столбцами типа LOB
  • Example#1886 - Пример использования oci_define_by_name с приведенными типами
  • Example#1887 - Вывод сообщения об ошибке Oracle после ошибки соединения
  • Example#1888 - Вывод сообщения об ошибке Oracle после ошибки разбора
  • Example#1889 - Вывод сообщения об ошибке Oracle, ошибочного запроса и позиции ошибки запуска запроса
  • Example#1890 - oci_execute при выолнении запросов
  • Example#1891 - oci_execute без указания определенного режима
  • Example#1892 - oci_execute с OCI_NO_AUTO_COMMIT
  • Example#1893 - oci_execute с различными режимами
  • Example#1894 - oci_execute с OCI_DESCRIBE_ONLY
  • Example#1895 - Пример использования oci_fetch_all
  • Example#1896 - Пример использования oci_fetch_all с OCI_FETCHSTATEMENT_BY_ROW
  • Example#1897 - Пример использования oci_fetch_all с OCI_NUM
  • Example#1898 - oci_fetch_array с OCI_BOTH
  • Example#1899 - oci_fetch_array с OCI_NUM
  • Example#1900 - oci_fetch_array с OCI_ASSOC
  • Example#1901 - oci_fetch_array с OCI_RETURN_NULLS
  • Example#1902 - oci_fetch_array с OCI_RETURN_LOBS
  • Example#1903 - oci_fetch_array с регистрозависимыми названиями полей
  • Example#1904 - oci_fetch_array с полями с одинаковыми названиями
  • Example#1905 - oci_fetch_array с полями DATE
  • Example#1906 - oci_fetch_array с REF CURSOR
  • Example#1907 - oci_fetch_array с LIMIT-подобным запросом
  • Example#1908 - Пример использования oci_fetch_object
  • Example#1909 - Пример использования oci_fetch_object с названиями столбцов в различных регистрах
  • Example#1910 - Пример использования oci_fetch_object с LOB
  • Example#1911 - Пример использования oci_fetch с определенными переменными
  • Example#1912 - Пример использования oci_fetch с oci_result
  • Example#1913 - Пример использования oci_field_name
  • Example#1914 - Пример использования oci_field_size
  • Example#1915 - Пример использования oci_field_type
  • Example#1916 - Пример использованияoci_new_connect
  • Example#1917 - Использование REF CURSOR в хранимых процедурах Oracle
  • Example#1918 - Использование REF CURSOR в запросах Oracle
  • Example#1919 - Пример использования oci_new_descriptor
  • Example#1920 - Пример использования oci_new_descriptor
  • Example#1921 - Пример использования oci_num_fields
  • Example#1922 - Пример использования oci_num_rows
  • Example#1923 - Пример использования oci_parse с SQL-запросами
  • Example#1924 - Пример использования oci_parse с PL/SQL-запросами
  • Example#1925 - Пример использования oci_rollback
  • Example#1926 - Пример использования отката до SAVEPOINT
  • Example#1927 - Пример использования oci_server_version
  • Example#1928 - Установка действия
  • Example#1929 - Установка идентификатора клиента для пользователя
  • Example#1930 - Установка клиентской информации
  • Example#1931 - Два скрипта могут использовать различные версии функции myfunc() одновременно
  • Example#1932 - Установка имени модуля
  • Example#1933 - Смена значения предворительной выборки по умолчанию для запроса
  • Example#1934 - Смена значения предварительной выборки по умолчанию для выборки REF CURSOR
  • Example#1935 - Установка значения предварительной выборки при передаче REF CURSOR обратно в Oracle
  • Example#1936 - Пример использования oci_statement_type
  • Example#1937 - Connect to Ovrimos SQL Server and select from a system table
  • Example#1938 - ovrimos_connect Example
  • Example#1939 - A fetch into example
  • Example#1940 - A fetch row example
  • Example#1941 - ovrimos_prepare Example
  • Example#1942 - Prepare a statement, execute, and view the result
  • Example#1943 - ovrimos_result_all with meta-information
  • Example#1944 - Creating a Paradox database with two fields
  • Example#1945 - Turn a paradox date into a human readable form
  • Example#1946 - Set the date/time fields in a paradox database to the current date/time
  • Example#1947 - Opening a Paradox database
  • Example#1948 - Opening a Paradox database
  • Example#1949 - Turn a paradox timestamp into a human readable form
  • Example#1950 - Пример работы с расширением PostgreSQL
  • Example#1951 - Пример использования pg_affected_rows
  • Example#1952 - Пример использования pg_cancel_query
  • Example#1953 - Пример использования pg_client_encoding
  • Example#1954 - Пример использования pg_close
  • Example#1955 - Использование функции pg_connect
  • Example#1956 - Пример использования pg_connection_busy
  • Example#1957 - Пример использования pg_connection_reset
  • Example#1958 - Пример использования pg_connection_status
  • Example#1959 - Пример использования pg_convert
  • Example#1960 - Пример использования pg_copy_from
  • Example#1961 - Пример использования pg_copy_to
  • Example#1962 - Пример использования pg_dbname
  • Example#1963 - Пример использования pg_delete
  • Example#1964 - Пример использования pg_end_copy
  • Example#1965 - Пример использования pg_escape_bytea
  • Example#1966 - pg_escape_identifier example
  • Example#1967 - pg_escape_literal example
  • Example#1968 - Пример использования pg_escape_string
  • Example#1969 - Пример использования pg_execute
  • Example#1970 - Пример использования pg_fetch_all_columns
  • Example#1971 - Пример использования
  • Example#1972 - Пример использования pg_fetch_array
  • Example#1973 - Пример использования pg_fetch_assoc
  • Example#1974 - Пример использования pg_fetch_object
  • Example#1975 - Пример использования pg_fetch_result
  • Example#1976 - Пример использования pg_fetch_row
  • Example#1977 - Пример использования pg_field_is_null
  • Example#1978 - Получение информации о полях выборки
  • Example#1979 - Получение информации о полях выборки
  • Example#1980 - Получение информации о полях выборки
  • Example#1981 - Получение информации о полях выборки
  • Example#1982 - Получение информации о поле выборки
  • Example#1983 - Получение информации о полях выборки
  • Example#1984 - Получение информации о поле выборки
  • Example#1985 - Пример использования pg_free_result
  • Example#1986 - PostgreSQL NOTIFY сообщение
  • Example#1987 - PID сервера PostgreSQL
  • Example#1988 - Пример использования pg_get_result
  • Example#1989 - Пример использования pg_host
  • Example#1990 - Пример использования pg_insert
  • Example#1991 - Пример использования pg_last_error
  • Example#1992 - Пример использования pg_last_notice
  • Example#1993 - Пример использования pg_last_oid
  • Example#1994 - Пример использования pg_lo_close
  • Example#1995 - Пример использования pg_lo_create
  • Example#1996 - Пример использования pg_lo_export
  • Example#1997 - Пример использования pg_lo_import
  • Example#1998 - Пример использования pg_lo_open
  • Example#1999 - Пример использования pg_lo_read_all
  • Example#2000 - Пример использования pg_lo_read
  • Example#2001 - Пример использования pg_lo_seek
  • Example#2002 - Пример использования pg_lo_tell
  • Example#2003 - Пример использования pg_lo_unlink
  • Example#2004 - Пример использования pg_lo_write
  • Example#2005 - Получение метаданных таблицы
  • Example#2006 - Пример использования pg_num_fields
  • Example#2007 - Пример использования pg_num_rows
  • Example#2008 - Пример использования pg_options
  • Example#2009 - Пример использования pg_parameter_status
  • Example#2010 - Пример использования pg_pconnect
  • Example#2011 - Пример использования pg_ping
  • Example#2012 - Пример использования pg_port
  • Example#2013 - Пример использования pg_prepare
  • Example#2014 - Пример использования pg_put_line
  • Example#2015 - Пример использования pg_query_params
  • Example#2016 - Пример использования pg_query
  • Example#2017 - Использование нескольких выражений в pg_query
  • Example#2018 - Пример использования pg_result_error_field
  • Example#2019 - Пример использования pg_result_error
  • Example#2020 - Пример использования pg_result_seek
  • Example#2021 - Пример использования pg_result_status
  • Example#2022 - Пример использования pg_select
  • Example#2023 - Пример использования pg_send_execute
  • Example#2024 - Пример использования pg_send_prepare
  • Example#2025 - Пример использования pg_send_query_params
  • Example#2026 - Пример использования pg_send_query
  • Example#2027 - Пример использования pg_set_client_encoding
  • Example#2028 - Пример использования pg_set_error_verbosity
  • Example#2029 - Пример использования pg_trace
  • Example#2030 - Пример использования pg_transaction_status
  • Example#2031 - Пример использования pg_tty
  • Example#2032 - Пример использования pg_unescape_bytea
  • Example#2033 - Пример использования pg_untrace
  • Example#2034 - Пример использования pg_update
  • Example#2035 - Пример использования pg_version
  • Example#2036 - Процедурный стиль
  • Example#2037 - Объектно-ориентированный стиль
  • Example#2038 - Процедурный стиль
  • Example#2039 - Объектно-ориентированный стиль
  • Example#2040 - Процедурный стиль
  • Example#2041 - Объектно-ориентированный стиль
  • Example#2042 - Пример использования sqlite_close
  • Example#2043 - Пример агрегирующей функции max_length
  • Example#2044 - Пример использования sqlite_create_function
  • Example#2045 - Пример использования функции php
  • Example#2046 - Пример с использованием процедурного стиля
  • Example#2047 - Object-oriented example
  • Example#2048 - Пример использования sqlite_factory
  • Example#2049 - Процедурный стиль
  • Example#2050 - Объектно-ориентированный стиль
  • Example#2051 - Процедурный стиль
  • Example#2052 - Объектно-ориентированный стиль
  • Example#2053 - Процедурный стиль
  • Example#2054 - Объектно-ориентированный стиль
  • Example#2055 - Пример использования sqlite_fetch_single
  • Example#2056 - Процедурный стиль
  • Example#2057 - Объектно-ориентированнный стиль
  • Example#2058 - Пример использованияsqlite_open
  • Example#2059 - Пример реализации агрегирующей функции max_length, способной работать с бинарными данными
  • Example#2060 - SQLite3::changes example
  • Example#2061 - SQLite3::close example
  • Example#2062 - SQLite3::__construct example
  • Example#2063 - SQLite3::createFunction example
  • Example#2064 - SQLite3::exec example
  • Example#2065 - SQLite3::loadExtension example
  • Example#2066 - SQLite3::open example
  • Example#2067 - Пример SQLite3::prepare
  • Example#2068 - Пример SQLite3::query
  • Example#2069 - SQLite3::querySingle example
  • Example#2070 - SQLite3::version example
  • Example#2071 - SQLite3Stmt::bindValue example
  • Example#2072 - sqlsrv_begin_transaction example
  • Example#2073 - sqlsrv_cancel example
  • Example#2074 - sqlsrv_client_info example
  • Example#2075 - sqlsrv_close example
  • Example#2076 - sqlsrv_commit example
  • Example#2077 - Connect using Windows Authentication.
  • Example#2078 - Connect by specifying a user name and password.
  • Example#2079 - Connect on a specifed port.
  • Example#2080 - functionname example
  • Example#2081 - sqlsrv_execute example
  • Example#2082 - Retrieving an associative array.
  • Example#2083 - Retrieving a numeric array.
  • Example#2084 - sqlsrv_fetch_object example
  • Example#2085 - sqlsrv_fetch example
  • Example#2086 - sqlsrv_field_metadata example
  • Example#2087 - sqlsrv_free_stmt example
  • Example#2088 - sqlsrv_get_field example
  • Example#2089 - sqlsrv_has_rows example
  • Example#2090 - sqlsrv_next_result example
  • Example#2091 - sqlsrv_num_fields example
  • Example#2092 - sqlsrv_num_rows example
  • Example#2093 - sqlsrv_prepare example
  • Example#2094 - sqlsrv_query example
  • Example#2095 - sqlsrv_rollback example
  • Example#2096 - sqlsrv_rows_affected example
  • Example#2097 - sqlsrv_send_stream_data example
  • Example#2098 - sqlsrv_server_info example
  • Example#2099 - Delete-Query
  • Example#2100 - sybase_connect example
  • Example#2101 - Identical fieldnames
  • Example#2102 - sybase_fetch_object return as Foo
  • Example#2103 - sybase_set_message_handler callback function
  • Example#2104 - sybase_set_message_handler callback to a class
  • Example#2105 - sybase_set_message_handler unhandled messages
  • Example#2106 - sybase_unbuffered_query example
  • Example#2107 - Putting and getting a key-value pair
  • Example#2108 - TokyoTyrant::add example
  • Example#2109 - TokyoTyrant::connect example
  • Example#2110 - TokyoTyrant::connectUri example
  • Example#2111 - TokyoTyrant::copy example
  • Example#2112 - TokyoTyrant::ext example
  • Example#2113 - TokyoTyrant::fwmKeys example
  • Example#2114 - TokyoTyrant::get example
  • Example#2115 - TokyoTyrant::getIterator example
  • Example#2116 - TokyoTyrant::num example
  • Example#2117 - TokyoTyrant::out example
  • Example#2118 - TokyoTyrant::put example
  • Example#2119 - TokyoTyrant::putCat example
  • Example#2120 - tokyotyrant::putKeep example
  • Example#2121 - TokyoTyrant::putNr example
  • Example#2122 - TokyoTyrant::putShl example
  • Example#2123 - TokyoTyrant::setMaster example
  • Example#2124 - TokyoTyrant::size example
  • Example#2125 - TokyoTyrant::stat example
  • Example#2126 - TokyoTyrant::vanish example
  • Example#2127 - TokyoTyrantTable::genUid example
  • Example#2128 - TokyoTyrantTable::get example
  • Example#2129 - TokyoTyrantTable::getIterator example
  • Example#2130 - TokyoTyrantTable::getQuery example
  • Example#2131 - TokyoTyrantTable::out example
  • Example#2132 - TokyoTyrantTable::put example
  • Example#2133 - TokyoTyrantTable::putCat example
  • Example#2134 - TokyoTyrantTable::putKeep example
  • Example#2135 - TokyoTyrantQuery::addCond example
  • Example#2136 - TokyoTyrantQuery::__construct example
  • Example#2137 - TokyoTyrantQuery::count example
  • Example#2138 - TokyoTyrantQuery iterator example
  • Example#2139 - TokyoTyrantQuery::hint example
  • Example#2140 - TokyoTyrantQuery iterator example
  • Example#2141 - TokyoTyrantQuery::metaSearch example
  • Example#2142 - TokyoTyrantQuery iterator example
  • Example#2143 - TokyoTyrantQuery::out example
  • Example#2144 - TokyoTyrantQuery iterator example
  • Example#2145 - TokyoTyrantQuery::search example
  • Example#2146 - TokyoTyrantQuery iterator example
  • Example#2147 - TokyoTyrantIterator::__construct example
  • Example#2148 - Closing an open file descriptor
  • Example#2149 - Setting and clearing a lock
  • Example#2150 - Opening a file descriptor
  • Example#2151 - Positioning in a file
  • Example#2152 - Setting the baud rate on a serial port
  • Example#2153 - Пример использования chdir
  • Example#2154 - Пример использования chroot
  • Example#2155 - Пример использования closedir
  • Example#2156 - Пример использования dir
  • Example#2157 - Пример использования getcwd
  • Example#2158 - Пример использования функции opendir
  • Example#2159 - Вывести список всех элементов каталога
  • Example#2160 - Получить список элементов в текущем каталоге и отбросить элементы с именами . и ..
  • Example#2161 - Простой пример использования функции scandir
  • Example#2162 - Альтернативный вариант функции scandir для PHP 4
  • Example#2163 - A finfo_buffer example
  • Example#2164 - Пример использования finfo_file
  • Example#2165 - Объектно-ориентированный стиль
  • Example#2166 - Процедурный стиль
  • Example#2167 - Пример mime_content_type
  • Example#2168 - Пример использования функции basename
  • Example#2169 - Изменение группы файла
  • Example#2170 - Пример простого использования chown
  • Example#2171 - Пример использования clearstatcache
  • Example#2172 - Пример использования функции copy
  • Example#2173 - Пример использования функции dirname
  • Example#2174 - Пример использования функции disk_free_space
  • Example#2175 - Пример использования disk_total_space
  • Example#2176 - Простой пример использования функции fclose
  • Example#2177 - Обработка таймаутов с функцией feof
  • Example#2178 - Пример feof с неверным файловым указателем
  • Example#2179 - Пример записи файла с помощью fflush
  • Example#2180 - Пример использования функции fgetc
  • Example#2181 - Чтение и вывод на экран содержимого CSV-файла
  • Example#2182 - Построчное чтение файла
  • Example#2183 - Построчное чтение PHP-файла
  • Example#2184 - Проверка существования файла
  • Example#2185 - Получить и вывести исходный код домашней страницы вебсайта
  • Example#2186 - Поиск файлов в include_path
  • Example#2187 - Чтение секции файла
  • Example#2188 - Использование потоковых контекстов
  • Example#2189 - Пример простого использования
  • Example#2190 - Использование флагов
  • Example#2191 - Пример использования file
  • Example#2192 - Пример использования функции fileatime
  • Example#2193 - Пример использования функции filectime
  • Example#2194 - Поиск группы файла
  • Example#2195 - Сравнение индексного дескриптора файла с текущим файлом
  • Example#2196 - Пример использования функции filemtime
  • Example#2197 - Находим владельца файла
  • Example#2198 - Отображение прав доступа в виде восьмеричного числа
  • Example#2199 - Отображение полных прав доступа
  • Example#2200 - Пример использования функции filesize
  • Example#2201 - Пример использования функции filetype
  • Example#2202 - Пример использования функции flock
  • Example#2203 - Использование flock с параметром LOCK_NB
  • Example#2204 - Проверяет соответствие цвета шаблону подстановки
  • Example#2205 - Примеры использования fopen
  • Example#2206 - Использование fpassthru с бинарными файлами
  • Example#2207 - Пример использования fputcsv
  • Example#2208 - Простой пример использования fread
  • Example#2209 - Пример бинарного чтения с помощью fread
  • Example#2210 - Примеры удаленного чтения с помощью fread
  • Example#2211 - Пример использования функции fscanf
  • Example#2212 - Содержимое файла users.txt
  • Example#2213 - Пример использования функции fseek
  • Example#2214 - Пример использования функции fstat
  • Example#2215 - Пример использования функции ftell
  • Example#2216 - Пример обрезания файла
  • Example#2217 - Простой пример использования fwrite
  • Example#2218 - Удобный способ, как при помощи glob можно заменить opendir и её друзей.
  • Example#2219 - Пример использования функции is_dir
  • Example#2220 - Пример использования функции is_executable
  • Example#2221 - Пример использования is_file
  • Example#2222 - Создаем файл и подтверждаем, что он является символической ссылкой
  • Example#2223 - is_readable example
  • Example#2224 - Пример использования функции is_uploaded_file
  • Example#2225 - Пример использования is_writable
  • Example#2226 - Пример изменения группы символической ссылки
  • Example#2227 - Изменение владельца символической ссылки
  • Example#2228 - Создание простой жесткой ссылки
  • Example#2229 - Пример использования функции linkinfo
  • Example#2230 - Сравнение функций stat и lstat
  • Example#2231 - Пример использования функции mkdir
  • Example#2232 - Использование mkdir с параметром recursive
  • Example#2233 - Загрузка нескольких файлов
  • Example#2234 - Содержимое sample.ini
  • Example#2235 - Пример использования функции parse_ini_file
  • Example#2236 - Обработка php.ini файла функцией parse_ini_file
  • Example#2237 - Пример использования функции pathinfo
  • Example#2238 - Пример с pathinfo, показывающий разницу между null и отсутствием расширения.
  • Example#2239 - Пример использования pclose
  • Example#2240 - Пример использования функции popen
  • Example#2241 - popen example
  • Example#2242 - Форсирование скачки с помощью readfile
  • Example#2243 - Пример использования функции readlink
  • Example#2244 - Пример использования realpath_cache_get
  • Example#2245 - Пример использования realpath_cache_size
  • Example#2246 - Пример использования функции realpath
  • Example#2247 - realpath на Windows
  • Example#2248 - Пример использования функции rename
  • Example#2249 - Пример перезаписи rewind
  • Example#2250 - Пример использования rmdir
  • Example#2251 - Пример использования stat
  • Example#2252 - Использование информации из stat вместе с touch
  • Example#2253 - Создание символической ссылки
  • Example#2254 - Пример использования функции tempnam
  • Example#2255 - Пример использования функции tmpfile
  • Example#2256 - Пример использования функции touch
  • Example#2257 - Использование touch с параметром time
  • Example#2258 - Пример использования umask
  • Example#2259 - Пример простого использования unlink
  • Example#2260 - Example usage of inotify
  • Example#2261 - Setting the path to magic.mime
  • Example#2262 - setproctitle example
  • Example#2263 - setthreadtitle example
  • Example#2264 - Проверить, подписан ли файл системным администратором
  • Example#2265 - Вывести имена всех расширенных атрибутов файла
  • Example#2266 - Удалить все расширенные атрибуты файла
  • Example#2267 - Установить расширенные атрибуты .wav файла
  • Example#2268 - xattr_supported example
  • Example#2269 - xdiff_file_bdiff_size example
  • Example#2270 - xdiff_file_bdiff example
  • Example#2271 - xdiff_file_bpatch example
  • Example#2272 - xdiff_file_diff_binary example
  • Example#2273 - xdiff_file_diff example
  • Example#2274 - xdiff_file_merge3 example
  • Example#2275 - xdiff_file_patch_binary example
  • Example#2276 - xdiff_file_patch example
  • Example#2277 - Patch reversing example
  • Example#2278 - xdiff_file_rabdiff example
  • Example#2279 - xdiff_string_bdiff_size example
  • Example#2280 - xdiff_string_diff example
  • Example#2281 - xdiff_string_patch example
  • Example#2282 - Enchant Usage Example
  • Example#2283 - List the backends provided by the given broker
  • Example#2284 - A enchant_broker_dict_exists example
  • Example#2285 - List all available dictionaries for one broker
  • Example#2286 - A enchant_broker_request_dict example
  • Example#2287 - A enchant_dict_describe example
  • Example#2288 - A enchant_dict_quick_check example
  • Example#2289 - A enchant_dict_suggest example
  • Example#2290 - Пример использования bindtextdomain
  • Example#2291 - gettext-check
  • Example#2292 - Пример использования ngettext
  • Example#2293 - Пример использования iconv_get_encoding
  • Example#2294 - Пример использования iconv_mime_decode_headers
  • Example#2295 - Пример использования iconv_mime_decode
  • Example#2296 - Пример использования iconv_mime_encode
  • Example#2297 - Пример использования iconv_set_encoding
  • Example#2298 - Пример использования iconv
  • Example#2299 - Пример использования ob_iconv_handler
  • Example#2300 - Example of using the procedural API
  • Example#2301 - Example of using the object-oriented API
  • Example#2302 - FRENCH_COLLATION rules
  • Example#2303 - ALTERNATE_HANDLING rules
  • Example#2304 - CASE_FIRST rules
  • Example#2305 - CASE_LEVEL rules
  • Example#2306 - collator_asortexample
  • Example#2307 - collator_compareexample
  • Example#2308 - Collator::__construct example
  • Example#2309 - collator_create example
  • Example#2310 - collator_get_attribute example
  • Example#2311 - collator_get_error_code example
  • Example#2312 - collator_get_error_message example
  • Example#2313 - collator_get_locale example
  • Example#2314 - collator_get_sort_keyexample
  • Example#2315 - collator_get_strength example
  • Example#2316 - collator_set_attribute example
  • Example#2317 - collator_set_strength example
  • Example#2318 - collator_sort_with_sort_keys example
  • Example#2319 - collator_sort example
  • Example#2320 - numfmt_create example
  • Example#2321 - NumberFormatter::create example
  • Example#2322 - numfmt_format_currency example
  • Example#2323 - OO example
  • Example#2324 - numfmt_format example
  • Example#2325 - OO example
  • Example#2326 - numfmt_get_attribute example
  • Example#2327 - OO example
  • Example#2328 - numfmt_get_error_code example
  • Example#2329 - OO example
  • Example#2330 - numfmt_get_error_message example
  • Example#2331 - OO example
  • Example#2332 - numfmt_get_locale example
  • Example#2333 - numfmt_get_pattern example
  • Example#2334 - OO example
  • Example#2335 - numfmt_get_symbol example
  • Example#2336 - OO example
  • Example#2337 - numfmt_get_text_attribute example
  • Example#2338 - OO example
  • Example#2339 - numfmt_parse_currency example
  • Example#2340 - OO example
  • Example#2341 - numfmt_parse example
  • Example#2342 - OO example
  • Example#2343 - numfmt_set_attribute example
  • Example#2344 - OO example
  • Example#2345 - numfmt_set_pattern example
  • Example#2346 - OO example
  • Example#2347 - numfmt_set_symbol example
  • Example#2348 - OO example
  • Example#2349 - numfmt_set_text_attribute example
  • Example#2350 - OO example
  • Example#2351 - locale_accept_from_http example
  • Example#2352 - OO example
  • Example#2353 - locale_compose example
  • Example#2354 - OO example
  • Example#2355 - locale_filter_matches example
  • Example#2356 - OO example
  • Example#2357 - locale_get_all_variants example
  • Example#2358 - OO example
  • Example#2359 - locale_get_default example
  • Example#2360 - OO example
  • Example#2361 - locale_get_display_language example
  • Example#2362 - OO example
  • Example#2363 - locale_get_display_name example
  • Example#2364 - OO example
  • Example#2365 - locale_get_display_region example
  • Example#2366 - OO example
  • Example#2367 - locale_get_display_script example
  • Example#2368 - OO example
  • Example#2369 - locale_get_display_variant example
  • Example#2370 - OO example
  • Example#2371 - locale_get_keywords example
  • Example#2372 - OO example
  • Example#2373 - locale_get_primary_language example
  • Example#2374 - OO example
  • Example#2375 - locale_get_region example
  • Example#2376 - OO example
  • Example#2377 - locale_get_script example
  • Example#2378 - OO example
  • Example#2379 - locale_lookup example
  • Example#2380 - OO example
  • Example#2381 - locale_parse example
  • Example#2382 - OO example
  • Example#2383 - locale_set_default example
  • Example#2384 - OO example
  • Example#2385 - normalizer_is_normalized example
  • Example#2386 - OO example
  • Example#2387 - normalizer_normalize example
  • Example#2388 - OO example
  • Example#2389 - msgfmt_create example
  • Example#2390 - OO example
  • Example#2391 - msgfmt_format_message example
  • Example#2392 - OO example
  • Example#2393 - msgfmt_format example
  • Example#2394 - OO example
  • Example#2395 - msgfmt_get_error_code example
  • Example#2396 - OO example
  • Example#2397 - msgfmt_get_error_message example
  • Example#2398 - OO example
  • Example#2399 - msgfmt_get_locale example
  • Example#2400 - OO example
  • Example#2401 - msgfmt_get_pattern example
  • Example#2402 - OO example
  • Example#2403 - msgfmt_parse_message example
  • Example#2404 - OO example
  • Example#2405 - msgfmt_parse example
  • Example#2406 - OO example
  • Example#2407 - msgfmt_set_pattern example
  • Example#2408 - OO example
  • Example#2409 - datefmt_create example
  • Example#2410 - OO example
  • Example#2411 - datefmt_format example
  • Example#2412 - OO example
  • Example#2413 - datefmt_get_calendar example
  • Example#2414 - OO example
  • Example#2415 - datefmt_get_datetype example
  • Example#2416 - OO example
  • Example#2417 - datefmt_get_error_code example
  • Example#2418 - OO example
  • Example#2419 - datefmt_get_error_message example
  • Example#2420 - OO example
  • Example#2421 - datefmt_get_locale example
  • Example#2422 - OO example
  • Example#2423 - datefmt_get_pattern example
  • Example#2424 - OO example
  • Example#2425 - datefmt_get_timetype example
  • Example#2426 - OO example
  • Example#2427 - datefmt_get_timezone_id example
  • Example#2428 - OO example
  • Example#2429 - datefmt_is_lenient example
  • Example#2430 - OO example
  • Example#2431 - datefmt_localtime example
  • Example#2432 - OO example
  • Example#2433 - datefmt_parse example
  • Example#2434 - OO example
  • Example#2435 - datefmt_set_calendar example
  • Example#2436 - OO example
  • Example#2437 - datefmt_set_lenient example
  • Example#2438 - OO example
  • Example#2439 - datefmt_set_pattern example
  • Example#2440 - OO example
  • Example#2441 - datefmt_set_timezone_id example
  • Example#2442 - OO example
  • Example#2443 - resourcebundle_count example
  • Example#2444 - OO example
  • Example#2445 - resourcebundle_create example
  • Example#2446 - ResourceBundle::create example
  • Example#2447 - resourcebundle_get_error_code example
  • Example#2448 - OO example
  • Example#2449 - resourcebundle_get_error_message example
  • Example#2450 - OO example
  • Example#2451 - resourcebundle_get example
  • Example#2452 - OO example
  • Example#2453 - resourcebundle_locales example
  • Example#2454 - OO example
  • Example#2455 - Converting escaped UTF-16 code units
  • Example#2456 - grapheme_extract example
  • Example#2457 - grapheme_stripos example
  • Example#2458 - grapheme_stristr example
  • Example#2459 - grapheme_strlen example
  • Example#2460 - grapheme_strpos example
  • Example#2461 - grapheme_strripos example
  • Example#2462 - grapheme_strrpos example
  • Example#2463 - grapheme_strstr example
  • Example#2464 - grapheme_substr example
  • Example#2465 - idn_to_ascii example
  • Example#2466 - idn_to_utf8 example
  • Example#2467 - intl_error_name example
  • Example#2468 - intl_get_error_code example
  • Example#2469 - intl_get_error_message example
  • Example#2470 - intl_is_failure example
  • Example#2471 - Примеры настроек php.ini
  • Example#2472 - Настройки php.ini для пользователей EUC-JP
  • Example#2473 - Настройки php.ini для пользователей SJIS
  • Example#2474 - Отключение преобразования кодировки HTTP ввода в php.ini
  • Example#2475 - Пример настройки php.ini
  • Example#2476 - Пример скрипта
  • Example#2477 - Пример использования mb_convert_case
  • Example#2478 - Пример использования mb_convert_case с нелатинским UTF-8 текстом
  • Example#2479 - Пример использования mb_convert_encoding
  • Example#2480 - Пример использования mb_convert_kana
  • Example#2481 - Пример использования mb_convert_variables
  • Example#2482 - Пример convmap
  • Example#2483 - Пример использования mb_detect_encoding
  • Example#2484 - Пример бесполезных списков
  • Example#2485 - Пример использования mb_detect_order
  • Example#2486 - Пример использования mb_encode_mimeheader
  • Example#2487 - Пример convmap
  • Example#2488 - Пример использования mb_encode_numericentity
  • Example#2489 - Пример использования mb_encoding_aliases
  • Example#2490 - mb_ereg_replace_callback example
  • Example#2491 - mb_ereg_replace_callback using anonymous function supported in PHP 5.3.0 or later
  • Example#2492 - Пример использования mb_internal_encoding
  • Example#2493 - Пример использования mb_list_encodings
  • Example#2494 - Пример использования mb_output_handler
  • Example#2495 - Пример использования mb_preferred_mime_name
  • Example#2496 - Пример использования mb_strimwidth
  • Example#2497 - Пример использования mb_strtolower
  • Example#2498 - Пример использовани mb_strtolower с нелатинскими буквами
  • Example#2499 - Пример использования mb_strtoupper
  • Example#2500 - Пример использования mb_strtoupper с нелатинскими буквами
  • Example#2501 - Пример использования mb_substitute_character
  • Example#2502 - Пример использования mb_substr_count
  • Example#2503 - pspell_add_to_personal
  • Example#2504 - Пример использования pspell_check
  • Example#2505 - Пример использования pspell_add_to_personal
  • Example#2506 - pspell_config_create
  • Example#2507 - pspell_config_ignore
  • Example#2508 - Пример использования pspell_config_mode
  • Example#2509 - pspell_config_personal
  • Example#2510 - pspell_config_repl
  • Example#2511 - pspell_config_runtogether
  • Example#2512 - pspell_new_config
  • Example#2513 - pspell_new_personal
  • Example#2514 - pspell_new
  • Example#2515 - pspell_add_to_personal
  • Example#2516 - pspell_store_replacement
  • Example#2517 - Пример использования pspell_suggest
  • Example#2518 - Basic recode_file example
  • Example#2519 - Basic recode_string example
  • Example#2520 - Пример использования Cairo
  • Example#2521 - cairo_create example
  • Example#2522 - cairo_font_face_get_type example
  • Example#2523 - cairo_font_face_status example
  • Example#2524 - cairo_font_options_create example
  • Example#2525 - cairo_font_options_equal example
  • Example#2526 - cairo_font_options_get_antialias example
  • Example#2527 - cairo_font_options_get_hint_metrics example
  • Example#2528 - cairo_font_options_get_hint_style example
  • Example#2529 - cairo_font_options_get_subpixel_order example
  • Example#2530 - cairo_font_options_hash example
  • Example#2531 - cairo_font_options_merge example
  • Example#2532 - cairo_font_options_set_antialias example
  • Example#2533 - cairo_font_options_set_hint_metrics example
  • Example#2534 - cairo_font_options_set_hint_style example
  • Example#2535 - cairo_font_options_set_subpixel_order example
  • Example#2536 - cairo_font_options_status example
  • Example#2537 - cairo_format_stride_for_width example
  • Example#2538 - cairo_image_surface_create_for_data example
  • Example#2539 - cairo_image_surface_create_from_png example
  • Example#2540 - cairo_image_surface_create example
  • Example#2541 - cairo_image_surface_get_data example
  • Example#2542 - cairo_image_surface_get_format example
  • Example#2543 - cairo_image_surface_get_height example
  • Example#2544 - cairo_image_surface_get_stride example
  • Example#2545 - cairo_image_surface_get_width example
  • Example#2546 - cairo_matrix_invert example
  • Example#2547 - cairo_matrix_multiply example
  • Example#2548 - cairo_matrix_rotate example
  • Example#2549 - cairo_matrix_transform_distance example
  • Example#2550 - cairo_matrix_transform_point example
  • Example#2551 - cairo_matrix_translate example
  • Example#2552 - cairo_pattern_add_color_stop_rgb example
  • Example#2553 - cairo_pattern_add_color_stop_rgba example
  • Example#2554 - cairo_pattern_create_for_surface example
  • Example#2555 - cairo_pattern_create_linear example
  • Example#2556 - cairo_pattern_create_radial example
  • Example#2557 - cairo_pattern_create_rgb example
  • Example#2558 - cairo_pattern_create_rgba example
  • Example#2559 - cairo_pattern_get_color_stop_count example
  • Example#2560 - cairo_pattern_get_color_stop_rgba example
  • Example#2561 - cairo_pattern_get_extend example
  • Example#2562 - cairo_pattern_get_filter example
  • Example#2563 - cairo_pattern_get_linear_points example
  • Example#2564 - cairo_pattern_get_matrix example
  • Example#2565 - cairo_pattern_get_radial_circles example
  • Example#2566 - cairo_pattern_get_rgba example
  • Example#2567 - cairo_pattern_get_surface example
  • Example#2568 - cairo_pattern_get_type example
  • Example#2569 - cairo_pattern_set_extend example
  • Example#2570 - cairo_pattern_set_filter example
  • Example#2571 - cairo_pattern_set_matrix example
  • Example#2572 - cairo_pattern_status example
  • Example#2573 - cairo_pdf_surface_create example
  • Example#2574 - cairo_pdf_surface_set_size example
  • Example#2575 - cairo_ps_get_levels example
  • Example#2576 - cairo_ps_level_to_string example
  • Example#2577 - cairo_ps_surface_create example
  • Example#2578 - cairo_ps_surface_dsc_begin_page_setup example
  • Example#2579 - cairo_ps_surface_dsc_begin_setup example
  • Example#2580 - cairo_ps_surface_dsc_comment example
  • Example#2581 - cairo_ps_surface_get_eps example
  • Example#2582 - cairo_ps_surface_restrict_to_level example
  • Example#2583 - cairo_ps_surface_set_eps example
  • Example#2584 - cairo_ps_surface_set_size example
  • Example#2585 - cairo_scaled_font_create example
  • Example#2586 - cairo_scaled_font_extents example
  • Example#2587 - cairo_scaled_font_get_ctm example
  • Example#2588 - cairo_scaled_font_get_font_face example
  • Example#2589 - cairo_scaled_font_get_font_matrix example
  • Example#2590 - cairo_scaled_font_get_font_options example
  • Example#2591 - cairo_scaled_font_get_scale_matrix example
  • Example#2592 - cairo_scaled_font_get_type example
  • Example#2593 - cairo_scaled_font_glyph_extents example
  • Example#2594 - cairo_scaled_font_status example
  • Example#2595 - cairo_scaled_font_text_extents example
  • Example#2596 - cairo_surface_copy_page example
  • Example#2597 - cairo_surface_create_similar example
  • Example#2598 - cairo_surface_finish example
  • Example#2599 - cairo_surface_flush example
  • Example#2600 - cairo_surface_get_content example
  • Example#2601 - cairo_surface_get_device_offset example
  • Example#2602 - cairo_surface_get_font_options example
  • Example#2603 - cairo_surface_get_type example
  • Example#2604 - cairo_surface_mark_dirty_rectangle example
  • Example#2605 - cairo_surface_mark_dirty example
  • Example#2606 - cairo_surface_set_device_offset example
  • Example#2607 - cairo_surface_set_fallback_resolution example
  • Example#2608 - cairo_surface_show_page example
  • Example#2609 - cairo_surface_status example
  • Example#2610 - cairo_surface_write_to_png example
  • Example#2611 - cairo_svg_surface_create example
  • Example#2612 - cairo_svg_surface_restrict_to_version example
  • Example#2613 - cairo_svg_version_to_string example
  • Example#2614 - Объектно-ориентированный стиль
  • Example#2615 - Процедурный стиль
  • Example#2616 - Объектно-ориентированный стиль
  • Example#2617 - Процедурный стиль
  • Example#2618 - Объектно-ориентированный стиль
  • Example#2619 - Процедурный стиль
  • Example#2620 - Объектно-ориентированный стиль
  • Example#2621 - Процедурный стиль
  • Example#2622 - Объектно-ориентированный стиль
  • Example#2623 - Процедурный стиль
  • Example#2624 - Объектно-ориентированный стиль
  • Example#2625 - Процедурный стиль
  • Example#2626 - Объектно-ориентированный стиль
  • Example#2627 - Процедурный стиль
  • Example#2628 - Объектно-ориентированный стиль
  • Example#2629 - Процедурный стиль
  • Example#2630 - Объектно-ориентированный стиль
  • Example#2631 - Процедурный стиль
  • Example#2632 - Объектно-ориентированный стиль
  • Example#2633 - Процедурный стиль
  • Example#2634 - Объектно-ориентированный стиль
  • Example#2635 - Процедурный стиль
  • Example#2636 - Объектно-ориентированный стиль
  • Example#2637 - Процедурный стиль
  • Example#2638 - Объектно-ориентированный стиль
  • Example#2639 - Процедурный стиль
  • Example#2640 - CairoContext::__construct example
  • Example#2641 - Объектно-ориентированный стиль
  • Example#2642 - Процедурный стиль
  • Example#2643 - Объектно-ориентированный стиль
  • Example#2644 - Процедурный стиль
  • Example#2645 - Объектно-ориентированный стиль
  • Example#2646 - Процедурный стиль
  • Example#2647 - Объектно-ориентированный стиль
  • Example#2648 - Процедурный стиль
  • Example#2649 - Объектно-ориентированный стиль
  • Example#2650 - Процедурный стиль
  • Example#2651 - Объектно-ориентированный стиль
  • Example#2652 - Процедурный стиль
  • Example#2653 - Объектно-ориентированный стиль
  • Example#2654 - Процедурный стиль
  • Example#2655 - Объектно-ориентированный стиль
  • Example#2656 - Процедурный стиль
  • Example#2657 - Объектно-ориентированный стиль
  • Example#2658 - Процедурный стиль
  • Example#2659 - Объектно-ориентированный стиль
  • Example#2660 - Процедурный стиль
  • Example#2661 - Объектно-ориентированный стиль
  • Example#2662 - Процедурный стиль
  • Example#2663 - Объектно-ориентированный стиль
  • Example#2664 - Процедурный стиль
  • Example#2665 - Объектно-ориентированный стиль
  • Example#2666 - Процедурный стиль
  • Example#2667 - Объектно-ориентированный стиль
  • Example#2668 - Процедурный стиль
  • Example#2669 - Объектно-ориентированный стиль
  • Example#2670 - Процедурный стиль
  • Example#2671 - Объектно-ориентированный стиль
  • Example#2672 - Процедурный стиль
  • Example#2673 - Объектно-ориентированный стиль
  • Example#2674 - Процедурный стиль
  • Example#2675 - Объектно-ориентированный стиль
  • Example#2676 - Процедурный стиль
  • Example#2677 - Объектно-ориентированный стиль
  • Example#2678 - Процедурный стиль
  • Example#2679 - Объектно-ориентированный стиль
  • Example#2680 - Процедурный стиль
  • Example#2681 - Объектно-ориентированный стиль
  • Example#2682 - Процедурный стиль
  • Example#2683 - Объектно-ориентированный стиль
  • Example#2684 - Процедурный стиль
  • Example#2685 - Объектно-ориентированный стиль
  • Example#2686 - Процедурный стиль
  • Example#2687 - Объектно-ориентированный стиль
  • Example#2688 - Процедурный стиль
  • Example#2689 - Объектно-ориентированный стиль
  • Example#2690 - Процедурный стиль
  • Example#2691 - Объектно-ориентированный стиль
  • Example#2692 - Процедурный стиль
  • Example#2693 - Объектно-ориентированный стиль
  • Example#2694 - Процедурный стиль
  • Example#2695 - Объектно-ориентированный стиль
  • Example#2696 - Процедурный стиль
  • Example#2697 - Объектно-ориентированный стиль
  • Example#2698 - Процедурный стиль
  • Example#2699 - Объектно-ориентированный стиль
  • Example#2700 - Процедурный стиль
  • Example#2701 - Объектно-ориентированный стиль
  • Example#2702 - Процедурный стиль
  • Example#2703 - Объектно-ориентированный стиль
  • Example#2704 - Процедурный стиль
  • Example#2705 - Объектно-ориентированный стиль
  • Example#2706 - Процедурный стиль
  • Example#2707 - Объектно-ориентированный стиль
  • Example#2708 - Процедурный стиль
  • Example#2709 - Объектно-ориентированный стиль
  • Example#2710 - Процедурный стиль
  • Example#2711 - Объектно-ориентированный стиль
  • Example#2712 - Процедурный стиль
  • Example#2713 - Объектно-ориентированный стиль
  • Example#2714 - Процедурный стиль
  • Example#2715 - Объектно-ориентированный стиль
  • Example#2716 - Процедурный стиль
  • Example#2717 - Объектно-ориентированный стиль
  • Example#2718 - Процедурный стиль
  • Example#2719 - Объектно-ориентированный стиль
  • Example#2720 - Процедурный стиль
  • Example#2721 - Объектно-ориентированный стиль
  • Example#2722 - Процедурный стиль
  • Example#2723 - Объектно-ориентированный стиль
  • Example#2724 - Процедурный стиль
  • Example#2725 - Объектно-ориентированный стиль
  • Example#2726 - Процедурный стиль
  • Example#2727 - Объектно-ориентированный стиль
  • Example#2728 - Процедурный стиль
  • Example#2729 - Объектно-ориентированный стиль
  • Example#2730 - Процедурный стиль
  • Example#2731 - Объектно-ориентированный стиль
  • Example#2732 - Процедурный стиль
  • Example#2733 - Объектно-ориентированный стиль
  • Example#2734 - Процедурный стиль
  • Example#2735 - Объектно-ориентированный стиль
  • Example#2736 - Процедурный стиль
  • Example#2737 - Объектно-ориентированный стиль
  • Example#2738 - Процедурный стиль
  • Example#2739 - Объектно-ориентированный стиль
  • Example#2740 - Процедурный стиль
  • Example#2741 - Объектно-ориентированный стиль
  • Example#2742 - Процедурный стиль
  • Example#2743 - Объектно-ориентированный стиль
  • Example#2744 - Процедурный стиль
  • Example#2745 - Объектно-ориентированный стиль
  • Example#2746 - Процедурный стиль
  • Example#2747 - Объектно-ориентированный стиль
  • Example#2748 - Процедурный стиль
  • Example#2749 - Объектно-ориентированный стиль
  • Example#2750 - Процедурный стиль
  • Example#2751 - Объектно-ориентированный стиль
  • Example#2752 - Процедурный стиль
  • Example#2753 - Объектно-ориентированный стиль
  • Example#2754 - Процедурный стиль
  • Example#2755 - Объектно-ориентированный стиль
  • Example#2756 - Процедурный стиль
  • Example#2757 - Объектно-ориентированный стиль
  • Example#2758 - Процедурный стиль
  • Example#2759 - Объектно-ориентированный стиль
  • Example#2760 - Процедурный стиль
  • Example#2761 - Объектно-ориентированный стиль
  • Example#2762 - Процедурный стиль
  • Example#2763 - Объектно-ориентированный стиль
  • Example#2764 - Процедурный стиль
  • Example#2765 - Объектно-ориентированный стиль
  • Example#2766 - Процедурный стиль
  • Example#2767 - Объектно-ориентированный стиль
  • Example#2768 - Процедурный стиль
  • Example#2769 - Объектно-ориентированный стиль
  • Example#2770 - Процедурный стиль
  • Example#2771 - Объектно-ориентированный стиль
  • Example#2772 - Процедурный стиль
  • Example#2773 - Объектно-ориентированный стиль
  • Example#2774 - Процедурный стиль
  • Example#2775 - Объектно-ориентированный стиль
  • Example#2776 - Процедурный стиль
  • Example#2777 - Объектно-ориентированный стиль
  • Example#2778 - Процедурный стиль
  • Example#2779 - Объектно-ориентированный стиль
  • Example#2780 - Процедурный стиль
  • Example#2781 - Объектно-ориентированный стиль
  • Example#2782 - Процедурный стиль
  • Example#2783 - Объектно-ориентированный стиль
  • Example#2784 - Процедурный стиль
  • Example#2785 - Объектно-ориентированный стиль
  • Example#2786 - Процедурный стиль
  • Example#2787 - Объектно-ориентированный стиль
  • Example#2788 - Процедурный стиль
  • Example#2789 - Объектно-ориентированный стиль
  • Example#2790 - Процедурный стиль
  • Example#2791 - Объектно-ориентированный стиль
  • Example#2792 - Процедурный стиль
  • Example#2793 - Объектно-ориентированный стиль
  • Example#2794 - Процедурный стиль
  • Example#2795 - Объектно-ориентированный стиль
  • Example#2796 - Процедурный стиль
  • Example#2797 - Объектно-ориентированный стиль
  • Example#2798 - Процедурный стиль
  • Example#2799 - Объектно-ориентированный стиль
  • Example#2800 - Процедурный стиль
  • Example#2801 - Объектно-ориентированный стиль
  • Example#2802 - Процедурный стиль
  • Example#2803 - Объектно-ориентированный стиль
  • Example#2804 - Процедурный стиль
  • Example#2805 - Объектно-ориентированный стиль
  • Example#2806 - Процедурный стиль
  • Example#2807 - Объектно-ориентированный стиль
  • Example#2808 - Процедурный стиль
  • Example#2809 - Объектно-ориентированный стиль
  • Example#2810 - Процедурный стиль
  • Example#2811 - Объектно-ориентированный стиль
  • Example#2812 - Процедурный стиль
  • Example#2813 - Объектно-ориентированный стиль
  • Example#2814 - Процедурный стиль
  • Example#2815 - CairoSurface::createSimilar example
  • Example#2816 - CairoSurface::finish example
  • Example#2817 - CairoSurface::flush example
  • Example#2818 - CairoSurface::getContent example
  • Example#2819 - CairoSurface::getDeviceOffset example
  • Example#2820 - Объектно-ориентированный стиль
  • Example#2821 - Процедурный стиль
  • Example#2822 - CairoSurface::getType example
  • Example#2823 - CairoSurface::markDirty example
  • Example#2824 - CairoSurface::markDirtyRectangle example
  • Example#2825 - CairoSurface::setDeviceOffset example
  • Example#2826 - CairoSurface::setFallbackResolution example
  • Example#2827 - Объектно-ориентированный стиль
  • Example#2828 - Процедурный стиль
  • Example#2829 - Объектно-ориентированный стиль
  • Example#2830 - Процедурный стиль
  • Example#2831 - CairoSurface::writeToPng example
  • Example#2832 - CairoSvgSurface::__construct example
  • Example#2833 - CairoSvgSurface::getVersions example
  • Example#2834 - Процедурный стиль
  • Example#2835 - CairoSvgSurface::restrictToVersion example
  • Example#2836 - CairoSvgSurface::versionToString example
  • Example#2837 - CairoImageSurface::__construct example
  • Example#2838 - CairoImageSurface::createForData example
  • Example#2839 - CairoImageSurface::createFromPng example
  • Example#2840 - CairoImageSurface::getData example
  • Example#2841 - CairoImageSurface::getFormat example
  • Example#2842 - CairoImageSurface::getHeight example
  • Example#2843 - CairoImageSurface::getStride example
  • Example#2844 - CairoImageSurface::getWidth example
  • Example#2845 - CairoPdfSurface::__construct example
  • Example#2846 - CairoPdfSurface::setSize example
  • Example#2847 - CairoPsSurface::__construct example
  • Example#2848 - CairoPsSurface::dscBeginPageSetup example
  • Example#2849 - CairoPsSurface::dscBeginSetup example
  • Example#2850 - CairoPsSurface::dscComment example
  • Example#2851 - CairoPsSurface::getEps example
  • Example#2852 - CairoPsSurface::getLevels example
  • Example#2853 - CairoPsSurface::levelToString example
  • Example#2854 - CairoPsSurface::restrictToLevel example
  • Example#2855 - CairoPsSurface::setEps example
  • Example#2856 - CairoPsSurface::setSize example
  • Example#2857 - CairoFontFace::__construct example
  • Example#2858 - CairoFontFace::getType example
  • Example#2859 - Объектно-ориентированный стиль
  • Example#2860 - Процедурный стиль
  • Example#2861 - CairoFontOptions::__construct example
  • Example#2862 - CairoFontOptions::equal example
  • Example#2863 - Объектно-ориентированный стиль
  • Example#2864 - Процедурный стиль
  • Example#2865 - CairoFontOptions::getHintMetrics example
  • Example#2866 - CairoFontOptions::getHintStyle example
  • Example#2867 - CairoFontOptions::getSubpixelOrder example
  • Example#2868 - CairoFontOptions::hash example
  • Example#2869 - CairoFontOptions::merge example
  • Example#2870 - Объектно-ориентированный стиль
  • Example#2871 - Процедурный стиль
  • Example#2872 - CairoFontOptions::setHintMetrics example
  • Example#2873 - CairoFontOptions::setHintStyle example
  • Example#2874 - CairoFontOptions::setSubpixelOrder example
  • Example#2875 - Объектно-ориентированный стиль
  • Example#2876 - Процедурный стиль
  • Example#2877 - CairoScaledFont::__construct example
  • Example#2878 - CairoScaledFont::extents example
  • Example#2879 - CairoScaledFont::getCtm example
  • Example#2880 - Объектно-ориентированный стиль
  • Example#2881 - Процедурный стиль
  • Example#2882 - Объектно-ориентированный стиль
  • Example#2883 - Процедурный стиль
  • Example#2884 - Объектно-ориентированный стиль
  • Example#2885 - Процедурный стиль
  • Example#2886 - CairoScaledFont::getScaleMatrix example
  • Example#2887 - CairoScaledFont::getType example
  • Example#2888 - CairoScaledFont::glyphExtents example
  • Example#2889 - Объектно-ориентированный стиль
  • Example#2890 - Процедурный стиль
  • Example#2891 - Объектно-ориентированный стиль
  • Example#2892 - Процедурный стиль
  • Example#2893 - CairoPattern::__construct example
  • Example#2894 - Объектно-ориентированный стиль
  • Example#2895 - Процедурный стиль
  • Example#2896 - CairoPattern::getType example
  • Example#2897 - Объектно-ориентированный стиль
  • Example#2898 - Процедурный стиль
  • Example#2899 - Объектно-ориентированный стиль
  • Example#2900 - Процедурный стиль
  • Example#2901 - CairoGradientPattern::addColorStopRgb example
  • Example#2902 - CairoGradientPattern::addColorStopRgba example
  • Example#2903 - CairoGradientPattern::getColorStopCount example
  • Example#2904 - CairoGradientPattern::getColorStopRgba example
  • Example#2905 - CairoGradientPattern::getExtend example
  • Example#2906 - CairoGradientPattern::setExtend example
  • Example#2907 - CairoSolidPattern::__construct example
  • Example#2908 - CairoSolidPattern::getRgba example
  • Example#2909 - CairoSurfacePattern::__construct example
  • Example#2910 - CairoSurfacePattern::getExtend example
  • Example#2911 - CairoSurfacePattern::getFilter example
  • Example#2912 - CairoSurfacePattern::getSurface example
  • Example#2913 - CairoSurfacePattern::setExtend example
  • Example#2914 - CairoSurfacePattern::setFilter example
  • Example#2915 - CairoLinearGradient::__construct example
  • Example#2916 - CairoLinearGradient::getPoints example
  • Example#2917 - CairoRadialGradient::__construct example
  • Example#2918 - CairoRadialGradient::getCircles example
  • Example#2919 - CairoFormat::strideForWidth example
  • Example#2920 - Объектно-ориентированный стиль
  • Example#2921 - Процедурный стиль
  • Example#2922 - Объектно-ориентированный стиль
  • Example#2923 - Процедурный стиль
  • Example#2924 - Объектно-ориентированный стиль
  • Example#2925 - Процедурный стиль
  • Example#2926 - Объектно-ориентированный стиль
  • Example#2927 - Процедурный стиль
  • Example#2928 - Объектно-ориентированный стиль
  • Example#2929 - Процедурный стиль
  • Example#2930 - CairoMatrix::invert example
  • Example#2931 - CairoMatrix::multiply example
  • Example#2932 - Объектно-ориентированный стиль
  • Example#2933 - Процедурный стиль
  • Example#2934 - Объектно-ориентированный стиль
  • Example#2935 - Процедурный стиль
  • Example#2936 - CairoMatrix::transformDistance example
  • Example#2937 - CairoMatrix::transformPoint example
  • Example#2938 - Объектно-ориентированный стиль
  • Example#2939 - Процедурный стиль
  • Example#2940 - Пример использования exif_imagetype
  • Example#2941 - Пример использования exif_read_data
  • Example#2942 - Пример использования exif_tagname
  • Example#2943 - Пример использования exif_thumbnail
  • Example#2944 - Создание PNG средствами PHP
  • Example#2945 - Добавление водяных знаков на изображения с помощью альфа-каналов
  • Example#2946 - Использование imagecopymerge создать полупрозрачный водяной знак
  • Example#2947 - Использование gd_info
  • Example#2948 - getimagesize и MIME типы
  • Example#2949 - Пример использования getimagesize
  • Example#2950 - getimagesize (URL)
  • Example#2951 - getimagesize() возвращающая IPTC
  • Example#2952 - Пример использования getimagesizefromstring
  • Example#2953 - Пример использования image_type_to_extension
  • Example#2954 - Пример использования image_type_to_mime_type
  • Example#2955 - Пример использования image2wbmp
  • Example#2956 - Пример использования imagealphablending
  • Example#2957 - Сравнение двух линий, одна из которых рисуется с включенным сглаживанием
  • Example#2958 - Рисование окружности с помощью функции imagearc
  • Example#2959 - Пример использования imagechar
  • Example#2960 - Пример использования imagecharup
  • Example#2961 - Пример использования imagecolorallocate
  • Example#2962 - Пример использования imagecolorallocatealpha
  • Example#2963 - Доступ к компонентам RGB цвета
  • Example#2964 - Удобочитаемые RGB значения с использованием imagecolorsforindex
  • Example#2965 - Поиск набора цветов изображения
  • Example#2966 - Поиск набора цветов изображения
  • Example#2967 - Пример использования imagecolorclosesthwb
  • Example#2968 - Пример использования imagecolordeallocate
  • Example#2969 - Получение цветов GD логотипа
  • Example#2970 - Получение цветов GD логотипа
  • Example#2971 - Пример использования imagecolormatch
  • Example#2972 - Использование imagecoloresolve для получения цветов из изображения.
  • Example#2973 - Пример использования imagecoloresolvealpha для получения цветов из изображения
  • Example#2974 - Пример использования imagecolorset
  • Example#2975 - Пример использования imagecolorsforindex
  • Example#2976 - Получение количества цветов в изображении, используя imagecolorstotal
  • Example#2977 - Пример использования imagecolortransparent
  • Example#2978 - Создание рельефа на логотипе PHP.net
  • Example#2979 - Размытие по Гаусу
  • Example#2980 - Обрезка логотипа PHP.net
  • Example#2981 - Совмещение двух копий логотипа PHP.net с 75% прозрачностью
  • Example#2982 - Пример использования imagecopymergegray
  • Example#2983 - Простой пример
  • Example#2984 - Ресэмплирование изображения с сохранением пропорций
  • Example#2985 - Изменение размера изображения
  • Example#2986 - Создание нового GD потока изображения и вывод изображения.
  • Example#2987 - Пример использования imagecreatefromgd2
  • Example#2988 - Пример использования imagecreatefromgd2part
  • Example#2989 - Пример использования imagecreatefromgd
  • Example#2990 - Пример обработки ошибки при загрузке GIF
  • Example#2991 - Пример обработки ошибки при загрузке JPEG
  • Example#2992 - Пример обработки ошибки при загрузке PNG
  • Example#2993 - Пример использования imagecreatefromstring
  • Example#2994 - Пример обработки ошибки при загрузке WBMP
  • Example#2995 - Преобразование XBM изображения в png, используя imagecreatefromxbm
  • Example#2996 - Создание изображения, используя imagecreatefromxpm
  • Example#2997 - Создание нового потока GD изображения и вывод картинки.
  • Example#2998 - Пример использования imagedashedline
  • Example#2999 - Альтернатива функции imagedashedline
  • Example#3000 - Пример использования imagedestroy
  • Example#3001 - Пример использования imageellipse
  • Example#3002 - Пример использования imagefill
  • Example#3003 - Создание трехмерного пирога
  • Example#3004 - Пример использования imagefilledellipse
  • Example#3005 - Пример использования imagefilledpolygon
  • Example#3006 - Пример использования imagefilledrectangle
  • Example#3007 - Закрашивание эллипса
  • Example#3008 - Пример использования imagefilter с фильтром grayscale
  • Example#3009 - Пример использования imagefilter с фильтром яркости
  • Example#3010 - Пример использования imagefilter с фильтром colorize
  • Example#3011 - Пример использования imagefilter с фильтром negate
  • Example#3012 - Пример использования imagefilter с фильтром pixelate
  • Example#3013 - Пример использования imagefontheight на встроенных шрифтах
  • Example#3014 - Использование imagefontheight вместе с imageloadfont
  • Example#3015 - Использование imagefontwidth на встроенных шрифтах
  • Example#3016 - Использование imagefontwidth вместе с imageloadfont
  • Example#3017 - Пример использования imageftbbox
  • Example#3018 - Пример использования imagefttext
  • Example#3019 - Пример использования imagegammacorrect
  • Example#3020 - Вывод GD2 изображения
  • Example#3021 - Сохранение GD2 изображения
  • Example#3022 - Вывод GD-изображения
  • Example#3023 - Сохранение GD-изображения
  • Example#3024 - Вывод изображения, используя imagegif
  • Example#3025 - Преобразование PNG в GIF, используя imagegif
  • Example#3026 - Пример использования imagegrabscreen
  • Example#3027 - Пример использования imagegrabwindow
  • Example#3028 - Включение интерлейсинга, используя imageinterlace
  • Example#3029 - Простое определение полноцветных изображений с помощью imageistruecolor
  • Example#3030 - Вывод JPEG-изображения
  • Example#3031 - Сохранение изображения JPEG
  • Example#3032 - Вывод JPEG-изображения с 75% качеством
  • Example#3033 - Пример использования imagelayereffect
  • Example#3034 - Рисование жирной линии
  • Example#3035 - Пример использования imageloadfont
  • Example#3036 - Пример использования imagepalettecopy
  • Example#3037 - Пример использования imagepolygon
  • Example#3038 - Пример использования imagepsbbox
  • Example#3039 - Пример использования imagepsencodefont
  • Example#3040 - Пример использования imagepsextendfont
  • Example#3041 - Пример использования imagepsfreefont
  • Example#3042 - Пример использования imagepsloadfont
  • Example#3043 - Пример использования imagepsslantfont
  • Example#3044 - Пример использования imagepstext
  • Example#3045 - Пример использования imagerectangle
  • Example#3046 - Поворот изображения на 180 градусов
  • Example#3047 - Пример использования imagesavealpha
  • Example#3048 - Пример использования imagesetbrush
  • Example#3049 - Пример использования imagesetpixel
  • Example#3050 - Пример использования imagesetstyle
  • Example#3051 - Пример использования imagesetthickness
  • Example#3052 - Пример использования imagesettile
  • Example#3053 - Пример использования imagestring
  • Example#3054 - Пример использования imagestringup
  • Example#3055 - Пример использования imagesx
  • Example#3056 - Пример использования imagesy
  • Example#3057 - Преобразование truecolor-изображения в палитровое
  • Example#3058 - Пример использования imagettfbbox
  • Example#3059 - Пример использования imagettftext
  • Example#3060 - Проверка поддержки PNG
  • Example#3061 - Вывод WBMP изображения
  • Example#3062 - Сохранение WBMP изображения
  • Example#3063 - Вывод изображения с измененным верхним слоем
  • Example#3064 - Сохранение XBM файла
  • Example#3065 - Сохранение XBM файла с отличным цветом верхнего слоя
  • Example#3066 - Встраивание IPTC данных в JPEG
  • Example#3067 - iptcparse() используется совместно с getimagesize
  • Example#3068 - Пример использования jpeg2wbmp
  • Example#3069 - Пример использования png2wbmp
  • Example#3070 - Gmagick Example
  • Example#3071 - Gmagick::despeckleimage example
  • Example#3072 - Создание миниатюры в Imagick
  • Example#3073 - Создание миниатюр для всех JPG файлов в директории
  • Example#3074 - Создание отражения
  • Example#3075 - Заливка текста градиентом
  • Example#3076 - Чтение GIF изображения и изменение размера всех фреймов
  • Example#3077 - Использование Imagick::adaptiveBlurImage:
  • Example#3078 - Использование Imagick::adaptiveResizeImage
  • Example#3079 - Пример использования Imagick::adaptiveSharpenImage
  • Example#3080 - Использование Imagick::annotateImage:
  • Example#3081 - Пример использования Imagick::appendImages
  • Example#3082 - Использование Imagick::blurImage:
  • Example#3083 - Использование Imagick::chopImage:
  • Example#3084 - Использование Imagick::clutImage:
  • Example#3085 - Using Imagick::commentImage:
  • Example#3086 - Using Imagick::compareImageLayers
  • Example#3087 - Using Imagick::compareImages:
  • Example#3088 - Using Imagick::distortImage:
  • Example#3089 - Using Imagick::evaluateImage
  • Example#3090 - Using Imagick::exportImagePixels
  • Example#3091 - Imagick::floodfillPaintImage example
  • Example#3092 - Using Imagick::getImageLength:
  • Example#3093 - Using Imagick::getImageProperties:
  • Example#3094 - Using Imagick::getImageProperty:
  • Example#3095 - Using Imagick::getIteratorIndex:
  • Example#3096 - Imagick::importImagePixels example
  • Example#3097 - Using Imagick::newImage:
  • Example#3098 - Using Imagick::optimizeImageLayers
  • Example#3099 - Using Imagick::pingImageBlob
  • Example#3100 - Using Imagick::pingImageFile
  • Example#3101 - A Imagick::polaroidImage example
  • Example#3102 - Using Imagick::queryFontMetrics:
  • Example#3103 - Using Imagick::roundCorners:
  • Example#3104 - A Imagick::setFont example
  • Example#3105 - A Imagick::setImage example
  • Example#3106 - A Imagick::setImageOpacity example
  • Example#3107 - Using Imagick::setImageProperty:
  • Example#3108 - Using Imagick::setIteratorIndex:
  • Example#3109 - A Imagick::setPointSize example
  • Example#3110 - Using Imagick::transformImage:
  • Example#3111 - Using Imagick::trimImage:
  • Example#3112 - Пример использования imap_append
  • Example#3113 - imap_check example
  • Example#3114 - imap_createmailbox example
  • Example#3115 - imap_delete example
  • Example#3116 - imap_fetch_overview example
  • Example#3117 - imap_gc example
  • Example#3118 - imap_get_quota example
  • Example#3119 - imap_get_quota 4.3 or greater example
  • Example#3120 - imap_get_quotaroot example
  • Example#3121 - imap_getacl example
  • Example#3122 - imap_getmailboxes example
  • Example#3123 - imap_list example
  • Example#3124 - imap_mail_compose example
  • Example#3125 - imap_mailboxmsginfo example
  • Example#3126 - imap_mime_header_decode example
  • Example#3127 - Different use of imap_open
  • Example#3128 - imap_open example
  • Example#3129 - imap_ping Example
  • Example#3130 - imap_reopen example
  • Example#3131 - imap_rfc822_parse_adrlist example
  • Example#3132 - imap_rfc822_write_address example
  • Example#3133 - imap_search example
  • Example#3134 - imap_set_quota example
  • Example#3135 - imap_setflag_full example
  • Example#3136 - imap_status example
  • Example#3137 - imap_thread Example
  • Example#3138 - imap_timeout example
  • Example#3139 - Вычисляет хеш-сумму и подписка пользователя на что-либо
  • Example#3140 - Отправка письма.
  • Example#3141 - Отправка письма с дополнительными заголовками.
  • Example#3142 - Отправка письма с дополнительными аргументами командной строки.
  • Example#3143 - Отправка HTML-сообщения
  • Example#3144 - mailparse_determine_best_xfer_encoding example
  • Example#3145 - mailparse_rfc822_parse_addresses example
  • Example#3146 - mailparse_stream_encode example
  • Example#3147 - mailparse_uudecode_all example
  • Example#3148 - Пример использования bcadd
  • Example#3149 - Пример использования bccomp
  • Example#3150 - Пример использования bcdiv
  • Example#3151 - Пример использования bcmod
  • Example#3152 - Пример использования bcmul
  • Example#3153 - Пример использования bcpow
  • Example#3154 - Пример уменьшения точности в bcpow
  • Example#3155 - Пример использования bcscale
  • Example#3156 - Пример использования bcsqrt
  • Example#3157 - Пример использования bcsub
  • Example#3158 - Вычисление факториала с помощью GMP
  • Example#3159 - Пример использования gmp_abs
  • Example#3160 - Пример использования gmp_add
  • Example#3161 - Пример использования gmp_and
  • Example#3162 - Пример использования gmp_clrbit
  • Example#3163 - Пример использования gmp_cmp
  • Example#3164 - Пример использования gmp_com
  • Example#3165 - Пример использования gmp_div_q
  • Example#3166 - Деление GMP чисел
  • Example#3167 - Пример использования gmp_div_r
  • Example#3168 - Пример использования gmp_divexact
  • Example#3169 - Пример использования gmp_fact
  • Example#3170 - Пример использования gmp_gcd
  • Example#3171 - Решение линейного Диофантового уравнения
  • Example#3172 - Пример использования gmp_hamdist
  • Example#3173 - Создание GMP числа
  • Example#3174 - Пример использования gmp_intval
  • Example#3175 - Пример использования gmp_invert
  • Example#3176 - Пример использования gmp_jacobi
  • Example#3177 - Пример использования gmp_legendre
  • Example#3178 - Пример использования gmp_mod
  • Example#3179 - Пример использования gmp_mul
  • Example#3180 - Пример использования gmp_neg
  • Example#3181 - Пример использования gmp_nextprime
  • Example#3182 - Пример использования gmp_or
  • Example#3183 - Пример использования gmp_perfect_square
  • Example#3184 - Пример использования gmp_popcount
  • Example#3185 - Пример использования gmp_pow
  • Example#3186 - Пример использования gmp_powm
  • Example#3187 - Пример использования gmp_prob_prime
  • Example#3188 - Пример использования gmp_random
  • Example#3189 - Пример использования gmp_scan0
  • Example#3190 - Пример использования gmp_scan1
  • Example#3191 - Пример использования gmp_setbit
  • Example#3192 - Пример использования gmp_sign
  • Example#3193 - Пример использования gmp_sqrt
  • Example#3194 - Пример использования gmp_sqrtrem
  • Example#3195 - Преобразование GMP числа в строку
  • Example#3196 - Пример использования gmp_sub
  • Example#3197 - Пример использования gmp_testbit
  • Example#3198 - Пример использования gmp_xor
  • Example#3199 - Using Lapack::eigenValues:
  • Example#3200 - Using Lapack::leastSquaresByFactorisation:
  • Example#3201 - Using Lapack::leastSquaresBySVD:
  • Example#3202 - Using Lapack::pseudoInverse:
  • Example#3203 - Using Lapack::singularValues:
  • Example#3204 - Using Lapack::singularValues:
  • Example#3205 - Пример использования abs
  • Example#3206 - Пример использования base_convert
  • Example#3207 - Пример использования bindec
  • Example#3208 - Пример. bindec интерпретирует ввод как беззнаковое число
  • Example#3209 - Пример использования ceil
  • Example#3210 - Пример использования cos
  • Example#3211 - Пример использования decbin
  • Example#3212 - Пример использования dechex
  • Example#3213 - Пример использования decoct
  • Example#3214 - Пример использования deg2rad
  • Example#3215 - Пример использования exp
  • Example#3216 - Пример использования floor
  • Example#3217 - Пример использования fmod
  • Example#3218 - Пример использования hexdec
  • Example#3219 - Пример использования is_nan
  • Example#3220 - Пример использования max
  • Example#3221 - Пример использования min
  • Example#3222 - Вычисление случайного числа с плавающей точкой
  • Example#3223 - Пример использования mt_rand
  • Example#3224 - Пример использования mt_srand
  • Example#3225 - Пример использования octdec
  • Example#3226 - Пример использования pi
  • Example#3227 - Примеры использования pow
  • Example#3228 - Пример использования rad2deg
  • Example#3229 - Пример использования rand
  • Example#3230 - Пример использования round
  • Example#3231 - Примеры использования пареметра mode
  • Example#3232 - Пример использования sin
  • Example#3233 - Пример использованияsqrt
  • Example#3234 - Пример использования srand
  • Example#3235 - Пример использования tan
  • Example#3236 - Evaluating a FDF document
  • Example#3237 - Adding JavaScript code to a FDF
  • Example#3238 - Populating a PDF document
  • Example#3239 - Storing an uploaded file
  • Example#3240 - Detecting all fieldnames in a FDF
  • Example#3241 - Accessing the form data
  • Example#3242 - Accessing the form data
  • Example#3243 - Retrieving FDF as a string
  • Example#3244 - Passing FDF data to a second form
  • Example#3245 - Процедурный пример создания чистой подписи GnuPG
  • Example#3246 - Объектно ориентированный пример создания чистой подписи GnuPG
  • Example#3247 - keylistiterator
  • Example#3248 - Procedural gnupg_adddecryptkey example
  • Example#3249 - OO gnupg_adddecryptkey example
  • Example#3250 - Процедурный пример использования gnupg_addencryptkey
  • Example#3251 - Объектно-ориентированный пример использования gnupg_addencryptkey
  • Example#3252 - Процедурный пример использования gnupg_addsignkey
  • Example#3253 - Объектно-ориентированный пример использования gnupg_addsignkey
  • Example#3254 - Процедурный пример использования gnupg_cleardecryptkeys
  • Example#3255 - Объектно-ориентированный пример использования gnupg_cleardecryptkeys
  • Example#3256 - Процедурный пример использования gnupg_clearencryptkeys
  • Example#3257 - Объектно-ориентированный пример использования gnupg_clearencryptkeys
  • Example#3258 - Процедурный пример использования gnupg_clearsignkeys
  • Example#3259 - Объектно-ориентированный пример использования gnupg_clearsignkeys
  • Example#3260 - Процедурный пример использования gnupg_decrypt
  • Example#3261 - Объектно-ориентированный пример использования gnupg_encrypt
  • Example#3262 - Процедурный пример использования gnupg_decryptverify
  • Example#3263 - Объектно-ориентированный пример использования gnupg_decryptverify
  • Example#3264 - Procedural gnupg_encrypt example
  • Example#3265 - OO gnupg_encrypt example
  • Example#3266 - Процедурный пример использования gnupg_encryptsign
  • Example#3267 - Объектно-ориентированный пример использования gnupg_encryptsign
  • Example#3268 - Процедурный пример использования gnupg_export
  • Example#3269 - Объектно-ориентированный пример использования gnupg_export
  • Example#3270 - Процедурный пример использования gnupg_geterror
  • Example#3271 - Объектно-ориентированный пример использования gnupg_geterror
  • Example#3272 - Процедурный пример использования gnupg_getprotocol
  • Example#3273 - Объектно-ориентированный пример использования gnupg_getprotocol
  • Example#3274 - Procedural gnupg_import example
  • Example#3275 - OO gnupg_import example
  • Example#3276 - Процедурный пример использования gnupg_init
  • Example#3277 - Объектно-ориентированный пример инициализации GnuPG
  • Example#3278 - Процедурный пример использования gnupg_keyinfo
  • Example#3279 - Объектно-ориентированный пример использования gnupg_keyinfo
  • Example#3280 - Процедурный пример использования gnupg_setarmor
  • Example#3281 - Объектно-ориентированный пример использования gnupg_setarmor
  • Example#3282 - Процедурный пример использования gnupg_seterrormode
  • Example#3283 - Объектно-ориентированный пример использования gnupg_seterrormode
  • Example#3284 - Процедурный пример использования gnupg_setsignmode
  • Example#3285 - Объектно-ориентированный пример использования gnupg_setsignmode
  • Example#3286 - Процедурный пример использования gnupg_sign
  • Example#3287 - Объектно-ориентированный пример использования gnupg_sign
  • Example#3288 - Процедурный пример использования gnupg_verify
  • Example#3289 - Объектно ориентированный пример использования gnupg_verify
  • Example#3290 - Fancy "Hello world"
  • Example#3291 - swfaction example
  • Example#3292 - swfaction example
  • Example#3293 - swfaction example
  • Example#3294 - swfsprite example
  • Example#3295 - ming_useswfversion example
  • Example#3296 - Importing a DBL file
  • Example#3297 - Using an alpha mask
  • Example#3298 - Usual interactions with buttons
  • Example#3299 - Drag example
  • Example#3300 - swfdisplayitem::multcolor example
  • Example#3301 - swfdisplayitem::rotateto example
  • Example#3302 - swfdisplayitem::setname example
  • Example#3303 - swfgradient example
  • Example#3304 - swfmorph example
  • Example#3305 - Displaying your $movie in a browser
  • Example#3306 - Streaming example
  • Example#3307 - SWFShape::addFill example
  • Example#3308 - swfshape example
  • Example#3309 - swfshape::setline example
  • Example#3310 - swftext example
  • Example#3311 - Пример PDFlib на PHP 4
  • Example#3312 - Пример PDFlib на PHP 5
  • Example#3313 - Creating and using a pattern
  • Example#3314 - Creating and using a template
  • Example#3315 - Hyphennate a text
  • Example#3316 - Drawing a rectangle
  • Example#3317 - Creating and using a spot color
  • Example#3318 - Rotation of the coordinate system
  • Example#3319 - Placing text at a given position
  • Example#3320 - Drawing a dashed line
  • Example#3321 - Translation of the coordinate system
  • Example#3322 - Basic RPMReader Example
  • Example#3323 - rpm_close example
  • Example#3324 - rpm_get_tag example
  • Example#3325 - rpm_is_valid example
  • Example#3326 - rpm_open example
  • Example#3327 - rpm_version example
  • Example#3328 - SWF example
  • Example#3329 - swf_addbuttonrecord example
  • Example#3330 - Creating a simple flash file based on user input and outputting it and saving it in a database
  • Example#3331 - Horizontal text example
  • Example#3332 - A simple 3D-rotation around a text
  • Example#3333 - Incorrect requests
  • Example#3334 - Calling request from a request callback
  • Example#3335 - Calling request from a request callback
  • Example#3336 - Using eio with libevent
  • Example#3337 - Cancelling a request
  • Example#3338 - Calling eio_chmod
  • Example#3339 - Making a custom request
  • Example#3340 - Grouping requests
  • Example#3341 - Using eio with libevent
  • Example#3342 - eio_cancel example
  • Example#3343 - eio_custom example
  • Example#3344 - eio_event_loop example
  • Example#3345 - eio_lstat example
  • Example#3346 - Using eio with libevent
  • Example#3347 - Grouping requests
  • Example#3348 - eio_grp example
  • Example#3349 - eio_link example
  • Example#3350 - eio_lstat example
  • Example#3351 - eio_mkdir example
  • Example#3352 - eio_mknod example
  • Example#3353 - eio_nreqs example
  • Example#3354 - eio_open example
  • Example#3355 - eio_poll example
  • Example#3356 - eio_read example
  • Example#3357 - eio_readdir example
  • Example#3358 - eio_readlink example
  • Example#3359 - eio_realpath example
  • Example#3360 - eio_rename example
  • Example#3361 - eio_rmdir example
  • Example#3362 - eio_stat example
  • Example#3363 - eio_statvfs example
  • Example#3364 - eio_symlink example
  • Example#3365 - Expect Usage Example
  • Example#3366 - Another Expect Usage Example
  • Example#3367 - expect_expectl example
  • Example#3368 - expect_popen example
  • Example#3369 - polling STDIN using basic API
  • Example#3370 - polling STDIN using buffered event API
  • Example#3371 - Process Control Example
  • Example#3372 - pcntl_fork example
  • Example#3373 - pcntl_signal_dispatch example
  • Example#3374 - pcntl_signal example
  • Example#3375 - pcntl_sigprocmask example
  • Example#3376 - pcntl_sigwaitinfo example
  • Example#3377 - posix_access example
  • Example#3378 - posix_ctermid example
  • Example#3379 - posix_get_last_error example
  • Example#3380 - posix_getcwd example
  • Example#3381 - posix_getegid example
  • Example#3382 - posix_geteuid example
  • Example#3383 - posix_getgid example
  • Example#3384 - Example use of posix_getgrgid
  • Example#3385 - Example use of posix_getgrnam
  • Example#3386 - Example use of posix_getgroups
  • Example#3387 - Example use of posix_getlogin
  • Example#3388 - Example use of posix_getpgid
  • Example#3389 - Example use of posix_getpid
  • Example#3390 - Example use of posix_getppid
  • Example#3391 - Example use of posix_getpwnam
  • Example#3392 - Example use of posix_getpwuid
  • Example#3393 - Example use of posix_getrlimit
  • Example#3394 - Example use of posix_getsid
  • Example#3395 - Example use of posix_getuid
  • Example#3396 - A posix_mknod example
  • Example#3397 - posix_setegid example
  • Example#3398 - posix_setgid example
  • Example#3399 - posix_setuid example
  • Example#3400 - posix_strerror example
  • Example#3401 - Example use of posix_times
  • Example#3402 - Example use of posix_uname
  • Example#3403 - Пример использования escapeshellarg
  • Example#3404 - Пример использования escapeshellcmd
  • Example#3405 - Пример функции exec
  • Example#3406 - Пример использования proc_open
  • Example#3407 - Пример использования shell_exec
  • Example#3408 - Пример использования system
  • Example#3409 -
  • Example#3410 - Обзор операций с разделяемой памятью
  • Example#3411 - Закрытие блока разделяемой памяти
  • Example#3412 - Удаление блока разделяемой памяти
  • Example#3413 - Резервирование участка разделяемой памяти
  • Example#3414 - Чтение данных из участка разделяемой памяти
  • Example#3415 - Получение размера блока разделяемой памяти
  • Example#3416 - Запись данных в участок разделяемой памяти
  • Example#3417 - Пример использования geoip_continent_code_by_name
  • Example#3418 - Пример использования geoip_country_code_by_name
  • Example#3419 - Пример использования geoip_country_code3_by_name
  • Example#3420 - Пример использования geoip_country_name_by_name
  • Example#3421 - Пример использования geoip_region_by_name
  • Example#3422 - Пример использованияgeoip_db_avail
  • Example#3423 - Пример использованияgeoip_db_filename
  • Example#3424 - Пример использования geoip_db_get_all_info
  • Example#3425 - Пример использования geoip_db_get_all_info
  • Example#3426 - Пример использования geoip_id_by_name
  • Example#3427 - Пример использованияgeoip_isp_by_name
  • Example#3428 - Пример использованияgeoip_org_by_name
  • Example#3429 - Пример использования geoip_record_by_name
  • Example#3430 - Пример использования geoip_region_by_name
  • Example#3431 - Пример использования geoip_region_name_by_code (Для Канады/США)
  • Example#3432 - Пример использования geoip_region_name_by_code(коды FIPS)
  • Example#3433 - Пример использования geoip_time_zone_by_country_and_region для кода региона US/Canada
  • Example#3434 - Использование geoip_time_zone_by_country_and_region используя коды FIPS
  • Example#3435 - Пример использования json_decode
  • Example#3436 - Доступ к свойствам объектов с неправильными именами
  • Example#3437 - Распространенная ошибка при использовании json_decode
  • Example#3438 - Ошибки с глубиной вложенных объектов (depth)
  • Example#3439 - json_decode с большими целыми числами
  • Example#3440 - Пример использования json_encode
  • Example#3441 - Пример использования json_encode, показывающий действия всех опций
  • Example#3442 - Пример с последовательными индексами начинающимися с нуля и непоследовательными индексами массивов
  • Example#3443 - Пример использования json_last_error
  • Example#3444 - Совместное использование json_last_error и json_encode
  • Example#3445 - Judy array example
  • Example#3446 - Lua::assignexample
  • Example#3447 - Lua::callexample
  • Example#3448 - Lua::evalexample
  • Example#3449 - Lua::registerCallbackexample
  • Example#3450 - LuaClosure::__invokeexample
  • Example#3451 - Пример функции constant
  • Example#3452 - Определение Констант
  • Example#3453 - Проверка констант
  • Example#3454 - Пример функции eval - простое слияние текста
  • Example#3455 - Пример использования exit
  • Example#3456 - Пример использования exit со статусом выхода
  • Example#3457 - Функции выключения и деструкторы выполняются независимо
  • Example#3458 - Вывод информации о браузере пользователя
  • Example#3459 - Пример использования __halt_compiler
  • Example#3460 - Пример использования highlight_string
  • Example#3461 - Пример использования ignore_user_abort
  • Example#3462 - Пример использования pack
  • Example#3463 - Пример использования php_strip_whitespace
  • Example#3464 - Пример использования sleep
  • Example#3465 - Пример использования sys_getloadavg
  • Example#3466 - Пример использования time_nanosleep
  • Example#3467 - Пример использования time_sleep_until
  • Example#3468 - Пример использования uniqid
  • Example#3469 - Пример использования unpack
  • Example#3470 - Пример использования unpack с замещающим аргументом
  • Example#3471 - Пример использования unpack с безымянными ключами
  • Example#3472 - Пример использования usleep
  • Example#3473 - parsekit_compile_file example
  • Example#3474 - parsekit_compile_string example
  • Example#3475 - parsekit_func_arginfo example
  • Example#3476 - Пример использования SplDoublyLinkedList::__construct
  • Example#3477 - Пример использования SplStack::__construct
  • Example#3478 - Пример использования SplQueue::__construct
  • Example#3479 - Эффективная обработка задач с помощью SplQueue
  • Example#3480 - Пример использования SplFixedArray
  • Example#3481 - Пример использования SplFixedArray::__construct
  • Example#3482 - Пример SplFixedArray::count
  • Example#3483 - Пример использования SplFixedArray::fromArray
  • Example#3484 - Пример использования SplFixedArray::getSize
  • Example#3485 - Пример использования SplFixedArray::setSize
  • Example#3486 - Пример использования SplFixedArray::toArray
  • Example#3487 - SplObjectStorage as a set
  • Example#3488 - SplObjectStorage as a map
  • Example#3489 - SplObjectStorage::addAll example
  • Example#3490 - SplObjectStorage::attach example
  • Example#3491 - SplObjectStorage::contains example
  • Example#3492 - SplObjectStorage::count example
  • Example#3493 - SplObjectStorage::current example
  • Example#3494 - SplObjectStorage::detach example
  • Example#3495 - SplObjectStorage::getHash example
  • Example#3496 - SplObjectStorage::getInfo example
  • Example#3497 - SplObjectStorage::key example
  • Example#3498 - SplObjectStorage::next example
  • Example#3499 - SplObjectStorage::offsetExists example
  • Example#3500 - SplObjectStorage::offsetGet example
  • Example#3501 - SplObjectStorage::offsetSet example
  • Example#3502 - SplObjectStorage::offsetUnset example
  • Example#3503 - SplObjectStorage::removeAll example
  • Example#3504 - SplObjectStorage::removeAllExcept example
  • Example#3505 - SplObjectStorage::rewind example
  • Example#3506 - SplObjectStorage::serialize example
  • Example#3507 - SplObjectStorage::setInfo example
  • Example#3508 - SplObjectStorage::unserialize example
  • Example#3509 - SplObjectStorage::valid example
  • Example#3510 - Пример использованияAppendIterator::append
  • Example#3511 - Итерация AppendIterator с помощью foreach
  • Example#3512 - Итерация AppendIterator с помощью AppendIterator API
  • Example#3513 - Пример использования AppendIterator::getInnerIterator
  • Example#3514 - Пример использования AppendIterator.getIteratorIndex
  • Example#3515 - Пример использования AppendIterator::key
  • Example#3516 - Пример использования ArrayIterator::current
  • Example#3517 - Пример использования ArrayIterator::key
  • Example#3518 - ArrayIterator::next example
  • Example#3519 - Пример использования ArrayIterator::rewind
  • Example#3520 - Пример использования ArrayIterator::valid
  • Example#3521 - Доступные аргументы обратного вызова
  • Example#3522 - Основные примеры обратного вызова
  • Example#3523 - Пример использования DirectoryIterator::__construct
  • Example#3524 - Пример использования DirectoryIterator::current
  • Example#3525 - Пример использования DirectoryIterator::getATime
  • Example#3526 - Пример использования DirectoryIterator::getBasename
  • Example#3527 - Пример использования DirectoryIterator::getCTime
  • Example#3528 - Пример использования DirectoryIterator::getFilename
  • Example#3529 - Пример использования DirectoryIterator::getGroup
  • Example#3530 - Пример использования DirectoryIterator::getInode
  • Example#3531 - Пример использования DirectoryIterator::getMTime
  • Example#3532 - Пример использования DirectoryIterator::getOwner
  • Example#3533 - Пример использования DirectoryIterator::getPath
  • Example#3534 - Пример использования DirectoryIterator::getPathname
  • Example#3535 - Пример использования DirectoryIterator::getPerms
  • Example#3536 - Пример использования DirectoryIterator::getSize
  • Example#3537 - Пример использования DirectoryIterator::getType
  • Example#3538 - Пример использования DirectoryIterator::isDir
  • Example#3539 - Пример использования DirectoryIterator::isDot
  • Example#3540 - DirectoryIterator::isExecutable example
  • Example#3541 - Пример использования DirectoryIterator::isFile example
  • Example#3542 - Пример использования DirectoryIterator::isLink
  • Example#3543 - Пример использования DirectoryIterator::isReadable
  • Example#3544 - Пример использования DirectoryIterator::isWritable
  • Example#3545 - Пример использования DirectoryIterator::key
  • Example#3546 - Пример использования DirectoryIterator::next
  • Example#3547 - Пример использования DirectoryIterator::rewind
  • Example#3548 - Пример использования DirectoryIterator::seek
  • Example#3549 - Пример использования DirectoryIterator::__toString
  • Example#3550 - Пример использования DirectoryIterator::valid
  • Example#3551 - FilesystemIterator::__construct example
  • Example#3552 - FilesystemIterator::current example
  • Example#3553 - FilesystemIterator::key example
  • Example#3554 - FilesystemIterator::next example
  • Example#3555 - FilesystemIterator::rewind example
  • Example#3556 - FilesystemIterator::key example
  • Example#3557 - Пример использования FilterIterator::accept
  • Example#3558 - GlobIterator example
  • Example#3559 - GlobIterator::count example
  • Example#3560 - InfiniteIterator::__construct example
  • Example#3561 - Пример использования LimitIterator
  • Example#3562 - LimitIterator::__construct example
  • Example#3563 - LimitIterator::getPosition example
  • Example#3564 - Итерирование MultipleIterator
  • Example#3565 - Пример использования NoRewindIterator::__construct
  • Example#3566 - Пример использования NoRewindIterator::rewind
  • Example#3567 - RecursiveArrayIterator::getChildren example
  • Example#3568 - RecursiveArrayIterator::hasChildren example
  • Example#3569 - Доступные аргументы обратного вызова
  • Example#3570 - Простой пример рекурсивного обратного вызова
  • Example#3571 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#3572 - RecursiveDirectoryIterator example
  • Example#3573 - Basic RecursiveFilterIterator example
  • Example#3574 - RecursiveFilterIterator example
  • Example#3575 - Iterating a RecursiveIteratorIterator
  • Example#3576 - RecursiveRegexIterator::__construct example
  • Example#3577 - RecursiveRegexIterator::getChildren example
  • Example#3578 - RecursiveRegexIterator::hasChildren example
  • Example#3579 - RegexIterator::accept example
  • Example#3580 - RegexIterator::__construct example
  • Example#3581 - RegexIterator::getFlags example
  • Example#3582 - RegexIterator::getMode example
  • Example#3583 - RegexIterator::getPregFlags example
  • Example#3584 - RegexIterator::setFlags example
  • Example#3585 - RegexIterator::setMode example
  • Example#3586 - RegexIterator::setPregFlags example
  • Example#3587 - Пример использования Countable::count
  • Example#3588 - Basic usage
  • Example#3589 - Пример использования SeekableIterator::seek
  • Example#3590 - class_implements example
  • Example#3591 - class_parents example
  • Example#3592 - class_uses example
  • Example#3593 - Пример использования iterator_apply
  • Example#3594 - Пример использования iterator_count
  • Example#3595 - Пример использования iterator_to_array
  • Example#3596 - spl_autoload_register as a replacement for an __autoload function
  • Example#3597 - spl_autoload_register example where the class is not loaded
  • Example#3598 - Пример использования spl_classes
  • Example#3599 - A spl_object_hash example
  • Example#3600 - Пример использования SplFileInfo::__construct
  • Example#3601 - Пример использования SplFileInfo::getBasename
  • Example#3602 - SplFileInfo::getCTime example
  • Example#3603 - Пример использования SplFileInfo::getExtension
  • Example#3604 -
  • Example#3605 - Пример использования SplFileInfo::getFilename
  • Example#3606 - Пример использования SplFileInfo::getGroup
  • Example#3607 - SplFileInfo::getLinkTarget example
  • Example#3608 - SplFileInfo::getOwner example
  • Example#3609 - SplFileInfo::getPath example
  • Example#3610 - SplFileInfo::getPathInfo example
  • Example#3611 - SplFileInfo::getPathname example
  • Example#3612 - SplFileInfo::getPerms example
  • Example#3613 - SplFileInfo::getRealPath example
  • Example#3614 - Пример использования SplFileInfo::getType
  • Example#3615 - Пример использования SplFileInfo::isDir
  • Example#3616 - Пример использования SplFileInfo::isExecutable
  • Example#3617 - Пример использования SplFileInfo::isFile
  • Example#3618 - Пример использования SplFileInfo::isLink
  • Example#3619 - Пример использования SplFileInfo::isReadable
  • Example#3620 - Пример использования SplFileInfo::openFile
  • Example#3621 - SplFileInfo::setFileClass example
  • Example#3622 - SplFileInfo::setFileClass example
  • Example#3623 - Пример использования SplFileInfo::__toString
  • Example#3624 - SplFileObject::__construct example
  • Example#3625 - SplFileObject::current example
  • Example#3626 - Пример использования SplFileObject::eof
  • Example#3627 - Пример использования SplFileObject::fflush
  • Example#3628 - Пример использования SplFileObject::fgetc
  • Example#3629 - SplFileObject::fgetcsv example
  • Example#3630 - SplFileObject::READ_CSV example
  • Example#3631 - Пример использования SplFileObject::fgets
  • Example#3632 - SplFileObject::fgetss example
  • Example#3633 - Пример использования SplFileObject::flock
  • Example#3634 - SplFileObject::fpassthru example
  • Example#3635 - SplFileObject::fscanf example
  • Example#3636 - SplFileObject::fseek example
  • Example#3637 - Пример использования SplFileObject::fstat
  • Example#3638 - SplFileObject::ftell example
  • Example#3639 - SplFileObject::ftruncate example
  • Example#3640 - Пример использования SplFileObject::fwrite
  • Example#3641 - Пример использования SplFileObject::getCsvControl
  • Example#3642 - SplFileObject::getFlags example
  • Example#3643 - Пример использования SplFileObject::getMaxLineLen
  • Example#3644 - SplFileObject::key example
  • Example#3645 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#3646 - Пример использования SplFileObject::next
  • Example#3647 - SplFileObject::rewind example
  • Example#3648 - SplFileObject::seek example
  • Example#3649 - Пример использования SplFileObject::setCsvControl
  • Example#3650 - Пример использования SplFileObject::setFlags
  • Example#3651 - Пример использования SplFileObject::setMaxLineLen
  • Example#3652 - Пример использования SplFileObject::valid
  • Example#3653 - Пример использования SplTempFileObject
  • Example#3654 - Пример использования ArrayObject::append
  • Example#3655 - Пример использования ArrayObject::asort
  • Example#3656 - Пример использования ArrayObject::__construct
  • Example#3657 - Пример использования ArrayObject::count
  • Example#3658 - Пример использования ArrayObject::exchangeArray
  • Example#3659 - Пример использования ArrayObject::getArrayCopy
  • Example#3660 - Пример использования ArrayObject::getFlags
  • Example#3661 - Пример использования ArrayObject::getIterator
  • Example#3662 - Пример использования ArrayObject::getIteratorClass
  • Example#3663 - Пример использования ArrayObject::ksort
  • Example#3664 - Пример использования ArrayObject::natcasesort
  • Example#3665 - Пример использования ArrayObject::natsort
  • Example#3666 - Пример использования ArrayObject::offsetExists
  • Example#3667 - Пример использования ArrayObject::offsetGet
  • Example#3668 - Пример использования ArrayObject::offsetSet
  • Example#3669 - Пример использования ArrayObject::offsetUnset
  • Example#3670 - Пример использования ArrayObject::serialize
  • Example#3671 - Пример использования ArrayObject::setFlags
  • Example#3672 - Пример использования ArrayObject::setIteratorClass
  • Example#3673 - Пример использования ArrayObject::uasort
  • Example#3674 - Пример использования ArrayObject::uksort
  • Example#3675 - SplInt usage example
  • Example#3676 - SplFloat usage example
  • Example#3677 - SplEnum usage example
  • Example#3678 - SplEnum::getConstList example
  • Example#3679 - SplBool usage example
  • Example#3680 - SplString usage example
  • Example#3681 - Using file_get_contents to retrieve data from multiple sources
  • Example#3682 - Making a POST request to an https server
  • Example#3683 - Writing data to a compressed file
  • Example#3684 - A Stream for reading/writing global variables
  • Example#3685 - Listing files from tar archives
  • Example#3686 - Использование stream_context_create
  • Example#3687 - Пример использования stream_context_get_default
  • Example#3688 - Пример использования stream_context_get_options
  • Example#3689 - Пример использования stream_context_get_params
  • Example#3690 - stream_context_set_default example
  • Example#3691 - Пример использования stream_copy_to_stream
  • Example#3692 - Контроль применения фильтров
  • Example#3693 - Фильтр для перевода букв в верхний регистр в потоке foo-bar.txt
  • Example#3694 - Регистрация стандартного фильтра, соответствующего множественным именам фильтров.
  • Example#3695 - Динамическое изменение фильтров потока
  • Example#3696 - Пример использования stream_get_contents
  • Example#3697 - Пример использования функции stream_get_filters
  • Example#3698 - Пример использования функцииstream_get_meta_data
  • Example#3699 - Пример использования stream_get_transports
  • Example#3700 - Пример использования stream_get_wrappers
  • Example#3701 - Проверка существования обёртки потока
  • Example#3702 - stream_is_local example
  • Example#3703 - Пример использования stream_notification_callback
  • Example#3704 - Простой индикатор для загрузчика файлов из командной строки
  • Example#3705 - Пример использования stream_resolve_include_path
  • Example#3706 - Пример использованияstream_select
  • Example#3707 - Пример использования stream_set_timeout
  • Example#3708 - Пример использования stream_set_write_buffer
  • Example#3709 - Пример использования функции stream_socket_client
  • Example#3710 - Использование UDP-соединения
  • Example#3711 - Пример использования stream_socket_enable_crypto
  • Example#3712 - Пример использования stream_socket_pair
  • Example#3713 - Пример использования функции stream_socket_recvfrom
  • Example#3714 - Пример использования stream_socket_sendto
  • Example#3715 - Пример использования серверных сокетов TCP
  • Example#3716 - Пример использования серверных сокетов UDP
  • Example#3717 - Пример использования stream_socket_shutdown
  • Example#3718 - Как зарегистрировать обёртку потока
  • Example#3719 - Базовые возможности использования Tidy
  • Example#3720 - Пример использования функции tidy::getBody
  • Example#3721 - Пример использования функции tidy::cleanrepair
  • Example#3722 - Пример использования функции tidy::__construct
  • Example#3723 - Пример использования функции tidy::diagnose
  • Example#3724 - tidy_get_error_buffer example
  • Example#3725 - Пример использования функции tidy::getConfig
  • Example#3726 - Пример использования функции tidy_getopt
  • Example#3727 - Печать всех опций вместе с описанием и значением по умолчанию
  • Example#3728 - Пример использования функции tidy::getStatus
  • Example#3729 - Пример использования функции tidy::head
  • Example#3730 - Пример использования функции tidy::html
  • Example#3731 - Пример использования функции tidy::parseFile
  • Example#3732 - Пример использования функции tidy::parseString
  • Example#3733 - Пример использования функции tidy::repairFile
  • Example#3734 - Пример использования функции tidy::repairString
  • Example#3735 - Пример использования функции tidy::root
  • Example#3736 - Пример использования функции tidyNode::getParent
  • Example#3737 - Пример использования функции tidyNode::hasChildren
  • Example#3738 - Пример использования функции tidyNode::hasSiblings
  • Example#3739 - Извлечение кода ASP из смешанного HTML-документа
  • Example#3740 - Извлечение комментариев из смешанного HTML-документа
  • Example#3741 - Извлечение HTML-кода из смешанного HTML-документа
  • Example#3742 - Извлечение JSTE-кода из смешанного HTML-документа
  • Example#3743 - Извлечение PHP-кода из смешанного HTML-документа
  • Example#3744 - Извлечение обычного текста из смешанного HTML-документа
  • Example#3745 - Пример использования ob_tidyhandler
  • Example#3746 - Пример использования tidy_access_count
  • Example#3747 - Пример использования tidy_config_count
  • Example#3748 - Пример использования tidy_error_count
  • Example#3749 - Пример использования функции tidy_get_output
  • Example#3750 - Пример использования функции tidy_setopt
  • Example#3751 - Пример использования функции tidy_warning_count
  • Example#3752 - Удаление комментариев лексром
  • Example#3753 - Пример использования token_get_all
  • Example#3754 - Пример использования token_name
  • Example#3755 - Пример использования base64_decode
  • Example#3756 - Пример использования base64_encode
  • Example#3757 - Пример использования get_headers
  • Example#3758 - Пример использования запроса HEAD в функцииget_headers
  • Example#3759 - Что обрабатывает функция get_meta_tags
  • Example#3760 - Что возвращает функция get_meta_tags
  • Example#3761 - Простой пример использования http_build_query
  • Example#3762 - Пример использования http_build_query с числовыми индексами элементов.
  • Example#3763 - Пример использования http_build_query с многомерными массивами
  • Example#3764 - Пример использования http_build_query с объектом
  • Example#3765 - Пример использования parse_url
  • Example#3766 - Пример использования rawurldecode
  • Example#3767 - Пример использования rawurlencode для включение пароля в FTP URL
  • Example#3768 - Пример использования rawurlencode
  • Example#3769 - Пример использования urldecode
  • Example#3770 - Пример использования urlencode
  • Example#3771 - Пример использования urlencode и htmlentities
  • Example#3772 - Basic Javascript execution
  • Example#3773 - Пример работы с Yaml
  • Example#3774 - Parse callback example
  • Example#3775 - Emit callback example
  • Example#3776 - yaml_emit example
  • Example#3777 - yaml_parse example
  • Example#3778 - A classic Application directory layout
  • Example#3779 - Entry
  • Example#3780 - Rewrite rule
  • Example#3781 - Application config
  • Example#3782 - Default controller
  • Example#3783 - Default view template
  • Example#3784 - Run the Applicatioin
  • Example#3785 - An array of yaf configuration example
  • Example#3786 - an ini file of yaf configuration example
  • Example#3787 - A Bootstrapexample
  • Example#3788 - Yaf_Application::bootstrapexample
  • Example#3789 - Yaf_Application::clearLastErrorexample
  • Example#3790 - A ini config file example
  • Example#3791 - Yaf_Application::__constructexample
  • Example#3792 - Yaf_Application::__constructexample
  • Example#3793 - Yaf_Application::environexample
  • Example#3794 - Yaf_Application::executeexample
  • Example#3795 - Yaf_Application::getConfigexample
  • Example#3796 - Yaf_Application::getDispatcherexample
  • Example#3797 - Yaf_Application::getLastErrorMsgexample
  • Example#3798 - Yaf_Application::getLastErrorNoexample
  • Example#3799 - Yaf_Application::getModulesexample
  • Example#3800 - Yaf_Dispatcher::autoRenderexample
  • Example#3801 - Yaf_Dispatcher::catchExceptionexample
  • Example#3802 - Yaf_Dispatcher::registerPluginexample
  • Example#3803 - A custom View engineexample
  • Example#3804 - Yaf_Dispatcher::setViewexample
  • Example#3805 - Yaf_Config_Iniexample
  • Example#3806 - define action in a separate file
  • Example#3807 - Dummy_action.php
  • Example#3808 - Yaf_Action_Abstract::executeexample
  • Example#3809 - Yaf_Action_Abstract::executeexample
  • Example#3810 - Yaf_View_Simple::assignexample
  • Example#3811 - templateexample
  • Example#3812 - Yaf_View_Simple::assignRefexample
  • Example#3813 - templateexample
  • Example#3814 - Yaf_View_Simple::clearexample
  • Example#3815 - Yaf_View_Simple::__constructorexample
  • Example#3816 - Yaf_View_Simple::__setexample
  • Example#3817 - Config example
  • Example#3818 - Register localnamespace
  • Example#3819 - Load class example
  • Example#3820 - Load namespace class example
  • Example#3821 - MVC class loading example
  • Example#3822 - MVC class distinctions
  • Example#3823 - MVC loading example
  • Example#3824 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#3825 - Yaf_Route_Mapexample
  • Example#3826 - Yaf_Route_Mapexample
  • Example#3827 - Yaf_Route_Mapexample
  • Example#3828 - Yaf_Route_Regexexample
  • Example#3829 - Yaf_Route_Regexexample
  • Example#3830 - Yaf_Route_Rewriteexample
  • Example#3831 - Yaf_Route_Rewriteexample
  • Example#3832 - Rewrite rule for Apache
  • Example#3833 - Rewrite rule for Apache
  • Example#3834 - Rewrite rule for Lighttpd
  • Example#3835 - Rewrite rule for Nginx
  • Example#3836 - Yaf_Route_Static(default route)example
  • Example#3837 - application.iniexample
  • Example#3838 - Yaf_Dispatcher::autoConfigexample
  • Example#3839 - Yaf_Dispatcher::autoRenderexample
  • Example#3840 - Register some routes in Bootstrap
  • Example#3841 - plugin Dummy.php (under application.directory/plugins)
  • Example#3842 - Yaf_Route_Simple::routeexample
  • Example#3843 - Yaf_Route_Simple::routeexample
  • Example#3844 - Yaf_Route_Static::routeexample
  • Example#3845 - Yaf_Route_Supervarexample
  • Example#3846 - Taintexample
  • Example#3847 - Пример AMQP
  • Example#3848 - Пример использования AMQPConnection::connect
  • Example#3849 - Пример использования AMQPConnection::__construct
  • Example#3850 - Пример использования AMQPConnection::disconnect
  • Example#3851 - Пример использования AMQPConnection::isConnected
  • Example#3852 - Пример использования AMQPConnection::reconnect
  • Example#3853 - Пример использования AMQPConnection::setHost
  • Example#3854 - Пример использования AMQPConnection::setLogin
  • Example#3855 - Пример использования AMQPConnection::setPassword
  • Example#3856 - Пример использования AMQPConnection::setPort
  • Example#3857 - Пример использования AMQPConnection::setVhost
  • Example#3858 - Пример использования AMQPExchange::declare
  • Example#3859 - Пример использования AMQPExchange::delete
  • Example#3860 - Пример использования AMQPQueue::ack с AMQPQueue::get
  • Example#3861 - Пример использования AMQPQueue::ack с AMQPQueue::consume
  • Example#3862 - Пример использования AMQPQueue::consume
  • Example#3863 - Пример использования AMQPQueue::get
  • Example#3864 - Creating a chdb file
  • Example#3865 - Loading and looking up a chdb file
  • Example#3866 - chdb::get example
  • Example#3867 - chdb_create example
  • Example#3868 - Использование модуля cURL для сохранения стартовой страницы example.com
  • Example#3869 - Инициализация сеанса cURL и загрузка web-страницы
  • Example#3870 - Копирование дескриптора cURL
  • Example#3871 - Пример использования curl_errno
  • Example#3872 - Пример использования curl_error
  • Example#3873 - Загрузка web-страницы
  • Example#3874 - curl_getinfo example
  • Example#3875 - Инициализация нового сеанса cURL и загрузка web-страницы
  • Example#3876 - Пример использования curl_multi_add_handle
  • Example#3877 - Пример использования curl_multi_close
  • Example#3878 - Пример использования curl_multi_exec
  • Example#3879 - Пример использования curl_multi_info_read
  • Example#3880 - Пример использования curl_multi_init
  • Example#3881 - Инициализация новой сессии cURL и загрузка веб-страницы
  • Example#3882 - Наша собственная реализация curl_setopt_array
  • Example#3883 - Инициализация сеанса CURL и загрузка web-страницы
  • Example#3884 - Закачка файла
  • Example#3885 - Пример использования curl_version
  • Example#3886 - Пример использования FTP-функций
  • Example#3887 - Пример использования ftp_alloc
  • Example#3888 - Пример использования функции ftp_cdup
  • Example#3889 - Пример использования ftp_chdir
  • Example#3890 - Пример использования ftp_chmod
  • Example#3891 - Пример использования ftp_close
  • Example#3892 - Пример использования ftp_connect
  • Example#3893 - Пример использования ftp_delete
  • Example#3894 - Пример использования ftp_exec
  • Example#3895 - Пример использования ftp_fget
  • Example#3896 - Пример использования ftp_fput
  • Example#3897 - Пример использования ftp_get_option
  • Example#3898 - Пример использования ftp_get
  • Example#3899 - Пример использования ftp_login
  • Example#3900 - Пример использования ftp_mdtm
  • Example#3901 - Пример использования ftp_mkdir
  • Example#3902 - Пример использования ftp_nb_continue
  • Example#3903 - Пример использования ftp_nb_fget
  • Example#3904 - Пример использования ftp_nb_fput
  • Example#3905 - Пример использования ftp_nb_get
  • Example#3906 - Возобновление скачивания файла с помощью ftp_nb_get
  • Example#3907 - Скачивание файла начиная с позиции 100 в новый файл с помощью ftp_nb_get
  • Example#3908 - Пример использования ftp_nb_put
  • Example#3909 - Возобновление загрузки файла с помощью ftp_nb_put
  • Example#3910 - Пример использования ftp_nlist
  • Example#3911 - Пример использования ftp_pasv
  • Example#3912 - Пример использования ftp_put
  • Example#3913 - Пример использования ftp_pwd
  • Example#3914 - Использование ftp_raw для входа на FTP-сервер
  • Example#3915 - Пример использования ftp_rawlist
  • Example#3916 - Пример использования ftp_rename
  • Example#3917 - Пример использования ftp_rmdir
  • Example#3918 - Пример использования ftp_set_option
  • Example#3919 - Отправка команды SITE FTP-серверу
  • Example#3920 - Пример использования ftp_size
  • Example#3921 - Пример использования функции ftp_ssl_connect
  • Example#3922 - Пример использования ftp_systype
  • Example#3923 - Базовый клиент и обработчик Gearman
  • Example#3924 - Базовый клиент и обработчик Gearman, фоновый режим
  • Example#3925 - Базовые клиент и обработчик Gearman, отправка задач
  • Example#3926 - Добавление двух серверов задач
  • Example#3927 - Добавление двух серверов задач
  • Example#3928 - Основное представление двух задач
  • Example#3929 - Основное представление двух задач с передачей контекста приложения
  • Example#3930 - Две задачи, одна в фоновом режиме другая нет
  • Example#3931 - Высокоприоритетная задача вместе с двумя нормальными задачами
  • Example#3932 - Низкоприоритетная задача вместе с двумя нормальными задачами
  • Example#3933 - Монитор завершения множественных фоновых задач
  • Example#3934 - Простое представление задания с непосредственным возвратом
  • Example#3935 - Передача задания и получение инкрементного состояния
  • Example#3936 - Отправляет и отслеживает фоновое задание
  • Example#3937 - Simple job submission with immediate return
  • Example#3938 - Submitting a job and retrieving incremental status
  • Example#3939 - Get the status of a long running job
  • Example#3940 - Monitor the status of a long running background job
  • Example#3941 - Simple worker making use of extra application context data
  • Example#3942 - Add alternate Gearman servers
  • Example#3943 - Add two job servers
  • Example#3944 - A simple worker with a 5 second timeout
  • Example#3945 - Running worker in non-blocking mode
  • Example#3946 - GearmanWorker::work example
  • Example#3947 - Hypothetical output from gopher://gopher.example.com/
  • Example#3948 - Using gopher_parsedir
  • Example#3949 - Search for all UPnP devices and services.
  • Example#3950 - Implementing light server
  • Example#3951 - Implementing light client
  • Example#3952 - Create new UPnP context and get IP address of the host
  • Example#3953 - Create new UPnP context and get port number
  • Example#3954 - Create new UPnP context and set host path
  • Example#3955 - Create new UPnP context
  • Example#3956 - Create new UPnP context and set callback
  • Example#3957 - Create new UPnP context and start browsing
  • Example#3958 - Create new UPnP context and start browsing
  • Example#3959 - Create new UPnP context and get device info service
  • Example#3960 - Create new UPnP context and get device info service
  • Example#3961 - A HttpDeflateStream example
  • Example#3962 - A HttpInflateStream example
  • Example#3963 - A HttpRequest::addCookies example
  • Example#3964 - GET example
  • Example#3965 - POST example
  • Example#3966 - A HttpRequestPool example
  • Example#3967 - A HttpRequestPool::socketPerform example
  • Example#3968 - A HttpResponse::capture example
  • Example#3969 - A HttpResponse::send example
  • Example#3970 - A http_cache_etag example
  • Example#3971 - A http_cache_last_modified example
  • Example#3972 - A http_chunked_decode example
  • Example#3973 - A http_support example
  • Example#3974 - Using http_negotiate_charset
  • Example#3975 - Using http_negotiate_content_type
  • Example#3976 - Using http_negotiate_language
  • Example#3977 - Using http_parse_cookie
  • Example#3978 - Using http_parse_headers
  • Example#3979 - Using http_parse_message
  • Example#3980 - A http_parse_params example
  • Example#3981 - A http_persistent_handles_count example
  • Example#3982 - A http_persistent_handles_ident example
  • Example#3983 - A http_get example
  • Example#3984 - A http_post_fields example
  • Example#3985 - A http_redirect example
  • Example#3986 - A http_send_file example
  • Example#3987 - A http_throttle example
  • Example#3988 - A http_build_url example
  • Example#3989 - modifying an attribute
  • Example#3990 - adding a completely new attribute
  • Example#3991 - modifying Title attribute
  • Example#3992 - modifying Title attribute
  • Example#3993 - removing attribute
  • Example#3994 - Retrieve an object
  • Example#3995 - Java Example
  • Example#3996 - AWT Example
  • Example#3997 - Java exception handler
  • Example#3998 - Пример LDAP поиска
  • Example#3999 - Полный пример с проверкой подлинности привязки
  • Example#4000 - Пример использования привязки LDAP
  • Example#4001 - Использование анонимной привязки LDAP
  • Example#4002 - Полный пример проверки пароля
  • Example#4003 - Пример подключения к серверу LDAP.
  • Example#4004 - Пример безопасного подключения к серверу LDAP.
  • Example#4005 - LDAP pagination
  • Example#4006 - LDAP pagination
  • Example#4007 - Перечисление всех сообщений об ошибках LDAP
  • Example#4008 - Генерирование и фиксация ошибки
  • Example#4009 - Показывает список атрибутов, соответствующие определенной записи директории
  • Example#4010 - Проверка версии протокола
  • Example#4011 - Список всех значений атрибута "mail" для записи каталога
  • Example#4012 - Выводит список всех организационных единиц организации
  • Example#4013 - LDAP поиск
  • Example#4014 - Устанавливает версию протокола
  • Example#4015 - Устанавливает управление сервером
  • Example#4016 - Пример использования расширения memcache
  • Example#4017 - Использование memcache в качестве обработчика сессий
  • Example#4018 - Memcache::add example
  • Example#4019 - Memcache::addServer example
  • Example#4020 - Memcache::close example
  • Example#4021 - Memcache::connect example
  • Example#4022 - Memcache::decrement example
  • Example#4023 - Memcache::delete example
  • Example#4024 - Memcache::flush example
  • Example#4025 - Memcache::get example
  • Example#4026 - Memcache::getExtendedStats example
  • Example#4027 - Memcache::getServerStatus example
  • Example#4028 - Memcache::getVersion example
  • Example#4029 - Memcache::increment example
  • Example#4030 - Memcache::pconnect example
  • Example#4031 - Memcache::replace example
  • Example#4032 - Memcache::set example
  • Example#4033 - Memcache::set example
  • Example#4034 - Memcache::setCompressThreshold example
  • Example#4035 - Memcache::setServerParams example
  • Example#4036 - Result callback example
  • Example#4037 - Read-through callback example
  • Example#4038 - Memcached::addServer example
  • Example#4039 - Memcached::addServers example
  • Example#4040 - Memcached::append example
  • Example#4041 - Memcached::cas example
  • Example#4042 - Creating a Memcached object
  • Example#4043 - Memcached::decrement example
  • Example#4044 - Memcached::delete example
  • Example#4045 - Memcached::fetch example
  • Example#4046 - Memcached::getDelayed example
  • Example#4047 - Memcached::flush example
  • Example#4048 - Memcached::get example #1
  • Example#4049 - Memcached::get example #2
  • Example#4050 - Memcached::getDelayed example
  • Example#4051 - Memcached::getMulti example
  • Example#4052 - Memcached::GET_PRESERVE_ORDER example
  • Example#4053 - Retrieving Memcached options
  • Example#4054 - Memcached::getResultCode example
  • Example#4055 - Memcached::getResultMessage example
  • Example#4056 - Memcached::getServerByKey example
  • Example#4057 - Memcached::getServerList example
  • Example#4058 - Memcached::getStats example
  • Example#4059 - Memcached::getVersion example
  • Example#4060 - Memcached::increment example
  • Example#4061 - Memcached::prepend example
  • Example#4062 - Memcached::set example
  • Example#4063 - Memcached::setByKey example
  • Example#4064 - Memcached::setMulti example
  • Example#4065 - Setting a Memcached option
  • Example#4066 - mqseries_back example
  • Example#4067 - mqseries_begin example
  • Example#4068 - mqseries_close example
  • Example#4069 - mqseries_cmit example
  • Example#4070 - mqseries_conn example
  • Example#4071 - mqseries_connx example
  • Example#4072 - mqseries_disc example
  • Example#4073 - mqseries_get example
  • Example#4074 - mqseries_inq example
  • Example#4075 - mqseries_open example
  • Example#4076 - mqseries_put example
  • Example#4077 - mqseries_strerror example
  • Example#4078 - Пример использования define_syslog_variables
  • Example#4079 - Using dns_get_record
  • Example#4080 - Using dns_get_record and DNS_ANY
  • Example#4081 - fsockopen Example
  • Example#4082 - Using UDP connection
  • Example#4083 - Простой пример использования gethostbyaddr
  • Example#4084 - Простой пример использования gethostbyname
  • Example#4085 - Пример использования функции gethostbynamel
  • Example#4086 - Пример использования gethostname
  • Example#4087 - Пример использования getprotobyname
  • Example#4088 - Пример использования getservbyname
  • Example#4089 - Пример использования header_register_callback
  • Example#4090 - Уничтожение определенного заголовка.
  • Example#4091 - Уничтожение всех предварительно установленных заголовков.
  • Example#4092 - Download dialog
  • Example#4093 - Caching directives
  • Example#4094 - Пример использования headers_list
  • Example#4095 - Пример использования headers_sent
  • Example#4096 - Пример использования headers_list
  • Example#4097 - Пример использования inet_ntop
  • Example#4098 - Пример использования inet_pton
  • Example#4099 - Пример использования ip2long
  • Example#4100 - Отображение IP адресов
  • Example#4101 - Валидация IP
  • Example#4102 - setcookie send example
  • Example#4103 - setcookie delete example
  • Example#4104 - setcookie and arrays
  • Example#4105 - Пример использования syslog
  • Example#4106 - Procedural usage of rrd
  • Example#4107 - OO usage of rrd
  • Example#4108 - RRDGraph::setOptions examples
  • Example#4109 - RRDUpdater::update examples
  • Example#4110 - Creating a connection and connecting to a remote WebSphere MQSeries Messaging Server
  • Example#4111 - Creating a connection and connecting to a remote WebSphere Application Server
  • Example#4112 - Creating a connection and connecting to an MQTT server
  • Example#4113 - Creating a message with a simple text body
  • Example#4114 - Setting a text format property using the default syntax
  • Example#4115 - Setting a property using a type hint
  • Example#4116 - Retrieving a property from a message header
  • Example#4117 - Adding a message to a queue and receiving a response
  • Example#4118 - Creating a durable subscription to a topic
  • Example#4119 - Subscribing to a topic using a WebSphere Platform Messaging (WPM) server
  • Example#4120 - Receiving published data using a durable subscription
  • Example#4121 - Deleting a durable subscription to a topic
  • Example#4122 - Handling an error from a method that returns no result
  • Example#4123 - Handling an error from a method that returns a result
  • Example#4124 - Committing the current unit of work
  • Example#4125 - Creating a connection to a Messaging Server using the IBM MQSeries protocol (WMQ)
  • Example#4126 - Creating a connection with application transaction control and default host and port values
  • Example#4127 - Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)
  • Example#4128 - Creating a connection object and connecting to a Messaging Server
  • Example#4129 - Disconnecting from a Messaging Server
  • Example#4130 - Using the error number and description properties
  • Example#4131 - Using the error number and description properties
  • Example#4132 - Checking whether there us a connection to a Messaging Server
  • Example#4133 - Retrieve the next message from a queue without removing it
  • Example#4134 - Retrieve a specific message from a queue without removing it from the queue
  • Example#4135 - Retrieve all messages in a queue without removing them
  • Example#4136 - Retrieve all messages from a queue with a matching correlation id
  • Example#4137 - Receiving a message from a queue
  • Example#4138 - Receiving a message from a queue with options
  • Example#4139 - Receiving a message from a subscription
  • Example#4140 - Removing a message from a queue by message id
  • Example#4141 - Cancelling an in-flight unit of work
  • Example#4142 - Send a message to a queue
  • Example#4143 - Publish a message to a topic
  • Example#4144 - Send a request and receive a response
  • Example#4145 - Turn on debugging output
  • Example#4146 - Turn off debugging output
  • Example#4147 - Subscribe to a topic
  • Example#4148 - Delete a subscription
  • Example#4149 - Setting a text string into the body of a message
  • Example#4150 - Creating a message
  • Example#4151 - Creating a message with a simple text payload
  • Example#4152 - Setting a text format property using the default syntax
  • Example#4153 - Setting a text format property using a type hint
  • Example#4154 - Setting properties as the sender of a message
  • Example#4155 - Retreiving property values from a message
  • Example#4156 - snmp_get_quick_print example
  • Example#4157 - Using snmp_get_valueretrieval
  • Example#4158 - Using snmp_read_mib
  • Example#4159 - Using snmp_set_enum_print
  • Example#4160 - Using snmprealwalk
  • Example#4161 - Using snmp_set_quick_print
  • Example#4162 - Using snmp_set_valueretrieval
  • Example#4163 - Using snmp2_get
  • Example#4164 - Using snmp2_get_next
  • Example#4165 - Using snmp2_real_walk
  • Example#4166 - Using snmp2_set
  • Example#4167 - Using snmp2_set for setting BITS SNMP object id
  • Example#4168 - snm2_pwalk Example
  • Example#4169 - Using snmp3_get
  • Example#4170 - Using snmp3_getnext
  • Example#4171 - Using snmp3_real_walk
  • Example#4172 - Using snmp3_set
  • Example#4173 - Using snmp3_set for setting BITS SNMP object id
  • Example#4174 - snmp3_walk Example
  • Example#4175 - Using snmpget
  • Example#4176 - Using snmpgetnext
  • Example#4177 - Using snmprealwalk
  • Example#4178 - Using snmpset
  • Example#4179 - Using snmpset for setting BITS SNMP object id
  • Example#4180 - snmpwalk Example
  • Example#4181 - snmpwalkoid Example
  • Example#4182 - SNMP::close example
  • Example#4183 - Fetching sysLocation
  • Example#4184 - Single SNMP object
  • Example#4185 - Miltiple SNMP objects
  • Example#4186 - SNMP::getErrno example
  • Example#4187 - SNMP::getError example
  • Example#4188 - Single SNMP object
  • Example#4189 - Miltiple SNMP objects
  • Example#4190 - Set single SNMP object id
  • Example#4191 - Set multiple values using single SNMP::set call
  • Example#4192 - Using SNMP::set for setting BITS SNMP object id
  • Example#4193 - SNMP::setSecurity example
  • Example#4194 - SNMP::walk example
  • Example#4195 - suffix_as_key example
  • Example#4196 - Socket example: Simple TCP/IP server
  • Example#4197 - Socket example: Simple TCP/IP client
  • Example#4198 - Using socket_bind to set the source address
  • Example#4199 - socket_create_pair example
  • Example#4200 - socket_create_pair IPC example
  • Example#4201 - socket_set_option example
  • Example#4202 - socket_import_stream example
  • Example#4203 - socket_last_error example
  • Example#4204 - socket_recv example
  • Example#4205 - socket_recvfrom example
  • Example#4206 - Using NULL with socket_select
  • Example#4207 - Understanding socket_select's result
  • Example#4208 - socket_select example
  • Example#4209 - socket_sendto Example
  • Example#4210 - socket_set_block example
  • Example#4211 - socket_set_nonblock example
  • Example#4212 - socket_set_option example
  • Example#4213 - socket_strerror example
  • Example#4214 - Authentication using a public hostkey
  • Example#4215 - Retrieving a list of authentication methods
  • Example#4216 - Authenticating with a password
  • Example#4217 - Authentication using a public key
  • Example#4218 - ssh2_connect example
  • Example#4219 - Executing a command
  • Example#4220 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4221 - Checking the fingerprint against a known value
  • Example#4222 - Determining what methods were negotiated
  • Example#4223 - Adding a publickey with ssh2_publickey_add
  • Example#4224 - Listing authorized keys with ssh2_publickey_list
  • Example#4225 - Downloading a file via SCP
  • Example#4226 - Uploading a file via SCP
  • Example#4227 - Stating a symbolic link via SFTP
  • Example#4228 - Creating a directory on a remote server
  • Example#4229 - Reading a symbolic link
  • Example#4230 - Resolving a pathname
  • Example#4231 - Renaming a file via sftp
  • Example#4232 - Removing a directory on a remote server
  • Example#4233 - Stating a file via SFTP
  • Example#4234 - Creating a symbolic link
  • Example#4235 - Deleting a file
  • Example#4236 - Opening a file via SFTP
  • Example#4237 - Executing a command
  • Example#4238 - Opening a tunnel to an arbitrary host
  • Example#4239 - Объектно-ориентированный стиль
  • Example#4240 - Процедурный стиль
  • Example#4241 - Пример использования stomp_connect_error
  • Example#4242 - Пример использования stomp_version
  • Example#4243 - Объектно-ориентированный стиль
  • Example#4244 - Процедурный стиль
  • Example#4245 - Объектно-ориентированный стиль
  • Example#4246 - Процедурный стиль
  • Example#4247 - Объектно-ориентированный стиль
  • Example#4248 - Процедурный стиль
  • Example#4249 - Объектно-ориентированный стиль
  • Example#4250 - Процедурный стиль
  • Example#4251 - Объектно-ориентированный стиль
  • Example#4252 - Процедурный стиль
  • Example#4253 - Объектно-ориентированный стиль
  • Example#4254 - Процедурный стиль
  • Example#4255 - Объектно-ориентированный стиль
  • Example#4256 - Процедурный стиль
  • Example#4257 - Объектно-ориентированный стиль
  • Example#4258 - Процедурный стиль
  • Example#4259 - Объектно-ориентированный стиль
  • Example#4260 - Процедурный стиль
  • Example#4261 - Train from array
  • Example#4262 - Train from a file
  • Example#4263 - svn_add example
  • Example#4264 - Простой пример аутентификации
  • Example#4265 - Пример использования функции svn_blame
  • Example#4266 - Простой пример использования функции svn_cat()
  • Example#4267 - Простой пример
  • Example#4268 - Простой пример
  • Example#4269 - Простой пример
  • Example#4270 - Простой пример
  • Example#4271 - Простой пример
  • Example#4272 - Вывод различий между двумя ревизиями одного файла
  • Example#4273 - Более удобный способ вывода различий между двумя файла
  • Example#4274 - Пример использования svn_export
  • Example#4275 - Простой пример
  • Example#4276 - Пример использования svn_log
  • Example#4277 - Пример использования svn_ls
  • Example#4278 - Простой пример
  • Example#4279 - Базовый пример
  • Example#4280 - Deny all connections from localhost
  • Example#4281 - Ban an URL
  • Example#4282 - Get statistic snapshot
  • Example#4283 - Read varnish shared memory log
  • Example#4284 - VarnishAdmin::__construct example
  • Example#4285 - Parallel searching using Yaz
  • Example#4286 - Найстройка CCL
  • Example#4287 - CCL Parsing
  • Example#4288 - Record Update
  • Example#4289 - Array for GRS-1 record
  • Example#4290 - Working with MARCXML
  • Example#4291 - PHP function that scans titles
  • Example#4292 - Query Examples
  • Example#4293 - Критерии сортировки
  • Example#4294 - Example for NIS errors
  • Example#4295 - Example for the NIS first
  • Example#4296 - Example for the default domain
  • Example#4297 - Example for the NIS master
  • Example#4298 - Example for NIS match
  • Example#4299 - Example for NIS next
  • Example#4300 - Example for the NIS order
  • Example#4301 -
  • Example#4302 - Пример использования udm_api_version
  • Example#4303 - udm_cat_listexample
  • Example#4304 - Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
  • Example#4305 - Пример использования udm_load_ispell_data
  • Example#4306 - Пример использования udm_load_ispell_data
  • Example#4307 - Пример использования solr_get_version
  • Example#4308 - Contents of the BootStrap file
  • Example#4309 - Adding a document to the index
  • Example#4310 - Merging one document into another document
  • Example#4311 - Searching for documents - SolrObject responses
  • Example#4312 - Searching for documents - SolrDocument responses
  • Example#4313 - Simple TermsComponent example - basic
  • Example#4314 - Simple TermsComponent example - using a prefix
  • Example#4315 - Simple TermsComponent example - specifying a minimum frequency
  • Example#4316 - Simple Facet Example
  • Example#4317 - Simple Facet Example - with optional field override for mincount
  • Example#4318 - Connecting to SSL-Enabled Server
  • Example#4319 - SolrDocument::toArray example
  • Example#4320 - SolrObject::__construct example
  • Example#4321 - SolrObject::offsetUnset example
  • Example#4322 - SolrClient::addDocument example
  • Example#4323 - SolrClient::addDocuments example
  • Example#4324 - SolrClient::__construct example
  • Example#4325 - SolrQuery::deleteByQuery example
  • Example#4326 - SolrClient::ping example
  • Example#4327 - SolrClient::query example
  • Example#4328 - SolrClient::request example
  • Example#4329 - SolrClient::setResponseWriter example
  • Example#4330 - SolrParams::setParam example
  • Example#4331 - SolrQuery::addFacetField example
  • Example#4332 - SolrQuery::addFilterQuery example
  • Example#4333 - Примеры использования
  • Example#4334 - Basic search query
  • Example#4335 - A Swish::__construct example
  • Example#4336 - Basic Swish::getMetaList example
  • Example#4337 - Basic Swish::getPropertyList example
  • Example#4338 - Basic Swish::prepare example
  • Example#4339 - Basic Swish::query example
  • Example#4340 - Basic SwishResult::stem example
  • Example#4341 - Basic SwishResults::getParsedWords example
  • Example#4342 - Basic SwishResults::nextResult example
  • Example#4343 - Basic SwishResults::seekResult example
  • Example#4344 - Basic SwishSearch::execute example
  • Example#4345 - Basic SwishSearch::resetLimit example
  • Example#4346 - Basic SwishSearch::setLimit example
  • Example#4347 - Basic SwishSearch::setPhraseDelimiter example
  • Example#4348 - Basic SwishSearch::setSort example
  • Example#4349 - Basic SwishSearch::setStructure example
  • Example#4350 - Отключение парсера PHP для директории при помощи .htaccess
  • Example#4351 - Пример использования apache_get_modules
  • Example#4352 - Пример apache_get_version
  • Example#4353 - Пример использования apache_getenv
  • Example#4354 - Пример использования apache_lookup_uri
  • Example#4355 - Пример передачи информации между PHP и Perl
  • Example#4356 - Пример записи значений в access.log
  • Example#4357 - Пример использования apache_request_headers
  • Example#4358 - Пример использования apache_response_headers
  • Example#4359 - Пример использования apache_setenv для установки переменной окружения Apache.
  • Example#4360 - Пример использования getallheaders
  • Example#4361 - nsapi_request_headers example
  • Example#4362 - Регистрация переменной с помощью $_SESSION.
  • Example#4363 - Отмена объявления переменной с помощью $_SESSION.
  • Example#4364 - Подсчет количества посещений конкретного пользователя
  • Example#4365 - Пример
  • Example#4366 - session_cache_expire example
  • Example#4367 - session_cache_limiter example
  • Example#4368 - Destroying a session with $_SESSION
  • Example#4369 - session_name example
  • Example#4370 - A session_regenerate_id example
  • Example#4371 - Custom session handler: see full code in SessionHandlerInterface synposis.
  • Example#4372 - Custom session save handler using objects
  • Example#4373 - A session example: page1.php
  • Example#4374 - A session example: page2.php
  • Example#4375 - Using SessionHandler to add encryption to internal PHP save handlers.
  • Example#4376 - Example using SessionHandlerInterface
  • Example#4377 - Пример использования bbcode_add_smiley
  • Example#4378 - bbcode_create example
  • Example#4379 - Пример использования bbcode_set_arg_parser
  • Example#4380 - Пример использования bbcode_set_flags
  • Example#4381 - Примеры правильных шаблонов
  • Example#4382 - Примеры неправильных шаблонов
  • Example#4383 - Пример для сравнения функций preg_filter и preg_replace
  • Example#4384 - Пример использования preg_grep
  • Example#4385 - Пример использования preg_last_error
  • Example#4386 - Получение всех телефонных номеров из текста.
  • Example#4387 - Жадный поиск совпадений с HTML-тэгами
  • Example#4388 - Использование именованных подмасок
  • Example#4389 - Поиск подстроки "php" в тексте
  • Example#4390 - Поиск слова "web" в тексте
  • Example#4391 - Извлечение доменного имени из URL
  • Example#4392 - Использование именованных подмасок
  • Example#4393 - preg_quote пример
  • Example#4394 - Выделение курсивом слова в тексте
  • Example#4395 - preg_replace_callback и create_function
  • Example#4396 - Пример использования preg_replace_callback
  • Example#4397 - Рекурсивная обработка BB-кодов с помощью preg_replace_callback
  • Example#4398 - Использование подмасок, за которыми следует цифра
  • Example#4399 - Использование массивов с числовыми индексами в качестве аргументов функции preg_replace
  • Example#4400 - Замена по нескольким шаблонам
  • Example#4401 - Чистка пробелов
  • Example#4402 - Использование параметра count
  • Example#4403 - preg_split пример: Получение подстрок из заданного текста
  • Example#4404 - Разбиваем строку на составляющие символы
  • Example#4405 - Разбиваем строку с указанием смещения для каждой из найденных подстрок
  • Example#4406 - Примеры регулярных выражений
  • Example#4407 - Пример использования ereg_replace
  • Example#4408 - Пример использования ereg_replace
  • Example#4409 - Замена URL-адресов на ссылки
  • Example#4410 - Пример использования ereg
  • Example#4411 - Выделение результатов поиска
  • Example#4412 - Пример использования eregi
  • Example#4413 - Пример использования split
  • Example#4414 - Пример использования split
  • Example#4415 - Пример spliti
  • Example#4416 - Пример функции sql_regcase
  • Example#4417 - addcslashes example
  • Example#4418 - Пример использования addslashes
  • Example#4419 - Пример использования chr
  • Example#4420 - Пример использования chunk_split
  • Example#4421 - Пример использования convert_uudecode
  • Example#4422 - Пример использования convert_uuencode
  • Example#4423 - Пример использования count_chars
  • Example#4424 - Вывод контрольной суммы CRC32
  • Example#4425 - Пример использования crypt
  • Example#4426 - Использование crypt и htpasswd
  • Example#4427 - Использование crypt с различными видами хэшей
  • Example#4428 - Примеры использования echo
  • Example#4429 - Пример использования explode
  • Example#4430 - Примеры с использованием параметра limit
  • Example#4431 - fprintf: заполнение нулями
  • Example#4432 - fprintf: форматирование денежных величин
  • Example#4433 - Пример таблицы преобразований
  • Example#4434 - Пример использования hex2bin
  • Example#4435 - Декодирование HTML-сущностей
  • Example#4436 - Пример использования htmlentities
  • Example#4437 - Использование ENT_IGNORE
  • Example#4438 - Пример использования функции htmlspecialchars_decode
  • Example#4439 - Пример использования htmlspecialchars
  • Example#4440 - Пример использования implode
  • Example#4441 - Пример использования lcfirst
  • Example#4442 - Пример использования levenshtein
  • Example#4443 - Пример использования localeconv
  • Example#4444 - Пример использования ltrim
  • Example#4445 - Пример использования md5_file
  • Example#4446 - Пример использования md5
  • Example#4447 - Простой пример использования metaphone
  • Example#4448 - Использование параметра phonemes
  • Example#4449 - Пример использования money_format
  • Example#4450 - Пример использования nl2br
  • Example#4451 - Генерирование корректной HTML-верстки с помощью параметра is_xhtml
  • Example#4452 - Различные разделители строк
  • Example#4453 - Пример использования number_format
  • Example#4454 - Пример использования ord
  • Example#4455 - Использование parse_str
  • Example#4456 - Примеры использования print
  • Example#4457 - Пример использования rtrim
  • Example#4458 - Примеры использования setlocale
  • Example#4459 - Примеры использования setlocale в Windows
  • Example#4460 - Пример использования sha1_file
  • Example#4461 - Пример использования sha1
  • Example#4462 - Примеры soundex
  • Example#4463 - Изменение порядка параметров
  • Example#4464 - Изменение порядка параметров
  • Example#4465 - Изменение порядка параметров
  • Example#4466 - Изменение порядка параметров
  • Example#4467 - Использование описателя позиции и совместо с другими описателями
  • Example#4468 - sprintf: заполнение нулями
  • Example#4469 - printf: описатели строк
  • Example#4470 - sprintf: целые числа, дополненные нулями
  • Example#4471 - sprintf: форматирование денежных величин
  • Example#4472 - sprintf: научная нотация
  • Example#4473 - Пример использования sscanf
  • Example#4474 - sscanf - использование необязательных аргументов
  • Example#4475 - Пример использования str_ireplace
  • Example#4476 - Пример использования str_pad
  • Example#4477 - Пример использования str_repeat
  • Example#4478 - Примеры использования str_replace
  • Example#4479 - Примеры потенциальных трюков с str_replace
  • Example#4480 - Пример использования str_rot13
  • Example#4481 - Пример использования str_shuffle
  • Example#4482 - Пример использования str_split
  • Example#4483 - Пример использования str_word_count
  • Example#4484 - Пример использования strcasecmp
  • Example#4485 - Пример использования strcspn
  • Example#4486 - Пример использования strip_tags
  • Example#4487 - Пример использования stripos
  • Example#4488 - Пример использования stripslashes
  • Example#4489 - Использование stripslashes с массивом
  • Example#4490 - Пример использования stristr
  • Example#4491 - Проверка на вхождение строки
  • Example#4492 - Использование "нестроки" в поиске
  • Example#4493 - Пример использования strlen
  • Example#4494 - Пример использования strpbrk
  • Example#4495 - Использование ===
  • Example#4496 - Использование !==
  • Example#4497 - Использование смещения
  • Example#4498 - Пример использования strrchr
  • Example#4499 - Пример использования strrev
  • Example#4500 - Пример использования strripos
  • Example#4501 - Проверка существования искомой строки
  • Example#4502 - Поиск со смещением
  • Example#4503 - Пример использования strspn
  • Example#4504 - Пример использования strstr
  • Example#4505 - Пример использования strtok
  • Example#4506 - Старый способ обработки пустых подстрок функцией strtok
  • Example#4507 - Новый способ обработки пустых подстрок функцией strtok
  • Example#4508 - Пример использования strtolower
  • Example#4509 - Пример использования strtoupper
  • Example#4510 - Пример использования strtr
  • Example#4511 - Пример использования strtr с двумя аргументами
  • Example#4512 - Сравнение поведения функции strtr
  • Example#4513 - Пример использования substr_compare
  • Example#4514 - Пример использования substr_count
  • Example#4515 - Простой пример использования substr_replace
  • Example#4516 - Использование substr_replace для одновременной множественной замены строк
  • Example#4517 - Использование отрицательного параметра start
  • Example#4518 - Использование отрицательного параметра length
  • Example#4519 - Базовое использование substr
  • Example#4520 - substr и приведение типов
  • Example#4521 -
  • Example#4522 - Пример использования trim
  • Example#4523 - Обрезание значений массива с помощью trim
  • Example#4524 - Пример использования ucfirst
  • Example#4525 - Пример использования ucwords
  • Example#4526 - vfprintf: дополнение нулями целых чисел
  • Example#4527 - vprintf: дополнение нулями целых чисел
  • Example#4528 - vsprintf: дополнение нулями целых чисел
  • Example#4529 - Пример использования wordwrap
  • Example#4530 - Пример использования wordwrap
  • Example#4531 - Пример использования array_change_key_case
  • Example#4532 - Пример использования array_chunk
  • Example#4533 - Простой пример использования array_combine
  • Example#4534 - Пример использования array_count_values
  • Example#4535 - Пример использования array_diff_assoc
  • Example#4536 - Пример array_diff_assoc
  • Example#4537 - Пример использования array_diff_key
  • Example#4538 - Пример использования array_diff_uassoc
  • Example#4539 - Пример использования array_diff_ukey
  • Example#4540 - Пример использования array_diff
  • Example#4541 - Пример использования array_fill_keys
  • Example#4542 - Пример использования array_fill
  • Example#4543 - Пример использования array_filter
  • Example#4544 - Использование array_filter без callback-функции
  • Example#4545 - Пример использования array_flip
  • Example#4546 - Пример использования array_flip с коллизиями
  • Example#4547 - Пример использования array_intersect_assoc
  • Example#4548 - Пример использования array_intersect_key
  • Example#4549 - Пример использования array_intersect_uassoc
  • Example#4550 - Пример использования array_intersect_ukey
  • Example#4551 - Пример использования array_intersect
  • Example#4552 - Пример использования array_key_exists
  • Example#4553 - array_key_exists и isset
  • Example#4554 - Пример использования array_keys
  • Example#4555 - Пример использования array_map
  • Example#4556 - Использование array_map вместе с lambda-функцией (начиная с версии PHP 5.3.0)
  • Example#4557 - Пример использования array_map: обработка нескольких массивов
  • Example#4558 - Создание массива массивов
  • Example#4559 - Использование array_map со строковыми ключами
  • Example#4560 - Пример использования array_merge_recursive
  • Example#4561 - Пример использования array_merge в PHP 5
  • Example#4562 - Пример использования array_merge
  • Example#4563 - Простой пример использования array_merge
  • Example#4564 - Сортировка нескольких массивов
  • Example#4565 - Сортировка многомерного массива
  • Example#4566 - Сортировка результатов из базы данных
  • Example#4567 - Сортировка без учета регистра
  • Example#4568 - Пример использования array_pad
  • Example#4569 - Пример использованияarray_pop
  • Example#4570 - Примеры использования array_product
  • Example#4571 - Пример использования array_push
  • Example#4572 - Пример использования array_rand
  • Example#4573 - Пример использованияarray_reduce
  • Example#4574 - Пример использования array_replace_recursive
  • Example#4575 - array_replace_recursive and recursive behavior
  • Example#4576 - Пример использования array_replace
  • Example#4577 - Пример использования array_reverse
  • Example#4578 - Пример использования array_search
  • Example#4579 - Пример использования array_shift
  • Example#4580 - Пример использования array_slice
  • Example#4581 - Примеры использования array_splice
  • Example#4582 - array_splice examples
  • Example#4583 - Пример использования array_sum
  • Example#4584 - Пример использования array_udiff_assoc
  • Example#4585 - Пример использованияarray_udiff_uassoc
  • Example#4586 - Пример использования array_udiff
  • Example#4587 - Пример использования array_uintersect_assoc
  • Example#4588 - Пример использования array_uintersect_uassoc
  • Example#4589 - Пример использования array_uintersect
  • Example#4590 - Пример использования array_unique
  • Example#4591 - array_unique и типы:
  • Example#4592 - Пример использования array_unshift
  • Example#4593 - Пример использования array_values
  • Example#4594 - Пример использования array_walk_recursive
  • Example#4595 - Пример использования array_walk
  • Example#4596 - Пример использования array
  • Example#4597 - Автоматическая индексация с помощью array
  • Example#4598 - array, нумерация которого начинаяется с 1
  • Example#4599 - Доступ к массиву внутри двойных кавычек
  • Example#4600 - Пример использования arsort
  • Example#4601 - Пример использования asort
  • Example#4602 - Пример использования compact
  • Example#4603 - Пример использования count
  • Example#4604 - Пример рекурсивного использования count
  • Example#4605 - Пример использования current и дружественных функций
  • Example#4606 - Примеры использования each
  • Example#4607 - Обход массива функцией each
  • Example#4608 - Пример использования end
  • Example#4609 - Пример использования extract
  • Example#4610 - Пример использования in_array
  • Example#4611 - Пример использования in_array с параметром strict
  • Example#4612 - Пример использования in_array с массивом в качестве параметра needle
  • Example#4613 - Пример использования key
  • Example#4614 - Пример использования krsort
  • Example#4615 - Пример использования ksort
  • Example#4616 - Примеры использования list
  • Example#4617 - Пример использования list
  • Example#4618 - Использование list с индексами массивов
  • Example#4619 - Использование list с индексами массива
  • Example#4620 - Пример использования natcasesort
  • Example#4621 - Простой пример использования natsort
  • Example#4622 - Примеры использования различных трюков с natsort
  • Example#4623 - Пример использования next и друзей
  • Example#4624 - Пример использования prev и друзей
  • Example#4625 - Примеры использования range
  • Example#4626 - Пример использования reset
  • Example#4627 - Пример использования rsort
  • Example#4628 - Пример использования shuffle
  • Example#4629 - Пример использования sort
  • Example#4630 - Пример использования sort с регистронезависимым естественным упорядочением
  • Example#4631 - Простой пример использования uasort
  • Example#4632 - Пример использования uksort
  • Example#4633 - Пример использования usort
  • Example#4634 - Пример использования функции usort с многомерными массивами
  • Example#4635 - Пример использования usort с методом класса
  • Example#4636 - Пример использования функции usort с применением анонимной функции для сортировки многомерного массива
  • Example#4637 - classes.inc
  • Example#4638 - test_script.php
  • Example#4639 - Альтернатива call_user_method_array
  • Example#4640 - Альтернатива call_user_method
  • Example#4641 - Пример использования class_alias
  • Example#4642 - Пример использования class_exists
  • Example#4643 - Пример использования параметра autoload
  • Example#4644 - Пример использования get_called_class
  • Example#4645 - Пример использования get_class_methods
  • Example#4646 - Пример использования get_class_vars
  • Example#4647 - get_class_vars и поведение области видимости
  • Example#4648 - Использование get_class
  • Example#4649 - Использование get_class в родительском классе
  • Example#4650 - Пример использования get_declared_classes
  • Example#4651 - Пример использования get_declared_interfaces
  • Example#4652 - Пример использования get_object_vars
  • Example#4653 - Пример использования get_parent_class
  • Example#4654 - Пример использования interface_exists
  • Example#4655 - Пример использования is_a
  • Example#4656 - Использование оператора instanceof в PHP 5
  • Example#4657 - Пример использования is_subclass_of
  • Example#4658 - Пример использования method_exists
  • Example#4659 - Пример статического использования method_exists
  • Example#4660 - Пример использования property_exists
  • Example#4661 - Пример использования classkit_import
  • Example#4662 - Пример использования classkit_method_add
  • Example#4663 - Пример использования classkit_method_copy
  • Example#4664 - Пример использования classkit_method_redefine
  • Example#4665 - Пример использования classkit_method_remove
  • Example#4666 - Пример использования classkit_method_rename
  • Example#4667 - Пример использования ctype_alnum (с использованием локали по умолчанию)
  • Example#4668 - Пример использования ctype_alpha (с использованием локали по умолчанию)
  • Example#4669 - Пример использования ctype_cntrl
  • Example#4670 - Пример использования ctype_digit
  • Example#4671 - Пример использования ctype_digit со сравнением строк и целых чисел
  • Example#4672 - Пример использования ctype_graph
  • Example#4673 - Пример использования ctype_lower (с использованием локали по умолчанию)
  • Example#4674 - Пример использования ctype_print
  • Example#4675 - Пример использования ctype_punct
  • Example#4676 - Пример использования ctype_space
  • Example#4677 - Пример использования ctype_upper (с использованием локали по умолчанию)
  • Example#4678 - Пример использования ctype_xdigit
  • Example#4679 - Настройка фильтра по умолчанию для работы аналогично функции htmlspecialchars
  • Example#4680 - Настройка фильтра по умолчанию для работы аналогично функции htmlspecialchars
  • Example#4681 - Валидация e-mail адреса, используя функцию filter_var
  • Example#4682 - Валидация IP адреса, используя функцию filter_var
  • Example#4683 - Дополнительные параметры функции filter_var
  • Example#4684 - Нормализация и валидация e-mail адресов
  • Example#4685 - Настройка фильтра по умолчанию
  • Example#4686 - Пример использования filter_input_array
  • Example#4687 - Пример использования filter_input
  • Example#4688 - Пример использования filter_list
  • Example#4689 - Пример использования filter_var_array
  • Example#4690 - Пример использования filter_var
  • Example#4691 - Использование call_user_func_array
  • Example#4692 - Пример использования call_user_func_array и имени из пространства имен
  • Example#4693 - Использование lambda-функции
  • Example#4694 - Пример использования call_user_func с ссылками
  • Example#4695 - Пример использования call_user_func
  • Example#4696 - Использование call_user_func и пространства имен
  • Example#4697 - Вызов метода класса из call_user_func
  • Example#4698 - Использование лямбда-функции и call_user_func
  • Example#4699 - Создание анонимной функции с помощью create_function
  • Example#4700 - Создание функции-обработчика с помощью create_function
  • Example#4701 - Использование анонимной функции как функции-обработчика
  • Example#4702 - forward_static_call_array example
  • Example#4703 - forward_static_call example
  • Example#4704 - Пример использования func_get_arg
  • Example#4705 - Использование func_get_arg до и после PHP 5.3
  • Example#4706 - Пример передачи аргументов по ссылке и по значению с func_get_arg
  • Example#4707 - Пример использования func_get_args
  • Example#4708 - Использование func_get_args до и после PHP 5.3
  • Example#4709 - Пример передачи аргументов по ссылке и по значению с func_get_args
  • Example#4710 - Пример использования func_num_args
  • Example#4711 - Использование func_num_args до и после PHP 5.3
  • Example#4712 - Пример использования function_exists
  • Example#4713 - Пример использования get_defined_functions
  • Example#4714 - Пример использования register_shutdown_function
  • Example#4715 - Пример использования register_tick_function
  • Example#4716 - Class association
  • Example#4717 - Object association
  • Example#4718 - storage_classes.inc
  • Example#4719 - test_aggregation.php
  • Example#4720 - Using aggregate_info
  • Example#4721 - Quickhash Example
  • Example#4722 - Quickhash ArrayAccess Example
  • Example#4723 - Quickhash Iterator Example
  • Example#4724 - Quickhash String Values Example
  • Example#4725 - QuickHashIntSet::add example
  • Example#4726 - QuickHashIntSet::__construct example
  • Example#4727 - QuickHashIntSet::delete example
  • Example#4728 - QuickHashIntSet::exists example
  • Example#4729 - QuickHashIntSet::getSize example
  • Example#4730 - QuickHashIntSet::loadFromFile example
  • Example#4731 - QuickHashIntSet::loadFromString example
  • Example#4732 - QuickHashIntSet::saveToFile example
  • Example#4733 - QuickHashIntSet::saveToString example
  • Example#4734 - QuickHashIntHash::add example
  • Example#4735 - QuickHashIntHash::__construct example
  • Example#4736 - QuickHashIntHash::delete example
  • Example#4737 - QuickHashIntHash::exists example
  • Example#4738 - QuickHashIntHash::get example
  • Example#4739 - QuickHashIntHash::getSize example
  • Example#4740 - QuickHash IntHash file format
  • Example#4741 - QuickHash IntHash file format
  • Example#4742 - QuickHashIntHash::loadFromFile example
  • Example#4743 - QuickHashIntHash::loadFromString example
  • Example#4744 - QuickHashIntHash::saveToFile example
  • Example#4745 - QuickHashIntHash::saveToString example
  • Example#4746 - QuickHashIntHash::set example
  • Example#4747 - QuickHashIntHash::update example
  • Example#4748 - QuickHashStringIntHash::add example
  • Example#4749 - QuickHashStringIntHash::__construct example
  • Example#4750 - QuickHashStringIntHash::delete example
  • Example#4751 - QuickHashStringIntHash::get example
  • Example#4752 - QuickHashStringIntHash::getSize example
  • Example#4753 - QuickHash StringIntHash file format
  • Example#4754 - QuickHash IntHash file format
  • Example#4755 - QuickHashStringIntHash::loadFromFile example
  • Example#4756 - QuickHashStringIntHash::loadFromString example
  • Example#4757 - QuickHashStringIntHash::saveToFile example
  • Example#4758 - QuickHashStringIntHash::saveToString example
  • Example#4759 - QuickHashStringIntHash::set example
  • Example#4760 - QuickHashStringIntHash::update example
  • Example#4761 - QuickHashIntStringHash::add example
  • Example#4762 - QuickHashIntStringHash::__construct example
  • Example#4763 - QuickHashIntStringHash::delete example
  • Example#4764 - QuickHashIntStringHash::get example
  • Example#4765 - QuickHashIntStringHash::getSize example
  • Example#4766 - QuickHash IntString file format
  • Example#4767 - QuickHash IntString file format
  • Example#4768 - QuickHashIntStringHash::loadFromFile example
  • Example#4769 - QuickHashIntStringHash::loadFromString example
  • Example#4770 - QuickHashIntStringHash::saveToFile example
  • Example#4771 - QuickHashIntStringHash::saveToString example
  • Example#4772 - QuickHashIntStringHash::set example
  • Example#4773 - QuickHashIntStringHash::update example
  • Example#4774 - Пример использования Reflection из shell (Терминала)
  • Example#4775 - Расширение встроенных классов
  • Example#4776 - Простой пример использования ReflectionClass
  • Example#4777 - Пример использования ReflectionClass::getDefaultProperties
  • Example#4778 - Пример использования ReflectionClass::getDocComment
  • Example#4779 - Пример использования ReflectionClass::getEndLine
  • Example#4780 - Пример использования ReflectionClass::getInterfaceNames
  • Example#4781 - Пример использования ReflectionClass::getInterfaces
  • Example#4782 - Пример использования ReflectionClass::getName
  • Example#4783 - Пример использования ReflectionClass::getNamespaceName
  • Example#4784 - Пример фильтрации с помощью ReflectionClass::getProperties
  • Example#4785 - Пример использования ReflectionClass::getShortName
  • Example#4786 - Пример использования ReflectionClass::hasConstant
  • Example#4787 - Пример использования ReflectionClass::hasMethod
  • Example#4788 - Пример использования ReflectionClass::hasProperty
  • Example#4789 - Пример использования ReflectionClass::inNamespace
  • Example#4790 - Пример использования ReflectionClass::isAbstract
  • Example#4791 - Пример использования ReflectionClass::isAbstract
  • Example#4792 - Пример использования ReflectionClass::isInstance и его аналогов
  • Example#4793 - Пример использования ReflectionClass::isInstantiable
  • Example#4794 - Пример использования ReflectionClass::isIterateable
  • Example#4795 - Пример использования ReflectionClass::__toString
  • Example#4796 - Пример использования ReflectionExtension
  • Example#4797 - Пример использования ReflectionExtension::getClasses
  • Example#4798 - Пример использования ReflectionExtension::getClassNames
  • Example#4799 - Пример использования ReflectionExtension::getConstants
  • Example#4800 - Пример использования ReflectionExtension::getDependencies
  • Example#4801 - Пример использования ReflectionExtension::getFunctions
  • Example#4802 - Пример использования ReflectionExtension::getINIEntries
  • Example#4803 - Пример использования ReflectionExtension::getName
  • Example#4804 - Пример использования ReflectionExtension::getVersion
  • Example#4805 - Пример использования ReflectionExtension::info
  • Example#4806 - Пример использования ReflectionFunction::__construct
  • Example#4807 - Пример использования ReflectionFunction::invoke
  • Example#4808 - Пример использования ReflectionFunction::invokeArgs
  • Example#4809 - Пример использования ReflectionFunction::invokeArgs со ссылками на аргументы
  • Example#4810 - Пример использования ReflectionFunction::__toString
  • Example#4811 - Пример использования ReflectionFunctionAbstract::isDeprecated
  • Example#4812 - Пример использования ReflectionMethod::__construct
  • Example#4813 - Пример использования ReflectionMethod::getDeclaringClass
  • Example#4814 - Пример использования ReflectionMethod::getModifiers
  • Example#4815 - Пример использования ReflectionMethod::getPrototype
  • Example#4816 - Пример использования ReflectionMethod::invoke
  • Example#4817 - Пример использования ReflectionMethod::invokeArgs
  • Example#4818 - Пример использования ReflectionMethod::__toString
  • Example#4819 - Использования класса ReflectionParameter
  • Example#4820 - Получение
  • Example#4821 - Пример использования ReflectionProperty::__construct
  • Example#4822 - Получение значений защищенных и частных свойств, используя класс ReflectionProperty
  • Example#4823 - Пример использования ReflectionProperty::getValue
  • Example#4824 - Пример использования ReflectionProperty::setValue
  • Example#4825 - Пример использования debug_zval_dump
  • Example#4826 -
  • Example#4827 -
  • Example#4828 - Простое сравнение empty и isset.
  • Example#4829 - empty и строковые индексы
  • Example#4830 - Пример использования floatval
  • Example#4831 - Пример использования get_defined_vars
  • Example#4832 - Пример использования get_resource_type
  • Example#4833 - Пример использования gettype
  • Example#4834 - Пример использования import_request_variables
  • Example#4835 - Примеры использования intval
  • Example#4836 - Проверяет, является ли переменная массивом
  • Example#4837 - Пример использования is_bool
  • Example#4838 - Пример использования is_callable
  • Example#4839 - Пример использования is_float
  • Example#4840 - Пример использования is_int
  • Example#4841 - Пример использования is_null
  • Example#4842 - Примеры использованияis_numeric
  • Example#4843 - Пример использования is_object
  • Example#4844 - Пример использования is_resource
  • Example#4845 - Пример использования is_scalar
  • Example#4846 - Пример использования is_string
  • Example#4847 - Пример использования isset
  • Example#4848 - isset и строковые индексы
  • Example#4849 - Пример использования print_r
  • Example#4850 - Пример использования параметра return
  • Example#4851 - Пример использования serialize
  • Example#4852 - Пример использования settype
  • Example#4853 - Пример использования strval с магическим методом PHP 5 __toString().
  • Example#4854 - Пример использования unserialize
  • Example#4855 - Пример использования unserialize_callback_func
  • Example#4856 - Пример использования unset
  • Example#4857 - Использование приведения типа (unset)
  • Example#4858 - Пример использования var_dump
  • Example#4859 - Примеры использования var_export
  • Example#4860 - Экспорт классов в PHP с версии 5.1.0
  • Example#4861 - Использование __set_state() (в PHP с версии 5.1.0)
  • Example#4862 -
  • Example#4863 - OAuth::fetch example
  • Example#4864 - OAuth::getAccessToken example
  • Example#4865 - OAuth::getRequestToken example
  • Example#4866 - OAuth::setRequestEngine example
  • Example#4867 - An OAuth::setRsaCertificate example
  • Example#4868 - OAuth::setToken example
  • Example#4869 - OAuthProvider::__construct example
  • Example#4870 - Example OAuthProvider::consumerHandler callback
  • Example#4871 - OAuthProvider::generateToken example
  • Example#4872 - OAuthProvider::is2LeggedEndpoint example
  • Example#4873 - Example OAuthProvider::timestampNonceHandler callback
  • Example#4874 - Example OAuthProvider::tokenHandler callback
  • Example#4875 - A sample SCA component
  • Example#4876 - The structure of an SCA for PHP component
  • Example#4877 - Obtaining a proxy for a local PHP class
  • Example#4878 - Obtaining a proxy for a web service
  • Example#4879 - Calling services
  • Example#4880 - Obtaining a proxy using getService
  • Example#4881 - Making calls on the proxy
  • Example#4882 - StockQuote Service
  • Example#4883 - Generated WSDL
  • Example#4884 - Generated WSDL
  • Example#4885 - location attribute
  • Example#4886 - method with two arguments
  • Example#4887 - types section illustrating named parameters
  • Example#4888 - A Component that uses Data Structures
  • Example#4889 - An SCA::getService example
  • Example#4890 - is_soap_fault example
  • Example#4891 - SOAP's standard method for error reporting is exceptions
  • Example#4892 - Пример использования SoapClient::__doRequest
  • Example#4893 - Пример использования SoapClient::__getFunctions
  • Example#4894 - Пример использования SoapClient::__getLastRequest()
  • Example#4895 - Пример использования SoapClient::__getLastRequest()
  • Example#4896 - Пример использования SoapClient::__getLastResponse()
  • Example#4897 - Пример использования SoapClient::__getLastResponse()
  • Example#4898 - Пример использования SoapClient::__getTypes
  • Example#4899 - Пример использования SoapClient::__setLocation
  • Example#4900 - Пример использования SoapClient::__setSoapHeaders
  • Example#4901 - Установка нескольких заголовков
  • Example#4902 - Пример использования SoapClient::__soapCall
  • Example#4903 - Пример использования SoapClient::SoapClient
  • Example#4904 - SoapServer::addFunction example
  • Example#4905 - SoapServer::getFunctions example
  • Example#4906 - SoapServer::handle example
  • Example#4907 - SoapServer::setPersistence example
  • Example#4908 - SoapServer::SoapServer example
  • Example#4909 - Some examples
  • Example#4910 - Some examples
  • Example#4911 - SoapHeader::SoapHeader example
  • Example#4912 - SoapParam::SoapParam example
  • Example#4913 - SoapVar::SoapVar example
  • Example#4914 - Пример клиентской функции XMLRPC
  • Example#4915 - Пример XML-RPC типа
  • Example#4916 - Пример использования xmlrpc_set_type
  • Example#4917 - For Each in ASP
  • Example#4918 - while() ... Next() in PHP 4
  • Example#4919 - foreach in PHP 5
  • Example#4920 - COM example (1)
  • Example#4921 - COM example (2)
  • Example#4922 - DOTNET example
  • Example#4923 - Variant example, PHP 4.x style
  • Example#4924 - Variant example, PHP 5 style
  • Example#4925 - COM event sink example
  • Example#4926 - OO syntax
  • Example#4927 - Don't use com_invoke(), use OO syntax instead
  • Example#4928 - OO syntax
  • Example#4929 - OO syntax
  • Example#4930 - Пример printer_abort
  • Example#4931 - Пример printer_close
  • Example#4932 - Пример printer_create_dc
  • Example#4933 - Пример printer_draw_bmp
  • Example#4934 - Пример использования printer_draw_chord
  • Example#4935 - Пример printer_draw_elipse
  • Example#4936 - Пример printer_draw_line
  • Example#4937 - Пример printer_draw_pie
  • Example#4938 - Пример printer_draw_rectangle
  • Example#4939 - Пример printer_draw_roundrect
  • Example#4940 - Пример printer_draw_text
  • Example#4941 - Пример printer_get_option
  • Example#4942 - Пример printer_list
  • Example#4943 - Пример printer_logical_fontheight
  • Example#4944 - Пример printer_open
  • Example#4945 - Пример printer_select_brush
  • Example#4946 - Пример printer_select_font
  • Example#4947 - Пример printer_select_pen
  • Example#4948 - Пример printer_set_option
  • Example#4949 - Пример printer_start_doc
  • Example#4950 - Пример printer_write
  • Example#4951 - Получить аптайм и отобразить его в окне сообщения
  • Example#4952 - Статистические данные о текущем процессе PHP
  • Example#4953 - Статистические данные о глобальном использовании памяти
  • Example#4954 - Registering a PHP script to run as a service
  • Example#4955 - Unregistering a service
  • Example#4956 - Running as a service
  • Example#4957 - A win32_create_service example
  • Example#4958 - A win32_delete_service example
  • Example#4959 - Пример win32_start_service_ctrl_dispatcher
  • Example#4960 - Создание нового объекта класса DOMAttr
  • Example#4961 - Пример использования DOMAttr::isId()
  • Example#4962 - Создание объекта класса DOMCdataSection
  • Example#4963 - Создание объекта DOMComment
  • Example#4964 - Создание объекта DOMDocument
  • Example#4965 - Создание нового элемента и вставка его в качестве корневого
  • Example#4966 - Создание элемента и вставка в документ в качестве корневого
  • Example#4967 - Пример префикса пространства имен
  • Example#4968 - Пример использования DOMDocument::getElementById()
  • Example#4969 - Простой пример использования
  • Example#4970 - Получение всех XInclude элементов
  • Example#4971 - Пример использования DOMDocument::importNode
  • Example#4972 - Создание документа
  • Example#4973 - Создание документа
  • Example#4974 - Создание документа
  • Example#4975 - Создание документа
  • Example#4976 - Статический вызов loadXML
  • Example#4977 - Добавление нового метода в класс DOMElement для упрощения кода
  • Example#4978 - Извлечение элементов в виде пользовательского класса
  • Example#4979 - Получение имени документа-владельца узла
  • Example#4980 - Сохранение DOM дерева в файл
  • Example#4981 - Сохранение HTML дерева в виде строки
  • Example#4982 - Сохранение HTML дерева в файл
  • Example#4983 - Сохранение DOM дерева в виде строки
  • Example#4984 - Пример DTD проверки
  • Example#4985 - Пример использования DOMDocument::xinclude()
  • Example#4986 - Добавление XML данных в документ
  • Example#4987 - Создание DOMElement
  • Example#4988 - Установка значения атрибута
  • Example#4989 - Создание нового объекта DOMEntityReference
  • Example#4990 - Создание документа с прикрепленной DTD
  • Example#4991 - Тестирование Вашей реализации DOM
  • Example#4992 - Добавление дочернего узла
  • Example#4993 - Пример использования DOMNode::getLineNo
  • Example#4994 - Пример использования DOMNode::getNodePath
  • Example#4995 - Удаление дочернего узла
  • Example#4996 - Сохраняем URI пространства имен родительского узла
  • Example#4997 - Вывод содержимого таблицы
  • Example#4998 - Создание объекта класса DOMProcessingInstruction
  • Example#4999 - Создание нового узла DOMText
  • Example#5000 - Определение количества всех английских книг
  • Example#5001 - Получение списка всех книг на английском
  • Example#5002 - book.xml
  • Example#5003 - DOMXPath::registerPHPFunctions с php:functionString
  • Example#5004 - DOMXPath::registerPHPFunctions с php:function
  • Example#5005 - Импорт SimpleXML в DOM с помощью функции dom_import_simplexml
  • Example#5006 - Включаемый файл example.inc c XML-строкой
  • Example#5007 - Получение всех атрибутов узла
  • Example#5008 - Создание простого HTML заголовка
  • Example#5009 - Извлечение корневого элемента
  • Example#5010 - Создание простого HTML заголовка
  • Example#5011 - Создание простого HTML заголовка
  • Example#5012 - Создание простого HTML заголовка
  • Example#5013 - Подстановка Xincludes
  • Example#5014 - Получение имени типа документа
  • Example#5015 - Извлечение public id
  • Example#5016 - Извлечение системного идентификатора
  • Example#5017 - Получение имени атрибута
  • Example#5018 - Получение значения атрибута
  • Example#5019 - Получение содержимого
  • Example#5020 - Проверка существования атрибута
  • Example#5021 - Установка значения атрибута
  • Example#5022 - Получение имени узла
  • Example#5023 - Добавление сына
  • Example#5024 - Добавление сына
  • Example#5025 - Добавление сына
  • Example#5026 - Получение содержимого
  • Example#5027 - Добавление сына
  • Example#5028 - Перебор сыновей узла
  • Example#5029 -
  • Example#5030 - Обнаружение документа узла
  • Example#5031 - Обнаружение документа узла
  • Example#5032 - Удаление сына
  • Example#5033 - Сохранение результата XSLT-преобразования в файл
  • Example#5034 - Вывод результата XSLT преобразования
  • Example#5035 - Открытие XML документа из файла
  • Example#5036 - Открытие XML документа из строки
  • Example#5037 - Пример использования domxml_version
  • Example#5038 - Пример использования domxml_xslt_version
  • Example#5039 - Пример использования xpath_eval_expression
  • Example#5040 - Пример использования libxml_get_errors
  • Example#5041 - libxml_set_external_entity_loader example
  • Example#5042 - Пример использования libxml_set_streams_context
  • Example#5043 - Пример использования libxml_use_internal_errors
  • Example#5044 - Access via property name
  • Example#5045 - Access via property name as array index
  • Example#5046 - Data Object iteration
  • Example#5047 - Access many-valued property by name
  • Example#5048 - Many-valued element access
  • Example#5049 - Many-valued property iteration
  • Example#5050 - Chained property access
  • Example#5051 - XPath navigation
  • Example#5052 - XPath querying
  • Example#5053 - Creating child data objects
  • Example#5054 - Unset a primitive property
  • Example#5055 - Unset a data object
  • Example#5056 - Unset a referenced data object
  • Example#5057 - Access via property index
  • Example#5058 - Getting the SDO_Sequence interface
  • Example#5059 - Get/set sequence values
  • Example#5060 - Sequence iteration
  • Example#5061 - Sequence versus Data Object
  • Example#5062 - Adding to a sequence
  • Example#5063 - Removing from a sequence
  • Example#5064 - Reflecting on a Data Object
  • Example#5065 - Accessing the type information
  • Example#5066 - A SDO_DAS_DataFactory::addPropertyToType example
  • Example#5067 - A SDO_DAS_DataFactory::addType example
  • Example#5068 - Creating a data object
  • Example#5069 - Retrieving a data object
  • Example#5070 - Updating a data object
  • Example#5071 - Deleting a data object
  • Example#5072 - One company, one department - Create
  • Example#5073 - One company, one department - Retrieve and Update
  • Example#5074 - One company, two departments - Retrieve and Delete
  • Example#5075 - One company, one department, one employee - Create
  • Example#5076 - One company, one department, one employee - Retrieve and update
  • Example#5077 - One company, two departments, two employees - Retrieve and delete
  • Example#5078 - Retrieving a data object using executePreparedQuery
  • Example#5079 - Loading, altering, and saving an XML document
  • Example#5080 - Creating a new XML document
  • Example#5081 - Setting XML document properties
  • Example#5082 - Using an open type
  • Example#5083 - Finding out what you can from the document
  • Example#5084 - Printing the SDO model
  • Example#5085 - Файл example.php с XML строкой
  • Example#5086 - Получение части документа <plot>
  • Example#5087 - Получение строки <line>
  • Example#5088 - Доступ к не уникальным элементам в SimpleXML
  • Example#5089 - Использование атрибутов
  • Example#5090 - Сравнение элементов и атрибутов с текстом
  • Example#5091 - Сравнение двух элементов
  • Example#5092 - Использование XPath
  • Example#5093 - Установка значений
  • Example#5094 - Добавление элементов и атрибутов
  • Example#5095 - Взаимодействие с DOM
  • Example#5096 - Загрузка синтаксически неправильной XML строки
  • Example#5097 - Добавление атрибутов и потомков к SimpleXML-элементу
  • Example#5098 - Добавление атрибутов и потомков к SimpleXML элементу
  • Example#5099 - Получение XML
  • Example#5100 - Использование asXML() с результатами SimpleXMLElement::xpath
  • Example#5101 - Интерпретация XML строки
  • Example#5102 - Обход псевдо-массива children()
  • Example#5103 - Использование пространства имен
  • Example#5104 - Создание объекта SimpleXMLElement
  • Example#5105 - Создание объекта SimpleXMLElement из URL
  • Example#5106 - Подсчет количества дочерних элементов
  • Example#5107 - Получение пространства имен документа
  • Example#5108 - Работа с несколькими пространствами имен
  • Example#5109 - Получение имен XML элемента
  • Example#5110 - Получение пространств имен, используемых в документе
  • Example#5111 - Установка префикса пространства имен для использования в запросе XPath
  • Example#5112 - Xpath
  • Example#5113 - Возвращение текущего элемента
  • Example#5114 - Возвращает вложенные элементы текущего элемента
  • Example#5115 - Проверяет, имеет ли текущий элемент вложенные элементы
  • Example#5116 - Получает имя текущего XML-тега
  • Example#5117 - Перемещение к следующему элементу
  • Example#5118 - Возврат к первому элементу
  • Example#5119 - Проверяет, является ли текущий элемент допустимым
  • Example#5120 - Импорт DOM
  • Example#5121 - Интерпретация XML-документа
  • Example#5122 - Интерпретация XML-строки
  • Example#5123 - Serializing a single value with WDDX
  • Example#5124 - Using incremental packets with WDDX
  • Example#5125 - wddx_serialize_vars example
  • Example#5126 - Показать структуру элемента XML
  • Example#5127 - Отображение XML в HTML
  • Example#5128 - Пример использования внешней сущности
  • Example#5129 - xmltest.xml
  • Example#5130 - xmltest2.xml
  • Example#5131 - Пример использования xml_parse_into_struct
  • Example#5132 - moldb.xml - небольшая база данных с информацией о молекулах
  • Example#5133 - parsemoldb.php - разбирает moldb.xml и помещает данные в массив молекул
  • Example#5134 - Пример использования xml_set_object
  • Example#5135 - Проверка правильности XML
  • Example#5136 - collection.xml
  • Example#5137 - collection.xsl
  • Example#5138 - Создаёт XSLTProcessor
  • Example#5139 - Проверка поддержки EXSLT
  • Example#5140 - Простой вызов функции PHP из таблицы стилей
  • Example#5141 - Изменение владельца перед преобразованием
  • Example#5142 - Пример вывода профилирующей информации
  • Example#5143 - Преобразование в DOMDocument
  • Example#5144 - Преобразование в HTML файл
  • Example#5145 - Трансформация в строку
  • Example#5146 - Пример использования xslt_backend_name
  • Example#5147 - Пример использования xslt_backend_version
  • Example#5148 - Пример использования xslt_create
  • Example#5149 - Обработка ошибок с использованием функций xslt_error и xslt_errno.
  • Example#5150 - Использование функции xslt_process для преобразования XML и XSL файлов в новый XML файл
  • Example#5151 - Использование функции xslt_process для преобразования XML и XSL файлов в переменную, содержащую результирующие XML данные
  • Example#5152 - Использование функции xslt_process для преобразования XML и XSL данных, содержащихся в переменных и сохранения результата в другую переменную с XML кодом.
  • Example#5153 - Передача PHP переменных в XSL файлы
  • Example#5154 - Пример использования xslt_set_error_handler
  • Example#5155 - Использование возможностей протоколирования XSLT
  • Example#5156 - Использование собственного обработчика ошибок в качестве метода
  • Example#5157 - Пример использования xslt_set_sax_handlers
  • Example#5158 - Обработчик в объектно-ориентированном стиле
  • Example#5159 - Пример использования xslt_set_scheme_handlers
  • Example#5160 - Пример использования xslt_setopt
  • Example#5161 - "counter"'s basic interface
  • Example#5162 - "counter"'s extended interface
  • Example#5163 - "counter"'s objective interface
  • Example#5164 - An example config.m4 file
  • Example#5165 - Sample configure output
  • Example#5166 - counter's config.m4 file
  • Example#5167 - An example config.w32 file
  • Example#5168 - counter's config.w32 file
  • Example#5169 - Files in the counter extension, in no particular order
  • Example#5170 - zend_module declaration in the counter extension
  • Example#5171 - zend_module definition in PHP 5.3
  • Example#5172 - Counter extension module definition
  • Example#5173 - The wrong way to store the basic counter interface's value
  • Example#5174 - The counter module's globals
  • Example#5175 - The counter module's global structure declaration
  • Example#5176 - Accessor macros for per-module globals
  • Example#5177 - The right way to store the basic counter interface's value
  • Example#5178 - counter's PHP_MINFO function
  • Example#5179 - PHP's leak warnings
  • Example#5180 - Minimal PHP extension with one function
  • Example#5181 - A simple function
  • Example#5182 - Example macros for invoking pdo_SKEL_error
  • Example#5183 - Using pdo_parse_params
  • Example#5184 - Implementing preparer for drivers that don't support native prepared statements
  • Example#5185 - simple stream example that displays the PHP home page
  • Example#5186 - How to accept a stream as a parameter
  • Example#5187 - How to return a stream from a function
  • Example#5188 - The default config.m4.
  • Example#5189 - A simple extension.
  • Example#5190 - A test file for first_module.so.
  • Example#5191 - Internal declaration of zend_function_entry.
  • Example#5192 - Internal declaration of zend_module_entry.
  • Example#5193 - PHP's implementation of variable arguments in fsockopen().
  • Example#5194 - PHP/Zend zval type definition.
  • Example#5195 - Testing for referenced parameter passing.
  • Example#5196 - Creating variables with different scopes.
  • Example#5197 - Creation of a long.
  • Example#5198 - Adding an element to an associative array.
  • Example#5199 - Adding an element to an indexed array.
  • Example#5200 - Source code and screenshot for output in phpinfo.
  • Example#5201 - Printing execution information.
  • Example#5202 - Calling user functions.
  • Example#5203 - Скрытый элемент HTML формы
  • Example#5204 - Данные, редактируемые пользователем
  • Example#5205 - В URL
  • Example#5206 - Генерирование Javascript из PHP
  • Example#5207 - Эмулирование Register Globals
  • Example#5208 - Пример кода на PHP/FI
  • Example#5209 - В ядре PHP
  • Example#5210 - Объектно-ориентированный код в ядре PHP
  • Example#5211 - В расширении bzip2
  • Example#5212 - В расширении datetime
  • Example#5213 - В расширении dBase
  • Example#5214 - В расширении mcrypt
  • Example#5215 - В расширении oci8
  • Example#5216 - В расширении SPL
  • Example#5217 - В расширении Semaphore (sysvmsg)
  • Example#5218 - Пример Zip для версий 5.2.1+
  • Example#5219 - strrpos и strripos теперь используют в качестве искомого параметра (needle) всю строку
  • Example#5220 - Объект без свойств больше не считается "пустым"
  • Example#5221 - В некоторых случаях классы должны быть объявлены перед использованием
  • Example#5222 - Изменения конфигурационных файлах Apache при переходе на PHP 5
  • Example#5223 - Изменения в конфигурационных файлах Apache при переходе на PHP 5, CGI-режим
  • Example#5224 - Example of object comparison in PHP 4
  • Example#5225 - Compound object comparisons in PHP 4
  • Example#5226 - Активация полного логирования и сообщения об ошибках для dev. домена
  • Example#5227 - Добавление скрипта безопасности для защищенных зон
  • Example#5228 - include_path в Unix
  • Example#5229 - include_path в Windows
  • Example#5230 - string.rot13
  • Example#5231 - string.toupper
  • Example#5232 - string.tolower
  • Example#5233 - string.strip_tags
  • Example#5234 - convert.base64-encode и convert.base64-decode
  • Example#5235 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5236 - zlib.deflate и zlib.inflate
  • Example#5237 - Упрощенное использование zlib.deflate
  • Example#5238 - bzip2.compress и bzip2.decompress
  • Example#5239 - Шифрование вывода в файл используя 3DES
  • Example#5240 - Чтение зашифрованного файла

User Contributed Notes

There are no user contributed notes for this page.
Список функций и методов
Руководство в формате HTML Help
Алфавитный список


Руководство в формате HTML Help

  • About This Edition
  • Using PHP Manual CHM Edition
    • The HTML Help Toolbar
    • The Navigation Pane
    • Keyboard Shortcuts
  • The Full Text Search
    • General searching rules
    • Searching for words or phrases
    • Defining search terms
    • Using nested expressions when searching
  • Specialities of this Edition
    • User Preferences
    • Presentational Specialities
  • Integrating the PHP Manual
  • Skin development
    • Page Display Process
    • Page Elements
    • CSS classes
  • CHM Edition Credits

User Contributed Notes

There are no user contributed notes for this page.
Список примеров
About This Edition
Руководство по PHP


About This Edition

The Windows HTML Help Edition of the PHP Manual is aimed at developers, who want the manual at hand every time, and would like to read manual pages and user notes without waiting for a remote web page to download. This edition gives you the full content of the manual plus the user notes, with some great features provided by the viewer application by the scripts we use to generate this format and by other contributors in the form of skins.

This distribution of the PHP Manual contains many files, including the main manual file php_manual_en.chm. You can view the manual by double clicking on this file (as you already guessed). You may also see a php_manual_en.chw file in the directory, it's generated the first time you use the index tab, and it contains an index with the manual's pages.

For those interested in technical details about Microsoft HTML Help, » http://www.helpware.net/ is a great resource. For more information and positioning of Windows HTML Help in the Microsoft help formats and services history, see this » WinWriters article.

User Contributed Notes

There are no user contributed notes for this page.
Руководство в формате HTML Help
Using PHP Manual CHM Edition
Руководство в формате HTML Help


Using PHP Manual CHM Edition

Содержание

  • The HTML Help Toolbar
  • The Navigation Pane
  • Keyboard Shortcuts

When you double click on a CHM, a HTML Help Viewer window opens with three panes. On the left side of the window is the Navigation pane. It contains four navigational tabs: the Contents, Index, Search and Favorites tabs. On the right side of the window is the Topic pane. It displays the selected help topic, or the default help topic on startup. The help pages are all separate HTML files, your Internet Explorer displays the pages in the Topic pane. The third pane is the toolbar, which is located below the help window title bar. You can adjust the horizontal layout with dragging the vertical border between the Navigation pane and the Topic pane.

Note, that when you open the CHM the first time, it may appear in a strange position and size. From then, Windows remembers the window position, size and the last opened tab. All these including your favorites are stored in a file named hh.dat. If you move your file to another directory, all these remembered settings will be lost (including your favorites listing!). If you replace your CHM file with a new one, with the same name, this is not a problem though. The file names and path values are stored in hh.dat.

User Contributed Notes

There are no user contributed notes for this page.
About This Edition
The HTML Help Toolbar
Руководство в формате HTML Help


The HTML Help Toolbar

The HTML Help Toolbar contains the following icons, when you view the PHP Manual:

  • Hide/Show - Hides/shows the navigation pane.
  • Locate - Locates a topic in the contents tab (in case you reached a topic with search, index or favorites, and would like to see where it is in the table of contents tree view).
  • Back - Goes back in the history.
  • Forward - Goes forward in the history.
  • Refresh - Reloads the current page.
  • Home - Opens the startup page of the CHM.
  • Print - Opens the print dialog box.
  • Options - Provides a dropdown with more options.
Using this toolbar is really easy, many of the toolbar icons are strongly related to their Internet Explorer equivalents.

User Contributed Notes

There are no user contributed notes for this page.
Using PHP Manual CHM Edition
The Navigation Pane
Using PHP Manual CHM Edition


The Navigation Pane

The Navigation Pane contains four navigational tabs: the Contents, Index, Search and Favorites tabs. These all provide different methods to access a topic in the help file.

  • The contents tab reveals a tree like table of contents, where you can navigate to the desired topic by opening and closing parts of the tree. You can even access the deepest sections using this TOC. If you right click on an item here and choose "Print...", you'll have the option to print the selected topic or the selected topic and all subtopics. However printing is not the initial goal of this representation of the manual (the PDF version is suitable for printing).
  • The index tab lists a huge number of "keywords" (actually manual page titles). You can pick one, or start to type a keyword, see the list adjusting to your input, and then click on a topic, or press enter if the selected topic is the one you would like to see.
  • The search tab shows one of the most powerful features of the HTML Help Viewer, the full text search (also known as FTS). Here you can type in your search expression, optionally connecting words with AND/OR/NEAR/NOT. Before you click 'List topics', you can also set some options at the bottom. After the search results are displayed, you'll realize that manual text and user note results are separated. To sort out the two types, click on the 'Location' column header. Now from the search results list, you can pick a topic, and see it's page. The keywords you searched for are highlighted on the page.
  • The favorites tab enables you to store your most used topics in a list, easily accessible. Here you can see the list, add the current topic to it, remove one, or display a selected item. You can also specify your own title for the favorite, by typing it into the 'Current topic:' box. The user note page titles are prepended with a 'N:' string so you can distinguish them from normal manual pages in the favorites listing.

User Contributed Notes

There are no user contributed notes for this page.
The HTML Help Toolbar
Keyboard Shortcuts
Using PHP Manual CHM Edition


Keyboard Shortcuts

There are many keyboard shortcuts you can use to increase your productivity. Many users find it more appropriate to use these keyboard shortcuts to access topics, instead of clicking.

General Help Viewer Shortcuts
To | Press
Close the Help Viewer | ALT+F4
Display the Options menu | ALT+O
Hide or show the Navigation pane | ALT+O, and then T
Print a topic | ALT+O, and then P
Move back to the previous topic | ALT+LEFT ARROW
Move forward to the next topic (provided you have viewed it just previously) | ALT+RIGHT ARROW
Turn on or off search highlighting. | ALT+O, and then O
Return to the help file home page | ALT+O, and then H
Switch between the Navigation pane and the Topic pane | F6
Scroll through all the links in a topic or through all the options on a Navigation pane tab | TAB
Display context (right click) menu [see the User Preferences section] | SHIFT+F10
Contents Tab Shortcuts
To | Press
Display the Contents tab | ALT+C
Open and close a book or folder | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic | DOWN ARROW and UP ARROW
Display the selected topic | ENTER
Index Tab Shortcuts
To | Press
Display the Index tab | ALT+N
Type a keyword to search for | ALT+W, and then type the word
Select a keyword in the list | UP ARROW and DOWN ARROW
Display the associated topic | ENTER or ALT+D
Search Tab shortcuts
To | Press
Display the Search tab | ALT+S
Type a keyword to search for | ALT+W, and then type the word
Start a search | ALT+L
Select a topic in the results list | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Search for a keyword in the result list of a prior search | ALT+U
Search for words similar to the keyword. For example, to find words like "running" and "runs" for the keyword "run" | ALT+M
Only search through topic titles | ALT+R
Favorites Tab Shortcuts
To | Press
Display the Favorites tab | ALT+I
Add the currently displayed topic to the Favorites list | ALT+A
Select a topic in the Favorites list | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Remove the selected topic from the list | ALT+R
Topic Pane Shortcuts
To | Press
Index Lookup | Select the words you would like to look up and press F1
Find on page | CTRL+F, and then adjust options
Refresh page | F5

User Contributed Notes

There are no user contributed notes for this page.
The Navigation Pane
The Full Text Search
Using PHP Manual CHM Edition


The Full Text Search

Содержание

  • General searching rules
  • Searching for words or phrases
  • Defining search terms
  • Using nested expressions when searching

This edition of the PHP Manual includes an advanced full text search possibility provided by the viewer application. This enables users to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.

User Contributed Notes

There are no user contributed notes for this page.
Keyboard Shortcuts
General searching rules
Руководство в формате HTML Help


General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.
  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.
  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.
  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

Замечание:

If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."

User Contributed Notes

There are no user contributed notes for this page.
The Full Text Search
Searching for words or phrases
The Full Text Search


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

Word and phrase searches
Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase | "new operator" or new operator | Topics that contain the literal phrase "new operator" and all its grammatical variations. Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.
Wildcard expressions | esc* or HT?? | Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term. Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

Замечание:

Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".

User Contributed Notes

There are no user contributed notes for this page.
General searching rules
Defining search terms
The Full Text Search


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

Search operators
Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

Замечание:

The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.

User Contributed Notes

There are no user contributed notes for this page.
Searching for words or phrases
Using nested expressions when searching
The Full Text Search


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.
  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".
  • You cannot nest expressions more than five levels deep.

User Contributed Notes

There are no user contributed notes for this page.
Defining search terms
Specialities of this Edition
The Full Text Search


Specialities of this Edition

Содержание

  • User Preferences
  • Presentational Specialities

The HTML Help Edition of the PHP Manual over-performs the presentational and interactive capabilities offered by other editions (including the online manual).

User Contributed Notes

There are no user contributed notes for this page.
Using nested expressions when searching
User Preferences
Руководство в формате HTML Help


User Preferences

Most of the interactive features of this manual are provided by the viewer application (including full text search, index, favorites list), but we extended this list with PHP Manual specific tools. All these can be adjusted to your needs using a simple desktop application named php_manual_prefs.exe. If you run this program you can see three groups of settings: Online Functions, Context Menu, and Skin. All your settings are stored in php_manual_prefs.js.

Online functions enable you to have elements connected to websites. The two ones you can see on all manual pages are "This page online" and "Report a bug". As you can figure out the first one shows you the same page in the online manual, the second one opens a page from » http://bugs.php.net/ and prefills some bug data for you. You need to select a mirror site to use for "php.net sensitive" online functions. We recommend choosing a close mirror site to get the best speed. Other components that may be limited by this online functions setting include context menu items opening new websites ("Google search selection" for example). Custom designs may also include elements restricted by this setting.

The context menu settings enables you to choose which context menu you prefer. This application provides you with an option to define your own context menu adding elements to it from a predefined set. You can have this custom context menu for the right click of your mouse, and have the original menu for CTRL+right click, or the opposite way. Three special types of custom context menu items exist:

Context menu items
Type | Examples | Comments
Page Jump | Function Reference, Function Index | These items jump to a specific page in the CHM. Page Jump options are not restricted to point inside the CHM though. They can point to websites or other resources. Page jump options with a protocol part in the URL open in new window.
Function Call | Print page, Select all, Copy selection to clipboard, Google Search Selection | These are "function calls" for internally defined context menu functions. The last two examples have the speciality that they only show up in the menu if you rightclicked on a selection. Currently there is no way to extend the context menu with skin defined functions.
Special display | Google SearchBox, AlltheWeb SearchBox | These are displayed as HTML forms, where you can enter search keywords, press ENTER, and receive a new window with the search issued in the appropriate search engine. Currently there is no way to extend the set of specially displayed context menu items.
Possible context menu elements and their "abstract implementations" are stored in context.ini. You have the ability to add possible page jump options there, but there is no way currently to extend the context menu system with user (skin) defined functions. The possible mirror sites are listed in mirrors.ini. Feel free to suggest more bundled context menu items to us at » php-doc-chm@lists.php.net.

The skins setting enables you to choose from the two bundled default skins, or from any user defined skins. The Low skin is optimized to display correctly at any small size, the High skin is optimized for your viewing pleasure. Other skins may be developed according to our skins development guide. The recommended place for skins on the file system is the skins/SKINNAME subfolder of the PHP Manual directory. Though this is not required, some skins may define other rules (not recommended). We included sample skins for you to see examples of how to develop skins for the PHP Manual.

You have three buttons to choose from at the bottom. The Apply button applies your changes without exiting, the OK button applies and closes the application, the Cancel button does not modify your settings and closes the program.

User Contributed Notes

There are no user contributed notes for this page.
Specialities of this Edition
Presentational Specialities
Specialities of this Edition


Presentational Specialities

This edition of the PHP Manual is highly optimized for screen presentation. Skins may be developed to better support printing, as this was not the goal of the included skins. This approach allowed us to make many modifications to the presentation of different parts of the manual.

The first thing you'll notice is that all examples are color coded, using the PHP function show_source(). The actual colors used are defined by CSS classes. Examples also have links to PHP functions used in them to provide quick access to reference material. All code examples have a "copy to clipboard" link by the side of them with which you can copy the text contents of the example to the clipboard.

External links are marked with a special » sign, and open in a new browser window. We also included the "path to this page" information on all pages for you to easily identify where you are and navigate as needed.

Other parts of the manual are quite similar to the online ones by default, though custom skins can modify many elements on the pages.

User Contributed Notes

There are no user contributed notes for this page.
User Preferences
Integrating the PHP Manual
Specialities of this Edition


Integrating the PHP Manual

Замечание:

The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

Замечание:

All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name collisions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a » HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

If you would like to integrate the manual into an IDE without direct support for the PHP manual (actually the underscore to hyphen conversion), you can use the included _function.html file to access a function page. This file is simply a redirector, and can be parameterized via the URL, as _function.html#mysql_close. This page will redirect you to the mysql_close function page (function.mysql-close.html) automatically. You can provide the full path of this file if your IDE supports context sensitive help, and provide the IDE specified string as the parameter. An example for this is the UltraEdit 9 intergation (see the edition's website).

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at » http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at » http://www.microsoft.com/download/en/details.aspx?id=21138.

User Contributed Notes

There are no user contributed notes for this page.
Presentational Specialities
Skin development
Руководство в формате HTML Help


Skin development

Содержание

  • Page Display Process
  • Page Elements
  • CSS classes

This edition of the PHP Manual allows users to choose from skins to display the contents, as well as develop custom skins to meet some special needs. We decided to support skins because we realized that one skin cannot satisfy everybody's needs in a such heavily used edition.

We included two skins by default inside the CHM. These cannot be modified or removed, so if you have the CHM, you have these two skins inside. The Low skin is optimized for small window display, the High skin is a variation of the Low one with some graphics added to spice it up.

A skin must have at least two files, a skin loader JavaScript file and a CSS file. The two inline skins have these files inside the CHM. The skin loader JS should at least load in the CSS file and display the page contents to the viewer. Theoretically there are two kinds of skins: CSS skins and Full skins. CSS skins only modify the CSS and does not amend the page layout. Full skins also modify the page layout. We have included sample skins for both the CSS skin type and the Full skin type ("greenlinks" and "headernostalgia" respectively).

Внимание

Note that though the current skin development methods are quite final, there may be heavy changes in used CSS classes or page elements while we refine the skin development ideas. As this edition is currently in development stage, the information described herein is not to be considered completely stable.

User Contributed Notes

There are no user contributed notes for this page.
Integrating the PHP Manual
Page Display Process
Руководство в формате HTML Help


Page Display Process

If you are going to develop your own skin, you should know how one page is loaded and displayed to the user, and how a skin fits in this process. For these paragraphs, we assume that you have put your CHM into c:\phpmanual, so it's accessible as c:\phpmanual\php_manual_LANG.chm (where LANG is the language code), and you would like to see the function page of "echo", which is function.echo.html inside the CHM. See the sections about integration for more information on CHM contents.

  • First of all the HTML content is loaded in from function.echo.html from inside the CHM.
  • At the top of this file, there is a HTML <script> tag, which loads in the _script.js file from the CHM. This file contains all the JS code needed to move on with the process. Most importantly this JS defines many variables (like where the CHM is, or what is the actual page viewed) and many functions to print out the context menu or handle online functions.
  • At last _script.js loads in the preferences file from outside the CHM (c:\phpmanual\php_manual_prefs.js in our example). This JS file defines the preference variables, and calls back prefHandler() which is also defined in _script.js.
  • That function loads in the skin JS file as the preferences dictate. The skin JS file should load in the needed CSS file, and define a displayPage() function, which displays the page if called.
  • The HTML file (function.echo.html in this example) also contains a function call to load in the user notes, which simply puts the notes into this HTML file using DHTML to be displayed as if they were here before...
  • The HTML file also contains a body onload attribute which calls the skin-defined displayPage() function to show the page to the user. This is the last function called, it should present the page in it's complete form to the user.
Every action is synchronized with calling back a function in the previously loaded file when the JS is in memory. The notes loading and skin JS loading is only synchronized with the page's onload event (which as the Microsoft documentation says only fires if the page is completely loaded).

This load and callback chain may seem to be too complicated, but so far this seemed to be the best way to do as many things as possible parallel, while also synchronize some calls.

As you can see your skin JavaScript file is loaded in by _script.js and it's displayPage() function is called by the body onload event.

User Contributed Notes

There are no user contributed notes for this page.
Skin development
Page Elements
Skin development


Page Elements

The PHP Manual pages are all HTML files with several HTML tags in them for both presentational and divisional purposes. The HTML pages contain divisions to be used for skinning purposes and misc divisions added by the DocBook XSL sheets.

A HTML page can be either a function reference page or another kind of page (like a feature description). Skins should get ready to skin these two kinds of pages separately most of the time (depending on the actual design).

The pages are structured using <div> tags with appropriate IDs to ease the skin writers work. A page consists of these parts:

  • <div id="pageContent"></div> contains all the page contents. This begins right after <body> and ends just before </body>. This division is hidden by default, you need to show it after you are ready with the page rewriting process.
  • <div id="pageHeaders"></div> contains the page header parts. This includes the text only main title (in a <span id="pageTitle"></span>) and function properties, in case this is a function page (contained in <span id="funcPurpose"></span>, <span id="funcAvail"></span> and <span id="funcUsage"></span>). In case one of these three is not available, the current page is not a function page.
  • <div id="pageText"></div> contains the majority of the page contents, including examples, manual notes, warnings, etc. This also includes see also parts for now, as we still cannot differentiate between see also and normal text parts (may be a thing to change in the future).
  • <div id="pageNotes"></div> contains the user notes (itself loaded in from another HTML file by JS). It contains a heading, and then a <div> without ID for every user note and spans in that divs for every element of a user note (with "email", "date" and "text" IDs respectively).
  • <div id="pageNav"></div> contains the
navigation table, which is further divided into spans (<span
id="navPrev"></span>, <span
id="navPath"></span>, <span
id="navNext"></span>, <span
id="navOnline"></span>, <span
id="navThisOnline"></span> and <span
id="navReportBug"></span>), where navThisOnline
and navReportBug is inside navOnline.
If you would like to rewrite the page, you should first read in the parts you need from the page to JS variables, then clear the contents of pageContent (or just the part you would like to rewrite), write in the new content and show the pageContent div for the user. If you would not like to make any structural changes, you can simply display the pageContent div and only specify a special style sheet in your skin JS file (see the "greenlinks" skin for an example).

You can find a "Full skin" developed to show you how to make skins built on top of this structure. The skin name is "headernostalgia". It rewrites the header part and removes the footer navigational table.

User Contributed Notes

There are no user contributed notes for this page.
Page Display Process
CSS classes
Skin development


CSS classes

We cannot provide accurate documentation currently on usable CSS classes, as some of the DocBook XSL sheets classes are not used and some classes are added. Please see the sample CSS files included for first time reference.

User Contributed Notes

There are no user contributed notes for this page.
Page Elements
CHM Edition Credits
Skin development


CHM Edition Credits

This enhanced version of the PHP Manual would never come to existence, if the following people would not help with their contribution to the project (in no particular order):

  • Holger Eggert, who created the two default designs, and provided many usability tips
  • Gonzalo De la Pena Andreu, who added many comments on how it would be ideal to provide the skinnable interface
  • Olexandr Vynnychenko added countless comments and testing all the time
  • Brendan Ferguson, who provided many optimizations, improvements to the HTML and JS codes behind the manual pages
  • Sandor Hojtsy, who coded the manual preferences desktop application
  • And at last but not least, everybody, who provided feedback through our mailing list, and in the user survey

User Contributed Notes

There are no user contributed notes for this page.
CSS classes
Руководство в формате HTML Help